# Driver development

> Driver foundations and subsystem programming interfaces.

---

# Driver development

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> Start with the driver model, then find the subsystem API you need.

<a id="rst-driver-implementer-s-api-guide"></a>
<a id="rst-general-information-for-driver-authors"></a>
<a id="rst-useful-support-libraries"></a>
<a id="rst-bus-level-documentation"></a>
<a id="rst-subsystem-specific-apis"></a>

Driver development combines common kernel facilities with the interfaces of a
particular bus or device subsystem.

Start with the [Device and driver model](</kernel/hardware/driver-api/driver-model/index.md>)
and [Driver basics](</kernel/hardware/driver-api/fundamentals/basics.md>). Then use the guides for
[Device I/O](</kernel/hardware/driver-api/io-and-dma/device-io.md>),
[DMA engines](</kernel/hardware/driver-api/dmaengine/index.md>) and
[Firmware loading](</kernel/hardware/driver-api/firmware/index.md>) as needed.

The remaining shelves collect subsystem APIs, platform services and media
interfaces. CXL has its own group covering the programming model, allocation,
devices and platform integration.

Use [Hardware and drivers](</kernel/hardware/start-here/overview.md>) for device-family
documentation and [Kernel development](</kernel/development/start-here/overview.md>)
for build and test guidance.

---

# Managing Ownership of the Framebuffer Aperture

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> Reference for Managing Ownership of the Framebuffer Aperture.

<a id="rst-managing-ownership-of-the-framebuffer-aperture"></a>

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


A graphics device might be supported by different drivers, but only one
driver can be active at any given time. Many systems load a generic
graphics drivers, such as EFI-GOP or VESA, early during the boot process.
During later boot stages, they replace the generic driver with a dedicated,
hardware-specific driver. To take over the device, the dedicated driver
first has to remove the generic driver. Aperture functions manage
ownership of framebuffer memory and hand-over between drivers.

Graphics drivers should call [`aperture_remove_conflicting_devices()`](#c-aperture_remove_conflicting_devices)
at the top of their probe function. The function removes any generic
driver that is currently associated with the given framebuffer memory.
An example for a graphics device on the platform bus is shown below.

```c
static int example_probe(struct platform_device *pdev)
{
        struct resource *mem;
        resource_size_t base, size;
        int ret;

        mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
        if (!mem)
                return -ENODEV;
        base = mem->start;
        size = resource_size(mem);

        ret = aperture_remove_conflicting_devices(base, size, "example");
        if (ret)
                return ret;

        // Initialize the hardware
        ...

        return 0;
}

static const struct platform_driver example_driver = {
        .probe = example_probe,
        ...
};
```

The given example reads the platform device's I/O-memory range from the
device instance. An active framebuffer will be located within this range.
The call to [`aperture_remove_conflicting_devices()`](#c-aperture_remove_conflicting_devices) releases drivers that
have previously claimed ownership of the range and are currently driving
output on the framebuffer. If successful, the new driver can take over
the device.

While the given example uses a platform device, the aperture helpers work
with every bus that has an addressable framebuffer. In the case of PCI,
device drivers can also call [`aperture_remove_conflicting_pci_devices()`](#c-aperture_remove_conflicting_pci_devices) and
let the function detect the apertures automatically. Device drivers without
knowledge of the framebuffer's location can call
[`aperture_remove_all_conflicting_devices()`](#c-aperture_remove_all_conflicting_devices), which removes all known devices.

Drivers that are susceptible to being removed by other drivers, such as
generic EFI or VESA drivers, have to register themselves as owners of their
framebuffer apertures. Ownership of the framebuffer memory is achieved
by calling [`devm_aperture_acquire_for_platform_device()`](#c-devm_aperture_acquire_for_platform_device). If successful, the
driver is the owner of the framebuffer range. The function fails if the
framebuffer is already owned by another driver. See below for an example.

```c
static int generic_probe(struct platform_device *pdev)
{
        struct resource *mem;
        resource_size_t base, size;

        mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
        if (!mem)
                return -ENODEV;
        base = mem->start;
        size = resource_size(mem);

        ret = devm_aperture_acquire_for_platform_device(pdev, base, size);
        if (ret)
                return ret;

        // Initialize the hardware
        ...

        return 0;
}

static int generic_remove(struct platform_device *)
{
        // Hot-unplug the device
        ...

        return 0;
}

static const struct platform_driver generic_driver = {
        .probe = generic_probe,
        .remove = generic_remove,
        ...
};
```

The similar to the previous example, the generic driver claims ownership
of the framebuffer memory from its probe function. This will fail if the
memory range, or parts of it, is already owned by another driver.

If successful, the generic driver is now subject to forced removal by
another driver. This only works for platform drivers that support hot
unplugging. When a driver calls [`aperture_remove_conflicting_devices()`](#c-aperture_remove_conflicting_devices)
et al for the registered framebuffer range, the aperture helpers call
[`platform_device_unregister()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-platform_device_unregister) and the generic driver unloads itself. The
generic driver also has to provide a remove function to make this work.
Once hot unplugged from hardware, it may not access the device's
registers, framebuffer memory, ROM, etc afterwards.



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

```c
int aperture_remove_all_conflicting_devices(const char *name)
```

remove all existing framebuffers

**Parameters**

- `const char *name`: a descriptive name of the requesting driver

**Description**

This function removes all graphics device drivers. Use this function on systems
that can have their framebuffer located anywhere in memory.

**Return**

0 on success, or a negative errno code otherwise



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

```c
int devm_aperture_acquire_for_platform_device(struct platform_device *pdev, resource_size_t base, resource_size_t size)
```

Acquires ownership of an aperture on behalf of a platform device.

**Parameters**

- `struct platform_device *pdev`: the platform device to own the aperture
- `resource_size_t base`: the aperture's byte offset in physical memory
- `resource_size_t size`: the aperture size in bytes

**Description**

Installs the given device as the new owner of the aperture. The function
expects the aperture to be provided by a platform device. If another
driver takes over ownership of the aperture, aperture helpers will then
unregister the platform device automatically. All acquired apertures are
released automatically when the underlying device goes away.

The function fails if the aperture, or parts of it, is currently
owned by another device. To evict current owners, callers should use
`remove_conflicting_devices()` et al. before calling this function.

**Return**

0 on success, or a negative errno value otherwise.

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

```c
int aperture_remove_conflicting_devices(resource_size_t base, resource_size_t size, const char *name)
```

remove devices in the given range

**Parameters**

- `resource_size_t base`: the aperture's base address in physical memory
- `resource_size_t size`: aperture size in bytes
- `const char *name`: a descriptive name of the requesting driver

**Description**

This function removes devices that own apertures within **base** and **size**.

**Return**

0 on success, or a negative errno code otherwise

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

```c
int __aperture_remove_legacy_vga_devices(struct pci_dev *pdev)
```

remove legacy VGA devices of a PCI devices

**Parameters**

- `struct pci_dev *pdev`: PCI device

**Description**

This function removes VGA devices provided by **pdev**, such as a VGA
framebuffer or a console. This is useful if you have a VGA-compatible
PCI graphics device with framebuffers in non-BAR locations. Drivers
should acquire ownership of those memory areas and afterwards call
this helper to release remaining VGA devices.

If your hardware has its framebuffers accessible via PCI BARS, use
[`aperture_remove_conflicting_pci_devices()`](#c-aperture_remove_conflicting_pci_devices) instead. The function will
release any VGA devices automatically.

- WARNING: Apparently we must remove graphics drivers before calling

  this helper. Otherwise the vga fbdev driver falls over if
  we have vgacon configured.

**Return**

0 on success, or a negative errno code otherwise

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

```c
int aperture_remove_conflicting_pci_devices(struct pci_dev *pdev, const char *name)
```

remove existing framebuffers for PCI devices

**Parameters**

- `struct pci_dev *pdev`: PCI device
- `const char *name`: a descriptive name of the requesting driver

**Description**

This function removes devices that own apertures within any of **pdev**'s
memory bars. The function assumes that PCI device with shadowed ROM
drives a primary display and therefore kicks out vga16fb as well.

**Return**

0 on success, or a negative errno code otherwise

---

# Driver Basics

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> Reference for Driver Basics.

> **Peios:** The generated declarations below are read from the kernel source. Peios adds native checks at the file, process, IPC and socket boundaries; inherited comments about Unix permissions or capability names are not a complete access policy. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) and the [VFS callback reference](</kernel/internals/filesystems/vfs.md>) for the Peios integration contracts.


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

<a id="rst-driver-entry-and-exit-points"></a>

## Driver Entry and Exit points


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

```c
module_init(x)
```

driver initialization entry point

**Parameters**

- `x`: function to be run at kernel boot time or module insertion

**Description**

[`module_init()`](#c-module_init) will either be called during `do_initcalls()` (if
builtin) or at module insertion time (if a module).  There can only
be one per module.

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

```c
module_exit(x)
```

driver exit entry point

**Parameters**

- `x`: function to be run when driver is removed

**Description**

[`module_exit()`](#c-module_exit) will wrap the driver clean-up code
with `cleanup_module()` when used with rmmod when
the driver is a module.  If the driver is statically
compiled into the kernel, [`module_exit()`](#c-module_exit) has no effect.
There can only be one per module.

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

ELF information preserved from the livepatch module

**Definition**

```c
struct klp_modinfo {
    Elf_Ehdr hdr;
    Elf_Shdr *sechdrs;
    char *secstrings;
    unsigned int symndx;
};
```

**Members**

- `hdr`: ELF header
- `sechdrs`: Section header table
- `secstrings`: String table for the section headers
- `symndx`: The symbol table section index

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

```c
bool try_module_get(struct module *module)
```

take module refcount unless module is being removed

**Parameters**

- `struct module *module`: the module we should check for

**Description**

Only try to get a module reference count if the module is not being removed.
This call will fail if the module is in the process of being removed.

Care must also be taken to ensure the module exists and is alive prior to
usage of this call. This can be gauranteed through two means:

1) Direct protection: you know an earlier caller must have increased the
   module reference through `__module_get()`. This can typically be achieved
   by having another entity other than the module itself increment the
   module reference count.

2) Implied protection: there is an implied protection against module
   removal. An example of this is the implied protection used by kernfs /
   sysfs. The sysfs store / read file operations are guaranteed to exist
   through the use of kernfs's active reference (see `kernfs_active()`) and a
   sysfs / kernfs file removal cannot happen unless the same file is not
   active. Therefore, if a sysfs file is being read or written to the module
   which created it must still exist. It is therefore safe to use
   [`try_module_get()`](#c-try_module_get) on module sysfs store / read ops.

One of the real values to [`try_module_get()`](#c-try_module_get) is the `module_is_live()` check
which ensures that the caller of [`try_module_get()`](#c-try_module_get) can yield to userspace
module removal requests and gracefully fail if the module is on its way out.

Returns true if the reference count was successfully incremented.

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

```c
void module_put(struct module *module)
```

release a reference count to a module

**Parameters**

- `struct module *module`: the module we should release a reference count for

**Description**

If you successfully bump a reference count to a module with [`try_module_get()`](#c-try_module_get),
when you are finished you must call [`module_put()`](#c-module_put) to release that reference
count.


<a id="rst-driver-device-table"></a>

## Driver device table


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

identifies USB devices for probing and hotplugging

**Definition**

```c
struct usb_device_id {
    __u16 match_flags;
    __u16 idVendor;
    __u16 idProduct;
    __u16 bcdDevice_lo;
    __u16 bcdDevice_hi;
    __u8 bDeviceClass;
    __u8 bDeviceSubClass;
    __u8 bDeviceProtocol;
    __u8 bInterfaceClass;
    __u8 bInterfaceSubClass;
    __u8 bInterfaceProtocol;
    __u8 bInterfaceNumber;
    kernel_ulong_t driver_info  ;
};
```

**Members**

- `match_flags`: Bit mask controlling which of the other fields are used to
  match against new devices. Any field except for driver_info may be
  used, although some only make sense in conjunction with other fields.
  This is usually set by a USB_DEVICE_*() macro, which sets all
  other fields in this structure except for driver_info.
- `idVendor`: USB vendor ID for a device; numbers are assigned
  by the USB forum to its members.
- `idProduct`: Vendor-assigned product ID.
- `bcdDevice_lo`: Low end of range of vendor-assigned product version numbers.
  This is also used to identify individual product versions, for
  a range consisting of a single device.
- `bcdDevice_hi`: High end of version number range.  The range of product
  versions is inclusive.
- `bDeviceClass`: Class of device; numbers are assigned
  by the USB forum.  Products may choose to implement classes,
  or be vendor-specific.  Device classes specify behavior of all
  the interfaces on a device.
- `bDeviceSubClass`: Subclass of device; associated with bDeviceClass.
- `bDeviceProtocol`: Protocol of device; associated with bDeviceClass.
- `bInterfaceClass`: Class of interface; numbers are assigned
  by the USB forum.  Products may choose to implement classes,
  or be vendor-specific.  Interface classes specify behavior only
  of a given interface; other interfaces may support other classes.
- `bInterfaceSubClass`: Subclass of interface; associated with bInterfaceClass.
- `bInterfaceProtocol`: Protocol of interface; associated with bInterfaceClass.
- `bInterfaceNumber`: Number of interface; composite devices may use
  fixed interface numbers to differentiate between vendor-specific
  interfaces.
- `driver_info`: Holds information used by the driver.  Usually it holds
  a pointer to a descriptor understood by the driver, or perhaps
  device flags.

**Description**

In most cases, drivers will create a table of device IDs by using
[`USB_DEVICE()`](/kernel/hardware/driver-api/usb/usb.md#c-USB_DEVICE), or similar macros designed for that purpose.
They will then export it to userspace using `MODULE_DEVICE_TABLE()`,
and provide it to the USB core through their usb_driver structure.

See the [`usb_match_id()`](/kernel/hardware/driver-api/usb/usb.md#c-usb_match_id) function for information about how matches are
performed.  Briefly, you will normally use one of several macros to help
construct these entries.  Each entry you provide will either identify
one or more specific products, or will identify a class of products
which have agreed to behave the same.  You should put the more specific
matches towards the beginning of your table, so that driver_info can
record quirks of specific products.

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

```c
ACPI_DEVICE_CLASS(_cls, _msk)
```

macro used to describe an ACPI device with the PCI-defined class-code information

**Parameters**

- `_cls`: the class, subclass, prog-if triple for this device
- `_msk`: the class mask for this device

**Description**

This macro is used to create a struct acpi_device_id that matches a
specific PCI class. The .id and .driver_data fields will be left
initialized with the default value.

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

identifies PHY devices on an MDIO/MII bus

**Definition**

```c
struct mdio_device_id {
    __u32 phy_id;
    __u32 phy_id_mask;
};
```

**Members**

- `phy_id`: The result of
  (mdio_read(`MII_PHYSID1`) \<\< 16 | mdio_read(`MII_PHYSID2`)) & **phy_id_mask**
  for this PHY type
- `phy_id_mask`: Defines the significant bits of **phy_id**.  A value of 0
  is used to terminate an array of struct mdio_device_id.

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

identifies a device on an AMBA bus

**Definition**

```c
struct amba_id {
    unsigned int            id;
    unsigned int            mask;
    void *data;
};
```

**Members**

- `id`: The significant bits if the hardware device ID
- `mask`: Bitmask specifying which bits of the id field are significant when
  matching.  A driver binds to a device when ((hardware device ID) & mask)
  == id.
- `data`: Private data used by the driver.

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

identifies devices in MIPS CDMM bus

**Definition**

```c
struct mips_cdmm_device_id {
    __u8 type;
};
```

**Members**

- `type`: Device type identifier.

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

MEI client device identifier

**Definition**

```c
struct mei_cl_device_id {
    char name[MEI_CL_NAME_SIZE];
    uuid_le uuid;
    __u8 version;
    kernel_ulong_t driver_info;
};
```

**Members**

- `name`: helper name
- `uuid`: client uuid
- `version`: client protocol version
- `driver_info`: information used by the driver.

**Description**

identifies mei client device by uuid and name

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

RIO device identifier

**Definition**

```c
struct rio_device_id {
    __u16 did, vid;
    __u16 asm_did, asm_vid;
};
```

**Members**

- `did`: RapidIO device ID
- `vid`: RapidIO vendor ID
- `asm_did`: RapidIO assembly device ID
- `asm_vid`: RapidIO assembly vendor ID

**Description**

Identifies a RapidIO device based on both the device/vendor IDs and
the assembly device/vendor IDs.

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

MC object device identifier

**Definition**

```c
struct fsl_mc_device_id {
    __u16 vendor;
    const char obj_type[16];
};
```

**Members**

- `vendor`: vendor ID
- `obj_type`: MC object type

**Description**

Type of entries in the "device Id" table for MC object devices supported by
a MC object device driver. The last entry of the table has vendor set to 0x0

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

Thunderbolt service identifiers

**Definition**

```c
struct tb_service_id {
    __u32 match_flags;
    char protocol_key[8 + 1];
    __u32 protocol_id;
    __u32 protocol_version;
    __u32 protocol_revision;
    kernel_ulong_t driver_data;
};
```

**Members**

- `match_flags`: Flags used to match the structure
- `protocol_key`: Protocol key the service supports
- `protocol_id`: Protocol id the service supports
- `protocol_version`: Version of the protocol
- `protocol_revision`: Revision of the protocol software
- `driver_data`: Driver specific data

**Description**

Thunderbolt XDomain services are exposed as devices where each device
carries the protocol information the service supports. Thunderbolt
XDomain service drivers match against that information.

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

USB Type-C alternate mode identifiers

**Definition**

```c
struct typec_device_id {
    __u16 svid;
    __u8 mode;
    kernel_ulong_t driver_data;
};
```

**Members**

- `svid`: Standard or Vendor ID
- `mode`: Mode index
- `driver_data`: Driver specific data

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

tee based device identifier

**Definition**

```c
struct tee_client_device_id {
    uuid_t uuid;
};
```

**Members**

- `uuid`: For TEE based client devices we use the device uuid as
  the identifier.

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

WMI device identifier

**Definition**

```c
struct wmi_device_id {
    const char guid_string[UUID_STRING_LEN+1];
    const void *context;
};
```

**Members**

- `guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
- `context`: pointer to driver specific data

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

MHI device identification

**Definition**

```c
struct mhi_device_id {
    const char chan[MHI_NAME_SIZE];
    kernel_ulong_t driver_data;
};
```

**Members**

- `chan`: MHI channel name
- `driver_data`: driver data;

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

dfl device identifier

**Definition**

```c
struct dfl_device_id {
    __u16 type;
    __u16 feature_id;
    kernel_ulong_t driver_data;
};
```

**Members**

- `type`: DFL FIU type of the device. See enum dfl_id_type.
- `feature_id`: feature identifier local to its DFL FIU type.
- `driver_data`: driver specific data.

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

ISHTP device identifier

**Definition**

```c
struct ishtp_device_id {
    guid_t guid;
    kernel_ulong_t driver_data;
};
```

**Members**

- `guid`: GUID of the device.
- `driver_data`: pointer to driver specific data

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

CDX device identifier

**Definition**

```c
struct cdx_device_id {
    __u16 vendor;
    __u16 device;
    __u16 subvendor;
    __u16 subdevice;
    __u32 class;
    __u32 class_mask;
    __u32 override_only;
};
```

**Members**

- `vendor`: Vendor ID
- `device`: Device ID
- `subvendor`: Subsystem vendor ID (or CDX_ANY_ID)
- `subdevice`: Subsystem device ID (or CDX_ANY_ID)
- `class`: Device class
  Most drivers do not need to specify class/class_mask
  as vendor/device is normally sufficient.
- `class_mask`: Limit which sub-fields of the class field are compared.
- `override_only`: Match only when dev->driver_override is this driver.

**Description**

Type of entries in the "device Id" table for CDX devices supported by
a CDX device driver.

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

Identifies a coreboot table entry

**Definition**

```c
struct coreboot_device_id {
    __u32 tag;
    kernel_ulong_t driver_data;
};
```

**Members**

- `tag`: tag ID
- `driver_data`: driver specific data


<a id="rst-delaying-and-scheduling-routines"></a>

## Delaying and scheduling routines


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

snapshot of system and user cputime

**Definition**

```c
struct prev_cputime {
    #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE;
        u64 utime;
        u64 stime;
        raw_spinlock_t lock;
    #endif;
};
```

**Members**

- `utime`: time spent in user mode
- `stime`: time spent in system mode
- `lock`: protects the above two fields

**Description**

Stores previous user/system time values such that we can guarantee
monotonicity.

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

```c
bool __task_lazy_mmu_mode_active(struct task_struct *tsk)
```

Test the lazy MMU mode state for a task.

**Parameters**

- `struct task_struct *tsk`: The task to check.

**Description**

Test whether **tsk** has its lazy MMU mode state set to active (i.e. enabled
and not paused).

This function only considers the state saved in task_struct; to test whether
current actually is in lazy MMU mode, [`is_lazy_mmu_mode_active()`](#c-is_lazy_mmu_mode_active) should be
used instead.

This function is intended for architectures that implement the lazy MMU
mode; it must not be called from generic code.

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

```c
bool is_lazy_mmu_mode_active(void)
```

Test whether we are currently in lazy MMU mode.

**Parameters**

- `void`: no arguments

**Description**

Test whether the current context is in lazy MMU mode. This is true if both:
1. We are not in interrupt context
2. Lazy MMU mode is active for the current task

This function is intended for architectures that implement the lazy MMU
mode; it must not be called from generic code.

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

```c
int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
```

set CPU affinity mask of a task

**Parameters**

- `struct task_struct *p`: the task
- `const struct cpumask *new_mask`: CPU affinity mask

**Return**

zero if successful, or a negative error code

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

```c
int task_nice(const struct task_struct *p)
```

return the nice value of a given task.

**Parameters**

- `const struct task_struct *p`: the task in question.

**Return**

The nice value \[ -20 ... 0 ... 19 \].

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

```c
bool is_idle_task(const struct task_struct *p)
```

is the specified task an idle task?

**Parameters**

- `const struct task_struct *p`: the task in question.

**Return**

1 if **p** is an idle task. 0 otherwise.



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

```c
int wake_up_process(struct task_struct *p)
```

Wake up a specific process

**Parameters**

- `struct task_struct *p`: The process to be woken up.

**Description**

Attempt to wake up the nominated process and move it to the set of runnable
processes.

This function executes a full memory barrier before accessing the task state.

**Return**

1 if the process was woken up, 0 if it was already running.

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

```c
void preempt_notifier_register(struct preempt_notifier *notifier)
```

tell me when current is being preempted & rescheduled

**Parameters**

- `struct preempt_notifier *notifier`: notifier struct to register

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

```c
void preempt_notifier_unregister(struct preempt_notifier *notifier)
```

no longer interested in preemption notifications

**Parameters**

- `struct preempt_notifier *notifier`: notifier struct to unregister

**Description**

This is *not* safe to call from within a preemption notifier.

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

```c
__visible void notrace preempt_schedule_notrace(void)
```

preempt_schedule called by tracing

**Parameters**

- `void`: no arguments

**Description**

The tracing infrastructure uses preempt_enable_notrace to prevent
recursion and tracing preempt enabling caused by the tracing
infrastructure itself. But as tracing can happen in areas coming
from userspace or just about to enter userspace, a preempt enable
can occur before `user_exit()` is called. This will cause the scheduler
to be called when the system is still in usermode.

To prevent this, the preempt_enable_notrace will use this function
instead of `preempt_schedule()` to exit user context if needed before
calling the scheduler.



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

```c
int cpupri_find_fitness(struct cpupri *cp, struct task_struct *p, struct cpumask *lowest_mask, bool (*fitness_fn)(struct task_struct *p, int cpu))
```

find the best (lowest-pri) CPU in the system

**Parameters**

- `struct cpupri *cp`: The cpupri context
- `struct task_struct *p`: The task
- `struct cpumask *lowest_mask`: A mask to fill in with selected CPUs (or NULL)
- `bool (*fitness_fn)(struct task_struct *p, int cpu)`: A pointer to a function to do custom checks whether the CPU
  fits a specific criteria so that we only return those CPUs.

**Note**

This function returns the recommended CPUs as calculated during the
current invocation.  By the time the call returns, the CPUs may have in
fact changed priorities any number of times.  While not ideal, it is not
an issue of correctness since the normal rebalancer logic will correct
any discrepancies created by racing against the uncertainty of the current
priority configuration.

**Return**

(int)bool - CPUs were found

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

```c
void cpupri_set(struct cpupri *cp, int cpu, int newpri)
```

update the CPU priority setting

**Parameters**

- `struct cpupri *cp`: The cpupri context
- `int cpu`: The target CPU
- `int newpri`: The priority (INVALID,NORMAL,RT1-RT99,HIGHER) to assign to this CPU

**Note**

Assumes cpu_rq(cpu)->lock is locked

**Return**

(void)

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

```c
int cpupri_init(struct cpupri *cp)
```

initialize the cpupri structure

**Parameters**

- `struct cpupri *cp`: The cpupri context

**Return**

-ENOMEM on memory allocation failure.

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

```c
void cpupri_cleanup(struct cpupri *cp)
```

clean up the cpupri structure

**Parameters**

- `struct cpupri *cp`: The cpupri context



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

```c
void update_tg_load_avg(struct cfs_rq *cfs_rq)
```

update the tg's load avg

**Parameters**

- `struct cfs_rq *cfs_rq`: the cfs_rq whose avg changed

**Description**

This function 'ensures': tg->load_avg := \Sum tg->cfs_rq\[\]->avg.load.
However, because tg->load_avg is a global value there are performance
considerations.

In order to avoid having to look at the other cfs_rq's, we use a
differential update where we store the last value we propagated. This in
turn allows skipping updates if the differential is 'small'.

Updating tg's load_avg is necessary before `update_cfs_share()`.

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

```c
int update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
```

update the cfs_rq's load/util averages

**Parameters**

- `u64 now`: current time, as per `cfs_rq_clock_pelt()`
- `struct cfs_rq *cfs_rq`: cfs_rq to update

**Description**

The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
avg. The immediate corollary is that all (fair) tasks must be attached.

cfs_rq->avg is used for `task_h_load()` and `update_cfs_share()` for example.

Since both these conditions indicate a changed cfs_rq->avg.load we should
call [`update_tg_load_avg()`](#c-update_tg_load_avg) when this function returns true.

**Return**

true if the load decayed or we removed load.

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

```c
void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
```

attach this entity to its cfs_rq load avg

**Parameters**

- `struct cfs_rq *cfs_rq`: cfs_rq to attach to
- `struct sched_entity *se`: sched_entity to attach

**Description**

Must call [`update_cfs_rq_load_avg()`](#c-update_cfs_rq_load_avg) before this, since we rely on
cfs_rq->avg.last_update_time being current.

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

```c
void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
```

detach this entity from its cfs_rq load avg

**Parameters**

- `struct cfs_rq *cfs_rq`: cfs_rq to detach from
- `struct sched_entity *se`: sched_entity to detach

**Description**

Must call [`update_cfs_rq_load_avg()`](#c-update_cfs_rq_load_avg) before this, since we rely on
cfs_rq->avg.last_update_time being current.

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

```c
unsigned long cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
```

Estimates the amount of CPU capacity used by CFS tasks.

**Parameters**

- `int cpu`: the CPU to get the utilization for
- `struct task_struct *p`: task for which the CPU utilization should be predicted or NULL
- `int dst_cpu`: CPU **p** migrates to, -1 if **p** moves from **cpu** or **p** == NULL
- `int boost`: 1 to enable boosting, otherwise 0

**Description**

The unit of the return value must be the same as the one of CPU capacity
so that CPU utilization can be compared with CPU capacity.

CPU utilization is the sum of running time of runnable tasks plus the
recent utilization of currently non-runnable tasks on that CPU.
It represents the amount of CPU capacity currently used by CFS tasks in
the range \[0..max CPU capacity\] with max CPU capacity being the CPU
capacity at f_max.

The estimated CPU utilization is defined as the maximum between CPU
utilization and sum of the estimated utilization of the currently
runnable tasks on that CPU. It preserves a utilization "snapshot" of
previously-executed tasks, which helps better deduce how busy a CPU will
be when a long-sleeping task wakes up. The contribution to CPU utilization
of such a task would be significantly decayed at this point of time.

Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
CPU contention for CFS tasks can be detected by CPU runnable > CPU
utilization. Boosting is implemented in [`cpu_util()`](#c-cpu_util) so that internal
users (e.g. EAS) can use it next to external users (e.g. schedutil),
latter via `cpu_util_cfs_boost()`.

CPU utilization can be higher than the current CPU capacity
(f_curr/f_max * max CPU capacity) or even the max CPU capacity because
of rounding errors as well as task migrations or wakeups of new tasks.
CPU utilization has to be capped to fit into the \[0..max CPU capacity\]
range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
could be seen as over-utilized even though CPU1 has 20% of spare CPU
capacity. CPU utilization is allowed to overshoot current CPU capacity
though since this is useful for predicting the CPU capacity required
after task migrations (scheduler-driven DVFS).

**Return**

(Boosted) (estimated) utilization for the specified CPU.

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

```c
bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
```

Check whether asym_packing priority must be used

**Parameters**

- `struct sched_domain *sd`: The scheduling domain of the load balancing
- `int cpu`: A CPU

**Description**

Always use CPU priority when balancing load between SMT siblings. When
balancing load between cores, it is not sufficient that **cpu** is idle. Only
use CPU priority if the whole core is idle.

**Return**

True if the priority of **cpu** must be followed. False otherwise.

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

```c
bool sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
```

Check if the destination CPU can do asym_packing balance

**Parameters**

- `struct lb_env *env`: The load balancing environment
- `struct sg_lb_stats *sgs`: Load-balancing statistics of the candidate busiest group
- `struct sched_group *group`: The candidate busiest group

**Description**

**env**::dst_cpu can do asym_packing if it has higher priority than the
preferred CPU of **group**.

**Return**

true if **env**::dst_cpu can do with asym_packing load balance. False
otherwise.

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

```c
void update_sg_lb_stats(struct lb_env *env, struct sd_lb_stats *sds, struct sched_group *group, struct sg_lb_stats *sgs, bool *sg_overloaded, bool *sg_overutilized)
```

Update sched_group's statistics for load balancing.

**Parameters**

- `struct lb_env *env`: The load balancing environment.
- `struct sd_lb_stats *sds`: Load-balancing data with statistics of the local group.
- `struct sched_group *group`: sched_group whose statistics are to be updated.
- `struct sg_lb_stats *sgs`: variable to hold the statistics for this group.
- `bool *sg_overloaded`: sched_group is overloaded
- `bool *sg_overutilized`: sched_group is overutilized

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

```c
bool update_sd_pick_busiest(struct lb_env *env, struct sd_lb_stats *sds, struct sched_group *sg, struct sg_lb_stats *sgs)
```

return 1 on busiest group

**Parameters**

- `struct lb_env *env`: The load balancing environment.
- `struct sd_lb_stats *sds`: sched_domain statistics
- `struct sched_group *sg`: sched_group candidate to be checked for being the busiest
- `struct sg_lb_stats *sgs`: sched_group statistics

**Description**

Determine if **sg** is a busier group than the previously selected
busiest group.

**Return**

`true` if **sg** is a busier group than the previously selected
busiest group. `false` otherwise.

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

```c
int idle_cpu_without(int cpu, struct task_struct *p)
```

would a given CPU be idle without p ?

**Parameters**

- `int cpu`: the processor on which idleness is tested.
- `struct task_struct *p`: task which should be ignored.

**Return**

1 if the CPU would be idle. 0 otherwise.

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

```c
void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
```

Update sched_domain's statistics for load balancing.

**Parameters**

- `struct lb_env *env`: The load balancing environment.
- `struct sd_lb_stats *sds`: variable to hold the statistics for this sched_domain.

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

```c
void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
```

Calculate the amount of imbalance present within the groups of a given sched_domain during load balance.

**Parameters**

- `struct lb_env *env`: load balance environment
- `struct sd_lb_stats *sds`: statistics of the sched_domain whose imbalance is to be calculated.

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

```c
struct sched_group * sched_balance_find_src_group(struct lb_env *env)
```

Returns the busiest group within the sched_domain if there is an imbalance.

**Parameters**

- `struct lb_env *env`: The load balancing environment.

**Description**

Also calculates the amount of runnable load which should be moved
to restore balance.

**Return**

- The busiest group if imbalance exists.



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

```c
DECLARE_COMPLETION(work)
```

declare and initialize a completion structure

**Parameters**

- `work`: identifier for the completion structure

**Description**

This macro declares and initializes a completion structure. Generally used
for static declarations. You should use the _ONSTACK variant for automatic
variables.

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

```c
DECLARE_COMPLETION_ONSTACK(work)
```

declare and initialize a completion structure

**Parameters**

- `work`: identifier for the completion structure

**Description**

This macro declares and initializes a completion structure on the kernel
stack.

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

```c
void init_completion(struct completion *x)
```

Initialize a dynamically allocated completion

**Parameters**

- `struct completion *x`: pointer to completion structure that is to be initialized

**Description**

This inline function will initialize a dynamically created completion
structure.

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

```c
void reinit_completion(struct completion *x)
```

reinitialize a completion structure

**Parameters**

- `struct completion *x`: pointer to completion structure that is to be reinitialized

**Description**

This inline function should be used to reinitialize a completion structure so it can
be reused. This is especially important after `complete_all()` is used.


<a id="rst-time-and-timer-routines"></a>

## Time and timer routines


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

```c
u64 get_jiffies_64(void)
```

read the 64-bit non-atomic jiffies_64 value

**Parameters**

- `void`: no arguments

**Description**

When BITS_PER_LONG \< 64, this uses sequence number sampling using
jiffies_lock to protect the 64-bit read.

**Return**

current 64-bit jiffies value

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

```c
time_after(a, b)
```

returns true if the time a is after time b.

**Parameters**

- `a`: first comparable as unsigned long
- `b`: second comparable as unsigned long

**Description**

Do this with "\<0" and ">=0" to only test the sign of the result. A
good compiler would generate better code (and a really good compiler
wouldn't care). Gcc is currently neither.

**Return**

`true` is time a is after time b, otherwise `false`.

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

```c
time_before(a, b)
```

returns true if the time a is before time b.

**Parameters**

- `a`: first comparable as unsigned long
- `b`: second comparable as unsigned long

**Return**

`true` is time a is before time b, otherwise `false`.

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

```c
time_after_eq(a, b)
```

returns true if the time a is after or the same as time b.

**Parameters**

- `a`: first comparable as unsigned long
- `b`: second comparable as unsigned long

**Return**

`true` is time a is after or the same as time b, otherwise `false`.

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

```c
time_before_eq(a, b)
```

returns true if the time a is before or the same as time b.

**Parameters**

- `a`: first comparable as unsigned long
- `b`: second comparable as unsigned long

**Return**

`true` is time a is before or the same as time b, otherwise `false`.

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

```c
time_in_range(a, b, c)
```

Calculate whether a is in the range of \[b, c\].

**Parameters**

- `a`: time to test
- `b`: beginning of the range
- `c`: end of the range

**Return**

`true` is time a is in the range \[b, c\], otherwise `false`.

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

```c
time_in_range_open(a, b, c)
```

Calculate whether a is in the range of \[b, c).

**Parameters**

- `a`: time to test
- `b`: beginning of the range
- `c`: end of the range

**Return**

`true` is time a is in the range \[b, c), otherwise `false`.

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

```c
time_after64(a, b)
```

returns true if the time a is after time b.

**Parameters**

- `a`: first comparable as __u64
- `b`: second comparable as __u64

**Description**

This must be used when utilizing jiffies_64 (i.e. return value of
[`get_jiffies_64()`](#c-get_jiffies_64)).

**Return**

`true` is time a is after time b, otherwise `false`.

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

```c
time_before64(a, b)
```

returns true if the time a is before time b.

**Parameters**

- `a`: first comparable as __u64
- `b`: second comparable as __u64

**Description**

This must be used when utilizing jiffies_64 (i.e. return value of
[`get_jiffies_64()`](#c-get_jiffies_64)).

**Return**

`true` is time a is before time b, otherwise `false`.

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

```c
time_after_eq64(a, b)
```

returns true if the time a is after or the same as time b.

**Parameters**

- `a`: first comparable as __u64
- `b`: second comparable as __u64

**Description**

This must be used when utilizing jiffies_64 (i.e. return value of
[`get_jiffies_64()`](#c-get_jiffies_64)).

**Return**

`true` is time a is after or the same as time b, otherwise `false`.

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

```c
time_before_eq64(a, b)
```

returns true if the time a is before or the same as time b.

**Parameters**

- `a`: first comparable as __u64
- `b`: second comparable as __u64

**Description**

This must be used when utilizing jiffies_64 (i.e. return value of
[`get_jiffies_64()`](#c-get_jiffies_64)).

**Return**

`true` is time a is before or the same as time b, otherwise `false`.

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

```c
time_in_range64(a, b, c)
```

Calculate whether a is in the range of \[b, c\].

**Parameters**

- `a`: time to test
- `b`: beginning of the range
- `c`: end of the range

**Return**

`true` is time a is in the range \[b, c\], otherwise `false`.

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

```c
time_is_before_jiffies(a)
```

return true if a is before jiffies

**Parameters**

- `a`: time (unsigned long) to compare to jiffies

**Return**

`true` is time a is before jiffies, otherwise `false`.

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

```c
time_is_before_jiffies64(a)
```

return true if a is before jiffies_64

**Parameters**

- `a`: time (__u64) to compare to jiffies_64

**Return**

`true` is time a is before jiffies_64, otherwise `false`.

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

```c
time_is_after_jiffies(a)
```

return true if a is after jiffies

**Parameters**

- `a`: time (unsigned long) to compare to jiffies

**Return**

`true` is time a is after jiffies, otherwise `false`.

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

```c
time_is_after_jiffies64(a)
```

return true if a is after jiffies_64

**Parameters**

- `a`: time (__u64) to compare to jiffies_64

**Return**

`true` is time a is after jiffies_64, otherwise `false`.

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

```c
time_is_before_eq_jiffies(a)
```

return true if a is before or equal to jiffies

**Parameters**

- `a`: time (unsigned long) to compare to jiffies

**Return**

`true` is time a is before or the same as jiffies, otherwise `false`.

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

```c
time_is_before_eq_jiffies64(a)
```

return true if a is before or equal to jiffies_64

**Parameters**

- `a`: time (__u64) to compare to jiffies_64

**Return**

`true` is time a is before or the same jiffies_64, otherwise `false`.

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

```c
time_is_after_eq_jiffies(a)
```

return true if a is after or equal to jiffies

**Parameters**

- `a`: time (unsigned long) to compare to jiffies

**Return**

`true` is time a is after or the same as jiffies, otherwise `false`.

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

```c
time_is_after_eq_jiffies64(a)
```

return true if a is after or equal to jiffies_64

**Parameters**

- `a`: time (__u64) to compare to jiffies_64

**Return**

`true` is time a is after or the same as jiffies_64, otherwise `false`.

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

```c
unsigned int jiffies_to_msecs(const unsigned long j)
```

Convert jiffies to milliseconds

**Parameters**

- `const unsigned long j`: jiffies value

**Description**

This inline version takes care of HZ in {100,250,1000}.

**Return**

milliseconds value

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

```c
unsigned int jiffies_to_usecs(const unsigned long j)
```

Convert jiffies to microseconds

**Parameters**

- `const unsigned long j`: jiffies value

**Return**

microseconds value

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

```c
u64 jiffies_to_nsecs(const unsigned long j)
```

Convert jiffies to nanoseconds

**Parameters**

- `const unsigned long j`: jiffies value

**Return**

nanoseconds value

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

```c
unsigned long msecs_to_jiffies(const unsigned int m)
```

- convert milliseconds to jiffies

**Parameters**

- `const unsigned int m`: time in milliseconds

**Description**

conversion is done as follows:

- negative values mean 'infinite timeout' (MAX_JIFFY_OFFSET)

- 'too large' values \[that would result in larger than
  MAX_JIFFY_OFFSET values\] mean 'infinite timeout' too.

- all other values are converted to jiffies by either multiplying
  the input value by a factor or dividing it with a factor and
  handling any 32-bit overflows.
  for the details see `_msecs_to_jiffies()`

[`msecs_to_jiffies()`](#c-msecs_to_jiffies) checks for the passed in value being a constant
via `__builtin_constant_p()` allowing gcc to eliminate most of the
code. [`__msecs_to_jiffies()`](#c-__msecs_to_jiffies) is called if the value passed does not
allow constant folding and the actual conversion must be done at
runtime.
The HZ range specific helpers `_msecs_to_jiffies()` are called both
directly here and from [`__msecs_to_jiffies()`](#c-__msecs_to_jiffies) in the case where
constant folding is not possible.

**Return**

jiffies value

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

```c
secs_to_jiffies(_secs)
```

- convert seconds to jiffies

**Parameters**

- `_secs`: time in seconds

**Description**

Conversion is done by simple multiplication with HZ

[`secs_to_jiffies()`](#c-secs_to_jiffies) is defined as a macro rather than a static inline
function so it can be used in static initializers.

**Return**

jiffies value

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

```c
unsigned long usecs_to_jiffies(const unsigned int u)
```

- convert microseconds to jiffies

**Parameters**

- `const unsigned int u`: time in microseconds

**Description**

conversion is done as follows:

- 'too large' values \[that would result in larger than
  MAX_JIFFY_OFFSET values\] mean 'infinite timeout' too.

- all other values are converted to jiffies by either multiplying
  the input value by a factor or dividing it with a factor and
  handling any 32-bit overflows as for msecs_to_jiffies.

[`usecs_to_jiffies()`](#c-usecs_to_jiffies) checks for the passed in value being a constant
via `__builtin_constant_p()` allowing gcc to eliminate most of the
code. [`__usecs_to_jiffies()`](#c-__usecs_to_jiffies) is called if the value passed does not
allow constant folding and the actual conversion must be done at
runtime.
The HZ range specific helpers `_usecs_to_jiffies()` are called both
directly here and from [`__msecs_to_jiffies()`](#c-__msecs_to_jiffies) in the case where
constant folding is not possible.

**Return**

jiffies value



#### `jiffies_to_msecs()`

```c
unsigned int jiffies_to_msecs(const unsigned long j)
```

Convert jiffies to milliseconds

**Parameters**

- `const unsigned long j`: jiffies value

**Return**

milliseconds value

#### `jiffies_to_usecs()`

```c
unsigned int jiffies_to_usecs(const unsigned long j)
```

Convert jiffies to microseconds

**Parameters**

- `const unsigned long j`: jiffies value

**Return**

microseconds value

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

```c
time64_t mktime64(const unsigned int year0, const unsigned int mon0, const unsigned int day, const unsigned int hour, const unsigned int min, const unsigned int sec)
```

Converts date to seconds.

**Parameters**

- `const unsigned int year0`: year to convert
- `const unsigned int mon0`: month to convert
- `const unsigned int day`: day to convert
- `const unsigned int hour`: hour to convert
- `const unsigned int min`: minute to convert
- `const unsigned int sec`: second to convert

**Description**

Converts Gregorian date to seconds since 1970-01-01 00:00:00.
Assumes input in normal date format, i.e. 1980-12-31 23:59:59
=> year=1980, mon=12, day=31, hour=23, min=59, sec=59.

\[For the Julian calendar (which was used in Russia before 1917,
Britain & colonies before 1752, anywhere else before 1582,
and is still in use by some communities) leave out the
-year/100+year/400 terms, and add 10.\]

This algorithm was first published by Gauss (I think).

A leap second can be indicated by calling this function with sec as
60 (allowable under ISO 8601).  The leap second is treated the same
as the following second since they don't exist in UNIX time.

An encoding of midnight at the end of the day as 24:00:00 - ie. midnight
tomorrow - (allowable under ISO 8601) is supported.

**Return**

seconds since the epoch time for the given input date

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

```c
void set_normalized_timespec64(struct timespec64 *ts, time64_t sec, s64 nsec)
```

set timespec sec and nsec parts and normalize

**Parameters**

- `struct timespec64 *ts`: pointer to timespec variable to be set
- `time64_t sec`: seconds to set
- `s64 nsec`: nanoseconds to set

**Description**

Set seconds and nanoseconds field of a timespec variable and
normalize to the timespec storage format

**Note**

The tv_nsec part is always in the range of 0 \<= tv_nsec \< NSEC_PER_SEC.
For negative values only the tv_sec field is negative !

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

```c
struct timespec64 ns_to_timespec64(s64 nsec)
```

Convert nanoseconds to timespec64

**Parameters**

- `s64 nsec`: the nanoseconds value to be converted

**Return**

the timespec64 representation of the nsec parameter.

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

```c
unsigned long __msecs_to_jiffies(const unsigned int m)
```

- convert milliseconds to jiffies

**Parameters**

- `const unsigned int m`: time in milliseconds

**Description**

conversion is done as follows:

- negative values mean 'infinite timeout' (MAX_JIFFY_OFFSET)

- 'too large' values \[that would result in larger than
  MAX_JIFFY_OFFSET values\] mean 'infinite timeout' too.

- all other values are converted to jiffies by either multiplying
  the input value by a factor or dividing it with a factor and
  handling any 32-bit overflows.
  for the details see `_msecs_to_jiffies()`

[`msecs_to_jiffies()`](#c-msecs_to_jiffies) checks for the passed in value being a constant
via `__builtin_constant_p()` allowing gcc to eliminate most of the
code, [`__msecs_to_jiffies()`](#c-__msecs_to_jiffies) is called if the value passed does not
allow constant folding and the actual conversion must be done at
runtime.
The _msecs_to_jiffies helpers are the HZ dependent conversion
routines found in include/linux/jiffies.h

**Return**

jiffies value

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

```c
unsigned long __usecs_to_jiffies(const unsigned int u)
```

- convert microseconds to jiffies

**Parameters**

- `const unsigned int u`: time in milliseconds

**Return**

jiffies value

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

```c
unsigned long timespec64_to_jiffies(const struct timespec64 *value)
```

convert a timespec64 value to jiffies

**Parameters**

- `const struct timespec64 *value`: pointer to `struct timespec64`

**Description**

The TICK_NSEC - 1 rounds up the value to the next resolution.  Note
that a remainder subtract here would not do the right thing as the
resolution values don't fall on second boundaries.  I.e. the line:
nsec -= nsec % TICK_NSEC; is NOT a correct resolution rounding.
Note that due to the small error in the multiplier here, this
rounding is incorrect for sufficiently large values of tv_nsec, but
well formed timespecs should have tv_nsec \< NSEC_PER_SEC, so we're
OK.

Rather, we just shift the bits off the right.

The >> (NSEC_JIFFIE_SC - SEC_JIFFIE_SC) converts the scaled nsec
value to a scaled second value.

**Return**

jiffies value

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

```c
void jiffies_to_timespec64(const unsigned long jiffies, struct timespec64 *value)
```

convert jiffies value to `struct timespec64`

**Parameters**

- `const unsigned long jiffies`: jiffies value
- `struct timespec64 *value`: pointer to `struct timespec64`

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

```c
clock_t jiffies_to_clock_t(unsigned long x)
```

Convert jiffies to clock_t

**Parameters**

- `unsigned long x`: jiffies value

**Return**

jiffies converted to clock_t (CLOCKS_PER_SEC)

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

```c
unsigned long clock_t_to_jiffies(unsigned long x)
```

Convert clock_t to jiffies

**Parameters**

- `unsigned long x`: clock_t value

**Return**

clock_t value converted to jiffies

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

```c
notrace u64 jiffies_64_to_clock_t(u64 x)
```

Convert jiffies_64 to clock_t

**Parameters**

- `u64 x`: jiffies_64 value

**Return**

jiffies_64 value converted to 64-bit "clock_t" (CLOCKS_PER_SEC)

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

```c
u64 jiffies64_to_nsecs(u64 j)
```

Convert jiffies64 to nanoseconds

**Parameters**

- `u64 j`: jiffies64 value

**Return**

nanoseconds value

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

```c
u64 jiffies64_to_msecs(const u64 j)
```

Convert jiffies64 to milliseconds

**Parameters**

- `const u64 j`: jiffies64 value

**Return**

milliseconds value

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

```c
u64 nsecs_to_jiffies64(u64 n)
```

Convert nsecs in u64 to jiffies64

**Parameters**

- `u64 n`: nsecs in u64

**Description**

Unlike {m,u}secs_to_jiffies, type of input is not unsigned int but u64.
And this doesn't return MAX_JIFFY_OFFSET since this function is designed
for scheduler, not for use in device drivers to calculate timeout value.

**note**

NSEC_PER_SEC = 10^9 = (5^9 * 2^9) = (1953125 * 512)
ULLONG_MAX ns = 18446744073.709551615 secs = about 584 years

**Return**

nsecs converted to jiffies64 value

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

```c
unsigned long nsecs_to_jiffies(u64 n)
```

Convert nsecs in u64 to jiffies

**Parameters**

- `u64 n`: nsecs in u64

**Description**

Unlike {m,u}secs_to_jiffies, type of input is not unsigned int but u64.
And this doesn't return MAX_JIFFY_OFFSET since this function is designed
for scheduler, not for use in device drivers to calculate timeout value.

**note**

NSEC_PER_SEC = 10^9 = (5^9 * 2^9) = (1953125 * 512)
ULLONG_MAX ns = 18446744073.709551615 secs = about 584 years

**Return**

nsecs converted to jiffies value

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

```c
struct timespec64 timespec64_add_safe(const struct timespec64 lhs, const struct timespec64 rhs)
```

Add two timespec64 values and do a safety check for overflow.

**Parameters**

- `const struct timespec64 lhs`: first (left) timespec64 to add
- `const struct timespec64 rhs`: second (right) timespec64 to add

**Description**

It's assumed that both values are valid (>= 0).
And, each timespec64 is in normalized form.

**Return**

sum of **lhs** + **rhs**

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

```c
int get_timespec64(struct timespec64 *ts, const struct __kernel_timespec __user *uts)
```

get user's time value into kernel space

**Parameters**

- `struct timespec64 *ts`: destination `struct timespec64`
- `const struct __kernel_timespec __user *uts`: user's time value as `struct __kernel_timespec`

**Description**

Handles compat or 32-bit modes.

**Return**

0 on success or negative errno on error

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

```c
int put_timespec64(const struct timespec64 *ts, struct __kernel_timespec __user *uts)
```

convert timespec64 value to __kernel_timespec format and copy the latter to userspace

**Parameters**

- `const struct timespec64 *ts`: input `struct timespec64`
- `struct __kernel_timespec __user *uts`: user's `struct __kernel_timespec`

**Return**

0 on success or negative errno on error

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

```c
int get_old_timespec32(struct timespec64 *ts, const void __user *uts)
```

get user's old-format time value into kernel space

**Parameters**

- `struct timespec64 *ts`: destination `struct timespec64`
- `const void __user *uts`: user's old-format time value (`struct old_timespec32`)

**Description**

Handles X86_X32_ABI compatibility conversion.

**Return**

0 on success or negative errno on error

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

```c
int put_old_timespec32(const struct timespec64 *ts, void __user *uts)
```

convert timespec64 value to `struct old_timespec32` and copy the latter to userspace

**Parameters**

- `const struct timespec64 *ts`: input `struct timespec64`
- `void __user *uts`: user's `struct old_timespec32`

**Description**

Handles X86_X32_ABI compatibility conversion.

**Return**

0 on success or negative errno on error

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

```c
int get_itimerspec64(struct itimerspec64 *it, const struct __kernel_itimerspec __user *uit)
```

get user's `struct __kernel_itimerspec` into kernel space

**Parameters**

- `struct itimerspec64 *it`: destination `struct itimerspec64`
- `const struct __kernel_itimerspec __user *uit`: user's `struct __kernel_itimerspec`

**Return**

0 on success or negative errno on error

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

```c
int put_itimerspec64(const struct itimerspec64 *it, struct __kernel_itimerspec __user *uit)
```

convert `struct itimerspec64` to __kernel_itimerspec format and copy the latter to userspace

**Parameters**

- `const struct itimerspec64 *it`: input `struct itimerspec64`
- `struct __kernel_itimerspec __user *uit`: user's `struct __kernel_itimerspec`

**Return**

0 on success or negative errno on error

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

```c
int get_old_itimerspec32(struct itimerspec64 *its, const struct old_itimerspec32 __user *uits)
```

get user's `struct old_itimerspec32` into kernel space

**Parameters**

- `struct itimerspec64 *its`: destination `struct itimerspec64`
- `const struct old_itimerspec32 __user *uits`: user's `struct old_itimerspec32`

**Return**

0 on success or negative errno on error

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

```c
int put_old_itimerspec32(const struct itimerspec64 *its, struct old_itimerspec32 __user *uits)
```

convert `struct itimerspec64` to `struct old_itimerspec32` and copy the latter to userspace

**Parameters**

- `const struct itimerspec64 *its`: input `struct itimerspec64`
- `struct old_itimerspec32 __user *uits`: user's `struct old_itimerspec32`

**Return**

0 on success or negative errno on error



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

```c
unsigned long __round_jiffies_relative(unsigned long j, int cpu)
```

function to round jiffies to a full second

**Parameters**

- `unsigned long j`: the time in (relative) jiffies that should be rounded
- `int cpu`: the processor number on which the timeout will happen

**Description**

[`__round_jiffies_relative()`](#c-__round_jiffies_relative) rounds a time delta  in the future (in jiffies)
up or down to (approximately) full seconds. This is useful for timers
for which the exact time they fire does not matter too much, as long as
they fire approximately every X seconds.

By rounding these timers to whole seconds, all such timers will fire
at the same time, rather than at various times spread out. The goal
of this is to have the CPU wake up less, which saves power.

The exact rounding is skewed for each processor to avoid all
processors firing at the exact same time, which could lead
to lock contention or spurious cache line bouncing.

The return value is the rounded version of the **j** parameter.

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

```c
unsigned long round_jiffies(unsigned long j)
```

function to round jiffies to a full second

**Parameters**

- `unsigned long j`: the time in (absolute) jiffies that should be rounded

**Description**

[`round_jiffies()`](#c-round_jiffies) rounds an absolute time in the future (in jiffies)
up or down to (approximately) full seconds. This is useful for timers
for which the exact time they fire does not matter too much, as long as
they fire approximately every X seconds.

By rounding these timers to whole seconds, all such timers will fire
at the same time, rather than at various times spread out. The goal
of this is to have the CPU wake up less, which saves power.

The return value is the rounded version of the **j** parameter.

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

```c
unsigned long round_jiffies_relative(unsigned long j)
```

function to round jiffies to a full second

**Parameters**

- `unsigned long j`: the time in (relative) jiffies that should be rounded

**Description**

[`round_jiffies_relative()`](#c-round_jiffies_relative) rounds a time delta  in the future (in jiffies)
up or down to (approximately) full seconds. This is useful for timers
for which the exact time they fire does not matter too much, as long as
they fire approximately every X seconds.

By rounding these timers to whole seconds, all such timers will fire
at the same time, rather than at various times spread out. The goal
of this is to have the CPU wake up less, which saves power.

The return value is the rounded version of the **j** parameter.

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

```c
unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
```

function to round jiffies up to a full second

**Parameters**

- `unsigned long j`: the time in (relative) jiffies that should be rounded
- `int cpu`: the processor number on which the timeout will happen

**Description**

This is the same as [`__round_jiffies_relative()`](#c-__round_jiffies_relative) except that it will never
round down.  This is useful for timeouts for which the exact time
of firing does not matter too much, as long as they don't fire too
early.

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

```c
unsigned long round_jiffies_up(unsigned long j)
```

function to round jiffies up to a full second

**Parameters**

- `unsigned long j`: the time in (absolute) jiffies that should be rounded

**Description**

This is the same as [`round_jiffies()`](#c-round_jiffies) except that it will never
round down.  This is useful for timeouts for which the exact time
of firing does not matter too much, as long as they don't fire too
early.

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

```c
unsigned long round_jiffies_up_relative(unsigned long j)
```

function to round jiffies up to a full second

**Parameters**

- `unsigned long j`: the time in (relative) jiffies that should be rounded

**Description**

This is the same as [`round_jiffies_relative()`](#c-round_jiffies_relative) except that it will never
round down.  This is useful for timeouts for which the exact time
of firing does not matter too much, as long as they don't fire too
early.

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

```c
void timer_init_key(struct timer_list *timer, void (*func)(struct timer_list *), unsigned int flags, const char *name, struct lock_class_key *key)
```

initialize a timer

**Parameters**

- `struct timer_list *timer`: the timer to be initialized
- `void (*func)(struct timer_list *)`: timer callback function
- `unsigned int flags`: timer flags
- `const char *name`: name of the timer
- `struct lock_class_key *key`: lockdep class key of the fake lock used for tracking timer
  sync lock dependencies

**Description**

[`timer_init_key()`](#c-timer_init_key) must be done to a timer prior to calling *any* of the
other timer functions.

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

```c
int mod_timer_pending(struct timer_list *timer, unsigned long expires)
```

Modify a pending timer's timeout

**Parameters**

- `struct timer_list *timer`: The pending timer to be modified
- `unsigned long expires`: New absolute timeout in jiffies

**Description**

[`mod_timer_pending()`](#c-mod_timer_pending) is the same for pending timers as [`mod_timer()`](#c-mod_timer), but
will not activate inactive timers.

If **timer->function** == NULL then the start operation is silently
discarded.

**Return**

* `0` - The timer was inactive and not modified or was in
  shutdown state and the operation was discarded
* `1` - The timer was active and requeued to expire at **expires**

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

```c
int mod_timer(struct timer_list *timer, unsigned long expires)
```

Modify a timer's timeout

**Parameters**

- `struct timer_list *timer`: The timer to be modified
- `unsigned long expires`: New absolute timeout in jiffies

**Description**

mod_timer(timer, expires) is equivalent to:

timer_delete(timer); timer->expires = expires; add_timer(timer);

[`mod_timer()`](#c-mod_timer) is more efficient than the above open coded sequence. In
case that the timer is inactive, the [`timer_delete()`](#c-timer_delete) part is a NOP. The
timer is in any case activated with the new expiry time **expires**.

Note that if there are multiple unserialized concurrent users of the
same timer, then [`mod_timer()`](#c-mod_timer) is the only safe way to modify the timeout,
since [`add_timer()`](#c-add_timer) cannot modify an already running timer.

If **timer->function** == NULL then the start operation is silently
discarded. In this case the return value is 0 and meaningless.

**Return**

* `0` - The timer was inactive and started or was in shutdown
  state and the operation was discarded
* `1` - The timer was active and requeued to expire at **expires** or
  the timer was active and not modified because **expires** did
  not change the effective expiry time

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

```c
int timer_reduce(struct timer_list *timer, unsigned long expires)
```

Modify a timer's timeout if it would reduce the timeout

**Parameters**

- `struct timer_list *timer`: The timer to be modified
- `unsigned long expires`: New absolute timeout in jiffies

**Description**

[`timer_reduce()`](#c-timer_reduce) is very similar to [`mod_timer()`](#c-mod_timer), except that it will only
modify an enqueued timer if that would reduce the expiration time. If
**timer** is not enqueued it starts the timer.

If **timer->function** == NULL then the start operation is silently
discarded.

**Return**

* `0` - The timer was inactive and started or was in shutdown
  state and the operation was discarded
* `1` - The timer was active and requeued to expire at **expires** or
  the timer was active and not modified because **expires**
  did not change the effective expiry time such that the
  timer would expire earlier than already scheduled

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

```c
void add_timer(struct timer_list *timer)
```

Start a timer

**Parameters**

- `struct timer_list *timer`: The timer to be started

**Description**

Start **timer** to expire at **timer->expires** in the future. **timer->expires**
is the absolute expiry time measured in 'jiffies'. When the timer expires
timer->function(timer) will be invoked from soft interrupt context.

The **timer->expires** and **timer->function** fields must be set prior
to calling this function.

If **timer->function** == NULL then the start operation is silently
discarded.

If **timer->expires** is already in the past **timer** will be queued to
expire at the next timer tick.

This can only operate on an inactive timer. Attempts to invoke this on
an active timer are rejected with a warning.

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

```c
void add_timer_local(struct timer_list *timer)
```

Start a timer on the local CPU

**Parameters**

- `struct timer_list *timer`: The timer to be started

**Description**

Same as [`add_timer()`](#c-add_timer) except that the timer flag TIMER_PINNED is set.

See [`add_timer()`](#c-add_timer) for further details.

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

```c
void add_timer_global(struct timer_list *timer)
```

Start a timer without TIMER_PINNED flag set

**Parameters**

- `struct timer_list *timer`: The timer to be started

**Description**

Same as [`add_timer()`](#c-add_timer) except that the timer flag TIMER_PINNED is unset.

See [`add_timer()`](#c-add_timer) for further details.

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

```c
void add_timer_on(struct timer_list *timer, int cpu)
```

Start a timer on a particular CPU

**Parameters**

- `struct timer_list *timer`: The timer to be started
- `int cpu`: The CPU to start it on

**Description**

Same as [`add_timer()`](#c-add_timer) except that it starts the timer on the given CPU and
the TIMER_PINNED flag is set. When timer shouldn't be a pinned timer in
the next round, [`add_timer_global()`](#c-add_timer_global) should be used instead as it unsets
the TIMER_PINNED flag.

See [`add_timer()`](#c-add_timer) for further details.

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

```c
int timer_delete(struct timer_list *timer)
```

Deactivate a timer

**Parameters**

- `struct timer_list *timer`: The timer to be deactivated

**Description**

The function only deactivates a pending timer, but contrary to
[`timer_delete_sync()`](#c-timer_delete_sync) it does not take into account whether the timer's
callback function is concurrently executed on a different CPU or not.
It neither prevents rearming of the timer.  If **timer** can be rearmed
concurrently then the return value of this function is meaningless.

**Return**

* `0` - The timer was not pending
* `1` - The timer was pending and deactivated

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

```c
int timer_shutdown(struct timer_list *timer)
```

Deactivate a timer and prevent rearming

**Parameters**

- `struct timer_list *timer`: The timer to be deactivated

**Description**

The function does not wait for an eventually running timer callback on a
different CPU but it prevents rearming of the timer. Any attempt to arm
**timer** after this function returns will be silently ignored.

This function is useful for teardown code and should only be used when
[`timer_shutdown_sync()`](#c-timer_shutdown_sync) cannot be invoked due to locking or context constraints.

**Return**

* `0` - The timer was not pending
* `1` - The timer was pending

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

```c
int timer_delete_sync_try(struct timer_list *timer)
```

Try to deactivate a timer

**Parameters**

- `struct timer_list *timer`: Timer to deactivate

**Description**

This function tries to deactivate a timer. On success the timer is not
queued and the timer callback function is not running on any CPU.

This function does not guarantee that the timer cannot be rearmed right
after dropping the base lock. That needs to be prevented by the calling
code if necessary.

**Return**

* `0`  - The timer was not pending
* `1`  - The timer was pending and deactivated
* `-1` - The timer callback function is running on a different CPU

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

```c
int timer_delete_sync(struct timer_list *timer)
```

Deactivate a timer and wait for the handler to finish.

**Parameters**

- `struct timer_list *timer`: The timer to be deactivated

**Description**

Synchronization rules: Callers must prevent restarting of the timer,
otherwise this function is meaningless. It must not be called from
interrupt contexts unless the timer is an irqsafe one. The caller must
not hold locks which would prevent completion of the timer's callback
function. The timer's handler must not call [`add_timer_on()`](#c-add_timer_on). Upon exit
the timer is not queued and the handler is not running on any CPU.

For !irqsafe timers, the caller must not hold locks that are held in
interrupt context. Even if the lock has nothing to do with the timer in
question.  Here's why:

```text
CPU0                             CPU1
----                             ----
                                 <SOFTIRQ>
                                   call_timer_fn();
                                   base->running_timer = mytimer;
spin_lock_irq(somelock);
                                 <IRQ>
                                    spin_lock(somelock);
timer_delete_sync(mytimer);
while (base->running_timer == mytimer);
```

Now [`timer_delete_sync()`](#c-timer_delete_sync) will never return and never release somelock.
The interrupt on the other CPU is waiting to grab somelock but it has
interrupted the softirq that CPU0 is waiting to finish.

This function cannot guarantee that the timer is not rearmed again by
some concurrent or preempting code, right after it dropped the base
lock. If there is the possibility of a concurrent rearm then the return
value of the function is meaningless.

If such a guarantee is needed, e.g. for teardown situations then use
[`timer_shutdown_sync()`](#c-timer_shutdown_sync) instead.

**Return**

* `0` - The timer was not pending
* `1` - The timer was pending and deactivated

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

```c
int timer_shutdown_sync(struct timer_list *timer)
```

Shutdown a timer and prevent rearming

**Parameters**

- `struct timer_list *timer`: The timer to be shutdown

**Description**

- When the function returns it is guaranteed that:
  - **timer** is not queued
  - The callback function of **timer** is not running
  - **timer** cannot be enqueued again. Any attempt to rearm
    **timer** is silently ignored.

See [`timer_delete_sync()`](#c-timer_delete_sync) for synchronization rules.

This function is useful for final teardown of an infrastructure where
the timer is subject to a circular dependency problem.

A common pattern for this is a timer and a workqueue where the timer can
schedule work and work can arm the timer. On shutdown the workqueue must
be destroyed and the timer must be prevented from rearming. Unless the
code has conditionals like 'if (mything->in_shutdown)' to prevent that
there is no way to get this correct with [`timer_delete_sync()`](#c-timer_delete_sync).

[`timer_shutdown_sync()`](#c-timer_shutdown_sync) is solving the problem. The correct ordering of
calls in this case is:

timer_shutdown_sync(`mything->timer`);
workqueue_destroy(`mything->workqueue`);

After this 'mything' can be safely freed.

This obviously implies that the timer is not required to be functional
for the rest of the shutdown operation.

**Return**

* `0` - The timer was not pending
* `1` - The timer was pending


<a id="rst-high-resolution-timers"></a>

## High-resolution timers


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

```c
ktime_t ktime_set(const s64 secs, const unsigned long nsecs)
```

Set a ktime_t variable from a seconds/nanoseconds value

**Parameters**

- `const s64 secs`: seconds to set
- `const unsigned long nsecs`: nanoseconds to set

**Return**

The ktime_t representation of the value.

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

```c
int ktime_compare(const ktime_t cmp1, const ktime_t cmp2)
```

Compares two ktime_t variables for less, greater or equal

**Parameters**

- `const ktime_t cmp1`: comparable1
- `const ktime_t cmp2`: comparable2

**Return**

\...
cmp1  \< cmp2: return \<0
cmp1 == cmp2: return 0
cmp1  > cmp2: return >0

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

```c
bool ktime_after(const ktime_t cmp1, const ktime_t cmp2)
```

Compare if a ktime_t value is bigger than another one.

**Parameters**

- `const ktime_t cmp1`: comparable1
- `const ktime_t cmp2`: comparable2

**Return**

true if cmp1 happened after cmp2.

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

```c
bool ktime_before(const ktime_t cmp1, const ktime_t cmp2)
```

Compare if a ktime_t value is smaller than another one.

**Parameters**

- `const ktime_t cmp1`: comparable1
- `const ktime_t cmp2`: comparable2

**Return**

true if cmp1 happened before cmp2.

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

```c
bool ktime_to_timespec64_cond(const ktime_t kt, struct timespec64 *ts)
```

convert a ktime_t variable to timespec64 format only if the variable contains data

**Parameters**

- `const ktime_t kt`: the ktime_t variable to convert
- `struct timespec64 *ts`: the timespec variable to store the result in

**Return**

`true` if there was a successful conversion, `false` if kt was 0.



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

simple sleeper structure

**Definition**

```c
struct hrtimer_sleeper {
    struct hrtimer timer;
    struct task_struct *task;
};
```

**Members**

- `timer`: embedded timer structure
- `task`: task to wake up

**Description**

task is set to NULL, when the timer expires.

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

```c
void hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
```

(re)start an hrtimer

**Parameters**

- `struct hrtimer *timer`: the timer to be added
- `ktime_t tim`: expiry time
- `const enum hrtimer_mode mode`: timer mode: absolute (HRTIMER_MODE_ABS) or
  relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED);
  softirq based mode is considered for debug purpose only!

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

```c
ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
```

get remaining time for the timer

**Parameters**

- `const struct hrtimer *timer`: the timer to read

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

```c
bool hrtimer_is_queued(struct hrtimer *timer)
```

check, whether the timer is on one of the queues

**Parameters**

- `struct hrtimer *timer`: Timer to check

**Return**

True if the timer is queued, false otherwise

**Description**

The function can be used lockless, but it gives only a current snapshot.

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

```c
void hrtimer_update_function(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *))
```

Update the timer's callback function

**Parameters**

- `struct hrtimer *timer`: Timer to update
- `enum hrtimer_restart (*function)(struct hrtimer *)`: New callback function

**Description**

Only safe to call if the timer is not enqueued. Can be called in the callback function if the
timer is not enqueued at the same time (see the comments above HRTIMER_STATE_ENQUEUED).

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

```c
u64 hrtimer_forward_now(struct hrtimer *timer, ktime_t interval)
```

forward the timer expiry so it expires after now

**Parameters**

- `struct hrtimer *timer`: hrtimer to forward
- `ktime_t interval`: the interval to forward

**Description**

It is a variant of [`hrtimer_forward()`](#c-hrtimer_forward). The timer will expire after the current
time of the hrtimer clock base. See [`hrtimer_forward()`](#c-hrtimer_forward) for details.



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

```c
u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
```

forward the timer expiry

**Parameters**

- `struct hrtimer *timer`: hrtimer to forward
- `ktime_t now`: forward past this time
- `ktime_t interval`: the interval to forward

**Description**

Forward the timer expiry so it will expire in the future.

> [!NOTE]
> This only updates the timer expiry value and does not requeue the timer.

There is also a variant of the function [`hrtimer_forward_now()`](#c-hrtimer_forward_now).

**Context**

Can be safely called from the callback function of **timer**. If called
from other contexts **timer** must neither be enqueued nor running the
callback and the caller needs to take care of serialization.

**Return**

The number of overruns are returned.

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

```c
void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim, u64 delta_ns, const enum hrtimer_mode mode)
```

(re)start an hrtimer

**Parameters**

- `struct hrtimer *timer`: the timer to be added
- `ktime_t tim`: expiry time
- `u64 delta_ns`: "slack" range for the timer
- `const enum hrtimer_mode mode`: timer mode: absolute (HRTIMER_MODE_ABS) or
  relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED);
  softirq based mode is considered for debug purpose only!

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

```c
int hrtimer_try_to_cancel(struct hrtimer *timer)
```

try to deactivate a timer

**Parameters**

- `struct hrtimer *timer`: hrtimer to stop

**Description**

* 0 when the timer was not active
* 1 when the timer was active
* -1 when the timer is currently executing the callback function and
  cannot be stopped

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

```c
int hrtimer_cancel(struct hrtimer *timer)
```

cancel a timer and wait for the handler to finish.

**Parameters**

- `struct hrtimer *timer`: the timer to be cancelled

**Return**

0 when the timer was not active
1 when the timer was active

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

```c
ktime_t __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust)
```

get remaining time for the timer

**Parameters**

- `const struct hrtimer *timer`: the timer to read
- `bool adjust`: adjust relative timers when CONFIG_TIME_LOW_RES=y

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

```c
void hrtimer_setup(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *), clockid_t clock_id, enum hrtimer_mode mode)
```

initialize a timer to the given clock

**Parameters**

- `struct hrtimer *timer`: the timer to be initialized
- `enum hrtimer_restart (*function)(struct hrtimer *)`: the callback function
- `clockid_t clock_id`: the clock to be used
- `enum hrtimer_mode mode`: The modes which are relevant for initialization:
  HRTIMER_MODE_ABS, HRTIMER_MODE_REL, HRTIMER_MODE_ABS_SOFT,
  HRTIMER_MODE_REL_SOFT

**Description**

The PINNED variants of the above can be handed in,
but the PINNED bit is ignored as pinning happens
when the hrtimer is started

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

```c
void hrtimer_setup_on_stack(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *), clockid_t clock_id, enum hrtimer_mode mode)
```

initialize a timer on stack memory

**Parameters**

- `struct hrtimer *timer`: The timer to be initialized
- `enum hrtimer_restart (*function)(struct hrtimer *)`: the callback function
- `clockid_t clock_id`: The clock to be used
- `enum hrtimer_mode mode`: The timer mode

**Description**

Similar to [`hrtimer_setup()`](#c-hrtimer_setup), except that this one must be used if struct hrtimer is in stack
memory.

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

```c
void hrtimer_sleeper_start_expires(struct hrtimer_sleeper *sl, enum hrtimer_mode mode)
```

Start a hrtimer sleeper timer

**Parameters**

- `struct hrtimer_sleeper *sl`: sleeper to be started
- `enum hrtimer_mode mode`: timer mode abs/rel

**Description**

Wrapper around `hrtimer_start_expires()` for hrtimer_sleeper based timers
to allow PREEMPT_RT to tweak the delivery mode (soft/hardirq context)

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

```c
void hrtimer_setup_sleeper_on_stack(struct hrtimer_sleeper *sl, clockid_t clock_id, enum hrtimer_mode mode)
```

initialize a sleeper in stack memory

**Parameters**

- `struct hrtimer_sleeper *sl`: sleeper to be initialized
- `clockid_t clock_id`: the clock to be used
- `enum hrtimer_mode mode`: timer mode abs/rel


<a id="rst-wait-queues-and-wake-events"></a>

## Wait queues and Wake events


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

```c
int waitqueue_active(struct wait_queue_head *wq_head)
```

- locklessly test for waiters on the queue

**Parameters**

- `struct wait_queue_head *wq_head`: the waitqueue to test for waiters

**Description**

returns true if the wait list is not empty

**NOTE**

this function is lockless and requires care, incorrect usage _will_
lead to sporadic and non-obvious failure.

Use either while holding wait_queue_head::lock or when used for wakeups
with an extra `smp_mb()` like:

```text
CPU0 - waker                    CPU1 - waiter

                                for (;;) {
@cond = true;                     prepare_to_wait(&wq_head, &wait, state);
smp_mb();                         // smp_mb() from set_current_state()
if (waitqueue_active(wq_head))         if (@cond)
  wake_up(wq_head);                      break;
                                  schedule();
                                }
                                finish_wait(&wq_head, &wait);
```

Because without the explicit `smp_mb()` it's possible for the
[`waitqueue_active()`](#c-waitqueue_active) load to get hoisted over the **cond** store such that we'll
observe an empty wait list while the waiter might not observe **cond**.

Also note that this 'optimization' trades a `spin_lock()` for an `smp_mb()`,
which (when the lock is uncontended) are of roughly equal cost.

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

```c
bool wq_has_single_sleeper(struct wait_queue_head *wq_head)
```

check if there is only one sleeper

**Parameters**

- `struct wait_queue_head *wq_head`: wait queue head

**Description**

Returns true of wq_head has only one sleeper on the list.

Please refer to the comment for waitqueue_active.

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

```c
bool wq_has_sleeper(struct wait_queue_head *wq_head)
```

check if there are any waiting processes

**Parameters**

- `struct wait_queue_head *wq_head`: wait queue head

**Description**

Returns true if wq_head has waiting processes

Please refer to the comment for waitqueue_active.

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

```c
void wake_up_pollfree(struct wait_queue_head *wq_head)
```

signal that a polled waitqueue is going away

**Parameters**

- `struct wait_queue_head *wq_head`: the wait queue head

**Description**

In the very rare cases where a ->`poll()` implementation uses a waitqueue whose
lifetime is tied to a task rather than to the 'struct file' being polled,
this function must be called before the waitqueue is freed so that
non-blocking polls (e.g. epoll) are notified that the queue is going away.

The caller must also RCU-delay the freeing of the wait_queue_head, e.g. via
an explicit [`synchronize_rcu()`](/kernel/internals/core-api/kernel-api.md#c-synchronize_rcu) or [`call_rcu()`](/kernel/internals/core-api/kernel-api.md#c-call_rcu), or via SLAB_TYPESAFE_BY_RCU.

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

```c
wait_event(wq_head, condition)
```

sleep until a condition gets true

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_UNINTERRUPTIBLE) until the
**condition** evaluates to true. The **condition** is checked each time
the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

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

```c
wait_event_freezable(wq_head, condition)
```

sleep (or freeze) until a condition gets true

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE -- so as not to contribute
to system load) until the **condition** evaluates to true. The
**condition** is checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

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

```c
wait_event_timeout(wq_head, condition, timeout)
```

sleep until a condition gets true or a timeout elapses

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `timeout`: timeout, in jiffies

**Description**

The process is put to sleep (TASK_UNINTERRUPTIBLE) until the
**condition** evaluates to true. The **condition** is checked each time
the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

**Return**

0 if the **condition** evaluated to `false` after the **timeout** elapsed,
1 if the **condition** evaluated to `true` after the **timeout** elapsed,
or the remaining jiffies (at least 1) if the **condition** evaluated
to `true` before the **timeout** elapsed.

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

```c
wait_event_cmd(wq_head, condition, cmd1, cmd2)
```

sleep until a condition gets true

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `cmd1`: the command will be executed before sleep
- `cmd2`: the command will be executed after sleep

**Description**

The process is put to sleep (TASK_UNINTERRUPTIBLE) until the
**condition** evaluates to true. The **condition** is checked each time
the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

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

```c
wait_event_interruptible(wq_head, condition)
```

sleep until a condition gets true

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or a signal is received.
The **condition** is checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

The function will return -ERESTARTSYS if it was interrupted by a
signal and 0 if **condition** evaluated to true.

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

```c
wait_event_interruptible_timeout(wq_head, condition, timeout)
```

sleep until a condition gets true or a timeout elapses

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `timeout`: timeout, in jiffies

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or a signal is received.
The **condition** is checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

**Return**

0 if the **condition** evaluated to `false` after the **timeout** elapsed,
1 if the **condition** evaluated to `true` after the **timeout** elapsed,
the remaining jiffies (at least 1) if the **condition** evaluated
to `true` before the **timeout** elapsed, or -`ERESTARTSYS` if it was
interrupted by a signal.

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

```c
wait_event_hrtimeout(wq_head, condition, timeout)
```

sleep until a condition gets true or a timeout elapses

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `timeout`: timeout, as a ktime_t

**Description**

The process is put to sleep (TASK_UNINTERRUPTIBLE) until the
**condition** evaluates to true or a signal is received.
The **condition** is checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

The function returns 0 if **condition** became true, or -ETIME if the timeout
elapsed.

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

```c
wait_event_interruptible_hrtimeout(wq, condition, timeout)
```

sleep until a condition gets true or a timeout elapses

**Parameters**

- `wq`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `timeout`: timeout, as a ktime_t

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or a signal is received.
The **condition** is checked each time the waitqueue **wq** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

The function returns 0 if **condition** became true, -ERESTARTSYS if it was
interrupted by a signal, or -ETIME if the timeout elapsed.

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

```c
wait_event_idle(wq_head, condition)
```

wait for a condition without contributing to system load

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_IDLE) until the
**condition** evaluates to true.
The **condition** is checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

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

```c
wait_event_idle_exclusive(wq_head, condition)
```

wait for a condition with contributing to system load

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_IDLE) until the
**condition** evaluates to true.
The **condition** is checked each time the waitqueue **wq_head** is woken up.

The process is put on the wait queue with an WQ_FLAG_EXCLUSIVE flag
set thus if other processes wait on the same list, when this
process is woken further processes are not considered.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

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

```c
wait_event_idle_timeout(wq_head, condition, timeout)
```

sleep without load until a condition becomes true or a timeout elapses

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `timeout`: timeout, in jiffies

**Description**

The process is put to sleep (TASK_IDLE) until the
**condition** evaluates to true. The **condition** is checked each time
the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

**Return**

0 if the **condition** evaluated to `false` after the **timeout** elapsed,
1 if the **condition** evaluated to `true` after the **timeout** elapsed,
or the remaining jiffies (at least 1) if the **condition** evaluated
to `true` before the **timeout** elapsed.

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

```c
wait_event_idle_exclusive_timeout(wq_head, condition, timeout)
```

sleep without load until a condition becomes true or a timeout elapses

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `timeout`: timeout, in jiffies

**Description**

The process is put to sleep (TASK_IDLE) until the
**condition** evaluates to true. The **condition** is checked each time
the waitqueue **wq_head** is woken up.

The process is put on the wait queue with an WQ_FLAG_EXCLUSIVE flag
set thus if other processes wait on the same list, when this
process is woken further processes are not considered.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

**Return**

0 if the **condition** evaluated to `false` after the **timeout** elapsed,
1 if the **condition** evaluated to `true` after the **timeout** elapsed,
or the remaining jiffies (at least 1) if the **condition** evaluated
to `true` before the **timeout** elapsed.

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

```c
wait_event_interruptible_locked(wq, condition)
```

sleep until a condition gets true

**Parameters**

- `wq`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or a signal is received.
The **condition** is checked each time the waitqueue **wq** is woken up.

It must be called with wq.lock being held.  This spinlock is
unlocked while sleeping but **condition** testing is done while lock
is held and when this macro exits the lock is held.

The lock is locked/unlocked using `spin_lock()`/`spin_unlock()`
functions which must match the way they are locked/unlocked outside
of this macro.

`wake_up_locked()` has to be called after changing any variable that could
change the result of the wait condition.

The function will return -ERESTARTSYS if it was interrupted by a
signal and 0 if **condition** evaluated to true.

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

```c
wait_event_interruptible_locked_irq(wq, condition)
```

sleep until a condition gets true

**Parameters**

- `wq`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or a signal is received.
The **condition** is checked each time the waitqueue **wq** is woken up.

It must be called with wq.lock being held.  This spinlock is
unlocked while sleeping but **condition** testing is done while lock
is held and when this macro exits the lock is held.

The lock is locked/unlocked using `spin_lock_irq()`/`spin_unlock_irq()`
functions which must match the way they are locked/unlocked outside
of this macro.

`wake_up_locked()` has to be called after changing any variable that could
change the result of the wait condition.

The function will return -ERESTARTSYS if it was interrupted by a
signal and 0 if **condition** evaluated to true.

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

```c
wait_event_interruptible_exclusive_locked(wq, condition)
```

sleep exclusively until a condition gets true

**Parameters**

- `wq`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or a signal is received.
The **condition** is checked each time the waitqueue **wq** is woken up.

It must be called with wq.lock being held.  This spinlock is
unlocked while sleeping but **condition** testing is done while lock
is held and when this macro exits the lock is held.

The lock is locked/unlocked using `spin_lock()`/`spin_unlock()`
functions which must match the way they are locked/unlocked outside
of this macro.

The process is put on the wait queue with an WQ_FLAG_EXCLUSIVE flag
set thus when other process waits process on the list if this
process is awaken further processes are not considered.

`wake_up_locked()` has to be called after changing any variable that could
change the result of the wait condition.

The function will return -ERESTARTSYS if it was interrupted by a
signal and 0 if **condition** evaluated to true.

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

```c
wait_event_interruptible_exclusive_locked_irq(wq, condition)
```

sleep until a condition gets true

**Parameters**

- `wq`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or a signal is received.
The **condition** is checked each time the waitqueue **wq** is woken up.

It must be called with wq.lock being held.  This spinlock is
unlocked while sleeping but **condition** testing is done while lock
is held and when this macro exits the lock is held.

The lock is locked/unlocked using `spin_lock_irq()`/`spin_unlock_irq()`
functions which must match the way they are locked/unlocked outside
of this macro.

The process is put on the wait queue with an WQ_FLAG_EXCLUSIVE flag
set thus when other process waits process on the list if this
process is awaken further processes are not considered.

`wake_up_locked()` has to be called after changing any variable that could
change the result of the wait condition.

The function will return -ERESTARTSYS if it was interrupted by a
signal and 0 if **condition** evaluated to true.

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

```c
wait_event_killable(wq_head, condition)
```

sleep until a condition gets true

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for

**Description**

The process is put to sleep (TASK_KILLABLE) until the
**condition** evaluates to true or a signal is received.
The **condition** is checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

The function will return -ERESTARTSYS if it was interrupted by a
signal and 0 if **condition** evaluated to true.

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

```c
wait_event_state(wq_head, condition, state)
```

sleep until a condition gets true

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `state`: state to sleep in

**Description**

The process is put to sleep (**state**) until the **condition** evaluates to true
or a signal is received (when allowed by **state**).  The **condition** is checked
each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

The function will return -ERESTARTSYS if it was interrupted by a signal
(when allowed by **state**) and 0 if **condition** evaluated to true.

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

```c
wait_event_killable_timeout(wq_head, condition, timeout)
```

sleep until a condition gets true or a timeout elapses

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `timeout`: timeout, in jiffies

**Description**

The process is put to sleep (TASK_KILLABLE) until the
**condition** evaluates to true or a kill signal is received.
The **condition** is checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

Only kill signals interrupt this process.

**Return**

0 if the **condition** evaluated to `false` after the **timeout** elapsed,
1 if the **condition** evaluated to `true` after the **timeout** elapsed,
the remaining jiffies (at least 1) if the **condition** evaluated
to `true` before the **timeout** elapsed, or -`ERESTARTSYS` if it was
interrupted by a kill signal.

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

```c
wait_event_lock_irq_cmd(wq_head, condition, lock, cmd)
```

sleep until a condition gets true. The condition is checked under the lock. This is expected to be called with the lock taken.

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `lock`: a locked spinlock_t, which will be released before cmd
  and `schedule()` and reacquired afterwards.
- `cmd`: a command which is invoked outside the critical section before
  sleep

**Description**

The process is put to sleep (TASK_UNINTERRUPTIBLE) until the
**condition** evaluates to true. The **condition** is checked each time
the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

This is supposed to be called while holding the lock. The lock is
dropped before invoking the cmd and going to sleep and is reacquired
afterwards.

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

```c
wait_event_lock_irq(wq_head, condition, lock)
```

sleep until a condition gets true. The condition is checked under the lock. This is expected to be called with the lock taken.

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `lock`: a locked spinlock_t, which will be released before `schedule()`
  and reacquired afterwards.

**Description**

The process is put to sleep (TASK_UNINTERRUPTIBLE) until the
**condition** evaluates to true. The **condition** is checked each time
the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

This is supposed to be called while holding the lock. The lock is
dropped before going to sleep and is reacquired afterwards.

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

```c
wait_event_interruptible_lock_irq_cmd(wq_head, condition, lock, cmd)
```

sleep until a condition gets true. The condition is checked under the lock. This is expected to be called with the lock taken.

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `lock`: a locked spinlock_t, which will be released before cmd and
  `schedule()` and reacquired afterwards.
- `cmd`: a command which is invoked outside the critical section before
  sleep

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or a signal is received. The **condition** is
checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

This is supposed to be called while holding the lock. The lock is
dropped before invoking the cmd and going to sleep and is reacquired
afterwards.

The macro will return -ERESTARTSYS if it was interrupted by a signal
and 0 if **condition** evaluated to true.

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

```c
wait_event_interruptible_lock_irq(wq_head, condition, lock)
```

sleep until a condition gets true. The condition is checked under the lock. This is expected to be called with the lock taken.

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `lock`: a locked spinlock_t, which will be released before `schedule()`
  and reacquired afterwards.

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or signal is received. The **condition** is
checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

This is supposed to be called while holding the lock. The lock is
dropped before going to sleep and is reacquired afterwards.

The macro will return -ERESTARTSYS if it was interrupted by a signal
and 0 if **condition** evaluated to true.

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

```c
wait_event_interruptible_lock_irq_timeout(wq_head, condition, lock, timeout)
```

sleep until a condition gets true or a timeout elapses. The condition is checked under the lock. This is expected to be called with the lock taken.

**Parameters**

- `wq_head`: the waitqueue to wait on
- `condition`: a C expression for the event to wait for
- `lock`: a locked spinlock_t, which will be released before `schedule()`
  and reacquired afterwards.
- `timeout`: timeout, in jiffies

**Description**

The process is put to sleep (TASK_INTERRUPTIBLE) until the
**condition** evaluates to true or signal is received. The **condition** is
checked each time the waitqueue **wq_head** is woken up.

`wake_up()` has to be called after changing any variable that could
change the result of the wait condition.

This is supposed to be called while holding the lock. The lock is
dropped before going to sleep and is reacquired afterwards.

The function returns 0 if the **timeout** elapsed, -ERESTARTSYS if it
was interrupted by a signal, and the remaining jiffies otherwise
if the condition evaluated to true before the timeout elapsed.



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

```c
int __wake_up(struct wait_queue_head *wq_head, unsigned int mode, int nr_exclusive, void *key)
```

wake up threads blocked on a waitqueue.

**Parameters**

- `struct wait_queue_head *wq_head`: the waitqueue
- `unsigned int mode`: which threads
- `int nr_exclusive`: how many wake-one or wake-many threads to wake up
- `void *key`: is directly passed to the wakeup function

**Description**

If this function wakes up a task, it executes a full memory barrier
before accessing the task state.  Returns the number of exclusive
tasks that were awaken.

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

```c
void __wake_up_sync_key(struct wait_queue_head *wq_head, unsigned int mode, void *key)
```

wake up threads blocked on a waitqueue.

**Parameters**

- `struct wait_queue_head *wq_head`: the waitqueue
- `unsigned int mode`: which threads
- `void *key`: opaque value to be passed to wakeup targets

**Description**

The sync wakeup differs that the waker knows that it will schedule
away soon, so while the target thread will be woken up, it will not
be migrated to another CPU - ie. the two threads are 'synchronized'
with each other. This can prevent needless bouncing between CPUs.

On UP it can prevent extra preemption.

If this function wakes up a task, it executes a full memory barrier before
accessing the task state.

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

```c
void __wake_up_locked_sync_key(struct wait_queue_head *wq_head, unsigned int mode, void *key)
```

wake up a thread blocked on a locked waitqueue.

**Parameters**

- `struct wait_queue_head *wq_head`: the waitqueue
- `unsigned int mode`: which threads
- `void *key`: opaque value to be passed to wakeup targets

**Description**

The sync wakeup differs in that the waker knows that it will schedule
away soon, so while the target thread will be woken up, it will not
be migrated to another CPU - ie. the two threads are 'synchronized'
with each other. This can prevent needless bouncing between CPUs.

On UP it can prevent extra preemption.

If this function wakes up a task, it executes a full memory barrier before
accessing the task state.

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

```c
void finish_wait(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry)
```

clean up after waiting in a queue

**Parameters**

- `struct wait_queue_head *wq_head`: waitqueue waited on
- `struct wait_queue_entry *wq_entry`: wait descriptor

**Description**

Sets current thread back to running state and removes
the wait descriptor from the given waitqueue if still
queued.


<a id="rst-internal-functions"></a>

## Internal Functions


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

```c
int wait_task_stopped(struct wait_opts *wo, int ptrace, struct task_struct *p)
```

Wait for `TASK_STOPPED` or `TASK_TRACED`

**Parameters**

- `struct wait_opts *wo`: wait options
- `int ptrace`: is the wait for ptrace
- `struct task_struct *p`: task to wait for

**Description**

Handle `sys_wait4()` work for `p` in state `TASK_STOPPED` or `TASK_TRACED`.

**Context**

read_lock(`tasklist_lock`), which is released if return value is
non-zero.  Also, grabs and releases **p->sighand->siglock**.

**Return**

0 if wait condition didn't exist and search for other wait conditions
should continue.  Non-zero return, -errno on failure and **p**'s pid on
success, implies that tasklist_lock is released and wait condition
search should terminate.



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

```c
bool task_set_jobctl_pending(struct task_struct *task, unsigned long mask)
```

set jobctl pending bits

**Parameters**

- `struct task_struct *task`: target task
- `unsigned long mask`: pending bits to set

**Description**

Clear **mask** from **task->jobctl**.  **mask** must be subset of
`JOBCTL_PENDING_MASK` | `JOBCTL_STOP_CONSUME` | `JOBCTL_STOP_SIGMASK` |
`JOBCTL_TRAPPING`.  If stop signo is being set, the existing signo is
cleared.  If **task** is already being killed or exiting, this function
becomes noop.

**Context**

Must be called with **task->sighand->siglock** held.

**Return**

`true` if **mask** is set, `false` if made noop because **task** was dying.

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

```c
void task_clear_jobctl_trapping(struct task_struct *task)
```

clear jobctl trapping bit

**Parameters**

- `struct task_struct *task`: target task

**Description**

If JOBCTL_TRAPPING is set, a ptracer is waiting for us to enter TRACED.
Clear it and wake up the ptracer.  Note that we don't need any further
locking.  **task->siglock** guarantees that **task->parent** points to the
ptracer.

**Context**

Must be called with **task->sighand->siglock** held.

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

```c
void task_clear_jobctl_pending(struct task_struct *task, unsigned long mask)
```

clear jobctl pending bits

**Parameters**

- `struct task_struct *task`: target task
- `unsigned long mask`: pending bits to clear

**Description**

Clear **mask** from **task->jobctl**.  **mask** must be subset of
`JOBCTL_PENDING_MASK`.  If `JOBCTL_STOP_PENDING` is being cleared, other
STOP bits are cleared together.

If clearing of **mask** leaves no stop or trap pending, this function calls
[`task_clear_jobctl_trapping()`](#c-task_clear_jobctl_trapping).

**Context**

Must be called with **task->sighand->siglock** held.

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

```c
bool task_participate_group_stop(struct task_struct *task)
```

participate in a group stop

**Parameters**

- `struct task_struct *task`: task participating in a group stop

**Description**

**task** has `JOBCTL_STOP_PENDING` set and is participating in a group stop.
Group stop states are cleared and the group stop count is consumed if
`JOBCTL_STOP_CONSUME` was set.  If the consumption completes the group
stop, the appropriate `SIGNAL_*` flags are set.

**Context**

Must be called with **task->sighand->siglock** held.

**Return**

`true` if group stop completion should be notified to the parent, `false`
otherwise.

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

```c
void ptrace_trap_notify(struct task_struct *t)
```

schedule trap to notify ptracer

**Parameters**

- `struct task_struct *t`: tracee wanting to notify tracer

**Description**

This function schedules sticky ptrace trap which is cleared on the next
TRAP_STOP to notify ptracer of an event.  **t** must have been seized by
ptracer.

If **t** is running, STOP trap will be taken.  If trapped for STOP and
ptracer is listening for events, tracee is woken up so that it can
re-trap for the new event.  If trapped otherwise, STOP trap will be
eventually taken without returning to userland after the existing traps
are finished by PTRACE_CONT.

**Context**

Must be called with **task->sighand->siglock** held.

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

```c
int force_sig_seccomp(int syscall, int reason, bool force_coredump)
```

signals the task to allow in-process syscall emulation

**Parameters**

- `int syscall`: syscall number to send to userland
- `int reason`: filter-supplied reason code to send to userland (via si_errno)
- `bool force_coredump`: true to trigger a coredump

**Description**

Forces a SIGSYS with a code of SYS_SECCOMP and related sigsys info.

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

```c
void do_notify_parent_cldstop(struct task_struct *tsk, bool for_ptracer, int why)
```

notify parent of stopped/continued state change

**Parameters**

- `struct task_struct *tsk`: task reporting the state change
- `bool for_ptracer`: the notification is for ptracer
- `int why`: CLD_{CONTINUED|STOPPED|TRAPPED} to report

**Description**

Notify **tsk**'s parent that the stopped/continued state has changed.  If
**for_ptracer** is `false`, **tsk**'s group leader notifies to its real parent.
If `true`, **tsk** reports to **tsk->parent** which should be the ptracer.

**Context**

Must be called with tasklist_lock at least read locked.

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

```c
bool do_signal_stop(int signr)
```

handle group stop for SIGSTOP and other stop signals

**Parameters**

- `int signr`: signr causing group stop if initiating

**Description**

If `JOBCTL_STOP_PENDING` is not set yet, initiate group stop with **signr**
and participate in it.  If already set, participate in the existing
group stop.  If participated in a group stop (and thus slept), `true` is
returned with siglock released.

If ptraced, this function doesn't handle stop itself.  Instead,
`JOBCTL_TRAP_STOP` is scheduled and `false` is returned with siglock
untouched.  The caller must ensure that INTERRUPT trap handling takes
places afterwards.

**Context**

Must be called with **current->sighand->siglock** held, which is released
on `true` return.

**Return**

`false` if group stop is already cancelled or ptrace trap is scheduled.
`true` if participated in group stop.

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

```c
void do_jobctl_trap(void)
```

take care of ptrace jobctl traps

**Parameters**

- `void`: no arguments

**Description**

When PT_SEIZED, it's used for both group stop and explicit
SEIZE/INTERRUPT traps.  Both generate PTRACE_EVENT_STOP trap with
accompanying siginfo.  If stopped, lower eight bits of exit_code contain
the stop signal; otherwise, `SIGTRAP`.

When !PT_SEIZED, it's used only for group stop trap with stop signal
number as exit_code and no siginfo.

**Context**

Must be called with **current->sighand->siglock** held, which may be
released and re-acquired before returning with intervening sleep.

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

```c
void do_freezer_trap(void)
```

handle the freezer jobctl trap

**Parameters**

- `void`: no arguments

**Description**

Puts the task into frozen state, if only the task is not about to quit.
In this case it drops JOBCTL_TRAP_FREEZE.

**Context**

Must be called with **current->sighand->siglock** held,
which is always released before returning.

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

```c
void signal_delivered(struct ksignal *ksig, int stepping)
```

called after signal delivery to update blocked signals

**Parameters**

- `struct ksignal *ksig`: kernel signal struct
- `int stepping`: nonzero if debugger single-step or block-step in use

**Description**

This function should be called when a signal has successfully been
delivered. It updates the blocked signals accordingly (**ksig->ka.sa.sa_mask**
is always blocked), and the signal itself is blocked unless `SA_NODEFER`
is set in **ksig->ka.sa.sa_flags**.  Tracing is notified.

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

```c
long sys_restart_syscall(void)
```

restart a system call

**Parameters**

- `void`: no arguments

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

```c
void set_current_blocked(sigset_t *newset)
```

change current->blocked mask

**Parameters**

- `sigset_t *newset`: new mask

**Description**

It is wrong to change ->blocked directly, this helper should be used
to ensure the process can't miss a shared signal we are going to block.

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

```c
long sys_rt_sigprocmask(int how, sigset_t __user * nset, sigset_t __user * oset, size_t sigsetsize)
```

change the list of currently blocked signals

**Parameters**

- `int how`: whether to add, remove, or set signals
- `sigset_t __user * nset`: stores pending signals
- `sigset_t __user * oset`: previous value of signal mask if non-null
- `size_t sigsetsize`: size of sigset_t type

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

```c
long sys_rt_sigpending(sigset_t __user * uset, size_t sigsetsize)
```

examine a pending signal that has been raised while blocked

**Parameters**

- `sigset_t __user * uset`: stores pending signals
- `size_t sigsetsize`: size of sigset_t type or larger

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

```c
void copy_siginfo_to_external32(struct compat_siginfo *to, const struct kernel_siginfo *from)
```

copy a kernel siginfo into a compat user siginfo

**Parameters**

- `struct compat_siginfo *to`: compat siginfo destination
- `const struct kernel_siginfo *from`: kernel siginfo source

**Note**

This function does not work properly for the SIGCHLD on x32, but
fortunately it doesn't have to.  The only valid callers for this function are
copy_siginfo_to_user32, which is overriden for x32 and the coredump code.
The latter does not care because SIGCHLD will never cause a coredump.

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

```c
int do_sigtimedwait(const sigset_t *which, kernel_siginfo_t *info, const struct timespec64 *ts)
```

wait for queued signals specified in **which**

**Parameters**

- `const sigset_t *which`: queued signals to wait for
- `kernel_siginfo_t *info`: if non-null, the signal's siginfo is returned here
- `const struct timespec64 *ts`: upper bound on process time suspension

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

```c
long sys_rt_sigtimedwait(const sigset_t __user * uthese, siginfo_t __user * uinfo, const struct __kernel_timespec __user * uts, size_t sigsetsize)
```

synchronously wait for queued signals specified in **uthese**

**Parameters**

- `const sigset_t __user * uthese`: queued signals to wait for
- `siginfo_t __user * uinfo`: if non-null, the signal's siginfo is returned here
- `const struct __kernel_timespec __user * uts`: upper bound on process time suspension
- `size_t sigsetsize`: size of sigset_t type

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

```c
long sys_kill(pid_t pid, int sig)
```

send a signal to a process

**Parameters**

- `pid_t pid`: the PID of the process
- `int sig`: signal to be sent

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

```c
long sys_pidfd_send_signal(int pidfd, int sig, siginfo_t __user * info, unsigned int flags)
```

Signal a process through a pidfd

**Parameters**

- `int pidfd`: file descriptor of the process
- `int sig`: signal to send
- `siginfo_t __user * info`: signal info
- `unsigned int flags`: future flags

**Description**

Send the signal to the thread group or to the individual thread depending
on PIDFD_THREAD.
In the future extension to **flags** may be used to override the default scope
of **pidfd**.

**Return**

0 on success, negative errno on failure

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

```c
long sys_tgkill(pid_t tgid, pid_t pid, int sig)
```

send signal to one specific thread

**Parameters**

- `pid_t tgid`: the thread group ID of the thread
- `pid_t pid`: the PID of the thread
- `int sig`: signal to be sent

**Description**

This syscall also checks the **tgid** and returns -ESRCH even if the PID
exists but it's not belonging to the target process anymore. This
method solves the problem of threads exiting and PIDs getting reused.

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

```c
long sys_tkill(pid_t pid, int sig)
```

send signal to one specific task

**Parameters**

- `pid_t pid`: the PID of the task
- `int sig`: signal to be sent

**Description**

Send a signal to only one task, even if it's a CLONE_THREAD task.

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

```c
long sys_rt_sigqueueinfo(pid_t pid, int sig, siginfo_t __user * uinfo)
```

send signal information to a signal

**Parameters**

- `pid_t pid`: the PID of the thread
- `int sig`: signal to be sent
- `siginfo_t __user * uinfo`: signal info to be sent

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

```c
long sys_sigpending(old_sigset_t __user * uset)
```

examine pending signals

**Parameters**

- `old_sigset_t __user * uset`: where mask of pending signal is returned

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

```c
long sys_sigprocmask(int how, old_sigset_t __user * nset, old_sigset_t __user * oset)
```

examine and change blocked signals

**Parameters**

- `int how`: whether to add, remove, or set signals
- `old_sigset_t __user * nset`: signals to add or remove (if non-null)
- `old_sigset_t __user * oset`: previous value of signal mask if non-null

**Description**

Some platforms have their own version with special arguments;
others support only sys_rt_sigprocmask.

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

```c
long sys_rt_sigaction(int sig, const struct sigaction __user * act, struct sigaction __user * oact, size_t sigsetsize)
```

alter an action taken by a process

**Parameters**

- `int sig`: signal to be sent
- `const struct sigaction __user * act`: new sigaction
- `struct sigaction __user * oact`: used to save the previous sigaction
- `size_t sigsetsize`: size of sigset_t type

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

```c
long sys_rt_sigsuspend(sigset_t __user * unewset, size_t sigsetsize)
```

replace the signal mask for a value with the **unewset** value until a signal is received

**Parameters**

- `sigset_t __user * unewset`: new signal mask value
- `size_t sigsetsize`: size of sigset_t type



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

```c
kthread_create(threadfn, data, namefmt, arg...)
```

create a kthread on the current node

**Parameters**

- `threadfn`: the function to run in the thread
- `data`: data pointer for **threadfn()**
- `namefmt`: printf-style format string for the thread name
- `arg...`: arguments for **namefmt**.

**Description**

This macro will create a kthread on the current node, leaving it in
the stopped state.  This is just a helper for [`kthread_create_on_node()`](#c-kthread_create_on_node);
see the documentation there for more details.

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

```c
kthread_run(threadfn, data, namefmt, ...)
```

create and wake a thread.

**Parameters**

- `threadfn`: the function to run until signal_pending(current).
- `data`: data ptr for **threadfn**.
- `namefmt`: printf-style name for the thread.
- `...`: variable arguments

**Description**

Convenient wrapper for [`kthread_create()`](#c-kthread_create) followed by
[`wake_up_process()`](#c-wake_up_process).  Returns the kthread or ERR_PTR(-ENOMEM).

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

```c
struct task_struct * kthread_run_on_cpu(int (*threadfn)(void *data), void *data, unsigned int cpu, const char *namefmt)
```

create and wake a cpu bound thread.

**Parameters**

- `int (*threadfn)(void *data)`: the function to run until signal_pending(current).
- `void *data`: data ptr for **threadfn**.
- `unsigned int cpu`: The cpu on which the thread should be bound,
- `const char *namefmt`: printf-style name for the thread. Format is restricted
  to "name.*`u`". Code fills in cpu number.

**Description**

Convenient wrapper for [`kthread_create_on_cpu()`](#c-kthread_create_on_cpu)
followed by [`wake_up_process()`](#c-wake_up_process).  Returns the kthread or
ERR_PTR(-ENOMEM).

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

```c
kthread_run_worker(flags, namefmt, ...)
```

create and wake a kthread worker.

**Parameters**

- `flags`: flags modifying the default behavior of the worker
- `namefmt`: printf-style name for the thread.
- `...`: variable arguments

**Description**

Convenient wrapper for `kthread_create_worker()` followed by
[`wake_up_process()`](#c-wake_up_process).  Returns the kthread_worker or ERR_PTR(-ENOMEM).

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

```c
struct kthread_worker * kthread_run_worker_on_cpu(int cpu, unsigned int flags, const char namefmt[])
```

create and wake a cpu bound kthread worker.

**Parameters**

- `int cpu`: CPU number
- `unsigned int flags`: flags modifying the default behavior of the worker
- `const char namefmt[]`: printf-style name for the thread. Format is restricted
  to "name.*`u`". Code fills in cpu number.

**Description**

Convenient wrapper for [`kthread_create_worker_on_cpu()`](#c-kthread_create_worker_on_cpu)
followed by [`wake_up_process()`](#c-wake_up_process).  Returns the kthread_worker or
ERR_PTR(-ENOMEM).



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

```c
bool kthread_should_stop(void)
```

should this kthread return now?

**Parameters**

- `void`: no arguments

**Description**

When someone calls [`kthread_stop()`](#c-kthread_stop) on your kthread, it will be woken
and this will return true.  You should then return, and your return
value will be passed through to [`kthread_stop()`](#c-kthread_stop).

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

```c
bool kthread_should_park(void)
```

should this kthread park now?

**Parameters**

- `void`: no arguments

**Description**

When someone calls [`kthread_park()`](#c-kthread_park) on your kthread, it will be woken
and this will return true.  You should then do the necessary
cleanup and call `kthread_parkme()`

Similar to [`kthread_should_stop()`](#c-kthread_should_stop), but this keeps the thread alive
and in a park position. [`kthread_unpark()`](#c-kthread_unpark) "restarts" the thread and
calls the thread function again.

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

```c
bool kthread_freezable_should_stop(bool *was_frozen)
```

should this freezable kthread return now?

**Parameters**

- `bool *was_frozen`: optional out parameter, indicates whether `current` was frozen

**Description**

[`kthread_should_stop()`](#c-kthread_should_stop) for freezable kthreads, which will enter
refrigerator if necessary.  This function is safe from [`kthread_stop()`](#c-kthread_stop) /
freezer deadlock and freezable kthreads should use this function instead
of calling `try_to_freeze()` directly.

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

```c
void * kthread_func(struct task_struct *task)
```

return the function specified on kthread creation

**Parameters**

- `struct task_struct *task`: kthread task in question

**Description**

Returns NULL if the task is not a kthread.

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

```c
void * kthread_data(struct task_struct *task)
```

return data value specified on kthread creation

**Parameters**

- `struct task_struct *task`: kthread task in question

**Description**

Return the data value specified when kthread **task** was created.
The caller is responsible for ensuring the validity of **task** when
calling this function.

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

```c
void __noreturn kthread_complete_and_exit(struct completion *comp, long code)
```

Exit the current kthread.

**Parameters**

- `struct completion *comp`: Completion to complete
- `long code`: The integer value to return to [`kthread_stop()`](#c-kthread_stop).

**Description**

If present, complete **comp** and then return code to [`kthread_stop()`](#c-kthread_stop).

A kernel thread whose module may be removed after the completion of
**comp** can use this function to exit safely.

Does not return.

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

```c
struct task_struct * kthread_create_on_node(int (*threadfn)(void *data), void *data, int node, const char namefmt[], ...)
```

create a kthread.

**Parameters**

- `int (*threadfn)(void *data)`: the function to run until signal_pending(current).
- `void *data`: data ptr for **threadfn**.
- `int node`: task and thread structures for the thread are allocated on this node
- `const char namefmt[]`: printf-style name for the thread.
- `...`: variable arguments

**Description**

This helper function creates and names a kernel
thread.  The thread will be stopped: use [`wake_up_process()`](#c-wake_up_process) to start
it.  See also [`kthread_run()`](#c-kthread_run).  The new thread has SCHED_NORMAL policy and
is affine to all CPUs.

If thread is going to be bound on a particular cpu, give its node
in **node**, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
When woken, the thread will run **threadfn()** with **data** as its
argument. **threadfn()** can either return directly if it is a
standalone thread for which no one will call [`kthread_stop()`](#c-kthread_stop), or
return when '[`kthread_should_stop()`](#c-kthread_should_stop)' is true (which means
[`kthread_stop()`](#c-kthread_stop) has been called).  The return value should be zero
or a negative error number; it will be passed to [`kthread_stop()`](#c-kthread_stop).

Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).

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

```c
void kthread_bind(struct task_struct *p, unsigned int cpu)
```

bind a just-created kthread to a cpu.

**Parameters**

- `struct task_struct *p`: thread created by [`kthread_create()`](#c-kthread_create).
- `unsigned int cpu`: cpu (might not be online, must be possible) for **k** to run on.

**Description**

This function is equivalent to `set_cpus_allowed()`,
except that **cpu** doesn't need to be online, and the thread must be
stopped (i.e., just returned from [`kthread_create()`](#c-kthread_create)).

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

```c
struct task_struct * kthread_create_on_cpu(int (*threadfn)(void *data), void *data, unsigned int cpu, const char *namefmt)
```

Create a cpu bound kthread

**Parameters**

- `int (*threadfn)(void *data)`: the function to run until signal_pending(current).
- `void *data`: data ptr for **threadfn**.
- `unsigned int cpu`: The cpu on which the thread should be bound,
- `const char *namefmt`: printf-style name for the thread. Format is restricted
  to "name.*`u`". Code fills in cpu number.

**Description**

This helper function creates and names a kernel thread

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

```c
void kthread_unpark(struct task_struct *k)
```

unpark a thread created by [`kthread_create()`](#c-kthread_create).

**Parameters**

- `struct task_struct *k`: thread created by [`kthread_create()`](#c-kthread_create).

**Description**

Sets [`kthread_should_park()`](#c-kthread_should_park) for **k** to return false, wakes it, and
waits for it to return. If the thread is marked percpu then its
bound to the cpu again.

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

```c
int kthread_park(struct task_struct *k)
```

park a thread created by [`kthread_create()`](#c-kthread_create).

**Parameters**

- `struct task_struct *k`: thread created by [`kthread_create()`](#c-kthread_create).

**Description**

Sets [`kthread_should_park()`](#c-kthread_should_park) for **k** to return true, wakes it, and
waits for it to return. This can also be called after [`kthread_create()`](#c-kthread_create)
instead of calling [`wake_up_process()`](#c-wake_up_process): the thread will park without
calling `threadfn()`.

Returns 0 if the thread is parked, -ENOSYS if the thread exited.
If called by the kthread itself just the park bit is set.

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

```c
int kthread_stop(struct task_struct *k)
```

stop a thread created by [`kthread_create()`](#c-kthread_create).

**Parameters**

- `struct task_struct *k`: thread created by [`kthread_create()`](#c-kthread_create).

**Description**

Sets [`kthread_should_stop()`](#c-kthread_should_stop) for **k** to return true, wakes it, and
waits for it to exit. This can also be called after [`kthread_create()`](#c-kthread_create)
instead of calling [`wake_up_process()`](#c-wake_up_process): the thread will exit without
calling `threadfn()`.

If `threadfn()` may call `kthread_exit()` itself, the caller must ensure
task_struct can't go away.

Returns the result of `threadfn()`, or `-EINTR` if [`wake_up_process()`](#c-wake_up_process)
was never called.

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

```c
int kthread_stop_put(struct task_struct *k)
```

stop a thread and put its task struct

**Parameters**

- `struct task_struct *k`: thread created by [`kthread_create()`](#c-kthread_create).

**Description**

Stops a thread created by [`kthread_create()`](#c-kthread_create) and put its task_struct.
Only use when holding an extra task struct reference obtained by
calling `get_task_struct()`.

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

```c
int kthread_affine_preferred(struct task_struct *p, const struct cpumask *mask)
```

Define a kthread's preferred affinity

**Parameters**

- `struct task_struct *p`: thread created by [`kthread_create()`](#c-kthread_create).
- `const struct cpumask *mask`: preferred mask of CPUs (might not be online, must be possible) for **p**
  to run on.

**Description**

Similar to `kthread_bind_mask()` except that the affinity is not a requirement
but rather a preference that can be constrained by CPU isolation or CPU hotplug.
Must be called before the first wakeup of the kthread.

Returns 0 if the affinity has been applied.

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

```c
int kthread_worker_fn(void *worker_ptr)
```

kthread function to process kthread_worker

**Parameters**

- `void *worker_ptr`: pointer to initialized kthread_worker

**Description**

This function implements the main cycle of kthread worker. It processes
work_list until it is stopped with [`kthread_stop()`](#c-kthread_stop). It sleeps when the queue
is empty.

The works are not allowed to keep any locks, disable preemption or interrupts
when they finish. There is defined a safe point for freezing when one work
finishes and before a new one is started.

Also the works must not be handled by more than one worker at the same time,
see also [`kthread_queue_work()`](#c-kthread_queue_work).

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

```c
struct kthread_worker * kthread_create_worker_on_node(unsigned int flags, int node, const char namefmt[], ...)
```

create a kthread worker

**Parameters**

- `unsigned int flags`: flags modifying the default behavior of the worker
- `int node`: task structure for the thread is allocated on this node
- `const char namefmt[]`: printf-style name for the kthread worker (task).
- `...`: variable arguments

**Description**

Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
when the needed structures could not get allocated, and ERR_PTR(-EINTR)
when the caller was killed by a fatal signal.

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

```c
struct kthread_worker * kthread_create_worker_on_cpu(int cpu, unsigned int flags, const char namefmt[])
```

create a kthread worker and bind it to a given CPU and the associated NUMA node.

**Parameters**

- `int cpu`: CPU number
- `unsigned int flags`: flags modifying the default behavior of the worker
- `const char namefmt[]`: printf-style name for the thread. Format is restricted
  to "name.*`u`". Code fills in cpu number.

**Description**

Use a valid CPU number if you want to bind the kthread worker
to the given CPU and the associated NUMA node.

A good practice is to add the cpu number also into the worker name.
For example, use kthread_create_worker_on_cpu(cpu, "helper/`d`", cpu).

CPU hotplug:
The kthread worker API is simple and generic. It just provides a way
to create, use, and destroy workers.

It is up to the API user how to handle CPU hotplug. They have to decide
how to handle pending work items, prevent queuing new ones, and
restore the functionality when the CPU goes off and on. There are a
few catches:

- CPU affinity gets lost when it is scheduled on an offline CPU.

- The worker might not exist when the CPU was off when the user
  created the workers.

Good practice is to implement two CPU hotplug callbacks and to
destroy/create the worker when the CPU goes down/up.

**Return**

The pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
when the needed structures could not get allocated, and ERR_PTR(-EINTR)
when the caller was killed by a fatal signal.

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

```c
bool kthread_queue_work(struct kthread_worker *worker, struct kthread_work *work)
```

queue a kthread_work

**Parameters**

- `struct kthread_worker *worker`: target kthread_worker
- `struct kthread_work *work`: kthread_work to queue

**Description**

Queue **work** to work processor **task** for async execution.  **task**
must have been created with `kthread_create_worker()`.  Returns `true`
if **work** was successfully queued, `false` if it was already pending.

Reinitialize the work if it needs to be used by another worker.
For example, when the worker was stopped and started again.

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

```c
void kthread_delayed_work_timer_fn(struct timer_list *t)
```

callback that queues the associated kthread delayed work when the timer expires.

**Parameters**

- `struct timer_list *t`: pointer to the expired timer

**Description**

The format of the function is defined by struct timer_list.
It should have been called from irqsafe timer with irq already off.

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

```c
bool kthread_queue_delayed_work(struct kthread_worker *worker, struct kthread_delayed_work *dwork, unsigned long delay)
```

queue the associated kthread work after a delay.

**Parameters**

- `struct kthread_worker *worker`: target kthread_worker
- `struct kthread_delayed_work *dwork`: kthread_delayed_work to queue
- `unsigned long delay`: number of jiffies to wait before queuing

**Description**

If the work has not been pending it starts a timer that will queue
the work after the given **delay**. If **delay** is zero, it queues the
work immediately.

**Return**

`false` if the **work** has already been pending. It means that
either the timer was running or the work was queued. It returns `true`
otherwise.

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

```c
void kthread_flush_work(struct kthread_work *work)
```

flush a kthread_work

**Parameters**

- `struct kthread_work *work`: work to flush

**Description**

If **work** is queued or executing, wait for it to finish execution.

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

```c
bool kthread_mod_delayed_work(struct kthread_worker *worker, struct kthread_delayed_work *dwork, unsigned long delay)
```

modify delay of or queue a kthread delayed work

**Parameters**

- `struct kthread_worker *worker`: kthread worker to use
- `struct kthread_delayed_work *dwork`: kthread delayed work to queue
- `unsigned long delay`: number of jiffies to wait before queuing

**Description**

If **dwork** is idle, equivalent to [`kthread_queue_delayed_work()`](#c-kthread_queue_delayed_work). Otherwise,
modify **dwork**'s timer so that it expires after **delay**. If **delay** is zero,
**work** is guaranteed to be queued immediately.

A special case is when the work is being canceled in parallel.
It might be caused either by the real [`kthread_cancel_delayed_work_sync()`](#c-kthread_cancel_delayed_work_sync)
or yet another [`kthread_mod_delayed_work()`](#c-kthread_mod_delayed_work) call. We let the other command
win and return `true` here. The return value can be used for reference
counting and the number of queued works stays the same. Anyway, the caller
is supposed to synchronize these operations a reasonable way.

This function is safe to call from any context including IRQ handler.
See `__kthread_cancel_work()` and [`kthread_delayed_work_timer_fn()`](#c-kthread_delayed_work_timer_fn)
for details.

**Return**

`false` if **dwork** was idle and queued, `true` otherwise.

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

```c
bool kthread_cancel_work_sync(struct kthread_work *work)
```

cancel a kthread work and wait for it to finish

**Parameters**

- `struct kthread_work *work`: the kthread work to cancel

**Description**

Cancel **work** and wait for its execution to finish.  This function
can be used even if the work re-queues itself. On return from this
function, **work** is guaranteed to be not pending or executing on any CPU.

kthread_cancel_work_sync(`delayed_work->work`) must not be used for
delayed_work's. Use [`kthread_cancel_delayed_work_sync()`](#c-kthread_cancel_delayed_work_sync) instead.

The caller must ensure that the worker on which **work** was last
queued can't be destroyed before this function returns.

**Return**

`true` if **work** was pending, `false` otherwise.

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

```c
bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
```

cancel a kthread delayed work and wait for it to finish.

**Parameters**

- `struct kthread_delayed_work *dwork`: the kthread delayed work to cancel

**Description**

This is [`kthread_cancel_work_sync()`](#c-kthread_cancel_work_sync) for delayed works.

**Return**

`true` if **dwork** was pending, `false` otherwise.

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

```c
void kthread_flush_worker(struct kthread_worker *worker)
```

flush all current works on a kthread_worker

**Parameters**

- `struct kthread_worker *worker`: worker to flush

**Description**

Wait until all currently executing or pending works on **worker** are
finished.

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

```c
void kthread_destroy_worker(struct kthread_worker *worker)
```

destroy a kthread worker

**Parameters**

- `struct kthread_worker *worker`: worker to be destroyed

**Description**

Flush and destroy **worker**.  The simple flush is enough because the kthread
worker API is used only in trivial scenarios.  There are no multi-step state
machines needed.

Note that this function is not responsible for handling delayed work, so
caller should be responsible for queuing or canceling all delayed work items
before invoke this function.

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

```c
void kthread_use_mm(struct mm_struct *mm)
```

make the calling kthread operate on an address space

**Parameters**

- `struct mm_struct *mm`: address space to operate on

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

```c
void kthread_unuse_mm(struct mm_struct *mm)
```

reverse the effect of [`kthread_use_mm()`](#c-kthread_use_mm)

**Parameters**

- `struct mm_struct *mm`: address space to operate on

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

```c
void kthread_associate_blkcg(struct cgroup_subsys_state *css)
```

associate blkcg to current kthread

**Parameters**

- `struct cgroup_subsys_state *css`: the cgroup info

**Description**

Current thread must be a kthread. The thread is running jobs on behalf of
other threads. In some cases, we expect the jobs attach cgroup info of
original threads instead of that of current thread. This function stores
original thread's cgroup info in current kthread context for later
retrieval.


<a id="rst-reference-counting"></a>

## Reference counting


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

```c
void refcount_set(refcount_t *r, int n)
```

set a refcount's value

**Parameters**

- `refcount_t *r`: the refcount
- `int n`: value to which the refcount will be set

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

```c
void refcount_set_release(refcount_t *r, int n)
```

set a refcount's value with release ordering

**Parameters**

- `refcount_t *r`: the refcount
- `int n`: value to which the refcount will be set

**Description**

This function should be used when memory occupied by the object might be
reused to store another object -- consider SLAB_TYPESAFE_BY_RCU.

Provides release memory ordering which will order previous memory operations
against this store. This ensures all updates to this object are visible
once the refcount is set and stale values from the object previously
occupying this memory are overwritten with new ones.

This function should be called only after new object is fully initialized.
After this call the object should be considered visible to other tasks even
if it was not yet added into an object collection normally used to discover
it. This is because other tasks might have discovered the object previously
occupying the same memory and after memory reuse they can succeed in taking
refcount to the new object and start using it.

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

```c
unsigned int refcount_read(const refcount_t *r)
```

get a refcount's value

**Parameters**

- `const refcount_t *r`: the refcount

**Return**

the refcount's value

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

```c
bool refcount_add_not_zero(int i, refcount_t *r)
```

add a value to a refcount unless it is 0

**Parameters**

- `int i`: the value to add to the refcount
- `refcount_t *r`: the refcount

**Description**

Will saturate at REFCOUNT_SATURATED and WARN.

Provides no memory ordering, it is assumed the caller has guaranteed the
object memory to be stable (RCU, etc.). It does provide a control dependency
and thereby orders future stores. See the comment on top.

Use of this function is not recommended for the normal reference counting
use case in which references are taken and released one at a time.  In these
cases, [`refcount_inc()`](#c-refcount_inc), or one of its variants, should instead be used to
increment a reference count.

**Return**

false if the passed refcount is 0, true otherwise

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

```c
bool refcount_add_not_zero_acquire(int i, refcount_t *r)
```

add a value to a refcount with acquire ordering unless it is 0

**Parameters**

- `int i`: the value to add to the refcount
- `refcount_t *r`: the refcount

**Description**

Will saturate at REFCOUNT_SATURATED and WARN.

This function should be used when memory occupied by the object might be
reused to store another object -- consider SLAB_TYPESAFE_BY_RCU.

Provides acquire memory ordering on success, it is assumed the caller has
guaranteed the object memory to be stable (RCU, etc.). It does provide a
control dependency and thereby orders future stores. See the comment on top.

Use of this function is not recommended for the normal reference counting
use case in which references are taken and released one at a time.  In these
cases, [`refcount_inc_not_zero_acquire()`](#c-refcount_inc_not_zero_acquire) should instead be used to increment a
reference count.

**Return**

false if the passed refcount is 0, true otherwise

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

```c
void refcount_add(int i, refcount_t *r)
```

add a value to a refcount

**Parameters**

- `int i`: the value to add to the refcount
- `refcount_t *r`: the refcount

**Description**

Similar to [`atomic_add()`](#c-atomic_add), but will saturate at REFCOUNT_SATURATED and WARN.

Provides no memory ordering, it is assumed the caller has guaranteed the
object memory to be stable (RCU, etc.). It does provide a control dependency
and thereby orders future stores. See the comment on top.

Use of this function is not recommended for the normal reference counting
use case in which references are taken and released one at a time.  In these
cases, [`refcount_inc()`](#c-refcount_inc), or one of its variants, should instead be used to
increment a reference count.

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

```c
bool refcount_inc_not_zero(refcount_t *r)
```

increment a refcount unless it is 0

**Parameters**

- `refcount_t *r`: the refcount to increment

**Description**

Similar to [`atomic_inc_not_zero()`](#c-atomic_inc_not_zero), but will saturate at REFCOUNT_SATURATED
and WARN.

Provides no memory ordering, it is assumed the caller has guaranteed the
object memory to be stable (RCU, etc.). It does provide a control dependency
and thereby orders future stores. See the comment on top.

**Return**

true if the increment was successful, false otherwise

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

```c
bool refcount_inc_not_zero_acquire(refcount_t *r)
```

increment a refcount with acquire ordering unless it is 0

**Parameters**

- `refcount_t *r`: the refcount to increment

**Description**

Similar to [`refcount_inc_not_zero()`](#c-refcount_inc_not_zero), but provides acquire memory ordering on
success.

This function should be used when memory occupied by the object might be
reused to store another object -- consider SLAB_TYPESAFE_BY_RCU.

Provides acquire memory ordering on success, it is assumed the caller has
guaranteed the object memory to be stable (RCU, etc.). It does provide a
control dependency and thereby orders future stores. See the comment on top.

**Return**

true if the increment was successful, false otherwise

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

```c
void refcount_inc(refcount_t *r)
```

increment a refcount

**Parameters**

- `refcount_t *r`: the refcount to increment

**Description**

Similar to [`atomic_inc()`](#c-atomic_inc), but will saturate at REFCOUNT_SATURATED and WARN.

Provides no memory ordering, it is assumed the caller already has a
reference on the object.

Will WARN if the refcount is 0, as this represents a possible use-after-free
condition.

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

```c
bool refcount_sub_and_test(int i, refcount_t *r)
```

subtract from a refcount and test if it is 0

**Parameters**

- `int i`: amount to subtract from the refcount
- `refcount_t *r`: the refcount

**Description**

Similar to [`atomic_dec_and_test()`](#c-atomic_dec_and_test), but it will WARN, return false and
ultimately leak on underflow and will fail to decrement when saturated
at REFCOUNT_SATURATED.

Provides release memory ordering, such that prior loads and stores are done
before, and provides an acquire ordering on success such that `free()`
must come after.

Use of this function is not recommended for the normal reference counting
use case in which references are taken and released one at a time.  In these
cases, [`refcount_dec()`](#c-refcount_dec), or one of its variants, should instead be used to
decrement a reference count.

**Return**

true if the resulting refcount is 0, false otherwise

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

```c
bool refcount_dec_and_test(refcount_t *r)
```

decrement a refcount and test if it is 0

**Parameters**

- `refcount_t *r`: the refcount

**Description**

Similar to [`atomic_dec_and_test()`](#c-atomic_dec_and_test), it will WARN on underflow and fail to
decrement when saturated at REFCOUNT_SATURATED.

Provides release memory ordering, such that prior loads and stores are done
before, and provides an acquire ordering on success such that `free()`
must come after.

**Return**

true if the resulting refcount is 0, false otherwise

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

```c
void refcount_dec(refcount_t *r)
```

decrement a refcount

**Parameters**

- `refcount_t *r`: the refcount

**Description**

Similar to [`atomic_dec()`](#c-atomic_dec), it will WARN on underflow and fail to decrement
when saturated at REFCOUNT_SATURATED.

Provides release memory ordering, such that prior loads and stores are done
before.



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

```c
bool refcount_dec_if_one(refcount_t *r)
```

decrement a refcount if it is 1

**Parameters**

- `refcount_t *r`: the refcount

**Description**

No atomic_t counterpart, it attempts a 1 -> 0 transition and returns the
success thereof.

Like all decrement operations, it provides release memory order and provides
a control dependency.

It can be used like a try-delete operator; this explicit case is provided
and not cmpxchg in generic, because that would allow implementing unsafe
operations.

**Return**

true if the resulting refcount is 0, false otherwise

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

```c
bool refcount_dec_not_one(refcount_t *r)
```

decrement a refcount if it is not 1

**Parameters**

- `refcount_t *r`: the refcount

**Description**

No atomic_t counterpart, it decrements unless the value is 1, in which case
it will return false.

Was often done like: atomic_add_unless(`var`, -1, 1)

**Return**

true if the decrement operation was successful, false otherwise

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

```c
bool refcount_dec_and_mutex_lock(refcount_t *r, struct mutex *lock)
```

return holding mutex if able to decrement refcount to 0

**Parameters**

- `refcount_t *r`: the refcount
- `struct mutex *lock`: the mutex to be locked

**Description**

Similar to [`atomic_dec_and_mutex_lock()`](/kernel/development/kernel-hacking/locking.md#c-atomic_dec_and_mutex_lock), it will WARN on underflow and fail
to decrement when saturated at REFCOUNT_SATURATED.

Provides release memory ordering, such that prior loads and stores are done
before, and provides a control dependency such that `free()` must come after.
See the comment on top.

**Return**

true and hold mutex if able to decrement refcount to 0, false
otherwise

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

```c
bool refcount_dec_and_lock(refcount_t *r, spinlock_t *lock)
```

return holding spinlock if able to decrement refcount to 0

**Parameters**

- `refcount_t *r`: the refcount
- `spinlock_t *lock`: the spinlock to be locked

**Description**

Similar to `atomic_dec_and_lock()`, it will WARN on underflow and fail to
decrement when saturated at REFCOUNT_SATURATED.

Provides release memory ordering, such that prior loads and stores are done
before, and provides a control dependency such that `free()` must come after.
See the comment on top.

**Return**

true and hold spinlock if able to decrement refcount to 0, false
otherwise

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

```c
bool refcount_dec_and_lock_irqsave(refcount_t *r, spinlock_t *lock, unsigned long *flags)
```

return holding spinlock with disabled interrupts if able to decrement refcount to 0

**Parameters**

- `refcount_t *r`: the refcount
- `spinlock_t *lock`: the spinlock to be locked
- `unsigned long *flags`: saved IRQ-flags if the is acquired

**Description**

Same as [`refcount_dec_and_lock()`](#c-refcount_dec_and_lock) above except that the spinlock is acquired
with disabled interrupts.

**Return**

true and hold spinlock if able to decrement refcount to 0, false
otherwise


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

## Atomics


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

```c
int atomic_read(const atomic_t *v)
```

atomic load with relaxed ordering

**Parameters**

- `const atomic_t *v`: pointer to atomic_t

**Description**

Atomically loads the value of **v** with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_read()`](#c-raw_atomic_read) there.

**Return**

The value loaded from **v**.

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

```c
int atomic_read_acquire(const atomic_t *v)
```

atomic load with acquire ordering

**Parameters**

- `const atomic_t *v`: pointer to atomic_t

**Description**

Atomically loads the value of **v** with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_read_acquire()`](#c-raw_atomic_read_acquire) there.

**Return**

The value loaded from **v**.

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

```c
void atomic_set(atomic_t *v, int i)
```

atomic set with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int i`: int value to assign

**Description**

Atomically sets **v** to **i** with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_set()`](#c-raw_atomic_set) there.

**Return**

Nothing.

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

```c
void atomic_set_release(atomic_t *v, int i)
```

atomic set with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int i`: int value to assign

**Description**

Atomically sets **v** to **i** with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_set_release()`](#c-raw_atomic_set_release) there.

**Return**

Nothing.

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

```c
void atomic_add(int i, atomic_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_add()`](#c-raw_atomic_add) there.

**Return**

Nothing.

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

```c
int atomic_add_return(int i, atomic_t *v)
```

atomic add with full ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_add_return()`](#c-raw_atomic_add_return) there.

**Return**

The updated value of **v**.

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

```c
int atomic_add_return_acquire(int i, atomic_t *v)
```

atomic add with acquire ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_add_return_acquire()`](#c-raw_atomic_add_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
int atomic_add_return_release(int i, atomic_t *v)
```

atomic add with release ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_add_return_release()`](#c-raw_atomic_add_return_release) there.

**Return**

The updated value of **v**.

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

```c
int atomic_add_return_relaxed(int i, atomic_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_add_return_relaxed()`](#c-raw_atomic_add_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
int atomic_fetch_add(int i, atomic_t *v)
```

atomic add with full ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_add()`](#c-raw_atomic_fetch_add) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_add_acquire(int i, atomic_t *v)
```

atomic add with acquire ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_add_acquire()`](#c-raw_atomic_fetch_add_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_add_release(int i, atomic_t *v)
```

atomic add with release ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_add_release()`](#c-raw_atomic_fetch_add_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_add_relaxed(int i, atomic_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_add_relaxed()`](#c-raw_atomic_fetch_add_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_sub(int i, atomic_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_sub()`](#c-raw_atomic_sub) there.

**Return**

Nothing.

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

```c
int atomic_sub_return(int i, atomic_t *v)
```

atomic subtract with full ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_sub_return()`](#c-raw_atomic_sub_return) there.

**Return**

The updated value of **v**.

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

```c
int atomic_sub_return_acquire(int i, atomic_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_sub_return_acquire()`](#c-raw_atomic_sub_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
int atomic_sub_return_release(int i, atomic_t *v)
```

atomic subtract with release ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_sub_return_release()`](#c-raw_atomic_sub_return_release) there.

**Return**

The updated value of **v**.

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

```c
int atomic_sub_return_relaxed(int i, atomic_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_sub_return_relaxed()`](#c-raw_atomic_sub_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
int atomic_fetch_sub(int i, atomic_t *v)
```

atomic subtract with full ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_sub()`](#c-raw_atomic_fetch_sub) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_sub_acquire(int i, atomic_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_sub_acquire()`](#c-raw_atomic_fetch_sub_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_sub_release(int i, atomic_t *v)
```

atomic subtract with release ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_sub_release()`](#c-raw_atomic_fetch_sub_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_sub_relaxed(int i, atomic_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_sub_relaxed()`](#c-raw_atomic_fetch_sub_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_inc(atomic_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_inc()`](#c-raw_atomic_inc) there.

**Return**

Nothing.

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

```c
int atomic_inc_return(atomic_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_inc_return()`](#c-raw_atomic_inc_return) there.

**Return**

The updated value of **v**.

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

```c
int atomic_inc_return_acquire(atomic_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_inc_return_acquire()`](#c-raw_atomic_inc_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
int atomic_inc_return_release(atomic_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_inc_return_release()`](#c-raw_atomic_inc_return_release) there.

**Return**

The updated value of **v**.

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

```c
int atomic_inc_return_relaxed(atomic_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_inc_return_relaxed()`](#c-raw_atomic_inc_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
int atomic_fetch_inc(atomic_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_inc()`](#c-raw_atomic_fetch_inc) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_inc_acquire(atomic_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_inc_acquire()`](#c-raw_atomic_fetch_inc_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_inc_release(atomic_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_inc_release()`](#c-raw_atomic_fetch_inc_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_inc_relaxed(atomic_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_inc_relaxed()`](#c-raw_atomic_fetch_inc_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_dec(atomic_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_dec()`](#c-raw_atomic_dec) there.

**Return**

Nothing.

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

```c
int atomic_dec_return(atomic_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_dec_return()`](#c-raw_atomic_dec_return) there.

**Return**

The updated value of **v**.

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

```c
int atomic_dec_return_acquire(atomic_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_dec_return_acquire()`](#c-raw_atomic_dec_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
int atomic_dec_return_release(atomic_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_dec_return_release()`](#c-raw_atomic_dec_return_release) there.

**Return**

The updated value of **v**.

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

```c
int atomic_dec_return_relaxed(atomic_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_dec_return_relaxed()`](#c-raw_atomic_dec_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
int atomic_fetch_dec(atomic_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_dec()`](#c-raw_atomic_fetch_dec) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_dec_acquire(atomic_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_dec_acquire()`](#c-raw_atomic_fetch_dec_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_dec_release(atomic_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_dec_release()`](#c-raw_atomic_fetch_dec_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_dec_relaxed(atomic_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_dec_relaxed()`](#c-raw_atomic_fetch_dec_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_and(int i, atomic_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_and()`](#c-raw_atomic_and) there.

**Return**

Nothing.

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

```c
int atomic_fetch_and(int i, atomic_t *v)
```

atomic bitwise AND with full ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_and()`](#c-raw_atomic_fetch_and) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_and_acquire(int i, atomic_t *v)
```

atomic bitwise AND with acquire ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_and_acquire()`](#c-raw_atomic_fetch_and_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_and_release(int i, atomic_t *v)
```

atomic bitwise AND with release ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_and_release()`](#c-raw_atomic_fetch_and_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_and_relaxed(int i, atomic_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_and_relaxed()`](#c-raw_atomic_fetch_and_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_andnot(int i, atomic_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_andnot()`](#c-raw_atomic_andnot) there.

**Return**

Nothing.

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

```c
int atomic_fetch_andnot(int i, atomic_t *v)
```

atomic bitwise AND NOT with full ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_andnot()`](#c-raw_atomic_fetch_andnot) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_andnot_acquire(int i, atomic_t *v)
```

atomic bitwise AND NOT with acquire ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_andnot_acquire()`](#c-raw_atomic_fetch_andnot_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_andnot_release(int i, atomic_t *v)
```

atomic bitwise AND NOT with release ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_andnot_release()`](#c-raw_atomic_fetch_andnot_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_andnot_relaxed(int i, atomic_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_andnot_relaxed()`](#c-raw_atomic_fetch_andnot_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_or(int i, atomic_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_or()`](#c-raw_atomic_or) there.

**Return**

Nothing.

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

```c
int atomic_fetch_or(int i, atomic_t *v)
```

atomic bitwise OR with full ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_or()`](#c-raw_atomic_fetch_or) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_or_acquire(int i, atomic_t *v)
```

atomic bitwise OR with acquire ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_or_acquire()`](#c-raw_atomic_fetch_or_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_or_release(int i, atomic_t *v)
```

atomic bitwise OR with release ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_or_release()`](#c-raw_atomic_fetch_or_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_or_relaxed(int i, atomic_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_or_relaxed()`](#c-raw_atomic_fetch_or_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_xor(int i, atomic_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_xor()`](#c-raw_atomic_xor) there.

**Return**

Nothing.

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

```c
int atomic_fetch_xor(int i, atomic_t *v)
```

atomic bitwise XOR with full ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_xor()`](#c-raw_atomic_fetch_xor) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_xor_acquire(int i, atomic_t *v)
```

atomic bitwise XOR with acquire ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_xor_acquire()`](#c-raw_atomic_fetch_xor_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_xor_release(int i, atomic_t *v)
```

atomic bitwise XOR with release ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_xor_release()`](#c-raw_atomic_fetch_xor_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_fetch_xor_relaxed(int i, atomic_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_xor_relaxed()`](#c-raw_atomic_fetch_xor_relaxed) there.

**Return**

The original value of **v**.

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

```c
int atomic_xchg(atomic_t *v, int new)
```

atomic exchange with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int new`: int value to assign

**Description**

Atomically updates **v** to **new** with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_xchg()`](#c-raw_atomic_xchg) there.

**Return**

The original value of **v**.

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

```c
int atomic_xchg_acquire(atomic_t *v, int new)
```

atomic exchange with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int new`: int value to assign

**Description**

Atomically updates **v** to **new** with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_xchg_acquire()`](#c-raw_atomic_xchg_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_xchg_release(atomic_t *v, int new)
```

atomic exchange with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int new`: int value to assign

**Description**

Atomically updates **v** to **new** with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_xchg_release()`](#c-raw_atomic_xchg_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_xchg_relaxed(atomic_t *v, int new)
```

atomic exchange with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int new`: int value to assign

**Description**

Atomically updates **v** to **new** with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_xchg_relaxed()`](#c-raw_atomic_xchg_relaxed) there.

**Return**

The original value of **v**.

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

```c
int atomic_cmpxchg(atomic_t *v, int old, int new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int old`: int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_cmpxchg()`](#c-raw_atomic_cmpxchg) there.

**Return**

The original value of **v**.

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

```c
int atomic_cmpxchg_acquire(atomic_t *v, int old, int new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int old`: int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_cmpxchg_acquire()`](#c-raw_atomic_cmpxchg_acquire) there.

**Return**

The original value of **v**.

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

```c
int atomic_cmpxchg_release(atomic_t *v, int old, int new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int old`: int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_cmpxchg_release()`](#c-raw_atomic_cmpxchg_release) there.

**Return**

The original value of **v**.

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

```c
int atomic_cmpxchg_relaxed(atomic_t *v, int old, int new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int old`: int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_cmpxchg_relaxed()`](#c-raw_atomic_cmpxchg_relaxed) there.

**Return**

The original value of **v**.

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

```c
bool atomic_try_cmpxchg(atomic_t *v, int *old, int new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int *old`: pointer to int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_try_cmpxchg()`](#c-raw_atomic_try_cmpxchg) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic_try_cmpxchg_acquire(atomic_t *v, int *old, int new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int *old`: pointer to int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_try_cmpxchg_acquire()`](#c-raw_atomic_try_cmpxchg_acquire) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic_try_cmpxchg_release(atomic_t *v, int *old, int new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int *old`: pointer to int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_try_cmpxchg_release()`](#c-raw_atomic_try_cmpxchg_release) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic_try_cmpxchg_relaxed(atomic_t *v, int *old, int new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int *old`: pointer to int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_try_cmpxchg_relaxed()`](#c-raw_atomic_try_cmpxchg_relaxed) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic_sub_and_test(int i, atomic_t *v)
```

atomic subtract and test if zero with full ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_sub_and_test()`](#c-raw_atomic_sub_and_test) there.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool atomic_dec_and_test(atomic_t *v)
```

atomic decrement and test if zero with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_dec_and_test()`](#c-raw_atomic_dec_and_test) there.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool atomic_inc_and_test(atomic_t *v)
```

atomic increment and test if zero with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_inc_and_test()`](#c-raw_atomic_inc_and_test) there.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool atomic_add_negative(int i, atomic_t *v)
```

atomic add and test if negative with full ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_add_negative()`](#c-raw_atomic_add_negative) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool atomic_add_negative_acquire(int i, atomic_t *v)
```

atomic add and test if negative with acquire ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_add_negative_acquire()`](#c-raw_atomic_add_negative_acquire) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool atomic_add_negative_release(int i, atomic_t *v)
```

atomic add and test if negative with release ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_add_negative_release()`](#c-raw_atomic_add_negative_release) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool atomic_add_negative_relaxed(int i, atomic_t *v)
```

atomic add and test if negative with relaxed ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_add_negative_relaxed()`](#c-raw_atomic_add_negative_relaxed) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
int atomic_fetch_add_unless(atomic_t *v, int a, int u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int a`: int value to add
- `int u`: int value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_fetch_add_unless()`](#c-raw_atomic_fetch_add_unless) there.

**Return**

The original value of **v**.

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

```c
bool atomic_add_unless(atomic_t *v, int a, int u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int a`: int value to add
- `int u`: int value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_add_unless()`](#c-raw_atomic_add_unless) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool atomic_inc_not_zero(atomic_t *v)
```

atomic increment unless zero with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

If (**v** != 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_inc_not_zero()`](#c-raw_atomic_inc_not_zero) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool atomic_inc_unless_negative(atomic_t *v)
```

atomic increment unless negative with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

If (**v** >= 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_inc_unless_negative()`](#c-raw_atomic_inc_unless_negative) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool atomic_dec_unless_positive(atomic_t *v)
```

atomic decrement unless positive with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

If (**v** \<= 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_dec_unless_positive()`](#c-raw_atomic_dec_unless_positive) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
int atomic_dec_if_positive(atomic_t *v)
```

atomic decrement if positive with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

If (**v** > 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_dec_if_positive()`](#c-raw_atomic_dec_if_positive) there.

**Return**

The old value of (**v** - 1), regardless of whether **v** was updated.

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

```c
s64 atomic64_read(const atomic64_t *v)
```

atomic load with relaxed ordering

**Parameters**

- `const atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically loads the value of **v** with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_read()`](#c-raw_atomic64_read) there.

**Return**

The value loaded from **v**.

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

```c
s64 atomic64_read_acquire(const atomic64_t *v)
```

atomic load with acquire ordering

**Parameters**

- `const atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically loads the value of **v** with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_read_acquire()`](#c-raw_atomic64_read_acquire) there.

**Return**

The value loaded from **v**.

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

```c
void atomic64_set(atomic64_t *v, s64 i)
```

atomic set with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 i`: s64 value to assign

**Description**

Atomically sets **v** to **i** with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_set()`](#c-raw_atomic64_set) there.

**Return**

Nothing.

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

```c
void atomic64_set_release(atomic64_t *v, s64 i)
```

atomic set with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 i`: s64 value to assign

**Description**

Atomically sets **v** to **i** with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_set_release()`](#c-raw_atomic64_set_release) there.

**Return**

Nothing.

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

```c
void atomic64_add(s64 i, atomic64_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_add()`](#c-raw_atomic64_add) there.

**Return**

Nothing.

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

```c
s64 atomic64_add_return(s64 i, atomic64_t *v)
```

atomic add with full ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_add_return()`](#c-raw_atomic64_add_return) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_add_return_acquire(s64 i, atomic64_t *v)
```

atomic add with acquire ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_add_return_acquire()`](#c-raw_atomic64_add_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_add_return_release(s64 i, atomic64_t *v)
```

atomic add with release ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_add_return_release()`](#c-raw_atomic64_add_return_release) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_add_return_relaxed(s64 i, atomic64_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_add_return_relaxed()`](#c-raw_atomic64_add_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_fetch_add(s64 i, atomic64_t *v)
```

atomic add with full ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_add()`](#c-raw_atomic64_fetch_add) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_add_acquire(s64 i, atomic64_t *v)
```

atomic add with acquire ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_add_acquire()`](#c-raw_atomic64_fetch_add_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_add_release(s64 i, atomic64_t *v)
```

atomic add with release ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_add_release()`](#c-raw_atomic64_fetch_add_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_add_relaxed(s64 i, atomic64_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_add_relaxed()`](#c-raw_atomic64_fetch_add_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic64_sub(s64 i, atomic64_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_sub()`](#c-raw_atomic64_sub) there.

**Return**

Nothing.

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

```c
s64 atomic64_sub_return(s64 i, atomic64_t *v)
```

atomic subtract with full ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_sub_return()`](#c-raw_atomic64_sub_return) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_sub_return_acquire(s64 i, atomic64_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_sub_return_acquire()`](#c-raw_atomic64_sub_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_sub_return_release(s64 i, atomic64_t *v)
```

atomic subtract with release ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_sub_return_release()`](#c-raw_atomic64_sub_return_release) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_sub_return_relaxed(s64 i, atomic64_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_sub_return_relaxed()`](#c-raw_atomic64_sub_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_fetch_sub(s64 i, atomic64_t *v)
```

atomic subtract with full ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_sub()`](#c-raw_atomic64_fetch_sub) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_sub_acquire(s64 i, atomic64_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_sub_acquire()`](#c-raw_atomic64_fetch_sub_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_sub_release(s64 i, atomic64_t *v)
```

atomic subtract with release ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_sub_release()`](#c-raw_atomic64_fetch_sub_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_sub_relaxed(s64 i, atomic64_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_sub_relaxed()`](#c-raw_atomic64_fetch_sub_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic64_inc(atomic64_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_inc()`](#c-raw_atomic64_inc) there.

**Return**

Nothing.

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

```c
s64 atomic64_inc_return(atomic64_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_inc_return()`](#c-raw_atomic64_inc_return) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_inc_return_acquire(atomic64_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_inc_return_acquire()`](#c-raw_atomic64_inc_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_inc_return_release(atomic64_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_inc_return_release()`](#c-raw_atomic64_inc_return_release) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_inc_return_relaxed(atomic64_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_inc_return_relaxed()`](#c-raw_atomic64_inc_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_fetch_inc(atomic64_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_inc()`](#c-raw_atomic64_fetch_inc) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_inc_acquire(atomic64_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_inc_acquire()`](#c-raw_atomic64_fetch_inc_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_inc_release(atomic64_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_inc_release()`](#c-raw_atomic64_fetch_inc_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_inc_relaxed(atomic64_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_inc_relaxed()`](#c-raw_atomic64_fetch_inc_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic64_dec(atomic64_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_dec()`](#c-raw_atomic64_dec) there.

**Return**

Nothing.

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

```c
s64 atomic64_dec_return(atomic64_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_dec_return()`](#c-raw_atomic64_dec_return) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_dec_return_acquire(atomic64_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_dec_return_acquire()`](#c-raw_atomic64_dec_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_dec_return_release(atomic64_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_dec_return_release()`](#c-raw_atomic64_dec_return_release) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_dec_return_relaxed(atomic64_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_dec_return_relaxed()`](#c-raw_atomic64_dec_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
s64 atomic64_fetch_dec(atomic64_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_dec()`](#c-raw_atomic64_fetch_dec) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_dec_acquire(atomic64_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_dec_acquire()`](#c-raw_atomic64_fetch_dec_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_dec_release(atomic64_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_dec_release()`](#c-raw_atomic64_fetch_dec_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_dec_relaxed(atomic64_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_dec_relaxed()`](#c-raw_atomic64_fetch_dec_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic64_and(s64 i, atomic64_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_and()`](#c-raw_atomic64_and) there.

**Return**

Nothing.

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

```c
s64 atomic64_fetch_and(s64 i, atomic64_t *v)
```

atomic bitwise AND with full ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_and()`](#c-raw_atomic64_fetch_and) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_and_acquire(s64 i, atomic64_t *v)
```

atomic bitwise AND with acquire ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_and_acquire()`](#c-raw_atomic64_fetch_and_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_and_release(s64 i, atomic64_t *v)
```

atomic bitwise AND with release ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_and_release()`](#c-raw_atomic64_fetch_and_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_and_relaxed(s64 i, atomic64_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_and_relaxed()`](#c-raw_atomic64_fetch_and_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic64_andnot(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_andnot()`](#c-raw_atomic64_andnot) there.

**Return**

Nothing.

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

```c
s64 atomic64_fetch_andnot(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with full ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_andnot()`](#c-raw_atomic64_fetch_andnot) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_andnot_acquire(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with acquire ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_andnot_acquire()`](#c-raw_atomic64_fetch_andnot_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_andnot_release(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with release ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_andnot_release()`](#c-raw_atomic64_fetch_andnot_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_andnot_relaxed(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_andnot_relaxed()`](#c-raw_atomic64_fetch_andnot_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic64_or(s64 i, atomic64_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_or()`](#c-raw_atomic64_or) there.

**Return**

Nothing.

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

```c
s64 atomic64_fetch_or(s64 i, atomic64_t *v)
```

atomic bitwise OR with full ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_or()`](#c-raw_atomic64_fetch_or) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_or_acquire(s64 i, atomic64_t *v)
```

atomic bitwise OR with acquire ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_or_acquire()`](#c-raw_atomic64_fetch_or_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_or_release(s64 i, atomic64_t *v)
```

atomic bitwise OR with release ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_or_release()`](#c-raw_atomic64_fetch_or_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_or_relaxed(s64 i, atomic64_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_or_relaxed()`](#c-raw_atomic64_fetch_or_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic64_xor(s64 i, atomic64_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_xor()`](#c-raw_atomic64_xor) there.

**Return**

Nothing.

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

```c
s64 atomic64_fetch_xor(s64 i, atomic64_t *v)
```

atomic bitwise XOR with full ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_xor()`](#c-raw_atomic64_fetch_xor) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_xor_acquire(s64 i, atomic64_t *v)
```

atomic bitwise XOR with acquire ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_xor_acquire()`](#c-raw_atomic64_fetch_xor_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_xor_release(s64 i, atomic64_t *v)
```

atomic bitwise XOR with release ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_xor_release()`](#c-raw_atomic64_fetch_xor_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_fetch_xor_relaxed(s64 i, atomic64_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_xor_relaxed()`](#c-raw_atomic64_fetch_xor_relaxed) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_xchg(atomic64_t *v, s64 new)
```

atomic exchange with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 new`: s64 value to assign

**Description**

Atomically updates **v** to **new** with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_xchg()`](#c-raw_atomic64_xchg) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_xchg_acquire(atomic64_t *v, s64 new)
```

atomic exchange with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 new`: s64 value to assign

**Description**

Atomically updates **v** to **new** with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_xchg_acquire()`](#c-raw_atomic64_xchg_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_xchg_release(atomic64_t *v, s64 new)
```

atomic exchange with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 new`: s64 value to assign

**Description**

Atomically updates **v** to **new** with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_xchg_release()`](#c-raw_atomic64_xchg_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_xchg_relaxed(atomic64_t *v, s64 new)
```

atomic exchange with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 new`: s64 value to assign

**Description**

Atomically updates **v** to **new** with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_xchg_relaxed()`](#c-raw_atomic64_xchg_relaxed) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_cmpxchg(atomic64_t *v, s64 old, s64 new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 old`: s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_cmpxchg()`](#c-raw_atomic64_cmpxchg) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_cmpxchg_acquire(atomic64_t *v, s64 old, s64 new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 old`: s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_cmpxchg_acquire()`](#c-raw_atomic64_cmpxchg_acquire) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_cmpxchg_release(atomic64_t *v, s64 old, s64 new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 old`: s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_cmpxchg_release()`](#c-raw_atomic64_cmpxchg_release) there.

**Return**

The original value of **v**.

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

```c
s64 atomic64_cmpxchg_relaxed(atomic64_t *v, s64 old, s64 new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 old`: s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_cmpxchg_relaxed()`](#c-raw_atomic64_cmpxchg_relaxed) there.

**Return**

The original value of **v**.

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

```c
bool atomic64_try_cmpxchg(atomic64_t *v, s64 *old, s64 new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 *old`: pointer to s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_try_cmpxchg()`](#c-raw_atomic64_try_cmpxchg) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic64_try_cmpxchg_acquire(atomic64_t *v, s64 *old, s64 new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 *old`: pointer to s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_try_cmpxchg_acquire()`](#c-raw_atomic64_try_cmpxchg_acquire) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic64_try_cmpxchg_release(atomic64_t *v, s64 *old, s64 new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 *old`: pointer to s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_try_cmpxchg_release()`](#c-raw_atomic64_try_cmpxchg_release) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic64_try_cmpxchg_relaxed(atomic64_t *v, s64 *old, s64 new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 *old`: pointer to s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_try_cmpxchg_relaxed()`](#c-raw_atomic64_try_cmpxchg_relaxed) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic64_sub_and_test(s64 i, atomic64_t *v)
```

atomic subtract and test if zero with full ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_sub_and_test()`](#c-raw_atomic64_sub_and_test) there.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool atomic64_dec_and_test(atomic64_t *v)
```

atomic decrement and test if zero with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_dec_and_test()`](#c-raw_atomic64_dec_and_test) there.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool atomic64_inc_and_test(atomic64_t *v)
```

atomic increment and test if zero with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_inc_and_test()`](#c-raw_atomic64_inc_and_test) there.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool atomic64_add_negative(s64 i, atomic64_t *v)
```

atomic add and test if negative with full ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_add_negative()`](#c-raw_atomic64_add_negative) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool atomic64_add_negative_acquire(s64 i, atomic64_t *v)
```

atomic add and test if negative with acquire ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_add_negative_acquire()`](#c-raw_atomic64_add_negative_acquire) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool atomic64_add_negative_release(s64 i, atomic64_t *v)
```

atomic add and test if negative with release ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_add_negative_release()`](#c-raw_atomic64_add_negative_release) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool atomic64_add_negative_relaxed(s64 i, atomic64_t *v)
```

atomic add and test if negative with relaxed ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic64_add_negative_relaxed()`](#c-raw_atomic64_add_negative_relaxed) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
s64 atomic64_fetch_add_unless(atomic64_t *v, s64 a, s64 u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 a`: s64 value to add
- `s64 u`: s64 value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_fetch_add_unless()`](#c-raw_atomic64_fetch_add_unless) there.

**Return**

The original value of **v**.

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

```c
bool atomic64_add_unless(atomic64_t *v, s64 a, s64 u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 a`: s64 value to add
- `s64 u`: s64 value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_add_unless()`](#c-raw_atomic64_add_unless) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool atomic64_inc_not_zero(atomic64_t *v)
```

atomic increment unless zero with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

If (**v** != 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_inc_not_zero()`](#c-raw_atomic64_inc_not_zero) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool atomic64_inc_unless_negative(atomic64_t *v)
```

atomic increment unless negative with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

If (**v** >= 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_inc_unless_negative()`](#c-raw_atomic64_inc_unless_negative) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool atomic64_dec_unless_positive(atomic64_t *v)
```

atomic decrement unless positive with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

If (**v** \<= 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_dec_unless_positive()`](#c-raw_atomic64_dec_unless_positive) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
s64 atomic64_dec_if_positive(atomic64_t *v)
```

atomic decrement if positive with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

If (**v** > 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic64_dec_if_positive()`](#c-raw_atomic64_dec_if_positive) there.

**Return**

The old value of (**v** - 1), regardless of whether **v** was updated.

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

```c
long atomic_long_read(const atomic_long_t *v)
```

atomic load with relaxed ordering

**Parameters**

- `const atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically loads the value of **v** with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_read()`](#c-raw_atomic_long_read) there.

**Return**

The value loaded from **v**.

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

```c
long atomic_long_read_acquire(const atomic_long_t *v)
```

atomic load with acquire ordering

**Parameters**

- `const atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically loads the value of **v** with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_read_acquire()`](#c-raw_atomic_long_read_acquire) there.

**Return**

The value loaded from **v**.

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

```c
void atomic_long_set(atomic_long_t *v, long i)
```

atomic set with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long i`: long value to assign

**Description**

Atomically sets **v** to **i** with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_set()`](#c-raw_atomic_long_set) there.

**Return**

Nothing.

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

```c
void atomic_long_set_release(atomic_long_t *v, long i)
```

atomic set with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long i`: long value to assign

**Description**

Atomically sets **v** to **i** with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_set_release()`](#c-raw_atomic_long_set_release) there.

**Return**

Nothing.

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

```c
void atomic_long_add(long i, atomic_long_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_add()`](#c-raw_atomic_long_add) there.

**Return**

Nothing.

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

```c
long atomic_long_add_return(long i, atomic_long_t *v)
```

atomic add with full ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_add_return()`](#c-raw_atomic_long_add_return) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_add_return_acquire(long i, atomic_long_t *v)
```

atomic add with acquire ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_add_return_acquire()`](#c-raw_atomic_long_add_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_add_return_release(long i, atomic_long_t *v)
```

atomic add with release ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_add_return_release()`](#c-raw_atomic_long_add_return_release) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_add_return_relaxed(long i, atomic_long_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_add_return_relaxed()`](#c-raw_atomic_long_add_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_fetch_add(long i, atomic_long_t *v)
```

atomic add with full ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_add()`](#c-raw_atomic_long_fetch_add) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_add_acquire(long i, atomic_long_t *v)
```

atomic add with acquire ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_add_acquire()`](#c-raw_atomic_long_fetch_add_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_add_release(long i, atomic_long_t *v)
```

atomic add with release ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_add_release()`](#c-raw_atomic_long_fetch_add_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_add_relaxed(long i, atomic_long_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_add_relaxed()`](#c-raw_atomic_long_fetch_add_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_long_sub(long i, atomic_long_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_sub()`](#c-raw_atomic_long_sub) there.

**Return**

Nothing.

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

```c
long atomic_long_sub_return(long i, atomic_long_t *v)
```

atomic subtract with full ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_sub_return()`](#c-raw_atomic_long_sub_return) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_sub_return_acquire(long i, atomic_long_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_sub_return_acquire()`](#c-raw_atomic_long_sub_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_sub_return_release(long i, atomic_long_t *v)
```

atomic subtract with release ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_sub_return_release()`](#c-raw_atomic_long_sub_return_release) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_sub_return_relaxed(long i, atomic_long_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_sub_return_relaxed()`](#c-raw_atomic_long_sub_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_fetch_sub(long i, atomic_long_t *v)
```

atomic subtract with full ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_sub()`](#c-raw_atomic_long_fetch_sub) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_sub_acquire(long i, atomic_long_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_sub_acquire()`](#c-raw_atomic_long_fetch_sub_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_sub_release(long i, atomic_long_t *v)
```

atomic subtract with release ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_sub_release()`](#c-raw_atomic_long_fetch_sub_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_sub_relaxed(long i, atomic_long_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_sub_relaxed()`](#c-raw_atomic_long_fetch_sub_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_long_inc(atomic_long_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_inc()`](#c-raw_atomic_long_inc) there.

**Return**

Nothing.

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

```c
long atomic_long_inc_return(atomic_long_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_inc_return()`](#c-raw_atomic_long_inc_return) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_inc_return_acquire(atomic_long_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_inc_return_acquire()`](#c-raw_atomic_long_inc_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_inc_return_release(atomic_long_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_inc_return_release()`](#c-raw_atomic_long_inc_return_release) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_inc_return_relaxed(atomic_long_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_inc_return_relaxed()`](#c-raw_atomic_long_inc_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_fetch_inc(atomic_long_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_inc()`](#c-raw_atomic_long_fetch_inc) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_inc_acquire(atomic_long_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_inc_acquire()`](#c-raw_atomic_long_fetch_inc_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_inc_release(atomic_long_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_inc_release()`](#c-raw_atomic_long_fetch_inc_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_inc_relaxed(atomic_long_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_inc_relaxed()`](#c-raw_atomic_long_fetch_inc_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_long_dec(atomic_long_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_dec()`](#c-raw_atomic_long_dec) there.

**Return**

Nothing.

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

```c
long atomic_long_dec_return(atomic_long_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_dec_return()`](#c-raw_atomic_long_dec_return) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_dec_return_acquire(atomic_long_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_dec_return_acquire()`](#c-raw_atomic_long_dec_return_acquire) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_dec_return_release(atomic_long_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_dec_return_release()`](#c-raw_atomic_long_dec_return_release) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_dec_return_relaxed(atomic_long_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_dec_return_relaxed()`](#c-raw_atomic_long_dec_return_relaxed) there.

**Return**

The updated value of **v**.

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

```c
long atomic_long_fetch_dec(atomic_long_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_dec()`](#c-raw_atomic_long_fetch_dec) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_dec_acquire(atomic_long_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_dec_acquire()`](#c-raw_atomic_long_fetch_dec_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_dec_release(atomic_long_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_dec_release()`](#c-raw_atomic_long_fetch_dec_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_dec_relaxed(atomic_long_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_dec_relaxed()`](#c-raw_atomic_long_fetch_dec_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_long_and(long i, atomic_long_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_and()`](#c-raw_atomic_long_and) there.

**Return**

Nothing.

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

```c
long atomic_long_fetch_and(long i, atomic_long_t *v)
```

atomic bitwise AND with full ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_and()`](#c-raw_atomic_long_fetch_and) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_and_acquire(long i, atomic_long_t *v)
```

atomic bitwise AND with acquire ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_and_acquire()`](#c-raw_atomic_long_fetch_and_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_and_release(long i, atomic_long_t *v)
```

atomic bitwise AND with release ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_and_release()`](#c-raw_atomic_long_fetch_and_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_and_relaxed(long i, atomic_long_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_and_relaxed()`](#c-raw_atomic_long_fetch_and_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_long_andnot(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_andnot()`](#c-raw_atomic_long_andnot) there.

**Return**

Nothing.

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

```c
long atomic_long_fetch_andnot(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with full ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_andnot()`](#c-raw_atomic_long_fetch_andnot) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_andnot_acquire(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with acquire ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_andnot_acquire()`](#c-raw_atomic_long_fetch_andnot_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_andnot_release(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with release ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_andnot_release()`](#c-raw_atomic_long_fetch_andnot_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_andnot_relaxed(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_andnot_relaxed()`](#c-raw_atomic_long_fetch_andnot_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_long_or(long i, atomic_long_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_or()`](#c-raw_atomic_long_or) there.

**Return**

Nothing.

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

```c
long atomic_long_fetch_or(long i, atomic_long_t *v)
```

atomic bitwise OR with full ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_or()`](#c-raw_atomic_long_fetch_or) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_or_acquire(long i, atomic_long_t *v)
```

atomic bitwise OR with acquire ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_or_acquire()`](#c-raw_atomic_long_fetch_or_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_or_release(long i, atomic_long_t *v)
```

atomic bitwise OR with release ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_or_release()`](#c-raw_atomic_long_fetch_or_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_or_relaxed(long i, atomic_long_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_or_relaxed()`](#c-raw_atomic_long_fetch_or_relaxed) there.

**Return**

The original value of **v**.

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

```c
void atomic_long_xor(long i, atomic_long_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_xor()`](#c-raw_atomic_long_xor) there.

**Return**

Nothing.

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

```c
long atomic_long_fetch_xor(long i, atomic_long_t *v)
```

atomic bitwise XOR with full ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_xor()`](#c-raw_atomic_long_fetch_xor) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_xor_acquire(long i, atomic_long_t *v)
```

atomic bitwise XOR with acquire ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_xor_acquire()`](#c-raw_atomic_long_fetch_xor_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_xor_release(long i, atomic_long_t *v)
```

atomic bitwise XOR with release ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_xor_release()`](#c-raw_atomic_long_fetch_xor_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_fetch_xor_relaxed(long i, atomic_long_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_xor_relaxed()`](#c-raw_atomic_long_fetch_xor_relaxed) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_xchg(atomic_long_t *v, long new)
```

atomic exchange with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long new`: long value to assign

**Description**

Atomically updates **v** to **new** with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_xchg()`](#c-raw_atomic_long_xchg) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_xchg_acquire(atomic_long_t *v, long new)
```

atomic exchange with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long new`: long value to assign

**Description**

Atomically updates **v** to **new** with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_xchg_acquire()`](#c-raw_atomic_long_xchg_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_xchg_release(atomic_long_t *v, long new)
```

atomic exchange with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long new`: long value to assign

**Description**

Atomically updates **v** to **new** with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_xchg_release()`](#c-raw_atomic_long_xchg_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_xchg_relaxed(atomic_long_t *v, long new)
```

atomic exchange with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long new`: long value to assign

**Description**

Atomically updates **v** to **new** with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_xchg_relaxed()`](#c-raw_atomic_long_xchg_relaxed) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_cmpxchg(atomic_long_t *v, long old, long new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long old`: long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_cmpxchg()`](#c-raw_atomic_long_cmpxchg) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_cmpxchg_acquire(atomic_long_t *v, long old, long new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long old`: long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_cmpxchg_acquire()`](#c-raw_atomic_long_cmpxchg_acquire) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_cmpxchg_release(atomic_long_t *v, long old, long new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long old`: long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_cmpxchg_release()`](#c-raw_atomic_long_cmpxchg_release) there.

**Return**

The original value of **v**.

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

```c
long atomic_long_cmpxchg_relaxed(atomic_long_t *v, long old, long new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long old`: long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_cmpxchg_relaxed()`](#c-raw_atomic_long_cmpxchg_relaxed) there.

**Return**

The original value of **v**.

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

```c
bool atomic_long_try_cmpxchg(atomic_long_t *v, long *old, long new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long *old`: pointer to long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_try_cmpxchg()`](#c-raw_atomic_long_try_cmpxchg) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic_long_try_cmpxchg_acquire(atomic_long_t *v, long *old, long new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long *old`: pointer to long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_try_cmpxchg_acquire()`](#c-raw_atomic_long_try_cmpxchg_acquire) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic_long_try_cmpxchg_release(atomic_long_t *v, long *old, long new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long *old`: pointer to long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_try_cmpxchg_release()`](#c-raw_atomic_long_try_cmpxchg_release) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic_long_try_cmpxchg_relaxed(atomic_long_t *v, long *old, long new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long *old`: pointer to long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_try_cmpxchg_relaxed()`](#c-raw_atomic_long_try_cmpxchg_relaxed) there.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool atomic_long_sub_and_test(long i, atomic_long_t *v)
```

atomic subtract and test if zero with full ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_sub_and_test()`](#c-raw_atomic_long_sub_and_test) there.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool atomic_long_dec_and_test(atomic_long_t *v)
```

atomic decrement and test if zero with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_dec_and_test()`](#c-raw_atomic_long_dec_and_test) there.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool atomic_long_inc_and_test(atomic_long_t *v)
```

atomic increment and test if zero with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_inc_and_test()`](#c-raw_atomic_long_inc_and_test) there.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool atomic_long_add_negative(long i, atomic_long_t *v)
```

atomic add and test if negative with full ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_add_negative()`](#c-raw_atomic_long_add_negative) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool atomic_long_add_negative_acquire(long i, atomic_long_t *v)
```

atomic add and test if negative with acquire ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_add_negative_acquire()`](#c-raw_atomic_long_add_negative_acquire) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool atomic_long_add_negative_release(long i, atomic_long_t *v)
```

atomic add and test if negative with release ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_add_negative_release()`](#c-raw_atomic_long_add_negative_release) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool atomic_long_add_negative_relaxed(long i, atomic_long_t *v)
```

atomic add and test if negative with relaxed ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Unsafe to use in noinstr code; use [`raw_atomic_long_add_negative_relaxed()`](#c-raw_atomic_long_add_negative_relaxed) there.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
long atomic_long_fetch_add_unless(atomic_long_t *v, long a, long u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long a`: long value to add
- `long u`: long value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_fetch_add_unless()`](#c-raw_atomic_long_fetch_add_unless) there.

**Return**

The original value of **v**.

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

```c
bool atomic_long_add_unless(atomic_long_t *v, long a, long u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long a`: long value to add
- `long u`: long value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_add_unless()`](#c-raw_atomic_long_add_unless) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool atomic_long_inc_not_zero(atomic_long_t *v)
```

atomic increment unless zero with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

If (**v** != 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_inc_not_zero()`](#c-raw_atomic_long_inc_not_zero) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool atomic_long_inc_unless_negative(atomic_long_t *v)
```

atomic increment unless negative with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

If (**v** >= 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_inc_unless_negative()`](#c-raw_atomic_long_inc_unless_negative) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool atomic_long_dec_unless_positive(atomic_long_t *v)
```

atomic decrement unless positive with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

If (**v** \<= 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_dec_unless_positive()`](#c-raw_atomic_long_dec_unless_positive) there.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
long atomic_long_dec_if_positive(atomic_long_t *v)
```

atomic decrement if positive with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

If (**v** > 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Unsafe to use in noinstr code; use [`raw_atomic_long_dec_if_positive()`](#c-raw_atomic_long_dec_if_positive) there.

**Return**

The old value of (**v** - 1), regardless of whether **v** was updated.



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

```c
int raw_atomic_read(const atomic_t *v)
```

atomic load with relaxed ordering

**Parameters**

- `const atomic_t *v`: pointer to atomic_t

**Description**

Atomically loads the value of **v** with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_read()`](#c-atomic_read) elsewhere.

**Return**

The value loaded from **v**.

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

```c
int raw_atomic_read_acquire(const atomic_t *v)
```

atomic load with acquire ordering

**Parameters**

- `const atomic_t *v`: pointer to atomic_t

**Description**

Atomically loads the value of **v** with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_read_acquire()`](#c-atomic_read_acquire) elsewhere.

**Return**

The value loaded from **v**.

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

```c
void raw_atomic_set(atomic_t *v, int i)
```

atomic set with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int i`: int value to assign

**Description**

Atomically sets **v** to **i** with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_set()`](#c-atomic_set) elsewhere.

**Return**

Nothing.

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

```c
void raw_atomic_set_release(atomic_t *v, int i)
```

atomic set with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int i`: int value to assign

**Description**

Atomically sets **v** to **i** with release ordering.

Safe to use in noinstr code; prefer [`atomic_set_release()`](#c-atomic_set_release) elsewhere.

**Return**

Nothing.

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

```c
void raw_atomic_add(int i, atomic_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_add()`](#c-atomic_add) elsewhere.

**Return**

Nothing.

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

```c
int raw_atomic_add_return(int i, atomic_t *v)
```

atomic add with full ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_add_return()`](#c-atomic_add_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_add_return_acquire(int i, atomic_t *v)
```

atomic add with acquire ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_add_return_acquire()`](#c-atomic_add_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_add_return_release(int i, atomic_t *v)
```

atomic add with release ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_add_return_release()`](#c-atomic_add_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_add_return_relaxed(int i, atomic_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_add_return_relaxed()`](#c-atomic_add_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_fetch_add(int i, atomic_t *v)
```

atomic add with full ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_add()`](#c-atomic_fetch_add) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_add_acquire(int i, atomic_t *v)
```

atomic add with acquire ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_add_acquire()`](#c-atomic_fetch_add_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_add_release(int i, atomic_t *v)
```

atomic add with release ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_add_release()`](#c-atomic_fetch_add_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_add_relaxed(int i, atomic_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_add_relaxed()`](#c-atomic_fetch_add_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_sub(int i, atomic_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_sub()`](#c-atomic_sub) elsewhere.

**Return**

Nothing.

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

```c
int raw_atomic_sub_return(int i, atomic_t *v)
```

atomic subtract with full ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_sub_return()`](#c-atomic_sub_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_sub_return_acquire(int i, atomic_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_sub_return_acquire()`](#c-atomic_sub_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_sub_return_release(int i, atomic_t *v)
```

atomic subtract with release ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_sub_return_release()`](#c-atomic_sub_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_sub_return_relaxed(int i, atomic_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_sub_return_relaxed()`](#c-atomic_sub_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_fetch_sub(int i, atomic_t *v)
```

atomic subtract with full ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_sub()`](#c-atomic_fetch_sub) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_sub_acquire(int i, atomic_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_sub_acquire()`](#c-atomic_fetch_sub_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_sub_release(int i, atomic_t *v)
```

atomic subtract with release ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_sub_release()`](#c-atomic_fetch_sub_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_sub_relaxed(int i, atomic_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_sub_relaxed()`](#c-atomic_fetch_sub_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_inc(atomic_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_inc()`](#c-atomic_inc) elsewhere.

**Return**

Nothing.

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

```c
int raw_atomic_inc_return(atomic_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_inc_return()`](#c-atomic_inc_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_inc_return_acquire(atomic_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_inc_return_acquire()`](#c-atomic_inc_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_inc_return_release(atomic_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic_inc_return_release()`](#c-atomic_inc_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_inc_return_relaxed(atomic_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_inc_return_relaxed()`](#c-atomic_inc_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_fetch_inc(atomic_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_inc()`](#c-atomic_fetch_inc) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_inc_acquire(atomic_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_inc_acquire()`](#c-atomic_fetch_inc_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_inc_release(atomic_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_inc_release()`](#c-atomic_fetch_inc_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_inc_relaxed(atomic_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_inc_relaxed()`](#c-atomic_fetch_inc_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_dec(atomic_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_dec()`](#c-atomic_dec) elsewhere.

**Return**

Nothing.

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

```c
int raw_atomic_dec_return(atomic_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_dec_return()`](#c-atomic_dec_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_dec_return_acquire(atomic_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_dec_return_acquire()`](#c-atomic_dec_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_dec_return_release(atomic_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic_dec_return_release()`](#c-atomic_dec_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_dec_return_relaxed(atomic_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_dec_return_relaxed()`](#c-atomic_dec_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
int raw_atomic_fetch_dec(atomic_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_dec()`](#c-atomic_fetch_dec) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_dec_acquire(atomic_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_dec_acquire()`](#c-atomic_fetch_dec_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_dec_release(atomic_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_dec_release()`](#c-atomic_fetch_dec_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_dec_relaxed(atomic_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_dec_relaxed()`](#c-atomic_fetch_dec_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_and(int i, atomic_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_and()`](#c-atomic_and) elsewhere.

**Return**

Nothing.

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

```c
int raw_atomic_fetch_and(int i, atomic_t *v)
```

atomic bitwise AND with full ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_and()`](#c-atomic_fetch_and) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_and_acquire(int i, atomic_t *v)
```

atomic bitwise AND with acquire ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_and_acquire()`](#c-atomic_fetch_and_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_and_release(int i, atomic_t *v)
```

atomic bitwise AND with release ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_and_release()`](#c-atomic_fetch_and_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_and_relaxed(int i, atomic_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_and_relaxed()`](#c-atomic_fetch_and_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_andnot(int i, atomic_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_andnot()`](#c-atomic_andnot) elsewhere.

**Return**

Nothing.

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

```c
int raw_atomic_fetch_andnot(int i, atomic_t *v)
```

atomic bitwise AND NOT with full ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_andnot()`](#c-atomic_fetch_andnot) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_andnot_acquire(int i, atomic_t *v)
```

atomic bitwise AND NOT with acquire ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_andnot_acquire()`](#c-atomic_fetch_andnot_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_andnot_release(int i, atomic_t *v)
```

atomic bitwise AND NOT with release ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_andnot_release()`](#c-atomic_fetch_andnot_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_andnot_relaxed(int i, atomic_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_andnot_relaxed()`](#c-atomic_fetch_andnot_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_or(int i, atomic_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_or()`](#c-atomic_or) elsewhere.

**Return**

Nothing.

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

```c
int raw_atomic_fetch_or(int i, atomic_t *v)
```

atomic bitwise OR with full ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_or()`](#c-atomic_fetch_or) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_or_acquire(int i, atomic_t *v)
```

atomic bitwise OR with acquire ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_or_acquire()`](#c-atomic_fetch_or_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_or_release(int i, atomic_t *v)
```

atomic bitwise OR with release ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_or_release()`](#c-atomic_fetch_or_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_or_relaxed(int i, atomic_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_or_relaxed()`](#c-atomic_fetch_or_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_xor(int i, atomic_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_xor()`](#c-atomic_xor) elsewhere.

**Return**

Nothing.

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

```c
int raw_atomic_fetch_xor(int i, atomic_t *v)
```

atomic bitwise XOR with full ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_xor()`](#c-atomic_fetch_xor) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_xor_acquire(int i, atomic_t *v)
```

atomic bitwise XOR with acquire ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_xor_acquire()`](#c-atomic_fetch_xor_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_xor_release(int i, atomic_t *v)
```

atomic bitwise XOR with release ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_xor_release()`](#c-atomic_fetch_xor_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_fetch_xor_relaxed(int i, atomic_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `int i`: int value
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_fetch_xor_relaxed()`](#c-atomic_fetch_xor_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_xchg(atomic_t *v, int new)
```

atomic exchange with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int new`: int value to assign

**Description**

Atomically updates **v** to **new** with full ordering.

Safe to use in noinstr code; prefer [`atomic_xchg()`](#c-atomic_xchg) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_xchg_acquire(atomic_t *v, int new)
```

atomic exchange with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int new`: int value to assign

**Description**

Atomically updates **v** to **new** with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_xchg_acquire()`](#c-atomic_xchg_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_xchg_release(atomic_t *v, int new)
```

atomic exchange with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int new`: int value to assign

**Description**

Atomically updates **v** to **new** with release ordering.

Safe to use in noinstr code; prefer [`atomic_xchg_release()`](#c-atomic_xchg_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_xchg_relaxed(atomic_t *v, int new)
```

atomic exchange with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int new`: int value to assign

**Description**

Atomically updates **v** to **new** with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_xchg_relaxed()`](#c-atomic_xchg_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_cmpxchg(atomic_t *v, int old, int new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int old`: int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_cmpxchg()`](#c-atomic_cmpxchg) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_cmpxchg_acquire(atomic_t *v, int old, int new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int old`: int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_cmpxchg_acquire()`](#c-atomic_cmpxchg_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_cmpxchg_release(atomic_t *v, int old, int new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int old`: int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_cmpxchg_release()`](#c-atomic_cmpxchg_release) elsewhere.

**Return**

The original value of **v**.

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

```c
int raw_atomic_cmpxchg_relaxed(atomic_t *v, int old, int new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int old`: int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_cmpxchg_relaxed()`](#c-atomic_cmpxchg_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
bool raw_atomic_try_cmpxchg(atomic_t *v, int *old, int new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int *old`: pointer to int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_try_cmpxchg()`](#c-atomic_try_cmpxchg) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic_try_cmpxchg_acquire(atomic_t *v, int *old, int new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int *old`: pointer to int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_try_cmpxchg_acquire()`](#c-atomic_try_cmpxchg_acquire) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic_try_cmpxchg_release(atomic_t *v, int *old, int new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int *old`: pointer to int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_try_cmpxchg_release()`](#c-atomic_try_cmpxchg_release) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic_try_cmpxchg_relaxed(atomic_t *v, int *old, int new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int *old`: pointer to int value to compare with
- `int new`: int value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_try_cmpxchg_relaxed()`](#c-atomic_try_cmpxchg_relaxed) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic_sub_and_test(int i, atomic_t *v)
```

atomic subtract and test if zero with full ordering

**Parameters**

- `int i`: int value to subtract
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_sub_and_test()`](#c-atomic_sub_and_test) elsewhere.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool raw_atomic_dec_and_test(atomic_t *v)
```

atomic decrement and test if zero with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_dec_and_test()`](#c-atomic_dec_and_test) elsewhere.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool raw_atomic_inc_and_test(atomic_t *v)
```

atomic increment and test if zero with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_inc_and_test()`](#c-atomic_inc_and_test) elsewhere.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool raw_atomic_add_negative(int i, atomic_t *v)
```

atomic add and test if negative with full ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_add_negative()`](#c-atomic_add_negative) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool raw_atomic_add_negative_acquire(int i, atomic_t *v)
```

atomic add and test if negative with acquire ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_add_negative_acquire()`](#c-atomic_add_negative_acquire) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool raw_atomic_add_negative_release(int i, atomic_t *v)
```

atomic add and test if negative with release ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_add_negative_release()`](#c-atomic_add_negative_release) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool raw_atomic_add_negative_relaxed(int i, atomic_t *v)
```

atomic add and test if negative with relaxed ordering

**Parameters**

- `int i`: int value to add
- `atomic_t *v`: pointer to atomic_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_add_negative_relaxed()`](#c-atomic_add_negative_relaxed) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
int raw_atomic_fetch_add_unless(atomic_t *v, int a, int u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int a`: int value to add
- `int u`: int value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_fetch_add_unless()`](#c-atomic_fetch_add_unless) elsewhere.

**Return**

The original value of **v**.

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

```c
bool raw_atomic_add_unless(atomic_t *v, int a, int u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t
- `int a`: int value to add
- `int u`: int value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_add_unless()`](#c-atomic_add_unless) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool raw_atomic_inc_not_zero(atomic_t *v)
```

atomic increment unless zero with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

If (**v** != 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_inc_not_zero()`](#c-atomic_inc_not_zero) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool raw_atomic_inc_unless_negative(atomic_t *v)
```

atomic increment unless negative with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

If (**v** >= 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_inc_unless_negative()`](#c-atomic_inc_unless_negative) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool raw_atomic_dec_unless_positive(atomic_t *v)
```

atomic decrement unless positive with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

If (**v** \<= 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_dec_unless_positive()`](#c-atomic_dec_unless_positive) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
int raw_atomic_dec_if_positive(atomic_t *v)
```

atomic decrement if positive with full ordering

**Parameters**

- `atomic_t *v`: pointer to atomic_t

**Description**

If (**v** > 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_dec_if_positive()`](#c-atomic_dec_if_positive) elsewhere.

**Return**

The old value of (**v** - 1), regardless of whether **v** was updated.

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

```c
s64 raw_atomic64_read(const atomic64_t *v)
```

atomic load with relaxed ordering

**Parameters**

- `const atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically loads the value of **v** with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_read()`](#c-atomic64_read) elsewhere.

**Return**

The value loaded from **v**.

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

```c
s64 raw_atomic64_read_acquire(const atomic64_t *v)
```

atomic load with acquire ordering

**Parameters**

- `const atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically loads the value of **v** with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_read_acquire()`](#c-atomic64_read_acquire) elsewhere.

**Return**

The value loaded from **v**.

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

```c
void raw_atomic64_set(atomic64_t *v, s64 i)
```

atomic set with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 i`: s64 value to assign

**Description**

Atomically sets **v** to **i** with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_set()`](#c-atomic64_set) elsewhere.

**Return**

Nothing.

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

```c
void raw_atomic64_set_release(atomic64_t *v, s64 i)
```

atomic set with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 i`: s64 value to assign

**Description**

Atomically sets **v** to **i** with release ordering.

Safe to use in noinstr code; prefer [`atomic64_set_release()`](#c-atomic64_set_release) elsewhere.

**Return**

Nothing.

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

```c
void raw_atomic64_add(s64 i, atomic64_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_add()`](#c-atomic64_add) elsewhere.

**Return**

Nothing.

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

```c
s64 raw_atomic64_add_return(s64 i, atomic64_t *v)
```

atomic add with full ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_add_return()`](#c-atomic64_add_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_add_return_acquire(s64 i, atomic64_t *v)
```

atomic add with acquire ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_add_return_acquire()`](#c-atomic64_add_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_add_return_release(s64 i, atomic64_t *v)
```

atomic add with release ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_add_return_release()`](#c-atomic64_add_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_add_return_relaxed(s64 i, atomic64_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_add_return_relaxed()`](#c-atomic64_add_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_fetch_add(s64 i, atomic64_t *v)
```

atomic add with full ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_add()`](#c-atomic64_fetch_add) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_add_acquire(s64 i, atomic64_t *v)
```

atomic add with acquire ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_add_acquire()`](#c-atomic64_fetch_add_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_add_release(s64 i, atomic64_t *v)
```

atomic add with release ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_add_release()`](#c-atomic64_fetch_add_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_add_relaxed(s64 i, atomic64_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_add_relaxed()`](#c-atomic64_fetch_add_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic64_sub(s64 i, atomic64_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_sub()`](#c-atomic64_sub) elsewhere.

**Return**

Nothing.

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

```c
s64 raw_atomic64_sub_return(s64 i, atomic64_t *v)
```

atomic subtract with full ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_sub_return()`](#c-atomic64_sub_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_sub_return_acquire(s64 i, atomic64_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_sub_return_acquire()`](#c-atomic64_sub_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_sub_return_release(s64 i, atomic64_t *v)
```

atomic subtract with release ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_sub_return_release()`](#c-atomic64_sub_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_sub_return_relaxed(s64 i, atomic64_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_sub_return_relaxed()`](#c-atomic64_sub_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_fetch_sub(s64 i, atomic64_t *v)
```

atomic subtract with full ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_sub()`](#c-atomic64_fetch_sub) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_sub_acquire(s64 i, atomic64_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_sub_acquire()`](#c-atomic64_fetch_sub_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_sub_release(s64 i, atomic64_t *v)
```

atomic subtract with release ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_sub_release()`](#c-atomic64_fetch_sub_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_sub_relaxed(s64 i, atomic64_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_sub_relaxed()`](#c-atomic64_fetch_sub_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic64_inc(atomic64_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_inc()`](#c-atomic64_inc) elsewhere.

**Return**

Nothing.

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

```c
s64 raw_atomic64_inc_return(atomic64_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_inc_return()`](#c-atomic64_inc_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_inc_return_acquire(atomic64_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_inc_return_acquire()`](#c-atomic64_inc_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_inc_return_release(atomic64_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_inc_return_release()`](#c-atomic64_inc_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_inc_return_relaxed(atomic64_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_inc_return_relaxed()`](#c-atomic64_inc_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_fetch_inc(atomic64_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_inc()`](#c-atomic64_fetch_inc) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_inc_acquire(atomic64_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_inc_acquire()`](#c-atomic64_fetch_inc_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_inc_release(atomic64_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_inc_release()`](#c-atomic64_fetch_inc_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_inc_relaxed(atomic64_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_inc_relaxed()`](#c-atomic64_fetch_inc_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic64_dec(atomic64_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_dec()`](#c-atomic64_dec) elsewhere.

**Return**

Nothing.

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

```c
s64 raw_atomic64_dec_return(atomic64_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_dec_return()`](#c-atomic64_dec_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_dec_return_acquire(atomic64_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_dec_return_acquire()`](#c-atomic64_dec_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_dec_return_release(atomic64_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_dec_return_release()`](#c-atomic64_dec_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_dec_return_relaxed(atomic64_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_dec_return_relaxed()`](#c-atomic64_dec_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
s64 raw_atomic64_fetch_dec(atomic64_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_dec()`](#c-atomic64_fetch_dec) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_dec_acquire(atomic64_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_dec_acquire()`](#c-atomic64_fetch_dec_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_dec_release(atomic64_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_dec_release()`](#c-atomic64_fetch_dec_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_dec_relaxed(atomic64_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_dec_relaxed()`](#c-atomic64_fetch_dec_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic64_and(s64 i, atomic64_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_and()`](#c-atomic64_and) elsewhere.

**Return**

Nothing.

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

```c
s64 raw_atomic64_fetch_and(s64 i, atomic64_t *v)
```

atomic bitwise AND with full ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_and()`](#c-atomic64_fetch_and) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_and_acquire(s64 i, atomic64_t *v)
```

atomic bitwise AND with acquire ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_and_acquire()`](#c-atomic64_fetch_and_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_and_release(s64 i, atomic64_t *v)
```

atomic bitwise AND with release ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_and_release()`](#c-atomic64_fetch_and_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_and_relaxed(s64 i, atomic64_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_and_relaxed()`](#c-atomic64_fetch_and_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic64_andnot(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_andnot()`](#c-atomic64_andnot) elsewhere.

**Return**

Nothing.

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

```c
s64 raw_atomic64_fetch_andnot(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with full ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_andnot()`](#c-atomic64_fetch_andnot) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_andnot_acquire(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with acquire ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_andnot_acquire()`](#c-atomic64_fetch_andnot_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_andnot_release(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with release ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_andnot_release()`](#c-atomic64_fetch_andnot_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_andnot_relaxed(s64 i, atomic64_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_andnot_relaxed()`](#c-atomic64_fetch_andnot_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic64_or(s64 i, atomic64_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_or()`](#c-atomic64_or) elsewhere.

**Return**

Nothing.

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

```c
s64 raw_atomic64_fetch_or(s64 i, atomic64_t *v)
```

atomic bitwise OR with full ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_or()`](#c-atomic64_fetch_or) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_or_acquire(s64 i, atomic64_t *v)
```

atomic bitwise OR with acquire ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_or_acquire()`](#c-atomic64_fetch_or_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_or_release(s64 i, atomic64_t *v)
```

atomic bitwise OR with release ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_or_release()`](#c-atomic64_fetch_or_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_or_relaxed(s64 i, atomic64_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_or_relaxed()`](#c-atomic64_fetch_or_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic64_xor(s64 i, atomic64_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_xor()`](#c-atomic64_xor) elsewhere.

**Return**

Nothing.

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

```c
s64 raw_atomic64_fetch_xor(s64 i, atomic64_t *v)
```

atomic bitwise XOR with full ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_xor()`](#c-atomic64_fetch_xor) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_xor_acquire(s64 i, atomic64_t *v)
```

atomic bitwise XOR with acquire ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_xor_acquire()`](#c-atomic64_fetch_xor_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_xor_release(s64 i, atomic64_t *v)
```

atomic bitwise XOR with release ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_xor_release()`](#c-atomic64_fetch_xor_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_fetch_xor_relaxed(s64 i, atomic64_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `s64 i`: s64 value
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_fetch_xor_relaxed()`](#c-atomic64_fetch_xor_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_xchg(atomic64_t *v, s64 new)
```

atomic exchange with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 new`: s64 value to assign

**Description**

Atomically updates **v** to **new** with full ordering.

Safe to use in noinstr code; prefer [`atomic64_xchg()`](#c-atomic64_xchg) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_xchg_acquire(atomic64_t *v, s64 new)
```

atomic exchange with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 new`: s64 value to assign

**Description**

Atomically updates **v** to **new** with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_xchg_acquire()`](#c-atomic64_xchg_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_xchg_release(atomic64_t *v, s64 new)
```

atomic exchange with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 new`: s64 value to assign

**Description**

Atomically updates **v** to **new** with release ordering.

Safe to use in noinstr code; prefer [`atomic64_xchg_release()`](#c-atomic64_xchg_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_xchg_relaxed(atomic64_t *v, s64 new)
```

atomic exchange with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 new`: s64 value to assign

**Description**

Atomically updates **v** to **new** with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_xchg_relaxed()`](#c-atomic64_xchg_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_cmpxchg(atomic64_t *v, s64 old, s64 new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 old`: s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_cmpxchg()`](#c-atomic64_cmpxchg) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_cmpxchg_acquire(atomic64_t *v, s64 old, s64 new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 old`: s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_cmpxchg_acquire()`](#c-atomic64_cmpxchg_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_cmpxchg_release(atomic64_t *v, s64 old, s64 new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 old`: s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_cmpxchg_release()`](#c-atomic64_cmpxchg_release) elsewhere.

**Return**

The original value of **v**.

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

```c
s64 raw_atomic64_cmpxchg_relaxed(atomic64_t *v, s64 old, s64 new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 old`: s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_cmpxchg_relaxed()`](#c-atomic64_cmpxchg_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
bool raw_atomic64_try_cmpxchg(atomic64_t *v, s64 *old, s64 new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 *old`: pointer to s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_try_cmpxchg()`](#c-atomic64_try_cmpxchg) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic64_try_cmpxchg_acquire(atomic64_t *v, s64 *old, s64 new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 *old`: pointer to s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_try_cmpxchg_acquire()`](#c-atomic64_try_cmpxchg_acquire) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic64_try_cmpxchg_release(atomic64_t *v, s64 *old, s64 new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 *old`: pointer to s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_try_cmpxchg_release()`](#c-atomic64_try_cmpxchg_release) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic64_try_cmpxchg_relaxed(atomic64_t *v, s64 *old, s64 new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 *old`: pointer to s64 value to compare with
- `s64 new`: s64 value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_try_cmpxchg_relaxed()`](#c-atomic64_try_cmpxchg_relaxed) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic64_sub_and_test(s64 i, atomic64_t *v)
```

atomic subtract and test if zero with full ordering

**Parameters**

- `s64 i`: s64 value to subtract
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_sub_and_test()`](#c-atomic64_sub_and_test) elsewhere.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool raw_atomic64_dec_and_test(atomic64_t *v)
```

atomic decrement and test if zero with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_dec_and_test()`](#c-atomic64_dec_and_test) elsewhere.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool raw_atomic64_inc_and_test(atomic64_t *v)
```

atomic increment and test if zero with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_inc_and_test()`](#c-atomic64_inc_and_test) elsewhere.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool raw_atomic64_add_negative(s64 i, atomic64_t *v)
```

atomic add and test if negative with full ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic64_add_negative()`](#c-atomic64_add_negative) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool raw_atomic64_add_negative_acquire(s64 i, atomic64_t *v)
```

atomic add and test if negative with acquire ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic64_add_negative_acquire()`](#c-atomic64_add_negative_acquire) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool raw_atomic64_add_negative_release(s64 i, atomic64_t *v)
```

atomic add and test if negative with release ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic64_add_negative_release()`](#c-atomic64_add_negative_release) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool raw_atomic64_add_negative_relaxed(s64 i, atomic64_t *v)
```

atomic add and test if negative with relaxed ordering

**Parameters**

- `s64 i`: s64 value to add
- `atomic64_t *v`: pointer to atomic64_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic64_add_negative_relaxed()`](#c-atomic64_add_negative_relaxed) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
s64 raw_atomic64_fetch_add_unless(atomic64_t *v, s64 a, s64 u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 a`: s64 value to add
- `s64 u`: s64 value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_fetch_add_unless()`](#c-atomic64_fetch_add_unless) elsewhere.

**Return**

The original value of **v**.

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

```c
bool raw_atomic64_add_unless(atomic64_t *v, s64 a, s64 u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t
- `s64 a`: s64 value to add
- `s64 u`: s64 value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_add_unless()`](#c-atomic64_add_unless) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool raw_atomic64_inc_not_zero(atomic64_t *v)
```

atomic increment unless zero with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

If (**v** != 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_inc_not_zero()`](#c-atomic64_inc_not_zero) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool raw_atomic64_inc_unless_negative(atomic64_t *v)
```

atomic increment unless negative with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

If (**v** >= 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_inc_unless_negative()`](#c-atomic64_inc_unless_negative) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool raw_atomic64_dec_unless_positive(atomic64_t *v)
```

atomic decrement unless positive with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

If (**v** \<= 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_dec_unless_positive()`](#c-atomic64_dec_unless_positive) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
s64 raw_atomic64_dec_if_positive(atomic64_t *v)
```

atomic decrement if positive with full ordering

**Parameters**

- `atomic64_t *v`: pointer to atomic64_t

**Description**

If (**v** > 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic64_dec_if_positive()`](#c-atomic64_dec_if_positive) elsewhere.

**Return**

The old value of (**v** - 1), regardless of whether **v** was updated.



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

```c
long raw_atomic_long_read(const atomic_long_t *v)
```

atomic load with relaxed ordering

**Parameters**

- `const atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically loads the value of **v** with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_read()`](#c-atomic_long_read) elsewhere.

**Return**

The value loaded from **v**.

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

```c
long raw_atomic_long_read_acquire(const atomic_long_t *v)
```

atomic load with acquire ordering

**Parameters**

- `const atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically loads the value of **v** with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_read_acquire()`](#c-atomic_long_read_acquire) elsewhere.

**Return**

The value loaded from **v**.

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

```c
void raw_atomic_long_set(atomic_long_t *v, long i)
```

atomic set with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long i`: long value to assign

**Description**

Atomically sets **v** to **i** with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_set()`](#c-atomic_long_set) elsewhere.

**Return**

Nothing.

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

```c
void raw_atomic_long_set_release(atomic_long_t *v, long i)
```

atomic set with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long i`: long value to assign

**Description**

Atomically sets **v** to **i** with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_set_release()`](#c-atomic_long_set_release) elsewhere.

**Return**

Nothing.

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

```c
void raw_atomic_long_add(long i, atomic_long_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_add()`](#c-atomic_long_add) elsewhere.

**Return**

Nothing.

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

```c
long raw_atomic_long_add_return(long i, atomic_long_t *v)
```

atomic add with full ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_add_return()`](#c-atomic_long_add_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_add_return_acquire(long i, atomic_long_t *v)
```

atomic add with acquire ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_add_return_acquire()`](#c-atomic_long_add_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_add_return_release(long i, atomic_long_t *v)
```

atomic add with release ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_add_return_release()`](#c-atomic_long_add_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_add_return_relaxed(long i, atomic_long_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_add_return_relaxed()`](#c-atomic_long_add_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_fetch_add(long i, atomic_long_t *v)
```

atomic add with full ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_add()`](#c-atomic_long_fetch_add) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_add_acquire(long i, atomic_long_t *v)
```

atomic add with acquire ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_add_acquire()`](#c-atomic_long_fetch_add_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_add_release(long i, atomic_long_t *v)
```

atomic add with release ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_add_release()`](#c-atomic_long_fetch_add_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_add_relaxed(long i, atomic_long_t *v)
```

atomic add with relaxed ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_add_relaxed()`](#c-atomic_long_fetch_add_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_long_sub(long i, atomic_long_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_sub()`](#c-atomic_long_sub) elsewhere.

**Return**

Nothing.

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

```c
long raw_atomic_long_sub_return(long i, atomic_long_t *v)
```

atomic subtract with full ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_sub_return()`](#c-atomic_long_sub_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_sub_return_acquire(long i, atomic_long_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_sub_return_acquire()`](#c-atomic_long_sub_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_sub_return_release(long i, atomic_long_t *v)
```

atomic subtract with release ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_sub_return_release()`](#c-atomic_long_sub_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_sub_return_relaxed(long i, atomic_long_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_sub_return_relaxed()`](#c-atomic_long_sub_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_fetch_sub(long i, atomic_long_t *v)
```

atomic subtract with full ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_sub()`](#c-atomic_long_fetch_sub) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_sub_acquire(long i, atomic_long_t *v)
```

atomic subtract with acquire ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_sub_acquire()`](#c-atomic_long_fetch_sub_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_sub_release(long i, atomic_long_t *v)
```

atomic subtract with release ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_sub_release()`](#c-atomic_long_fetch_sub_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_sub_relaxed(long i, atomic_long_t *v)
```

atomic subtract with relaxed ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_sub_relaxed()`](#c-atomic_long_fetch_sub_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_long_inc(atomic_long_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_inc()`](#c-atomic_long_inc) elsewhere.

**Return**

Nothing.

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

```c
long raw_atomic_long_inc_return(atomic_long_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_inc_return()`](#c-atomic_long_inc_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_inc_return_acquire(atomic_long_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_inc_return_acquire()`](#c-atomic_long_inc_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_inc_return_release(atomic_long_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_inc_return_release()`](#c-atomic_long_inc_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_inc_return_relaxed(atomic_long_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_inc_return_relaxed()`](#c-atomic_long_inc_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_fetch_inc(atomic_long_t *v)
```

atomic increment with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_inc()`](#c-atomic_long_fetch_inc) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_inc_acquire(atomic_long_t *v)
```

atomic increment with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_inc_acquire()`](#c-atomic_long_fetch_inc_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_inc_release(atomic_long_t *v)
```

atomic increment with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_inc_release()`](#c-atomic_long_fetch_inc_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_inc_relaxed(atomic_long_t *v)
```

atomic increment with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_inc_relaxed()`](#c-atomic_long_fetch_inc_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_long_dec(atomic_long_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_dec()`](#c-atomic_long_dec) elsewhere.

**Return**

Nothing.

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

```c
long raw_atomic_long_dec_return(atomic_long_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_dec_return()`](#c-atomic_long_dec_return) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_dec_return_acquire(atomic_long_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_dec_return_acquire()`](#c-atomic_long_dec_return_acquire) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_dec_return_release(atomic_long_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_dec_return_release()`](#c-atomic_long_dec_return_release) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_dec_return_relaxed(atomic_long_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_dec_return_relaxed()`](#c-atomic_long_dec_return_relaxed) elsewhere.

**Return**

The updated value of **v**.

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

```c
long raw_atomic_long_fetch_dec(atomic_long_t *v)
```

atomic decrement with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_dec()`](#c-atomic_long_fetch_dec) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_dec_acquire(atomic_long_t *v)
```

atomic decrement with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_dec_acquire()`](#c-atomic_long_fetch_dec_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_dec_release(atomic_long_t *v)
```

atomic decrement with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_dec_release()`](#c-atomic_long_fetch_dec_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_dec_relaxed(atomic_long_t *v)
```

atomic decrement with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_dec_relaxed()`](#c-atomic_long_fetch_dec_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_long_and(long i, atomic_long_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_and()`](#c-atomic_long_and) elsewhere.

**Return**

Nothing.

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

```c
long raw_atomic_long_fetch_and(long i, atomic_long_t *v)
```

atomic bitwise AND with full ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_and()`](#c-atomic_long_fetch_and) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_and_acquire(long i, atomic_long_t *v)
```

atomic bitwise AND with acquire ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_and_acquire()`](#c-atomic_long_fetch_and_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_and_release(long i, atomic_long_t *v)
```

atomic bitwise AND with release ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_and_release()`](#c-atomic_long_fetch_and_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_and_relaxed(long i, atomic_long_t *v)
```

atomic bitwise AND with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_and_relaxed()`](#c-atomic_long_fetch_and_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_long_andnot(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_andnot()`](#c-atomic_long_andnot) elsewhere.

**Return**

Nothing.

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

```c
long raw_atomic_long_fetch_andnot(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with full ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_andnot()`](#c-atomic_long_fetch_andnot) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_andnot_acquire(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with acquire ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_andnot_acquire()`](#c-atomic_long_fetch_andnot_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_andnot_release(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with release ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_andnot_release()`](#c-atomic_long_fetch_andnot_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_andnot_relaxed(long i, atomic_long_t *v)
```

atomic bitwise AND NOT with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** & **\~i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_andnot_relaxed()`](#c-atomic_long_fetch_andnot_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_long_or(long i, atomic_long_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_or()`](#c-atomic_long_or) elsewhere.

**Return**

Nothing.

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

```c
long raw_atomic_long_fetch_or(long i, atomic_long_t *v)
```

atomic bitwise OR with full ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_or()`](#c-atomic_long_fetch_or) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_or_acquire(long i, atomic_long_t *v)
```

atomic bitwise OR with acquire ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_or_acquire()`](#c-atomic_long_fetch_or_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_or_release(long i, atomic_long_t *v)
```

atomic bitwise OR with release ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_or_release()`](#c-atomic_long_fetch_or_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_or_relaxed(long i, atomic_long_t *v)
```

atomic bitwise OR with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** | **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_or_relaxed()`](#c-atomic_long_fetch_or_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
void raw_atomic_long_xor(long i, atomic_long_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_xor()`](#c-atomic_long_xor) elsewhere.

**Return**

Nothing.

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

```c
long raw_atomic_long_fetch_xor(long i, atomic_long_t *v)
```

atomic bitwise XOR with full ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_xor()`](#c-atomic_long_fetch_xor) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_xor_acquire(long i, atomic_long_t *v)
```

atomic bitwise XOR with acquire ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_xor_acquire()`](#c-atomic_long_fetch_xor_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_xor_release(long i, atomic_long_t *v)
```

atomic bitwise XOR with release ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_xor_release()`](#c-atomic_long_fetch_xor_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_fetch_xor_relaxed(long i, atomic_long_t *v)
```

atomic bitwise XOR with relaxed ordering

**Parameters**

- `long i`: long value
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** ^ **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_fetch_xor_relaxed()`](#c-atomic_long_fetch_xor_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_xchg(atomic_long_t *v, long new)
```

atomic exchange with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long new`: long value to assign

**Description**

Atomically updates **v** to **new** with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_xchg()`](#c-atomic_long_xchg) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_xchg_acquire(atomic_long_t *v, long new)
```

atomic exchange with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long new`: long value to assign

**Description**

Atomically updates **v** to **new** with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_xchg_acquire()`](#c-atomic_long_xchg_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_xchg_release(atomic_long_t *v, long new)
```

atomic exchange with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long new`: long value to assign

**Description**

Atomically updates **v** to **new** with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_xchg_release()`](#c-atomic_long_xchg_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_xchg_relaxed(atomic_long_t *v, long new)
```

atomic exchange with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long new`: long value to assign

**Description**

Atomically updates **v** to **new** with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_xchg_relaxed()`](#c-atomic_long_xchg_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_cmpxchg(atomic_long_t *v, long old, long new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long old`: long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_cmpxchg()`](#c-atomic_long_cmpxchg) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_cmpxchg_acquire(atomic_long_t *v, long old, long new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long old`: long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_cmpxchg_acquire()`](#c-atomic_long_cmpxchg_acquire) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_cmpxchg_release(atomic_long_t *v, long old, long new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long old`: long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_cmpxchg_release()`](#c-atomic_long_cmpxchg_release) elsewhere.

**Return**

The original value of **v**.

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

```c
long raw_atomic_long_cmpxchg_relaxed(atomic_long_t *v, long old, long new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long old`: long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_cmpxchg_relaxed()`](#c-atomic_long_cmpxchg_relaxed) elsewhere.

**Return**

The original value of **v**.

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

```c
bool raw_atomic_long_try_cmpxchg(atomic_long_t *v, long *old, long new)
```

atomic compare and exchange with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long *old`: pointer to long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with full ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_try_cmpxchg()`](#c-atomic_long_try_cmpxchg) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic_long_try_cmpxchg_acquire(atomic_long_t *v, long *old, long new)
```

atomic compare and exchange with acquire ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long *old`: pointer to long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with acquire ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_try_cmpxchg_acquire()`](#c-atomic_long_try_cmpxchg_acquire) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic_long_try_cmpxchg_release(atomic_long_t *v, long *old, long new)
```

atomic compare and exchange with release ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long *old`: pointer to long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with release ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_try_cmpxchg_release()`](#c-atomic_long_try_cmpxchg_release) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic_long_try_cmpxchg_relaxed(atomic_long_t *v, long *old, long new)
```

atomic compare and exchange with relaxed ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long *old`: pointer to long value to compare with
- `long new`: long value to assign

**Description**

If (**v** == **old**), atomically updates **v** to **new** with relaxed ordering.
Otherwise, **v** is not modified, **old** is updated to the current value of **v**,
and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_try_cmpxchg_relaxed()`](#c-atomic_long_try_cmpxchg_relaxed) elsewhere.

**Return**

**true** if the exchange occurred, **false** otherwise.

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

```c
bool raw_atomic_long_sub_and_test(long i, atomic_long_t *v)
```

atomic subtract and test if zero with full ordering

**Parameters**

- `long i`: long value to subtract
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_sub_and_test()`](#c-atomic_long_sub_and_test) elsewhere.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool raw_atomic_long_dec_and_test(atomic_long_t *v)
```

atomic decrement and test if zero with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** - 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_dec_and_test()`](#c-atomic_long_dec_and_test) elsewhere.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool raw_atomic_long_inc_and_test(atomic_long_t *v)
```

atomic increment and test if zero with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + 1) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_inc_and_test()`](#c-atomic_long_inc_and_test) elsewhere.

**Return**

**true** if the resulting value of **v** is zero, **false** otherwise.

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

```c
bool raw_atomic_long_add_negative(long i, atomic_long_t *v)
```

atomic add and test if negative with full ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with full ordering.

Safe to use in noinstr code; prefer [`atomic_long_add_negative()`](#c-atomic_long_add_negative) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool raw_atomic_long_add_negative_acquire(long i, atomic_long_t *v)
```

atomic add and test if negative with acquire ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with acquire ordering.

Safe to use in noinstr code; prefer [`atomic_long_add_negative_acquire()`](#c-atomic_long_add_negative_acquire) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool raw_atomic_long_add_negative_release(long i, atomic_long_t *v)
```

atomic add and test if negative with release ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with release ordering.

Safe to use in noinstr code; prefer [`atomic_long_add_negative_release()`](#c-atomic_long_add_negative_release) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
bool raw_atomic_long_add_negative_relaxed(long i, atomic_long_t *v)
```

atomic add and test if negative with relaxed ordering

**Parameters**

- `long i`: long value to add
- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

Atomically updates **v** to (**v** + **i**) with relaxed ordering.

Safe to use in noinstr code; prefer [`atomic_long_add_negative_relaxed()`](#c-atomic_long_add_negative_relaxed) elsewhere.

**Return**

**true** if the resulting value of **v** is negative, **false** otherwise.

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

```c
long raw_atomic_long_fetch_add_unless(atomic_long_t *v, long a, long u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long a`: long value to add
- `long u`: long value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_fetch_add_unless()`](#c-atomic_long_fetch_add_unless) elsewhere.

**Return**

The original value of **v**.

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

```c
bool raw_atomic_long_add_unless(atomic_long_t *v, long a, long u)
```

atomic add unless value with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t
- `long a`: long value to add
- `long u`: long value to compare with

**Description**

If (**v** != **u**), atomically updates **v** to (**v** + **a**) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_add_unless()`](#c-atomic_long_add_unless) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool raw_atomic_long_inc_not_zero(atomic_long_t *v)
```

atomic increment unless zero with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

If (**v** != 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_inc_not_zero()`](#c-atomic_long_inc_not_zero) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool raw_atomic_long_inc_unless_negative(atomic_long_t *v)
```

atomic increment unless negative with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

If (**v** >= 0), atomically updates **v** to (**v** + 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_inc_unless_negative()`](#c-atomic_long_inc_unless_negative) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
bool raw_atomic_long_dec_unless_positive(atomic_long_t *v)
```

atomic decrement unless positive with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

If (**v** \<= 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_dec_unless_positive()`](#c-atomic_long_dec_unless_positive) elsewhere.

**Return**

**true** if **v** was updated, **false** otherwise.

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

```c
long raw_atomic_long_dec_if_positive(atomic_long_t *v)
```

atomic decrement if positive with full ordering

**Parameters**

- `atomic_long_t *v`: pointer to atomic_long_t

**Description**

If (**v** > 0), atomically updates **v** to (**v** - 1) with full ordering.
Otherwise, **v** is not modified and relaxed ordering is provided.

Safe to use in noinstr code; prefer [`atomic_long_dec_if_positive()`](#c-atomic_long_dec_if_positive) elsewhere.

**Return**

The old value of (**v** - 1), regardless of whether **v** was updated.


<a id="rst-kernel-objects-manipulation"></a>

## Kernel objects manipulation


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

```c
char * kobject_get_path(const struct kobject *kobj, gfp_t gfp_mask)
```

Allocate memory and fill in the path for **kobj**.

**Parameters**

- `const struct kobject *kobj`: kobject in question, with which to build the path
- `gfp_t gfp_mask`: the allocation type used to allocate the path

**Return**

The newly allocated memory, caller must free with [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

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

```c
int kobject_set_name(struct kobject *kobj, const char *fmt, ...)
```

Set the name of a kobject.

**Parameters**

- `struct kobject *kobj`: struct kobject to set the name of
- `const char *fmt`: format string used to build the name
- `...`: variable arguments

**Description**

This sets the name of the kobject.  If you have already added the
kobject to the system, you must call [`kobject_rename()`](#c-kobject_rename) in order to
change the name of the kobject.

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

```c
void kobject_init(struct kobject *kobj, const struct kobj_type *ktype)
```

Initialize a kobject structure.

**Parameters**

- `struct kobject *kobj`: pointer to the kobject to initialize
- `const struct kobj_type *ktype`: pointer to the ktype for this kobject.

**Description**

This function will properly initialize a kobject such that it can then
be passed to the [`kobject_add()`](#c-kobject_add) call.

After this function is called, the kobject MUST be cleaned up by a call
to [`kobject_put()`](#c-kobject_put), not by a call to kfree directly to ensure that all of
the memory is cleaned up properly.

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

```c
int kobject_add(struct kobject *kobj, struct kobject *parent, const char *fmt, ...)
```

The main kobject add function.

**Parameters**

- `struct kobject *kobj`: the kobject to add
- `struct kobject *parent`: pointer to the parent of the kobject.
- `const char *fmt`: format to name the kobject with.
- `...`: variable arguments

**Description**

The kobject name is set and added to the kobject hierarchy in this
function.

If **parent** is set, then the parent of the **kobj** will be set to it.
If **parent** is NULL, then the parent of the **kobj** will be set to the
kobject associated with the kset assigned to this kobject.  If no kset
is assigned to the kobject, then the kobject will be located in the
root of the sysfs tree.

Note, no "add" uevent will be created with this call, the caller should set
up all of the necessary sysfs files for the object and then call
[`kobject_uevent()`](#c-kobject_uevent) with the UEVENT_ADD parameter to ensure that
userspace is properly notified of this kobject's creation.

If this function returns success, [`kobject_put()`](#c-kobject_put) must also be called
in order to properly clean up the memory associated with the object.

In short, once this function is called, [`kobject_put()`](#c-kobject_put) MUST be called
when the use of the object is finished in order to properly free
everything.

**Return**

If this function returns an error, [`kobject_put()`](#c-kobject_put) must be
called to properly clean up the memory associated with the
object.  Under no instance should the kobject that is passed
to this function be directly freed with a call to [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree),
that can leak memory.

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

```c
int kobject_init_and_add(struct kobject *kobj, const struct kobj_type *ktype, struct kobject *parent, const char *fmt, ...)
```

Initialize a kobject structure and add it to the kobject hierarchy.

**Parameters**

- `struct kobject *kobj`: pointer to the kobject to initialize
- `const struct kobj_type *ktype`: pointer to the ktype for this kobject.
- `struct kobject *parent`: pointer to the parent of this kobject.
- `const char *fmt`: the name of the kobject.
- `...`: variable arguments

**Description**

This function combines the call to [`kobject_init()`](#c-kobject_init) and [`kobject_add()`](#c-kobject_add).

If this function returns an error, [`kobject_put()`](#c-kobject_put) must be called to
properly clean up the memory associated with the object.  This is the
same type of error handling after a call to [`kobject_add()`](#c-kobject_add) and kobject
lifetime rules are the same here.

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

```c
int kobject_rename(struct kobject *kobj, const char *new_name)
```

Change the name of an object.

**Parameters**

- `struct kobject *kobj`: object in question.
- `const char *new_name`: object's new name

**Description**

It is the responsibility of the caller to provide mutual
exclusion between two different calls of kobject_rename
on the same kobject and to ensure that new_name is valid and
won't conflict with other kobjects.

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

```c
int kobject_move(struct kobject *kobj, struct kobject *new_parent)
```

Move object to another parent.

**Parameters**

- `struct kobject *kobj`: object in question.
- `struct kobject *new_parent`: object's new parent (can be NULL)

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

```c
void kobject_del(struct kobject *kobj)
```

Unlink kobject from hierarchy.

**Parameters**

- `struct kobject *kobj`: object.

**Description**

This is the function that should be called to delete an object
successfully added via [`kobject_add()`](#c-kobject_add).

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

```c
struct kobject * kobject_get(struct kobject *kobj)
```

Increment refcount for object.

**Parameters**

- `struct kobject *kobj`: object.

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

```c
void kobject_put(struct kobject *kobj)
```

Decrement refcount for object.

**Parameters**

- `struct kobject *kobj`: object.

**Description**

Decrement the refcount, and if 0, call `kobject_cleanup()`.

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

```c
struct kobject * kobject_create_and_add(const char *name, struct kobject *parent)
```

Create a struct kobject dynamically and register it with sysfs.

**Parameters**

- `const char *name`: the name for the kobject
- `struct kobject *parent`: the parent kobject of this kobject, if any.

**Description**

This function creates a kobject structure dynamically and registers it
with sysfs.  When you are finished with this structure, call
[`kobject_put()`](#c-kobject_put) and the structure will be dynamically freed when
it is no longer being used.

If the kobject was not able to be created, NULL will be returned.

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

```c
int kset_register(struct kset *k)
```

Initialize and add a kset.

**Parameters**

- `struct kset *k`: kset.

**NOTE**

On error, the kset.kobj.name allocated `by()` `kobj_set_name()`
is freed, it can not be used any more.

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

```c
void kset_unregister(struct kset *k)
```

Remove a kset.

**Parameters**

- `struct kset *k`: kset.

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

```c
struct kobject * kset_find_obj(struct kset *kset, const char *name)
```

Search for object in kset.

**Parameters**

- `struct kset *kset`: kset we're looking in.
- `const char *name`: object's name.

**Description**

Lock kset via **kset->subsys**, and iterate over **kset->list**,
looking for a matching kobject. If matching object is found
take a reference and return the object.

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

```c
struct kset * kset_create_and_add(const char *name, const struct kset_uevent_ops *uevent_ops, struct kobject *parent_kobj)
```

Create a struct kset dynamically and add it to sysfs.

**Parameters**

- `const char *name`: the name for the kset
- `const struct kset_uevent_ops *uevent_ops`: a struct kset_uevent_ops for the kset
- `struct kobject *parent_kobj`: the parent kobject of this kset, if any.

**Description**

This function creates a kset structure dynamically and registers it
with sysfs.  When you are finished with this structure, call
[`kset_unregister()`](#c-kset_unregister) and the structure will be dynamically freed when it
is no longer being used.

If the kset was not able to be created, NULL will be returned.



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

```c
int kobject_uevent_env(struct kobject *kobj, enum kobject_action action, char *envp_ext[])
```

send an uevent with environmental data

**Parameters**

- `struct kobject *kobj`: struct kobject that the action is happening to
- `enum kobject_action action`: action that is happening
- `char *envp_ext[]`: pointer to environmental data

**Description**

Returns 0 if [`kobject_uevent_env()`](#c-kobject_uevent_env) is completed with success or the
corresponding error when it fails.

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

```c
int kobject_uevent(struct kobject *kobj, enum kobject_action action)
```

notify userspace by sending an uevent

**Parameters**

- `struct kobject *kobj`: struct kobject that the action is happening to
- `enum kobject_action action`: action that is happening

**Description**

Returns 0 if [`kobject_uevent()`](#c-kobject_uevent) is completed with success or the
corresponding error when it fails.

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

```c
int add_uevent_var(struct kobj_uevent_env *env, const char *format, ...)
```

add key value string to the environment buffer

**Parameters**

- `struct kobj_uevent_env *env`: environment buffer structure
- `const char *format`: printf format for the key=value pair
- `...`: variable arguments

**Description**

Returns 0 if environment variable was added successfully or -ENOMEM
if no space was available.


<a id="rst-kernel-utility-functions"></a>

## Kernel utility functions


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

```c
ARRAY_SIZE(arr)
```

get the number of elements in array **arr**

**Parameters**

- `arr`: array to be sized

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

```c
ARRAY_END(arr)
```

get a pointer to one past the last element in array **arr**

**Parameters**

- `arr`: array



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

```c
container_of(ptr, type, member)
```

cast a member of a structure out to the containing structure

**Parameters**

- `ptr`: the pointer to the member.
- `type`: the type of the container struct this is embedded in.
- `member`: the name of the member within the struct.

**Description**

WARNING: any const qualifier of **ptr** is lost.
Do not use [`container_of()`](#c-container_of) in new code.

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

```c
container_of_const(ptr, type, member)
```

cast a member of a structure out to the containing structure and preserve the const-ness of the pointer

**Parameters**

- `ptr`: the pointer to the member
- `type`: the type of the container struct this is embedded in.
- `member`: the name of the member within the struct.

**Description**

Always prefer [`container_of_const()`](#c-container_of_const) instead of [`container_of()`](#c-container_of) in new code.






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

```c
sizeof_field(TYPE, MEMBER)
```

Report the size of a struct field in bytes

**Parameters**

- `TYPE`: The structure containing the field of interest
- `MEMBER`: The field to return the size of

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

```c
offsetofend(TYPE, MEMBER)
```

Report the offset of a struct field within the struct

**Parameters**

- `TYPE`: The type of the structure
- `MEMBER`: The member within the structure to get the end offset of

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

```c
struct_group(NAME, MEMBERS...)
```

Wrap a set of declarations in a mirrored struct

**Parameters**

- `NAME`: The identifier name of the mirrored sub-struct
- `MEMBERS...`: The member declarations for the mirrored structs

**Description**

Used to create an anonymous union of two structs with identical
layout and size: one anonymous and one named. The former can be
used normally without sub-struct naming, and the latter can be
used to reason about the start, end, and size of the group of
struct members.

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

```c
struct_group_attr(NAME, ATTRS, MEMBERS...)
```

Create a [`struct_group()`](#c-struct_group) with trailing attributes

**Parameters**

- `NAME`: The identifier name of the mirrored sub-struct
- `ATTRS`: Any struct attributes to apply
- `MEMBERS...`: The member declarations for the mirrored structs

**Description**

Used to create an anonymous union of two structs with identical
layout and size: one anonymous and one named. The former can be
used normally without sub-struct naming, and the latter can be
used to reason about the start, end, and size of the group of
struct members. Includes structure attributes argument.

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

```c
struct_group_tagged(TAG, NAME, MEMBERS...)
```

Create a struct_group with a reusable tag

**Parameters**

- `TAG`: The tag name for the named sub-struct
- `NAME`: The identifier name of the mirrored sub-struct
- `MEMBERS...`: The member declarations for the mirrored structs

**Description**

Used to create an anonymous union of two structs with identical
layout and size: one anonymous and one named. The former can be
used normally without sub-struct naming, and the latter can be
used to reason about the start, end, and size of the group of
struct members. Includes struct tag argument for the named copy,
so the specified layout can be reused later.

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

```c
DECLARE_FLEX_ARRAY(TYPE, NAME)
```

Declare a flexible array usable in a union

**Parameters**

- `TYPE`: The type of each flexible array element
- `NAME`: The name of the flexible array member

**Description**

In order to have a flexible array member in a union or alone in a
struct, it needs to be wrapped in an anonymous struct with at least 1
named member, but that member can be empty.

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

```c
__TRAILING_OVERLAP(TYPE, NAME, FAM, ATTRS, MEMBERS)
```

Overlap a flexible-array member with trailing members.

**Parameters**

- `TYPE`: Flexible structure type name, including "struct" keyword.
- `NAME`: Name for a variable to define.
- `FAM`: The flexible-array member within **TYPE**
- `ATTRS`: Any struct attributes (usually empty)
- `MEMBERS`: Trailing overlapping members.

**Description**

Creates a union between a flexible-array member (FAM) in a struct and a set
of additional members that would otherwise follow it.

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

```c
TRAILING_OVERLAP(TYPE, NAME, FAM, MEMBERS)
```

Overlap a flexible-array member with trailing members.

**Parameters**

- `TYPE`: Flexible structure type name, including "struct" keyword.
- `NAME`: Name for a variable to define.
- `FAM`: The flexible-array member within **TYPE**
- `MEMBERS`: Trailing overlapping members.

**Description**

Creates a union between a flexible-array member (FAM) in a struct and a set
of additional members that would otherwise follow it.



#### <a id="c-for_each_if"></a>`for_each_if()`

```c
for_each_if(condition)
```

helper for handling conditionals in various for_each macros

**Parameters**

- `condition`: The condition to check

**Description**

Typical use:

```text
#define for_each_foo_bar(x, y) \'
        list_for_each_entry(x, y->list, head) \'
                for_each_if(x->something == SOMETHING)
```

The [`for_each_if()`](#c-for_each_if) macro makes the use of `for_each_foo_bar()` less error
prone.

#### <a id="c-find_closest"></a>`find_closest()`

```c
find_closest(x, a, as)
```

locate the closest element in a sorted array

**Parameters**

- `x`: The reference value.
- `a`: The array in which to look for the closest element. Must be sorted
  in ascending order.
- `as`: Size of 'a'.

**Description**

Returns the index of the element closest to 'x'.

**Note**

- If using an array of negative numbers (or mixed positive numbers),

  then be sure that 'x' is of a signed-type to get good results.

#### <a id="c-find_closest_descending"></a>`find_closest_descending()`

```c
find_closest_descending(x, a, as)
```

locate the closest element in a sorted array

**Parameters**

- `x`: The reference value.
- `a`: The array in which to look for the closest element. Must be sorted
  in descending order.
- `as`: Size of 'a'.

**Description**

Similar to [`find_closest()`](#c-find_closest) but 'a' is expected to be sorted in descending
order. The iteration is done in reverse order, so that the comparison
of '__fc_right' & '__fc_left' also works for unsigned numbers.

#### <a id="c-PTR_IF"></a>`PTR_IF()`

```c
PTR_IF(cond, ptr)
```

evaluate to **ptr** if **cond** is true, or to NULL otherwise.

**Parameters**

- `cond`: A conditional, usually in a form of IS_ENABLED(CONFIG_FOO)
- `ptr`: A pointer to assign if **cond** is true.

**Description**

PTR_IF(IS_ENABLED(CONFIG_FOO), ptr) evaluates to **ptr** if CONFIG_FOO is set
to 'y' or 'm', or to NULL otherwise. The **ptr** argument must be a pointer.

The macro can be very useful to help compiler dropping dead code.

For instance, consider the following:

```text
#ifdef CONFIG_FOO_SUSPEND
static int foo_suspend(struct device *dev)
{
   ...
}
#endif

static struct pm_ops foo_ops = {
#ifdef CONFIG_FOO_SUSPEND
    .suspend = foo_suspend,
#endif
};
```

While this works, the `foo_suspend()` macro is compiled conditionally,
only when CONFIG_FOO_SUSPEND is set. This is problematic, as there could
be a build bug in this function, we wouldn't have a way to know unless
the configuration option is set.

An alternative is to declare `foo_suspend()` always, but mark it
as __maybe_unused. This works, but the __maybe_unused attribute
is required to instruct the compiler that the function may not
be referenced anywhere, and is safe to remove without making
a fuss about it. This makes the programmer responsible for tagging
the functions that can be garbage-collected.

With the macro it is possible to write the following:

```text
static int foo_suspend(struct device *dev)
{
   ...
}

static struct pm_ops foo_ops = {
    .suspend = PTR_IF(IS_ENABLED(CONFIG_FOO_SUSPEND), foo_suspend),
};
```

The `foo_suspend()` function will now be automatically dropped by the
compiler, and it does not require any specific attribute.

#### <a id="c-u64_to_user_ptr"></a>`u64_to_user_ptr()`

```c
u64_to_user_ptr(x)
```

cast a pointer passed as u64 from user space to void __user *

**Parameters**

- `x`: The u64 value from user space, usually via IOCTL

**Description**

[`u64_to_user_ptr()`](#c-u64_to_user_ptr) simply casts a pointer passed as u64 from user space to void
__user * correctly. Using this lets us get rid of all the tiresome casts.

#### <a id="c-is_insidevar"></a>`is_insidevar()`

```c
is_insidevar(ptr, var)
```

check if the **ptr** points inside the **var** memory range.

**Parameters**

- `ptr`: the pointer to a memory address.
- `var`: the variable which address and size identify the memory range.

**Description**

Evaluates to true if the address in **ptr** lies within the memory
range allocated to **var**.



#### <a id="c-upper_32_bits"></a>`upper_32_bits()`

```c
upper_32_bits(n)
```

return bits 32-63 of a number

**Parameters**

- `n`: the number we're accessing

**Description**

A basic shift-right of a 64- or 32-bit quantity.  Use this to suppress
the "right shift count >= width of type" warning when that quantity is
32-bits.

#### <a id="c-lower_32_bits"></a>`lower_32_bits()`

```c
lower_32_bits(n)
```

return bits 0-31 of a number

**Parameters**

- `n`: the number we're accessing

#### <a id="c-upper_16_bits"></a>`upper_16_bits()`

```c
upper_16_bits(n)
```

return bits 16-31 of a number

**Parameters**

- `n`: the number we're accessing

#### <a id="c-lower_16_bits"></a>`lower_16_bits()`

```c
lower_16_bits(n)
```

return bits 0-15 of a number

**Parameters**

- `n`: the number we're accessing

#### <a id="c-REPEAT_BYTE"></a>`REPEAT_BYTE()`

```c
REPEAT_BYTE(x)
```

repeat the value **x** multiple times as an unsigned long value

**Parameters**

- `x`: value to repeat

**NOTE**

**x** is not checked for > 0xff; larger values produce odd results.

#### <a id="c-REPEAT_BYTE_U32"></a>`REPEAT_BYTE_U32()`

```c
REPEAT_BYTE_U32(x)
```

repeat the value **x** multiple times as a u32 value

**Parameters**

- `x`: value to repeat

**NOTE**

**x** is not checked for > 0xff; larger values produce odd results.



#### <a id="c-console_list_lock"></a>`console_list_lock()`

```c
void console_list_lock(void)
```

Lock the console list

**Parameters**

- `void`: no arguments

**Description**

For console list or console->flags updates

#### <a id="c-console_list_unlock"></a>`console_list_unlock()`

```c
void console_list_unlock(void)
```

Unlock the console list

**Parameters**

- `void`: no arguments

**Description**

Counterpart to [`console_list_lock()`](#c-console_list_lock)

#### <a id="c-console_srcu_read_lock"></a>`console_srcu_read_lock()`

```c
int console_srcu_read_lock(void)
```

Register a new reader for the SRCU-protected console list

**Parameters**

- `void`: no arguments

**Description**

Use [`for_each_console_srcu()`](/kernel/hardware/driver-api/tty/console.md#c-for_each_console_srcu) to iterate the console list

**Context**

Any context.

**Return**

A cookie to pass to [`console_srcu_read_unlock()`](#c-console_srcu_read_unlock).

#### <a id="c-console_srcu_read_unlock"></a>`console_srcu_read_unlock()`

```c
void console_srcu_read_unlock(int cookie)
```

Unregister an old reader from the SRCU-protected console list

**Parameters**

- `int cookie`: cookie returned from [`console_srcu_read_lock()`](#c-console_srcu_read_lock)

**Description**

Counterpart to [`console_srcu_read_lock()`](#c-console_srcu_read_lock)

#### <a id="c-match_devname_and_update_preferred_console"></a>`match_devname_and_update_preferred_console()`

```c
int match_devname_and_update_preferred_console(const char *devname, const char *name, const short idx)
```

Update a preferred console when matching devname is found.

**Parameters**

- `const char *devname`: DEVNAME:0.0 style device name
- `const char *name`: Name of the corresponding console driver, e.g. "ttyS"
- `const short idx`: Console index, e.g. port number.

**Description**

The function checks whether a device with the given **devname** is
preferred via the console=DEVNAME:0.0 command line option.
It fills the missing console driver name and console index
so that a later `register_console()` call could find (match)
and enable this device.

It might be used when a driver subsystem initializes particular
devices with already known DEVNAME:0.0 style names. And it
could predict which console driver name and index this device
would later get associated with.

**Return**

0 on success, negative error code on failure.

#### <a id="c-console_lock"></a>`console_lock()`

```c
void console_lock(void)
```

block the console subsystem from printing

**Parameters**

- `void`: no arguments

**Description**

Acquires a lock which guarantees that no consoles will
be in or enter their `write()` callback.

Can sleep, returns nothing.

#### <a id="c-console_trylock"></a>`console_trylock()`

```c
int console_trylock(void)
```

try to block the console subsystem from printing

**Parameters**

- `void`: no arguments

**Description**

Try to acquire a lock which guarantees that no consoles will
be in or enter their `write()` callback.

returns 1 on success, and 0 on failure to acquire the lock.

#### <a id="c-console_unlock"></a>`console_unlock()`

```c
void console_unlock(void)
```

unblock the legacy console subsystem from printing

**Parameters**

- `void`: no arguments

**Description**

Releases the console_lock which the caller holds to block printing of
the legacy console subsystem.

While the console_lock was held, console output may have been buffered
by [`printk()`](/kernel/internals/core-api/printk-basics.md#c-printk). If this is the case, [`console_unlock()`](#c-console_unlock) emits the output on
legacy consoles prior to releasing the lock.

[`console_unlock()`](#c-console_unlock); may be called from any context.

#### <a id="c-console_force_preferred_locked"></a>`console_force_preferred_locked()`

```c
void console_force_preferred_locked(struct console *con)
```

force a registered console preferred

**Parameters**

- `struct console *con`: The registered console to force preferred.

**Description**

Must be called under [`console_list_lock()`](#c-console_list_lock).

#### <a id="c-printk_timed_ratelimit"></a>`printk_timed_ratelimit()`

```c
bool printk_timed_ratelimit(unsigned long *caller_jiffies, unsigned int interval_msecs)
```

caller-controlled printk ratelimiting

**Parameters**

- `unsigned long *caller_jiffies`: pointer to caller's state
- `unsigned int interval_msecs`: minimum interval between prints

**Description**

[`printk_timed_ratelimit()`](#c-printk_timed_ratelimit) returns true if more than **interval_msecs**
milliseconds have elapsed since the last time [`printk_timed_ratelimit()`](#c-printk_timed_ratelimit)
returned true.

#### <a id="c-kmsg_dump_register"></a>`kmsg_dump_register()`

```c
int kmsg_dump_register(struct kmsg_dumper *dumper)
```

register a kernel log dumper.

**Parameters**

- `struct kmsg_dumper *dumper`: pointer to the kmsg_dumper structure

**Description**

Adds a kernel log dumper to the system. The dump callback in the
structure will be called when the kernel oopses or panics and must be
set. Returns zero on success and `-EINVAL` or `-EBUSY` otherwise.

#### <a id="c-kmsg_dump_unregister"></a>`kmsg_dump_unregister()`

```c
int kmsg_dump_unregister(struct kmsg_dumper *dumper)
```

unregister a kmsg dumper.

**Parameters**

- `struct kmsg_dumper *dumper`: pointer to the kmsg_dumper structure

**Description**

Removes a dump device from the system. Returns zero on success and
`-EINVAL` otherwise.

#### <a id="c-kmsg_dump_get_line"></a>`kmsg_dump_get_line()`

```c
bool kmsg_dump_get_line(struct kmsg_dump_iter *iter, bool syslog, char *line, size_t size, size_t *len)
```

retrieve one kmsg log line

**Parameters**

- `struct kmsg_dump_iter *iter`: kmsg dump iterator
- `bool syslog`: include the "\<4>" prefixes
- `char *line`: buffer to copy the line to
- `size_t size`: maximum size of the buffer
- `size_t *len`: length of line placed into buffer

**Description**

Start at the beginning of the kmsg buffer, with the oldest kmsg
record, and copy one record into the provided buffer.

Consecutive calls will return the next available record moving
towards the end of the buffer with the youngest messages.

A return value of FALSE indicates that there are no more records to
read.

#### <a id="c-kmsg_dump_get_buffer"></a>`kmsg_dump_get_buffer()`

```c
bool kmsg_dump_get_buffer(struct kmsg_dump_iter *iter, bool syslog, char *buf, size_t size, size_t *len_out)
```

copy kmsg log lines

**Parameters**

- `struct kmsg_dump_iter *iter`: kmsg dump iterator
- `bool syslog`: include the "\<4>" prefixes
- `char *buf`: buffer to copy the line to
- `size_t size`: maximum size of the buffer
- `size_t *len_out`: length of line placed into buffer

**Description**

Start at the end of the kmsg buffer and fill the provided buffer
with as many of the *youngest* kmsg records that fit into it.
If the buffer is large enough, all available kmsg records will be
copied with a single call.

Consecutive calls will fill the buffer with the next block of
available older records, not including the earlier retrieved ones.

A return value of FALSE indicates that there are no more records to
read.

#### <a id="c-kmsg_dump_rewind"></a>`kmsg_dump_rewind()`

```c
void kmsg_dump_rewind(struct kmsg_dump_iter *iter)
```

reset the iterator

**Parameters**

- `struct kmsg_dump_iter *iter`: kmsg dump iterator

**Description**

Reset the dumper's iterator so that [`kmsg_dump_get_line()`](#c-kmsg_dump_get_line) and
[`kmsg_dump_get_buffer()`](#c-kmsg_dump_get_buffer) can be called again and used multiple
times within the same dumper.`dump()` callback.

#### <a id="c-__printk_cpu_sync_wait"></a>`__printk_cpu_sync_wait()`

```c
void __printk_cpu_sync_wait(void)
```

Busy wait until the printk cpu-reentrant spinning lock is not owned by any CPU.

**Parameters**

- `void`: no arguments

**Context**

Any context.

#### <a id="c-__printk_cpu_sync_try_get"></a>`__printk_cpu_sync_try_get()`

```c
int __printk_cpu_sync_try_get(void)
```

Try to acquire the printk cpu-reentrant spinning lock.

**Parameters**

- `void`: no arguments

**Description**

If no processor has the lock, the calling processor takes the lock and
becomes the owner. If the calling processor is already the owner of the
lock, this function succeeds immediately.

**Context**

Any context. Expects interrupts to be disabled.

**Return**

1 on success, otherwise 0.

#### <a id="c-__printk_cpu_sync_put"></a>`__printk_cpu_sync_put()`

```c
void __printk_cpu_sync_put(void)
```

Release the printk cpu-reentrant spinning lock.

**Parameters**

- `void`: no arguments

**Description**

The calling processor must be the owner of the lock.

**Context**

Any context. Expects interrupts to be disabled.



#### <a id="c-vpanic"></a>`vpanic()`

```c
void vpanic(const char *fmt, va_list args)
```

halt the system

**Parameters**

- `const char *fmt`: The text string to print
- `va_list args`: Arguments for the format string

**Description**

Display a message, then perform cleanups. This function never returns.

#### <a id="c-add_taint"></a>`add_taint()`

```c
void add_taint(unsigned flag, enum lockdep_ok lockdep_ok)
```

add a taint flag if not already set.

**Parameters**

- `unsigned flag`: one of the TAINT_* constants.
- `enum lockdep_ok lockdep_ok`: whether lock debugging is still OK.

**Description**

If something bad has gone wrong, you'll want **lockdebug_ok** = false, but for
some notewortht-but-not-corrupting cases, it can be set to true.


<a id="rst-device-resource-management"></a>

## Device Resource Management


#### <a id="c-__devres_alloc_node"></a>`__devres_alloc_node()`

```c
void * __devres_alloc_node(dr_release_t release, size_t size, gfp_t gfp, int nid, const char *name)
```

Allocate device resource data

**Parameters**

- `dr_release_t release`: Release function devres will be associated with
- `size_t size`: Allocation size
- `gfp_t gfp`: Allocation flags
- `int nid`: NUMA node
- `const char *name`: Name of the resource

**Description**

Allocate devres of **size** bytes.  The allocated area is zeroed, then
associated with **release**.  The returned pointer can be passed to
other devres_*() functions.

**Return**

Pointer to allocated devres on success, NULL on failure.

#### <a id="c-devres_for_each_res"></a>`devres_for_each_res()`

```c
void devres_for_each_res(struct device *dev, dr_release_t release, dr_match_t match, void *match_data, void (*fn)(struct device *, void *, void *), void *data)
```

Resource iterator

**Parameters**

- `struct device *dev`: Device to iterate resource from
- `dr_release_t release`: Look for resources associated with this release function
- `dr_match_t match`: Match function (optional)
- `void *match_data`: Data for the match function
- `void (*fn)(struct device *, void *, void *)`: Function to be called for each matched resource.
- `void *data`: Data for **fn**, the 3rd parameter of **fn**

**Description**

Call **fn** for each devres of **dev** which is associated with **release**
and for which **match** returns 1.

**Return**

void

#### <a id="c-devres_free"></a>`devres_free()`

```c
void devres_free(void *res)
```

Free device resource data

**Parameters**

- `void *res`: Pointer to devres data to free

**Description**

Free devres created with `devres_alloc()`.

#### <a id="c-devres_add"></a>`devres_add()`

```c
void devres_add(struct device *dev, void *res)
```

Register device resource

**Parameters**

- `struct device *dev`: Device to add resource to
- `void *res`: Resource to register

**Description**

Register devres **res** to **dev**.  **res** should have been allocated
using `devres_alloc()`.  On driver detach, the associated release
function will be invoked and devres will be freed automatically.

#### <a id="c-devres_find"></a>`devres_find()`

```c
void * devres_find(struct device *dev, dr_release_t release, dr_match_t match, void *match_data)
```

Find device resource

**Parameters**

- `struct device *dev`: Device to lookup resource from
- `dr_release_t release`: Look for resources associated with this release function
- `dr_match_t match`: Match function (optional)
- `void *match_data`: Data for the match function

**Description**

Find the latest devres of **dev** which is associated with **release**
and for which **match** returns 1.  If **match** is NULL, it's considered
to match all.

**Return**

Pointer to found devres, NULL if not found.

#### <a id="c-devres_get"></a>`devres_get()`

```c
void * devres_get(struct device *dev, void *new_res, dr_match_t match, void *match_data)
```

Find devres, if non-existent, add one atomically

**Parameters**

- `struct device *dev`: Device to lookup or add devres for
- `void *new_res`: Pointer to new initialized devres to add if not found
- `dr_match_t match`: Match function (optional)
- `void *match_data`: Data for the match function

**Description**

Find the latest devres of **dev** which has the same release function
as **new_res** and for which **match** return 1.  If found, **new_res** is
freed; otherwise, **new_res** is added atomically.

**Return**

Pointer to found or added devres.

#### <a id="c-devres_remove"></a>`devres_remove()`

```c
void * devres_remove(struct device *dev, dr_release_t release, dr_match_t match, void *match_data)
```

Find a device resource and remove it

**Parameters**

- `struct device *dev`: Device to find resource from
- `dr_release_t release`: Look for resources associated with this release function
- `dr_match_t match`: Match function (optional)
- `void *match_data`: Data for the match function

**Description**

Find the latest devres of **dev** associated with **release** and for
which **match** returns 1.  If **match** is NULL, it's considered to
match all.  If found, the resource is removed atomically and
returned.

**Return**

Pointer to removed devres on success, NULL if not found.

#### <a id="c-devres_destroy"></a>`devres_destroy()`

```c
int devres_destroy(struct device *dev, dr_release_t release, dr_match_t match, void *match_data)
```

Find a device resource and destroy it

**Parameters**

- `struct device *dev`: Device to find resource from
- `dr_release_t release`: Look for resources associated with this release function
- `dr_match_t match`: Match function (optional)
- `void *match_data`: Data for the match function

**Description**

Find the latest devres of **dev** associated with **release** and for
which **match** returns 1.  If **match** is NULL, it's considered to
match all.  If found, the resource is removed atomically and freed.

Note that the release function for the resource will not be called,
only the devres-allocated data will be freed.  The caller becomes
responsible for freeing any other data.

**Return**

0 if devres is found and freed, -ENOENT if not found.

#### <a id="c-devres_release"></a>`devres_release()`

```c
int devres_release(struct device *dev, dr_release_t release, dr_match_t match, void *match_data)
```

Find a device resource and destroy it, calling release

**Parameters**

- `struct device *dev`: Device to find resource from
- `dr_release_t release`: Look for resources associated with this release function
- `dr_match_t match`: Match function (optional)
- `void *match_data`: Data for the match function

**Description**

Find the latest devres of **dev** associated with **release** and for
which **match** returns 1.  If **match** is NULL, it's considered to
match all.  If found, the resource is removed atomically, the
release function called and the resource freed.

**Return**

0 if devres is found and freed, -ENOENT if not found.

#### <a id="c-devres_open_group"></a>`devres_open_group()`

```c
void * devres_open_group(struct device *dev, void *id, gfp_t gfp)
```

Open a new devres group

**Parameters**

- `struct device *dev`: Device to open devres group for
- `void *id`: Separator ID
- `gfp_t gfp`: Allocation flags

**Description**

Open a new devres group for **dev** with **id**.  For **id**, using a
pointer to an object which won't be used for another group is
recommended.  If **id** is NULL, address-wise unique ID is created.

**Return**

ID of the new group, NULL on failure.

#### <a id="c-devres_close_group"></a>`devres_close_group()`

```c
void devres_close_group(struct device *dev, void *id)
```

Close a devres group

**Parameters**

- `struct device *dev`: Device to close devres group for
- `void *id`: ID of target group, can be NULL

**Description**

Close the group identified by **id**.  If **id** is NULL, the latest open
group is selected.

#### <a id="c-devres_remove_group"></a>`devres_remove_group()`

```c
void devres_remove_group(struct device *dev, void *id)
```

Remove a devres group

**Parameters**

- `struct device *dev`: Device to remove group for
- `void *id`: ID of target group, can be NULL

**Description**

Remove the group identified by **id**.  If **id** is NULL, the latest
open group is selected.  Note that removing a group doesn't affect
any other resources.

#### <a id="c-devres_release_group"></a>`devres_release_group()`

```c
int devres_release_group(struct device *dev, void *id)
```

Release resources in a devres group

**Parameters**

- `struct device *dev`: Device to release group for
- `void *id`: ID of target group, can be NULL

**Description**

Release all resources in the group identified by **id**.  If **id** is
NULL, the latest open group is selected.  The selected group and
groups properly nested inside the selected group are removed.

**Return**

The number of released non-group resources.

#### <a id="c-__devm_add_action"></a>`__devm_add_action()`

```c
int __devm_add_action(struct device *dev, void (*action)(void *), void *data, const char *name)
```

add a custom action to list of managed resources

**Parameters**

- `struct device *dev`: Device that owns the action
- `void (*action)(void *)`: Function that should be called
- `void *data`: Pointer to data passed to **action** implementation
- `const char *name`: Name of the resource (for debugging purposes)

**Description**

This adds a custom action to the list of managed resources so that
it gets executed as part of standard resource unwinding.

#### <a id="c-devm_remove_action_nowarn"></a>`devm_remove_action_nowarn()`

```c
int devm_remove_action_nowarn(struct device *dev, void (*action)(void *), void *data)
```

removes previously added custom action

**Parameters**

- `struct device *dev`: Device that owns the action
- `void (*action)(void *)`: Function implementing the action
- `void *data`: Pointer to data passed to **action** implementation

**Description**

Removes instance of **action** previously added by `devm_add_action()`.
Both action and data should match one of the existing entries.

In contrast to `devm_remove_action()`, this function does not `WARN()` if no
entry could have been found.

This should only be used if the action is contained in an object with
independent lifetime management, e.g. the Devres rust abstraction.

Causing the warning from regular driver code most likely indicates an abuse
of the devres API.

**Return**

0 on success, -ENOENT if no entry could have been found.

#### <a id="c-devm_release_action"></a>`devm_release_action()`

```c
void devm_release_action(struct device *dev, void (*action)(void *), void *data)
```

release previously added custom action

**Parameters**

- `struct device *dev`: Device that owns the action
- `void (*action)(void *)`: Function implementing the action
- `void *data`: Pointer to data passed to **action** implementation

**Description**

Releases and removes instance of **action** previously added by
`devm_add_action()`.  Both action and data should match one of the
existing entries.

#### <a id="c-devm_kmalloc"></a>`devm_kmalloc()`

```c
void * devm_kmalloc(struct device *dev, size_t size, gfp_t gfp)
```

Resource-managed kmalloc

**Parameters**

- `struct device *dev`: Device to allocate memory for
- `size_t size`: Allocation size
- `gfp_t gfp`: Allocation gfp flags

**Description**

Managed kmalloc.  Memory allocated with this function is
automatically freed on driver detach.  Like all other devres
resources, guaranteed alignment is unsigned long long.

**Return**

Pointer to allocated memory on success, NULL on failure.

#### <a id="c-devm_krealloc"></a>`devm_krealloc()`

```c
void * devm_krealloc(struct device *dev, void *ptr, size_t new_size, gfp_t gfp)
```

Resource-managed `krealloc()`

**Parameters**

- `struct device *dev`: Device to re-allocate memory for
- `void *ptr`: Pointer to the memory chunk to re-allocate
- `size_t new_size`: New allocation size
- `gfp_t gfp`: Allocation gfp flags

**Description**

Managed `krealloc()`. Resizes the memory chunk allocated with [`devm_kmalloc()`](#c-devm_kmalloc).
Behaves similarly to regular `krealloc()`: if **ptr** is NULL or ZERO_SIZE_PTR,
it's the equivalent of [`devm_kmalloc()`](#c-devm_kmalloc). If new_size is zero, it frees the
previously allocated memory and returns ZERO_SIZE_PTR. This function doesn't
change the order in which the release callback for the re-alloc'ed devres
will be called (except when falling back to [`devm_kmalloc()`](#c-devm_kmalloc) or when freeing
resources when new_size is zero). The contents of the memory are preserved
up to the lesser of new and old sizes.

#### <a id="c-devm_kstrdup"></a>`devm_kstrdup()`

```c
char * devm_kstrdup(struct device *dev, const char *s, gfp_t gfp)
```

Allocate resource managed space and copy an existing string into that.

**Parameters**

- `struct device *dev`: Device to allocate memory for
- `const char *s`: the string to duplicate
- `gfp_t gfp`: the GFP mask used in the [`devm_kmalloc()`](#c-devm_kmalloc) call when
  allocating memory

**Return**

Pointer to allocated string on success, NULL on failure.

#### <a id="c-devm_kstrdup_const"></a>`devm_kstrdup_const()`

```c
const char * devm_kstrdup_const(struct device *dev, const char *s, gfp_t gfp)
```

resource managed conditional string duplication

**Parameters**

- `struct device *dev`: device for which to duplicate the string
- `const char *s`: the string to duplicate
- `gfp_t gfp`: the GFP mask used in the [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) call when allocating memory

**Description**

Strings allocated by devm_kstrdup_const will be automatically freed when
the associated device is detached.

**Return**

Source string if it is in .rodata section otherwise it falls back to
devm_kstrdup.

#### <a id="c-devm_kvasprintf"></a>`devm_kvasprintf()`

```c
char * devm_kvasprintf(struct device *dev, gfp_t gfp, const char *fmt, va_list ap)
```

Allocate resource managed space and format a string into that.

**Parameters**

- `struct device *dev`: Device to allocate memory for
- `gfp_t gfp`: the GFP mask used in the [`devm_kmalloc()`](#c-devm_kmalloc) call when
  allocating memory
- `const char *fmt`: The `printf()`-style format string
- `va_list ap`: Arguments for the format string

**Return**

Pointer to allocated string on success, NULL on failure.

#### <a id="c-devm_kasprintf"></a>`devm_kasprintf()`

```c
char * devm_kasprintf(struct device *dev, gfp_t gfp, const char *fmt, ...)
```

Allocate resource managed space and format a string into that.

**Parameters**

- `struct device *dev`: Device to allocate memory for
- `gfp_t gfp`: the GFP mask used in the [`devm_kmalloc()`](#c-devm_kmalloc) call when
  allocating memory
- `const char *fmt`: The `printf()`-style format string
- `...`: Arguments for the format string

**Return**

Pointer to allocated string on success, NULL on failure.

#### <a id="c-devm_kfree"></a>`devm_kfree()`

```c
void devm_kfree(struct device *dev, const void *p)
```

Resource-managed kfree

**Parameters**

- `struct device *dev`: Device this memory belongs to
- `const void *p`: Memory to free

**Description**

Free memory allocated with [`devm_kmalloc()`](#c-devm_kmalloc).

#### <a id="c-devm_kmemdup"></a>`devm_kmemdup()`

```c
void * devm_kmemdup(struct device *dev, const void *src, size_t len, gfp_t gfp)
```

Resource-managed kmemdup

**Parameters**

- `struct device *dev`: Device this memory belongs to
- `const void *src`: Memory region to duplicate
- `size_t len`: Memory region length
- `gfp_t gfp`: GFP mask to use

**Description**

Duplicate region of a memory using resource managed kmalloc

#### <a id="c-devm_kmemdup_const"></a>`devm_kmemdup_const()`

```c
const void * devm_kmemdup_const(struct device *dev, const void *src, size_t len, gfp_t gfp)
```

conditionally duplicate and manage a region of memory

**Parameters**

- `struct device *dev`: Device this memory belongs to
- `const void *src`: memory region to duplicate
- `size_t len`: memory region length,
- `gfp_t gfp`: GFP mask to use

**Return**

source address if it is in .rodata or the return value of [`kmemdup()`](/kernel/internals/core-api/kernel-api.md#c-kmemdup)
to which the function falls back otherwise.

#### <a id="c-devm_get_free_pages"></a>`devm_get_free_pages()`

```c
unsigned long devm_get_free_pages(struct device *dev, gfp_t gfp_mask, unsigned int order)
```

Resource-managed __get_free_pages

**Parameters**

- `struct device *dev`: Device to allocate memory for
- `gfp_t gfp_mask`: Allocation gfp flags
- `unsigned int order`: Allocation size is (1 \<\< order) pages

**Description**

Managed get_free_pages.  Memory allocated with this function is
automatically freed on driver detach.

**Return**

Address of allocated memory on success, 0 on failure.

#### <a id="c-devm_free_pages"></a>`devm_free_pages()`

```c
void devm_free_pages(struct device *dev, unsigned long addr)
```

Resource-managed free_pages

**Parameters**

- `struct device *dev`: Device this memory belongs to
- `unsigned long addr`: Memory to free

**Description**

Free memory allocated with [`devm_get_free_pages()`](#c-devm_get_free_pages). Unlike free_pages,
there is no need to supply the **order**.

#### <a id="c-__devm_alloc_percpu"></a>`__devm_alloc_percpu()`

```c
void __percpu * __devm_alloc_percpu(struct device *dev, size_t size, size_t align)
```

Resource-managed alloc_percpu

**Parameters**

- `struct device *dev`: Device to allocate per-cpu memory for
- `size_t size`: Size of per-cpu memory to allocate
- `size_t align`: Alignment of per-cpu memory to allocate

**Description**

Managed alloc_percpu. Per-cpu memory allocated with this function is
automatically freed on driver detach.

**Return**

Pointer to allocated memory on success, NULL on failure.

---

# Component Helper for Aggregate Drivers

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> Reference for Component Helper for Aggregate Drivers.

<a id="rst-component-helper-for-aggregate-drivers"></a>
<a id="rst-component"></a>


The component helper allows drivers to collect a pile of sub-devices,
including their bound drivers, into an aggregate driver. Various subsystems
already provide functions to get hold of such components, e.g.
`of_clk_get_by_name()`. The component helper can be used when such a
subsystem-specific way to find a device is not available: The component
helper fills the niche of aggregate drivers for specific hardware, where
further standardization into a subsystem would not be practical. The common
example is when a logical device (e.g. a DRM display driver) is spread around
the SoC on various components (scanout engines, blending blocks, transcoders
for various outputs and so on).

The component helper also doesn't solve runtime dependencies, e.g. for system
suspend and resume operations. See also device links.

Components are registered using [`component_add()`](#c-component_add) and unregistered with
[`component_del()`](#c-component_del), usually from the driver's probe and disconnect functions.

Aggregate drivers first assemble a component match list of what they need
using [`component_match_add()`](#c-component_match_add). This is then registered as an aggregate driver
using [`component_master_add_with_match()`](#c-component_master_add_with_match), and unregistered using
[`component_master_del()`](#c-component_master_del).


<a id="rst-api"></a>

## API


#### <a id="c-struct-component_ops"></a>`struct component_ops`

callbacks for component drivers

**Definition**

```c
struct component_ops {
    int (*bind)(struct device *comp, struct device *master, void *master_data);
    void (*unbind)(struct device *comp, struct device *master, void *master_data);
};
```

**Members**

- `bind`: Called through [`component_bind_all()`](#c-component_bind_all) when the aggregate driver is
  ready to bind the overall driver.
- `unbind`: Called through [`component_unbind_all()`](#c-component_unbind_all) when the aggregate driver is
  ready to bind the overall driver, or when [`component_bind_all()`](#c-component_bind_all) fails
  part-ways through and needs to unbind some already bound components.

**Description**

Components are registered with [`component_add()`](#c-component_add) and unregistered with
[`component_del()`](#c-component_del).

#### <a id="c-struct-component_master_ops"></a>`struct component_master_ops`

callback for the aggregate driver

**Definition**

```c
struct component_master_ops {
    int (*bind)(struct device *master);
    void (*unbind)(struct device *master);
};
```

**Members**

- `bind`: Called when all components or the aggregate driver, as specified in
  the match list passed to [`component_master_add_with_match()`](#c-component_master_add_with_match), are
  ready. Usually there are 3 steps to bind an aggregate driver:

  1. Allocate a structure for the aggregate driver.

  2. Bind all components to the aggregate driver by calling
     [`component_bind_all()`](#c-component_bind_all) with the aggregate driver structure as opaque
     pointer data.

  3. Register the aggregate driver with the subsystem to publish its
     interfaces.

  Note that the lifetime of the aggregate driver does not align with
  any of the underlying [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) instances. Therefore devm cannot
  be used and all resources acquired or allocated in this callback must
  be explicitly released in the **unbind** callback.
- `unbind`: Called when either the aggregate driver, using
  [`component_master_del()`](#c-component_master_del), or one of its components, using
  [`component_del()`](#c-component_del), is unregistered.

**Description**

Aggregate drivers are registered with [`component_master_add_with_match()`](#c-component_master_add_with_match) and
unregistered with [`component_master_del()`](#c-component_master_del).

#### <a id="c-component_match_add"></a>`component_match_add()`

```c
void component_match_add(struct device *parent, struct component_match **matchptr, int (*compare)(struct device *, void *), void *compare_data)
```

add a component match entry

**Parameters**

- `struct device *parent`: device with the aggregate driver
- `struct component_match **matchptr`: pointer to the list of component matches
- `int (*compare)(struct device *, void *)`: compare function to match against all components
- `void *compare_data`: opaque pointer passed to the **compare** function

**Description**

Adds a new component match to the list stored in **matchptr**, which the **parent**
aggregate driver needs to function. The list of component matches pointed to
by **matchptr** must be initialized to NULL before adding the first match. This
only matches against components added with [`component_add()`](#c-component_add).

The allocated match list in **matchptr** is automatically released using devm
actions.

See also [`component_match_add_release()`](#c-component_match_add_release) and [`component_match_add_typed()`](#c-component_match_add_typed).



#### <a id="c-component_compare_of"></a>`component_compare_of()`

```c
int component_compare_of(struct device *dev, void *data)
```

A common component compare function for of_node

**Parameters**

- `struct device *dev`: component device
- `void *data`:

  **compare_data** from [`component_match_add_release()`](#c-component_match_add_release)

**Description**

A common compare function when compare_data is device of_node. e.g.
component_match_add_release(masterdev, `match`, component_release_of,
component_compare_of, component_dev_of_node)

#### <a id="c-component_release_of"></a>`component_release_of()`

```c
void component_release_of(struct device *dev, void *data)
```

A common component release function for of_node

**Parameters**

- `struct device *dev`: component device
- `void *data`:

  **compare_data** from [`component_match_add_release()`](#c-component_match_add_release)

**Description**

About the example, Please see [`component_compare_of()`](#c-component_compare_of).

#### <a id="c-component_compare_dev"></a>`component_compare_dev()`

```c
int component_compare_dev(struct device *dev, void *data)
```

A common component compare function for dev

**Parameters**

- `struct device *dev`: component device
- `void *data`:

  **compare_data** from [`component_match_add_release()`](#c-component_match_add_release)

**Description**

A common compare function when compare_data is struce device. e.g.
component_match_add(masterdev, `match`, component_compare_dev, component_dev)

#### <a id="c-component_compare_dev_name"></a>`component_compare_dev_name()`

```c
int component_compare_dev_name(struct device *dev, void *data)
```

A common component compare function for device name

**Parameters**

- `struct device *dev`: component device
- `void *data`:

  **compare_data** from [`component_match_add_release()`](#c-component_match_add_release)

**Description**

A common compare function when compare_data is device name string. e.g.
component_match_add(masterdev, `match`, component_compare_dev_name,
"component_dev_name")

#### <a id="c-component_match_add_release"></a>`component_match_add_release()`

```c
void component_match_add_release(struct device *parent, struct component_match **matchptr, void (*release)(struct device *, void *), int (*compare)(struct device *, void *), void *compare_data)
```

add a component match entry with release callback

**Parameters**

- `struct device *parent`: parent device of the aggregate driver
- `struct component_match **matchptr`: pointer to the list of component matches
- `void (*release)(struct device *, void *)`: release function for **compare_data**
- `int (*compare)(struct device *, void *)`: compare function to match against all components
- `void *compare_data`: opaque pointer passed to the **compare** function

**Description**

Adds a new component match to the list stored in **matchptr**, which the
aggregate driver needs to function. The list of component matches pointed to
by **matchptr** must be initialized to NULL before adding the first match. This
only matches against components added with [`component_add()`](#c-component_add).

The allocated match list in **matchptr** is automatically released using devm
actions, where upon **release** will be called to free any references held by
**compare_data**, e.g. when **compare_data** is a `device_node` that must be
released with [`of_node_put()`](/kernel/hardware/devicetree/kernel-api.md#c-of_node_put).

See also [`component_match_add()`](#c-component_match_add) and [`component_match_add_typed()`](#c-component_match_add_typed).

#### <a id="c-component_match_add_typed"></a>`component_match_add_typed()`

```c
void component_match_add_typed(struct device *parent, struct component_match **matchptr, int (*compare_typed)(struct device *, int, void *), void *compare_data)
```

add a component match entry for a typed component

**Parameters**

- `struct device *parent`: parent device of the aggregate driver
- `struct component_match **matchptr`: pointer to the list of component matches
- `int (*compare_typed)(struct device *, int, void *)`: compare function to match against all typed components
- `void *compare_data`: opaque pointer passed to the **compare** function

**Description**

Adds a new component match to the list stored in **matchptr**, which the
aggregate driver needs to function. The list of component matches pointed to
by **matchptr** must be initialized to NULL before adding the first match. This
only matches against components added with [`component_add_typed()`](#c-component_add_typed).

The allocated match list in **matchptr** is automatically released using devm
actions.

See also [`component_match_add_release()`](#c-component_match_add_release) and [`component_match_add_typed()`](#c-component_match_add_typed).

#### <a id="c-component_master_add_with_match"></a>`component_master_add_with_match()`

```c
int component_master_add_with_match(struct device *parent, const struct component_master_ops *ops, struct component_match *match)
```

register an aggregate driver

**Parameters**

- `struct device *parent`: parent device of the aggregate driver
- `const struct component_master_ops *ops`: callbacks for the aggregate driver
- `struct component_match *match`: component match list for the aggregate driver

**Description**

Registers a new aggregate driver consisting of the components added to **match**
by calling one of the [`component_match_add()`](#c-component_match_add) functions. Once all components in
**match** are available, it will be assembled by calling
[`component_master_ops.bind`](#c-struct-component_master_ops) from **ops**. Must be unregistered by calling
[`component_master_del()`](#c-component_master_del).

#### <a id="c-component_master_del"></a>`component_master_del()`

```c
void component_master_del(struct device *parent, const struct component_master_ops *ops)
```

unregister an aggregate driver

**Parameters**

- `struct device *parent`: parent device of the aggregate driver
- `const struct component_master_ops *ops`: callbacks for the aggregate driver

**Description**

Unregisters an aggregate driver registered with
[`component_master_add_with_match()`](#c-component_master_add_with_match). If necessary the aggregate driver is first
disassembled by calling [`component_master_ops.unbind`](#c-struct-component_master_ops) from **ops**.

#### <a id="c-component_unbind_all"></a>`component_unbind_all()`

```c
void component_unbind_all(struct device *parent, void *data)
```

unbind all components of an aggregate driver

**Parameters**

- `struct device *parent`: parent device of the aggregate driver
- `void *data`: opaque pointer, passed to all components

**Description**

Unbinds all components of the aggregate device by passing **data** to their
[`component_ops.unbind`](#c-struct-component_ops) functions. Should be called from
[`component_master_ops.unbind`](#c-struct-component_master_ops).

#### <a id="c-component_bind_all"></a>`component_bind_all()`

```c
int component_bind_all(struct device *parent, void *data)
```

bind all components of an aggregate driver

**Parameters**

- `struct device *parent`: parent device of the aggregate driver
- `void *data`: opaque pointer, passed to all components

**Description**

Binds all components of the aggregate **dev** by passing **data** to their
[`component_ops.bind`](#c-struct-component_ops) functions. Should be called from
[`component_master_ops.bind`](#c-struct-component_master_ops).

#### <a id="c-component_add_typed"></a>`component_add_typed()`

```c
int component_add_typed(struct device *dev, const struct component_ops *ops, int subcomponent)
```

register a component

**Parameters**

- `struct device *dev`: component device
- `const struct component_ops *ops`: component callbacks
- `int subcomponent`: nonzero identifier for subcomponents

**Description**

Register a new component for **dev**. Functions in **ops** will be call when the
aggregate driver is ready to bind the overall driver by calling
[`component_bind_all()`](#c-component_bind_all). See also [`struct component_ops`](#c-struct-component_ops).

**subcomponent** must be nonzero and is used to differentiate between multiple
components registered on the same device **dev**. These components are match
using [`component_match_add_typed()`](#c-component_match_add_typed).

The component needs to be unregistered at driver unload/disconnect by
calling [`component_del()`](#c-component_del).

See also [`component_add()`](#c-component_add).

#### <a id="c-component_add"></a>`component_add()`

```c
int component_add(struct device *dev, const struct component_ops *ops)
```

register a component

**Parameters**

- `struct device *dev`: component device
- `const struct component_ops *ops`: component callbacks

**Description**

Register a new component for **dev**. Functions in **ops** will be called when the
aggregate driver is ready to bind the overall driver by calling
[`component_bind_all()`](#c-component_bind_all). See also [`struct component_ops`](#c-struct-component_ops).

The component needs to be unregistered at driver unload/disconnect by
calling [`component_del()`](#c-component_del).

See also [`component_add_typed()`](#c-component_add_typed) for a variant that allows multiple different
components on the same device.

#### <a id="c-component_del"></a>`component_del()`

```c
void component_del(struct device *dev, const struct component_ops *ops)
```

unregister a component

**Parameters**

- `struct device *dev`: component device
- `const struct component_ops *ops`: component callbacks

**Description**

Unregister a component added with [`component_add()`](#c-component_add). If the component is bound
into an aggregate driver, this will force the entire aggregate driver, including
all its components, to be unbound.

---

# Kernel Connector

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> Kernel connector - new netlink based userspace <-> kernel space easy to use communication module.

<a id="rst-kernel-connector"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Kernel connector - new netlink based userspace &lt;-&gt; kernel space easy to use communication module.

The Connector driver makes it easy to connect various agents using a netlink based network.  One must register a callback and an identifier. When the driver receives a special netlink message with the appropriate identifier, the appropriate callback will be called.

From the userspace point of view it's quite straightforward:

> - socket();
>
> - bind();
>
> - send();
>
> - recv();

But if kernelspace wants to use the full power of such connections, the driver writer must create special sockets, must know about struct sk_buff handling, etc...  The Connector driver allows any kernelspace agents to use netlink based networking for inter-process communication in a significantly easier way:



```text
int cn_add_callback(const struct cb_id *id, char *name, void (*callback) (struct cn_msg *, struct netlink_skb_parms *));
void cn_netlink_send_mult(struct cn_msg *msg, u16 len, u32 portid, u32 __group, int gfp_mask);
void cn_netlink_send(struct cn_msg *msg, u32 portid, u32 __group, int gfp_mask);

struct cb_id
{
      __u32                   idx;
      __u32                   val;
};
```

idx and val are unique identifiers which must be registered in the connector.h header for in-kernel usage.  `void (*callback) (void *)` is a callback function which will be called when a message with above idx.val is received by the connector core.  The argument for that function must be dereferenced to `struct cn_msg *`:



```text
struct cn_msg
{
      struct cb_id            id;

      __u32                   seq;
      __u32                   ack;

      __u16                   len;    /* Length of the following data */
      __u16                   flags;
      __u8                    data[0];
};
```

<a id="rst-connector-interfaces"></a>

## Connector interfaces

> 
> #### <a id="c-cn_add_callback"></a>`cn_add_callback()`
>
> ```c
> int cn_add_callback(const struct cb_id *id, const char *name, void (*callback)(struct cn_msg *, struct netlink_skb_parms *))
> ```
>
> Registers new callback with connector core.
>
> **Parameters**
>
> - `const struct cb_id *id`: unique connector's user identifier.
>   It must be registered in connector.h for legal
>   in-kernel users.
> - `const char *name`: connector's callback symbolic name.
> - `void (*callback)(struct cn_msg *, struct netlink_skb_parms *)`: connector's callback.
>   parameters are `cn_msg` and the sender's credentials
>
> #### <a id="c-cn_del_callback"></a>`cn_del_callback()`
>
> ```c
> void cn_del_callback(const struct cb_id *id)
> ```
>
> Unregisters new callback with connector core.
>
> **Parameters**
>
> - `const struct cb_id *id`: unique connector's user identifier.
>
> #### <a id="c-cn_netlink_send_mult"></a>`cn_netlink_send_mult()`
>
> ```c
> int cn_netlink_send_mult(struct cn_msg *msg, u16 len, u32 portid, u32 group, gfp_t gfp_mask, netlink_filter_fn filter, void *filter_data)
> ```
>
> Sends message to the specified groups.
>
> **Parameters**
>
> - `struct cn_msg *msg`: message header(with attached data).
> - `u16 len`: Number of **msg** to be sent.
> - `u32 portid`: destination port.
>   If non-zero the message will be sent to the given port,
>   which should be set to the original sender.
> - `u32 group`: destination group.
>   If **portid** and **group** is zero, then appropriate group will
>   be searched through all registered connector users, and
>   message will be delivered to the group which was created
>   for user with the same ID as in **msg**.
>   If **group** is not zero, then message will be delivered
>   to the specified group.
> - `gfp_t gfp_mask`: GFP mask.
> - `netlink_filter_fn filter`: Filter function to be used at netlink layer.
> - `void *filter_data`: Filter data to be supplied to the filter function
>
> **Description**
>
> It can be safely called from softirq context, but may silently
> fail under strong memory pressure.
>
> If there are no listeners for given group `-ESRCH` can be returned.
>
> #### <a id="c-cn_netlink_send"></a>`cn_netlink_send()`
>
> ```c
> int cn_netlink_send(struct cn_msg *msg, u32 portid, u32 group, gfp_t gfp_mask)
> ```
>
> Sends message to the specified groups.
>
> **Parameters**
>
> - `struct cn_msg *msg`: message header(with attached data).
> - `u32 portid`: destination port.
>   If non-zero the message will be sent to the given port,
>   which should be set to the original sender.
> - `u32 group`: destination group.
>   If **portid** and **group** is zero, then appropriate group will
>   be searched through all registered connector users, and
>   message will be delivered to the group which was created
>   for user with the same ID as in **msg**.
>   If **group** is not zero, then message will be delivered
>   to the specified group.
> - `gfp_t gfp_mask`: GFP mask.
>
> **Description**
>
> It can be safely called from softirq context, but may silently
> fail under strong memory pressure.
>
> If there are no listeners for given group `-ESRCH` can be returned.
>
>
> - **Note:**
>
>   When registering new callback user, connector core assigns netlink group to the user which is equal to its id.idx.

<a id="rst-protocol-description"></a>

## Protocol description

The current framework offers a transport layer with fixed headers.  The recommended protocol which uses such a header is as following:

msg-&gt;seq and msg-&gt;ack are used to determine message genealogy.  When someone sends a message, they use a locally unique sequence and random acknowledge number.  The sequence number may be copied into nlmsghdr-&gt;nlmsg_seq too.

The sequence number is incremented with each message sent.

If you expect a reply to the message, then the sequence number in the received message MUST be the same as in the original message, and the acknowledge number MUST be the same + 1.

If we receive a message and its sequence number is not equal to one we are expecting, then it is a new message.  If we receive a message and its sequence number is the same as one we are expecting, but its acknowledge is not equal to the sequence number in the original message + 1, then it is a new message.

Obviously, the protocol header contains the above id.

The connector allows event notification in the following form: kernel driver or userspace process can ask connector to notify it when selected ids will be turned on or off (registered or unregistered its callback).  It is done by sending a special command to the connector driver (it also registers itself with id=\{-1, -1\}).

As example of this usage can be found in the cn_test.c module which uses the connector to request notification and to send messages.

<a id="rst-reliability"></a>

## Reliability

Netlink itself is not a reliable protocol.  That means that messages can be lost due to memory pressure or process' receiving queue overflowed, so caller is warned that it must be prepared.  That is why the struct cn_msg \[main connector's message header\] contains u32 seq and u32 ack fields.

<a id="rst-userspace-usage"></a>

## Userspace usage

2.6.14 has a new netlink socket implementation, which by default does not allow people to send data to netlink groups other than 1. So, if you wish to use a netlink socket (for example using connector) with a different group number, the userspace application must subscribe to that group first.  It can be achieved by the following pseudocode:



```text
s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);

l_local.nl_family = AF_NETLINK;
l_local.nl_groups = 12345;
l_local.nl_pid = 0;

if (bind(s, (struct sockaddr *)&l_local, sizeof(struct sockaddr_nl)) == -1) {
      perror("bind");
      close(s);
      return -1;
}

{
      int on = l_local.nl_groups;
      setsockopt(s, 270, 1, &on, sizeof(on));
}
```

Where 270 above is SOL_NETLINK, and 1 is a NETLINK_ADD_MEMBERSHIP socket option.  To drop a multicast subscription, one should call the above socket option with the NETLINK_DROP_MEMBERSHIP parameter which is defined as 0.

2.6.14 netlink code only allows to select a group which is less or equal to the maximum group number, which is used at netlink_kernel_create() time. In case of connector it is CN_NETLINK_USERS + 0xf, so if you want to use group number 12345, you must increment CN_NETLINK_USERS to that number. Additional 0xf numbers are allocated to be used by non-in-kernel users.

Due to this limitation, group 0xffffffff does not work now, so one can not use add/remove connector's group notifications, but as far as I know, only cn_test.c test module used it.

Some work in netlink area is still being done, so things can be changed in 2.6.15 timeframe, if it will happen, documentation will be updated for that kernel.

<a id="rst-code-samples"></a>

## Code samples

Sample code for a connector test module and user space can be found in samples/connector/. To build this code, enable CONFIG_CONNECTOR and CONFIG_SAMPLES.

---

# Console Drivers

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> The Linux kernel has 2 general types of console drivers. The first type is assigned by the kernel to all the virtual consoles during the boot process. This type will be called 'system driver', and only one system driver is allowed to…

<a id="rst-console-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The Linux kernel has 2 general types of console drivers.  The first type is assigned by the kernel to all the virtual consoles during the boot process. This type will be called 'system driver', and only one system driver is allowed to exist. The system driver is persistent and it can never be unloaded, though it may become inactive.

The second type has to be explicitly loaded and unloaded. This will be called 'modular driver' by this document. Multiple modular drivers can coexist at any time with each driver sharing the console with other drivers including the system driver. However, modular drivers cannot take over the console that is currently occupied by another modular driver. (Exception: Drivers that call do_take_over_console() will succeed in the takeover regardless of the type of driver occupying the consoles.) They can only take over the console that is occupied by the system driver. In the same token, if the modular driver is released by the console, the system driver will take over.

Modular drivers, from the programmer's point of view, have to call:



```text
do_take_over_console() - load and bind driver to console layer
give_up_console() - unload driver; it will only work if driver
                    is fully unbound
```

In newer kernels, the following are also available:



```text
do_register_con_driver()
do_unregister_con_driver()
```

If sysfs is enabled, the contents of /sys/class/vtconsole can be examined. This shows the console backends currently registered by the system which are named vtcon&lt;n&gt; where &lt;n&gt; is an integer from 0 to 15. Thus:



```text
ls /sys/class/vtconsole
.  ..  vtcon0  vtcon1
```

Each directory in /sys/class/vtconsole has 3 files:



```text
ls /sys/class/vtconsole/vtcon0
.  ..  bind  name  uevent
```

What do these files signify?

> 1. bind - this is a read/write file. It shows the status of the driver if read, or acts to bind or unbind the driver to the virtual consoles when written to. The possible values are:
>
>    - **0**
>
>      - means the driver is not bound and if echo'ed, commands the driver to unbind
>
>    - **1**
>
>      - means the driver is bound and if echo'ed, commands the driver to bind
>
> 2. name - read-only file. Shows the name of the driver in this format:
>
>
>
>    ```text
>    cat /sys/class/vtconsole/vtcon0/name
>    (S) VGA+
>
>        '(S)' stands for a (S)ystem driver, i.e., it cannot be directly
>        commanded to bind or unbind
>
>        'VGA+' is the name of the driver
>
>    cat /sys/class/vtconsole/vtcon1/name
>    (M) frame buffer device
>
>        In this case, '(M)' stands for a (M)odular driver, one that can be
>        directly commanded to bind or unbind.
>    ```
>
> 3. uevent - ignore this file

When unbinding, the modular driver is detached first, and then the system driver takes over the consoles vacated by the driver. Binding, on the other hand, will bind the driver to the consoles that are currently occupied by a system driver.

- **NOTE1:**

  Binding and unbinding must be selected in Kconfig. It's under:



  ```text
  Device Drivers ->
      Character devices ->
              Support for binding and unbinding console drivers
  ```

- **NOTE2:**

  If any of the virtual consoles are in KD_GRAPHICS mode, then binding or unbinding will not succeed. An example of an application that sets the console to KD_GRAPHICS is X.

How useful is this feature? This is very useful for console driver developers. By unbinding the driver from the console layer, one can unload the driver, make changes, recompile, reload and rebind the driver without any need for rebooting the kernel. For regular users who may want to switch from framebuffer console to VGA console and vice versa, this feature also makes this possible. (NOTE NOTE NOTE: Please read fbcon.txt under Documentation/fb for more details.)

<a id="rst-notes-for-developers"></a>

## Notes for developers

do_take_over_console() is now broken up into:



```text
do_register_con_driver()
do_bind_con_driver() - private function
```

give_up_console() is a wrapper to do_unregister_con_driver(), and a driver must be fully unbound for this call to succeed. con_is_bound() will check if the driver is bound or not.

<a id="rst-guidelines-for-console-driver-writers"></a>

## Guidelines for console driver writers

In order for binding to and unbinding from the console to properly work, console drivers must follow these guidelines:

1. All drivers, except system drivers, must call either do_register_con_driver() or do_take_over_console(). do_register_con_driver() will just add the driver to the console's internal list. It won't take over the console. do_take_over_console(), as it name implies, will also take over (or bind to) the console.

2. All resources allocated during con-&gt;con_init() must be released in con-&gt;con_deinit().

3. All resources allocated in con-&gt;con_startup() must be released when the driver, which was previously bound, becomes unbound.  The console layer does not have a complementary call to con-&gt;con_startup() so it's up to the driver to check when it's legal to release these resources. Calling con_is_bound() in con-&gt;con_deinit() will help.  If the call returned false(), then it's safe to release the resources.  This balance has to be ensured because con-&gt;con_startup() can be called again when a request to rebind the driver to the console arrives.

4. Upon exit of the driver, ensure that the driver is totally unbound. If the condition is satisfied, then the driver must call do_unregister_con_driver() or give_up_console().

5. do_unregister_con_driver() can also be called on conditions which make it impossible for the driver to service console requests.  This can happen with the framebuffer console that suddenly lost all of its drivers.

The current crop of console drivers should still work correctly, but binding and unbinding them may cause problems. With minimal fixes, these drivers can be made to work correctly.

Antonino Daplas &lt;[adaplas@pol.net](<mailto:adaplas@pol.net>)&gt;

---

# Device links

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> By default, the driver core only enforces dependencies between devices that are borne out of a parent/child relationship within the device hierarchy: When suspending, resuming or shutting down the system, devices are ordered based on this…

<a id="rst-device-links"></a>
<a id="rst-device-link"></a>

By default, the driver core only enforces dependencies between devices that are borne out of a parent/child relationship within the device hierarchy: When suspending, resuming or shutting down the system, devices are ordered based on this relationship, i.e. children are always suspended before their parent, and the parent is always resumed before its children.

Sometimes there is a need to represent device dependencies beyond the mere parent/child relationship, e.g. between siblings, and have the driver core automatically take care of them.

Secondly, the driver core by default does not enforce any driver presence dependencies, i.e. that one device must be bound to a driver before another one can probe or function correctly.

Often these two dependency types come together, so a device depends on another one both with regards to driver presence *and* with regards to suspend/resume and shutdown ordering.

Device links allow representation of such dependencies in the driver core.

In its standard or *managed* form, a device link combines *both* dependency types:  It guarantees correct suspend/resume and shutdown ordering between a "supplier" device and its "consumer" devices, and it guarantees driver presence on the supplier.  The consumer devices are not probed before the supplier is bound to a driver, and they're unbound before the supplier is unbound.

When driver presence on the supplier is irrelevant and only correct suspend/resume and shutdown ordering is needed, the device link may simply be set up with the `DL_FLAG_STATELESS` flag.  In other words, enforcing driver presence on the supplier is optional.

Another optional feature is runtime PM integration:  By setting the `DL_FLAG_PM_RUNTIME` flag on addition of the device link, the PM core is instructed to runtime resume the supplier and keep it active whenever and for as long as the consumer is runtime resumed.

<a id="rst-usage"></a>

## Usage

The earliest point in time when device links can be added is after `device_add()` has been called for the supplier and `device_initialize()` has been called for the consumer.

It is legal to add them later, but care must be taken that the system remains in a consistent state:  E.g. a device link cannot be added in the midst of a suspend/resume transition, so either commencement of such a transition needs to be prevented with `lock_system_sleep()`, or the device link needs to be added from a function which is guaranteed not to run in parallel to a suspend/resume transition, such as from a device `->probe` callback or a boot-time PCI quirk.

Another example for an inconsistent state would be a device link that represents a driver presence dependency, yet is added from the consumer's `->probe` callback while the supplier hasn't started to probe yet:  Had the driver core known about the device link earlier, it wouldn't have probed the consumer in the first place.  The onus is thus on the consumer to check presence of the supplier after adding the link, and defer probing on non-presence.  \[Note that it is valid to create a link from the consumer's `->probe` callback while the supplier is still probing, but the consumer must know that the supplier is functional already at the link creation time (that is the case, for instance, if the consumer has just acquired some resources that would not have been available had the supplier not been functional then).\]

If a device link with `DL_FLAG_STATELESS` set (i.e. a stateless device link) is added in the `->probe` callback of the supplier or consumer driver, it is typically deleted in its `->remove` callback for symmetry.  That way, if the driver is compiled as a module, the device link is added on module load and orderly deleted on unload.  The same restrictions that apply to device link addition (e.g. exclusion of a parallel suspend/resume transition) apply equally to deletion.  Device links managed by the driver core are deleted automatically by it.

Several flags may be specified on device link addition, two of which have already been mentioned above:  `DL_FLAG_STATELESS` to express that no driver presence dependency is needed (but only correct suspend/resume and shutdown ordering) and `DL_FLAG_PM_RUNTIME` to express that runtime PM integration is desired.

Two other flags are specifically targeted at use cases where the device link is added from the consumer's `->probe` callback:  `DL_FLAG_RPM_ACTIVE` can be specified to runtime resume the supplier and prevent it from suspending before the consumer is runtime suspended.  `DL_FLAG_AUTOREMOVE_CONSUMER` causes the device link to be automatically purged when the consumer fails to probe or later unbinds.

Similarly, when the device link is added from supplier's `->probe` callback, `DL_FLAG_AUTOREMOVE_SUPPLIER` causes the device link to be automatically purged when the supplier fails to probe or later unbinds.

If neither `DL_FLAG_AUTOREMOVE_CONSUMER` nor `DL_FLAG_AUTOREMOVE_SUPPLIER` is set, `DL_FLAG_AUTOPROBE_CONSUMER` can be used to request the driver core to probe for a driver for the consumer driver on the link automatically after a driver has been bound to the supplier device.

Note, however, that any combinations of `DL_FLAG_AUTOREMOVE_CONSUMER`, `DL_FLAG_AUTOREMOVE_SUPPLIER` or `DL_FLAG_AUTOPROBE_CONSUMER` with `DL_FLAG_STATELESS` are invalid and cannot be used.

<a id="rst-limitations"></a>

## Limitations

Driver authors should be aware that a driver presence dependency for managed device links (i.e. when `DL_FLAG_STATELESS` is not specified on link addition) may cause probing of the consumer to be deferred indefinitely.  This can become a problem if the consumer is required to probe before a certain initcall level is reached.  Worse, if the supplier driver is blacklisted or missing, the consumer will never be probed.

Moreover, managed device links cannot be deleted directly.  They are deleted by the driver core when they are not necessary any more in accordance with the `DL_FLAG_AUTOREMOVE_CONSUMER` and `DL_FLAG_AUTOREMOVE_SUPPLIER` flags. However, stateless device links (i.e. device links with `DL_FLAG_STATELESS` set) are expected to be removed by whoever called `device_link_add()` to add them with the help of either `device_link_del()` or `device_link_remove()`.

Passing `DL_FLAG_RPM_ACTIVE` along with `DL_FLAG_STATELESS` to `device_link_add()` may cause the PM-runtime usage counter of the supplier device to remain nonzero after a subsequent invocation of either `device_link_del()` or `device_link_remove()` to remove the device link returned by it.  This happens if `device_link_add()` is called twice in a row for the same consumer-supplier pair without removing the link between these calls, in which case allowing the PM-runtime usage counter of the supplier to drop on an attempt to remove the link may cause it to be suspended while the consumer is still PM-runtime-active and that has to be avoided.  \[To work around this limitation it is sufficient to let the consumer runtime suspend at least once, or call `pm_runtime_set_suspended()` for it with PM-runtime disabled, between the `device_link_add()` and `device_link_del()` or `device_link_remove()` calls.\]

Sometimes drivers depend on optional resources.  They are able to operate in a degraded mode (reduced feature set or performance) when those resources are not present.  An example is an SPI controller that can use a DMA engine or work in PIO mode.  The controller can determine presence of the optional resources at probe time but on non-presence there is no way to know whether they will become available in the near future (due to a supplier driver probing) or never.  Consequently it cannot be determined whether to defer probing or not.  It would be possible to notify drivers when optional resources become available after probing, but it would come at a high cost for drivers as switching between modes of operation at runtime based on the availability of such resources would be much more complex than a mechanism based on probe deferral.  In any case optional resources are beyond the scope of device links.

<a id="rst-examples"></a>

## Examples

- An MMU device exists alongside a busmaster device, both are in the same power domain.  The MMU implements DMA address translation for the busmaster device and shall be runtime resumed and kept active whenever and as long as the busmaster device is active.  The busmaster device's driver shall not bind before the MMU is bound.  To achieve this, a device link with runtime PM integration is added from the busmaster device (consumer) to the MMU device (supplier).  The effect with regards to runtime PM is the same as if the MMU was the parent of the master device.

  The fact that both devices share the same power domain would normally suggest usage of a struct dev_pm_domain or struct generic_pm_domain, however these are not independent devices that happen to share a power switch, but rather the MMU device serves the busmaster device and is useless without it.  A device link creates a synthetic hierarchical relationship between the devices and is thus more apt.

- A Thunderbolt host controller comprises a number of PCIe hotplug ports and an NHI device to manage the PCIe switch.  On resume from system sleep, the NHI device needs to re-establish PCI tunnels to attached devices before the hotplug ports can resume.  If the hotplug ports were children of the NHI, this resume order would automatically be enforced by the PM core, but unfortunately they're aunts.  The solution is to add device links from the hotplug ports (consumers) to the NHI device (supplier).  A driver presence dependency is not necessary for this use case.

- Discrete GPUs in hybrid graphics laptops often feature an HDA controller for HDMI/DP audio.  In the device hierarchy the HDA controller is a sibling of the VGA device, yet both share the same power domain and the HDA controller is only ever needed when an HDMI/DP display is attached to the VGA device.  A device link from the HDA controller (consumer) to the VGA device (supplier) aptly represents this relationship.

- ACPI allows definition of a device start order by way of \_DEP objects. A classical example is when ACPI power management methods on one device are implemented in terms of I<sup>2</sup>C accesses and require a specific I<sup>2</sup>C controller to be present and functional for the power management of the device in question to work.

- In some SoCs a functional dependency exists from display, video codec and video processing IP cores on transparent memory access IP cores that handle burst access and compression/decompression.

<a id="rst-alternatives"></a>

## Alternatives

- A struct dev_pm_domain can be used to override the bus, class or device type callbacks.  It is intended for devices sharing a single on/off switch, however it does not guarantee a specific suspend/resume ordering, this needs to be implemented separately. It also does not by itself track the runtime PM status of the involved devices and turn off the power switch only when all of them are runtime suspended.  Furthermore it cannot be used to enforce a specific shutdown ordering or a driver presence dependency.

- A struct generic_pm_domain is a lot more heavyweight than a device link and does not allow for shutdown ordering or driver presence dependencies.  It also cannot be used on ACPI systems.

<a id="rst-implementation"></a>

## Implementation

The device hierarchy, which -- as the name implies -- is a tree, becomes a directed acyclic graph once device links are added.

Ordering of these devices during suspend/resume is determined by the dpm_list.  During shutdown it is determined by the devices_kset.  With no device links present, the two lists are a flattened, one-dimensional representations of the device tree such that a device is placed behind all its ancestors.  That is achieved by traversing the ACPI namespace or OpenFirmware device tree top-down and appending devices to the lists as they are discovered.

Once device links are added, the lists need to satisfy the additional constraint that a device is placed behind all its suppliers, recursively. To ensure this, upon addition of the device link the consumer and the entire sub-graph below it (all children and consumers of the consumer) are moved to the end of the list.  (Call to `device_reorder_to_tail()` from `device_link_add()`.)

To prevent introduction of dependency loops into the graph, it is verified upon device link addition that the supplier is not dependent on the consumer or any children or consumers of the consumer. (Call to `device_is_dependent()` from `device_link_add()`.) If that constraint is violated, `device_link_add()` will return `NULL` and a `WARNING` will be logged.

Notably this also prevents the addition of a device link from a parent device to a child.  However the converse is allowed, i.e. a device link from a child to a parent.  Since the driver core already guarantees correct suspend/resume and shutdown ordering between parent and child, such a device link only makes sense if a driver presence dependency is needed on top of that.  In this case driver authors should weigh carefully if a device link is at all the right tool for the purpose. A more suitable approach might be to simply use deferred probing or add a device flag causing the parent driver to be probed before the child one.

<a id="rst-state-machine"></a>

## State machine


#### <a id="c-enum-device_link_state"></a>`enum device_link_state`

Device link states.

**Constants**

- `DL_STATE_NONE`: The presence of the drivers is not being tracked.
- `DL_STATE_DORMANT`: None of the supplier/consumer drivers is present.
- `DL_STATE_AVAILABLE`: The supplier driver is present, but the consumer is not.
- `DL_STATE_CONSUMER_PROBE`: The consumer is probing (supplier driver present).
- `DL_STATE_ACTIVE`: Both the supplier and consumer drivers are present.
- `DL_STATE_SUPPLIER_UNBIND`: The supplier driver is unbinding.




```text
                .=============================.
                |                             |
                v                             |
DORMANT <=> AVAILABLE <=> CONSUMER_PROBE => ACTIVE
   ^                                          |
   |                                          |
   '============ SUPPLIER_UNBIND <============'
```

- The initial state of a device link is automatically determined by `device_link_add()` based on the driver presence on the supplier and consumer.  If the link is created before any devices are probed, it is set to `DL_STATE_DORMANT`.

- When a supplier device is bound to a driver, links to its consumers progress to `DL_STATE_AVAILABLE`. (Call to `device_links_driver_bound()` from `driver_bound()`.)

- Before a consumer device is probed, presence of supplier drivers is verified by checking the consumer device is not in the wait_for_suppliers list and by checking that links to suppliers are in `DL_STATE_AVAILABLE` state.  The state of the links is updated to `DL_STATE_CONSUMER_PROBE`. (Call to `device_links_check_suppliers()` from `really_probe()`.) This prevents the supplier from unbinding. (Call to `wait_for_device_probe()` from `device_links_unbind_consumers()`.)

- If the probe fails, links to suppliers revert back to `DL_STATE_AVAILABLE`. (Call to `device_links_no_driver()` from `really_probe()`.)

- If the probe succeeds, links to suppliers progress to `DL_STATE_ACTIVE`. (Call to `device_links_driver_bound()` from `driver_bound()`.)

- When the consumer's driver is later on removed, links to suppliers revert back to `DL_STATE_AVAILABLE`. (Call to `__device_links_no_driver()` from `device_links_driver_cleanup()`, which in turn is called from `__device_release_driver()`.)

- Before a supplier's driver is removed, links to consumers that are not bound to a driver are updated to `DL_STATE_SUPPLIER_UNBIND`. (Call to `device_links_busy()` from `__device_release_driver()`.) This prevents the consumers from binding. (Call to `device_links_check_suppliers()` from `really_probe()`.) Consumers that are bound are freed from their driver; consumers that are probing are waited for until they are done. (Call to `device_links_unbind_consumers()` from `__device_release_driver()`.) Once all links to consumers are in `DL_STATE_SUPPLIER_UNBIND` state, the supplier driver is released and the links revert to `DL_STATE_DORMANT`. (Call to `device_links_driver_cleanup()` from `__device_release_driver()`.)

<a id="rst-api"></a>

## API

See device_link_add(), device_link_del() and device_link_remove().

---

# Frame Buffer Library

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> The frame buffer drivers depend heavily on four data structures. These structures are declared in include/linux/fb.h. They are fb_info, fb_var_screeninfo, fb_fix_screeninfo and fb_monospecs. The last three can be made available to and from…

<a id="rst-frame-buffer-library"></a>

The frame buffer drivers depend heavily on four data structures. These structures are declared in include/linux/fb.h. They are fb_info, fb_var_screeninfo, fb_fix_screeninfo and fb_monospecs. The last three can be made available to and from userland.

fb_info defines the current state of a particular video card. Inside fb_info, there exists a fb_ops structure which is a collection of needed functions to make fbdev and fbcon work. fb_info is only visible to the kernel.

fb_var_screeninfo is used to describe the features of a video card that are user defined. With fb_var_screeninfo, things such as depth and the resolution may be defined.

The next structure is fb_fix_screeninfo. This defines the properties of a card that are created when a mode is set and can't be changed otherwise. A good example of this is the start of the frame buffer memory. This "locks" the address of the frame buffer memory, so that it cannot be changed or moved.

The last structure is fb_monospecs. In the old API, there was little importance for fb_monospecs. This allowed for forbidden things such as setting a mode of 800x600 on a fix frequency monitor. With the new API, fb_monospecs prevents such things, and if used correctly, can prevent a monitor from being cooked. fb_monospecs will not be useful until kernels 2.5.x.

<a id="rst-frame-buffer-memory"></a>

## Frame Buffer Memory


#### <a id="c-register_framebuffer"></a>`register_framebuffer()`

```c
int register_framebuffer(struct fb_info *fb_info)
```

registers a frame buffer device

**Parameters**

- `struct fb_info *fb_info`: frame buffer info structure

**Description**

Registers a frame buffer device **fb_info**.

Returns negative errno on error, or zero for success.

#### <a id="c-unregister_framebuffer"></a>`unregister_framebuffer()`

```c
void unregister_framebuffer(struct fb_info *fb_info)
```

releases a frame buffer device

**Parameters**

- `struct fb_info *fb_info`: frame buffer info structure

**Description**

Unregisters a frame buffer device **fb_info**.

Returns negative errno on error, or zero for success.

This function will also notify the framebuffer console
to release the driver.

This is meant to be called within a driver's [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)
function. If this is called outside [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit), ensure
that the driver implements `fb_open()` and `fb_release()` to
check that no processes are using the device.

#### <a id="c-devm_register_framebuffer"></a>`devm_register_framebuffer()`

```c
int devm_register_framebuffer(struct device *dev, struct fb_info *fb_info)
```

resource-managed frame buffer device registration

**Parameters**

- `struct device *dev`: device the framebuffer belongs to
- `struct fb_info *fb_info`: frame buffer info structure

**Description**

Registers a frame buffer device **fb_info** to device **dev**.

Returns negative errno on error, or zero for success.

#### <a id="c-fb_set_suspend"></a>`fb_set_suspend()`

```c
void fb_set_suspend(struct fb_info *info, int state)
```

low level driver signals suspend

**Parameters**

- `struct fb_info *info`: framebuffer affected
- `int state`: 0 = resuming, !=0 = suspending

**Description**

This is meant to be used by low level drivers to
signal suspend/resume to the core & clients.
It must be called with the console semaphore held


<a id="rst-frame-buffer-colormap"></a>

## Frame Buffer Colormap


#### <a id="c-fb_dealloc_cmap"></a>`fb_dealloc_cmap()`

```c
void fb_dealloc_cmap(struct fb_cmap *cmap)
```

deallocate a colormap

**Parameters**

- `struct fb_cmap *cmap`: frame buffer colormap structure

**Description**

Deallocates a colormap that was previously allocated with
`fb_alloc_cmap()`.

#### <a id="c-fb_copy_cmap"></a>`fb_copy_cmap()`

```c
int fb_copy_cmap(const struct fb_cmap *from, struct fb_cmap *to)
```

copy a colormap

**Parameters**

- `const struct fb_cmap *from`: frame buffer colormap structure
- `struct fb_cmap *to`: frame buffer colormap structure

**Description**

Copy contents of colormap from **from** to **to**.

#### <a id="c-fb_set_cmap"></a>`fb_set_cmap()`

```c
int fb_set_cmap(struct fb_cmap *cmap, struct fb_info *info)
```

set the colormap

**Parameters**

- `struct fb_cmap *cmap`: frame buffer colormap structure
- `struct fb_info *info`: frame buffer info structure

**Description**

Sets the colormap **cmap** for a screen of device **info**.

Returns negative errno on error, or zero on success.

#### <a id="c-fb_default_cmap"></a>`fb_default_cmap()`

```c
const struct fb_cmap * fb_default_cmap(int len)
```

get default colormap

**Parameters**

- `int len`: size of palette for a depth

**Description**

Gets the default colormap for a specific screen depth.  **len**
is the size of the palette for a particular screen depth.

Returns pointer to a frame buffer colormap structure.

#### <a id="c-fb_invert_cmaps"></a>`fb_invert_cmaps()`

```c
void fb_invert_cmaps(void)
```

invert all defaults colormaps

**Parameters**

- `void`: no arguments

**Description**

Invert all default colormaps.


<a id="rst-frame-buffer-video-mode-database"></a>

## Frame Buffer Video Mode Database


#### <a id="c-fb_try_mode"></a>`fb_try_mode()`

```c
int fb_try_mode(struct fb_var_screeninfo *var, struct fb_info *info, const struct fb_videomode *mode, unsigned int bpp)
```

test a video mode

**Parameters**

- `struct fb_var_screeninfo *var`: frame buffer user defined part of display
- `struct fb_info *info`: frame buffer info structure
- `const struct fb_videomode *mode`: frame buffer video mode structure
- `unsigned int bpp`: color depth in bits per pixel

**Description**

Tries a video mode to test it's validity for device **info**.

Returns 1 on success.

#### <a id="c-fb_delete_videomode"></a>`fb_delete_videomode()`

```c
void fb_delete_videomode(const struct fb_videomode *mode, struct list_head *head)
```

removed videomode entry from modelist

**Parameters**

- `const struct fb_videomode *mode`: videomode to remove
- `struct list_head *head`: struct list_head of modelist

**NOTES**

Will remove all matching mode entries



#### <a id="c-fb_find_mode"></a>`fb_find_mode()`

```c
int fb_find_mode(struct fb_var_screeninfo *var, struct fb_info *info, const char *mode_option, const struct fb_videomode *db, unsigned int dbsize, const struct fb_videomode *default_mode, unsigned int default_bpp)
```

finds a valid video mode

**Parameters**

- `struct fb_var_screeninfo *var`: frame buffer user defined part of display
- `struct fb_info *info`: frame buffer info structure
- `const char *mode_option`: string video mode to find
- `const struct fb_videomode *db`: video mode database
- `unsigned int dbsize`: size of **db**
- `const struct fb_videomode *default_mode`: default video mode to fall back to
- `unsigned int default_bpp`: default color depth in bits per pixel

**Description**

Finds a suitable video mode, starting with the specified mode
in **mode_option** with fallback to **default_mode**.  If
**default_mode** fails, all modes in the video mode database will
be tried.

Valid mode specifiers for **mode_option**:

```text
<xres>x<yres>[M][R][-<bpp>][@<refresh>][i][p][m]
```

or

```text
<name>[-<bpp>][@<refresh>]
```

with \<xres>, \<yres>, \<bpp> and \<refresh> decimal numbers and
\<name> a string.

If 'M' is present after yres (and before refresh/bpp if present),
the function will compute the timings using VESA(tm) Coordinated
Video Timings (CVT).  If 'R' is present after 'M', will compute with
reduced blanking (for flatpanels).  If 'i' or 'p' are present, compute
interlaced or progressive mode.  If 'm' is present, add margins equal
to 1.8% of xres rounded down to 8 pixels, and 1.8% of yres. The char
'i', 'p' and 'm' must be after 'M' and 'R'. Example:

```text
1024x768MR-8@60m - Reduced blank with margins at 60Hz.
```

**NOTE**

The passed struct **var** is _not_ cleared!  This allows you
to supply values for e.g. the grayscale and accel_flags fields.

Returns zero for failure, 1 if using specified **mode_option**,
2 if using specified **mode_option** with an ignored refresh rate,
3 if default mode is used, 4 if fall back to any valid mode.

#### <a id="c-fb_var_to_videomode"></a>`fb_var_to_videomode()`

```c
void fb_var_to_videomode(struct fb_videomode *mode, const struct fb_var_screeninfo *var)
```

convert fb_var_screeninfo to fb_videomode

**Parameters**

- `struct fb_videomode *mode`: pointer to struct fb_videomode
- `const struct fb_var_screeninfo *var`: pointer to struct fb_var_screeninfo

#### <a id="c-fb_videomode_to_var"></a>`fb_videomode_to_var()`

```c
void fb_videomode_to_var(struct fb_var_screeninfo *var, const struct fb_videomode *mode)
```

convert fb_videomode to fb_var_screeninfo

**Parameters**

- `struct fb_var_screeninfo *var`: pointer to struct fb_var_screeninfo
- `const struct fb_videomode *mode`: pointer to struct fb_videomode

#### <a id="c-fb_mode_is_equal"></a>`fb_mode_is_equal()`

```c
int fb_mode_is_equal(const struct fb_videomode *mode1, const struct fb_videomode *mode2)
```

compare 2 videomodes

**Parameters**

- `const struct fb_videomode *mode1`: first videomode
- `const struct fb_videomode *mode2`: second videomode

**Return**

1 if equal, 0 if not

#### <a id="c-fb_find_best_mode"></a>`fb_find_best_mode()`

```c
const struct fb_videomode * fb_find_best_mode(const struct fb_var_screeninfo *var, struct list_head *head)
```

find best matching videomode

**Parameters**

- `const struct fb_var_screeninfo *var`: pointer to struct fb_var_screeninfo
- `struct list_head *head`: pointer to struct list_head of modelist

**Return**

struct fb_videomode, NULL if none found

**Description**

IMPORTANT:
This function assumes that all modelist entries in
info->modelist are valid.

**NOTES**

Finds best matching videomode which has an equal or greater dimension than
var->xres and var->yres.  If more than 1 videomode is found, will return
the videomode with the highest refresh rate

#### <a id="c-fb_find_nearest_mode"></a>`fb_find_nearest_mode()`

```c
const struct fb_videomode * fb_find_nearest_mode(const struct fb_videomode *mode, struct list_head *head)
```

find closest videomode

**Parameters**

- `const struct fb_videomode *mode`: pointer to struct fb_videomode
- `struct list_head *head`: pointer to modelist

**Description**

Finds best matching videomode, smaller or greater in dimension.
If more than 1 videomode is found, will return the videomode with
the closest refresh rate.

#### <a id="c-fb_match_mode"></a>`fb_match_mode()`

```c
const struct fb_videomode * fb_match_mode(const struct fb_var_screeninfo *var, struct list_head *head)
```

find a videomode which exactly matches the timings in var

**Parameters**

- `const struct fb_var_screeninfo *var`: pointer to struct fb_var_screeninfo
- `struct list_head *head`: pointer to struct list_head of modelist

**Return**

struct fb_videomode, NULL if none found

#### <a id="c-fb_add_videomode"></a>`fb_add_videomode()`

```c
int fb_add_videomode(const struct fb_videomode *mode, struct list_head *head)
```

adds videomode entry to modelist

**Parameters**

- `const struct fb_videomode *mode`: videomode to add
- `struct list_head *head`: struct list_head of modelist

**NOTES**

Will only add unmatched mode entries

#### <a id="c-fb_destroy_modelist"></a>`fb_destroy_modelist()`

```c
void fb_destroy_modelist(struct list_head *head)
```

destroy modelist

**Parameters**

- `struct list_head *head`: struct list_head of modelist

#### <a id="c-fb_videomode_to_modelist"></a>`fb_videomode_to_modelist()`

```c
void fb_videomode_to_modelist(const struct fb_videomode *modedb, int num, struct list_head *head)
```

convert mode array to mode list

**Parameters**

- `const struct fb_videomode *modedb`: array of struct fb_videomode
- `int num`: number of entries in array
- `struct list_head *head`: struct list_head of modelist


<a id="rst-frame-buffer-macintosh-video-mode-database"></a>

## Frame Buffer Macintosh Video Mode Database


#### <a id="c-mac_vmode_to_var"></a>`mac_vmode_to_var()`

```c
int mac_vmode_to_var(int vmode, int cmode, struct fb_var_screeninfo *var)
```

converts vmode/cmode pair to var structure

**Parameters**

- `int vmode`: MacOS video mode
- `int cmode`: MacOS color mode
- `struct fb_var_screeninfo *var`: frame buffer video mode structure

**Description**

Converts a MacOS vmode/cmode pair to a frame buffer video
mode structure.

Returns negative errno on error, or zero for success.

#### <a id="c-mac_map_monitor_sense"></a>`mac_map_monitor_sense()`

```c
int mac_map_monitor_sense(int sense)
```

Convert monitor sense to vmode

**Parameters**

- `int sense`: Macintosh monitor sense number

**Description**

Converts a Macintosh monitor sense number to a MacOS
vmode number.

Returns MacOS vmode video mode number.

#### <a id="c-mac_find_mode"></a>`mac_find_mode()`

```c
int mac_find_mode(struct fb_var_screeninfo *var, struct fb_info *info, const char *mode_option, unsigned int default_bpp)
```

find a video mode

**Parameters**

- `struct fb_var_screeninfo *var`: frame buffer user defined part of display
- `struct fb_info *info`: frame buffer info structure
- `const char *mode_option`: video mode name (see mac_modedb\[\])
- `unsigned int default_bpp`: default color depth in bits per pixel

**Description**

Finds a suitable video mode.  Tries to set mode specified
by **mode_option**.  If the name of the wanted mode begins with
'mac', the Mac video mode database will be used, otherwise it
will fall back to the standard video mode database.

**Note**

- Function marked as __init and can only be used during

  system boot.

  Returns error code from fb_find_mode (see fb_find_mode
  function).


<a id="rst-frame-buffer-fonts"></a>

## Frame Buffer Fonts

Refer to the file lib/fonts/fonts.c for more information.

---

# Device drivers infrastructure

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> Reference for Device drivers infrastructure.

<a id="rst-device-drivers-infrastructure"></a>

<a id="rst-the-basic-device-driver-model-structures"></a>

## The Basic Device Driver-Model Structures


#### <a id="c-struct-subsys_interface"></a>`struct subsys_interface`

interfaces to device functions

**Definition**

```c
struct subsys_interface {
    const char *name;
    const struct bus_type *subsys;
    struct list_head node;
    int (*add_dev)(struct device *dev, struct subsys_interface *sif);
    void (*remove_dev)(struct device *dev, struct subsys_interface *sif);
};
```

**Members**

- `name`: name of the device function
- `subsys`: subsystem of the devices to attach to
- `node`: the list of functions registered at the subsystem
- `add_dev`: device hookup to device function handler
- `remove_dev`: device hookup to device function handler

**Description**

Simple interfaces attached to a subsystem. Multiple interfaces can
attach to a subsystem and its devices. Unlike drivers, they do not
exclusively claim or control devices. Interfaces usually represent
a specific functionality of a subsystem/class of devices.

#### <a id="c-struct-device_attribute"></a>`struct device_attribute`

Interface for exporting device attributes.

**Definition**

```c
struct device_attribute {
    struct attribute        attr;
    ssize_t (*show)(struct device *dev, struct device_attribute *attr, char *buf);
    ssize_t (*store)(struct device *dev, struct device_attribute *attr, const char *buf, size_t count);
};
```

**Members**

- `attr`: sysfs attribute definition.
- `show`: Show handler.
- `store`: Store handler.

#### <a id="c-struct-dev_ext_attribute"></a>`struct dev_ext_attribute`

Exported device attribute with extra context.

**Definition**

```c
struct dev_ext_attribute {
    struct device_attribute attr;
    void *var;
};
```

**Members**

- `attr`: Exported device attribute.
- `var`: Pointer to context.

#### <a id="c-DEVICE_ATTR"></a>`DEVICE_ATTR()`

```c
DEVICE_ATTR(_name, _mode, _show, _store)
```

Define a device attribute.

**Parameters**

- `_name`: Attribute name.
- `_mode`: File mode.
- `_show`: Show handler. Optional, but mandatory if attribute is readable.
- `_store`: Store handler. Optional, but mandatory if attribute is writable.

**Description**

Convenience macro for defining a struct device_attribute.

For example, `DEVICE_ATTR(foo, 0644, foo_show, foo_store);` expands to:

```c
struct device_attribute dev_attr_foo = {
        .attr   = { .name = "foo", .mode = 0644 },
        .show   = foo_show,
        .store  = foo_store,
};
```

#### <a id="c-DEVICE_ATTR_PREALLOC"></a>`DEVICE_ATTR_PREALLOC()`

```c
DEVICE_ATTR_PREALLOC(_name, _mode, _show, _store)
```

Define a preallocated device attribute.

**Parameters**

- `_name`: Attribute name.
- `_mode`: File mode.
- `_show`: Show handler. Optional, but mandatory if attribute is readable.
- `_store`: Store handler. Optional, but mandatory if attribute is writable.

**Description**

Like [`DEVICE_ATTR()`](#c-DEVICE_ATTR), but `SYSFS_PREALLOC` is set on **_mode**.

#### <a id="c-DEVICE_ATTR_RW"></a>`DEVICE_ATTR_RW()`

```c
DEVICE_ATTR_RW(_name)
```

Define a read-write device attribute.

**Parameters**

- `_name`: Attribute name.

**Description**

Like [`DEVICE_ATTR()`](#c-DEVICE_ATTR), but **_mode** is 0644, **_show** is \<_name>_show,
and **_store** is \<_name>_store.

#### <a id="c-DEVICE_ATTR_ADMIN_RW"></a>`DEVICE_ATTR_ADMIN_RW()`

```c
DEVICE_ATTR_ADMIN_RW(_name)
```

Define an admin-only read-write device attribute.

**Parameters**

- `_name`: Attribute name.

**Description**

Like [`DEVICE_ATTR_RW()`](#c-DEVICE_ATTR_RW), but **_mode** is 0600.

#### <a id="c-DEVICE_ATTR_RO"></a>`DEVICE_ATTR_RO()`

```c
DEVICE_ATTR_RO(_name)
```

Define a readable device attribute.

**Parameters**

- `_name`: Attribute name.

**Description**

Like [`DEVICE_ATTR()`](#c-DEVICE_ATTR), but **_mode** is 0444 and **_show** is \<_name>_show.

#### <a id="c-DEVICE_ATTR_ADMIN_RO"></a>`DEVICE_ATTR_ADMIN_RO()`

```c
DEVICE_ATTR_ADMIN_RO(_name)
```

Define an admin-only readable device attribute.

**Parameters**

- `_name`: Attribute name.

**Description**

Like [`DEVICE_ATTR_RO()`](#c-DEVICE_ATTR_RO), but **_mode** is 0400.

#### <a id="c-DEVICE_ATTR_WO"></a>`DEVICE_ATTR_WO()`

```c
DEVICE_ATTR_WO(_name)
```

Define an admin-only writable device attribute.

**Parameters**

- `_name`: Attribute name.

**Description**

Like [`DEVICE_ATTR()`](#c-DEVICE_ATTR), but **_mode** is 0200 and **_store** is \<_name>_store.

#### <a id="c-DEVICE_ULONG_ATTR"></a>`DEVICE_ULONG_ATTR()`

```c
DEVICE_ULONG_ATTR(_name, _mode, _var)
```

Define a device attribute backed by an unsigned long.

**Parameters**

- `_name`: Attribute name.
- `_mode`: File mode.
- `_var`: Identifier of unsigned long.

**Description**

Like [`DEVICE_ATTR()`](#c-DEVICE_ATTR), but **_show** and **_store** are automatically provided
such that reads and writes to the attribute from userspace affect **_var**.

#### <a id="c-DEVICE_INT_ATTR"></a>`DEVICE_INT_ATTR()`

```c
DEVICE_INT_ATTR(_name, _mode, _var)
```

Define a device attribute backed by an int.

**Parameters**

- `_name`: Attribute name.
- `_mode`: File mode.
- `_var`: Identifier of int.

**Description**

Like [`DEVICE_ULONG_ATTR()`](#c-DEVICE_ULONG_ATTR), but **_var** is an int.

#### <a id="c-DEVICE_BOOL_ATTR"></a>`DEVICE_BOOL_ATTR()`

```c
DEVICE_BOOL_ATTR(_name, _mode, _var)
```

Define a device attribute backed by a bool.

**Parameters**

- `_name`: Attribute name.
- `_mode`: File mode.
- `_var`: Identifier of bool.

**Description**

Like [`DEVICE_ULONG_ATTR()`](#c-DEVICE_ULONG_ATTR), but **_var** is a bool.

#### <a id="c-DEVICE_STRING_ATTR_RO"></a>`DEVICE_STRING_ATTR_RO()`

```c
DEVICE_STRING_ATTR_RO(_name, _mode, _var)
```

Define a device attribute backed by a r/o string.

**Parameters**

- `_name`: Attribute name.
- `_mode`: File mode.
- `_var`: Identifier of string.

**Description**

Like [`DEVICE_ULONG_ATTR()`](#c-DEVICE_ULONG_ATTR), but **_var** is a string. Because the length of the
string allocation is unknown, the attribute must be read-only.

#### <a id="c-enum-dl_dev_state"></a>`enum dl_dev_state`

Device driver presence tracking information.

**Constants**

- `DL_DEV_NO_DRIVER`: There is no driver attached to the device.
- `DL_DEV_PROBING`: A driver is probing.
- `DL_DEV_DRIVER_BOUND`: The driver has been bound to the device.
- `DL_DEV_UNBINDING`: The driver is unbinding from the device.

#### <a id="c-enum-device_removable"></a>`enum device_removable`

Whether the device is removable. The criteria for a device to be classified as removable is determined by its subsystem or bus.

**Constants**

- `DEVICE_REMOVABLE_NOT_SUPPORTED`: This attribute is not supported for this
  device (default).
- `DEVICE_REMOVABLE_UNKNOWN`: Device location is Unknown.
- `DEVICE_FIXED`: Device is not removable by the user.
- `DEVICE_REMOVABLE`: Device is removable by the user.

#### <a id="c-struct-dev_links_info"></a>`struct dev_links_info`

Device data related to device links.

**Definition**

```c
struct dev_links_info {
    struct list_head suppliers;
    struct list_head consumers;
    struct list_head defer_sync;
    enum dl_dev_state status;
};
```

**Members**

- `suppliers`: List of links to supplier devices.
- `consumers`: List of links to consumer devices.
- `defer_sync`: Hook to global list of devices that have deferred sync_state.
- `status`: Driver status information.

#### <a id="c-struct-dev_msi_info"></a>`struct dev_msi_info`

Device data related to MSI

**Definition**

```c
struct dev_msi_info {
    #ifdef CONFIG_GENERIC_MSI_IRQ;
        struct irq_domain       *domain;
        struct msi_device_data  *data;
    #endif;
};
```

**Members**

- `domain`: The MSI interrupt domain associated to the device
- `data`: Pointer to MSI device data

#### <a id="c-enum-device_physical_location_panel"></a>`enum device_physical_location_panel`

Describes which panel surface of the system's housing the device connection point resides on.

**Constants**

- `DEVICE_PANEL_TOP`: Device connection point is on the top panel.
- `DEVICE_PANEL_BOTTOM`: Device connection point is on the bottom panel.
- `DEVICE_PANEL_LEFT`: Device connection point is on the left panel.
- `DEVICE_PANEL_RIGHT`: Device connection point is on the right panel.
- `DEVICE_PANEL_FRONT`: Device connection point is on the front panel.
- `DEVICE_PANEL_BACK`: Device connection point is on the back panel.
- `DEVICE_PANEL_UNKNOWN`: The panel with device connection point is unknown.

#### <a id="c-enum-device_physical_location_vertical_position"></a>`enum device_physical_location_vertical_position`

Describes vertical position of the device connection point on the panel surface.

**Constants**

- `DEVICE_VERT_POS_UPPER`: Device connection point is at upper part of panel.
- `DEVICE_VERT_POS_CENTER`: Device connection point is at center part of panel.
- `DEVICE_VERT_POS_LOWER`: Device connection point is at lower part of panel.

#### <a id="c-enum-device_physical_location_horizontal_position"></a>`enum device_physical_location_horizontal_position`

Describes horizontal position of the device connection point on the panel surface.

**Constants**

- `DEVICE_HORI_POS_LEFT`: Device connection point is at left part of panel.
- `DEVICE_HORI_POS_CENTER`: Device connection point is at center part of panel.
- `DEVICE_HORI_POS_RIGHT`: Device connection point is at right part of panel.

#### <a id="c-struct-device_physical_location"></a>`struct device_physical_location`

Device data related to physical location of the device connection point.

**Definition**

```c
struct device_physical_location {
    enum device_physical_location_panel panel;
    enum device_physical_location_vertical_position vertical_position;
    enum device_physical_location_horizontal_position horizontal_position;
    bool dock;
    bool lid;
};
```

**Members**

- `panel`: Panel surface of the system's housing that the device connection
  point resides on.
- `vertical_position`: Vertical position of the device connection point within
  the panel.
- `horizontal_position`: Horizontal position of the device connection point
  within the panel.
- `dock`: Set if the device connection point resides in a docking station or
  port replicator.
- `lid`: Set if this device connection point resides on the lid of laptop
  system.

#### <a id="c-enum-struct_device_flags"></a>`enum struct_device_flags`

Flags in struct device

**Constants**

- `DEV_FLAG_READY_TO_PROBE`: If set then [`device_add()`](#c-device_add) has finished enough
  initialization that probe could be called.
- `DEV_FLAG_COUNT`: Number of defined struct_device_flags.

**Description**

Each flag should have a set of accessor functions created via
`__create_dev_flag_accessors()` for each access.

#### <a id="c-struct-device"></a>`struct device`

The basic device structure

**Definition**

```c
struct device {
        struct kobject kobj;
        struct device           *parent;
        struct device_private   *p;
        const char              *init_name;
        const struct device_type *type;
        const struct bus_type   *bus;
        struct device_driver *driver;
        void *platform_data;
        void *driver_data;
        struct {
            const char      *name;
            spinlock_t lock;
        } driver_override;
        struct mutex            mutex;
        struct dev_links_info   links;
        struct dev_pm_info      power;
        struct dev_pm_domain    *pm_domain;
    #ifdef CONFIG_ENERGY_MODEL;
        struct em_perf_domain   *em_pd;
    #endif;
    #ifdef CONFIG_PINCTRL;
        struct dev_pin_info     *pins;
    #endif;
        struct dev_msi_info     msi;
    #ifdef CONFIG_ARCH_HAS_DMA_OPS;
        const struct dma_map_ops *dma_ops;
    #endif;
        u64 *dma_mask;
        u64 coherent_dma_mask;
        u64 bus_dma_limit;
        const struct bus_dma_region *dma_range_map;
        struct device_dma_parameters *dma_parms;
        struct list_head        dma_pools;
    #ifdef CONFIG_DMA_DECLARE_COHERENT;
        struct dma_coherent_mem *dma_mem;
    #endif;
    #ifdef CONFIG_DMA_CMA;
        struct cma *cma_area;
    #endif;
    #ifdef CONFIG_SWIOTLB;
        struct io_tlb_mem *dma_io_tlb_mem;
    #endif;
    #ifdef CONFIG_SWIOTLB_DYNAMIC;
        struct list_head dma_io_tlb_pools;
        spinlock_t dma_io_tlb_lock;
        bool dma_uses_io_tlb;
    #endif;
        struct dev_archdata     archdata;
        struct device_node      *of_node;
        struct fwnode_handle    *fwnode;
    #ifdef CONFIG_NUMA;
        int numa_node;
    #endif;
        dev_t devt;
        u32 id;
        spinlock_t devres_lock;
        struct list_head        devres_head;
        const struct class      *class;
        const struct attribute_group **groups;
        void (*release)(struct device *dev);
        struct iommu_group      *iommu_group;
        struct dev_iommu        *iommu;
        struct device_physical_location *physical_location;
        enum device_removable   removable;
        bool offline_disabled:1;
        bool offline:1;
        bool of_node_reused:1;
        bool state_synced:1;
        bool can_match:1;
    #if defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_DEVICE) ||     defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU) ||     defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU_ALL);
        bool dma_coherent:1;
    #endif;
    #ifdef CONFIG_DMA_OPS_BYPASS;
        bool dma_ops_bypass : 1;
    #endif;
    #ifdef CONFIG_DMA_NEED_SYNC;
        bool dma_skip_sync:1;
    #endif;
    #ifdef CONFIG_IOMMU_DMA;
        bool dma_iommu:1;
    #endif;
        unsigned long flags[BITS_TO_LONGS(DEV_FLAG_COUNT)];
};
```

**Members**

- `kobj`: A top-level, abstract class from which other classes are derived.
- `parent`: The device's "parent" device, the device to which it is attached.
  In most cases, a parent device is some sort of bus or host
  controller. If parent is NULL, the device, is a top-level device,
  which is not usually what you want.
- `p`: Holds the private data of the driver core portions of the device.
  See the comment of the struct device_private for detail.
- `init_name`: Initial name of the device.
- `type`: The type of device.
  This identifies the device type and carries type-specific
  information.
- `bus`: Type of bus device is on.
- `driver`: Which driver has allocated this
- `platform_data`: Platform data specific to the device.
- `driver_data`: Private pointer for driver specific info.
- `driver_override`: Driver name to force a match.  Do not touch directly; use
  [`device_set_driver_override()`](#c-device_set_driver_override) instead.
- `mutex`: Mutex to synchronize calls to its driver.
- `links`: Links to suppliers and consumers of this device.
- `power`: For device power management.
  See Documentation/driver-api/pm/devices.rst for details.
- `pm_domain`: Provide callbacks that are executed during system suspend,
  hibernation, system resume and during runtime PM transitions
  along with subsystem-level and driver-level callbacks.
- `em_pd`: device's energy model performance domain
- `pins`: For device pin management.
  See Documentation/driver-api/pin-control.rst for details.
- `msi`: MSI related data
- `dma_ops`: DMA mapping operations for this device.
- `dma_mask`: Dma mask (if dma'ble device).
- `coherent_dma_mask`: Like dma_mask, but for alloc_coherent mapping as not all
  hardware supports 64-bit addresses for consistent allocations
  such descriptors.
- `bus_dma_limit`: Limit of an upstream bridge or bus which imposes a smaller
  DMA limit than the device itself supports.
- `dma_range_map`: map for DMA memory ranges relative to that of RAM
- `dma_parms`: A low level driver may set these to teach IOMMU code about
  segment limitations.
- `dma_pools`: Dma pools (if dma'ble device).
- `dma_mem`: Internal for coherent mem override.
- `cma_area`: Contiguous memory area for dma allocations
- `dma_io_tlb_mem`: Software IO TLB allocator.  Not for driver use.
- `dma_io_tlb_pools`: List of transient swiotlb memory pools.
- `dma_io_tlb_lock`: Protects changes to the list of active pools.
- `dma_uses_io_tlb`: `true` if device has used the software IO TLB.
- `archdata`: For arch-specific additions.
- `of_node`: Associated device tree node.
- `fwnode`: Associated device node supplied by platform firmware.
- `numa_node`: NUMA node this device is close to.
- `devt`: For creating the sysfs "dev".
- `id`: device instance
- `devres_lock`: Spinlock to protect the resource of the device.
- `devres_head`: The resources list of the device.
- `class`: The class of the device.
- `groups`: Optional attribute groups.
- `release`: Callback to free the device after all references have
  gone away. This should be set by the allocator of the
  device (i.e. the bus driver that discovered the device).
- `iommu_group`: IOMMU group the device belongs to.
- `iommu`: Per device generic IOMMU runtime data
- `physical_location`: Describes physical location of the device connection
  point in the system housing.
- `removable`: Whether the device can be removed from the system. This
  should be set by the subsystem / bus driver that discovered
  the device.
- `offline_disabled`: If set, the device is permanently online.
- `offline`: Set after successful invocation of bus type's .`offline()`.
- `of_node_reused`: Set if the device-tree node is shared with an ancestor
  device.
- `state_synced`: The hardware state of this device has been synced to match
  the software state of this device by calling the driver/bus
  `sync_state()` callback.
- `can_match`: The device has matched with a driver at least once or it is in
  a bus (like AMBA) which can't check for matching drivers until
  other devices probe successfully.
- `dma_coherent`: this particular device is dma coherent, even if the
  architecture supports non-coherent devices.
- `dma_ops_bypass`: If set to `true` then the dma_ops are bypassed for the
  streaming DMA operations (->map_* / ->unmap_* / ->sync_*),
  and optionall (if the coherent mask is large enough) also
  for dma allocations.  This flag is managed by the dma ops
  instance from ->dma_supported.
- `dma_skip_sync`: DMA sync operations can be skipped for coherent buffers.
- `dma_iommu`: Device is using default IOMMU implementation for DMA and
  doesn't rely on dma_ops structure.
- `flags`: DEV_FLAG_XXX flags. Use atomic bitfield operations to modify.

**Example**

- For devices on custom boards, as typical of embedded

  and SOC based hardware, Linux often uses platform_data to point
  to board-specific structures describing devices and how they
  are wired.  That can include what ports are available, chip
  variants, which GPIO pins act in what additional roles, and so
  on.  This shrinks the "Board Support Packages" (BSPs) and
  minimizes board-specific #ifdefs in drivers.

**Description**

At the lowest level, every device in a Linux system is represented by an
instance of struct device. The device structure contains the information
that the device model core needs to model the system. Most subsystems,
however, track additional information about the devices they host. As a
result, it is rare for devices to be represented by bare device structures;
instead, that structure, like kobject structures, is usually embedded within
a higher-level representation of the device.

#### <a id="c-struct-device_link"></a>`struct device_link`

Device link representation.

**Definition**

```c
struct device_link {
    struct device *supplier;
    struct list_head s_node;
    struct device *consumer;
    struct list_head c_node;
    struct device link_dev;
    enum device_link_state status;
    u32 flags;
    refcount_t rpm_active;
    struct kref kref;
    struct work_struct rm_work;
    bool supplier_preactivated;
};
```

**Members**

- `supplier`: The device on the supplier end of the link.
- `s_node`: Hook to the supplier device's list of links to consumers.
- `consumer`: The device on the consumer end of the link.
- `c_node`: Hook to the consumer device's list of links to suppliers.
- `link_dev`: device used to expose link details in sysfs
- `status`: The state of the link (with respect to the presence of drivers).
- `flags`: Link flags.
- `rpm_active`: Whether or not the consumer device is runtime-PM-active.
- `kref`: Count repeated addition of the same link.
- `rm_work`: Work structure used for removing the link.
- `supplier_preactivated`: Supplier has been made active before consumer probe.

#### <a id="c-device_set_driver_override"></a>`device_set_driver_override()`

```c
int device_set_driver_override(struct device *dev, const char *s)
```

Helper to set or clear driver override.

**Parameters**

- `struct device *dev`: Device to change
- `const char *s`: NUL-terminated string, new driver name to force a match, pass empty
  string to clear it ("" or "\n", where the latter is only for sysfs
  interface).

**Description**

Helper to set or clear driver override of a device.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-device_has_driver_override"></a>`device_has_driver_override()`

```c
bool device_has_driver_override(struct device *dev)
```

Check if a driver override has been set.

**Parameters**

- `struct device *dev`: device to check

**Description**

Returns true if a driver override has been set for this device.

#### <a id="c-device_match_driver_override"></a>`device_match_driver_override()`

```c
int device_match_driver_override(struct device *dev, const struct device_driver *drv)
```

Match a driver against the device's driver_override.

**Parameters**

- `struct device *dev`: device to check
- `const struct device_driver *drv`: driver to match against

**Description**

Returns > 0 if a driver override is set and matches the given driver, 0 if a
driver override is set but does not match, or \< 0 if a driver override is not
set at all.

#### <a id="c-device_iommu_mapped"></a>`device_iommu_mapped()`

```c
bool device_iommu_mapped(struct device *dev)
```

Returns true when the device DMA is translated by an IOMMU

**Parameters**

- `struct device *dev`: Device to perform the check on

#### <a id="c-dev_name"></a>`dev_name()`

```c
const char * dev_name(const struct device *dev)
```

Return a device's name.

**Parameters**

- `const struct device *dev`: Device with name to get.

**Return**

The kobject name of the device, or its initial name if unavailable.

#### <a id="c-dev_bus_name"></a>`dev_bus_name()`

```c
const char * dev_bus_name(const struct device *dev)
```

Return a device's bus/class name, if at all possible

**Parameters**

- `const struct device *dev`: struct device to get the bus/class name of

**Description**

Will return the name of the bus/class the device is attached to.  If it is
not attached to a bus/class, an empty string will be returned.

#### <a id="c-device_find_child_by_name"></a>`device_find_child_by_name()`

```c
struct device * device_find_child_by_name(struct device *parent, const char *name)
```

device iterator for locating a child device.

**Parameters**

- `struct device *parent`: parent struct device
- `const char *name`: name of the child device

**Description**

This is similar to the [`device_find_child()`](#c-device_find_child) function above, but it
returns a reference to a device that has the name **name**.

**NOTE**

you will need to drop the reference with [`put_device()`](#c-put_device) after use.

#### <a id="c-device_find_any_child"></a>`device_find_any_child()`

```c
struct device * device_find_any_child(struct device *parent)
```

device iterator for locating a child device, if any.

**Parameters**

- `struct device *parent`: parent struct device

**Description**

This is similar to the [`device_find_child()`](#c-device_find_child) function above, but it
returns a reference to a child device, if any.

**NOTE**

you will need to drop the reference with [`put_device()`](#c-put_device) after use.

#### <a id="c-device_lock_set_class"></a>`device_lock_set_class()`

```c
device_lock_set_class(dev, key)
```

Specify a temporary lock class while a device is attached to a driver

**Parameters**

- `dev`: device to modify
- `key`: lock class key data

**Description**

This must be called with the `device_lock()` already held, for example
from driver ->`probe()`. Take care to only override the default
lockdep_no_validate class.

#### <a id="c-device_lock_reset_class"></a>`device_lock_reset_class()`

```c
device_lock_reset_class(dev)
```

Return a device to the default lockdep novalidate state

**Parameters**

- `dev`: device to modify

**Description**

This must be called with the `device_lock()` already held, for example
from driver ->`remove()`.



#### <a id="c-struct-bus_type"></a>`struct bus_type`

The bus type of the device

**Definition**

```c
struct bus_type {
    const char              *name;
    const char              *dev_name;
    const struct attribute_group **bus_groups;
    const struct attribute_group **dev_groups;
    const struct attribute_group **drv_groups;
    int (*match)(struct device *dev, const struct device_driver *drv);
    int (*uevent)(const struct device *dev, struct kobj_uevent_env *env);
    int (*probe)(struct device *dev);
    void (*sync_state)(struct device *dev);
    void (*remove)(struct device *dev);
    void (*shutdown)(struct device *dev);
    const struct cpumask *(*irq_get_affinity)(struct device *dev, unsigned int irq_vec);
    int (*online)(struct device *dev);
    int (*offline)(struct device *dev);
    int (*suspend)(struct device *dev, pm_message_t state);
    int (*resume)(struct device *dev);
    int (*num_vf)(struct device *dev);
    int (*dma_configure)(struct device *dev);
    void (*dma_cleanup)(struct device *dev);
    const struct dev_pm_ops *pm;
    bool driver_override;
    bool need_parent_lock;
};
```

**Members**

- `name`: The name of the bus.
- `dev_name`: Used for subsystems to enumerate devices like ("foo`u`", dev->id).
- `bus_groups`: Default attributes of the bus.
- `dev_groups`: Default attributes of the devices on the bus.
- `drv_groups`: Default attributes of the device drivers on the bus.
- `match`: Called, perhaps multiple times, whenever a new device or driver
  is added for this bus. It should return a positive value if the
  given device can be handled by the given driver and zero
  otherwise. It may also return error code if determining that
  the driver supports the device is not possible. In case of
  -EPROBE_DEFER it will queue the device for deferred probing.
- `uevent`: Called when a device is added, removed, or a few other things
  that generate uevents to add the environment variables.
- `probe`: Called when a new device or driver add to this bus, and callback
  the specific driver's probe to initial the matched device.
- `sync_state`: Called to sync device state to software state after all the
  state tracking consumers linked to this device (present at
  the time of late_initcall) have successfully bound to a
  driver. If the device has no consumers, this function will
  be called at late_initcall_sync level. If the device has
  consumers that are never bound to a driver, this function
  will never get called until they do.
- `remove`: Called when a device removed from this bus.
- `shutdown`: Called at shut-down time to quiesce the device.
- `irq_get_affinity`: Get IRQ affinity mask for the device on this bus.
- `online`: Called to put the device back online (after offlining it).
- `offline`: Called to put the device offline for hot-removal. May fail.
- `suspend`: Called when a device on this bus wants to go to sleep mode.
- `resume`: Called to bring a device on this bus out of sleep mode.
- `num_vf`: Called to find out how many virtual functions a device on this
  bus supports.
- `dma_configure`: Called to setup DMA configuration on a device on
  this bus.
- `dma_cleanup`: Called to cleanup DMA configuration on a device on
  this bus.
- `pm`: Power management operations of this bus, callback the specific
  device driver's pm-ops.
- `driver_override`: Set to true if this bus supports the driver_override
  mechanism, which allows userspace to force a specific
  driver to bind to a device via a sysfs attribute.
- `need_parent_lock`: When probing or removing a device on this bus, the
  device core should lock the device's parent.

**Note**

- This callback may be invoked with or without the device

  lock held.

**Description**

A bus is a channel between the processor and one or more devices. For the
purposes of the device model, all devices are connected via a bus, even if
it is an internal, virtual, "platform" bus. Buses can plug into each other.
A USB controller is usually a PCI device, for example. The device model
represents the actual connections between buses and the devices they control.
A bus is represented by the bus_type structure. It contains the name, the
default attributes, the bus' methods, PM operations, and the driver core's
private data.

#### <a id="c-enum-bus_notifier_event"></a>`enum bus_notifier_event`

Bus Notifier events that have happened

**Constants**

- `BUS_NOTIFY_ADD_DEVICE`: device is added to this bus
- `BUS_NOTIFY_DEL_DEVICE`: device is about to be removed from this bus
- `BUS_NOTIFY_REMOVED_DEVICE`: device is successfully removed from this bus
- `BUS_NOTIFY_BIND_DRIVER`: a driver is about to be bound to this device on this bus
- `BUS_NOTIFY_BOUND_DRIVER`: a driver is successfully bound to this device on this bus
- `BUS_NOTIFY_UNBIND_DRIVER`: a driver is about to be unbound from this device on this bus
- `BUS_NOTIFY_UNBOUND_DRIVER`: a driver is successfully unbound from this device on this bus
- `BUS_NOTIFY_DRIVER_NOT_BOUND`: a driver failed to be bound to this device on this bus

**Description**

These are the value passed to a bus notifier when a specific event happens.

Note that bus notifiers are likely to be called with the device lock already
held by the driver core, so be careful in any notifier callback as to what
you do with the device structure.

All bus notifiers are called with the target struct device * as an argument.



#### <a id="c-struct-class"></a>`struct class`

device classes

**Definition**

```c
struct class {
    const char              *name;
    const struct attribute_group    **class_groups;
    const struct attribute_group    **dev_groups;
    int (*dev_uevent)(const struct device *dev, struct kobj_uevent_env *env);
    char *(*devnode)(const struct device *dev, umode_t *mode);
    void (*class_release)(const struct class *class);
    void (*dev_release)(struct device *dev);
    int (*shutdown_pre)(struct device *dev);
    const struct kobj_ns_type_operations *ns_type;
    const struct ns_common *(*namespace)(const struct device *dev);
    void (*get_ownership)(const struct device *dev, kuid_t *uid, kgid_t *gid);
    const struct dev_pm_ops *pm;
};
```

**Members**

- `name`: Name of the class.
- `class_groups`: Default attributes of this class.
- `dev_groups`: Default attributes of the devices that belong to the class.
- `dev_uevent`: Called when a device is added, removed from this class, or a
  few other things that generate uevents to add the environment
  variables.
- `devnode`: Callback to provide the devtmpfs.
- `class_release`: Called to release this class.
- `dev_release`: Called to release the device.
- `shutdown_pre`: Called at shut-down time before driver shutdown.
- `ns_type`: Callbacks so sysfs can detemine namespaces.
- `namespace`: Namespace of the device belongs to this class.
- `get_ownership`: Allows class to specify uid/gid of the sysfs directories
  for the devices belonging to the class. Usually tied to
  device's namespace.
- `pm`: The default device power management operations of this class.

**Description**

A class is a higher-level view of a device that abstracts out low-level
implementation details. Drivers may see a SCSI disk or an ATA disk, but,
at the class level, they are all simply disks. Classes allow user space
to work with devices based on what they do, rather than how they are
connected or how they work.



#### <a id="c-enum-probe_type"></a>`enum probe_type`

device driver probe type to try Device drivers may opt in for special handling of their respective probe routines. This tells the core what to expect and prefer.

**Constants**

- `PROBE_DEFAULT_STRATEGY`: Used by drivers that work equally well
  whether probed synchronously or asynchronously.
- `PROBE_PREFER_ASYNCHRONOUS`: Drivers for "slow" devices which
  probing order is not essential for booting the system may
  opt into executing their probes asynchronously.
- `PROBE_FORCE_SYNCHRONOUS`: Use this to annotate drivers that need
  their probe routines to run synchronously with driver and
  device registration (with the exception of -EPROBE_DEFER
  handling - re-probing always ends up being done asynchronously).

**Description**

Note that the end goal is to switch the kernel to use asynchronous
probing by default, so annotating drivers with
`PROBE_PREFER_ASYNCHRONOUS` is a temporary measure that allows us
to speed up boot process while we are validating the rest of the
drivers.

#### <a id="c-struct-device_driver"></a>`struct device_driver`

The basic device driver structure

**Definition**

```c
struct device_driver {
    const char              *name;
    const struct bus_type   *bus;
    struct module           *owner;
    const char              *mod_name;
    bool suppress_bind_attrs;
    enum probe_type probe_type;
    const struct of_device_id       *of_match_table;
    const struct acpi_device_id     *acpi_match_table;
    int (*probe) (struct device *dev);
    void (*sync_state)(struct device *dev);
    int (*remove) (struct device *dev);
    void (*shutdown) (struct device *dev);
    int (*suspend) (struct device *dev, pm_message_t state);
    int (*resume) (struct device *dev);
    const struct attribute_group **groups;
    const struct attribute_group **dev_groups;
    const struct dev_pm_ops *pm;
    void (*coredump) (struct device *dev);
    struct driver_private *p;
    struct {
        void (*post_unbind_rust)(struct device *dev);
    } p_cb;
};
```

**Members**

- `name`: Name of the device driver.
- `bus`: The bus which the device of this driver belongs to.
- `owner`: The module owner.
- `mod_name`: Used for built-in modules.
- `suppress_bind_attrs`: Disables bind/unbind via sysfs.
- `probe_type`: Type of the probe (synchronous or asynchronous) to use.
- `of_match_table`: The open firmware table.
- `acpi_match_table`: The ACPI match table.
- `probe`: Called to query the existence of a specific device,
  whether this driver can work with it, and bind the driver
  to a specific device.
- `sync_state`: Called to sync device state to software state after all the
  state tracking consumers linked to this device (present at
  the time of late_initcall) have successfully bound to a
  driver. If the device has no consumers, this function will
  be called at late_initcall_sync level. If the device has
  consumers that are never bound to a driver, this function
  will never get called until they do.
- `remove`: Called when the device is removed from the system to
  unbind a device from this driver.
- `shutdown`: Called at shut-down time to quiesce the device.
- `suspend`: Called to put the device to sleep mode. Usually to a
  low power state.
- `resume`: Called to bring a device from sleep mode.
- `groups`: Default attributes that get created by the driver core
  automatically.
- `dev_groups`: Additional attributes attached to device instance once
  it is bound to the driver.
- `pm`: Power management operations of the device which matched
  this driver.
- `coredump`: Called when sysfs entry is written to. The device driver
  is expected to call the dev_coredump API resulting in a
  uevent.
- `p`: Driver core's private data, no one other than the driver
  core can touch this.
- `p_cb`: Callbacks private to the driver core; no one other than the
  driver core is allowed to touch this.

**Description**

The device driver-model tracks all of the drivers known to the system.
The main reason for this tracking is to enable the driver core to match
up drivers with new devices. Once drivers are known objects within the
system, however, a number of other things become possible. Device drivers
can export information and configuration variables that are independent
of any specific device.


<a id="rst-device-drivers-base"></a>

## Device Drivers Base


#### <a id="c-driver_init"></a>`driver_init()`

```c
void driver_init(void)
```

initialize driver model.

**Parameters**

- `void`: no arguments

**Description**

Call the driver model init functions to initialize their
subsystems. Called early from init/main.c.



#### <a id="c-driver_find_device_by_name"></a>`driver_find_device_by_name()`

```c
struct device * driver_find_device_by_name(const struct device_driver *drv, const char *name)
```

device iterator for locating a particular device of a specific name.

**Parameters**

- `const struct device_driver *drv`: the driver we're iterating
- `const char *name`: name of the device to match

#### <a id="c-driver_find_device_by_of_node"></a>`driver_find_device_by_of_node()`

```c
struct device * driver_find_device_by_of_node(const struct device_driver *drv, const struct device_node *np)
```

device iterator for locating a particular device by of_node pointer.

**Parameters**

- `const struct device_driver *drv`: the driver we're iterating
- `const struct device_node *np`: of_node pointer to match.

#### <a id="c-driver_find_device_by_fwnode"></a>`driver_find_device_by_fwnode()`

```c
struct device * driver_find_device_by_fwnode(struct device_driver *drv, const struct fwnode_handle *fwnode)
```

device iterator for locating a particular device by fwnode pointer.

**Parameters**

- `struct device_driver *drv`: the driver we're iterating
- `const struct fwnode_handle *fwnode`: fwnode pointer to match.

#### <a id="c-driver_find_device_by_devt"></a>`driver_find_device_by_devt()`

```c
struct device * driver_find_device_by_devt(const struct device_driver *drv, dev_t devt)
```

device iterator for locating a particular device by devt.

**Parameters**

- `const struct device_driver *drv`: the driver we're iterating
- `dev_t devt`: devt pointer to match.

#### <a id="c-driver_find_device_by_acpi_dev"></a>`driver_find_device_by_acpi_dev()`

```c
struct device * driver_find_device_by_acpi_dev(const struct device_driver *drv, const struct acpi_device *adev)
```

device iterator for locating a particular device matching the ACPI_COMPANION device.

**Parameters**

- `const struct device_driver *drv`: the driver we're iterating
- `const struct acpi_device *adev`: ACPI_COMPANION device to match.

#### <a id="c-module_driver"></a>`module_driver()`

```c
module_driver(__driver, __register, __unregister, ...)
```

Helper macro for drivers that don't do anything special in module init/exit. This eliminates a lot of boilerplate. Each module may only use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit).

**Parameters**

- `__driver`: driver name
- `__register`: register function for this driver type
- `__unregister`: unregister function for this driver type
- `...`: Additional arguments to be passed to __register and __unregister.

**Description**

Use this macro to construct bus specific macros for registering
drivers, and do not use it on its own.

#### <a id="c-builtin_driver"></a>`builtin_driver()`

```c
builtin_driver(__driver, __register, ...)
```

Helper macro for drivers that don't do anything special in init and have no exit. This eliminates some boilerplate. Each driver may only use this macro once, and calling it replaces device_initcall (or in some cases, the legacy __initcall). This is meant to be a direct parallel of [`module_driver()`](#c-module_driver) above but without the __exit stuff that is not used for builtin cases.

**Parameters**

- `__driver`: driver name
- `__register`: register function for this driver type
- `...`: Additional arguments to be passed to __register

**Description**

Use this macro to construct bus specific macros for registering
drivers, and do not use it on its own.



#### <a id="c-driver_set_override"></a>`driver_set_override()`

```c
int driver_set_override(struct device *dev, const char **override, const char *s, size_t len)
```

Helper to set or clear driver override.

**Parameters**

- `struct device *dev`: Device to change
- `const char **override`: Address of string to change (e.g. [`device->driver_override`](#c-struct-device));
  The contents will be freed and hold newly allocated override.
- `const char *s`: NUL-terminated string, new driver name to force a match, pass empty
  string to clear it ("" or "\n", where the latter is only for sysfs
  interface).
- `size_t len`: length of **s**

**Description**

Helper to set or clear driver override in a device, intended for the cases
when the driver_override field is allocated by driver/bus code.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-driver_for_each_device"></a>`driver_for_each_device()`

```c
int driver_for_each_device(struct device_driver *drv, struct device *start, void *data, device_iter_t fn)
```

Iterator for devices bound to a driver.

**Parameters**

- `struct device_driver *drv`: Driver we're iterating.
- `struct device *start`: Device to begin with
- `void *data`: Data to pass to the callback.
- `device_iter_t fn`: Function to call for each device.

**Description**

Iterate over the **drv**'s list of devices calling **fn** for each one.

#### <a id="c-driver_find_device"></a>`driver_find_device()`

```c
struct device * driver_find_device(const struct device_driver *drv, struct device *start, const void *data, device_match_t match)
```

device iterator for locating a particular device.

**Parameters**

- `const struct device_driver *drv`: The device's driver
- `struct device *start`: Device to begin with
- `const void *data`: Data to pass to match function
- `device_match_t match`: Callback function to check device

**Description**

This is similar to the [`driver_for_each_device()`](#c-driver_for_each_device) function above, but
it returns a reference to a device that is 'found' for later use, as
determined by the **match** callback.

The callback should return 0 if the device doesn't match and non-zero
if it does.  If the callback returns non-zero, this function will
return to the caller and not iterate over any more devices.

#### <a id="c-driver_create_file"></a>`driver_create_file()`

```c
int driver_create_file(const struct device_driver *drv, const struct driver_attribute *attr)
```

create sysfs file for driver.

**Parameters**

- `const struct device_driver *drv`: driver.
- `const struct driver_attribute *attr`: driver attribute descriptor.

#### <a id="c-driver_remove_file"></a>`driver_remove_file()`

```c
void driver_remove_file(const struct device_driver *drv, const struct driver_attribute *attr)
```

remove sysfs file for driver.

**Parameters**

- `const struct device_driver *drv`: driver.
- `const struct driver_attribute *attr`: driver attribute descriptor.

#### <a id="c-driver_register"></a>`driver_register()`

```c
int driver_register(struct device_driver *drv)
```

register driver with bus

**Parameters**

- `struct device_driver *drv`: driver to register

**Description**

We pass off most of the work to the `bus_add_driver()` call,
since most of the things we have to do deal with the bus
structures.

#### <a id="c-driver_unregister"></a>`driver_unregister()`

```c
void driver_unregister(struct device_driver *drv)
```

remove driver from system.

**Parameters**

- `struct device_driver *drv`: driver.

**Description**

Again, we pass off most of the work to the bus-level call.



#### <a id="c-device_link_wait_removal"></a>`device_link_wait_removal()`

```c
void device_link_wait_removal(void)
```

Wait for ongoing devlink removal jobs to terminate

**Parameters**

- `void`: no arguments

#### <a id="c-device_link_add"></a>`device_link_add()`

```c
struct device_link * device_link_add(struct device *consumer, struct device *supplier, u32 flags)
```

Create a link between two devices.

**Parameters**

- `struct device *consumer`: Consumer end of the link.
- `struct device *supplier`: Supplier end of the link.
- `u32 flags`: Link flags.

**Return**

On success, a device_link struct will be returned.
On error or invalid flag settings, NULL will be returned.

**Description**

The caller is responsible for the proper synchronization of the link creation
with runtime PM.  First, setting the DL_FLAG_PM_RUNTIME flag will cause the
runtime PM framework to take the link into account.  Second, if the
DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
be forced into the active meta state and reference-counted upon the creation
of the link.  If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
ignored.

If DL_FLAG_STATELESS is set in **flags**, the caller of this function is
expected to release the link returned by it directly with the help of either
[`device_link_del()`](#c-device_link_del) or [`device_link_remove()`](#c-device_link_remove).

If that flag is not set, however, the caller of this function is handing the
management of the link over to the driver core entirely and its return value
can only be used to check whether or not the link is present.  In that case,
the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device link
flags can be used to indicate to the driver core when the link can be safely
deleted.  Namely, setting one of them in **flags** indicates to the driver core
that the link is not going to be used (by the given caller of this function)
after unbinding the consumer or supplier driver, respectively, from its
device, so the link can be deleted at that point.  If none of them is set,
the link will be maintained until one of the devices pointed to by it (either
the consumer or the supplier) is unregistered.

Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and
DL_FLAG_AUTOREMOVE_SUPPLIER are not set in **flags** (that is, a persistent
managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can
be used to request the driver core to automatically probe for a consumer
driver after successfully binding a driver to the supplier device.

The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,
DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set in **flags** at
the same time is invalid and will cause NULL to be returned upfront.
However, if a device link between the given **consumer** and **supplier** pair
exists already when this function is called for them, the existing link will
be returned regardless of its current type and status (the link's flags may
be modified then).  The caller of this function is then expected to treat
the link as though it has just been created, so (in particular) if
DL_FLAG_STATELESS was passed in **flags**, the link needs to be released
explicitly when not needed any more (as stated above).

A side effect of the link creation is re-ordering of dpm_list and the
devices_kset list by moving the consumer device and all devices depending
on it to the ends of these lists (that does not happen to devices that have
not been registered when this function is called).

The supplier device is required to be registered when this function is called
and NULL will be returned if that is not the case.  The consumer device need
not be registered, however.

#### <a id="c-device_link_del"></a>`device_link_del()`

```c
void device_link_del(struct device_link *link)
```

Delete a stateless link between two devices.

**Parameters**

- `struct device_link *link`: Device link to delete.

**Description**

The caller must ensure proper synchronization of this function with runtime
PM.  If the link was added multiple times, it needs to be deleted as often.
Care is required for hotplugged devices:  Their links are purged on removal
and calling [`device_link_del()`](#c-device_link_del) is then no longer allowed.

#### <a id="c-device_link_remove"></a>`device_link_remove()`

```c
void device_link_remove(void *consumer, struct device *supplier)
```

Delete a stateless link between two devices.

**Parameters**

- `void *consumer`: Consumer end of the link.
- `struct device *supplier`: Supplier end of the link.

**Description**

The caller must ensure proper synchronization of this function with runtime
PM.

#### <a id="c-dev_driver_string"></a>`dev_driver_string()`

```c
const char * dev_driver_string(const struct device *dev)
```

Return a device's driver name, if at all possible

**Parameters**

- `const struct device *dev`: struct device to get the name of

**Description**

Will return the device's driver's name if it is bound to a device.  If
the device is not bound to a driver, it will return the name of the bus
it is attached to.  If it is not attached to a bus either, an empty
string will be returned.

#### <a id="c-devm_device_add_group"></a>`devm_device_add_group()`

```c
int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
```

given a device, create a managed attribute group

**Parameters**

- `struct device *dev`: The device to create the group for
- `const struct attribute_group *grp`: The attribute group to create

**Description**

This function creates a group for the first time.  It will explicitly
warn and error if any of the attribute files being created already exist.

Returns 0 on success or error code on failure.

#### <a id="c-device_create_file"></a>`device_create_file()`

```c
int device_create_file(struct device *dev, const struct device_attribute *attr)
```

create sysfs attribute file for device.

**Parameters**

- `struct device *dev`: device.
- `const struct device_attribute *attr`: device attribute descriptor.

#### <a id="c-device_remove_file"></a>`device_remove_file()`

```c
void device_remove_file(struct device *dev, const struct device_attribute *attr)
```

remove sysfs attribute file.

**Parameters**

- `struct device *dev`: device.
- `const struct device_attribute *attr`: device attribute descriptor.

#### <a id="c-device_remove_file_self"></a>`device_remove_file_self()`

```c
bool device_remove_file_self(struct device *dev, const struct device_attribute *attr)
```

remove sysfs attribute file from its own method.

**Parameters**

- `struct device *dev`: device.
- `const struct device_attribute *attr`: device attribute descriptor.

**Description**

See `kernfs_remove_self()` for details.

#### <a id="c-device_create_bin_file"></a>`device_create_bin_file()`

```c
int device_create_bin_file(struct device *dev, const struct bin_attribute *attr)
```

create sysfs binary attribute file for device.

**Parameters**

- `struct device *dev`: device.
- `const struct bin_attribute *attr`: device binary attribute descriptor.

#### <a id="c-device_remove_bin_file"></a>`device_remove_bin_file()`

```c
void device_remove_bin_file(struct device *dev, const struct bin_attribute *attr)
```

remove sysfs binary attribute file

**Parameters**

- `struct device *dev`: device.
- `const struct bin_attribute *attr`: device binary attribute descriptor.

#### <a id="c-device_initialize"></a>`device_initialize()`

```c
void device_initialize(struct device *dev)
```

init device structure.

**Parameters**

- `struct device *dev`: device.

**Description**

This prepares the device for use by other layers by initializing
its fields.
It is the first half of [`device_register()`](#c-device_register), if called by
that function, though it can also be called separately, so one
may use **dev**'s fields. In particular, [`get_device()`](#c-get_device)/[`put_device()`](#c-put_device)
may be used for reference counting of **dev** after calling this
function.

All fields in **dev** must be initialized by the caller to 0, except
for those explicitly set to some other value.  The simplest
approach is to use [`kzalloc()`](/kernel/internals/core-api/mm-api.md#c-kzalloc) to allocate the structure containing
**dev**.

**NOTE**

Use [`put_device()`](#c-put_device) to give up your reference instead of freeing
**dev** directly once you have called this function.

#### <a id="c-dev_set_name"></a>`dev_set_name()`

```c
int dev_set_name(struct device *dev, const char *fmt, ...)
```

set a device name

**Parameters**

- `struct device *dev`: device
- `const char *fmt`: format string for the device's name
- `...`: variable arguments

#### <a id="c-device_add"></a>`device_add()`

```c
int device_add(struct device *dev)
```

add device to device hierarchy.

**Parameters**

- `struct device *dev`: device.

**Description**

This is part 2 of [`device_register()`](#c-device_register), though may be called
separately _iff_ [`device_initialize()`](#c-device_initialize) has been called separately.

This adds **dev** to the kobject hierarchy via [`kobject_add()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-kobject_add), adds it
to the global and sibling lists for the device, then
adds it to the other relevant subsystems of the driver model.

Do not call this routine or [`device_register()`](#c-device_register) more than once for
any device structure.  The driver model core is not designed to work
with devices that get unregistered and then spring back to life.
(Among other things, it's very hard to guarantee that all references
to the previous incarnation of **dev** have been dropped.)  Allocate
and register a fresh new struct device instead.

**NOTE**

_Never_ directly free **dev** after calling this function, even
if it returned an error! Always use [`put_device()`](#c-put_device) to give up your
reference instead.

Rule of thumb is: if [`device_add()`](#c-device_add) succeeds, you should call
[`device_del()`](#c-device_del) when you want to get rid of it. If [`device_add()`](#c-device_add) has
*not* succeeded, use *only* [`put_device()`](#c-put_device) to drop the reference
count.

#### <a id="c-device_register"></a>`device_register()`

```c
int device_register(struct device *dev)
```

register a device with the system.

**Parameters**

- `struct device *dev`: pointer to the device structure

**Description**

This happens in two clean steps - initialize the device
and add it to the system. The two steps can be called
separately, but this is the easiest and most common.
I.e. you should only call the two helpers separately if
have a clearly defined need to use and refcount the device
before it is added to the hierarchy.

For more information, see the kerneldoc for [`device_initialize()`](#c-device_initialize)
and [`device_add()`](#c-device_add).

**NOTE**

_Never_ directly free **dev** after calling this function, even
if it returned an error! Always use [`put_device()`](#c-put_device) to give up the
reference initialized in this function instead.

#### <a id="c-get_device"></a>`get_device()`

```c
struct device * get_device(struct device *dev)
```

increment reference count for device.

**Parameters**

- `struct device *dev`: device.

**Description**

This simply forwards the call to [`kobject_get()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-kobject_get), though
we do take care to provide for the case that we get a NULL
pointer passed in.

#### <a id="c-put_device"></a>`put_device()`

```c
void put_device(struct device *dev)
```

decrement reference count.

**Parameters**

- `struct device *dev`: device in question.

#### <a id="c-device_del"></a>`device_del()`

```c
void device_del(struct device *dev)
```

delete device from system.

**Parameters**

- `struct device *dev`: device.

**Description**

This is the first part of the device unregistration
sequence. This removes the device from the lists we control
from here, has it removed from the other driver model
subsystems it was added to in [`device_add()`](#c-device_add), and removes it
from the kobject hierarchy.

**NOTE**

this should be called manually _iff_ [`device_add()`](#c-device_add) was
also called manually.

#### <a id="c-device_unregister"></a>`device_unregister()`

```c
void device_unregister(struct device *dev)
```

unregister device from system.

**Parameters**

- `struct device *dev`: device going away.

**Description**

We do this in two parts, like we do [`device_register()`](#c-device_register). First,
we remove it from all the subsystems with [`device_del()`](#c-device_del), then
we decrement the reference count via [`put_device()`](#c-put_device). If that
is the final reference count, the device will be cleaned up
via `device_release()` above. Otherwise, the structure will
stick around until the final reference to the device is dropped.

#### <a id="c-device_for_each_child"></a>`device_for_each_child()`

```c
int device_for_each_child(struct device *parent, void *data, device_iter_t fn)
```

device child iterator.

**Parameters**

- `struct device *parent`: parent struct device.
- `void *data`: data for the callback.
- `device_iter_t fn`: function to be called for each device.

**Description**

Iterate over **parent**'s child devices, and call **fn** for each,
passing it **data**.

We check the return of **fn** each time. If it returns anything
other than 0, we break out and return that value.

#### <a id="c-device_for_each_child_reverse"></a>`device_for_each_child_reverse()`

```c
int device_for_each_child_reverse(struct device *parent, void *data, device_iter_t fn)
```

device child iterator in reversed order.

**Parameters**

- `struct device *parent`: parent struct device.
- `void *data`: data for the callback.
- `device_iter_t fn`: function to be called for each device.

**Description**

Iterate over **parent**'s child devices, and call **fn** for each,
passing it **data**.

We check the return of **fn** each time. If it returns anything
other than 0, we break out and return that value.

#### <a id="c-device_for_each_child_reverse_from"></a>`device_for_each_child_reverse_from()`

```c
int device_for_each_child_reverse_from(struct device *parent, struct device *from, void *data, device_iter_t fn)
```

device child iterator in reversed order.

**Parameters**

- `struct device *parent`: parent struct device.
- `struct device *from`: optional starting point in child list
- `void *data`: data for the callback.
- `device_iter_t fn`: function to be called for each device.

**Description**

Iterate over **parent**'s child devices, starting at **from**, and call **fn**
for each, passing it **data**. This helper is identical to
[`device_for_each_child_reverse()`](#c-device_for_each_child_reverse) when **from** is NULL.

**fn** is checked each iteration. If it returns anything other than 0,
iteration stop and that value is returned to the caller of
[`device_for_each_child_reverse_from()`](#c-device_for_each_child_reverse_from);

#### <a id="c-device_find_child"></a>`device_find_child()`

```c
struct device * device_find_child(struct device *parent, const void *data, device_match_t match)
```

device iterator for locating a particular device.

**Parameters**

- `struct device *parent`: parent struct device
- `const void *data`: Data to pass to match function
- `device_match_t match`: Callback function to check device

**Description**

This is similar to the [`device_for_each_child()`](#c-device_for_each_child) function above, but it
returns a reference to a device that is 'found' for later use, as
determined by the **match** callback.

The callback should return 0 if the device doesn't match and non-zero
if it does.  If the callback returns non-zero and a reference to the
current device can be obtained, this function will return to the caller
and not iterate over any more devices.

**NOTE**

you will need to drop the reference with [`put_device()`](#c-put_device) after use.

#### <a id="c-__root_device_register"></a>`__root_device_register()`

```c
struct device * __root_device_register(const char *name, struct module *owner)
```

allocate and register a root device

**Parameters**

- `const char *name`: root device name
- `struct module *owner`: owner module of the root device, usually THIS_MODULE

**Description**

This function allocates a root device and registers it
using [`device_register()`](#c-device_register). In order to free the returned
device, use [`root_device_unregister()`](#c-root_device_unregister).

Root devices are dummy devices which allow other devices
to be grouped under /sys/devices. Use this function to
allocate a root device and then use it as the parent of
any device which should appear under /sys/devices/{name}

The /sys/devices/{name} directory will also contain a
'module' symlink which points to the **owner** directory
in sysfs.

Returns [`struct device`](#c-struct-device) pointer on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

**Note**

You probably want to use `root_device_register()`.

#### <a id="c-root_device_unregister"></a>`root_device_unregister()`

```c
void root_device_unregister(struct device *dev)
```

unregister and free a root device

**Parameters**

- `struct device *dev`: device going away

**Description**

This function unregisters and cleans up a device that was created by
`root_device_register()`.

#### <a id="c-device_create"></a>`device_create()`

```c
struct device * device_create(const struct class *class, struct device *parent, dev_t devt, void *drvdata, const char *fmt, ...)
```

creates a device and registers it with sysfs

**Parameters**

- `const struct class *class`: pointer to the struct class that this device should be registered to
- `struct device *parent`: pointer to the parent struct device of this new device, if any
- `dev_t devt`: the dev_t for the char device to be added
- `void *drvdata`: the data to be added to the device for callbacks
- `const char *fmt`: string for the device's name
- `...`: variable arguments

**Description**

This function can be used by char device classes.  A struct device
will be created in sysfs, registered to the specified class.

A "dev" file will be created, showing the dev_t for the device, if
the dev_t is not 0,0.
If a pointer to a parent struct device is passed in, the newly created
struct device will be a child of that device in sysfs.
The pointer to the struct device will be returned from the call.
Any further sysfs files that might be required can be created using this
pointer.

Returns [`struct device`](#c-struct-device) pointer on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

#### <a id="c-device_create_with_groups"></a>`device_create_with_groups()`

```c
struct device * device_create_with_groups(const struct class *class, struct device *parent, dev_t devt, void *drvdata, const struct attribute_group **groups, const char *fmt, ...)
```

creates a device and registers it with sysfs

**Parameters**

- `const struct class *class`: pointer to the struct class that this device should be registered to
- `struct device *parent`: pointer to the parent struct device of this new device, if any
- `dev_t devt`: the dev_t for the char device to be added
- `void *drvdata`: the data to be added to the device for callbacks
- `const struct attribute_group **groups`: NULL-terminated list of attribute groups to be created
- `const char *fmt`: string for the device's name
- `...`: variable arguments

**Description**

This function can be used by char device classes.  A struct device
will be created in sysfs, registered to the specified class.
Additional attributes specified in the groups parameter will also
be created automatically.

A "dev" file will be created, showing the dev_t for the device, if
the dev_t is not 0,0.
If a pointer to a parent struct device is passed in, the newly created
struct device will be a child of that device in sysfs.
The pointer to the struct device will be returned from the call.
Any further sysfs files that might be required can be created using this
pointer.

Returns [`struct device`](#c-struct-device) pointer on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

#### <a id="c-device_destroy"></a>`device_destroy()`

```c
void device_destroy(const struct class *class, dev_t devt)
```

removes a device that was created with [`device_create()`](#c-device_create)

**Parameters**

- `const struct class *class`: pointer to the struct class that this device was registered with
- `dev_t devt`: the dev_t of the device that was previously registered

**Description**

This call unregisters and cleans up a device that was created with a
call to [`device_create()`](#c-device_create).

#### <a id="c-device_rename"></a>`device_rename()`

```c
int device_rename(struct device *dev, const char *new_name)
```

renames a device

**Parameters**

- `struct device *dev`: the pointer to the struct device to be renamed
- `const char *new_name`: the new name of the device

**Description**

It is the responsibility of the caller to provide mutual
exclusion between two different calls of device_rename
on the same device to ensure that new_name is valid and
won't conflict with other devices.

**Note**

given that some subsystems (networking and infiniband) use this
function, with no immediate plans for this to change, we cannot assume or
require that this function not be called at all.

However, if you're writing new code, do not call this function. The following
text from Kay Sievers offers some insight:

Renaming devices is racy at many levels, symlinks and other stuff are not
replaced atomically, and you get a "move" uevent, but it's not easy to
connect the event to the old and new device. Device nodes are not renamed at
all, there isn't even support for that in the kernel now.

In the meantime, during renaming, your target name might be taken by another
driver, creating conflicts. Or the old name is taken directly after you
renamed it -- then you get events for the same DEVPATH, before you even see
the "move" event. It's just a mess, and nothing new should ever rely on
kernel device renaming. Besides that, it's not even implemented now for
other things than (driver-core wise very simple) network devices.

Make up a "real" name in the driver before you register anything, or add
some other attributes for userspace to find the device, or use udev to add
symlinks -- but never rename kernel devices later, it's a complete mess. We
don't even want to get into that and try to implement the missing pieces in
the core. We really have other pieces to fix in the driver core mess. :)

#### <a id="c-device_move"></a>`device_move()`

```c
int device_move(struct device *dev, struct device *new_parent, enum dpm_order dpm_order)
```

moves a device to a new parent

**Parameters**

- `struct device *dev`: the pointer to the struct device to be moved
- `struct device *new_parent`: the new parent of the device (can be NULL)
- `enum dpm_order dpm_order`: how to reorder the dpm_list

#### <a id="c-dev_err_probe"></a>`dev_err_probe()`

```c
int dev_err_probe(const struct device *dev, int err, const char *fmt, ...)
```

probe error check and log helper

**Parameters**

- `const struct device *dev`: the pointer to the struct device
- `int err`: error value to test
- `const char *fmt`: printf-style format string
- `...`: arguments as specified in the format string

**Description**

This helper implements common pattern present in probe functions for error
checking: print debug or error message depending if the error value is
-EPROBE_DEFER and propagate error upwards.
In case of -EPROBE_DEFER it sets also defer probe reason, which can be
checked later by reading devices_deferred debugfs attribute.
It replaces the following code sequence:

```text
if (err != -EPROBE_DEFER)
        dev_err(dev, ...);
else
        dev_dbg(dev, ...);
return err;
```

with:

```text
return dev_err_probe(dev, err, ...);
```

Using this helper in your probe function is totally fine even if **err**
is known to never be -EPROBE_DEFER.
The benefit compared to a normal `dev_err()` is the standardized format
of the error code, which is emitted symbolically (i.e. you get "EAGAIN"
instead of "-35"), and having the error code returned allows more
compact error paths.

Returns **err**.

#### <a id="c-dev_warn_probe"></a>`dev_warn_probe()`

```c
int dev_warn_probe(const struct device *dev, int err, const char *fmt, ...)
```

probe error check and log helper

**Parameters**

- `const struct device *dev`: the pointer to the struct device
- `int err`: error value to test
- `const char *fmt`: printf-style format string
- `...`: arguments as specified in the format string

**Description**

This helper implements common pattern present in probe functions for error
checking: print debug or warning message depending if the error value is
-EPROBE_DEFER and propagate error upwards.
In case of -EPROBE_DEFER it sets also defer probe reason, which can be
checked later by reading devices_deferred debugfs attribute.
It replaces the following code sequence:

```text
if (err != -EPROBE_DEFER)
        dev_warn(dev, ...);
else
        dev_dbg(dev, ...);
return err;
```

with:

```text
return dev_warn_probe(dev, err, ...);
```

Using this helper in your probe function is totally fine even if **err**
is known to never be -EPROBE_DEFER.
The benefit compared to a normal `dev_warn()` is the standardized format
of the error code, which is emitted symbolically (i.e. you get "EAGAIN"
instead of "-35"), and having the error code returned allows more
compact error paths.

Returns **err**.

#### <a id="c-set_primary_fwnode"></a>`set_primary_fwnode()`

```c
void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
```

Change the primary firmware node of a given device.

**Parameters**

- `struct device *dev`: Device to handle.
- `struct fwnode_handle *fwnode`: New primary firmware node of the device.

**Description**

Set the device's firmware node pointer to **fwnode**, but if a secondary
firmware node of the device is present, preserve it.

- Valid fwnode cases are:
  - primary --> secondary --> -ENODEV
  - primary --> NULL
  - secondary --> -ENODEV
  - NULL

#### <a id="c-set_secondary_fwnode"></a>`set_secondary_fwnode()`

```c
void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
```

Change the secondary firmware node of a given device.

**Parameters**

- `struct device *dev`: Device to handle.
- `struct fwnode_handle *fwnode`: New secondary firmware node of the device.

**Description**

If a primary firmware node of the device is present, set its secondary
pointer to **fwnode**.  Otherwise, set the device's firmware node pointer to
**fwnode**.

#### <a id="c-device_remove_of_node"></a>`device_remove_of_node()`

```c
void device_remove_of_node(struct device *dev)
```

Remove an of_node from a device

**Parameters**

- `struct device *dev`: device whose device tree node is being removed

#### <a id="c-device_add_of_node"></a>`device_add_of_node()`

```c
int device_add_of_node(struct device *dev, struct device_node *of_node)
```

Add an of_node to an existing device

**Parameters**

- `struct device *dev`: device whose device tree node is being added
- `struct device_node *of_node`: of_node to add

**Return**

0 on success or error code on failure.

#### <a id="c-device_set_of_node_from_dev"></a>`device_set_of_node_from_dev()`

```c
void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
```

reuse device-tree node of another device

**Parameters**

- `struct device *dev`: device whose device-tree node is being set
- `const struct device *dev2`: device whose device-tree node is being reused

**Description**

Takes another reference to the new device-tree node after first dropping
any reference held to the old node.

#### <a id="c-get_dev_from_fwnode"></a>`get_dev_from_fwnode()`

```c
struct device * get_dev_from_fwnode(struct fwnode_handle *fwnode)
```

Obtain a reference count of the struct device the struct fwnode_handle is associated with.

**Parameters**

- `struct fwnode_handle *fwnode`: The pointer to the struct fwnode_handle to obtain the struct device
  reference count of.

**Description**

This function obtains a reference count of the device the device pointer
embedded in the struct fwnode_handle points to.

Note that the struct device pointer embedded in struct fwnode_handle does
*not* have a reference count of the struct device itself.

Hence, it is a UAF (and thus a bug) to call this function if the caller can't
guarantee that the last reference count of the corresponding struct device is
not dropped concurrently.

This is possible since struct fwnode_handle has its own reference count and
hence can out-live the struct device it is associated with.



#### <a id="c-register_syscore"></a>`register_syscore()`

```c
void register_syscore(struct syscore *syscore)
```

Register a set of system core operations.

**Parameters**

- `struct syscore *syscore`: System core operations to register.

#### <a id="c-unregister_syscore"></a>`unregister_syscore()`

```c
void unregister_syscore(struct syscore *syscore)
```

Unregister a set of system core operations.

**Parameters**

- `struct syscore *syscore`: System core operations to unregister.

#### <a id="c-syscore_suspend"></a>`syscore_suspend()`

```c
int syscore_suspend(void)
```

Execute all the registered system core suspend callbacks.

**Parameters**

- `void`: no arguments

**Description**

This function is executed with one CPU on-line and disabled interrupts.

#### <a id="c-syscore_resume"></a>`syscore_resume()`

```c
void syscore_resume(void)
```

Execute all the registered system core resume callbacks.

**Parameters**

- `void`: no arguments

**Description**

This function is executed with one CPU on-line and disabled interrupts.



#### <a id="c-class_find_device_by_name"></a>`class_find_device_by_name()`

```c
struct device * class_find_device_by_name(const struct class *class, const char *name)
```

device iterator for locating a particular device of a specific name.

**Parameters**

- `const struct class *class`: class type
- `const char *name`: name of the device to match

#### <a id="c-class_find_device_by_of_node"></a>`class_find_device_by_of_node()`

```c
struct device * class_find_device_by_of_node(const struct class *class, const struct device_node *np)
```

device iterator for locating a particular device matching the of_node.

**Parameters**

- `const struct class *class`: class type
- `const struct device_node *np`: of_node of the device to match.

#### <a id="c-class_find_device_by_fwnode"></a>`class_find_device_by_fwnode()`

```c
struct device * class_find_device_by_fwnode(const struct class *class, const struct fwnode_handle *fwnode)
```

device iterator for locating a particular device matching the fwnode.

**Parameters**

- `const struct class *class`: class type
- `const struct fwnode_handle *fwnode`: fwnode of the device to match.

#### <a id="c-class_find_device_by_devt"></a>`class_find_device_by_devt()`

```c
struct device * class_find_device_by_devt(const struct class *class, dev_t devt)
```

device iterator for locating a particular device matching the device type.

**Parameters**

- `const struct class *class`: class type
- `dev_t devt`: device type of the device to match.

#### <a id="c-class_find_device_by_acpi_dev"></a>`class_find_device_by_acpi_dev()`

```c
struct device * class_find_device_by_acpi_dev(const struct class *class, const struct acpi_device *adev)
```

device iterator for locating a particular device matching the ACPI_COMPANION device.

**Parameters**

- `const struct class *class`: class type
- `const struct acpi_device *adev`: ACPI_COMPANION device to match.



#### <a id="c-class_create"></a>`class_create()`

```c
struct class * class_create(const char *name)
```

create a struct class structure

**Parameters**

- `const char *name`: pointer to a string for the name of this class.

**Description**

This is used to create a struct class pointer that can then be used
in calls to [`device_create()`](#c-device_create).

Returns [`struct class`](#c-struct-class) pointer on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

Note, the pointer created here is to be destroyed when finished by
making a call to [`class_destroy()`](#c-class_destroy).

#### <a id="c-class_destroy"></a>`class_destroy()`

```c
void class_destroy(const struct class *cls)
```

destroys a struct class structure

**Parameters**

- `const struct class *cls`: pointer to the struct class that is to be destroyed

**Description**

Note, the pointer to be destroyed must have been created with a call
to [`class_create()`](#c-class_create).

#### <a id="c-class_dev_iter_init"></a>`class_dev_iter_init()`

```c
void class_dev_iter_init(struct class_dev_iter *iter, const struct class *class, const struct device *start, const struct device_type *type)
```

initialize class device iterator

**Parameters**

- `struct class_dev_iter *iter`: class iterator to initialize
- `const struct class *class`: the class we wanna iterate over
- `const struct device *start`: the device to start iterating from, if any
- `const struct device_type *type`: device_type of the devices to iterate over, NULL for all

**Description**

Initialize class iterator **iter** such that it iterates over devices
of **class**.  If **start** is set, the list iteration will start there,
otherwise if it is NULL, the iteration starts at the beginning of
the list.

#### <a id="c-class_dev_iter_next"></a>`class_dev_iter_next()`

```c
struct device * class_dev_iter_next(struct class_dev_iter *iter)
```

iterate to the next device

**Parameters**

- `struct class_dev_iter *iter`: class iterator to proceed

**Description**

Proceed **iter** to the next device and return it.  Returns NULL if
iteration is complete.

The returned device is referenced and won't be released till
iterator is proceed to the next device or exited.  The caller is
free to do whatever it wants to do with the device including
calling back into class code.

#### <a id="c-class_dev_iter_exit"></a>`class_dev_iter_exit()`

```c
void class_dev_iter_exit(struct class_dev_iter *iter)
```

finish iteration

**Parameters**

- `struct class_dev_iter *iter`: class iterator to finish

**Description**

Finish an iteration.  Always call this function after iteration is
complete whether the iteration ran till the end or not.

#### <a id="c-class_for_each_device"></a>`class_for_each_device()`

```c
int class_for_each_device(const struct class *class, const struct device *start, void *data, device_iter_t fn)
```

device iterator

**Parameters**

- `const struct class *class`: the class we're iterating
- `const struct device *start`: the device to start with in the list, if any.
- `void *data`: data for the callback
- `device_iter_t fn`: function to be called for each device

**Description**

Iterate over **class**'s list of devices, and call **fn** for each,
passing it **data**.  If **start** is set, the list iteration will start
there, otherwise if it is NULL, the iteration starts at the
beginning of the list.

We check the return of **fn** each time. If it returns anything
other than 0, we break out and return that value.

**fn** is allowed to do anything including calling back into class
code.  There's no locking restriction.

#### <a id="c-class_find_device"></a>`class_find_device()`

```c
struct device * class_find_device(const struct class *class, const struct device *start, const void *data, device_match_t match)
```

device iterator for locating a particular device

**Parameters**

- `const struct class *class`: the class we're iterating
- `const struct device *start`: Device to begin with
- `const void *data`: data for the match function
- `device_match_t match`: function to check device

**Description**

This is similar to the `class_for_each_dev()` function above, but it
returns a reference to a device that is 'found' for later use, as
determined by the **match** callback.

The callback should return 0 if the device doesn't match and non-zero
if it does.  If the callback returns non-zero, this function will
return to the caller and not iterate over any more devices.

Note, you will need to drop the reference with [`put_device()`](#c-put_device) after use.

**match** is allowed to do anything including calling back into class
code.  There's no locking restriction.

#### <a id="c-class_compat_register"></a>`class_compat_register()`

```c
struct class_compat * class_compat_register(const char *name)
```

register a compatibility class

**Parameters**

- `const char *name`: the name of the class

**Description**

Compatibility class are meant as a temporary user-space compatibility
workaround when converting a family of class devices to a bus devices.

#### <a id="c-class_compat_unregister"></a>`class_compat_unregister()`

```c
void class_compat_unregister(struct class_compat *cls)
```

unregister a compatibility class

**Parameters**

- `struct class_compat *cls`: the class to unregister

#### <a id="c-class_compat_create_link"></a>`class_compat_create_link()`

```c
int class_compat_create_link(struct class_compat *cls, struct device *dev)
```

create a compatibility class device link to a bus device

**Parameters**

- `struct class_compat *cls`: the compatibility class
- `struct device *dev`: the target bus device

#### <a id="c-class_compat_remove_link"></a>`class_compat_remove_link()`

```c
void class_compat_remove_link(struct class_compat *cls, struct device *dev)
```

remove a compatibility class device link to a bus device

**Parameters**

- `struct class_compat *cls`: the compatibility class
- `struct device *dev`: the target bus device

#### <a id="c-class_is_registered"></a>`class_is_registered()`

```c
bool class_is_registered(const struct class *class)
```

determine if at this moment in time, a class is registered in the driver core or not.

**Parameters**

- `const struct class *class`: the class to check

**Description**

Returns a boolean to state if the class is registered in the driver core
or not.  Note that the value could switch right after this call is made,
so only use this in places where you "know" it is safe to do so (usually
to determine if the specific class has been registered yet or not).

Be careful in using this.



#### <a id="c-struct-faux_device"></a>`struct faux_device`

a "faux" device

**Definition**

```c
struct faux_device {
    struct device dev;
};
```

**Members**

- `dev`: internal struct device of the object

**Description**

A simple faux device that can be created/destroyed.  To be used when a
driver only needs to have a device to "hang" something off.  This can be
used for downloading firmware or other basic tasks.  Use this instead of
a struct platform_device if the device has no resources assigned to
it at all.

#### <a id="c-struct-faux_device_ops"></a>`struct faux_device_ops`

a set of callbacks for a struct faux_device

**Definition**

```c
struct faux_device_ops {
    int (*probe)(struct faux_device *faux_dev);
    void (*remove)(struct faux_device *faux_dev);
};
```

**Members**

- `probe`: called when a faux device is probed by the driver core
  before the device is fully bound to the internal faux bus
  code.  If probe succeeds, return 0, otherwise return a
  negative error number to stop the probe sequence from
  succeeding.
- `remove`: called when a faux device is removed from the system

**Description**

Both **probe** and **remove** are optional, if not needed, set to NULL.



#### <a id="c-faux_device_create_with_groups"></a>`faux_device_create_with_groups()`

```c
struct faux_device * faux_device_create_with_groups(const char *name, struct device *parent, const struct faux_device_ops *faux_ops, const struct attribute_group **groups)
```

Create and register with the driver core a faux device and populate the device with an initial set of sysfs attributes.

**Parameters**

- `const char *name`: The name of the device we are adding, must be unique for
  all faux devices.
- `struct device *parent`: Pointer to a potential parent struct device.  If set to
  NULL, the device will be created in the "root" of the faux
  device tree in sysfs.
- `const struct faux_device_ops *faux_ops`: struct faux_device_ops that the new device will call back
  into, can be NULL.
- `const struct attribute_group **groups`: The set of sysfs attributes that will be created for this
  device when it is registered with the driver core.

**Description**

Create a new faux device and register it in the driver core properly.
If present, callbacks in **faux_ops** will be called with the device that
for the caller to do something with at the proper time given the
device's lifecycle.

Note, when this function is called, the functions specified in struct
faux_ops can be called before the function returns, so be prepared for
everything to be properly initialized before that point in time.  If the
probe callback (if one is present) does NOT succeed, the creation of the
device will fail and NULL will be returned.

**Return**

* NULL if an error happened with creating the device
* pointer to a valid struct faux_device that is registered with sysfs

#### <a id="c-faux_device_create"></a>`faux_device_create()`

```c
struct faux_device * faux_device_create(const char *name, struct device *parent, const struct faux_device_ops *faux_ops)
```

create and register with the driver core a faux device

**Parameters**

- `const char *name`: The name of the device we are adding, must be unique for all
  faux devices.
- `struct device *parent`: Pointer to a potential parent struct device.  If set to
  NULL, the device will be created in the "root" of the faux
  device tree in sysfs.
- `const struct faux_device_ops *faux_ops`: struct faux_device_ops that the new device will call back
  into, can be NULL.

**Description**

Create a new faux device and register it in the driver core properly.
If present, callbacks in **faux_ops** will be called with the device that
for the caller to do something with at the proper time given the
device's lifecycle.

Note, when this function is called, the functions specified in struct
faux_ops can be called before the function returns, so be prepared for
everything to be properly initialized before that point in time.

**Return**

* NULL if an error happened with creating the device
* pointer to a valid struct faux_device that is registered with sysfs

#### <a id="c-faux_device_destroy"></a>`faux_device_destroy()`

```c
void faux_device_destroy(struct faux_device *faux_dev)
```

destroy a faux device

**Parameters**

- `struct faux_device *faux_dev`: faux device to destroy

**Description**

Unregisters and cleans up a device that was created with a call to
[`faux_device_create()`](#c-faux_device_create)



#### <a id="c-struct-node_access_nodes"></a>`struct node_access_nodes`

Access class device to hold user visible relationships to other nodes.

**Definition**

```c
struct node_access_nodes {
        struct device           dev;
        struct list_head        list_node;
        unsigned int            access;
    #ifdef CONFIG_HMEM_REPORTING;
        struct access_coordinate        coord;
    #endif;
};
```

**Members**

- `dev`: Device for this memory access class
- `list_node`: List element in the node's access list
- `access`: The access class rank
- `coord`: Heterogeneous memory performance coordinates

#### <a id="c-struct-node_cache_info"></a>`struct node_cache_info`

Internal tracking for memory node caches

**Definition**

```c
struct node_cache_info {
    struct device dev;
    struct list_head node;
    struct node_cache_attrs cache_attrs;
};
```

**Members**

- `dev`: Device represeting the cache level
- `node`: List element for tracking in the node
- `cache_attrs`: Attributes for this cache level

#### <a id="c-node_add_cache"></a>`node_add_cache()`

```c
void node_add_cache(unsigned int nid, struct node_cache_attrs *cache_attrs)
```

add cache attribute to a memory node

**Parameters**

- `unsigned int nid`: Node identifier that has new cache attributes
- `struct node_cache_attrs *cache_attrs`: Attributes for the cache being added

#### <a id="c-register_memory_node_under_compute_node"></a>`register_memory_node_under_compute_node()`

```c
int register_memory_node_under_compute_node(unsigned int mem_nid, unsigned int cpu_nid, enum access_coordinate_class access)
```

link memory node to its compute node for a given access class.

**Parameters**

- `unsigned int mem_nid`: Memory node number
- `unsigned int cpu_nid`: Cpu  node number
- `enum access_coordinate_class access`: Access class to register

**Description**

For use with platforms that may have separate memory and compute nodes.
This function will export node relationships linking which memory
initiator nodes can access memory targets at a given ranked access
class.

#### <a id="c-register_node"></a>`register_node()`

```c
int register_node(int nid)
```

Initialize and register the node device.

**Parameters**

- `int nid`: Node number to use when creating the device.

**Return**

0 on success, -errno otherwise

#### <a id="c-unregister_node"></a>`unregister_node()`

```c
void unregister_node(int nid)
```

unregister a node device

**Parameters**

- `int nid`: nid of the node going away

**Description**

Unregisters the node device at node id **nid**. All the devices on the
node must be unregistered before calling this function.



#### <a id="c-transport_class_register"></a>`transport_class_register()`

```c
int transport_class_register(struct transport_class *tclass)
```

register an initial transport class

**Parameters**

- `struct transport_class *tclass`: a pointer to the transport class structure to be initialised

**Description**

The transport class contains an embedded class which is used to
identify it.  The caller should initialise this structure with
zeros and then generic class must have been initialised with the
actual transport class unique name.  There's a macro
`DECLARE_TRANSPORT_CLASS()` to do this (declared classes still must
be registered).

Returns 0 on success or error on failure.

#### <a id="c-transport_class_unregister"></a>`transport_class_unregister()`

```c
void transport_class_unregister(struct transport_class *tclass)
```

unregister a previously registered class

**Parameters**

- `struct transport_class *tclass`: The transport class to unregister

**Description**

Must be called prior to deallocating the memory for the transport
class.

#### <a id="c-anon_transport_class_register"></a>`anon_transport_class_register()`

```c
void anon_transport_class_register(struct anon_transport_class *atc)
```

register an anonymous class

**Parameters**

- `struct anon_transport_class *atc`: The anon transport class to register

**Description**

The anonymous transport class contains both a transport class and a
container.  The idea of an anonymous class is that it never
actually has any device attributes associated with it (and thus
saves on container storage).  So it can only be used for triggering
events.  Use prezero and then use `DECLARE_ANON_TRANSPORT_CLASS()` to
initialise the anon transport class storage.

#### <a id="c-anon_transport_class_unregister"></a>`anon_transport_class_unregister()`

```c
void anon_transport_class_unregister(struct anon_transport_class *atc)
```

unregister an anon class

**Parameters**

- `struct anon_transport_class *atc`: Pointer to the anon transport class to unregister

**Description**

Must be called prior to deallocating the memory for the anon
transport class.

#### <a id="c-transport_setup_device"></a>`transport_setup_device()`

```c
void transport_setup_device(struct device *dev)
```

declare a new dev for transport class association but don't make it visible yet.

**Parameters**

- `struct device *dev`: the generic device representing the entity being added

**Description**

Usually, dev represents some component in the HBA system (either
the HBA itself or a device remote across the HBA bus).  This
routine is simply a trigger point to see if any set of transport
classes wishes to associate with the added device.  This allocates
storage for the class device and initialises it, but does not yet
add it to the system or add attributes to it (you do this with
transport_add_device).  If you have no need for a separate setup
and add operations, use transport_register_device (see
transport_class.h).

#### <a id="c-transport_add_device"></a>`transport_add_device()`

```c
int transport_add_device(struct device *dev)
```

declare a new dev for transport class association

**Parameters**

- `struct device *dev`: the generic device representing the entity being added

**Description**

Usually, dev represents some component in the HBA system (either
the HBA itself or a device remote across the HBA bus).  This
routine is simply a trigger point used to add the device to the
system and register attributes for it.

#### <a id="c-transport_configure_device"></a>`transport_configure_device()`

```c
void transport_configure_device(struct device *dev)
```

configure an already set up device

**Parameters**

- `struct device *dev`: generic device representing device to be configured

**Description**

The idea of configure is simply to provide a point within the setup
process to allow the transport class to extract information from a
device after it has been setup.  This is used in SCSI because we
have to have a setup device to begin using the HBA, but after we
send the initial inquiry, we use configure to extract the device
parameters.  The device need not have been added to be configured.

#### <a id="c-transport_remove_device"></a>`transport_remove_device()`

```c
void transport_remove_device(struct device *dev)
```

remove the visibility of a device

**Parameters**

- `struct device *dev`: generic device to remove

**Description**

This call removes the visibility of the device (to the user from
sysfs), but does not destroy it.  To eliminate a device entirely
you must also call transport_destroy_device.  If you don't need to
do remove and destroy as separate operations, use
`transport_unregister_device()` (see transport_class.h) which will
perform both calls for you.

#### <a id="c-transport_destroy_device"></a>`transport_destroy_device()`

```c
void transport_destroy_device(struct device *dev)
```

destroy a removed device

**Parameters**

- `struct device *dev`: device to eliminate from the transport class.

**Description**

This call triggers the elimination of storage associated with the
transport classdev.  Note: all it really does is relinquish a
reference to the classdev.  The memory will not be freed until the
last reference goes to zero.  Note also that the classdev retains a
reference count on dev, so dev too will remain for as long as the
transport class device remains around.



#### <a id="c-driver_deferred_probe_check_state"></a>`driver_deferred_probe_check_state()`

```c
int driver_deferred_probe_check_state(struct device *dev)
```

Check deferred probe state

**Parameters**

- `struct device *dev`: device to check

**Return**

* -ENODEV if initcalls have completed and modules are disabled.
* -ETIMEDOUT if the deferred probe timeout was set and has expired
  and modules are enabled.
* -EPROBE_DEFER in other cases.

**Description**

Drivers or subsystems can opt-in to calling this function instead of directly
returning -EPROBE_DEFER.

#### <a id="c-device_is_bound"></a>`device_is_bound()`

```c
bool device_is_bound(struct device *dev)
```

Check if device is bound to a driver

**Parameters**

- `struct device *dev`: device to check

**Description**

Returns true if passed device has already finished probing successfully
against a driver.

This function must be called with the device lock held.

#### <a id="c-device_bind_driver"></a>`device_bind_driver()`

```c
int device_bind_driver(struct device *dev)
```

bind a driver to one device.

**Parameters**

- `struct device *dev`: device.

**Description**

Allow manual attachment of a driver to a device.
Caller must have already set **dev->driver**.

Note that this does not modify the bus reference count.
Please verify that is accounted for before calling this.
(It is ok to call with no other effort from a driver's `probe()` method.)

This function must be called with the device lock held.

Callers should prefer to use [`device_driver_attach()`](#c-device_driver_attach) instead.

#### <a id="c-wait_for_device_probe"></a>`wait_for_device_probe()`

```c
void wait_for_device_probe(void)
```

**Parameters**

- `void`: no arguments

**Description**

Wait for device probing to be completed.

#### <a id="c-device_attach"></a>`device_attach()`

```c
int device_attach(struct device *dev)
```

try to attach device to a driver.

**Parameters**

- `struct device *dev`: device.

**Description**

Walk the list of drivers that the bus has and call
`driver_probe_device()` for each pair. If a compatible
pair is found, break out and return.

Returns 1 if the device was bound to a driver;
0 if no matching driver was found;
-ENODEV if the device is not registered.

When called for a USB interface, **dev->parent** lock must be held.

#### <a id="c-device_driver_attach"></a>`device_driver_attach()`

```c
int device_driver_attach(const struct device_driver *drv, struct device *dev)
```

attach a specific driver to a specific device

**Parameters**

- `const struct device_driver *drv`: Driver to attach
- `struct device *dev`: Device to attach it to

**Description**

Manually attach driver to a device. Will acquire both **dev** lock and
**dev->parent** lock if needed. Returns 0 on success, -ERR on failure.

#### <a id="c-driver_attach"></a>`driver_attach()`

```c
int driver_attach(const struct device_driver *drv)
```

try to bind driver to devices.

**Parameters**

- `const struct device_driver *drv`: driver.

**Description**

Walk the list of devices that the bus has on it and try to
match the driver with each one.  If `driver_probe_device()`
returns 0 and the **dev->driver** is set, we've found a
compatible pair.

#### <a id="c-device_release_driver"></a>`device_release_driver()`

```c
void device_release_driver(struct device *dev)
```

manually detach device from driver.

**Parameters**

- `struct device *dev`: device.

**Description**

Manually detach device from driver.
When called for a USB interface, **dev->parent** lock must be held.

If this function is to be called with **dev->parent** lock held, ensure that
the device's consumers are unbound in advance or that their locks can be
acquired under the **dev->parent** lock.



#### <a id="c-platform_device_register_resndata"></a>`platform_device_register_resndata()`

```c
struct platform_device * platform_device_register_resndata(struct device *parent, const char *name, int id, const struct resource *res, unsigned int num, const void *data, size_t size)
```

add a platform-level device with resources and platform-specific data

**Parameters**

- `struct device *parent`: parent device for the device we're adding
- `const char *name`: base name of the device we're adding
- `int id`: instance id
- `const struct resource *res`: set of resources that needs to be allocated for the device
- `unsigned int num`: number of resources
- `const void *data`: platform specific data for this platform device
- `size_t size`: size of platform specific data

**Description**

Returns `struct platform_device` pointer on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

#### <a id="c-platform_device_register_simple"></a>`platform_device_register_simple()`

```c
struct platform_device * platform_device_register_simple(const char *name, int id, const struct resource *res, unsigned int num)
```

add a platform-level device and its resources

**Parameters**

- `const char *name`: base name of the device we're adding
- `int id`: instance id
- `const struct resource *res`: set of resources that needs to be allocated for the device
- `unsigned int num`: number of resources

**Description**

This function creates a simple platform device that requires minimal
resource and memory management. Canned release function freeing memory
allocated for the device allows drivers using such devices to be
unloaded without waiting for the last reference to the device to be
dropped.

This interface is primarily intended for use with legacy drivers which
probe hardware directly.  Because such drivers create sysfs device nodes
themselves, rather than letting system infrastructure handle such device
enumeration tasks, they don't fully conform to the Linux driver model.
In particular, when such drivers are built as modules, they can't be
"hotplugged".

Returns `struct platform_device` pointer on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

#### <a id="c-platform_device_register_data"></a>`platform_device_register_data()`

```c
struct platform_device * platform_device_register_data(struct device *parent, const char *name, int id, const void *data, size_t size)
```

add a platform-level device with platform-specific data

**Parameters**

- `struct device *parent`: parent device for the device we're adding
- `const char *name`: base name of the device we're adding
- `int id`: instance id
- `const void *data`: platform specific data for this platform device
- `size_t size`: size of platform specific data

**Description**

This function creates a simple platform device that requires minimal
resource and memory management. Canned release function freeing memory
allocated for the device allows drivers using such devices to be
unloaded without waiting for the last reference to the device to be
dropped.

Returns `struct platform_device` pointer on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.



#### <a id="c-platform_get_resource"></a>`platform_get_resource()`

```c
struct resource * platform_get_resource(struct platform_device *dev, unsigned int type, unsigned int num)
```

get a resource for a device

**Parameters**

- `struct platform_device *dev`: platform device
- `unsigned int type`: resource type
- `unsigned int num`: resource index

**Return**

a pointer to the resource or NULL on failure.

#### <a id="c-devm_platform_get_and_ioremap_resource"></a>`devm_platform_get_and_ioremap_resource()`

```c
void __iomem * devm_platform_get_and_ioremap_resource(struct platform_device *pdev, unsigned int index, struct resource **res)
```

call `devm_ioremap_resource()` for a platform device and get resource

**Parameters**

- `struct platform_device *pdev`: platform device to use both for memory resource lookup as well as
  resource management
- `unsigned int index`: resource index
- `struct resource **res`: optional output parameter to store a pointer to the obtained resource.

**Return**

a pointer to the remapped memory or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded error code
on failure.

#### <a id="c-devm_platform_ioremap_resource"></a>`devm_platform_ioremap_resource()`

```c
void __iomem * devm_platform_ioremap_resource(struct platform_device *pdev, unsigned int index)
```

call `devm_ioremap_resource()` for a platform device

**Parameters**

- `struct platform_device *pdev`: platform device to use both for memory resource lookup as well as
  resource management
- `unsigned int index`: resource index

**Return**

a pointer to the remapped memory or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded error code
on failure.

#### <a id="c-devm_platform_ioremap_resource_byname"></a>`devm_platform_ioremap_resource_byname()`

```c
void __iomem * devm_platform_ioremap_resource_byname(struct platform_device *pdev, const char *name)
```

call devm_ioremap_resource for a platform device, retrieve the resource by name

**Parameters**

- `struct platform_device *pdev`: platform device to use both for memory resource lookup as well as
  resource management
- `const char *name`: name of the resource

**Return**

a pointer to the remapped memory or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded error code
on failure.

#### <a id="c-platform_get_irq_affinity"></a>`platform_get_irq_affinity()`

```c
int platform_get_irq_affinity(struct platform_device *dev, unsigned int num, const struct cpumask **affinity)
```

get an optional IRQ and its affinity for a device

**Parameters**

- `struct platform_device *dev`: platform device
- `unsigned int num`: interrupt number index
- `const struct cpumask **affinity`: optional cpumask pointer to get the affinity of a per-cpu interrupt

**Description**

Gets an interupt for a platform device. Device drivers should check the
return value for errors so as to not pass a negative integer value to
the [`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq) APIs. Optional affinity information is provided in the
affinity pointer if available, and NULL otherwise.

**Return**

non-zero interrupt number on success, negative error number on failure.

#### <a id="c-platform_get_irq_optional"></a>`platform_get_irq_optional()`

```c
int platform_get_irq_optional(struct platform_device *dev, unsigned int num)
```

get an optional interrupt for a device

**Parameters**

- `struct platform_device *dev`: platform device
- `unsigned int num`: interrupt number index

**Description**

Gets an interrupt for a platform device. Device drivers should check the
return value for errors so as to not pass a negative integer value to
the [`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq) APIs. This is the same as [`platform_get_irq()`](#c-platform_get_irq), except
that it does not print an error message if an interrupt can not be
obtained.

For example:

```text
int irq = platform_get_irq_optional(pdev, 0);
if (irq < 0)
        return irq;
```

**Return**

non-zero interrupt number on success, negative error number on failure.

#### <a id="c-platform_get_irq"></a>`platform_get_irq()`

```c
int platform_get_irq(struct platform_device *dev, unsigned int num)
```

get an IRQ for a device

**Parameters**

- `struct platform_device *dev`: platform device
- `unsigned int num`: IRQ number index

**Description**

Gets an IRQ for a platform device and prints an error message if finding the
IRQ fails. Device drivers should check the return value for errors so as to
not pass a negative integer value to the [`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq) APIs.

For example:

```text
int irq = platform_get_irq(pdev, 0);
if (irq < 0)
        return irq;
```

**Return**

non-zero IRQ number on success, negative error number on failure.

#### <a id="c-platform_irq_count"></a>`platform_irq_count()`

```c
int platform_irq_count(struct platform_device *dev)
```

Count the number of IRQs a platform device uses

**Parameters**

- `struct platform_device *dev`: platform device

**Return**

Number of IRQs a platform device uses or EPROBE_DEFER

#### <a id="c-devm_platform_get_irqs_affinity"></a>`devm_platform_get_irqs_affinity()`

```c
int devm_platform_get_irqs_affinity(struct platform_device *dev, struct irq_affinity *affd, unsigned int minvec, unsigned int maxvec, int **irqs)
```

devm method to get a set of IRQs for a device using an interrupt affinity descriptor

**Parameters**

- `struct platform_device *dev`: platform device pointer
- `struct irq_affinity *affd`: affinity descriptor
- `unsigned int minvec`: minimum count of interrupt vectors
- `unsigned int maxvec`: maximum count of interrupt vectors
- `int **irqs`: pointer holder for IRQ numbers

**Description**

Gets a set of IRQs for a platform device, and updates IRQ afffinty according
to the passed affinity descriptor

**Return**

Number of vectors on success, negative error number on failure.

#### <a id="c-platform_get_resource_byname"></a>`platform_get_resource_byname()`

```c
struct resource * platform_get_resource_byname(struct platform_device *dev, unsigned int type, const char *name)
```

get a resource for a device by name

**Parameters**

- `struct platform_device *dev`: platform device
- `unsigned int type`: resource type
- `const char *name`: resource name

#### <a id="c-platform_get_irq_byname"></a>`platform_get_irq_byname()`

```c
int platform_get_irq_byname(struct platform_device *dev, const char *name)
```

get an IRQ for a device by name

**Parameters**

- `struct platform_device *dev`: platform device
- `const char *name`: IRQ name

**Description**

Get an IRQ like [`platform_get_irq()`](#c-platform_get_irq), but then by name rather then by index.

**Return**

non-zero IRQ number on success, negative error number on failure.

#### <a id="c-platform_get_irq_byname_optional"></a>`platform_get_irq_byname_optional()`

```c
int platform_get_irq_byname_optional(struct platform_device *dev, const char *name)
```

get an optional IRQ for a device by name

**Parameters**

- `struct platform_device *dev`: platform device
- `const char *name`: IRQ name

**Description**

Get an optional IRQ by name like [`platform_get_irq_byname()`](#c-platform_get_irq_byname). Except that it
does not print an error message if an IRQ can not be obtained.

**Return**

non-zero IRQ number on success, negative error number on failure.

#### <a id="c-platform_add_devices"></a>`platform_add_devices()`

```c
int platform_add_devices(struct platform_device **devs, int num)
```

add a numbers of platform devices

**Parameters**

- `struct platform_device **devs`: array of platform devices to add
- `int num`: number of platform devices in array

**Return**

0 on success, negative error number on failure.

#### <a id="c-platform_device_put"></a>`platform_device_put()`

```c
void platform_device_put(struct platform_device *pdev)
```

destroy a platform device

**Parameters**

- `struct platform_device *pdev`: platform device to free

**Description**

Free all memory associated with a platform device.  This function must
_only_ be externally called in error cases.  All other usage is a bug.

#### <a id="c-platform_device_alloc"></a>`platform_device_alloc()`

```c
struct platform_device * platform_device_alloc(const char *name, int id)
```

create a platform device

**Parameters**

- `const char *name`: base name of the device we're adding
- `int id`: instance id

**Description**

Create a platform device object which can have other objects attached
to it, and which will have attached objects freed when it is released.

#### <a id="c-platform_device_add_resources"></a>`platform_device_add_resources()`

```c
int platform_device_add_resources(struct platform_device *pdev, const struct resource *res, unsigned int num)
```

add resources to a platform device

**Parameters**

- `struct platform_device *pdev`: platform device allocated by platform_device_alloc to add resources to
- `const struct resource *res`: set of resources that needs to be allocated for the device
- `unsigned int num`: number of resources

**Description**

Add a copy of the resources to the platform device.  The memory
associated with the resources will be freed when the platform device is
released.

#### <a id="c-platform_device_add_data"></a>`platform_device_add_data()`

```c
int platform_device_add_data(struct platform_device *pdev, const void *data, size_t size)
```

add platform-specific data to a platform device

**Parameters**

- `struct platform_device *pdev`: platform device allocated by platform_device_alloc to add resources to
- `const void *data`: platform specific data for this platform device
- `size_t size`: size of platform specific data

**Description**

Add a copy of platform specific data to the platform device's
platform_data pointer.  The memory associated with the platform data
will be freed when the platform device is released.

#### <a id="c-platform_device_add"></a>`platform_device_add()`

```c
int platform_device_add(struct platform_device *pdev)
```

add a platform device to device hierarchy

**Parameters**

- `struct platform_device *pdev`: platform device we're adding

**Description**

This is part 2 of [`platform_device_register()`](#c-platform_device_register), though may be called
separately _iff_ pdev was allocated by [`platform_device_alloc()`](#c-platform_device_alloc).

#### <a id="c-platform_device_del"></a>`platform_device_del()`

```c
void platform_device_del(struct platform_device *pdev)
```

remove a platform-level device

**Parameters**

- `struct platform_device *pdev`: platform device we're removing

**Description**

Note that this function will also release all memory- and port-based
resources owned by the device (**dev->resource**).  This function must
_only_ be externally called in error cases.  All other usage is a bug.

#### <a id="c-platform_device_register"></a>`platform_device_register()`

```c
int platform_device_register(struct platform_device *pdev)
```

add a platform-level device

**Parameters**

- `struct platform_device *pdev`: platform device we're adding

**NOTE**

_Never_ directly free **pdev** after calling this function, even if it
returned an error! Always use [`platform_device_put()`](#c-platform_device_put) to give up the
reference initialised in this function instead.

#### <a id="c-platform_device_unregister"></a>`platform_device_unregister()`

```c
void platform_device_unregister(struct platform_device *pdev)
```

unregister a platform-level device

**Parameters**

- `struct platform_device *pdev`: platform device we're unregistering

**Description**

Unregistration is done in 2 steps. First we release all resources
and remove it from the subsystem, then we drop reference count by
calling [`platform_device_put()`](#c-platform_device_put).

#### <a id="c-platform_device_register_full"></a>`platform_device_register_full()`

```c
struct platform_device * platform_device_register_full(const struct platform_device_info *pdevinfo)
```

add a platform-level device with resources and platform-specific data

**Parameters**

- `const struct platform_device_info *pdevinfo`: data used to create device

**Description**

Returns `struct platform_device` pointer on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

#### <a id="c-__platform_driver_register"></a>`__platform_driver_register()`

```c
int __platform_driver_register(struct platform_driver *drv, struct module *owner)
```

register a driver for platform-level devices

**Parameters**

- `struct platform_driver *drv`: platform driver structure
- `struct module *owner`: owning module/driver

#### <a id="c-platform_driver_unregister"></a>`platform_driver_unregister()`

```c
void platform_driver_unregister(struct platform_driver *drv)
```

unregister a driver for platform-level devices

**Parameters**

- `struct platform_driver *drv`: platform driver structure

#### <a id="c-__platform_driver_probe"></a>`__platform_driver_probe()`

```c
int __platform_driver_probe(struct platform_driver *drv, int (*probe)(struct platform_device *), struct module *module)
```

register driver for non-hotpluggable device

**Parameters**

- `struct platform_driver *drv`: platform driver structure
- `int (*probe)(struct platform_device *)`: the driver probe routine, probably from an __init section
- `struct module *module`: module which will be the owner of the driver

**Description**

Use this instead of `platform_driver_register()` when you know the device
is not hotpluggable and has already been registered, and you want to
remove its run-once `probe()` infrastructure from memory after the driver
has bound to the device.

One typical use for this would be with drivers for controllers integrated
into system-on-chip processors, where the controller devices have been
configured as part of board setup.

Note that this is incompatible with deferred probing.

Returns zero if the driver registered and bound to a device, else returns
a negative error code and with the driver not registered.

#### <a id="c-__platform_create_bundle"></a>`__platform_create_bundle()`

```c
struct platform_device * __platform_create_bundle(struct platform_driver *driver, int (*probe)(struct platform_device *), struct resource *res, unsigned int n_res, const void *data, size_t size, struct module *module)
```

register driver and create corresponding device

**Parameters**

- `struct platform_driver *driver`: platform driver structure
- `int (*probe)(struct platform_device *)`: the driver probe routine, probably from an __init section
- `struct resource *res`: set of resources that needs to be allocated for the device
- `unsigned int n_res`: number of resources
- `const void *data`: platform specific data for this platform device
- `size_t size`: size of platform specific data
- `struct module *module`: module which will be the owner of the driver

**Description**

Use this in legacy-style modules that probe hardware directly and
register a single platform device and corresponding platform driver.

Returns `struct platform_device` pointer on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

#### <a id="c-__platform_register_drivers"></a>`__platform_register_drivers()`

```c
int __platform_register_drivers(struct platform_driver * const *drivers, unsigned int count, struct module *owner)
```

register an array of platform drivers

**Parameters**

- `struct platform_driver * const *drivers`: an array of drivers to register
- `unsigned int count`: the number of drivers to register
- `struct module *owner`: module owning the drivers

**Description**

Registers platform drivers specified by an array. On failure to register a
driver, all previously registered drivers will be unregistered. Callers of
this API should use [`platform_unregister_drivers()`](#c-platform_unregister_drivers) to unregister drivers in
the reverse order.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-platform_unregister_drivers"></a>`platform_unregister_drivers()`

```c
void platform_unregister_drivers(struct platform_driver * const *drivers, unsigned int count)
```

unregister an array of platform drivers

**Parameters**

- `struct platform_driver * const *drivers`: an array of drivers to unregister
- `unsigned int count`: the number of drivers to unregister

**Description**

Unregisters platform drivers specified by an array. This is typically used
to complement an earlier call to `platform_register_drivers()`. Drivers are
unregistered in the reverse order in which they were registered.

#### <a id="c-platform_find_device_by_driver"></a>`platform_find_device_by_driver()`

```c
struct device * platform_find_device_by_driver(struct device *start, const struct device_driver *drv)
```

Find a platform device with a given driver.

**Parameters**

- `struct device *start`: The device to start the search from.
- `const struct device_driver *drv`: The device driver to look for.



#### <a id="c-bus_find_device_by_name"></a>`bus_find_device_by_name()`

```c
struct device * bus_find_device_by_name(const struct bus_type *bus, struct device *start, const char *name)
```

device iterator for locating a particular device of a specific name.

**Parameters**

- `const struct bus_type *bus`: bus type
- `struct device *start`: Device to begin with
- `const char *name`: name of the device to match

#### <a id="c-bus_find_device_by_of_node"></a>`bus_find_device_by_of_node()`

```c
struct device * bus_find_device_by_of_node(const struct bus_type *bus, const struct device_node *np)
```

device iterator for locating a particular device matching the of_node.

**Parameters**

- `const struct bus_type *bus`: bus type
- `const struct device_node *np`: of_node of the device to match.

#### <a id="c-bus_find_device_by_fwnode"></a>`bus_find_device_by_fwnode()`

```c
struct device * bus_find_device_by_fwnode(const struct bus_type *bus, const struct fwnode_handle *fwnode)
```

device iterator for locating a particular device matching the fwnode.

**Parameters**

- `const struct bus_type *bus`: bus type
- `const struct fwnode_handle *fwnode`: fwnode of the device to match.

#### <a id="c-bus_find_device_by_devt"></a>`bus_find_device_by_devt()`

```c
struct device * bus_find_device_by_devt(const struct bus_type *bus, dev_t devt)
```

device iterator for locating a particular device matching the device type.

**Parameters**

- `const struct bus_type *bus`: bus type
- `dev_t devt`: device type of the device to match.

#### <a id="c-bus_find_next_device"></a>`bus_find_next_device()`

```c
struct device * bus_find_next_device(const struct bus_type *bus, struct device *cur)
```

Find the next device after a given device in a given bus.

**Parameters**

- `const struct bus_type *bus`: bus type
- `struct device *cur`: device to begin the search with.

#### <a id="c-bus_find_device_by_acpi_dev"></a>`bus_find_device_by_acpi_dev()`

```c
struct device * bus_find_device_by_acpi_dev(const struct bus_type *bus, const struct acpi_device *adev)
```

device iterator for locating a particular device matching the ACPI COMPANION device.

**Parameters**

- `const struct bus_type *bus`: bus type
- `const struct acpi_device *adev`: ACPI COMPANION device to match.



#### <a id="c-bus_for_each_dev"></a>`bus_for_each_dev()`

```c
int bus_for_each_dev(const struct bus_type *bus, struct device *start, void *data, device_iter_t fn)
```

device iterator.

**Parameters**

- `const struct bus_type *bus`: bus type.
- `struct device *start`: device to start iterating from.
- `void *data`: data for the callback.
- `device_iter_t fn`: function to be called for each device.

**Description**

Iterate over **bus**'s list of devices, and call **fn** for each,
passing it **data**. If **start** is not NULL, we use that device to
begin iterating from.

We check the return of **fn** each time. If it returns anything
other than 0, we break out and return that value.

**NOTE**

The device that returns a non-zero value is not retained
in any way, nor is its refcount incremented. If the caller needs
to retain this data, it should do so, and increment the reference
count in the supplied callback.

#### <a id="c-bus_find_device"></a>`bus_find_device()`

```c
struct device * bus_find_device(const struct bus_type *bus, struct device *start, const void *data, device_match_t match)
```

device iterator for locating a particular device.

**Parameters**

- `const struct bus_type *bus`: bus type
- `struct device *start`: Device to begin with
- `const void *data`: Data to pass to match function
- `device_match_t match`: Callback function to check device

**Description**

This is similar to the [`bus_for_each_dev()`](#c-bus_for_each_dev) function above, but it
returns a reference to a device that is 'found' for later use, as
determined by the **match** callback.

The callback should return 0 if the device doesn't match and non-zero
if it does.  If the callback returns non-zero, this function will
return to the caller and not iterate over any more devices.

#### <a id="c-bus_for_each_drv"></a>`bus_for_each_drv()`

```c
int bus_for_each_drv(const struct bus_type *bus, struct device_driver *start, void *data, int (*fn)(struct device_driver *, void *))
```

driver iterator

**Parameters**

- `const struct bus_type *bus`: bus we're dealing with.
- `struct device_driver *start`: driver to start iterating on.
- `void *data`: data to pass to the callback.
- `int (*fn)(struct device_driver *, void *)`: function to call for each driver.

**Description**

This is nearly identical to the device iterator above.
We iterate over each driver that belongs to **bus**, and call
**fn** for each. If **fn** returns anything but 0, we break out
and return it. If **start** is not NULL, we use it as the head
of the list.

**NOTE**

we don't return the driver that returns a non-zero
value, nor do we leave the reference count incremented for that
driver. If the caller needs to know that info, it must set it
in the callback. It must also be sure to increment the refcount
so it doesn't disappear before returning to the caller.

#### <a id="c-bus_rescan_devices"></a>`bus_rescan_devices()`

```c
int bus_rescan_devices(const struct bus_type *bus)
```

rescan devices on the bus for possible drivers

**Parameters**

- `const struct bus_type *bus`: the bus to scan.

**Description**

This function will look for devices on the bus with no driver
attached and rescan it against existing drivers to see if it matches
any by calling [`device_attach()`](#c-device_attach) for the unbound devices.

#### <a id="c-device_reprobe"></a>`device_reprobe()`

```c
int device_reprobe(struct device *dev)
```

remove driver for a device and probe for a new driver

**Parameters**

- `struct device *dev`: the device to reprobe

**Description**

This function detaches the attached driver (if any) for the given
device and restarts the driver probing process.  It is intended
to use if probing criteria changed during a devices lifetime and
driver attachment should change accordingly.

#### <a id="c-bus_register"></a>`bus_register()`

```c
int bus_register(const struct bus_type *bus)
```

register a driver-core subsystem

**Parameters**

- `const struct bus_type *bus`: bus to register

**Description**

Once we have that, we register the bus with the kobject
infrastructure, then register the children subsystems it has:
the devices and drivers that belong to the subsystem.

#### <a id="c-bus_unregister"></a>`bus_unregister()`

```c
void bus_unregister(const struct bus_type *bus)
```

remove a bus from the system

**Parameters**

- `const struct bus_type *bus`: bus.

**Description**

Unregister the child subsystems and the bus itself.
Finally, we call `bus_put()` to release the refcount

#### <a id="c-subsys_system_register"></a>`subsys_system_register()`

```c
int subsys_system_register(const struct bus_type *subsys, const struct attribute_group **groups)
```

register a subsystem at /sys/devices/system/

**Parameters**

- `const struct bus_type *subsys`: system subsystem
- `const struct attribute_group **groups`: default attributes for the root device

**Description**

All 'system' subsystems have a /sys/devices/system/\<name> root device
with the name of the subsystem. The root device can carry subsystem-
wide attributes. All registered devices are below this single root
device and are named after the subsystem with a simple enumeration
number appended. The registered devices are not explicitly named;
only 'id' in the device needs to be set.

Do not use this interface for anything new, it exists for compatibility
with bad ideas only. New subsystems should use plain subsystems; and
add the subsystem-wide attributes should be added to the subsystem
directory itself and not some create fake root-device placed in
/sys/devices/system/\<name>.

#### <a id="c-subsys_virtual_register"></a>`subsys_virtual_register()`

```c
int subsys_virtual_register(const struct bus_type *subsys, const struct attribute_group **groups)
```

register a subsystem at /sys/devices/virtual/

**Parameters**

- `const struct bus_type *subsys`: virtual subsystem
- `const struct attribute_group **groups`: default attributes for the root device

**Description**

All 'virtual' subsystems have a /sys/devices/system/\<name> root device
with the name of the subsystem.  The root device can carry subsystem-wide
attributes.  All registered devices are below this single root device.
There's no restriction on device naming.  This is for kernel software
constructs which need sysfs interface.

#### <a id="c-driver_find"></a>`driver_find()`

```c
struct device_driver * driver_find(const char *name, const struct bus_type *bus)
```

locate driver on a bus by its name.

**Parameters**

- `const char *name`: name of the driver.
- `const struct bus_type *bus`: bus to scan for the driver.

**Description**

Call [`kset_find_obj()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-kset_find_obj) to iterate over list of drivers on
a bus to find driver by name. Return driver if found.

This routine provides no locking to prevent the driver it returns
from being unregistered or unloaded while the caller is using it.
The caller is responsible for preventing this.

#### <a id="c-bus_get_dev_root"></a>`bus_get_dev_root()`

```c
struct device * bus_get_dev_root(const struct bus_type *bus)
```

return a pointer to the "device root" of a bus

**Parameters**

- `const struct bus_type *bus`: bus to return the device root of.

**Description**

If a bus has a "device root" structure, return it, WITH THE REFERENCE
COUNT INCREMENTED.

Note, when finished with the device, a call to [`put_device()`](#c-put_device) is required.

If the device root is not present (or bus is not a valid pointer), NULL
will be returned.


<a id="rst-device-drivers-dma-management"></a>

## Device Drivers DMA Management


#### <a id="c-dmam_free_coherent"></a>`dmam_free_coherent()`

```c
void dmam_free_coherent(struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle)
```

Managed `dma_free_coherent()`

**Parameters**

- `struct device *dev`: Device to free coherent memory for
- `size_t size`: Size of allocation
- `void *vaddr`: Virtual address of the memory to free
- `dma_addr_t dma_handle`: DMA handle of the memory to free

**Description**

Managed `dma_free_coherent()`.

#### <a id="c-dmam_alloc_attrs"></a>`dmam_alloc_attrs()`

```c
void * dmam_alloc_attrs(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs)
```

Managed `dma_alloc_attrs()`

**Parameters**

- `struct device *dev`: Device to allocate non_coherent memory for
- `size_t size`: Size of allocation
- `dma_addr_t *dma_handle`: Out argument for allocated DMA handle
- `gfp_t gfp`: Allocation flags
- `unsigned long attrs`: Flags in the DMA_ATTR_* namespace.

**Description**

Managed `dma_alloc_attrs()`.  Memory allocated using this function will be
automatically released on driver detach.

**Return**

Pointer to allocated memory on success, NULL on failure.

#### <a id="c-dma_map_sg_attrs"></a>`dma_map_sg_attrs()`

```c
unsigned int dma_map_sg_attrs(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction dir, unsigned long attrs)
```

Map the given buffer for DMA

**Parameters**

- `struct device *dev`: The device for which to perform the DMA operation
- `struct scatterlist *sg`: The sg_table object describing the buffer
- `int nents`: Number of entries to map
- `enum dma_data_direction dir`: DMA direction
- `unsigned long attrs`: Optional DMA attributes for the map operation

**Description**

Maps a buffer described by a scatterlist passed in the sg argument with
nents segments for the **dir** DMA operation by the **dev** device.

Returns the number of mapped entries (which can be less than nents)
on success. Zero is returned for any error.

`dma_unmap_sg_attrs()` should be used to unmap the buffer with the
original sg and original nents (not the value returned by this funciton).

#### <a id="c-dma_map_sgtable"></a>`dma_map_sgtable()`

```c
int dma_map_sgtable(struct device *dev, struct sg_table *sgt, enum dma_data_direction dir, unsigned long attrs)
```

Map the given buffer for DMA

**Parameters**

- `struct device *dev`: The device for which to perform the DMA operation
- `struct sg_table *sgt`: The sg_table object describing the buffer
- `enum dma_data_direction dir`: DMA direction
- `unsigned long attrs`: Optional DMA attributes for the map operation

**Description**

Maps a buffer described by a scatterlist stored in the given sg_table
object for the **dir** DMA operation by the **dev** device. After success, the
ownership for the buffer is transferred to the DMA domain.  One has to
call `dma_sync_sgtable_for_cpu()` or `dma_unmap_sgtable()` to move the
ownership of the buffer back to the CPU domain before touching the
buffer by the CPU.

Returns 0 on success or a negative error code on error. The following
error codes are supported with the given meaning:

- -EINVAL            An invalid argument, unaligned access or other error

  in usage. Will not succeed if retried.
  - -ENOMEM            Insufficient resources (like memory or IOVA space) to

    complete the mapping. Should succeed if retried later.
  - -EIO               Legacy error code with an unknown meaning. eg. this is

    returned if a lower level call returned
    DMA_MAPPING_ERROR.
  - -EREMOTEIO         The DMA device cannot access P2PDMA memory specified

    in the sg_table. This will not succeed if retried.

#### <a id="c-dma_need_unmap"></a>`dma_need_unmap()`

```c
bool dma_need_unmap(struct device *dev)
```

does this device need dma_unmap_* operations

**Parameters**

- `struct device *dev`: device to check

**Description**

If this function returns `false`, drivers can skip calling dma_unmap_* after
finishing an I/O.  This function must be called after all mappings that might
need to be unmapped have been performed.

#### <a id="c-dma_can_mmap"></a>`dma_can_mmap()`

```c
bool dma_can_mmap(struct device *dev)
```

check if a given device supports dma_mmap_*

**Parameters**

- `struct device *dev`: device to check

**Description**

Returns `true` if **dev** supports `dma_mmap_coherent()` and [`dma_mmap_attrs()`](#c-dma_mmap_attrs) to
map DMA allocations to userspace.

#### <a id="c-dma_mmap_attrs"></a>`dma_mmap_attrs()`

```c
int dma_mmap_attrs(struct device *dev, struct vm_area_struct *vma, void *cpu_addr, dma_addr_t dma_addr, size_t size, unsigned long attrs)
```

map a coherent DMA allocation into user space

**Parameters**

- `struct device *dev`: valid struct device pointer, or NULL for ISA and EISA-like devices
- `struct vm_area_struct *vma`: vm_area_struct describing requested user mapping
- `void *cpu_addr`: kernel CPU-view address returned from dma_alloc_attrs
- `dma_addr_t dma_addr`: device-view address returned from dma_alloc_attrs
- `size_t size`: size of memory originally requested in dma_alloc_attrs
- `unsigned long attrs`: attributes of mapping properties requested in dma_alloc_attrs

**Description**

Map a coherent DMA buffer previously allocated by dma_alloc_attrs into user
space.  The coherent DMA buffer must not be freed by the driver until the
user space mapping has been released.

#### <a id="c-dma_addressing_limited"></a>`dma_addressing_limited()`

```c
bool dma_addressing_limited(struct device *dev)
```

return if the device is addressing limited

**Parameters**

- `struct device *dev`: device to check

**Description**

Return `true` if the devices DMA mask is too small to address all memory in
the system, else `false`.  Lack of addressing bits is the prime reason for
bounce buffering, but might not be the only one.


<a id="rst-device-drivers-pnp-support"></a>

## Device drivers PnP support


#### <a id="c-pnp_register_protocol"></a>`pnp_register_protocol()`

```c
int pnp_register_protocol(struct pnp_protocol *protocol)
```

adds a pnp protocol to the pnp layer

**Parameters**

- `struct pnp_protocol *protocol`: pointer to the corresponding pnp_protocol structure

**Description**

Ex protocols: ISAPNP, PNPBIOS, etc



#### <a id="c-pnp_request_card_device"></a>`pnp_request_card_device()`

```c
struct pnp_dev * pnp_request_card_device(struct pnp_card_link *clink, const char *id, struct pnp_dev *from)
```

Searches for a PnP device under the specified card

**Parameters**

- `struct pnp_card_link *clink`: pointer to the card link, cannot be NULL
- `const char *id`: pointer to a PnP ID structure that explains the rules for finding the device
- `struct pnp_dev *from`: Starting place to search from. If NULL it will start from the beginning.

#### <a id="c-pnp_release_card_device"></a>`pnp_release_card_device()`

```c
void pnp_release_card_device(struct pnp_dev *dev)
```

call this when the driver no longer needs the device

**Parameters**

- `struct pnp_dev *dev`: pointer to the PnP device structure

#### <a id="c-pnp_register_card_driver"></a>`pnp_register_card_driver()`

```c
int pnp_register_card_driver(struct pnp_card_driver *drv)
```

registers a PnP card driver with the PnP Layer

**Parameters**

- `struct pnp_card_driver *drv`: pointer to the driver to register

#### <a id="c-pnp_unregister_card_driver"></a>`pnp_unregister_card_driver()`

```c
void pnp_unregister_card_driver(struct pnp_card_driver *drv)
```

unregisters a PnP card driver from the PnP Layer

**Parameters**

- `struct pnp_card_driver *drv`: pointer to the driver to unregister



#### <a id="c-pnp_add_id"></a>`pnp_add_id()`

```c
struct pnp_id * pnp_add_id(struct pnp_dev *dev, const char *id)
```

adds an EISA id to the specified device

**Parameters**

- `struct pnp_dev *dev`: pointer to the desired device
- `const char *id`: pointer to an EISA id string



#### <a id="c-pnp_start_dev"></a>`pnp_start_dev()`

```c
int pnp_start_dev(struct pnp_dev *dev)
```

low-level start of the PnP device

**Parameters**

- `struct pnp_dev *dev`: pointer to the desired device

**Description**

assumes that resources have already been allocated

#### <a id="c-pnp_stop_dev"></a>`pnp_stop_dev()`

```c
int pnp_stop_dev(struct pnp_dev *dev)
```

low-level disable of the PnP device

**Parameters**

- `struct pnp_dev *dev`: pointer to the desired device

**Description**

does not free resources

#### <a id="c-pnp_activate_dev"></a>`pnp_activate_dev()`

```c
int pnp_activate_dev(struct pnp_dev *dev)
```

activates a PnP device for use

**Parameters**

- `struct pnp_dev *dev`: pointer to the desired device

**Description**

does not validate or set resources so be careful.

#### <a id="c-pnp_disable_dev"></a>`pnp_disable_dev()`

```c
int pnp_disable_dev(struct pnp_dev *dev)
```

disables device

**Parameters**

- `struct pnp_dev *dev`: pointer to the desired device

**Description**

inform the correct pnp protocol so that resources can be used by other devices



#### <a id="c-pnp_is_active"></a>`pnp_is_active()`

```c
int pnp_is_active(struct pnp_dev *dev)
```

Determines if a device is active based on its current resources

**Parameters**

- `struct pnp_dev *dev`: pointer to the desired PnP device


<a id="rst-userspace-io-devices"></a>

## Userspace IO devices


#### <a id="c-uio_event_notify"></a>`uio_event_notify()`

```c
void uio_event_notify(struct uio_info *info)
```

trigger an interrupt event

**Parameters**

- `struct uio_info *info`: UIO device capabilities

#### <a id="c-__uio_register_device"></a>`__uio_register_device()`

```c
int __uio_register_device(struct module *owner, struct device *parent, struct uio_info *info)
```

register a new userspace IO device

**Parameters**

- `struct module *owner`: module that creates the new device
- `struct device *parent`: parent device
- `struct uio_info *info`: UIO device capabilities

**Description**

returns zero on success or a negative error code.

#### <a id="c-__devm_uio_register_device"></a>`__devm_uio_register_device()`

```c
int __devm_uio_register_device(struct module *owner, struct device *parent, struct uio_info *info)
```

Resource managed [`uio_register_device()`](#c-uio_register_device)

**Parameters**

- `struct module *owner`: module that creates the new device
- `struct device *parent`: parent device
- `struct uio_info *info`: UIO device capabilities

**Description**

returns zero on success or a negative error code.

#### <a id="c-uio_unregister_device"></a>`uio_unregister_device()`

```c
void uio_unregister_device(struct uio_info *info)
```

unregister a industrial IO device

**Parameters**

- `struct uio_info *info`: UIO device capabilities



#### <a id="c-struct-uio_mem"></a>`struct uio_mem`

description of a UIO memory region

**Definition**

```c
struct uio_mem {
    const char              *name;
    phys_addr_t addr;
    dma_addr_t dma_addr;
    unsigned long           offs;
    resource_size_t size;
    int memtype;
    void __iomem            *internal_addr;
    struct device           *dma_device;
    struct uio_map          *map;
};
```

**Members**

- `name`: name of the memory region for identification
- `addr`: address of the device's memory rounded to page
  size (phys_addr is used since addr can be
  logical, virtual, or physical & phys_addr_t
  should always be large enough to handle any of
  the address types)
- `dma_addr`: DMA handle set by dma_alloc_coherent, used with
  UIO_MEM_DMA_COHERENT only (**addr** should be the
  void * returned from the same dma_alloc_coherent call)
- `offs`: offset of device memory within the page
- `size`: size of IO (multiple of page size)
- `memtype`: type of memory addr points to
- `internal_addr`: ioremap-ped version of addr, for driver internal use
- `dma_device`: device struct that was passed to dma_alloc_coherent,
  used with UIO_MEM_DMA_COHERENT only
- `map`: for use by the UIO core only.

#### <a id="c-struct-uio_port"></a>`struct uio_port`

description of a UIO port region

**Definition**

```c
struct uio_port {
    const char              *name;
    unsigned long           start;
    unsigned long           size;
    int porttype;
    struct uio_portio       *portio;
};
```

**Members**

- `name`: name of the port region for identification
- `start`: start of port region
- `size`: size of port region
- `porttype`: type of port (see UIO_PORT_* below)
- `portio`: for use by the UIO core only.

#### <a id="c-struct-uio_info"></a>`struct uio_info`

UIO device capabilities

**Definition**

```c
struct uio_info {
    struct uio_device       *uio_dev;
    const char              *name;
    const char              *version;
    struct uio_mem          mem[MAX_UIO_MAPS];
    struct uio_port         port[MAX_UIO_PORT_REGIONS];
    long irq;
    unsigned long           irq_flags;
    void *priv;
    irqreturn_t (*handler)(int irq, struct uio_info *dev_info);
    int (*mmap)(struct uio_info *info, struct vm_area_struct *vma);
    int (*open)(struct uio_info *info, struct inode *inode);
    int (*release)(struct uio_info *info, struct inode *inode);
    int (*irqcontrol)(struct uio_info *info, s32 irq_on);
};
```

**Members**

- `uio_dev`: the UIO device this info belongs to
- `name`: device name
- `version`: device driver version
- `mem`: list of mappable memory regions, size==0 for end of list
- `port`: list of port regions, size==0 for end of list
- `irq`: interrupt number or UIO_IRQ_CUSTOM
- `irq_flags`: flags for [`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq)
- `priv`: optional private data
- `handler`: the device's irq handler
- `mmap`: mmap operation for this uio device
- `open`: open operation for this uio device
- `release`: release operation for this uio device
- `irqcontrol`: disable/enable irqs when 0/1 is written to /dev/uioX

#### <a id="c-uio_register_device"></a>`uio_register_device()`

```c
uio_register_device(parent, info)
```

register a new userspace IO device

**Parameters**

- `parent`: parent device
- `info`: UIO device capabilities

**Description**

returns zero on success or a negative error code.

#### <a id="c-devm_uio_register_device"></a>`devm_uio_register_device()`

```c
devm_uio_register_device(parent, info)
```

Resource managed [`uio_register_device()`](#c-uio_register_device)

**Parameters**

- `parent`: parent device
- `info`: UIO device capabilities

**Description**

returns zero on success or a negative error code.

---

# Message-based devices

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> Reference for Message-based devices.

<a id="rst-message-based-devices"></a>

<a id="rst-fusion-message-devices"></a>

## Fusion message devices


#### <a id="c-mpt_register"></a>`mpt_register()`

```c
u8 mpt_register(MPT_CALLBACK cbfunc, MPT_DRIVER_CLASS dclass, char *func_name)
```

Register protocol-specific main callback handler.

**Parameters**

- `MPT_CALLBACK cbfunc`: callback function pointer
- `MPT_DRIVER_CLASS dclass`: Protocol driver's class (`MPT_DRIVER_CLASS` enum value)
- `char *func_name`: call function's name

**Description**

This routine is called by a protocol-specific driver (SCSI host,
LAN, SCSI target) to register its reply callback routine.  Each
protocol-specific driver must do this before it will be able to
use any IOC resources, such as obtaining request frames.

**NOTES**

- The SCSI protocol driver currently calls this routine thrice

  in order to register separate callbacks; one for "normal" SCSI IO;
  one for MptScsiTaskMgmt requests; one for Scan/DV requests.

  Returns u8 valued "handle" in the range (and S.O.D. order)
  {N,...,7,6,5,...,1} if successful.
  A return value of MPT_MAX_PROTOCOL_DRIVERS (including zero!) should be
  considered an error by the caller.

#### <a id="c-mpt_deregister"></a>`mpt_deregister()`

```c
void mpt_deregister(u8 cb_idx)
```

Deregister a protocol drivers resources.

**Parameters**

- `u8 cb_idx`: previously registered callback handle

**Description**

Each protocol-specific driver should call this routine when its
module is unloaded.

#### <a id="c-mpt_event_register"></a>`mpt_event_register()`

```c
int mpt_event_register(u8 cb_idx, MPT_EVHANDLER ev_cbfunc)
```

Register protocol-specific event callback handler.

**Parameters**

- `u8 cb_idx`: previously registered (via mpt_register) callback handle
- `MPT_EVHANDLER ev_cbfunc`: callback function

**Description**

This routine can be called by one or more protocol-specific drivers
if/when they choose to be notified of MPT events.

Returns 0 for success.

#### <a id="c-mpt_event_deregister"></a>`mpt_event_deregister()`

```c
void mpt_event_deregister(u8 cb_idx)
```

Deregister protocol-specific event callback handler

**Parameters**

- `u8 cb_idx`: previously registered callback handle

**Description**

Each protocol-specific driver should call this routine
when it does not (or can no longer) handle events,
or when its module is unloaded.

#### <a id="c-mpt_reset_register"></a>`mpt_reset_register()`

```c
int mpt_reset_register(u8 cb_idx, MPT_RESETHANDLER reset_func)
```

Register protocol-specific IOC reset handler.

**Parameters**

- `u8 cb_idx`: previously registered (via mpt_register) callback handle
- `MPT_RESETHANDLER reset_func`: reset function

**Description**

This routine can be called by one or more protocol-specific drivers
if/when they choose to be notified of IOC resets.

Returns 0 for success.

#### <a id="c-mpt_reset_deregister"></a>`mpt_reset_deregister()`

```c
void mpt_reset_deregister(u8 cb_idx)
```

Deregister protocol-specific IOC reset handler.

**Parameters**

- `u8 cb_idx`: previously registered callback handle

**Description**

Each protocol-specific driver should call this routine
when it does not (or can no longer) handle IOC reset handling,
or when its module is unloaded.

#### <a id="c-mpt_device_driver_register"></a>`mpt_device_driver_register()`

```c
int mpt_device_driver_register(struct mpt_pci_driver * dd_cbfunc, u8 cb_idx)
```

Register device driver hooks

**Parameters**

- `struct mpt_pci_driver * dd_cbfunc`: driver callbacks struct
- `u8 cb_idx`: MPT protocol driver index

#### <a id="c-mpt_device_driver_deregister"></a>`mpt_device_driver_deregister()`

```c
void mpt_device_driver_deregister(u8 cb_idx)
```

DeRegister device driver hooks

**Parameters**

- `u8 cb_idx`: MPT protocol driver index

#### <a id="c-mpt_get_msg_frame"></a>`mpt_get_msg_frame()`

```c
MPT_FRAME_HDR* mpt_get_msg_frame(u8 cb_idx, MPT_ADAPTER *ioc)
```

Obtain an MPT request frame from the pool

**Parameters**

- `u8 cb_idx`: Handle of registered MPT protocol driver
- `MPT_ADAPTER *ioc`: Pointer to MPT adapter structure

**Description**

Obtain an MPT request frame from the pool (of 1024) that are
allocated per MPT adapter.

Returns pointer to a MPT request frame or `NULL` if none are available
or IOC is not active.

#### <a id="c-mpt_put_msg_frame"></a>`mpt_put_msg_frame()`

```c
void mpt_put_msg_frame(u8 cb_idx, MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)
```

Send a protocol-specific MPT request frame to an IOC

**Parameters**

- `u8 cb_idx`: Handle of registered MPT protocol driver
- `MPT_ADAPTER *ioc`: Pointer to MPT adapter structure
- `MPT_FRAME_HDR *mf`: Pointer to MPT request frame

**Description**

This routine posts an MPT request frame to the request post FIFO of a
specific MPT adapter.

#### <a id="c-mpt_put_msg_frame_hi_pri"></a>`mpt_put_msg_frame_hi_pri()`

```c
void mpt_put_msg_frame_hi_pri(u8 cb_idx, MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)
```

Send a hi-pri protocol-specific MPT request frame

**Parameters**

- `u8 cb_idx`: Handle of registered MPT protocol driver
- `MPT_ADAPTER *ioc`: Pointer to MPT adapter structure
- `MPT_FRAME_HDR *mf`: Pointer to MPT request frame

**Description**

Send a protocol-specific MPT request frame to an IOC using
hi-priority request queue.

This routine posts an MPT request frame to the request post FIFO of a
specific MPT adapter.

#### <a id="c-mpt_free_msg_frame"></a>`mpt_free_msg_frame()`

```c
void mpt_free_msg_frame(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)
```

Place MPT request frame back on FreeQ.

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT adapter structure
- `MPT_FRAME_HDR *mf`: Pointer to MPT request frame

**Description**

This routine places a MPT request frame back on the MPT adapter's
FreeQ.

#### <a id="c-mpt_send_handshake_request"></a>`mpt_send_handshake_request()`

```c
int mpt_send_handshake_request(u8 cb_idx, MPT_ADAPTER *ioc, int reqBytes, u32 *req, int sleepFlag)
```

Send MPT request via doorbell handshake method.

**Parameters**

- `u8 cb_idx`: Handle of registered MPT protocol driver
- `MPT_ADAPTER *ioc`: Pointer to MPT adapter structure
- `int reqBytes`: Size of the request in bytes
- `u32 *req`: Pointer to MPT request frame
- `int sleepFlag`: Use schedule if CAN_SLEEP else use udelay.

**Description**

This routine is used exclusively to send MptScsiTaskMgmt
requests since they are required to be sent via doorbell handshake.

**NOTE**

- It is the callers responsibility to byte-swap fields in the

  request which are greater than 1 byte in size.

  Returns 0 for success, non-zero for failure.

#### <a id="c-mpt_verify_adapter"></a>`mpt_verify_adapter()`

```c
int mpt_verify_adapter(int iocid, MPT_ADAPTER **iocpp)
```

Given IOC identifier, set pointer to its adapter structure.

**Parameters**

- `int iocid`: IOC unique identifier (integer)
- `MPT_ADAPTER **iocpp`: Pointer to pointer to IOC adapter

**Description**

Given a unique IOC identifier, set pointer to the associated MPT
adapter structure.

Returns iocid and sets iocpp if iocid is found.
Returns -1 if iocid is not found.

#### <a id="c-mpt_attach"></a>`mpt_attach()`

```c
int mpt_attach(struct pci_dev *pdev, const struct pci_device_id *id)
```

Install a PCI intelligent MPT adapter.

**Parameters**

- `struct pci_dev *pdev`: Pointer to pci_dev structure
- `const struct pci_device_id *id`: PCI device ID information

**Description**

This routine performs all the steps necessary to bring the IOC of
a MPT adapter to a OPERATIONAL state.  This includes registering
memory regions, registering the interrupt, and allocating request
and reply memory pools.

This routine also pre-fetches the LAN MAC address of a Fibre Channel
MPT adapter.

Returns 0 for success, non-zero for failure.

TODO: Add support for polled controllers

#### <a id="c-mpt_detach"></a>`mpt_detach()`

```c
void mpt_detach(struct pci_dev *pdev)
```

Remove a PCI intelligent MPT adapter.

**Parameters**

- `struct pci_dev *pdev`: Pointer to pci_dev structure

#### <a id="c-mpt_suspend"></a>`mpt_suspend()`

```c
int mpt_suspend(struct pci_dev *pdev, pm_message_t state)
```

Fusion MPT base driver suspend routine.

**Parameters**

- `struct pci_dev *pdev`: Pointer to pci_dev structure
- `pm_message_t state`: new state to enter

#### <a id="c-mpt_resume"></a>`mpt_resume()`

```c
int mpt_resume(struct pci_dev *pdev)
```

Fusion MPT base driver resume routine.

**Parameters**

- `struct pci_dev *pdev`: Pointer to pci_dev structure

#### <a id="c-mpt_GetIocState"></a>`mpt_GetIocState()`

```c
u32 mpt_GetIocState(MPT_ADAPTER *ioc, int cooked)
```

Get the current state of a MPT adapter.

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure
- `int cooked`: Request raw or cooked IOC state

**Description**

Returns all IOC Doorbell register bits if cooked==0, else just the
Doorbell bits in MPI_IOC_STATE_MASK.

#### <a id="c-mpt_alloc_fw_memory"></a>`mpt_alloc_fw_memory()`

```c
int mpt_alloc_fw_memory(MPT_ADAPTER *ioc, int size)
```

allocate firmware memory

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure
- `int size`: total FW bytes

**Description**

If memory has already been allocated, the same (cached) value
is returned.

Return 0 if successful, or non-zero for failure

#### <a id="c-mpt_free_fw_memory"></a>`mpt_free_fw_memory()`

```c
void mpt_free_fw_memory(MPT_ADAPTER *ioc)
```

free firmware memory

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure

**Description**

If alt_img is NULL, delete from ioc structure.
Else, delete a secondary image in same format.

#### <a id="c-mptbase_sas_persist_operation"></a>`mptbase_sas_persist_operation()`

```c
int mptbase_sas_persist_operation(MPT_ADAPTER *ioc, u8 persist_opcode)
```

Perform operation on SAS Persistent Table

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure
- `u8 persist_opcode`: see below

**Description**

```text
===============================  ======================================
MPI_SAS_OP_CLEAR_NOT_PRESENT     Free all persist TargetID mappings for
                                 devices not currently present.
MPI_SAS_OP_CLEAR_ALL_PERSISTENT  Clear al persist TargetID mappings
===============================  ======================================
```

**NOTE**

Don't use not this function during interrupt time.

Returns 0 for success, non-zero error

#### <a id="c-mpt_raid_phys_disk_pg0"></a>`mpt_raid_phys_disk_pg0()`

```c
int mpt_raid_phys_disk_pg0(MPT_ADAPTER *ioc, u8 phys_disk_num, RaidPhysDiskPage0_t *phys_disk)
```

returns phys disk page zero

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to a Adapter Structure
- `u8 phys_disk_num`: io unit unique phys disk num generated by the ioc
- `RaidPhysDiskPage0_t *phys_disk`: requested payload data returned

**Return**

0 on success
-EFAULT if read of config page header fails or data pointer not NULL
-ENOMEM if pci_alloc failed

#### <a id="c-mpt_raid_phys_disk_get_num_paths"></a>`mpt_raid_phys_disk_get_num_paths()`

```c
int mpt_raid_phys_disk_get_num_paths(MPT_ADAPTER *ioc, u8 phys_disk_num)
```

returns number paths associated to this phys_num

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to a Adapter Structure
- `u8 phys_disk_num`: io unit unique phys disk num generated by the ioc

**Return**

returns number paths

#### <a id="c-mpt_raid_phys_disk_pg1"></a>`mpt_raid_phys_disk_pg1()`

```c
int mpt_raid_phys_disk_pg1(MPT_ADAPTER *ioc, u8 phys_disk_num, RaidPhysDiskPage1_t *phys_disk)
```

returns phys disk page 1

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to a Adapter Structure
- `u8 phys_disk_num`: io unit unique phys disk num generated by the ioc
- `RaidPhysDiskPage1_t *phys_disk`: requested payload data returned

**Return**

0 on success
-EFAULT if read of config page header fails or data pointer not NULL
-ENOMEM if pci_alloc failed

#### <a id="c-mpt_findImVolumes"></a>`mpt_findImVolumes()`

```c
int mpt_findImVolumes(MPT_ADAPTER *ioc)
```

Identify IDs of hidden disks and RAID Volumes

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to a Adapter Strucutre

**Return**

0 on success
-EFAULT if read of config page header fails or data pointer not NULL
-ENOMEM if pci_alloc failed

#### <a id="c-mpt_config"></a>`mpt_config()`

```c
int mpt_config(MPT_ADAPTER *ioc, CONFIGPARMS *pCfg)
```

Generic function to issue config message

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to an adapter structure
- `CONFIGPARMS *pCfg`: Pointer to a configuration structure. Struct contains
  action, page address, direction, physical address
  and pointer to a configuration page header
  Page header is updated.

**Description**

Returns 0 for success
-EAGAIN if no msg frames currently available
-EFAULT for non-successful reply or no reply (timeout)

#### <a id="c-mpt_print_ioc_summary"></a>`mpt_print_ioc_summary()`

```c
void mpt_print_ioc_summary(MPT_ADAPTER *ioc, char *buffer, int *size, int len, int showlan)
```

Write ASCII summary of IOC to a buffer.

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure
- `char *buffer`: Pointer to buffer where IOC summary info should be written
- `int *size`: Pointer to number of bytes we wrote (set by this routine)
- `int len`: Offset at which to start writing in buffer
- `int showlan`: Display LAN stuff?

**Description**

This routine writes (english readable) ASCII text, which represents
a summary of IOC information, to a buffer.

#### <a id="c-mpt_set_taskmgmt_in_progress_flag"></a>`mpt_set_taskmgmt_in_progress_flag()`

```c
int mpt_set_taskmgmt_in_progress_flag(MPT_ADAPTER *ioc)
```

set flags associated with task management

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure

**Description**

Returns 0 for SUCCESS or -1 if FAILED.

If -1 is return, then it was not possible to set the flags

#### <a id="c-mpt_clear_taskmgmt_in_progress_flag"></a>`mpt_clear_taskmgmt_in_progress_flag()`

```c
void mpt_clear_taskmgmt_in_progress_flag(MPT_ADAPTER *ioc)
```

clear flags associated with task management

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure

#### <a id="c-mpt_halt_firmware"></a>`mpt_halt_firmware()`

```c
void __noreturn mpt_halt_firmware(MPT_ADAPTER *ioc)
```

Halts the firmware if it is operational and panic the kernel

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure

#### <a id="c-mpt_Soft_Hard_ResetHandler"></a>`mpt_Soft_Hard_ResetHandler()`

```c
int mpt_Soft_Hard_ResetHandler(MPT_ADAPTER *ioc, int sleepFlag)
```

Try less expensive reset

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure
- `int sleepFlag`: Indicates if sleep or schedule must be called.

**Description**

Returns 0 for SUCCESS or -1 if FAILED.
Try for softreset first, only if it fails go for expensive
HardReset.

#### <a id="c-mpt_HardResetHandler"></a>`mpt_HardResetHandler()`

```c
int mpt_HardResetHandler(MPT_ADAPTER *ioc, int sleepFlag)
```

Generic reset handler

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure
- `int sleepFlag`: Indicates if sleep or schedule must be called.

**Description**

Issues SCSI Task Management call based on input arg values.
If TaskMgmt fails, returns associated SCSI request.

Remark: _HardResetHandler can be invoked from an interrupt thread (timer)
or a non-interrupt thread.  In the former, must not call `schedule()`.

**Note**

- A return of -1 is a FATAL error case, as it means a

  FW reload/initialization failed.

  Returns 0 for SUCCESS or -1 if FAILED.



#### <a id="c-mptscsih_info"></a>`mptscsih_info()`

```c
const char * mptscsih_info(struct Scsi_Host *SChost)
```

Return information about MPT adapter

**Parameters**

- `struct Scsi_Host *SChost`: Pointer to Scsi_Host structure

**Description**

(linux scsi_host_template.info routine)

Returns pointer to buffer where information was written.

#### <a id="c-mptscsih_qcmd"></a>`mptscsih_qcmd()`

```c
enum scsi_qc_status mptscsih_qcmd(struct scsi_cmnd *SCpnt)
```

Primary Fusion MPT SCSI initiator IO start routine.

**Parameters**

- `struct scsi_cmnd *SCpnt`: Pointer to scsi_cmnd structure

**Description**

(linux scsi_host_template.queuecommand routine)
This is the primary SCSI IO start routine.  Create a MPI SCSIIORequest
from a linux scsi_cmnd request and send it to the IOC.

Returns 0. (rtn value discarded by linux scsi mid-layer)

#### <a id="c-mptscsih_IssueTaskMgmt"></a>`mptscsih_IssueTaskMgmt()`

```c
int mptscsih_IssueTaskMgmt(MPT_SCSI_HOST *hd, u8 type, u8 channel, u8 id, u64 lun, int ctx2abort, ulong timeout)
```

Generic send Task Management function.

**Parameters**

- `MPT_SCSI_HOST *hd`: Pointer to MPT_SCSI_HOST structure
- `u8 type`: Task Management type
- `u8 channel`: channel number for task management
- `u8 id`: Logical Target ID for reset (if appropriate)
- `u64 lun`: Logical Unit for reset (if appropriate)
- `int ctx2abort`: Context for the task to be aborted (if appropriate)
- `ulong timeout`: timeout for task management control

**Description**

Remark: _HardResetHandler can be invoked from an interrupt thread (timer)
or a non-interrupt thread.  In the former, must not call `schedule()`.

Not all fields are meaningfull for all task types.

Returns 0 for SUCCESS, or FAILED.

#### <a id="c-mptscsih_abort"></a>`mptscsih_abort()`

```c
int mptscsih_abort(struct scsi_cmnd * SCpnt)
```

Abort linux scsi_cmnd routine, new_eh variant

**Parameters**

- `struct scsi_cmnd * SCpnt`: Pointer to scsi_cmnd structure, IO to be aborted

**Description**

(linux scsi_host_template.eh_abort_handler routine)

Returns SUCCESS or FAILED.

#### <a id="c-mptscsih_dev_reset"></a>`mptscsih_dev_reset()`

```c
int mptscsih_dev_reset(struct scsi_cmnd * SCpnt)
```

Perform a SCSI LOGICAL_UNIT_RESET!

**Parameters**

- `struct scsi_cmnd * SCpnt`: Pointer to scsi_cmnd structure, IO which reset is due to

**Description**

(linux scsi_host_template.eh_dev_reset_handler routine)

Returns SUCCESS or FAILED.

#### <a id="c-mptscsih_bus_reset"></a>`mptscsih_bus_reset()`

```c
int mptscsih_bus_reset(struct scsi_cmnd * SCpnt)
```

Perform a SCSI BUS_RESET! new_eh variant

**Parameters**

- `struct scsi_cmnd * SCpnt`: Pointer to scsi_cmnd structure, IO which reset is due to

**Description**

(linux scsi_host_template.eh_bus_reset_handler routine)

Returns SUCCESS or FAILED.

#### <a id="c-mptscsih_host_reset"></a>`mptscsih_host_reset()`

```c
int mptscsih_host_reset(struct scsi_cmnd *SCpnt)
```

Perform a SCSI host adapter RESET (new_eh variant)

**Parameters**

- `struct scsi_cmnd *SCpnt`: Pointer to scsi_cmnd structure, IO which reset is due to

**Description**

(linux scsi_host_template.eh_host_reset_handler routine)

Returns SUCCESS or FAILED.

#### <a id="c-mptscsih_taskmgmt_complete"></a>`mptscsih_taskmgmt_complete()`

```c
int mptscsih_taskmgmt_complete(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf, MPT_FRAME_HDR *mr)
```

Registered with Fusion MPT base driver

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure
- `MPT_FRAME_HDR *mf`: Pointer to SCSI task mgmt request frame
- `MPT_FRAME_HDR *mr`: Pointer to SCSI task mgmt reply frame

**Description**

This routine is called from mptbase.c::`mpt_interrupt()` at the completion
of any SCSI task management request.
This routine is registered with the MPT (base) driver at driver
load/init time via the [`mpt_register()`](#c-mpt_register) API call.

Returns 1 indicating alloc'd request frame ptr should be freed.

#### <a id="c-mptscsih_get_scsi_lookup"></a>`mptscsih_get_scsi_lookup()`

```c
struct scsi_cmnd * mptscsih_get_scsi_lookup(MPT_ADAPTER *ioc, int i)
```

retrieves scmd entry

**Parameters**

- `MPT_ADAPTER *ioc`: Pointer to MPT_ADAPTER structure
- `int i`: index into the array

**Description**

Returns the scsi_cmd pointer

---

# Miscellaneous Devices

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> Reference for Miscellaneous Devices.

<a id="rst-miscellaneous-devices"></a>


#### <a id="c-misc_register"></a>`misc_register()`

```c
int misc_register(struct miscdevice *misc)
```

register a miscellaneous device

**Parameters**

- `struct miscdevice *misc`: device structure

**Description**

Register a miscellaneous device with the kernel. If the minor
number is set to `MISC_DYNAMIC_MINOR` a minor number is assigned
and placed in the minor field of the structure. For other cases
the minor number requested is used.

The structure passed is linked into the kernel and may not be
destroyed until it has been unregistered. By default, an `open()`
syscall to the device sets file->private_data to point to the
structure. Drivers don't need open in fops for this.

A zero is returned on success and a negative errno code for
failure.

#### <a id="c-misc_deregister"></a>`misc_deregister()`

```c
void misc_deregister(struct miscdevice *misc)
```

unregister a miscellaneous device

**Parameters**

- `struct miscdevice *misc`: device to unregister

**Description**

Unregister a miscellaneous device that was previously
successfully registered with [`misc_register()`](#c-misc_register).

---

# Parallel Port Devices

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> See serial/driver.rst for related APIs.

<a id="rst-parallel-port-devices"></a>

## Parallel Port Devices


#### <a id="c-parport_register_driver"></a>`parport_register_driver()`

```c
parport_register_driver(driver)
```

register a parallel port device driver

**Parameters**

- `driver`: structure describing the driver

**Description**

This can be called by a parallel port device driver in order
to receive notifications about ports being found in the
system, as well as ports no longer available.

The **driver** structure is allocated by the caller and must not be
deallocated until after calling [`parport_unregister_driver()`](#c-parport_unregister_driver).

If using the non device model:
The driver's `attach()` function may block.  The port that
`attach()` is given will be valid for the duration of the
callback, but if the driver wants to take a copy of the
pointer it must call [`parport_get_port()`](#c-parport_get_port) to do so.  Calling
`parport_register_device()` on that port will do this for you.

The driver's `detach()` function may block.  The port that
`detach()` is given will be valid for the duration of the
callback, but if the driver wants to take a copy of the
pointer it must call [`parport_get_port()`](#c-parport_get_port) to do so.

Returns 0 on success. The non device model will always succeeds.
but the new device model can fail and will return the error code.

#### <a id="c-module_parport_driver"></a>`module_parport_driver()`

```c
module_parport_driver(__parport_driver)
```

Helper macro for registering a modular parport driver

**Parameters**

- `__parport_driver`: struct parport_driver to be used

**Description**

Helper macro for parport drivers which do not do anything special in module
init and exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit).

#### <a id="c-parport_yield"></a>`parport_yield()`

```c
int parport_yield(struct pardevice *dev)
```

relinquish a parallel port temporarily

**Parameters**

- `struct pardevice *dev`: a device on the parallel port

**Description**

This function relinquishes the port if it would be helpful to other
drivers to do so.  Afterwards it tries to reclaim the port using
[`parport_claim()`](#c-parport_claim), and the return value is the same as for
[`parport_claim()`](#c-parport_claim).  If it fails, the port is left unclaimed and it is
the driver's responsibility to reclaim the port.

The [`parport_yield()`](#c-parport_yield) and [`parport_yield_blocking()`](#c-parport_yield_blocking) functions are for
marking points in the driver at which other drivers may claim the
port and use their devices.  Yielding the port is similar to
releasing it and reclaiming it, but is more efficient because no
action is taken if there are no other devices needing the port.  In
fact, nothing is done even if there are other devices waiting but
the current device is still within its "timeslice".  The default
timeslice is half a second, but it can be adjusted via the /proc
interface.

#### <a id="c-parport_yield_blocking"></a>`parport_yield_blocking()`

```c
int parport_yield_blocking(struct pardevice *dev)
```

relinquish a parallel port temporarily

**Parameters**

- `struct pardevice *dev`: a device on the parallel port

**Description**

This function relinquishes the port if it would be helpful to other
drivers to do so.  Afterwards it tries to reclaim the port using
[`parport_claim_or_block()`](#c-parport_claim_or_block), and the return value is the same as for
[`parport_claim_or_block()`](#c-parport_claim_or_block).



#### <a id="c-parport_wait_event"></a>`parport_wait_event()`

```c
int parport_wait_event(struct parport *port, signed long timeout)
```

wait for an event on a parallel port

**Parameters**

- `struct parport *port`: port to wait on
- `signed long timeout`: time to wait (in jiffies)

**Description**

This function waits for up to **timeout** jiffies for an
interrupt to occur on a parallel port.  If the port timeout is
set to zero, it returns immediately.

If an interrupt occurs before the timeout period elapses, this
function returns zero immediately.  If it times out, it returns
one.  An error code less than zero indicates an error (most
likely a pending signal), and the calling code should finish
what it's doing as soon as it can.

#### <a id="c-parport_wait_peripheral"></a>`parport_wait_peripheral()`

```c
int parport_wait_peripheral(struct parport *port, unsigned char mask, unsigned char result)
```

wait for status lines to change in 35ms

**Parameters**

- `struct parport *port`: port to watch
- `unsigned char mask`: status lines to watch
- `unsigned char result`: desired values of chosen status lines

**Description**

This function waits until the masked status lines have the
desired values, or until 35ms have elapsed (see IEEE 1284-1994
page 24 to 25 for why this value in particular is hardcoded).
The **mask** and **result** parameters are bitmasks, with the bits
defined by the constants in parport.h: `PARPORT_STATUS_BUSY`,
and so on.

The port is polled quickly to start off with, in anticipation
of a fast response from the peripheral.  This fast polling
time is configurable (using /proc), and defaults to 500usec.
If the timeout for this port (see [`parport_set_timeout()`](#c-parport_set_timeout)) is
zero, the fast polling time is 35ms, and this function does
not call `schedule()`.

If the timeout for this port is non-zero, after the fast
polling fails it uses [`parport_wait_event()`](#c-parport_wait_event) to wait for up to
10ms, waking up if an interrupt occurs.

#### <a id="c-parport_negotiate"></a>`parport_negotiate()`

```c
int parport_negotiate(struct parport *port, int mode)
```

negotiate an IEEE 1284 mode

**Parameters**

- `struct parport *port`: port to use
- `int mode`: mode to negotiate to

**Description**

Use this to negotiate to a particular IEEE 1284 transfer mode.
The **mode** parameter should be one of the constants in
parport.h starting `IEEE1284_MODE_xxx`.

The return value is 0 if the peripheral has accepted the
negotiation to the mode specified, -1 if the peripheral is not
IEEE 1284 compliant (or not present), or 1 if the peripheral
has rejected the negotiation.

#### <a id="c-parport_write"></a>`parport_write()`

```c
ssize_t parport_write(struct parport *port, const void *buffer, size_t len)
```

write a block of data to a parallel port

**Parameters**

- `struct parport *port`: port to write to
- `const void *buffer`: data buffer (in kernel space)
- `size_t len`: number of bytes of data to transfer

**Description**

This will write up to **len** bytes of **buffer** to the port
specified, using the IEEE 1284 transfer mode most recently
negotiated to (using [`parport_negotiate()`](#c-parport_negotiate)), as long as that
mode supports forward transfers (host to peripheral).

It is the caller's responsibility to ensure that the first
**len** bytes of **buffer** are valid.

This function returns the number of bytes transferred (if zero
or positive), or else an error code.

#### <a id="c-parport_read"></a>`parport_read()`

```c
ssize_t parport_read(struct parport *port, void *buffer, size_t len)
```

read a block of data from a parallel port

**Parameters**

- `struct parport *port`: port to read from
- `void *buffer`: data buffer (in kernel space)
- `size_t len`: number of bytes of data to transfer

**Description**

This will read up to **len** bytes of **buffer** to the port
specified, using the IEEE 1284 transfer mode most recently
negotiated to (using [`parport_negotiate()`](#c-parport_negotiate)), as long as that
mode supports reverse transfers (peripheral to host).

It is the caller's responsibility to ensure that the first
**len** bytes of **buffer** are available to write to.

This function returns the number of bytes transferred (if zero
or positive), or else an error code.

#### <a id="c-parport_set_timeout"></a>`parport_set_timeout()`

```c
long parport_set_timeout(struct pardevice *dev, long inactivity)
```

set the inactivity timeout for a device

**Parameters**

- `struct pardevice *dev`: device on a port
- `long inactivity`: inactivity timeout (in jiffies)

**Description**

This sets the inactivity timeout for a particular device on a
port.  This affects functions like [`parport_wait_peripheral()`](#c-parport_wait_peripheral).
The special value 0 means not to call `schedule()` while dealing
with this device.

The return value is the previous inactivity timeout.

Any callers of [`parport_wait_event()`](#c-parport_wait_event) for this device are woken
up.



#### <a id="c-__parport_register_driver"></a>`__parport_register_driver()`

```c
int __parport_register_driver(struct parport_driver *drv, struct module *owner, const char *mod_name)
```

register a parallel port device driver

**Parameters**

- `struct parport_driver *drv`: structure describing the driver
- `struct module *owner`: owner module of drv
- `const char *mod_name`: module name string

**Description**

This can be called by a parallel port device driver in order
to receive notifications about ports being found in the
system, as well as ports no longer available.

If devmodel is true then the new device model is used
for registration.

The **drv** structure is allocated by the caller and must not be
deallocated until after calling [`parport_unregister_driver()`](#c-parport_unregister_driver).

If using the non device model:
The driver's `attach()` function may block.  The port that
`attach()` is given will be valid for the duration of the
callback, but if the driver wants to take a copy of the
pointer it must call [`parport_get_port()`](#c-parport_get_port) to do so.  Calling
`parport_register_device()` on that port will do this for you.

The driver's `detach()` function may block.  The port that
`detach()` is given will be valid for the duration of the
callback, but if the driver wants to take a copy of the
pointer it must call [`parport_get_port()`](#c-parport_get_port) to do so.

Returns 0 on success. The non device model will always succeeds.
but the new device model can fail and will return the error code.

#### <a id="c-parport_unregister_driver"></a>`parport_unregister_driver()`

```c
void parport_unregister_driver(struct parport_driver *drv)
```

deregister a parallel port device driver

**Parameters**

- `struct parport_driver *drv`: structure describing the driver that was given to
  [`parport_register_driver()`](#c-parport_register_driver)

**Description**

This should be called by a parallel port device driver that
has registered itself using [`parport_register_driver()`](#c-parport_register_driver) when it
is about to be unloaded.

When it returns, the driver's `attach()` routine will no longer
be called, and for each port that `attach()` was called for, the
`detach()` routine will have been called.

All the driver's `attach()` and `detach()` calls are guaranteed to have
finished by the time this function returns.

#### <a id="c-parport_get_port"></a>`parport_get_port()`

```c
struct parport * parport_get_port(struct parport *port)
```

increment a port's reference count

**Parameters**

- `struct parport *port`: the port

**Description**

This ensures that a struct parport pointer remains valid
until the matching [`parport_put_port()`](#c-parport_put_port) call.

#### <a id="c-parport_put_port"></a>`parport_put_port()`

```c
void parport_put_port(struct parport *port)
```

decrement a port's reference count

**Parameters**

- `struct parport *port`: the port

**Description**

This should be called once for each call to [`parport_get_port()`](#c-parport_get_port),
once the port is no longer needed. When the reference count reaches
zero (port is no longer used), free_port is called.

#### <a id="c-parport_register_port"></a>`parport_register_port()`

```c
struct parport * parport_register_port(unsigned long base, int irq, int dma, struct parport_operations *ops)
```

register a parallel port

**Parameters**

- `unsigned long base`: base I/O address
- `int irq`: IRQ line
- `int dma`: DMA channel
- `struct parport_operations *ops`: pointer to the port driver's port operations structure

**Description**

When a parallel port (lowlevel) driver finds a port that
should be made available to parallel port device drivers, it
should call [`parport_register_port()`](#c-parport_register_port).  The **base**, **irq**, and
**dma** parameters are for the convenience of port drivers, and
for ports where they aren't meaningful needn't be set to
anything special.  They can be altered afterwards by adjusting
the relevant members of the parport structure that is returned
and represents the port.  They should not be tampered with
after calling parport_announce_port, however.

If there are parallel port device drivers in the system that
have registered themselves using [`parport_register_driver()`](#c-parport_register_driver),
they are not told about the port at this time; that is done by
[`parport_announce_port()`](#c-parport_announce_port).

The **ops** structure is allocated by the caller, and must not be
deallocated before calling [`parport_remove_port()`](#c-parport_remove_port).

If there is no memory to allocate a new parport structure,
this function will return `NULL`.

#### <a id="c-parport_announce_port"></a>`parport_announce_port()`

```c
void parport_announce_port(struct parport *port)
```

tell device drivers about a parallel port

**Parameters**

- `struct parport *port`: parallel port to announce

**Description**

After a port driver has registered a parallel port with
parport_register_port, and performed any necessary
initialisation or adjustments, it should call
[`parport_announce_port()`](#c-parport_announce_port) in order to notify all device drivers
that have called [`parport_register_driver()`](#c-parport_register_driver).  Their `attach()`
functions will be called, with **port** as the parameter.

#### <a id="c-parport_remove_port"></a>`parport_remove_port()`

```c
void parport_remove_port(struct parport *port)
```

deregister a parallel port

**Parameters**

- `struct parport *port`: parallel port to deregister

**Description**

When a parallel port driver is forcibly unloaded, or a
parallel port becomes inaccessible, the port driver must call
this function in order to deal with device drivers that still
want to use it.

The parport structure associated with the port has its
operations structure replaced with one containing 'null'
operations that return errors or just don't do anything.

Any drivers that have registered themselves using
[`parport_register_driver()`](#c-parport_register_driver) are notified that the port is no
longer accessible by having their `detach()` routines called
with **port** as the parameter.

#### <a id="c-parport_register_dev_model"></a>`parport_register_dev_model()`

```c
struct pardevice * parport_register_dev_model(struct parport *port, const char *name, const struct pardev_cb *par_dev_cb, int id)
```

register a device on a parallel port

**Parameters**

- `struct parport *port`: port to which the device is attached
- `const char *name`: a name to refer to the device
- `const struct pardev_cb *par_dev_cb`: struct containing callbacks
- `int id`: device number to be given to the device

**Description**

This function, called by parallel port device drivers,
declares that a device is connected to a port, and tells the
system all it needs to know.

The struct pardev_cb contains pointer to callbacks. preemption
callback function, **preempt**, is called when this device driver
has claimed access to the port but another device driver wants
to use it.  It is given, **private**, as its parameter, and should
return zero if it is willing for the system to release the port
to another driver on its behalf. If it wants to keep control of
the port it should return non-zero, and no action will be taken.
It is good manners for the driver to try to release the port at
the earliest opportunity after its preemption callback rejects a
preemption attempt. Note that if a preemption callback is happy
for preemption to go ahead, there is no need to release the
port; it is done automatically. This function may not block, as
it may be called from interrupt context. If the device driver
does not support preemption, **preempt** can be `NULL`.

The wake-up ("kick") callback function, **wakeup**, is called when
the port is available to be claimed for exclusive access; that
is, [`parport_claim()`](#c-parport_claim) is guaranteed to succeed when called from
inside the wake-up callback function.  If the driver wants to
claim the port it should do so; otherwise, it need not take
any action.  This function may not block, as it may be called
from interrupt context.  If the device driver does not want to
be explicitly invited to claim the port in this way, **wakeup** can
be `NULL`.

The interrupt handler, **irq_func**, is called when an interrupt
arrives from the parallel port.  Note that if a device driver
wants to use interrupts it should use `parport_enable_irq()`,
and can also check the irq member of the parport structure
representing the port.

The parallel port (lowlevel) driver is the one that has called
[`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq) and whose interrupt handler is called first.
This handler does whatever needs to be done to the hardware to
acknowledge the interrupt (for PC-style ports there is nothing
special to be done).  It then tells the IEEE 1284 code about
the interrupt, which may involve reacting to an IEEE 1284
event depending on the current IEEE 1284 phase.  After this,
it calls **irq_func**.  Needless to say, **irq_func** will be called
from interrupt context, and may not block.

The `PARPORT_DEV_EXCL` flag is for preventing port sharing, and
so should only be used when sharing the port with other device
drivers is impossible and would lead to incorrect behaviour.
Use it sparingly!  Normally, **flags** will be zero.

This function returns a pointer to a structure that represents
the device on the port, or `NULL` if there is not enough memory
to allocate space for that structure.

#### <a id="c-parport_unregister_device"></a>`parport_unregister_device()`

```c
void parport_unregister_device(struct pardevice *dev)
```

deregister a device on a parallel port

**Parameters**

- `struct pardevice *dev`: pointer to structure representing device

**Description**

This undoes the effect of `parport_register_device()`.

#### <a id="c-parport_find_number"></a>`parport_find_number()`

```c
struct parport * parport_find_number(int number)
```

find a parallel port by number

**Parameters**

- `int number`: parallel port number

**Description**

This returns the parallel port with the specified number, or
`NULL` if there is none.

There is an implicit [`parport_get_port()`](#c-parport_get_port) done already; to throw
away the reference to the port that [`parport_find_number()`](#c-parport_find_number)
gives you, use [`parport_put_port()`](#c-parport_put_port).

#### <a id="c-parport_find_base"></a>`parport_find_base()`

```c
struct parport * parport_find_base(unsigned long base)
```

find a parallel port by base address

**Parameters**

- `unsigned long base`: base I/O address

**Description**

This returns the parallel port with the specified base
address, or `NULL` if there is none.

There is an implicit [`parport_get_port()`](#c-parport_get_port) done already; to throw
away the reference to the port that [`parport_find_base()`](#c-parport_find_base)
gives you, use [`parport_put_port()`](#c-parport_put_port).

#### <a id="c-parport_claim"></a>`parport_claim()`

```c
int parport_claim(struct pardevice *dev)
```

claim access to a parallel port device

**Parameters**

- `struct pardevice *dev`: pointer to structure representing a device on the port

**Description**

This function will not block and so can be used from interrupt
context.  If [`parport_claim()`](#c-parport_claim) succeeds in claiming access to
the port it returns zero and the port is available to use.  It
may fail (returning non-zero) if the port is in use by another
driver and that driver is not willing to relinquish control of
the port.

#### <a id="c-parport_claim_or_block"></a>`parport_claim_or_block()`

```c
int parport_claim_or_block(struct pardevice *dev)
```

claim access to a parallel port device

**Parameters**

- `struct pardevice *dev`: pointer to structure representing a device on the port

**Description**

This behaves like [`parport_claim()`](#c-parport_claim), but will block if necessary
to wait for the port to be free.  A return value of 1
indicates that it slept; 0 means that it succeeded without
needing to sleep.  A negative error code indicates failure.

#### <a id="c-parport_release"></a>`parport_release()`

```c
void parport_release(struct pardevice *dev)
```

give up access to a parallel port device

**Parameters**

- `struct pardevice *dev`: pointer to structure representing parallel port device

**Description**

This function cannot fail, but it should not be called without
the port claimed.  Similarly, if the port is already claimed
you should not try claiming it again.



#### <a id="c-parport_open"></a>`parport_open()`

```c
struct pardevice * parport_open(int devnum, const char *name)
```

find a device by canonical device number

**Parameters**

- `int devnum`: canonical device number
- `const char *name`: name to associate with the device

**Description**

This function is similar to `parport_register_device()`, except
that it locates a device by its number rather than by the port
it is attached to.

All parameters except for **devnum** are the same as for
`parport_register_device()`.  The return value is the same as
for `parport_register_device()`.

#### <a id="c-parport_close"></a>`parport_close()`

```c
void parport_close(struct pardevice *dev)
```

close a device opened with [`parport_open()`](#c-parport_open)

**Parameters**

- `struct pardevice *dev`: device to close

**Description**

This is to [`parport_open()`](#c-parport_open) as [`parport_unregister_device()`](#c-parport_unregister_device) is to
`parport_register_device()`.


<a id="rst-x50-uart-driver"></a>

## 16x50 UART Driver


#### <a id="c-serial8250_get_port"></a>`serial8250_get_port()`

```c
struct uart_8250_port * serial8250_get_port(int line)
```

retrieve struct uart_8250_port

**Parameters**

- `int line`: serial line number

**Description**

This function retrieves struct uart_8250_port for the specific line.
This struct *must* *not* be used to perform a 8250 or serial core operation
which is not accessible otherwise. Its only purpose is to make the struct
accessible to the runtime-pm callbacks for context suspend/restore.
The lock assumption made here is none because runtime-pm suspend/resume
callbacks should not be invoked if there is any operation performed on the
port.

#### <a id="c-serial8250_suspend_port"></a>`serial8250_suspend_port()`

```c
void serial8250_suspend_port(int line)
```

suspend one serial port

**Parameters**

- `int line`: serial line number

**Description**

Suspend one serial port.

#### <a id="c-serial8250_resume_port"></a>`serial8250_resume_port()`

```c
void serial8250_resume_port(int line)
```

resume one serial port

**Parameters**

- `int line`: serial line number

**Description**

Resume one serial port.

#### <a id="c-serial8250_register_8250_port"></a>`serial8250_register_8250_port()`

```c
int serial8250_register_8250_port(const struct uart_8250_port *up)
```

register a serial port

**Parameters**

- `const struct uart_8250_port *up`: serial port template

**Description**

Configure the serial port specified by the request. If the
port exists and is in use, it is hung up and unregistered
first.

The port is then probed and if necessary the IRQ is autodetected
If this fails an error is returned.

On success the port is ready to use and the line number is returned.

#### <a id="c-serial8250_unregister_port"></a>`serial8250_unregister_port()`

```c
void serial8250_unregister_port(int line)
```

remove a 16x50 serial port at runtime

**Parameters**

- `int line`: serial line number

**Description**

Remove one serial port.  This may not be called from interrupt
context.  We hand the port back to the our control.


See serial/driver.rst for related APIs.

<a id="rst-pulse-width-modulation-pwm"></a>

## Pulse-Width Modulation (PWM)

Pulse-width modulation is a modulation technique primarily used to control power supplied to electrical devices.

The PWM framework provides an abstraction for providers and consumers of PWM signals. A controller that provides one or more PWM signals is registered as `struct pwm_chip <pwm_chip>`. Providers are expected to embed this structure in a driver-specific structure. This structure contains fields that describe a particular chip.

A chip exposes one or more PWM signal sources, each of which exposed as a `struct pwm_device <pwm_device>`. Operations can be performed on PWM devices to control the period, duty cycle, polarity and active state of the signal.

Note that PWM devices are exclusive resources: they can always only be used by one consumer at a time.


#### <a id="c-enum-pwm_polarity"></a>`enum pwm_polarity`

polarity of a PWM signal

**Constants**

- `PWM_POLARITY_NORMAL`: a high signal for the duration of the duty-
  cycle, followed by a low signal for the remainder of the pulse
  period
- `PWM_POLARITY_INVERSED`: a low signal for the duration of the duty-
  cycle, followed by a high signal for the remainder of the pulse
  period

#### <a id="c-struct-pwm_args"></a>`struct pwm_args`

board-dependent PWM arguments

**Definition**

```c
struct pwm_args {
    u64 period;
    enum pwm_polarity polarity;
};
```

**Members**

- `period`: reference period
- `polarity`: reference polarity

**Description**

This structure describes board-dependent arguments attached to a PWM
device. These arguments are usually retrieved from the PWM lookup table or
device tree.

Do not confuse this with the PWM state: PWM arguments represent the initial
configuration that users want to use on this PWM device rather than the
current PWM hardware state.

#### <a id="c-struct-pwm_waveform"></a>`struct pwm_waveform`

description of a PWM waveform

**Definition**

```c
struct pwm_waveform {
    u64 period_length_ns;
    u64 duty_length_ns;
    u64 duty_offset_ns;
};
```

**Members**

- `period_length_ns`: PWM period
- `duty_length_ns`: PWM duty cycle
- `duty_offset_ns`: offset of the rising edge from the period's start

**Description**

This is a representation of a PWM waveform alternative to struct pwm_state
below. It's more expressive than struct pwm_state as it contains a
duty_offset_ns and so can represent offsets other than zero (with .polarity =
PWM_POLARITY_NORMAL) and period - duty_cycle (.polarity =
PWM_POLARITY_INVERSED).

Note there is no explicit bool for enabled. A "disabled" PWM is represented
by .period_length_ns = 0. Note further that the behaviour of a "disabled" PWM
is undefined. Depending on the hardware's capabilities it might drive the
active or inactive level, go high-z or even continue to toggle.

The unit for all three members is nanoseconds.

#### <a id="c-struct-pwm_device"></a>`struct pwm_device`

PWM channel object

**Definition**

```c
struct pwm_device {
    const char *label;
    unsigned long flags;
    unsigned int hwpwm;
    struct pwm_chip *chip;
    struct pwm_args args;
    struct pwm_state state;
    struct pwm_state last;
};
```

**Members**

- `label`: name of the PWM device
- `flags`: flags associated with the PWM device
- `hwpwm`: per-chip relative index of the PWM device
- `chip`: PWM chip providing this PWM device
- `args`: PWM arguments
- `state`: last applied state
- `last`: last implemented state (for PWM_DEBUG)

#### <a id="c-pwm_get_state"></a>`pwm_get_state()`

```c
void pwm_get_state(const struct pwm_device *pwm, struct pwm_state *state)
```

retrieve the current PWM state

**Parameters**

- `const struct pwm_device *pwm`: PWM device
- `struct pwm_state *state`: state to fill with the current PWM state

**Description**

The returned PWM state represents the state that was applied by a previous call to
[`pwm_apply_might_sleep()`](#c-pwm_apply_might_sleep). Drivers may have to slightly tweak that state before programming it to
hardware. If [`pwm_apply_might_sleep()`](#c-pwm_apply_might_sleep) was never called, this returns either the current hardware
state (if supported) or the default settings.

#### <a id="c-pwm_init_state"></a>`pwm_init_state()`

```c
void pwm_init_state(const struct pwm_device *pwm, struct pwm_state *state)
```

prepare a new state to be applied with [`pwm_apply_might_sleep()`](#c-pwm_apply_might_sleep)

**Parameters**

- `const struct pwm_device *pwm`: PWM device
- `struct pwm_state *state`: state to fill with the prepared PWM state

**Description**

This functions prepares a state that can later be tweaked and applied
to the PWM device with [`pwm_apply_might_sleep()`](#c-pwm_apply_might_sleep). This is a convenient function
that first retrieves the current PWM state and the replaces the period
and polarity fields with the reference values defined in pwm->args.
Once the function returns, you can adjust the ->enabled and ->duty_cycle
fields according to your needs before calling [`pwm_apply_might_sleep()`](#c-pwm_apply_might_sleep).

->duty_cycle is initially set to zero to avoid cases where the current
->duty_cycle value exceed the pwm_args->period one, which would trigger
an error if the user calls [`pwm_apply_might_sleep()`](#c-pwm_apply_might_sleep) without adjusting ->duty_cycle
first.

#### <a id="c-pwm_get_relative_duty_cycle"></a>`pwm_get_relative_duty_cycle()`

```c
unsigned int pwm_get_relative_duty_cycle(const struct pwm_state *state, unsigned int scale)
```

Get a relative duty cycle value

**Parameters**

- `const struct pwm_state *state`: PWM state to extract the duty cycle from
- `unsigned int scale`: target scale of the relative duty cycle

**Description**

This functions converts the absolute duty cycle stored in **state** (expressed
in nanosecond) into a value relative to the period.

For example if you want to get the duty_cycle expressed in percent, call:

pwm_get_state(pwm, `state`);
duty = pwm_get_relative_duty_cycle(`state`, 100);

**Return**

rounded relative duty cycle multiplied by **scale**

#### <a id="c-pwm_set_relative_duty_cycle"></a>`pwm_set_relative_duty_cycle()`

```c
int pwm_set_relative_duty_cycle(struct pwm_state *state, unsigned int duty_cycle, unsigned int scale)
```

Set a relative duty cycle value

**Parameters**

- `struct pwm_state *state`: PWM state to fill
- `unsigned int duty_cycle`: relative duty cycle value
- `unsigned int scale`: scale in which **duty_cycle** is expressed

**Description**

This functions converts a relative into an absolute duty cycle (expressed
in nanoseconds), and puts the result in state->duty_cycle.

For example if you want to configure a 50% duty cycle, call:

pwm_init_state(pwm, `state`);
pwm_set_relative_duty_cycle(`state`, 50, 100);
pwm_apply_might_sleep(pwm, `state`);

**Return**

0 on success or `-EINVAL` if **duty_cycle** and/or **scale** are
inconsistent (**scale** == 0 or **duty_cycle** > **scale**)

#### <a id="c-struct-pwm_capture"></a>`struct pwm_capture`

PWM capture data

**Definition**

```c
struct pwm_capture {
    unsigned int period;
    unsigned int duty_cycle;
};
```

**Members**

- `period`: period of the PWM signal (in nanoseconds)
- `duty_cycle`: duty cycle of the PWM signal (in nanoseconds)

#### <a id="c-struct-pwm_ops"></a>`struct pwm_ops`

PWM controller operations

**Definition**

```c
struct pwm_ops {
    int (*request)(struct pwm_chip *chip, struct pwm_device *pwm);
    void (*free)(struct pwm_chip *chip, struct pwm_device *pwm);
    int (*capture)(struct pwm_chip *chip, struct pwm_device *pwm, struct pwm_capture *result, unsigned long timeout);
    size_t sizeof_wfhw;
    int (*round_waveform_tohw)(struct pwm_chip *chip, struct pwm_device *pwm, const struct pwm_waveform *wf, void *wfhw);
    int (*round_waveform_fromhw)(struct pwm_chip *chip, struct pwm_device *pwm, const void *wfhw, struct pwm_waveform *wf);
    int (*read_waveform)(struct pwm_chip *chip, struct pwm_device *pwm, void *wfhw);
    int (*write_waveform)(struct pwm_chip *chip, struct pwm_device *pwm, const void *wfhw);
    int (*apply)(struct pwm_chip *chip, struct pwm_device *pwm, const struct pwm_state *state);
    int (*get_state)(struct pwm_chip *chip, struct pwm_device *pwm, struct pwm_state *state);
};
```

**Members**

- `request`: optional hook for requesting a PWM
- `free`: optional hook for freeing a PWM
- `capture`: capture and report PWM signal
- `sizeof_wfhw`: size (in bytes) of driver specific waveform presentation
- `round_waveform_tohw`: convert a struct pwm_waveform to driver specific presentation
- `round_waveform_fromhw`: convert a driver specific waveform presentation to struct pwm_waveform
- `read_waveform`: read driver specific waveform presentation from hardware
- `write_waveform`: write driver specific waveform presentation to hardware
- `apply`: atomically apply a new PWM config
- `get_state`: get the current PWM state.

#### <a id="c-struct-pwm_chip"></a>`struct pwm_chip`

abstract a PWM controller

**Definition**

```c
struct pwm_chip {
    struct device dev;
    struct cdev cdev;
    const struct pwm_ops *ops;
    struct module *owner;
    unsigned int id;
    unsigned int npwm;
    struct pwm_device * (*of_xlate)(struct pwm_chip *chip, const struct of_phandle_args *args);
    bool atomic;
    struct gpio_chip gpio;
    bool uses_pwmchip_alloc;
    bool operational;
    union {
        struct mutex nonatomic_lock;
        spinlock_t atomic_lock;
    };
    struct pwm_device pwms[] ;
};
```

**Members**

- `dev`: device providing the PWMs
- `cdev`: `struct cdev` for this device
- `ops`: callbacks for this PWM controller
- `owner`: module providing this chip
- `id`: unique number of this PWM chip
- `npwm`: number of PWMs controlled by this chip
- `of_xlate`: request a PWM device given a device tree PWM specifier
- `atomic`: can the driver's ->`apply()` be called in atomic context
- `gpio`: [`struct gpio_chip`](/kernel/hardware/driver-api/gpio/index.md#c-struct-gpio_chip) to operate this PWM chip's lines as GPO
- `uses_pwmchip_alloc`: signals if pwmchip_allow was used to allocate this chip
- `operational`: signals if the chip can be used (or is already deregistered)
- `{unnamed_union}`: anonymous
- `nonatomic_lock`: mutex for nonatomic chips
- `atomic_lock`: mutex for atomic chips
- `pwms`: array of PWM devices allocated by the framework

#### <a id="c-pwmchip_supports_waveform"></a>`pwmchip_supports_waveform()`

```c
bool pwmchip_supports_waveform(struct pwm_chip *chip)
```

checks if the given chip supports waveform callbacks

**Parameters**

- `struct pwm_chip *chip`: The pwm_chip to test

**Return**

true iff the pwm chip support the waveform functions like
[`pwm_set_waveform_might_sleep()`](#c-pwm_set_waveform_might_sleep) and [`pwm_round_waveform_might_sleep()`](#c-pwm_round_waveform_might_sleep)

#### <a id="c-pwm_config"></a>`pwm_config()`

```c
int pwm_config(struct pwm_device *pwm, int duty_ns, int period_ns)
```

change a PWM device configuration

**Parameters**

- `struct pwm_device *pwm`: PWM device
- `int duty_ns`: "on" time (in nanoseconds)
- `int period_ns`: duration (in nanoseconds) of one cycle

**Return**

0 on success or a negative error code on failure.

#### <a id="c-pwm_enable"></a>`pwm_enable()`

```c
int pwm_enable(struct pwm_device *pwm)
```

start a PWM output toggling

**Parameters**

- `struct pwm_device *pwm`: PWM device

**Return**

0 on success or a negative error code on failure.

#### <a id="c-pwm_disable"></a>`pwm_disable()`

```c
void pwm_disable(struct pwm_device *pwm)
```

stop a PWM output toggling

**Parameters**

- `struct pwm_device *pwm`: PWM device

#### <a id="c-pwm_might_sleep"></a>`pwm_might_sleep()`

```c
bool pwm_might_sleep(struct pwm_device *pwm)
```

is [`pwm_apply_atomic()`](#c-pwm_apply_atomic) supported?

**Parameters**

- `struct pwm_device *pwm`: PWM device

**Return**

false if [`pwm_apply_atomic()`](#c-pwm_apply_atomic) can be called from atomic context.



#### <a id="c-pwm_round_waveform_might_sleep"></a>`pwm_round_waveform_might_sleep()`

```c
int pwm_round_waveform_might_sleep(struct pwm_device *pwm, struct pwm_waveform *wf)
```

Query hardware capabilities Cannot be used in atomic context.

**Parameters**

- `struct pwm_device *pwm`: PWM device
- `struct pwm_waveform *wf`: waveform to round and output parameter

**Description**

Typically a given waveform cannot be implemented exactly by hardware, e.g.
because hardware only supports coarse period resolution or no duty_offset.
This function returns the actually implemented waveform if you pass **wf** to
[`pwm_set_waveform_might_sleep()`](#c-pwm_set_waveform_might_sleep) now.

Note however that the world doesn't stop turning when you call it, so when
doing:

```text
pwm_round_waveform_might_sleep(mypwm, &wf);
pwm_set_waveform_might_sleep(mypwm, &wf, true);
```

the latter might fail, e.g. because an input clock changed its rate between
these two calls and the waveform determined by
[`pwm_round_waveform_might_sleep()`](#c-pwm_round_waveform_might_sleep) cannot be implemented any more.

Usually all values passed in **wf** are rounded down to the nearest possible
value (in the order period_length_ns, duty_length_ns and then
duty_offset_ns). Only if this isn't possible, a value might grow. See the
documentation for [`pwm_set_waveform_might_sleep()`](#c-pwm_set_waveform_might_sleep) for a more formal
description.

**Return**

0 on success, 1 if at least one value had to be rounded up or a
negative errno.

**Context**

May sleep.

#### <a id="c-pwm_get_waveform_might_sleep"></a>`pwm_get_waveform_might_sleep()`

```c
int pwm_get_waveform_might_sleep(struct pwm_device *pwm, struct pwm_waveform *wf)
```

Query hardware about current configuration Cannot be used in atomic context.

**Parameters**

- `struct pwm_device *pwm`: PWM device
- `struct pwm_waveform *wf`: output parameter

**Description**

Stores the current configuration of the PWM in **wf**. Note this is the
equivalent of [`pwm_get_state_hw()`](#c-pwm_get_state_hw) (and not [`pwm_get_state()`](#c-pwm_get_state)) for pwm_waveform.

**Return**

0 on success or a negative errno

**Context**

May sleep.

#### <a id="c-pwm_set_waveform_might_sleep"></a>`pwm_set_waveform_might_sleep()`

```c
int pwm_set_waveform_might_sleep(struct pwm_device *pwm, const struct pwm_waveform *wf, bool exact)
```

Apply a new waveform Cannot be used in atomic context.

**Parameters**

- `struct pwm_device *pwm`: PWM device
- `const struct pwm_waveform *wf`: The waveform to apply
- `bool exact`: If true no rounding is allowed

**Description**

Typically a requested waveform cannot be implemented exactly, e.g. because
you requested .period_length_ns = 100 ns, but the hardware can only set
periods that are a multiple of 8.5 ns. With that hardware passing **exact** =
true results in [`pwm_set_waveform_might_sleep()`](#c-pwm_set_waveform_might_sleep) failing and returning -EDOM.
If **exact** = false you get a period of 93.5 ns (i.e. the biggest period not
bigger than the requested value).
Note that even with **exact** = true, some rounding by less than 1 ns is
possible/needed. In the above example requesting .period_length_ns = 94 and
**exact** = true, you get the hardware configured with period = 93.5 ns.

Let C be the set of possible hardware configurations for a given PWM device,
consisting of tuples (p, d, o) where p is the period length, d is the duty
length and o the duty offset.

The following algorithm is implemented to pick the hardware setting
(p, d, o) ∈ C for a given request (p', d', o') with **exact** = false:

```text
p = max( { ṗ | ∃ ḋ, ȯ : (ṗ, ḋ, ȯ) ∈ C ∧ ṗ ≤ p' } ∪ { min({ ṗ | ∃ ḋ, ȯ : (ṗ, ḋ, ȯ) ∈ C }) })
d = max( { ḋ | ∃ ȯ : (p, ḋ, ȯ) ∈ C ∧ ḋ ≤ d' } ∪ { min({ ḋ | ∃ ȯ : (p, ḋ, ȯ) ∈ C }) })
o = max( { ȯ | (p, d, ȯ) ∈ C ∧ ȯ ≤ o' } ∪ { min({ ȯ | (p, d, ȯ) ∈ C }) })
```

In words: The chosen period length is the maximal possible period length not
bigger than the requested period length and if that doesn't exist, the
minimal period length. The chosen duty length is the maximal possible duty
length that is compatible with the chosen period length and isn't bigger than
the requested duty length. Again if such a value doesn't exist, the minimal
duty length compatible with the chosen period is picked. After that the duty
offset compatible with the chosen period and duty length is chosen in the
same way.

**Return**

0 on success, -EDOM if setting failed due to the exact waveform not
being possible (if **exact**), or a different negative errno on failure.

**Context**

May sleep.

#### <a id="c-pwm_apply_might_sleep"></a>`pwm_apply_might_sleep()`

```c
int pwm_apply_might_sleep(struct pwm_device *pwm, const struct pwm_state *state)
```

atomically apply a new state to a PWM device Cannot be used in atomic context.

**Parameters**

- `struct pwm_device *pwm`: PWM device
- `const struct pwm_state *state`: new state to apply

**Return**

0 on success, or a negative errno

**Context**

May sleep.

#### <a id="c-pwm_apply_atomic"></a>`pwm_apply_atomic()`

```c
int pwm_apply_atomic(struct pwm_device *pwm, const struct pwm_state *state)
```

apply a new state to a PWM device from atomic context Not all PWM devices support this function, check with [`pwm_might_sleep()`](#c-pwm_might_sleep).

**Parameters**

- `struct pwm_device *pwm`: PWM device
- `const struct pwm_state *state`: new state to apply

**Return**

0 on success, or a negative errno

**Context**

Any

#### <a id="c-pwm_get_state_hw"></a>`pwm_get_state_hw()`

```c
int pwm_get_state_hw(struct pwm_device *pwm, struct pwm_state *state)
```

get the current PWM state from hardware

**Parameters**

- `struct pwm_device *pwm`: PWM device
- `struct pwm_state *state`: state to fill with the current PWM state

**Description**

Similar to [`pwm_get_state()`](#c-pwm_get_state) but reads the current PWM state from hardware
instead of the requested state.

**Return**

0 on success or a negative error code on failure.

**Context**

May sleep.

#### <a id="c-pwm_adjust_config"></a>`pwm_adjust_config()`

```c
int pwm_adjust_config(struct pwm_device *pwm)
```

adjust the current PWM config to the PWM arguments

**Parameters**

- `struct pwm_device *pwm`: PWM device

**Description**

This function will adjust the PWM config to the PWM arguments provided
by the DT or PWM lookup table. This is particularly useful to adapt
the bootloader config to the Linux one.

**Return**

0 on success or a negative error code on failure.

**Context**

May sleep.

#### <a id="c-pwm_get"></a>`pwm_get()`

```c
struct pwm_device * pwm_get(struct device *dev, const char *con_id)
```

look up and request a PWM device

**Parameters**

- `struct device *dev`: device for PWM consumer
- `const char *con_id`: consumer name

**Description**

Lookup is first attempted using DT. If the device was not instantiated from
a device tree, a PWM chip and a relative index is looked up via a table
supplied by board setup code (see `pwm_add_table()`).

Once a PWM chip has been found the specified PWM device will be requested
and is ready to be used.

**Return**

A pointer to the requested PWM device or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-encoded
error code on failure.

#### <a id="c-pwm_put"></a>`pwm_put()`

```c
void pwm_put(struct pwm_device *pwm)
```

release a PWM device

**Parameters**

- `struct pwm_device *pwm`: PWM device

#### <a id="c-devm_pwm_get"></a>`devm_pwm_get()`

```c
struct pwm_device * devm_pwm_get(struct device *dev, const char *con_id)
```

resource managed [`pwm_get()`](#c-pwm_get)

**Parameters**

- `struct device *dev`: device for PWM consumer
- `const char *con_id`: consumer name

**Description**

This function performs like [`pwm_get()`](#c-pwm_get) but the acquired PWM device will
automatically be released on driver detach.

**Return**

A pointer to the requested PWM device or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-encoded
error code on failure.

#### <a id="c-devm_fwnode_pwm_get"></a>`devm_fwnode_pwm_get()`

```c
struct pwm_device * devm_fwnode_pwm_get(struct device *dev, struct fwnode_handle *fwnode, const char *con_id)
```

request a resource managed PWM from firmware node

**Parameters**

- `struct device *dev`: device for PWM consumer
- `struct fwnode_handle *fwnode`: firmware node to get the PWM from
- `const char *con_id`: consumer name

**Description**

Returns the PWM device parsed from the firmware node. See `of_pwm_get()` and
`acpi_pwm_get()` for a detailed description.

**Return**

A pointer to the requested PWM device or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-encoded
error code on failure.

#### <a id="c-__pwmchip_add"></a>`__pwmchip_add()`

```c
int __pwmchip_add(struct pwm_chip *chip, struct module *owner)
```

register a new PWM chip

**Parameters**

- `struct pwm_chip *chip`: the PWM chip to add
- `struct module *owner`: reference to the module providing the chip.

**Description**

Register a new PWM chip. **owner** is supposed to be THIS_MODULE, use the
pwmchip_add wrapper to do this right.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-pwmchip_remove"></a>`pwmchip_remove()`

```c
void pwmchip_remove(struct pwm_chip *chip)
```

remove a PWM chip

**Parameters**

- `struct pwm_chip *chip`: the PWM chip to remove

**Description**

Removes a PWM chip.

---

# MTD NAND Driver Programming Interface

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> The generic NAND driver supports almost all NAND and AG-AND based chips and connects them to the Memory Technology Devices (MTD) subsystem of the Linux Kernel.

<a id="rst-mtd-nand-driver-programming-interface"></a>

**Author:** Thomas Gleixner

<a id="rst-introduction"></a>

## Introduction

The generic NAND driver supports almost all NAND and AG-AND based chips and connects them to the Memory Technology Devices (MTD) subsystem of the Linux Kernel.

This documentation is provided for developers who want to implement board drivers or filesystem drivers suitable for NAND devices.

<a id="rst-known-bugs-and-assumptions"></a>

## Known Bugs And Assumptions

None.

<a id="rst-documentation-hints"></a>

## Documentation hints

The function and structure docs are autogenerated. Each function and struct member has a short description which is marked with an \[XXX\] identifier. The following chapters explain the meaning of those identifiers.

<a id="rst-function-identifiers-xxx"></a>

### Function identifiers \[XXX\]

The functions are marked with \[XXX\] identifiers in the short comment. The identifiers explain the usage and scope of the functions. Following identifiers are used:

- \[MTD Interface\]

  These functions provide the interface to the MTD kernel API. They are not replaceable and provide functionality which is complete hardware independent.

- \[NAND Interface\]

  These functions are exported and provide the interface to the NAND kernel API.

- \[GENERIC\]

  Generic functions are not replaceable and provide functionality which is complete hardware independent.

- \[DEFAULT\]

  Default functions provide hardware related functionality which is suitable for most of the implementations. These functions can be replaced by the board driver if necessary. Those functions are called via pointers in the NAND chip description structure. The board driver can set the functions which should be replaced by board dependent functions before calling nand_scan(). If the function pointer is NULL on entry to nand_scan() then the pointer is set to the default function which is suitable for the detected chip type.

<a id="rst-struct-member-identifiers-xxx"></a>

### Struct member identifiers \[XXX\]

The struct members are marked with \[XXX\] identifiers in the comment. The identifiers explain the usage and scope of the members. Following identifiers are used:

- \[INTERN\]

  These members are for NAND driver internal use only and must not be modified. Most of these values are calculated from the chip geometry information which is evaluated during nand_scan().

- \[REPLACEABLE\]

  Replaceable members hold hardware related functions which can be provided by the board driver. The board driver can set the functions which should be replaced by board dependent functions before calling nand_scan(). If the function pointer is NULL on entry to nand_scan() then the pointer is set to the default function which is suitable for the detected chip type.

- \[BOARDSPECIFIC\]

  Board specific members hold hardware related information which must be provided by the board driver. The board driver must set the function pointers and datafields before calling nand_scan().

- \[OPTIONAL\]

  Optional members can hold information relevant for the board driver. The generic NAND driver code does not use this information.

<a id="rst-basic-board-driver"></a>

## Basic board driver

For most boards it will be sufficient to provide just the basic functions and fill out some really board dependent members in the nand chip description structure.

<a id="rst-basic-defines"></a>

### Basic defines

At least you have to provide a nand_chip structure and a storage for the ioremap'ed chip address. You can allocate the nand_chip structure using kmalloc or you can allocate it statically. The NAND chip structure embeds an mtd structure which will be registered to the MTD subsystem. You can extract a pointer to the mtd structure from a nand_chip pointer using the nand_to_mtd() helper.

Kmalloc based example



```text
static struct mtd_info *board_mtd;
static void __iomem *baseaddr;
```

Static example



```text
static struct nand_chip board_chip;
static void __iomem *baseaddr;
```

<a id="rst-partition-defines"></a>

### Partition defines

If you want to divide your device into partitions, then define a partitioning scheme suitable to your board.



```text
#define NUM_PARTITIONS 2
static struct mtd_partition partition_info[] = {
    { .name = "Flash partition 1",
      .offset =  0,
      .size =    8 * 1024 * 1024 },
    { .name = "Flash partition 2",
      .offset =  MTDPART_OFS_NEXT,
      .size =    MTDPART_SIZ_FULL },
};
```

<a id="rst-hardware-control-function"></a>

### Hardware control function

The hardware control function provides access to the control pins of the NAND chip(s). The access can be done by GPIO pins or by address lines. If you use address lines, make sure that the timing requirements are met.

*GPIO based example*



```text
static void board_hwcontrol(struct mtd_info *mtd, int cmd)
{
    switch(cmd){
        case NAND_CTL_SETCLE: /* Set CLE pin high */ break;
        case NAND_CTL_CLRCLE: /* Set CLE pin low */ break;
        case NAND_CTL_SETALE: /* Set ALE pin high */ break;
        case NAND_CTL_CLRALE: /* Set ALE pin low */ break;
        case NAND_CTL_SETNCE: /* Set nCE pin low */ break;
        case NAND_CTL_CLRNCE: /* Set nCE pin high */ break;
    }
}
```

*Address lines based example.* It's assumed that the nCE pin is driven by a chip select decoder.



```text
static void board_hwcontrol(struct mtd_info *mtd, int cmd)
{
    struct nand_chip *this = mtd_to_nand(mtd);
    switch(cmd){
        case NAND_CTL_SETCLE: this->legacy.IO_ADDR_W |= CLE_ADRR_BIT;  break;
        case NAND_CTL_CLRCLE: this->legacy.IO_ADDR_W &= ~CLE_ADRR_BIT; break;
        case NAND_CTL_SETALE: this->legacy.IO_ADDR_W |= ALE_ADRR_BIT;  break;
        case NAND_CTL_CLRALE: this->legacy.IO_ADDR_W &= ~ALE_ADRR_BIT; break;
    }
}
```

<a id="rst-device-ready-function"></a>

### Device ready function

If the hardware interface has the ready busy pin of the NAND chip connected to a GPIO or other accessible I/O pin, this function is used to read back the state of the pin. The function has no arguments and should return 0, if the device is busy (R/B pin is low) and 1, if the device is ready (R/B pin is high). If the hardware interface does not give access to the ready busy pin, then the function must not be defined and the function pointer this-&gt;legacy.dev_ready is set to NULL.

<a id="rst-init-function"></a>

### Init function

The init function allocates memory and sets up all the board specific parameters and function pointers. When everything is set up nand_scan() is called. This function tries to detect and identify then chip. If a chip is found all the internal data fields are initialized accordingly. The structure(s) have to be zeroed out first and then filled with the necessary information about the device.



```text
static int __init board_init (void)
{
    struct nand_chip *this;
    int err = 0;

    /* Allocate memory for MTD device structure and private data */
    this = kzalloc(sizeof(struct nand_chip), GFP_KERNEL);
    if (!this) {
        printk ("Unable to allocate NAND MTD device structure.\n");
        err = -ENOMEM;
        goto out;
    }

    board_mtd = nand_to_mtd(this);

    /* map physical address */
    baseaddr = ioremap(CHIP_PHYSICAL_ADDRESS, 1024);
    if (!baseaddr) {
        printk("Ioremap to access NAND chip failed\n");
        err = -EIO;
        goto out_mtd;
    }

    /* Set address of NAND IO lines */
    this->legacy.IO_ADDR_R = baseaddr;
    this->legacy.IO_ADDR_W = baseaddr;
    /* Reference hardware control function */
    this->hwcontrol = board_hwcontrol;
    /* Set command delay time, see datasheet for correct value */
    this->legacy.chip_delay = CHIP_DEPENDEND_COMMAND_DELAY;
    /* Assign the device ready function, if available */
    this->legacy.dev_ready = board_dev_ready;
    this->eccmode = NAND_ECC_SOFT;

    /* Scan to find existence of the device */
    if (nand_scan (this, 1)) {
        err = -ENXIO;
        goto out_ior;
    }

    add_mtd_partitions(board_mtd, partition_info, NUM_PARTITIONS);
    goto out;

out_ior:
    iounmap(baseaddr);
out_mtd:
    kfree (this);
out:
    return err;
}
module_init(board_init);
```

<a id="rst-exit-function"></a>

### Exit function

The exit function is only necessary if the driver is compiled as a module. It releases all resources which are held by the chip driver and unregisters the partitions in the MTD layer.



```text
#ifdef MODULE
static void __exit board_cleanup (void)
{
    /* Unregister device */
    WARN_ON(mtd_device_unregister(board_mtd));
    /* Release resources */
    nand_cleanup(mtd_to_nand(board_mtd));

    /* unmap physical address */
    iounmap(baseaddr);

    /* Free the MTD device structure */
    kfree (mtd_to_nand(board_mtd));
}
module_exit(board_cleanup);
#endif
```

<a id="rst-advanced-board-driver-functions"></a>

## Advanced board driver functions

This chapter describes the advanced functionality of the NAND driver. For a list of functions which can be overridden by the board driver see the documentation of the nand_chip structure.

<a id="rst-multiple-chip-control"></a>

### Multiple chip control

The nand driver can control chip arrays. Therefore the board driver must provide an own select_chip function. This function must (de)select the requested chip. The function pointer in the nand_chip structure must be set before calling nand_scan(). The maxchip parameter of nand_scan() defines the maximum number of chips to scan for. Make sure that the select_chip function can handle the requested number of chips.

The nand driver concatenates the chips to one virtual chip and provides this virtual chip to the MTD layer.

*Note: The driver can only handle linear chip arrays of equally sized chips. There is no support for parallel arrays which extend the buswidth.*

*GPIO based example*



```text
static void board_select_chip (struct mtd_info *mtd, int chip)
{
    /* Deselect all chips, set all nCE pins high */
    GPIO(BOARD_NAND_NCE) |= 0xff;
    if (chip >= 0)
        GPIO(BOARD_NAND_NCE) &= ~ (1 << chip);
}
```

*Address lines based example.* Its assumed that the nCE pins are connected to an address decoder.



```text
static void board_select_chip (struct mtd_info *mtd, int chip)
{
    struct nand_chip *this = mtd_to_nand(mtd);

    /* Deselect all chips */
    this->legacy.IO_ADDR_R &= ~BOARD_NAND_ADDR_MASK;
    this->legacy.IO_ADDR_W &= ~BOARD_NAND_ADDR_MASK;
    switch (chip) {
    case 0:
        this->legacy.IO_ADDR_R |= BOARD_NAND_ADDR_CHIP0;
        this->legacy.IO_ADDR_W |= BOARD_NAND_ADDR_CHIP0;
        break;
    ....
    case n:
        this->legacy.IO_ADDR_R |= BOARD_NAND_ADDR_CHIPn;
        this->legacy.IO_ADDR_W |= BOARD_NAND_ADDR_CHIPn;
        break;
    }
}
```

<a id="rst-hardware-ecc-support"></a>

### Hardware ECC support

<a id="rst-functions-and-constants"></a>

#### Functions and constants

The nand driver supports three different types of hardware ECC.

- NAND_ECC_HW3_256

  Hardware ECC generator providing 3 bytes ECC per 256 byte.

- NAND_ECC_HW3_512

  Hardware ECC generator providing 3 bytes ECC per 512 byte.

- NAND_ECC_HW6_512

  Hardware ECC generator providing 6 bytes ECC per 512 byte.

- NAND_ECC_HW8_512

  Hardware ECC generator providing 8 bytes ECC per 512 byte.

If your hardware generator has a different functionality add it at the appropriate place in nand_base.c

The board driver must provide following functions:

- enable_hwecc

  This function is called before reading / writing to the chip. Reset or initialize the hardware generator in this function. The function is called with an argument which let you distinguish between read and write operations.

- calculate_ecc

  This function is called after read / write from / to the chip. Transfer the ECC from the hardware to the buffer. If the option NAND_HWECC_SYNDROME is set then the function is only called on write. See below.

- correct_data

  In case of an ECC error this function is called for error detection and correction. Return 1 respectively 2 in case the error can be corrected. If the error is not correctable return -1. If your hardware generator matches the default algorithm of the nand_ecc software generator then use the correction function provided by nand_ecc instead of implementing duplicated code.

<a id="rst-hardware-ecc-with-syndrome-calculation"></a>

#### Hardware ECC with syndrome calculation

Many hardware ECC implementations provide Reed-Solomon codes and calculate an error syndrome on read. The syndrome must be converted to a standard Reed-Solomon syndrome before calling the error correction code in the generic Reed-Solomon library.

The ECC bytes must be placed immediately after the data bytes in order to make the syndrome generator work. This is contrary to the usual layout used by software ECC. The separation of data and out of band area is not longer possible. The nand driver code handles this layout and the remaining free bytes in the oob area are managed by the autoplacement code. Provide a matching oob-layout in this case. See rts_from4.c and diskonchip.c for implementation reference. In those cases we must also use bad block tables on FLASH, because the ECC layout is interfering with the bad block marker positions. See bad block table support for details.

<a id="rst-bad-block-table-support"></a>

### Bad block table support

Most NAND chips mark the bad blocks at a defined position in the spare area. Those blocks must not be erased under any circumstances as the bad block information would be lost. It is possible to check the bad block mark each time when the blocks are accessed by reading the spare area of the first page in the block. This is time consuming so a bad block table is used.

The nand driver supports various types of bad block tables.

- Per device

  The bad block table contains all bad block information of the device which can consist of multiple chips.

- Per chip

  A bad block table is used per chip and contains the bad block information for this particular chip.

- Fixed offset

  The bad block table is located at a fixed offset in the chip (device). This applies to various DiskOnChip devices.

- Automatic placed

  The bad block table is automatically placed and detected either at the end or at the beginning of a chip (device)

- Mirrored tables

  The bad block table is mirrored on the chip (device) to allow updates of the bad block table without data loss.

nand_scan() calls the function nand_default_bbt(). nand_default_bbt() selects appropriate default bad block table descriptors depending on the chip information which was retrieved by nand_scan().

The standard policy is scanning the device for bad blocks and build a ram based bad block table which allows faster access than always checking the bad block information on the flash chip itself.

<a id="rst-flash-based-tables"></a>

#### Flash based tables

It may be desired or necessary to keep a bad block table in FLASH. For AG-AND chips this is mandatory, as they have no factory marked bad blocks. They have factory marked good blocks. The marker pattern is erased when the block is erased to be reused. So in case of powerloss before writing the pattern back to the chip this block would be lost and added to the bad blocks. Therefore we scan the chip(s) when we detect them the first time for good blocks and store this information in a bad block table before erasing any of the blocks.

The blocks in which the tables are stored are protected against accidental access by marking them bad in the memory bad block table. The bad block table management functions are allowed to circumvent this protection.

The simplest way to activate the FLASH based bad block table support is to set the option NAND_BBT_USE_FLASH in the bbt_option field of the nand chip structure before calling nand_scan(). For AG-AND chips is this done by default. This activates the default FLASH based bad block table functionality of the NAND driver. The default bad block table options are

- Store bad block table per chip

- Use 2 bits per block

- Automatic placement at the end of the chip

- Use mirrored tables with version numbers

- Reserve 4 blocks at the end of the chip

<a id="rst-user-defined-tables"></a>

#### User defined tables

User defined tables are created by filling out a nand_bbt_descr structure and storing the pointer in the nand_chip structure member bbt_td before calling nand_scan(). If a mirror table is necessary a second structure must be created and a pointer to this structure must be stored in bbt_md inside the nand_chip structure. If the bbt_md member is set to NULL then only the main table is used and no scan for the mirrored table is performed.

The most important field in the nand_bbt_descr structure is the options field. The options define most of the table properties. Use the predefined constants from rawnand.h to define the options.

- Number of bits per block

  The supported number of bits is 1, 2, 4, 8.

- Table per chip

  Setting the constant NAND_BBT_PERCHIP selects that a bad block table is managed for each chip in a chip array. If this option is not set then a per device bad block table is used.

- Table location is absolute

  Use the option constant NAND_BBT_ABSPAGE and define the absolute page number where the bad block table starts in the field pages. If you have selected bad block tables per chip and you have a multi chip array then the start page must be given for each chip in the chip array. Note: there is no scan for a table ident pattern performed, so the fields pattern, veroffs, offs, len can be left uninitialized

- Table location is automatically detected

  The table can either be located in the first or the last good blocks of the chip (device). Set NAND_BBT_LASTBLOCK to place the bad block table at the end of the chip (device). The bad block tables are marked and identified by a pattern which is stored in the spare area of the first page in the block which holds the bad block table. Store a pointer to the pattern in the pattern field. Further the length of the pattern has to be stored in len and the offset in the spare area must be given in the offs member of the nand_bbt_descr structure. For mirrored bad block tables different patterns are mandatory.

- Table creation

  Set the option NAND_BBT_CREATE to enable the table creation if no table can be found during the scan. Usually this is done only once if a new chip is found.

- Table write support

  Set the option NAND_BBT_WRITE to enable the table write support. This allows the update of the bad block table(s) in case a block has to be marked bad due to wear. The MTD interface function block_markbad is calling the update function of the bad block table. If the write support is enabled then the table is updated on FLASH.

  Note: Write support should only be enabled for mirrored tables with version control.

- Table version control

  Set the option NAND_BBT_VERSION to enable the table version control. It's highly recommended to enable this for mirrored tables with write support. It makes sure that the risk of losing the bad block table information is reduced to the loss of the information about the one worn out block which should be marked bad. The version is stored in 4 consecutive bytes in the spare area of the device. The position of the version number is defined by the member veroffs in the bad block table descriptor.

- Save block contents on write

  In case that the block which holds the bad block table does contain other useful information, set the option NAND_BBT_SAVECONTENT. When the bad block table is written then the whole block is read the bad block table is updated and the block is erased and everything is written back. If this option is not set only the bad block table is written and everything else in the block is ignored and erased.

- Number of reserved blocks

  For automatic placement some blocks must be reserved for bad block table storage. The number of reserved blocks is defined in the maxblocks member of the bad block table description structure. Reserving 4 blocks for mirrored tables should be a reasonable number. This also limits the number of blocks which are scanned for the bad block table ident pattern.

<a id="rst-spare-area-auto-placement"></a>

### Spare area (auto)placement

The nand driver implements different possibilities for placement of filesystem data in the spare area,

- Placement defined by fs driver

- Automatic placement

The default placement function is automatic placement. The nand driver has built in default placement schemes for the various chiptypes. If due to hardware ECC functionality the default placement does not fit then the board driver can provide a own placement scheme.

File system drivers can provide a own placement scheme which is used instead of the default placement scheme.

Placement schemes are defined by a nand_oobinfo structure



```text
struct nand_oobinfo {
    int useecc;
    int eccbytes;
    int eccpos[24];
    int oobfree[8][2];
};
```

- useecc

  The useecc member controls the ecc and placement function. The header file include/mtd/mtd-abi.h contains constants to select ecc and placement. MTD_NANDECC_OFF switches off the ecc complete. This is not recommended and available for testing and diagnosis only. MTD_NANDECC_PLACE selects caller defined placement, MTD_NANDECC_AUTOPLACE selects automatic placement.

- eccbytes

  The eccbytes member defines the number of ecc bytes per page.

- eccpos

  The eccpos array holds the byte offsets in the spare area where the ecc codes are placed.

- oobfree

  The oobfree array defines the areas in the spare area which can be used for automatic placement. The information is given in the format \{offset, size\}. offset defines the start of the usable area, size the length in bytes. More than one area can be defined. The list is terminated by an \{0, 0\} entry.

<a id="rst-placement-defined-by-fs-driver"></a>

#### Placement defined by fs driver

The calling function provides a pointer to a nand_oobinfo structure which defines the ecc placement. For writes the caller must provide a spare area buffer along with the data buffer. The spare area buffer size is (number of pages) \* (size of spare area). For reads the buffer size is (number of pages) \* ((size of spare area) + (number of ecc steps per page) \* sizeof (int)). The driver stores the result of the ecc check for each tuple in the spare buffer. The storage sequence is:



```text
<spare data page 0><ecc result 0>...<ecc result n>

...

<spare data page n><ecc result 0>...<ecc result n>
```

This is a legacy mode used by YAFFS1.

If the spare area buffer is NULL then only the ECC placement is done according to the given scheme in the nand_oobinfo structure.

<a id="rst-automatic-placement"></a>

#### Automatic placement

Automatic placement uses the built in defaults to place the ecc bytes in the spare area. If filesystem data have to be stored / read into the spare area then the calling function must provide a buffer. The buffer size per page is determined by the oobfree array in the nand_oobinfo structure.

If the spare area buffer is NULL then only the ECC placement is done according to the default builtin scheme.

<a id="rst-spare-area-autoplacement-default-schemes"></a>

### Spare area autoplacement default schemes

<a id="rst-byte-pagesize"></a>

#### 256 byte pagesize


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Content

</th>
<th>


Comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x00

</td>
<td>


ECC byte 0

</td>
<td>


Error correction code byte 0

</td>
</tr>
<tr>
<td>


0x01

</td>
<td>


ECC byte 1

</td>
<td>


Error correction code byte 1

</td>
</tr>
<tr>
<td>


0x02

</td>
<td>


ECC byte 2

</td>
<td>


Error correction code byte 2

</td>
</tr>
<tr>
<td>


0x03

</td>
<td>


Autoplace 0

</td>
<td>




</td>
</tr>
<tr>
<td>


0x04

</td>
<td>


Autoplace 1

</td>
<td>




</td>
</tr>
<tr>
<td>


0x05

</td>
<td>


Bad block marker

</td>
<td>


If any bit in this byte is zero, then this block is bad. This applies only to the first page in a block. In the remaining pages this byte is reserved

</td>
</tr>
<tr>
<td>


0x06

</td>
<td>


Autoplace 2

</td>
<td>




</td>
</tr>
<tr>
<td>


0x07

</td>
<td>


Autoplace 3

</td>
<td>




</td>
</tr>
</tbody>
</table>

<a id="rst-byte-pagesize-1"></a>

#### 512 byte pagesize


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Content

</th>
<th>


Comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x00

</td>
<td>


ECC byte 0

</td>
<td>


Error correction code byte 0 of the lower 256 Byte data in this page

</td>
</tr>
<tr>
<td>


0x01

</td>
<td>


ECC byte 1

</td>
<td>


Error correction code byte 1 of the lower 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x02

</td>
<td>


ECC byte 2

</td>
<td>


Error correction code byte 2 of the lower 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x03

</td>
<td>


ECC byte 3

</td>
<td>


Error correction code byte 0 of the upper 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x04

</td>
<td>


reserved

</td>
<td>


reserved

</td>
</tr>
<tr>
<td>


0x05

</td>
<td>


Bad block marker

</td>
<td>


If any bit in this byte is zero, then this block is bad. This applies only to the first page in a block. In the remaining pages this byte is reserved

</td>
</tr>
<tr>
<td>


0x06

</td>
<td>


ECC byte 4

</td>
<td>


Error correction code byte 1 of the upper 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x07

</td>
<td>


ECC byte 5

</td>
<td>


Error correction code byte 2 of the upper 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x08 - 0x0F

</td>
<td>


Autoplace 0 - 7

</td>
<td>




</td>
</tr>
</tbody>
</table>

<a id="rst-byte-pagesize-2"></a>

#### 2048 byte pagesize


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Content

</th>
<th>


Comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x00

</td>
<td>


Bad block marker

</td>
<td>


If any bit in this byte is zero, then this block is bad. This applies only to the first page in a block. In the remaining pages this byte is reserved

</td>
</tr>
<tr>
<td>


0x01

</td>
<td>


Reserved

</td>
<td>


Reserved

</td>
</tr>
<tr>
<td>


0x02-0x27

</td>
<td>


Autoplace 0 - 37

</td>
<td>




</td>
</tr>
<tr>
<td>


0x28

</td>
<td>


ECC byte 0

</td>
<td>


Error correction code byte 0 of the first 256 Byte data in this page

</td>
</tr>
<tr>
<td>


0x29

</td>
<td>


ECC byte 1

</td>
<td>


Error correction code byte 1 of the first 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2A

</td>
<td>


ECC byte 2

</td>
<td>


Error correction code byte 2 of the first 256 Bytes data in this page

</td>
</tr>
<tr>
<td>


0x2B

</td>
<td>


ECC byte 3

</td>
<td>


Error correction code byte 0 of the second 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2C

</td>
<td>


ECC byte 4

</td>
<td>


Error correction code byte 1 of the second 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2D

</td>
<td>


ECC byte 5

</td>
<td>


Error correction code byte 2 of the second 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2E

</td>
<td>


ECC byte 6

</td>
<td>


Error correction code byte 0 of the third 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x2F

</td>
<td>


ECC byte 7

</td>
<td>


Error correction code byte 1 of the third 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x30

</td>
<td>


ECC byte 8

</td>
<td>


Error correction code byte 2 of the third 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x31

</td>
<td>


ECC byte 9

</td>
<td>


Error correction code byte 0 of the fourth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x32

</td>
<td>


ECC byte 10

</td>
<td>


Error correction code byte 1 of the fourth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x33

</td>
<td>


ECC byte 11

</td>
<td>


Error correction code byte 2 of the fourth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x34

</td>
<td>


ECC byte 12

</td>
<td>


Error correction code byte 0 of the fifth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x35

</td>
<td>


ECC byte 13

</td>
<td>


Error correction code byte 1 of the fifth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x36

</td>
<td>


ECC byte 14

</td>
<td>


Error correction code byte 2 of the fifth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x37

</td>
<td>


ECC byte 15

</td>
<td>


Error correction code byte 0 of the sixth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x38

</td>
<td>


ECC byte 16

</td>
<td>


Error correction code byte 1 of the sixth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x39

</td>
<td>


ECC byte 17

</td>
<td>


Error correction code byte 2 of the sixth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3A

</td>
<td>


ECC byte 18

</td>
<td>


Error correction code byte 0 of the seventh 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3B

</td>
<td>


ECC byte 19

</td>
<td>


Error correction code byte 1 of the seventh 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3C

</td>
<td>


ECC byte 20

</td>
<td>


Error correction code byte 2 of the seventh 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3D

</td>
<td>


ECC byte 21

</td>
<td>


Error correction code byte 0 of the eighth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3E

</td>
<td>


ECC byte 22

</td>
<td>


Error correction code byte 1 of the eighth 256 Bytes of data in this page

</td>
</tr>
<tr>
<td>


0x3F

</td>
<td>


ECC byte 23

</td>
<td>


Error correction code byte 2 of the eighth 256 Bytes of data in this page

</td>
</tr>
</tbody>
</table>

<a id="rst-filesystem-support"></a>

## Filesystem support

The NAND driver provides all necessary functions for a filesystem via the MTD interface.

Filesystems must be aware of the NAND peculiarities and restrictions. One major restrictions of NAND Flash is, that you cannot write as often as you want to a page. The consecutive writes to a page, before erasing it again, are restricted to 1-3 writes, depending on the manufacturers specifications. This applies similar to the spare area.

Therefore NAND aware filesystems must either write in page size chunks or hold a writebuffer to collect smaller writes until they sum up to pagesize. Available NAND aware filesystems: JFFS2, YAFFS.

The spare area usage to store filesystem data is controlled by the spare area placement functionality which is described in one of the earlier chapters.

<a id="rst-tools"></a>

## Tools

The MTD project provides a couple of helpful tools to handle NAND Flash.

- flasherase, flasheraseall: Erase and format FLASH partitions

- nandwrite: write filesystem images to NAND FLASH

- nanddump: dump the contents of a NAND FLASH partitions

These tools are aware of the NAND restrictions. Please use those tools instead of complaining about errors which are caused by non NAND aware access methods.

<a id="rst-constants"></a>

## Constants

This chapter describes the constants which might be relevant for a driver developer.

<a id="rst-chip-option-constants"></a>

### Chip option constants

<a id="rst-constants-for-chip-id-table"></a>

#### Constants for chip id table

These constants are defined in rawnand.h. They are OR-ed together to describe the chip functionality:



```text
/* Buswitdh is 16 bit */
#define NAND_BUSWIDTH_16    0x00000002
/* Device supports partial programming without padding */
#define NAND_NO_PADDING     0x00000004
/* Chip has cache program function */
#define NAND_CACHEPRG       0x00000008
/* Chip has copy back function */
#define NAND_COPYBACK       0x00000010
/* AND Chip which has 4 banks and a confusing page / block
 * assignment. See Renesas datasheet for further information */
#define NAND_IS_AND     0x00000020
/* Chip has a array of 4 pages which can be read without
 * additional ready /busy waits */
#define NAND_4PAGE_ARRAY    0x00000040
```

<a id="rst-constants-for-runtime-options"></a>

#### Constants for runtime options

These constants are defined in rawnand.h. They are OR-ed together to describe the functionality:



```text
/* The hw ecc generator provides a syndrome instead a ecc value on read
 * This can only work if we have the ecc bytes directly behind the
 * data bytes. Applies for DOC and AG-AND Renesas HW Reed Solomon generators */
#define NAND_HWECC_SYNDROME 0x00020000
```

<a id="rst-ecc-selection-constants"></a>

### ECC selection constants

Use these constants to select the ECC algorithm:



```text
/* No ECC. Usage is not recommended ! */
#define NAND_ECC_NONE       0
/* Software ECC 3 byte ECC per 256 Byte data */
#define NAND_ECC_SOFT       1
/* Hardware ECC 3 byte ECC per 256 Byte data */
#define NAND_ECC_HW3_256    2
/* Hardware ECC 3 byte ECC per 512 Byte data */
#define NAND_ECC_HW3_512    3
/* Hardware ECC 6 byte ECC per 512 Byte data */
#define NAND_ECC_HW6_512    4
/* Hardware ECC 8 byte ECC per 512 Byte data */
#define NAND_ECC_HW8_512    6
```

<a id="rst-hardware-control-related-constants"></a>

### Hardware control related constants

These constants describe the requested hardware access function when the boardspecific hardware control function is called:



```text
/* Select the chip by setting nCE to low */
#define NAND_CTL_SETNCE     1
/* Deselect the chip by setting nCE to high */
#define NAND_CTL_CLRNCE     2
/* Select the command latch by setting CLE to high */
#define NAND_CTL_SETCLE     3
/* Deselect the command latch by setting CLE to low */
#define NAND_CTL_CLRCLE     4
/* Select the address latch by setting ALE to high */
#define NAND_CTL_SETALE     5
/* Deselect the address latch by setting ALE to low */
#define NAND_CTL_CLRALE     6
/* Set write protection by setting WP to high. Not used! */
#define NAND_CTL_SETWP      7
/* Clear write protection by setting WP to low. Not used! */
#define NAND_CTL_CLRWP      8
```

<a id="rst-bad-block-table-related-constants"></a>

### Bad block table related constants

These constants describe the options used for bad block table descriptors:



```text
/* Options for the bad block table descriptors */

/* The number of bits used per block in the bbt on the device */
#define NAND_BBT_NRBITS_MSK 0x0000000F
#define NAND_BBT_1BIT       0x00000001
#define NAND_BBT_2BIT       0x00000002
#define NAND_BBT_4BIT       0x00000004
#define NAND_BBT_8BIT       0x00000008
/* The bad block table is in the last good block of the device */
#define NAND_BBT_LASTBLOCK  0x00000010
/* The bbt is at the given page, else we must scan for the bbt */
#define NAND_BBT_ABSPAGE    0x00000020
/* bbt is stored per chip on multichip devices */
#define NAND_BBT_PERCHIP    0x00000080
/* bbt has a version counter at offset veroffs */
#define NAND_BBT_VERSION    0x00000100
/* Create a bbt if none axists */
#define NAND_BBT_CREATE     0x00000200
/* Write bbt if necessary */
#define NAND_BBT_WRITE      0x00001000
/* Read and write back block contents when writing bbt */
#define NAND_BBT_SAVECONTENT    0x00002000
```

<a id="rst-structures"></a>

## Structures

This chapter contains the autogenerated documentation of the structures which are used in the NAND driver and might be relevant for a driver developer. Each struct member has a short description which is marked with an \[XXX\] identifier. See the chapter "Documentation hints" for an explanation.


#### <a id="c-struct-nand_parameters"></a>`struct nand_parameters`

NAND generic parameters from the parameter page

**Definition**

```c
struct nand_parameters {
    const char *model;
    bool supports_set_get_features;
    bool supports_read_cache;
    unsigned long set_feature_list[BITS_TO_LONGS(ONFI_FEATURE_NUMBER)];
    unsigned long get_feature_list[BITS_TO_LONGS(ONFI_FEATURE_NUMBER)];
    struct onfi_params *onfi;
};
```

**Members**

- `model`: Model name
- `supports_set_get_features`: The NAND chip supports setting/getting features
- `supports_read_cache`: The NAND chip supports read cache operations
- `set_feature_list`: Bitmap of features that can be set
- `get_feature_list`: Bitmap of features that can be get
- `onfi`: ONFI specific parameters

#### <a id="c-struct-nand_id"></a>`struct nand_id`

NAND id structure

**Definition**

```c
struct nand_id {
    u8 data[NAND_MAX_ID_LEN];
    int len;
};
```

**Members**

- `data`: buffer containing the id bytes.
- `len`: ID length.

#### <a id="c-struct-nand_ecc_step_info"></a>`struct nand_ecc_step_info`

ECC step information of ECC engine

**Definition**

```c
struct nand_ecc_step_info {
    int stepsize;
    const int *strengths;
    int nstrengths;
};
```

**Members**

- `stepsize`: data bytes per ECC step
- `strengths`: array of supported strengths
- `nstrengths`: number of supported strengths

#### <a id="c-struct-nand_ecc_caps"></a>`struct nand_ecc_caps`

capability of ECC engine

**Definition**

```c
struct nand_ecc_caps {
    const struct nand_ecc_step_info *stepinfos;
    int nstepinfos;
    int (*calc_ecc_bytes)(int step_size, int strength);
};
```

**Members**

- `stepinfos`: array of ECC step information
- `nstepinfos`: number of ECC step information
- `calc_ecc_bytes`: driver's hook to calculate ECC bytes per step

#### <a id="c-struct-nand_ecc_ctrl"></a>`struct nand_ecc_ctrl`

Control structure for ECC

**Definition**

```c
struct nand_ecc_ctrl {
    enum nand_ecc_engine_type engine_type;
    enum nand_ecc_placement placement;
    enum nand_ecc_algo algo;
    int steps;
    int size;
    int bytes;
    int total;
    int strength;
    int prepad;
    int postpad;
    unsigned int options;
    u8 *calc_buf;
    u8 *code_buf;
    void (*hwctl)(struct nand_chip *chip, int mode);
    int (*calculate)(struct nand_chip *chip, const uint8_t *dat, uint8_t *ecc_code);
    int (*correct)(struct nand_chip *chip, uint8_t *dat, uint8_t *read_ecc, uint8_t *calc_ecc);
    int (*read_page_raw)(struct nand_chip *chip, uint8_t *buf, int oob_required, int page);
    int (*write_page_raw)(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page);
    int (*read_page)(struct nand_chip *chip, uint8_t *buf, int oob_required, int page);
    int (*read_subpage)(struct nand_chip *chip, uint32_t offs, uint32_t len, uint8_t *buf, int page);
    int (*write_subpage)(struct nand_chip *chip, uint32_t offset, uint32_t data_len, const uint8_t *data_buf, int oob_required, int page);
    int (*write_page)(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page);
    int (*write_oob_raw)(struct nand_chip *chip, int page);
    int (*read_oob_raw)(struct nand_chip *chip, int page);
    int (*read_oob)(struct nand_chip *chip, int page);
    int (*write_oob)(struct nand_chip *chip, int page);
};
```

**Members**

- `engine_type`: ECC engine type
- `placement`: OOB bytes placement
- `algo`: ECC algorithm
- `steps`: number of ECC steps per page
- `size`: data bytes per ECC step
- `bytes`: ECC bytes per step
- `total`: total number of ECC bytes per page
- `strength`: max number of correctible bits per ECC step
- `prepad`: padding information for syndrome based ECC generators
- `postpad`: padding information for syndrome based ECC generators
- `options`: ECC specific options (see NAND_ECC_XXX flags defined above)
- `calc_buf`: buffer for calculated ECC, size is oobsize.
- `code_buf`: buffer for ECC read from flash, size is oobsize.
- `hwctl`: function to control hardware ECC generator. Must only
  be provided if an hardware ECC is available
- `calculate`: function for ECC calculation or readback from ECC hardware
- `correct`: function for ECC correction, matching to ECC generator (sw/hw).
  Should return a positive number representing the number of
  corrected bitflips, -EBADMSG if the number of bitflips exceed
  ECC strength, or any other error code if the error is not
  directly related to correction.
  If -EBADMSG is returned the input buffers should be left
  untouched.
- `read_page_raw`: function to read a raw page without ECC. This function
  should hide the specific layout used by the ECC
  controller and always return contiguous in-band and
  out-of-band data even if they're not stored
  contiguously on the NAND chip (e.g.
  NAND_ECC_PLACEMENT_INTERLEAVED interleaves in-band and
  out-of-band data).
- `write_page_raw`: function to write a raw page without ECC. This function
  should hide the specific layout used by the ECC
  controller and consider the passed data as contiguous
  in-band and out-of-band data. ECC controller is
  responsible for doing the appropriate transformations
  to adapt to its specific layout (e.g.
  NAND_ECC_PLACEMENT_INTERLEAVED interleaves in-band and
  out-of-band data).
- `read_page`: function to read a page according to the ECC generator
  requirements; returns maximum number of bitflips corrected in
  any single ECC step, -EIO hw error
- `read_subpage`: function to read parts of the page covered by ECC;
  returns same as `read_page()`
- `write_subpage`: function to write parts of the page covered by ECC.
- `write_page`: function to write a page according to the ECC generator
  requirements.
- `write_oob_raw`: function to write chip OOB data without ECC
- `read_oob_raw`: function to read chip OOB data without ECC
- `read_oob`: function to read chip OOB data
- `write_oob`: function to write chip OOB data

#### <a id="c-struct-nand_sdr_timings"></a>`struct nand_sdr_timings`

SDR NAND chip timings

**Definition**

```c
struct nand_sdr_timings {
    u64 tBERS_max;
    u32 tCCS_min;
    u64 tPROG_max;
    u64 tR_max;
    u32 tALH_min;
    u32 tADL_min;
    u32 tALS_min;
    u32 tAR_min;
    u32 tCEA_max;
    u32 tCEH_min;
    u32 tCH_min;
    u32 tCHZ_max;
    u32 tCLH_min;
    u32 tCLR_min;
    u32 tCLS_min;
    u32 tCOH_min;
    u32 tCS_min;
    u32 tDH_min;
    u32 tDS_min;
    u32 tFEAT_max;
    u32 tIR_min;
    u32 tITC_max;
    u32 tRC_min;
    u32 tREA_max;
    u32 tREH_min;
    u32 tRHOH_min;
    u32 tRHW_min;
    u32 tRHZ_max;
    u32 tRLOH_min;
    u32 tRP_min;
    u32 tRR_min;
    u64 tRST_max;
    u32 tWB_max;
    u32 tWC_min;
    u32 tWH_min;
    u32 tWHR_min;
    u32 tWP_min;
    u32 tWW_min;
};
```

**Members**

- `tBERS_max`: Block erase time
- `tCCS_min`: Change column setup time
- `tPROG_max`: Page program time
- `tR_max`: Page read time
- `tALH_min`: ALE hold time
- `tADL_min`: ALE to data loading time
- `tALS_min`: ALE setup time
- `tAR_min`: ALE to RE# delay
- `tCEA_max`: CE# access time
- `tCEH_min`: CE# high hold time
- `tCH_min`: CE# hold time
- `tCHZ_max`: CE# high to output hi-Z
- `tCLH_min`: CLE hold time
- `tCLR_min`: CLE to RE# delay
- `tCLS_min`: CLE setup time
- `tCOH_min`: CE# high to output hold
- `tCS_min`: CE# setup time
- `tDH_min`: Data hold time
- `tDS_min`: Data setup time
- `tFEAT_max`: Busy time for Set Features and Get Features
- `tIR_min`: Output hi-Z to RE# low
- `tITC_max`: Interface and Timing Mode Change time
- `tRC_min`: RE# cycle time
- `tREA_max`: RE# access time
- `tREH_min`: RE# high hold time
- `tRHOH_min`: RE# high to output hold
- `tRHW_min`: RE# high to WE# low
- `tRHZ_max`: RE# high to output hi-Z
- `tRLOH_min`: RE# low to output hold
- `tRP_min`: RE# pulse width
- `tRR_min`: Ready to RE# low (data only)
- `tRST_max`: Device reset time, measured from the falling edge of R/B# to the
  rising edge of R/B#.
- `tWB_max`: WE# high to SR\[6\] low
- `tWC_min`: WE# cycle time
- `tWH_min`: WE# high hold time
- `tWHR_min`: WE# high to RE# low
- `tWP_min`: WE# pulse width
- `tWW_min`: WP# transition to WE# low

**Description**

This struct defines the timing requirements of a SDR NAND chip.
These information can be found in every NAND datasheets and the timings
meaning are described in the ONFI specifications:
https://media-www.micron.com/-/media/client/onfi/specs/onfi_3_1_spec.pdf
(chapter 4.15 Timing Parameters)

All these timings are expressed in picoseconds.

#### <a id="c-struct-nand_nvddr_timings"></a>`struct nand_nvddr_timings`

NV-DDR NAND chip timings

**Definition**

```c
struct nand_nvddr_timings {
    u64 tBERS_max;
    u32 tCCS_min;
    u64 tPROG_max;
    u64 tR_max;
    u32 tAC_min;
    u32 tAC_max;
    u32 tADL_min;
    u32 tCAD_min;
    u32 tCAH_min;
    u32 tCALH_min;
    u32 tCALS_min;
    u32 tCAS_min;
    u32 tCEH_min;
    u32 tCH_min;
    u32 tCK_min;
    u32 tCS_min;
    u32 tDH_min;
    u32 tDQSCK_min;
    u32 tDQSCK_max;
    u32 tDQSD_min;
    u32 tDQSD_max;
    u32 tDQSHZ_max;
    u32 tDQSQ_max;
    u32 tDS_min;
    u32 tDSC_min;
    u32 tFEAT_max;
    u32 tITC_max;
    u32 tQHS_max;
    u32 tRHW_min;
    u32 tRR_min;
    u32 tRST_max;
    u32 tWB_max;
    u32 tWHR_min;
    u32 tWRCK_min;
    u32 tWW_min;
};
```

**Members**

- `tBERS_max`: Block erase time
- `tCCS_min`: Change column setup time
- `tPROG_max`: Page program time
- `tR_max`: Page read time
- `tAC_min`: Access window of DQ\[7:0\] from CLK
- `tAC_max`: Access window of DQ\[7:0\] from CLK
- `tADL_min`: ALE to data loading time
- `tCAD_min`: Command, Address, Data delay
- `tCAH_min`: Command/Address DQ hold time
- `tCALH_min`: W/R_n, CLE and ALE hold time
- `tCALS_min`: W/R_n, CLE and ALE setup time
- `tCAS_min`: Command/address DQ setup time
- `tCEH_min`: CE# high hold time
- `tCH_min`: CE# hold time
- `tCK_min`: Average clock cycle time
- `tCS_min`: CE# setup time
- `tDH_min`: Data hold time
- `tDQSCK_min`: Start of the access window of DQS from CLK
- `tDQSCK_max`: End of the access window of DQS from CLK
- `tDQSD_min`: Min W/R_n low to DQS/DQ driven by device
- `tDQSD_max`: Max W/R_n low to DQS/DQ driven by device
- `tDQSHZ_max`: W/R_n high to DQS/DQ tri-state by device
- `tDQSQ_max`: DQS-DQ skew, DQS to last DQ valid, per access
- `tDS_min`: Data setup time
- `tDSC_min`: DQS cycle time
- `tFEAT_max`: Busy time for Set Features and Get Features
- `tITC_max`: Interface and Timing Mode Change time
- `tQHS_max`: Data hold skew factor
- `tRHW_min`: Data output cycle to command, address, or data input cycle
- `tRR_min`: Ready to RE# low (data only)
- `tRST_max`: Device reset time, measured from the falling edge of R/B# to the
  rising edge of R/B#.
- `tWB_max`: WE# high to SR\[6\] low
- `tWHR_min`: WE# high to RE# low
- `tWRCK_min`: W/R_n low to data output cycle
- `tWW_min`: WP# transition to WE# low

**Description**

This struct defines the timing requirements of a NV-DDR NAND data interface.
These information can be found in every NAND datasheets and the timings
meaning are described in the ONFI specifications:
https://media-www.micron.com/-/media/client/onfi/specs/onfi_4_1_gold.pdf
(chapter 4.18.2 NV-DDR)

All these timings are expressed in picoseconds.

#### <a id="c-enum-nand_interface_type"></a>`enum nand_interface_type`

NAND interface type

**Constants**

- `NAND_SDR_IFACE`: Single Data Rate interface
- `NAND_NVDDR_IFACE`: Double Data Rate interface

#### <a id="c-struct-nand_interface_config"></a>`struct nand_interface_config`

NAND interface timing

**Definition**

```c
struct nand_interface_config {
    enum nand_interface_type type;
    struct nand_timings {
        unsigned int mode;
        union {
            struct nand_sdr_timings sdr;
            struct nand_nvddr_timings nvddr;
        };
    } timings;
};
```

**Members**

- `type`: type of the timing
- `timings`: The timing information
- `timings.mode`: Timing mode as defined in the specification
- `{unnamed_union}`: anonymous
- `timings.sdr`: Use it when **type** is `NAND_SDR_IFACE`.
- `timings.nvddr`: Use it when **type** is `NAND_NVDDR_IFACE`.

#### <a id="c-nand_interface_is_sdr"></a>`nand_interface_is_sdr()`

```c
bool nand_interface_is_sdr(const struct nand_interface_config *conf)
```

get the interface type

**Parameters**

- `const struct nand_interface_config *conf`: The data interface

#### <a id="c-nand_interface_is_nvddr"></a>`nand_interface_is_nvddr()`

```c
bool nand_interface_is_nvddr(const struct nand_interface_config *conf)
```

get the interface type

**Parameters**

- `const struct nand_interface_config *conf`: The data interface

#### <a id="c-nand_get_sdr_timings"></a>`nand_get_sdr_timings()`

```c
const struct nand_sdr_timings * nand_get_sdr_timings(const struct nand_interface_config *conf)
```

get SDR timing from data interface

**Parameters**

- `const struct nand_interface_config *conf`: The data interface

#### <a id="c-nand_get_nvddr_timings"></a>`nand_get_nvddr_timings()`

```c
const struct nand_nvddr_timings * nand_get_nvddr_timings(const struct nand_interface_config *conf)
```

get NV-DDR timing from data interface

**Parameters**

- `const struct nand_interface_config *conf`: The data interface

#### <a id="c-struct-nand_op_cmd_instr"></a>`struct nand_op_cmd_instr`

Definition of a command instruction

**Definition**

```c
struct nand_op_cmd_instr {
    u8 opcode;
};
```

**Members**

- `opcode`: the command to issue in one cycle

#### <a id="c-struct-nand_op_addr_instr"></a>`struct nand_op_addr_instr`

Definition of an address instruction

**Definition**

```c
struct nand_op_addr_instr {
    unsigned int naddrs;
    const u8 *addrs;
};
```

**Members**

- `naddrs`: length of the **addrs** array
- `addrs`: array containing the address cycles to issue

#### <a id="c-struct-nand_op_data_instr"></a>`struct nand_op_data_instr`

Definition of a data instruction

**Definition**

```c
struct nand_op_data_instr {
    unsigned int len;
    union {
        void *in;
        const void *out;
    } buf;
    bool force_8bit;
};
```

**Members**

- `len`: number of data bytes to move
- `buf`: buffer to fill
- `buf.in`: buffer to fill when reading from the NAND chip
- `buf.out`: buffer to read from when writing to the NAND chip
- `force_8bit`: force 8-bit access

**Description**

Please note that "in" and "out" are inverted from the ONFI specification
and are from the controller perspective, so a "in" is a read from the NAND
chip while a "out" is a write to the NAND chip.

#### <a id="c-struct-nand_op_waitrdy_instr"></a>`struct nand_op_waitrdy_instr`

Definition of a wait ready instruction

**Definition**

```c
struct nand_op_waitrdy_instr {
    unsigned int timeout_ms;
};
```

**Members**

- `timeout_ms`: maximum delay while waiting for the ready/busy pin in ms

#### <a id="c-enum-nand_op_instr_type"></a>`enum nand_op_instr_type`

Definition of all instruction types

**Constants**

- `NAND_OP_CMD_INSTR`: command instruction
- `NAND_OP_ADDR_INSTR`: address instruction
- `NAND_OP_DATA_IN_INSTR`: data in instruction
- `NAND_OP_DATA_OUT_INSTR`: data out instruction
- `NAND_OP_WAITRDY_INSTR`: wait ready instruction

#### <a id="c-struct-nand_op_instr"></a>`struct nand_op_instr`

Instruction object

**Definition**

```c
struct nand_op_instr {
    enum nand_op_instr_type type;
    union {
        struct nand_op_cmd_instr cmd;
        struct nand_op_addr_instr addr;
        struct nand_op_data_instr data;
        struct nand_op_waitrdy_instr waitrdy;
    } ctx;
    unsigned int delay_ns;
};
```

**Members**

- `type`: the instruction type
- `ctx`: extra data associated to the instruction. You'll have to use the
  appropriate element depending on **type**
- `ctx.cmd`: use it if **type** is `NAND_OP_CMD_INSTR`
- `ctx.addr`: use it if **type** is `NAND_OP_ADDR_INSTR`
- `ctx.data`: use it if **type** is `NAND_OP_DATA_IN_INSTR`
  or `NAND_OP_DATA_OUT_INSTR`
- `ctx.waitrdy`: use it if **type** is `NAND_OP_WAITRDY_INSTR`
- `delay_ns`: delay the controller should apply after the instruction has been
  issued on the bus. Most modern controllers have internal timings
  control logic, and in this case, the controller driver can ignore
  this field.

#### <a id="c-struct-nand_subop"></a>`struct nand_subop`

a sub operation

**Definition**

```c
struct nand_subop {
    unsigned int cs;
    const struct nand_op_instr *instrs;
    unsigned int ninstrs;
    unsigned int first_instr_start_off;
    unsigned int last_instr_end_off;
};
```

**Members**

- `cs`: the CS line to select for this NAND sub-operation
- `instrs`: array of instructions
- `ninstrs`: length of the **instrs** array
- `first_instr_start_off`: offset to start from for the first instruction
  of the sub-operation
- `last_instr_end_off`: offset to end at (excluded) for the last instruction
  of the sub-operation

**Description**

Both **first_instr_start_off** and **last_instr_end_off** only apply to data or
address instructions.

When an operation cannot be handled as is by the NAND controller, it will
be split by the parser into sub-operations which will be passed to the
controller driver.

#### <a id="c-struct-nand_op_parser_addr_constraints"></a>`struct nand_op_parser_addr_constraints`

Constraints for address instructions

**Definition**

```c
struct nand_op_parser_addr_constraints {
    unsigned int maxcycles;
};
```

**Members**

- `maxcycles`: maximum number of address cycles the controller can issue in a
  single step

#### <a id="c-struct-nand_op_parser_data_constraints"></a>`struct nand_op_parser_data_constraints`

Constraints for data instructions

**Definition**

```c
struct nand_op_parser_data_constraints {
    unsigned int maxlen;
};
```

**Members**

- `maxlen`: maximum data length that the controller can handle in a single step

#### <a id="c-struct-nand_op_parser_pattern_elem"></a>`struct nand_op_parser_pattern_elem`

One element of a pattern

**Definition**

```c
struct nand_op_parser_pattern_elem {
    enum nand_op_instr_type type;
    bool optional;
    union {
        struct nand_op_parser_addr_constraints addr;
        struct nand_op_parser_data_constraints data;
    } ctx;
};
```

**Members**

- `type`: the instructuction type
- `optional`: whether this element of the pattern is optional or mandatory
- `ctx`: address or data constraint
- `ctx.addr`: address constraint (number of cycles)
- `ctx.data`: data constraint (data length)

#### <a id="c-struct-nand_op_parser_pattern"></a>`struct nand_op_parser_pattern`

NAND sub-operation pattern descriptor

**Definition**

```c
struct nand_op_parser_pattern {
    const struct nand_op_parser_pattern_elem *elems;
    unsigned int nelems;
    int (*exec)(struct nand_chip *chip, const struct nand_subop *subop);
};
```

**Members**

- `elems`: array of pattern elements
- `nelems`: number of pattern elements in **elems** array
- `exec`: the function that will issue a sub-operation

**Description**

A pattern is a list of elements, each element reprensenting one instruction
with its constraints. The pattern itself is used by the core to match NAND
chip operation with NAND controller operations.
Once a match between a NAND controller operation pattern and a NAND chip
operation (or a sub-set of a NAND operation) is found, the pattern ->`exec()`
hook is called so that the controller driver can issue the operation on the
bus.

Controller drivers should declare as many patterns as they support and pass
this list of patterns (created with the help of the following macro) to
the [`nand_op_parser_exec_op()`](#c-nand_op_parser_exec_op) helper.

#### <a id="c-struct-nand_op_parser"></a>`struct nand_op_parser`

NAND controller operation parser descriptor

**Definition**

```c
struct nand_op_parser {
    const struct nand_op_parser_pattern *patterns;
    unsigned int npatterns;
};
```

**Members**

- `patterns`: array of supported patterns
- `npatterns`: length of the **patterns** array

**Description**

The parser descriptor is just an array of supported patterns which will be
iterated by [`nand_op_parser_exec_op()`](#c-nand_op_parser_exec_op) everytime it tries to execute an
NAND operation (or tries to determine if a specific operation is supported).

It is worth mentioning that patterns will be tested in their declaration
order, and the first match will be taken, so it's important to order patterns
appropriately so that simple/inefficient patterns are placed at the end of
the list. Usually, this is where you put single instruction patterns.

#### <a id="c-struct-nand_operation"></a>`struct nand_operation`

NAND operation descriptor

**Definition**

```c
struct nand_operation {
    unsigned int cs;
    bool deassert_wp;
    const struct nand_op_instr *instrs;
    unsigned int ninstrs;
};
```

**Members**

- `cs`: the CS line to select for this NAND operation
- `deassert_wp`: set to true when the operation requires the WP pin to be
  de-asserted (ERASE, PROG, ...)
- `instrs`: array of instructions to execute
- `ninstrs`: length of the **instrs** array

**Description**

The actual operation structure that will be passed to chip->`exec_op()`.

#### <a id="c-struct-nand_controller_ops"></a>`struct nand_controller_ops`

Controller operations

**Definition**

```c
struct nand_controller_ops {
    int (*attach_chip)(struct nand_chip *chip);
    void (*detach_chip)(struct nand_chip *chip);
    int (*exec_op)(struct nand_chip *chip, const struct nand_operation *op, bool check_only);
    int (*setup_interface)(struct nand_chip *chip, int chipnr, const struct nand_interface_config *conf);
};
```

**Members**

- `attach_chip`: this method is called after the NAND detection phase after
  flash ID and MTD fields such as erase size, page size and OOB
  size have been set up. ECC requirements are available if
  provided by the NAND chip or device tree. Typically used to
  choose the appropriate ECC configuration and allocate
  associated resources.
  This hook is optional.
- `detach_chip`: free all resources allocated/claimed in
  nand_controller_ops->`attach_chip()`.
  This hook is optional.
- `exec_op`: controller specific method to execute NAND operations.
  This method replaces chip->legacy.`cmdfunc()`,
  chip->legacy.{read,write}_{buf,byte,word}(),
  chip->legacy.`dev_ready()` and chip->legacy.`waitfunc()`.
- `setup_interface`: setup the data interface and timing. If chipnr is set to
  `NAND_DATA_IFACE_CHECK_ONLY` this means the configuration
  should not be applied but only checked.
  This hook is optional.

#### <a id="c-struct-nand_controller"></a>`struct nand_controller`

Structure used to describe a NAND controller

**Definition**

```c
struct nand_controller {
    struct mutex lock;
    const struct nand_controller_ops *ops;
    struct {
        unsigned int data_only_read: 1;
        unsigned int cont_read: 1;
    } supported_op;
    bool controller_wp;
};
```

**Members**

- `lock`: lock used to serialize accesses to the NAND controller
- `ops`: NAND controller operations.
- `supported_op`: NAND controller known-to-be-supported operations,
  only writable by the core after initial checking.
- `supported_op.data_only_read`: The controller supports reading more data from
  the bus without restarting an entire read operation nor
  changing the column.
- `supported_op.cont_read`: The controller supports sequential cache reads.
- `controller_wp`: the controller is in charge of handling the WP pin.

#### <a id="c-struct-nand_legacy"></a>`struct nand_legacy`

NAND chip legacy fields/hooks

**Definition**

```c
struct nand_legacy {
    void __iomem *IO_ADDR_R;
    void __iomem *IO_ADDR_W;
    void (*select_chip)(struct nand_chip *chip, int cs);
    u8 (*read_byte)(struct nand_chip *chip);
    void (*write_byte)(struct nand_chip *chip, u8 byte);
    void (*write_buf)(struct nand_chip *chip, const u8 *buf, int len);
    void (*read_buf)(struct nand_chip *chip, u8 *buf, int len);
    void (*cmd_ctrl)(struct nand_chip *chip, int dat, unsigned int ctrl);
    void (*cmdfunc)(struct nand_chip *chip, unsigned command, int column, int page_addr);
    int (*dev_ready)(struct nand_chip *chip);
    int (*waitfunc)(struct nand_chip *chip);
    int (*block_bad)(struct nand_chip *chip, loff_t ofs);
    int (*block_markbad)(struct nand_chip *chip, loff_t ofs);
    int (*set_features)(struct nand_chip *chip, int feature_addr, u8 *subfeature_para);
    int (*get_features)(struct nand_chip *chip, int feature_addr, u8 *subfeature_para);
    int chip_delay;
    struct nand_controller dummy_controller;
};
```

**Members**

- `IO_ADDR_R`: address to read the 8 I/O lines of the flash device
- `IO_ADDR_W`: address to write the 8 I/O lines of the flash device
- `select_chip`: select/deselect a specific target/die
- `read_byte`: read one byte from the chip
- `write_byte`: write a single byte to the chip on the low 8 I/O lines
- `write_buf`: write data from the buffer to the chip
- `read_buf`: read data from the chip into the buffer
- `cmd_ctrl`: hardware specific function for controlling ALE/CLE/nCE. Also used
  to write command and address
- `cmdfunc`: hardware specific function for writing commands to the chip.
- `dev_ready`: hardware specific function for accessing device ready/busy line.
  If set to NULL no access to ready/busy is available and the
  ready/busy information is read from the chip status register.
- `waitfunc`: hardware specific function for wait on ready.
- `block_bad`: check if a block is bad, using OOB markers
- `block_markbad`: mark a block bad
- `set_features`: set the NAND chip features
- `get_features`: get the NAND chip features
- `chip_delay`: chip dependent delay for transferring data from array to read
  regs (tR).
- `dummy_controller`: dummy controller implementation for drivers that can
  only control a single chip

**Description**

If you look at this structure you're already wrong. These fields/hooks are
all deprecated.

#### <a id="c-struct-nand_chip_ops"></a>`struct nand_chip_ops`

NAND chip operations

**Definition**

```c
struct nand_chip_ops {
    int (*suspend)(struct nand_chip *chip);
    void (*resume)(struct nand_chip *chip);
    int (*lock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
    int (*unlock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
    int (*setup_read_retry)(struct nand_chip *chip, int retry_mode);
    int (*choose_interface_config)(struct nand_chip *chip, struct nand_interface_config *iface);
};
```

**Members**

- `suspend`: Suspend operation
- `resume`: Resume operation
- `lock_area`: Lock operation
- `unlock_area`: Unlock operation
- `setup_read_retry`: Set the read-retry mode (mostly needed for MLC NANDs)
- `choose_interface_config`: Choose the best interface configuration

#### <a id="c-struct-nand_manufacturer"></a>`struct nand_manufacturer`

NAND manufacturer structure

**Definition**

```c
struct nand_manufacturer {
    const struct nand_manufacturer_desc *desc;
    void *priv;
};
```

**Members**

- `desc`: The manufacturer description
- `priv`: Private information for the manufacturer driver

#### <a id="c-struct-nand_secure_region"></a>`struct nand_secure_region`

NAND secure region structure

**Definition**

```c
struct nand_secure_region {
    u64 offset;
    u64 size;
};
```

**Members**

- `offset`: Offset of the start of the secure region
- `size`: Size of the secure region

#### <a id="c-struct-nand_chip"></a>`struct nand_chip`

NAND Private Flash Chip Data

**Definition**

```c
struct nand_chip {
    struct nand_device base;
    struct nand_id id;
    struct nand_parameters parameters;
    struct nand_manufacturer manufacturer;
    struct nand_chip_ops ops;
    struct nand_legacy legacy;
    unsigned int options;
    const struct nand_interface_config *current_interface_config;
    struct nand_interface_config *best_interface_config;
    unsigned int bbt_erase_shift;
    unsigned int bbt_options;
    unsigned int badblockpos;
    unsigned int badblockbits;
    struct nand_bbt_descr *bbt_td;
    struct nand_bbt_descr *bbt_md;
    struct nand_bbt_descr *badblock_pattern;
    u8 *bbt;
    unsigned int page_shift;
    unsigned int phys_erase_shift;
    unsigned int chip_shift;
    unsigned int pagemask;
    unsigned int subpagesize;
    u8 *data_buf;
    u8 *oob_poi;
    struct {
        unsigned int bitflips;
        int page;
    } pagecache;
    unsigned long buf_align;
    struct mutex lock;
    unsigned int suspended : 1;
    wait_queue_head_t resume_wq;
    int cur_cs;
    int read_retries;
    struct nand_secure_region *secure_regions;
    u8 nr_secure_regions;
    struct {
        bool ongoing;
        unsigned int first_page;
        unsigned int pause_page;
        unsigned int last_page;
    } cont_read;
    struct nand_controller *controller;
    struct nand_ecc_ctrl ecc;
    void *priv;
};
```

**Members**

- `base`: Inherit from the generic NAND device
- `id`: Holds NAND ID
- `parameters`: Holds generic parameters under an easily readable form
- `manufacturer`: Manufacturer information
- `ops`: NAND chip operations
- `legacy`: All legacy fields/hooks. If you develop a new driver, don't even try
  to use any of these fields/hooks, and if you're modifying an
  existing driver that is using those fields/hooks, you should
  consider reworking the driver and avoid using them.
- `options`: Various chip options. They can partly be set to inform nand_scan
  about special functionality. See the defines for further
  explanation.
- `current_interface_config`: The currently used NAND interface configuration
- `best_interface_config`: The best NAND interface configuration which fits both
  the NAND chip and NAND controller constraints. If
  unset, the default reset interface configuration must
  be used.
- `bbt_erase_shift`: Number of address bits in a bbt entry
- `bbt_options`: Bad block table specific options. All options used here must
  come from bbm.h. By default, these options will be copied to
  the appropriate nand_bbt_descr's.
- `badblockpos`: Bad block marker position in the oob area
- `badblockbits`: Minimum number of set bits in a good block's bad block marker
  position; i.e., BBM = 11110111b is good when badblockbits = 7
- `bbt_td`: Bad block table descriptor for flash lookup
- `bbt_md`: Bad block table mirror descriptor
- `badblock_pattern`: Bad block scan pattern used for initial bad block scan
- `bbt`: Bad block table pointer
- `page_shift`: Number of address bits in a page (column address bits)
- `phys_erase_shift`: Number of address bits in a physical eraseblock
- `chip_shift`: Number of address bits in one chip
- `pagemask`: Page number mask = number of (pages / chip) - 1
- `subpagesize`: Holds the subpagesize
- `data_buf`: Buffer for data, size is (page size + oobsize)
- `oob_poi`: pointer on the OOB area covered by data_buf
- `pagecache`: Structure containing page cache related fields
- `pagecache.bitflips`: Number of bitflips of the cached page
- `pagecache.page`: Page number currently in the cache. -1 means no page is
  currently cached
- `buf_align`: Minimum buffer alignment required by a platform
- `lock`: Lock protecting the suspended field. Also used to serialize accesses
  to the NAND device
- `suspended`: Set to 1 when the device is suspended, 0 when it's not
- `resume_wq`: wait queue to sleep if rawnand is in suspended state.
- `cur_cs`: Currently selected target. -1 means no target selected, otherwise we
  should always have cur_cs >= 0 && cur_cs \< `nanddev_ntargets()`.
  NAND Controller drivers should not modify this value, but they're
  allowed to read it.
- `read_retries`: The number of read retry modes supported
- `secure_regions`: Structure containing the secure regions info
- `nr_secure_regions`: Number of secure regions
- `cont_read`: Sequential page read internals
- `cont_read.ongoing`: Whether a continuous read is ongoing or not
- `cont_read.first_page`: Start of the continuous read operation
- `cont_read.pause_page`: End of the current sequential cache read operation
- `cont_read.last_page`: End of the continuous read operation
- `controller`: The hardware controller structure which is shared among multiple
  independent devices
- `ecc`: The ECC controller structure
- `priv`: Chip private data

#### <a id="c-nand_get_interface_config"></a>`nand_get_interface_config()`

```c
const struct nand_interface_config * nand_get_interface_config(struct nand_chip *chip)
```

Retrieve the current interface configuration of a NAND chip

**Parameters**

- `struct nand_chip *chip`: The NAND chip

#### <a id="c-struct-nand_flash_dev"></a>`struct nand_flash_dev`

NAND Flash Device ID Structure

**Definition**

```c
struct nand_flash_dev {
    char *name;
    union {
        struct {
            uint8_t mfr_id;
            uint8_t dev_id;
        };
        uint8_t id[NAND_MAX_ID_LEN];
    };
    unsigned int pagesize;
    unsigned int chipsize;
    unsigned int erasesize;
    unsigned int options;
    uint16_t id_len;
    uint16_t oobsize;
    struct {
        uint16_t strength_ds;
        uint16_t step_ds;
    } ecc;
};
```

**Members**

- `name`: a human-readable name of the NAND chip
- `{unnamed_union}`: anonymous
- `{unnamed_struct}`: anonymous
- `mfr_id`: manufacturer ID part of the full chip ID array (refers the same
  memory address as `id[0]`)
- `dev_id`: device ID part of the full chip ID array (refers the same memory
  address as `id[1]`)
- `id`: full device ID array
- `pagesize`: size of the NAND page in bytes; if 0, then the real page size (as
  well as the eraseblock size) is determined from the extended NAND
  chip ID array)
- `chipsize`: total chip size in MiB
- `erasesize`: eraseblock size in bytes (determined from the extended ID if 0)
- `options`: stores various chip bit options
- `id_len`: The valid length of the **id**.
- `oobsize`: OOB size
- `ecc`: ECC correctability and step information from the datasheet.
- `ecc.strength_ds`: The ECC correctability from the datasheet, same as the
  **ecc_strength_ds** in nand_chip{}.
- `ecc.step_ds`: The ECC step required by the **ecc.strength_ds**, same as the
  **ecc_step_ds** in nand_chip{}, also from the datasheet.
  For example, the "4bit ECC for each 512Byte" can be set with
  NAND_ECC_INFO(4, 512).

#### <a id="c-nand_opcode_8bits"></a>`nand_opcode_8bits()`

```c
int nand_opcode_8bits(unsigned int command)
```

Check if the opcode's address should be sent only on the lower 8 bits

**Parameters**

- `unsigned int command`: opcode to check

#### <a id="c-nand_get_data_buf"></a>`nand_get_data_buf()`

```c
void * nand_get_data_buf(struct nand_chip *chip)
```

Get the internal page buffer

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

Returns the pre-allocated page buffer after invalidating the cache. This
function should be used by drivers that do not want to allocate their own
bounce buffer and still need such a buffer for specific operations (most
commonly when reading OOB data only).

Be careful to never call this function in the write/write_oob path, because
the core may have placed the data to be written out in this buffer.

**Return**

pointer to the page cache buffer


<a id="rst-public-functions-provided"></a>

## Public Functions Provided

This chapter contains the autogenerated documentation of the NAND kernel API functions which are exported. Each function has a short description which is marked with an \[XXX\] identifier. See the chapter "Documentation hints" for an explanation.


#### <a id="c-nand_extract_bits"></a>`nand_extract_bits()`

```c
void nand_extract_bits(u8 *dst, unsigned int dst_off, const u8 *src, unsigned int src_off, unsigned int nbits)
```

Copy unaligned bits from one buffer to another one

**Parameters**

- `u8 *dst`: destination buffer
- `unsigned int dst_off`: bit offset at which the writing starts
- `const u8 *src`: source buffer
- `unsigned int src_off`: bit offset at which the reading starts
- `unsigned int nbits`: number of bits to copy from **src** to **dst**

**Description**

Copy bits from one memory region to another (overlap authorized).

#### <a id="c-nand_select_target"></a>`nand_select_target()`

```c
void nand_select_target(struct nand_chip *chip, unsigned int cs)
```

Select a NAND target (A.K.A. die)

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `unsigned int cs`: the CS line to select. Note that this CS id is always from the chip
  PoV, not the controller one

**Description**

Select a NAND target so that further operations executed on **chip** go to the
selected NAND target.

#### <a id="c-nand_deselect_target"></a>`nand_deselect_target()`

```c
void nand_deselect_target(struct nand_chip *chip)
```

Deselect the currently selected target

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

Deselect the currently selected NAND target. The result of operations
executed on **chip** after the target has been deselected is undefined.

#### <a id="c-nand_soft_waitrdy"></a>`nand_soft_waitrdy()`

```c
int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
```

Poll STATUS reg until RDY bit is set to 1

**Parameters**

- `struct nand_chip *chip`: NAND chip structure
- `unsigned long timeout_ms`: Timeout in ms

**Description**

Poll the STATUS register using ->`exec_op()` until the RDY bit becomes 1.
If that does not happen whitin the specified timeout, -ETIMEDOUT is
returned.

This helper is intended to be used when the controller does not have access
to the NAND R/B pin.

Be aware that calling this helper from an ->`exec_op()` implementation means
->`exec_op()` must be re-entrant.

Return 0 if the NAND chip is ready, a negative error otherwise.

#### <a id="c-nand_gpio_waitrdy"></a>`nand_gpio_waitrdy()`

```c
int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod, unsigned long timeout_ms)
```

Poll R/B GPIO pin until ready

**Parameters**

- `struct nand_chip *chip`: NAND chip structure
- `struct gpio_desc *gpiod`: GPIO descriptor of R/B pin
- `unsigned long timeout_ms`: Timeout in ms

**Description**

Poll the R/B GPIO pin until it becomes ready. If that does not happen
whitin the specified timeout, -ETIMEDOUT is returned.

This helper is intended to be used when the controller has access to the
NAND R/B pin over GPIO.

Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.

#### <a id="c-nand_read_page_op"></a>`nand_read_page_op()`

```c
int nand_read_page_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_page, void *buf, unsigned int len)
```

Do a READ PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int page`: page to read
- `unsigned int offset_in_page`: offset within the page
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer

**Description**

This function issues a READ PAGE operation.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_change_read_column_op"></a>`nand_change_read_column_op()`

```c
int nand_change_read_column_op(struct nand_chip *chip, unsigned int offset_in_page, void *buf, unsigned int len, bool force_8bit)
```

Do a CHANGE READ COLUMN operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int offset_in_page`: offset within the page
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer
- `bool force_8bit`: force 8-bit bus access

**Description**

This function issues a CHANGE READ COLUMN operation.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_read_oob_op"></a>`nand_read_oob_op()`

```c
int nand_read_oob_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_oob, void *buf, unsigned int len)
```

Do a READ OOB operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int page`: page to read
- `unsigned int offset_in_oob`: offset within the OOB area
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer

**Description**

This function issues a READ OOB operation.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_prog_page_begin_op"></a>`nand_prog_page_begin_op()`

```c
int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_page, const void *buf, unsigned int len)
```

starts a PROG PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int page`: page to write
- `unsigned int offset_in_page`: offset within the page
- `const void *buf`: buffer containing the data to write to the page
- `unsigned int len`: length of the buffer

**Description**

This function issues the first half of a PROG PAGE operation.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_prog_page_end_op"></a>`nand_prog_page_end_op()`

```c
int nand_prog_page_end_op(struct nand_chip *chip)
```

ends a PROG PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip

**Description**

This function issues the second half of a PROG PAGE operation.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_prog_page_op"></a>`nand_prog_page_op()`

```c
int nand_prog_page_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_page, const void *buf, unsigned int len)
```

Do a full PROG PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int page`: page to write
- `unsigned int offset_in_page`: offset within the page
- `const void *buf`: buffer containing the data to write to the page
- `unsigned int len`: length of the buffer

**Description**

This function issues a full PROG PAGE operation.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_change_write_column_op"></a>`nand_change_write_column_op()`

```c
int nand_change_write_column_op(struct nand_chip *chip, unsigned int offset_in_page, const void *buf, unsigned int len, bool force_8bit)
```

Do a CHANGE WRITE COLUMN operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int offset_in_page`: offset within the page
- `const void *buf`: buffer containing the data to send to the NAND
- `unsigned int len`: length of the buffer
- `bool force_8bit`: force 8-bit bus access

**Description**

This function issues a CHANGE WRITE COLUMN operation.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_readid_op"></a>`nand_readid_op()`

```c
int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf, unsigned int len)
```

Do a READID operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 addr`: address cycle to pass after the READID command
- `void *buf`: buffer used to store the ID
- `unsigned int len`: length of the buffer

**Description**

This function sends a READID command and reads back the ID returned by the
NAND.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_status_op"></a>`nand_status_op()`

```c
int nand_status_op(struct nand_chip *chip, u8 *status)
```

Do a STATUS operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 *status`: out variable to store the NAND status

**Description**

This function sends a STATUS command and reads back the status returned by
the NAND.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_exit_status_op"></a>`nand_exit_status_op()`

```c
int nand_exit_status_op(struct nand_chip *chip)
```

Exit a STATUS operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip

**Description**

This function sends a READ0 command to cancel the effect of the STATUS
command to avoid reading only the status until a new read command is sent.

This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_erase_op"></a>`nand_erase_op()`

```c
int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
```

Do an erase operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `unsigned int eraseblock`: block to erase

**Description**

This function sends an ERASE command and waits for the NAND to be ready
before returning.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_reset_op"></a>`nand_reset_op()`

```c
int nand_reset_op(struct nand_chip *chip)
```

Do a reset operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip

**Description**

This function sends a RESET command and waits for the NAND to be ready
before returning.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_read_data_op"></a>`nand_read_data_op()`

```c
int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len, bool force_8bit, bool check_only)
```

Read data from the NAND

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer
- `bool force_8bit`: force 8-bit bus access
- `bool check_only`: do not actually run the command, only checks if the
  controller driver supports it

**Description**

This function does a raw data read on the bus. Usually used after launching
another NAND operation like [`nand_read_page_op()`](#c-nand_read_page_op).
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_write_data_op"></a>`nand_write_data_op()`

```c
int nand_write_data_op(struct nand_chip *chip, const void *buf, unsigned int len, bool force_8bit)
```

Write data from the NAND

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `const void *buf`: buffer containing the data to send on the bus
- `unsigned int len`: length of the buffer
- `bool force_8bit`: force 8-bit bus access

**Description**

This function does a raw data write on the bus. Usually used after launching
another NAND operation like `nand_write_page_begin_op()`.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_op_parser_exec_op"></a>`nand_op_parser_exec_op()`

```c
int nand_op_parser_exec_op(struct nand_chip *chip, const struct nand_op_parser *parser, const struct nand_operation *op, bool check_only)
```

exec_op parser

**Parameters**

- `struct nand_chip *chip`: the NAND chip
- `const struct nand_op_parser *parser`: patterns description provided by the controller driver
- `const struct nand_operation *op`: the NAND operation to address
- `bool check_only`: when true, the function only checks if **op** can be handled but
  does not execute the operation

**Description**

Helper function designed to ease integration of NAND controller drivers that
only support a limited set of instruction sequences. The supported sequences
are described in **parser**, and the framework takes care of splitting **op** into
multiple sub-operations (if required) and pass them back to the ->`exec()`
callback of the matching pattern if **check_only** is set to false.

NAND controller drivers should call this function from their own ->`exec_op()`
implementation.

Returns 0 on success, a negative error code otherwise. A failure can be
caused by an unsupported operation (none of the supported patterns is able
to handle the requested operation), or an error returned by one of the
matching pattern->`exec()` hook.

#### <a id="c-nand_subop_get_addr_start_off"></a>`nand_subop_get_addr_start_off()`

```c
unsigned int nand_subop_get_addr_start_off(const struct nand_subop *subop, unsigned int instr_idx)
```

Get the start offset in an address array

**Parameters**

- `const struct nand_subop *subop`: The entire sub-operation
- `unsigned int instr_idx`: Index of the instruction inside the sub-operation

**Description**

During driver development, one could be tempted to directly use the
->addr.addrs field of address instructions. This is wrong as address
instructions might be split.

Given an address instruction, returns the offset of the first cycle to issue.

#### <a id="c-nand_subop_get_num_addr_cyc"></a>`nand_subop_get_num_addr_cyc()`

```c
unsigned int nand_subop_get_num_addr_cyc(const struct nand_subop *subop, unsigned int instr_idx)
```

Get the remaining address cycles to assert

**Parameters**

- `const struct nand_subop *subop`: The entire sub-operation
- `unsigned int instr_idx`: Index of the instruction inside the sub-operation

**Description**

During driver development, one could be tempted to directly use the
->addr->naddrs field of a data instruction. This is wrong as instructions
might be split.

Given an address instruction, returns the number of address cycle to issue.

#### <a id="c-nand_subop_get_data_start_off"></a>`nand_subop_get_data_start_off()`

```c
unsigned int nand_subop_get_data_start_off(const struct nand_subop *subop, unsigned int instr_idx)
```

Get the start offset in a data array

**Parameters**

- `const struct nand_subop *subop`: The entire sub-operation
- `unsigned int instr_idx`: Index of the instruction inside the sub-operation

**Description**

During driver development, one could be tempted to directly use the
->data->buf.{in,out} field of data instructions. This is wrong as data
instructions might be split.

Given a data instruction, returns the offset to start from.

#### <a id="c-nand_subop_get_data_len"></a>`nand_subop_get_data_len()`

```c
unsigned int nand_subop_get_data_len(const struct nand_subop *subop, unsigned int instr_idx)
```

Get the number of bytes to retrieve

**Parameters**

- `const struct nand_subop *subop`: The entire sub-operation
- `unsigned int instr_idx`: Index of the instruction inside the sub-operation

**Description**

During driver development, one could be tempted to directly use the
->data->len field of a data instruction. This is wrong as data instructions
might be split.

Returns the length of the chunk of data to send/receive.

#### <a id="c-nand_reset"></a>`nand_reset()`

```c
int nand_reset(struct nand_chip *chip, int chipnr)
```

Reset and initialize a NAND device

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `int chipnr`: Internal die id

**Description**

Save the timings data structure, then apply SDR timings mode 0 (see
nand_reset_interface for details), do the reset operation, and apply
back the previous timings.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_read_page_raw"></a>`nand_read_page_raw()`

```c
int nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[INTERN\] read raw page data without ecc

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

Not for syndrome calculating ECC controllers, which use a special oob layout.

#### <a id="c-nand_monolithic_read_page_raw"></a>`nand_monolithic_read_page_raw()`

```c
int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf, int oob_required, int page)
```

Monolithic page read in raw mode

**Parameters**

- `struct nand_chip *chip`: NAND chip info structure
- `u8 *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

This is a raw page read, ie. without any error detection/correction.
Monolithic means we are requesting all the relevant data (main plus
eventually OOB) to be loaded in the NAND cache and sent over the
bus (from the NAND chip to the NAND controller) in a single
operation. This is an alternative to [`nand_read_page_raw()`](#c-nand_read_page_raw), which
first reads the main data, and if the OOB data is requested too,
then reads more data on the bus.

#### <a id="c-nand_read_page_hwecc_oob_first"></a>`nand_read_page_hwecc_oob_first()`

```c
int nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

Hardware ECC page read with ECC data read from OOB area

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

Hardware ECC for large page chips, which requires the ECC data to be
extracted from the OOB before the actual data is read.

#### <a id="c-nand_read_oob_std"></a>`nand_read_oob_std()`

```c
int nand_read_oob_std(struct nand_chip *chip, int page)
```

\[REPLACEABLE\] the most common OOB data read function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `int page`: page number to read

#### <a id="c-nand_write_oob_std"></a>`nand_write_oob_std()`

```c
int nand_write_oob_std(struct nand_chip *chip, int page)
```

\[REPLACEABLE\] the most common OOB data write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `int page`: page number to write

#### <a id="c-nand_write_page_raw"></a>`nand_write_page_raw()`

```c
int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[INTERN\] raw page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

Not for syndrome calculating ECC controllers, which use a special oob layout.

#### <a id="c-nand_monolithic_write_page_raw"></a>`nand_monolithic_write_page_raw()`

```c
int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf, int oob_required, int page)
```

Monolithic page write in raw mode

**Parameters**

- `struct nand_chip *chip`: NAND chip info structure
- `const u8 *buf`: data buffer to write
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

This is a raw page write, ie. without any error detection/correction.
Monolithic means we are requesting all the relevant data (main plus
eventually OOB) to be sent over the bus and effectively programmed
into the NAND chip arrays in a single operation. This is an
alternative to [`nand_write_page_raw()`](#c-nand_write_page_raw), which first sends the main
data, then eventually send the OOB data by latching more data
cycles on the NAND bus, and finally sends the program command to
synchronyze the NAND chip cache.

#### <a id="c-rawnand_dt_parse_gpio_cs"></a>`rawnand_dt_parse_gpio_cs()`

```c
int rawnand_dt_parse_gpio_cs(struct device *dev, struct gpio_desc ***cs_array, unsigned int *ncs_array)
```

Parse the gpio-cs property of a controller

**Parameters**

- `struct device *dev`: Device that will be parsed. Also used for managed allocations.
- `struct gpio_desc ***cs_array`: Array of GPIO desc pointers allocated on success
- `unsigned int *ncs_array`: Number of entries in **cs_array** updated on success.
  **return** 0 on success, an error otherwise.

#### <a id="c-nand_ecc_choose_conf"></a>`nand_ecc_choose_conf()`

```c
int nand_ecc_choose_conf(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)
```

Set the ECC strength and ECC step size

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const struct nand_ecc_caps *caps`: ECC engine caps info structure
- `int oobavail`: OOB size that the ECC engine can use

**Description**

Choose the ECC configuration according to following logic.

1. If both ECC step size and ECC strength are already set (usually by DT)
   then check if it is supported by this controller.
2. If the user provided the nand-ecc-maximize property, then select maximum
   ECC strength.
3. Otherwise, try to match the ECC step size and ECC strength closest
   to the chip's requirement. If available OOB size can't fit the chip
   requirement then fallback to the maximum ECC step size and ECC strength.

On success, the chosen ECC settings are set.

#### <a id="c-nand_scan_with_ids"></a>`nand_scan_with_ids()`

```c
int nand_scan_with_ids(struct nand_chip *chip, unsigned int maxchips, struct nand_flash_dev *ids)
```

\[NAND Interface\] Scan for the NAND device

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `unsigned int maxchips`: number of chips to scan for.
- `struct nand_flash_dev *ids`: optional flash IDs table

**Description**

This fills out all the uninitialized function pointers with the defaults.
The flash ID is read and the mtd/chip structures are filled with the
appropriate values.

#### <a id="c-nand_cleanup"></a>`nand_cleanup()`

```c
void nand_cleanup(struct nand_chip *chip)
```

\[NAND Interface\] Free resources held by the NAND device

**Parameters**

- `struct nand_chip *chip`: NAND chip object


<a id="rst-internal-functions-provided"></a>

## Internal Functions Provided

This chapter contains the autogenerated documentation of the NAND driver internal functions. Each function has a short description which is marked with an \[XXX\] identifier. See the chapter "Documentation hints" for an explanation. The functions marked with \[DEFAULT\] might be relevant for a board driver developer.


#### <a id="c-nand_release_device"></a>`nand_release_device()`

```c
void nand_release_device(struct nand_chip *chip)
```

\[GENERIC\] release chip

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

Release chip lock and wake up anyone waiting on the device.

#### <a id="c-nand_bbm_get_next_page"></a>`nand_bbm_get_next_page()`

```c
int nand_bbm_get_next_page(struct nand_chip *chip, int page)
```

Get the next page for bad block markers

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `int page`: First page to start checking for bad block marker usage

**Description**

Returns an integer that corresponds to the page offset within a block, for
a page that is used to store bad block markers. If no more pages are
available, -EINVAL is returned.

#### <a id="c-nand_block_bad"></a>`nand_block_bad()`

```c
int nand_block_bad(struct nand_chip *chip, loff_t ofs)
```

\[DEFAULT\] Read bad block marker from the chip

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset from device start

**Description**

Check, if the block is bad.

#### <a id="c-nand_region_is_secured"></a>`nand_region_is_secured()`

```c
bool nand_region_is_secured(struct nand_chip *chip, loff_t offset, u64 size)
```

Check if the region is secured

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t offset`: Offset of the region to check
- `u64 size`: Size of the region to check

**Description**

Checks if the region is secured by comparing the offset and size with the
list of secure regions obtained from DT. Returns true if the region is
secured else false.

#### <a id="c-nand_get_device"></a>`nand_get_device()`

```c
void nand_get_device(struct nand_chip *chip)
```

\[GENERIC\] Get chip for selected access

**Parameters**

- `struct nand_chip *chip`: NAND chip structure

**Description**

Lock the device and its controller for exclusive access

#### <a id="c-nand_check_wp"></a>`nand_check_wp()`

```c
int nand_check_wp(struct nand_chip *chip)
```

\[GENERIC\] check if the chip is write protected

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

Check, if the device is write protected. The function expects, that the
device is already selected.

#### <a id="c-nand_fill_oob"></a>`nand_fill_oob()`

```c
uint8_t * nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len, struct mtd_oob_ops *ops)
```

\[INTERN\] Transfer client buffer to oob

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `uint8_t *oob`: oob data buffer
- `size_t len`: oob data write length
- `struct mtd_oob_ops *ops`: oob ops structure

#### <a id="c-nand_do_write_oob"></a>`nand_do_write_oob()`

```c
int nand_do_write_oob(struct nand_chip *chip, loff_t to, struct mtd_oob_ops *ops)
```

\[MTD Interface\] NAND write out-of-band

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t to`: offset to write to
- `struct mtd_oob_ops *ops`: oob operation description structure

**Description**

NAND write out-of-band.

#### <a id="c-nand_default_block_markbad"></a>`nand_default_block_markbad()`

```c
int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)
```

\[DEFAULT\] mark a block bad via bad block marker

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset from device start

**Description**

This is the default implementation, which can be overridden by a hardware
specific driver. It provides the details for writing a bad block marker to a
block.

#### <a id="c-nand_markbad_bbm"></a>`nand_markbad_bbm()`

```c
int nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)
```

mark a block by updating the BBM

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset of the block to mark bad

#### <a id="c-nand_block_markbad_lowlevel"></a>`nand_block_markbad_lowlevel()`

```c
int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)
```

mark a block bad

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset from device start

**Description**

This function performs the generic NAND bad block marking steps (i.e., bad
block table(s) and/or marker(s)). We only allow the hardware driver to
specify how to write bad block markers to OOB (chip->legacy.block_markbad).

We try operations in the following order:

(1) erase the affected block, to allow OOB marker to be written cleanly
(2) write bad block marker to OOB area of affected block (unless flag
NAND_BBT_NO_OOB_BBM is present)
(3) update the BBT

Note that we retain the first error encountered in (2) or (3), finish the
procedures, and dump the error in the end.

#### <a id="c-nand_block_isreserved"></a>`nand_block_isreserved()`

```c
int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
```

\[GENERIC\] Check if a block is marked reserved.

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t ofs`: offset from device start

**Description**

Check if the block is marked as reserved.

#### <a id="c-nand_block_checkbad"></a>`nand_block_checkbad()`

```c
int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)
```

\[GENERIC\] Check if a block is marked bad

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t ofs`: offset from device start
- `int allowbbt`: 1, if its allowed to access the bbt area

**Description**

Check, if the block is bad. Either by reading the bad block table or
calling of the scan function.

#### <a id="c-panic_nand_wait"></a>`panic_nand_wait()`

```c
void panic_nand_wait(struct nand_chip *chip, unsigned long timeo)
```

\[GENERIC\] wait until the command is done

**Parameters**

- `struct nand_chip *chip`: NAND chip structure
- `unsigned long timeo`: timeout

**Description**

Wait for command done. This is a helper function for nand_wait used when
we are in interrupt context. May happen when in panic and trying to write
an oops through mtdoops.

#### <a id="c-nand_reset_interface"></a>`nand_reset_interface()`

```c
int nand_reset_interface(struct nand_chip *chip, int chipnr)
```

Reset data interface and timings

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `int chipnr`: Internal die id

**Description**

Reset the Data interface and timings to ONFI mode 0.

Returns 0 for success or negative error code otherwise.

#### <a id="c-nand_setup_interface"></a>`nand_setup_interface()`

```c
int nand_setup_interface(struct nand_chip *chip, int chipnr)
```

Setup the best data interface and timings

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `int chipnr`: Internal die id

**Description**

Configure what has been reported to be the best data interface and NAND
timings supported by the chip and the driver.

Returns 0 for success or negative error code otherwise.

#### <a id="c-nand_choose_best_sdr_timings"></a>`nand_choose_best_sdr_timings()`

```c
int nand_choose_best_sdr_timings(struct nand_chip *chip, struct nand_interface_config *iface, struct nand_sdr_timings *spec_timings)
```

Pick up the best SDR timings that both the NAND controller and the NAND chip support

**Parameters**

- `struct nand_chip *chip`: the NAND chip
- `struct nand_interface_config *iface`: the interface configuration (can eventually be updated)
- `struct nand_sdr_timings *spec_timings`: specific timings, when not fitting the ONFI specification

**Description**

If specific timings are provided, use them. Otherwise, retrieve supported
timing modes from ONFI information.

#### <a id="c-nand_choose_best_nvddr_timings"></a>`nand_choose_best_nvddr_timings()`

```c
int nand_choose_best_nvddr_timings(struct nand_chip *chip, struct nand_interface_config *iface, struct nand_nvddr_timings *spec_timings)
```

Pick up the best NVDDR timings that both the NAND controller and the NAND chip support

**Parameters**

- `struct nand_chip *chip`: the NAND chip
- `struct nand_interface_config *iface`: the interface configuration (can eventually be updated)
- `struct nand_nvddr_timings *spec_timings`: specific timings, when not fitting the ONFI specification

**Description**

If specific timings are provided, use them. Otherwise, retrieve supported
timing modes from ONFI information.

#### <a id="c-nand_choose_best_timings"></a>`nand_choose_best_timings()`

```c
int nand_choose_best_timings(struct nand_chip *chip, struct nand_interface_config *iface)
```

Pick up the best NVDDR or SDR timings that both NAND controller and the NAND chip support

**Parameters**

- `struct nand_chip *chip`: the NAND chip
- `struct nand_interface_config *iface`: the interface configuration (can eventually be updated)

**Description**

If specific timings are provided, use them. Otherwise, retrieve supported
timing modes from ONFI information.

#### <a id="c-nand_choose_interface_config"></a>`nand_choose_interface_config()`

```c
int nand_choose_interface_config(struct nand_chip *chip)
```

find the best data interface and timings

**Parameters**

- `struct nand_chip *chip`: The NAND chip

**Description**

Find the best data interface and NAND timings supported by the chip
and the driver. Eventually let the NAND manufacturer driver propose his own
set of timings.

After this function nand_chip->interface_config is initialized with the best
timing mode available.

Returns 0 for success or negative error code otherwise.

#### <a id="c-nand_fill_column_cycles"></a>`nand_fill_column_cycles()`

```c
int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs, unsigned int offset_in_page)
```

fill the column cycles of an address

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 *addrs`: Array of address cycles to fill
- `unsigned int offset_in_page`: The offset in the page

**Description**

Fills the first or the first two bytes of the **addrs** field depending
on the NAND bus width and the page size.

Returns the number of cycles needed to encode the column, or a negative
error code in case one of the arguments is invalid.

#### <a id="c-nand_read_param_page_op"></a>`nand_read_param_page_op()`

```c
int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf, unsigned int len)
```

Do a READ PARAMETER PAGE operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 page`: parameter page to read
- `void *buf`: buffer used to store the data
- `unsigned int len`: length of the buffer

**Description**

This function issues a READ PARAMETER PAGE operation.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_set_features_op"></a>`nand_set_features_op()`

```c
int nand_set_features_op(struct nand_chip *chip, u8 feature, const void *data)
```

Do a SET FEATURES operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 feature`: feature id
- `const void *data`: 4 bytes of data

**Description**

This function sends a SET FEATURES command and waits for the NAND to be
ready before returning.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-nand_get_features_op"></a>`nand_get_features_op()`

```c
int nand_get_features_op(struct nand_chip *chip, u8 feature, void *data)
```

Do a GET FEATURES operation

**Parameters**

- `struct nand_chip *chip`: The NAND chip
- `u8 feature`: feature id
- `void *data`: 4 bytes of data

**Description**

This function sends a GET FEATURES command and waits for the NAND to be
ready before returning.
This function does not select/unselect the CS line.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-struct-nand_op_parser_ctx"></a>`struct nand_op_parser_ctx`

Context used by the parser

**Definition**

```c
struct nand_op_parser_ctx {
    const struct nand_op_instr *instrs;
    unsigned int ninstrs;
    struct nand_subop subop;
};
```

**Members**

- `instrs`: array of all the instructions that must be addressed
- `ninstrs`: length of the **instrs** array
- `subop`: Sub-operation to be passed to the NAND controller

**Description**

This structure is used by the core to split NAND operations into
sub-operations that can be handled by the NAND controller.

#### <a id="c-nand_op_parser_must_split_instr"></a>`nand_op_parser_must_split_instr()`

```c
bool nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat, const struct nand_op_instr *instr, unsigned int *start_offset)
```

Checks if an instruction must be split

**Parameters**

- `const struct nand_op_parser_pattern_elem *pat`: the parser pattern element that matches **instr**
- `const struct nand_op_instr *instr`: pointer to the instruction to check
- `unsigned int *start_offset`: this is an in/out parameter. If **instr** has already been
  split, then **start_offset** is the offset from which to start
  (either an address cycle or an offset in the data buffer).
  Conversely, if the function returns true (ie. instr must be
  split), this parameter is updated to point to the first
  data/address cycle that has not been taken care of.

**Description**

Some NAND controllers are limited and cannot send X address cycles with a
unique operation, or cannot read/write more than Y bytes at the same time.
In this case, split the instruction that does not fit in a single
controller-operation into two or more chunks.

Returns true if the instruction must be split, false otherwise.
The **start_offset** parameter is also updated to the offset at which the next
bundle of instruction must start (if an address or a data instruction).

#### <a id="c-nand_op_parser_match_pat"></a>`nand_op_parser_match_pat()`

```c
bool nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat, struct nand_op_parser_ctx *ctx)
```

Checks if a pattern matches the instructions remaining in the parser context

**Parameters**

- `const struct nand_op_parser_pattern *pat`: the pattern to test
- `struct nand_op_parser_ctx *ctx`: the parser context structure to match with the pattern **pat**

**Description**

Check if **pat** matches the set or a sub-set of instructions remaining in **ctx**.
Returns true if this is the case, false ortherwise. When true is returned,
**ctx->subop** is updated with the set of instructions to be passed to the
controller driver.

#### <a id="c-nand_get_features"></a>`nand_get_features()`

```c
int nand_get_features(struct nand_chip *chip, int addr, u8 *subfeature_param)
```

wrapper to perform a GET_FEATURE

**Parameters**

- `struct nand_chip *chip`: NAND chip info structure
- `int addr`: feature address
- `u8 *subfeature_param`: the subfeature parameters, a four bytes array

**Description**

Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
operation cannot be handled.

#### <a id="c-nand_set_features"></a>`nand_set_features()`

```c
int nand_set_features(struct nand_chip *chip, int addr, u8 *subfeature_param)
```

wrapper to perform a SET_FEATURE

**Parameters**

- `struct nand_chip *chip`: NAND chip info structure
- `int addr`: feature address
- `u8 *subfeature_param`: the subfeature parameters, a four bytes array

**Description**

Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
operation cannot be handled.

#### <a id="c-nand_read_page_raw_notsupp"></a>`nand_read_page_raw_notsupp()`

```c
int nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf, int oob_required, int page)
```

dummy read raw page function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `u8 *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

Returns -ENOTSUPP unconditionally.

#### <a id="c-nand_read_page_raw_syndrome"></a>`nand_read_page_raw_syndrome()`

```c
int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[INTERN\] read raw page data without ecc

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

We need a special oob layout and handling even when OOB isn't used.

#### <a id="c-nand_read_page_swecc"></a>`nand_read_page_swecc()`

```c
int nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] software ECC based page read function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

#### <a id="c-nand_read_subpage"></a>`nand_read_subpage()`

```c
int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi, int page)
```

\[REPLACEABLE\] ECC based sub-page read function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint32_t data_offs`: offset of requested data within the page
- `uint32_t readlen`: data length
- `uint8_t *bufpoi`: buffer to store read data
- `int page`: page number to read

#### <a id="c-nand_read_page_hwecc"></a>`nand_read_page_hwecc()`

```c
int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC based page read function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

Not for syndrome calculating ECC controllers which need a special oob layout.

#### <a id="c-nand_read_page_syndrome"></a>`nand_read_page_syndrome()`

```c
int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC syndrome based page read

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint8_t *buf`: buffer to store read data
- `int oob_required`: caller requires OOB data read to chip->oob_poi
- `int page`: page number to read

**Description**

The hw generator calculates the error syndrome automatically. Therefore we
need a special oob layout and handling.

#### <a id="c-nand_transfer_oob"></a>`nand_transfer_oob()`

```c
uint8_t * nand_transfer_oob(struct nand_chip *chip, uint8_t *oob, struct mtd_oob_ops *ops, size_t len)
```

\[INTERN\] Transfer oob to client buffer

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `uint8_t *oob`: oob destination address
- `struct mtd_oob_ops *ops`: oob ops structure
- `size_t len`: size of oob to transfer

#### <a id="c-nand_setup_read_retry"></a>`nand_setup_read_retry()`

```c
int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)
```

\[INTERN\] Set the READ RETRY mode

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `int retry_mode`: the retry mode to use

**Description**

Some vendors supply a special command to shift the Vt threshold, to be used
when there are too many bitflips in a page (i.e., ECC error). After setting
a new threshold, the host should retry reading the page.

#### <a id="c-nand_do_read_ops"></a>`nand_do_read_ops()`

```c
int nand_do_read_ops(struct nand_chip *chip, loff_t from, struct mtd_oob_ops *ops)
```

\[INTERN\] Read data with ECC

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t from`: offset to read from
- `struct mtd_oob_ops *ops`: oob ops structure

**Description**

Internal function. Called with chip held.

#### <a id="c-nand_read_oob_syndrome"></a>`nand_read_oob_syndrome()`

```c
int nand_read_oob_syndrome(struct nand_chip *chip, int page)
```

\[REPLACEABLE\] OOB data read function for HW ECC with syndromes

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `int page`: page number to read

#### <a id="c-nand_write_oob_syndrome"></a>`nand_write_oob_syndrome()`

```c
int nand_write_oob_syndrome(struct nand_chip *chip, int page)
```

\[REPLACEABLE\] OOB data write function for HW ECC with syndrome - only for large page flash

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `int page`: page number to write

#### <a id="c-nand_do_read_oob"></a>`nand_do_read_oob()`

```c
int nand_do_read_oob(struct nand_chip *chip, loff_t from, struct mtd_oob_ops *ops)
```

\[INTERN\] NAND read out-of-band

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t from`: offset to read from
- `struct mtd_oob_ops *ops`: oob operations description structure

**Description**

NAND read out-of-band data from the spare area.

#### <a id="c-nand_read_oob"></a>`nand_read_oob()`

```c
int nand_read_oob(struct mtd_info *mtd, loff_t from, struct mtd_oob_ops *ops)
```

\[MTD Interface\] NAND read data and/or out-of-band

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t from`: offset to read from
- `struct mtd_oob_ops *ops`: oob operation description structure

**Description**

NAND read data and/or out-of-band data.

#### <a id="c-nand_write_page_raw_notsupp"></a>`nand_write_page_raw_notsupp()`

```c
int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf, int oob_required, int page)
```

dummy raw page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const u8 *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

Returns -ENOTSUPP unconditionally.

#### <a id="c-nand_write_page_raw_syndrome"></a>`nand_write_page_raw_syndrome()`

```c
int nand_write_page_raw_syndrome(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[INTERN\] raw page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

We need a special oob layout and handling even when ECC isn't checked.

#### <a id="c-nand_write_page_swecc"></a>`nand_write_page_swecc()`

```c
int nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] software ECC based page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

#### <a id="c-nand_write_page_hwecc"></a>`nand_write_page_hwecc()`

```c
int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC based page write function

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

#### <a id="c-nand_write_subpage_hwecc"></a>`nand_write_subpage_hwecc()`

```c
int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset, uint32_t data_len, const uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC based subpage write

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `uint32_t offset`: column address of subpage within the page
- `uint32_t data_len`: data length
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

#### <a id="c-nand_write_page_syndrome"></a>`nand_write_page_syndrome()`

```c
int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)
```

\[REPLACEABLE\] hardware ECC syndrome based page write

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const uint8_t *buf`: data buffer
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write

**Description**

The hw generator calculates the error syndrome automatically. Therefore we
need a special oob layout and handling.

#### <a id="c-nand_write_page"></a>`nand_write_page()`

```c
int nand_write_page(struct nand_chip *chip, uint32_t offset, int data_len, const uint8_t *buf, int oob_required, int page, int raw)
```

write one page

**Parameters**

- `struct nand_chip *chip`: NAND chip descriptor
- `uint32_t offset`: address offset within the page
- `int data_len`: length of actual data to be written
- `const uint8_t *buf`: the data to write
- `int oob_required`: must write chip->oob_poi to OOB
- `int page`: page number to write
- `int raw`: use _raw version of write_page

#### <a id="c-nand_do_write_ops"></a>`nand_do_write_ops()`

```c
int nand_do_write_ops(struct nand_chip *chip, loff_t to, struct mtd_oob_ops *ops)
```

\[INTERN\] NAND write with ECC

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `loff_t to`: offset to write to
- `struct mtd_oob_ops *ops`: oob operations description structure

**Description**

NAND write with ECC.

#### <a id="c-panic_nand_write"></a>`panic_nand_write()`

```c
int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen, const uint8_t *buf)
```

\[MTD Interface\] NAND write with ECC

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t to`: offset to write to
- `size_t len`: number of bytes to write
- `size_t *retlen`: pointer to variable to store the number of written bytes
- `const uint8_t *buf`: the data to write

**Description**

NAND write with ECC. Used when performing writes in interrupt context, this
may for example be called by mtdoops when writing an oops while in panic.

#### <a id="c-nand_write_oob"></a>`nand_write_oob()`

```c
int nand_write_oob(struct mtd_info *mtd, loff_t to, struct mtd_oob_ops *ops)
```

\[MTD Interface\] NAND write data and/or out-of-band

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t to`: offset to write to
- `struct mtd_oob_ops *ops`: oob operation description structure

#### <a id="c-nand_erase"></a>`nand_erase()`

```c
int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
```

\[MTD Interface\] erase block(s)

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `struct erase_info *instr`: erase instruction

**Description**

Erase one ore more blocks.

#### <a id="c-nand_erase_nand"></a>`nand_erase_nand()`

```c
int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr, int allowbbt)
```

\[INTERN\] erase block(s)

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `struct erase_info *instr`: erase instruction
- `int allowbbt`: allow erasing the bbt area

**Description**

Erase one ore more blocks.

#### <a id="c-nand_sync"></a>`nand_sync()`

```c
void nand_sync(struct mtd_info *mtd)
```

\[MTD Interface\] sync

**Parameters**

- `struct mtd_info *mtd`: MTD device structure

**Description**

Sync is actually a wait for chip ready function.

#### <a id="c-nand_block_isbad"></a>`nand_block_isbad()`

```c
int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
```

\[MTD Interface\] Check if block at offset is bad

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t offs`: offset relative to mtd start

#### <a id="c-nand_block_markbad"></a>`nand_block_markbad()`

```c
int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
```

\[MTD Interface\] Mark block at the given offset as bad

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t ofs`: offset relative to mtd start

#### <a id="c-nand_suspend"></a>`nand_suspend()`

```c
int nand_suspend(struct mtd_info *mtd)
```

\[MTD Interface\] Suspend the NAND flash

**Parameters**

- `struct mtd_info *mtd`: MTD device structure

**Description**

Returns 0 for success or negative error code otherwise.

#### <a id="c-nand_resume"></a>`nand_resume()`

```c
void nand_resume(struct mtd_info *mtd)
```

\[MTD Interface\] Resume the NAND flash

**Parameters**

- `struct mtd_info *mtd`: MTD device structure

#### <a id="c-nand_shutdown"></a>`nand_shutdown()`

```c
void nand_shutdown(struct mtd_info *mtd)
```

\[MTD Interface\] Finish the current NAND operation and prevent further operations

**Parameters**

- `struct mtd_info *mtd`: MTD device structure

#### <a id="c-nand_lock"></a>`nand_lock()`

```c
int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
```

\[MTD Interface\] Lock the NAND flash

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t ofs`: offset byte address
- `uint64_t len`: number of bytes to lock (must be a multiple of block/page size)

#### <a id="c-nand_unlock"></a>`nand_unlock()`

```c
int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
```

\[MTD Interface\] Unlock the NAND flash

**Parameters**

- `struct mtd_info *mtd`: MTD device structure
- `loff_t ofs`: offset byte address
- `uint64_t len`: number of bytes to unlock (must be a multiple of block/page size)

#### <a id="c-nand_scan_ident"></a>`nand_scan_ident()`

```c
int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips, struct nand_flash_dev *table)
```

Scan for the NAND device

**Parameters**

- `struct nand_chip *chip`: NAND chip object
- `unsigned int maxchips`: number of chips to scan for
- `struct nand_flash_dev *table`: alternative NAND ID table

**Description**

This is the first phase of the normal `nand_scan()` function. It reads the
flash ID and sets up MTD fields accordingly.

This helper used to be called directly from controller drivers that needed
to tweak some ECC-related parameters before [`nand_scan_tail()`](#c-nand_scan_tail). This separation
prevented dynamic allocations during this phase which was unconvenient and
as been banned for the benefit of the ->`init_ecc()`/`cleanup_ecc()` hooks.

#### <a id="c-nand_check_ecc_caps"></a>`nand_check_ecc_caps()`

```c
int nand_check_ecc_caps(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)
```

check the sanity of preset ECC settings

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const struct nand_ecc_caps *caps`: ECC caps info structure
- `int oobavail`: OOB size that the ECC engine can use

**Description**

When ECC step size and strength are already set, check if they are supported
by the controller and the calculated ECC bytes fit within the chip's OOB.
On success, the calculated ECC bytes is set.

#### <a id="c-nand_match_ecc_req"></a>`nand_match_ecc_req()`

```c
int nand_match_ecc_req(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)
```

meet the chip's requirement with least ECC bytes

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const struct nand_ecc_caps *caps`: ECC engine caps info structure
- `int oobavail`: OOB size that the ECC engine can use

**Description**

If a chip's ECC requirement is provided, try to meet it with the least
number of ECC bytes (i.e. with the largest number of OOB-free bytes).
On success, the chosen ECC settings are set.

#### <a id="c-nand_maximize_ecc"></a>`nand_maximize_ecc()`

```c
int nand_maximize_ecc(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)
```

choose the max ECC strength available

**Parameters**

- `struct nand_chip *chip`: nand chip info structure
- `const struct nand_ecc_caps *caps`: ECC engine caps info structure
- `int oobavail`: OOB size that the ECC engine can use

**Description**

Choose the max ECC strength that is supported on the controller, and can fit
within the chip's OOB.  On success, the chosen ECC settings are set.

#### <a id="c-nand_scan_tail"></a>`nand_scan_tail()`

```c
int nand_scan_tail(struct nand_chip *chip)
```

Scan for the NAND device

**Parameters**

- `struct nand_chip *chip`: NAND chip object

**Description**

This is the second phase of the normal `nand_scan()` function. It fills out
all the uninitialized function pointers with the defaults and scans for a
bad block table if appropriate.



#### <a id="c-check_pattern"></a>`check_pattern()`

```c
int check_pattern(uint8_t *buf, int len, int paglen, struct nand_bbt_descr *td)
```

\[GENERIC\] check if a pattern is in the buffer

**Parameters**

- `uint8_t *buf`: the buffer to search
- `int len`: the length of buffer to search
- `int paglen`: the pagelength
- `struct nand_bbt_descr *td`: search pattern descriptor

**Description**

Check for a pattern at the given place. Used to search bad block tables and
good / bad block identifiers.

#### <a id="c-check_short_pattern"></a>`check_short_pattern()`

```c
int check_short_pattern(uint8_t *buf, struct nand_bbt_descr *td)
```

\[GENERIC\] check if a pattern is in the buffer

**Parameters**

- `uint8_t *buf`: the buffer to search
- `struct nand_bbt_descr *td`: search pattern descriptor

**Description**

Check for a pattern at the given place. Used to search bad block tables and
good / bad block identifiers. Same as check_pattern, but no optional empty
check.

#### <a id="c-add_marker_len"></a>`add_marker_len()`

```c
u32 add_marker_len(struct nand_bbt_descr *td)
```

compute the length of the marker in data area

**Parameters**

- `struct nand_bbt_descr *td`: BBT descriptor used for computation

**Description**

The length will be 0 if the marker is located in OOB area.

#### <a id="c-read_bbt"></a>`read_bbt()`

```c
int read_bbt(struct nand_chip *this, uint8_t *buf, int page, int num, struct nand_bbt_descr *td, int offs)
```

\[GENERIC\] Read the bad block table starting from page

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `int page`: the starting page
- `int num`: the number of bbt descriptors to read
- `struct nand_bbt_descr *td`: the bbt describtion table
- `int offs`: block number offset in the table

**Description**

Read the bad block table starting from page.

#### <a id="c-read_abs_bbt"></a>`read_abs_bbt()`

```c
int read_abs_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, int chip)
```

\[GENERIC\] Read the bad block table starting at a given page

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table
- `int chip`: read the table for a specific chip, -1 read all chips; applies only if
  NAND_BBT_PERCHIP option is set

**Description**

Read the bad block table for all chips starting at a given page. We assume
that the bbt bits are in consecutive order.

#### <a id="c-scan_read_oob"></a>`scan_read_oob()`

```c
int scan_read_oob(struct nand_chip *this, uint8_t *buf, loff_t offs, size_t len)
```

\[GENERIC\] Scan data+OOB region to buffer

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `loff_t offs`: offset at which to scan
- `size_t len`: length of data region to read

**Description**

Scan read data from data+OOB. May traverse multiple pages, interleaving
page,OOB,page,OOB,... in buf. Completes transfer and returns the "strongest"
ECC condition (error or bitflip). May quit on the first (non-ECC) error.

#### <a id="c-read_abs_bbts"></a>`read_abs_bbts()`

```c
void read_abs_bbts(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, struct nand_bbt_descr *md)
```

\[GENERIC\] Read the bad block table(s) for all chips starting at a given page

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table
- `struct nand_bbt_descr *md`: descriptor for the bad block table mirror

**Description**

Read the bad block table(s) for all chips starting at a given page. We
assume that the bbt bits are in consecutive order.

#### <a id="c-create_bbt"></a>`create_bbt()`

```c
int create_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *bd, int chip)
```

\[GENERIC\] Create a bad block table by scanning the device

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *bd`: descriptor for the good/bad block search pattern
- `int chip`: create the table for a specific chip, -1 read all chips; applies only
  if NAND_BBT_PERCHIP option is set

**Description**

Create a bad block table by scanning the device for the given good/bad block
identify pattern.

#### <a id="c-search_bbt"></a>`search_bbt()`

```c
int search_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td)
```

\[GENERIC\] scan the device for a specific bad block table

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table

**Description**

Read the bad block table by searching for a given ident pattern. Search is
preformed either from the beginning up or from the end of the device
downwards. The search starts always at the start of a block. If the option
NAND_BBT_PERCHIP is given, each chip is searched for a bbt, which contains
the bad block information of this chip. This is necessary to provide support
for certain DOC devices.

The bbt ident pattern resides in the oob area of the first page in a block.

#### <a id="c-search_read_bbts"></a>`search_read_bbts()`

```c
void search_read_bbts(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, struct nand_bbt_descr *md)
```

\[GENERIC\] scan the device for bad block table(s)

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table
- `struct nand_bbt_descr *md`: descriptor for the bad block table mirror

**Description**

Search and read the bad block table(s).

#### <a id="c-get_bbt_block"></a>`get_bbt_block()`

```c
int get_bbt_block(struct nand_chip *this, struct nand_bbt_descr *td, struct nand_bbt_descr *md, int chip)
```

Get the first valid eraseblock suitable to store a BBT

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *td`: the BBT description
- `struct nand_bbt_descr *md`: the mirror BBT descriptor
- `int chip`: the CHIP selector

**Description**

This functions returns a positive block number pointing a valid eraseblock
suitable to store a BBT (i.e. in the range reserved for BBT), or -ENOSPC if
all blocks are already used of marked bad. If td->pages\[chip\] was already
pointing to a valid block we re-use it, otherwise we search for the next
valid one.

#### <a id="c-mark_bbt_block_bad"></a>`mark_bbt_block_bad()`

```c
void mark_bbt_block_bad(struct nand_chip *this, struct nand_bbt_descr *td, int chip, int block)
```

Mark one of the block reserved for BBT bad

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *td`: the BBT description
- `int chip`: the CHIP selector
- `int block`: the BBT block to mark

**Description**

Blocks reserved for BBT can become bad. This functions is an helper to mark
such blocks as bad. It takes care of updating the in-memory BBT, marking the
block as bad using a bad block marker and invalidating the associated
td->pages\[\] entry.

#### <a id="c-write_bbt"></a>`write_bbt()`

```c
int write_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, struct nand_bbt_descr *md, int chipsel)
```

\[GENERIC\] (Re)write the bad block table

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *td`: descriptor for the bad block table
- `struct nand_bbt_descr *md`: descriptor for the bad block table mirror
- `int chipsel`: selector for a specific chip, -1 for all

**Description**

(Re)write the bad block table.

#### <a id="c-nand_memory_bbt"></a>`nand_memory_bbt()`

```c
int nand_memory_bbt(struct nand_chip *this, struct nand_bbt_descr *bd)
```

\[GENERIC\] create a memory based bad block table

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `struct nand_bbt_descr *bd`: descriptor for the good/bad block search pattern

**Description**

The function creates a memory based bbt by scanning the device for
manufacturer / software marked good / bad blocks.

#### <a id="c-check_create"></a>`check_create()`

```c
int check_create(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *bd)
```

\[GENERIC\] create and write bbt(s) if necessary

**Parameters**

- `struct nand_chip *this`: the NAND device
- `uint8_t *buf`: temporary buffer
- `struct nand_bbt_descr *bd`: descriptor for the good/bad block search pattern

**Description**

The function checks the results of the previous call to read_bbt and creates
/ updates the bbt(s) if necessary. Creation is necessary if no bbt was found
for the chip/device. Update is necessary if one of the tables is missing or
the version nr. of one table is less than the other.

#### <a id="c-nand_update_bbt"></a>`nand_update_bbt()`

```c
int nand_update_bbt(struct nand_chip *this, loff_t offs)
```

update bad block table(s)

**Parameters**

- `struct nand_chip *this`: the NAND device
- `loff_t offs`: the offset of the newly marked block

**Description**

The function updates the bad block table(s).

#### <a id="c-mark_bbt_region"></a>`mark_bbt_region()`

```c
void mark_bbt_region(struct nand_chip *this, struct nand_bbt_descr *td)
```

\[GENERIC\] mark the bad block table regions

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *td`: bad block table descriptor

**Description**

The bad block table regions are marked as "bad" to prevent accidental
erasures / writes. The regions are identified by the mark 0x02.

#### <a id="c-verify_bbt_descr"></a>`verify_bbt_descr()`

```c
void verify_bbt_descr(struct nand_chip *this, struct nand_bbt_descr *bd)
```

verify the bad block description

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *bd`: the table to verify

**Description**

This functions performs a few sanity checks on the bad block description
table.

#### <a id="c-nand_scan_bbt"></a>`nand_scan_bbt()`

```c
int nand_scan_bbt(struct nand_chip *this, struct nand_bbt_descr *bd)
```

\[NAND Interface\] scan, find, read and maybe create bad block table(s)

**Parameters**

- `struct nand_chip *this`: the NAND device
- `struct nand_bbt_descr *bd`: descriptor for the good/bad block search pattern

**Description**

The function checks, if a bad block table(s) is/are already available. If
not it scans the device for manufacturer marked good / bad blocks and writes
the bad block table(s) to the selected place.

The bad block table memory is allocated here. It must be freed by calling
the nand_free_bbt function.

#### <a id="c-nand_create_badblock_pattern"></a>`nand_create_badblock_pattern()`

```c
int nand_create_badblock_pattern(struct nand_chip *this)
```

\[INTERN\] Creates a BBT descriptor structure

**Parameters**

- `struct nand_chip *this`: NAND chip to create descriptor for

**Description**

This function allocates and initializes a nand_bbt_descr for BBM detection
based on the properties of **this**. The new descriptor is stored in
this->badblock_pattern. Thus, this->badblock_pattern should be NULL when
passed to this function.

#### <a id="c-nand_isreserved_bbt"></a>`nand_isreserved_bbt()`

```c
int nand_isreserved_bbt(struct nand_chip *this, loff_t offs)
```

\[NAND Interface\] Check if a block is reserved

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `loff_t offs`: offset in the device

#### <a id="c-nand_isbad_bbt"></a>`nand_isbad_bbt()`

```c
int nand_isbad_bbt(struct nand_chip *this, loff_t offs, int allowbbt)
```

\[NAND Interface\] Check if a block is bad

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `loff_t offs`: offset in the device
- `int allowbbt`: allow access to bad block table region

#### <a id="c-nand_markbad_bbt"></a>`nand_markbad_bbt()`

```c
int nand_markbad_bbt(struct nand_chip *this, loff_t offs)
```

\[NAND Interface\] Mark a block bad in the BBT

**Parameters**

- `struct nand_chip *this`: NAND chip object
- `loff_t offs`: offset of the bad block


<a id="rst-credits"></a>

## Credits

The following people have contributed to the NAND driver:

1. Steven J. Hill[sjhill@realitydiluted.com](<mailto:sjhill@realitydiluted.com>)

2. David Woodhouse[dwmw2@infradead.org](<mailto:dwmw2@infradead.org>)

3. Thomas Gleixner[tglx@kernel.org](<mailto:tglx@kernel.org>)

A lot of users have provided bugfixes, improvements and helping hands for testing. Thanks a lot.

The following people have contributed to this document:

1. Thomas Gleixner[tglx@kernel.org](<mailto:tglx@kernel.org>)

---

# Writing s390 channel device drivers

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> This document describes the interfaces available for device drivers that drive s390 based channel attached I/O devices. This includes interfaces for interaction with the hardware and interfaces for interacting with the common driver core.…

<a id="rst-writing-s390-channel-device-drivers"></a>

**Author:** Cornelia Huck

<a id="rst-introduction"></a>

## Introduction

This document describes the interfaces available for device drivers that drive s390 based channel attached I/O devices. This includes interfaces for interaction with the hardware and interfaces for interacting with the common driver core. Those interfaces are provided by the s390 common I/O layer.

The document assumes a familarity with the technical terms associated with the s390 channel I/O architecture. For a description of this architecture, please refer to the "z/Architecture: Principles of Operation", IBM publication no. SA22-7832.

While most I/O devices on a s390 system are typically driven through the channel I/O mechanism described here, there are various other methods (like the diag interface). These are out of the scope of this document.

The s390 common I/O layer also provides access to some devices that are not strictly considered I/O devices. They are considered here as well, although they are not the focus of this document.

Some additional information can also be found in the kernel source under [Documentation/arch/s390/driver-model.rst](/kernel/hardware/arch/s390/driver-model.md).

<a id="rst-the-css-bus"></a>

## The css bus

The css bus contains the subchannels available on the system. They fall into several categories:

- Standard I/O subchannels, for use by the system. They have a child device on the ccw bus and are described below.

- I/O subchannels bound to the vfio-ccw driver. See [Documentation/arch/s390/vfio-ccw.rst](/kernel/hardware/arch/s390/vfio-ccw.md).

- Message subchannels. No Linux driver currently exists.

- CHSC subchannels (at most one). The chsc subchannel driver can be used to send asynchronous chsc commands.

- eADM subchannels. Used for talking to storage class memory.

<a id="rst-the-ccw-bus"></a>

## The ccw bus

The ccw bus typically contains the majority of devices available to a s390 system. Named after the channel command word (ccw), the basic command structure used to address its devices, the ccw bus contains so-called channel attached devices. They are addressed via I/O subchannels, visible on the css bus. A device driver for channel-attached devices, however, will never interact with the subchannel directly, but only via the I/O device on the ccw bus, the ccw device.

<a id="rst-i-o-functions-for-channel-attached-devices"></a>

### I/O functions for channel-attached devices

Some hardware structures have been translated into C structures for use by the common I/O layer and device drivers. For more information on the hardware structures represented here, please consult the Principles of Operation.


#### <a id="c-struct-ccw1"></a>`struct ccw1`

channel command word

**Definition**

```c
struct ccw1 {
    __u8 cmd_code;
    __u8 flags;
    __u16 count;
    dma32_t cda;
};
```

**Members**

- `cmd_code`: command code
- `flags`: flags, like IDA addressing, etc.
- `count`: byte count
- `cda`: data address

**Description**

The ccw is the basic structure to build channel programs that perform
operations with the device or the control unit. Only Format-1 channel
command words are supported.

#### <a id="c-struct-ccw0"></a>`struct ccw0`

channel command word

**Definition**

```c
struct ccw0 {
    __u8 cmd_code;
    __u32 cda : 24;
    __u8 flags;
    __u8 reserved;
    __u16 count;
};
```

**Members**

- `cmd_code`: command code
- `cda`: data address
- `flags`: flags, like IDA addressing, etc.
- `reserved`: will be ignored
- `count`: byte count

**Description**

The format-0 ccw structure.

#### <a id="c-struct-erw"></a>`struct erw`

extended report word

**Definition**

```c
struct erw {
    __u32 res0  : 3;
    __u32 auth  : 1;
    __u32 pvrf  : 1;
    __u32 cpt   : 1;
    __u32 fsavf : 1;
    __u32 cons  : 1;
    __u32 scavf : 1;
    __u32 fsaf  : 1;
    __u32 scnt  : 6;
    __u32 res16 : 16;
};
```

**Members**

- `res0`: reserved
- `auth`: authorization check
- `pvrf`: path-verification-required flag
- `cpt`: channel-path timeout
- `fsavf`: failing storage address validity flag
- `cons`: concurrent sense
- `scavf`: secondary ccw address validity flag
- `fsaf`: failing storage address format
- `scnt`: sense count, if **cons** == `1`
- `res16`: reserved

#### <a id="c-struct-erw_eadm"></a>`struct erw_eadm`

EADM Subchannel extended report word

**Definition**

```c
struct erw_eadm {
    __u32 : 16;
    __u32 b : 1;
    __u32 r : 1;
    __u32 : 14;
};
```

**Members**

- `b`: aob error
- `r`: arsb error

#### <a id="c-struct-sublog"></a>`struct sublog`

subchannel logout area

**Definition**

```c
struct sublog {
    __u32 res0  : 1;
    __u32 esf   : 7;
    __u32 lpum  : 8;
    __u32 arep  : 1;
    __u32 fvf   : 5;
    __u32 sacc  : 2;
    __u32 termc : 2;
    __u32 devsc : 1;
    __u32 serr  : 1;
    __u32 ioerr : 1;
    __u32 seqc  : 3;
};
```

**Members**

- `res0`: reserved
- `esf`: extended status flags
- `lpum`: last path used mask
- `arep`: ancillary report
- `fvf`: field-validity flags
- `sacc`: storage access code
- `termc`: termination code
- `devsc`: device-status check
- `serr`: secondary error
- `ioerr`: i/o-error alert
- `seqc`: sequence code

#### <a id="c-struct-esw0"></a>`struct esw0`

Format 0 Extended Status Word (ESW)

**Definition**

```c
struct esw0 {
    struct sublog sublog;
    struct erw erw;
    dma32_t faddr[2];
    dma32_t saddr;
};
```

**Members**

- `sublog`: subchannel logout
- `erw`: extended report word
- `faddr`: failing storage address
- `saddr`: secondary ccw address

#### <a id="c-struct-esw1"></a>`struct esw1`

Format 1 Extended Status Word (ESW)

**Definition**

```c
struct esw1 {
    __u8 zero0;
    __u8 lpum;
    __u16 zero16;
    struct erw erw;
    __u32 zeros[3];
};
```

**Members**

- `zero0`: reserved zeros
- `lpum`: last path used mask
- `zero16`: reserved zeros
- `erw`: extended report word
- `zeros`: three fullwords of zeros

#### <a id="c-struct-esw2"></a>`struct esw2`

Format 2 Extended Status Word (ESW)

**Definition**

```c
struct esw2 {
    __u8 zero0;
    __u8 lpum;
    __u16 dcti;
    struct erw erw;
    __u32 zeros[3];
};
```

**Members**

- `zero0`: reserved zeros
- `lpum`: last path used mask
- `dcti`: device-connect-time interval
- `erw`: extended report word
- `zeros`: three fullwords of zeros

#### <a id="c-struct-esw3"></a>`struct esw3`

Format 3 Extended Status Word (ESW)

**Definition**

```c
struct esw3 {
    __u8 zero0;
    __u8 lpum;
    __u16 res;
    struct erw erw;
    __u32 zeros[3];
};
```

**Members**

- `zero0`: reserved zeros
- `lpum`: last path used mask
- `res`: reserved
- `erw`: extended report word
- `zeros`: three fullwords of zeros

#### <a id="c-struct-esw_eadm"></a>`struct esw_eadm`

EADM Subchannel Extended Status Word (ESW)

**Definition**

```c
struct esw_eadm {
    __u32 sublog;
    struct erw_eadm erw;
    __u32 : 32;
    __u32 : 32;
    __u32 : 32;
};
```

**Members**

- `sublog`: subchannel logout
- `erw`: extended report word

#### <a id="c-struct-irb"></a>`struct irb`

interruption response block

**Definition**

```c
struct irb {
    union scsw scsw;
    union {
        struct esw0 esw0;
        struct esw1 esw1;
        struct esw2 esw2;
        struct esw3 esw3;
        struct esw_eadm eadm;
    } esw;
    __u8 ecw[32];
};
```

**Members**

- `scsw`: subchannel status word
- `esw`: extended status word
- `ecw`: extended control word

**Description**

The irb that is handed to the device driver when an interrupt occurs. For
solicited interrupts, the common I/O layer already performs checks whether
a field is valid; a field not being valid is always passed as `0`.
If a unit check occurred, **ecw** may contain sense data; this is retrieved
by the common I/O layer itself if the device doesn't support concurrent
sense (so that the device driver never needs to perform basic sense itself).
For unsolicited interrupts, the irb is passed as-is (expect for sense data,
if applicable).

#### <a id="c-struct-ciw"></a>`struct ciw`

command information word (CIW) layout

**Definition**

```c
struct ciw {
    __u32 et       :  2;
    __u32 reserved :  2;
    __u32 ct       :  4;
    __u32 cmd      :  8;
    __u32 count    : 16;
};
```

**Members**

- `et`: entry type
- `reserved`: reserved bits
- `ct`: command type
- `cmd`: command code
- `count`: command count

#### <a id="c-struct-ccw_dev_id"></a>`struct ccw_dev_id`

unique identifier for ccw devices

**Definition**

```c
struct ccw_dev_id {
    u8 ssid;
    u16 devno;
};
```

**Members**

- `ssid`: subchannel set id
- `devno`: device number

**Description**

This structure is not directly based on any hardware structure. The
hardware identifies a device by its device number and its subchannel,
which is in turn identified by its id. In order to get a unique identifier
for ccw devices across subchannel sets, **struct** ccw_dev_id has been
introduced.

#### <a id="c-ccw_dev_id_is_equal"></a>`ccw_dev_id_is_equal()`

```c
int ccw_dev_id_is_equal(struct ccw_dev_id *dev_id1, struct ccw_dev_id *dev_id2)
```

compare two ccw_dev_ids

**Parameters**

- `struct ccw_dev_id *dev_id1`: a ccw_dev_id
- `struct ccw_dev_id *dev_id2`: another ccw_dev_id

**Return**

`1` if the two structures are equal field-by-field,
`0` if not.

**Context**

any

#### <a id="c-pathmask_to_pos"></a>`pathmask_to_pos()`

```c
u8 pathmask_to_pos(u8 mask)
```

find the position of the left-most bit in a pathmask

**Parameters**

- `u8 mask`: pathmask with at least one bit set


<a id="rst-ccw-devices"></a>

### ccw devices

Devices that want to initiate channel I/O need to attach to the ccw bus. Interaction with the driver core is done via the common I/O layer, which provides the abstractions of ccw devices and ccw device drivers.

The functions that initiate or terminate channel I/O all act upon a ccw device structure. Device drivers must not bypass those functions or strange side effects may happen.


#### <a id="c-struct-ccw_device"></a>`struct ccw_device`

channel attached device

**Definition**

```c
struct ccw_device {
    spinlock_t *ccwlock;
    struct ccw_device_id id;
    struct ccw_driver *drv;
    struct device dev;
    int online;
    void (*handler) (struct ccw_device *, unsigned long, struct irb *);
};
```

**Members**

- `ccwlock`: pointer to device lock
- `id`: id of this device
- `drv`: ccw driver for this device
- `dev`: embedded device structure
- `online`: online status of device
- `handler`: interrupt handler

**Description**

**handler** is a member of the device rather than the driver since a driver
can have different interrupt handlers for different ccw devices
(multi-subchannel drivers).

#### <a id="c-struct-ccw_driver"></a>`struct ccw_driver`

device driver for channel attached devices

**Definition**

```c
struct ccw_driver {
    struct ccw_device_id *ids;
    int (*probe) (struct ccw_device *);
    void (*remove) (struct ccw_device *);
    int (*set_online) (struct ccw_device *);
    int (*set_offline) (struct ccw_device *);
    int (*notify) (struct ccw_device *, int);
    void (*path_event) (struct ccw_device *, int *);
    void (*shutdown) (struct ccw_device *);
    enum uc_todo (*uc_handler) (struct ccw_device *, struct irb *);
    struct device_driver driver;
    enum interruption_class int_class;
};
```

**Members**

- `ids`: ids supported by this driver
- `probe`: function called on probe
- `remove`: function called on remove
- `set_online`: called when setting device online
- `set_offline`: called when setting device offline
- `notify`: notify driver of device state changes
- `path_event`: notify driver of channel path events
- `shutdown`: called at device shutdown
- `uc_handler`: callback for unit check handler
- `driver`: embedded device driver structure
- `int_class`: interruption class to use for accounting interrupts



#### <a id="c-ccw_device_set_offline"></a>`ccw_device_set_offline()`

```c
int ccw_device_set_offline(struct ccw_device *cdev)
```

disable a ccw device for I/O

**Parameters**

- `struct ccw_device *cdev`: target ccw device

**Description**

This function calls the driver's `set_offline()` function for **cdev**, if
given, and then disables **cdev**.

**Return**

`0` on success and a negative error value on failure.

**Context**

enabled, ccw device lock not held

#### <a id="c-ccw_device_set_online"></a>`ccw_device_set_online()`

```c
int ccw_device_set_online(struct ccw_device *cdev)
```

enable a ccw device for I/O

**Parameters**

- `struct ccw_device *cdev`: target ccw device

**Description**

This function first enables **cdev** and then calls the driver's `set_online()`
function for **cdev**, if given. If `set_online()` returns an error, **cdev** is
disabled again.

**Return**

`0` on success and a negative error value on failure.

**Context**

enabled, ccw device lock not held

#### <a id="c-get_ccwdev_by_dev_id"></a>`get_ccwdev_by_dev_id()`

```c
struct ccw_device * get_ccwdev_by_dev_id(struct ccw_dev_id *dev_id)
```

obtain device from a ccw device id

**Parameters**

- `struct ccw_dev_id *dev_id`: id of the device to be searched

**Description**

This function searches all devices attached to the ccw bus for a device
matching **dev_id**.

**Return**

If a device is found its reference count is increased and returned;
else `NULL` is returned.

#### <a id="c-get_ccwdev_by_busid"></a>`get_ccwdev_by_busid()`

```c
struct ccw_device * get_ccwdev_by_busid(struct ccw_driver *cdrv, const char *bus_id)
```

obtain device from a bus id

**Parameters**

- `struct ccw_driver *cdrv`: driver the device is owned by
- `const char *bus_id`: bus id of the device to be searched

**Description**

This function searches all devices owned by **cdrv** for a device with a bus
id matching **bus_id**.

**Return**

If a match is found, its reference count of the found device is increased
and it is returned; else `NULL` is returned.

#### <a id="c-ccw_driver_register"></a>`ccw_driver_register()`

```c
int ccw_driver_register(struct ccw_driver *cdriver)
```

register a ccw driver

**Parameters**

- `struct ccw_driver *cdriver`: driver to be registered

**Description**

This function is mainly a wrapper around [`driver_register()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-driver_register).

**Return**

`0` on success and a negative error value on failure.

#### <a id="c-ccw_driver_unregister"></a>`ccw_driver_unregister()`

```c
void ccw_driver_unregister(struct ccw_driver *cdriver)
```

deregister a ccw driver

**Parameters**

- `struct ccw_driver *cdriver`: driver to be deregistered

**Description**

This function is mainly a wrapper around [`driver_unregister()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-driver_unregister).

#### <a id="c-ccw_device_siosl"></a>`ccw_device_siosl()`

```c
int ccw_device_siosl(struct ccw_device *cdev)
```

initiate logging

**Parameters**

- `struct ccw_device *cdev`: ccw device

**Description**

This function is used to invoke model-dependent logging within the channel
subsystem.



#### <a id="c-ccw_device_set_options_mask"></a>`ccw_device_set_options_mask()`

```c
int ccw_device_set_options_mask(struct ccw_device *cdev, unsigned long flags)
```

set some options and unset the rest

**Parameters**

- `struct ccw_device *cdev`: device for which the options are to be set
- `unsigned long flags`: options to be set

**Description**

All flags specified in **flags** are set, all flags not specified in **flags**
are cleared.

**Return**

`0` on success, -`EINVAL` on an invalid flag combination.

#### <a id="c-ccw_device_set_options"></a>`ccw_device_set_options()`

```c
int ccw_device_set_options(struct ccw_device *cdev, unsigned long flags)
```

set some options

**Parameters**

- `struct ccw_device *cdev`: device for which the options are to be set
- `unsigned long flags`: options to be set

**Description**

All flags specified in **flags** are set, the remainder is left untouched.

**Return**

`0` on success, -`EINVAL` if an invalid flag combination would ensue.

#### <a id="c-ccw_device_clear_options"></a>`ccw_device_clear_options()`

```c
void ccw_device_clear_options(struct ccw_device *cdev, unsigned long flags)
```

clear some options

**Parameters**

- `struct ccw_device *cdev`: device for which the options are to be cleared
- `unsigned long flags`: options to be cleared

**Description**

All flags specified in **flags** are cleared, the remainder is left untouched.

#### <a id="c-ccw_device_is_pathgroup"></a>`ccw_device_is_pathgroup()`

```c
int ccw_device_is_pathgroup(struct ccw_device *cdev)
```

determine if paths to this device are grouped

**Parameters**

- `struct ccw_device *cdev`: ccw device

**Description**

Return non-zero if there is a path group, zero otherwise.

#### <a id="c-ccw_device_is_multipath"></a>`ccw_device_is_multipath()`

```c
int ccw_device_is_multipath(struct ccw_device *cdev)
```

determine if device is operating in multipath mode

**Parameters**

- `struct ccw_device *cdev`: ccw device

**Description**

Return non-zero if device is operating in multipath mode, zero otherwise.

#### <a id="c-ccw_device_clear"></a>`ccw_device_clear()`

```c
int ccw_device_clear(struct ccw_device *cdev, unsigned long intparm)
```

terminate I/O request processing

**Parameters**

- `struct ccw_device *cdev`: target ccw device
- `unsigned long intparm`: interruption parameter to be returned upon conclusion of csch

**Description**

[`ccw_device_clear()`](#c-ccw_device_clear) calls csch on **cdev**'s subchannel.

**Return**

`0` on success,
-`ENODEV` on device not operational,
-`EINVAL` on invalid device state.

**Context**

Interrupts disabled, ccw device lock held

#### <a id="c-ccw_device_start_timeout_key"></a>`ccw_device_start_timeout_key()`

```c
int ccw_device_start_timeout_key(struct ccw_device *cdev, struct ccw1 *cpa, unsigned long intparm, __u8 lpm, __u8 key, unsigned long flags, int expires)
```

start a s390 channel program with timeout and key

**Parameters**

- `struct ccw_device *cdev`: target ccw device
- `struct ccw1 *cpa`: logical start address of channel program
- `unsigned long intparm`: user specific interruption parameter; will be presented back to
  **cdev**'s interrupt handler. Allows a device driver to associate
  the interrupt with a particular I/O request.
- `__u8 lpm`: defines the channel path to be used for a specific I/O request. A
  value of 0 will make cio use the opm.
- `__u8 key`: storage key to be used for the I/O
- `unsigned long flags`: additional flags; defines the action to be performed for I/O
  processing.
- `int expires`: timeout value in jiffies

**Description**

Start a S/390 channel program. When the interrupt arrives, the
IRQ handler is called, either immediately, delayed (dev-end missing,
or sense required) or never (no IRQ handler registered).
This function notifies the device driver if the channel program has not
completed during the time specified by **expires**. If a timeout occurs, the
channel program is terminated via xsch, hsch or csch, and the device's
interrupt handler will be called with an irb containing ERR_PTR(-`ETIMEDOUT`).
The interruption handler will echo back the **intparm** specified here, unless
another interruption parameter is specified by a subsequent invocation of
[`ccw_device_halt()`](#c-ccw_device_halt) or [`ccw_device_clear()`](#c-ccw_device_clear).

**Return**

`0`, if the operation was successful;
-`EBUSY`, if the device is busy, or status pending;
-`EACCES`, if no path specified in **lpm** is operational;
-`ENODEV`, if the device is not operational.

**Context**

Interrupts disabled, ccw device lock held

#### <a id="c-ccw_device_start_key"></a>`ccw_device_start_key()`

```c
int ccw_device_start_key(struct ccw_device *cdev, struct ccw1 *cpa, unsigned long intparm, __u8 lpm, __u8 key, unsigned long flags)
```

start a s390 channel program with key

**Parameters**

- `struct ccw_device *cdev`: target ccw device
- `struct ccw1 *cpa`: logical start address of channel program
- `unsigned long intparm`: user specific interruption parameter; will be presented back to
  **cdev**'s interrupt handler. Allows a device driver to associate
  the interrupt with a particular I/O request.
- `__u8 lpm`: defines the channel path to be used for a specific I/O request. A
  value of 0 will make cio use the opm.
- `__u8 key`: storage key to be used for the I/O
- `unsigned long flags`: additional flags; defines the action to be performed for I/O
  processing.

**Description**

Start a S/390 channel program. When the interrupt arrives, the
IRQ handler is called, either immediately, delayed (dev-end missing,
or sense required) or never (no IRQ handler registered).
The interruption handler will echo back the **intparm** specified here, unless
another interruption parameter is specified by a subsequent invocation of
[`ccw_device_halt()`](#c-ccw_device_halt) or [`ccw_device_clear()`](#c-ccw_device_clear).

**Return**

`0`, if the operation was successful;
-`EBUSY`, if the device is busy, or status pending;
-`EACCES`, if no path specified in **lpm** is operational;
-`ENODEV`, if the device is not operational.

**Context**

Interrupts disabled, ccw device lock held

#### <a id="c-ccw_device_start"></a>`ccw_device_start()`

```c
int ccw_device_start(struct ccw_device *cdev, struct ccw1 *cpa, unsigned long intparm, __u8 lpm, unsigned long flags)
```

start a s390 channel program

**Parameters**

- `struct ccw_device *cdev`: target ccw device
- `struct ccw1 *cpa`: logical start address of channel program
- `unsigned long intparm`: user specific interruption parameter; will be presented back to
  **cdev**'s interrupt handler. Allows a device driver to associate
  the interrupt with a particular I/O request.
- `__u8 lpm`: defines the channel path to be used for a specific I/O request. A
  value of 0 will make cio use the opm.
- `unsigned long flags`: additional flags; defines the action to be performed for I/O
  processing.

**Description**

Start a S/390 channel program. When the interrupt arrives, the
IRQ handler is called, either immediately, delayed (dev-end missing,
or sense required) or never (no IRQ handler registered).
The interruption handler will echo back the **intparm** specified here, unless
another interruption parameter is specified by a subsequent invocation of
[`ccw_device_halt()`](#c-ccw_device_halt) or [`ccw_device_clear()`](#c-ccw_device_clear).

**Return**

`0`, if the operation was successful;
-`EBUSY`, if the device is busy, or status pending;
-`EACCES`, if no path specified in **lpm** is operational;
-`ENODEV`, if the device is not operational.

**Context**

Interrupts disabled, ccw device lock held

#### <a id="c-ccw_device_start_timeout"></a>`ccw_device_start_timeout()`

```c
int ccw_device_start_timeout(struct ccw_device *cdev, struct ccw1 *cpa, unsigned long intparm, __u8 lpm, unsigned long flags, int expires)
```

start a s390 channel program with timeout

**Parameters**

- `struct ccw_device *cdev`: target ccw device
- `struct ccw1 *cpa`: logical start address of channel program
- `unsigned long intparm`: user specific interruption parameter; will be presented back to
  **cdev**'s interrupt handler. Allows a device driver to associate
  the interrupt with a particular I/O request.
- `__u8 lpm`: defines the channel path to be used for a specific I/O request. A
  value of 0 will make cio use the opm.
- `unsigned long flags`: additional flags; defines the action to be performed for I/O
  processing.
- `int expires`: timeout value in jiffies

**Description**

Start a S/390 channel program. When the interrupt arrives, the
IRQ handler is called, either immediately, delayed (dev-end missing,
or sense required) or never (no IRQ handler registered).
This function notifies the device driver if the channel program has not
completed during the time specified by **expires**. If a timeout occurs, the
channel program is terminated via xsch, hsch or csch, and the device's
interrupt handler will be called with an irb containing ERR_PTR(-`ETIMEDOUT`).
The interruption handler will echo back the **intparm** specified here, unless
another interruption parameter is specified by a subsequent invocation of
[`ccw_device_halt()`](#c-ccw_device_halt) or [`ccw_device_clear()`](#c-ccw_device_clear).

**Return**

`0`, if the operation was successful;
-`EBUSY`, if the device is busy, or status pending;
-`EACCES`, if no path specified in **lpm** is operational;
-`ENODEV`, if the device is not operational.

**Context**

Interrupts disabled, ccw device lock held

#### <a id="c-ccw_device_halt"></a>`ccw_device_halt()`

```c
int ccw_device_halt(struct ccw_device *cdev, unsigned long intparm)
```

halt I/O request processing

**Parameters**

- `struct ccw_device *cdev`: target ccw device
- `unsigned long intparm`: interruption parameter to be returned upon conclusion of hsch

**Description**

[`ccw_device_halt()`](#c-ccw_device_halt) calls hsch on **cdev**'s subchannel.
The interruption handler will echo back the **intparm** specified here, unless
another interruption parameter is specified by a subsequent invocation of
[`ccw_device_clear()`](#c-ccw_device_clear).

**Return**

`0` on success,
-`ENODEV` on device not operational,
-`EINVAL` on invalid device state,
-`EBUSY` on device busy or interrupt pending.

**Context**

Interrupts disabled, ccw device lock held

#### <a id="c-ccw_device_resume"></a>`ccw_device_resume()`

```c
int ccw_device_resume(struct ccw_device *cdev)
```

resume channel program execution

**Parameters**

- `struct ccw_device *cdev`: target ccw device

**Description**

[`ccw_device_resume()`](#c-ccw_device_resume) calls rsch on **cdev**'s subchannel.

**Return**

`0` on success,
-`ENODEV` on device not operational,
-`EINVAL` on invalid device state,
-`EBUSY` on device busy or interrupt pending.

**Context**

Interrupts disabled, ccw device lock held

#### <a id="c-ccw_device_get_ciw"></a>`ccw_device_get_ciw()`

```c
struct ciw * ccw_device_get_ciw(struct ccw_device *cdev, __u32 ct)
```

Search for CIW command in extended sense data.

**Parameters**

- `struct ccw_device *cdev`: ccw device to inspect
- `__u32 ct`: command type to look for

**Description**

During SenseID, command information words (CIWs) describing special
commands available to the device may have been stored in the extended
sense data. This function searches for CIWs of a specified command
type in the extended sense data.

**Return**

`NULL` if no extended sense data has been stored or if no CIW of the
specified command type could be found,
else a pointer to the CIW of the specified command type.

#### <a id="c-ccw_device_get_path_mask"></a>`ccw_device_get_path_mask()`

```c
__u8 ccw_device_get_path_mask(struct ccw_device *cdev)
```

get currently available paths

**Parameters**

- `struct ccw_device *cdev`: ccw device to be queried

**Return**

`0` if no subchannel for the device is available,
else the mask of currently available paths for the ccw device's subchannel.

#### <a id="c-ccw_device_get_chp_desc"></a>`ccw_device_get_chp_desc()`

```c
struct channel_path_desc_fmt0 * ccw_device_get_chp_desc(struct ccw_device *cdev, int chp_idx)
```

return newly allocated channel-path descriptor

**Parameters**

- `struct ccw_device *cdev`: device to obtain the descriptor for
- `int chp_idx`: index of the channel path

**Description**

On success return a newly allocated copy of the channel-path description
data associated with the given channel path. Return `NULL` on error.

#### <a id="c-ccw_device_get_util_str"></a>`ccw_device_get_util_str()`

```c
u8 * ccw_device_get_util_str(struct ccw_device *cdev, int chp_idx)
```

return newly allocated utility strings

**Parameters**

- `struct ccw_device *cdev`: device to obtain the utility strings for
- `int chp_idx`: index of the channel path

**Description**

On success return a newly allocated copy of the utility strings
associated with the given channel path. Return `NULL` on error.

#### <a id="c-ccw_device_get_id"></a>`ccw_device_get_id()`

```c
void ccw_device_get_id(struct ccw_device *cdev, struct ccw_dev_id *dev_id)
```

obtain a ccw device id

**Parameters**

- `struct ccw_device *cdev`: device to obtain the id for
- `struct ccw_dev_id *dev_id`: where to fill in the values

#### <a id="c-ccw_device_tm_start_timeout_key"></a>`ccw_device_tm_start_timeout_key()`

```c
int ccw_device_tm_start_timeout_key(struct ccw_device *cdev, struct tcw *tcw, unsigned long intparm, u8 lpm, u8 key, int expires)
```

perform start function

**Parameters**

- `struct ccw_device *cdev`: ccw device on which to perform the start function
- `struct tcw *tcw`: transport-command word to be started
- `unsigned long intparm`: user defined parameter to be passed to the interrupt handler
- `u8 lpm`: mask of paths to use
- `u8 key`: storage key to use for storage access
- `int expires`: time span in jiffies after which to abort request

**Description**

Start the tcw on the given ccw device. Return zero on success, non-zero
otherwise.

#### <a id="c-ccw_device_tm_start_key"></a>`ccw_device_tm_start_key()`

```c
int ccw_device_tm_start_key(struct ccw_device *cdev, struct tcw *tcw, unsigned long intparm, u8 lpm, u8 key)
```

perform start function

**Parameters**

- `struct ccw_device *cdev`: ccw device on which to perform the start function
- `struct tcw *tcw`: transport-command word to be started
- `unsigned long intparm`: user defined parameter to be passed to the interrupt handler
- `u8 lpm`: mask of paths to use
- `u8 key`: storage key to use for storage access

**Description**

Start the tcw on the given ccw device. Return zero on success, non-zero
otherwise.

#### <a id="c-ccw_device_tm_start"></a>`ccw_device_tm_start()`

```c
int ccw_device_tm_start(struct ccw_device *cdev, struct tcw *tcw, unsigned long intparm, u8 lpm)
```

perform start function

**Parameters**

- `struct ccw_device *cdev`: ccw device on which to perform the start function
- `struct tcw *tcw`: transport-command word to be started
- `unsigned long intparm`: user defined parameter to be passed to the interrupt handler
- `u8 lpm`: mask of paths to use

**Description**

Start the tcw on the given ccw device. Return zero on success, non-zero
otherwise.

#### <a id="c-ccw_device_tm_start_timeout"></a>`ccw_device_tm_start_timeout()`

```c
int ccw_device_tm_start_timeout(struct ccw_device *cdev, struct tcw *tcw, unsigned long intparm, u8 lpm, int expires)
```

perform start function

**Parameters**

- `struct ccw_device *cdev`: ccw device on which to perform the start function
- `struct tcw *tcw`: transport-command word to be started
- `unsigned long intparm`: user defined parameter to be passed to the interrupt handler
- `u8 lpm`: mask of paths to use
- `int expires`: time span in jiffies after which to abort request

**Description**

Start the tcw on the given ccw device. Return zero on success, non-zero
otherwise.

#### <a id="c-ccw_device_get_mdc"></a>`ccw_device_get_mdc()`

```c
int ccw_device_get_mdc(struct ccw_device *cdev, u8 mask)
```

accumulate max data count

**Parameters**

- `struct ccw_device *cdev`: ccw device for which the max data count is accumulated
- `u8 mask`: mask of paths to use

**Description**

Return the number of 64K-bytes blocks all paths at least support
for a transport command. Return value 0 indicates failure.

#### <a id="c-ccw_device_tm_intrg"></a>`ccw_device_tm_intrg()`

```c
int ccw_device_tm_intrg(struct ccw_device *cdev)
```

perform interrogate function

**Parameters**

- `struct ccw_device *cdev`: ccw device on which to perform the interrogate function

**Description**

Perform an interrogate function on the given ccw device. Return zero on
success, non-zero otherwise.

#### <a id="c-ccw_device_get_schid"></a>`ccw_device_get_schid()`

```c
void ccw_device_get_schid(struct ccw_device *cdev, struct subchannel_id *schid)
```

obtain a subchannel id

**Parameters**

- `struct ccw_device *cdev`: device to obtain the id for
- `struct subchannel_id *schid`: where to fill in the values

#### <a id="c-ccw_device_pnso"></a>`ccw_device_pnso()`

```c
int ccw_device_pnso(struct ccw_device *cdev, struct chsc_pnso_area *pnso_area, u8 oc, struct chsc_pnso_resume_token resume_token, int cnc)
```

Perform Network-Subchannel Operation

**Parameters**

- `struct ccw_device *cdev`: device on which PNSO is performed
- `struct chsc_pnso_area *pnso_area`: request and response block for the operation
- `u8 oc`: Operation Code
- `struct chsc_pnso_resume_token resume_token`: resume token for multiblock response
- `int cnc`: Boolean change-notification control

**Description**

pnso_area must be allocated by the caller with get_zeroed_page(GFP_KERNEL)

Returns 0 on success.

#### <a id="c-ccw_device_get_cssid"></a>`ccw_device_get_cssid()`

```c
int ccw_device_get_cssid(struct ccw_device *cdev, u8 *cssid)
```

obtain Channel Subsystem ID

**Parameters**

- `struct ccw_device *cdev`: device to obtain the CSSID for
- `u8 *cssid`: The resulting Channel Subsystem ID

#### <a id="c-ccw_device_get_iid"></a>`ccw_device_get_iid()`

```c
int ccw_device_get_iid(struct ccw_device *cdev, u8 *iid)
```

obtain MIF-image ID

**Parameters**

- `struct ccw_device *cdev`: device to obtain the MIF-image ID for
- `u8 *iid`: The resulting MIF-image ID

#### <a id="c-ccw_device_get_chpid"></a>`ccw_device_get_chpid()`

```c
int ccw_device_get_chpid(struct ccw_device *cdev, int chp_idx, u8 *chpid)
```

obtain Channel Path ID

**Parameters**

- `struct ccw_device *cdev`: device to obtain the Channel Path ID for
- `int chp_idx`: Index of the channel path
- `u8 *chpid`: The resulting Channel Path ID

#### <a id="c-ccw_device_get_chid"></a>`ccw_device_get_chid()`

```c
int ccw_device_get_chid(struct ccw_device *cdev, int chp_idx, u16 *chid)
```

obtain Channel ID associated with specified CHPID

**Parameters**

- `struct ccw_device *cdev`: device to obtain the Channel ID for
- `int chp_idx`: Index of the channel path
- `u16 *chid`: The resulting Channel ID


<a id="rst-the-channel-measurement-facility"></a>

### The channel-measurement facility

The channel-measurement facility provides a means to collect measurement data which is made available by the channel subsystem for each channel attached device.


#### <a id="c-struct-cmbdata"></a>`struct cmbdata`

channel measurement block data for user space

**Definition**

```c
struct cmbdata {
    __u64 size;
    __u64 elapsed_time;
    __u64 ssch_rsch_count;
    __u64 sample_count;
    __u64 device_connect_time;
    __u64 function_pending_time;
    __u64 device_disconnect_time;
    __u64 control_unit_queuing_time;
    __u64 device_active_only_time;
    __u64 device_busy_time;
    __u64 initial_command_response_time;
};
```

**Members**

- `size`: size of the stored data
- `elapsed_time`: time since last sampling
- `ssch_rsch_count`: number of ssch and rsch
- `sample_count`: number of samples
- `device_connect_time`: time of device connect
- `function_pending_time`: time of function pending
- `device_disconnect_time`: time of device disconnect
- `control_unit_queuing_time`: time of control unit queuing
- `device_active_only_time`: time of device active only
- `device_busy_time`: time of device busy (ext. format)
- `initial_command_response_time`: initial command response time (ext. format)

**Description**

All values are stored as 64 bit for simplicity, especially
in 32 bit emulation mode. All time values are normalized to
nanoseconds.
Currently, two formats are known, which differ by the size of
this structure, i.e. the last two members are only set when
the extended channel measurement facility (first shipped in
z990 machines) is activated.
Potentially, more fields could be added, which would result in a
new ioctl number.



#### <a id="c-enable_cmf"></a>`enable_cmf()`

```c
int enable_cmf(struct ccw_device *cdev)
```

switch on the channel measurement for a specific device

**Parameters**

- `struct ccw_device *cdev`: The ccw device to be enabled

**Description**

Enable channel measurements for **cdev**. If this is called on a device
for which channel measurement is already enabled a reset of the
measurement data is triggered.

**Return**

`0` for success or a negative error value.

**Context**

non-atomic

#### <a id="c-disable_cmf"></a>`disable_cmf()`

```c
int disable_cmf(struct ccw_device *cdev)
```

switch off the channel measurement for a specific device

**Parameters**

- `struct ccw_device *cdev`: The ccw device to be disabled

**Return**

`0` for success or a negative error value.

**Context**

non-atomic

#### <a id="c-cmf_read"></a>`cmf_read()`

```c
u64 cmf_read(struct ccw_device *cdev, int index)
```

read one value from the current channel measurement block

**Parameters**

- `struct ccw_device *cdev`: the channel to be read
- `int index`: the index of the value to be read

**Return**

The value read or `0` if the value cannot be read.

**Context**

any

#### <a id="c-cmf_readall"></a>`cmf_readall()`

```c
int cmf_readall(struct ccw_device *cdev, struct cmbdata *data)
```

read the current channel measurement block

**Parameters**

- `struct ccw_device *cdev`: the channel to be read
- `struct cmbdata *data`: a pointer to a data block that will be filled

**Return**

`0` on success, a negative error value otherwise.

**Context**

any


<a id="rst-the-ccwgroup-bus"></a>

## The ccwgroup bus

The ccwgroup bus only contains artificial devices, created by the user. Many networking devices (e.g. qeth) are in fact composed of several ccw devices (like read, write and data channel for qeth). The ccwgroup bus provides a mechanism to create a meta-device which contains those ccw devices as slave devices and can be associated with the netdevice.

<a id="rst-ccw-group-devices"></a>

### ccw group devices


#### <a id="c-struct-ccwgroup_device"></a>`struct ccwgroup_device`

ccw group device

**Definition**

```c
struct ccwgroup_device {
    enum {
        CCWGROUP_OFFLINE,
        CCWGROUP_ONLINE,
    } state;
    unsigned int count;
    struct device   dev;
    struct work_struct ungroup_work;
    struct ccw_device *cdev[];
};
```

**Members**

- `state`: online/offline state
- `count`: number of attached slave devices
- `dev`: embedded device structure
- `ungroup_work`: used to ungroup the ccwgroup device
- `cdev`: variable number of slave devices, allocated as needed

#### <a id="c-struct-ccwgroup_driver"></a>`struct ccwgroup_driver`

driver for ccw group devices

**Definition**

```c
struct ccwgroup_driver {
    int (*setup) (struct ccwgroup_device *);
    void (*remove) (struct ccwgroup_device *);
    int (*set_online) (struct ccwgroup_device *);
    int (*set_offline) (struct ccwgroup_device *);
    void (*shutdown)(struct ccwgroup_device *);
    struct device_driver driver;
    struct ccw_driver *ccw_driver;
};
```

**Members**

- `setup`: function called during device creation to setup the device
- `remove`: function called on remove
- `set_online`: function called when device is set online
- `set_offline`: function called when device is set offline
- `shutdown`: function called when device is shut down
- `driver`: embedded driver structure
- `ccw_driver`: supported ccw_driver (optional)



#### <a id="c-ccwgroup_set_online"></a>`ccwgroup_set_online()`

```c
int ccwgroup_set_online(struct ccwgroup_device *gdev)
```

enable a ccwgroup device

**Parameters**

- `struct ccwgroup_device *gdev`: target ccwgroup device

**Description**

This function attempts to put the ccwgroup device into the online state.

**Return**

`0` on success and a negative error value on failure.

#### <a id="c-ccwgroup_set_offline"></a>`ccwgroup_set_offline()`

```c
int ccwgroup_set_offline(struct ccwgroup_device *gdev, bool call_gdrv)
```

disable a ccwgroup device

**Parameters**

- `struct ccwgroup_device *gdev`: target ccwgroup device
- `bool call_gdrv`: Call the registered gdrv set_offline function

**Description**

This function attempts to put the ccwgroup device into the offline state.

**Return**

`0` on success and a negative error value on failure.

#### <a id="c-ccwgroup_create_dev"></a>`ccwgroup_create_dev()`

```c
int ccwgroup_create_dev(struct device *parent, struct ccwgroup_driver *gdrv, int num_devices, const char *buf)
```

create and register a ccw group device

**Parameters**

- `struct device *parent`: parent device for the new device
- `struct ccwgroup_driver *gdrv`: driver for the new group device
- `int num_devices`: number of slave devices
- `const char *buf`: buffer containing comma separated bus ids of slave devices

**Description**

Create and register a new ccw group device as a child of **parent**. Slave
devices are obtained from the list of bus ids given in **buf**.

**Return**

`0` on success and an error code on failure.

**Context**

non-atomic

#### <a id="c-ccwgroup_driver_register"></a>`ccwgroup_driver_register()`

```c
int ccwgroup_driver_register(struct ccwgroup_driver *cdriver)
```

register a ccw group driver

**Parameters**

- `struct ccwgroup_driver *cdriver`: driver to be registered

**Description**

This function is mainly a wrapper around [`driver_register()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-driver_register).

#### <a id="c-ccwgroup_driver_unregister"></a>`ccwgroup_driver_unregister()`

```c
void ccwgroup_driver_unregister(struct ccwgroup_driver *cdriver)
```

deregister a ccw group driver

**Parameters**

- `struct ccwgroup_driver *cdriver`: driver to be deregistered

**Description**

This function is mainly a wrapper around [`driver_unregister()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-driver_unregister).

#### <a id="c-ccwgroup_probe_ccwdev"></a>`ccwgroup_probe_ccwdev()`

```c
int ccwgroup_probe_ccwdev(struct ccw_device *cdev)
```

probe function for slave devices

**Parameters**

- `struct ccw_device *cdev`: ccw device to be probed

**Description**

This is a dummy probe function for ccw devices that are slave devices in
a ccw group device.

**Return**

always `0`

#### <a id="c-ccwgroup_remove_ccwdev"></a>`ccwgroup_remove_ccwdev()`

```c
void ccwgroup_remove_ccwdev(struct ccw_device *cdev)
```

remove function for slave devices

**Parameters**

- `struct ccw_device *cdev`: ccw device to be removed

**Description**

This is a remove function for ccw devices that are slave devices in a ccw
group device. It sets the ccw device offline and also deregisters the
embedding ccw group device.


<a id="rst-generic-interfaces"></a>

## Generic interfaces

The following section contains interfaces in use not only by drivers dealing with ccw devices, but drivers for various other s390 hardware as well.

<a id="rst-adapter-interrupts"></a>

### Adapter interrupts

The common I/O layer provides helper functions for dealing with adapter interrupts and interrupt vectors.


#### <a id="c-register_adapter_interrupt"></a>`register_adapter_interrupt()`

```c
int register_adapter_interrupt(struct airq_struct *airq)
```

register adapter interrupt handler

**Parameters**

- `struct airq_struct *airq`: pointer to adapter interrupt descriptor

**Description**

Returns 0 on success, or -EINVAL.

#### <a id="c-unregister_adapter_interrupt"></a>`unregister_adapter_interrupt()`

```c
void unregister_adapter_interrupt(struct airq_struct *airq)
```

unregister adapter interrupt handler

**Parameters**

- `struct airq_struct *airq`: pointer to adapter interrupt descriptor

#### <a id="c-airq_iv_create"></a>`airq_iv_create()`

```c
struct airq_iv * airq_iv_create(unsigned long bits, unsigned long flags, unsigned long *vec)
```

create an interrupt vector

**Parameters**

- `unsigned long bits`: number of bits in the interrupt vector
- `unsigned long flags`: allocation flags
- `unsigned long *vec`: pointer to pinned guest memory if AIRQ_IV_GUESTVEC

**Description**

Returns a pointer to an interrupt vector structure

#### <a id="c-airq_iv_release"></a>`airq_iv_release()`

```c
void airq_iv_release(struct airq_iv *iv)
```

release an interrupt vector

**Parameters**

- `struct airq_iv *iv`: pointer to interrupt vector structure

#### <a id="c-airq_iv_alloc"></a>`airq_iv_alloc()`

```c
unsigned long airq_iv_alloc(struct airq_iv *iv, unsigned long num)
```

allocate irq bits from an interrupt vector

**Parameters**

- `struct airq_iv *iv`: pointer to an interrupt vector structure
- `unsigned long num`: number of consecutive irq bits to allocate

**Description**

Returns the bit number of the first irq in the allocated block of irqs,
or -1UL if no bit is available or the AIRQ_IV_ALLOC flag has not been
specified

#### <a id="c-airq_iv_free"></a>`airq_iv_free()`

```c
void airq_iv_free(struct airq_iv *iv, unsigned long bit, unsigned long num)
```

free irq bits of an interrupt vector

**Parameters**

- `struct airq_iv *iv`: pointer to interrupt vector structure
- `unsigned long bit`: number of the first irq bit to free
- `unsigned long num`: number of consecutive irq bits to free

#### <a id="c-airq_iv_scan"></a>`airq_iv_scan()`

```c
unsigned long airq_iv_scan(struct airq_iv *iv, unsigned long start, unsigned long end)
```

scan interrupt vector for non-zero bits

**Parameters**

- `struct airq_iv *iv`: pointer to interrupt vector structure
- `unsigned long start`: bit number to start the search
- `unsigned long end`: bit number to end the search

**Description**

Returns the bit number of the next non-zero interrupt bit, or
-1UL if the scan completed without finding any more any non-zero bits.

---

# SM501 Driver

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> The Silicon Motion SM501 multimedia companion chip is a multifunction device which may provide numerous interfaces including USB host controller USB gadget, asynchronous serial ports, audio functions, and a dual display video interface.…

<a id="rst-sm501-driver"></a>

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2006, 2007 Simtec Electronics

The Silicon Motion SM501 multimedia companion chip is a multifunction device which may provide numerous interfaces including USB host controller USB gadget, asynchronous serial ports, audio functions, and a dual display video interface. The device may be connected by PCI or local bus with varying functions enabled.

<a id="rst-core"></a>

## Core

The core driver in drivers/mfd provides common services for the drivers which manage the specific hardware blocks. These services include locking for common registers, clock control and resource management.

The core registers drivers for both PCI and generic bus based chips via the platform device and driver system.

On detection of a device, the core initialises the chip (which may be specified by the platform data) and then exports the selected peripheral set as platform devices for the specific drivers.

The core re-uses the platform device system as the platform device system provides enough features to support the drivers without the need to create a new bus-type and the associated code to go with it.

<a id="rst-resources"></a>

## Resources

Each peripheral has a view of the device which is implicitly narrowed to the specific set of resources that peripheral requires in order to function correctly.

The centralised memory allocation allows the driver to ensure that the maximum possible resource allocation can be made to the video subsystem as this is by-far the most resource-sensitive of the on-chip functions.

The primary issue with memory allocation is that of moving the video buffers once a display mode is chosen. Indeed when a video mode change occurs the memory footprint of the video subsystem changes.

Since video memory is difficult to move without changing the display (unless sufficient contiguous memory can be provided for the old and new modes simultaneously) the video driver fully utilises the memory area given to it by aligning fb0 to the start of the area and fb1 to the end of it. Any memory left over in the middle is used for the acceleration functions, which are transient and thus their location is less critical as it can be moved.

<a id="rst-configuration"></a>

## Configuration

The platform device driver uses a set of platform data to pass configurations through to the core and the subsidiary drivers so that there can be support for more than one system carrying an SM501 built into a single kernel image.

The PCI driver assumes that the PCI card behaves as per the Silicon Motion reference design.

There is an errata (AB-5) affecting the selection of the of the M1XCLK and M1CLK frequencies. These two clocks must be sourced from the same PLL, although they can then be divided down individually. If this is not set, then SM501 may lock and hang the whole system. The driver will refuse to attach if the PLL selection is different.

---

# The Userspace I/O HOWTO

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> If you know of any translations for this document, or you are interested in translating it, please email me hjk@hansjkoch.de.

<a id="rst-the-userspace-i-o-howto"></a>

**Author:** Hans-Jürgen Koch Linux developer, Linutronix

**Date:** 2006-12-11

<a id="rst-about-this-document"></a>

## About this document

<a id="rst-translations"></a>

### Translations

If you know of any translations for this document, or you are interested in translating it, please email me [hjk@hansjkoch.de](<mailto:hjk@hansjkoch.de>).

<a id="rst-preface"></a>

### Preface

For many types of devices, creating a Linux kernel driver is overkill. All that is really needed is some way to handle an interrupt and provide access to the memory space of the device. The logic of controlling the device does not necessarily have to be within the kernel, as the device does not need to take advantage of any of other resources that the kernel provides. One such common class of devices that are like this are for industrial I/O cards.

To address this situation, the userspace I/O system (UIO) was designed. For typical industrial I/O cards, only a very small kernel module is needed. The main part of the driver will run in user space. This simplifies development and reduces the risk of serious bugs within a kernel module.

Please note that UIO is not an universal driver interface. Devices that are already handled well by other kernel subsystems (like networking or serial or USB) are no candidates for an UIO driver. Hardware that is ideally suited for an UIO driver fulfills all of the following:

- The device has memory that can be mapped. The device can be controlled completely by writing to this memory.

- The device usually generates interrupts.

- The device does not fit into one of the standard kernel subsystems.

<a id="rst-acknowledgments"></a>

### Acknowledgments

I'd like to thank Thomas Gleixner and Benedikt Spranger of Linutronix, who have not only written most of the UIO code, but also helped greatly writing this HOWTO by giving me all kinds of background information.

<a id="rst-feedback"></a>

### Feedback

Find something wrong with this document? (Or perhaps something right?) I would love to hear from you. Please email me at [hjk@hansjkoch.de](<mailto:hjk@hansjkoch.de>).

<a id="rst-about-uio"></a>

## About UIO

If you use UIO for your card's driver, here's what you get:

- only one small kernel module to write and maintain.

- develop the main part of your driver in user space, with all the tools and libraries you're used to.

- bugs in your driver won't crash the kernel.

- updates of your driver can take place without recompiling the kernel.

<a id="rst-how-uio-works"></a>

### How UIO works

Each UIO device is accessed through a device file and several sysfs attribute files. The device file will be called `/dev/uio0` for the first device, and `/dev/uio1`, `/dev/uio2` and so on for subsequent devices.

`/dev/uioX` is used to access the address space of the card. Just use `mmap()` to access registers or RAM locations of your card.

Interrupts are handled by reading from `/dev/uioX`. A blocking `read()` from `/dev/uioX` will return as soon as an interrupt occurs. You can also use `select()` on `/dev/uioX` to wait for an interrupt. The integer value read from `/dev/uioX` represents the total interrupt count. You can use this number to figure out if you missed some interrupts.

For some hardware that has more than one interrupt source internally, but not separate IRQ mask and status registers, there might be situations where userspace cannot determine what the interrupt source was if the kernel handler disables them by writing to the chip's IRQ register. In such a case, the kernel has to disable the IRQ completely to leave the chip's register untouched. Now the userspace part can determine the cause of the interrupt, but it cannot re-enable interrupts. Another cornercase is chips where re-enabling interrupts is a read-modify-write operation to a combined IRQ status/acknowledge register. This would be racy if a new interrupt occurred simultaneously.

To address these problems, UIO also implements a write() function. It is normally not used and can be ignored for hardware that has only a single interrupt source or has separate IRQ mask and status registers. If you need it, however, a write to `/dev/uioX` will call the `irqcontrol()` function implemented by the driver. You have to write a 32-bit value that is usually either 0 or 1 to disable or enable interrupts. If a driver does not implement `irqcontrol()`, `write()` will return with `-ENOSYS`.

To handle interrupts properly, your custom kernel module can provide its own interrupt handler. It will automatically be called by the built-in handler.

For cards that don't generate interrupts but need to be polled, there is the possibility to set up a timer that triggers the interrupt handler at configurable time intervals. This interrupt simulation is done by calling `uio_event_notify()` from the timer's event handler.

Each driver provides attributes that are used to read or write variables. These attributes are accessible through sysfs files. A custom kernel driver module can add its own attributes to the device owned by the uio driver, but not added to the UIO device itself at this time. This might change in the future if it would be found to be useful.

The following standard attributes are provided by the UIO framework:

- `name`: The name of your device. It is recommended to use the name of your kernel module for this.

- `version`: A version string defined by your driver. This allows the user space part of your driver to deal with different versions of the kernel module.

- `event`: The total number of interrupts handled by the driver since the last time the device node was read.

These attributes appear under the `/sys/class/uio/uioX` directory. Please note that this directory might be a symlink, and not a real directory. Any userspace code that accesses it must be able to handle this.

Each UIO device can make one or more memory regions available for memory mapping. This is necessary because some industrial I/O cards require access to more than one PCI memory region in a driver.

Each mapping has its own directory in sysfs, the first mapping appears as `/sys/class/uio/uioX/maps/map0/`. Subsequent mappings create directories `map1/`, `map2/`, and so on. These directories will only appear if the size of the mapping is not 0.

Each `mapX/` directory contains four read-only files that show attributes of the memory:

- `name`: A string identifier for this mapping. This is optional, the string can be empty. Drivers can set this to make it easier for userspace to find the correct mapping.

- `addr`: The address of memory that can be mapped.

- `size`: The size, in bytes, of the memory pointed to by addr.

- `offset`: The offset, in bytes, that has to be added to the pointer returned by `mmap()` to get to the actual device memory. This is important if the device's memory is not page aligned. Remember that pointers returned by `mmap()` are always page aligned, so it is good style to always add this offset.

From userspace, the different mappings are distinguished by adjusting the `offset` parameter of the `mmap()` call. To map the memory of mapping N, you have to use N times the page size as your offset:



```text
offset = N * getpagesize();
```

Sometimes there is hardware with memory-like regions that can not be mapped with the technique described here, but there are still ways to access them from userspace. The most common example are x86 ioports. On x86 systems, userspace can access these ioports using `ioperm()`, `iopl()`, `inb()`, `outb()`, and similar functions.

Since these ioport regions can not be mapped, they will not appear under `/sys/class/uio/uioX/maps/` like the normal memory described above. Without information about the port regions a hardware has to offer, it becomes difficult for the userspace part of the driver to find out which ports belong to which UIO device.

To address this situation, the new directory `/sys/class/uio/uioX/portio/` was added. It only exists if the driver wants to pass information about one or more port regions to userspace. If that is the case, subdirectories named `port0`, `port1`, and so on, will appear underneath `/sys/class/uio/uioX/portio/`.

Each `portX/` directory contains four read-only files that show name, start, size, and type of the port region:

- `name`: A string identifier for this port region. The string is optional and can be empty. Drivers can set it to make it easier for userspace to find a certain port region.

- `start`: The first port of this region.

- `size`: The number of ports in this region.

- `porttype`: A string describing the type of port.

<a id="rst-writing-your-own-kernel-module"></a>

## Writing your own kernel module

Please have a look at `uio_cif.c` as an example. The following paragraphs explain the different sections of this file.

<a id="rst-struct-uio-info"></a>

### struct uio_info

This structure tells the framework the details of your driver, Some of the members are required, others are optional.

- `const char *name`: Required. The name of your driver as it will appear in sysfs. I recommend using the name of your module for this.

- `const char *version`: Required. This string appears in `/sys/class/uio/uioX/version`.

- `struct uio_mem mem[ MAX_UIO_MAPS ]`: Required if you have memory that can be mapped with `mmap()`. For each mapping you need to fill one of the `uio_mem` structures. See the description below for details.

- `struct uio_port port[ MAX_UIO_PORTS_REGIONS ]`: Required if you want to pass information about ioports to userspace. For each port region you need to fill one of the `uio_port` structures. See the description below for details.

- `long irq`: Required. If your hardware generates an interrupt, it's your modules task to determine the irq number during initialization. If you don't have a hardware generated interrupt but want to trigger the interrupt handler in some other way, set `irq` to `UIO_IRQ_CUSTOM`. If you had no interrupt at all, you could set `irq` to `UIO_IRQ_NONE`, though this rarely makes sense.

- `unsigned long irq_flags`: Required if you've set `irq` to a hardware interrupt number. The flags given here will be used in the call to `request_irq()`.

- `int (*mmap)(struct uio_info *info, struct vm_area_struct *vma)`: Optional. If you need a special `mmap()` function, you can set it here. If this pointer is not NULL, your `mmap()` will be called instead of the built-in one.

- `int (*open)(struct uio_info *info, struct inode *inode)`: Optional. You might want to have your own `open()`, e.g. to enable interrupts only when your device is actually used.

- `int (*release)(struct uio_info *info, struct inode *inode)`: Optional. If you define your own `open()`, you will probably also want a custom `release()` function.

- `int (*irqcontrol)(struct uio_info *info, s32 irq_on)`: Optional. If you need to be able to enable or disable interrupts from userspace by writing to `/dev/uioX`, you can implement this function. The parameter `irq_on` will be 0 to disable interrupts and 1 to enable them.

Usually, your device will have one or more memory regions that can be mapped to user space. For each region, you have to set up a `struct uio_mem` in the `mem[]` array. Here's a description of the fields of `struct uio_mem`:

- `const char *name`: Optional. Set this to help identify the memory region, it will show up in the corresponding sysfs node.

- `int memtype`: Required if the mapping is used. Set this to `UIO_MEM_PHYS` if you have physical memory on your card to be mapped. Use `UIO_MEM_LOGICAL` for logical memory (e.g. allocated with `__get_free_pages()` but not kmalloc()). There's also `UIO_MEM_VIRTUAL` for virtual memory.

- `phys_addr_t addr`: Required if the mapping is used. Fill in the address of your memory block. This address is the one that appears in sysfs.

- `resource_size_t size`: Fill in the size of the memory block that `addr` points to. If `size` is zero, the mapping is considered unused. Note that you *must* initialize `size` with zero for all unused mappings.

- `void *internal_addr`: If you have to access this memory region from within your kernel module, you will want to map it internally by using something like `ioremap()`. Addresses returned by this function cannot be mapped to user space, so you must not store it in `addr`. Use `internal_addr` instead to remember such an address.

Please do not touch the `map` element of `struct uio_mem`\! It is used by the UIO framework to set up sysfs files for this mapping. Simply leave it alone.

Sometimes, your device can have one or more port regions which can not be mapped to userspace. But if there are other possibilities for userspace to access these ports, it makes sense to make information about the ports available in sysfs. For each region, you have to set up a `struct uio_port` in the `port[]` array. Here's a description of the fields of `struct uio_port`:

- `char *porttype`: Required. Set this to one of the predefined constants. Use `UIO_PORT_X86` for the ioports found in x86 architectures.

- `unsigned long start`: Required if the port region is used. Fill in the number of the first port of this region.

- `unsigned long size`: Fill in the number of ports in this region. If `size` is zero, the region is considered unused. Note that you *must* initialize `size` with zero for all unused regions.

Please do not touch the `portio` element of `struct uio_port`\! It is used internally by the UIO framework to set up sysfs files for this region. Simply leave it alone.

<a id="rst-adding-an-interrupt-handler"></a>

### Adding an interrupt handler

What you need to do in your interrupt handler depends on your hardware and on how you want to handle it. You should try to keep the amount of code in your kernel interrupt handler low. If your hardware requires no action that you *have* to perform after each interrupt, then your handler can be empty.

If, on the other hand, your hardware *needs* some action to be performed after each interrupt, then you *must* do it in your kernel module. Note that you cannot rely on the userspace part of your driver. Your userspace program can terminate at any time, possibly leaving your hardware in a state where proper interrupt handling is still required.

There might also be applications where you want to read data from your hardware at each interrupt and buffer it in a piece of kernel memory you've allocated for that purpose. With this technique you could avoid loss of data if your userspace program misses an interrupt.

A note on shared interrupts: Your driver should support interrupt sharing whenever this is possible. It is possible if and only if your driver can detect whether your hardware has triggered the interrupt or not. This is usually done by looking at an interrupt status register. If your driver sees that the IRQ bit is actually set, it will perform its actions, and the handler returns IRQ_HANDLED. If the driver detects that it was not your hardware that caused the interrupt, it will do nothing and return IRQ_NONE, allowing the kernel to call the next possible interrupt handler.

If you decide not to support shared interrupts, your card won't work in computers with no free interrupts. As this frequently happens on the PC platform, you can save yourself a lot of trouble by supporting interrupt sharing.

<a id="rst-using-uio-pdrv-for-platform-devices"></a>

### Using uio_pdrv for platform devices

In many cases, UIO drivers for platform devices can be handled in a generic way. In the same place where you define your `struct platform_device`, you simply also implement your interrupt handler and fill your `struct uio_info`. A pointer to this `struct uio_info` is then used as `platform_data` for your platform device.

You also need to set up an array of `struct resource` containing addresses and sizes of your memory mappings. This information is passed to the driver using the `.resource` and `.num_resources` elements of `struct platform_device`.

You now have to set the `.name` element of `struct platform_device` to `"uio_pdrv"` to use the generic UIO platform device driver. This driver will fill the `mem[]` array according to the resources given, and register the device.

The advantage of this approach is that you only have to edit a file you need to edit anyway. You do not have to create an extra driver.

<a id="rst-using-uio-pdrv-genirq-for-platform-devices"></a>

### Using uio_pdrv_genirq for platform devices

Especially in embedded devices, you frequently find chips where the irq pin is tied to its own dedicated interrupt line. In such cases, where you can be really sure the interrupt is not shared, we can take the concept of `uio_pdrv` one step further and use a generic interrupt handler. That's what `uio_pdrv_genirq` does.

The setup for this driver is the same as described above for `uio_pdrv`, except that you do not implement an interrupt handler. The `.handler` element of `struct uio_info` must remain `NULL`. The `.irq_flags` element must not contain `IRQF_SHARED`.

You will set the `.name` element of `struct platform_device` to `"uio_pdrv_genirq"` to use this driver.

The generic interrupt handler of `uio_pdrv_genirq` will simply disable the interrupt line using `disable_irq_nosync()`. After doing its work, userspace can reenable the interrupt by writing 0x00000001 to the UIO device file. The driver already implements an `irq_control()` to make this possible, you must not implement your own.

Using `uio_pdrv_genirq` not only saves a few lines of interrupt handler code. You also do not need to know anything about the chip's internal registers to create the kernel part of the driver. All you need to know is the irq number of the pin the chip is connected to.

When used in a device-tree enabled system, the driver needs to be probed with the `"of_id"` module parameter set to the `"compatible"` string of the node the driver is supposed to handle. By default, the node's name (without the unit address) is exposed as name for the UIO device in userspace. To set a custom name, a property named `"linux,uio-name"` may be specified in the DT node.

<a id="rst-using-uio-dmem-genirq-for-platform-devices"></a>

### Using uio_dmem_genirq for platform devices

In addition to statically allocated memory ranges, they may also be a desire to use dynamically allocated regions in a user space driver. In particular, being able to access memory made available through the dma-mapping API, may be particularly useful. The `uio_dmem_genirq` driver provides a way to accomplish this.

This driver is used in a similar manner to the `"uio_pdrv_genirq"` driver with respect to interrupt configuration and handling.

Set the `.name` element of `struct platform_device` to `"uio_dmem_genirq"` to use this driver.

When using this driver, fill in the `.platform_data` element of `struct platform_device`, which is of type `struct uio_dmem_genirq_pdata` and which contains the following elements:

- `struct uio_info uioinfo`: The same structure used as the `uio_pdrv_genirq` platform data

- `unsigned int *dynamic_region_sizes`: Pointer to list of sizes of dynamic memory regions to be mapped into user space.

- `unsigned int num_dynamic_regions`: Number of elements in `dynamic_region_sizes` array.

The dynamic regions defined in the platform data will be appended to the \`\` mem\[\] \`\` array after the platform device resources, which implies that the total number of static and dynamic memory regions cannot exceed `MAX_UIO_MAPS`.

The dynamic memory regions will be allocated when the UIO device file, `/dev/uioX` is opened. Similar to static memory resources, the memory region information for dynamic regions is then visible via sysfs at `/sys/class/uio/uioX/maps/mapY/*`. The dynamic memory regions will be freed when the UIO device file is closed. When no processes are holding the device file open, the address returned to userspace is \~0.

<a id="rst-writing-a-driver-in-userspace"></a>

## Writing a driver in userspace

Once you have a working kernel module for your hardware, you can write the userspace part of your driver. You don't need any special libraries, your driver can be written in any reasonable language, you can use floating point numbers and so on. In short, you can use all the tools and libraries you'd normally use for writing a userspace application.

<a id="rst-getting-information-about-your-uio-device"></a>

### Getting information about your UIO device

Information about all UIO devices is available in sysfs. The first thing you should do in your driver is check `name` and `version` to make sure you're talking to the right device and that its kernel driver has the version you expect.

You should also make sure that the memory mapping you need exists and has the size you expect.

There is a tool called `lsuio` that lists UIO devices and their attributes. It is available here:

[http://www.osadl.org/projects/downloads/UIO/user/](<http://www.osadl.org/projects/downloads/UIO/user/>)

With `lsuio` you can quickly check if your kernel module is loaded and which attributes it exports. Have a look at the manpage for details.

The source code of `lsuio` can serve as an example for getting information about an UIO device. The file `uio_helper.c` contains a lot of functions you could use in your userspace driver code.

<a id="rst-mmap-device-memory"></a>

### mmap() device memory

After you made sure you've got the right device with the memory mappings you need, all you have to do is to call `mmap()` to map the device's memory to userspace.

The parameter `offset` of the `mmap()` call has a special meaning for UIO devices: It is used to select which mapping of your device you want to map. To map the memory of mapping N, you have to use N times the page size as your offset:



```text
offset = N * getpagesize();
```

N starts from zero, so if you've got only one memory range to map, set `offset = 0`. A drawback of this technique is that memory is always mapped beginning with its start address.

<a id="rst-waiting-for-interrupts"></a>

### Waiting for interrupts

After you successfully mapped your devices memory, you can access it like an ordinary array. Usually, you will perform some initialization. After that, your hardware starts working and will generate an interrupt as soon as it's finished, has some data available, or needs your attention because an error occurred.

`/dev/uioX` is a read-only file. A `read()` will always block until an interrupt occurs. There is only one legal value for the `count` parameter of `read()`, and that is the size of a signed 32 bit integer (4). Any other value for `count` causes `read()` to fail. The signed 32 bit integer read is the interrupt count of your device. If the value is one more than the value you read the last time, everything is OK. If the difference is greater than one, you missed interrupts.

You can also use `select()` on `/dev/uioX`.

<a id="rst-generic-pci-uio-driver"></a>

## Generic PCI UIO driver

The generic driver is a kernel module named uio_pci_generic. It can work with any device compliant to PCI 2.3 (circa 2002) and any compliant PCI Express device. Using this, you only need to write the userspace driver, removing the need to write a hardware-specific kernel module.

<a id="rst-making-the-driver-recognize-the-device"></a>

### Making the driver recognize the device

Since the driver does not declare any device ids, it will not get loaded automatically and will not automatically bind to any devices, you must load it and allocate id to the driver yourself. For example:



```text
modprobe uio_pci_generic
echo "8086 10f5" > /sys/bus/pci/drivers/uio_pci_generic/new_id
```

If there already is a hardware specific kernel driver for your device, the generic driver still won't bind to it, in this case if you want to use the generic driver (why would you?) you'll have to manually unbind the hardware specific driver and bind the generic driver, like this:



```text
echo -n 0000:00:19.0 > /sys/bus/pci/drivers/e1000e/unbind
echo -n 0000:00:19.0 > /sys/bus/pci/drivers/uio_pci_generic/bind
```

You can verify that the device has been bound to the driver by looking for it in sysfs, for example like the following:



```text
ls -l /sys/bus/pci/devices/0000:00:19.0/driver
```

Which if successful should print:



```text
.../0000:00:19.0/driver -> ../../../bus/pci/drivers/uio_pci_generic
```

Note that the generic driver will not bind to old PCI 2.2 devices. If binding the device failed, run the following command:



```text
dmesg
```

and look in the output for failure reasons.

<a id="rst-things-to-know-about-uio-pci-generic"></a>

### Things to know about uio_pci_generic

Interrupts are handled using the Interrupt Disable bit in the PCI command register and Interrupt Status bit in the PCI status register. All devices compliant to PCI 2.3 (circa 2002) and all compliant PCI Express devices should support these bits. uio_pci_generic detects this support, and won't bind to devices which do not support the Interrupt Disable Bit in the command register.

On each interrupt, uio_pci_generic sets the Interrupt Disable bit. This prevents the device from generating further interrupts until the bit is cleared. The userspace driver should clear this bit before blocking and waiting for more interrupts.

<a id="rst-writing-userspace-driver-using-uio-pci-generic"></a>

### Writing userspace driver using uio_pci_generic

Userspace driver can use pci sysfs interface, or the libpci library that wraps it, to talk to the device and to re-enable interrupts by writing to the command register.

<a id="rst-example-code-using-uio-pci-generic"></a>

### Example code using uio_pci_generic

Here is some sample userspace driver code using uio_pci_generic:



```text
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

int main()
{
    int uiofd;
    int configfd;
    int err;
    int i;
    unsigned icount;
    unsigned char command_high;

    uiofd = open("/dev/uio0", O_RDONLY);
    if (uiofd < 0) {
        perror("uio open:");
        return errno;
    }
    configfd = open("/sys/class/uio/uio0/device/config", O_RDWR);
    if (configfd < 0) {
        perror("config open:");
        return errno;
    }

    /* Read and cache command value */
    err = pread(configfd, &command_high, 1, 5);
    if (err != 1) {
        perror("command config read:");
        return errno;
    }
    command_high &= ~0x4;

    for(i = 0;; ++i) {
        /* Print out a message, for debugging. */
        if (i == 0)
            fprintf(stderr, "Started uio test driver.\n");
        else
            fprintf(stderr, "Interrupts: %d\n", icount);

        /****************************************/
        /* Here we got an interrupt from the
           device. Do something to it. */
        /****************************************/

        /* Re-enable interrupts. */
        err = pwrite(configfd, &command_high, 1, 5);
        if (err != 1) {
            perror("config write:");
            break;
        }

        /* Wait for next interrupt. */
        err = read(uiofd, &icount, 4);
        if (err != 4) {
            perror("uio read:");
            break;
        }

    }
    return errno;
}
```

<a id="rst-generic-hyper-v-uio-driver"></a>

## Generic Hyper-V UIO driver

The generic driver is a kernel module named uio_hv_generic. It supports devices on the Hyper-V VMBus similar to uio_pci_generic on PCI bus.

<a id="rst-making-the-driver-recognize-the-device-1"></a>

### Making the driver recognize the device

Since the driver does not declare any device GUID's, it will not get loaded automatically and will not automatically bind to any devices, you must load it and allocate id to the driver yourself. For example, to use the network device class GUID:



```text
modprobe uio_hv_generic
echo "f8615163-df3e-46c5-913f-f2d2f965ed0e" > /sys/bus/vmbus/drivers/uio_hv_generic/new_id
```

If there already is a hardware specific kernel driver for the device, the generic driver still won't bind to it, in this case if you want to use the generic driver for a userspace library you'll have to manually unbind the hardware specific driver and bind the generic driver, using the device specific GUID like this:



```text
echo -n ed963694-e847-4b2a-85af-bc9cfc11d6f3 > /sys/bus/vmbus/drivers/hv_netvsc/unbind
echo -n ed963694-e847-4b2a-85af-bc9cfc11d6f3 > /sys/bus/vmbus/drivers/uio_hv_generic/bind
```

You can verify that the device has been bound to the driver by looking for it in sysfs, for example like the following:



```text
ls -l /sys/bus/vmbus/devices/ed963694-e847-4b2a-85af-bc9cfc11d6f3/driver
```

Which if successful should print:



```text
.../ed963694-e847-4b2a-85af-bc9cfc11d6f3/driver -> ../../../bus/vmbus/drivers/uio_hv_generic
```

<a id="rst-things-to-know-about-uio-hv-generic"></a>

### Things to know about uio_hv_generic

On each interrupt, uio_hv_generic sets the Interrupt Disable bit. This prevents the device from generating further interrupts until the bit is cleared. The userspace driver should clear this bit before blocking and waiting for more interrupts.

When host rescinds a device, the interrupt file descriptor is marked down and any reads of the interrupt file descriptor will return -EIO. Similar to a closed socket or disconnected serial device.

- **The vmbus device regions are mapped into uio device resources:**

  0. Channel ring buffers: guest to host and host to guest

  1. Guest to host interrupt signalling pages

  2. Guest to host monitor page

  3. Network receive buffer region

  4. Network send buffer region

If a subchannel is created by a request to host, then the uio_hv_generic device driver will create a sysfs binary file for the per-channel ring buffer. For example:



```text
/sys/bus/vmbus/devices/3811fe4d-0fa0-4b62-981a-74fc1084c757/channels/21/ring
```

<a id="rst-further-information"></a>

## Further information

- [OSADL homepage.](<http://www.osadl.org>)<a id="rst-osadl-homepage"></a>

- [Linutronix homepage.](<http://www.linutronix.de>)<a id="rst-linutronix-homepage"></a>

---

# VFIO Mediated devices

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> The number of use cases for virtualizing DMA devices that do not have built-in SR_IOV capability is increasing. Previously, to virtualize such devices, developers had to create their own management interfaces and APIs, and then integrate…

<a id="rst-vfio-mediated-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2016, NVIDIA CORPORATION. All rights reserved.

**Author:** Neo Jia &lt;[cjia@nvidia.com](<mailto:cjia@nvidia.com>)&gt;

**Author:** Kirti Wankhede &lt;[kwankhede@nvidia.com](<mailto:kwankhede@nvidia.com>)&gt;

<a id="rst-virtual-function-i-o-vfio-mediated-devices-1"></a>

## Virtual Function I/O (VFIO) Mediated devices\[1\]

The number of use cases for virtualizing DMA devices that do not have built-in SR_IOV capability is increasing. Previously, to virtualize such devices, developers had to create their own management interfaces and APIs, and then integrate them with user space software. To simplify integration with user space software, we have identified common requirements and a unified management interface for such devices.

The VFIO driver framework provides unified APIs for direct device access. It is an IOMMU/device-agnostic framework for exposing direct device access to user space in a secure, IOMMU-protected environment. This framework is used for multiple devices, such as GPUs, network adapters, and compute accelerators. With direct device access, virtual machines or user space applications have direct access to the physical device. This framework is reused for mediated devices.

The mediated core driver provides a common interface for mediated device management that can be used by drivers of different devices. This module provides a generic interface to perform these operations:

- Create and destroy a mediated device

- Add a mediated device to and remove it from a mediated bus driver

- Add a mediated device to and remove it from an IOMMU group

The mediated core driver also provides an interface to register a bus driver. For example, the mediated VFIO mdev driver is designed for mediated devices and supports VFIO APIs. The mediated bus driver adds a mediated device to and removes it from a VFIO group.

The following high-level block diagram shows the main components and interfaces in the VFIO mediated driver framework. The diagram shows NVIDIA, Intel, and IBM devices as examples, as these devices are the first devices to use this module:



```text
+---------------+
|               |
| +-----------+ |  mdev_register_driver() +--------------+
| |           | +<------------------------+              |
| |  mdev     | |                         |              |
| |  bus      | +------------------------>+ vfio_mdev.ko |<-> VFIO user
| |  driver   | |     probe()/remove()    |              |    APIs
| |           | |                         +--------------+
| +-----------+ |
|               |
|  MDEV CORE    |
|   MODULE      |
|   mdev.ko     |
| +-----------+ |  mdev_register_parent() +--------------+
| |           | +<------------------------+              |
| |           | |                         | ccw_device.ko|<-> physical
| |           | +------------------------>+              |    device
| |           | |        callbacks        +--------------+
| | Physical  | |
| |  device   | |  mdev_register_parent() +--------------+
| | interface | |<------------------------+              |
| |           | |                         |  i915.ko     |<-> physical
| |           | +------------------------>+              |    device
| |           | |        callbacks        +--------------+
| +-----------+ |
+---------------+
```

<a id="rst-registration-interfaces"></a>

## Registration Interfaces

The mediated core driver provides the following types of registration interfaces:

- Registration interface for a mediated bus driver

- Physical device driver interface

<a id="rst-registration-interface-for-a-mediated-bus-driver"></a>

### Registration Interface for a Mediated Bus Driver

The registration interface for a mediated device driver provides the following structure to represent a mediated device's driver:



```text
/*
 * struct mdev_driver [2] - Mediated device's driver
 * @probe: called when new device created
 * @remove: called when device removed
 * @driver: device driver structure
 */
struct mdev_driver {
        int  (*probe)  (struct mdev_device *dev);
        void (*remove) (struct mdev_device *dev);
        unsigned int (*get_available)(struct mdev_type *mtype);
        ssize_t (*show_description)(struct mdev_type *mtype, char *buf);
        struct device_driver    driver;
};
```

A mediated bus driver for mdev should use this structure in the function calls to register and unregister itself with the core driver:

- Register:



  ```text
  int mdev_register_driver(struct mdev_driver *drv);
  ```

- Unregister:



  ```text
  void mdev_unregister_driver(struct mdev_driver *drv);
  ```

The mediated bus driver's probe function should create a vfio_device on top of the mdev_device and connect it to an appropriate implementation of vfio_device_ops.

When a driver wants to add the GUID creation sysfs to an existing device it has probe'd to then it should call:



```text
int mdev_register_parent(struct mdev_parent *parent, struct device *dev,
                    struct mdev_driver *mdev_driver);
```

This will provide the 'mdev_supported_types/XX/create' files which can then be used to trigger the creation of a mdev_device. The created mdev_device will be attached to the specified driver.

When the driver needs to remove itself it calls:



```text
void mdev_unregister_parent(struct mdev_parent *parent);
```

Which will unbind and destroy all the created mdevs and remove the sysfs files.

<a id="rst-mediated-device-management-interface-through-sysfs"></a>

## Mediated Device Management Interface Through sysfs

The management interface through sysfs enables user space software, such as libvirt, to query and configure mediated devices in a hardware-agnostic fashion. This management interface provides flexibility to the underlying physical device's driver to support features such as:

- Mediated device hot plug

- Multiple mediated devices in a single virtual machine

- Multiple mediated devices from different physical devices

<a id="rst-links-in-the-mdev-bus-class-directory"></a>

### Links in the mdev_bus Class Directory

The /sys/class/mdev_bus/ directory contains links to devices that are registered with the mdev core driver.

<a id="rst-directories-and-files-under-the-sysfs-for-each-physical-device"></a>

### Directories and files under the sysfs for Each Physical Device



```text
|- [parent physical device]
|--- Vendor-specific-attributes [optional]
|--- [mdev_supported_types]
|     |--- [<type-id>]
|     |   |--- create
|     |   |--- name
|     |   |--- available_instances
|     |   |--- device_api
|     |   |--- description
|     |   |--- [devices]
|     |--- [<type-id>]
|     |   |--- create
|     |   |--- name
|     |   |--- available_instances
|     |   |--- device_api
|     |   |--- description
|     |   |--- [devices]
|     |--- [<type-id>]
|          |--- create
|          |--- name
|          |--- available_instances
|          |--- device_api
|          |--- description
|          |--- [devices]
```

- \[mdev_supported_types\]

  The list of currently supported mediated device types and their details.

  \[&lt;type-id&gt;\], device_api, and available_instances are mandatory attributes that should be provided by vendor driver.

- \[&lt;type-id&gt;\]

  The \[&lt;type-id&gt;\] name is created by adding the device driver string as a prefix to the string provided by the vendor driver. This format of this name is as follows:



  ```text
  sprintf(buf, "%s-%s", dev_driver_string(parent->dev), group->name);
  ```

- device_api

  This attribute shows which device API is being created, for example, "vfio-pci" for a PCI device.

- available_instances

  This attribute shows the number of devices of type &lt;type-id&gt; that can be created.

- \[device\]

  This directory contains links to the devices of type &lt;type-id&gt; that have been created.

- name

  This attribute shows a human readable name.

- description

  This attribute can show brief features/description of the type. This is an optional attribute.

<a id="rst-directories-and-files-under-the-sysfs-for-each-mdev-device"></a>

### Directories and Files Under the sysfs for Each mdev Device



```text
|- [parent phy device]
|--- [$MDEV_UUID]
       |--- remove
       |--- mdev_type {link to its type}
       |--- vendor-specific-attributes [optional]
```

- remove (write only)

Writing '1' to the 'remove' file destroys the mdev device. The vendor driver can fail the remove() callback if that device is active and the vendor driver doesn't support hot unplug.

Example:



```text
# echo 1 > /sys/bus/mdev/devices/$mdev_UUID/remove
```

<a id="rst-mediated-device-hot-plug"></a>

### Mediated device Hot plug

Mediated devices can be created and assigned at runtime. The procedure to hot plug a mediated device is the same as the procedure to hot plug a PCI device.

<a id="rst-translation-apis-for-mediated-devices"></a>

## Translation APIs for Mediated Devices

The following APIs are provided for translating user pfn to host pfn in a VFIO driver:



```text
int vfio_pin_pages(struct vfio_device *device, dma_addr_t iova,
                          int npage, int prot, struct page **pages);

void vfio_unpin_pages(struct vfio_device *device, dma_addr_t iova,
                            int npage);
```

These functions call back into the back-end IOMMU module by using the pin_pages and unpin_pages callbacks of the struct vfio_iommu_driver_ops\[4\]. Currently these callbacks are supported in the TYPE1 IOMMU module. To enable them for other IOMMU backend modules, such as PPC64 sPAPR module, they need to provide these two callback functions.

<a id="rst-references"></a>

## References

1. See [Documentation/driver-api/vfio.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/vfio.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) for more information on VFIO.

2. struct mdev_driver in include/linux/mdev.h

3. struct mdev_parent_ops in include/linux/mdev.h

4. struct vfio_iommu_driver_ops in include/linux/vfio.h

---

# Acceptance criteria for vfio-pci device specific driver variants

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> The vfio-pci driver exists as a device agnostic driver using the system IOMMU and relying on the robustness of platform fault handling to provide isolated device access to userspace. While the vfio-pci driver does include some device…

<a id="rst-acceptance-criteria-for-vfio-pci-device-specific-driver-variants"></a>

<a id="rst-overview"></a>

## Overview

<!-- SPDX-License-Identifier: GPL-2.0 -->

The vfio-pci driver exists as a device agnostic driver using the system IOMMU and relying on the robustness of platform fault handling to provide isolated device access to userspace.  While the vfio-pci driver does include some device specific support, further extensions for yet more advanced device specific features are not sustainable.  The vfio-pci driver has therefore split out vfio-pci-core as a library that may be reused to implement features requiring device specific knowledge, ex. saving and loading device state for the purposes of supporting migration.

In support of such features, it's expected that some device specific variants may interact with parent devices (ex. SR-IOV PF in support of a user assigned VF) or other extensions that may not be otherwise accessible via the vfio-pci base driver.  Authors of such drivers should be diligent not to create exploitable interfaces via these interactions or allow unchecked userspace data to have an effect beyond the scope of the assigned device.

New driver submissions are therefore requested to have approval via sign-off/ack/review/etc for any interactions with parent drivers. Additionally, drivers should make an attempt to provide sufficient documentation for reviewers to understand the device specific extensions, for example in the case of migration data, how is the device state composed and consumed, which portions are not otherwise available to the user via vfio-pci, what safeguards exist to validate the data, etc.  To that extent, authors should additionally expect to require reviews from at least one of the listed reviewers, in addition to the overall vfio maintainer.

---

# VFIO - "Virtual Function I/O" 1

_Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals_

> Many modern systems now provide DMA and interrupt remapping facilities to help ensure I/O devices behave within the boundaries they've been allotted. This includes x86 hardware with AMD-Vi and Intel VT-d, POWER systems with Partitionable…

> **Peios:** The `chown` examples below describe Linux ownership metadata. They do not delegate native Peios access to VFIO devices. Provision the required descriptor and handle access, and satisfy the device/ioctl and sysfs gates as applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-vfio-virtual-function-i-o-1"></a>

Title notes: <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)

Many modern systems now provide DMA and interrupt remapping facilities to help ensure I/O devices behave within the boundaries they've been allotted.  This includes x86 hardware with AMD-Vi and Intel VT-d, POWER systems with Partitionable Endpoints (PEs) and embedded PowerPC systems such as Freescale PAMU.  The VFIO driver is an IOMMU/device agnostic framework for exposing direct device access to userspace, in a secure, IOMMU protected environment.  In other words, this allows safe <a id="rst-footnote-reference-2"></a>[2](#rst-footnote-2), non-privileged, userspace drivers.

Why do we want that?  Virtual machines often make use of direct device access ("device assignment") when configured for the highest possible I/O performance.  From a device and host perspective, this simply turns the VM into a userspace driver, with the benefits of significantly reduced latency, higher bandwidth, and direct use of bare-metal device drivers <a id="rst-footnote-reference-3"></a>[3](#rst-footnote-3).

Some applications, particularly in the high performance computing field, also benefit from low-overhead, direct device access from userspace.  Examples include network adapters (often non-TCP/IP based) and compute accelerators.  Prior to VFIO, these drivers had to either go through the full development cycle to become proper upstream driver, be maintained out of tree, or make use of the UIO framework, which has no notion of IOMMU protection, limited interrupt support, and requires root privileges to access things like PCI configuration space.

The VFIO driver framework intends to unify these, replacing both the KVM PCI specific device assignment code as well as provide a more secure, more featureful userspace driver environment than UIO.

<a id="rst-groups-devices-and-iommus"></a>

## Groups, Devices, and IOMMUs

Devices are the main target of any I/O driver.  Devices typically create a programming interface made up of I/O access, interrupts, and DMA.  Without going into the details of each of these, DMA is by far the most critical aspect for maintaining a secure environment as allowing a device read-write access to system memory imposes the greatest risk to the overall system integrity.

To help mitigate this risk, many modern IOMMUs now incorporate isolation properties into what was, in many cases, an interface only meant for translation (ie. solving the addressing problems of devices with limited address spaces).  With this, devices can now be isolated from each other and from arbitrary memory access, thus allowing things like secure direct assignment of devices into virtual machines.

This isolation is not always at the granularity of a single device though.  Even when an IOMMU is capable of this, properties of devices, interconnects, and IOMMU topologies can each reduce this isolation. For instance, an individual device may be part of a larger multi- function enclosure.  While the IOMMU may be able to distinguish between devices within the enclosure, the enclosure may not require transactions between devices to reach the IOMMU.  Examples of this could be anything from a multi-function PCI device with backdoors between functions to a non-PCI-ACS (Access Control Services) capable bridge allowing redirection without reaching the IOMMU.  Topology can also play a factor in terms of hiding devices.  A PCIe-to-PCI bridge masks the devices behind it, making transaction appear as if from the bridge itself.  Obviously IOMMU design plays a major factor as well.

Therefore, while for the most part an IOMMU may have device level granularity, any system is susceptible to reduced granularity.  The IOMMU API therefore supports a notion of IOMMU groups.  A group is a set of devices which is isolatable from all other devices in the system.  Groups are therefore the unit of ownership used by VFIO.

While the group is the minimum granularity that must be used to ensure secure user access, it's not necessarily the preferred granularity.  In IOMMUs which make use of page tables, it may be possible to share a set of page tables between different groups, reducing the overhead both to the platform (reduced TLB thrashing, reduced duplicate page tables), and to the user (programming only a single set of translations).  For this reason, VFIO makes use of a container class, which may hold one or more groups.  A container is created by simply opening the /dev/vfio/vfio character device.

On its own, the container provides little functionality, with all but a couple version and extension query interfaces locked away. The user needs to add a group into the container for the next level of functionality.  To do this, the user first needs to identify the group associated with the desired device.  This can be done using the sysfs links described in the example below.  By unbinding the device from the host driver and binding it to a VFIO driver, a new VFIO group will appear for the group as /dev/vfio/$GROUP, where $GROUP is the IOMMU group number of which the device is a member. If the IOMMU group contains multiple devices, each will need to be bound to a VFIO driver before operations on the VFIO group are allowed (it's also sufficient to only unbind the device from host drivers if a VFIO driver is unavailable; this will make the group available, but not that particular device).  TBD - interface for disabling driver probing/locking a device.

Once the group is ready, it may be added to the container by opening the VFIO group character device (/dev/vfio/$GROUP) and using the VFIO\_GROUP\_SET\_CONTAINER ioctl, passing the file descriptor of the previously opened container file.  If desired and if the IOMMU driver supports sharing the IOMMU context between groups, multiple groups may be set to the same container.  If a group fails to set to a container with existing groups, a new empty container will need to be used instead.

With a group (or groups) attached to a container, the remaining ioctls become available, enabling access to the VFIO IOMMU interfaces. Additionally, it now becomes possible to get file descriptors for each device within a group using an ioctl on the VFIO group file descriptor.

The VFIO device API includes ioctls for describing the device, the I/O regions and their read/write/mmap offsets on the device descriptor, as well as mechanisms for describing and registering interrupt notifications.

<a id="rst-vfio-usage-example"></a>

## VFIO Usage Example

Assume user wants to access PCI device 0000:06:0d.0:



```text
$ readlink /sys/bus/pci/devices/0000:06:0d.0/iommu_group
../../../../kernel/iommu_groups/26
```

This device is therefore in IOMMU group 26.  This device is on the pci bus, therefore the user will make use of vfio-pci to manage the group:



```text
# modprobe vfio-pci
```

Binding this device to the vfio-pci driver creates the VFIO group character devices for this group:



```text
$ lspci -n -s 0000:06:0d.0
06:0d.0 0401: 1102:0002 (rev 08)
# echo 0000:06:0d.0 > /sys/bus/pci/devices/0000:06:0d.0/driver/unbind
# echo 1102 0002 > /sys/bus/pci/drivers/vfio-pci/new_id
```

Now we need to look at what other devices are in the group to free it for use by VFIO:



```text
$ ls -l /sys/bus/pci/devices/0000:06:0d.0/iommu_group/devices
total 0
lrwxrwxrwx. 1 root root 0 Apr 23 16:13 0000:00:1e.0 ->
        ../../../../devices/pci0000:00/0000:00:1e.0
lrwxrwxrwx. 1 root root 0 Apr 23 16:13 0000:06:0d.0 ->
        ../../../../devices/pci0000:00/0000:00:1e.0/0000:06:0d.0
lrwxrwxrwx. 1 root root 0 Apr 23 16:13 0000:06:0d.1 ->
        ../../../../devices/pci0000:00/0000:00:1e.0/0000:06:0d.1
```

This device is behind a PCIe-to-PCI bridge <a id="rst-footnote-reference-4"></a>[4](#rst-footnote-4), therefore we also need to add device 0000:06:0d.1 to the group following the same procedure as above.  Device 0000:00:1e.0 is a bridge that does not currently have a host driver, therefore it's not required to bind this device to the vfio-pci driver (vfio-pci does not currently support PCI bridges).

The final step is to provide the user with access to the group if unprivileged operation is desired (note that /dev/vfio/vfio provides no capabilities on its own and is therefore expected to be set to mode 0666 by the system):



```text
# chown user:user /dev/vfio/26
```

The user now has full access to all the devices and the iommu for this group and can access them as follows:



```text
int container, group, device, i;
struct vfio_group_status group_status =
                                { .argsz = sizeof(group_status) };
struct vfio_iommu_type1_info iommu_info = { .argsz = sizeof(iommu_info) };
struct vfio_iommu_type1_dma_map dma_map = { .argsz = sizeof(dma_map) };
struct vfio_device_info device_info = { .argsz = sizeof(device_info) };

/* Create a new container */
container = open("/dev/vfio/vfio", O_RDWR);

if (ioctl(container, VFIO_GET_API_VERSION) != VFIO_API_VERSION)
        /* Unknown API version */

if (!ioctl(container, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU))
        /* Doesn't support the IOMMU driver we want. */

/* Open the group */
group = open("/dev/vfio/26", O_RDWR);

/* Test the group is viable and available */
ioctl(group, VFIO_GROUP_GET_STATUS, &group_status);

if (!(group_status.flags & VFIO_GROUP_FLAGS_VIABLE))
        /* Group is not viable (ie, not all devices bound for vfio) */

/* Add the group to the container */
ioctl(group, VFIO_GROUP_SET_CONTAINER, &container);

/* Enable the IOMMU model we want */
ioctl(container, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU);

/* Get addition IOMMU info */
ioctl(container, VFIO_IOMMU_GET_INFO, &iommu_info);

/* Allocate some space and setup a DMA mapping */
dma_map.vaddr = mmap(0, 1024 * 1024, PROT_READ | PROT_WRITE,
                     MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
dma_map.size = 1024 * 1024;
dma_map.iova = 0; /* 1MB starting at 0x0 from device view */
dma_map.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE;

ioctl(container, VFIO_IOMMU_MAP_DMA, &dma_map);

/* Get a file descriptor for the device */
device = ioctl(group, VFIO_GROUP_GET_DEVICE_FD, "0000:06:0d.0");

/* Test and setup the device */
ioctl(device, VFIO_DEVICE_GET_INFO, &device_info);

for (i = 0; i < device_info.num_regions; i++) {
        struct vfio_region_info reg = { .argsz = sizeof(reg) };

        reg.index = i;

        ioctl(device, VFIO_DEVICE_GET_REGION_INFO, &reg);

        /* Setup mappings... read/write offsets, mmaps
         * For PCI devices, config space is a region */
}

for (i = 0; i < device_info.num_irqs; i++) {
        struct vfio_irq_info irq = { .argsz = sizeof(irq) };

        irq.index = i;

        ioctl(device, VFIO_DEVICE_GET_IRQ_INFO, &irq);

        /* Setup IRQs... eventfds, VFIO_DEVICE_SET_IRQS */
}

/* Gratuitous device reset and go... */
ioctl(device, VFIO_DEVICE_RESET);
```

<a id="rst-iommufd-and-vfio-iommu-type1"></a>

## IOMMUFD and vfio\_iommu\_type1

IOMMUFD is the new user API to manage I/O page tables from userspace. It intends to be the portal of delivering advanced userspace DMA features (nested translation <a id="rst-footnote-reference-5"></a>[5](#rst-footnote-5), PASID <a id="rst-footnote-reference-6"></a>[6](#rst-footnote-6), etc.) while also providing a backwards compatibility interface for existing VFIO\_TYPE1v2\_IOMMU use cases.  Eventually the vfio\_iommu\_type1 driver, as well as the legacy vfio container and group model is intended to be deprecated.

The IOMMUFD backwards compatibility interface can be enabled two ways. In the first method, the kernel can be configured with CONFIG\_IOMMUFD\_VFIO\_CONTAINER, in which case the IOMMUFD subsystem transparently provides the entire infrastructure for the VFIO container and IOMMU backend interfaces.  The compatibility mode can also be accessed if the VFIO container interface, ie. /dev/vfio/vfio is simply symlink'd to /dev/iommu.  Note that at the time of writing, the compatibility mode is not entirely feature complete relative to VFIO\_TYPE1v2\_IOMMU (ex. DMA mapping MMIO) and does not attempt to provide compatibility to the VFIO\_SPAPR\_TCE\_IOMMU interface.  Therefore it is not generally advisable at this time to switch from native VFIO implementations to the IOMMUFD compatibility interfaces.

Long term, VFIO users should migrate to device access through the cdev interface described below, and native access through the IOMMUFD provided interfaces.

<a id="rst-vfio-device-cdev"></a>

## VFIO Device cdev

Traditionally user acquires a device fd via VFIO\_GROUP\_GET\_DEVICE\_FD in a VFIO group.

With CONFIG\_VFIO\_DEVICE\_CDEV=y the user can now acquire a device fd by directly opening a character device /dev/vfio/devices/vfioX where "X" is the number allocated uniquely by VFIO for registered devices. cdev interface does not support noiommu devices, so user should use the legacy group interface if noiommu is wanted.

The cdev only works with IOMMUFD.  Both VFIO drivers and applications must adapt to the new cdev security model which requires using VFIO\_DEVICE\_BIND\_IOMMUFD to claim DMA ownership before starting to actually use the device.  Once BIND succeeds then a VFIO device can be fully accessed by the user.

VFIO device cdev doesn't rely on VFIO group/container/iommu drivers. Hence those modules can be fully compiled out in an environment where no legacy VFIO application exists.

So far SPAPR does not support IOMMUFD yet.  So it cannot support device cdev either.

vfio device cdev access is still bound by IOMMU group semantics, ie. there can be only one DMA owner for the group.  Devices belonging to the same group can not be bound to multiple iommufd\_ctx or shared between native kernel and vfio bus driver or other driver supporting the driver\_managed\_dma flag.  A violation of this ownership requirement will fail at the VFIO\_DEVICE\_BIND\_IOMMUFD ioctl, which gates full device access.

<a id="rst-device-cdev-example"></a>

## Device cdev Example

Assume user wants to access PCI device 0000:6a:01.0:



```text
$ ls /sys/bus/pci/devices/0000:6a:01.0/vfio-dev/
vfio0
```

This device is therefore represented as vfio0.  The user can verify its existence:



```text
$ ls -l /dev/vfio/devices/vfio0
crw------- 1 root root 511, 0 Feb 16 01:22 /dev/vfio/devices/vfio0
$ cat /sys/bus/pci/devices/0000:6a:01.0/vfio-dev/vfio0/dev
511:0
$ ls -l /dev/char/511\:0
lrwxrwxrwx 1 root root 21 Feb 16 01:22 /dev/char/511:0 -> ../vfio/devices/vfio0
```

Then provide the user with access to the device if unprivileged operation is desired:



```text
$ chown user:user /dev/vfio/devices/vfio0
```

Finally the user could get cdev fd by:



```text
cdev_fd = open("/dev/vfio/devices/vfio0", O_RDWR);
```

An opened cdev\_fd doesn't give the user any permission of accessing the device except binding the cdev\_fd to an iommufd.  After that point then the device is fully accessible including attaching it to an IOMMUFD IOAS/HWPT to enable userspace DMA:



```text
struct vfio_device_bind_iommufd bind = {
        .argsz = sizeof(bind),
        .flags = 0,
};
struct iommu_ioas_alloc alloc_data  = {
        .size = sizeof(alloc_data),
        .flags = 0,
};
struct vfio_device_attach_iommufd_pt attach_data = {
        .argsz = sizeof(attach_data),
        .flags = 0,
};
struct iommu_ioas_map map = {
        .size = sizeof(map),
        .flags = IOMMU_IOAS_MAP_READABLE |
                 IOMMU_IOAS_MAP_WRITEABLE |
                 IOMMU_IOAS_MAP_FIXED_IOVA,
        .__reserved = 0,
};

iommufd = open("/dev/iommu", O_RDWR);

bind.iommufd = iommufd;
ioctl(cdev_fd, VFIO_DEVICE_BIND_IOMMUFD, &bind);

ioctl(iommufd, IOMMU_IOAS_ALLOC, &alloc_data);
attach_data.pt_id = alloc_data.out_ioas_id;
ioctl(cdev_fd, VFIO_DEVICE_ATTACH_IOMMUFD_PT, &attach_data);

/* Allocate some space and setup a DMA mapping */
map.user_va = (int64_t)mmap(0, 1024 * 1024, PROT_READ | PROT_WRITE,
                            MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
map.iova = 0; /* 1MB starting at 0x0 from device view */
map.length = 1024 * 1024;
map.ioas_id = alloc_data.out_ioas_id;

ioctl(iommufd, IOMMU_IOAS_MAP, &map);

/* Other device operations as stated in "VFIO Usage Example" */
```

<a id="rst-vfio-user-api"></a>

## VFIO User API

Please see include/uapi/linux/vfio.h for complete API documentation.

<a id="rst-vfio-bus-driver-api"></a>

## VFIO bus driver API

VFIO bus drivers, such as vfio-pci make use of only a few interfaces into VFIO core.  When devices are bound and unbound to the driver, Following interfaces are called when devices are bound to and unbound from the driver:



```text
int vfio_register_group_dev(struct vfio_device *device);
int vfio_register_emulated_iommu_dev(struct vfio_device *device);
void vfio_unregister_group_dev(struct vfio_device *device);
```

The driver should embed the vfio\_device in its own structure and use vfio\_alloc\_device() to allocate the structure, and can register @init/@release callbacks to manage any private state wrapping the vfio\_device:



```text
vfio_alloc_device(dev_struct, member, dev, ops);
void vfio_put_device(struct vfio_device *device);
```

vfio\_register\_group\_dev() indicates to the core to begin tracking the iommu\_group of the specified dev and register the dev as owned by a VFIO bus driver. Once vfio\_register\_group\_dev() returns it is possible for userspace to start accessing the driver, thus the driver should ensure it is completely ready before calling it. The driver provides an ops structure for callbacks similar to a file operations structure:



```text
struct vfio_device_ops {
        char    *name;
        int     (*init)(struct vfio_device *vdev);
        void    (*release)(struct vfio_device *vdev);
        int     (*bind_iommufd)(struct vfio_device *vdev,
                                struct iommufd_ctx *ictx, u32 *out_device_id);
        void    (*unbind_iommufd)(struct vfio_device *vdev);
        int     (*attach_ioas)(struct vfio_device *vdev, u32 *pt_id);
        void    (*detach_ioas)(struct vfio_device *vdev);
        int     (*open_device)(struct vfio_device *vdev);
        void    (*close_device)(struct vfio_device *vdev);
        ssize_t (*read)(struct vfio_device *vdev, char __user *buf,
                        size_t count, loff_t *ppos);
        ssize_t (*write)(struct vfio_device *vdev, const char __user *buf,
                 size_t count, loff_t *size);
        long    (*ioctl)(struct vfio_device *vdev, unsigned int cmd,
                         unsigned long arg);
        int     (*mmap)(struct vfio_device *vdev, struct vm_area_struct *vma);
        void    (*request)(struct vfio_device *vdev, unsigned int count);
        int     (*match)(struct vfio_device *vdev, char *buf);
        void    (*dma_unmap)(struct vfio_device *vdev, u64 iova, u64 length);
        int     (*device_feature)(struct vfio_device *device, u32 flags,
                                  void __user *arg, size_t argsz);
};
```

Each function is passed the vdev that was originally registered in the vfio\_register\_group\_dev() or vfio\_register\_emulated\_iommu\_dev() call above. This allows the bus driver to obtain its private data using container\_of().



```text
- The init/release callbacks are issued when vfio_device is initialized
  and released.

- The open/close device callbacks are issued when the first
  instance of a file descriptor for the device is created (eg.
  via VFIO_GROUP_GET_DEVICE_FD) for a user session.

- The ioctl callback provides a direct pass through for some VFIO_DEVICE_*
  ioctls.

- The [un]bind_iommufd callbacks are issued when the device is bound to
  and unbound from iommufd.

- The [de]attach_ioas callback is issued when the device is attached to
  and detached from an IOAS managed by the bound iommufd. However, the
  attached IOAS can also be automatically detached when the device is
  unbound from iommufd.

- The read/write/mmap callbacks implement the device region access defined
  by the device's own VFIO_DEVICE_GET_REGION_INFO ioctl.

- The request callback is issued when device is going to be unregistered,
  such as when trying to unbind the device from the vfio bus driver.

- The dma_unmap callback is issued when a range of iovas are unmapped
  in the container or IOAS attached by the device. Drivers which make
  use of the vfio page pinning interface must implement this callback in
  order to unpin pages within the dma_unmap range. Drivers must tolerate
  this callback even before calls to open_device().
```

<a id="rst-ppc64-spapr-implementation-note"></a>

## PPC64 sPAPR implementation note

This implementation has some specifics:

1. On older systems (POWER7 with P5IOC2/IODA1) only one IOMMU group per container is supported as an IOMMU table is allocated at the boot time, one table per a IOMMU group which is a Partitionable Endpoint (PE) (PE is often a PCI domain but not always).

   Newer systems (POWER8 with IODA2) have improved hardware design which allows to remove this limitation and have multiple IOMMU groups per a VFIO container.

2. The hardware supports so called DMA windows - the PCI address range within which DMA transfer is allowed, any attempt to access address space out of the window leads to the whole PE isolation.

3. PPC64 guests are paravirtualized but not fully emulated. There is an API to map/unmap pages for DMA, and it normally maps 1..32 pages per call and currently there is no way to reduce the number of calls. In order to make things faster, the map/unmap handling has been implemented in real mode which provides an excellent performance which has limitations such as inability to do locked pages accounting in real time.

4. According to sPAPR specification, A Partitionable Endpoint (PE) is an I/O subtree that can be treated as a unit for the purposes of partitioning and error recovery. A PE may be a single or multi-function IOA (IO Adapter), a function of a multi-function IOA, or multiple IOAs (possibly including switch and bridge structures above the multiple IOAs). PPC64 guests detect PCI errors and recover from them via EEH RTAS services, which works on the basis of additional ioctl commands.

   So 4 additional ioctls have been added:

   > - **VFIO\_IOMMU\_SPAPR\_TCE\_GET\_INFO**
   >
   >   returns the size and the start of the DMA window on the PCI bus.
   >
   > - **VFIO\_IOMMU\_ENABLE**
   >
   >   enables the container. The locked pages accounting is done at this point. This lets user first to know what the DMA window is and adjust rlimit before doing any real job.
   >
   > - **VFIO\_IOMMU\_DISABLE**
   >
   >   disables the container.
   >
   > - **VFIO\_EEH\_PE\_OP**
   >
   >   provides an API for EEH setup, error detection and recovery.

   The code flow from the example above should be slightly changed:



   ```text
   struct vfio_eeh_pe_op pe_op = { .argsz = sizeof(pe_op), .flags = 0 };

   .....
   /* Add the group to the container */
   ioctl(group, VFIO_GROUP_SET_CONTAINER, &container);

   /* Enable the IOMMU model we want */
   ioctl(container, VFIO_SET_IOMMU, VFIO_SPAPR_TCE_IOMMU)

   /* Get addition sPAPR IOMMU info */
   vfio_iommu_spapr_tce_info spapr_iommu_info;
   ioctl(container, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &spapr_iommu_info);

   if (ioctl(container, VFIO_IOMMU_ENABLE))
           /* Cannot enable container, may be low rlimit */

   /* Allocate some space and setup a DMA mapping */
   dma_map.vaddr = mmap(0, 1024 * 1024, PROT_READ | PROT_WRITE,
                        MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);

   dma_map.size = 1024 * 1024;
   dma_map.iova = 0; /* 1MB starting at 0x0 from device view */
   dma_map.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE;

   /* Check here is .iova/.size are within DMA window from spapr_iommu_info */
   ioctl(container, VFIO_IOMMU_MAP_DMA, &dma_map);

   /* Get a file descriptor for the device */
   device = ioctl(group, VFIO_GROUP_GET_DEVICE_FD, "0000:06:0d.0");

   ....

   /* Gratuitous device reset and go... */
   ioctl(device, VFIO_DEVICE_RESET);

   /* Make sure EEH is supported */
   ioctl(container, VFIO_CHECK_EXTENSION, VFIO_EEH);

   /* Enable the EEH functionality on the device */
   pe_op.op = VFIO_EEH_PE_ENABLE;
   ioctl(container, VFIO_EEH_PE_OP, &pe_op);

   /* You're suggested to create additional data struct to represent
    * PE, and put child devices belonging to same IOMMU group to the
    * PE instance for later reference.
    */

   /* Check the PE's state and make sure it's in functional state */
   pe_op.op = VFIO_EEH_PE_GET_STATE;
   ioctl(container, VFIO_EEH_PE_OP, &pe_op);

   /* Save device state using pci_save_state().
    * EEH should be enabled on the specified device.
    */

   ....

   /* Inject EEH error, which is expected to be caused by 32-bits
    * config load.
    */
   pe_op.op = VFIO_EEH_PE_INJECT_ERR;
   pe_op.err.type = EEH_ERR_TYPE_32;
   pe_op.err.func = EEH_ERR_FUNC_LD_CFG_ADDR;
   pe_op.err.addr = 0ul;
   pe_op.err.mask = 0ul;
   ioctl(container, VFIO_EEH_PE_OP, &pe_op);

   ....

   /* When 0xFF's returned from reading PCI config space or IO BARs
    * of the PCI device. Check the PE's state to see if that has been
    * frozen.
    */
   ioctl(container, VFIO_EEH_PE_OP, &pe_op);

   /* Waiting for pending PCI transactions to be completed and don't
    * produce any more PCI traffic from/to the affected PE until
    * recovery is finished.
    */

   /* Enable IO for the affected PE and collect logs. Usually, the
    * standard part of PCI config space, AER registers are dumped
    * as logs for further analysis.
    */
   pe_op.op = VFIO_EEH_PE_UNFREEZE_IO;
   ioctl(container, VFIO_EEH_PE_OP, &pe_op);

   /*
    * Issue PE reset: hot or fundamental reset. Usually, hot reset
    * is enough. However, the firmware of some PCI adapters would
    * require fundamental reset.
    */
   pe_op.op = VFIO_EEH_PE_RESET_HOT;
   ioctl(container, VFIO_EEH_PE_OP, &pe_op);
   pe_op.op = VFIO_EEH_PE_RESET_DEACTIVATE;
   ioctl(container, VFIO_EEH_PE_OP, &pe_op);

   /* Configure the PCI bridges for the affected PE */
   pe_op.op = VFIO_EEH_PE_CONFIGURE;
   ioctl(container, VFIO_EEH_PE_OP, &pe_op);

   /* Restored state we saved at initialization time. pci_restore_state()
    * is good enough as an example.
    */

   /* Hopefully, error is recovered successfully. Now, you can resume to
    * start PCI traffic to/from the affected PE.
    */

   ....
   ```

5. There is v2 of SPAPR TCE IOMMU. It deprecates VFIO\_IOMMU\_ENABLE/ VFIO\_IOMMU\_DISABLE and implements 2 new ioctls: VFIO\_IOMMU\_SPAPR\_REGISTER\_MEMORY and VFIO\_IOMMU\_SPAPR\_UNREGISTER\_MEMORY (which are unsupported in v1 IOMMU).

   PPC64 paravirtualized guests generate a lot of map/unmap requests, and the handling of those includes pinning/unpinning pages and updating mm::locked\_vm counter to make sure we do not exceed the rlimit. The v2 IOMMU splits accounting and pinning into separate operations:

   - VFIO\_IOMMU\_SPAPR\_REGISTER\_MEMORY/VFIO\_IOMMU\_SPAPR\_UNREGISTER\_MEMORY ioctls receive a user space address and size of the block to be pinned. Bisecting is not supported and VFIO\_IOMMU\_UNREGISTER\_MEMORY is expected to be called with the exact address and size used for registering the memory block. The userspace is not expected to call these often. The ranges are stored in a linked list in a VFIO container.

   - VFIO\_IOMMU\_MAP\_DMA/VFIO\_IOMMU\_UNMAP\_DMA ioctls only update the actual IOMMU table and do not do pinning; instead these check that the userspace address is from pre-registered range.

   This separation helps in optimizing DMA for guests.

6. sPAPR specification allows guests to have an additional DMA window(s) on a PCI bus with a variable page size. Two ioctls have been added to support this: VFIO\_IOMMU\_SPAPR\_TCE\_CREATE and VFIO\_IOMMU\_SPAPR\_TCE\_REMOVE. The platform has to support the functionality or error will be returned to the userspace. The existing hardware supports up to 2 DMA windows, one is 2GB long, uses 4K pages and called "default 32bit window"; the other can be as big as entire RAM, use different page size, it is optional - guests create those in run-time if the guest driver supports 64bit DMA.

   VFIO\_IOMMU\_SPAPR\_TCE\_CREATE receives a page shift, a DMA window size and a number of TCE table levels (if a TCE table is going to be big enough and the kernel may not be able to allocate enough of physically contiguous memory). It creates a new window in the available slot and returns the bus address where the new window starts. Due to hardware limitation, the user space cannot choose the location of DMA windows.

   VFIO\_IOMMU\_SPAPR\_TCE\_REMOVE receives the bus start address of the window and removes it.

---

<a id="rst-footnote-1"></a>



**[1]** VFIO was originally an acronym for "Virtual Function I/O" in its initial implementation by Tom Lyon while as Cisco.  We've since outgrown the acronym, but it's catchy.

<a id="rst-footnote-2"></a>



**[2]** "safe" also depends upon a device being "well behaved".  It's possible for multi-function devices to have backdoors between functions and even for single function devices to have alternative access to things like PCI config space through MMIO registers.  To guard against the former we can include additional precautions in the IOMMU driver to group multi-function PCI devices together (iommu=group\_mf).  The latter we can't prevent, but the IOMMU should still provide isolation.  For PCI, SR-IOV Virtual Functions are the best indicator of "well behaved", as these are designed for virtualization usage models.

<a id="rst-footnote-3"></a>



**[3]** As always there are trade-offs to virtual machine device assignment that are beyond the scope of VFIO.  It's expected that future IOMMU technologies will reduce some, but maybe not all, of these trade-offs.

<a id="rst-footnote-4"></a>



**[4]** In this case the device is below a PCI bridge, so transactions from either function of the device are indistinguishable to the iommu:



```text
-[0000:00]-+-1e.0-[06]--+-0d.0
                        \-0d.1

00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev 90)
```

<a id="rst-footnote-5"></a>



**[5]** Nested translation is an IOMMU feature which supports two stage address translations.  This improves the address translation efficiency in IOMMU virtualization.

<a id="rst-footnote-6"></a>



**[6]** PASID stands for Process Address Space ID, introduced by PCI Express.  It is a prerequisite for Shared Virtual Addressing (SVA) and Scalable I/O Virtualization (Scalable IOV).

---

# 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

---

# Auxiliary Bus

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> Reference for Auxiliary Bus.

<a id="rst-auxiliary-bus-1"></a>
<a id="rst-auxiliary-bus"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->


In some subsystems, the functionality of the core device (PCI/ACPI/other) is
too complex for a single device to be managed by a monolithic driver (e.g.
Sound Open Firmware), multiple devices might implement a common intersection
of functionality (e.g. NICs + RDMA), or a driver may want to export an
interface for another subsystem to drive (e.g. SIOV Physical Function export
Virtual Function management).  A split of the functionality into child-
devices representing sub-domains of functionality makes it possible to
compartmentalize, layer, and distribute domain-specific concerns via a Linux
device-driver model.

An example for this kind of requirement is the audio subsystem where a
single IP is handling multiple entities such as HDMI, Soundwire, local
devices such as mics/speakers etc. The split for the core's functionality
can be arbitrary or be defined by the DSP firmware topology and include
hooks for test/debug. This allows for the audio core device to be minimal
and focused on hardware-specific control and communication.

Each auxiliary_device represents a part of its parent functionality. The
generic behavior can be extended and specialized as needed by encapsulating
an auxiliary_device within other domain-specific structures and the use of
.ops callbacks. Devices on the auxiliary bus do not share any structures and
the use of a communication channel with the parent is domain-specific.

Note that ops are intended as a way to augment instance behavior within a
class of auxiliary devices, it is not the mechanism for exporting common
infrastructure from the parent. Consider `EXPORT_SYMBOL_NS()` to convey
infrastructure from the parent module to the auxiliary module(s).


<a id="rst-when-should-the-auxiliary-bus-be-used"></a>

## When Should the Auxiliary Bus Be Used


The auxiliary bus is to be used when a driver and one or more kernel
modules, who share a common header file with the driver, need a mechanism to
connect and provide access to a shared object allocated by the
auxiliary_device's registering driver.  The registering driver for the
auxiliary_device(s) and the kernel module(s) registering auxiliary_drivers
can be from the same subsystem, or from multiple subsystems.

The emphasis here is on a common generic interface that keeps subsystem
customization out of the bus infrastructure.

One example is a PCI network device that is RDMA-capable and exports a child
device to be driven by an auxiliary_driver in the RDMA subsystem.  The PCI
driver allocates and registers an auxiliary_device for each physical
function on the NIC.  The RDMA driver registers an auxiliary_driver that
claims each of these auxiliary_devices.  This conveys data/ops published by
the parent PCI device/driver to the RDMA auxiliary_driver.

Another use case is for the PCI device to be split out into multiple sub
functions.  For each sub function an auxiliary_device is created.  A PCI sub
function driver binds to such devices that creates its own one or more class
devices.  A PCI sub function auxiliary device is likely to be contained in a
struct with additional attributes such as user defined sub function number
and optional attributes such as resources and a link to the parent device.
These attributes could be used by systemd/udev; and hence should be
initialized before a driver binds to an auxiliary_device.

A key requirement for utilizing the auxiliary bus is that there is no
dependency on a physical bus, device, register accesses or regmap support.
These individual devices split from the core cannot live on the platform bus
as they are not physical devices that are controlled by DT/ACPI.  The same
argument applies for not using MFD in this scenario as MFD relies on
individual function devices being physical devices.


<a id="rst-auxiliary-device-creation"></a>

## Auxiliary Device Creation


#### <a id="c-struct-auxiliary_device"></a>`struct auxiliary_device`

auxiliary device object.

**Definition**

```c
struct auxiliary_device {
    struct device dev;
    const char *name;
    u32 id;
    struct {
        struct xarray irqs;
        struct mutex lock;
        bool irq_dir_exists;
    } sysfs;
};
```

**Members**

- `dev`: Device,
  The release and parent fields of the device structure must be filled
  in
- `name`: Match name found by the auxiliary device driver,
- `id`: unique identitier if multiple devices of the same name are exported,
- `sysfs`: embedded struct which hold all sysfs related fields,
- `sysfs.irqs`: irqs xarray contains irq indices which are used by the device,
- `sysfs.lock`: Synchronize irq sysfs creation,
- `sysfs.irq_dir_exists`: whether "irqs" directory exists,

**Description**

An auxiliary_device represents a part of its parent device's functionality.
It is given a name that, combined with the registering drivers
KBUILD_MODNAME, creates a match_name that is used for driver binding, and an
id that combined with the match_name provide a unique name to register with
the bus subsystem.  For example, a driver registering an auxiliary device is
named 'foo_mod.ko' and the subdevice is named 'foo_dev'.  The match name is
therefore 'foo_mod.foo_dev'.

Registering an auxiliary_device is a three-step process.

First, a 'struct auxiliary_device' needs to be defined or allocated for each
sub-device desired.  The name, id, dev.release, and dev.parent fields of
this structure must be filled in as follows.

The 'name' field is to be given a name that is recognized by the auxiliary
driver.  If two auxiliary_devices with the same match_name, eg
"foo_mod.foo_dev", are registered onto the bus, they must have unique id
values (e.g. "x" and "y") so that the registered devices names are
"foo_mod.foo_dev.x" and "foo_mod.foo_dev.y".  If match_name + id are not
unique, then the device_add fails and generates an error message.

The auxiliary_device.dev.type.release or auxiliary_device.dev.release must
be populated with a non-NULL pointer to successfully register the
auxiliary_device.  This release call is where resources associated with the
auxiliary device must be free'ed.  Because once the device is placed on the
bus the parent driver can not tell what other code may have a reference to
this data.

The auxiliary_device.dev.parent should be set.  Typically to the registering
drivers device.

Second, call [`auxiliary_device_init()`](#c-auxiliary_device_init), which checks several aspects of the
auxiliary_device struct and performs a [`device_initialize()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-device_initialize).  After this step
completes, any error state must have a call to `auxiliary_device_uninit()` in
its resolution path.

The third and final step in registering an auxiliary_device is to perform a
call to `auxiliary_device_add()`, which sets the name of the device and adds
the device to the bus.

```c
#define MY_DEVICE_NAME "foo_dev"

...

struct auxiliary_device *my_aux_dev = my_aux_dev_alloc(xxx);

// Step 1:
my_aux_dev->name = MY_DEVICE_NAME;
my_aux_dev->id = my_unique_id_alloc(xxx);
my_aux_dev->dev.release = my_aux_dev_release;
my_aux_dev->dev.parent = my_dev;

// Step 2:
if (auxiliary_device_init(my_aux_dev))
        goto fail;

// Step 3:
if (auxiliary_device_add(my_aux_dev)) {
        auxiliary_device_uninit(my_aux_dev);
        goto fail;
}

...
```

Unregistering an auxiliary_device is a two-step process to mirror the
register process.  First call `auxiliary_device_delete()`, then call
`auxiliary_device_uninit()`.

```c
auxiliary_device_delete(my_dev->my_aux_dev);
auxiliary_device_uninit(my_dev->my_aux_dev);
```



#### <a id="c-auxiliary_device_init"></a>`auxiliary_device_init()`

```c
int auxiliary_device_init(struct auxiliary_device *auxdev)
```

check auxiliary_device and initialize

**Parameters**

- `struct auxiliary_device *auxdev`: auxiliary device struct

**Description**

This is the second step in the three-step process to register an
auxiliary_device.

When this function returns an error code, then the device_initialize will
*not* have been performed, and the caller will be responsible to free any
memory allocated for the auxiliary_device in the error path directly.

It returns 0 on success.  On success, the device_initialize has been
performed.  After this point any error unwinding will need to include a call
to `auxiliary_device_uninit()`.  In this post-initialize error scenario, a call
to the device's .release callback will be triggered, and all memory clean-up
is expected to be handled there.

#### <a id="c-__auxiliary_device_add"></a>`__auxiliary_device_add()`

```c
int __auxiliary_device_add(struct auxiliary_device *auxdev, const char *modname)
```

add an auxiliary bus device

**Parameters**

- `struct auxiliary_device *auxdev`: auxiliary bus device to add to the bus
- `const char *modname`: name of the parent device's driver module

**Description**

This is the third step in the three-step process to register an
auxiliary_device.

This function must be called after a successful call to
[`auxiliary_device_init()`](#c-auxiliary_device_init), which will perform the device_initialize.  This
means that if this returns an error code, then a call to
`auxiliary_device_uninit()` must be performed so that the .release callback
will be triggered to free the memory associated with the auxiliary_device.

The expectation is that users will call the "auxiliary_device_add" macro so
that the caller's KBUILD_MODNAME is automatically inserted for the modname
parameter.  Only if a user requires a custom name would this version be
called directly.


<a id="rst-auxiliary-device-memory-model-and-lifespan"></a>

### Auxiliary Device Memory Model and Lifespan


The registering driver is the entity that allocates memory for the
auxiliary_device and registers it on the auxiliary bus.  It is important to
note that, as opposed to the platform bus, the registering driver is wholly
responsible for the management of the memory used for the device object.

To be clear the memory for the auxiliary_device is freed in the `release()`
callback defined by the registering driver.  The registering driver should
only call `auxiliary_device_delete()` and then `auxiliary_device_uninit()` when
it is done with the device.  The `release()` function is then automatically
called if and when other code releases their reference to the devices.

A parent object, defined in the shared header file, contains the
auxiliary_device.  It also contains a pointer to the shared object(s), which
also is defined in the shared header.  Both the parent object and the shared
object(s) are allocated by the registering driver.  This layout allows the
auxiliary_driver's registering module to perform a [`container_of()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-container_of) call to go
from the pointer to the auxiliary_device, that is passed during the call to
the auxiliary_driver's probe function, up to the parent object, and then
have access to the shared object(s).

The memory for the shared object(s) must have a lifespan equal to, or
greater than, the lifespan of the memory for the auxiliary_device.  The
auxiliary_driver should only consider that the shared object is valid as
long as the auxiliary_device is still registered on the auxiliary bus.  It
is up to the registering driver to manage (e.g. free or keep available) the
memory for the shared object beyond the life of the auxiliary_device.

The registering driver must unregister all auxiliary devices before its own
driver.`remove()` is completed.  An easy way to ensure this is to use the
`devm_add_action_or_reset()` call to register a function against the parent
device which unregisters the auxiliary device object(s).

Finally, any operations which operate on the auxiliary devices must continue
to function (if only to return an error) after the registering driver
unregisters the auxiliary device.


<a id="rst-auxiliary-drivers"></a>

## Auxiliary Drivers


#### <a id="c-struct-auxiliary_driver"></a>`struct auxiliary_driver`

Definition of an auxiliary bus driver

**Definition**

```c
struct auxiliary_driver {
    int (*probe)(struct auxiliary_device *auxdev, const struct auxiliary_device_id *id);
    void (*remove)(struct auxiliary_device *auxdev);
    void (*shutdown)(struct auxiliary_device *auxdev);
    int (*suspend)(struct auxiliary_device *auxdev, pm_message_t state);
    int (*resume)(struct auxiliary_device *auxdev);
    const char *name;
    struct device_driver driver;
    const struct auxiliary_device_id *id_table;
};
```

**Members**

- `probe`: Called when a matching device is added to the bus.
- `remove`: Called when device is removed from the bus.
- `shutdown`: Called at shut-down time to quiesce the device.
- `suspend`: Called to put the device to sleep mode. Usually to a power state.
- `resume`: Called to bring a device from sleep mode.
- `name`: Driver name.
- `driver`: Core driver structure.
- `id_table`: Table of devices this driver should match on the bus.

**Description**

Auxiliary drivers follow the standard driver model convention, where
discovery/enumeration is handled by the core, and drivers provide `probe()`
and `remove()` methods. They support power management and shutdown
notifications using the standard conventions.

Auxiliary drivers register themselves with the bus by calling
`auxiliary_driver_register()`. The id_table contains the match_names of
auxiliary devices that a driver can bind with.

```c
static const struct auxiliary_device_id my_auxiliary_id_table[] = {
        { .name = "foo_mod.foo_dev" },
        {},
};

MODULE_DEVICE_TABLE(auxiliary, my_auxiliary_id_table);

struct auxiliary_driver my_drv = {
        .name = "myauxiliarydrv",
        .id_table = my_auxiliary_id_table,
        .probe = my_drv_probe,
        .remove = my_drv_remove
};
```

#### <a id="c-module_auxiliary_driver"></a>`module_auxiliary_driver()`

```c
module_auxiliary_driver(__auxiliary_driver)
```

Helper macro for registering an auxiliary driver

**Parameters**

- `__auxiliary_driver`: auxiliary driver struct

**Description**

Helper macro for auxiliary drivers which do not do anything special in
module init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)

```c
module_auxiliary_driver(my_drv);
```



#### <a id="c-__auxiliary_driver_register"></a>`__auxiliary_driver_register()`

```c
int __auxiliary_driver_register(struct auxiliary_driver *auxdrv, struct module *owner, const char *modname)
```

register a driver for auxiliary bus devices

**Parameters**

- `struct auxiliary_driver *auxdrv`: auxiliary_driver structure
- `struct module *owner`: owning module/driver
- `const char *modname`: KBUILD_MODNAME for parent driver

**Description**

The expectation is that users will call the "auxiliary_driver_register"
macro so that the caller's KBUILD_MODNAME is automatically inserted for the
modname parameter.  Only if a user requires a custom name would this version
be called directly.

#### <a id="c-auxiliary_driver_unregister"></a>`auxiliary_driver_unregister()`

```c
void auxiliary_driver_unregister(struct auxiliary_driver *auxdrv)
```

unregister a driver

**Parameters**

- `struct auxiliary_driver *auxdrv`: auxiliary_driver structure


<a id="rst-example-usage"></a>

## Example Usage


Auxiliary devices are created and registered by a subsystem-level core
device that needs to break up its functionality into smaller fragments. One
way to extend the scope of an auxiliary_device is to encapsulate it within a
domain-specific structure defined by the parent device. This structure
contains the auxiliary_device and any associated shared data/callbacks
needed to establish the connection with the parent.

An example is:

```c
 struct foo {
      struct auxiliary_device auxdev;
      void (*connect)(struct auxiliary_device *auxdev);
      void (*disconnect)(struct auxiliary_device *auxdev);
      void *data;
};
```

The parent device then registers the auxiliary_device by calling
[`auxiliary_device_init()`](#c-auxiliary_device_init), and then `auxiliary_device_add()`, with the pointer
to the auxdev member of the above structure. The parent provides a name for
the auxiliary_device that, combined with the parent's KBUILD_MODNAME,
creates a match_name that is be used for matching and binding with a driver.

Whenever an auxiliary_driver is registered, based on the match_name, the
auxiliary_driver's `probe()` is invoked for the matching devices.  The
auxiliary_driver can also be encapsulated inside custom drivers that make
the core device's functionality extensible by adding additional
domain-specific ops as follows:

```c
struct my_ops {
        void (*send)(struct auxiliary_device *auxdev);
        void (*receive)(struct auxiliary_device *auxdev);
};


struct my_driver {
        struct auxiliary_driver auxiliary_drv;
        const struct my_ops ops;
};
```

An example of this type of usage is:

```c
const struct auxiliary_device_id my_auxiliary_id_table[] = {
        { .name = "foo_mod.foo_dev" },
        { },
};

const struct my_ops my_custom_ops = {
        .send = my_tx,
        .receive = my_rx,
};

const struct my_driver my_drv = {
        .auxiliary_drv = {
                .name = "myauxiliarydrv",
                .id_table = my_auxiliary_id_table,
                .probe = my_probe,
                .remove = my_remove,
                .shutdown = my_shutdown,
        },
        .ops = my_custom_ops,
};
```

Please note that such custom ops approach is valid, but it is hard to implement
it right without global locks per-device to protect from auxiliary_drv removal
during call to that ops. In addition, this implementation lacks proper module
dependency, which causes to load/unload races between auxiliary parent and devices
modules.

The most easiest way to provide these ops reliably without needing to
have a lock is to EXPORT_SYMBOL*() them and rely on already existing
modules infrastructure for validity and correct dependencies chains.

---

# EISA bus support

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> This document groups random notes about porting EISA drivers to the new EISA/sysfs API.

<a id="rst-eisa-bus-support"></a>

**Author:** Marc Zyngier &lt;[maz@wild-wind.fr.eu.org](<mailto:maz@wild-wind.fr.eu.org>)&gt;

This document groups random notes about porting EISA drivers to the new EISA/sysfs API.

Starting from version 2.5.59, the EISA bus is almost given the same status as other much more mainstream buses such as PCI or USB. This has been possible through sysfs, which defines a nice enough set of abstractions to manage buses, devices and drivers.

Although the new API is quite simple to use, converting existing drivers to the new infrastructure is not an easy task (mostly because detection code is generally also used to probe ISA cards). Moreover, most EISA drivers are among the oldest Linux drivers so, as you can imagine, some dust has settled here over the years.

The EISA infrastructure is made up of three parts:

> - The bus code implements most of the generic code. It is shared among all the architectures that the EISA code runs on. It implements bus probing (detecting EISA cards available on the bus), allocates I/O resources, allows fancy naming through sysfs, and offers interfaces for driver to register.
>
> - The bus root driver implements the glue between the bus hardware and the generic bus code. It is responsible for discovering the device implementing the bus, and setting it up to be latter probed by the bus code. This can go from something as simple as reserving an I/O region on x86, to the rather more complex, like the hppa EISA code. This is the part to implement in order to have EISA running on an "new" platform.
>
> - The driver offers the bus a list of devices that it manages, and implements the necessary callbacks to probe and release devices whenever told to.

Every function/structure below lives in &lt;linux/eisa.h&gt;, which depends heavily on &lt;linux/device.h&gt;.

<a id="rst-bus-root-driver"></a>

## Bus root driver



```text
int eisa_root_register (struct eisa_root_device *root);
```

The eisa_root_register function is used to declare a device as the root of an EISA bus. The eisa_root_device structure holds a reference to this device, as well as some parameters for probing purposes:



```text
struct eisa_root_device {
        struct device   *dev;    /* Pointer to bridge device */
        struct resource *res;
        unsigned long    bus_base_addr;
        int              slots;  /* Max slot number */
        int              force_probe; /* Probe even when no slot 0 */
        u64              dma_mask; /* from bridge device */
        int              bus_nr; /* Set by eisa_root_register */
        struct resource  eisa_root_res; /* ditto */
};
```


<table>
<tbody>
<tr>
<td>


node

</td>
<td>


used for eisa_root_register internal purpose

</td>
</tr>
<tr>
<td>


dev

</td>
<td>


pointer to the root device

</td>
</tr>
<tr>
<td>


res

</td>
<td>


root device I/O resource

</td>
</tr>
<tr>
<td>


bus_base_addr

</td>
<td>


slot 0 address on this bus

</td>
</tr>
<tr>
<td>


slots

</td>
<td>


max slot number to probe

</td>
</tr>
<tr>
<td>


force_probe

</td>
<td>


Probe even when slot 0 is empty (no EISA mainboard)

</td>
</tr>
<tr>
<td>


dma_mask

</td>
<td>


Default DMA mask. Usually the bridge device dma_mask.

</td>
</tr>
<tr>
<td>


bus_nr

</td>
<td>


unique bus id, set by eisa_root_register

</td>
</tr>
</tbody>
</table>

<a id="rst-driver"></a>

## Driver



```text
int eisa_driver_register (struct eisa_driver *edrv);
void eisa_driver_unregister (struct eisa_driver *edrv);
```

Clear enough ?



```text
struct eisa_device_id {
        char sig[EISA_SIG_LEN];
        unsigned long driver_data;
};

struct eisa_driver {
        const struct eisa_device_id *id_table;
        struct device_driver         driver;
};
```


<table>
<tbody>
<tr>
<td>


id_table

</td>
<td>


an array of NULL terminated EISA id strings, followed by an empty string. Each string can optionally be paired with a driver-dependent value (driver_data).

</td>
</tr>
<tr>
<td>


driver

</td>
<td>


a generic driver, such as described in [Documentation/driver-api/driver-model/driver.rst](/kernel/hardware/driver-api/driver-model/driver.md). Only .name, .probe and .remove members are mandatory.

</td>
</tr>
</tbody>
</table>

An example is the 3c59x driver:



```text
static struct eisa_device_id vortex_eisa_ids[] = {
        { "TCM5920", EISA_3C592_OFFSET },
        { "TCM5970", EISA_3C597_OFFSET },
        { "" }
};

static struct eisa_driver vortex_eisa_driver = {
        .id_table = vortex_eisa_ids,
        .driver   = {
                .name    = "3c59x",
                .probe   = vortex_eisa_probe,
                .remove  = vortex_eisa_remove
        }
};
```

<a id="rst-device"></a>

## Device

The sysfs framework calls .probe and .remove functions upon device discovery and removal (note that the .remove function is only called when driver is built as a module).

Both functions are passed a pointer to a 'struct device', which is encapsulated in a 'struct eisa_device' described as follows:



```text
struct eisa_device {
        struct eisa_device_id id;
        int                   slot;
        int                   state;
        unsigned long         base_addr;
        struct resource       res[EISA_MAX_RESOURCES];
        u64                   dma_mask;
        struct device         dev; /* generic device */
};
```


<table>
<tbody>
<tr>
<td>


id

</td>
<td>


EISA id, as read from device. id.driver_data is set from the matching driver EISA id.

</td>
</tr>
<tr>
<td>


slot

</td>
<td>


slot number which the device was detected on

</td>
</tr>
<tr>
<td>


state

</td>
<td>


set of flags indicating the state of the device. Current flags are EISA_CONFIG_ENABLED and EISA_CONFIG_FORCED.

</td>
</tr>
<tr>
<td>


res

</td>
<td>


set of four 256 bytes I/O regions allocated to this device

</td>
</tr>
<tr>
<td>


dma_mask

</td>
<td>


DMA mask set from the parent device.

</td>
</tr>
<tr>
<td>


dev

</td>
<td>


generic device (see [Documentation/driver-api/driver-model/device.rst](/kernel/hardware/driver-api/driver-model/device.md))

</td>
</tr>
</tbody>
</table>

You can get the 'struct eisa_device' from 'struct device' using the 'to_eisa_device' macro.

<a id="rst-misc-stuff"></a>

## Misc stuff



```text
void eisa_set_drvdata (struct eisa_device *edev, void *data);
```

Stores data into the device's driver_data area.



```text
void *eisa_get_drvdata (struct eisa_device *edev):
```

Gets the pointer previously stored into the device's driver_data area.



```text
int eisa_get_region_index (void *addr);
```

Returns the region number (0 &lt;= x &lt; EISA_MAX_RESOURCES) of a given address.

<a id="rst-kernel-parameters"></a>

## Kernel parameters

- **eisa_bus.enable_dev**

  A comma-separated list of slots to be enabled, even if the firmware set the card as disabled. The driver must be able to properly initialize the device in such conditions.

- **eisa_bus.disable_dev**

  A comma-separated list of slots to be disabled, even if the firmware set the card as enabled. The driver won't be called to handle this device.

- **virtual_root.force_probe**

  Force the probing code to probe EISA slots even when it cannot find an EISA compliant mainboard (nothing appears on slot 0). Defaults to 0 (don't force), and set to 1 (force probing) when CONFIG_EISA_VLB_PRIMING is set.

<a id="rst-random-notes"></a>

## Random notes

Converting an EISA driver to the new API mostly involves *deleting* code (since probing is now in the core EISA code). Unfortunately, most drivers share their probing routine between ISA, and EISA. Special care must be taken when ripping out the EISA code, so other buses won't suffer from these surgical strikes...

You *must not* expect any EISA device to be detected when returning from eisa_driver_register, since the chances are that the bus has not yet been probed. In fact, that's what happens most of the time (the bus root driver usually kicks in rather late in the boot process). Unfortunately, most drivers are doing the probing by themselves, and expect to have explored the whole machine when they exit their probe routine.

For example, switching your favorite EISA SCSI card to the "hotplug" model is "the right thing"(tm).

<a id="rst-thanks"></a>

## Thanks

I'd like to thank the following people for their help:

- Xavier Benigni for lending me a wonderful Alpha Jensen,

- James Bottomley, Jeff Garzik for getting this stuff into the kernel,

- Andries Brouwer for contributing numerous EISA ids,

- Catrin Jones for coping with far too many machines at home.

---

# Firewire (IEEE 1394) driver Interface Guide

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> use/maintain+any resource on IEEE 1394 bus.

<a id="rst-firewire-ieee-1394-driver-interface-guide"></a>

<a id="rst-introduction-and-overview"></a>

## Introduction and Overview

- **The Linux FireWire subsystem adds some interfaces into the Linux system to**

  use/maintain+any resource on IEEE 1394 bus.

The main purpose of these interfaces is to access address space on each node on IEEE 1394 bus by ISO/IEC 13213 (IEEE 1212) procedure, and to control isochronous resources on the bus by IEEE 1394 procedure.

Two types of interfaces are added, according to consumers of the interface. A set of userspace interfaces is available via `firewire character devices`. A set of kernel interfaces is available via exported symbols in `firewire-core` module.

<a id="rst-firewire-char-device-data-structures"></a>

## Firewire char device data structures




```text
What:           /dev/fw[0-9]+
Date:           May 2007
KernelVersion:  2.6.22
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                The character device files /dev/fw* are the interface between
                firewire-core and IEEE 1394 device drivers implemented in
                userspace.  The ioctl(2)- and read(2)-based ABI is defined and
                documented in <linux/firewire-cdev.h>.

                This ABI offers most of the features which firewire-core also
                exposes to kernelspace IEEE 1394 drivers.

                Each /dev/fw* is associated with one IEEE 1394 node, which can
                be remote or local nodes.  Operations on a /dev/fw* file have
                different scope:

                  - The 1394 node which is associated with the file:

                          - Asynchronous request transmission
                          - Get the Configuration ROM
                          - Query node ID
                          - Query maximum speed of the path between this node
                            and local node

                  - The 1394 bus (i.e. "card") to which the node is attached to:

                          - Isochronous stream transmission and reception
                          - Asynchronous stream transmission and reception
                          - Asynchronous broadcast request transmission
                          - PHY packet transmission and reception
                          - Allocate, reallocate, deallocate isochronous
                            resources (channels, bandwidth) at the bus's IRM
                          - Query node IDs of local node, root node, IRM, bus
                            manager
                          - Query cycle time
                          - Bus reset initiation, bus reset event reception

                  - All 1394 buses:

                          - Allocation of IEEE 1212 address ranges on the local
                            link layers, reception of inbound requests to such
                            an address range, asynchronous response transmission
                            to inbound requests
                          - Addition of descriptors or directories to the local
                            nodes' Configuration ROM

                Due to the different scope of operations and in order to let
                userland implement different access permission models, some
                operations are restricted to /dev/fw* files that are associated
                with a local node:

                          - Addition of descriptors or directories to the local
                            nodes' Configuration ROM
                          - PHY packet transmission and reception

                A /dev/fw* file remains associated with one particular node
                during its entire life time.  Bus topology changes, and hence
                node ID changes, are tracked by firewire-core.  ABI users do not
                need to be aware of topology.

                The following file operations are supported:

                open(2)
                    Currently the only useful flags are O_RDWR.

                ioctl(2)
                    Initiate various actions.  Some take immediate effect, others
                    are performed asynchronously while or after the ioctl returns.
                    See the inline documentation in <linux/firewire-cdev.h> for
                    descriptions of all ioctls.

                poll(2), select(2), epoll_wait(2) etc.
                    Watch for events to become available to be read.

                read(2)
                    Receive various events.  There are solicited events like
                    outbound asynchronous transaction completion or isochronous
                    buffer completion, and unsolicited events such as bus resets,
                    request reception, or PHY packet reception.  Always use a read
                    buffer which is large enough to receive the largest event that
                    could ever arrive.  See <linux/firewire-cdev.h> for descriptions
                    of all event types and for which ioctls affect reception of
                    events.

                mmap(2)
                    Allocate a DMA buffer for isochronous reception or transmission
                    and map it into the process address space.  The arguments should
                    be used as follows:  addr = NULL, length = the desired buffer
                    size, i.e. number of packets times size of largest packet,
                    prot = at least PROT_READ for reception and at least PROT_WRITE
                    for transmission, flags = MAP_SHARED, fd = the handle to the
                    /dev/fw*, offset = 0.

                Isochronous reception works in packet-per-buffer fashion except
                for multichannel reception which works in buffer-fill mode.

                munmap(2)
                    Unmap the isochronous I/O buffer from the process address space.

                close(2)
                    Besides stopping and freeing I/O contexts that were associated
                    with the file descriptor, back out any changes to the local
                    nodes' Configuration ROM.  Deallocate isochronous channels and
                    bandwidth at the IRM that were marked for kernel-assisted
                    re- and deallocation.

Users:          libraw1394;
                libdc1394;
                libhinawa;
                tools like linux-firewire-utils, fwhack, ...

```



#### <a id="c-struct-fw_cdev_event_common"></a>`struct fw_cdev_event_common`

Common part of all fw_cdev_event_* types

**Definition**

```c
struct fw_cdev_event_common {
    __u64 closure;
    __u32 type;
};
```

**Members**

- `closure`: For arbitrary use by userspace
- `type`: Discriminates the fw_cdev_event_* types

**Description**

This struct may be used to access generic members of all fw_cdev_event_*
types regardless of the specific type.

Data passed in the **closure** field for a request will be returned in the
corresponding event.  It is big enough to hold a pointer on all platforms.
The ioctl used to set **closure** depends on the **type** of event.

#### <a id="c-struct-fw_cdev_event_bus_reset"></a>`struct fw_cdev_event_bus_reset`

Sent when a bus reset occurred

**Definition**

```c
struct fw_cdev_event_bus_reset {
    __u64 closure;
    __u32 type;
    __u32 node_id;
    __u32 local_node_id;
    __u32 bm_node_id;
    __u32 irm_node_id;
    __u32 root_node_id;
    __u32 generation;
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_GET_INFO` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_BUS_RESET`
- `node_id`: New node ID of this node
- `local_node_id`: Node ID of the local node, i.e. of the controller
- `bm_node_id`: Node ID of the bus manager
- `irm_node_id`: Node ID of the iso resource manager
- `root_node_id`: Node ID of the root node
- `generation`: New bus generation

**Description**

This event is sent when the bus the device belongs to goes through a bus
reset.  It provides information about the new bus configuration, such as
new node ID for this device, new root ID, and others.

If **bm_node_id** is 0xffff right after bus reset it can be reread by an
`FW_CDEV_IOC_GET_INFO` ioctl after bus manager selection was finished.
Kernels with ABI version \< 4 do not set **bm_node_id**.

#### <a id="c-struct-fw_cdev_event_response"></a>`struct fw_cdev_event_response`

Sent when a response packet was received

**Definition**

```c
struct fw_cdev_event_response {
    __u64 closure;
    __u32 type;
    __u32 rcode;
    __u32 length;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_SEND_REQUEST`
  or `FW_CDEV_IOC_SEND_BROADCAST_REQUEST`
  or `FW_CDEV_IOC_SEND_STREAM_PACKET` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_RESPONSE`
- `rcode`: Response code returned by the remote node
- `length`: Data length, i.e. the response's payload size in bytes
- `data`: Payload data, if any

**Description**

This event is sent instead of [`fw_cdev_event_response`](#c-struct-fw_cdev_event_response) if the kernel or the client implements
ABI version \<= 5. It has the lack of time stamp field comparing to [`fw_cdev_event_response2`](#c-struct-fw_cdev_event_response2).

#### <a id="c-struct-fw_cdev_event_response2"></a>`struct fw_cdev_event_response2`

Sent when a response packet was received

**Definition**

```c
struct fw_cdev_event_response2 {
    __u64 closure;
    __u32 type;
    __u32 rcode;
    __u32 length;
    __u32 request_tstamp;
    __u32 response_tstamp;
    __u32 padding;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_SEND_REQUEST`
  or `FW_CDEV_IOC_SEND_BROADCAST_REQUEST`
  or `FW_CDEV_IOC_SEND_STREAM_PACKET` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_RESPONSE`
- `rcode`: Response code returned by the remote node
- `length`: Data length, i.e. the response's payload size in bytes
- `request_tstamp`: The time stamp of isochronous cycle at which the request was sent.
- `response_tstamp`: The time stamp of isochronous cycle at which the response was sent.
- `padding`: Padding to keep the size of structure as multiples of 8 in various architectures
  since 4 byte alignment is used for 8 byte of object type in System V ABI for i386
  architecture.
- `data`: Payload data, if any

**Description**

This event is sent when the stack receives a response to an outgoing request
sent by `FW_CDEV_IOC_SEND_REQUEST` ioctl.  The payload data for responses
carrying data (read and lock responses) follows immediately and can be
accessed through the **data** field.

The event is also generated after conclusions of transactions that do not
involve response packets.  This includes unified write transactions,
broadcast write transactions, and transmission of asynchronous stream
packets.  **rcode** indicates success or failure of such transmissions.

The value of **request_tstamp** expresses the isochronous cycle at which the request was sent to
initiate the transaction. The value of **response_tstamp** expresses the isochronous cycle at which
the response arrived to complete the transaction. Each value is unsigned 16 bit integer
containing three low order bits of second field and all 13 bits of cycle field in format of
CYCLE_TIMER register.

#### <a id="c-struct-fw_cdev_event_request"></a>`struct fw_cdev_event_request`

Old version of [`fw_cdev_event_request2`](#c-struct-fw_cdev_event_request2)

**Definition**

```c
struct fw_cdev_event_request {
    __u64 closure;
    __u32 type;
    __u32 tcode;
    __u64 offset;
    __u32 handle;
    __u32 length;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_ALLOCATE` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_REQUEST`
- `tcode`: Transaction code of the incoming request
- `offset`: The offset into the 48-bit per-node address space
- `handle`: Reference to the kernel-side pending request
- `length`: Data length, i.e. the request's payload size in bytes
- `data`: Incoming data, if any

**Description**

This event is sent instead of [`fw_cdev_event_request2`](#c-struct-fw_cdev_event_request2) if the kernel or
the client implements ABI version \<= 3.  [`fw_cdev_event_request`](#c-struct-fw_cdev_event_request) lacks
essential information; use [`fw_cdev_event_request2`](#c-struct-fw_cdev_event_request2) instead.

#### <a id="c-struct-fw_cdev_event_request2"></a>`struct fw_cdev_event_request2`

Sent on incoming request to an address region

**Definition**

```c
struct fw_cdev_event_request2 {
    __u64 closure;
    __u32 type;
    __u32 tcode;
    __u64 offset;
    __u32 source_node_id;
    __u32 destination_node_id;
    __u32 card;
    __u32 generation;
    __u32 handle;
    __u32 length;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_ALLOCATE` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_REQUEST2`
- `tcode`: Transaction code of the incoming request
- `offset`: The offset into the 48-bit per-node address space
- `source_node_id`: Sender node ID
- `destination_node_id`: Destination node ID
- `card`: The index of the card from which the request came
- `generation`: Bus generation in which the request is valid
- `handle`: Reference to the kernel-side pending request
- `length`: Data length, i.e. the request's payload size in bytes
- `data`: Incoming data, if any

**Description**

This event is sent instead of [`fw_cdev_event_request3`](#c-struct-fw_cdev_event_request3) if the kernel or the client implements
ABI version \<= 5. It has the lack of time stamp field comparing to [`fw_cdev_event_request3`](#c-struct-fw_cdev_event_request3).

#### <a id="c-struct-fw_cdev_event_request3"></a>`struct fw_cdev_event_request3`

Sent on incoming request to an address region

**Definition**

```c
struct fw_cdev_event_request3 {
    __u64 closure;
    __u32 type;
    __u32 tcode;
    __u64 offset;
    __u32 source_node_id;
    __u32 destination_node_id;
    __u32 card;
    __u32 generation;
    __u32 handle;
    __u32 length;
    __u32 tstamp;
    __u32 padding;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_ALLOCATE` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_REQUEST2`
- `tcode`: Transaction code of the incoming request
- `offset`: The offset into the 48-bit per-node address space
- `source_node_id`: Sender node ID
- `destination_node_id`: Destination node ID
- `card`: The index of the card from which the request came
- `generation`: Bus generation in which the request is valid
- `handle`: Reference to the kernel-side pending request
- `length`: Data length, i.e. the request's payload size in bytes
- `tstamp`: The time stamp of isochronous cycle at which the request arrived.
- `padding`: Padding to keep the size of structure as multiples of 8 in various architectures
  since 4 byte alignment is used for 8 byte of object type in System V ABI for i386
  architecture.
- `data`: Incoming data, if any

**Description**

This event is sent when the stack receives an incoming request to an address
region registered using the `FW_CDEV_IOC_ALLOCATE` ioctl.  The request is
guaranteed to be completely contained in the specified region.  Userspace is
responsible for sending the response by `FW_CDEV_IOC_SEND_RESPONSE` ioctl,
using the same **handle**.

The payload data for requests carrying data (write and lock requests)
follows immediately and can be accessed through the **data** field.

Unlike [`fw_cdev_event_request`](#c-struct-fw_cdev_event_request), **tcode** of lock requests is one of the
firewire-core specific `TCODE_LOCK_MASK_SWAP`...`TCODE_LOCK_VENDOR_DEPENDENT`,
i.e. encodes the extended transaction code.

**card** may differ from [`fw_cdev_get_info.card`](#c-struct-fw_cdev_get_info) because requests are received
from all cards of the Linux host.  **source_node_id**, **destination_node_id**, and
**generation** pertain to that card.  Destination node ID and bus generation may
therefore differ from the corresponding fields of the last
[`fw_cdev_event_bus_reset`](#c-struct-fw_cdev_event_bus_reset).

**destination_node_id** may also differ from the current node ID because of a
non-local bus ID part or in case of a broadcast write request.  Note, a
client must call an `FW_CDEV_IOC_SEND_RESPONSE` ioctl even in case of a
broadcast write request; the kernel will then release the kernel-side pending
request but will not actually send a response packet.

In case of a write request to FCP_REQUEST or FCP_RESPONSE, the kernel already
sent a write response immediately after the request was received; in this
case the client must still call an `FW_CDEV_IOC_SEND_RESPONSE` ioctl to
release the kernel-side pending request, though another response won't be
sent.

If the client subsequently needs to initiate requests to the sender node of
an [`fw_cdev_event_request3`](#c-struct-fw_cdev_event_request3), it needs to use a device file with matching
card index, node ID, and generation for outbound requests.

**tstamp** is isochronous cycle at which the request arrived. It is 16 bit integer value and the
higher 3 bits expresses three low order bits of second field in the format of CYCLE_TIME
register and the rest 13 bits expresses cycle field.

#### <a id="c-struct-fw_cdev_event_iso_interrupt"></a>`struct fw_cdev_event_iso_interrupt`

Sent when an iso packet was completed

**Definition**

```c
struct fw_cdev_event_iso_interrupt {
    __u64 closure;
    __u32 type;
    __u32 cycle;
    __u32 header_length;
    __u32 header[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common);
  set by `FW_CDEV_CREATE_ISO_CONTEXT` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_ISO_INTERRUPT`
- `cycle`: Cycle counter of the last completed packet
- `header_length`: Total length of following headers, in bytes
- `header`: Stripped headers, if any

**Description**

This event is sent when the controller has completed an [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet)
with the `FW_CDEV_ISO_INTERRUPT` bit set, when explicitly requested with
`FW_CDEV_IOC_FLUSH_ISO`, or when there have been so many completed packets
without the interrupt bit set that the kernel's internal buffer for **header**
is about to overflow.  (In the last case, ABI versions \< 5 drop header data
up to the next interrupt packet.)

Isochronous transmit events (context type `FW_CDEV_ISO_CONTEXT_TRANSMIT`):

In version 3 and some implementations of version 2 of the ABI, `header_length`
is a multiple of 4 and `header` contains timestamps of all packets up until
the interrupt packet.  The format of the timestamps is as described below for
isochronous reception.  In version 1 of the ABI, `header_length` was 0.

Isochronous receive events (context type `FW_CDEV_ISO_CONTEXT_RECEIVE`):

The headers stripped of all packets up until and including the interrupt
packet are returned in the **header** field.  The amount of header data per
packet is as specified at iso context creation by
[`fw_cdev_create_iso_context.header_size`](#c-struct-fw_cdev_create_iso_context).

Hence, _interrupt.header_length / _context.header_size is the number of
packets received in this interrupt event.  The client can now iterate
through the `mmap()`'ed DMA buffer according to this number of packets and
to the buffer sizes as the client specified in [`fw_cdev_queue_iso`](#c-struct-fw_cdev_queue_iso).

Since version 2 of this ABI, the portion for each packet in _interrupt.header
consists of the 1394 isochronous packet header, followed by a timestamp
quadlet if [`fw_cdev_create_iso_context.header_size`](#c-struct-fw_cdev_create_iso_context) > 4, followed by quadlets
from the packet payload if [`fw_cdev_create_iso_context.header_size`](#c-struct-fw_cdev_create_iso_context) > 8.

Format of 1394 iso packet header:  16 bits data_length, 2 bits tag, 6 bits
channel, 4 bits tcode, 4 bits sy, in big endian byte order.
data_length is the actual received size of the packet without the four
1394 iso packet header bytes.

Format of timestamp:  16 bits invalid, 3 bits cycleSeconds, 13 bits
cycleCount, in big endian byte order.

In version 1 of the ABI, no timestamp quadlet was inserted; instead, payload
data followed directly after the 1394 is header if header_size > 4.
Behaviour of ver. 1 of this ABI is no longer available since ABI ver. 2.

#### <a id="c-struct-fw_cdev_event_iso_interrupt_mc"></a>`struct fw_cdev_event_iso_interrupt_mc`

An iso buffer chunk was completed

**Definition**

```c
struct fw_cdev_event_iso_interrupt_mc {
    __u64 closure;
    __u32 type;
    __u32 completed;
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common);
  set by `FW_CDEV_CREATE_ISO_CONTEXT` ioctl
- `type`: `FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL`
- `completed`: Offset into the receive buffer; data before this offset is valid

**Description**

This event is sent in multichannel contexts (context type
`FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL`) for [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet) buffer
chunks that have been completely filled and that have the
`FW_CDEV_ISO_INTERRUPT` bit set, or when explicitly requested with
`FW_CDEV_IOC_FLUSH_ISO`.

- The buffer is continuously filled with the following data, per packet:
  - the 1394 iso packet header as described at [`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt),
    but in little endian byte order,
  - packet payload (as many bytes as specified in the data_length field of
    the 1394 iso packet header) in big endian byte order,
  - 0...3 padding bytes as needed to align the following trailer quadlet,
  - trailer quadlet, containing the reception timestamp as described at
    [`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt), but in little endian byte order.

Hence the per-packet size is data_length (rounded up to a multiple of 4) + 8.
When processing the data, stop before a packet that would cross the
**completed** offset.

A packet near the end of a buffer chunk will typically spill over into the
next queued buffer chunk.  It is the responsibility of the client to check
for this condition, assemble a broken-up packet from its parts, and not to
re-queue any buffer chunks in which as yet unread packet parts reside.

#### <a id="c-struct-fw_cdev_event_iso_resource"></a>`struct fw_cdev_event_iso_resource`

Iso resources were allocated or freed

**Definition**

```c
struct fw_cdev_event_iso_resource {
    __u64 closure;
    __u32 type;
    __u32 handle;
    __s32 channel;
    __s32 bandwidth;
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common);
  set by`FW_CDEV_IOC_(DE)ALLOCATE_ISO_RESOURCE(_ONCE)` ioctl
- `type`: `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` or
  `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED`
- `handle`: Reference by which an allocated resource can be deallocated
- `channel`: Isochronous channel which was (de)allocated, if any
- `bandwidth`: Bandwidth allocation units which were (de)allocated, if any

**Description**

An `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` event is sent after an isochronous
resource was allocated at the IRM.  The client has to check **channel** and
**bandwidth** for whether the allocation actually succeeded.

An `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED` event is sent after an isochronous
resource was deallocated at the IRM.  It is also sent when automatic
reallocation after a bus reset failed.

**channel** is \<0 if no channel was (de)allocated or if reallocation failed.
**bandwidth** is 0 if no bandwidth was (de)allocated or if reallocation failed.

#### <a id="c-struct-fw_cdev_event_phy_packet"></a>`struct fw_cdev_event_phy_packet`

A PHY packet was transmitted or received

**Definition**

```c
struct fw_cdev_event_phy_packet {
    __u64 closure;
    __u32 type;
    __u32 rcode;
    __u32 length;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_SEND_PHY_PACKET`
  or `FW_CDEV_IOC_RECEIVE_PHY_PACKETS` ioctl
- `type`: `FW_CDEV_EVENT_PHY_PACKET_SENT` or %..._RECEIVED
- `rcode`: `RCODE_`..., indicates success or failure of transmission
- `length`: Data length in bytes
- `data`: Incoming data for `FW_CDEV_IOC_RECEIVE_PHY_PACKETS`. For `FW_CDEV_IOC_SEND_PHY_PACKET`
  the field has the same data in the request, thus the length of 8 bytes.

**Description**

This event is sent instead of [`fw_cdev_event_phy_packet2`](#c-struct-fw_cdev_event_phy_packet2) if the kernel or
the client implements ABI version \<= 5. It has the lack of time stamp field comparing to
[`fw_cdev_event_phy_packet2`](#c-struct-fw_cdev_event_phy_packet2).

#### <a id="c-struct-fw_cdev_event_phy_packet2"></a>`struct fw_cdev_event_phy_packet2`

A PHY packet was transmitted or received with time stamp.

**Definition**

```c
struct fw_cdev_event_phy_packet2 {
    __u64 closure;
    __u32 type;
    __u32 rcode;
    __u32 length;
    __u32 tstamp;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_SEND_PHY_PACKET`
  or `FW_CDEV_IOC_RECEIVE_PHY_PACKETS` ioctl
- `type`: `FW_CDEV_EVENT_PHY_PACKET_SENT2` or `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`
- `rcode`: `RCODE_`..., indicates success or failure of transmission
- `length`: Data length in bytes
- `tstamp`: For `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`, the time stamp of isochronous cycle at
  which the packet arrived. For `FW_CDEV_EVENT_PHY_PACKET_SENT2` and non-ping packet,
  the time stamp of isochronous cycle at which the packet was sent. For ping packet,
  the tick count for round-trip time measured by 1394 OHCI controller.
- `data`: Incoming data

**Description**

The time stamp of isochronous cycle at which either the response was sent for
`FW_CDEV_EVENT_PHY_PACKET_SENT2` or the request arrived for
`FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`.

If **type** is `FW_CDEV_EVENT_PHY_PACKET_SENT2`, **length** is 8 and **data** consists of the two PHY
packet quadlets to be sent, in host byte order,

If **type** is `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`, **length** is 8 and **data** consists of the two PHY
packet quadlets, in host byte order.

For `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`, the **tstamp** is the isochronous cycle at which the
packet arrived. It is 16 bit integer value and the higher 3 bits expresses three low order bits
of second field and the rest 13 bits expresses cycle field in the format of CYCLE_TIME register.

For `FW_CDEV_EVENT_PHY_PACKET_SENT2`, the **tstamp** has different meanings whether to sent the
packet for ping or not. If it's not for ping, the **tstamp** is the isochronous cycle at which the
packet was sent, and use the same format as the case of `FW_CDEV_EVENT_PHY_PACKET_SENT2`. If it's
for ping, the **tstamp** is for round-trip time measured by 1394 OHCI controller with 42.195 MHz
resolution.

#### <a id="c-union-fw_cdev_event"></a>`union fw_cdev_event`

Convenience union of fw_cdev_event_* types

**Definition**

```c
union fw_cdev_event {
    struct fw_cdev_event_common             common;
    struct fw_cdev_event_bus_reset          bus_reset;
    struct fw_cdev_event_response           response;
    struct fw_cdev_event_request            request;
    struct fw_cdev_event_request2           request2;
    struct fw_cdev_event_iso_interrupt      iso_interrupt;
    struct fw_cdev_event_iso_interrupt_mc   iso_interrupt_mc;
    struct fw_cdev_event_iso_resource       iso_resource;
    struct fw_cdev_event_phy_packet         phy_packet;
    struct fw_cdev_event_request3           request3;
    struct fw_cdev_event_response2          response2;
    struct fw_cdev_event_phy_packet2        phy_packet2;
};
```

**Members**

- `common`: Valid for all types
- `bus_reset`: Valid if **common.type** == `FW_CDEV_EVENT_BUS_RESET`
- `response`: Valid if **common.type** == `FW_CDEV_EVENT_RESPONSE`
- `request`: Valid if **common.type** == `FW_CDEV_EVENT_REQUEST`
- `request2`: Valid if **common.type** == `FW_CDEV_EVENT_REQUEST2`
- `iso_interrupt`: Valid if **common.type** == `FW_CDEV_EVENT_ISO_INTERRUPT`
- `iso_interrupt_mc`: Valid if **common.type** ==
  `FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL`
- `iso_resource`: Valid if **common.type** ==
  `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` or
  `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED`
- `phy_packet`: Valid if **common.type** ==
  `FW_CDEV_EVENT_PHY_PACKET_SENT` or
  `FW_CDEV_EVENT_PHY_PACKET_RECEIVED`
- `request3`: Valid if **common.type** == `FW_CDEV_EVENT_REQUEST3`
- `response2`: Valid if **common.type** == `FW_CDEV_EVENT_RESPONSE2`
- `phy_packet2`: Valid if **common.type** == `FW_CDEV_EVENT_PHY_PACKET_SENT2` or
  `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`

**Description**

Convenience union for userspace use.  Events could be read(2) into an
appropriately aligned char buffer and then cast to this union for further
processing.  Note that for a request, response or iso_interrupt event,
the data\[\] or header\[\] may make the size of the full event larger than
sizeof(union fw_cdev_event).  Also note that if you attempt to read(2)
an event into a buffer that is not large enough for it, the data that does
not fit will be discarded so that the next read(2) will return a new event.

#### <a id="c-struct-fw_cdev_get_info"></a>`struct fw_cdev_get_info`

General purpose information ioctl

**Definition**

```c
struct fw_cdev_get_info {
    __u32 version;
    __u32 rom_length;
    __u64 rom;
    __u64 bus_reset;
    __u64 bus_reset_closure;
    __u32 card;
};
```

**Members**

- `version`: The version field is just a running serial number.  Both an
  input parameter (ABI version implemented by the client) and
  output parameter (ABI version implemented by the kernel).
  A client shall fill in the ABI **version** for which the client
  was implemented.  This is necessary for forward compatibility.
- `rom_length`: If **rom** is non-zero, up to **rom_length** bytes of Configuration
  ROM will be copied into that user space address.  In either
  case, **rom_length** is updated with the actual length of the
  Configuration ROM.
- `rom`: If non-zero, address of a buffer to be filled by a copy of the
  device's Configuration ROM
- `bus_reset`: If non-zero, address of a buffer to be filled by a
  [`struct fw_cdev_event_bus_reset`](#c-struct-fw_cdev_event_bus_reset) with the current state
  of the bus.  This does not cause a bus reset to happen.
- `bus_reset_closure`: Value of `closure` in this and subsequent bus reset events
- `card`: The index of the card this device belongs to

**Description**

The `FW_CDEV_IOC_GET_INFO` ioctl is usually the very first one which a client
performs right after it opened a /dev/fw* file.

As a side effect, reception of `FW_CDEV_EVENT_BUS_RESET` events to be read(2)
is started by this ioctl.

#### <a id="c-struct-fw_cdev_send_request"></a>`struct fw_cdev_send_request`

Send an asynchronous request packet

**Definition**

```c
struct fw_cdev_send_request {
    __u32 tcode;
    __u32 length;
    __u64 offset;
    __u64 closure;
    __u64 data;
    __u32 generation;
};
```

**Members**

- `tcode`: Transaction code of the request
- `length`: Length of outgoing payload, in bytes
- `offset`: 48-bit offset at destination node
- `closure`: Passed back to userspace in the response event
- `data`: Userspace pointer to payload
- `generation`: The bus generation where packet is valid

**Description**

Send a request to the device.  This ioctl implements all outgoing requests. Both quadlet and
block request specify the payload as a pointer to the data in the **data** field. Once the
transaction completes, the kernel writes either [`fw_cdev_event_response`](#c-struct-fw_cdev_event_response) event or
[`fw_cdev_event_response`](#c-struct-fw_cdev_event_response) event back. The **closure** field is passed back to user space in the
response event.

#### <a id="c-struct-fw_cdev_send_response"></a>`struct fw_cdev_send_response`

Send an asynchronous response packet

**Definition**

```c
struct fw_cdev_send_response {
    __u32 rcode;
    __u32 length;
    __u64 data;
    __u32 handle;
};
```

**Members**

- `rcode`: Response code as determined by the userspace handler
- `length`: Length of outgoing payload, in bytes
- `data`: Userspace pointer to payload
- `handle`: The handle from the [`fw_cdev_event_request`](#c-struct-fw_cdev_event_request)

**Description**

Send a response to an incoming request.  By setting up an address range using
the `FW_CDEV_IOC_ALLOCATE` ioctl, userspace can listen for incoming requests.  An
incoming request will generate an `FW_CDEV_EVENT_REQUEST`, and userspace must
send a reply using this ioctl.  The event has a handle to the kernel-side
pending transaction, which should be used with this ioctl.

#### <a id="c-struct-fw_cdev_allocate"></a>`struct fw_cdev_allocate`

Allocate a CSR in an address range

**Definition**

```c
struct fw_cdev_allocate {
    __u64 offset;
    __u64 closure;
    __u32 length;
    __u32 handle;
    __u64 region_end;
};
```

**Members**

- `offset`: Start offset of the address range
- `closure`: To be passed back to userspace in request events
- `length`: Length of the CSR, in bytes
- `handle`: Handle to the allocation, written by the kernel
- `region_end`: First address above the address range (added in ABI v4, 2.6.36)

**Description**

Allocate an address range in the 48-bit address space on the local node
(the controller).  This allows userspace to listen for requests with an
offset within that address range.  Every time when the kernel receives a
request within the range, an [`fw_cdev_event_request2`](#c-struct-fw_cdev_event_request2) event will be emitted.
(If the kernel or the client implements ABI version \<= 3, an
[`fw_cdev_event_request`](#c-struct-fw_cdev_event_request) will be generated instead.)

The **closure** field is passed back to userspace in these request events.
The **handle** field is an out parameter, returning a handle to the allocated
range to be used for later deallocation of the range.

The address range is allocated on all local nodes.  The address allocation
is exclusive except for the FCP command and response registers.  If an
exclusive address region is already in use, the ioctl fails with errno set
to `EBUSY`.

If kernel and client implement ABI version >= 4, the kernel looks up a free
spot of size **length** inside \[**offset**..**region_end**) and, if found, writes
the start address of the new CSR back in **offset**.  I.e. **offset** is an
in and out parameter.  If this automatic placement of a CSR in a bigger
address range is not desired, the client simply needs to set **region_end**
= **offset** + **length**.

If the kernel or the client implements ABI version \<= 3, **region_end** is
ignored and effectively assumed to be **offset** + **length**.

**region_end** is only present in a kernel header >= 2.6.36.  If necessary,
this can for example be tested by #ifdef FW_CDEV_EVENT_REQUEST2.

#### <a id="c-struct-fw_cdev_deallocate"></a>`struct fw_cdev_deallocate`

Free a CSR address range or isochronous resource

**Definition**

```c
struct fw_cdev_deallocate {
    __u32 handle;
};
```

**Members**

- `handle`: Handle to the address range or iso resource, as returned by the
  kernel when the range or resource was allocated

#### <a id="c-struct-fw_cdev_initiate_bus_reset"></a>`struct fw_cdev_initiate_bus_reset`

Initiate a bus reset

**Definition**

```c
struct fw_cdev_initiate_bus_reset {
    __u32 type;
};
```

**Members**

- `type`: `FW_CDEV_SHORT_RESET` or `FW_CDEV_LONG_RESET`

**Description**

Initiate a bus reset for the bus this device is on.  The bus reset can be
either the original (long) bus reset or the arbitrated (short) bus reset
introduced in 1394a-2000.

The ioctl returns immediately.  A subsequent [`fw_cdev_event_bus_reset`](#c-struct-fw_cdev_event_bus_reset)
indicates when the reset actually happened.  Since ABI v4, this may be
considerably later than the ioctl because the kernel ensures a grace period
between subsequent bus resets as per IEEE 1394 bus management specification.

#### <a id="c-struct-fw_cdev_add_descriptor"></a>`struct fw_cdev_add_descriptor`

Add contents to the local node's config ROM

**Definition**

```c
struct fw_cdev_add_descriptor {
    __u32 immediate;
    __u32 key;
    __u64 data;
    __u32 length;
    __u32 handle;
};
```

**Members**

- `immediate`: If non-zero, immediate key to insert before pointer
- `key`: Upper 8 bits of root directory pointer
- `data`: Userspace pointer to contents of descriptor block
- `length`: Length of descriptor block data, in quadlets
- `handle`: Handle to the descriptor, written by the kernel

**Description**

Add a descriptor block and optionally a preceding immediate key to the local
node's Configuration ROM.

The **key** field specifies the upper 8 bits of the descriptor root directory
pointer and the **data** and **length** fields specify the contents. The **key**
should be of the form 0xXX000000. The offset part of the root directory entry
will be filled in by the kernel.

If not 0, the **immediate** field specifies an immediate key which will be
inserted before the root directory pointer.

**immediate**, **key**, and **data** array elements are CPU-endian quadlets.

If successful, the kernel adds the descriptor and writes back a **handle** to
the kernel-side object to be used for later removal of the descriptor block
and immediate key.  The kernel will also generate a bus reset to signal the
change of the Configuration ROM to other nodes.

This ioctl affects the Configuration ROMs of all local nodes.
The ioctl only succeeds on device files which represent a local node.

#### <a id="c-struct-fw_cdev_remove_descriptor"></a>`struct fw_cdev_remove_descriptor`

Remove contents from the Configuration ROM

**Definition**

```c
struct fw_cdev_remove_descriptor {
    __u32 handle;
};
```

**Members**

- `handle`: Handle to the descriptor, as returned by the kernel when the
  descriptor was added

**Description**

Remove a descriptor block and accompanying immediate key from the local
nodes' Configuration ROMs.  The kernel will also generate a bus reset to
signal the change of the Configuration ROM to other nodes.

#### <a id="c-struct-fw_cdev_create_iso_context"></a>`struct fw_cdev_create_iso_context`

Create a context for isochronous I/O

**Definition**

```c
struct fw_cdev_create_iso_context {
    __u32 type;
    __u32 header_size;
    __u32 channel;
    __u32 speed;
    __u64 closure;
    __u32 handle;
};
```

**Members**

- `type`: `FW_CDEV_ISO_CONTEXT_TRANSMIT` or `FW_CDEV_ISO_CONTEXT_RECEIVE` or
  `FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL`
- `header_size`: Header size to strip in single-channel reception
- `channel`: Channel to bind to in single-channel reception or transmission
- `speed`: Transmission speed
- `closure`: To be returned in [`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt) or
  `fw_cdev_event_iso_interrupt_multichannel`
- `handle`: Handle to context, written back by kernel

**Description**

Prior to sending or receiving isochronous I/O, a context must be created.
The context records information about the transmit or receive configuration
and typically maps to an underlying hardware resource.  A context is set up
for either sending or receiving.  It is bound to a specific isochronous
**channel**.

In case of multichannel reception, **header_size** and **channel** are ignored
and the channels are selected by `FW_CDEV_IOC_SET_ISO_CHANNELS`.

For `FW_CDEV_ISO_CONTEXT_RECEIVE` contexts, **header_size** must be at least 4
and must be a multiple of 4.  It is ignored in other context types.

**speed** is ignored in receive context types.

If a context was successfully created, the kernel writes back a handle to the
context, which must be passed in for subsequent operations on that context.

Limitations:
No more than one iso context can be created per fd.
The total number of contexts that all userspace and kernelspace drivers can
create on a card at a time is a hardware limit, typically 4 or 8 contexts per
direction, and of them at most one multichannel receive context.

#### <a id="c-struct-fw_cdev_set_iso_channels"></a>`struct fw_cdev_set_iso_channels`

Select channels in multichannel reception

**Definition**

```c
struct fw_cdev_set_iso_channels {
    __u64 channels;
    __u32 handle;
};
```

**Members**

- `channels`: Bitmask of channels to listen to
- `handle`: Handle of the mutichannel receive context

**Description**

**channels** is the bitwise or of 1ULL \<\< n for each channel n to listen to.

The ioctl fails with errno `EBUSY` if there is already another receive context
on a channel in **channels**.  In that case, the bitmask of all unoccupied
channels is returned in **channels**.

#### <a id="c-struct-fw_cdev_iso_packet"></a>`struct fw_cdev_iso_packet`

Isochronous packet

**Definition**

```c
struct fw_cdev_iso_packet {
    __u32 control;
    __u32 header[];
};
```

**Members**

- `control`: Contains the header length (8 uppermost bits),
  the sy field (4 bits), the tag field (2 bits), a sync flag
  or a skip flag (1 bit), an interrupt flag (1 bit), and the
  payload length (16 lowermost bits)
- `header`: Header and payload in case of a transmit context.

**Description**

[`struct fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet) is used to describe isochronous packet queues.
Use the FW_CDEV_ISO_* macros to fill in **control**.
The **header** array is empty in case of receive contexts.

Context type `FW_CDEV_ISO_CONTEXT_TRANSMIT`:

**control.HEADER_LENGTH** must be a multiple of 4.  It specifies the numbers of
bytes in **header** that will be prepended to the packet's payload.  These bytes
are copied into the kernel and will not be accessed after the ioctl has
returned.

The **control.SY** and TAG fields are copied to the iso packet header.  These
fields are specified by IEEE 1394a and IEC 61883-1.

The **control.SKIP** flag specifies that no packet is to be sent in a frame.
When using this, all other fields except **control.INTERRUPT** must be zero.

When a packet with the **control.INTERRUPT** flag set has been completed, an
[`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt) event will be sent.

Context type `FW_CDEV_ISO_CONTEXT_RECEIVE`:

**control.HEADER_LENGTH** must be a multiple of the context's header_size.
If the HEADER_LENGTH is larger than the context's header_size, multiple
packets are queued for this entry.

The **control.SY** and TAG fields are ignored.

If the **control.SYNC** flag is set, the context drops all packets until a
packet with a sy field is received which matches [`fw_cdev_start_iso.sync`](#c-struct-fw_cdev_start_iso).

**control.PAYLOAD_LENGTH** defines how many payload bytes can be received for
one packet (in addition to payload quadlets that have been defined as headers
and are stripped and returned in the [`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt) structure).
If more bytes are received, the additional bytes are dropped.  If less bytes
are received, the remaining bytes in this part of the payload buffer will not
be written to, not even by the next packet.  I.e., packets received in
consecutive frames will not necessarily be consecutive in memory.  If an
entry has queued multiple packets, the PAYLOAD_LENGTH is divided equally
among them.

When a packet with the **control.INTERRUPT** flag set has been completed, an
[`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt) event will be sent.  An entry that has queued
multiple receive packets is completed when its last packet is completed.

Context type `FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL`:

Here, [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet) would be more aptly named _iso_buffer_chunk since
it specifies a chunk of the `mmap()`'ed buffer, while the number and alignment
of packets to be placed into the buffer chunk is not known beforehand.

**control.PAYLOAD_LENGTH** is the size of the buffer chunk and specifies room
for header, payload, padding, and trailer bytes of one or more packets.
It must be a multiple of 4.

**control.HEADER_LENGTH**, TAG and SY are ignored.  SYNC is treated as described
for single-channel reception.

When a buffer chunk with the **control.INTERRUPT** flag set has been filled
entirely, an [`fw_cdev_event_iso_interrupt_mc`](#c-struct-fw_cdev_event_iso_interrupt_mc) event will be sent.

#### <a id="c-struct-fw_cdev_queue_iso"></a>`struct fw_cdev_queue_iso`

Queue isochronous packets for I/O

**Definition**

```c
struct fw_cdev_queue_iso {
    __u64 packets;
    __u64 data;
    __u32 size;
    __u32 handle;
};
```

**Members**

- `packets`: Userspace pointer to an array of [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet)
- `data`: Pointer into `mmap()`'ed payload buffer
- `size`: Size of the **packets** array, in bytes
- `handle`: Isochronous context handle

**Description**

Queue a number of isochronous packets for reception or transmission.
This ioctl takes a pointer to an array of [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet) structs,
which describe how to transmit from or receive into a contiguous region
of a `mmap()`'ed payload buffer.  As part of transmit packet descriptors,
a series of headers can be supplied, which will be prepended to the
payload during DMA.

The kernel may or may not queue all packets, but will write back updated
values of the **packets**, **data** and **size** fields, so the ioctl can be
resubmitted easily.

In case of a multichannel receive context, **data** must be quadlet-aligned
relative to the buffer start.

#### <a id="c-struct-fw_cdev_start_iso"></a>`struct fw_cdev_start_iso`

Start an isochronous transmission or reception

**Definition**

```c
struct fw_cdev_start_iso {
    __s32 cycle;
    __u32 sync;
    __u32 tags;
    __u32 handle;
};
```

**Members**

- `cycle`: Cycle in which to start I/O.  If **cycle** is greater than or
  equal to 0, the I/O will start on that cycle.
- `sync`: Determines the value to wait for receive packets that have
  the `FW_CDEV_ISO_SYNC` bit set
- `tags`: Tag filter bit mask.  Only valid for isochronous reception.
  Determines the tag values for which packets will be accepted.
  Use FW_CDEV_ISO_CONTEXT_MATCH_* macros to set **tags**.
- `handle`: Isochronous context handle within which to transmit or receive

#### <a id="c-struct-fw_cdev_stop_iso"></a>`struct fw_cdev_stop_iso`

Stop an isochronous transmission or reception

**Definition**

```c
struct fw_cdev_stop_iso {
    __u32 handle;
};
```

**Members**

- `handle`: Handle of isochronous context to stop

#### <a id="c-struct-fw_cdev_flush_iso"></a>`struct fw_cdev_flush_iso`

flush completed iso packets

**Definition**

```c
struct fw_cdev_flush_iso {
    __u32 handle;
};
```

**Members**

- `handle`: handle of isochronous context to flush

**Description**

For `FW_CDEV_ISO_CONTEXT_TRANSMIT` or `FW_CDEV_ISO_CONTEXT_RECEIVE` contexts,
report any completed packets.

For `FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL` contexts, report the current
offset in the receive buffer, if it has changed; this is typically in the
middle of some buffer chunk.

Any `FW_CDEV_EVENT_ISO_INTERRUPT` or `FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL`
events generated by this ioctl are sent synchronously, i.e., are available
for reading from the file descriptor when this ioctl returns.

#### <a id="c-struct-fw_cdev_get_cycle_timer"></a>`struct fw_cdev_get_cycle_timer`

read cycle timer register

**Definition**

```c
struct fw_cdev_get_cycle_timer {
    __u64 local_time;
    __u32 cycle_timer;
};
```

**Members**

- `local_time`: system time, in microseconds since the Epoch
- `cycle_timer`: Cycle Time register contents

**Description**

Same as `FW_CDEV_IOC_GET_CYCLE_TIMER2`, but fixed to use `CLOCK_REALTIME`
and only with microseconds resolution.

In version 1 and 2 of the ABI, this ioctl returned unreliable (non-
monotonic) **cycle_timer** values on certain controllers.

#### <a id="c-struct-fw_cdev_get_cycle_timer2"></a>`struct fw_cdev_get_cycle_timer2`

read cycle timer register

**Definition**

```c
struct fw_cdev_get_cycle_timer2 {
    __s64 tv_sec;
    __s32 tv_nsec;
    __s32 clk_id;
    __u32 cycle_timer;
};
```

**Members**

- `tv_sec`: system time, seconds
- `tv_nsec`: system time, sub-seconds part in nanoseconds
- `clk_id`: input parameter, clock from which to get the system time
- `cycle_timer`: Cycle Time register contents

**Description**

The `FW_CDEV_IOC_GET_CYCLE_TIMER2` ioctl reads the isochronous cycle timer
and also the system clock.  This allows to correlate reception time of
isochronous packets with system time.

**clk_id** lets you choose a clock like with POSIX' clock_gettime function.
Supported **clk_id** values are POSIX' `CLOCK_REALTIME` and `CLOCK_MONOTONIC`
and Linux' `CLOCK_MONOTONIC_RAW`.

**cycle_timer** consists of 7 bits cycleSeconds, 13 bits cycleCount, and
12 bits cycleOffset, in host byte order.  Cf. the Cycle Time register
per IEEE 1394 or Isochronous Cycle Timer register per OHCI-1394.

#### <a id="c-struct-fw_cdev_allocate_iso_resource"></a>`struct fw_cdev_allocate_iso_resource`

(De)allocate a channel or bandwidth

**Definition**

```c
struct fw_cdev_allocate_iso_resource {
    __u64 closure;
    __u64 channels;
    __u32 bandwidth;
    __u32 handle;
};
```

**Members**

- `closure`: Passed back to userspace in corresponding iso resource events
- `channels`: Isochronous channels of which one is to be (de)allocated
- `bandwidth`: Isochronous bandwidth units to be (de)allocated
- `handle`: Handle to the allocation, written by the kernel (only valid in
  case of `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE` ioctls)

**Description**

The `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE` ioctl initiates allocation of an
isochronous channel and/or of isochronous bandwidth at the isochronous
resource manager (IRM).  Only one of the channels specified in **channels** is
allocated.  An `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` is sent after
communication with the IRM, indicating success or failure in the event data.
The kernel will automatically reallocate the resources after bus resets.
Should a reallocation fail, an `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED` event
will be sent.  The kernel will also automatically deallocate the resources
when the file descriptor is closed.

The `FW_CDEV_IOC_DEALLOCATE_ISO_RESOURCE` ioctl can be used to initiate
deallocation of resources which were allocated as described above.
An `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED` event concludes this operation.

The `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE` ioctl is a variant of allocation
without automatic re- or deallocation.
An `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` event concludes this operation,
indicating success or failure in its data.

The `FW_CDEV_IOC_DEALLOCATE_ISO_RESOURCE_ONCE` ioctl works like
`FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE` except that resources are freed
instead of allocated.
An `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED` event concludes this operation.

To summarize, `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE` allocates iso resources
for the lifetime of the fd or **handle**.
In contrast, `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE` allocates iso resources
for the duration of a bus generation.

**channels** is a host-endian bitfield with the least significant bit
representing channel 0 and the most significant bit representing channel 63:
1ULL \<\< c for each channel c that is a candidate for (de)allocation.

**bandwidth** is expressed in bandwidth allocation units, i.e. the time to send
one quadlet of data (payload or header data) at speed S1600.

#### <a id="c-struct-fw_cdev_send_stream_packet"></a>`struct fw_cdev_send_stream_packet`

send an asynchronous stream packet

**Definition**

```c
struct fw_cdev_send_stream_packet {
    __u32 length;
    __u32 tag;
    __u32 channel;
    __u32 sy;
    __u64 closure;
    __u64 data;
    __u32 generation;
    __u32 speed;
};
```

**Members**

- `length`: Length of outgoing payload, in bytes
- `tag`: Data format tag
- `channel`: Isochronous channel to transmit to
- `sy`: Synchronization code
- `closure`: Passed back to userspace in the response event
- `data`: Userspace pointer to payload
- `generation`: The bus generation where packet is valid
- `speed`: Speed to transmit at

**Description**

The `FW_CDEV_IOC_SEND_STREAM_PACKET` ioctl sends an asynchronous stream packet to every device
which is listening to the specified channel. The kernel writes either [`fw_cdev_event_response`](#c-struct-fw_cdev_event_response)
event or [`fw_cdev_event_response2`](#c-struct-fw_cdev_event_response2) event which indicates success or failure of the transmission.

#### <a id="c-struct-fw_cdev_send_phy_packet"></a>`struct fw_cdev_send_phy_packet`

send a PHY packet

**Definition**

```c
struct fw_cdev_send_phy_packet {
    __u64 closure;
    __u32 data[2];
    __u32 generation;
};
```

**Members**

- `closure`: Passed back to userspace in the PHY-packet-sent event
- `data`: First and second quadlet of the PHY packet
- `generation`: The bus generation where packet is valid

**Description**

The `FW_CDEV_IOC_SEND_PHY_PACKET` ioctl sends a PHY packet to all nodes on the same card as this
device.  After transmission, either `FW_CDEV_EVENT_PHY_PACKET_SENT` event or
`FW_CDEV_EVENT_PHY_PACKET_SENT` event is generated.

The payload **data**\\[\\] shall be specified in host byte order.  Usually,
**data**\\[1\\] needs to be the bitwise inverse of **data**\\[0\\].  VersaPHY packets
are an exception to this rule.

The ioctl is only permitted on device files which represent a local node.

#### <a id="c-struct-fw_cdev_receive_phy_packets"></a>`struct fw_cdev_receive_phy_packets`

start reception of PHY packets

**Definition**

```c
struct fw_cdev_receive_phy_packets {
    __u64 closure;
};
```

**Members**

- `closure`: Passed back to userspace in phy packet events

**Description**

This ioctl activates issuing of either `FW_CDEV_EVENT_PHY_PACKET_RECEIVED` or
`FW_CDEV_EVENT_PHY_PACKET_RECEIVED2` due to incoming PHY packets from any node on the same bus
as the device.

The ioctl is only permitted on device files which represent a local node.


<a id="rst-firewire-device-probing-and-sysfs-interfaces"></a>

## Firewire device probing and sysfs interfaces




```text
What:           /sys/bus/firewire/devices/fw[0-9]+/
Date:           May 2007
KernelVersion:  2.6.22
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                IEEE 1394 node device attributes.
                Read-only.  Mutable during the node device's lifetime.
                See IEEE 1212 for semantic definitions.

                config_rom
                        Contents of the Configuration ROM register.
                        Binary attribute; an array of host-endian u32.

                guid
                        The node's EUI-64 in the bus information block of
                        Configuration ROM.
                        Hexadecimal string representation of an u64.


What:           /sys/bus/firewire/devices/fw[0-9]+/units
Date:           June 2009
KernelVersion:  2.6.31
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                IEEE 1394 node device attribute.
                Read-only.  Mutable during the node device's lifetime.
                See IEEE 1212 for semantic definitions.

                units
                        Summary of all units present in an IEEE 1394 node.
                        Contains space-separated tuples of specifier_id and
                        version of each unit present in the node.  Specifier_id
                        and version are hexadecimal string representations of
                        u24 of the respective unit directory entries.
                        Specifier_id and version within each tuple are separated
                        by a colon.

Users:          udev rules to set ownership and access permissions or ACLs of
                /dev/fw[0-9]+ character device files


What:           /sys/bus/firewire/devices/fw[0-9]+/is_local
Date:           July 2012
KernelVersion:  3.6
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                IEEE 1394 node device attribute.
                Read-only and immutable.
Values:         1: The sysfs entry represents a local node (a controller card).

                0: The sysfs entry represents a remote node.


What:           /sys/bus/firewire/devices/fw[0-9]+[.][0-9]+/
Date:           May 2007
KernelVersion:  2.6.22
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                IEEE 1394 unit device attributes.
                Read-only.  Immutable during the unit device's lifetime.
                See IEEE 1212 for semantic definitions.

                modalias
                        Same as MODALIAS in the uevent at device creation.

                rom_index
                        Offset of the unit directory within the parent device's
                        (node device's) Configuration ROM, in quadlets.
                        Decimal string representation.


What:           /sys/bus/firewire/devices/*/
Date:           May 2007
KernelVersion:  2.6.22
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                Attributes common to IEEE 1394 node devices and unit devices.
                Read-only.  Mutable during the node device's lifetime.
                Immutable during the unit device's lifetime.
                See IEEE 1212 for semantic definitions.

                These attributes are only created if the root directory of an
                IEEE 1394 node or the unit directory of an IEEE 1394 unit
                actually contains according entries.

                hardware_version
                        Hexadecimal string representation of an u24.

                hardware_version_name
                        Contents of a respective textual descriptor leaf.

                model
                        Hexadecimal string representation of an u24.

                model_name
                        Contents of a respective textual descriptor leaf.

                specifier_id
                        Hexadecimal string representation of an u24.
                        Mandatory in unit directories according to IEEE 1212.

                vendor
                        Hexadecimal string representation of an u24.
                        Mandatory in the root directory according to IEEE 1212.

                vendor_name
                        Contents of a respective textual descriptor leaf.

                version
                        Hexadecimal string representation of an u24.
                        Mandatory in unit directories according to IEEE 1212.


What:           /sys/bus/firewire/drivers/sbp2/fw*/host*/target*/*:*:*:*/ieee1394_id
                formerly
                /sys/bus/ieee1394/drivers/sbp2/fw*/host*/target*/*:*:*:*/ieee1394_id
Date:           Feb 2004
KernelVersion:  2.6.4
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                SCSI target port identifier and logical unit identifier of a
                logical unit of an SBP-2 target.  The identifiers are specified
                in SAM-2...SAM-4 annex A.  They are persistent and world-wide
                unique properties the SBP-2 attached target.

                Read-only attribute, immutable during the target's lifetime.
                Format, as exposed by firewire-sbp2 since 2.6.22, May 2007:
                Colon-separated hexadecimal string representations of

                        u64 EUI-64 : u24 directory_ID : u16 LUN

                without 0x prefixes, without whitespace.  The former sbp2 driver
                (removed in 2.6.37 after being superseded by firewire-sbp2) used
                a somewhat shorter format which was not as close to SAM.

Users:          udev rules to create /dev/disk/by-id/ symlinks

```



#### <a id="c-fw_csr_string"></a>`fw_csr_string()`

```c
int fw_csr_string(const u32 *directory, int key, char *buf, size_t size)
```

reads a string from the configuration ROM

**Parameters**

- `const u32 *directory`: e.g. root directory or unit directory
- `int key`: the key of the preceding directory entry
- `char *buf`: where to put the string
- `size_t size`: size of **buf**, in bytes

**Description**

The string is taken from a minimal ASCII text descriptor leaf just after the entry with the
**key**. The string is zero-terminated. An overlong string is silently truncated such that it
and the zero byte fit into **size**.

Returns strlen(buf) or a negative error code.


<a id="rst-firewire-core-transaction-interfaces"></a>

## Firewire core transaction interfaces


#### <a id="c-__fw_send_request"></a>`__fw_send_request()`

```c
void __fw_send_request(struct fw_card *card, struct fw_transaction *t, int tcode, int destination_id, int generation, int speed, unsigned long long offset, void *payload, size_t length, union fw_transaction_callback callback, bool with_tstamp, void *callback_data)
```

submit a request packet for transmission to generate callback for response subaction with or without time stamp.

**Parameters**

- `struct fw_card *card`: interface to send the request at
- `struct fw_transaction *t`: transaction instance to which the request belongs
- `int tcode`: transaction code
- `int destination_id`: destination node ID, consisting of bus_ID and phy_ID
- `int generation`: bus generation in which request and response are valid
- `int speed`: transmission speed
- `unsigned long long offset`: 48bit wide offset into destination's address space
- `void *payload`: data payload for the request subaction
- `size_t length`: length of the payload, in bytes
- `union fw_transaction_callback callback`: union of two functions whether to receive time stamp or not for response
  subaction.
- `bool with_tstamp`: Whether to receive time stamp or not for response subaction.
- `void *callback_data`: data to be passed to the transaction completion callback

**Description**

Submit a request packet into the asynchronous request transmission queue.
Can be called from atomic context.  If you prefer a blocking API, use
[`fw_run_transaction()`](#c-fw_run_transaction) in a context that can sleep.

In case of lock requests, specify one of the firewire-core specific `TCODE_`
constants instead of `TCODE_LOCK_REQUEST` in **tcode**.

Make sure that the value in **destination_id** is not older than the one in
**generation**.  Otherwise the request is in danger to be sent to a wrong node.

In case of asynchronous stream packets i.e. `TCODE_STREAM_DATA`, the caller
needs to synthesize **destination_id** with `fw_stream_packet_destination_id()`.
It will contain tag, channel, and sy data instead of a node ID then.

The payload buffer at **data** is going to be DMA-mapped except in case of
**length** \<= 8 or of local (loopback) requests.  Hence make sure that the
buffer complies with the restrictions of the streaming DMA mapping API.
**payload** must not be freed before the **callback** is called.

In case of request types without payload, **data** is NULL and **length** is 0.

After the transaction is completed successfully or unsuccessfully, the
**callback** will be called.  Among its parameters is the response code which
is either one of the rcodes per IEEE 1394 or, in case of internal errors,
the firewire-core specific `RCODE_SEND_ERROR`.  The other firewire-core
specific rcodes (`RCODE_CANCELLED`, `RCODE_BUSY`, `RCODE_GENERATION`,
`RCODE_NO_ACK`) denote transaction timeout, busy responder, stale request
generation, or missing ACK respectively.

Note some timing corner cases:  `fw_send_request()` may complete much earlier
than when the request packet actually hits the wire.  On the other hand,
transaction completion and hence execution of **callback** may happen even
before `fw_send_request()` returns.

#### <a id="c-fw_run_transaction"></a>`fw_run_transaction()`

```c
int fw_run_transaction(struct fw_card *card, int tcode, int destination_id, int generation, int speed, unsigned long long offset, void *payload, size_t length)
```

send request and sleep until transaction is completed

**Parameters**

- `struct fw_card *card`: card interface for this request
- `int tcode`: transaction code
- `int destination_id`: destination node ID, consisting of bus_ID and phy_ID
- `int generation`: bus generation in which request and response are valid
- `int speed`: transmission speed
- `unsigned long long offset`: 48bit wide offset into destination's address space
- `void *payload`: data payload for the request subaction
- `size_t length`: length of the payload, in bytes

**Description**

Returns the RCODE.  See `fw_send_request()` for parameter documentation.
Unlike `fw_send_request()`, **data** points to the payload of the request or/and
to the payload of the response.  DMA mapping restrictions apply to outbound
request payloads of >= 8 bytes but not to inbound response payloads.

#### <a id="c-fw_core_add_address_handler"></a>`fw_core_add_address_handler()`

```c
int fw_core_add_address_handler(struct fw_address_handler *handler, const struct fw_address_region *region)
```

register for incoming requests

**Parameters**

- `struct fw_address_handler *handler`: callback
- `const struct fw_address_region *region`: region in the IEEE 1212 node space address range

**Description**

region->start, ->end, and handler->length have to be quadlet-aligned.

When a request is received that falls within the specified address range, the specified callback
is invoked.  The parameters passed to the callback give the details of the particular request.
The callback is invoked in the workqueue context in most cases. However, if the request is
initiated by the local node, the callback is invoked in the initiator's context.

To be called in process context.
Return value:  0 on success, non-zero otherwise.

The start offset of the handler's address region is determined by
[`fw_core_add_address_handler()`](#c-fw_core_add_address_handler) and is returned in handler->offset.

Address allocations are exclusive, except for the FCP registers.

#### <a id="c-fw_core_remove_address_handler"></a>`fw_core_remove_address_handler()`

```c
void fw_core_remove_address_handler(struct fw_address_handler *handler)
```

unregister an address handler

**Parameters**

- `struct fw_address_handler *handler`: callback

**Description**

To be called in process context.

When [`fw_core_remove_address_handler()`](#c-fw_core_remove_address_handler) returns, **handler->callback()** is
guaranteed to not run on any CPU anymore.

#### <a id="c-fw_send_response"></a>`fw_send_response()`

```c
void fw_send_response(struct fw_card *card, struct fw_request *request, int rcode)
```

- send response packet for asynchronous transaction.

**Parameters**

- `struct fw_card *card`: interface to send the response at.
- `struct fw_request *request`: firewire request data for the transaction.
- `int rcode`: response code to send.

**Description**

Submit a response packet into the asynchronous response transmission queue. The **request**
is going to be released when the transmission successfully finishes later.

#### <a id="c-fw_get_request_speed"></a>`fw_get_request_speed()`

```c
int fw_get_request_speed(struct fw_request *request)
```

returns speed at which the **request** was received

**Parameters**

- `struct fw_request *request`: firewire request data

#### <a id="c-fw_request_get_timestamp"></a>`fw_request_get_timestamp()`

```c
u32 fw_request_get_timestamp(const struct fw_request *request)
```

Get timestamp of the request.

**Parameters**

- `const struct fw_request *request`: The opaque pointer to request structure.

**Description**

Get timestamp when 1394 OHCI controller receives the asynchronous request subaction. The
timestamp consists of the low order 3 bits of second field and the full 13 bits of count
field of isochronous cycle time register.

**Return**

timestamp of the request.

#### <a id="c-fw_rcode_string"></a>`fw_rcode_string()`

```c
const char * fw_rcode_string(int rcode)
```

convert a firewire result code to an error description

**Parameters**

- `int rcode`: the result code


<a id="rst-firewire-isochronous-i-o-interfaces"></a>

## Firewire Isochronous I/O interfaces


#### <a id="c-fw_iso_context_schedule_flush_completions"></a>`fw_iso_context_schedule_flush_completions()`

```c
void fw_iso_context_schedule_flush_completions(struct fw_iso_context *ctx)
```

schedule work item to process isochronous context.

**Parameters**

- `struct fw_iso_context *ctx`: the isochronous context

**Description**

Schedule a work item on workqueue to process the isochronous context. The registered callback
function is called by the worker when a queued packet buffer with the interrupt flag is
completed, either after transmission in the IT context or after being filled in the IR context.
The callback function is also called when the header buffer in the context becomes full, If it
is required to process the context in the current context, [`fw_iso_context_flush_completions()`](#c-fw_iso_context_flush_completions) is
available instead.

**Context**

Any context.



#### <a id="c-fw_iso_context_flush_completions"></a>`fw_iso_context_flush_completions()`

```c
int fw_iso_context_flush_completions(struct fw_iso_context *ctx)
```

process isochronous context in current process context.

**Parameters**

- `struct fw_iso_context *ctx`: the isochronous context

**Description**

Process the isochronous context in the current process context. The registered callback function
is called when a queued packet buffer with the interrupt flag is completed, either after
transmission in the IT context or after being filled in the IR context. Additionally, the
callback function is also called for the packet buffer completed at last. Furthermore, the
callback function is called as well when the header buffer in the context becomes full. If it is
required to process the context asynchronously, [`fw_iso_context_schedule_flush_completions()`](#c-fw_iso_context_schedule_flush_completions) is
available instead.

**Context**

Process context. May sleep due to [`disable_work_sync()`](/kernel/internals/core-api/workqueue.md#c-disable_work_sync).

#### <a id="c-fw_iso_resource_manage"></a>`fw_iso_resource_manage()`

```c
void fw_iso_resource_manage(struct fw_card *card, int generation, u64 channels_mask, int *channel, int *bandwidth, bool allocate)
```

Allocate or deallocate a channel and/or bandwidth

**Parameters**

- `struct fw_card *card`: card interface for this action
- `int generation`: bus generation
- `u64 channels_mask`: bitmask for channel allocation
- `int *channel`: pointer for returning channel allocation result
- `int *bandwidth`: pointer for returning bandwidth allocation result
- `bool allocate`: whether to allocate (true) or deallocate (false)

**Description**

In parameters: card, generation, channels_mask, bandwidth, allocate
Out parameters: channel, bandwidth

This function blocks (sleeps) during communication with the IRM.

Allocates or deallocates at most one channel out of channels_mask.
channels_mask is a bitfield with MSB for channel 63 and LSB for channel 0.
(Note, the IRM's CHANNELS_AVAILABLE is a big-endian bitfield with MSB for
channel 0 and LSB for channel 63.)
Allocates or deallocates as many bandwidth allocation units as specified.

Returns channel \< 0 if no channel was allocated or deallocated.
Returns bandwidth = 0 if no bandwidth was allocated or deallocated.

If generation is stale, deallocations succeed but allocations fail with
channel = -EAGAIN.

If channel allocation fails, no bandwidth will be allocated either.
If bandwidth allocation fails, no channel will be allocated either.
But deallocations of channel and bandwidth are tried independently
of each other's success.

---

# High Speed Synchronous Serial Interface (HSI)

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> High Speed Synchronous Interface (HSI) is a full duplex, low latency protocol, that is optimized for die-level interconnect between an Application Processor and a Baseband chipset. It has been specified by the MIPI alliance in 2003 and…

<a id="rst-high-speed-synchronous-serial-interface-hsi"></a>

<a id="rst-introduction"></a>

## Introduction

High Speed Synchronous Interface (HSI) is a full duplex, low latency protocol, that is optimized for die-level interconnect between an Application Processor and a Baseband chipset. It has been specified by the MIPI alliance in 2003 and implemented by multiple vendors since then.

The HSI interface supports full duplex communication over multiple channels (typically 8) and is capable of reaching speeds up to 200 Mbit/s.

The serial protocol uses two signals, DATA and FLAG as combined data and clock signals and an additional READY signal for flow control. An additional WAKE signal can be used to wakeup the chips from standby modes. The signals are commonly prefixed by AC for signals going from the application die to the cellular die and CA for signals going the other way around.



```text
+------------+                                 +---------------+
|  Cellular  |                                 |  Application  |
|    Die     |                                 |      Die      |
|            | - - - - - - CAWAKE - - - - - - >|               |
|           T|------------ CADATA ------------>|R              |
|           X|------------ CAFLAG ------------>|X              |
|            |<----------- ACREADY ------------|               |
|            |                                 |               |
|            |                                 |               |
|            |< - - - - -  ACWAKE - - - - - - -|               |
|           R|<----------- ACDATA -------------|T              |
|           X|<----------- ACFLAG -------------|X              |
|            |------------ CAREADY ----------->|               |
|            |                                 |               |
|            |                                 |               |
+------------+                                 +---------------+
```

<a id="rst-hsi-subsystem-in-linux"></a>

## HSI Subsystem in Linux

In the Linux kernel the hsi subsystem is supposed to be used for HSI devices. The hsi subsystem contains drivers for hsi controllers including support for multi-port controllers and provides a generic API for using the HSI ports.

It also contains HSI client drivers, which make use of the generic API to implement a protocol used on the HSI interface. These client drivers can use an arbitrary number of channels.

<a id="rst-hsi-char-device"></a>

## hsi-char Device

Each port automatically registers a generic client driver called hsi_char, which provides a character device for userspace representing the HSI port. It can be used to communicate via HSI from userspace. Userspace may configure the hsi_char device using the following ioctl commands:

- **HSC_RESET**

  flush the HSI port

- **HSC_SET_PM**

  enable or disable the client.

- **HSC_SEND_BREAK**

  send break

- **HSC_SET_RX**

  set RX configuration

- **HSC_GET_RX**

  get RX configuration

- **HSC_SET_TX**

  set TX configuration

- **HSC_GET_TX**

  get TX configuration

<a id="rst-the-kernel-hsi-api"></a>

## The kernel HSI API


#### <a id="c-struct-hsi_channel"></a>`struct hsi_channel`

channel resource used by the hsi clients

**Definition**

```c
struct hsi_channel {
    unsigned int    id;
    const char      *name;
};
```

**Members**

- `id`: Channel number
- `name`: Channel name

#### <a id="c-struct-hsi_config"></a>`struct hsi_config`

Configuration for RX/TX HSI modules

**Definition**

```c
struct hsi_config {
    unsigned int            mode;
    struct hsi_channel      *channels;
    unsigned int            num_channels;
    unsigned int            num_hw_channels;
    unsigned int            speed;
    union {
        unsigned int    flow;
        unsigned int    arb_mode;
    };
};
```

**Members**

- `mode`: Bit transmission mode (STREAM or FRAME)
- `channels`: Channel resources used by the client
- `num_channels`: Number of channel resources
- `num_hw_channels`: Number of channels the transceiver is configured for \[1..16\]
- `speed`: Max bit transmission speed (Kbit/s)
- `{unnamed_union}`: anonymous
- `flow`: RX flow type (SYNCHRONIZED or PIPELINE)
- `arb_mode`: Arbitration mode for TX frame (Round robin, priority)

#### <a id="c-struct-hsi_board_info"></a>`struct hsi_board_info`

HSI client board info

**Definition**

```c
struct hsi_board_info {
    const char              *name;
    unsigned int            hsi_id;
    unsigned int            port;
    struct hsi_config       tx_cfg;
    struct hsi_config       rx_cfg;
    void *platform_data;
    struct dev_archdata     *archdata;
};
```

**Members**

- `name`: Name for the HSI device
- `hsi_id`: HSI controller id where the client sits
- `port`: Port number in the controller where the client sits
- `tx_cfg`: HSI TX configuration
- `rx_cfg`: HSI RX configuration
- `platform_data`: Platform related data
- `archdata`: Architecture-dependent device data

#### <a id="c-struct-hsi_client"></a>`struct hsi_client`

HSI client attached to an HSI port

**Definition**

```c
struct hsi_client {
    struct device           device;
    struct hsi_config       tx_cfg;
    struct hsi_config       rx_cfg;
};
```

**Members**

- `device`: Driver model representation of the device
- `tx_cfg`: HSI TX configuration
- `rx_cfg`: HSI RX configuration

#### <a id="c-struct-hsi_client_driver"></a>`struct hsi_client_driver`

Driver associated to an HSI client

**Definition**

```c
struct hsi_client_driver {
    struct device_driver    driver;
};
```

**Members**

- `driver`: Driver model representation of the driver

#### <a id="c-struct-hsi_msg"></a>`struct hsi_msg`

HSI message descriptor

**Definition**

```c
struct hsi_msg {
    struct list_head        link;
    struct hsi_client       *cl;
    struct sg_table         sgt;
    void *context;
    void (*complete)(struct hsi_msg *msg);
    void (*destructor)(struct hsi_msg *msg);
    int status;
    unsigned int            actual_len;
    unsigned int            channel;
    unsigned int            ttype:1;
    unsigned int            break_frame:1;
};
```

**Members**

- `link`: Free to use by the current descriptor owner
- `cl`: HSI device client that issues the transfer
- `sgt`: Head of the scatterlist array
- `context`: Client context data associated to the transfer
- `complete`: Transfer completion callback
- `destructor`: Destructor to free resources when flushing
- `status`: Status of the transfer when completed
- `actual_len`: Actual length of data transferred on completion
- `channel`: Channel were to TX/RX the message
- `ttype`: Transfer type (TX if set, RX otherwise)
- `break_frame`: if true HSI will send/receive a break frame. Data buffers are
  ignored in the request.

#### <a id="c-struct-hsi_port"></a>`struct hsi_port`

HSI port device

**Definition**

```c
struct hsi_port {
    struct device                   device;
    struct hsi_config               tx_cfg;
    struct hsi_config               rx_cfg;
    unsigned int                    num;
    unsigned int                    shared:1;
    int claimed;
    struct mutex                    lock;
    int (*async)(struct hsi_msg *msg);
    int (*setup)(struct hsi_client *cl);
    int (*flush)(struct hsi_client *cl);
    int (*start_tx)(struct hsi_client *cl);
    int (*stop_tx)(struct hsi_client *cl);
    int (*release)(struct hsi_client *cl);
    struct blocking_notifier_head   n_head;
};
```

**Members**

- `device`: Driver model representation of the device
- `tx_cfg`: Current TX path configuration
- `rx_cfg`: Current RX path configuration
- `num`: Port number
- `shared`: Set when port can be shared by different clients
- `claimed`: Reference count of clients which claimed the port
- `lock`: Serialize port claim
- `async`: Asynchronous transfer callback
- `setup`: Callback to set the HSI client configuration
- `flush`: Callback to clean the HW state and destroy all pending transfers
- `start_tx`: Callback to inform that a client wants to TX data
- `stop_tx`: Callback to inform that a client no longer wishes to TX data
- `release`: Callback to inform that a client no longer uses the port
- `n_head`: Notifier chain for signaling port events to the clients.

#### <a id="c-struct-hsi_controller"></a>`struct hsi_controller`

HSI controller device

**Definition**

```c
struct hsi_controller {
    struct device           device;
    struct module           *owner;
    unsigned int            id;
    unsigned int            num_ports;
    struct hsi_port         **port;
};
```

**Members**

- `device`: Driver model representation of the device
- `owner`: Pointer to the module owning the controller
- `id`: HSI controller ID
- `num_ports`: Number of ports in the HSI controller
- `port`: Array of HSI ports

#### <a id="c-hsi_id"></a>`hsi_id()`

```c
unsigned int hsi_id(struct hsi_client *cl)
```

Get HSI controller ID associated to a client

**Parameters**

- `struct hsi_client *cl`: Pointer to a HSI client

**Description**

Return the controller id where the client is attached to

#### <a id="c-hsi_port_id"></a>`hsi_port_id()`

```c
unsigned int hsi_port_id(struct hsi_client *cl)
```

Gets the port number a client is attached to

**Parameters**

- `struct hsi_client *cl`: Pointer to HSI client

**Description**

Return the port number associated to the client

#### <a id="c-hsi_setup"></a>`hsi_setup()`

```c
int hsi_setup(struct hsi_client *cl)
```

Configure the client's port

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client

**Description**

When sharing ports, clients should either relay on a single
client setup or have the same setup for all of them.

Return -errno on failure, 0 on success

#### <a id="c-hsi_flush"></a>`hsi_flush()`

```c
int hsi_flush(struct hsi_client *cl)
```

Flush all pending transactions on the client's port

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client

**Description**

This function will destroy all pending hsi_msg in the port and reset
the HW port so it is ready to receive and transmit from a clean state.

Return -errno on failure, 0 on success

#### <a id="c-hsi_async_read"></a>`hsi_async_read()`

```c
int hsi_async_read(struct hsi_client *cl, struct hsi_msg *msg)
```

Submit a read transfer

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client
- `struct hsi_msg *msg`: HSI message descriptor of the transfer

**Description**

Return -errno on failure, 0 on success

#### <a id="c-hsi_async_write"></a>`hsi_async_write()`

```c
int hsi_async_write(struct hsi_client *cl, struct hsi_msg *msg)
```

Submit a write transfer

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client
- `struct hsi_msg *msg`: HSI message descriptor of the transfer

**Description**

Return -errno on failure, 0 on success

#### <a id="c-hsi_start_tx"></a>`hsi_start_tx()`

```c
int hsi_start_tx(struct hsi_client *cl)
```

Signal the port that the client wants to start a TX

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client

**Description**

Return -errno on failure, 0 on success

#### <a id="c-hsi_stop_tx"></a>`hsi_stop_tx()`

```c
int hsi_stop_tx(struct hsi_client *cl)
```

Signal the port that the client no longer wants to transmit

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client

**Description**

Return -errno on failure, 0 on success



#### <a id="c-hsi_port_unregister_clients"></a>`hsi_port_unregister_clients()`

```c
void hsi_port_unregister_clients(struct hsi_port *port)
```

Unregister an HSI port

**Parameters**

- `struct hsi_port *port`: The HSI port to unregister

#### <a id="c-hsi_unregister_controller"></a>`hsi_unregister_controller()`

```c
void hsi_unregister_controller(struct hsi_controller *hsi)
```

Unregister an HSI controller

**Parameters**

- `struct hsi_controller *hsi`: The HSI controller to register

#### <a id="c-hsi_register_controller"></a>`hsi_register_controller()`

```c
int hsi_register_controller(struct hsi_controller *hsi)
```

Register an HSI controller and its ports

**Parameters**

- `struct hsi_controller *hsi`: The HSI controller to register

**Description**

Returns -errno on failure, 0 on success.

#### <a id="c-hsi_register_client_driver"></a>`hsi_register_client_driver()`

```c
int hsi_register_client_driver(struct hsi_client_driver *drv)
```

Register an HSI client to the HSI bus

**Parameters**

- `struct hsi_client_driver *drv`: HSI client driver to register

**Description**

Returns -errno on failure, 0 on success.

#### <a id="c-hsi_put_controller"></a>`hsi_put_controller()`

```c
void hsi_put_controller(struct hsi_controller *hsi)
```

Free an HSI controller

**Parameters**

- `struct hsi_controller *hsi`: Pointer to the HSI controller to freed

**Description**

HSI controller drivers should only use this function if they need
to free their allocated hsi_controller structures before a successful
call to hsi_register_controller. Other use is not allowed.

#### <a id="c-hsi_alloc_controller"></a>`hsi_alloc_controller()`

```c
struct hsi_controller * hsi_alloc_controller(unsigned int n_ports, gfp_t flags)
```

Allocate an HSI controller and its ports

**Parameters**

- `unsigned int n_ports`: Number of ports on the HSI controller
- `gfp_t flags`: Kernel allocation flags

**Description**

Return NULL on failure or a pointer to an hsi_controller on success.

#### <a id="c-hsi_free_msg"></a>`hsi_free_msg()`

```c
void hsi_free_msg(struct hsi_msg *msg)
```

Free an HSI message

**Parameters**

- `struct hsi_msg *msg`: Pointer to the HSI message

**Description**

Client is responsible to free the buffers pointed by the scatterlists.

#### <a id="c-hsi_alloc_msg"></a>`hsi_alloc_msg()`

```c
struct hsi_msg * hsi_alloc_msg(unsigned int nents, gfp_t flags)
```

Allocate an HSI message

**Parameters**

- `unsigned int nents`: Number of memory entries
- `gfp_t flags`: Kernel allocation flags

**Description**

nents can be 0. This mainly makes sense for read transfer.
In that case, HSI drivers will call the complete callback when
there is data to be read without consuming it.

Return NULL on failure or a pointer to an hsi_msg on success.

#### <a id="c-hsi_async"></a>`hsi_async()`

```c
int hsi_async(struct hsi_client *cl, struct hsi_msg *msg)
```

Submit an HSI transfer to the controller

**Parameters**

- `struct hsi_client *cl`: HSI client sending the transfer
- `struct hsi_msg *msg`: The HSI transfer passed to controller

**Description**

The HSI message must have the channel, ttype, complete and destructor
fields set beforehand. If nents > 0 then the client has to initialize
also the scatterlists to point to the buffers to write to or read from.

HSI controllers relay on pre-allocated buffers from their clients and they
do not allocate buffers on their own.

Once the HSI message transfer finishes, the HSI controller calls the
complete callback with the status and actual_len fields of the HSI message
updated. The complete callback can be called before returning from
hsi_async.

Returns -errno on failure or 0 on success

#### <a id="c-hsi_claim_port"></a>`hsi_claim_port()`

```c
int hsi_claim_port(struct hsi_client *cl, unsigned int share)
```

Claim the HSI client's port

**Parameters**

- `struct hsi_client *cl`: HSI client that wants to claim its port
- `unsigned int share`: Flag to indicate if the client wants to share the port or not.

**Description**

Returns -errno on failure, 0 on success.

#### <a id="c-hsi_release_port"></a>`hsi_release_port()`

```c
void hsi_release_port(struct hsi_client *cl)
```

Release the HSI client's port

**Parameters**

- `struct hsi_client *cl`: HSI client which previously claimed its port

#### <a id="c-hsi_register_port_event"></a>`hsi_register_port_event()`

```c
int hsi_register_port_event(struct hsi_client *cl, void (*handler)(struct hsi_client *, unsigned long))
```

Register a client to receive port events

**Parameters**

- `struct hsi_client *cl`: HSI client that wants to receive port events
- `void (*handler)(struct hsi_client *, unsigned long)`: Event handler callback

**Description**

Clients should register a callback to be able to receive
events from the ports. Registration should happen after
claiming the port.
The handler can be called in interrupt context.

Returns -errno on error, or 0 on success.

#### <a id="c-hsi_unregister_port_event"></a>`hsi_unregister_port_event()`

```c
int hsi_unregister_port_event(struct hsi_client *cl)
```

Stop receiving port events for a client

**Parameters**

- `struct hsi_client *cl`: HSI client that wants to stop receiving port events

**Description**

Clients should call this function before releasing their associated
port.

Returns -errno on error, or 0 on success.

#### <a id="c-hsi_event"></a>`hsi_event()`

```c
int hsi_event(struct hsi_port *port, unsigned long event)
```

Notifies clients about port events

**Parameters**

- `struct hsi_port *port`: Port where the event occurred
- `unsigned long event`: The event type

**Description**

Clients should not be concerned about wake line behavior. However, due
to a race condition in HSI HW protocol, clients need to be notified
about wake line changes, so they can implement a workaround for it.

Events:
HSI_EVENT_START_RX - Incoming wake line high
HSI_EVENT_STOP_RX - Incoming wake line down

Returns -errno on error, or 0 on success.

#### <a id="c-hsi_get_channel_id_by_name"></a>`hsi_get_channel_id_by_name()`

```c
int hsi_get_channel_id_by_name(struct hsi_client *cl, char *name)
```

acquire channel id by channel name

**Parameters**

- `struct hsi_client *cl`: HSI client, which uses the channel
- `char *name`: name the channel is known under

**Description**

Clients can call this function to get the hsi channel ids similar to
requesting IRQs or GPIOs by name. This function assumes the same
channel configuration is used for RX and TX.

Returns -errno on error or channel id on success.

---

# I2C and SMBus Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> I2C (or without fancy typography, "I2C") is an acronym for the "Inter-IC" bus, a simple bus protocol which is widely used where low data rate communications suffice. Since it's also a licensed trademark, some vendors use another name (such…

<a id="rst-i2c-and-smbus-subsystem"></a>

I<sup>2</sup>C (or without fancy typography, "I2C") is an acronym for the "Inter-IC" bus, a simple bus protocol which is widely used where low data rate communications suffice. Since it's also a licensed trademark, some vendors use another name (such as "Two-Wire Interface", TWI) for the same bus. I2C only needs two signals (SCL for clock, SDA for data), conserving board real estate and minimizing signal quality issues. Most I2C devices use seven bit addresses, and bus speeds of up to 400 kHz; there's a high speed extension (3.4 MHz) that's not yet found wide use. I2C is a multi-master bus; open drain signaling is used to arbitrate between masters, as well as to handshake and to synchronize clocks from slower clients.

The Linux I2C programming interfaces support the master side of bus interactions and the slave side. The programming interface is structured around two kinds of driver, and two kinds of device. An I2C "Adapter Driver" abstracts the controller hardware; it binds to a physical device (perhaps a PCI device or platform_device) and exposes a `struct i2c_adapter <i2c_adapter>` representing each I2C bus segment it manages. On each I2C bus segment will be I2C devices represented by a `struct i2c_client <i2c_client>`. Those devices will be bound to a `struct i2c_driver <i2c_driver>`, which should follow the standard Linux driver model. There are functions to perform various I2C protocol operations; at this writing all such functions are usable only from task context.

The System Management Bus (SMBus) is a sibling protocol. Most SMBus systems are also I2C conformant. The electrical constraints are tighter for SMBus, and it standardizes particular protocol messages and idioms. Controllers that support I2C can also support most SMBus operations, but SMBus controllers don't support all the protocol options that an I2C controller will. There are functions to perform various SMBus protocol operations, either using I2C primitives or by issuing SMBus commands to i2c_adapter devices which don't support those I2C operations.


#### <a id="c-i2c_master_recv"></a>`i2c_master_recv()`

```c
int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
```

issue a single I2C message in master receive mode

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `char *buf`: Where to store data read from slave
- `int count`: How many bytes to read, must be less than 64k since msg.len is u16

**Description**

Returns negative errno, or else the number of bytes read.

#### <a id="c-i2c_master_recv_dmasafe"></a>`i2c_master_recv_dmasafe()`

```c
int i2c_master_recv_dmasafe(const struct i2c_client *client, char *buf, int count)
```

issue a single I2C message in master receive mode using a DMA safe buffer

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `char *buf`: Where to store data read from slave, must be safe to use with DMA
- `int count`: How many bytes to read, must be less than 64k since msg.len is u16

**Description**

Returns negative errno, or else the number of bytes read.

#### <a id="c-i2c_master_send"></a>`i2c_master_send()`

```c
int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
```

issue a single I2C message in master transmit mode

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `const char *buf`: Data that will be written to the slave
- `int count`: How many bytes to write, must be less than 64k since msg.len is u16

**Description**

Returns negative errno, or else the number of bytes written.

#### <a id="c-i2c_master_send_dmasafe"></a>`i2c_master_send_dmasafe()`

```c
int i2c_master_send_dmasafe(const struct i2c_client *client, const char *buf, int count)
```

issue a single I2C message in master transmit mode using a DMA safe buffer

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `const char *buf`: Data that will be written to the slave, must be safe to use with DMA
- `int count`: How many bytes to write, must be less than 64k since msg.len is u16

**Description**

Returns negative errno, or else the number of bytes written.

#### <a id="c-struct-i2c_device_identity"></a>`struct i2c_device_identity`

i2c client device identification

**Definition**

```c
struct i2c_device_identity {
        u16 manufacturer_id;
    #define I2C_DEVICE_ID_NXP_SEMICONDUCTORS                0;
    #define I2C_DEVICE_ID_NXP_SEMICONDUCTORS_1              1;
    #define I2C_DEVICE_ID_NXP_SEMICONDUCTORS_2              2;
    #define I2C_DEVICE_ID_NXP_SEMICONDUCTORS_3              3;
    #define I2C_DEVICE_ID_RAMTRON_INTERNATIONAL             4;
    #define I2C_DEVICE_ID_ANALOG_DEVICES                    5;
    #define I2C_DEVICE_ID_STMICROELECTRONICS                6;
    #define I2C_DEVICE_ID_ON_SEMICONDUCTOR                  7;
    #define I2C_DEVICE_ID_SPRINTEK_CORPORATION              8;
    #define I2C_DEVICE_ID_ESPROS_PHOTONICS_AG               9;
    #define I2C_DEVICE_ID_FUJITSU_SEMICONDUCTOR            10;
    #define I2C_DEVICE_ID_FLIR                             11;
    #define I2C_DEVICE_ID_O2MICRO                          12;
    #define I2C_DEVICE_ID_ATMEL                            13;
    #define I2C_DEVICE_ID_NONE                         0xffff;
        u16 part_id;
        u8 die_revision;
};
```

**Members**

- `manufacturer_id`: 0 - 4095, database maintained by NXP
- `part_id`: 0 - 511, according to manufacturer
- `die_revision`: 0 - 7, according to manufacturer

#### <a id="c-enum-i2c_driver_flags"></a>`enum i2c_driver_flags`

Flags for an I2C device driver

**Constants**

- `I2C_DRV_ACPI_WAIVE_D0_PROBE`: Don't put the device in D0 state for probe

#### <a id="c-struct-i2c_driver"></a>`struct i2c_driver`

represent an I2C device driver

**Definition**

```c
struct i2c_driver {
    unsigned int class;
    int (*probe)(struct i2c_client *client);
    void (*remove)(struct i2c_client *client);
    void (*shutdown)(struct i2c_client *client);
    void (*alert)(struct i2c_client *client, enum i2c_alert_protocol protocol, unsigned int data);
    int (*command)(struct i2c_client *client, unsigned int cmd, void *arg);
    struct device_driver driver;
    const struct i2c_device_id *id_table;
    int (*detect)(struct i2c_client *client, struct i2c_board_info *info);
    const unsigned short *address_list;
    struct list_head clients;
    u32 flags;
};
```

**Members**

- `class`: What kind of i2c device we instantiate (for detect)
- `probe`: Callback for device binding
- `remove`: Callback for device unbinding
- `shutdown`: Callback for device shutdown
- `alert`: Alert callback, for example for the SMBus alert protocol
- `command`: Callback for bus-wide signaling (optional)
- `driver`: Device driver model driver
- `id_table`: List of I2C devices supported by this driver
- `detect`: Callback for device detection
- `address_list`: The I2C addresses to probe (for detect)
- `clients`: List of detected clients we created (for i2c-core use only)
- `flags`: A bitmask of flags defined in [`enum i2c_driver_flags`](#c-enum-i2c_driver_flags)

**Description**

The driver.owner field should be set to the module owner of this driver.
The driver.name field should be set to the name of this driver.

For automatic device detection, both **detect** and **address_list** must
be defined. **class** should also be set, otherwise only devices forced
with module parameters will be created. The detect function must
fill at least the name field of the i2c_board_info structure it is
handed upon successful detection, and possibly also the flags field.

If **detect** is missing, the driver will still work fine for enumerated
devices. Detected devices simply won't be supported. This is expected
for the many I2C/SMBus devices which can't be detected reliably, and
the ones which can always be enumerated in practice.

The i2c_client structure which is handed to the **detect** callback is
not a real i2c_client. It is initialized just enough so that you can
call i2c_smbus_read_byte_data and friends on it. Don't do anything
else with it. In particular, calling dev_dbg and friends on it is
not allowed.

#### <a id="c-struct-i2c_client"></a>`struct i2c_client`

represent an I2C slave device

**Definition**

```c
struct i2c_client {
        unsigned short flags;
    #define I2C_CLIENT_PEC          0x04;
    #define I2C_CLIENT_TEN          0x10;
    #define I2C_CLIENT_SLAVE        0x20;
    #define I2C_CLIENT_HOST_NOTIFY  0x40;
    #define I2C_CLIENT_WAKE         0x80;
    #define I2C_CLIENT_SCCB         0x9000;
        unsigned short addr;
        char name[I2C_NAME_SIZE];
        struct i2c_adapter *adapter;
        struct device dev;
        int init_irq;
        int irq;
        struct list_head detected;
    #if IS_ENABLED(CONFIG_I2C_SLAVE);
        i2c_slave_cb_t slave_cb;
    #endif;
        void *devres_group_id;
        struct dentry *debugfs;
};
```

**Members**

- `flags`: see I2C_CLIENT_* for possible flags
- `addr`: Address used on the I2C bus connected to the parent adapter.
- `name`: Indicates the type of the device, usually a chip name that's
  generic enough to hide second-sourcing and compatible revisions.
- `adapter`: manages the bus segment hosting this I2C device
- `dev`: Driver model device node for the slave.
- `init_irq`: IRQ that was set at initialization
- `irq`: indicates the IRQ generated by this device (if any)
- `detected`: member of an i2c_driver.clients list or i2c-core's
  userspace_devices list
- `slave_cb`: Callback when I2C slave mode of an adapter is used. The adapter
  calls it to pass on slave events to the slave driver.
- `devres_group_id`: id of the devres group that will be created for resources
  acquired when probing this device.
- `debugfs`: pointer to the debugfs subdirectory which the I2C core created
  for this client.

**Description**

An i2c_client identifies a single device (i.e. chip) connected to an
i2c bus. The behaviour exposed to Linux is defined by the driver
managing the device.

#### <a id="c-struct-i2c_board_info"></a>`struct i2c_board_info`

template for device creation

**Definition**

```c
struct i2c_board_info {
    char type[I2C_NAME_SIZE];
    unsigned short  flags;
    unsigned short  addr;
    const char      *dev_name;
    void *platform_data;
    struct fwnode_handle *fwnode;
    const struct software_node *swnode;
    const struct resource *resources;
    unsigned int    num_resources;
    int irq;
};
```

**Members**

- `type`: chip type, to initialize i2c_client.name
- `flags`: to initialize i2c_client.flags
- `addr`: stored in i2c_client.addr
- `dev_name`: Overrides the default \<busnr>-\<addr> dev_name if set
- `platform_data`: stored in i2c_client.dev.platform_data
- `fwnode`: device node supplied by the platform firmware
- `swnode`: software node for the device
- `resources`: resources associated with the device
- `num_resources`: number of resources in the **resources** array
- `irq`: stored in i2c_client.irq

**Description**

I2C doesn't actually support hardware probing, although controllers and
devices may be able to use I2C_SMBUS_QUICK to tell whether or not there's
a device at a given address.  Drivers commonly need more information than
that, such as chip type, configuration, associated IRQ, and so on.

i2c_board_info is used to build tables of information listing I2C devices
that are present.  This information is used to grow the driver model tree.
For mainboards this is done statically using [`i2c_register_board_info()`](#c-i2c_register_board_info);
bus numbers identify adapters that aren't yet available.  For add-on boards,
[`i2c_new_client_device()`](#c-i2c_new_client_device) does this dynamically with the adapter already known.

#### <a id="c-I2C_BOARD_INFO"></a>`I2C_BOARD_INFO()`

```c
I2C_BOARD_INFO(dev_type, dev_addr)
```

macro used to list an i2c device and its address

**Parameters**

- `dev_type`: identifies the device type
- `dev_addr`: the device's address on the bus.

**Description**

This macro initializes essential fields of a struct i2c_board_info,
declaring what has been provided on a particular board.  Optional
fields (such as associated irq, or device-specific platform_data)
are provided using conventional syntax.

#### <a id="c-struct-i2c_algorithm"></a>`struct i2c_algorithm`

represent I2C transfer methods

**Definition**

```c
struct i2c_algorithm {
        union {
            int (*xfer)(struct i2c_adapter *adap, struct i2c_msg *msgs, int num);
            int (*master_xfer)(struct i2c_adapter *adap, struct i2c_msg *msgs, int num);
        };
        union {
            int (*xfer_atomic)(struct i2c_adapter *adap, struct i2c_msg *msgs, int num);
            int (*master_xfer_atomic)(struct i2c_adapter *adap, struct i2c_msg *msgs, int num);
        };
        int (*smbus_xfer)(struct i2c_adapter *adap, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data);
        int (*smbus_xfer_atomic)(struct i2c_adapter *adap, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data);
        u32 (*functionality)(struct i2c_adapter *adap);
    #if IS_ENABLED(CONFIG_I2C_SLAVE);
        union {
            int (*reg_target)(struct i2c_client *client);
            int (*reg_slave)(struct i2c_client *client);
        };
        union {
            int (*unreg_target)(struct i2c_client *client);
            int (*unreg_slave)(struct i2c_client *client);
        };
    #endif;
};
```

**Members**

- `{unnamed_union}`: anonymous
- `xfer`: Transfer a given number of messages defined by the msgs array via
  the specified adapter.
- `master_xfer`: deprecated, use **xfer**
- `{unnamed_union}`: anonymous
- `xfer_atomic`: Same as **xfer**. Yet, only using atomic context so e.g. PMICs
  can be accessed very late before shutdown. Optional.
- `master_xfer_atomic`: deprecated, use **xfer_atomic**
- `smbus_xfer`: Issue SMBus transactions to the given I2C adapter. If this
  is not present, then the bus layer will try and convert the SMBus calls
  into I2C transfers instead.
- `smbus_xfer_atomic`: Same as **smbus_xfer**. Yet, only using atomic context
  so e.g. PMICs can be accessed very late before shutdown. Optional.
- `functionality`: Return the flags that this algorithm/adapter pair supports
  from the `I2C_FUNC_*` flags.
- `{unnamed_union}`: anonymous
- `reg_target`: Register given client to local target mode of this adapter
- `reg_slave`: deprecated, use **reg_target**
- `{unnamed_union}`: anonymous
- `unreg_target`: Unregister given client from local target mode of this adapter
- `unreg_slave`: deprecated, use **unreg_target**

**Description**

i2c_algorithm is the interface to a class of hardware solutions which can
be addressed using the same bus algorithms - i.e. bit-banging or the PCF8584
to name two of the most common.

The return codes from the `xfer{_atomic}` fields should indicate the
type of error code that occurred during the transfer, as documented in the
Kernel Documentation file Documentation/i2c/fault-codes.rst. Otherwise, the
number of messages executed should be returned.

#### <a id="c-struct-i2c_lock_operations"></a>`struct i2c_lock_operations`

represent I2C locking operations

**Definition**

```c
struct i2c_lock_operations {
    void (*lock_bus)(struct i2c_adapter *adapter, unsigned int flags);
    int (*trylock_bus)(struct i2c_adapter *adapter, unsigned int flags);
    void (*unlock_bus)(struct i2c_adapter *adapter, unsigned int flags);
};
```

**Members**

- `lock_bus`: Get exclusive access to an I2C bus segment
- `trylock_bus`: Try to get exclusive access to an I2C bus segment
- `unlock_bus`: Release exclusive access to an I2C bus segment

**Description**

The main operations are wrapped by i2c_lock_bus and i2c_unlock_bus.

#### <a id="c-struct-i2c_timings"></a>`struct i2c_timings`

I2C timing information

**Definition**

```c
struct i2c_timings {
    u32 bus_freq_hz;
    u32 scl_rise_ns;
    u32 scl_fall_ns;
    u32 scl_int_delay_ns;
    u32 sda_fall_ns;
    u32 sda_hold_ns;
    u32 digital_filter_width_ns;
    u32 analog_filter_cutoff_freq_hz;
};
```

**Members**

- `bus_freq_hz`: the bus frequency in Hz
- `scl_rise_ns`: time SCL signal takes to rise in ns; t(r) in the I2C specification
- `scl_fall_ns`: time SCL signal takes to fall in ns; t(f) in the I2C specification
- `scl_int_delay_ns`: time IP core additionally needs to setup SCL in ns
- `sda_fall_ns`: time SDA signal takes to fall in ns; t(f) in the I2C specification
- `sda_hold_ns`: time IP core additionally needs to hold SDA in ns
- `digital_filter_width_ns`: width in ns of spikes on i2c lines that the IP core
  digital filter can filter out
- `analog_filter_cutoff_freq_hz`: threshold frequency for the low pass IP core
  analog filter

#### <a id="c-struct-i2c_bus_recovery_info"></a>`struct i2c_bus_recovery_info`

I2C bus recovery information

**Definition**

```c
struct i2c_bus_recovery_info {
    int (*recover_bus)(struct i2c_adapter *adap);
    int (*get_scl)(struct i2c_adapter *adap);
    void (*set_scl)(struct i2c_adapter *adap, int val);
    int (*get_sda)(struct i2c_adapter *adap);
    void (*set_sda)(struct i2c_adapter *adap, int val);
    int (*get_bus_free)(struct i2c_adapter *adap);
    void (*prepare_recovery)(struct i2c_adapter *adap);
    void (*unprepare_recovery)(struct i2c_adapter *adap);
    struct gpio_desc *scl_gpiod;
    struct gpio_desc *sda_gpiod;
    struct pinctrl *pinctrl;
    struct pinctrl_state *pins_default;
    struct pinctrl_state *pins_gpio;
};
```

**Members**

- `recover_bus`: Recover routine. Either pass driver's `recover_bus()` routine, or
  `i2c_generic_scl_recovery()`.
- `get_scl`: This gets current value of SCL line. Mandatory for generic SCL
  recovery. Populated internally for generic GPIO recovery.
- `set_scl`: This sets/clears the SCL line. Mandatory for generic SCL recovery.
  Populated internally for generic GPIO recovery.
- `get_sda`: This gets current value of SDA line. This or `set_sda()` is mandatory
  for generic SCL recovery. Populated internally, if sda_gpio is a valid
  GPIO, for generic GPIO recovery.
- `set_sda`: This sets/clears the SDA line. This or `get_sda()` is mandatory for
  generic SCL recovery. Populated internally, if sda_gpio is a valid GPIO,
  for generic GPIO recovery.
- `get_bus_free`: Returns the bus free state as seen from the IP core in case it
  has a more complex internal logic than just reading SDA. Optional.
- `prepare_recovery`: This will be called before starting recovery. Platform may
  configure padmux here for SDA/SCL line or something else they want.
- `unprepare_recovery`: This will be called after completing recovery. Platform
  may configure padmux here for SDA/SCL line or something else they want.
- `scl_gpiod`: gpiod of the SCL line. Only required for GPIO recovery.
- `sda_gpiod`: gpiod of the SDA line. Only required for GPIO recovery.
- `pinctrl`: pinctrl used by GPIO recovery to change the state of the I2C pins.
  Optional.
- `pins_default`: default pinctrl state of SCL/SDA lines, when they are assigned
  to the I2C bus. Optional. Populated internally for GPIO recovery, if
  state with the name PINCTRL_STATE_DEFAULT is found and pinctrl is valid.
- `pins_gpio`: recovery pinctrl state of SCL/SDA lines, when they are used as
  GPIOs. Optional. Populated internally for GPIO recovery, if this state
  is called "gpio" or "recovery" and pinctrl is valid.

#### <a id="c-struct-i2c_adapter_quirks"></a>`struct i2c_adapter_quirks`

describe flaws of an i2c adapter

**Definition**

```c
struct i2c_adapter_quirks {
    u64 flags;
    int max_num_msgs;
    u16 max_write_len;
    u16 max_read_len;
    u16 max_comb_1st_msg_len;
    u16 max_comb_2nd_msg_len;
};
```

**Members**

- `flags`: see I2C_AQ_* for possible flags and read below
- `max_num_msgs`: maximum number of messages per transfer
- `max_write_len`: maximum length of a write message
- `max_read_len`: maximum length of a read message
- `max_comb_1st_msg_len`: maximum length of the first msg in a combined message
- `max_comb_2nd_msg_len`: maximum length of the second msg in a combined message

**Description**

Note about combined messages: Some I2C controllers can only send one message
per transfer, plus something called combined message or write-then-read.
This is (usually) a small write message followed by a read message and
barely enough to access register based devices like EEPROMs. There is a flag
to support this mode. It implies max_num_msg = 2 and does the length checks
with max_comb_*_len because combined message mode usually has its own
limitations. Because of HW implementations, some controllers can actually do
write-then-anything or other variants. To support that, write-then-read has
been broken out into smaller bits like write-first and read-second which can
be combined as needed.

#### <a id="c-i2c_lock_bus"></a>`i2c_lock_bus()`

```c
void i2c_lock_bus(struct i2c_adapter *adapter, unsigned int flags)
```

Get exclusive access to an I2C bus segment

**Parameters**

- `struct i2c_adapter *adapter`: Target I2C bus segment
- `unsigned int flags`: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
  locks only this branch in the adapter tree

#### <a id="c-i2c_trylock_bus"></a>`i2c_trylock_bus()`

```c
int i2c_trylock_bus(struct i2c_adapter *adapter, unsigned int flags)
```

Try to get exclusive access to an I2C bus segment

**Parameters**

- `struct i2c_adapter *adapter`: Target I2C bus segment
- `unsigned int flags`: I2C_LOCK_ROOT_ADAPTER tries to locks the root i2c adapter,
  I2C_LOCK_SEGMENT tries to lock only this branch in the adapter tree

**Return**

true if the I2C bus segment is locked, false otherwise

#### <a id="c-i2c_unlock_bus"></a>`i2c_unlock_bus()`

```c
void i2c_unlock_bus(struct i2c_adapter *adapter, unsigned int flags)
```

Release exclusive access to an I2C bus segment

**Parameters**

- `struct i2c_adapter *adapter`: Target I2C bus segment
- `unsigned int flags`: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
  unlocks only this branch in the adapter tree

#### <a id="c-i2c_mark_adapter_suspended"></a>`i2c_mark_adapter_suspended()`

```c
void i2c_mark_adapter_suspended(struct i2c_adapter *adap)
```

Report suspended state of the adapter to the core

**Parameters**

- `struct i2c_adapter *adap`: Adapter to mark as suspended

**Description**

When using this helper to mark an adapter as suspended, the core will reject
further transfers to this adapter. The usage of this helper is optional but
recommended for devices having distinct handlers for system suspend and
runtime suspend. More complex devices are free to implement custom solutions
to reject transfers when suspended.

#### <a id="c-i2c_mark_adapter_resumed"></a>`i2c_mark_adapter_resumed()`

```c
void i2c_mark_adapter_resumed(struct i2c_adapter *adap)
```

Report resumed state of the adapter to the core

**Parameters**

- `struct i2c_adapter *adap`: Adapter to mark as resumed

**Description**

When using this helper to mark an adapter as resumed, the core will allow
further transfers to this adapter. See also further notes to
**i2c_mark_adapter_suspended()**.

#### <a id="c-i2c_check_quirks"></a>`i2c_check_quirks()`

```c
bool i2c_check_quirks(struct i2c_adapter *adap, u64 quirks)
```

Function for checking the quirk flags in an i2c adapter

**Parameters**

- `struct i2c_adapter *adap`: i2c adapter
- `u64 quirks`: quirk flags

**Return**

true if the adapter has all the specified quirk flags, false if not

#### <a id="c-module_i2c_driver"></a>`module_i2c_driver()`

```c
module_i2c_driver(__i2c_driver)
```

Helper macro for registering a modular I2C driver

**Parameters**

- `__i2c_driver`: i2c_driver struct

**Description**

Helper macro for I2C drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)

#### <a id="c-builtin_i2c_driver"></a>`builtin_i2c_driver()`

```c
builtin_i2c_driver(__i2c_driver)
```

Helper macro for registering a builtin I2C driver

**Parameters**

- `__i2c_driver`: i2c_driver struct

**Description**

Helper macro for I2C drivers which do not do anything special in their
init. This eliminates a lot of boilerplate. Each driver may only
use this macro once, and calling it replaces `device_initcall()`.



#### <a id="c-i2c_register_board_info"></a>`i2c_register_board_info()`

```c
int i2c_register_board_info(int busnum, struct i2c_board_info const *info, unsigned len)
```

statically declare I2C devices

**Parameters**

- `int busnum`: identifies the bus to which these devices belong
- `struct i2c_board_info const *info`: vector of i2c device descriptors
- `unsigned len`: how many descriptors in the vector; may be zero to reserve
  the specified bus number.

**Description**

Systems using the Linux I2C driver stack can declare tables of board info
while they initialize.  This should be done in board-specific init code
near `arch_initcall()` time, or equivalent, before any I2C adapter driver is
registered.  For example, mainboard init code could define several devices,
as could the init code for each daughtercard in a board stack.

The I2C devices will be created later, after the adapter for the relevant
bus has been registered.  After that moment, standard driver model tools
are used to bind "new style" I2C drivers to the devices.  The bus number
for any device declared using this routine is not available for dynamic
allocation.

The board info passed can safely be __initdata, but be careful of embedded
pointers (for platform_data, functions, etc) since that won't be copied.



#### <a id="c-i2c_verify_client"></a>`i2c_verify_client()`

```c
struct i2c_client * i2c_verify_client(struct device *dev)
```

return parameter as i2c_client, or NULL

**Parameters**

- `struct device *dev`: device, probably from some driver model iterator

**Description**

When traversing the driver model tree, perhaps using driver model
iterators like **device_for_each_child()**, you can't assume very much
about the nodes you find.  Use this function to avoid oopses caused
by wrongly treating some non-I2C device as an i2c_client.

#### <a id="c-i2c_new_client_device"></a>`i2c_new_client_device()`

```c
struct i2c_client * i2c_new_client_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
```

instantiate an i2c device

**Parameters**

- `struct i2c_adapter *adap`: the adapter managing the device
- `struct i2c_board_info const *info`: describes one I2C device; bus_num is ignored

**Context**

can sleep

**Description**

Create an i2c device. Binding is handled through driver model
`probe()`/`remove()` methods.  A driver may be bound to this device when we
return from this function, or any later moment (e.g. maybe hotplugging will
load the driver module).  This call is not appropriate for use by mainboard
initialization logic, which usually runs during an `arch_initcall()` long
before any i2c_adapter could exist.

This returns the new i2c client, which may be saved for later use with
[`i2c_unregister_device()`](#c-i2c_unregister_device); or an ERR_PTR to describe the error.

#### <a id="c-i2c_unregister_device"></a>`i2c_unregister_device()`

```c
void i2c_unregister_device(struct i2c_client *client)
```

reverse effect of i2c_new_*`_device()`

**Parameters**

- `struct i2c_client *client`: value returned from i2c_new_*`_device()`

**Context**

can sleep

#### <a id="c-i2c_find_device_by_fwnode"></a>`i2c_find_device_by_fwnode()`

```c
struct i2c_client * i2c_find_device_by_fwnode(struct fwnode_handle *fwnode)
```

find an i2c_client for the fwnode

**Parameters**

- `struct fwnode_handle *fwnode`: `struct fwnode_handle` corresponding to the [`struct i2c_client`](#c-struct-i2c_client)

**Description**

Look up and return the [`struct i2c_client`](#c-struct-i2c_client) corresponding to the **fwnode**.
If no client can be found, or **fwnode** is NULL, this returns NULL.

The user must call put_device(`client->dev`) once done with the i2c client.

#### <a id="c-i2c_new_dummy_device"></a>`i2c_new_dummy_device()`

```c
struct i2c_client * i2c_new_dummy_device(struct i2c_adapter *adapter, u16 address)
```

return a new i2c device bound to a dummy driver

**Parameters**

- `struct i2c_adapter *adapter`: the adapter managing the device
- `u16 address`: seven bit address to be used

**Context**

can sleep

**Description**

This returns an I2C client bound to the "dummy" driver, intended for use
with devices that consume multiple addresses.  Examples of such chips
include various EEPROMS (like 24c04 and 24c08 models).

These dummy devices have two main uses.  First, most I2C and SMBus calls
except [`i2c_transfer()`](#c-i2c_transfer) need a client handle; the dummy will be that handle.
And second, this prevents the specified address from being bound to a
different driver.

This returns the new i2c client, which should be saved for later use with
[`i2c_unregister_device()`](#c-i2c_unregister_device); or an ERR_PTR to describe the error.

#### <a id="c-devm_i2c_new_dummy_device"></a>`devm_i2c_new_dummy_device()`

```c
struct i2c_client * devm_i2c_new_dummy_device(struct device *dev, struct i2c_adapter *adapter, u16 address)
```

return a new i2c device bound to a dummy driver

**Parameters**

- `struct device *dev`: device the managed resource is bound to
- `struct i2c_adapter *adapter`: the adapter managing the device
- `u16 address`: seven bit address to be used

**Context**

can sleep

**Description**

This is the device-managed version of **i2c_new_dummy_device**. It returns the
new i2c client or an ERR_PTR in case of an error.

#### <a id="c-i2c_new_ancillary_device"></a>`i2c_new_ancillary_device()`

```c
struct i2c_client * i2c_new_ancillary_device(struct i2c_client *client, const char *name, u16 default_addr)
```

Helper to get the instantiated secondary address and create the associated device

**Parameters**

- `struct i2c_client *client`: Handle to the primary client
- `const char *name`: Handle to specify which secondary address to get
- `u16 default_addr`: Used as a fallback if no secondary address was specified

**Context**

can sleep

**Description**

I2C clients can be composed of multiple I2C slaves bound together in a single
component. The I2C client driver then binds to the master I2C slave and needs
to create I2C dummy clients to communicate with all the other slaves.

This function creates and returns an I2C dummy client whose I2C address is
retrieved from the platform firmware based on the given slave name. If no
address is specified by the firmware default_addr is used.

On DT-based platforms the address is retrieved from the "reg" property entry
cell whose "reg-names" value matches the slave name.

This returns the new i2c client, which should be saved for later use with
[`i2c_unregister_device()`](#c-i2c_unregister_device); or an ERR_PTR to describe the error.

#### <a id="c-i2c_verify_adapter"></a>`i2c_verify_adapter()`

```c
struct i2c_adapter * i2c_verify_adapter(struct device *dev)
```

return parameter as i2c_adapter or NULL

**Parameters**

- `struct device *dev`: device, probably from some driver model iterator

**Description**

When traversing the driver model tree, perhaps using driver model
iterators like **device_for_each_child()**, you can't assume very much
about the nodes you find.  Use this function to avoid oopses caused
by wrongly treating some non-I2C device as an i2c_adapter.

#### <a id="c-i2c_handle_smbus_host_notify"></a>`i2c_handle_smbus_host_notify()`

```c
int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
```

Forward a Host Notify event to the correct I2C client.

**Parameters**

- `struct i2c_adapter *adap`: the adapter
- `unsigned short addr`: the I2C address of the notifying device

**Context**

can't sleep

**Description**

Helper function to be called from an I2C bus driver's interrupt
handler. It will schedule the Host Notify IRQ.

#### <a id="c-i2c_add_adapter"></a>`i2c_add_adapter()`

```c
int i2c_add_adapter(struct i2c_adapter *adapter)
```

declare i2c adapter, use dynamic bus number

**Parameters**

- `struct i2c_adapter *adapter`: the adapter to add

**Context**

can sleep

**Description**

This routine is used to declare an I2C adapter when its bus number
doesn't matter or when its bus number is specified by an dt alias.
Examples of bases when the bus number doesn't matter: I2C adapters
dynamically added by USB links or PCI plugin cards.

When this returns zero, a new bus number was allocated and stored
in adap->nr, and the specified adapter became available for clients.
Otherwise, a negative errno value is returned.

#### <a id="c-i2c_add_numbered_adapter"></a>`i2c_add_numbered_adapter()`

```c
int i2c_add_numbered_adapter(struct i2c_adapter *adap)
```

declare i2c adapter, use static bus number

**Parameters**

- `struct i2c_adapter *adap`: the adapter to register (with adap->nr initialized)

**Context**

can sleep

**Description**

This routine is used to declare an I2C adapter when its bus number
matters.  For example, use it for I2C adapters from system-on-chip CPUs,
or otherwise built in to the system's mainboard, and where i2c_board_info
is used to properly configure I2C devices.

If the requested bus number is set to -1, then this function will behave
identically to i2c_add_adapter, and will dynamically assign a bus number.

If no devices have pre-been declared for this bus, then be sure to
register the adapter before any dynamically allocated ones.  Otherwise
the required bus ID may not be available.

When this returns zero, the specified adapter became available for
clients using the bus number provided in adap->nr.  Also, the table
of I2C devices pre-declared using [`i2c_register_board_info()`](#c-i2c_register_board_info) is scanned,
and the appropriate driver model device nodes are created.  Otherwise, a
negative errno value is returned.

#### <a id="c-i2c_del_adapter"></a>`i2c_del_adapter()`

```c
void i2c_del_adapter(struct i2c_adapter *adap)
```

unregister I2C adapter

**Parameters**

- `struct i2c_adapter *adap`: the adapter being unregistered

**Context**

can sleep

**Description**

This unregisters an I2C adapter which was previously registered
by **i2c_add_adapter** or **i2c_add_numbered_adapter**.

#### <a id="c-devm_i2c_add_adapter"></a>`devm_i2c_add_adapter()`

```c
int devm_i2c_add_adapter(struct device *dev, struct i2c_adapter *adapter)
```

device-managed variant of [`i2c_add_adapter()`](#c-i2c_add_adapter)

**Parameters**

- `struct device *dev`: managing device for adding this I2C adapter
- `struct i2c_adapter *adapter`: the adapter to add

**Context**

can sleep

**Description**

Add adapter with dynamic bus number, same with [`i2c_add_adapter()`](#c-i2c_add_adapter)
but the adapter will be auto deleted on driver detach.

#### <a id="c-i2c_find_adapter_by_fwnode"></a>`i2c_find_adapter_by_fwnode()`

```c
struct i2c_adapter * i2c_find_adapter_by_fwnode(struct fwnode_handle *fwnode)
```

find an i2c_adapter for the fwnode

**Parameters**

- `struct fwnode_handle *fwnode`: `struct fwnode_handle` corresponding to the `struct i2c_adapter`

**Description**

Look up and return the `struct i2c_adapter` corresponding to the **fwnode**.
If no adapter can be found, or **fwnode** is NULL, this returns NULL.

The user must call put_device(`adapter->dev`) once done with the i2c adapter.

#### <a id="c-i2c_get_adapter_by_fwnode"></a>`i2c_get_adapter_by_fwnode()`

```c
struct i2c_adapter * i2c_get_adapter_by_fwnode(struct fwnode_handle *fwnode)
```

find an i2c_adapter for the fwnode

**Parameters**

- `struct fwnode_handle *fwnode`: `struct fwnode_handle` corresponding to the `struct i2c_adapter`

**Description**

Look up and return the `struct i2c_adapter` corresponding to the **fwnode**,
and increment the adapter module's use count. If no adapter can be found,
or **fwnode** is NULL, this returns NULL.

The user must call i2c_put_adapter(adapter) once done with the i2c adapter.
Note that this is different from `i2c_find_adapter_by_node()`.

#### <a id="c-i2c_parse_fw_timings"></a>`i2c_parse_fw_timings()`

```c
void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
```

get I2C related timing parameters from firmware

**Parameters**

- `struct device *dev`: The device to scan for I2C timing properties
- `struct i2c_timings *t`: the i2c_timings struct to be filled with values
- `bool use_defaults`: bool to use sane defaults derived from the I2C specification
  when properties are not found, otherwise don't update

**Description**

Scan the device for the generic I2C properties describing timing parameters
for the signal and fill the given struct with the results. If a property was
not found and use_defaults was true, then maximum timings are assumed which
are derived from the I2C specification. If use_defaults is not used, the
results will be as before, so drivers can apply their own defaults before
calling this helper. The latter is mainly intended for avoiding regressions
of existing drivers which want to switch to this function. New drivers
almost always should use the defaults.

#### <a id="c-i2c_del_driver"></a>`i2c_del_driver()`

```c
void i2c_del_driver(struct i2c_driver *driver)
```

unregister I2C driver

**Parameters**

- `struct i2c_driver *driver`: the driver being unregistered

**Context**

can sleep

#### <a id="c-__i2c_transfer"></a>`__i2c_transfer()`

```c
int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
```

unlocked flavor of i2c_transfer

**Parameters**

- `struct i2c_adapter *adap`: Handle to I2C bus
- `struct i2c_msg *msgs`: One or more messages to execute before STOP is issued to
  terminate the operation; each message begins with a START.
- `int num`: Number of messages to be executed.

**Description**

Returns negative errno, else the number of messages executed.

Adapter lock must be held when calling this function. No debug logging
takes place.

#### <a id="c-i2c_transfer"></a>`i2c_transfer()`

```c
int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
```

execute a single or combined I2C message

**Parameters**

- `struct i2c_adapter *adap`: Handle to I2C bus
- `struct i2c_msg *msgs`: One or more messages to execute before STOP is issued to
  terminate the operation; each message begins with a START.
- `int num`: Number of messages to be executed.

**Description**

Returns negative errno, else the number of messages executed.

Note that there is no requirement that each message be sent to
the same slave address, although that is the most common model.

#### <a id="c-i2c_transfer_buffer_flags"></a>`i2c_transfer_buffer_flags()`

```c
int i2c_transfer_buffer_flags(const struct i2c_client *client, char *buf, int count, u16 flags)
```

issue a single I2C message transferring data to/from a buffer

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `char *buf`: Where the data is stored
- `int count`: How many bytes to transfer, must be less than 64k since msg.len is u16
- `u16 flags`: The flags to be used for the message, e.g. I2C_M_RD for reads

**Description**

Returns negative errno, or else the number of bytes transferred.

#### <a id="c-i2c_get_device_id"></a>`i2c_get_device_id()`

```c
int i2c_get_device_id(const struct i2c_client *client, struct i2c_device_identity *id)
```

get manufacturer, part id and die revision of a device

**Parameters**

- `const struct i2c_client *client`: The device to query
- `struct i2c_device_identity *id`: The queried information

**Description**

Returns negative errno on error, zero on success.

#### <a id="c-i2c_client_get_device_id"></a>`i2c_client_get_device_id()`

```c
const struct i2c_device_id * i2c_client_get_device_id(const struct i2c_client *client)
```

get the driver match table entry of a device

**Parameters**

- `const struct i2c_client *client`: the device to query. The device must be bound to a driver

**Description**

Returns a pointer to the matching entry if found, NULL otherwise.

#### <a id="c-i2c_get_dma_safe_msg_buf"></a>`i2c_get_dma_safe_msg_buf()`

```c
u8 * i2c_get_dma_safe_msg_buf(struct i2c_msg *msg, unsigned int threshold)
```

get a DMA safe buffer for the given i2c_msg

**Parameters**

- `struct i2c_msg *msg`: the message to be checked
- `unsigned int threshold`: the minimum number of bytes for which using DMA makes sense.
  Should at least be 1.

**Return**

NULL if a DMA safe buffer was not obtained. Use msg->buf with PIO.
Or a valid pointer to be used with DMA. After use, release it by
calling [`i2c_put_dma_safe_msg_buf()`](#c-i2c_put_dma_safe_msg_buf).

**Description**

This function must only be called from process context!

#### <a id="c-i2c_put_dma_safe_msg_buf"></a>`i2c_put_dma_safe_msg_buf()`

```c
void i2c_put_dma_safe_msg_buf(u8 *buf, struct i2c_msg *msg, bool xferred)
```

release DMA safe buffer and sync with i2c_msg

**Parameters**

- `u8 *buf`: the buffer obtained from [`i2c_get_dma_safe_msg_buf()`](#c-i2c_get_dma_safe_msg_buf). May be NULL.
- `struct i2c_msg *msg`: the message which the buffer corresponds to
- `bool xferred`: bool saying if the message was transferred



#### <a id="c-i2c_smbus_pec"></a>`i2c_smbus_pec()`

```c
u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
```

Incremental CRC8 over the given input data array

**Parameters**

- `u8 crc`: previous return crc8 value
- `u8 *p`: pointer to data buffer.
- `size_t count`: number of bytes in data buffer.

**Description**

Incremental CRC8 over count bytes in the array pointed to by p

#### <a id="c-i2c_smbus_read_byte"></a>`i2c_smbus_read_byte()`

```c
s32 i2c_smbus_read_byte(const struct i2c_client *client)
```

SMBus "receive byte" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device

**Description**

This executes the SMBus "receive byte" protocol, returning negative errno
else the byte received from the device.

#### <a id="c-i2c_smbus_write_byte"></a>`i2c_smbus_write_byte()`

```c
s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
```

SMBus "send byte" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 value`: Byte to be sent

**Description**

This executes the SMBus "send byte" protocol, returning negative errno
else zero on success.

#### <a id="c-i2c_smbus_read_byte_data"></a>`i2c_smbus_read_byte_data()`

```c
s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
```

SMBus "read byte" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave

**Description**

This executes the SMBus "read byte" protocol, returning negative errno
else a data byte received from the device.

#### <a id="c-i2c_smbus_write_byte_data"></a>`i2c_smbus_write_byte_data()`

```c
s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command, u8 value)
```

SMBus "write byte" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u8 value`: Byte being written

**Description**

This executes the SMBus "write byte" protocol, returning negative errno
else zero on success.

#### <a id="c-i2c_smbus_read_word_data"></a>`i2c_smbus_read_word_data()`

```c
s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
```

SMBus "read word" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave

**Description**

This executes the SMBus "read word" protocol, returning negative errno
else a 16-bit unsigned "word" received from the device.

#### <a id="c-i2c_smbus_write_word_data"></a>`i2c_smbus_write_word_data()`

```c
s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command, u16 value)
```

SMBus "write word" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u16 value`: 16-bit "word" being written

**Description**

This executes the SMBus "write word" protocol, returning negative errno
else zero on success.

#### <a id="c-i2c_smbus_read_block_data"></a>`i2c_smbus_read_block_data()`

```c
s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command, u8 *values)
```

SMBus "block read" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u8 *values`: Byte array into which data will be read; big enough to hold
  the data returned by the slave.  SMBus allows at most 32 bytes.

**Description**

This executes the SMBus "block read" protocol, returning negative errno
else the number of data bytes in the slave's response.

Note that using this function requires that the client's adapter support
the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality.  Not all adapter drivers
support this; its emulation through I2C messaging relies on a specific
mechanism (I2C_M_RECV_LEN) which may not be implemented.

#### <a id="c-i2c_smbus_write_block_data"></a>`i2c_smbus_write_block_data()`

```c
s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command, u8 length, const u8 *values)
```

SMBus "block write" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u8 length`: Size of data block; SMBus allows at most 32 bytes
- `const u8 *values`: Byte array which will be written.

**Description**

This executes the SMBus "block write" protocol, returning negative errno
else zero on success.

#### <a id="c-i2c_smbus_xfer"></a>`i2c_smbus_xfer()`

```c
s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags, char read_write, u8 command, int protocol, union i2c_smbus_data *data)
```

execute SMBus protocol operations

**Parameters**

- `struct i2c_adapter *adapter`: Handle to I2C bus
- `u16 addr`: Address of SMBus slave on that bus
- `unsigned short flags`: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
- `char read_write`: I2C_SMBUS_READ or I2C_SMBUS_WRITE
- `u8 command`: Byte interpreted by slave, for protocols which use such bytes
- `int protocol`: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
- `union i2c_smbus_data *data`: Data to be read or written

**Description**

This executes an SMBus protocol operation, and returns a negative
errno code else zero on success.

#### <a id="c-i2c_smbus_read_i2c_block_data_or_emulated"></a>`i2c_smbus_read_i2c_block_data_or_emulated()`

```c
s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client, u8 command, u8 length, u8 *values)
```

read block or emulate

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u8 length`: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
- `u8 *values`: Byte array into which data will be read; big enough to hold
  the data returned by the slave.  SMBus allows at most
  I2C_SMBUS_BLOCK_MAX bytes.

**Description**

This executes the SMBus "block read" protocol if supported by the adapter.
If block read is not supported, it emulates it using either word or byte
read protocols depending on availability.

The addresses of the I2C slave device that are accessed with this function
must be mapped to a linear region, so that a block read will have the same
effect as a byte read. Before using this function you must double-check
if the I2C slave does support exchanging a block transfer with a byte
transfer.

#### <a id="c-i2c_new_smbus_alert_device"></a>`i2c_new_smbus_alert_device()`

```c
struct i2c_client * i2c_new_smbus_alert_device(struct i2c_adapter *adapter, struct i2c_smbus_alert_setup *setup)
```

get ara client for SMBus alert support

**Parameters**

- `struct i2c_adapter *adapter`: the target adapter
- `struct i2c_smbus_alert_setup *setup`: setup data for the SMBus alert handler

**Context**

can sleep

**Description**

Setup handling of the SMBus alert protocol on a given I2C bus segment.

Handling can be done either through our IRQ handler, or by the
adapter (from its handler, periodic polling, or whatever).

This returns the ara client, which should be saved for later use with
`i2c_handle_smbus_alert()` and ultimately [`i2c_unregister_device()`](#c-i2c_unregister_device); or an
ERRPTR to indicate an error.

---

# InfiniBand and Remote DMA (RDMA) Interfaces

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> TBD

<a id="rst-infiniband-and-remote-dma-rdma-interfaces"></a>

<a id="rst-introduction-and-overview"></a>

## Introduction and Overview

TBD

<a id="rst-infiniband-core-interfaces"></a>

## InfiniBand core interfaces


#### <a id="c-iwpm_get_nlmsg_request"></a>`iwpm_get_nlmsg_request()`

```c
struct iwpm_nlmsg_request * iwpm_get_nlmsg_request(__u32 nlmsg_seq, u8 nl_client, gfp_t gfp)
```

Allocate and initialize netlink message request

**Parameters**

- `__u32 nlmsg_seq`: Sequence number of the netlink message
- `u8 nl_client`: The index of the netlink client
- `gfp_t gfp`: Indicates how the memory for the request should be allocated

**Description**

Returns the newly allocated netlink request object if successful,
otherwise returns NULL

#### <a id="c-iwpm_free_nlmsg_request"></a>`iwpm_free_nlmsg_request()`

```c
void iwpm_free_nlmsg_request(struct kref *kref)
```

Deallocate netlink message request

**Parameters**

- `struct kref *kref`: Holds reference of netlink message request

#### <a id="c-iwpm_find_nlmsg_request"></a>`iwpm_find_nlmsg_request()`

```c
struct iwpm_nlmsg_request * iwpm_find_nlmsg_request(__u32 echo_seq)
```

Find netlink message request in the request list

**Parameters**

- `__u32 echo_seq`: Sequence number of the netlink request to find

**Description**

Returns the found netlink message request,
if not found, returns NULL

#### <a id="c-iwpm_wait_complete_req"></a>`iwpm_wait_complete_req()`

```c
int iwpm_wait_complete_req(struct iwpm_nlmsg_request *nlmsg_request)
```

Block while servicing the netlink request

**Parameters**

- `struct iwpm_nlmsg_request *nlmsg_request`: Netlink message request to service

**Description**

Wakes up, after the request is completed or expired
Returns 0 if the request is complete without error

#### <a id="c-iwpm_get_nlmsg_seq"></a>`iwpm_get_nlmsg_seq()`

```c
int iwpm_get_nlmsg_seq(void)
```

Get the sequence number for a netlink message to send to the port mapper

**Parameters**

- `void`: no arguments

**Description**

Returns the sequence number for the netlink message.

#### <a id="c-iwpm_add_remote_info"></a>`iwpm_add_remote_info()`

```c
void iwpm_add_remote_info(struct iwpm_remote_info *reminfo)
```

Add remote address info of the connecting peer to the remote info hash table

**Parameters**

- `struct iwpm_remote_info *reminfo`: The remote info to be added

#### <a id="c-iwpm_check_registration"></a>`iwpm_check_registration()`

```c
u32 iwpm_check_registration(u8 nl_client, u32 reg)
```

Check if the client registration matches the given one

**Parameters**

- `u8 nl_client`: The index of the netlink client
- `u32 reg`: The given registration type to compare with

**Description**

Call `iwpm_register_pid()` to register a client
Returns true if the client registration matches reg,
otherwise returns false

#### <a id="c-iwpm_set_registration"></a>`iwpm_set_registration()`

```c
void iwpm_set_registration(u8 nl_client, u32 reg)
```

Set the client registration

**Parameters**

- `u8 nl_client`: The index of the netlink client
- `u32 reg`: Registration type to set

#### <a id="c-iwpm_get_registration"></a>`iwpm_get_registration()`

```c
u32 iwpm_get_registration(u8 nl_client)
```

Get the client registration

**Parameters**

- `u8 nl_client`: The index of the netlink client

**Description**

Returns the client registration type

#### <a id="c-iwpm_send_mapinfo"></a>`iwpm_send_mapinfo()`

```c
int iwpm_send_mapinfo(u8 nl_client, int iwpm_pid)
```

Send local and mapped IPv4/IPv6 address info of a client to the user space port mapper

**Parameters**

- `u8 nl_client`: The index of the netlink client
- `int iwpm_pid`: The pid of the user space port mapper

**Description**

If successful, returns the number of sent mapping info records

#### <a id="c-iwpm_mapinfo_available"></a>`iwpm_mapinfo_available()`

```c
int iwpm_mapinfo_available(void)
```

Check if any mapping info records is available in the hash table

**Parameters**

- `void`: no arguments

**Description**

Returns 1 if mapping information is available, otherwise returns 0

#### <a id="c-iwpm_compare_sockaddr"></a>`iwpm_compare_sockaddr()`

```c
int iwpm_compare_sockaddr(struct sockaddr_storage *a_sockaddr, struct sockaddr_storage *b_sockaddr)
```

Compare two sockaddr storage structs

**Parameters**

- `struct sockaddr_storage *a_sockaddr`: first sockaddr to compare
- `struct sockaddr_storage *b_sockaddr`: second sockaddr to compare

**Return**

0 if they are holding the same ip/tcp address info,
otherwise returns 1

#### <a id="c-iwpm_validate_nlmsg_attr"></a>`iwpm_validate_nlmsg_attr()`

```c
int iwpm_validate_nlmsg_attr(struct nlattr *nltb[], int nla_count)
```

Check for NULL netlink attributes

**Parameters**

- `struct nlattr *nltb[]`: Holds address of each netlink message attributes
- `int nla_count`: Number of netlink message attributes

**Description**

Returns error if any of the nla_count attributes is NULL

#### <a id="c-iwpm_create_nlmsg"></a>`iwpm_create_nlmsg()`

```c
struct sk_buff * iwpm_create_nlmsg(u32 nl_op, struct nlmsghdr **nlh, int nl_client)
```

Allocate skb and form a netlink message

**Parameters**

- `u32 nl_op`: Netlink message opcode
- `struct nlmsghdr **nlh`: Holds address of the netlink message header in skb
- `int nl_client`: The index of the netlink client

**Description**

Returns the newly allcated skb, or NULL if the tailroom of the skb
is insufficient to store the message header and payload

#### <a id="c-iwpm_parse_nlmsg"></a>`iwpm_parse_nlmsg()`

```c
int iwpm_parse_nlmsg(struct netlink_callback *cb, int policy_max, const struct nla_policy *nlmsg_policy, struct nlattr *nltb[], const char *msg_type)
```

Validate and parse the received netlink message

**Parameters**

- `struct netlink_callback *cb`: Netlink callback structure
- `int policy_max`: Maximum attribute type to be expected
- `const struct nla_policy *nlmsg_policy`: Validation policy
- `struct nlattr *nltb[]`: Array to store policy_max parsed elements
- `const char *msg_type`: Type of netlink message

**Description**

Returns 0 on success or a negative error code

#### <a id="c-iwpm_print_sockaddr"></a>`iwpm_print_sockaddr()`

```c
void iwpm_print_sockaddr(struct sockaddr_storage *sockaddr, char *msg)
```

Print IPv4/IPv6 address and TCP port

**Parameters**

- `struct sockaddr_storage *sockaddr`: Socket address to print
- `char *msg`: Message to print

#### <a id="c-iwpm_send_hello"></a>`iwpm_send_hello()`

```c
int iwpm_send_hello(u8 nl_client, int iwpm_pid, u16 abi_version)
```

Send hello response to iwpmd

**Parameters**

- `u8 nl_client`: The index of the netlink client
- `int iwpm_pid`: The pid of the user space port mapper
- `u16 abi_version`: The kernel's abi_version

**Description**

Returns 0 on success or a negative error code



#### <a id="c-ib_process_cq_direct"></a>`ib_process_cq_direct()`

```c
int ib_process_cq_direct(struct ib_cq *cq, int budget)
```

process a CQ in caller context

**Parameters**

- `struct ib_cq *cq`: CQ to process
- `int budget`: number of CQEs to poll for

**Description**

This function is used to process all outstanding CQ entries.
It does not offload CQ processing to a different context and does
not ask for completion interrupts from the HCA.
Using direct processing on CQ with non IB_POLL_DIRECT type may trigger
concurrent processing.

**Note**

do not pass -1 as `budget` unless it is guaranteed that the number
of completions that will be processed is small.

#### <a id="c-__ib_alloc_cq"></a>`__ib_alloc_cq()`

```c
struct ib_cq * __ib_alloc_cq(struct ib_device *dev, void *private, int nr_cqe, int comp_vector, enum ib_poll_context poll_ctx, const char *caller)
```

allocate a completion queue

**Parameters**

- `struct ib_device *dev`: device to allocate the CQ for
- `void *private`: driver private data, accessible from cq->cq_context
- `int nr_cqe`: number of CQEs to allocate
- `int comp_vector`: HCA completion vectors for this CQ
- `enum ib_poll_context poll_ctx`: context to poll the CQ from.
- `const char *caller`: module owner name.

**Description**

This is the proper interface to allocate a CQ for in-kernel users. A
CQ allocated with this interface will automatically be polled from the
specified context. The ULP must use wr->wr_cqe instead of wr->wr_id
to use this CQ abstraction.

#### <a id="c-__ib_alloc_cq_any"></a>`__ib_alloc_cq_any()`

```c
struct ib_cq * __ib_alloc_cq_any(struct ib_device *dev, void *private, int nr_cqe, enum ib_poll_context poll_ctx, const char *caller)
```

allocate a completion queue

**Parameters**

- `struct ib_device *dev`: device to allocate the CQ for
- `void *private`: driver private data, accessible from cq->cq_context
- `int nr_cqe`: number of CQEs to allocate
- `enum ib_poll_context poll_ctx`: context to poll the CQ from
- `const char *caller`: module owner name

**Description**

Attempt to spread ULP Completion Queues over each device's interrupt
vectors. A simple best-effort mechanism is used.

#### <a id="c-ib_free_cq"></a>`ib_free_cq()`

```c
void ib_free_cq(struct ib_cq *cq)
```

free a completion queue

**Parameters**

- `struct ib_cq *cq`: completion queue to free.

#### <a id="c-ib_cq_pool_get"></a>`ib_cq_pool_get()`

```c
struct ib_cq * ib_cq_pool_get(struct ib_device *dev, unsigned int nr_cqe, int comp_vector_hint, enum ib_poll_context poll_ctx)
```

Find the least used completion queue that matches a given cpu hint (or least used for wild card affinity) and fits nr_cqe.

**Parameters**

- `struct ib_device *dev`: rdma device
- `unsigned int nr_cqe`: number of needed cqe entries
- `int comp_vector_hint`: completion vector hint (-1) for the driver to assign
  a comp vector based on internal counter
- `enum ib_poll_context poll_ctx`: cq polling context

**Description**

Finds a cq that satisfies **comp_vector_hint** and **nr_cqe** requirements and
claim entries in it for us.  In case there is no available cq, allocate
a new cq with the requirements and add it to the device pool.
IB_POLL_DIRECT cannot be used for shared cqs so it is not a valid value
for **poll_ctx**.

#### <a id="c-ib_cq_pool_put"></a>`ib_cq_pool_put()`

```c
void ib_cq_pool_put(struct ib_cq *cq, unsigned int nr_cqe)
```

Return a CQ taken from a shared pool.

**Parameters**

- `struct ib_cq *cq`: The CQ to return.
- `unsigned int nr_cqe`: The max number of cqes that the user had requested.



#### <a id="c-ib_cm_listen"></a>`ib_cm_listen()`

```c
int ib_cm_listen(struct ib_cm_id *cm_id, __be64 service_id)
```

Initiates listening on the specified service ID for connection and service ID resolution requests.

**Parameters**

- `struct ib_cm_id *cm_id`: Connection identifier associated with the listen request.
- `__be64 service_id`: Service identifier matched against incoming connection
  and service ID resolution requests.  The service ID should be specified
  network-byte order.  If set to IB_CM_ASSIGN_SERVICE_ID, the CM will
  assign a service ID to the caller.

#### <a id="c-ib_cm_insert_listen"></a>`ib_cm_insert_listen()`

```c
struct ib_cm_id * ib_cm_insert_listen(struct ib_device *device, ib_cm_handler cm_handler, __be64 service_id)
```

Create a new listening ib_cm_id and listen on the given service ID.

**Parameters**

- `struct ib_device *device`: Device associated with the cm_id.  All related communication will
  be associated with the specified device.
- `ib_cm_handler cm_handler`: Callback invoked to notify the user of CM events.
- `__be64 service_id`: Service identifier matched against incoming connection
  and service ID resolution requests.  The service ID should be specified
  network-byte order.  If set to IB_CM_ASSIGN_SERVICE_ID, the CM will
  assign a service ID to the caller.

**Description**

If there's an existing ID listening on that same device and service ID,
return it.

Callers should call ib_destroy_cm_id when done with the listener ID.



#### <a id="c-rdma_rw_ctx_init"></a>`rdma_rw_ctx_init()`

```c
int rdma_rw_ctx_init(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct scatterlist *sg, u32 sg_cnt, u32 sg_offset, u64 remote_addr, u32 rkey, enum dma_data_direction dir)
```

initialize a RDMA READ/WRITE context

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to initialize
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct scatterlist *sg`: scatterlist to READ/WRITE from/to
- `u32 sg_cnt`: number of entries in **sg**
- `u32 sg_offset`: current byte offset into **sg**
- `u64 remote_addr`: remote address to read/write (relative to **rkey**)
- `u32 rkey`: remote key to operate on
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

**Description**

Returns the number of WQEs that will be needed on the workqueue if
successful, or a negative error code.

#### <a id="c-rdma_rw_ctx_init_bvec"></a>`rdma_rw_ctx_init_bvec()`

```c
int rdma_rw_ctx_init_bvec(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, const struct bio_vec *bvecs, u32 nr_bvec, struct bvec_iter iter, u64 remote_addr, u32 rkey, enum dma_data_direction dir)
```

initialize a RDMA READ/WRITE context from bio_vec

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to initialize
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `const struct bio_vec *bvecs`: bio_vec array to READ/WRITE from/to
- `u32 nr_bvec`: number of entries in **bvecs**
- `struct bvec_iter iter`: bvec iterator describing offset and length
- `u64 remote_addr`: remote address to read/write (relative to **rkey**)
- `u32 rkey`: remote key to operate on
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

**Description**

Maps the bio_vec array directly, avoiding intermediate scatterlist
conversion. Supports MR registration for iWARP devices and force_mr mode.

Returns the number of WQEs that will be needed on the workqueue if
successful, or a negative error code:

* -EINVAL  - **nr_bvec** is zero or **iter.bi_size** is zero
* -ENOMEM - DMA mapping or memory allocation failed

#### <a id="c-rdma_rw_ctx_signature_init"></a>`rdma_rw_ctx_signature_init()`

```c
int rdma_rw_ctx_signature_init(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct scatterlist *sg, u32 sg_cnt, struct scatterlist *prot_sg, u32 prot_sg_cnt, struct ib_sig_attrs *sig_attrs, u64 remote_addr, u32 rkey, enum dma_data_direction dir)
```

initialize a RW context with signature offload

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to initialize
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct scatterlist *sg`: scatterlist to READ/WRITE from/to
- `u32 sg_cnt`: number of entries in **sg**
- `struct scatterlist *prot_sg`: scatterlist to READ/WRITE protection information from/to
- `u32 prot_sg_cnt`: number of entries in **prot_sg**
- `struct ib_sig_attrs *sig_attrs`: signature offloading algorithms
- `u64 remote_addr`: remote address to read/write (relative to **rkey**)
- `u32 rkey`: remote key to operate on
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

**Description**

Returns the number of WQEs that will be needed on the workqueue if
successful, or a negative error code.

#### <a id="c-rdma_rw_ctx_wrs"></a>`rdma_rw_ctx_wrs()`

```c
struct ib_send_wr * rdma_rw_ctx_wrs(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct ib_cqe *cqe, struct ib_send_wr *chain_wr)
```

return chain of WRs for a RDMA READ or WRITE operation

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to operate on
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct ib_cqe *cqe`: completion queue entry for the last WR
- `struct ib_send_wr *chain_wr`: WR to append to the posted chain

**Description**

Return the WR chain for the set of RDMA READ/WRITE operations described by
**ctx**, as well as any memory registration operations needed.  If **chain_wr**
is non-NULL the WR it points to will be appended to the chain of WRs posted.
If **chain_wr** is not set **cqe** must be set so that the caller gets a
completion notification.

#### <a id="c-rdma_rw_ctx_post"></a>`rdma_rw_ctx_post()`

```c
int rdma_rw_ctx_post(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct ib_cqe *cqe, struct ib_send_wr *chain_wr)
```

post a RDMA READ or RDMA WRITE operation

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to operate on
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct ib_cqe *cqe`: completion queue entry for the last WR
- `struct ib_send_wr *chain_wr`: WR to append to the posted chain

**Description**

Post the set of RDMA READ/WRITE operations described by **ctx**, as well as
any memory registration operations needed.  If **chain_wr** is non-NULL the
WR it points to will be appended to the chain of WRs posted.  If **chain_wr**
is not set **cqe** must be set so that the caller gets a completion
notification.

#### <a id="c-rdma_rw_ctx_destroy"></a>`rdma_rw_ctx_destroy()`

```c
void rdma_rw_ctx_destroy(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct scatterlist *sg, u32 sg_cnt, enum dma_data_direction dir)
```

release all resources allocated by rdma_rw_ctx_init

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to release
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct scatterlist *sg`: scatterlist that was used for the READ/WRITE
- `u32 sg_cnt`: number of entries in **sg**
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

#### <a id="c-rdma_rw_ctx_destroy_bvec"></a>`rdma_rw_ctx_destroy_bvec()`

```c
void rdma_rw_ctx_destroy_bvec(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 __maybe_unused port_num, const struct bio_vec __maybe_unused *bvecs, u32 nr_bvec, enum dma_data_direction dir)
```

release resources from rdma_rw_ctx_init_bvec

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to release
- `struct ib_qp *qp`: queue pair to operate on
- `u32 __maybe_unused port_num`: port num to which the connection is bound (unused)
- `const struct bio_vec __maybe_unused *bvecs`: bio_vec array that was used for the READ/WRITE (unused)
- `u32 nr_bvec`: number of entries in **bvecs**
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

**Description**

Releases all resources allocated by a successful [`rdma_rw_ctx_init_bvec()`](#c-rdma_rw_ctx_init_bvec)
call. Must not be called if [`rdma_rw_ctx_init_bvec()`](#c-rdma_rw_ctx_init_bvec) returned an error.

The **port_num** and **bvecs** parameters are unused but present for API
symmetry with [`rdma_rw_ctx_destroy()`](#c-rdma_rw_ctx_destroy).

#### <a id="c-rdma_rw_ctx_destroy_signature"></a>`rdma_rw_ctx_destroy_signature()`

```c
void rdma_rw_ctx_destroy_signature(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct scatterlist *sg, u32 sg_cnt, struct scatterlist *prot_sg, u32 prot_sg_cnt, enum dma_data_direction dir)
```

release all resources allocated by rdma_rw_ctx_signature_init

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to release
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct scatterlist *sg`: scatterlist that was used for the READ/WRITE
- `u32 sg_cnt`: number of entries in **sg**
- `struct scatterlist *prot_sg`: scatterlist that was used for the READ/WRITE of the PI
- `u32 prot_sg_cnt`: number of entries in **prot_sg**
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

#### <a id="c-rdma_rw_mr_factor"></a>`rdma_rw_mr_factor()`

```c
unsigned int rdma_rw_mr_factor(struct ib_device *device, u32 port_num, unsigned int maxpages)
```

return number of MRs required for a payload

**Parameters**

- `struct ib_device *device`: device handling the connection
- `u32 port_num`: port num to which the connection is bound
- `unsigned int maxpages`: maximum payload pages per rdma_rw_ctx

**Description**

Returns the number of MRs the device requires to move **maxpayload**
bytes. The returned value is used during transport creation to
compute max_rdma_ctxts and the size of the transport's Send and
Send Completion Queues.

#### <a id="c-rdma_rw_max_send_wr"></a>`rdma_rw_max_send_wr()`

```c
unsigned int rdma_rw_max_send_wr(struct ib_device *dev, u32 port_num, unsigned int max_rdma_ctxs, u32 create_flags)
```

compute max Send WRs needed for RDMA R/W contexts

**Parameters**

- `struct ib_device *dev`: RDMA device
- `u32 port_num`: port number
- `unsigned int max_rdma_ctxs`: number of rdma_rw_ctx structures
- `u32 create_flags`: QP create flags (pass IB_QP_CREATE_INTEGRITY_EN if
  data integrity will be enabled on the QP)

**Description**

Returns the total number of Send Queue entries needed for
**max_rdma_ctxs**. The result accounts for memory registration and
invalidation work requests when the device requires them.

ULPs use this to size Send Queues and Send CQs before creating a
Queue Pair.



#### <a id="c-rdma_dev_access_netns"></a>`rdma_dev_access_netns()`

```c
bool rdma_dev_access_netns(const struct ib_device *dev, const struct net *net)
```

Return whether an rdma device can be accessed from a specified net namespace or not.

**Parameters**

- `const struct ib_device *dev`: Pointer to rdma device which needs to be checked
- `const struct net *net`: Pointer to net namesapce for which access to be checked

**Description**

When the rdma device is in shared mode, it ignores the net namespace.
When the rdma device is exclusive to a net namespace, rdma device net
namespace is checked against the specified one.

#### <a id="c-rdma_dev_has_raw_cap"></a>`rdma_dev_has_raw_cap()`

```c
bool rdma_dev_has_raw_cap(const struct ib_device *dev)
```

Returns whether a specified rdma device has CAP_NET_RAW capability or not.

**Parameters**

- `const struct ib_device *dev`: Pointer to rdma device whose capability to be checked

**Description**

Returns true if a rdma device's owning user namespace has CAP_NET_RAW
capability, otherwise false. When rdma subsystem is in legacy shared network,
namespace mode, the default net namespace is considered.

#### <a id="c-ib_device_put"></a>`ib_device_put()`

```c
void ib_device_put(struct ib_device *device)
```

Release IB device reference

**Parameters**

- `struct ib_device *device`: device whose reference to be released

**Description**

[`ib_device_put()`](#c-ib_device_put) releases reference to the IB device to allow it to be
unregistered and eventually free.

#### <a id="c-_ib_alloc_device"></a>`_ib_alloc_device()`

```c
struct ib_device * _ib_alloc_device(size_t size, struct net *net)
```

allocate an IB device struct

**Parameters**

- `size_t size`: size of structure to allocate
- `struct net *net`: network namespace device should be located in, namespace
  must stay valid until [`ib_register_device()`](#c-ib_register_device) is completed.

**Description**

Low-level drivers should use `ib_alloc_device()` to allocate `struct ib_device`.  **size** is the size of the structure to be allocated,
including any private data used by the low-level driver.
[`ib_dealloc_device()`](#c-ib_dealloc_device) must be used to free structures allocated with
`ib_alloc_device()`.

#### <a id="c-ib_dealloc_device"></a>`ib_dealloc_device()`

```c
void ib_dealloc_device(struct ib_device *device)
```

free an IB device struct

**Parameters**

- `struct ib_device *device`: structure to free

**Description**

Free a structure allocated with `ib_alloc_device()`.

#### <a id="c-ib_port_immutable_read"></a>`ib_port_immutable_read()`

```c
const struct ib_port_immutable* ib_port_immutable_read(struct ib_device *dev, unsigned int port)
```

Read rdma port's immutable data

**Parameters**

- `struct ib_device *dev`: IB device
- `unsigned int port`: port number whose immutable data to read. It starts with index 1 and
  valid upto including `rdma_end_port()`.

#### <a id="c-ib_register_device"></a>`ib_register_device()`

```c
int ib_register_device(struct ib_device *device, const char *name, struct device *dma_device)
```

Register an IB device with IB core

**Parameters**

- `struct ib_device *device`: Device to register
- `const char *name`: unique string device name. This may include a '%' which will
  cause a unique index to be added to the passed device name.
- `struct device *dma_device`: pointer to a DMA-capable device. If `NULL`, then the IB
  device will be used. In this case the caller should fully
  setup the ibdev for DMA. This usually means using dma_virt_ops.

**Description**

Low-level drivers use [`ib_register_device()`](#c-ib_register_device) to register their
devices with the IB core.  All registered clients will receive a
callback for each device that is added. **device** must be allocated
with `ib_alloc_device()`.

If the driver uses ops.dealloc_driver and calls any [`ib_unregister_device()`](#c-ib_unregister_device)
asynchronously then the device pointer may become freed as soon as this
function returns.

#### <a id="c-ib_unregister_device"></a>`ib_unregister_device()`

```c
void ib_unregister_device(struct ib_device *ib_dev)
```

Unregister an IB device

**Parameters**

- `struct ib_device *ib_dev`: The device to unregister

**Description**

Unregister an IB device.  All clients will receive a remove callback.

Callers should call this routine only once, and protect against races with
registration. Typically it should only be called as part of a remove
callback in an implementation of driver core's struct device_driver and
related.

If ops.dealloc_driver is used then ib_dev will be freed upon return from
this function.

#### <a id="c-ib_unregister_device_and_put"></a>`ib_unregister_device_and_put()`

```c
void ib_unregister_device_and_put(struct ib_device *ib_dev)
```

Unregister a device while holding a 'get'

**Parameters**

- `struct ib_device *ib_dev`: The device to unregister

**Description**

This is the same as [`ib_unregister_device()`](#c-ib_unregister_device), except it includes an internal
[`ib_device_put()`](#c-ib_device_put) that should match a 'get' obtained by the caller.

It is safe to call this routine concurrently from multiple threads while
holding the 'get'. When the function returns the device is fully
unregistered.

Drivers using this flow MUST use the driver_unregister callback to clean up
their resources associated with the device and dealloc it.

#### <a id="c-ib_unregister_driver"></a>`ib_unregister_driver()`

```c
void ib_unregister_driver(enum rdma_driver_id driver_id)
```

Unregister all IB devices for a driver

**Parameters**

- `enum rdma_driver_id driver_id`: The driver to unregister

**Description**

This implements a fence for device unregistration. It only returns once all
devices associated with the driver_id have fully completed their
unregistration and returned from ib_unregister_device*().

If device's are not yet unregistered it goes ahead and starts unregistering
them.

This does not block creation of new devices with the given driver_id, that
is the responsibility of the caller.

#### <a id="c-ib_unregister_device_queued"></a>`ib_unregister_device_queued()`

```c
void ib_unregister_device_queued(struct ib_device *ib_dev)
```

Unregister a device using a work queue

**Parameters**

- `struct ib_device *ib_dev`: The device to unregister

**Description**

This schedules an asynchronous unregistration using a WQ for the device. A
driver should use this to avoid holding locks while doing unregistration,
such as holding the RTNL lock.

Drivers using this API must use ib_unregister_driver before module unload
to ensure that all scheduled unregistrations have completed.

#### <a id="c-ib_register_client"></a>`ib_register_client()`

```c
int ib_register_client(struct ib_client *client)
```

Register an IB client

**Parameters**

- `struct ib_client *client`: Client to register

**Description**

Upper level users of the IB drivers can use [`ib_register_client()`](#c-ib_register_client) to
register callbacks for IB device addition and removal.  When an IB
device is added, each registered client's add method will be called
(in the order the clients were registered), and when a device is
removed, each client's remove method will be called (in the reverse
order that clients were registered).  In addition, when
[`ib_register_client()`](#c-ib_register_client) is called, the client will receive an add
callback for all devices already registered.

#### <a id="c-ib_unregister_client"></a>`ib_unregister_client()`

```c
void ib_unregister_client(struct ib_client *client)
```

Unregister an IB client

**Parameters**

- `struct ib_client *client`: Client to unregister

**Description**

Upper level users use [`ib_unregister_client()`](#c-ib_unregister_client) to remove their client
registration.  When [`ib_unregister_client()`](#c-ib_unregister_client) is called, the client
will receive a remove callback for each IB device still registered.

This is a full fence, once it returns no client callbacks will be called,
or are running in another thread.

#### <a id="c-ib_set_client_data"></a>`ib_set_client_data()`

```c
void ib_set_client_data(struct ib_device *device, struct ib_client *client, void *data)
```

Set IB client context

**Parameters**

- `struct ib_device *device`: Device to set context for
- `struct ib_client *client`: Client to set context for
- `void *data`: Context to set

**Description**

[`ib_set_client_data()`](#c-ib_set_client_data) sets client context data that can be retrieved with
`ib_get_client_data()`. This can only be called while the client is
registered to the device, once the ib_client `remove()` callback returns this
cannot be called.

#### <a id="c-ib_register_event_handler"></a>`ib_register_event_handler()`

```c
void ib_register_event_handler(struct ib_event_handler *event_handler)
```

Register an IB event handler

**Parameters**

- `struct ib_event_handler *event_handler`: Handler to register

**Description**

[`ib_register_event_handler()`](#c-ib_register_event_handler) registers an event handler that will be
called back when asynchronous IB events occur (as defined in
chapter 11 of the InfiniBand Architecture Specification). This
callback occurs in workqueue context.

#### <a id="c-ib_unregister_event_handler"></a>`ib_unregister_event_handler()`

```c
void ib_unregister_event_handler(struct ib_event_handler *event_handler)
```

Unregister an event handler

**Parameters**

- `struct ib_event_handler *event_handler`: Handler to unregister

**Description**

Unregister an event handler registered with
[`ib_register_event_handler()`](#c-ib_register_event_handler).

#### <a id="c-ib_query_port"></a>`ib_query_port()`

```c
int ib_query_port(struct ib_device *device, u32 port_num, struct ib_port_attr *port_attr)
```

Query IB port attributes

**Parameters**

- `struct ib_device *device`: Device to query
- `u32 port_num`: Port number to query
- `struct ib_port_attr *port_attr`: Port attributes

**Description**

[`ib_query_port()`](#c-ib_query_port) returns the attributes of a port through the
**port_attr** pointer.

#### <a id="c-ib_device_set_netdev"></a>`ib_device_set_netdev()`

```c
int ib_device_set_netdev(struct ib_device *ib_dev, struct net_device *ndev, u32 port)
```

Associate the ib_dev with an underlying net_device

**Parameters**

- `struct ib_device *ib_dev`: Device to modify
- `struct net_device *ndev`: net_device to affiliate, may be NULL
- `u32 port`: IB port the net_device is connected to

**Description**

Drivers should use this to link the ib_device to a netdev so the netdev
shows up in interfaces like ib_enum_roce_netdev. Only one netdev may be
affiliated with any port.

The caller must ensure that the given ndev is not unregistered or
unregistering, and that either the ib_device is unregistered or
[`ib_device_set_netdev()`](#c-ib_device_set_netdev) is called with NULL when the ndev sends a
NETDEV_UNREGISTER event.

#### <a id="c-ib_query_netdev_port"></a>`ib_query_netdev_port()`

```c
int ib_query_netdev_port(struct ib_device *ibdev, struct net_device *ndev, u32 *port)
```

Query the port number of a net_device associated with an ibdev

**Parameters**

- `struct ib_device *ibdev`: IB device
- `struct net_device *ndev`: Network device
- `u32 *port`: IB port the net_device is connected to

#### <a id="c-ib_device_get_by_netdev"></a>`ib_device_get_by_netdev()`

```c
struct ib_device * ib_device_get_by_netdev(struct net_device *ndev, enum rdma_driver_id driver_id)
```

Find an IB device associated with a netdev

**Parameters**

- `struct net_device *ndev`: netdev to locate
- `enum rdma_driver_id driver_id`: The driver ID that must match (RDMA_DRIVER_UNKNOWN matches all)

**Description**

Find and hold an ib_device that is associated with a netdev via
[`ib_device_set_netdev()`](#c-ib_device_set_netdev). The caller must call [`ib_device_put()`](#c-ib_device_put) on the
returned pointer.

#### <a id="c-ib_query_pkey"></a>`ib_query_pkey()`

```c
int ib_query_pkey(struct ib_device *device, u32 port_num, u16 index, u16 *pkey)
```

Get P_Key table entry

**Parameters**

- `struct ib_device *device`: Device to query
- `u32 port_num`: Port number to query
- `u16 index`: P_Key table index to query
- `u16 *pkey`: Returned P_Key

**Description**

[`ib_query_pkey()`](#c-ib_query_pkey) fetches the specified P_Key table entry.

#### <a id="c-ib_modify_device"></a>`ib_modify_device()`

```c
int ib_modify_device(struct ib_device *device, int device_modify_mask, struct ib_device_modify *device_modify)
```

Change IB device attributes

**Parameters**

- `struct ib_device *device`: Device to modify
- `int device_modify_mask`: Mask of attributes to change
- `struct ib_device_modify *device_modify`: New attribute values

**Description**

[`ib_modify_device()`](#c-ib_modify_device) changes a device's attributes as specified by
the **device_modify_mask** and **device_modify** structure.

#### <a id="c-ib_modify_port"></a>`ib_modify_port()`

```c
int ib_modify_port(struct ib_device *device, u32 port_num, int port_modify_mask, struct ib_port_modify *port_modify)
```

Modifies the attributes for the specified port.

**Parameters**

- `struct ib_device *device`: The device to modify.
- `u32 port_num`: The number of the port to modify.
- `int port_modify_mask`: Mask used to specify which attributes of the port
  to change.
- `struct ib_port_modify *port_modify`: New attribute values for the port.

**Description**

[`ib_modify_port()`](#c-ib_modify_port) changes a port's attributes as specified by the
**port_modify_mask** and **port_modify** structure.

#### <a id="c-ib_find_gid"></a>`ib_find_gid()`

```c
int ib_find_gid(struct ib_device *device, union ib_gid *gid, u32 *port_num, u16 *index)
```

Returns the port number and GID table index where a specified GID value occurs. Its searches only for IB link layer.

**Parameters**

- `struct ib_device *device`: The device to query.
- `union ib_gid *gid`: The GID value to search for.
- `u32 *port_num`: The port number of the device where the GID value was found.
- `u16 *index`: The index into the GID table where the GID was found.  This
  parameter may be NULL.

#### <a id="c-ib_find_pkey"></a>`ib_find_pkey()`

```c
int ib_find_pkey(struct ib_device *device, u32 port_num, u16 pkey, u16 *index)
```

Returns the PKey table index where a specified PKey value occurs.

**Parameters**

- `struct ib_device *device`: The device to query.
- `u32 port_num`: The port number of the device to search for the PKey.
- `u16 pkey`: The PKey value to search for.
- `u16 *index`: The index into the PKey table where the PKey was found.

#### <a id="c-ib_get_net_dev_by_params"></a>`ib_get_net_dev_by_params()`

```c
struct net_device * ib_get_net_dev_by_params(struct ib_device *dev, u32 port, u16 pkey, const union ib_gid *gid, const struct sockaddr *addr)
```

Return the appropriate net_dev for a received CM request

**Parameters**

- `struct ib_device *dev`: An RDMA device on which the request has been received.
- `u32 port`: Port number on the RDMA device.
- `u16 pkey`: The Pkey the request came on.
- `const union ib_gid *gid`: A GID that the net_dev uses to communicate.
- `const struct sockaddr *addr`: Contains the IP address that the request specified as its
  destination.



#### <a id="c-__ib_alloc_pd"></a>`__ib_alloc_pd()`

```c
struct ib_pd * __ib_alloc_pd(struct ib_device *device, unsigned int flags, const char *caller)
```

Allocates an unused protection domain.

**Parameters**

- `struct ib_device *device`: The device on which to allocate the protection domain.
- `unsigned int flags`: protection domain flags
- `const char *caller`: caller's build-time module name

**Description**

A protection domain object provides an association between QPs, shared
receive queues, address handles, memory regions, and memory windows.

Every PD has a local_dma_lkey which can be used as the lkey value for local
memory operations.

#### <a id="c-ib_dealloc_pd_user"></a>`ib_dealloc_pd_user()`

```c
int ib_dealloc_pd_user(struct ib_pd *pd, struct ib_udata *udata)
```

Deallocates a protection domain.

**Parameters**

- `struct ib_pd *pd`: The protection domain to deallocate.
- `struct ib_udata *udata`: Valid user data or NULL for kernel object

**Description**

It is an error to call this function while any resources in the pd still
exist.  The caller is responsible to synchronously destroy them and
guarantee no new allocations will happen.

#### <a id="c-rdma_copy_ah_attr"></a>`rdma_copy_ah_attr()`

```c
void rdma_copy_ah_attr(struct rdma_ah_attr *dest, const struct rdma_ah_attr *src)
```

Copy rdma ah attribute from source to destination.

**Parameters**

- `struct rdma_ah_attr *dest`: Pointer to destination ah_attr. Contents of the destination
  pointer is assumed to be invalid and attribute are overwritten.
- `const struct rdma_ah_attr *src`: Pointer to source ah_attr.

#### <a id="c-rdma_replace_ah_attr"></a>`rdma_replace_ah_attr()`

```c
void rdma_replace_ah_attr(struct rdma_ah_attr *old, const struct rdma_ah_attr *new)
```

Replace valid ah_attr with new one.

**Parameters**

- `struct rdma_ah_attr *old`: Pointer to existing ah_attr which needs to be replaced.
  old is assumed to be valid or zero'd
- `const struct rdma_ah_attr *new`: Pointer to the new ah_attr.

**Description**

[`rdma_replace_ah_attr()`](#c-rdma_replace_ah_attr) first releases any reference in the old ah_attr if
old the ah_attr is valid; after that it copies the new attribute and holds
the reference to the replaced ah_attr.

#### <a id="c-rdma_move_ah_attr"></a>`rdma_move_ah_attr()`

```c
void rdma_move_ah_attr(struct rdma_ah_attr *dest, struct rdma_ah_attr *src)
```

Move ah_attr pointed by source to destination.

**Parameters**

- `struct rdma_ah_attr *dest`: Pointer to destination ah_attr to copy to.
  dest is assumed to be valid or zero'd
- `struct rdma_ah_attr *src`: Pointer to the new ah_attr.

**Description**

[`rdma_move_ah_attr()`](#c-rdma_move_ah_attr) first releases any reference in the destination ah_attr
if it is valid. This also transfers ownership of internal references from
src to dest, making src invalid in the process. No new reference of the src
ah_attr is taken.

#### <a id="c-rdma_create_ah"></a>`rdma_create_ah()`

```c
struct ib_ah * rdma_create_ah(struct ib_pd *pd, struct rdma_ah_attr *ah_attr, u32 flags)
```

Creates an address handle for the given address vector.

**Parameters**

- `struct ib_pd *pd`: The protection domain associated with the address handle.
- `struct rdma_ah_attr *ah_attr`: The attributes of the address vector.
- `u32 flags`: Create address handle flags (see enum rdma_create_ah_flags).

**Description**

It returns 0 on success and returns appropriate error code on error.
The address handle is used to reference a local or global destination
in all UD QP post sends.

#### <a id="c-rdma_create_user_ah"></a>`rdma_create_user_ah()`

```c
struct ib_ah * rdma_create_user_ah(struct ib_pd *pd, struct rdma_ah_attr *ah_attr, struct ib_udata *udata)
```

Creates an address handle for the given address vector. It resolves destination mac address for ah attribute of RoCE type.

**Parameters**

- `struct ib_pd *pd`: The protection domain associated with the address handle.
- `struct rdma_ah_attr *ah_attr`: The attributes of the address vector.
- `struct ib_udata *udata`: pointer to user's input output buffer information need by
  provider driver.

**Description**

It returns 0 on success and returns appropriate error code on error.
The address handle is used to reference a local or global destination
in all UD QP post sends.

#### <a id="c-rdma_move_grh_sgid_attr"></a>`rdma_move_grh_sgid_attr()`

```c
void rdma_move_grh_sgid_attr(struct rdma_ah_attr *attr, union ib_gid *dgid, u32 flow_label, u8 hop_limit, u8 traffic_class, const struct ib_gid_attr *sgid_attr)
```

Sets the sgid attribute of GRH, taking ownership of the reference

**Parameters**

- `struct rdma_ah_attr *attr`: Pointer to AH attribute structure
- `union ib_gid *dgid`: Destination GID
- `u32 flow_label`: Flow label
- `u8 hop_limit`: Hop limit
- `u8 traffic_class`: traffic class
- `const struct ib_gid_attr *sgid_attr`: Pointer to SGID attribute

**Description**

This takes ownership of the sgid_attr reference. The caller must ensure
[`rdma_destroy_ah_attr()`](#c-rdma_destroy_ah_attr) is called before destroying the rdma_ah_attr after
calling this function.

#### <a id="c-rdma_destroy_ah_attr"></a>`rdma_destroy_ah_attr()`

```c
void rdma_destroy_ah_attr(struct rdma_ah_attr *ah_attr)
```

Release reference to SGID attribute of ah attribute.

**Parameters**

- `struct rdma_ah_attr *ah_attr`: Pointer to ah attribute

**Description**

Release reference to the SGID attribute of the ah attribute if it is
non NULL. It is safe to call this multiple times, and safe to call it on
a zero initialized ah_attr.

#### <a id="c-ib_create_srq_user"></a>`ib_create_srq_user()`

```c
struct ib_srq * ib_create_srq_user(struct ib_pd *pd, struct ib_srq_init_attr *srq_init_attr, struct ib_usrq_object *uobject, struct ib_udata *udata)
```

Creates a SRQ associated with the specified protection domain.

**Parameters**

- `struct ib_pd *pd`: The protection domain associated with the SRQ.
- `struct ib_srq_init_attr *srq_init_attr`: A list of initial attributes required to create the
  SRQ.  If SRQ creation succeeds, then the attributes are updated to
  the actual capabilities of the created SRQ.
- `struct ib_usrq_object *uobject`: uobject pointer if this is not a kernel SRQ
- `struct ib_udata *udata`: udata pointer if this is not a kernel SRQ

**Description**

srq_attr->max_wr and srq_attr->max_sge are read the determine the
requested size of the SRQ, and set to the actual values allocated
on return.  If `ib_create_srq()` succeeds, then max_wr and max_sge
will always be at least as large as the requested values.

#### <a id="c-ib_create_qp_user"></a>`ib_create_qp_user()`

```c
struct ib_qp * ib_create_qp_user(struct ib_device *dev, struct ib_pd *pd, struct ib_qp_init_attr *attr, struct ib_udata *udata, struct ib_uqp_object *uobj, const char *caller)
```

Creates a QP associated with the specified protection domain.

**Parameters**

- `struct ib_device *dev`: IB device
- `struct ib_pd *pd`: The protection domain associated with the QP.
- `struct ib_qp_init_attr *attr`: A list of initial attributes required to create the
  QP.  If QP creation succeeds, then the attributes are updated to
  the actual capabilities of the created QP.
- `struct ib_udata *udata`: User data
- `struct ib_uqp_object *uobj`: uverbs obect
- `const char *caller`: caller's build-time module name

#### <a id="c-ib_modify_qp_with_udata"></a>`ib_modify_qp_with_udata()`

```c
int ib_modify_qp_with_udata(struct ib_qp *ib_qp, struct ib_qp_attr *attr, int attr_mask, struct ib_udata *udata)
```

Modifies the attributes for the specified QP.

**Parameters**

- `struct ib_qp *ib_qp`: The QP to modify.
- `struct ib_qp_attr *attr`: On input, specifies the QP attributes to modify.  On output,
  the current values of selected QP attributes are returned.
- `int attr_mask`: A bit-mask used to specify which attributes of the QP
  are being modified.
- `struct ib_udata *udata`: pointer to user's input output buffer information
  are being modified.
  It returns 0 on success and returns appropriate error code on error.

#### <a id="c-ib_alloc_mr"></a>`ib_alloc_mr()`

```c
struct ib_mr * ib_alloc_mr(struct ib_pd *pd, enum ib_mr_type mr_type, u32 max_num_sg)
```

Allocates a memory region

**Parameters**

- `struct ib_pd *pd`: protection domain associated with the region
- `enum ib_mr_type mr_type`: memory region type
- `u32 max_num_sg`: maximum sg entries available for registration.

**Notes**

Memory registeration page/sg lists must not exceed max_num_sg.
For mr_type IB_MR_TYPE_MEM_REG, the total length cannot exceed
max_num_sg * used_page_size.

#### <a id="c-ib_alloc_mr_integrity"></a>`ib_alloc_mr_integrity()`

```c
struct ib_mr * ib_alloc_mr_integrity(struct ib_pd *pd, u32 max_num_data_sg, u32 max_num_meta_sg)
```

Allocates an integrity memory region

**Parameters**

- `struct ib_pd *pd`: protection domain associated with the region
- `u32 max_num_data_sg`: maximum data sg entries available for registration
- `u32 max_num_meta_sg`: maximum metadata sg entries available for
  registration

**Notes**

Memory registration page/sg lists must not exceed max_num_sg,
also the integrity page/sg lists must not exceed max_num_meta_sg.

#### <a id="c-ib_alloc_xrcd_user"></a>`ib_alloc_xrcd_user()`

```c
struct ib_xrcd * ib_alloc_xrcd_user(struct ib_device *device, struct inode *inode, struct ib_udata *udata)
```

Allocates an XRC domain.

**Parameters**

- `struct ib_device *device`: The device on which to allocate the XRC domain.
- `struct inode *inode`: inode to connect XRCD
- `struct ib_udata *udata`: Valid user data or NULL for kernel object

#### <a id="c-ib_dealloc_xrcd_user"></a>`ib_dealloc_xrcd_user()`

```c
int ib_dealloc_xrcd_user(struct ib_xrcd *xrcd, struct ib_udata *udata)
```

Deallocates an XRC domain.

**Parameters**

- `struct ib_xrcd *xrcd`: The XRC domain to deallocate.
- `struct ib_udata *udata`: Valid user data or NULL for kernel object

#### <a id="c-ib_create_wq"></a>`ib_create_wq()`

```c
struct ib_wq * ib_create_wq(struct ib_pd *pd, struct ib_wq_init_attr *wq_attr)
```

Creates a WQ associated with the specified protection domain.

**Parameters**

- `struct ib_pd *pd`: The protection domain associated with the WQ.
- `struct ib_wq_init_attr *wq_attr`: A list of initial attributes required to create the
  WQ. If WQ creation succeeds, then the attributes are updated to
  the actual capabilities of the created WQ.

**Description**

wq_attr->max_wr and wq_attr->max_sge determine
the requested size of the WQ, and set to the actual values allocated
on return.
If [`ib_create_wq()`](#c-ib_create_wq) succeeds, then max_wr and max_sge will always be
at least as large as the requested values.

#### <a id="c-ib_destroy_wq_user"></a>`ib_destroy_wq_user()`

```c
int ib_destroy_wq_user(struct ib_wq *wq, struct ib_udata *udata)
```

Destroys the specified user WQ.

**Parameters**

- `struct ib_wq *wq`: The WQ to destroy.
- `struct ib_udata *udata`: Valid user data

#### <a id="c-ib_map_mr_sg_pi"></a>`ib_map_mr_sg_pi()`

```c
int ib_map_mr_sg_pi(struct ib_mr *mr, struct scatterlist *data_sg, int data_sg_nents, unsigned int *data_sg_offset, struct scatterlist *meta_sg, int meta_sg_nents, unsigned int *meta_sg_offset, unsigned int page_size)
```

Map the dma mapped SG lists for PI (protection information) and set an appropriate memory region for registration.

**Parameters**

- `struct ib_mr *mr`: memory region
- `struct scatterlist *data_sg`: dma mapped scatterlist for data
- `int data_sg_nents`: number of entries in data_sg
- `unsigned int *data_sg_offset`: offset in bytes into data_sg
- `struct scatterlist *meta_sg`: dma mapped scatterlist for metadata
- `int meta_sg_nents`: number of entries in meta_sg
- `unsigned int *meta_sg_offset`: offset in bytes into meta_sg
- `unsigned int page_size`: page vector desired page size

**Description**

Constraints:
- The MR must be allocated with type IB_MR_TYPE_INTEGRITY.

After this completes successfully, the  memory region
is ready for registration.

**Return**

0 on success.

#### <a id="c-ib_map_mr_sg"></a>`ib_map_mr_sg()`

```c
int ib_map_mr_sg(struct ib_mr *mr, struct scatterlist *sg, int sg_nents, unsigned int *sg_offset, unsigned int page_size)
```

Map the largest prefix of a dma mapped SG list and set it the memory region.

**Parameters**

- `struct ib_mr *mr`: memory region
- `struct scatterlist *sg`: dma mapped scatterlist
- `int sg_nents`: number of entries in sg
- `unsigned int *sg_offset`: offset in bytes into sg
- `unsigned int page_size`: page vector desired page size

**Description**

Constraints:

- The first sg element is allowed to have an offset.
- Each sg element must either be aligned to page_size or virtually
  contiguous to the previous element. In case an sg element has a
  non-contiguous offset, the mapping prefix will not include it.
- The last sg element is allowed to have length less than page_size.
- If sg_nents total byte length exceeds the mr max_num_sge * page_size
  then only max_num_sg entries will be mapped.
- If the MR was allocated with type IB_MR_TYPE_SG_GAPS, none of these
  constraints holds and the page_size argument is ignored.

Returns the number of sg elements that were mapped to the memory region.

After this completes successfully, the  memory region
is ready for registration.

#### <a id="c-ib_sg_to_pages"></a>`ib_sg_to_pages()`

```c
int ib_sg_to_pages(struct ib_mr *mr, struct scatterlist *sgl, int sg_nents, unsigned int *sg_offset_p, int (*set_page)(struct ib_mr *, u64))
```

Convert the largest prefix of a sg list to a page vector

**Parameters**

- `struct ib_mr *mr`: memory region
- `struct scatterlist *sgl`: dma mapped scatterlist
- `int sg_nents`: number of entries in sg
- `unsigned int *sg_offset_p`:

  ```text
  ==== =======================================================
  IN   start offset in bytes into sg
  OUT  offset in bytes for element n of the sg of the first
       byte that has not been processed where n is the return
       value of this function.
  ==== =======================================================
  ```
- `int (*set_page)(struct ib_mr *, u64)`: driver page assignment function pointer

**Description**

Core service helper for drivers to convert the largest
prefix of given sg list to a page vector. The sg list
prefix converted is the prefix that meet the requirements
of ib_map_mr_sg.

Returns the number of sg elements that were assigned to
a page vector.

#### <a id="c-ib_drain_sq"></a>`ib_drain_sq()`

```c
void ib_drain_sq(struct ib_qp *qp)
```

Block until all SQ CQEs have been consumed by the application.

**Parameters**

- `struct ib_qp *qp`: queue pair to drain

**Description**

If the device has a provider-specific drain function, then
call that.  Otherwise call the generic drain function
`__ib_drain_sq()`.

The caller must:

ensure there is room in the CQ and SQ for the drain work request and
completion.

allocate the CQ using `ib_alloc_cq()`.

ensure that there are no other contexts that are posting WRs concurrently.
Otherwise the drain is not guaranteed.

#### <a id="c-ib_drain_rq"></a>`ib_drain_rq()`

```c
void ib_drain_rq(struct ib_qp *qp)
```

Block until all RQ CQEs have been consumed by the application.

**Parameters**

- `struct ib_qp *qp`: queue pair to drain

**Description**

If the device has a provider-specific drain function, then
call that.  Otherwise call the generic drain function
`__ib_drain_rq()`.

The caller must:

ensure there is room in the CQ and RQ for the drain work request and
completion.

allocate the CQ using `ib_alloc_cq()`.

ensure that there are no other contexts that are posting WRs concurrently.
Otherwise the drain is not guaranteed.

#### <a id="c-ib_drain_qp"></a>`ib_drain_qp()`

```c
void ib_drain_qp(struct ib_qp *qp)
```

Block until all CQEs have been consumed by the application on both the RQ and SQ.

**Parameters**

- `struct ib_qp *qp`: queue pair to drain

**Description**

The caller must:

ensure there is room in the CQ(s), SQ, and RQ for drain work requests
and completions.

allocate the CQs using `ib_alloc_cq()`.

ensure that there are no other contexts that are posting WRs concurrently.
Otherwise the drain is not guaranteed.

#### <a id="c-rdma_alloc_hw_stats_struct"></a>`rdma_alloc_hw_stats_struct()`

```c
struct rdma_hw_stats * rdma_alloc_hw_stats_struct(const struct rdma_stat_desc *descs, int num_counters, unsigned long lifespan)
```

Helper function to allocate dynamic struct for the drivers.

**Parameters**

- `const struct rdma_stat_desc *descs`: array of static descriptors
- `int num_counters`: number of elements in array
- `unsigned long lifespan`: milliseconds between updates

#### <a id="c-rdma_free_hw_stats_struct"></a>`rdma_free_hw_stats_struct()`

```c
void rdma_free_hw_stats_struct(struct rdma_hw_stats *stats)
```

Helper function to release rdma_hw_stats

**Parameters**

- `struct rdma_hw_stats *stats`: statistics to release



#### <a id="c-ib_pack"></a>`ib_pack()`

```c
void ib_pack(const struct ib_field *desc, int desc_len, void *structure, void *buf)
```

Pack a structure into a buffer

**Parameters**

- `const struct ib_field *desc`: Array of structure field descriptions
- `int desc_len`: Number of entries in **desc**
- `void *structure`: Structure to pack from
- `void *buf`: Buffer to pack into

**Description**

[`ib_pack()`](#c-ib_pack) packs a list of structure fields into a buffer,
controlled by the array of fields in **desc**.

#### <a id="c-ib_unpack"></a>`ib_unpack()`

```c
void ib_unpack(const struct ib_field *desc, int desc_len, void *buf, void *structure)
```

Unpack a buffer into a structure

**Parameters**

- `const struct ib_field *desc`: Array of structure field descriptions
- `int desc_len`: Number of entries in **desc**
- `void *buf`: Buffer to unpack from
- `void *structure`: Structure to unpack into

**Description**

[`ib_pack()`](#c-ib_pack) unpacks a list of structure fields from a buffer,
controlled by the array of fields in **desc**.



#### <a id="c-ib_sa_cancel_query"></a>`ib_sa_cancel_query()`

```c
void ib_sa_cancel_query(int id, struct ib_sa_query *query)
```

try to cancel an SA query

**Parameters**

- `int id`: ID of query to cancel
- `struct ib_sa_query *query`: query pointer to cancel

**Description**

Try to cancel an SA query.  If the id and query don't match up or
the query has already completed, nothing is done.  Otherwise the
query is canceled and will complete with a status of -EINTR.

#### <a id="c-ib_init_ah_attr_from_path"></a>`ib_init_ah_attr_from_path()`

```c
int ib_init_ah_attr_from_path(struct ib_device *device, u32 port_num, struct sa_path_rec *rec, struct rdma_ah_attr *ah_attr, const struct ib_gid_attr *gid_attr)
```

Initialize address handle attributes based on an SA path record.

**Parameters**

- `struct ib_device *device`: Device associated ah attributes initialization.
- `u32 port_num`: Port on the specified device.
- `struct sa_path_rec *rec`: path record entry to use for ah attributes initialization.
- `struct rdma_ah_attr *ah_attr`: address handle attributes to initialization from path record.
- `const struct ib_gid_attr *gid_attr`: SGID attribute to consider during initialization.

**Description**

When [`ib_init_ah_attr_from_path()`](#c-ib_init_ah_attr_from_path) returns success,
(a) for IB link layer it optionally contains a reference to SGID attribute
when GRH is present for IB link layer.
(b) for RoCE link layer it contains a reference to SGID attribute.
User must invoke [`rdma_destroy_ah_attr()`](#c-rdma_destroy_ah_attr) to release reference to SGID
attributes which are initialized using [`ib_init_ah_attr_from_path()`](#c-ib_init_ah_attr_from_path).

#### <a id="c-ib_sa_path_rec_get"></a>`ib_sa_path_rec_get()`

```c
int ib_sa_path_rec_get(struct ib_sa_client *client, struct ib_device *device, u32 port_num, struct sa_path_rec *rec, ib_sa_comp_mask comp_mask, unsigned long timeout_ms, gfp_t gfp_mask, void (*callback)(int status, struct sa_path_rec *resp, unsigned int num_paths, void *context), void *context, struct ib_sa_query **sa_query)
```

Start a Path get query

**Parameters**

- `struct ib_sa_client *client`: SA client
- `struct ib_device *device`: device to send query on
- `u32 port_num`: port number to send query on
- `struct sa_path_rec *rec`: Path Record to send in query
- `ib_sa_comp_mask comp_mask`: component mask to send in query
- `unsigned long timeout_ms`: time to wait for response
- `gfp_t gfp_mask`: GFP mask to use for internal allocations
- `void (*callback)(int status, struct sa_path_rec *resp, unsigned int num_paths, void *context)`: function called when query completes, times out or is
  canceled
- `void *context`: opaque user context passed to callback
- `struct ib_sa_query **sa_query`: query context, used to cancel query

**Description**

Send a Path Record Get query to the SA to look up a path.  The
callback function will be called when the query completes (or
fails); status is 0 for a successful response, -EINTR if the query
is canceled, -ETIMEDOUT is the query timed out, or -EIO if an error
occurred sending the query.  The resp parameter of the callback is
only valid if status is 0.

If the return value of [`ib_sa_path_rec_get()`](#c-ib_sa_path_rec_get) is negative, it is an
error code.  Otherwise it is a query ID that can be used to cancel
the query.

#### <a id="c-ib_sa_service_rec_get"></a>`ib_sa_service_rec_get()`

```c
int ib_sa_service_rec_get(struct ib_sa_client *client, struct ib_device *device, u32 port_num, struct sa_service_rec *rec, ib_sa_comp_mask comp_mask, unsigned long timeout_ms, gfp_t gfp_mask, void (*callback)(int status, struct sa_service_rec *resp, unsigned int num_services, void *context), void *context, struct ib_sa_query **sa_query)
```

Start a Service get query

**Parameters**

- `struct ib_sa_client *client`: SA client
- `struct ib_device *device`: device to send query on
- `u32 port_num`: port number to send query on
- `struct sa_service_rec *rec`: Service Record to send in query
- `ib_sa_comp_mask comp_mask`: component mask to send in query
- `unsigned long timeout_ms`: time to wait for response
- `gfp_t gfp_mask`: GFP mask to use for internal allocations
- `void (*callback)(int status, struct sa_service_rec *resp, unsigned int num_services, void *context)`: function called when query completes, times out or is
  canceled
- `void *context`: opaque user context passed to callback
- `struct ib_sa_query **sa_query`: query context, used to cancel query

**Description**

Send a Service Record Get query to the SA to look up a path.  The
callback function will be called when the query completes (or
fails); status is 0 for a successful response, -EINTR if the query
is canceled, -ETIMEDOUT is the query timed out, or -EIO if an error
occurred sending the query.  The resp parameter of the callback is
only valid if status is 0.

If the return value of [`ib_sa_service_rec_get()`](#c-ib_sa_service_rec_get) is negative, it is an
error code. Otherwise it is a query ID that can be used to cancel
the query.



#### <a id="c-ib_ud_header_init"></a>`ib_ud_header_init()`

```c
int ib_ud_header_init(int payload_bytes, int lrh_present, int eth_present, int vlan_present, int grh_present, int ip_version, int udp_present, int immediate_present, struct ib_ud_header *header)
```

Initialize UD header structure

**Parameters**

- `int payload_bytes`: Length of packet payload
- `int lrh_present`: specify if LRH is present
- `int eth_present`: specify if Eth header is present
- `int vlan_present`: packet is tagged vlan
- `int grh_present`: GRH flag (if non-zero, GRH will be included)
- `int ip_version`: if non-zero, IP header, V4 or V6, will be included
- `int udp_present`: if non-zero, UDP header will be included
- `int immediate_present`: specify if immediate data is present
- `struct ib_ud_header *header`: Structure to initialize

#### <a id="c-ib_ud_header_pack"></a>`ib_ud_header_pack()`

```c
int ib_ud_header_pack(struct ib_ud_header *header, void *buf)
```

Pack UD header struct into wire format

**Parameters**

- `struct ib_ud_header *header`: UD header struct
- `void *buf`: Buffer to pack into

**Description**

[`ib_ud_header_pack()`](#c-ib_ud_header_pack) packs the UD header structure **header** into wire
format in the buffer **buf**.



#### <a id="c-ib_umem_find_best_pgsz"></a>`ib_umem_find_best_pgsz()`

```c
unsigned long ib_umem_find_best_pgsz(struct ib_umem *umem, unsigned long pgsz_bitmap, unsigned long virt)
```

Find best HW page size to use for this MR

**Parameters**

- `struct ib_umem *umem`: umem struct
- `unsigned long pgsz_bitmap`: bitmap of HW supported page sizes
- `unsigned long virt`: IOVA

**Description**

This helper is intended for HW that support multiple page
sizes but can do only a single page size in an MR.

Returns 0 if the umem requires page sizes not supported by
the driver to be mapped. Drivers always supporting PAGE_SIZE
or smaller will never see a 0 result.

#### <a id="c-ib_umem_get"></a>`ib_umem_get()`

```c
struct ib_umem * ib_umem_get(struct ib_device *device, unsigned long addr, size_t size, int access)
```

Pin and DMA map userspace memory.

**Parameters**

- `struct ib_device *device`: IB device to connect UMEM
- `unsigned long addr`: userspace virtual address to start at
- `size_t size`: length of region to pin
- `int access`: IB_ACCESS_xxx flags for memory being pinned

#### <a id="c-ib_umem_release"></a>`ib_umem_release()`

```c
void ib_umem_release(struct ib_umem *umem)
```

release memory pinned with ib_umem_get

**Parameters**

- `struct ib_umem *umem`: umem struct to release



#### <a id="c-ib_umem_odp_alloc_implicit"></a>`ib_umem_odp_alloc_implicit()`

```c
struct ib_umem_odp * ib_umem_odp_alloc_implicit(struct ib_device *device, int access)
```

Allocate a parent implicit ODP umem

**Parameters**

- `struct ib_device *device`: IB device to create UMEM
- `int access`: ib_reg_mr access flags

**Description**

Implicit ODP umems do not have a VA range and do not have any page lists.
They exist only to hold the per_mm reference to help the driver create
children umems.

#### <a id="c-ib_umem_odp_alloc_child"></a>`ib_umem_odp_alloc_child()`

```c
struct ib_umem_odp * ib_umem_odp_alloc_child(struct ib_umem_odp *root, unsigned long addr, size_t size, const struct mmu_interval_notifier_ops *ops)
```

Allocate a child ODP umem under an implicit parent ODP umem

**Parameters**

- `struct ib_umem_odp *root`: The parent umem enclosing the child. This must be allocated using
  `ib_alloc_implicit_odp_umem()`
- `unsigned long addr`: The starting userspace VA
- `size_t size`: The length of the userspace VA
- `const struct mmu_interval_notifier_ops *ops`: MMU interval ops, currently only **invalidate**

#### <a id="c-ib_umem_odp_get"></a>`ib_umem_odp_get()`

```c
struct ib_umem_odp * ib_umem_odp_get(struct ib_device *device, unsigned long addr, size_t size, int access, const struct mmu_interval_notifier_ops *ops)
```

Create a umem_odp for a userspace va

**Parameters**

- `struct ib_device *device`: IB device struct to get UMEM
- `unsigned long addr`: userspace virtual address to start at
- `size_t size`: length of region to pin
- `int access`: IB_ACCESS_xxx flags for memory being pinned
- `const struct mmu_interval_notifier_ops *ops`: MMU interval ops, currently only **invalidate**

**Description**

The driver should use when the access flags indicate ODP memory. It avoids
pinning, instead, stores the mm for future page fault handling in
conjunction with MMU notifiers.

#### <a id="c-ib_umem_odp_map_dma_and_lock"></a>`ib_umem_odp_map_dma_and_lock()`

```c
int ib_umem_odp_map_dma_and_lock(struct ib_umem_odp *umem_odp, u64 user_virt, u64 bcnt, u64 access_mask, bool fault)
```

DMA map userspace memory in an ODP MR and lock it.

**Parameters**

- `struct ib_umem_odp *umem_odp`: the umem to map and pin
- `u64 user_virt`: the address from which we need to map.
- `u64 bcnt`: the minimal number of bytes to pin and map. The mapping might be
  bigger due to alignment, and may also be smaller in case of an error
  pinning or mapping a page. The actual pages mapped is returned in
  the return value.
- `u64 access_mask`: bit mask of the requested access permissions for the given
  range.
- `bool fault`: is faulting required for the given range

**Description**

Maps the range passed in the argument to DMA addresses.
Upon success the ODP MR will be locked to let caller complete its device
page table update.

Returns the number of pages mapped in success, negative error code
for failure.


<a id="rst-rdma-verbs-transport-library"></a>

## RDMA Verbs transport library


#### <a id="c-rvt_fast_reg_mr"></a>`rvt_fast_reg_mr()`

```c
int rvt_fast_reg_mr(struct rvt_qp *qp, struct ib_mr *ibmr, u32 key, int access)
```

fast register physical MR

**Parameters**

- `struct rvt_qp *qp`: the queue pair where the work request comes from
- `struct ib_mr *ibmr`: the memory region to be registered
- `u32 key`: updated key for this memory region
- `int access`: access flags for this memory region

**Description**

Returns 0 on success.

#### <a id="c-rvt_invalidate_rkey"></a>`rvt_invalidate_rkey()`

```c
int rvt_invalidate_rkey(struct rvt_qp *qp, u32 rkey)
```

invalidate an MR rkey

**Parameters**

- `struct rvt_qp *qp`: queue pair associated with the invalidate op
- `u32 rkey`: rkey to invalidate

**Description**

Returns 0 on success.

#### <a id="c-rvt_lkey_ok"></a>`rvt_lkey_ok()`

```c
int rvt_lkey_ok(struct rvt_lkey_table *rkt, struct rvt_pd *pd, struct rvt_sge *isge, struct rvt_sge *last_sge, struct ib_sge *sge, int acc)
```

check IB SGE for validity and initialize

**Parameters**

- `struct rvt_lkey_table *rkt`: table containing lkey to check SGE against
- `struct rvt_pd *pd`: protection domain
- `struct rvt_sge *isge`: outgoing internal SGE
- `struct rvt_sge *last_sge`: last outgoing SGE written
- `struct ib_sge *sge`: SGE to check
- `int acc`: access flags

**Description**

Check the IB SGE for validity and initialize our internal version
of it.

Increments the reference count when a new sge is stored.

**Return**

0 if compressed, 1 if added , otherwise returns -errno.

#### <a id="c-rvt_rkey_ok"></a>`rvt_rkey_ok()`

```c
int rvt_rkey_ok(struct rvt_qp *qp, struct rvt_sge *sge, u32 len, u64 vaddr, u32 rkey, int acc)
```

check the IB virtual address, length, and RKEY

**Parameters**

- `struct rvt_qp *qp`: qp for validation
- `struct rvt_sge *sge`: SGE state
- `u32 len`: length of data
- `u64 vaddr`: virtual address to place data
- `u32 rkey`: rkey to check
- `int acc`: access flags

**Return**

1 if successful, otherwise 0.

**Description**

increments the reference count upon success



#### <a id="c-rvt_compute_aeth"></a>`rvt_compute_aeth()`

```c
__be32 rvt_compute_aeth(struct rvt_qp *qp)
```

compute the AETH (syndrome + MSN)

**Parameters**

- `struct rvt_qp *qp`: the queue pair to compute the AETH for

**Description**

Returns the AETH.

#### <a id="c-rvt_get_credit"></a>`rvt_get_credit()`

```c
void rvt_get_credit(struct rvt_qp *qp, u32 aeth)
```

flush the send work queue of a QP

**Parameters**

- `struct rvt_qp *qp`: the qp who's send work queue to flush
- `u32 aeth`: the Acknowledge Extended Transport Header

**Description**

The QP s_lock should be held.

#### <a id="c-rvt_restart_sge"></a>`rvt_restart_sge()`

```c
u32 rvt_restart_sge(struct rvt_sge_state *ss, struct rvt_swqe *wqe, u32 len)
```

rewind the sge state for a wqe

**Parameters**

- `struct rvt_sge_state *ss`: the sge state pointer
- `struct rvt_swqe *wqe`: the wqe to rewind
- `u32 len`: the data length from the start of the wqe in bytes

**Description**

Returns the remaining data length.



#### <a id="c-rvt_check_ah"></a>`rvt_check_ah()`

```c
int rvt_check_ah(struct ib_device *ibdev, struct rdma_ah_attr *ah_attr)
```

validate the attributes of AH

**Parameters**

- `struct ib_device *ibdev`: the ib device
- `struct rdma_ah_attr *ah_attr`: the attributes of the AH

**Description**

If driver supports a more detailed check_ah function call back to it
otherwise just check the basics.

**Return**

0 on success



#### <a id="c-rvt_alloc_device"></a>`rvt_alloc_device()`

```c
struct rvt_dev_info * rvt_alloc_device(size_t size, int nports)
```

allocate rdi

**Parameters**

- `size_t size`: how big of a structure to allocate
- `int nports`: number of ports to allocate array slots for

**Description**

Use IB core device alloc to allocate space for the rdi which is assumed to be
inside of the ib_device. Any extra space that drivers require should be
included in size.

We also allocate a port array based on the number of ports.

**Return**

pointer to allocated rdi

#### <a id="c-rvt_dealloc_device"></a>`rvt_dealloc_device()`

```c
void rvt_dealloc_device(struct rvt_dev_info *rdi)
```

deallocate rdi

**Parameters**

- `struct rvt_dev_info *rdi`: structure to free

**Description**

Free a structure allocated with [`rvt_alloc_device()`](#c-rvt_alloc_device)

#### <a id="c-rvt_register_device"></a>`rvt_register_device()`

```c
int rvt_register_device(struct rvt_dev_info *rdi)
```

register a driver

**Parameters**

- `struct rvt_dev_info *rdi`: main dev structure for all of rdmavt operations

**Description**

It is up to drivers to allocate the rdi and fill in the appropriate
information.

**Return**

0 on success otherwise an errno.

#### <a id="c-rvt_unregister_device"></a>`rvt_unregister_device()`

```c
void rvt_unregister_device(struct rvt_dev_info *rdi)
```

remove a driver

**Parameters**

- `struct rvt_dev_info *rdi`: rvt dev struct

#### <a id="c-rvt_init_port"></a>`rvt_init_port()`

```c
int rvt_init_port(struct rvt_dev_info *rdi, struct rvt_ibport *port, int port_index, u16 *pkey_table)
```

init internal data for driver port

**Parameters**

- `struct rvt_dev_info *rdi`: rvt_dev_info struct
- `struct rvt_ibport *port`: rvt port
- `int port_index`: 0 based index of ports, different from IB core port num
- `u16 *pkey_table`: pkey_table for **port**

**Description**

Keep track of a list of ports. No need to have a detach port.
They persist until the driver goes away.

**Return**

always 0



#### <a id="c-rvt_cq_enter"></a>`rvt_cq_enter()`

```c
bool rvt_cq_enter(struct rvt_cq *cq, struct ib_wc *entry, bool solicited)
```

add a new entry to the completion queue

**Parameters**

- `struct rvt_cq *cq`: completion queue
- `struct ib_wc *entry`: work completion entry to add
- `bool solicited`: true if **entry** is solicited

**Description**

This may be called with qp->s_lock held.

**Return**

return true on success, else return
false if cq is full.



#### <a id="c-rvt_error_qp"></a>`rvt_error_qp()`

```c
int rvt_error_qp(struct rvt_qp *qp, enum ib_wc_status err)
```

put a QP into the error state

**Parameters**

- `struct rvt_qp *qp`: the QP to put into the error state
- `enum ib_wc_status err`: the receive completion error to signal if a RWQE is active

**Description**

Flushes both send and receive work queues.

**Return**

true if last WQE event should be generated.
The QP r_lock and s_lock should be held and interrupts disabled.
If we are already in error state, just return.

#### <a id="c-rvt_get_rwqe"></a>`rvt_get_rwqe()`

```c
int rvt_get_rwqe(struct rvt_qp *qp, bool wr_id_only)
```

copy the next RWQE into the QP's RWQE

**Parameters**

- `struct rvt_qp *qp`: the QP
- `bool wr_id_only`: update qp->r_wr_id only, not qp->r_sge

**Description**

Return -1 if there is a local error, 0 if no RWQE is available,
otherwise return 1.

Can be called from interrupt level.

#### <a id="c-rvt_comm_est"></a>`rvt_comm_est()`

```c
void rvt_comm_est(struct rvt_qp *qp)
```

handle trap with QP established

**Parameters**

- `struct rvt_qp *qp`: the QP

#### <a id="c-rvt_add_rnr_timer"></a>`rvt_add_rnr_timer()`

```c
void rvt_add_rnr_timer(struct rvt_qp *qp, u32 aeth)
```

add/start an rnr timer on the QP

**Parameters**

- `struct rvt_qp *qp`: the QP
- `u32 aeth`: aeth of RNR timeout, simulated aeth for loopback

#### <a id="c-rvt_stop_rc_timers"></a>`rvt_stop_rc_timers()`

```c
void rvt_stop_rc_timers(struct rvt_qp *qp)
```

stop all timers

**Parameters**

- `struct rvt_qp *qp`: the QP
  stop any pending timers

#### <a id="c-rvt_del_timers_sync"></a>`rvt_del_timers_sync()`

```c
void rvt_del_timers_sync(struct rvt_qp *qp)
```

wait for any timeout routines to exit

**Parameters**

- `struct rvt_qp *qp`: the QP

#### <a id="c-rvt_qp_iter_init"></a>`rvt_qp_iter_init()`

```c
struct rvt_qp_iter * rvt_qp_iter_init(struct rvt_dev_info *rdi, u64 v, void (*cb)(struct rvt_qp *qp, u64 v))
```

initial for QP iteration

**Parameters**

- `struct rvt_dev_info *rdi`: rvt devinfo
- `u64 v`: u64 value
- `void (*cb)(struct rvt_qp *qp, u64 v)`: user-defined callback

**Description**

This returns an iterator suitable for iterating QPs
in the system.

The **cb** is a user-defined callback and **v** is a 64-bit
value passed to and relevant for processing in the
**cb**.  An example use case would be to alter QP processing
based on criteria not part of the rvt_qp.

Use cases that require memory allocation to succeed
must preallocate appropriately.

**Return**

a pointer to an rvt_qp_iter or NULL

#### <a id="c-rvt_qp_iter_next"></a>`rvt_qp_iter_next()`

```c
int rvt_qp_iter_next(struct rvt_qp_iter *iter)
```

return the next QP in iter

**Parameters**

- `struct rvt_qp_iter *iter`: the iterator

**Description**

Fine grained QP iterator suitable for use
with debugfs seq_file mechanisms.

Updates iter->qp with the current QP when the return
value is 0.

**Return**

0 - iter->qp is valid 1 - no more QPs

#### <a id="c-rvt_qp_iter"></a>`rvt_qp_iter()`

```c
void rvt_qp_iter(struct rvt_dev_info *rdi, u64 v, void (*cb)(struct rvt_qp *qp, u64 v))
```

iterate all QPs

**Parameters**

- `struct rvt_dev_info *rdi`: rvt devinfo
- `u64 v`: a 64-bit value
- `void (*cb)(struct rvt_qp *qp, u64 v)`: a callback

**Description**

This provides a way for iterating all QPs.

The **cb** is a user-defined callback and **v** is a 64-bit
value passed to and relevant for processing in the
cb.  An example use case would be to alter QP processing
based on criteria not part of the rvt_qp.

The code has an internal iterator to simplify
non seq_file use cases.

#### <a id="c-rvt_copy_sge"></a>`rvt_copy_sge()`

```c
void rvt_copy_sge(struct rvt_qp *qp, struct rvt_sge_state *ss, void *data, u32 length, bool release, bool copy_last)
```

copy data to SGE memory

**Parameters**

- `struct rvt_qp *qp`: associated QP
- `struct rvt_sge_state *ss`: the SGE state
- `void *data`: the data to copy
- `u32 length`: the length of the data
- `bool release`: boolean to release MR
- `bool copy_last`: do a separate copy of the last 8 bytes

#### <a id="c-rvt_ruc_loopback"></a>`rvt_ruc_loopback()`

```c
void rvt_ruc_loopback(struct rvt_qp *sqp)
```

handle UC and RC loopback requests

**Parameters**

- `struct rvt_qp *sqp`: the sending QP

**Description**

This is called from `rvt_do_send()` to forward a WQE addressed to the same HFI
Note that although we are single threaded due to the send engine, we still
have to protect against `post_send()`.  We don't have to worry about
receive interrupts since this is a connected protocol and all packets
will pass through here.



#### <a id="c-rvt_mcast_find"></a>`rvt_mcast_find()`

```c
struct rvt_mcast * rvt_mcast_find(struct rvt_ibport *ibp, union ib_gid *mgid, u16 lid)
```

search the global table for the given multicast GID/LID

**Parameters**

- `struct rvt_ibport *ibp`: the IB port structure
- `union ib_gid *mgid`: the multicast GID to search for
- `u16 lid`: the multicast LID portion of the multicast address (host order)

**NOTE**

It is valid to have 1 MLID with multiple MGIDs.  It is not valid
to have 1 MGID with multiple MLIDs.

**Description**

The caller is responsible for decrementing the reference count if found.

**Return**

NULL if not found.


<a id="rst-upper-layer-protocols"></a>

## Upper Layer Protocols

<a id="rst-iscsi-extensions-for-rdma-iser"></a>

### iSCSI Extensions for RDMA (iSER)


#### <a id="c-struct-iser_data_buf"></a>`struct iser_data_buf`

iSER data buffer

**Definition**

```c
struct iser_data_buf {
    struct scatterlist *sg;
    int size;
    unsigned long      data_len;
    int dma_nents;
};
```

**Members**

- `sg`: pointer to the sg list
- `size`: num entries of this sg
- `data_len`: total buffer byte len
- `dma_nents`: returned by dma_map_sg

#### <a id="c-struct-iser_mem_reg"></a>`struct iser_mem_reg`

iSER memory registration info

**Definition**

```c
struct iser_mem_reg {
    struct ib_sge sge;
    u32 rkey;
    struct iser_fr_desc *desc;
};
```

**Members**

- `sge`: memory region sg element
- `rkey`: memory region remote key
- `desc`: pointer to fast registration context

#### <a id="c-struct-iser_tx_desc"></a>`struct iser_tx_desc`

iSER TX descriptor

**Definition**

```c
struct iser_tx_desc {
    struct iser_ctrl             iser_header;
    struct iscsi_hdr             iscsi_header;
    enum iser_desc_type        type;
    u64 dma_addr;
    struct ib_sge                tx_sg[2];
    int num_sge;
    struct ib_cqe                cqe;
    bool mapped;
    struct ib_reg_wr             reg_wr;
    struct ib_send_wr            send_wr;
    struct ib_send_wr            inv_wr;
};
```

**Members**

- `iser_header`: iser header
- `iscsi_header`: iscsi header
- `type`: command/control/dataout
- `dma_addr`: header buffer dma_address
- `tx_sg`: sg\[0\] points to iser/iscsi headers
  sg\[1\] optionally points to either of immediate data
  unsolicited data-out or control
- `num_sge`: number sges used on this TX task
- `cqe`: completion handler
- `mapped`: Is the task header mapped
- `reg_wr`: registration WR
- `send_wr`: send WR
- `inv_wr`: invalidate WR

#### <a id="c-struct-iser_rx_desc"></a>`struct iser_rx_desc`

iSER RX descriptor

**Definition**

```c
struct iser_rx_desc {
    struct iser_ctrl             iser_header;
    struct iscsi_hdr             iscsi_header;
    char data[ISER_RECV_DATA_SEG_LEN];
    u64 dma_addr;
    struct ib_sge                rx_sg;
    struct ib_cqe                cqe;
    char pad[ISER_RX_PAD_SIZE];
};
```

**Members**

- `iser_header`: iser header
- `iscsi_header`: iscsi header
- `data`: received data segment
- `dma_addr`: receive buffer dma address
- `rx_sg`: ib_sge of receive buffer
- `cqe`: completion handler
- `pad`: for sense data TODO: Modify to maximum sense length supported

#### <a id="c-struct-iser_login_desc"></a>`struct iser_login_desc`

iSER login descriptor

**Definition**

```c
struct iser_login_desc {
    void *req;
    void *rsp;
    u64 req_dma;
    u64 rsp_dma;
    struct ib_sge                sge;
    struct ib_cqe                cqe;
};
```

**Members**

- `req`: pointer to login request buffer
- `rsp`: pointer to login response buffer
- `req_dma`: DMA address of login request buffer
- `rsp_dma`: DMA address of login response buffer
- `sge`: IB sge for login post recv
- `cqe`: completion handler

#### <a id="c-struct-iser_device"></a>`struct iser_device`

iSER device handle

**Definition**

```c
struct iser_device {
    struct ib_device             *ib_device;
    struct ib_pd                 *pd;
    struct ib_event_handler      event_handler;
    struct list_head             ig_list;
    int refcount;
};
```

**Members**

- `ib_device`: RDMA device
- `pd`: Protection Domain for this device
- `event_handler`: IB events handle routine
- `ig_list`: entry in devices list
- `refcount`: Reference counter, dominated by open iser connections

#### <a id="c-struct-iser_reg_resources"></a>`struct iser_reg_resources`

Fast registration resources

**Definition**

```c
struct iser_reg_resources {
    struct ib_mr                     *mr;
    struct ib_mr                     *sig_mr;
};
```

**Members**

- `mr`: memory region
- `sig_mr`: signature memory region

#### <a id="c-struct-iser_fr_desc"></a>`struct iser_fr_desc`

Fast registration descriptor

**Definition**

```c
struct iser_fr_desc {
    struct list_head                  list;
    struct iser_reg_resources         rsc;
    bool sig_protected;
    struct list_head                  all_list;
};
```

**Members**

- `list`: entry in connection fastreg pool
- `rsc`: data buffer registration resources
- `sig_protected`: is region protected indicator
- `all_list`: first and last list members

#### <a id="c-struct-iser_fr_pool"></a>`struct iser_fr_pool`

connection fast registration pool

**Definition**

```c
struct iser_fr_pool {
    struct list_head        list;
    spinlock_t lock;
    int size;
    struct list_head        all_list;
};
```

**Members**

- `list`: list of fastreg descriptors
- `lock`: protects fastreg pool
- `size`: size of the pool
- `all_list`: first and last list members

#### <a id="c-struct-ib_conn"></a>`struct ib_conn`

Infiniband related objects

**Definition**

```c
struct ib_conn {
    struct rdma_cm_id           *cma_id;
    struct ib_qp                *qp;
    struct ib_cq                *cq;
    u32 cq_size;
    struct iser_device          *device;
    struct iser_fr_pool          fr_pool;
    bool pi_support;
    struct ib_cqe                reg_cqe;
};
```

**Members**

- `cma_id`: rdma_cm connection maneger handle
- `qp`: Connection Queue-pair
- `cq`: Connection completion queue
- `cq_size`: The number of max outstanding completions
- `device`: reference to iser device
- `fr_pool`: connection fast registration pool
- `pi_support`: Indicate device T10-PI support
- `reg_cqe`: completion handler

#### <a id="c-struct-iser_conn"></a>`struct iser_conn`

iSER connection context

**Definition**

```c
struct iser_conn {
    struct ib_conn               ib_conn;
    struct iscsi_conn            *iscsi_conn;
    struct iscsi_endpoint        *ep;
    enum iser_conn_state         state;
    unsigned qp_max_recv_dtos;
    u16 max_cmds;
    char name[ISER_OBJECT_NAME_SIZE];
    struct work_struct           release_work;
    struct mutex                 state_mutex;
    struct completion            stop_completion;
    struct completion            ib_completion;
    struct completion            up_completion;
    struct list_head             conn_list;
    struct iser_login_desc       login_desc;
    struct iser_rx_desc          *rx_descs;
    u32 num_rx_descs;
    unsigned short               scsi_sg_tablesize;
    unsigned short               pages_per_mr;
    bool snd_w_inv;
};
```

**Members**

- `ib_conn`: connection RDMA resources
- `iscsi_conn`: link to matching iscsi connection
- `ep`: transport handle
- `state`: connection logical state
- `qp_max_recv_dtos`: maximum number of data outs, corresponds
  to max number of post recvs
- `max_cmds`: maximum cmds allowed for this connection
- `name`: connection peer portal
- `release_work`: deferred work for release job
- `state_mutex`: protects iser onnection state
- `stop_completion`: conn_stop completion
- `ib_completion`: RDMA cleanup completion
- `up_completion`: connection establishment completed
  (state is ISER_CONN_UP)
- `conn_list`: entry in ig conn list
- `login_desc`: login descriptor
- `rx_descs`: rx buffers array (cyclic buffer)
- `num_rx_descs`: number of rx descriptors
- `scsi_sg_tablesize`: scsi host sg_tablesize
- `pages_per_mr`: maximum pages available for registration
- `snd_w_inv`: connection uses remote invalidation

#### <a id="c-struct-iscsi_iser_task"></a>`struct iscsi_iser_task`

iser task context

**Definition**

```c
struct iscsi_iser_task {
    struct iser_tx_desc          desc;
    struct iser_conn             *iser_conn;
    enum iser_task_status        status;
    struct scsi_cmnd             *sc;
    int command_sent;
    int dir[ISER_DIRS_NUM];
    struct iser_mem_reg          rdma_reg[ISER_DIRS_NUM];
    struct iser_data_buf         data[ISER_DIRS_NUM];
    struct iser_data_buf         prot[ISER_DIRS_NUM];
};
```

**Members**

- `desc`: TX descriptor
- `iser_conn`: link to iser connection
- `status`: current task status
- `sc`: link to scsi command
- `command_sent`: indicate if command was sent
- `dir`: iser data direction
- `rdma_reg`: task rdma registration desc
- `data`: iser data buffer desc
- `prot`: iser protection buffer desc

#### <a id="c-struct-iser_global"></a>`struct iser_global`

iSER global context

**Definition**

```c
struct iser_global {
    struct mutex      device_list_mutex;
    struct list_head  device_list;
    struct mutex      connlist_mutex;
    struct list_head  connlist;
    struct kmem_cache *desc_cache;
};
```

**Members**

- `device_list_mutex`: protects device_list
- `device_list`: iser devices global list
- `connlist_mutex`: protects connlist
- `connlist`: iser connections global list
- `desc_cache`: kmem cache for tx dataout



#### <a id="c-iscsi_iser_pdu_alloc"></a>`iscsi_iser_pdu_alloc()`

```c
int iscsi_iser_pdu_alloc(struct iscsi_task *task, uint8_t opcode)
```

allocate an iscsi-iser PDU

**Parameters**

- `struct iscsi_task *task`: iscsi task
- `uint8_t opcode`: iscsi command opcode

**Description**

- Netes: This routine can't fail, just assign iscsi task

  hdr and max hdr size.

#### <a id="c-iser_initialize_task_headers"></a>`iser_initialize_task_headers()`

```c
int iser_initialize_task_headers(struct iscsi_task *task, struct iser_tx_desc *tx_desc)
```

Initialize task headers

**Parameters**

- `struct iscsi_task *task`: iscsi task
- `struct iser_tx_desc *tx_desc`: iser tx descriptor

**Notes**

This routine may race with iser teardown flow for scsi
error handling TMFs. So for TMF we should acquire the
state mutex to avoid dereferencing the IB device which
may have already been terminated.

#### <a id="c-iscsi_iser_task_init"></a>`iscsi_iser_task_init()`

```c
int iscsi_iser_task_init(struct iscsi_task *task)
```

Initialize iscsi-iser task

**Parameters**

- `struct iscsi_task *task`: iscsi task

**Description**

Initialize the task for the scsi command or mgmt command.

**Return**

Returns zero on success or -ENOMEM when failing
to init task headers (dma mapping error).

#### <a id="c-iscsi_iser_mtask_xmit"></a>`iscsi_iser_mtask_xmit()`

```c
int iscsi_iser_mtask_xmit(struct iscsi_conn *conn, struct iscsi_task *task)
```

xmit management (immediate) task

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection
- `struct iscsi_task *task`: task management task

**Notes**

The function can return -EAGAIN in which case caller must
call it again later, or recover. '0' return code means successful
xmit.

#### <a id="c-iscsi_iser_task_xmit"></a>`iscsi_iser_task_xmit()`

```c
int iscsi_iser_task_xmit(struct iscsi_task *task)
```

xmit iscsi-iser task

**Parameters**

- `struct iscsi_task *task`: iscsi task

**Return**

zero on success or escalates $error on failure.

#### <a id="c-iscsi_iser_cleanup_task"></a>`iscsi_iser_cleanup_task()`

```c
void iscsi_iser_cleanup_task(struct iscsi_task *task)
```

cleanup an iscsi-iser task

**Parameters**

- `struct iscsi_task *task`: iscsi task

**Notes**

- In case the RDMA device is already NULL (might have

  been removed in DEVICE_REMOVAL CM event it will bail-out
  without doing dma unmapping.

#### <a id="c-iscsi_iser_check_protection"></a>`iscsi_iser_check_protection()`

```c
u8 iscsi_iser_check_protection(struct iscsi_task *task, sector_t *sector)
```

check protection information status of task.

**Parameters**

- `struct iscsi_task *task`: iscsi task
- `sector_t *sector`: error sector if exsists (output)

**Return**

zero if no data-integrity errors have occurred
0x1: data-integrity error occurred in the guard-block
0x2: data-integrity error occurred in the reference tag
0x3: data-integrity error occurred in the application tag

**Description**

In addition the error sector is marked.

#### <a id="c-iscsi_iser_conn_create"></a>`iscsi_iser_conn_create()`

```c
struct iscsi_cls_conn * iscsi_iser_conn_create(struct iscsi_cls_session *cls_session, uint32_t conn_idx)
```

create a new iscsi-iser connection

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi class connection
- `uint32_t conn_idx`: connection index within the session (for MCS)

**Return**

iscsi_cls_conn when iscsi_conn_setup succeeds or NULL
otherwise.

#### <a id="c-iscsi_iser_conn_bind"></a>`iscsi_iser_conn_bind()`

```c
int iscsi_iser_conn_bind(struct iscsi_cls_session *cls_session, struct iscsi_cls_conn *cls_conn, uint64_t transport_eph, int is_leading)
```

bind iscsi and iser connection structures

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi class session
- `struct iscsi_cls_conn *cls_conn`: iscsi class connection
- `uint64_t transport_eph`: transport end-point handle
- `int is_leading`: indicate if this is the session leading connection (MCS)

**Return**

zero on success, $error if iscsi_conn_bind fails and
-EINVAL in case end-point doesn't exists anymore or iser connection
state is not UP (teardown already started).

#### <a id="c-iscsi_iser_conn_start"></a>`iscsi_iser_conn_start()`

```c
int iscsi_iser_conn_start(struct iscsi_cls_conn *cls_conn)
```

start iscsi-iser connection

**Parameters**

- `struct iscsi_cls_conn *cls_conn`: iscsi class connection

**Notes**

- Here iser intialize (or re-initialize) stop_completion as

  from this point iscsi must call conn_stop in session/connection
  teardown so iser transport must wait for it.

#### <a id="c-iscsi_iser_conn_stop"></a>`iscsi_iser_conn_stop()`

```c
void iscsi_iser_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
```

stop iscsi-iser connection

**Parameters**

- `struct iscsi_cls_conn *cls_conn`: iscsi class connection
- `int flag`: indicate if recover or terminate (passed as is)

**Notes**

- Calling iscsi_conn_stop might theoretically race with

  DEVICE_REMOVAL event and dereference a previously freed RDMA device
  handle, so we call it under iser the state lock to protect against
  this kind of race.

#### <a id="c-iscsi_iser_session_destroy"></a>`iscsi_iser_session_destroy()`

```c
void iscsi_iser_session_destroy(struct iscsi_cls_session *cls_session)
```

destroy iscsi-iser session

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi class session

**Description**

Removes and free iscsi host.

#### <a id="c-iscsi_iser_session_create"></a>`iscsi_iser_session_create()`

```c
struct iscsi_cls_session * iscsi_iser_session_create(struct iscsi_endpoint *ep, uint16_t cmds_max, uint16_t qdepth, uint32_t initial_cmdsn)
```

create an iscsi-iser session

**Parameters**

- `struct iscsi_endpoint *ep`: iscsi end-point handle
- `uint16_t cmds_max`: maximum commands in this session
- `uint16_t qdepth`: session command queue depth
- `uint32_t initial_cmdsn`: initiator command sequnce number

**Description**

Allocates and adds a scsi host, expose DIF supprot if
exists, and sets up an iscsi session.

#### <a id="c-iscsi_iser_ep_connect"></a>`iscsi_iser_ep_connect()`

```c
struct iscsi_endpoint * iscsi_iser_ep_connect(struct Scsi_Host *shost, struct sockaddr *dst_addr, int non_blocking)
```

Initiate iSER connection establishment

**Parameters**

- `struct Scsi_Host *shost`: scsi_host
- `struct sockaddr *dst_addr`: destination address
- `int non_blocking`: indicate if routine can block

**Description**

Allocate an iscsi endpoint, an iser_conn structure and bind them.
After that start RDMA connection establishment via rdma_cm. We
don't allocate iser_conn embedded in iscsi_endpoint since in teardown
the endpoint will be destroyed at ep_disconnect while iser_conn will
cleanup its resources asynchronuously.

**Return**

iscsi_endpoint created by iscsi layer or ERR_PTR(error)
if fails.

#### <a id="c-iscsi_iser_ep_poll"></a>`iscsi_iser_ep_poll()`

```c
int iscsi_iser_ep_poll(struct iscsi_endpoint *ep, int timeout_ms)
```

poll for iser connection establishment to complete

**Parameters**

- `struct iscsi_endpoint *ep`: iscsi endpoint (created at ep_connect)
- `int timeout_ms`: polling timeout allowed in ms.

**Description**

This routine boils down to waiting for up_completion signaling
that cma_id got CONNECTED event.

**Return**

1 if succeeded in connection establishment, 0 if timeout expired
(libiscsi will retry will kick in) or -1 if interrupted by signal
or more likely iser connection state transitioned to TEMINATING or
DOWN during the wait period.

#### <a id="c-iscsi_iser_ep_disconnect"></a>`iscsi_iser_ep_disconnect()`

```c
void iscsi_iser_ep_disconnect(struct iscsi_endpoint *ep)
```

Initiate connection teardown process

**Parameters**

- `struct iscsi_endpoint *ep`: iscsi endpoint handle

**Description**

This routine is not blocked by iser and RDMA termination process
completion as we queue a deffered work for iser/RDMA destruction
and cleanup or actually call it immediately in case we didn't pass
iscsi conn bind/start stage, thus it is safe.



#### <a id="c-iser_send_command"></a>`iser_send_command()`

```c
int iser_send_command(struct iscsi_conn *conn, struct iscsi_task *task)
```

send command PDU

**Parameters**

- `struct iscsi_conn *conn`: link to matching iscsi connection
- `struct iscsi_task *task`: SCSI command task

#### <a id="c-iser_send_data_out"></a>`iser_send_data_out()`

```c
int iser_send_data_out(struct iscsi_conn *conn, struct iscsi_task *task, struct iscsi_data *hdr)
```

send data out PDU

**Parameters**

- `struct iscsi_conn *conn`: link to matching iscsi connection
- `struct iscsi_task *task`: SCSI command task
- `struct iscsi_data *hdr`: pointer to the LLD's iSCSI message header



#### <a id="c-iser_alloc_fastreg_pool"></a>`iser_alloc_fastreg_pool()`

```c
int iser_alloc_fastreg_pool(struct ib_conn *ib_conn, unsigned cmds_max, unsigned int size)
```

Creates pool of fast_reg descriptors for fast registration work requests.

**Parameters**

- `struct ib_conn *ib_conn`: connection RDMA resources
- `unsigned cmds_max`: max number of SCSI commands for this connection
- `unsigned int size`: max number of pages per map request

**Return**

0 on success, or errno code on failure

#### <a id="c-iser_free_fastreg_pool"></a>`iser_free_fastreg_pool()`

```c
void iser_free_fastreg_pool(struct ib_conn *ib_conn)
```

releases the pool of fast_reg descriptors

**Parameters**

- `struct ib_conn *ib_conn`: connection RDMA resources

#### <a id="c-iser_free_ib_conn_res"></a>`iser_free_ib_conn_res()`

```c
void iser_free_ib_conn_res(struct iser_conn *iser_conn, bool destroy)
```

release IB related resources

**Parameters**

- `struct iser_conn *iser_conn`: iser connection struct
- `bool destroy`: indicator if we need to try to release the
  iser device and memory regoins pool (only iscsi
  shutdown and DEVICE_REMOVAL will use this).

**Description**

This routine is called with the iser state mutex held
so the cm_id removal is out of here. It is Safe to
be invoked multiple times.

#### <a id="c-iser_conn_release"></a>`iser_conn_release()`

```c
void iser_conn_release(struct iser_conn *iser_conn)
```

Frees all conn objects and deallocs conn descriptor

**Parameters**

- `struct iser_conn *iser_conn`: iSER connection context

#### <a id="c-iser_conn_terminate"></a>`iser_conn_terminate()`

```c
int iser_conn_terminate(struct iser_conn *iser_conn)
```

triggers start of the disconnect procedures and waits for them to be done

**Parameters**

- `struct iser_conn *iser_conn`: iSER connection context

**Description**

Called with state mutex held

#### <a id="c-iser_post_send"></a>`iser_post_send()`

```c
int iser_post_send(struct ib_conn *ib_conn, struct iser_tx_desc *tx_desc)
```

Initiate a Send DTO operation

**Parameters**

- `struct ib_conn *ib_conn`: connection RDMA resources
- `struct iser_tx_desc *tx_desc`: iSER TX descriptor

**Return**

0 on success, -1 on failure


<a id="rst-omni-path-opa-virtual-nic-support"></a>

### Omni-Path (OPA) Virtual NIC support


#### <a id="c-struct-opa_vnic_ctrl_port"></a>`struct opa_vnic_ctrl_port`

OPA virtual NIC control port

**Definition**

```c
struct opa_vnic_ctrl_port {
    struct ib_device           *ibdev;
    struct opa_vnic_ctrl_ops   *ops;
    u8 num_ports;
};
```

**Members**

- `ibdev`: pointer to ib device
- `ops`: opa vnic control operations
- `num_ports`: number of opa ports

#### <a id="c-struct-opa_vnic_adapter"></a>`struct opa_vnic_adapter`

OPA VNIC netdev private data structure

**Definition**

```c
struct opa_vnic_adapter {
    struct net_device             *netdev;
    struct ib_device              *ibdev;
    struct opa_vnic_ctrl_port     *cport;
    const struct net_device_ops   *rn_ops;
    u8 port_num;
    u8 vport_num;
    struct mutex lock;
    struct __opa_veswport_info  info;
    u8 vema_mac_addr[ETH_ALEN];
    u32 umac_hash;
    u32 mmac_hash;
    struct hlist_head    *mactbl;
    struct mutex mactbl_lock;
    spinlock_t stats_lock;
    u8 flow_tbl[OPA_VNIC_FLOW_TBL_SIZE];
    unsigned long trap_timeout;
    u8 trap_count;
};
```

**Members**

- `netdev`: pointer to associated netdev
- `ibdev`: ib device
- `cport`: pointer to opa vnic control port
- `rn_ops`: rdma netdev's net_device_ops
- `port_num`: OPA port number
- `vport_num`: vesw port number
- `lock`: adapter lock
- `info`: virtual ethernet switch port information
- `vema_mac_addr`: mac address configured by vema
- `umac_hash`: unicast maclist hash
- `mmac_hash`: multicast maclist hash
- `mactbl`: hash table of MAC entries
- `mactbl_lock`: mac table lock
- `stats_lock`: statistics lock
- `flow_tbl`: flow to default port redirection table
- `trap_timeout`: trap timeout
- `trap_count`: no. of traps allowed within timeout period

#### <a id="c-struct-opa_vnic_mac_tbl_node"></a>`struct opa_vnic_mac_tbl_node`

OPA VNIC mac table node

**Definition**

```c
struct opa_vnic_mac_tbl_node {
    struct hlist_node                    hlist;
    u16 index;
    struct __opa_vnic_mactable_entry     entry;
};
```

**Members**

- `hlist`: hash list handle
- `index`: index of entry in the mac table
- `entry`: entry in the table



#### <a id="c-struct-opa_vesw_info"></a>`struct opa_vesw_info`

OPA vnic switch information

**Definition**

```c
struct opa_vesw_info {
    __be16 fabric_id;
    __be16 vesw_id;
    u8 rsvd0[6];
    __be16 def_port_mask;
    u8 rsvd1[2];
    __be16 pkey;
    u8 rsvd2[4];
    __be32 u_mcast_dlid;
    __be32 u_ucast_dlid[OPA_VESW_MAX_NUM_DEF_PORT];
    __be32 rc;
    u8 rsvd3[56];
    __be16 eth_mtu;
    u8 rsvd4[2];
};
```

**Members**

- `fabric_id`: 10-bit fabric id
- `vesw_id`: 12-bit virtual ethernet switch id
- `rsvd0`: reserved bytes
- `def_port_mask`: bitmask of default ports
- `rsvd1`: reserved bytes
- `pkey`: partition key
- `rsvd2`: reserved bytes
- `u_mcast_dlid`: unknown multicast dlid
- `u_ucast_dlid`: array of unknown unicast dlids
- `rc`: routing control
- `rsvd3`: reserved bytes
- `eth_mtu`: Ethernet MTU
- `rsvd4`: reserved bytes

#### <a id="c-struct-opa_per_veswport_info"></a>`struct opa_per_veswport_info`

OPA vnic per port information

**Definition**

```c
struct opa_per_veswport_info {
    __be32 port_num;
    u8 eth_link_status;
    u8 rsvd0[3];
    u8 base_mac_addr[ETH_ALEN];
    u8 config_state;
    u8 oper_state;
    __be16 max_mac_tbl_ent;
    __be16 max_smac_ent;
    __be32 mac_tbl_digest;
    u8 rsvd1[4];
    __be32 encap_slid;
    u8 pcp_to_sc_uc[OPA_VNIC_MAX_NUM_PCP];
    u8 pcp_to_vl_uc[OPA_VNIC_MAX_NUM_PCP];
    u8 pcp_to_sc_mc[OPA_VNIC_MAX_NUM_PCP];
    u8 pcp_to_vl_mc[OPA_VNIC_MAX_NUM_PCP];
    u8 non_vlan_sc_uc;
    u8 non_vlan_vl_uc;
    u8 non_vlan_sc_mc;
    u8 non_vlan_vl_mc;
    u8 rsvd2[48];
    __be16 uc_macs_gen_count;
    __be16 mc_macs_gen_count;
    u8 rsvd3[8];
};
```

**Members**

- `port_num`: port number
- `eth_link_status`: current ethernet link state
- `rsvd0`: reserved bytes
- `base_mac_addr`: base mac address
- `config_state`: configured port state
- `oper_state`: operational port state
- `max_mac_tbl_ent`: max number of mac table entries
- `max_smac_ent`: max smac entries in mac table
- `mac_tbl_digest`: mac table digest
- `rsvd1`: reserved bytes
- `encap_slid`: base slid for the port
- `pcp_to_sc_uc`: sc by pcp index for unicast ethernet packets
- `pcp_to_vl_uc`: vl by pcp index for unicast ethernet packets
- `pcp_to_sc_mc`: sc by pcp index for multicast ethernet packets
- `pcp_to_vl_mc`: vl by pcp index for multicast ethernet packets
- `non_vlan_sc_uc`: sc for non-vlan unicast ethernet packets
- `non_vlan_vl_uc`: vl for non-vlan unicast ethernet packets
- `non_vlan_sc_mc`: sc for non-vlan multicast ethernet packets
- `non_vlan_vl_mc`: vl for non-vlan multicast ethernet packets
- `rsvd2`: reserved bytes
- `uc_macs_gen_count`: generation count for unicast macs list
- `mc_macs_gen_count`: generation count for multicast macs list
- `rsvd3`: reserved bytes

#### <a id="c-struct-opa_veswport_info"></a>`struct opa_veswport_info`

OPA vnic port information

**Definition**

```c
struct opa_veswport_info {
    struct opa_vesw_info          vesw;
    struct opa_per_veswport_info  vport;
};
```

**Members**

- `vesw`: OPA vnic switch information
- `vport`: OPA vnic per port information

**Description**

On host, each of the virtual ethernet ports belongs
to a different virtual ethernet switches.

#### <a id="c-struct-opa_veswport_mactable_entry"></a>`struct opa_veswport_mactable_entry`

single entry in the forwarding table

**Definition**

```c
struct opa_veswport_mactable_entry {
    u8 mac_addr[ETH_ALEN];
    u8 mac_addr_mask[ETH_ALEN];
    __be32 dlid_sd;
};
```

**Members**

- `mac_addr`: MAC address
- `mac_addr_mask`: MAC address bit mask
- `dlid_sd`: Matching DLID and side data

**Description**

On the host each virtual ethernet port will have
a forwarding table. These tables are used to
map a MAC to a LID and other data. For more
details see struct opa_veswport_mactable_entries.
This is the structure of a single mactable entry

#### <a id="c-struct-opa_veswport_mactable"></a>`struct opa_veswport_mactable`

Forwarding table array

**Definition**

```c
struct opa_veswport_mactable {
    __be16 offset;
    __be16 num_entries;
    __be32 mac_tbl_digest;
    struct opa_veswport_mactable_entry  tbl_entries[];
};
```

**Members**

- `offset`: mac table starting offset
- `num_entries`: Number of entries to get or set
- `mac_tbl_digest`: mac table digest
- `tbl_entries`: Array of table entries

**Description**

The EM sends down this structure in a MAD indicating
the starting offset in the forwarding table that this
entry is to be loaded into and the number of entries
that that this MAD instance contains
The mac_tbl_digest has been added to this MAD structure. It will be set by
the EM and it will be used by the EM to check if there are any
discrepancies with this value and the value
maintained by the EM in the case of VNIC port being deleted or unloaded
A new instantiation of a VNIC will always have a value of zero.
This value is stored as part of the vnic adapter structure and will be
accessed by the GET and SET routines for both the mactable entries and the
veswport info.

#### <a id="c-struct-opa_veswport_summary_counters"></a>`struct opa_veswport_summary_counters`

summary counters

**Definition**

```c
struct opa_veswport_summary_counters {
    __be16 vp_instance;
    __be16 vesw_id;
    __be32 veswport_num;
    __be64 tx_errors;
    __be64 rx_errors;
    __be64 tx_packets;
    __be64 rx_packets;
    __be64 tx_bytes;
    __be64 rx_bytes;
    __be64 tx_unicast;
    __be64 tx_mcastbcast;
    __be64 tx_untagged;
    __be64 tx_vlan;
    __be64 tx_64_size;
    __be64 tx_65_127;
    __be64 tx_128_255;
    __be64 tx_256_511;
    __be64 tx_512_1023;
    __be64 tx_1024_1518;
    __be64 tx_1519_max;
    __be64 rx_unicast;
    __be64 rx_mcastbcast;
    __be64 rx_untagged;
    __be64 rx_vlan;
    __be64 rx_64_size;
    __be64 rx_65_127;
    __be64 rx_128_255;
    __be64 rx_256_511;
    __be64 rx_512_1023;
    __be64 rx_1024_1518;
    __be64 rx_1519_max;
    __be64 reserved[16];
};
```

**Members**

- `vp_instance`: vport instance on the OPA port
- `vesw_id`: virtual ethernet switch id
- `veswport_num`: virtual ethernet switch port number
- `tx_errors`: transmit errors
- `rx_errors`: receive errors
- `tx_packets`: transmit packets
- `rx_packets`: receive packets
- `tx_bytes`: transmit bytes
- `rx_bytes`: receive bytes
- `tx_unicast`: unicast packets transmitted
- `tx_mcastbcast`: multicast/broadcast packets transmitted
- `tx_untagged`: non-vlan packets transmitted
- `tx_vlan`: vlan packets transmitted
- `tx_64_size`: transmit packet length is 64 bytes
- `tx_65_127`: transmit packet length is >=65 and \< 127 bytes
- `tx_128_255`: transmit packet length is >=128 and \< 255 bytes
- `tx_256_511`: transmit packet length is >=256 and \< 511 bytes
- `tx_512_1023`: transmit packet length is >=512 and \< 1023 bytes
- `tx_1024_1518`: transmit packet length is >=1024 and \< 1518 bytes
- `tx_1519_max`: transmit packet length >= 1519 bytes
- `rx_unicast`: unicast packets received
- `rx_mcastbcast`: multicast/broadcast packets received
- `rx_untagged`: non-vlan packets received
- `rx_vlan`: vlan packets received
- `rx_64_size`: received packet length is 64 bytes
- `rx_65_127`: received packet length is >=65 and \< 127 bytes
- `rx_128_255`: received packet length is >=128 and \< 255 bytes
- `rx_256_511`: received packet length is >=256 and \< 511 bytes
- `rx_512_1023`: received packet length is >=512 and \< 1023 bytes
- `rx_1024_1518`: received packet length is >=1024 and \< 1518 bytes
- `rx_1519_max`: received packet length >= 1519 bytes
- `reserved`: reserved bytes

**Description**

All the above are counters of corresponding conditions.

#### <a id="c-struct-opa_veswport_error_counters"></a>`struct opa_veswport_error_counters`

error counters

**Definition**

```c
struct opa_veswport_error_counters {
    __be16 vp_instance;
    __be16 vesw_id;
    __be32 veswport_num;
    __be64 tx_errors;
    __be64 rx_errors;
    __be64 rsvd0;
    __be64 tx_smac_filt;
    __be64 rsvd1;
    __be64 rsvd2;
    __be64 rsvd3;
    __be64 tx_dlid_zero;
    __be64 rsvd4;
    __be64 tx_logic;
    __be64 rsvd5;
    __be64 tx_drop_state;
    __be64 rx_bad_veswid;
    __be64 rsvd6;
    __be64 rx_runt;
    __be64 rx_oversize;
    __be64 rsvd7;
    __be64 rx_eth_down;
    __be64 rx_drop_state;
    __be64 rx_logic;
    __be64 rsvd8;
    __be64 rsvd9[16];
};
```

**Members**

- `vp_instance`: vport instance on the OPA port
- `vesw_id`: virtual ethernet switch id
- `veswport_num`: virtual ethernet switch port number
- `tx_errors`: transmit errors
- `rx_errors`: receive errors
- `rsvd0`: reserved bytes
- `tx_smac_filt`: smac filter errors
- `rsvd1`: reserved bytes
- `rsvd2`: reserved bytes
- `rsvd3`: reserved bytes
- `tx_dlid_zero`: transmit packets with invalid dlid
- `rsvd4`: reserved bytes
- `tx_logic`: other transmit errors
- `rsvd5`: reserved bytes
- `tx_drop_state`: packet tansmission in non-forward port state
- `rx_bad_veswid`: received packet with invalid vesw id
- `rsvd6`: reserved bytes
- `rx_runt`: received ethernet packet with length \< 64 bytes
- `rx_oversize`: received ethernet packet with length > MTU size
- `rsvd7`: reserved bytes
- `rx_eth_down`: received packets when interface is down
- `rx_drop_state`: received packets in non-forwarding port state
- `rx_logic`: other receive errors
- `rsvd8`: reserved bytes
- `rsvd9`: reserved bytes

**Description**

All the above are counters of corresponding error conditions.

#### <a id="c-struct-opa_veswport_trap"></a>`struct opa_veswport_trap`

Trap message sent to EM by VNIC

**Definition**

```c
struct opa_veswport_trap {
    __be16 fabric_id;
    __be16 veswid;
    __be32 veswportnum;
    __be16 opaportnum;
    u8 veswportindex;
    u8 opcode;
    __be32 reserved;
};
```

**Members**

- `fabric_id`: 10 bit fabric id
- `veswid`: 12 bit virtual ethernet switch id
- `veswportnum`: logical port number on the Virtual switch
- `opaportnum`: physical port num (redundant on host)
- `veswportindex`: switch port index on opa port 0 based
- `opcode`: operation
- `reserved`: 32 bit for alignment

**Description**

The VNIC will send trap messages to the Ethernet manager to
inform it about changes to the VNIC config, behaviour etc.
This is the format of the trap payload.

#### <a id="c-struct-opa_vnic_iface_mac_entry"></a>`struct opa_vnic_iface_mac_entry`

single entry in the mac list

**Definition**

```c
struct opa_vnic_iface_mac_entry {
    u8 mac_addr[ETH_ALEN];
};
```

**Members**

- `mac_addr`: MAC address

#### <a id="c-struct-opa_veswport_iface_macs"></a>`struct opa_veswport_iface_macs`

Msg to set globally administered MAC

**Definition**

```c
struct opa_veswport_iface_macs {
    __be16 start_idx;
    __be16 num_macs_in_msg;
    __be16 tot_macs_in_lst;
    __be16 gen_count;
    struct opa_vnic_iface_mac_entry entry[];
};
```

**Members**

- `start_idx`: position of first entry (0 based)
- `num_macs_in_msg`: number of MACs in this message
- `tot_macs_in_lst`: The total number of MACs the agent has
- `gen_count`: gen_count to indicate change
- `entry`: The mac list entry

**Description**

Same attribute IDS and attribute modifiers as in locally administered
addresses used to set globally administered addresses

#### <a id="c-struct-opa_vnic_vema_mad"></a>`struct opa_vnic_vema_mad`

Generic VEMA MAD

**Definition**

```c
struct opa_vnic_vema_mad {
    struct ib_mad_hdr  mad_hdr;
    struct ib_rmpp_hdr rmpp_hdr;
    u8 reserved;
    u8 oui[3];
    u8 data[OPA_VNIC_EMA_DATA];
};
```

**Members**

- `mad_hdr`: Generic MAD header
- `rmpp_hdr`: RMPP header for vendor specific MADs
- `reserved`: reserved bytes
- `oui`: Unique org identifier
- `data`: MAD data

#### <a id="c-struct-opa_vnic_notice_attr"></a>`struct opa_vnic_notice_attr`

Generic Notice MAD

**Definition**

```c
struct opa_vnic_notice_attr {
    u8 gen_type;
    u8 oui_1;
    u8 oui_2;
    u8 oui_3;
    __be16 trap_num;
    __be16 toggle_count;
    __be32 issuer_lid;
    __be32 reserved;
    u8 issuer_gid[16];
    u8 raw_data[64];
};
```

**Members**

- `gen_type`: Generic/Specific bit and type of notice
- `oui_1`: Vendor ID byte 1
- `oui_2`: Vendor ID byte 2
- `oui_3`: Vendor ID byte 3
- `trap_num`: Trap number
- `toggle_count`: Notice toggle bit and count value
- `issuer_lid`: Trap issuer's lid
- `reserved`: reserved bytes
- `issuer_gid`: Issuer GID (only if Report method)
- `raw_data`: Trap message body

#### <a id="c-struct-opa_vnic_vema_mad_trap"></a>`struct opa_vnic_vema_mad_trap`

Generic VEMA MAD Trap

**Definition**

```c
struct opa_vnic_vema_mad_trap {
    struct ib_mad_hdr            mad_hdr;
    struct ib_rmpp_hdr           rmpp_hdr;
    u8 reserved;
    u8 oui[3];
    struct opa_vnic_notice_attr  notice;
};
```

**Members**

- `mad_hdr`: Generic MAD header
- `rmpp_hdr`: RMPP header for vendor specific MADs
- `reserved`: reserved bytes
- `oui`: Unique org identifier
- `notice`: Notice structure



#### <a id="c-opa_vnic_vema_report_event"></a>`opa_vnic_vema_report_event()`

```c
void opa_vnic_vema_report_event(struct opa_vnic_adapter *adapter, u8 event)
```

sent trap to report the specified event

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `u8 event`: event to be reported

**Description**

This function calls vema api to sent a trap for the given event.

#### <a id="c-opa_vnic_get_summary_counters"></a>`opa_vnic_get_summary_counters()`

```c
void opa_vnic_get_summary_counters(struct opa_vnic_adapter *adapter, struct opa_veswport_summary_counters *cntrs)
```

get summary counters

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_veswport_summary_counters *cntrs`: pointer to destination summary counters structure

**Description**

This function populates the summary counters that is maintained by the
given adapter to destination address provided.

#### <a id="c-opa_vnic_get_error_counters"></a>`opa_vnic_get_error_counters()`

```c
void opa_vnic_get_error_counters(struct opa_vnic_adapter *adapter, struct opa_veswport_error_counters *cntrs)
```

get error counters

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_veswport_error_counters *cntrs`: pointer to destination error counters structure

**Description**

This function populates the error counters that is maintained by the
given adapter to destination address provided.

#### <a id="c-opa_vnic_get_vesw_info"></a>`opa_vnic_get_vesw_info()`

```c
void opa_vnic_get_vesw_info(struct opa_vnic_adapter *adapter, struct opa_vesw_info *info)
```

- Get the vesw information

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_vesw_info *info`: pointer to destination vesw info structure

**Description**

This function copies the vesw info that is maintained by the
given adapter to destination address provided.

#### <a id="c-opa_vnic_set_vesw_info"></a>`opa_vnic_set_vesw_info()`

```c
void opa_vnic_set_vesw_info(struct opa_vnic_adapter *adapter, struct opa_vesw_info *info)
```

- Set the vesw information

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_vesw_info *info`: pointer to vesw info structure

**Description**

This function updates the vesw info that is maintained by the
given adapter with vesw info provided. Reserved fields are stored
and returned back to EM as is.

#### <a id="c-opa_vnic_get_per_veswport_info"></a>`opa_vnic_get_per_veswport_info()`

```c
void opa_vnic_get_per_veswport_info(struct opa_vnic_adapter *adapter, struct opa_per_veswport_info *info)
```

- Get the vesw per port information

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_per_veswport_info *info`: pointer to destination vport info structure

**Description**

This function copies the vesw per port info that is maintained by the
given adapter to destination address provided.
Note that the read only fields are not copied.

#### <a id="c-opa_vnic_set_per_veswport_info"></a>`opa_vnic_set_per_veswport_info()`

```c
void opa_vnic_set_per_veswport_info(struct opa_vnic_adapter *adapter, struct opa_per_veswport_info *info)
```

- Set vesw per port information

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_per_veswport_info *info`: pointer to vport info structure

**Description**

This function updates the vesw per port info that is maintained by the
given adapter with vesw per port info provided. Reserved fields are
stored and returned back to EM as is.

#### <a id="c-opa_vnic_query_mcast_macs"></a>`opa_vnic_query_mcast_macs()`

```c
void opa_vnic_query_mcast_macs(struct opa_vnic_adapter *adapter, struct opa_veswport_iface_macs *macs)
```

query multicast mac list

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_veswport_iface_macs *macs`: pointer mac list

**Description**

This function populates the provided mac list with the configured
multicast addresses in the adapter.

#### <a id="c-opa_vnic_query_ucast_macs"></a>`opa_vnic_query_ucast_macs()`

```c
void opa_vnic_query_ucast_macs(struct opa_vnic_adapter *adapter, struct opa_veswport_iface_macs *macs)
```

query unicast mac list

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_veswport_iface_macs *macs`: pointer mac list

**Description**

This function populates the provided mac list with the configured
unicast addresses in the adapter.



#### <a id="c-struct-opa_vnic_vema_port"></a>`struct opa_vnic_vema_port`

- VNIC VEMA port details

**Definition**

```c
struct opa_vnic_vema_port {
    struct opa_vnic_ctrl_port      *cport;
    struct ib_mad_agent            *mad_agent;
    struct opa_class_port_info      class_port_info;
    u64 tid;
    u8 port_num;
    struct xarray                   vports;
    struct ib_event_handler         event_handler;
    struct mutex                    lock;
};
```

**Members**

- `cport`: pointer to port
- `mad_agent`: pointer to mad agent for port
- `class_port_info`: Class port info information.
- `tid`: Transaction id
- `port_num`: OPA port number
- `vports`: vnic ports
- `event_handler`: ib event handler
- `lock`: adapter interface lock

#### <a id="c-vema_get_vport_num"></a>`vema_get_vport_num()`

```c
u8 vema_get_vport_num(struct opa_vnic_vema_mad *recvd_mad)
```

- Get the vnic from the mad

**Parameters**

- `struct opa_vnic_vema_mad *recvd_mad`: Received mad

**Return**

returns value of the vnic port number

#### <a id="c-vema_get_vport_adapter"></a>`vema_get_vport_adapter()`

```c
struct opa_vnic_adapter * vema_get_vport_adapter(struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_port *port)
```

- Get vnic port adapter from recvd mad

**Parameters**

- `struct opa_vnic_vema_mad *recvd_mad`: received mad
- `struct opa_vnic_vema_port *port`: ptr to port struct on which MAD was recvd

**Return**

vnic adapter

#### <a id="c-vema_mac_tbl_req_ok"></a>`vema_mac_tbl_req_ok()`

```c
bool vema_mac_tbl_req_ok(struct opa_veswport_mactable *mac_tbl)
```

- Check if mac request has correct values

**Parameters**

- `struct opa_veswport_mactable *mac_tbl`: mac table

**Description**

This function checks for the validity of the offset and number of
entries required.

**Return**

true if offset and num_entries are valid

#### <a id="c-vema_add_vport"></a>`vema_add_vport()`

```c
struct opa_vnic_adapter * vema_add_vport(struct opa_vnic_vema_port *port, u8 vport_num)
```

- Add a new vnic port

**Parameters**

- `struct opa_vnic_vema_port *port`: ptr to opa_vnic_vema_port struct
- `u8 vport_num`: vnic port number (to be added)

**Description**

Return a pointer to the vnic adapter structure

#### <a id="c-vema_get_class_port_info"></a>`vema_get_class_port_info()`

```c
void vema_get_class_port_info(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Get class info for port

**Parameters**

- `struct opa_vnic_vema_port *port`: Port on whic MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function copies the latest class port info value set for the
port and stores it for generating traps

#### <a id="c-vema_set_class_port_info"></a>`vema_set_class_port_info()`

```c
void vema_set_class_port_info(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Get class info for port

**Parameters**

- `struct opa_vnic_vema_port *port`: Port on whic MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function updates the port class info for the specific vnic
and sets up the response mad data

#### <a id="c-vema_get_veswport_info"></a>`vema_get_veswport_info()`

```c
void vema_get_veswport_info(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Get veswport info

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

#### <a id="c-vema_set_veswport_info"></a>`vema_set_veswport_info()`

```c
void vema_set_veswport_info(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Set veswport info

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function gets the port class infor for vnic

#### <a id="c-vema_get_mac_entries"></a>`vema_get_mac_entries()`

```c
void vema_get_mac_entries(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Get MAC entries in VNIC MAC table

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function gets the MAC entries that are programmed into
the VNIC MAC forwarding table. It checks for the validity of
the index into the MAC table and the number of entries that
are to be retrieved.

#### <a id="c-vema_set_mac_entries"></a>`vema_set_mac_entries()`

```c
void vema_set_mac_entries(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Set MAC entries in VNIC MAC table

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function sets the MAC entries in the VNIC forwarding table
It checks for the validity of the index and the number of forwarding
table entries to be programmed.

#### <a id="c-vema_set_delete_vesw"></a>`vema_set_delete_vesw()`

```c
void vema_set_delete_vesw(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Reset VESW info to POD values

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function clears all the fields of veswport info for the requested vesw
and sets them back to the power-on default values. It does not delete the
vesw.

#### <a id="c-vema_get_mac_list"></a>`vema_get_mac_list()`

```c
void vema_get_mac_list(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad, u16 attr_id)
```

- Get the unicast/multicast macs.

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad contains fields to set vnic parameters
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built
- `u16 attr_id`: Attribute ID indicating multicast or unicast mac list

#### <a id="c-vema_get_summary_counters"></a>`vema_get_summary_counters()`

```c
void vema_get_summary_counters(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Gets summary counters.

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad contains fields to set vnic parameters
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built

#### <a id="c-vema_get_error_counters"></a>`vema_get_error_counters()`

```c
void vema_get_error_counters(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Gets summary counters.

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad contains fields to set vnic parameters
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built

#### <a id="c-vema_get"></a>`vema_get()`

```c
void vema_get(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Process received get MAD

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built

#### <a id="c-vema_set"></a>`vema_set()`

```c
void vema_set(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Process received set MAD

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad contains fields to set vnic parameters
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built

#### <a id="c-vema_send"></a>`vema_send()`

```c
void vema_send(struct ib_mad_agent *mad_agent, struct ib_mad_send_wc *mad_wc)
```

- Send handler for VEMA MAD agent

**Parameters**

- `struct ib_mad_agent *mad_agent`: pointer to the mad agent
- `struct ib_mad_send_wc *mad_wc`: pointer to mad send work completion information

**Description**

Free all the data structures associated with the sent MAD

#### <a id="c-vema_recv"></a>`vema_recv()`

```c
void vema_recv(struct ib_mad_agent *mad_agent, struct ib_mad_send_buf *send_buf, struct ib_mad_recv_wc *mad_wc)
```

- Recv handler for VEMA MAD agent

**Parameters**

- `struct ib_mad_agent *mad_agent`: pointer to the mad agent
- `struct ib_mad_send_buf *send_buf`: Send buffer if found, else NULL
- `struct ib_mad_recv_wc *mad_wc`: pointer to mad send work completion information

**Description**

Handle only set and get methods and respond to other methods
as unsupported. Allocate response buffer and address handle
for the response MAD.

#### <a id="c-vema_get_port"></a>`vema_get_port()`

```c
struct opa_vnic_vema_port * vema_get_port(struct opa_vnic_ctrl_port *cport, u8 port_num)
```

- Gets the opa_vnic_vema_port

**Parameters**

- `struct opa_vnic_ctrl_port *cport`: pointer to control dev
- `u8 port_num`: Port number

**Description**

This function loops through the ports and returns
the opa_vnic_vema port structure that is associated
with the OPA port number

**Return**

ptr to requested opa_vnic_vema_port strucure
if success, NULL if not

#### <a id="c-opa_vnic_vema_send_trap"></a>`opa_vnic_vema_send_trap()`

```c
void opa_vnic_vema_send_trap(struct opa_vnic_adapter *adapter, struct __opa_veswport_trap *data, u32 lid)
```

- This function sends a trap to the EM

**Parameters**

- `struct opa_vnic_adapter *adapter`: pointer to vnic adapter
- `struct __opa_veswport_trap *data`: pointer to trap data filled by calling function
- `u32 lid`: issuers lid (encap_slid from vesw_port_info)

**Description**

This function is called from the VNIC driver to send a trap if there
is somethng the EM should be notified about. These events currently
are
1) UNICAST INTERFACE MACADDRESS changes
2) MULTICAST INTERFACE MACADDRESS changes
3) ETHERNET LINK STATUS changes
While allocating the send mad the remote site qpn used is 1
as this is the well known QP.

#### <a id="c-vema_unregister"></a>`vema_unregister()`

```c
void vema_unregister(struct opa_vnic_ctrl_port *cport)
```

- Unregisters agent

**Parameters**

- `struct opa_vnic_ctrl_port *cport`: pointer to control port

**Description**

This deletes the registration by VEMA for MADs

#### <a id="c-vema_register"></a>`vema_register()`

```c
int vema_register(struct opa_vnic_ctrl_port *cport)
```

- Registers agent

**Parameters**

- `struct opa_vnic_ctrl_port *cport`: pointer to control port

**Description**

This function registers the handlers for the VEMA MADs

**Return**

returns 0 on success. non zero otherwise

#### <a id="c-opa_vnic_ctrl_config_dev"></a>`opa_vnic_ctrl_config_dev()`

```c
void opa_vnic_ctrl_config_dev(struct opa_vnic_ctrl_port *cport, bool en)
```

- This function sends a trap to the EM by way of ib_modify_port to indicate support for ethernet on the fabric.

**Parameters**

- `struct opa_vnic_ctrl_port *cport`: pointer to control port
- `bool en`: enable or disable ethernet on fabric support

#### <a id="c-opa_vnic_vema_add_one"></a>`opa_vnic_vema_add_one()`

```c
int opa_vnic_vema_add_one(struct ib_device *device)
```

- Handle new ib device

**Parameters**

- `struct ib_device *device`: ib device pointer

**Description**

Allocate the vnic control port and initialize it.

#### <a id="c-opa_vnic_vema_rem_one"></a>`opa_vnic_vema_rem_one()`

```c
void opa_vnic_vema_rem_one(struct ib_device *device, void *client_data)
```

- Handle ib device removal

**Parameters**

- `struct ib_device *device`: ib device pointer
- `void *client_data`: ib client data

**Description**

Uninitialize and free the vnic control port.


<a id="rst-infiniband-scsi-rdma-protocol-target-support"></a>

### InfiniBand SCSI RDMA protocol target support


#### <a id="c-enum-srpt_command_state"></a>`enum srpt_command_state`

SCSI command state managed by SRPT

**Constants**

- `SRPT_STATE_NEW`: New command arrived and is being processed.
- `SRPT_STATE_NEED_DATA`: Processing a write or bidir command and waiting
  for data arrival.
- `SRPT_STATE_DATA_IN`: Data for the write or bidir command arrived and is
  being processed.
- `SRPT_STATE_CMD_RSP_SENT`: SRP_RSP for SRP_CMD has been sent.
- `SRPT_STATE_MGMT`: Processing a SCSI task management command.
- `SRPT_STATE_MGMT_RSP_SENT`: SRP_RSP for SRP_TSK_MGMT has been sent.
- `SRPT_STATE_DONE`: Command processing finished successfully, command
  processing has been aborted or command processing
  failed.

#### <a id="c-struct-srpt_ioctx"></a>`struct srpt_ioctx`

shared SRPT I/O context information

**Definition**

```c
struct srpt_ioctx {
    struct ib_cqe           cqe;
    void *buf;
    dma_addr_t dma;
    uint32_t offset;
    uint32_t index;
};
```

**Members**

- `cqe`: Completion queue element.
- `buf`: Pointer to the buffer.
- `dma`: DMA address of the buffer.
- `offset`: Offset of the first byte in **buf** and **dma** that is actually used.
- `index`: Index of the I/O context in its ioctx_ring array.

#### <a id="c-struct-srpt_recv_ioctx"></a>`struct srpt_recv_ioctx`

SRPT receive I/O context

**Definition**

```c
struct srpt_recv_ioctx {
    struct srpt_ioctx       ioctx;
    struct list_head        wait_list;
    int byte_len;
};
```

**Members**

- `ioctx`: See above.
- `wait_list`: Node for insertion in srpt_rdma_ch.cmd_wait_list.
- `byte_len`: Number of bytes in **ioctx.buf**.

#### <a id="c-struct-srpt_send_ioctx"></a>`struct srpt_send_ioctx`

SRPT send I/O context

**Definition**

```c
struct srpt_send_ioctx {
    struct srpt_ioctx       ioctx;
    struct srpt_rdma_ch     *ch;
    struct srpt_recv_ioctx  *recv_ioctx;
    struct srpt_rw_ctx      s_rw_ctx;
    struct srpt_rw_ctx      *rw_ctxs;
    struct scatterlist      imm_sg;
    struct ib_cqe           rdma_cqe;
    enum srpt_command_state state;
    struct se_cmd           cmd;
    u8 n_rdma;
    u8 n_rw_ctx;
    bool queue_status_only;
    u8 sense_data[TRANSPORT_SENSE_BUFFER];
};
```

**Members**

- `ioctx`: See above.
- `ch`: Channel pointer.
- `recv_ioctx`: Receive I/O context associated with this send I/O context.
  Only used for processing immediate data.
- `s_rw_ctx`:

  **rw_ctxs** points here if only a single rw_ctx is needed.
- `rw_ctxs`: RDMA read/write contexts.
- `imm_sg`: Scatterlist for immediate data.
- `rdma_cqe`: RDMA completion queue element.
- `state`: I/O context state.
- `cmd`: Target core command data structure.
- `n_rdma`: Number of work requests needed to transfer this ioctx.
- `n_rw_ctx`: Size of rw_ctxs array.
- `queue_status_only`: Send a SCSI status back to the initiator but no data.
- `sense_data`: Sense data to be sent to the initiator.

#### <a id="c-enum-rdma_ch_state"></a>`enum rdma_ch_state`

SRP channel state

**Constants**

- `CH_CONNECTING`: QP is in RTR state; waiting for RTU.
- `CH_LIVE`: QP is in RTS state.
- `CH_DISCONNECTING`: DREQ has been sent and waiting for DREP or DREQ has
  been received.
- `CH_DRAINING`: DREP has been received or waiting for DREP timed out
  and last work request has been queued.
- `CH_DISCONNECTED`: Last completion has been received.

#### <a id="c-struct-srpt_rdma_ch"></a>`struct srpt_rdma_ch`

RDMA channel

**Definition**

```c
struct srpt_rdma_ch {
    struct srpt_nexus       *nexus;
    struct ib_qp            *qp;
    union {
        struct {
            struct ib_cm_id         *cm_id;
        } ib_cm;
        struct {
            struct rdma_cm_id       *cm_id;
        } rdma_cm;
    };
    struct ib_cq            *cq;
    u32 cq_size;
    struct ib_cqe           zw_cqe;
    struct rcu_head         rcu;
    struct kref             kref;
    struct completion       *closed;
    int rq_size;
    u32 max_rsp_size;
    atomic_t sq_wr_avail;
    struct srpt_port        *sport;
    int max_ti_iu_len;
    atomic_t req_lim;
    atomic_t req_lim_delta;
    u16 imm_data_offset;
    spinlock_t spinlock;
    enum rdma_ch_state      state;
    struct kmem_cache       *rsp_buf_cache;
    struct srpt_send_ioctx  **ioctx_ring;
    struct kmem_cache       *req_buf_cache;
    struct srpt_recv_ioctx  **ioctx_recv_ring;
    struct list_head        list;
    struct list_head        cmd_wait_list;
    uint16_t pkey;
    bool using_rdma_cm;
    bool processing_wait_list;
    struct se_session       *sess;
    u8 sess_name[40];
    struct work_struct      release_work;
};
```

**Members**

- `nexus`: I_T nexus this channel is associated with.
- `qp`: IB queue pair used for communicating over this channel.
- `{unnamed_union}`: anonymous
- `ib_cm`: See below.
- `ib_cm.cm_id`: IB CM ID associated with the channel.
- `rdma_cm`: See below.
- `rdma_cm.cm_id`: RDMA CM ID associated with the channel.
- `cq`: IB completion queue for this channel.
- `cq_size`: Number of CQEs in **cq**.
- `zw_cqe`: Zero-length write CQE.
- `rcu`: RCU head.
- `kref`: kref for this channel.
- `closed`: Completion object that will be signaled as soon as a new
  channel object with the same identity can be created.
- `rq_size`: IB receive queue size.
- `max_rsp_size`: Maximum size of an RSP response message in bytes.
- `sq_wr_avail`: number of work requests available in the send queue.
- `sport`: pointer to the information of the HCA port used by this
  channel.
- `max_ti_iu_len`: maximum target-to-initiator information unit length.
- `req_lim`: request limit: maximum number of requests that may be sent
  by the initiator without having received a response.
- `req_lim_delta`: Number of credits not yet sent back to the initiator.
- `imm_data_offset`: Offset from start of SRP_CMD for immediate data.
- `spinlock`: Protects free_list and state.
- `state`: channel state. See also enum rdma_ch_state.
- `rsp_buf_cache`: kmem_cache for **ioctx_ring**.
- `ioctx_ring`: Send ring.
- `req_buf_cache`: kmem_cache for **ioctx_recv_ring**.
- `ioctx_recv_ring`: Receive I/O context ring.
- `list`: Node in srpt_nexus.ch_list.
- `cmd_wait_list`: List of SCSI commands that arrived before the RTU event. This
  list contains struct srpt_ioctx elements and is protected
  against concurrent modification by the cm_id spinlock.
- `pkey`: P_Key of the IB partition for this SRP channel.
- `using_rdma_cm`: Whether the RDMA/CM or IB/CM is used for this channel.
- `processing_wait_list`: Whether or not cmd_wait_list is being processed.
- `sess`: Session information associated with this SRP channel.
- `sess_name`: Session name.
- `release_work`: Allows scheduling of `srpt_release_channel()`.

#### <a id="c-struct-srpt_nexus"></a>`struct srpt_nexus`

I_T nexus

**Definition**

```c
struct srpt_nexus {
    struct rcu_head         rcu;
    struct list_head        entry;
    struct list_head        ch_list;
    u8 i_port_id[16];
    u8 t_port_id[16];
};
```

**Members**

- `rcu`: RCU head for this data structure.
- `entry`: srpt_port.nexus_list list node.
- `ch_list`: struct srpt_rdma_ch list. Protected by srpt_port.mutex.
- `i_port_id`: 128-bit initiator port identifier copied from SRP_LOGIN_REQ.
- `t_port_id`: 128-bit target port identifier copied from SRP_LOGIN_REQ.

#### <a id="c-struct-srpt_port_attrib"></a>`struct srpt_port_attrib`

attributes for SRPT port

**Definition**

```c
struct srpt_port_attrib {
    u32 srp_max_rdma_size;
    u32 srp_max_rsp_size;
    u32 srp_sq_size;
    bool use_srq;
};
```

**Members**

- `srp_max_rdma_size`: Maximum size of SRP RDMA transfers for new connections.
- `srp_max_rsp_size`: Maximum size of SRP response messages in bytes.
- `srp_sq_size`: Shared receive queue (SRQ) size.
- `use_srq`: Whether or not to use SRQ.

#### <a id="c-struct-srpt_tpg"></a>`struct srpt_tpg`

information about a single "target portal group"

**Definition**

```c
struct srpt_tpg {
    struct list_head        entry;
    struct srpt_port_id     *sport_id;
    struct se_portal_group  tpg;
};
```

**Members**

- `entry`: Entry in **sport_id->tpg_list**.
- `sport_id`: Port name this TPG is associated with.
- `tpg`: LIO TPG data structure.

**Description**

Zero or more target portal groups are associated with each port name
(srpt_port_id). With each TPG an ACL list is associated.

#### <a id="c-struct-srpt_port_id"></a>`struct srpt_port_id`

LIO RDMA port information

**Definition**

```c
struct srpt_port_id {
    struct mutex            mutex;
    struct list_head        tpg_list;
    struct se_wwn           wwn;
    char name[64];
};
```

**Members**

- `mutex`: Protects **tpg_list** changes.
- `tpg_list`: TPGs associated with the RDMA port name.
- `wwn`: WWN associated with the RDMA port name.
- `name`: ASCII representation of the port name.

**Description**

Multiple sysfs directories can be associated with a single RDMA port. This
data structure represents a single (port, name) pair.

#### <a id="c-struct-srpt_port"></a>`struct srpt_port`

SRPT RDMA port information

**Definition**

```c
struct srpt_port {
    struct srpt_device      *sdev;
    struct ib_mad_agent     *mad_agent;
    bool enabled;
    u8 port;
    u32 sm_lid;
    u32 lid;
    union ib_gid            gid;
    struct work_struct      work;
    char guid_name[64];
    struct srpt_port_id     *guid_id;
    char gid_name[64];
    struct srpt_port_id     *gid_id;
    struct srpt_port_attrib port_attrib;
    atomic_t refcount;
    struct completion       *freed_channels;
    struct mutex            mutex;
    struct list_head        nexus_list;
};
```

**Members**

- `sdev`: backpointer to the HCA information.
- `mad_agent`: per-port management datagram processing information.
- `enabled`: Whether or not this target port is enabled.
- `port`: one-based port number.
- `sm_lid`: cached value of the port's sm_lid.
- `lid`: cached value of the port's lid.
- `gid`: cached value of the port's gid.
- `work`: work structure for refreshing the aforementioned cached values.
- `guid_name`: port name in GUID format.
- `guid_id`: LIO target port information for the port name in GUID format.
- `gid_name`: port name in GID format.
- `gid_id`: LIO target port information for the port name in GID format.
- `port_attrib`: Port attributes that can be accessed through configfs.
- `refcount`: Number of objects associated with this port.
- `freed_channels`: Completion that will be signaled once **refcount** becomes 0.
- `mutex`: Protects nexus_list.
- `nexus_list`: Nexus list. See also srpt_nexus.entry.

#### <a id="c-struct-srpt_device"></a>`struct srpt_device`

information associated by SRPT with a single HCA

**Definition**

```c
struct srpt_device {
    struct kref             refcnt;
    struct ib_device        *device;
    struct ib_pd            *pd;
    u32 lkey;
    struct ib_srq           *srq;
    struct ib_cm_id         *cm_id;
    int srq_size;
    struct mutex            sdev_mutex;
    bool use_srq;
    struct kmem_cache       *req_buf_cache;
    struct srpt_recv_ioctx  **ioctx_ring;
    struct ib_event_handler event_handler;
    struct list_head        list;
    struct srpt_port        port[];
};
```

**Members**

- `refcnt`: Reference count for this device.
- `device`: Backpointer to the struct ib_device managed by the IB core.
- `pd`: IB protection domain.
- `lkey`: L_Key (local key) with write access to all local memory.
- `srq`: Per-HCA SRQ (shared receive queue).
- `cm_id`: Connection identifier.
- `srq_size`: SRQ size.
- `sdev_mutex`: Serializes use_srq changes.
- `use_srq`: Whether or not to use SRQ.
- `req_buf_cache`: kmem_cache for **ioctx_ring** buffers.
- `ioctx_ring`: Per-HCA SRQ.
- `event_handler`: Per-HCA asynchronous IB event handler.
- `list`: Node in srpt_dev_list.
- `port`: Information about the ports owned by this HCA.



#### <a id="c-srpt_event_handler"></a>`srpt_event_handler()`

```c
void srpt_event_handler(struct ib_event_handler *handler, struct ib_event *event)
```

asynchronous IB event callback function

**Parameters**

- `struct ib_event_handler *handler`: IB event handler registered by [`ib_register_event_handler()`](#c-ib_register_event_handler).
- `struct ib_event *event`: Description of the event that occurred.

**Description**

Callback function called by the InfiniBand core when an asynchronous IB
event occurs. This callback may occur in interrupt context. See also
section 11.5.2, Set Asynchronous Event Handler in the InfiniBand
Architecture Specification.

#### <a id="c-srpt_srq_event"></a>`srpt_srq_event()`

```c
void srpt_srq_event(struct ib_event *event, void *ctx)
```

SRQ event callback function

**Parameters**

- `struct ib_event *event`: Description of the event that occurred.
- `void *ctx`: Context pointer specified at SRQ creation time.

#### <a id="c-srpt_qp_event"></a>`srpt_qp_event()`

```c
void srpt_qp_event(struct ib_event *event, void *ptr)
```

QP event callback function

**Parameters**

- `struct ib_event *event`: Description of the event that occurred.
- `void *ptr`: SRPT RDMA channel.

#### <a id="c-srpt_set_ioc"></a>`srpt_set_ioc()`

```c
void srpt_set_ioc(u8 *c_list, u32 slot, u8 value)
```

initialize a IOUnitInfo structure

**Parameters**

- `u8 *c_list`: controller list.
- `u32 slot`: one-based slot number.
- `u8 value`: four-bit value.

**Description**

Copies the lowest four bits of value in element slot of the array of four
bit elements called c_list (controller list). The index slot is one-based.

#### <a id="c-srpt_get_class_port_info"></a>`srpt_get_class_port_info()`

```c
void srpt_get_class_port_info(struct ib_dm_mad *mad)
```

copy ClassPortInfo to a management datagram

**Parameters**

- `struct ib_dm_mad *mad`: Datagram that will be sent as response to DM_ATTR_CLASS_PORT_INFO.

**Description**

See also section 16.3.3.1 ClassPortInfo in the InfiniBand Architecture
Specification.

#### <a id="c-srpt_get_iou"></a>`srpt_get_iou()`

```c
void srpt_get_iou(struct ib_dm_mad *mad)
```

write IOUnitInfo to a management datagram

**Parameters**

- `struct ib_dm_mad *mad`: Datagram that will be sent as response to DM_ATTR_IOU_INFO.

**Description**

See also section 16.3.3.3 IOUnitInfo in the InfiniBand Architecture
Specification. See also section B.7, table B.6 in the SRP r16a document.

#### <a id="c-srpt_get_ioc"></a>`srpt_get_ioc()`

```c
void srpt_get_ioc(struct srpt_port *sport, u32 slot, struct ib_dm_mad *mad)
```

write IOControllerprofile to a management datagram

**Parameters**

- `struct srpt_port *sport`: HCA port through which the MAD has been received.
- `u32 slot`: Slot number specified in DM_ATTR_IOC_PROFILE query.
- `struct ib_dm_mad *mad`: Datagram that will be sent as response to DM_ATTR_IOC_PROFILE.

**Description**

See also section 16.3.3.4 IOControllerProfile in the InfiniBand
Architecture Specification. See also section B.7, table B.7 in the SRP
r16a document.

#### <a id="c-srpt_get_svc_entries"></a>`srpt_get_svc_entries()`

```c
void srpt_get_svc_entries(u64 ioc_guid, u16 slot, u8 hi, u8 lo, struct ib_dm_mad *mad)
```

write ServiceEntries to a management datagram

**Parameters**

- `u64 ioc_guid`: I/O controller GUID to use in reply.
- `u16 slot`: I/O controller number.
- `u8 hi`: End of the range of service entries to be specified in the reply.
- `u8 lo`: Start of the range of service entries to be specified in the reply..
- `struct ib_dm_mad *mad`: Datagram that will be sent as response to DM_ATTR_SVC_ENTRIES.

**Description**

See also section 16.3.3.5 ServiceEntries in the InfiniBand Architecture
Specification. See also section B.7, table B.8 in the SRP r16a document.

#### <a id="c-srpt_mgmt_method_get"></a>`srpt_mgmt_method_get()`

```c
void srpt_mgmt_method_get(struct srpt_port *sp, struct ib_mad *rq_mad, struct ib_dm_mad *rsp_mad)
```

process a received management datagram

**Parameters**

- `struct srpt_port *sp`: HCA port through which the MAD has been received.
- `struct ib_mad *rq_mad`: received MAD.
- `struct ib_dm_mad *rsp_mad`: response MAD.

#### <a id="c-srpt_mad_send_handler"></a>`srpt_mad_send_handler()`

```c
void srpt_mad_send_handler(struct ib_mad_agent *mad_agent, struct ib_mad_send_wc *mad_wc)
```

MAD send completion callback

**Parameters**

- `struct ib_mad_agent *mad_agent`: Return value of `ib_register_mad_agent()`.
- `struct ib_mad_send_wc *mad_wc`: Work completion reporting that the MAD has been sent.

#### <a id="c-srpt_mad_recv_handler"></a>`srpt_mad_recv_handler()`

```c
void srpt_mad_recv_handler(struct ib_mad_agent *mad_agent, struct ib_mad_send_buf *send_buf, struct ib_mad_recv_wc *mad_wc)
```

MAD reception callback function

**Parameters**

- `struct ib_mad_agent *mad_agent`: Return value of `ib_register_mad_agent()`.
- `struct ib_mad_send_buf *send_buf`: Not used.
- `struct ib_mad_recv_wc *mad_wc`: Work completion reporting that a MAD has been received.

#### <a id="c-srpt_refresh_port"></a>`srpt_refresh_port()`

```c
int srpt_refresh_port(struct srpt_port *sport)
```

configure a HCA port

**Parameters**

- `struct srpt_port *sport`: SRPT HCA port.

**Description**

Enable InfiniBand management datagram processing, update the cached sm_lid,
lid and gid values, and register a callback function for processing MADs
on the specified port.

**Note**

It is safe to call this function more than once for the same port.

#### <a id="c-srpt_unregister_mad_agent"></a>`srpt_unregister_mad_agent()`

```c
void srpt_unregister_mad_agent(struct srpt_device *sdev, int port_cnt)
```

unregister MAD callback functions

**Parameters**

- `struct srpt_device *sdev`: SRPT HCA pointer.
- `int port_cnt`: number of ports with registered MAD

**Note**

It is safe to call this function more than once for the same device.

#### <a id="c-srpt_alloc_ioctx"></a>`srpt_alloc_ioctx()`

```c
struct srpt_ioctx * srpt_alloc_ioctx(struct srpt_device *sdev, int ioctx_size, struct kmem_cache *buf_cache, enum dma_data_direction dir)
```

allocate a SRPT I/O context structure

**Parameters**

- `struct srpt_device *sdev`: SRPT HCA pointer.
- `int ioctx_size`: I/O context size.
- `struct kmem_cache *buf_cache`: I/O buffer cache.
- `enum dma_data_direction dir`: DMA data direction.

#### <a id="c-srpt_free_ioctx"></a>`srpt_free_ioctx()`

```c
void srpt_free_ioctx(struct srpt_device *sdev, struct srpt_ioctx *ioctx, struct kmem_cache *buf_cache, enum dma_data_direction dir)
```

free a SRPT I/O context structure

**Parameters**

- `struct srpt_device *sdev`: SRPT HCA pointer.
- `struct srpt_ioctx *ioctx`: I/O context pointer.
- `struct kmem_cache *buf_cache`: I/O buffer cache.
- `enum dma_data_direction dir`: DMA data direction.

#### <a id="c-srpt_alloc_ioctx_ring"></a>`srpt_alloc_ioctx_ring()`

```c
struct srpt_ioctx ** srpt_alloc_ioctx_ring(struct srpt_device *sdev, int ring_size, int ioctx_size, struct kmem_cache *buf_cache, int alignment_offset, enum dma_data_direction dir)
```

allocate a ring of SRPT I/O context structures

**Parameters**

- `struct srpt_device *sdev`: Device to allocate the I/O context ring for.
- `int ring_size`: Number of elements in the I/O context ring.
- `int ioctx_size`: I/O context size.
- `struct kmem_cache *buf_cache`: I/O buffer cache.
- `int alignment_offset`: Offset in each ring buffer at which the SRP information
  unit starts.
- `enum dma_data_direction dir`: DMA data direction.

#### <a id="c-srpt_free_ioctx_ring"></a>`srpt_free_ioctx_ring()`

```c
void srpt_free_ioctx_ring(struct srpt_ioctx **ioctx_ring, struct srpt_device *sdev, int ring_size, struct kmem_cache *buf_cache, enum dma_data_direction dir)
```

free the ring of SRPT I/O context structures

**Parameters**

- `struct srpt_ioctx **ioctx_ring`: I/O context ring to be freed.
- `struct srpt_device *sdev`: SRPT HCA pointer.
- `int ring_size`: Number of ring elements.
- `struct kmem_cache *buf_cache`: I/O buffer cache.
- `enum dma_data_direction dir`: DMA data direction.

#### <a id="c-srpt_set_cmd_state"></a>`srpt_set_cmd_state()`

```c
enum srpt_command_state srpt_set_cmd_state(struct srpt_send_ioctx *ioctx, enum srpt_command_state new)
```

set the state of a SCSI command

**Parameters**

- `struct srpt_send_ioctx *ioctx`: Send I/O context.
- `enum srpt_command_state new`: New I/O context state.

**Description**

Does not modify the state of aborted commands. Returns the previous command
state.

#### <a id="c-srpt_test_and_set_cmd_state"></a>`srpt_test_and_set_cmd_state()`

```c
bool srpt_test_and_set_cmd_state(struct srpt_send_ioctx *ioctx, enum srpt_command_state old, enum srpt_command_state new)
```

test and set the state of a command

**Parameters**

- `struct srpt_send_ioctx *ioctx`: Send I/O context.
- `enum srpt_command_state old`: Current I/O context state.
- `enum srpt_command_state new`: New I/O context state.

**Description**

Returns true if and only if the previous command state was equal to 'old'.

#### <a id="c-srpt_post_recv"></a>`srpt_post_recv()`

```c
int srpt_post_recv(struct srpt_device *sdev, struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *ioctx)
```

post an IB receive request

**Parameters**

- `struct srpt_device *sdev`: SRPT HCA pointer.
- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.
- `struct srpt_recv_ioctx *ioctx`: Receive I/O context pointer.

#### <a id="c-srpt_zerolength_write"></a>`srpt_zerolength_write()`

```c
int srpt_zerolength_write(struct srpt_rdma_ch *ch)
```

perform a zero-length RDMA write

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

**Description**

A quote from the InfiniBand specification: C9-88: For an HCA responder
using Reliable Connection service, for each zero-length RDMA READ or WRITE
request, the R_Key shall not be validated, even if the request includes
Immediate data.

#### <a id="c-srpt_get_desc_tbl"></a>`srpt_get_desc_tbl()`

```c
int srpt_get_desc_tbl(struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *ioctx, struct srp_cmd *srp_cmd, enum dma_data_direction *dir, struct scatterlist **sg, unsigned int *sg_cnt, u64 *data_len, u16 imm_data_offset)
```

parse the data descriptors of a SRP_CMD request

**Parameters**

- `struct srpt_recv_ioctx *recv_ioctx`: I/O context associated with the received command **srp_cmd**.
- `struct srpt_send_ioctx *ioctx`: I/O context that will be used for responding to the initiator.
- `struct srp_cmd *srp_cmd`: Pointer to the SRP_CMD request data.
- `enum dma_data_direction *dir`: Pointer to the variable to which the transfer direction will be
  written.
- `struct scatterlist **sg`: \[out\] scatterlist for the parsed SRP_CMD.
- `unsigned int *sg_cnt`: \[out\] length of **sg**.
- `u64 *data_len`: Pointer to the variable to which the total data length of all
  descriptors in the SRP_CMD request will be written.
- `u16 imm_data_offset`: \[in\] Offset in SRP_CMD requests at which immediate data
  starts.

**Description**

This function initializes ioctx->nrbuf and ioctx->r_bufs.

Returns -EINVAL when the SRP_CMD request contains inconsistent descriptors;
-ENOMEM when memory allocation fails and zero upon success.

#### <a id="c-srpt_init_ch_qp"></a>`srpt_init_ch_qp()`

```c
int srpt_init_ch_qp(struct srpt_rdma_ch *ch, struct ib_qp *qp)
```

initialize queue pair attributes

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.
- `struct ib_qp *qp`: Queue pair pointer.

**Description**

Initialized the attributes of queue pair 'qp' by allowing local write,
remote read and remote write. Also transitions 'qp' to state IB_QPS_INIT.

#### <a id="c-srpt_ch_qp_rtr"></a>`srpt_ch_qp_rtr()`

```c
int srpt_ch_qp_rtr(struct srpt_rdma_ch *ch, struct ib_qp *qp)
```

change the state of a channel to 'ready to receive' (RTR)

**Parameters**

- `struct srpt_rdma_ch *ch`: channel of the queue pair.
- `struct ib_qp *qp`: queue pair to change the state of.

**Description**

Returns zero upon success and a negative value upon failure.

**Note**

currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
If this structure ever becomes larger, it might be necessary to allocate
it dynamically instead of on the stack.

#### <a id="c-srpt_ch_qp_rts"></a>`srpt_ch_qp_rts()`

```c
int srpt_ch_qp_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp)
```

change the state of a channel to 'ready to send' (RTS)

**Parameters**

- `struct srpt_rdma_ch *ch`: channel of the queue pair.
- `struct ib_qp *qp`: queue pair to change the state of.

**Description**

Returns zero upon success and a negative value upon failure.

**Note**

currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
If this structure ever becomes larger, it might be necessary to allocate
it dynamically instead of on the stack.

#### <a id="c-srpt_ch_qp_err"></a>`srpt_ch_qp_err()`

```c
int srpt_ch_qp_err(struct srpt_rdma_ch *ch)
```

set the channel queue pair state to 'error'

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

#### <a id="c-srpt_get_send_ioctx"></a>`srpt_get_send_ioctx()`

```c
struct srpt_send_ioctx * srpt_get_send_ioctx(struct srpt_rdma_ch *ch)
```

obtain an I/O context for sending to the initiator

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

#### <a id="c-srpt_abort_cmd"></a>`srpt_abort_cmd()`

```c
int srpt_abort_cmd(struct srpt_send_ioctx *ioctx)
```

abort a SCSI command

**Parameters**

- `struct srpt_send_ioctx *ioctx`: I/O context associated with the SCSI command.

#### <a id="c-srpt_rdma_read_done"></a>`srpt_rdma_read_done()`

```c
void srpt_rdma_read_done(struct ib_cq *cq, struct ib_wc *wc)
```

RDMA read completion callback

**Parameters**

- `struct ib_cq *cq`: Completion queue.
- `struct ib_wc *wc`: Work completion.

**Description**

XXX: what is now target_execute_cmd used to be asynchronous, and unmapping
the data that has been transferred via IB RDMA had to be postponed until the
`check_stop_free()` callback.  None of this is necessary anymore and needs to
be cleaned up.

#### <a id="c-srpt_build_cmd_rsp"></a>`srpt_build_cmd_rsp()`

```c
int srpt_build_cmd_rsp(struct srpt_rdma_ch *ch, struct srpt_send_ioctx *ioctx, u64 tag, int status)
```

build a SRP_RSP response

**Parameters**

- `struct srpt_rdma_ch *ch`: RDMA channel through which the request has been received.
- `struct srpt_send_ioctx *ioctx`: I/O context associated with the SRP_CMD request. The response will
  be built in the buffer ioctx->buf points at and hence this function will
  overwrite the request data.
- `u64 tag`: tag of the request for which this response is being generated.
- `int status`: value for the STATUS field of the SRP_RSP information unit.

**Description**

Returns the size in bytes of the SRP_RSP response.

An SRP_RSP response contains a SCSI status or service response. See also
section 6.9 in the SRP r16a document for the format of an SRP_RSP
response. See also SPC-2 for more information about sense data.

#### <a id="c-srpt_build_tskmgmt_rsp"></a>`srpt_build_tskmgmt_rsp()`

```c
int srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch, struct srpt_send_ioctx *ioctx, u8 rsp_code, u64 tag)
```

build a task management response

**Parameters**

- `struct srpt_rdma_ch *ch`: RDMA channel through which the request has been received.
- `struct srpt_send_ioctx *ioctx`: I/O context in which the SRP_RSP response will be built.
- `u8 rsp_code`: RSP_CODE that will be stored in the response.
- `u64 tag`: Tag of the request for which this response is being generated.

**Description**

Returns the size in bytes of the SRP_RSP response.

An SRP_RSP response contains a SCSI status or service response. See also
section 6.9 in the SRP r16a document for the format of an SRP_RSP
response.

#### <a id="c-srpt_handle_cmd"></a>`srpt_handle_cmd()`

```c
void srpt_handle_cmd(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx)
```

process a SRP_CMD information unit

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.
- `struct srpt_recv_ioctx *recv_ioctx`: Receive I/O context.
- `struct srpt_send_ioctx *send_ioctx`: Send I/O context.

#### <a id="c-srpt_handle_tsk_mgmt"></a>`srpt_handle_tsk_mgmt()`

```c
void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx)
```

process a SRP_TSK_MGMT information unit

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.
- `struct srpt_recv_ioctx *recv_ioctx`: Receive I/O context.
- `struct srpt_send_ioctx *send_ioctx`: Send I/O context.

**Description**

Returns 0 if and only if the request will be processed by the target core.

For more information about SRP_TSK_MGMT information units, see also section
6.7 in the SRP r16a document.

#### <a id="c-srpt_handle_new_iu"></a>`srpt_handle_new_iu()`

```c
bool srpt_handle_new_iu(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx)
```

process a newly received information unit

**Parameters**

- `struct srpt_rdma_ch *ch`: RDMA channel through which the information unit has been received.
- `struct srpt_recv_ioctx *recv_ioctx`: Receive I/O context associated with the information unit.

#### <a id="c-srpt_send_done"></a>`srpt_send_done()`

```c
void srpt_send_done(struct ib_cq *cq, struct ib_wc *wc)
```

send completion callback

**Parameters**

- `struct ib_cq *cq`: Completion queue.
- `struct ib_wc *wc`: Work completion.

**Note**

Although this has not yet been observed during tests, at least in
theory it is possible that the [`srpt_get_send_ioctx()`](#c-srpt_get_send_ioctx) call invoked by
[`srpt_handle_new_iu()`](#c-srpt_handle_new_iu) fails. This is possible because the req_lim_delta
value in each response is set to one, and it is possible that this response
makes the initiator send a new request before the send completion for that
response has been processed. This could e.g. happen if the call to
`srpt_put_send_iotcx()` is delayed because of a higher priority interrupt or
if IB retransmission causes generation of the send completion to be
delayed. Incoming information units for which [`srpt_get_send_ioctx()`](#c-srpt_get_send_ioctx) fails
are queued on cmd_wait_list. The code below processes these delayed
requests one at a time.

#### <a id="c-srpt_create_ch_ib"></a>`srpt_create_ch_ib()`

```c
int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
```

create receive and send completion queues

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

#### <a id="c-srpt_close_ch"></a>`srpt_close_ch()`

```c
bool srpt_close_ch(struct srpt_rdma_ch *ch)
```

close a RDMA channel

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

**Description**

Make sure all resources associated with the channel will be deallocated at
an appropriate time.

Returns true if and only if the channel state has been modified into
CH_DRAINING.

#### <a id="c-srpt_cm_req_recv"></a>`srpt_cm_req_recv()`

```c
int srpt_cm_req_recv(struct srpt_device *const sdev, struct ib_cm_id *ib_cm_id, struct rdma_cm_id *rdma_cm_id, u8 port_num, __be16 pkey, const struct srp_login_req *req, const char *src_addr)
```

process the event IB_CM_REQ_RECEIVED

**Parameters**

- `struct srpt_device *const sdev`: HCA through which the login request was received.
- `struct ib_cm_id *ib_cm_id`: IB/CM connection identifier in case of IB/CM.
- `struct rdma_cm_id *rdma_cm_id`: RDMA/CM connection identifier in case of RDMA/CM.
- `u8 port_num`: Port through which the REQ message was received.
- `__be16 pkey`: P_Key of the incoming connection.
- `const struct srp_login_req *req`: SRP login request.
- `const char *src_addr`: GID (IB/CM) or IP address (RDMA/CM) of the port that submitted
  the login request.

**Description**

Ownership of the cm_id is transferred to the target session if this
function returns zero. Otherwise the caller remains the owner of cm_id.

#### <a id="c-srpt_cm_rtu_recv"></a>`srpt_cm_rtu_recv()`

```c
void srpt_cm_rtu_recv(struct srpt_rdma_ch *ch)
```

process an IB_CM_RTU_RECEIVED or USER_ESTABLISHED event

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

**Description**

An RTU (ready to use) message indicates that the connection has been
established and that the recipient may begin transmitting.

#### <a id="c-srpt_cm_handler"></a>`srpt_cm_handler()`

```c
int srpt_cm_handler(struct ib_cm_id *cm_id, const struct ib_cm_event *event)
```

IB connection manager callback function

**Parameters**

- `struct ib_cm_id *cm_id`: IB/CM connection identifier.
- `const struct ib_cm_event *event`: IB/CM event.

**Description**

A non-zero return value will cause the caller destroy the CM ID.

**Note**

[`srpt_cm_handler()`](#c-srpt_cm_handler) must only return a non-zero value when transferring
ownership of the cm_id to a channel by [`srpt_cm_req_recv()`](#c-srpt_cm_req_recv) failed. Returning
a non-zero value in any other case will trigger a race with the
`ib_destroy_cm_id()` call in `srpt_release_channel()`.

#### <a id="c-srpt_queue_response"></a>`srpt_queue_response()`

```c
void srpt_queue_response(struct se_cmd *cmd)
```

transmit the response to a SCSI command

**Parameters**

- `struct se_cmd *cmd`: SCSI target command.

**Description**

Callback function called by the TCM core. Must not block since it can be
invoked on the context of the IB completion handler.

#### <a id="c-srpt_release_sport"></a>`srpt_release_sport()`

```c
int srpt_release_sport(struct srpt_port *sport)
```

disable login and wait for associated channels

**Parameters**

- `struct srpt_port *sport`: SRPT HCA port.

#### <a id="c-srpt_lookup_port"></a>`srpt_lookup_port()`

```c
struct port_and_port_id srpt_lookup_port(const char *name)
```

Look up an RDMA port by name

**Parameters**

- `const char *name`: ASCII port name

**Description**

Increments the RDMA port reference count if an RDMA port pointer is returned.
The caller must drop that reference count by calling `srpt_port_put_ref()`.

#### <a id="c-srpt_add_one"></a>`srpt_add_one()`

```c
int srpt_add_one(struct ib_device *device)
```

InfiniBand device addition callback function

**Parameters**

- `struct ib_device *device`: Describes a HCA.

#### <a id="c-srpt_remove_one"></a>`srpt_remove_one()`

```c
void srpt_remove_one(struct ib_device *device, void *client_data)
```

InfiniBand device removal callback function

**Parameters**

- `struct ib_device *device`: Describes a HCA.
- `void *client_data`: The value passed as the third argument to [`ib_set_client_data()`](#c-ib_set_client_data).

#### <a id="c-srpt_close_session"></a>`srpt_close_session()`

```c
void srpt_close_session(struct se_session *se_sess)
```

forcibly close a session

**Parameters**

- `struct se_session *se_sess`: SCSI target session.

**Description**

Callback function invoked by the TCM core to clean up sessions associated
with a node ACL when the user invokes
rmdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id

#### <a id="c-srpt_parse_i_port_id"></a>`srpt_parse_i_port_id()`

```c
int srpt_parse_i_port_id(u8 i_port_id[16], const char *name)
```

parse an initiator port ID

**Parameters**

- `u8 i_port_id[16]`: Binary 128-bit port ID.
- `const char *name`: ASCII representation of a 128-bit initiator port ID.

#### <a id="c-srpt_make_tpg"></a>`srpt_make_tpg()`

```c
struct se_portal_group * srpt_make_tpg(struct se_wwn *wwn, const char *name)
```

configfs callback invoked for mkdir /sys/kernel/config/target/$driver/$port/$tpg

**Parameters**

- `struct se_wwn *wwn`: Corresponds to $driver/$port.
- `const char *name`: $tpg.

#### <a id="c-srpt_drop_tpg"></a>`srpt_drop_tpg()`

```c
void srpt_drop_tpg(struct se_portal_group *tpg)
```

configfs callback invoked for rmdir /sys/kernel/config/target/$driver/$port/$tpg

**Parameters**

- `struct se_portal_group *tpg`: Target portal group to deregister.

#### <a id="c-srpt_make_tport"></a>`srpt_make_tport()`

```c
struct se_wwn * srpt_make_tport(struct target_fabric_configfs *tf, struct config_group *group, const char *name)
```

configfs callback invoked for mkdir /sys/kernel/config/target/$driver/$port

**Parameters**

- `struct target_fabric_configfs *tf`: Not used.
- `struct config_group *group`: Not used.
- `const char *name`: $port.

#### <a id="c-srpt_drop_tport"></a>`srpt_drop_tport()`

```c
void srpt_drop_tport(struct se_wwn *wwn)
```

configfs callback invoked for rmdir /sys/kernel/config/target/$driver/$port

**Parameters**

- `struct se_wwn *wwn`: $port.

#### <a id="c-srpt_init_module"></a>`srpt_init_module()`

```c
int srpt_init_module(void)
```

kernel module initialization

**Parameters**

- `void`: no arguments

**Note**

Since [`ib_register_client()`](#c-ib_register_client) registers callback functions, and since at
least one of these callback functions ([`srpt_add_one()`](#c-srpt_add_one)) calls target core
functions, this driver must be registered with the target core before
[`ib_register_client()`](#c-ib_register_client) is called.


<a id="rst-iscsi-extensions-for-rdma-iser-target-support"></a>

### iSCSI Extensions for RDMA (iSER) target support


#### <a id="c-isert_conn_terminate"></a>`isert_conn_terminate()`

```c
void isert_conn_terminate(struct isert_conn *isert_conn)
```

Initiate connection termination

**Parameters**

- `struct isert_conn *isert_conn`: isert connection struct

**Notes**

In case the connection state is BOUND, move state
to TEMINATING and start teardown sequence (rdma_disconnect).
In case the connection state is UP, complete flush as well.

This routine must be called with mutex held. Thus it is
safe to call multiple times.

#### <a id="c-isert_put_unsol_pending_cmds"></a>`isert_put_unsol_pending_cmds()`

```c
void isert_put_unsol_pending_cmds(struct iscsit_conn *conn)
```

Drop commands waiting for unsolicitate dataout

**Parameters**

- `struct iscsit_conn *conn`: iscsi connection

**Description**

We might still have commands that are waiting for unsolicited
dataouts messages. We must put the extra reference on those
before blocking on the target_wait_for_session_cmds

---

# ISA Drivers

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> The following text is adapted from the commit message of the initial commit of the ISA bus driver authored by Rene Herman.

<a id="rst-isa-drivers"></a>

The following text is adapted from the commit message of the initial commit of the ISA bus driver authored by Rene Herman.

During the recent "isa drivers using platform devices" discussion it was pointed out that (ALSA) ISA drivers ran into the problem of not having the option to fail driver load (device registration rather) upon not finding their hardware due to a probe() error not being passed up through the driver model. In the course of that, I suggested a separate ISA bus might be best; Russell King agreed and suggested this bus could use the .match() method for the actual device discovery.

The attached does this. For this old non (generically) discoverable ISA hardware only the driver itself can do discovery so as a difference with the platform_bus, this isa_bus also distributes match() up to the driver.

As another difference: these devices only exist in the driver model due to the driver creating them because it might want to drive them, meaning that all device creation has been made internal as well.

The usage model this provides is nice, and has been acked from the ALSA side by Takashi Iwai and Jaroslav Kysela. The ALSA driver module_init's now (for oldisa-only drivers) become:



```text
static int __init alsa_card_foo_init(void)
{
        return isa_register_driver(&snd_foo_isa_driver, SNDRV_CARDS);
}

static void __exit alsa_card_foo_exit(void)
{
        isa_unregister_driver(&snd_foo_isa_driver);
}
```

Quite like the other bus models therefore. This removes a lot of duplicated init code from the ALSA ISA drivers.

The passed in isa_driver struct is the regular driver struct embedding a struct device_driver, the normal probe/remove/shutdown/suspend/resume callbacks, and as indicated that .match callback.

The "SNDRV_CARDS" you see being passed in is a "unsigned int ndev" parameter, indicating how many devices to create and call our methods with.

The platform_driver callbacks are called with a platform_device param; the isa_driver callbacks are being called with a `struct device *dev, unsigned int id` pair directly -- with the device creation completely internal to the bus it's much cleaner to not leak isa_dev's by passing them in at all. The id is the only thing we ever want other then the struct device anyways, and it makes for nicer code in the callbacks as well.

With this additional .match() callback ISA drivers have all options. If ALSA would want to keep the old non-load behaviour, it could stick all of the old .probe in .match, which would only keep them registered after everything was found to be present and accounted for. If it wanted the behaviour of always loading as it inadvertently did for a bit after the changeover to platform devices, it could just not provide a .match() and do everything in .probe() as before.

If it, as Takashi Iwai already suggested earlier as a way of following the model from saner buses more closely, wants to load when a later bind could conceivably succeed, it could use .match() for the prerequisites (such as checking the user wants the card enabled and that port/irq/dma values have been passed in) and .probe() for everything else. This is the nicest model.

To the code...

This exports only two functions; isa\_\{,un\}register_driver().

isa_register_driver() register's the struct device_driver, and then loops over the passed in ndev creating devices and registering them. This causes the bus match method to be called for them, which is:



```text
int isa_bus_match(struct device *dev, struct device_driver *driver)
{
        struct isa_driver *isa_driver = to_isa_driver(driver);

        if (dev->platform_data == isa_driver) {
                if (!isa_driver->match ||
                        isa_driver->match(dev, to_isa_dev(dev)->id))
                        return 1;
                dev->platform_data = NULL;
        }
        return 0;
}
```

The first thing this does is check if this device is in fact one of this driver's devices by seeing if the device's platform_data pointer is set to this driver. Platform devices compare strings, but we don't need to do that with everything being internal, so isa_register_driver() abuses dev-&gt;platform_data as a isa_driver pointer which we can then check here. I believe platform_data is available for this, but if rather not, moving the isa_driver pointer to the private struct isa_dev is ofcourse fine as well.

Then, if the driver did not provide a .match, it matches. If it did, the driver match() method is called to determine a match.

If it did **not** match, dev-&gt;platform_data is reset to indicate this to isa_register_driver which can then unregister the device again.

If during all this, there's any error, or no devices matched at all everything is backed out again and the error, or -ENODEV, is returned.

isa_unregister_driver() just unregisters the matched devices and the driver itself.

module_isa_driver is a helper macro for ISA drivers which do not do anything special in module init/exit. This eliminates a lot of boilerplate code. Each module may only use this macro once, and calling it replaces module_init and module_exit.

max_num_isa_dev is a macro to determine the maximum possible number of ISA devices which may be registered in the I/O port address space given the address extent of the ISA devices.

---

# libATA Developer's Guide

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> libATA is a library used inside the Linux kernel to support ATA host controllers and devices. libATA provides an ATA driver API, class transports for ATA and ATAPI devices, and SCSI<->ATA translation for ATA devices according to the T10…

<a id="rst-libata-developer-s-guide"></a>

**Author:** Jeff Garzik

<a id="rst-introduction"></a>

## Introduction

libATA is a library used inside the Linux kernel to support ATA host controllers and devices. libATA provides an ATA driver API, class transports for ATA and ATAPI devices, and SCSI&lt;-&gt;ATA translation for ATA devices according to the T10 SAT specification.

This Guide documents the libATA driver API, library functions, library internals, and a couple sample ATA low-level drivers.

<a id="rst-libata-driver-api"></a>

## libata Driver API

`struct ata_port_operations <ata_port_operations>` is defined for every low-level libata hardware driver, and it controls how the low-level driver interfaces with the ATA and SCSI layers.

FIS-based drivers will hook into the system with `->qc_prep()` and `->qc_issue()` high-level hooks. Hardware which behaves in a manner similar to PCI IDE hardware may utilize several generic helpers, defining at a bare minimum the bus I/O addresses of the ATA shadow register blocks.

<a id="rst-struct-ata-port-operations-ata-port-operations"></a>

### `struct ata_port_operations <ata_port_operations>`

<a id="rst-post-identify-device-configuration"></a>

#### Post-IDENTIFY device configuration



```text
void (*dev_config) (struct ata_port *, struct ata_device *);
```

Called after IDENTIFY \[PACKET\] DEVICE is issued to each device found. Typically used to apply device-specific fixups prior to issue of SET FEATURES - XFER MODE, and prior to operation.

This entry may be specified as NULL in ata_port_operations.

<a id="rst-set-pio-dma-mode"></a>

#### Set PIO/DMA mode



```text
void (*set_piomode) (struct ata_port *, struct ata_device *);
void (*set_dmamode) (struct ata_port *, struct ata_device *);
void (*post_set_mode) (struct ata_port *);
unsigned int (*mode_filter) (struct ata_port *, struct ata_device *, unsigned int);
```

Hooks called prior to the issue of SET FEATURES - XFER MODE command. The optional `->mode_filter()` hook is called when libata has built a mask of the possible modes. This is passed to the `->mode_filter()` function which should return a mask of valid modes after filtering those unsuitable due to hardware limits. It is not valid to use this interface to add modes.

`dev->pio_mode` and `dev->dma_mode` are guaranteed to be valid when `->set_piomode()` and when `->set_dmamode()` is called. The timings for any other drive sharing the cable will also be valid at this point. That is the library records the decisions for the modes of each drive on a channel before it attempts to set any of them.

`->post_set_mode()` is called unconditionally, after the SET FEATURES - XFER MODE command completes successfully.

`->set_piomode()` is always called (if present), but `->set_dma_mode()` is only called if DMA is possible.

<a id="rst-taskfile-read-write"></a>

#### Taskfile read/write



```text
void (*sff_tf_load) (struct ata_port *ap, struct ata_taskfile *tf);
void (*sff_tf_read) (struct ata_port *ap, struct ata_taskfile *tf);
```

`->tf_load()` is called to load the given taskfile into hardware registers / DMA buffers. `->tf_read()` is called to read the hardware registers / DMA buffers, to obtain the current set of taskfile register values. Most drivers for taskfile-based hardware (PIO or MMIO) use `ata_sff_tf_load()` and `ata_sff_tf_read()` for these hooks.

<a id="rst-pio-data-read-write"></a>

#### PIO data read/write



```text
void (*sff_data_xfer) (struct ata_device *, unsigned char *, unsigned int, int);
```

All bmdma-style drivers must implement this hook. This is the low-level operation that actually copies the data bytes during a PIO data transfer. Typically the driver will choose one of `ata_sff_data_xfer()`, or `ata_sff_data_xfer32()`.

<a id="rst-ata-command-execute"></a>

#### ATA command execute



```text
void (*sff_exec_command)(struct ata_port *ap, struct ata_taskfile *tf);
```

causes an ATA command, previously loaded with `->tf_load()`, to be initiated in hardware. Most drivers for taskfile-based hardware use `ata_sff_exec_command()` for this hook.

<a id="rst-per-cmd-atapi-dma-capabilities-filter"></a>

#### Per-cmd ATAPI DMA capabilities filter



```text
int (*check_atapi_dma) (struct ata_queued_cmd *qc);
```

Allow low-level driver to filter ATA PACKET commands, returning a status indicating whether or not it is OK to use DMA for the supplied PACKET command.

This hook may be specified as NULL, in which case libata will assume that atapi dma can be supported.

<a id="rst-read-specific-ata-shadow-registers"></a>

#### Read specific ATA shadow registers



```text
u8   (*sff_check_status)(struct ata_port *ap);
u8   (*sff_check_altstatus)(struct ata_port *ap);
```

Reads the Status/AltStatus ATA shadow register from hardware. On some hardware, reading the Status register has the side effect of clearing the interrupt condition. Most drivers for taskfile-based hardware use `ata_sff_check_status()` for this hook.

<a id="rst-write-specific-ata-shadow-register"></a>

#### Write specific ATA shadow register



```text
void (*sff_set_devctl)(struct ata_port *ap, u8 ctl);
```

Write the device control ATA shadow register to the hardware. Most drivers don't need to define this.

<a id="rst-select-ata-device-on-bus"></a>

#### Select ATA device on bus



```text
void (*sff_dev_select)(struct ata_port *ap, unsigned int device);
```

Issues the low-level hardware command(s) that causes one of N hardware devices to be considered 'selected' (active and available for use) on the ATA bus. This generally has no meaning on FIS-based devices.

Most drivers for taskfile-based hardware use `ata_sff_dev_select()` for this hook.

<a id="rst-private-tuning-method"></a>

#### Private tuning method



```text
void (*set_mode) (struct ata_port *ap);
```

By default libata performs drive and controller tuning in accordance with the ATA timing rules and also applies blacklists and cable limits. Some controllers need special handling and have custom tuning rules, typically raid controllers that use ATA commands but do not actually do drive timing.

> **Warning**
>
> This hook should not be used to replace the standard controller tuning logic when a controller has quirks. Replacing the default tuning logic in that case would bypass handling for drive and bridge quirks that may be important to data reliability. If a controller needs to filter the mode selection it should use the mode_filter hook instead.

<a id="rst-control-pci-ide-bmdma-engine"></a>

#### Control PCI IDE BMDMA engine



```text
void (*bmdma_setup) (struct ata_queued_cmd *qc);
void (*bmdma_start) (struct ata_queued_cmd *qc);
void (*bmdma_stop) (struct ata_port *ap);
u8   (*bmdma_status) (struct ata_port *ap);
```

When setting up an IDE BMDMA transaction, these hooks arm (`->bmdma_setup`), fire (`->bmdma_start`), and halt (`->bmdma_stop`) the hardware's DMA engine. `->bmdma_status` is used to read the standard PCI IDE DMA Status register.

These hooks are typically either no-ops, or simply not implemented, in FIS-based drivers.

Most legacy IDE drivers use `ata_bmdma_setup()` for the `bmdma_setup()` hook. `ata_bmdma_setup()` will write the pointer to the PRD table to the IDE PRD Table Address register, enable DMA in the DMA Command register, and call `exec_command()` to begin the transfer.

Most legacy IDE drivers use `ata_bmdma_start()` for the `bmdma_start()` hook. `ata_bmdma_start()` will write the ATA_DMA_START flag to the DMA Command register.

Many legacy IDE drivers use `ata_bmdma_stop()` for the `bmdma_stop()` hook. `ata_bmdma_stop()` clears the ATA_DMA_START flag in the DMA command register.

Many legacy IDE drivers use `ata_bmdma_status()` as the `bmdma_status()` hook.

<a id="rst-high-level-taskfile-hooks"></a>

#### High-level taskfile hooks



```text
enum ata_completion_errors (*qc_prep) (struct ata_queued_cmd *qc);
int (*qc_issue) (struct ata_queued_cmd *qc);
```

Higher-level hooks, these two hooks can potentially supersede several of the above taskfile/DMA engine hooks. `->qc_prep` is called after the buffers have been DMA-mapped, and is typically used to populate the hardware's DMA scatter-gather table. Some drivers use the standard `ata_bmdma_qc_prep()` and `ata_bmdma_dumb_qc_prep()` helper functions, but more advanced drivers roll their own.

`->qc_issue` is used to make a command active, once the hardware and S/G tables have been prepared. IDE BMDMA drivers use the helper function `ata_sff_qc_issue()` for taskfile protocol-based dispatch. More advanced drivers implement their own `->qc_issue`.

`ata_sff_qc_issue()` calls `->sff_tf_load()`, `->bmdma_setup()`, and `->bmdma_start()` as necessary to initiate a transfer.

<a id="rst-exception-and-probe-handling-eh"></a>

#### Exception and probe handling (EH)



```text
void (*freeze) (struct ata_port *ap);
void (*thaw) (struct ata_port *ap);
```

`ata_port_freeze()` is called when HSM violations or some other condition disrupts normal operation of the port. A frozen port is not allowed to perform any operation until the port is thawed, which usually follows a successful reset.

The optional `->freeze()` callback can be used for freezing the port hardware-wise (e.g. mask interrupt and stop DMA engine). If a port cannot be frozen hardware-wise, the interrupt handler must ack and clear interrupts unconditionally while the port is frozen.

The optional `->thaw()` callback is called to perform the opposite of `->freeze()`: prepare the port for normal operation once again. Unmask interrupts, start DMA engine, etc.



```text
void (*error_handler) (struct ata_port *ap);
```

`->error_handler()` is a driver's hook into probe, hotplug, and recovery and other exceptional conditions. The primary responsibility of an implementation is to call `ata_std_error_handler()`.

`ata_std_error_handler()` will perform a standard error handling sequence to resurect failed devices, detach lost devices and add new devices (if any). This function will call the various reset operations for a port, as needed. These operations are as follows.

- The 'prereset' operation (which may be NULL) is called during an EH reset, before any other action is taken.

- The 'postreset' hook (which may be NULL) is called after the EH reset is performed. Based on existing conditions, severity of the problem, and hardware capabilities,

- Either the 'softreset' operation or the 'hardreset' operation will be called to perform the low-level EH reset. If both operations are defined, 'hardreset' is preferred and used. If both are not defined, no low-level reset is performed and EH assumes that an ATA class device is connected through the link.



```text
void (*post_internal_cmd) (struct ata_queued_cmd *qc);
```

Perform any hardware-specific actions necessary to finish processing after executing a probe-time or EH-time command via `ata_exec_internal()`.

<a id="rst-hardware-interrupt-handling"></a>

#### Hardware interrupt handling



```text
irqreturn_t (*irq_handler)(int, void *, struct pt_regs *);
void (*irq_clear) (struct ata_port *);
```

`->irq_handler` is the interrupt handling routine registered with the system, by libata. `->irq_clear` is called during probe just before the interrupt handler is registered, to be sure hardware is quiet.

The second argument, dev_instance, should be cast to a pointer to `struct ata_host_set <ata_host_set>`.

Most legacy IDE drivers use `ata_sff_interrupt()` for the irq_handler hook, which scans all ports in the host_set, determines which queued command was active (if any), and calls ata_sff_host_intr(ap,qc).

Most legacy IDE drivers use `ata_sff_irq_clear()` for the `irq_clear()` hook, which simply clears the interrupt and error flags in the DMA status register.

<a id="rst-sata-phy-read-write"></a>

#### SATA phy read/write



```text
int (*scr_read) (struct ata_port *ap, unsigned int sc_reg,
         u32 *val);
int (*scr_write) (struct ata_port *ap, unsigned int sc_reg,
                   u32 val);
```

Read and write standard SATA phy registers. sc_reg is one of SCR_STATUS, SCR_CONTROL, SCR_ERROR, or SCR_ACTIVE.

<a id="rst-init-and-shutdown"></a>

#### Init and shutdown



```text
int (*port_start) (struct ata_port *ap);
void (*port_stop) (struct ata_port *ap);
void (*host_stop) (struct ata_host_set *host_set);
```

`->port_start()` is called just after the data structures for each port are initialized. Typically this is used to alloc per-port DMA buffers / tables / rings, enable DMA engines, and similar tasks. Some drivers also use this entry point as a chance to allocate driver-private memory for `ap->private_data`.

Many drivers use `ata_port_start()` as this hook or call it from their own `port_start()` hooks. `ata_port_start()` allocates space for a legacy IDE PRD table and returns.

`->port_stop()` is called after `->host_stop()`. Its sole function is to release DMA/memory resources, now that they are no longer actively being used. Many drivers also free driver-private data from port at this time.

`->host_stop()` is called after all `->port_stop()` calls have completed. The hook must finalize hardware shutdown, release DMA and other resources, etc. This hook may be specified as NULL, in which case it is not called.

<a id="rst-error-handling"></a>

## Error handling

This chapter describes how errors are handled under libata. Readers are advised to read SCSI EH ([Documentation/scsi/scsi_eh.rst](/kernel/hardware/scsi/scsi-eh.md)) and ATA exceptions doc first.

<a id="rst-origins-of-commands"></a>

### Origins of commands

In libata, a command is represented with `struct ata_queued_cmd <ata_queued_cmd>` or qc. qc's are preallocated during port initialization and repetitively used for command executions. Currently only one qc is allocated per port but yet-to-be-merged NCQ branch allocates one for each tag and maps each qc to NCQ tag 1-to-1.

libata commands can originate from two sources - libata itself and SCSI midlayer. libata internal commands are used for initialization and error handling. All normal blk requests and commands for SCSI emulation are passed as SCSI commands through queuecommand callback of SCSI host template.

<a id="rst-how-commands-are-issued"></a>

### How commands are issued

- **Internal commands**

  Once allocated qc's taskfile is initialized for the command to be executed. qc currently has two mechanisms to notify completion. One is via `qc->complete_fn()` callback and the other is completion `qc->waiting`. `qc->complete_fn()` callback is the asynchronous path used by normal SCSI translated commands and `qc->waiting` is the synchronous (issuer sleeps in process context) path used by internal commands.

  Once initialization is complete, host_set lock is acquired and the qc is issued.

- **SCSI commands**

  All libata drivers use `ata_scsi_queuecmd()` as `hostt->queuecommand` callback. scmds can either be simulated or translated. No qc is involved in processing a simulated scmd. The result is computed right away and the scmd is completed.

  `qc->complete_fn()` callback is used for completion notification. ATA commands use `ata_scsi_qc_complete()` while ATAPI commands use `atapi_qc_complete()`. Both functions end up calling `qc->scsidone` to notify upper layer when the qc is finished. After translation is completed, the qc is issued with `ata_qc_issue()`.

  Note that SCSI midlayer invokes hostt-&gt;queuecommand while holding host_set lock, so all above occur while holding host_set lock.

<a id="rst-how-commands-are-processed"></a>

### How commands are processed

Depending on which protocol and which controller are used, commands are processed differently. For the purpose of discussion, a controller which uses taskfile interface and all standard callbacks is assumed.

Currently 6 ATA command protocols are used. They can be sorted into the following four categories according to how they are processed.

- **ATA NO DATA or DMA**

  ATA_PROT_NODATA and ATA_PROT_DMA fall into this category. These types of commands don't require any software intervention once issued. Device will raise interrupt on completion.

- **ATA PIO**

  ATA_PROT_PIO is in this category. libata currently implements PIO with polling. ATA_NIEN bit is set to turn off interrupt and pio_task on ata_wq performs polling and IO.

- **ATAPI NODATA or DMA**

  ATA_PROT_ATAPI_NODATA and ATA_PROT_ATAPI_DMA are in this category. packet_task is used to poll BSY bit after issuing PACKET command. Once BSY is turned off by the device, packet_task transfers CDB and hands off processing to interrupt handler.

- **ATAPI PIO**

  ATA_PROT_ATAPI is in this category. ATA_NIEN bit is set and, as in ATAPI NODATA or DMA, packet_task submits cdb. However, after submitting cdb, further processing (data transfer) is handed off to pio_task.

<a id="rst-how-commands-are-completed"></a>

### How commands are completed

Once issued, all qc's are either completed with `ata_qc_complete()` or time out. For commands which are handled by interrupts, `ata_host_intr()` invokes `ata_qc_complete()`, and, for PIO tasks, pio_task invokes `ata_qc_complete()`. In error cases, packet_task may also complete commands.

`ata_qc_complete()` does the following.

1. DMA memory is unmapped.

2. ATA_QCFLAG_ACTIVE is cleared from qc-&gt;flags.

3. `qc->complete_fn` callback is invoked. If the return value of the callback is not zero. Completion is short circuited and `ata_qc_complete()` returns.

4. `__ata_qc_complete()` is called, which does

   1. `qc->flags` is cleared to zero.

   2. `ap->active_tag` and `qc->tag` are poisoned.

   3. `qc->waiting` is cleared &amp; completed (in that order).

   4. qc is deallocated by clearing appropriate bit in `ap->qactive`.

So, it basically notifies upper layer and deallocates qc. One exception is short-circuit path in \#3 which is used by `atapi_qc_complete()`.

For all non-ATAPI commands, whether it fails or not, almost the same code path is taken and very little error handling takes place. A qc is completed with success status if it succeeded, with failed status otherwise.

However, failed ATAPI commands require more handling as REQUEST SENSE is needed to acquire sense data. If an ATAPI command fails, `ata_qc_complete()` is invoked with error status, which in turn invokes `atapi_qc_complete()` via `qc->complete_fn()` callback.

This makes `atapi_qc_complete()` set `scmd->result` to SAM_STAT_CHECK_CONDITION, complete the scmd and return 1. As the sense data is empty but `scmd->result` is CHECK CONDITION, SCSI midlayer will invoke EH for the scmd, and returning 1 makes `ata_qc_complete()` to return without deallocating the qc. This leads us to `ata_scsi_error()` with partially completed qc.

<a id="rst-ata-scsi-error"></a>

### `ata_scsi_error()`

`ata_scsi_error()` is the current `transportt->eh_strategy_handler()` for libata. As discussed above, this will be entered in two cases - timeout and ATAPI error completion. This function will check if a qc is active and has not failed yet. Such a qc will be marked with AC_ERR_TIMEOUT such that EH will know to handle it later. Then it calls low level libata driver's `error_handler()` callback.

When the `error_handler()` callback is invoked it stops BMDMA and completes the qc. Note that as we're currently in EH, we cannot call scsi_done. As described in SCSI EH doc, a recovered scmd should be either retried with `scsi_queue_insert()` or finished with `scsi_finish_command()`. Here, we override `qc->scsidone` with `scsi_finish_command()` and calls `ata_qc_complete()`.

If EH is invoked due to a failed ATAPI qc, the qc here is completed but not deallocated. The purpose of this half-completion is to use the qc as place holder to make EH code reach this place. This is a bit hackish, but it works.

Once control reaches here, the qc is deallocated by invoking `__ata_qc_complete()` explicitly. Then, internal qc for REQUEST SENSE is issued. Once sense data is acquired, scmd is finished by directly invoking `scsi_finish_command()` on the scmd. Note that as we already have completed and deallocated the qc which was associated with the scmd, we don't need to/cannot call `ata_qc_complete()` again.

<a id="rst-problems-with-the-current-eh"></a>

### Problems with the current EH

- Error representation is too crude. Currently any and all error conditions are represented with ATA STATUS and ERROR registers. Errors which aren't ATA device errors are treated as ATA device errors by setting ATA_ERR bit. Better error descriptor which can properly represent ATA and other errors/exceptions is needed.

- When handling timeouts, no action is taken to make device forget about the timed out command and ready for new commands.

- EH handling via `ata_scsi_error()` is not properly protected from usual command processing. On EH entrance, the device is not in quiescent state. Timed out commands may succeed or fail any time. pio_task and atapi_task may still be running.

- Too weak error recovery. Devices / controllers causing HSM mismatch errors and other errors quite often require reset to return to known state. Also, advanced error handling is necessary to support features like NCQ and hotplug.

- ATA errors are directly handled in the interrupt handler and PIO errors in pio_task. This is problematic for advanced error handling for the following reasons.

  First, advanced error handling often requires context and internal qc execution.

  Second, even a simple failure (say, CRC error) needs information gathering and could trigger complex error handling (say, resetting &amp; reconfiguring). Having multiple code paths to gather information, enter EH and trigger actions makes life painful.

  Third, scattered EH code makes implementing low level drivers difficult. Low level drivers override libata callbacks. If EH is scattered over several places, each affected callbacks should perform its part of error handling. This can be error prone and painful.

<a id="rst-libata-library"></a>

## libata Library


#### <a id="c-ata_link_next"></a>`ata_link_next()`

```c
struct ata_link * ata_link_next(struct ata_link *link, struct ata_port *ap, enum ata_link_iter_mode mode)
```

link iteration helper

**Parameters**

- `struct ata_link *link`: the previous link, NULL to start
- `struct ata_port *ap`: ATA port containing links to iterate
- `enum ata_link_iter_mode mode`: iteration mode, one of ATA_LITER_*

**Description**

LOCKING:
Host lock or EH context.

**Return**

Pointer to the next link.

#### <a id="c-ata_dev_next"></a>`ata_dev_next()`

```c
struct ata_device * ata_dev_next(struct ata_device *dev, struct ata_link *link, enum ata_dev_iter_mode mode)
```

device iteration helper

**Parameters**

- `struct ata_device *dev`: the previous device, NULL to start
- `struct ata_link *link`: ATA link containing devices to iterate
- `enum ata_dev_iter_mode mode`: iteration mode, one of ATA_DITER_*

**Description**

LOCKING:
Host lock or EH context.

**Return**

Pointer to the next device.

#### <a id="c-atapi_cmd_type"></a>`atapi_cmd_type()`

```c
int atapi_cmd_type(u8 opcode)
```

Determine ATAPI command type from SCSI opcode

**Parameters**

- `u8 opcode`: SCSI opcode

**Description**

Determine ATAPI command type from **opcode**.

LOCKING:
None.

**Return**

ATAPI_{READ|WRITE|READ_CD|PASS_THRU|MISC}

#### <a id="c-ata_pack_xfermask"></a>`ata_pack_xfermask()`

```c
unsigned int ata_pack_xfermask(unsigned int pio_mask, unsigned int mwdma_mask, unsigned int udma_mask)
```

Pack pio, mwdma and udma masks into xfer_mask

**Parameters**

- `unsigned int pio_mask`: pio_mask
- `unsigned int mwdma_mask`: mwdma_mask
- `unsigned int udma_mask`: udma_mask

**Description**

Pack **pio_mask**, **mwdma_mask** and **udma_mask** into a single
unsigned int xfer_mask.

LOCKING:
None.

**Return**

Packed xfer_mask.

#### <a id="c-ata_xfer_mask2mode"></a>`ata_xfer_mask2mode()`

```c
u8 ata_xfer_mask2mode(unsigned int xfer_mask)
```

Find matching XFER_* for the given xfer_mask

**Parameters**

- `unsigned int xfer_mask`: xfer_mask of interest

**Description**

Return matching XFER_* value for **xfer_mask**.  Only the highest
bit of **xfer_mask** is considered.

LOCKING:
None.

**Return**

Matching XFER_* value, 0xff if no match found.

#### <a id="c-ata_xfer_mode2mask"></a>`ata_xfer_mode2mask()`

```c
unsigned int ata_xfer_mode2mask(u8 xfer_mode)
```

Find matching xfer_mask for XFER_*

**Parameters**

- `u8 xfer_mode`: XFER_* of interest

**Description**

Return matching xfer_mask for **xfer_mode**.

LOCKING:
None.

**Return**

Matching xfer_mask, 0 if no match found.

#### <a id="c-ata_xfer_mode2shift"></a>`ata_xfer_mode2shift()`

```c
int ata_xfer_mode2shift(u8 xfer_mode)
```

Find matching xfer_shift for XFER_*

**Parameters**

- `u8 xfer_mode`: XFER_* of interest

**Description**

Return matching xfer_shift for **xfer_mode**.

LOCKING:
None.

**Return**

Matching xfer_shift, -1 if no match found.

#### <a id="c-ata_mode_string"></a>`ata_mode_string()`

```c
const char * ata_mode_string(unsigned int xfer_mask)
```

convert xfer_mask to string

**Parameters**

- `unsigned int xfer_mask`: mask of bits supported; only highest bit counts.

**Description**

Determine string which represents the highest speed
(highest bit in **modemask**).

LOCKING:
None.

**Return**

Constant C string representing highest speed listed in
**mode_mask**, or the constant C string "\<n/a>".

#### <a id="c-ata_dev_classify"></a>`ata_dev_classify()`

```c
unsigned int ata_dev_classify(const struct ata_taskfile *tf)
```

determine device type based on ATA-spec signature

**Parameters**

- `const struct ata_taskfile *tf`: ATA taskfile register set for device to be identified

**Description**

Determine from taskfile register contents whether a device is
ATA or ATAPI, as per "Signature and persistence" section
of ATA/PI spec (volume 1, sect 5.14).

LOCKING:
None.

**Return**

Device type, `ATA_DEV_ATA`, `ATA_DEV_ATAPI`, `ATA_DEV_PMP`,
`ATA_DEV_ZAC`, or `ATA_DEV_UNKNOWN` the event of failure.

#### <a id="c-ata_id_string"></a>`ata_id_string()`

```c
void ata_id_string(const u16 *id, unsigned char *s, unsigned int ofs, unsigned int len)
```

Convert IDENTIFY DEVICE page into string

**Parameters**

- `const u16 *id`: IDENTIFY DEVICE results we will examine
- `unsigned char *s`: string into which data is output
- `unsigned int ofs`: offset into identify device page
- `unsigned int len`: length of string to return. must be an even number.

**Description**

The strings in the IDENTIFY DEVICE page are broken up into
16-bit chunks.  Run through the string, and output each
8-bit chunk linearly, regardless of platform.

LOCKING:
caller.

#### <a id="c-ata_id_c_string"></a>`ata_id_c_string()`

```c
void ata_id_c_string(const u16 *id, unsigned char *s, unsigned int ofs, unsigned int len)
```

Convert IDENTIFY DEVICE page into C string

**Parameters**

- `const u16 *id`: IDENTIFY DEVICE results we will examine
- `unsigned char *s`: string into which data is output
- `unsigned int ofs`: offset into identify device page
- `unsigned int len`: length of string to return. must be an odd number.

**Description**

This function is identical to ata_id_string except that it
trims trailing spaces and terminates the resulting string with
null.  **len** must be actual maximum length (even number) + 1.

LOCKING:
caller.

#### <a id="c-ata_id_xfermask"></a>`ata_id_xfermask()`

```c
unsigned int ata_id_xfermask(const u16 *id)
```

Compute xfermask from the given IDENTIFY data

**Parameters**

- `const u16 *id`: IDENTIFY data to compute xfer mask from

**Description**

Compute the xfermask for this device. This is not as trivial
as it seems if we must consider early devices correctly.

FIXME: pre IDE drive timing (do we care ?).

LOCKING:
None.

**Return**

Computed xfermask

#### <a id="c-ata_pio_need_iordy"></a>`ata_pio_need_iordy()`

```c
unsigned int ata_pio_need_iordy(const struct ata_device *adev)
```

check if iordy needed

**Parameters**

- `const struct ata_device *adev`: ATA device

**Description**

Check if the current speed of the device requires IORDY. Used
by various controllers for chip configuration.

#### <a id="c-ata_do_dev_read_id"></a>`ata_do_dev_read_id()`

```c
unsigned int ata_do_dev_read_id(struct ata_device *dev, struct ata_taskfile *tf, __le16 *id)
```

default ID read method

**Parameters**

- `struct ata_device *dev`: device
- `struct ata_taskfile *tf`: proposed taskfile
- `__le16 *id`: data buffer

**Description**

Issue the identify taskfile and hand back the buffer containing
identify data. For some RAID controllers and for pre ATA devices
this function is wrapped or replaced by the driver

#### <a id="c-ata_cable_40wire"></a>`ata_cable_40wire()`

```c
int ata_cable_40wire(struct ata_port *ap)
```

return 40 wire cable type

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which want to hardwire 40 wire cable
detection.

#### <a id="c-ata_cable_80wire"></a>`ata_cable_80wire()`

```c
int ata_cable_80wire(struct ata_port *ap)
```

return 80 wire cable type

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which want to hardwire 80 wire cable
detection.

#### <a id="c-ata_cable_unknown"></a>`ata_cable_unknown()`

```c
int ata_cable_unknown(struct ata_port *ap)
```

return unknown PATA cable.

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which have no PATA cable detection.

#### <a id="c-ata_cable_ignore"></a>`ata_cable_ignore()`

```c
int ata_cable_ignore(struct ata_port *ap)
```

return ignored PATA cable.

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which don't use cable type to limit
transfer mode.

#### <a id="c-ata_cable_sata"></a>`ata_cable_sata()`

```c
int ata_cable_sata(struct ata_port *ap)
```

return SATA cable type

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which have SATA cables

#### <a id="c-ata_dev_pair"></a>`ata_dev_pair()`

```c
struct ata_device * ata_dev_pair(struct ata_device *adev)
```

return other device on cable

**Parameters**

- `struct ata_device *adev`: device

**Description**

Obtain the other device on the same cable, or if none is
present NULL is returned

#### <a id="c-ata_set_mode"></a>`ata_set_mode()`

```c
int ata_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
```

Program timings and issue SET FEATURES - XFER

**Parameters**

- `struct ata_link *link`: link on which timings will be programmed
- `struct ata_device **r_failed_dev`: out parameter for failed device

**Description**

Standard implementation of the function used to tune and set
ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
`ata_dev_set_mode()` fails, pointer to the failing device is
returned in **r_failed_dev**.

LOCKING:
PCI/etc. bus probe sem.

**Return**

0 on success, negative errno otherwise

#### <a id="c-ata_wait_after_reset"></a>`ata_wait_after_reset()`

```c
int ata_wait_after_reset(struct ata_link *link, unsigned long deadline, int (*check_ready)(struct ata_link *link))
```

wait for link to become ready after reset

**Parameters**

- `struct ata_link *link`: link to be waited on
- `unsigned long deadline`: deadline jiffies for the operation
- `int (*check_ready)(struct ata_link *link)`: callback to check link readiness

**Description**

Wait for **link** to become ready after reset.

LOCKING:
EH context.

**Return**

0 if **link** is ready before **deadline**; otherwise, -errno.

#### <a id="c-ata_std_prereset"></a>`ata_std_prereset()`

```c
int ata_std_prereset(struct ata_link *link, unsigned long deadline)
```

prepare for reset

**Parameters**

- `struct ata_link *link`: ATA link to be reset
- `unsigned long deadline`: deadline jiffies for the operation

**Description**

**link** is about to be reset.  Initialize it.  Failure from
prereset makes libata abort whole reset sequence and give up
that port, so prereset should be best-effort.  It does its
best to prepare for reset sequence but if things go wrong, it
should just whine, not fail.

LOCKING:
Kernel thread context (may sleep)

**Return**

Always 0.

#### <a id="c-ata_std_postreset"></a>`ata_std_postreset()`

```c
void ata_std_postreset(struct ata_link *link, unsigned int *classes)
```

standard postreset callback

**Parameters**

- `struct ata_link *link`: the target ata_link
- `unsigned int *classes`: classes of attached devices

**Description**

This function is invoked after a successful reset.  Note that
the device might have been reset more than once using
different reset methods before postreset is invoked.

LOCKING:
Kernel thread context (may sleep)

#### <a id="c-ata_dev_set_feature"></a>`ata_dev_set_feature()`

```c
unsigned int ata_dev_set_feature(struct ata_device *dev, u8 subcmd, u8 action)
```

Issue SET FEATURES

**Parameters**

- `struct ata_device *dev`: Device to which command will be sent
- `u8 subcmd`: The SET FEATURES subcommand to be sent
- `u8 action`: The sector count represents a subcommand specific action

**Description**

Issue SET FEATURES command to device **dev** on port **ap** with sector count

LOCKING:
PCI/etc. bus probe sem.

**Return**

0 on success, AC_ERR_* mask otherwise.

#### <a id="c-ata_std_qc_defer"></a>`ata_std_qc_defer()`

```c
int ata_std_qc_defer(struct ata_queued_cmd *qc)
```

Check whether a qc needs to be deferred

**Parameters**

- `struct ata_queued_cmd *qc`: ATA command in question

**Description**

Non-NCQ commands cannot run with any other command, NCQ or
not.  As upper layer only knows the queue depth, we are
responsible for maintaining exclusion.  This function checks
whether a new command **qc** can be issued.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

ATA_DEFER_* if deferring is needed, 0 otherwise.

#### <a id="c-ata_qc_complete"></a>`ata_qc_complete()`

```c
void ata_qc_complete(struct ata_queued_cmd *qc)
```

Complete an active ATA command

**Parameters**

- `struct ata_queued_cmd *qc`: Command to complete

**Description**

Indicate to the mid and upper layers that an ATA command has
completed, with either an ok or not-ok status.

Refrain from calling this function multiple times when
successfully completing multiple NCQ commands.
`ata_qc_complete_multiple()` should be used instead, which will
properly update IRQ expect state.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_qc_get_active"></a>`ata_qc_get_active()`

```c
u64 ata_qc_get_active(struct ata_port *ap)
```

get bitmask of active qcs

**Parameters**

- `struct ata_port *ap`: port in question

**Description**

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Bitmask of active qcs

#### <a id="c-ata_link_online"></a>`ata_link_online()`

```c
bool ata_link_online(struct ata_link *link)
```

test whether the given link is online

**Parameters**

- `struct ata_link *link`: ATA link to test

**Description**

Test whether **link** is online.  This is identical to
[`ata_phys_link_online()`](#c-ata_phys_link_online) when there's no slave link.  When
there's a slave link, this function should only be called on
the master link and will return true if any of M/S links is
online.

LOCKING:
None.

**Return**

True if the port online status is available and online.

#### <a id="c-ata_link_offline"></a>`ata_link_offline()`

```c
bool ata_link_offline(struct ata_link *link)
```

test whether the given link is offline

**Parameters**

- `struct ata_link *link`: ATA link to test

**Description**

Test whether **link** is offline.  This is identical to
[`ata_phys_link_offline()`](#c-ata_phys_link_offline) when there's no slave link.  When
there's a slave link, this function should only be called on
the master link and will return true if both M/S links are
offline.

LOCKING:
None.

**Return**

True if the port offline status is available and offline.

#### <a id="c-ata_host_suspend"></a>`ata_host_suspend()`

```c
void ata_host_suspend(struct ata_host *host, pm_message_t mesg)
```

suspend host

**Parameters**

- `struct ata_host *host`: host to suspend
- `pm_message_t mesg`: PM message

**Description**

Suspend **host**.  Actual operation is performed by port suspend.

#### <a id="c-ata_host_resume"></a>`ata_host_resume()`

```c
void ata_host_resume(struct ata_host *host)
```

resume host

**Parameters**

- `struct ata_host *host`: host to resume

**Description**

Resume **host**.  Actual operation is performed by port resume.

#### <a id="c-ata_port_alloc"></a>`ata_port_alloc()`

```c
struct ata_port * ata_port_alloc(struct ata_host *host)
```

allocate and initialize basic ATA port resources

**Parameters**

- `struct ata_host *host`: ATA host this allocated port belongs to

**Description**

Allocate and initialize basic ATA port resources.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

Allocate ATA port on success, NULL on failure.

#### <a id="c-ata_host_alloc"></a>`ata_host_alloc()`

```c
struct ata_host * ata_host_alloc(struct device *dev, int n_ports)
```

allocate and init basic ATA host resources

**Parameters**

- `struct device *dev`: generic device this host is associated with
- `int n_ports`: the number of ATA ports associated with this host

**Description**

Allocate and initialize basic ATA host resources.  LLD calls
this function to allocate a host, initializes it fully and
attaches it using [`ata_host_register()`](#c-ata_host_register).

LOCKING:
Inherited from calling layer (may sleep).

**Return**

Allocate ATA host on success, NULL on failure.

#### <a id="c-ata_host_alloc_pinfo"></a>`ata_host_alloc_pinfo()`

```c
struct ata_host * ata_host_alloc_pinfo(struct device *dev, const struct ata_port_info * const * ppi, int n_ports)
```

alloc host and init with port_info array

**Parameters**

- `struct device *dev`: generic device this host is associated with
- `const struct ata_port_info * const * ppi`: array of ATA port_info to initialize host with
- `int n_ports`: number of ATA ports attached to this host

**Description**

Allocate ATA host and initialize with info from **ppi**.  If NULL
terminated, **ppi** may contain fewer entries than **n_ports**.  The
last entry will be used for the remaining ports.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

Allocate ATA host on success, NULL on failure.

#### <a id="c-ata_host_start"></a>`ata_host_start()`

```c
int ata_host_start(struct ata_host *host)
```

start and freeze ports of an ATA host

**Parameters**

- `struct ata_host *host`: ATA host to start ports for

**Description**

Start and then freeze ports of **host**.  Started status is
recorded in host->flags, so this function can be called
multiple times.  Ports are guaranteed to get started only
once.  If host->ops is not initialized yet, it is set to the
first non-dummy port ops.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

0 if all ports are started successfully, -errno otherwise.

#### <a id="c-ata_host_init"></a>`ata_host_init()`

```c
void ata_host_init(struct ata_host *host, struct device *dev, struct ata_port_operations *ops)
```

Initialize a host struct for sas (ipr, libsas)

**Parameters**

- `struct ata_host *host`: host to initialize
- `struct device *dev`: device host is attached to
- `struct ata_port_operations *ops`: port_ops

#### <a id="c-ata_host_register"></a>`ata_host_register()`

```c
int ata_host_register(struct ata_host *host, const struct scsi_host_template *sht)
```

register initialized ATA host

**Parameters**

- `struct ata_host *host`: ATA host to register
- `const struct scsi_host_template *sht`: template for SCSI host

**Description**

Register initialized ATA host.  **host** is allocated using
[`ata_host_alloc()`](#c-ata_host_alloc) and fully initialized by LLD.  This function
starts ports, registers **host** with ATA and SCSI layers and
probe registered devices.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

0 on success, -errno otherwise.

#### <a id="c-ata_host_activate"></a>`ata_host_activate()`

```c
int ata_host_activate(struct ata_host *host, int irq, irq_handler_t irq_handler, unsigned long irq_flags, const struct scsi_host_template *sht)
```

start host, request IRQ and register it

**Parameters**

- `struct ata_host *host`: target ATA host
- `int irq`: IRQ to request
- `irq_handler_t irq_handler`: irq_handler used when requesting IRQ
- `unsigned long irq_flags`: irq_flags used when requesting IRQ
- `const struct scsi_host_template *sht`: scsi_host_template to use when registering the host

**Description**

After allocating an ATA host and initializing it, most libata
LLDs perform three steps to activate the host - start host,
request IRQ and register it.  This helper takes necessary
arguments and performs the three steps in one go.

An invalid IRQ skips the IRQ registration and expects the host to
have set polling mode on the port. In this case, **irq_handler**
should be NULL.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

0 on success, -errno otherwise.

#### <a id="c-ata_host_detach"></a>`ata_host_detach()`

```c
void ata_host_detach(struct ata_host *host)
```

Detach all ports of an ATA host

**Parameters**

- `struct ata_host *host`: Host to detach

**Description**

Detach all ports of **host**.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_pci_remove_one"></a>`ata_pci_remove_one()`

```c
void ata_pci_remove_one(struct pci_dev *pdev)
```

PCI layer callback for device removal

**Parameters**

- `struct pci_dev *pdev`: PCI device that was removed

**Description**

PCI layer indicates to libata via this hook that hot-unplug or
module unload event has occurred.  Detach all ports.  Resource
release is handled via devres.

LOCKING:
Inherited from PCI layer (may sleep).

#### <a id="c-ata_platform_remove_one"></a>`ata_platform_remove_one()`

```c
void ata_platform_remove_one(struct platform_device *pdev)
```

Platform layer callback for device removal

**Parameters**

- `struct platform_device *pdev`: Platform device that was removed

**Description**

Platform layer indicates to libata via this hook that hot-unplug or
module unload event has occurred.  Detach all ports.  Resource
release is handled via devres.

LOCKING:
Inherited from platform layer (may sleep).

#### <a id="c-ata_msleep"></a>`ata_msleep()`

```c
void ata_msleep(struct ata_port *ap, unsigned int msecs)
```

ATA EH owner aware msleep

**Parameters**

- `struct ata_port *ap`: ATA port to attribute the sleep to
- `unsigned int msecs`: duration to sleep in milliseconds

**Description**

Sleeps **msecs**.  If the current task is owner of **ap**'s EH, the
ownership is released before going to sleep and reacquired
after the sleep is complete.  IOW, other ports sharing the
**ap->host** will be allowed to own the EH while this task is
sleeping.

LOCKING:
Might sleep.

#### <a id="c-ata_wait_register"></a>`ata_wait_register()`

```c
u32 ata_wait_register(struct ata_port *ap, void __iomem *reg, u32 mask, u32 val, unsigned int interval, unsigned int timeout)
```

wait until register value changes

**Parameters**

- `struct ata_port *ap`: ATA port to wait register for, can be NULL
- `void __iomem *reg`: IO-mapped register
- `u32 mask`: Mask to apply to read register value
- `u32 val`: Wait condition
- `unsigned int interval`: polling interval in milliseconds
- `unsigned int timeout`: timeout in milliseconds

**Description**

Waiting for some bits of register to change is a common
operation for ATA controllers.  This function reads 32bit LE
IO-mapped register **reg** and tests for the following condition.

(**\*reg** & mask) != val

If the condition is met, it returns; otherwise, the process is
repeated after **interval_msec** until timeout.

LOCKING:
Kernel thread context (may sleep)

**Return**

The final register value.


<a id="rst-libata-core-internals"></a>

## libata Core Internals


#### <a id="c-ata_dev_phys_link"></a>`ata_dev_phys_link()`

```c
struct ata_link * ata_dev_phys_link(struct ata_device *dev)
```

find physical link for a device

**Parameters**

- `struct ata_device *dev`: ATA device to look up physical link for

**Description**

Look up physical link which **dev** is attached to.  Note that
this is different from **dev->link** only when **dev** is on slave
link.  For all other cases, it's the same as **dev->link**.

LOCKING:
Don't care.

**Return**

Pointer to the found physical link.

#### <a id="c-ata_force_cbl"></a>`ata_force_cbl()`

```c
void ata_force_cbl(struct ata_port *ap)
```

force cable type according to libata.force

**Parameters**

- `struct ata_port *ap`: ATA port of interest

**Description**

Force cable type according to libata.force and whine about it.
The last entry which has matching port number is used, so it
can be specified as part of device force parameters.  For
example, both "a:40c,1.00:udma4" and "1.00:40c,udma4" have the
same effect.

LOCKING:
EH context.

#### <a id="c-ata_force_pflags"></a>`ata_force_pflags()`

```c
void ata_force_pflags(struct ata_port *ap)
```

force port flags according to libata.force

**Parameters**

- `struct ata_port *ap`: ATA port of interest

**Description**

Force port flags according to libata.force and whine about it.

LOCKING:
EH context.

#### <a id="c-ata_force_link_limits"></a>`ata_force_link_limits()`

```c
void ata_force_link_limits(struct ata_link *link)
```

force link limits according to libata.force

**Parameters**

- `struct ata_link *link`: ATA link of interest

**Description**

Force link flags and SATA spd limit according to libata.force
and whine about it.  When only the port part is specified
(e.g. 1:), the limit applies to all links connected to both
the host link and all fan-out ports connected via PMP.  If the
device part is specified as 0 (e.g. 1.00:), it specifies the
first fan-out link not the host link.  Device number 15 always
points to the host link whether PMP is attached or not.  If the
controller has slave link, device number 16 points to it.

LOCKING:
EH context.

#### <a id="c-ata_force_xfermask"></a>`ata_force_xfermask()`

```c
void ata_force_xfermask(struct ata_device *dev)
```

force xfermask according to libata.force

**Parameters**

- `struct ata_device *dev`: ATA device of interest

**Description**

Force xfer_mask according to libata.force and whine about it.
For consistency with link selection, device number 15 selects
the first device connected to the host link.

LOCKING:
EH context.

#### <a id="c-ata_force_quirks"></a>`ata_force_quirks()`

```c
void ata_force_quirks(struct ata_device *dev)
```

force quirks according to libata.force

**Parameters**

- `struct ata_device *dev`: ATA device of interest

**Description**

Force quirks according to libata.force and whine about it.
For consistency with link selection, device number 15 selects
the first device connected to the host link.

LOCKING:
EH context.

#### <a id="c-ata_set_rwcmd_protocol"></a>`ata_set_rwcmd_protocol()`

```c
bool ata_set_rwcmd_protocol(struct ata_device *dev, struct ata_taskfile *tf)
```

set taskfile r/w command and protocol

**Parameters**

- `struct ata_device *dev`: target device for the taskfile
- `struct ata_taskfile *tf`: taskfile to examine and configure

**Description**

Examine the device configuration and tf->flags to determine
the proper read/write command and protocol to use for **tf**.

LOCKING:
caller.

#### <a id="c-ata_tf_read_block"></a>`ata_tf_read_block()`

```c
u64 ata_tf_read_block(const struct ata_taskfile *tf, struct ata_device *dev)
```

Read block address from ATA taskfile

**Parameters**

- `const struct ata_taskfile *tf`: ATA taskfile of interest
- `struct ata_device *dev`: ATA device **tf** belongs to

**Description**

LOCKING:
None.

Read block address from **tf**.  This function can handle all
three address formats - LBA, LBA48 and CHS.  tf->protocol and
flags select the address format to use.

**Return**

Block address read from **tf**.

#### <a id="c-ata_build_rw_tf"></a>`ata_build_rw_tf()`

```c
int ata_build_rw_tf(struct ata_queued_cmd *qc, u64 block, u32 n_block, unsigned int tf_flags, int cdl, int class)
```

Build ATA taskfile for given read/write request

**Parameters**

- `struct ata_queued_cmd *qc`: Metadata associated with the taskfile to build
- `u64 block`: Block address
- `u32 n_block`: Number of blocks
- `unsigned int tf_flags`: RW/FUA etc...
- `int cdl`: Command duration limit index
- `int class`: IO priority class

**Description**

LOCKING:
None.

Build ATA taskfile for the command **qc** for read/write request described
by **block**, **n_block**, **tf_flags** and **class**.

0 on success, -ERANGE if the request is too large for **dev**,
-EINVAL if the request is invalid.

#### <a id="c-ata_unpack_xfermask"></a>`ata_unpack_xfermask()`

```c
void ata_unpack_xfermask(unsigned int xfer_mask, unsigned int *pio_mask, unsigned int *mwdma_mask, unsigned int *udma_mask)
```

Unpack xfer_mask into pio, mwdma and udma masks

**Parameters**

- `unsigned int xfer_mask`: xfer_mask to unpack
- `unsigned int *pio_mask`: resulting pio_mask
- `unsigned int *mwdma_mask`: resulting mwdma_mask
- `unsigned int *udma_mask`: resulting udma_mask

**Description**

Unpack **xfer_mask** into **pio_mask**, **mwdma_mask** and **udma_mask**.
Any NULL destination masks will be ignored.

#### <a id="c-ata_read_native_max_address"></a>`ata_read_native_max_address()`

```c
int ata_read_native_max_address(struct ata_device *dev, u64 *max_sectors)
```

Read native max address

**Parameters**

- `struct ata_device *dev`: target device
- `u64 *max_sectors`: out parameter for the result native max address

**Description**

Perform an LBA48 or LBA28 native size query upon the device in
question.

**Return**

0 on success, -EACCES if command is aborted by the drive.
-EIO on other errors.

#### <a id="c-ata_set_max_sectors"></a>`ata_set_max_sectors()`

```c
int ata_set_max_sectors(struct ata_device *dev, u64 new_sectors)
```

Set max sectors

**Parameters**

- `struct ata_device *dev`: target device
- `u64 new_sectors`: new max sectors value to set for the device

**Description**

Set max sectors of **dev** to **new_sectors**.

**Return**

0 on success, -EACCES if command is aborted or denied (due to
previous non-volatile SET_MAX) by the drive.  -EIO on other
errors.

#### <a id="c-ata_hpa_resize"></a>`ata_hpa_resize()`

```c
int ata_hpa_resize(struct ata_device *dev)
```

Resize a device with an HPA set

**Parameters**

- `struct ata_device *dev`: Device to resize

**Description**

Read the size of an LBA28 or LBA48 disk with HPA features and resize
it if required to the full size of the media. The caller must check
the drive has the HPA feature set enabled.

**Return**

0 on success, -errno on failure.

#### <a id="c-ata_dump_id"></a>`ata_dump_id()`

```c
void ata_dump_id(struct ata_device *dev, const u16 *id)
```

IDENTIFY DEVICE info debugging output

**Parameters**

- `struct ata_device *dev`: device from which the information is fetched
- `const u16 *id`: IDENTIFY DEVICE page to dump

**Description**

Dump selected 16-bit words from the given IDENTIFY DEVICE
page.

LOCKING:
caller.

#### <a id="c-ata_exec_internal"></a>`ata_exec_internal()`

```c
unsigned int ata_exec_internal(struct ata_device *dev, struct ata_taskfile *tf, const u8 *cdb, enum dma_data_direction dma_dir, void *buf, unsigned int buflen, unsigned int timeout)
```

execute libata internal command

**Parameters**

- `struct ata_device *dev`: Device to which the command is sent
- `struct ata_taskfile *tf`: Taskfile registers for the command and the result
- `const u8 *cdb`: CDB for packet command
- `enum dma_data_direction dma_dir`: Data transfer direction of the command
- `void *buf`: Data buffer of the command
- `unsigned int buflen`: Length of data buffer
- `unsigned int timeout`: Timeout in msecs (0 for default)

**Description**

Executes libata internal command with timeout. **tf** contains
the command on entry and the result on return. Timeout and error
conditions are reported via the return value. No recovery action
is taken after a command times out. It is the caller's duty to
clean up after timeout.

LOCKING:
None.  Should be called with kernel context, might sleep.

**Return**

Zero on success, AC_ERR_* mask on failure

#### <a id="c-ata_pio_mask_no_iordy"></a>`ata_pio_mask_no_iordy()`

```c
u32 ata_pio_mask_no_iordy(const struct ata_device *adev)
```

Return the non IORDY mask

**Parameters**

- `const struct ata_device *adev`: ATA device

**Description**

Compute the highest mode possible if we are not using iordy. Return
-1 if no iordy mode is available.

#### <a id="c-ata_dev_read_id"></a>`ata_dev_read_id()`

```c
int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class, unsigned int flags, u16 *id)
```

Read ID data from the specified device

**Parameters**

- `struct ata_device *dev`: target device
- `unsigned int *p_class`: pointer to class of the target device (may be changed)
- `unsigned int flags`: ATA_READID_* flags
- `u16 *id`: buffer to read IDENTIFY data into

**Description**

Read ID data from the specified device.  ATA_CMD_ID_ATA is
performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
for pre-ATA4 drives.

FIXME: ATA_CMD_ID_ATA is optional for early drives and right
now we abort if we hit that case.

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, -errno otherwise.

#### <a id="c-ata_dev_power_set_standby"></a>`ata_dev_power_set_standby()`

```c
void ata_dev_power_set_standby(struct ata_device *dev)
```

Set a device power mode to standby

**Parameters**

- `struct ata_device *dev`: target device

**Description**

Issue a STANDBY IMMEDIATE command to set a device power mode to standby.
For an HDD device, this spins down the disks.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_dev_power_set_active"></a>`ata_dev_power_set_active()`

```c
void ata_dev_power_set_active(struct ata_device *dev)
```

Set a device power mode to active

**Parameters**

- `struct ata_device *dev`: target device

**Description**

Issue a VERIFY command to enter to ensure that the device is in the
active power mode. For a spun-down HDD (standby or idle power mode),
the VERIFY command will complete after the disk spins up.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_read_log_page"></a>`ata_read_log_page()`

```c
unsigned int ata_read_log_page(struct ata_device *dev, u8 log, u8 page, void *buf, unsigned int sectors)
```

read a specific log page

**Parameters**

- `struct ata_device *dev`: target device
- `u8 log`: log to read
- `u8 page`: page to read
- `void *buf`: buffer to store read page
- `unsigned int sectors`: number of sectors to read

**Description**

Read log page using READ_LOG_EXT command.

LOCKING:
Kernel thread context (may sleep).

**Return**

0 on success, AC_ERR_* mask otherwise.

#### <a id="c-ata_dev_configure"></a>`ata_dev_configure()`

```c
int ata_dev_configure(struct ata_device *dev)
```

Configure the specified ATA/ATAPI device

**Parameters**

- `struct ata_device *dev`: Target device to configure

**Description**

Configure **dev** according to **dev->id**.  Generic and low-level
driver specific fixups are also applied.

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, -errno otherwise

#### <a id="c-sata_print_link_status"></a>`sata_print_link_status()`

```c
void sata_print_link_status(struct ata_link *link)
```

Print SATA link status

**Parameters**

- `struct ata_link *link`: SATA link to printk link status about

**Description**

This function prints link speed and status of a SATA link.

LOCKING:
None.

#### <a id="c-ata_timing_cycle2mode"></a>`ata_timing_cycle2mode()`

```c
u8 ata_timing_cycle2mode(unsigned int xfer_shift, int cycle)
```

find xfer mode for the specified cycle duration

**Parameters**

- `unsigned int xfer_shift`: ATA_SHIFT_* value for transfer type to examine.
- `int cycle`: cycle duration in ns

**Description**

Return matching xfer mode for **cycle**.  The returned mode is of
the transfer type specified by **xfer_shift**.  If **cycle** is too
slow for **xfer_shift**, 0xff is returned.  If **cycle** is faster
than the fastest known mode, the fasted mode is returned.

LOCKING:
None.

**Return**

Matching xfer_mode, 0xff if no match found.

#### <a id="c-ata_down_xfermask_limit"></a>`ata_down_xfermask_limit()`

```c
int ata_down_xfermask_limit(struct ata_device *dev, unsigned int sel)
```

adjust dev xfer masks downward

**Parameters**

- `struct ata_device *dev`: Device to adjust xfer masks
- `unsigned int sel`: ATA_DNXFER_* selector

**Description**

Adjust xfer masks of **dev** downward.  Note that this function
does not apply the change.  Invoking [`ata_set_mode()`](#c-ata_set_mode) afterwards
will apply the limit.

LOCKING:
Inherited from caller.

**Return**

0 on success, negative errno on failure

#### <a id="c-ata_wait_ready"></a>`ata_wait_ready()`

```c
int ata_wait_ready(struct ata_link *link, unsigned long deadline, int (*check_ready)(struct ata_link *link))
```

wait for link to become ready

**Parameters**

- `struct ata_link *link`: link to be waited on
- `unsigned long deadline`: deadline jiffies for the operation
- `int (*check_ready)(struct ata_link *link)`: callback to check link readiness

**Description**

Wait for **link** to become ready.  **check_ready** should return
positive number if **link** is ready, 0 if it isn't, -ENODEV if
link doesn't seem to be occupied, other errno for other error
conditions.

Transient -ENODEV conditions are allowed for
ATA_TMOUT_FF_WAIT.

LOCKING:
EH context.

**Return**

0 if **link** is ready before **deadline**; otherwise, -errno.

#### <a id="c-ata_dev_same_device"></a>`ata_dev_same_device()`

```c
int ata_dev_same_device(struct ata_device *dev, unsigned int new_class, const u16 *new_id)
```

Determine whether new ID matches configured device

**Parameters**

- `struct ata_device *dev`: device to compare against
- `unsigned int new_class`: class of the new device
- `const u16 *new_id`: IDENTIFY page of the new device

**Description**

Compare **new_class** and **new_id** against **dev** and determine
whether **dev** is the device indicated by **new_class** and
**new_id**.

LOCKING:
None.

**Return**

1 if **dev** matches **new_class** and **new_id**, 0 otherwise.

#### <a id="c-ata_dev_reread_id"></a>`ata_dev_reread_id()`

```c
int ata_dev_reread_id(struct ata_device *dev, unsigned int readid_flags)
```

Re-read IDENTIFY data

**Parameters**

- `struct ata_device *dev`: target ATA device
- `unsigned int readid_flags`: read ID flags

**Description**

Re-read IDENTIFY page and make sure **dev** is still attached to
the port.

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, negative errno otherwise

#### <a id="c-ata_dev_revalidate"></a>`ata_dev_revalidate()`

```c
int ata_dev_revalidate(struct ata_device *dev, unsigned int new_class, unsigned int readid_flags)
```

Revalidate ATA device

**Parameters**

- `struct ata_device *dev`: device to revalidate
- `unsigned int new_class`: new class code
- `unsigned int readid_flags`: read ID flags

**Description**

Re-read IDENTIFY page, make sure **dev** is still attached to the
port and reconfigure it according to the new IDENTIFY page.

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, negative errno otherwise

#### <a id="c-ata_is_40wire"></a>`ata_is_40wire()`

```c
int ata_is_40wire(struct ata_device *dev)
```

check drive side detection

**Parameters**

- `struct ata_device *dev`: device

**Description**

Perform drive side detection decoding, allowing for device vendors
who can't follow the documentation.

#### <a id="c-cable_is_40wire"></a>`cable_is_40wire()`

```c
int cable_is_40wire(struct ata_port *ap)
```

40/80/SATA decider

**Parameters**

- `struct ata_port *ap`: port to consider

**Description**

This function encapsulates the policy for speed management
in one place. At the moment we don't cache the result but
there is a good case for setting ap->cbl to the result when
we are called with unknown cables (and figuring out if it
impacts hotplug at all).

Return 1 if the cable appears to be 40 wire.

#### <a id="c-ata_dev_xfermask"></a>`ata_dev_xfermask()`

```c
void ata_dev_xfermask(struct ata_device *dev)
```

Compute supported xfermask of the given device

**Parameters**

- `struct ata_device *dev`: Device to compute xfermask for

**Description**

Compute supported xfermask of **dev** and store it in
dev->*_mask.  This function is responsible for applying all
known limits including host controller limits, device quirks, etc...

LOCKING:
None.

#### <a id="c-ata_dev_set_xfermode"></a>`ata_dev_set_xfermode()`

```c
unsigned int ata_dev_set_xfermode(struct ata_device *dev)
```

Issue SET FEATURES - XFER MODE command

**Parameters**

- `struct ata_device *dev`: Device to which command will be sent

**Description**

Issue SET FEATURES - XFER MODE command to device **dev**
on port **ap**.

LOCKING:
PCI/etc. bus probe sem.

**Return**

0 on success, AC_ERR_* mask otherwise.

#### <a id="c-ata_dev_init_params"></a>`ata_dev_init_params()`

```c
unsigned int ata_dev_init_params(struct ata_device *dev, u16 heads, u16 sectors)
```

Issue INIT DEV PARAMS command

**Parameters**

- `struct ata_device *dev`: Device to which command will be sent
- `u16 heads`: Number of heads (taskfile parameter)
- `u16 sectors`: Number of sectors (taskfile parameter)

**Description**

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, AC_ERR_* mask otherwise.

#### <a id="c-atapi_check_dma"></a>`atapi_check_dma()`

```c
int atapi_check_dma(struct ata_queued_cmd *qc)
```

Check whether ATAPI DMA can be supported

**Parameters**

- `struct ata_queued_cmd *qc`: Metadata associated with taskfile to check

**Description**

Allow low-level driver to filter ATA PACKET commands, returning
a status indicating whether or not it is OK to use DMA for the
supplied PACKET command.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

0 when ATAPI DMA can be used
nonzero otherwise

#### <a id="c-ata_sg_init"></a>`ata_sg_init()`

```c
void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg, unsigned int n_elem)
```

Associate command with scatter-gather table.

**Parameters**

- `struct ata_queued_cmd *qc`: Command to be associated
- `struct scatterlist *sg`: Scatter-gather table.
- `unsigned int n_elem`: Number of elements in s/g table.

**Description**

Initialize the data-related elements of queued_cmd **qc**
to point to a scatter-gather table **sg**, containing **n_elem**
elements.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_sg_clean"></a>`ata_sg_clean()`

```c
void ata_sg_clean(struct ata_queued_cmd *qc)
```

Unmap DMA memory associated with command

**Parameters**

- `struct ata_queued_cmd *qc`: Command containing DMA memory to be released

**Description**

Unmap all mapped DMA memory associated with this command.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_sg_setup"></a>`ata_sg_setup()`

```c
int ata_sg_setup(struct ata_queued_cmd *qc)
```

DMA-map the scatter-gather table associated with a command.

**Parameters**

- `struct ata_queued_cmd *qc`: Command with scatter-gather table to be mapped.

**Description**

DMA-map the scatter-gather table associated with queued_cmd **qc**.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, negative on error.

#### <a id="c-swap_buf_le16"></a>`swap_buf_le16()`

```c
void swap_buf_le16(u16 *buf, unsigned int buf_words)
```

swap halves of 16-bit words in place

**Parameters**

- `u16 *buf`: Buffer to swap
- `unsigned int buf_words`: Number of 16-bit words in buffer.

**Description**

Swap halves of 16-bit words if needed to convert from
little-endian byte order to native cpu byte order, or
vice-versa.

LOCKING:
Inherited from caller.

#### <a id="c-ata_qc_free"></a>`ata_qc_free()`

```c
void ata_qc_free(struct ata_queued_cmd *qc)
```

free unused ata_queued_cmd

**Parameters**

- `struct ata_queued_cmd *qc`: Command to complete

**Description**

Designed to free unused ata_queued_cmd object
in case something prevents using it.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_qc_issue"></a>`ata_qc_issue()`

```c
void ata_qc_issue(struct ata_queued_cmd *qc)
```

issue taskfile to device

**Parameters**

- `struct ata_queued_cmd *qc`: command to issue to device

**Description**

Prepare an ATA command to submission to device.
This includes mapping the data into a DMA-able
area, filling in the S/G table, and finally
writing the taskfile to hardware, starting the command.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_phys_link_online"></a>`ata_phys_link_online()`

```c
bool ata_phys_link_online(struct ata_link *link)
```

test whether the given link is online

**Parameters**

- `struct ata_link *link`: ATA link to test

**Description**

Test whether **link** is online.  Note that this function returns
0 if online status of **link** cannot be obtained, so
ata_link_online(link) != !ata_link_offline(link).

LOCKING:
None.

**Return**

True if the port online status is available and online.

#### <a id="c-ata_phys_link_offline"></a>`ata_phys_link_offline()`

```c
bool ata_phys_link_offline(struct ata_link *link)
```

test whether the given link is offline

**Parameters**

- `struct ata_link *link`: ATA link to test

**Description**

Test whether **link** is offline.  Note that this function
returns 0 if offline status of **link** cannot be obtained, so
ata_link_online(link) != !ata_link_offline(link).

LOCKING:
None.

**Return**

True if the port offline status is available and offline.

#### <a id="c-ata_dev_init"></a>`ata_dev_init()`

```c
void ata_dev_init(struct ata_device *dev)
```

Initialize an ata_device structure

**Parameters**

- `struct ata_device *dev`: Device structure to initialize

**Description**

Initialize **dev** in preparation for probing.

LOCKING:
Inherited from caller.

#### <a id="c-ata_link_init"></a>`ata_link_init()`

```c
void ata_link_init(struct ata_port *ap, struct ata_link *link, int pmp)
```

Initialize an ata_link structure

**Parameters**

- `struct ata_port *ap`: ATA port link is attached to
- `struct ata_link *link`: Link structure to initialize
- `int pmp`: Port multiplier port number

**Description**

Initialize **link**.

LOCKING:
Kernel thread context (may sleep)

#### <a id="c-sata_link_init_spd"></a>`sata_link_init_spd()`

```c
int sata_link_init_spd(struct ata_link *link)
```

Initialize link->sata_spd_limit

**Parameters**

- `struct ata_link *link`: Link to configure sata_spd_limit for

**Description**

Initialize `link->[hw_]sata_spd_limit` to the currently
configured value.

LOCKING:
Kernel thread context (may sleep).

**Return**

0 on success, -errno on failure.

#### <a id="c-ata_finalize_port_ops"></a>`ata_finalize_port_ops()`

```c
void ata_finalize_port_ops(struct ata_port_operations *ops)
```

finalize ata_port_operations

**Parameters**

- `struct ata_port_operations *ops`: ata_port_operations to finalize

**Description**

An ata_port_operations can inherit from another ops and that
ops can again inherit from another.  This can go on as many
times as necessary as long as there is no loop in the
inheritance chain.

Ops tables are finalized when the host is started.  NULL or
unspecified entries are inherited from the closet ancestor
which has the method and the entry is populated with it.
After finalization, the ops table directly points to all the
methods and ->inherits is no longer necessary and cleared.

Using ATA_OP_NULL, inheriting ops can force a method to NULL.

LOCKING:
None.

#### <a id="c-ata_dev_free_resources"></a>`ata_dev_free_resources()`

```c
void ata_dev_free_resources(struct ata_device *dev)
```

Free a device resources

**Parameters**

- `struct ata_device *dev`: Target ATA device

**Description**

Free resources allocated to support a device features.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_port_detach"></a>`ata_port_detach()`

```c
void ata_port_detach(struct ata_port *ap)
```

Detach ATA port in preparation of device removal

**Parameters**

- `struct ata_port *ap`: ATA port to be detached

**Description**

Detach all ATA devices and the associated SCSI devices of **ap**;
then, remove the associated SCSI host.  **ap** is guaranteed to
be quiescent on return from this function.

LOCKING:
Kernel thread context (may sleep).



#### <a id="c-__ata_ehi_push_desc"></a>`__ata_ehi_push_desc()`

```c
void __ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
```

push error description without adding separator

**Parameters**

- `struct ata_eh_info *ehi`: target EHI
- `const char *fmt`: printf format string
- `...`: variable arguments

**Description**

Format string according to **fmt** and append it to **ehi->desc**.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_ehi_push_desc"></a>`ata_ehi_push_desc()`

```c
void ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
```

push error description with separator

**Parameters**

- `struct ata_eh_info *ehi`: target EHI
- `const char *fmt`: printf format string
- `...`: variable arguments

**Description**

Format string according to **fmt** and append it to **ehi->desc**.
If **ehi->desc** is not empty, ", " is added in-between.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_ehi_clear_desc"></a>`ata_ehi_clear_desc()`

```c
void ata_ehi_clear_desc(struct ata_eh_info *ehi)
```

clean error description

**Parameters**

- `struct ata_eh_info *ehi`: target EHI

**Description**

Clear **ehi->desc**.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_port_desc"></a>`ata_port_desc()`

```c
void ata_port_desc(struct ata_port *ap, const char *fmt, ...)
```

append port description

**Parameters**

- `struct ata_port *ap`: target ATA port
- `const char *fmt`: printf format string
- `...`: variable arguments

**Description**

Format string according to **fmt** and append it to port
description.  If port description is not empty, " " is added
in-between.  This function is to be used while initializing
ata_host.  The description is printed on host registration.

LOCKING:
None.

#### <a id="c-ata_port_pbar_desc"></a>`ata_port_pbar_desc()`

```c
void ata_port_pbar_desc(struct ata_port *ap, int bar, ssize_t offset, const char *name)
```

append PCI BAR description

**Parameters**

- `struct ata_port *ap`: target ATA port
- `int bar`: target PCI BAR
- `ssize_t offset`: offset into PCI BAR
- `const char *name`: name of the area

**Description**

If **offset** is negative, this function formats a string which
contains the name, address, size and type of the BAR and
appends it to the port description.  If **offset** is zero or
positive, only name and offsetted address is appended.

LOCKING:
None.

#### <a id="c-ata_internal_cmd_timeout"></a>`ata_internal_cmd_timeout()`

```c
unsigned int ata_internal_cmd_timeout(struct ata_device *dev, u8 cmd)
```

determine timeout for an internal command

**Parameters**

- `struct ata_device *dev`: target device
- `u8 cmd`: internal command to be issued

**Description**

Determine timeout for internal command **cmd** for **dev**.

LOCKING:
EH context.

**Return**

Determined timeout.

#### <a id="c-ata_internal_cmd_timed_out"></a>`ata_internal_cmd_timed_out()`

```c
void ata_internal_cmd_timed_out(struct ata_device *dev, u8 cmd)
```

notification for internal command timeout

**Parameters**

- `struct ata_device *dev`: target device
- `u8 cmd`: internal command which timed out

**Description**

Notify EH that internal command **cmd** for **dev** timed out.  This
function should be called only for commands whose timeouts are
determined using [`ata_internal_cmd_timeout()`](#c-ata_internal_cmd_timeout).

LOCKING:
EH context.

#### <a id="c-ata_eh_acquire"></a>`ata_eh_acquire()`

```c
void ata_eh_acquire(struct ata_port *ap)
```

acquire EH ownership

**Parameters**

- `struct ata_port *ap`: ATA port to acquire EH ownership for

**Description**

Acquire EH ownership for **ap**.  This is the basic exclusion
mechanism for ports sharing a host.  Only one port hanging off
the same host can claim the ownership of EH.

LOCKING:
EH context.

#### <a id="c-ata_eh_release"></a>`ata_eh_release()`

```c
void ata_eh_release(struct ata_port *ap)
```

release EH ownership

**Parameters**

- `struct ata_port *ap`: ATA port to release EH ownership for

**Description**

Release EH ownership for **ap** if the caller.  The caller must
have acquired EH ownership using [`ata_eh_acquire()`](#c-ata_eh_acquire) previously.

LOCKING:
EH context.

#### <a id="c-ata_scsi_error"></a>`ata_scsi_error()`

```c
void ata_scsi_error(struct Scsi_Host *host)
```

SCSI layer error handler callback

**Parameters**

- `struct Scsi_Host *host`: SCSI host on which error occurred

**Description**

Handles SCSI-layer-thrown error events.

LOCKING:
Inherited from SCSI layer (none, can sleep)

**Return**

Zero.

#### <a id="c-ata_scsi_cmd_error_handler"></a>`ata_scsi_cmd_error_handler()`

```c
void ata_scsi_cmd_error_handler(struct Scsi_Host *host, struct ata_port *ap, struct list_head *eh_work_q)
```

error callback for a list of commands

**Parameters**

- `struct Scsi_Host *host`: scsi host containing the port
- `struct ata_port *ap`: ATA port within the host
- `struct list_head *eh_work_q`: list of commands to process

**Description**

process the given list of commands and return those finished to the
ap->eh_done_q.  This function is the first part of the libata error
handler which processes a given list of failed commands.

#### <a id="c-ata_scsi_port_error_handler"></a>`ata_scsi_port_error_handler()`

```c
void ata_scsi_port_error_handler(struct Scsi_Host *host, struct ata_port *ap)
```

recover the port after the commands

**Parameters**

- `struct Scsi_Host *host`: SCSI host containing the port
- `struct ata_port *ap`: the ATA port

**Description**

Handle the recovery of the port **ap** after all the commands
have been recovered.

#### <a id="c-ata_port_wait_eh"></a>`ata_port_wait_eh()`

```c
void ata_port_wait_eh(struct ata_port *ap)
```

Wait for the currently pending EH to complete

**Parameters**

- `struct ata_port *ap`: Port to wait EH for

**Description**

Wait until the currently pending EH is complete.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_eh_set_pending"></a>`ata_eh_set_pending()`

```c
void ata_eh_set_pending(struct ata_port *ap, bool fastdrain)
```

set ATA_PFLAG_EH_PENDING and activate fast drain

**Parameters**

- `struct ata_port *ap`: target ATA port
- `bool fastdrain`: activate fast drain

**Description**

Set ATA_PFLAG_EH_PENDING and activate fast drain if **fastdrain**
is non-zero and EH wasn't pending before.  Fast drain ensures
that EH kicks in in timely manner.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_qc_schedule_eh"></a>`ata_qc_schedule_eh()`

```c
void ata_qc_schedule_eh(struct ata_queued_cmd *qc)
```

schedule qc for error handling

**Parameters**

- `struct ata_queued_cmd *qc`: command to schedule error handling for

**Description**

Schedule error handling for **qc**.  EH will kick in as soon as
other commands are drained.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_std_sched_eh"></a>`ata_std_sched_eh()`

```c
void ata_std_sched_eh(struct ata_port *ap)
```

non-libsas ata_ports issue eh with this common routine

**Parameters**

- `struct ata_port *ap`: ATA port to schedule EH for

**Description**

LOCKING: inherited from ata_port_schedule_eh
spin_lock_irqsave(host lock)

#### <a id="c-ata_std_end_eh"></a>`ata_std_end_eh()`

```c
void ata_std_end_eh(struct ata_port *ap)
```

non-libsas ata_ports complete eh with this common routine

**Parameters**

- `struct ata_port *ap`: ATA port to end EH for

**Description**

In the libata object model there is a 1:1 mapping of ata_port to
shost, so host fields can be directly manipulated under ap->lock, in
the libsas case we need to hold a lock at the ha->level to coordinate
these events.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_port_schedule_eh"></a>`ata_port_schedule_eh()`

```c
void ata_port_schedule_eh(struct ata_port *ap)
```

schedule error handling without a qc

**Parameters**

- `struct ata_port *ap`: ATA port to schedule EH for

**Description**

Schedule error handling for **ap**.  EH will kick in as soon as
all commands are drained.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_link_abort"></a>`ata_link_abort()`

```c
int ata_link_abort(struct ata_link *link)
```

abort all qc's on the link

**Parameters**

- `struct ata_link *link`: ATA link to abort qc's for

**Description**

Abort all active qc's active on **link** and schedule EH.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Number of aborted qc's.

#### <a id="c-ata_port_abort"></a>`ata_port_abort()`

```c
int ata_port_abort(struct ata_port *ap)
```

abort all qc's on the port

**Parameters**

- `struct ata_port *ap`: ATA port to abort qc's for

**Description**

Abort all active qc's of **ap** and schedule EH.

LOCKING:
spin_lock_irqsave(host_set lock)

**Return**

Number of aborted qc's.

#### <a id="c-__ata_port_freeze"></a>`__ata_port_freeze()`

```c
void __ata_port_freeze(struct ata_port *ap)
```

freeze port

**Parameters**

- `struct ata_port *ap`: ATA port to freeze

**Description**

This function is called when HSM violation or some other
condition disrupts normal operation of the port.  Frozen port
is not allowed to perform any operation until the port is
thawed, which usually follows a successful reset.

ap->ops->`freeze()` callback can be used for freezing the port
hardware-wise (e.g. mask interrupt and stop DMA engine).  If a
port cannot be frozen hardware-wise, the interrupt handler
must ack and clear interrupts unconditionally while the port
is frozen.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_port_freeze"></a>`ata_port_freeze()`

```c
int ata_port_freeze(struct ata_port *ap)
```

abort & freeze port

**Parameters**

- `struct ata_port *ap`: ATA port to freeze

**Description**

Abort and freeze **ap**.  The freeze operation must be called
first, because some hardware requires special operations
before the taskfile registers are accessible.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Number of aborted commands.

#### <a id="c-ata_eh_freeze_port"></a>`ata_eh_freeze_port()`

```c
void ata_eh_freeze_port(struct ata_port *ap)
```

EH helper to freeze port

**Parameters**

- `struct ata_port *ap`: ATA port to freeze

**Description**

Freeze **ap**.

LOCKING:
None.

#### <a id="c-ata_eh_thaw_port"></a>`ata_eh_thaw_port()`

```c
void ata_eh_thaw_port(struct ata_port *ap)
```

EH helper to thaw port

**Parameters**

- `struct ata_port *ap`: ATA port to thaw

**Description**

Thaw frozen port **ap**.

LOCKING:
None.

#### <a id="c-ata_eh_qc_complete"></a>`ata_eh_qc_complete()`

```c
void ata_eh_qc_complete(struct ata_queued_cmd *qc)
```

Complete an active ATA command from EH

**Parameters**

- `struct ata_queued_cmd *qc`: Command to complete

**Description**

Indicate to the mid and upper layers that an ATA command has
completed.  To be used from EH.

#### <a id="c-ata_eh_qc_retry"></a>`ata_eh_qc_retry()`

```c
void ata_eh_qc_retry(struct ata_queued_cmd *qc)
```

Tell midlayer to retry an ATA command after EH

**Parameters**

- `struct ata_queued_cmd *qc`: Command to retry

**Description**

Indicate to the mid and upper layers that an ATA command
should be retried.  To be used from EH.

SCSI midlayer limits the number of retries to scmd->allowed.
scmd->allowed is incremented for commands which get retried
due to unrelated failures (qc->err_mask is zero).

#### <a id="c-ata_dev_disable"></a>`ata_dev_disable()`

```c
void ata_dev_disable(struct ata_device *dev)
```

disable ATA device

**Parameters**

- `struct ata_device *dev`: ATA device to disable

**Description**

Disable **dev**.

Locking:
EH context.

#### <a id="c-ata_eh_detach_dev"></a>`ata_eh_detach_dev()`

```c
void ata_eh_detach_dev(struct ata_device *dev)
```

detach ATA device

**Parameters**

- `struct ata_device *dev`: ATA device to detach

**Description**

Detach **dev**.

LOCKING:
None.

#### <a id="c-ata_eh_about_to_do"></a>`ata_eh_about_to_do()`

```c
void ata_eh_about_to_do(struct ata_link *link, struct ata_device *dev, unsigned int action)
```

about to perform eh_action

**Parameters**

- `struct ata_link *link`: target ATA link
- `struct ata_device *dev`: target ATA dev for per-dev action (can be NULL)
- `unsigned int action`: action about to be performed

**Description**

Called just before performing EH actions to clear related bits
in **link->eh_info** such that eh actions are not unnecessarily
repeated.

LOCKING:
None.

#### <a id="c-ata_eh_done"></a>`ata_eh_done()`

```c
void ata_eh_done(struct ata_link *link, struct ata_device *dev, unsigned int action)
```

EH action complete

**Parameters**

- `struct ata_link *link`: ATA link for which EH actions are complete
- `struct ata_device *dev`: target ATA dev for per-dev action (can be NULL)
- `unsigned int action`: action just completed

**Description**

Called right after performing EH actions to clear related bits
in **link->eh_context**.

LOCKING:
None.

#### <a id="c-ata_err_string"></a>`ata_err_string()`

```c
const char * ata_err_string(unsigned int err_mask)
```

convert err_mask to descriptive string

**Parameters**

- `unsigned int err_mask`: error mask to convert to string

**Description**

Convert **err_mask** to descriptive string.  Errors are
prioritized according to severity and only the most severe
error is reported.

LOCKING:
None.

**Return**

Descriptive string for **err_mask**

#### <a id="c-atapi_eh_tur"></a>`atapi_eh_tur()`

```c
unsigned int atapi_eh_tur(struct ata_device *dev, u8 *r_sense_key)
```

perform ATAPI TEST_UNIT_READY

**Parameters**

- `struct ata_device *dev`: target ATAPI device
- `u8 *r_sense_key`: out parameter for sense_key

**Description**

Perform ATAPI TEST_UNIT_READY.

LOCKING:
EH context (may sleep).

**Return**

0 on success, AC_ERR_* mask on failure.

#### <a id="c-ata_eh_decide_disposition"></a>`ata_eh_decide_disposition()`

```c
enum scsi_disposition ata_eh_decide_disposition(struct ata_queued_cmd *qc)
```

Disposition a qc based on sense data

**Parameters**

- `struct ata_queued_cmd *qc`: qc to examine

**Description**

For a regular SCSI command, the SCSI completion callback (`scsi_done()`)
will call `scsi_complete()`, which will call `scsi_decide_disposition()`,
which will call [`scsi_check_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_check_sense). `scsi_complete()` finally calls
`scsi_finish_command()`. This is fine for SCSI, since any eventual sense
data is usually returned in the completion itself (without invoking SCSI
EH). However, for a QC, we always need to fetch the sense data
explicitly using SCSI EH.

A command that is completed via SCSI EH will instead be completed using
[`scsi_eh_flush_done_q()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_eh_flush_done_q), which will call `scsi_finish_command()` directly
(without ever calling [`scsi_check_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_check_sense)).

For a command that went through SCSI EH, it is the responsibility of the
SCSI EH strategy handler to call `scsi_decide_disposition()`, see e.g. how
[`scsi_eh_get_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_eh_get_sense) calls `scsi_decide_disposition()` for SCSI LLDDs that
do not get the sense data as part of the completion.

Thus, for QC commands that went via SCSI EH, we need to call
[`scsi_check_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_check_sense) ourselves, similar to how [`scsi_eh_get_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_eh_get_sense) calls
`scsi_decide_disposition()`, which calls [`scsi_check_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_check_sense), in order to
set the correct SCSI ML byte (if any).

LOCKING:
EH context.

**Return**

SUCCESS or FAILED or NEEDS_RETRY or ADD_TO_MLQUEUE

#### <a id="c-ata_eh_request_sense"></a>`ata_eh_request_sense()`

```c
bool ata_eh_request_sense(struct ata_queued_cmd *qc)
```

perform REQUEST_SENSE_DATA_EXT

**Parameters**

- `struct ata_queued_cmd *qc`: qc to perform REQUEST_SENSE_SENSE_DATA_EXT to

**Description**

Perform REQUEST_SENSE_DATA_EXT after the device reported CHECK
SENSE.  This function is an EH helper.

LOCKING:
Kernel thread context (may sleep).

**Return**

true if sense data could be fetched, false otherwise.

#### <a id="c-atapi_eh_request_sense"></a>`atapi_eh_request_sense()`

```c
unsigned int atapi_eh_request_sense(struct ata_device *dev, u8 *sense_buf, u8 dfl_sense_key)
```

perform ATAPI REQUEST_SENSE

**Parameters**

- `struct ata_device *dev`: device to perform REQUEST_SENSE to
- `u8 *sense_buf`: result sense data buffer (SCSI_SENSE_BUFFERSIZE bytes long)
- `u8 dfl_sense_key`: default sense key to use

**Description**

Perform ATAPI REQUEST_SENSE after the device reported CHECK
SENSE.  This function is EH helper.

LOCKING:
Kernel thread context (may sleep).

**Return**

0 on success, AC_ERR_* mask on failure

#### <a id="c-ata_eh_analyze_serror"></a>`ata_eh_analyze_serror()`

```c
void ata_eh_analyze_serror(struct ata_link *link)
```

analyze SError for a failed port

**Parameters**

- `struct ata_link *link`: ATA link to analyze SError for

**Description**

Analyze SError if available and further determine cause of
failure.

LOCKING:
None.

#### <a id="c-ata_eh_analyze_tf"></a>`ata_eh_analyze_tf()`

```c
unsigned int ata_eh_analyze_tf(struct ata_queued_cmd *qc)
```

analyze taskfile of a failed qc

**Parameters**

- `struct ata_queued_cmd *qc`: qc to analyze

**Description**

Analyze taskfile of **qc** and further determine cause of
failure.  This function also requests ATAPI sense data if
available.

LOCKING:
Kernel thread context (may sleep).

**Return**

Determined recovery action

#### <a id="c-ata_eh_speed_down_verdict"></a>`ata_eh_speed_down_verdict()`

```c
unsigned int ata_eh_speed_down_verdict(struct ata_device *dev)
```

Determine speed down verdict

**Parameters**

- `struct ata_device *dev`: Device of interest

**Description**

This function examines error ring of **dev** and determines
whether NCQ needs to be turned off, transfer speed should be
stepped down, or falling back to PIO is necessary.

ECAT_ATA_BUS    : ATA_BUS error for any command

- ECAT_TOUT_HSM   : TIMEOUT for any command or HSM violation for

  IO commands

ECAT_UNK_DEV    : Unknown DEV error for IO commands

- ECAT_DUBIOUS_*  : Identical to above three but occurred while

  data transfer hasn't been verified.

Verdicts are

NCQ_OFF         : Turn off NCQ.

- SPEED_DOWN      : Speed down transfer speed but don't fall back

  to PIO.

FALLBACK_TO_PIO : Fall back to PIO.

Even if multiple verdicts are returned, only one action is
taken per error.  An action triggered by non-DUBIOUS errors
clears ering, while one triggered by DUBIOUS_* errors doesn't.
This is to expedite speed down decisions right after device is
initially configured.

The following are speed down rules.  #1 and #2 deal with
DUBIOUS errors.

1. If more than one DUBIOUS_ATA_BUS or DUBIOUS_TOUT_HSM errors
   occurred during last 5 mins, SPEED_DOWN and FALLBACK_TO_PIO.

2. If more than one DUBIOUS_TOUT_HSM or DUBIOUS_UNK_DEV errors
   occurred during last 5 mins, NCQ_OFF.

3. If more than 8 ATA_BUS, TOUT_HSM or UNK_DEV errors
   occurred during last 5 mins, FALLBACK_TO_PIO

4. If more than 3 TOUT_HSM or UNK_DEV errors occurred
   during last 10 mins, NCQ_OFF.

5. If more than 3 ATA_BUS or TOUT_HSM errors, or more than 6
   UNK_DEV errors occurred during last 10 mins, SPEED_DOWN.

LOCKING:
Inherited from caller.

**Return**

OR of ATA_EH_SPDN_* flags.

#### <a id="c-ata_eh_speed_down"></a>`ata_eh_speed_down()`

```c
unsigned int ata_eh_speed_down(struct ata_device *dev, unsigned int eflags, unsigned int err_mask)
```

record error and speed down if necessary

**Parameters**

- `struct ata_device *dev`: Failed device
- `unsigned int eflags`: mask of ATA_EFLAG_* flags
- `unsigned int err_mask`: err_mask of the error

**Description**

Record error and examine error history to determine whether
adjusting transmission speed is necessary.  It also sets
transmission limits appropriately if such adjustment is
necessary.

LOCKING:
Kernel thread context (may sleep).

**Return**

Determined recovery action.

#### <a id="c-ata_eh_worth_retry"></a>`ata_eh_worth_retry()`

```c
int ata_eh_worth_retry(struct ata_queued_cmd *qc)
```

analyze error and decide whether to retry

**Parameters**

- `struct ata_queued_cmd *qc`: qc to possibly retry

**Description**

Look at the cause of the error and decide if a retry
might be useful or not.  We don't want to retry media errors
because the drive itself has probably already taken 10-30 seconds
doing its own internal retries before reporting the failure.

#### <a id="c-ata_eh_quiet"></a>`ata_eh_quiet()`

```c
bool ata_eh_quiet(struct ata_queued_cmd *qc)
```

check if we need to be quiet about a command error

**Parameters**

- `struct ata_queued_cmd *qc`: qc to check

**Description**

Look at the qc flags anbd its scsi command request flags to determine
if we need to be quiet about the command failure.

#### <a id="c-ata_eh_link_set_lpm"></a>`ata_eh_link_set_lpm()`

```c
int ata_eh_link_set_lpm(struct ata_link *link, enum ata_lpm_policy policy, struct ata_device **r_failed_dev)
```

configure SATA interface power management

**Parameters**

- `struct ata_link *link`: link to configure
- `enum ata_lpm_policy policy`: the link power management policy
- `struct ata_device **r_failed_dev`: out parameter for failed device

**Description**

Enable SATA Interface power management.  This will enable
Device Interface Power Management (DIPM) for min_power and
medium_power_with_dipm policies, and then call driver specific
callbacks for enabling Host Initiated Power management.

LOCKING:
EH context.

**Return**

0 on success, -errno on failure.

#### <a id="c-ata_eh_link_autopsy"></a>`ata_eh_link_autopsy()`

```c
void ata_eh_link_autopsy(struct ata_link *link)
```

analyze error and determine recovery action

**Parameters**

- `struct ata_link *link`: host link to perform autopsy on

**Description**

Analyze why **link** failed and determine which recovery actions
are needed.  This function also sets more detailed AC_ERR_*
values and fills sense data for ATAPI CHECK SENSE.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_eh_autopsy"></a>`ata_eh_autopsy()`

```c
void ata_eh_autopsy(struct ata_port *ap)
```

analyze error and determine recovery action

**Parameters**

- `struct ata_port *ap`: host port to perform autopsy on

**Description**

Analyze all links of **ap** and determine why they failed and
which recovery actions are needed.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_get_cmd_name"></a>`ata_get_cmd_name()`

```c
const char * ata_get_cmd_name(u8 command)
```

get name for ATA command

**Parameters**

- `u8 command`: ATA command code to get name for

**Description**

Return a textual name of the given command or "unknown"

LOCKING:
None

#### <a id="c-ata_eh_link_report"></a>`ata_eh_link_report()`

```c
void ata_eh_link_report(struct ata_link *link)
```

report error handling to user

**Parameters**

- `struct ata_link *link`: ATA link EH is going on

**Description**

Report EH to user.

LOCKING:
None.

#### <a id="c-ata_eh_report"></a>`ata_eh_report()`

```c
void ata_eh_report(struct ata_port *ap)
```

report error handling to user

**Parameters**

- `struct ata_port *ap`: ATA port to report EH about

**Description**

Report EH to user.

LOCKING:
None.

#### <a id="c-ata_eh_set_mode"></a>`ata_eh_set_mode()`

```c
int ata_eh_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
```

Program timings and issue SET FEATURES - XFER

**Parameters**

- `struct ata_link *link`: link on which timings will be programmed
- `struct ata_device **r_failed_dev`: out parameter for failed device

**Description**

Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
[`ata_eh_set_mode()`](#c-ata_eh_set_mode) fails, pointer to the failing device is
returned in **r_failed_dev**.

LOCKING:
PCI/etc. bus probe sem.

**Return**

0 on success, negative errno otherwise

#### <a id="c-atapi_eh_clear_ua"></a>`atapi_eh_clear_ua()`

```c
int atapi_eh_clear_ua(struct ata_device *dev)
```

Clear ATAPI UNIT ATTENTION after reset

**Parameters**

- `struct ata_device *dev`: ATAPI device to clear UA for

**Description**

Resets and other operations can make an ATAPI device raise
UNIT ATTENTION which causes the next operation to fail.  This
function clears UA.

LOCKING:
EH context (may sleep).

**Return**

0 on success, -errno on failure.

#### <a id="c-ata_eh_maybe_retry_flush"></a>`ata_eh_maybe_retry_flush()`

```c
int ata_eh_maybe_retry_flush(struct ata_device *dev)
```

Retry FLUSH if necessary

**Parameters**

- `struct ata_device *dev`: ATA device which may need FLUSH retry

**Description**

If **dev** failed FLUSH, it needs to be reported upper layer
immediately as it means that **dev** failed to remap and already
lost at least a sector and further FLUSH retrials won't make
any difference to the lost sector.  However, if FLUSH failed
for other reasons, for example transmission error, FLUSH needs
to be retried.

This function determines whether FLUSH failure retry is
necessary and performs it if so.

**Return**

0 if EH can continue, -errno if EH needs to be repeated.

#### <a id="c-ata_eh_recover"></a>`ata_eh_recover()`

```c
int ata_eh_recover(struct ata_port *ap, struct ata_reset_operations *reset_ops, struct ata_link **r_failed_link)
```

recover host port after error

**Parameters**

- `struct ata_port *ap`: host port to recover
- `struct ata_reset_operations *reset_ops`: The set of reset operations to use
- `struct ata_link **r_failed_link`: out parameter for failed link

**Description**

This is the alpha and omega, eum and yang, heart and soul of
libata exception handling.  On entry, actions required to
recover each link and hotplug requests are recorded in the
link's eh_context.  This function executes all the operations
with appropriate retrials and fallbacks to resurrect failed
devices, detach goners and greet newcomers.

LOCKING:
Kernel thread context (may sleep).

**Return**

0 on success, -errno on failure.

#### <a id="c-ata_eh_finish"></a>`ata_eh_finish()`

```c
void ata_eh_finish(struct ata_port *ap)
```

finish up EH

**Parameters**

- `struct ata_port *ap`: host port to finish EH for

**Description**

Recovery is complete.  Clean up EH states and retry or finish
failed qcs.

LOCKING:
None.

#### <a id="c-ata_std_error_handler"></a>`ata_std_error_handler()`

```c
void ata_std_error_handler(struct ata_port *ap)
```

standard error handler

**Parameters**

- `struct ata_port *ap`: host port to handle error for

**Description**

Perform standard error handling sequence.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_eh_handle_port_suspend"></a>`ata_eh_handle_port_suspend()`

```c
void ata_eh_handle_port_suspend(struct ata_port *ap)
```

perform port suspend operation

**Parameters**

- `struct ata_port *ap`: port to suspend

**Description**

Suspend **ap**.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_eh_handle_port_resume"></a>`ata_eh_handle_port_resume()`

```c
void ata_eh_handle_port_resume(struct ata_port *ap)
```

perform port resume operation

**Parameters**

- `struct ata_port *ap`: port to resume

**Description**

Resume **ap**.

LOCKING:
Kernel thread context (may sleep).


<a id="rst-libata-scsi-translation-emulation"></a>

## libata SCSI translation/emulation


#### <a id="c-ata_std_bios_param"></a>`ata_std_bios_param()`

```c
int ata_std_bios_param(struct scsi_device *sdev, struct gendisk *unused, sector_t capacity, int geom[])
```

generic bios head/sector/cylinder calculator used by sd.

**Parameters**

- `struct scsi_device *sdev`: SCSI device for which BIOS geometry is to be determined
- `struct gendisk *unused`: gendisk associated with **sdev**
- `sector_t capacity`: capacity of SCSI device
- `int geom[]`: location to which geometry will be output

**Description**

Generic bios head/sector/cylinder calculator
used by sd. Most BIOSes nowadays expect a XXX/255/16  (CHS)
mapping. Some situations may arise where the disk is not
bootable if this is not used.

LOCKING:
Defined by the SCSI layer.  We don't really care.

**Return**

Zero.

#### <a id="c-ata_scsi_unlock_native_capacity"></a>`ata_scsi_unlock_native_capacity()`

```c
void ata_scsi_unlock_native_capacity(struct scsi_device *sdev)
```

unlock native capacity

**Parameters**

- `struct scsi_device *sdev`: SCSI device to adjust device capacity for

**Description**

This function is called if a partition on **sdev** extends beyond
the end of the device.  It requests EH to unlock HPA.

LOCKING:
Defined by the SCSI layer.  Might sleep.

#### <a id="c-ata_scsi_dma_need_drain"></a>`ata_scsi_dma_need_drain()`

```c
bool ata_scsi_dma_need_drain(struct request *rq)
```

Check whether data transfer may overflow

**Parameters**

- `struct request *rq`: request to be checked

**Description**

ATAPI commands which transfer variable length data to host
might overflow due to application error or hardware bug.  This
function checks whether overflow should be drained and ignored
for **request**.

LOCKING:
None.

**Return**

1 if ; otherwise, 0.

#### <a id="c-ata_scsi_sdev_init"></a>`ata_scsi_sdev_init()`

```c
int ata_scsi_sdev_init(struct scsi_device *sdev)
```

Early setup of SCSI device

**Parameters**

- `struct scsi_device *sdev`: SCSI device to examine

**Description**

This is called from `scsi_alloc_sdev()` when the scsi device
associated with an ATA device is scanned on a port.

LOCKING:
Defined by SCSI layer.  We don't really care.

#### <a id="c-ata_scsi_sdev_configure"></a>`ata_scsi_sdev_configure()`

```c
int ata_scsi_sdev_configure(struct scsi_device *sdev, struct queue_limits *lim)
```

Set SCSI device attributes

**Parameters**

- `struct scsi_device *sdev`: SCSI device to examine
- `struct queue_limits *lim`: queue limits

**Description**

This is called before we actually start reading
and writing to the device, to configure certain
SCSI mid-layer behaviors.

LOCKING:
Defined by SCSI layer.  We don't really care.

#### <a id="c-ata_scsi_sdev_destroy"></a>`ata_scsi_sdev_destroy()`

```c
void ata_scsi_sdev_destroy(struct scsi_device *sdev)
```

SCSI device is about to be destroyed

**Parameters**

- `struct scsi_device *sdev`: SCSI device to be destroyed

**Description**

**sdev** is about to be destroyed for hot/warm unplugging.  If
this unplugging was initiated by libata as indicated by NULL
dev->sdev, this function doesn't have to do anything.
Otherwise, SCSI layer initiated warm-unplug is in progress.
Clear dev->sdev, schedule the device for ATA detach and invoke
EH.

LOCKING:
Defined by SCSI layer.  We don't really care.

#### <a id="c-ata_scsi_queuecmd"></a>`ata_scsi_queuecmd()`

```c
enum scsi_qc_status ata_scsi_queuecmd(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
```

Issue SCSI cdb to libata-managed device

**Parameters**

- `struct Scsi_Host *shost`: SCSI host of command to be sent
- `struct scsi_cmnd *cmd`: SCSI command to be sent

**Description**

In some cases, this function translates SCSI commands into
ATA taskfiles, and queues the taskfiles to be sent to
hardware.  In other cases, this function simulates a
SCSI device by evaluating and responding to certain
SCSI commands.  This creates the overall effect of
ATA and ATAPI devices appearing as SCSI devices.

LOCKING:
ATA host lock

**Return**

Return value from `__ata_scsi_queuecmd()` if **cmd** can be queued,
0 otherwise.



#### <a id="c-ata_scsi_set_passthru_sense_fields"></a>`ata_scsi_set_passthru_sense_fields()`

```c
void ata_scsi_set_passthru_sense_fields(struct ata_queued_cmd *qc)
```

Set ATA fields in sense buffer

**Parameters**

- `struct ata_queued_cmd *qc`: ATA PASS-THROUGH command.

**Description**

Populates "ATA Status Return sense data descriptor" / "Fixed format
sense data" with ATA taskfile fields.

LOCKING:
None.

#### <a id="c-ata_get_identity"></a>`ata_get_identity()`

```c
int ata_get_identity(struct ata_port *ap, struct scsi_device *sdev, void __user *arg)
```

Handler for HDIO_GET_IDENTITY ioctl

**Parameters**

- `struct ata_port *ap`: target port
- `struct scsi_device *sdev`: SCSI device to get identify data for
- `void __user *arg`: User buffer area for identify data

**Description**

LOCKING:
Defined by the SCSI layer.  We don't really care.

**Return**

Zero on success, negative errno on error.

#### <a id="c-ata_cmd_ioctl"></a>`ata_cmd_ioctl()`

```c
int ata_cmd_ioctl(struct scsi_device *scsidev, void __user *arg)
```

Handler for HDIO_DRIVE_CMD ioctl

**Parameters**

- `struct scsi_device *scsidev`: Device to which we are issuing command
- `void __user *arg`: User provided data for issuing command

**Description**

LOCKING:
Defined by the SCSI layer.  We don't really care.

**Return**

Zero on success, negative errno on error.

#### <a id="c-ata_task_ioctl"></a>`ata_task_ioctl()`

```c
int ata_task_ioctl(struct scsi_device *scsidev, void __user *arg)
```

Handler for HDIO_DRIVE_TASK ioctl

**Parameters**

- `struct scsi_device *scsidev`: Device to which we are issuing command
- `void __user *arg`: User provided data for issuing command

**Description**

LOCKING:
Defined by the SCSI layer.  We don't really care.

**Return**

Zero on success, negative errno on error.

#### <a id="c-ata_scsi_qc_new"></a>`ata_scsi_qc_new()`

```c
struct ata_queued_cmd * ata_scsi_qc_new(struct ata_device *dev, struct scsi_cmnd *cmd)
```

acquire new ata_queued_cmd reference

**Parameters**

- `struct ata_device *dev`: ATA device to which the new command is attached
- `struct scsi_cmnd *cmd`: SCSI command that originated this ATA command

**Description**

Obtain a reference to an unused ata_queued_cmd structure,
which is the basic libata structure representing a single
ATA command sent to the hardware.

If a command was available, fill in the SCSI-specific
portions of the structure with information on the
current command.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Command allocated, or `NULL` if none available.

#### <a id="c-ata_to_sense_error"></a>`ata_to_sense_error()`

```c
void ata_to_sense_error(u8 drv_stat, u8 drv_err, u8 *sk, u8 *asc, u8 *ascq)
```

convert ATA error to SCSI error

**Parameters**

- `u8 drv_stat`: value contained in ATA status register
- `u8 drv_err`: value contained in ATA error register
- `u8 *sk`: the sense key we'll fill out
- `u8 *asc`: the additional sense code we'll fill out
- `u8 *ascq`: the additional sense code qualifier we'll fill out

**Description**

Converts an ATA error into a SCSI error.  Fill out pointers to
SK, ASC, and ASCQ bytes for later use in fixed or descriptor
format sense blocks.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_gen_ata_sense"></a>`ata_gen_ata_sense()`

```c
void ata_gen_ata_sense(struct ata_queued_cmd *qc)
```

generate a SCSI fixed sense block

**Parameters**

- `struct ata_queued_cmd *qc`: Command that we are erroring out

**Description**

Generate sense block for a failed ATA command **qc**.

LOCKING:
None.

#### <a id="c-ata_scsi_start_stop_xlat"></a>`ata_scsi_start_stop_xlat()`

```c
unsigned int ata_scsi_start_stop_xlat(struct ata_queued_cmd *qc)
```

Translate SCSI START STOP UNIT command

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Sets up an ATA taskfile to issue STANDBY (to stop) or READ VERIFY
(to start). Perhaps these commands should be preceded by
CHECK POWER MODE to see what power mode the device is already in.
\[See SAT revision 5 at www.t10.org\]

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on error.

#### <a id="c-ata_scsi_flush_xlat"></a>`ata_scsi_flush_xlat()`

```c
unsigned int ata_scsi_flush_xlat(struct ata_queued_cmd *qc)
```

Translate SCSI SYNCHRONIZE CACHE command

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Sets up an ATA taskfile to issue FLUSH CACHE or
FLUSH CACHE EXT.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on error.

#### <a id="c-scsi_6_lba_len"></a>`scsi_6_lba_len()`

```c
void scsi_6_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
```

Get LBA and transfer length

**Parameters**

- `const u8 *cdb`: SCSI command to translate
- `u64 *plba`: the LBA
- `u32 *plen`: the transfer length

**Description**

Calculate LBA and transfer length for 6-byte commands.

#### <a id="c-scsi_10_lba_len"></a>`scsi_10_lba_len()`

```c
void scsi_10_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
```

Get LBA and transfer length

**Parameters**

- `const u8 *cdb`: SCSI command to translate
- `u64 *plba`: the LBA
- `u32 *plen`: the transfer length

**Description**

Calculate LBA and transfer length for 10-byte commands.

#### <a id="c-scsi_16_lba_len"></a>`scsi_16_lba_len()`

```c
void scsi_16_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
```

Get LBA and transfer length

**Parameters**

- `const u8 *cdb`: SCSI command to translate
- `u64 *plba`: the LBA
- `u32 *plen`: the transfer length

**Description**

Calculate LBA and transfer length for 16-byte commands.

#### <a id="c-scsi_dld"></a>`scsi_dld()`

```c
int scsi_dld(const u8 *cdb)
```

Get duration limit descriptor index

**Parameters**

- `const u8 *cdb`: SCSI command to translate

**Description**

Returns the dld bits indicating the index of a command duration limit
descriptor.

#### <a id="c-ata_scsi_verify_xlat"></a>`ata_scsi_verify_xlat()`

```c
unsigned int ata_scsi_verify_xlat(struct ata_queued_cmd *qc)
```

Translate SCSI VERIFY command into an ATA one

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Converts SCSI VERIFY command to an ATA READ VERIFY command.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on error.

#### <a id="c-ata_scsi_rw_xlat"></a>`ata_scsi_rw_xlat()`

```c
unsigned int ata_scsi_rw_xlat(struct ata_queued_cmd *qc)
```

Translate SCSI r/w command into an ATA one

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Converts any of six SCSI read/write commands into the
ATA counterpart, including starting sector (LBA),
sector count, and taking into account the device's LBA48
support.

Commands `READ_6`, `READ_10`, `READ_16`, `WRITE_6`, `WRITE_10`, and
`WRITE_16` are currently supported.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on error.

#### <a id="c-ata_scsi_translate"></a>`ata_scsi_translate()`

```c
int ata_scsi_translate(struct ata_device *dev, struct scsi_cmnd *cmd, ata_xlat_func_t xlat_func)
```

Translate then issue SCSI command to ATA device

**Parameters**

- `struct ata_device *dev`: ATA device to which the command is addressed
- `struct scsi_cmnd *cmd`: SCSI command to execute
- `ata_xlat_func_t xlat_func`: Actor which translates **cmd** to an ATA taskfile

**Description**

Our ->`queuecommand()` function has decided that the SCSI
command issued can be directly translated into an ATA
command, rather than handled internally.

This function sets up an ata_queued_cmd structure for the
SCSI command, and sends that ata_queued_cmd to the hardware.

The xlat_func argument (actor) returns 0 if ready to execute
ATA command, else 1 to finish translation. If 1 is returned
then cmd->result (and possibly cmd->sense_buffer) are assumed
to be set reflecting an error condition or clean (early)
termination.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

0 on success, SCSI_ML_QUEUE_DEVICE_BUSY or SCSI_MLQUEUE_HOST_BUSY if the
command needs to be deferred.

#### <a id="c-ata_scsi_rbuf_fill"></a>`ata_scsi_rbuf_fill()`

```c
void ata_scsi_rbuf_fill(struct ata_device *dev, struct scsi_cmnd *cmd, unsigned int (*actor)(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf))
```

wrapper for SCSI command simulators

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `unsigned int (*actor)(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)`: Callback hook for desired SCSI command simulator

**Description**

Takes care of the hard work of simulating a SCSI command...
Mapping the response buffer, calling the command's handler,
and handling the handler's return value.  This return value
indicates whether the handler wishes the SCSI command to be
completed successfully (0), or not (in which case cmd->result
and sense buffer are assumed to be set).

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_std"></a>`ata_scsiop_inq_std()`

```c
unsigned int ata_scsiop_inq_std(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate standard INQUIRY command

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Returns standard device identification data associated
with non-VPD INQUIRY command output.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_00"></a>`ata_scsiop_inq_00()`

```c
unsigned int ata_scsiop_inq_00(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page 0, list of pages

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Returns list of inquiry VPD pages available.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_80"></a>`ata_scsiop_inq_80()`

```c
unsigned int ata_scsiop_inq_80(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page 80, device serial number

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Returns ATA device serial number.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_83"></a>`ata_scsiop_inq_83()`

```c
unsigned int ata_scsiop_inq_83(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page 83, device identity

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

- Yields two logical unit device identification designators:
  - vendor specific ASCII containing the ATA serial number
  - SAT defined "t10 vendor id based" containing ASCII vendor
    name ("ATA     "), model and serial numbers.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_89"></a>`ata_scsiop_inq_89()`

```c
unsigned int ata_scsiop_inq_89(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page 89, ATA info

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Yields SAT-specified ATA VPD page.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_b0"></a>`ata_scsiop_inq_b0()`

```c
unsigned int ata_scsiop_inq_b0(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B0, Block Limits

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B0h (Block Limits).

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_b1"></a>`ata_scsiop_inq_b1()`

```c
unsigned int ata_scsiop_inq_b1(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B1, Block Device Characteristics

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B1h (Block Device Characteristics).

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_b2"></a>`ata_scsiop_inq_b2()`

```c
unsigned int ata_scsiop_inq_b2(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B2, Logical Block Provisioning

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B2h (Logical Block Provisioning).

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_b6"></a>`ata_scsiop_inq_b6()`

```c
unsigned int ata_scsiop_inq_b6(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B6, Zoned Block Device Characteristics

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B2h (Zoned Block Device Characteristics).

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inq_b9"></a>`ata_scsiop_inq_b9()`

```c
unsigned int ata_scsiop_inq_b9(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B9, Concurrent Positioning Ranges

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B9h (Concurrent Positioning Ranges).

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_inquiry"></a>`ata_scsiop_inquiry()`

```c
unsigned int ata_scsiop_inquiry(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY command

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Returns data associated with an INQUIRY command output.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-modecpy"></a>`modecpy()`

```c
void modecpy(u8 *dest, const u8 *src, int n, bool changeable)
```

Prepare response for MODE SENSE

**Parameters**

- `u8 *dest`: output buffer
- `const u8 *src`: data being copied
- `int n`: length of mode page
- `bool changeable`: whether changeable parameters are requested

**Description**

Generate a generic MODE SENSE page for either current or changeable
parameters.

LOCKING:
None.

#### <a id="c-ata_msense_caching"></a>`ata_msense_caching()`

```c
unsigned int ata_msense_caching(u16 *id, u8 *buf, bool changeable)
```

Simulate MODE SENSE caching info page

**Parameters**

- `u16 *id`: device IDENTIFY data
- `u8 *buf`: output buffer
- `bool changeable`: whether changeable parameters are requested

**Description**

Generate a caching info page, which conditionally indicates
write caching to the SCSI layer, depending on device
capabilities.

LOCKING:
None.

#### <a id="c-ata_msense_control"></a>`ata_msense_control()`

```c
unsigned int ata_msense_control(struct ata_device *dev, u8 *buf, u8 spg, bool changeable)
```

Simulate MODE SENSE control mode page

**Parameters**

- `struct ata_device *dev`: ATA device of interest
- `u8 *buf`: output buffer
- `u8 spg`: sub-page code
- `bool changeable`: whether changeable parameters are requested

**Description**

Generate a generic MODE SENSE control mode page.

LOCKING:
None.

#### <a id="c-ata_msense_rw_recovery"></a>`ata_msense_rw_recovery()`

```c
unsigned int ata_msense_rw_recovery(u8 *buf, bool changeable)
```

Simulate MODE SENSE r/w error recovery page

**Parameters**

- `u8 *buf`: output buffer
- `bool changeable`: whether changeable parameters are requested

**Description**

Generate a generic MODE SENSE r/w error recovery page.

LOCKING:
None.

#### <a id="c-ata_scsiop_mode_sense"></a>`ata_scsiop_mode_sense()`

```c
unsigned int ata_scsiop_mode_sense(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate MODE SENSE 6, 10 commands

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Simulate MODE SENSE commands. Assume this is invoked for direct
access devices (e.g. disks) only. There should be no block
descriptor for other device types.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsiop_read_cap"></a>`ata_scsiop_read_cap()`

```c
unsigned int ata_scsiop_read_cap(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate READ CAPACITY\[ 16\] commands

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Simulate READ CAPACITY commands.

LOCKING:
None.

#### <a id="c-ata_scsiop_report_luns"></a>`ata_scsiop_report_luns()`

```c
unsigned int ata_scsiop_report_luns(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate REPORT LUNS command

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Simulate REPORT LUNS command.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-atapi_xlat"></a>`atapi_xlat()`

```c
unsigned int atapi_xlat(struct ata_queued_cmd *qc)
```

Initialize PACKET taskfile

**Parameters**

- `struct ata_queued_cmd *qc`: command structure to be initialized

**Description**

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on failure.

#### <a id="c-ata_scsi_find_dev"></a>`ata_scsi_find_dev()`

```c
struct ata_device * ata_scsi_find_dev(struct ata_port *ap, const struct scsi_device *scsidev)
```

lookup ata_device from scsi_cmnd

**Parameters**

- `struct ata_port *ap`: ATA port to which the device is attached
- `const struct scsi_device *scsidev`: SCSI device from which we derive the ATA device

**Description**

Given various information provided in struct scsi_cmnd,
map that onto an ATA bus, and using that mapping
determine which ata_device is associated with the
SCSI command to be sent.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Associated ATA device, or `NULL` if not found.

#### <a id="c-ata_scsi_pass_thru"></a>`ata_scsi_pass_thru()`

```c
unsigned int ata_scsi_pass_thru(struct ata_queued_cmd *qc)
```

convert ATA pass-thru CDB to taskfile

**Parameters**

- `struct ata_queued_cmd *qc`: command structure to be initialized

**Description**

Handles either 12, 16, or 32-byte versions of the CDB.

**Return**

Zero on success, non-zero on failure.

#### <a id="c-ata_format_dsm_trim_descr"></a>`ata_format_dsm_trim_descr()`

```c
size_t ata_format_dsm_trim_descr(struct scsi_cmnd *cmd, u32 trmax, u64 sector, u32 count)
```

SATL Write Same to DSM Trim

**Parameters**

- `struct scsi_cmnd *cmd`: SCSI command being translated
- `u32 trmax`: Maximum number of entries that will fit in sector_size bytes.
- `u64 sector`: Starting sector
- `u32 count`: Total Range of request in logical sectors

**Description**

Rewrite the WRITE SAME descriptor to be a DSM TRIM little-endian formatted
descriptor.

- Upto 64 entries of the format:
  63:48 Range Length
  47:0  LBA

  Range Length of 0 is ignored.
  LBA's should be sorted order and not overlap.

**NOTE**

this is the same format as ADD LBA(S) TO NV CACHE PINNED SET

**Return**

Number of bytes copied into sglist.

#### <a id="c-ata_scsi_write_same_xlat"></a>`ata_scsi_write_same_xlat()`

```c
unsigned int ata_scsi_write_same_xlat(struct ata_queued_cmd *qc)
```

SATL Write Same to ATA SCT Write Same

**Parameters**

- `struct ata_queued_cmd *qc`: Command to be translated

**Description**

Translate a SCSI WRITE SAME command to be either a DSM TRIM command or
an SCT Write Same command.
Based on WRITE SAME has the UNMAP flag:

- When set translate to DSM TRIM
- When clear translate to SCT Write Same

#### <a id="c-ata_scsiop_maint_in"></a>`ata_scsiop_maint_in()`

```c
unsigned int ata_scsiop_maint_in(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate a subset of MAINTENANCE_IN

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Yields a subset to satisfy [`scsi_report_opcode()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_report_opcode)

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsi_report_zones_complete"></a>`ata_scsi_report_zones_complete()`

```c
void ata_scsi_report_zones_complete(struct ata_queued_cmd *qc)
```

convert ATA output

**Parameters**

- `struct ata_queued_cmd *qc`: command structure returning the data

**Description**

Convert T-13 little-endian field representation into
T-10 big-endian field representation.
What a mess.

#### <a id="c-ata_mselect_caching"></a>`ata_mselect_caching()`

```c
int ata_mselect_caching(struct ata_queued_cmd *qc, const u8 *buf, int len, u16 *fp)
```

Simulate MODE SELECT for caching info page

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile
- `const u8 *buf`: input buffer
- `int len`: number of valid bytes in the input buffer
- `u16 *fp`: out parameter for the failed field on error

**Description**

Prepare a taskfile to modify caching information for the device.

LOCKING:
None.

#### <a id="c-ata_mselect_control"></a>`ata_mselect_control()`

```c
int ata_mselect_control(struct ata_queued_cmd *qc, u8 spg, const u8 *buf, int len, u16 *fp)
```

Simulate MODE SELECT for control page

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile
- `u8 spg`: target sub-page of the control page
- `const u8 *buf`: input buffer
- `int len`: number of valid bytes in the input buffer
- `u16 *fp`: out parameter for the failed field on error

**Description**

Prepare a taskfile to modify caching information for the device.

LOCKING:
None.

#### <a id="c-ata_scsi_mode_select_xlat"></a>`ata_scsi_mode_select_xlat()`

```c
unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc)
```

Simulate MODE SELECT 6, 10 commands

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Converts a MODE SELECT command to an ATA SET FEATURES taskfile.
Assume this is invoked for direct access devices (e.g. disks) only.
There should be no block descriptor for other device types.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsi_var_len_cdb_xlat"></a>`ata_scsi_var_len_cdb_xlat()`

```c
unsigned int ata_scsi_var_len_cdb_xlat(struct ata_queued_cmd *qc)
```

SATL variable length CDB to Handler

**Parameters**

- `struct ata_queued_cmd *qc`: Command to be translated

**Description**

Translate a SCSI variable length CDB to specified commands.
It checks a service action value in CDB to call corresponding handler.

**Return**

Zero on success, non-zero on failure

#### <a id="c-ata_get_xlat_func"></a>`ata_get_xlat_func()`

```c
ata_xlat_func_t ata_get_xlat_func(struct ata_device *dev, u8 cmd)
```

check if SCSI to ATA translation is possible

**Parameters**

- `struct ata_device *dev`: ATA device
- `u8 cmd`: SCSI command opcode to consider

**Description**

Look up the SCSI command given, and determine whether the
SCSI command is to be translated or simulated.

**Return**

Pointer to translation function if possible, `NULL` if not.

#### <a id="c-ata_scsi_simulate"></a>`ata_scsi_simulate()`

```c
void ata_scsi_simulate(struct ata_device *dev, struct scsi_cmnd *cmd)
```

simulate SCSI command on ATA device

**Parameters**

- `struct ata_device *dev`: the target device
- `struct scsi_cmnd *cmd`: SCSI command being sent to device.

**Description**

Interprets and directly executes a select list of SCSI commands
that can be handled internally.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsi_offline_dev"></a>`ata_scsi_offline_dev()`

```c
bool ata_scsi_offline_dev(struct ata_device *dev)
```

offline attached SCSI device

**Parameters**

- `struct ata_device *dev`: ATA device to offline attached SCSI device for

**Description**

This function is called from [`ata_eh_detach_dev()`](#c-ata_eh_detach_dev) and is responsible for
taking the SCSI device attached to **dev** offline.  This function is
called with host lock which protects dev->sdev against clearing.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

true if attached SCSI device exists, false otherwise.

#### <a id="c-ata_scsi_remove_dev"></a>`ata_scsi_remove_dev()`

```c
void ata_scsi_remove_dev(struct ata_device *dev)
```

remove attached SCSI device

**Parameters**

- `struct ata_device *dev`: ATA device to remove attached SCSI device for

**Description**

This function is called from `ata_eh_scsi_hotplug()` and
responsible for removing the SCSI device attached to **dev**.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_scsi_media_change_notify"></a>`ata_scsi_media_change_notify()`

```c
void ata_scsi_media_change_notify(struct ata_device *dev)
```

send media change event

**Parameters**

- `struct ata_device *dev`: Pointer to the disk device with media change event

**Description**

Tell the block layer to send a media change notification
event.

LOCKING:
spin_lock_irqsave(host lock)

#### <a id="c-ata_scsi_hotplug"></a>`ata_scsi_hotplug()`

```c
void ata_scsi_hotplug(struct work_struct *work)
```

SCSI part of hotplug

**Parameters**

- `struct work_struct *work`: Pointer to ATA port to perform SCSI hotplug on

**Description**

Perform SCSI part of hotplug.  It's executed from a separate
workqueue after EH completes.  This is necessary because SCSI
hot plugging requires working EH and hot unplugging is
synchronized with hot plugging with a mutex.

LOCKING:
Kernel thread context (may sleep).

#### <a id="c-ata_scsi_user_scan"></a>`ata_scsi_user_scan()`

```c
int ata_scsi_user_scan(struct Scsi_Host *shost, unsigned int channel, unsigned int id, u64 lun)
```

indication for user-initiated bus scan

**Parameters**

- `struct Scsi_Host *shost`: SCSI host to scan
- `unsigned int channel`: Channel to scan
- `unsigned int id`: ID to scan
- `u64 lun`: LUN to scan

**Description**

This function is called when user explicitly requests bus
scan.  Set probe pending flag and invoke EH.

LOCKING:
SCSI layer (we don't care)

**Return**

Zero.

#### <a id="c-ata_scsi_dev_rescan"></a>`ata_scsi_dev_rescan()`

```c
void ata_scsi_dev_rescan(struct work_struct *work)
```

initiate `scsi_rescan_device()`

**Parameters**

- `struct work_struct *work`: Pointer to ATA port to perform `scsi_rescan_device()`

**Description**

After ATA pass thru (SAT) commands are executed successfully,
libata need to propagate the changes to SCSI layer.

LOCKING:
Kernel thread context (may sleep).


<a id="rst-ata-errors-and-exceptions"></a>

## ATA errors and exceptions

This chapter tries to identify what error/exception conditions exist for ATA/ATAPI devices and describe how they should be handled in implementation-neutral way.

The term 'error' is used to describe conditions where either an explicit error condition is reported from device or a command has timed out.

The term 'exception' is either used to describe exceptional conditions which are not errors (say, power or hotplug events), or to describe both errors and non-error exceptional conditions. Where explicit distinction between error and exception is necessary, the term 'non-error exception' is used.

<a id="rst-exception-categories"></a>

### Exception categories

Exceptions are described primarily with respect to legacy taskfile + bus master IDE interface. If a controller provides other better mechanism for error reporting, mapping those into categories described below shouldn't be difficult.

In the following sections, two recovery actions - reset and reconfiguring transport - are mentioned. These are described further in [EH recovery actions](#rst-eh-recovery-actions).

<a id="rst-hsm-violation"></a>

#### HSM violation

This error is indicated when STATUS value doesn't match HSM requirement during issuing or execution any ATA/ATAPI command.

- ATA_STATUS doesn't contain \!BSY &amp;&amp; DRDY &amp;&amp; \!DRQ while trying to issue a command.

- \!BSY &amp;&amp; \!DRQ during PIO data transfer.

- DRQ on command completion.

- \!BSY &amp;&amp; ERR after CDB transfer starts but before the last byte of CDB is transferred. ATA/ATAPI standard states that "The device shall not terminate the PACKET command with an error before the last byte of the command packet has been written" in the error outputs description of PACKET command and the state diagram doesn't include such transitions.

In these cases, HSM is violated and not much information regarding the error can be acquired from STATUS or ERROR register. IOW, this error can be anything - driver bug, faulty device, controller and/or cable.

As HSM is violated, reset is necessary to restore known state. Reconfiguring transport for lower speed might be helpful too as transmission errors sometimes cause this kind of errors.

<a id="rst-ata-atapi-device-error-non-ncq-non-check-condition"></a>

#### ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)

These are errors detected and reported by ATA/ATAPI devices indicating device problems. For this type of errors, STATUS and ERROR register values are valid and describe error condition. Note that some of ATA bus errors are detected by ATA/ATAPI devices and reported using the same mechanism as device errors. Those cases are described later in this section.

For ATA commands, this type of errors are indicated by \!BSY &amp;&amp; ERR during command execution and on completion.

For ATAPI commands,

- \!BSY &amp;&amp; ERR &amp;&amp; ABRT right after issuing PACKET indicates that PACKET command is not supported and falls in this category.

- \!BSY &amp;&amp; ERR(==CHK) &amp;&amp; \!ABRT after the last byte of CDB is transferred indicates CHECK CONDITION and doesn't fall in this category.

- \!BSY &amp;&amp; ERR(==CHK) &amp;&amp; ABRT after the last byte of CDB is transferred \*probably\* indicates CHECK CONDITION and doesn't fall in this category.

Of errors detected as above, the following are not ATA/ATAPI device errors but ATA bus errors and should be handled according to [ATA bus error](#rst-ata-bus-error).

- **CRC error during data transfer**

  This is indicated by ICRC bit in the ERROR register and means that corruption occurred during data transfer. Up to ATA/ATAPI-7, the standard specifies that this bit is only applicable to UDMA transfers but ATA/ATAPI-8 draft revision 1f says that the bit may be applicable to multiword DMA and PIO.

- **ABRT error during data transfer or on completion**

  Up to ATA/ATAPI-7, the standard specifies that ABRT could be set on ICRC errors and on cases where a device is not able to complete a command. Combined with the fact that MWDMA and PIO transfer errors aren't allowed to use ICRC bit up to ATA/ATAPI-7, it seems to imply that ABRT bit alone could indicate transfer errors.

  However, ATA/ATAPI-8 draft revision 1f removes the part that ICRC errors can turn on ABRT. So, this is kind of gray area. Some heuristics are needed here.

ATA/ATAPI device errors can be further categorized as follows.

- **Media errors**

  This is indicated by UNC bit in the ERROR register. ATA devices reports UNC error only after certain number of retries cannot recover the data, so there's nothing much else to do other than notifying upper layer.

  READ and WRITE commands report CHS or LBA of the first failed sector but ATA/ATAPI standard specifies that the amount of transferred data on error completion is indeterminate, so we cannot assume that sectors preceding the failed sector have been transferred and thus cannot complete those sectors successfully as SCSI does.

- **Media changed / media change requested error**

  &lt;&lt;TODO: fill here&gt;&gt;

- **Address error**

  This is indicated by IDNF bit in the ERROR register. Report to upper layer.

- **Other errors**

  This can be invalid command or parameter indicated by ABRT ERROR bit or some other error condition. Note that ABRT bit can indicate a lot of things including ICRC and Address errors. Heuristics needed.

Depending on commands, not all STATUS/ERROR bits are applicable. These non-applicable bits are marked with "na" in the output descriptions but up to ATA/ATAPI-7 no definition of "na" can be found. However, ATA/ATAPI-8 draft revision 1f describes "N/A" as follows.

> - **3.2.3.3a N/A**
>
>   A keyword the indicates a field has no defined value in this standard and should not be checked by the host or device. N/A fields should be cleared to zero.

So, it seems reasonable to assume that "na" bits are cleared to zero by devices and thus need no explicit masking.

<a id="rst-atapi-device-check-condition"></a>

#### ATAPI device CHECK CONDITION

ATAPI device CHECK CONDITION error is indicated by set CHK bit (ERR bit) in the STATUS register after the last byte of CDB is transferred for a PACKET command. For this kind of errors, sense data should be acquired to gather information regarding the errors. REQUEST SENSE packet command should be used to acquire sense data.

Once sense data is acquired, this type of errors can be handled similarly to other SCSI errors. Note that sense data may indicate ATA bus error (e.g. Sense Key 04h HARDWARE ERROR &amp;&amp; ASC/ASCQ 47h/00h SCSI PARITY ERROR). In such cases, the error should be considered as an ATA bus error and handled according to [ATA bus error](#rst-ata-bus-error).

<a id="rst-ata-device-error-ncq"></a>

#### ATA device error (NCQ)

NCQ command error is indicated by cleared BSY and set ERR bit during NCQ command phase (one or more NCQ commands outstanding). Although STATUS and ERROR registers will contain valid values describing the error, READ LOG EXT is required to clear the error condition, determine which command has failed and acquire more information.

READ LOG EXT Log Page 10h reports which tag has failed and taskfile register values describing the error. With this information the failed command can be handled as a normal ATA command error as in [ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)](#rst-ata-atapi-device-error-non-ncq-non-check-condition) and all other in-flight commands must be retried. Note that this retry should not be counted - it's likely that commands retried this way would have completed normally if it were not for the failed command.

Note that ATA bus errors can be reported as ATA device NCQ errors. This should be handled as described in [ATA bus error](#rst-ata-bus-error).

If READ LOG EXT Log Page 10h fails or reports NQ, we're thoroughly screwed. This condition should be treated according to [HSM violation](#rst-hsm-violation).

<a id="rst-ata-bus-error"></a>

#### ATA bus error

ATA bus error means that data corruption occurred during transmission over ATA bus (SATA or PATA). This type of errors can be indicated by

- ICRC or ABRT error as described in [ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)](#rst-ata-atapi-device-error-non-ncq-non-check-condition).

- Controller-specific error completion with error information indicating transmission error.

- On some controllers, command timeout. In this case, there may be a mechanism to determine that the timeout is due to transmission error.

- Unknown/random errors, timeouts and all sorts of weirdities.

As described above, transmission errors can cause wide variety of symptoms ranging from device ICRC error to random device lockup, and, for many cases, there is no way to tell if an error condition is due to transmission error or not; therefore, it's necessary to employ some kind of heuristic when dealing with errors and timeouts. For example, encountering repetitive ABRT errors for known supported command is likely to indicate ATA bus error.

Once it's determined that ATA bus errors have possibly occurred, lowering ATA bus transmission speed is one of actions which may alleviate the problem. See [Reconfigure transport](#rst-reconfigure-transport) for more information.

<a id="rst-pci-bus-error"></a>

#### PCI bus error

Data corruption or other failures during transmission over PCI (or other system bus). For standard BMDMA, this is indicated by Error bit in the BMDMA Status register. This type of errors must be logged as it indicates something is very wrong with the system. Resetting host controller is recommended.

<a id="rst-late-completion"></a>

#### Late completion

This occurs when timeout occurs and the timeout handler finds out that the timed out command has completed successfully or with error. This is usually caused by lost interrupts. This type of errors must be logged. Resetting host controller is recommended.

<a id="rst-unknown-error-timeout"></a>

#### Unknown error (timeout)

This is when timeout occurs and the command is still processing or the host and device are in unknown state. When this occurs, HSM could be in any valid or invalid state. To bring the device to known state and make it forget about the timed out command, resetting is necessary. The timed out command may be retried.

Timeouts can also be caused by transmission errors. Refer to [ATA bus error](#rst-ata-bus-error) for more details.

<a id="rst-hotplug-and-power-management-exceptions"></a>

#### Hotplug and power management exceptions

&lt;&lt;TODO: fill here&gt;&gt;

<a id="rst-eh-recovery-actions"></a>

### EH recovery actions

This section discusses several important recovery actions.

<a id="rst-clearing-error-condition"></a>

#### Clearing error condition

Many controllers require its error registers to be cleared by error handler. Different controllers may have different requirements.

For SATA, it's strongly recommended to clear at least SError register during error handling.

<a id="rst-reset"></a>

#### Reset

During EH, resetting is necessary in the following cases.

- HSM is in unknown or invalid state

- HBA is in unknown or invalid state

- EH needs to make HBA/device forget about in-flight commands

- HBA/device behaves weirdly

Resetting during EH might be a good idea regardless of error condition to improve EH robustness. Whether to reset both or either one of HBA and device depends on situation but the following scheme is recommended.

- When it's known that HBA is in ready state but ATA/ATAPI device is in unknown state, reset only device.

- If HBA is in unknown state, reset both HBA and device.

HBA resetting is implementation specific. For a controller complying to taskfile/BMDMA PCI IDE, stopping active DMA transaction may be sufficient iff BMDMA state is the only HBA context. But even mostly taskfile/BMDMA PCI IDE complying controllers may have implementation specific requirements and mechanism to reset themselves. This must be addressed by specific drivers.

OTOH, ATA/ATAPI standard describes in detail ways to reset ATA/ATAPI devices.

- **PATA hardware reset**

  This is hardware initiated device reset signalled with asserted PATA RESET- signal. There is no standard way to initiate hardware reset from software although some hardware provides registers that allow driver to directly tweak the RESET- signal.

- **Software reset**

  This is achieved by turning CONTROL SRST bit on for at least 5us. Both PATA and SATA support it but, in case of SATA, this may require controller-specific support as the second Register FIS to clear SRST should be transmitted while BSY bit is still set. Note that on PATA, this resets both master and slave devices on a channel.

- **EXECUTE DEVICE DIAGNOSTIC command**

  Although ATA/ATAPI standard doesn't describe exactly, EDD implies some level of resetting, possibly similar level with software reset. Host-side EDD protocol can be handled with normal command processing and most SATA controllers should be able to handle EDD's just like other commands. As in software reset, EDD affects both devices on a PATA bus.

  Although EDD does reset devices, this doesn't suit error handling as EDD cannot be issued while BSY is set and it's unclear how it will act when device is in unknown/weird state.

- **ATAPI DEVICE RESET command**

  This is very similar to software reset except that reset can be restricted to the selected device without affecting the other device sharing the cable.

- **SATA phy reset**

  This is the preferred way of resetting a SATA device. In effect, it's identical to PATA hardware reset. Note that this can be done with the standard SCR Control register. As such, it's usually easier to implement than software reset.

One more thing to consider when resetting devices is that resetting clears certain configuration parameters and they need to be set to their previous or newly adjusted values after reset.

Parameters affected are.

- CHS set up with INITIALIZE DEVICE PARAMETERS (seldom used)

- Parameters set with SET FEATURES including transfer mode setting

- Block count set with SET MULTIPLE MODE

- Other parameters (SET MAX, MEDIA LOCK...)

ATA/ATAPI standard specifies that some parameters must be maintained across hardware or software reset, but doesn't strictly specify all of them. Always reconfiguring needed parameters after reset is required for robustness. Note that this also applies when resuming from deep sleep (power-off).

Also, ATA/ATAPI standard requires that IDENTIFY DEVICE / IDENTIFY PACKET DEVICE is issued after any configuration parameter is updated or a hardware reset and the result used for further operation. OS driver is required to implement revalidation mechanism to support this.

<a id="rst-reconfigure-transport"></a>

#### Reconfigure transport

For both PATA and SATA, a lot of corners are cut for cheap connectors, cables or controllers and it's quite common to see high transmission error rate. This can be mitigated by lowering transmission speed.

The following is a possible scheme Jeff Garzik suggested.

> If more than $N (3?) transmission errors happen in 15 minutes,
>
> - if SATA, decrease SATA PHY speed. if speed cannot be decreased,
>
> - decrease UDMA xfer speed. if at UDMA0, switch to PIO4,
>
> - decrease PIO xfer speed. if at PIO3, complain, but continue

<a id="rst-ata-piix-internals"></a>

## ata_piix Internals


#### <a id="c-ich_pata_cable_detect"></a>`ich_pata_cable_detect()`

```c
int ich_pata_cable_detect(struct ata_port *ap)
```

Probe host controller cable detect info

**Parameters**

- `struct ata_port *ap`: Port for which cable detect info is desired

**Description**

Read 80c cable indicator from ATA PCI device's PCI config
register.  This register is normally set by firmware (BIOS).

LOCKING:
None (inherited from caller).

#### <a id="c-piix_pata_prereset"></a>`piix_pata_prereset()`

```c
int piix_pata_prereset(struct ata_link *link, unsigned long deadline)
```

prereset for PATA host controller

**Parameters**

- `struct ata_link *link`: Target link
- `unsigned long deadline`: deadline jiffies for the operation

**Description**

LOCKING:
None (inherited from caller).

#### <a id="c-piix_set_piomode"></a>`piix_set_piomode()`

```c
void piix_set_piomode(struct ata_port *ap, struct ata_device *adev)
```

Initialize host controller PATA PIO timings

**Parameters**

- `struct ata_port *ap`: Port whose timings we are configuring
- `struct ata_device *adev`: Drive in question

**Description**

Set PIO mode for device, in host controller PCI config space.

LOCKING:
None (inherited from caller).

#### <a id="c-do_pata_set_dmamode"></a>`do_pata_set_dmamode()`

```c
void do_pata_set_dmamode(struct ata_port *ap, struct ata_device *adev, int isich)
```

Initialize host controller PATA PIO timings

**Parameters**

- `struct ata_port *ap`: Port whose timings we are configuring
- `struct ata_device *adev`: Drive in question
- `int isich`: set if the chip is an ICH device

**Description**

Set UDMA mode for device, in host controller PCI config space.

LOCKING:
None (inherited from caller).

#### <a id="c-piix_set_dmamode"></a>`piix_set_dmamode()`

```c
void piix_set_dmamode(struct ata_port *ap, struct ata_device *adev)
```

Initialize host controller PATA DMA timings

**Parameters**

- `struct ata_port *ap`: Port whose timings we are configuring
- `struct ata_device *adev`: um

**Description**

Set MW/UDMA mode for device, in host controller PCI config space.

LOCKING:
None (inherited from caller).

#### <a id="c-ich_set_dmamode"></a>`ich_set_dmamode()`

```c
void ich_set_dmamode(struct ata_port *ap, struct ata_device *adev)
```

Initialize host controller PATA DMA timings

**Parameters**

- `struct ata_port *ap`: Port whose timings we are configuring
- `struct ata_device *adev`: um

**Description**

Set MW/UDMA mode for device, in host controller PCI config space.

LOCKING:
None (inherited from caller).

#### <a id="c-piix_check_450nx_errata"></a>`piix_check_450nx_errata()`

```c
int piix_check_450nx_errata(struct pci_dev *ata_dev)
```

Check for problem 450NX setup

**Parameters**

- `struct pci_dev *ata_dev`: the PCI device to check

**Description**

Check for the present of 450NX errata #19 and errata #25. If
they are found return an error code so we can turn off DMA

#### <a id="c-piix_init_one"></a>`piix_init_one()`

```c
int piix_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
```

Register PIIX ATA PCI device with kernel services

**Parameters**

- `struct pci_dev *pdev`: PCI device to register
- `const struct pci_device_id *ent`: Entry in piix_pci_tbl matching with **pdev**

**Description**

Called from kernel PCI layer.  We probe for combined mode (sigh),
and then hand over control to libata, for it to do the rest.

LOCKING:
Inherited from PCI layer (may sleep).

**Return**

Zero on success, or -ERRNO value.


<a id="rst-sata-sil-internals"></a>

## sata_sil Internals


#### <a id="c-sil_set_mode"></a>`sil_set_mode()`

```c
int sil_set_mode(struct ata_link *link, struct ata_device **r_failed)
```

wrap set_mode functions

**Parameters**

- `struct ata_link *link`: link to set up
- `struct ata_device **r_failed`: returned device when we fail

**Description**

Wrap the libata method for device setup as after the setup we need
to inspect the results and do some configuration work

#### <a id="c-sil_dev_config"></a>`sil_dev_config()`

```c
void sil_dev_config(struct ata_device *dev)
```

Apply device/host-specific errata fixups

**Parameters**

- `struct ata_device *dev`: Device to be examined

**Description**

After the IDENTIFY \[PACKET\] DEVICE step is complete, and a
device is known to be present, this function is called.
We apply two errata fixups which are specific to Silicon Image,
a Seagate and a Maxtor fixup.

For certain Seagate devices, we must limit the maximum sectors
to under 8K.

For certain Maxtor devices, we must not program the drive
beyond udma5.

Both fixups are unfairly pessimistic.  As soon as I get more
information on these errata, I will create a more exhaustive
list, and apply the fixups to only the specific
devices/hosts/firmwares that need it.

20040111 - Seagate drives affected by the Mod15Write bug are quirked
The Maxtor quirk is in sil_quirks, but I'm keeping the original
pessimistic fix for the following reasons...
- There seems to be less info on it, only one device gleaned off the
Windows driver, maybe only one is affected.  More info would be greatly
appreciated.
- But then again UDMA5 is hardly anything to complain about


<a id="rst-thanks"></a>

## Thanks

The bulk of the ATA knowledge comes thanks to long conversations with Andre Hedrick (www.linux-ide.org), and long hours pondering the ATA and SCSI specifications.

Thanks to Alan Cox for pointing out similarities between SATA and SCSI, and in general for motivation to hack on libata.

libata's device detection method, ata_pio_devchk, and in general all the early probing was based on extensive study of Hale Landis's probe/reset code in his ATADRVR driver (www.ata-atapi.com).

---

# MEN Chameleon Bus

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> This document describes the architecture and implementation of the MEN Chameleon Bus (called MCB throughout this document).

<a id="rst-men-chameleon-bus"></a>

<!-- Table of Contents
=================
1 Introduction
    1.1 Scope of this Document
    1.2 Limitations of the current implementation
2 Architecture
    2.1 MEN Chameleon Bus
    2.2 Carrier Devices
    2.3 Parser
3 Resource handling
    3.1 Memory Resources
    3.2 IRQs
4 Writing an MCB driver
    4.1 The driver structure
    4.2 Probing and attaching
    4.3 Initializing the driver
    4.4 Using DMA -->

<a id="rst-introduction"></a>

## Introduction

This document describes the architecture and implementation of the MEN Chameleon Bus (called MCB throughout this document).

<a id="rst-scope-of-this-document"></a>

### Scope of this Document

This document is intended to be a short overview of the current implementation and does by no means describe the complete possibilities of MCB based devices.

<a id="rst-limitations-of-the-current-implementation"></a>

### Limitations of the current implementation

The current implementation is limited to PCI and PCIe based carrier devices that only use a single memory resource and share the PCI legacy IRQ.  Not implemented are:

- Multi-resource MCB devices like the VME Controller or M-Module carrier.

- MCB devices that need another MCB device, like SRAM for a DMA Controller's buffer descriptors or a video controller's video memory.

- A per-carrier IRQ domain for carrier devices that have one (or more) IRQs per MCB device like PCIe based carriers with MSI or MSI-X support.

<a id="rst-architecture"></a>

## Architecture

MCB is divided into 3 functional blocks:

- The MEN Chameleon Bus itself,

- drivers for MCB Carrier Devices and

- the parser for the Chameleon table.

<a id="rst-men-chameleon-bus-1"></a>

### MEN Chameleon Bus

The MEN Chameleon Bus is an artificial bus system that attaches to a so called Chameleon FPGA device found on some hardware produced my MEN Mikro Elektronik GmbH. These devices are multi-function devices implemented in a single FPGA and usually attached via some sort of PCI or PCIe link. Each FPGA contains a header section describing the content of the FPGA. The header lists the device id, PCI BAR, offset from the beginning of the PCI BAR, size in the FPGA, interrupt number and some other properties currently not handled by the MCB implementation.

<a id="rst-carrier-devices"></a>

### Carrier Devices

A carrier device is just an abstraction for the real world physical bus the Chameleon FPGA is attached to. Some IP Core drivers may need to interact with properties of the carrier device (like querying the IRQ number of a PCI device). To provide abstraction from the real hardware bus, an MCB carrier device provides callback methods to translate the driver's MCB function calls to hardware related function calls. For example a carrier device may implement the get_irq() method which can be translated into a hardware bus query for the IRQ number the device should use.

<a id="rst-parser"></a>

### Parser

The parser reads the first 512 bytes of a Chameleon device and parses the Chameleon table. Currently the parser only supports the Chameleon v2 variant of the Chameleon table but can easily be adopted to support an older or possible future variant. While parsing the table's entries new MCB devices are allocated and their resources are assigned according to the resource assignment in the Chameleon table. After resource assignment is finished, the MCB devices are registered at the MCB and thus at the driver core of the Linux kernel.

<a id="rst-resource-handling"></a>

## Resource handling

The current implementation assigns exactly one memory and one IRQ resource per MCB device. But this is likely going to change in the future.

<a id="rst-memory-resources"></a>

### Memory Resources

Each MCB device has exactly one memory resource, which can be requested from the MCB bus. This memory resource is the physical address of the MCB device inside the carrier and is intended to be passed to ioremap() and friends. It is already requested from the kernel by calling request_mem_region().

<a id="rst-irqs"></a>

### IRQs

Each MCB device has exactly one IRQ resource, which can be requested from the MCB bus. If a carrier device driver implements the -&gt;get_irq() callback method, the IRQ number assigned by the carrier device will be returned, otherwise the IRQ number inside the Chameleon table will be returned. This number is suitable to be passed to request_irq().

<a id="rst-writing-an-mcb-driver"></a>

## Writing an MCB driver

<a id="rst-the-driver-structure"></a>

### The driver structure

Each MCB driver has a structure to identify the device driver as well as device ids which identify the IP Core inside the FPGA. The driver structure also contains callback methods which get executed on driver probe and removal from the system:



```text
static const struct mcb_device_id foo_ids[] = {
        { .device = 0x123 },
        { }
};
MODULE_DEVICE_TABLE(mcb, foo_ids);

static struct mcb_driver foo_driver = {
driver = {
        .name = "foo-bar",
        .owner = THIS_MODULE,
},
        .probe = foo_probe,
        .remove = foo_remove,
        .id_table = foo_ids,
};
```

<a id="rst-probing-and-attaching"></a>

### Probing and attaching

When a driver is loaded and the MCB devices it services are found, the MCB core will call the driver's probe callback method. When the driver is removed from the system, the MCB core will call the driver's remove callback method:



```text
static init foo_probe(struct mcb_device *mdev, const struct mcb_device_id *id);
static void foo_remove(struct mcb_device *mdev);
```

<a id="rst-initializing-the-driver"></a>

### Initializing the driver

When the kernel is booted or your foo driver module is inserted, you have to perform driver initialization. Usually it is enough to register your driver module at the MCB core:



```text
static int __init foo_init(void)
{
        return mcb_register_driver(&foo_driver);
}
module_init(foo_init);

static void __exit foo_exit(void)
{
        mcb_unregister_driver(&foo_driver);
}
module_exit(foo_exit);
```

The module_mcb_driver() macro can be used to reduce the above code:



```text
module_mcb_driver(foo_driver);
```

<a id="rst-using-dma"></a>

### Using DMA

To make use of the kernel's DMA-API's function, you will need to use the carrier device's 'struct device'. Fortunately 'struct mcb_device' embeds a pointer (-&gt;dma_dev) to the carrier's device for DMA purposes:



```text
ret = dma_set_mask_and_coherent(&mdev->dma_dev, DMA_BIT_MASK(dma_bits));
if (rc)
        /* Handle errors */
```

---

# NTB Drivers

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> NTB (Non-Transparent Bridge) is a type of PCI-Express bridge chip that connects the separate memory systems of two or more computers to the same PCI-Express fabric. Existing NTB hardware supports a common feature set: doorbell registers…

<a id="rst-ntb-drivers"></a>

NTB (Non-Transparent Bridge) is a type of PCI-Express bridge chip that connects the separate memory systems of two or more computers to the same PCI-Express fabric. Existing NTB hardware supports a common feature set: doorbell registers and memory translation windows, as well as non common features like scratchpad and message registers. Scratchpad registers are read-and-writable registers that are accessible from either side of the device, so that peers can exchange a small amount of information at a fixed address. Message registers can be utilized for the same purpose. Additionally they are provided with special status bits to make sure the information isn't rewritten by another peer. Doorbell registers provide a way for peers to send interrupt events. Memory windows allow translated read and write access to the peer memory.

<a id="rst-ntb-core-driver-ntb"></a>

## NTB Core Driver (ntb)

The NTB core driver defines an api wrapping the common feature set, and allows clients interested in NTB features to discover NTB the devices supported by hardware drivers.  The term "client" is used here to mean an upper layer component making use of the NTB api.  The term "driver," or "hardware driver," is used here to mean a driver for a specific vendor and model of NTB hardware.

<a id="rst-ntb-client-drivers"></a>

## NTB Client Drivers

NTB client drivers should register with the NTB core driver.  After registering, the client probe and remove functions will be called appropriately as ntb hardware, or hardware drivers, are inserted and removed.  The registration uses the Linux Device framework, so it should feel familiar to anyone who has written a pci driver.

<a id="rst-ntb-typical-client-driver-implementation"></a>

### NTB Typical client driver implementation

Primary purpose of NTB is to share some piece of memory between at least two systems. So the NTB device features like Scratchpad/Message registers are mainly used to perform the proper memory window initialization. Typically there are two types of memory window interfaces supported by the NTB API: inbound translation configured on the local ntb port and outbound translation configured by the peer, on the peer ntb port. The first type is depicted on the next figure:



```text
Inbound translation:

Memory:              Local NTB Port:      Peer NTB Port:      Peer MMIO:
 ____________
| dma-mapped |-ntb_mw_set_trans(addr)  |
| memory     |        _v____________   |   ______________
| (addr)     |<======| MW xlat addr |<====| MW base addr |<== memory-mapped IO
|------------|       |--------------|  |  |--------------|
```

So typical scenario of the first type memory window initialization looks: 1) allocate a memory region, 2) put translated address to NTB config, 3) somehow notify a peer device of performed initialization, 4) peer device maps corresponding outbound memory window so to have access to the shared memory region.

The second type of interface, that implies the shared windows being initialized by a peer device, is depicted on the figure:



```text
Outbound translation:

Memory:        Local NTB Port:    Peer NTB Port:      Peer MMIO:
 ____________                      ______________
| dma-mapped |                |   | MW base addr |<== memory-mapped IO
| memory     |                |   |--------------|
| (addr)     |<===================| MW xlat addr |<-ntb_peer_mw_set_trans(addr)
|------------|                |   |--------------|
```

Typical scenario of the second type interface initialization would be: 1) allocate a memory region, 2) somehow deliver a translated address to a peer device, 3) peer puts the translated address to NTB config, 4) peer device maps outbound memory window so to have access to the shared memory region.

As one can see the described scenarios can be combined in one portable algorithm.

> - **Local device:**
>
>   1. Allocate memory for a shared window
>
>   2. Initialize memory window by translated address of the allocated region (it may fail if local memory window initialization is unsupported)
>
>   3. Send the translated address and memory window index to a peer device
>
> - **Peer device:**
>
>   1. Initialize memory window with retrieved address of the allocated by another device memory region (it may fail if peer memory window initialization is unsupported)
>
>   2. Map outbound memory window

In accordance with this scenario, the NTB Memory Window API can be used as follows:

> - **Local device:**
>
>   1. ntb_mw_count(pidx) - retrieve number of memory ranges, which can be allocated for memory windows between local device and peer device of port with specified index.
>
>   2. ntb_get_align(pidx, midx) - retrieve parameters restricting the shared memory region alignment and size. Then memory can be properly allocated.
>
>   3. Allocate physically contiguous memory region in compliance with restrictions retrieved in 2).
>
>   4. ntb_mw_set_trans(pidx, midx) - try to set translation address of the memory window with specified index for the defined peer device (it may fail if local translated address setting is not supported)
>
>   5. Send translated base address (usually together with memory window number) to the peer device using, for instance, scratchpad or message registers.
>
> - **Peer device:**
>
>   1. ntb_peer_mw_set_trans(pidx, midx) - try to set received from other device (related to pidx) translated address for specified memory window. It may fail if retrieved address, for instance, exceeds maximum possible address or isn't properly aligned.
>
>   2. ntb_peer_mw_get_addr(widx) - retrieve MMIO address to map the memory window so to have an access to the shared memory.

Also it is worth to note, that method ntb_mw_count(pidx) should return the same value as ntb_peer_mw_count() on the peer with port index - pidx.

<a id="rst-ntb-transport-client-ntb-transport-and-ntb-netdev-ntb-netdev"></a>

### NTB Transport Client (ntb_transport) and NTB Netdev (ntb_netdev)

The primary client for NTB is the Transport client, used in tandem with NTB Netdev.  These drivers function together to create a logical link to the peer, across the ntb, to exchange packets of network data.  The Transport client establishes a logical link to the peer, and creates queue pairs to exchange messages and data.  The NTB Netdev then creates an ethernet device using a Transport queue pair.  Network data is copied between socket buffers and the Transport queue pair buffer.  The Transport client may be used for other things besides Netdev, however no other applications have yet been written.

<a id="rst-ntb-ping-pong-test-client-ntb-pingpong"></a>

### NTB Ping Pong Test Client (ntb_pingpong)

The Ping Pong test client serves as a demonstration to exercise the doorbell and scratchpad registers of NTB hardware, and as an example simple NTB client. Ping Pong enables the link when started, waits for the NTB link to come up, and then proceeds to read and write the doorbell scratchpad registers of the NTB. The peers interrupt each other using a bit mask of doorbell bits, which is shifted by one in each round, to test the behavior of multiple doorbell bits and interrupt vectors.  The Ping Pong driver also reads the first local scratchpad, and writes the value plus one to the first peer scratchpad, each round before writing the peer doorbell register.

Module Parameters:

- - **unsafe - Some hardware has known issues with scratchpad and doorbell**

    registers.  By default, Ping Pong will not attempt to exercise such hardware.  You may override this behavior at your own risk by setting unsafe=1.

- - **delay_ms - Specify the delay between receiving a doorbell**

    interrupt event and setting the peer doorbell register for the next round.

- - **init_db - Specify the doorbell bits to start new series of rounds.  A new**

    series begins once all the doorbell bits have been shifted out of range.

- - **dyndbg - It is suggested to specify dyndbg=+p when loading this module, and**

    then to observe debugging output on the console.

<a id="rst-ntb-tool-test-client-ntb-tool"></a>

### NTB Tool Test Client (ntb_tool)

The Tool test client serves for debugging, primarily, ntb hardware and drivers. The Tool provides access through debugfs for reading, setting, and clearing the NTB doorbell, and reading and writing scratchpads.

The Tool does not currently have any module parameters.

Debugfs Files:

- - ***debugfs*/ntb_tool/*hw*/**

    A directory in debugfs will be created for each NTB device probed by the tool.  This directory is shortened to *hw* below.

- - ***hw*/db**

    This file is used to read, set, and clear the local doorbell.  Not all operations may be supported by all hardware.  To read the doorbell, read the file.  To set the doorbell, write `s` followed by the bits to set (eg: `echo 's 0x0101' > db`).  To clear the doorbell, write `c` followed by the bits to clear.

- - ***hw*/mask**

    This file is used to read, set, and clear the local doorbell mask. See *db* for details.

- - ***hw*/peer_db**

    This file is used to read, set, and clear the peer doorbell. See *db* for details.

- - ***hw*/peer_mask**

    This file is used to read, set, and clear the peer doorbell mask.  See *db* for details.

- - ***hw*/spad**

    This file is used to read and write local scratchpads.  To read the values of all scratchpads, read the file.  To write values, write a series of pairs of scratchpad number and value (eg: `echo '4 0x123 7 0xabc' > spad` \# to set scratchpads `4` and `7` to `0x123` and `0xabc`, respectively).

- - ***hw*/peer_spad**

    This file is used to read and write peer scratchpads.  See *spad* for details.

<a id="rst-ntb-msi-test-client-ntb-msi-test"></a>

### NTB MSI Test Client (ntb_msi_test)

The MSI test client serves to test and debug the MSI library which allows for passing MSI interrupts across NTB memory windows. The test client is interacted with through the debugfs filesystem:

- - ***debugfs*/ntb_msi_test/*hw*/**

    A directory in debugfs will be created for each NTB device probed by the msi test.  This directory is shortened to *hw* below.

- - ***hw*/port**

    This file describes the local port number

- - ***hw*/irq\*\_occurrences**

    One occurrences file exists for each interrupt and, when read, returns the number of times the interrupt has been triggered.

- - ***hw*/peer\*/port**

    This file describes the port number for each peer

- - ***hw*/peer\*/count**

    This file describes the number of interrupts that can be triggered on each peer

- - ***hw*/peer\*/trigger**

    Writing an interrupt number (any number less than the value specified in count) will trigger the interrupt on the specified peer. That peer's interrupt's occurrence file should be incremented.

<a id="rst-ntb-hardware-drivers"></a>

## NTB Hardware Drivers

NTB hardware drivers should register devices with the NTB core driver.  After registering, clients probe and remove functions will be called.

<a id="rst-ntb-intel-hardware-driver-ntb-hw-intel"></a>

### NTB Intel Hardware Driver (ntb_hw_intel)

The Intel hardware driver supports NTB on Xeon and Atom CPUs.

Module Parameters:

- - **b2b_mw_idx**

    If the peer ntb is to be accessed via a memory window, then use this memory window to access the peer ntb.  A value of zero or positive starts from the first mw idx, and a negative value starts from the last mw idx.  Both sides MUST set the same value here\!  The default value is `-1`.

- - **b2b_mw_share**

    If the peer ntb is to be accessed via a memory window, and if the memory window is large enough, still allow the client to use the second half of the memory window for address translation to the peer.

- - **xeon_b2b_usd_bar2_addr64**

    If using B2B topology on Xeon hardware, use this 64 bit address on the bus between the NTB devices for the window at BAR2, on the upstream side of the link.

- xeon_b2b_usd_bar4_addr64 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_usd_bar4_addr32 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_usd_bar5_addr32 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_dsd_bar2_addr64 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_dsd_bar4_addr64 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_dsd_bar4_addr32 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_dsd_bar5_addr32 - See *xeon_b2b_bar2_addr64*.

---

# PARPORT interface documentation

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> Described here are the following functions:

<a id="rst-parport-interface-documentation"></a>

**Time-stamp:** &lt;2000-02-24 13:30:20 twaugh&gt;

Described here are the following functions:

Global functions:



```text
parport_register_driver
parport_unregister_driver
parport_enumerate
parport_register_device
parport_unregister_device
parport_claim
parport_claim_or_block
parport_release
parport_yield
parport_yield_blocking
parport_wait_peripheral
parport_poll_peripheral
parport_wait_event
parport_negotiate
parport_read
parport_write
parport_open
parport_close
parport_device_id
parport_device_coords
parport_find_class
parport_find_device
parport_set_timeout
```

Port functions (can be overridden by low-level drivers):

> SPP:
>
>
>
> ```text
> port->ops->read_data
> port->ops->write_data
> port->ops->read_status
> port->ops->read_control
> port->ops->write_control
> port->ops->frob_control
> port->ops->enable_irq
> port->ops->disable_irq
> port->ops->data_forward
> port->ops->data_reverse
> ```
>
> EPP:
>
>
>
> ```text
> port->ops->epp_write_data
> port->ops->epp_read_data
> port->ops->epp_write_addr
> port->ops->epp_read_addr
> ```
>
> ECP:
>
>
>
> ```text
> port->ops->ecp_write_data
> port->ops->ecp_read_data
> port->ops->ecp_write_addr
> ```
>
> Other:
>
>
>
> ```text
> port->ops->nibble_read_data
> port->ops->byte_read_data
> port->ops->compat_write_data
> ```

The parport subsystem comprises `parport` (the core port-sharing code), and a variety of low-level drivers that actually do the port accesses.  Each low-level driver handles a particular style of port (PC, Amiga, and so on).

The parport interface to the device driver author can be broken down into global functions and port functions.

The global functions are mostly for communicating between the device driver and the parport subsystem: acquiring a list of available ports, claiming a port for exclusive use, and so on.  They also include `generic` functions for doing standard things that will work on any IEEE 1284-capable architecture.

The port functions are provided by the low-level drivers, although the core parport module provides generic `defaults` for some routines. The port functions can be split into three groups: SPP, EPP, and ECP.

SPP (Standard Parallel Port) functions modify so-called `SPP` registers: data, status, and control.  The hardware may not actually have registers exactly like that, but the PC does and this interface is modelled after common PC implementations.  Other low-level drivers may be able to emulate most of the functionality.

EPP (Enhanced Parallel Port) functions are provided for reading and writing in IEEE 1284 EPP mode, and ECP (Extended Capabilities Port) functions are used for IEEE 1284 ECP mode. (What about BECP? Does anyone care?)

Hardware assistance for EPP and/or ECP transfers may or may not be available, and if it is available it may or may not be used.  If hardware is not used, the transfer will be software-driven.  In order to cope with peripherals that only tenuously support IEEE 1284, a low-level driver specific function is provided, for altering 'fudge factors'.

<a id="rst-global-functions"></a>

## Global functions

<a id="rst-parport-register-driver-register-a-device-driver-with-parport"></a>

### parport_register_driver - register a device driver with parport

<a id="rst-synopsis"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_driver {
        const char *name;
        void (*attach) (struct parport *);
        void (*detach) (struct parport *);
        struct parport_driver *next;
};
int parport_register_driver (struct parport_driver *driver);
```

<a id="rst-description"></a>

#### DESCRIPTION

In order to be notified about parallel ports when they are detected, parport_register_driver should be called.  Your driver will immediately be notified of all ports that have already been detected, and of each new port as low-level drivers are loaded.

A `struct parport_driver` contains the textual name of your driver, a pointer to a function to handle new ports, and a pointer to a function to handle ports going away due to a low-level driver unloading.  Ports will only be detached if they are not being used (i.e. there are no devices registered on them).

The visible parts of the `struct parport *` argument given to attach/detach are:



```text
struct parport
{
        struct parport *next; /* next parport in list */
        const char *name;     /* port's name */
        unsigned int modes;   /* bitfield of hardware modes */
        struct parport_device_info probe_info;
                        /* IEEE1284 info */
        int number;           /* parport index */
        struct parport_operations *ops;
        ...
};
```

There are other members of the structure, but they should not be touched.

The `modes` member summarises the capabilities of the underlying hardware.  It consists of flags which may be bitwise-ored together:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> PARPORT_MODE_PCSPP
>
> </td>
> <td>
>
>
> IBM PC registers are available, i.e. functions that act on data, control and status registers are probably writing directly to the hardware.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_TRISTATE
>
> </td>
> <td>
>
>
> The data drivers may be turned off. This allows the data lines to be used for reverse (peripheral to host) transfers.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_COMPAT
>
> </td>
> <td>
>
>
> The hardware can assist with compatibility-mode (printer) transfers, i.e. compat_write_block.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_EPP
>
> </td>
> <td>
>
>
> The hardware can assist with EPP transfers.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_ECP
>
> </td>
> <td>
>
>
> The hardware can assist with ECP transfers.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_DMA
>
> </td>
> <td>
>
>
> The hardware can use DMA, so you might want to pass ISA DMA-able memory (i.e. memory allocated using the GFP_DMA flag with kmalloc) to the low-level driver in order to take advantage of it.
>
> </td>
> </tr>
> </tbody>
> </table>

There may be other flags in `modes` as well.

The contents of `modes` is advisory only.  For example, if the hardware is capable of DMA, and PARPORT_MODE_DMA is in `modes`, it doesn't necessarily mean that DMA will always be used when possible. Similarly, hardware that is capable of assisting ECP transfers won't necessarily be used.

<a id="rst-return-value"></a>

#### RETURN VALUE

Zero on success, otherwise an error code.

<a id="rst-errors"></a>

#### ERRORS

None. (Can it fail? Why return int?)

<a id="rst-example"></a>

#### EXAMPLE



```text
static void lp_attach (struct parport *port)
{
        ...
        private = kmalloc (...);
        dev[count++] = parport_register_device (...);
        ...
}

static void lp_detach (struct parport *port)
{
        ...
}

static struct parport_driver lp_driver = {
        "lp",
        lp_attach,
        lp_detach,
        NULL /* always put NULL here */
};

int lp_init (void)
{
        ...
        if (parport_register_driver (&lp_driver)) {
                /* Failed; nothing we can do. */
                return -EIO;
        }
        ...
}
```

<a id="rst-see-also"></a>

#### SEE ALSO

parport_unregister_driver, parport_register_device, parport_enumerate

<a id="rst-parport-unregister-driver-tell-parport-to-forget-about-this-driver"></a>

### parport_unregister_driver - tell parport to forget about this driver

<a id="rst-synopsis-1"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_driver {
        const char *name;
        void (*attach) (struct parport *);
        void (*detach) (struct parport *);
        struct parport_driver *next;
};
void parport_unregister_driver (struct parport_driver *driver);
```

<a id="rst-description-1"></a>

#### DESCRIPTION

This tells parport not to notify the device driver of new ports or of ports going away.  Registered devices belonging to that driver are NOT unregistered: parport_unregister_device must be used for each one.

<a id="rst-example-1"></a>

#### EXAMPLE



```text
void cleanup_module (void)
{
        ...
        /* Stop notifications. */
        parport_unregister_driver (&lp_driver);

        /* Unregister devices. */
        for (i = 0; i < NUM_DEVS; i++)
                parport_unregister_device (dev[i]);
        ...
}
```

<a id="rst-see-also-1"></a>

#### SEE ALSO

parport_register_driver, parport_enumerate

<a id="rst-parport-enumerate-retrieve-a-list-of-parallel-ports-deprecated"></a>

### parport_enumerate - retrieve a list of parallel ports (DEPRECATED)

<a id="rst-synopsis-2"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport *parport_enumerate (void);
```

<a id="rst-description-2"></a>

#### DESCRIPTION

Retrieve the first of a list of valid parallel ports for this machine. Successive parallel ports can be found using the `struct parport *next` element of the `struct parport *` that is returned.  If `next` is NULL, there are no more parallel ports in the list.  The number of ports in the list will not exceed PARPORT_MAX.

<a id="rst-return-value-1"></a>

#### RETURN VALUE

A `struct parport *` describing a valid parallel port for the machine, or NULL if there are none.

<a id="rst-errors-1"></a>

#### ERRORS

This function can return NULL to indicate that there are no parallel ports to use.

<a id="rst-example-2"></a>

#### EXAMPLE



```text
int detect_device (void)
{
        struct parport *port;

        for (port = parport_enumerate ();
        port != NULL;
        port = port->next) {
                /* Try to detect a device on the port... */
                ...
        }
        }

        ...
}
```

<a id="rst-notes"></a>

#### NOTES

parport_enumerate is deprecated; parport_register_driver should be used instead.

<a id="rst-see-also-2"></a>

#### SEE ALSO

parport_register_driver, parport_unregister_driver

<a id="rst-parport-register-device-register-to-use-a-port"></a>

### parport_register_device - register to use a port

<a id="rst-synopsis-3"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

typedef int (*preempt_func) (void *handle);
typedef void (*wakeup_func) (void *handle);
typedef int (*irq_func) (int irq, void *handle, struct pt_regs *);

struct pardevice *parport_register_device(struct parport *port,
                                          const char *name,
                                          preempt_func preempt,
                                          wakeup_func wakeup,
                                          irq_func irq,
                                          int flags,
                                          void *handle);
```

<a id="rst-description-3"></a>

#### DESCRIPTION

Use this function to register your device driver on a parallel port (`port`).  Once you have done that, you will be able to use parport_claim and parport_release in order to use the port.

The (`name`) argument is the name of the device that appears in /proc filesystem. The string must be valid for the whole lifetime of the device (until parport_unregister_device is called).

This function will register three callbacks into your driver: `preempt`, `wakeup` and `irq`.  Each of these may be NULL in order to indicate that you do not want a callback.

When the `preempt` function is called, it is because another driver wishes to use the parallel port.  The `preempt` function should return non-zero if the parallel port cannot be released yet -- if zero is returned, the port is lost to another driver and the port must be re-claimed before use.

The `wakeup` function is called once another driver has released the port and no other driver has yet claimed it.  You can claim the parallel port from within the `wakeup` function (in which case the claim is guaranteed to succeed), or choose not to if you don't need it now.

If an interrupt occurs on the parallel port your driver has claimed, the `irq` function will be called. (Write something about shared interrupts here.)

The `handle` is a pointer to driver-specific data, and is passed to the callback functions.

`flags` may be a bitwise combination of the following flags:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Flag
>
> </th>
> <th>
>
>
> Meaning
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> PARPORT_DEV_EXCL
>
> </td>
> <td>
>
>
> The device cannot share the parallel port at all. Use this only when absolutely necessary.
>
> </td>
> </tr>
> </tbody>
> </table>

The typedefs are not actually defined -- they are only shown in order to make the function prototype more readable.

The visible parts of the returned `struct pardevice` are:



```text
struct pardevice {
        struct parport *port;   /* Associated port */
        void *private;          /* Device driver's 'handle' */
        ...
};
```

<a id="rst-return-value-2"></a>

#### RETURN VALUE

A `struct pardevice *`: a handle to the registered parallel port device that can be used for parport_claim, parport_release, etc.

<a id="rst-errors-2"></a>

#### ERRORS

A return value of NULL indicates that there was a problem registering a device on that port.

<a id="rst-example-3"></a>

#### EXAMPLE



```text
static int preempt (void *handle)
{
        if (busy_right_now)
                return 1;

        must_reclaim_port = 1;
        return 0;
}

static void wakeup (void *handle)
{
        struct toaster *private = handle;
        struct pardevice *dev = private->dev;
        if (!dev) return; /* avoid races */

        if (want_port)
                parport_claim (dev);
}

static int toaster_detect (struct toaster *private, struct parport *port)
{
        private->dev = parport_register_device (port, "toaster", preempt,
                                                wakeup, NULL, 0,
                                                private);
        if (!private->dev)
                /* Couldn't register with parport. */
                return -EIO;

        must_reclaim_port = 0;
        busy_right_now = 1;
        parport_claim_or_block (private->dev);
        ...
        /* Don't need the port while the toaster warms up. */
        busy_right_now = 0;
        ...
        busy_right_now = 1;
        if (must_reclaim_port) {
                parport_claim_or_block (private->dev);
                must_reclaim_port = 0;
        }
        ...
}
```

<a id="rst-see-also-3"></a>

#### SEE ALSO

parport_unregister_device, parport_claim

<a id="rst-parport-unregister-device-finish-using-a-port"></a>

### parport_unregister_device - finish using a port

SYNPOPSIS



```text
#include <linux/parport.h>

void parport_unregister_device (struct pardevice *dev);
```

<a id="rst-description-4"></a>

#### DESCRIPTION

This function is the opposite of parport_register_device.  After using parport_unregister_device, `dev` is no longer a valid device handle.

You should not unregister a device that is currently claimed, although if you do it will be released automatically.

<a id="rst-example-4"></a>

#### EXAMPLE



```text
...
kfree (dev->private); /* before we lose the pointer */
parport_unregister_device (dev);
...
```

<a id="rst-see-also-4"></a>

#### SEE ALSO

parport_unregister_driver

<a id="rst-parport-claim-parport-claim-or-block-claim-the-parallel-port-for-a-device"></a>

### parport_claim, parport_claim_or_block - claim the parallel port for a device

<a id="rst-synopsis-4"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_claim (struct pardevice *dev);
int parport_claim_or_block (struct pardevice *dev);
```

<a id="rst-description-5"></a>

#### DESCRIPTION

These functions attempt to gain control of the parallel port on which `dev` is registered.  `parport_claim` does not block, but `parport_claim_or_block` may do. (Put something here about blocking interruptibly or non-interruptibly.)

You should not try to claim a port that you have already claimed.

<a id="rst-return-value-3"></a>

#### RETURN VALUE

A return value of zero indicates that the port was successfully claimed, and the caller now has possession of the parallel port.

If `parport_claim_or_block` blocks before returning successfully, the return value is positive.

<a id="rst-errors-3"></a>

#### ERRORS


<table>
<tbody>
<tr>
<td>


-EAGAIN

</td>
<td>


The port is unavailable at the moment, but another attempt to claim it may succeed.

</td>
</tr>
</tbody>
</table>

<a id="rst-see-also-5"></a>

#### SEE ALSO

parport_release

<a id="rst-parport-release-release-the-parallel-port"></a>

### parport_release - release the parallel port

<a id="rst-synopsis-5"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

void parport_release (struct pardevice *dev);
```

<a id="rst-description-6"></a>

#### DESCRIPTION

Once a parallel port device has been claimed, it can be released using `parport_release`.  It cannot fail, but you should not release a device that you do not have possession of.

<a id="rst-example-5"></a>

#### EXAMPLE



```text
static size_t write (struct pardevice *dev, const void *buf,
                size_t len)
{
        ...
        written = dev->port->ops->write_ecp_data (dev->port, buf,
                                                len);
        parport_release (dev);
        ...
}
```

<a id="rst-see-also-6"></a>

#### SEE ALSO

change_mode, parport_claim, parport_claim_or_block, parport_yield

<a id="rst-parport-yield-parport-yield-blocking-temporarily-release-a-parallel-port"></a>

### parport_yield, parport_yield_blocking - temporarily release a parallel port

<a id="rst-synopsis-6"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_yield (struct pardevice *dev)
int parport_yield_blocking (struct pardevice *dev);
```

<a id="rst-description-7"></a>

#### DESCRIPTION

When a driver has control of a parallel port, it may allow another driver to temporarily `borrow` it.  `parport_yield` does not block; `parport_yield_blocking` may do.

<a id="rst-return-value-4"></a>

#### RETURN VALUE

A return value of zero indicates that the caller still owns the port and the call did not block.

A positive return value from `parport_yield_blocking` indicates that the caller still owns the port and the call blocked.

A return value of -EAGAIN indicates that the caller no longer owns the port, and it must be re-claimed before use.

<a id="rst-errors-4"></a>

#### ERRORS


<table>
<tbody>
<tr>
<td>


-EAGAIN

</td>
<td>


Ownership of the parallel port was given away.

</td>
</tr>
</tbody>
</table>

<a id="rst-see-also-7"></a>

#### SEE ALSO

parport_release

<a id="rst-parport-wait-peripheral-wait-for-status-lines-up-to-35ms"></a>

### parport_wait_peripheral - wait for status lines, up to 35ms

<a id="rst-synopsis-7"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_wait_peripheral (struct parport *port,
                             unsigned char mask,
                             unsigned char val);
```

<a id="rst-description-8"></a>

#### DESCRIPTION

Wait for the status lines in mask to match the values in val.

<a id="rst-return-value-5"></a>

#### RETURN VALUE


<table>
<tbody>
<tr>
<td>


-EINTR

</td>
<td>


a signal is pending

</td>
</tr>
<tr>
<td>


0

</td>
<td>


the status lines in mask have values in val

</td>
</tr>
<tr>
<td>


1

</td>
<td>


timed out while waiting (35ms elapsed)

</td>
</tr>
</tbody>
</table>

<a id="rst-see-also-8"></a>

#### SEE ALSO

parport_poll_peripheral

<a id="rst-parport-poll-peripheral-wait-for-status-lines-in-usec"></a>

### parport_poll_peripheral - wait for status lines, in usec

<a id="rst-synopsis-8"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_poll_peripheral (struct parport *port,
                             unsigned char mask,
                             unsigned char val,
                             int usec);
```

<a id="rst-description-9"></a>

#### DESCRIPTION

Wait for the status lines in mask to match the values in val.

<a id="rst-return-value-6"></a>

#### RETURN VALUE


<table>
<tbody>
<tr>
<td>


-EINTR

</td>
<td>


a signal is pending

</td>
</tr>
<tr>
<td>


0

</td>
<td>


the status lines in mask have values in val

</td>
</tr>
<tr>
<td>


1

</td>
<td>


timed out while waiting (usec microseconds have elapsed)

</td>
</tr>
</tbody>
</table>

<a id="rst-see-also-9"></a>

#### SEE ALSO

parport_wait_peripheral

<a id="rst-parport-wait-event-wait-for-an-event-on-a-port"></a>

### parport_wait_event - wait for an event on a port

<a id="rst-synopsis-9"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_wait_event (struct parport *port, signed long timeout)
```

<a id="rst-description-10"></a>

#### DESCRIPTION

Wait for an event (e.g. interrupt) on a port.  The timeout is in jiffies.

<a id="rst-return-value-7"></a>

#### RETURN VALUE


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


success

</td>
</tr>
<tr>
<td>


&lt;0

</td>
<td>


error (exit as soon as possible)

</td>
</tr>
<tr>
<td>


&gt;0

</td>
<td>


timed out

</td>
</tr>
</tbody>
</table>

<a id="rst-parport-negotiate-perform-ieee-1284-negotiation"></a>

### parport_negotiate - perform IEEE 1284 negotiation

<a id="rst-synopsis-10"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_negotiate (struct parport *, int mode);
```

<a id="rst-description-11"></a>

#### DESCRIPTION

Perform IEEE 1284 negotiation.

<a id="rst-return-value-8"></a>

#### RETURN VALUE


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


handshake OK; IEEE 1284 peripheral and mode available

</td>
</tr>
<tr>
<td>


-1

</td>
<td>


handshake failed; peripheral not compliant (or none present)

</td>
</tr>
<tr>
<td>


1

</td>
<td>


handshake OK; IEEE 1284 peripheral present but mode not available

</td>
</tr>
</tbody>
</table>

<a id="rst-see-also-10"></a>

#### SEE ALSO

parport_read, parport_write

<a id="rst-parport-read-read-data-from-device"></a>

### parport_read - read data from device

<a id="rst-synopsis-11"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

ssize_t parport_read (struct parport *, void *buf, size_t len);
```

<a id="rst-description-12"></a>

#### DESCRIPTION

Read data from device in current IEEE 1284 transfer mode.  This only works for modes that support reverse data transfer.

<a id="rst-return-value-9"></a>

#### RETURN VALUE

If negative, an error code; otherwise the number of bytes transferred.

<a id="rst-see-also-11"></a>

#### SEE ALSO

parport_write, parport_negotiate

<a id="rst-parport-write-write-data-to-device"></a>

### parport_write - write data to device

<a id="rst-synopsis-12"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

ssize_t parport_write (struct parport *, const void *buf, size_t len);
```

<a id="rst-description-13"></a>

#### DESCRIPTION

Write data to device in current IEEE 1284 transfer mode.  This only works for modes that support forward data transfer.

<a id="rst-return-value-10"></a>

#### RETURN VALUE

If negative, an error code; otherwise the number of bytes transferred.

<a id="rst-see-also-12"></a>

#### SEE ALSO

parport_read, parport_negotiate

<a id="rst-parport-open-register-device-for-particular-device-number"></a>

### parport_open - register device for particular device number

<a id="rst-synopsis-13"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct pardevice *parport_open (int devnum, const char *name,
                                int (*pf) (void *),
                                void (*kf) (void *),
                                void (*irqf) (int, void *,
                                              struct pt_regs *),
                                int flags, void *handle);
```

<a id="rst-description-14"></a>

#### DESCRIPTION

This is like parport_register_device but takes a device number instead of a pointer to a struct parport.

<a id="rst-return-value-11"></a>

#### RETURN VALUE

See parport_register_device.  If no device is associated with devnum, NULL is returned.

<a id="rst-see-also-13"></a>

#### SEE ALSO

parport_register_device

<a id="rst-parport-close-unregister-device-for-particular-device-number"></a>

### parport_close - unregister device for particular device number

<a id="rst-synopsis-14"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

void parport_close (struct pardevice *dev);
```

<a id="rst-description-15"></a>

#### DESCRIPTION

This is the equivalent of parport_unregister_device for parport_open.

<a id="rst-see-also-14"></a>

#### SEE ALSO

parport_unregister_device, parport_open

<a id="rst-parport-device-id-obtain-ieee-1284-device-id"></a>

### parport_device_id - obtain IEEE 1284 Device ID

<a id="rst-synopsis-15"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

ssize_t parport_device_id (int devnum, char *buffer, size_t len);
```

<a id="rst-description-16"></a>

#### DESCRIPTION

Obtains the IEEE 1284 Device ID associated with a given device.

<a id="rst-return-value-12"></a>

#### RETURN VALUE

If negative, an error code; otherwise, the number of bytes of buffer that contain the device ID.  The format of the device ID is as follows:



```text
[length][ID]
```

The first two bytes indicate the inclusive length of the entire Device ID, and are in big-endian order.  The ID is a sequence of pairs of the form:



```text
key:value;
```

<a id="rst-notes-1"></a>

#### NOTES

Many devices have ill-formed IEEE 1284 Device IDs.

<a id="rst-see-also-15"></a>

#### SEE ALSO

parport_find_class, parport_find_device

<a id="rst-parport-device-coords-convert-device-number-to-device-coordinates"></a>

### parport_device_coords - convert device number to device coordinates

<a id="rst-synopsis-16"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_device_coords (int devnum, int *parport, int *mux,
                           int *daisy);
```

<a id="rst-description-17"></a>

#### DESCRIPTION

Convert between device number (zero-based) and device coordinates (port, multiplexor, daisy chain address).

<a id="rst-return-value-13"></a>

#### RETURN VALUE

Zero on success, in which case the coordinates are (`*parport`, `*mux`, `*daisy`).

<a id="rst-see-also-16"></a>

#### SEE ALSO

parport_open, parport_device_id

<a id="rst-parport-find-class-find-a-device-by-its-class"></a>

### parport_find_class - find a device by its class

<a id="rst-synopsis-17"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

typedef enum {
        PARPORT_CLASS_LEGACY = 0,       /* Non-IEEE1284 device */
        PARPORT_CLASS_PRINTER,
        PARPORT_CLASS_MODEM,
        PARPORT_CLASS_NET,
        PARPORT_CLASS_HDC,              /* Hard disk controller */
        PARPORT_CLASS_PCMCIA,
        PARPORT_CLASS_MEDIA,            /* Multimedia device */
        PARPORT_CLASS_FDC,              /* Floppy disk controller */
        PARPORT_CLASS_PORTS,
        PARPORT_CLASS_SCANNER,
        PARPORT_CLASS_DIGCAM,
        PARPORT_CLASS_OTHER,            /* Anything else */
        PARPORT_CLASS_UNSPEC,           /* No CLS field in ID */
        PARPORT_CLASS_SCSIADAPTER
} parport_device_class;

int parport_find_class (parport_device_class cls, int from);
```

<a id="rst-description-18"></a>

#### DESCRIPTION

Find a device by class.  The search starts from device number from+1.

<a id="rst-return-value-14"></a>

#### RETURN VALUE

The device number of the next device in that class, or -1 if no such device exists.

<a id="rst-notes-2"></a>

#### NOTES

Example usage:



```text
int devnum = -1;
while ((devnum = parport_find_class (PARPORT_CLASS_DIGCAM, devnum)) != -1) {
        struct pardevice *dev = parport_open (devnum, ...);
        ...
}
```

<a id="rst-see-also-17"></a>

#### SEE ALSO

parport_find_device, parport_open, parport_device_id

<a id="rst-parport-find-device-find-a-device-by-its-class"></a>

### parport_find_device - find a device by its class

<a id="rst-synopsis-18"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_find_device (const char *mfg, const char *mdl, int from);
```

<a id="rst-description-19"></a>

#### DESCRIPTION

Find a device by vendor and model.  The search starts from device number from+1.

<a id="rst-return-value-15"></a>

#### RETURN VALUE

The device number of the next device matching the specifications, or -1 if no such device exists.

<a id="rst-notes-3"></a>

#### NOTES

Example usage:



```text
int devnum = -1;
while ((devnum = parport_find_device ("IOMEGA", "ZIP+", devnum)) != -1) {
        struct pardevice *dev = parport_open (devnum, ...);
        ...
}
```

<a id="rst-see-also-18"></a>

#### SEE ALSO

parport_find_class, parport_open, parport_device_id

<a id="rst-parport-set-timeout-set-the-inactivity-timeout"></a>

### parport_set_timeout - set the inactivity timeout

<a id="rst-synopsis-19"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

long parport_set_timeout (struct pardevice *dev, long inactivity);
```

<a id="rst-description-20"></a>

#### DESCRIPTION

Set the inactivity timeout, in jiffies, for a registered device.  The previous timeout is returned.

<a id="rst-return-value-16"></a>

#### RETURN VALUE

The previous timeout, in jiffies.

<a id="rst-notes-4"></a>

#### NOTES

Some of the port-&gt;ops functions for a parport may take time, owing to delays at the peripheral.  After the peripheral has not responded for `inactivity` jiffies, a timeout will occur and the blocking function will return.

A timeout of 0 jiffies is a special case: the function must do as much as it can without blocking or leaving the hardware in an unknown state.  If port operations are performed from within an interrupt handler, for instance, a timeout of 0 jiffies should be used.

Once set for a registered device, the timeout will remain at the set value until set again.

<a id="rst-see-also-19"></a>

#### SEE ALSO

port-&gt;ops-&gt;xxx_read/write_yyy

<a id="rst-port-functions"></a>

## PORT FUNCTIONS

The functions in the port-&gt;ops structure (struct parport_operations) are provided by the low-level driver responsible for that port.

<a id="rst-port-ops-read-data-read-the-data-register"></a>

### port-&gt;ops-&gt;read_data - read the data register

<a id="rst-synopsis-20"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        unsigned char (*read_data) (struct parport *port);
        ...
};
```

<a id="rst-description-21"></a>

#### DESCRIPTION

If port-&gt;modes contains the PARPORT_MODE_TRISTATE flag and the PARPORT_CONTROL_DIRECTION bit in the control register is set, this returns the value on the data pins.  If port-&gt;modes contains the PARPORT_MODE_TRISTATE flag and the PARPORT_CONTROL_DIRECTION bit is not set, the return value \_may\_ be the last value written to the data register.  Otherwise the return value is undefined.

<a id="rst-see-also-20"></a>

#### SEE ALSO

write_data, read_status, write_control

<a id="rst-port-ops-write-data-write-the-data-register"></a>

### port-&gt;ops-&gt;write_data - write the data register

<a id="rst-synopsis-21"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*write_data) (struct parport *port, unsigned char d);
        ...
};
```

<a id="rst-description-22"></a>

#### DESCRIPTION

Writes to the data register.  May have side-effects (a STROBE pulse, for instance).

<a id="rst-see-also-21"></a>

#### SEE ALSO

read_data, read_status, write_control

<a id="rst-port-ops-read-status-read-the-status-register"></a>

### port-&gt;ops-&gt;read_status - read the status register

<a id="rst-synopsis-22"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        unsigned char (*read_status) (struct parport *port);
        ...
};
```

<a id="rst-description-23"></a>

#### DESCRIPTION

Reads from the status register.  This is a bitmask:

- PARPORT_STATUS_ERROR (printer fault, "nFault")

- PARPORT_STATUS_SELECT (on-line, "Select")

- PARPORT_STATUS_PAPEROUT (no paper, "PError")

- PARPORT_STATUS_ACK (handshake, "nAck")

- PARPORT_STATUS_BUSY (busy, "Busy")

There may be other bits set.

<a id="rst-see-also-22"></a>

#### SEE ALSO

read_data, write_data, write_control

<a id="rst-port-ops-read-control-read-the-control-register"></a>

### port-&gt;ops-&gt;read_control - read the control register

<a id="rst-synopsis-23"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        unsigned char (*read_control) (struct parport *port);
        ...
};
```

<a id="rst-description-24"></a>

#### DESCRIPTION

Returns the last value written to the control register (either from write_control or frob_control).  No port access is performed.

<a id="rst-see-also-23"></a>

#### SEE ALSO

read_data, write_data, read_status, write_control

<a id="rst-port-ops-write-control-write-the-control-register"></a>

### port-&gt;ops-&gt;write_control - write the control register

<a id="rst-synopsis-24"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*write_control) (struct parport *port, unsigned char s);
        ...
};
```

<a id="rst-description-25"></a>

#### DESCRIPTION

Writes to the control register. This is a bitmask:



```text
                          _______
- PARPORT_CONTROL_STROBE (nStrobe)
                          _______
- PARPORT_CONTROL_AUTOFD (nAutoFd)
                        _____
- PARPORT_CONTROL_INIT (nInit)
                          _________
- PARPORT_CONTROL_SELECT (nSelectIn)
```

<a id="rst-see-also-24"></a>

#### SEE ALSO

read_data, write_data, read_status, frob_control

<a id="rst-port-ops-frob-control-write-control-register-bits"></a>

### port-&gt;ops-&gt;frob_control - write control register bits

<a id="rst-synopsis-25"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        unsigned char (*frob_control) (struct parport *port,
                                unsigned char mask,
                                unsigned char val);
        ...
};
```

<a id="rst-description-26"></a>

#### DESCRIPTION

This is equivalent to reading from the control register, masking out the bits in mask, exclusive-or'ing with the bits in val, and writing the result to the control register.

As some ports don't allow reads from the control port, a software copy of its contents is maintained, so frob_control is in fact only one port access.

<a id="rst-see-also-25"></a>

#### SEE ALSO

read_data, write_data, read_status, write_control

<a id="rst-port-ops-enable-irq-enable-interrupt-generation"></a>

### port-&gt;ops-&gt;enable_irq - enable interrupt generation

<a id="rst-synopsis-26"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*enable_irq) (struct parport *port);
        ...
};
```

<a id="rst-description-27"></a>

#### DESCRIPTION

The parallel port hardware is instructed to generate interrupts at appropriate moments, although those moments are architecture-specific.  For the PC architecture, interrupts are commonly generated on the rising edge of nAck.

<a id="rst-see-also-26"></a>

#### SEE ALSO

disable_irq

<a id="rst-port-ops-disable-irq-disable-interrupt-generation"></a>

### port-&gt;ops-&gt;disable_irq - disable interrupt generation

<a id="rst-synopsis-27"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*disable_irq) (struct parport *port);
        ...
};
```

<a id="rst-description-28"></a>

#### DESCRIPTION

The parallel port hardware is instructed not to generate interrupts. The interrupt itself is not masked.

<a id="rst-see-also-27"></a>

#### SEE ALSO

enable_irq

<a id="rst-port-ops-data-forward-enable-data-drivers"></a>

### port-&gt;ops-&gt;data_forward - enable data drivers

<a id="rst-synopsis-28"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*data_forward) (struct parport *port);
        ...
};
```

<a id="rst-description-29"></a>

#### DESCRIPTION

Enables the data line drivers, for 8-bit host-to-peripheral communications.

<a id="rst-see-also-28"></a>

#### SEE ALSO

data_reverse

<a id="rst-port-ops-data-reverse-tristate-the-buffer"></a>

### port-&gt;ops-&gt;data_reverse - tristate the buffer

<a id="rst-synopsis-29"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*data_reverse) (struct parport *port);
        ...
};
```

<a id="rst-description-30"></a>

#### DESCRIPTION

Places the data bus in a high impedance state, if port-&gt;modes has the PARPORT_MODE_TRISTATE bit set.

<a id="rst-see-also-29"></a>

#### SEE ALSO

data_forward

<a id="rst-port-ops-epp-write-data-write-epp-data"></a>

### port-&gt;ops-&gt;epp_write_data - write EPP data

<a id="rst-synopsis-30"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*epp_write_data) (struct parport *port, const void *buf,
                                size_t len, int flags);
        ...
};
```

<a id="rst-description-31"></a>

#### DESCRIPTION

Writes data in EPP mode, and returns the number of bytes written.

The `flags` parameter may be one or more of the following, bitwise-or'ed together:


<table>
<tbody>
<tr>
<td>


PARPORT_EPP_FAST

</td>
<td>


Use fast transfers. Some chips provide 16-bit and 32-bit registers.  However, if a transfer times out, the return value may be unreliable.

</td>
</tr>
</tbody>
</table>

<a id="rst-see-also-30"></a>

#### SEE ALSO

epp_read_data, epp_write_addr, epp_read_addr

<a id="rst-port-ops-epp-read-data-read-epp-data"></a>

### port-&gt;ops-&gt;epp_read_data - read EPP data

<a id="rst-synopsis-31"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*epp_read_data) (struct parport *port, void *buf,
                                size_t len, int flags);
        ...
};
```

<a id="rst-description-32"></a>

#### DESCRIPTION

Reads data in EPP mode, and returns the number of bytes read.

The `flags` parameter may be one or more of the following, bitwise-or'ed together:


<table>
<tbody>
<tr>
<td>


PARPORT_EPP_FAST

</td>
<td>


Use fast transfers. Some chips provide 16-bit and 32-bit registers.  However, if a transfer times out, the return value may be unreliable.

</td>
</tr>
</tbody>
</table>

<a id="rst-see-also-31"></a>

#### SEE ALSO

epp_write_data, epp_write_addr, epp_read_addr

<a id="rst-port-ops-epp-write-addr-write-epp-address"></a>

### port-&gt;ops-&gt;epp_write_addr - write EPP address

<a id="rst-synopsis-32"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*epp_write_addr) (struct parport *port,
                                const void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-33"></a>

#### DESCRIPTION

Writes EPP addresses (8 bits each), and returns the number written.

The `flags` parameter may be one or more of the following, bitwise-or'ed together:


<table>
<tbody>
<tr>
<td>


PARPORT_EPP_FAST

</td>
<td>


Use fast transfers. Some chips provide 16-bit and 32-bit registers.  However, if a transfer times out, the return value may be unreliable.

</td>
</tr>
</tbody>
</table>

(Does PARPORT_EPP_FAST make sense for this function?)

<a id="rst-see-also-32"></a>

#### SEE ALSO

epp_write_data, epp_read_data, epp_read_addr

<a id="rst-port-ops-epp-read-addr-read-epp-address"></a>

### port-&gt;ops-&gt;epp_read_addr - read EPP address

<a id="rst-synopsis-33"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*epp_read_addr) (struct parport *port, void *buf,
                                size_t len, int flags);
        ...
};
```

<a id="rst-description-34"></a>

#### DESCRIPTION

Reads EPP addresses (8 bits each), and returns the number read.

The `flags` parameter may be one or more of the following, bitwise-or'ed together:


<table>
<tbody>
<tr>
<td>


PARPORT_EPP_FAST

</td>
<td>


Use fast transfers. Some chips provide 16-bit and 32-bit registers.  However, if a transfer times out, the return value may be unreliable.

</td>
</tr>
</tbody>
</table>

(Does PARPORT_EPP_FAST make sense for this function?)

<a id="rst-see-also-33"></a>

#### SEE ALSO

epp_write_data, epp_read_data, epp_write_addr

<a id="rst-port-ops-ecp-write-data-write-a-block-of-ecp-data"></a>

### port-&gt;ops-&gt;ecp_write_data - write a block of ECP data

<a id="rst-synopsis-34"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*ecp_write_data) (struct parport *port,
                                const void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-35"></a>

#### DESCRIPTION

Writes a block of ECP data.  The `flags` parameter is ignored.

<a id="rst-return-value-17"></a>

#### RETURN VALUE

The number of bytes written.

<a id="rst-see-also-34"></a>

#### SEE ALSO

ecp_read_data, ecp_write_addr

<a id="rst-port-ops-ecp-read-data-read-a-block-of-ecp-data"></a>

### port-&gt;ops-&gt;ecp_read_data - read a block of ECP data

<a id="rst-synopsis-35"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*ecp_read_data) (struct parport *port,
                                void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-36"></a>

#### DESCRIPTION

Reads a block of ECP data.  The `flags` parameter is ignored.

<a id="rst-return-value-18"></a>

#### RETURN VALUE

The number of bytes read.  NB. There may be more unread data in a FIFO.  Is there a way of stunning the FIFO to prevent this?

<a id="rst-see-also-35"></a>

#### SEE ALSO

ecp_write_block, ecp_write_addr

<a id="rst-port-ops-ecp-write-addr-write-a-block-of-ecp-addresses"></a>

### port-&gt;ops-&gt;ecp_write_addr - write a block of ECP addresses

<a id="rst-synopsis-36"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*ecp_write_addr) (struct parport *port,
                                const void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-37"></a>

#### DESCRIPTION

Writes a block of ECP addresses.  The `flags` parameter is ignored.

<a id="rst-return-value-19"></a>

#### RETURN VALUE

The number of bytes written.

<a id="rst-notes-5"></a>

#### NOTES

This may use a FIFO, and if so shall not return until the FIFO is empty.

<a id="rst-see-also-36"></a>

#### SEE ALSO

ecp_read_data, ecp_write_data

<a id="rst-port-ops-nibble-read-data-read-a-block-of-data-in-nibble-mode"></a>

### port-&gt;ops-&gt;nibble_read_data - read a block of data in nibble mode

<a id="rst-synopsis-37"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*nibble_read_data) (struct parport *port,
                                void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-38"></a>

#### DESCRIPTION

Reads a block of data in nibble mode.  The `flags` parameter is ignored.

<a id="rst-return-value-20"></a>

#### RETURN VALUE

The number of whole bytes read.

<a id="rst-see-also-37"></a>

#### SEE ALSO

byte_read_data, compat_write_data

<a id="rst-port-ops-byte-read-data-read-a-block-of-data-in-byte-mode"></a>

### port-&gt;ops-&gt;byte_read_data - read a block of data in byte mode

<a id="rst-synopsis-38"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*byte_read_data) (struct parport *port,
                                void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-39"></a>

#### DESCRIPTION

Reads a block of data in byte mode.  The `flags` parameter is ignored.

<a id="rst-return-value-21"></a>

#### RETURN VALUE

The number of bytes read.

<a id="rst-see-also-38"></a>

#### SEE ALSO

nibble_read_data, compat_write_data

<a id="rst-port-ops-compat-write-data-write-a-block-of-data-in-compatibility-mode"></a>

### port-&gt;ops-&gt;compat_write_data - write a block of data in compatibility mode

<a id="rst-synopsis-39"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*compat_write_data) (struct parport *port,
                                const void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-40"></a>

#### DESCRIPTION

Writes a block of data in compatibility mode.  The `flags` parameter is ignored.

<a id="rst-return-value-22"></a>

#### RETURN VALUE

The number of bytes written.

<a id="rst-see-also-39"></a>

#### SEE ALSO

nibble_read_data, byte_read_data

---

# SCSI Interfaces Guide

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> Once upon a time, the Small Computer Systems Interface defined both a parallel I/O bus and a data protocol to connect a wide variety of peripherals (disk drives, tape drives, modems, printers, scanners, optical drives, test equipment, and…

<a id="rst-scsi-interfaces-guide"></a>

**Author:** James Bottomley

**Author:** Rob Landley

<a id="rst-introduction"></a>

## Introduction

<a id="rst-protocol-vs-bus"></a>

### Protocol vs bus

Once upon a time, the Small Computer Systems Interface defined both a parallel I/O bus and a data protocol to connect a wide variety of peripherals (disk drives, tape drives, modems, printers, scanners, optical drives, test equipment, and medical devices) to a host computer.

Although the old parallel (fast/wide/ultra) SCSI bus has largely fallen out of use, the SCSI command set is more widely used than ever to communicate with devices over a number of different buses.

The [SCSI protocol](<https://www.t10.org/scsi-3.htm>) is a big-endian peer-to-peer packet based protocol. SCSI commands are 6, 10, 12, or 16 bytes long, often followed by an associated data payload.

SCSI commands can be transported over just about any kind of bus, and are the default protocol for storage devices attached to USB, SATA, SAS, Fibre Channel, FireWire, and ATAPI devices. SCSI packets are also commonly exchanged over Infiniband, TCP/IP ([iSCSI](<https://en.wikipedia.org/wiki/ISCSI>)), even [Parallel ports](<http://cyberelk.net/tim/parport/parscsi.html>).

<a id="rst-design-of-the-linux-scsi-subsystem"></a>

### Design of the Linux SCSI subsystem

The SCSI subsystem uses a three layer design, with upper, mid, and low layers. Every operation involving the SCSI subsystem (such as reading a sector from a disk) uses one driver at each of the 3 levels: one upper layer driver, one lower layer driver, and the SCSI midlayer.

The SCSI upper layer provides the interface between userspace and the kernel, in the form of block and char device nodes for I/O and ioctl(). The SCSI lower layer contains drivers for specific hardware devices.

In between is the SCSI mid-layer, analogous to a network routing layer such as the IPv4 stack. The SCSI mid-layer routes a packet based data protocol between the upper layer's /dev nodes and the corresponding devices in the lower layer. It manages command queues, provides error handling and power management functions, and responds to ioctl() requests.

<a id="rst-scsi-upper-layer"></a>

## SCSI upper layer

The upper layer supports the user-kernel interface by providing device nodes.

<a id="rst-sd-scsi-disk"></a>

### sd (SCSI Disk)

sd (sd_mod.o)

<a id="rst-sr-scsi-cd-rom"></a>

### sr (SCSI CD-ROM)

sr (sr_mod.o)

<a id="rst-st-scsi-tape"></a>

### st (SCSI Tape)

st (st.o)

<a id="rst-sg-scsi-generic"></a>

### sg (SCSI Generic)

sg (sg.o)

<a id="rst-ch-scsi-media-changer"></a>

### ch (SCSI Media Changer)

ch (ch.c)

<a id="rst-scsi-mid-layer"></a>

## SCSI mid layer

<a id="rst-scsi-midlayer-implementation"></a>

### SCSI midlayer implementation

<a id="rst-include-scsi-scsi-device-h"></a>

#### include/scsi/scsi_device.h


#### <a id="c-struct-scsi_vpd"></a>`struct scsi_vpd`

SCSI Vital Product Data

**Definition**

```c
struct scsi_vpd {
    struct rcu_head rcu;
    int len;
    unsigned char   data[];
};
```

**Members**

- `rcu`: For [`kfree_rcu()`](/kernel/internals/core-api/kernel-api.md#c-kfree_rcu).
- `len`: Length in bytes of **data**.
- `data`: VPD data as defined in various T10 SCSI standard documents.

#### <a id="c-shost_for_each_device"></a>`shost_for_each_device()`

```c
shost_for_each_device(sdev, shost)
```

iterate over all devices of a host

**Parameters**

- `sdev`: the `struct scsi_device` to use as a cursor
- `shost`: the `struct scsi_host` to iterate over

**Description**

Iterator that returns each device attached to **shost**.  This loop
takes a reference on each device and releases it at the end.  If
you break out of the loop, you must call scsi_device_put(sdev).

#### <a id="c-__shost_for_each_device"></a>`__shost_for_each_device()`

```c
__shost_for_each_device(sdev, shost)
```

iterate over all devices of a host (UNLOCKED)

**Parameters**

- `sdev`: the `struct scsi_device` to use as a cursor
- `shost`: the `struct scsi_host` to iterate over

**Description**

Iterator that returns each device attached to **shost**.  It does _not_
take a reference on the scsi_device, so the whole loop must be
protected by shost->host_lock.

**Note**

The only reason to use this is because you need to access the
device list in interrupt context.  Otherwise you really want to use
shost_for_each_device instead.

#### <a id="c-scsi_device_is_pseudo_dev"></a>`scsi_device_is_pseudo_dev()`

```c
bool scsi_device_is_pseudo_dev(struct scsi_device *sdev)
```

Whether a device is a pseudo SCSI device.

**Parameters**

- `struct scsi_device *sdev`: SCSI device to examine

**Description**

A pseudo SCSI device can be used to allocate SCSI commands but does not show
up in sysfs. Additionally, the logical unit information in **\*sdev** is made up.

This function tests the LUN number instead of comparing **sdev** with
**sdev->host->pseudo_sdev** because this function may be called before
**sdev->host->pseudo_sdev** has been initialized.

#### <a id="c-scsi_device_supports_vpd"></a>`scsi_device_supports_vpd()`

```c
int scsi_device_supports_vpd(struct scsi_device *sdev)
```

test if a device supports VPD pages

**Parameters**

- `struct scsi_device *sdev`: the `struct scsi_device` to test

**Description**

If the 'try_vpd_pages' flag is set it takes precedence.
Otherwise we will assume VPD pages are supported if the
SCSI level is at least SPC-3 and 'skip_vpd_pages' is not set.


<a id="rst-drivers-scsi-scsi-c"></a>

#### drivers/scsi/scsi.c

Main file for the SCSI midlayer.


#### <a id="c-scsi_change_queue_depth"></a>`scsi_change_queue_depth()`

```c
int scsi_change_queue_depth(struct scsi_device *sdev, int depth)
```

change a device's queue depth

**Parameters**

- `struct scsi_device *sdev`: SCSI Device in question
- `int depth`: number of commands allowed to be queued to the driver

**Description**

Sets the device queue depth and returns the new value.

#### <a id="c-scsi_track_queue_full"></a>`scsi_track_queue_full()`

```c
int scsi_track_queue_full(struct scsi_device *sdev, int depth)
```

track QUEUE_FULL events to adjust queue depth

**Parameters**

- `struct scsi_device *sdev`: SCSI Device in question
- `int depth`: Current number of outstanding SCSI commands on this device,
  not counting the one returned as QUEUE_FULL.

**Description**

- This function will track successive QUEUE_FULL events on a

  specific SCSI device to determine if and when there is a
  need to adjust the queue depth on the device.

Lock Status: None held on entry

**Return**

* 0 - No change needed
* >0 - Adjust queue depth to this new depth,
* -1 - Drop back to untagged operation using host->cmd_per_lun as the
  untagged command depth

**Notes**

- Low level drivers may call this at any time and we will do

  "The Right Thing."  We are interrupt context safe.

#### <a id="c-scsi_get_vpd_page"></a>`scsi_get_vpd_page()`

```c
int scsi_get_vpd_page(struct scsi_device *sdev, u8 page, unsigned char *buf, int buf_len)
```

Get Vital Product Data from a SCSI device

**Parameters**

- `struct scsi_device *sdev`: The device to ask
- `u8 page`: Which Vital Product Data to return
- `unsigned char *buf`: where to store the VPD
- `int buf_len`: number of bytes in the VPD buffer area

**Description**

SCSI devices may optionally supply Vital Product Data.  Each 'page'
of VPD is defined in the appropriate SCSI document (eg SPC, SBC).
If the device supports this VPD page, this routine fills **buf**
with the data from that page and return 0. If the VPD page is not
supported or its content cannot be retrieved, -EINVAL is returned.

#### <a id="c-scsi_report_opcode"></a>`scsi_report_opcode()`

```c
int scsi_report_opcode(struct scsi_device *sdev, unsigned char *buffer, unsigned int len, unsigned char opcode, unsigned short sa)
```

Find out if a given command is supported

**Parameters**

- `struct scsi_device *sdev`: scsi device to query
- `unsigned char *buffer`: scratch buffer (must be at least 20 bytes long)
- `unsigned int len`: length of buffer
- `unsigned char opcode`: opcode for the command to look up
- `unsigned short sa`: service action for the command to look up

**Description**

Uses the REPORT SUPPORTED OPERATION CODES to check support for the
command identified with **opcode** and **sa**. If the command does not
have a service action, **sa** must be 0. Returns -EINVAL if RSOC fails,
0 if the command is not supported and 1 if the device claims to
support the command.

#### <a id="c-scsi_device_get"></a>`scsi_device_get()`

```c
int scsi_device_get(struct scsi_device *sdev)
```

get an additional reference to a scsi_device

**Parameters**

- `struct scsi_device *sdev`: device to get a reference to

**Description**

Gets a reference to the scsi_device and increments the use count
of the underlying LLDD module.  You must hold host_lock of the
parent Scsi_Host or already have a reference when calling this.

This will fail if a device is deleted or cancelled, or when the LLD module
is in the process of being unloaded.

#### <a id="c-scsi_device_put"></a>`scsi_device_put()`

```c
void scsi_device_put(struct scsi_device *sdev)
```

release a reference to a scsi_device

**Parameters**

- `struct scsi_device *sdev`: device to release a reference on.

**Description**

Release a reference to the scsi_device and decrements the use
count of the underlying LLDD module.  The device is freed once the last
user vanishes.

#### <a id="c-starget_for_each_device"></a>`starget_for_each_device()`

```c
void starget_for_each_device(struct scsi_target *starget, void *data, void (*fn)(struct scsi_device *, void *))
```

helper to walk all devices of a target

**Parameters**

- `struct scsi_target *starget`: target whose devices we want to iterate over.
- `void *data`: Opaque passed to each function call.
- `void (*fn)(struct scsi_device *, void *)`: Function to call on each device

**Description**

This traverses over each device of **starget**.  The devices have
a reference that must be released by scsi_host_put when breaking
out of the loop.

#### <a id="c-__starget_for_each_device"></a>`__starget_for_each_device()`

```c
void __starget_for_each_device(struct scsi_target *starget, void *data, void (*fn)(struct scsi_device *, void *))
```

helper to walk all devices of a target (UNLOCKED)

**Parameters**

- `struct scsi_target *starget`: target whose devices we want to iterate over.
- `void *data`: parameter for callback **fn()**
- `void (*fn)(struct scsi_device *, void *)`: callback function that is invoked for each device

**Description**

This traverses over each device of **starget**.  It does _not_
take a reference on the scsi_device, so the whole loop must be
protected by shost->host_lock.

**Note**

The only reason why drivers would want to use this is because
they need to access the device list in irq context.  Otherwise you
really want to use starget_for_each_device instead.

#### <a id="c-__scsi_device_lookup_by_target"></a>`__scsi_device_lookup_by_target()`

```c
struct scsi_device * __scsi_device_lookup_by_target(struct scsi_target *starget, u64 lun)
```

find a device given the target (UNLOCKED)

**Parameters**

- `struct scsi_target *starget`: SCSI target pointer
- `u64 lun`: SCSI Logical Unit Number

**Description**

Looks up the scsi_device with the specified **lun** for a given
**starget**.  The returned scsi_device does not have an additional
reference.  You must hold the host's host_lock over this call and
any access to the returned scsi_device. A scsi_device in state
SDEV_DEL is skipped.

**Note**

The only reason why drivers should use this is because
they need to access the device list in irq context.  Otherwise you
really want to use scsi_device_lookup_by_target instead.

#### <a id="c-scsi_device_lookup_by_target"></a>`scsi_device_lookup_by_target()`

```c
struct scsi_device * scsi_device_lookup_by_target(struct scsi_target *starget, u64 lun)
```

find a device given the target

**Parameters**

- `struct scsi_target *starget`: SCSI target pointer
- `u64 lun`: SCSI Logical Unit Number

**Description**

Looks up the scsi_device with the specified **lun** for a given
**starget**.  The returned scsi_device has an additional reference that
needs to be released with scsi_device_put once you're done with it.

#### <a id="c-__scsi_device_lookup"></a>`__scsi_device_lookup()`

```c
struct scsi_device * __scsi_device_lookup(struct Scsi_Host *shost, uint channel, uint id, u64 lun)
```

find a device given the host (UNLOCKED)

**Parameters**

- `struct Scsi_Host *shost`: SCSI host pointer
- `uint channel`: SCSI channel (zero if only one channel)
- `uint id`: SCSI target number (physical unit number)
- `u64 lun`: SCSI Logical Unit Number

**Description**

Looks up the scsi_device with the specified **channel**, **id**, **lun**
for a given host. The returned scsi_device does not have an additional
reference.  You must hold the host's host_lock over this call and any access
to the returned scsi_device.

**Note**

The only reason why drivers would want to use this is because
they need to access the device list in irq context.  Otherwise you
really want to use scsi_device_lookup instead.

#### <a id="c-scsi_device_lookup"></a>`scsi_device_lookup()`

```c
struct scsi_device * scsi_device_lookup(struct Scsi_Host *shost, uint channel, uint id, u64 lun)
```

find a device given the host

**Parameters**

- `struct Scsi_Host *shost`: SCSI host pointer
- `uint channel`: SCSI channel (zero if only one channel)
- `uint id`: SCSI target number (physical unit number)
- `u64 lun`: SCSI Logical Unit Number

**Description**

Looks up the scsi_device with the specified **channel**, **id**, **lun**
for a given host.  The returned scsi_device has an additional reference that
needs to be released with scsi_device_put once you're done with it.


<a id="rst-drivers-scsi-scsicam-c"></a>

#### drivers/scsi/scsicam.c

[SCSI Common Access Method](<http://www.t10.org/ftp/t10/drafts/cam/cam-r12b.pdf>) support functions, for use with HDIO_GETGEO, etc.


#### <a id="c-scsi_bios_ptable"></a>`scsi_bios_ptable()`

```c
unsigned char * scsi_bios_ptable(struct gendisk *dev)
```

Read PC partition table out of first sector of device.

**Parameters**

- `struct gendisk *dev`: from this device

**Description**

- Reads the first sector from the device and returns `0x42` bytes

  starting at offset `0x1be`.

**Return**

partition table in kmalloc(GFP_KERNEL) memory, or NULL on error.

#### <a id="c-scsi_partsize"></a>`scsi_partsize()`

```c
bool scsi_partsize(struct gendisk *disk, sector_t capacity, int geom[3])
```

Parse cylinders/heads/sectors from PC partition table

**Parameters**

- `struct gendisk *disk`: gendisk of the disk to parse
- `sector_t capacity`: size of the disk in sectors
- `int geom[3]`: output in form of \[hds, cylinders, sectors\]

**Description**

Determine the BIOS mapping/geometry used to create the partition
table, storing the results in **geom**.

**Return**

`false` on failure, `true` on success.

#### <a id="c-scsicam_bios_param"></a>`scsicam_bios_param()`

```c
int scsicam_bios_param(struct gendisk *disk, sector_t capacity, int *ip)
```

Determine geometry of a disk in cylinders/heads/sectors.

**Parameters**

- `struct gendisk *disk`: which device
- `sector_t capacity`: size of the disk in sectors
- `int *ip`: return value: ip\[0\]=heads, ip\[1\]=sectors, ip\[2\]=cylinders

**Description**

- determine the BIOS mapping/geometry used for a drive in a

  SCSI-CAM system, storing the results in ip as required
  by the HDIO_GETGEO `ioctl()`.

**Return**

-1 on failure, 0 on success.


<a id="rst-drivers-scsi-scsi-error-c"></a>

#### drivers/scsi/scsi_error.c

Common SCSI error/timeout handling routines.


#### <a id="c-scsi_schedule_eh"></a>`scsi_schedule_eh()`

```c
void scsi_schedule_eh(struct Scsi_Host *shost)
```

schedule EH for SCSI host

**Parameters**

- `struct Scsi_Host *shost`: SCSI host to invoke error handling on.

**Description**

Schedule SCSI EH without scmd.

#### <a id="c-scsi_block_when_processing_errors"></a>`scsi_block_when_processing_errors()`

```c
int scsi_block_when_processing_errors(struct scsi_device *sdev)
```

Prevent cmds from being queued.

**Parameters**

- `struct scsi_device *sdev`: Device on which we are performing recovery.

**Description**

We block until the host is out of error recovery, and then check to
see whether the host or the device is offline.

- Return value:
  0 when dev was taken offline by error recovery. 1 OK to proceed.

#### <a id="c-scsi_check_sense"></a>`scsi_check_sense()`

```c
enum scsi_disposition scsi_check_sense(struct scsi_cmnd *scmd)
```

Examine scsi cmd sense

**Parameters**

- `struct scsi_cmnd *scmd`: Cmd to have sense checked.

**Description**

- Return value:
  SUCCESS or FAILED or NEEDS_RETRY or ADD_TO_MLQUEUE

**Notes**

When a deferred error is detected the current command has
not been executed and needs retrying.

#### <a id="c-scsi_eh_prep_cmnd"></a>`scsi_eh_prep_cmnd()`

```c
void scsi_eh_prep_cmnd(struct scsi_cmnd *scmd, struct scsi_eh_save *ses, unsigned char *cmnd, int cmnd_size, unsigned sense_bytes)
```

Save a scsi command info as part of error recovery

**Parameters**

- `struct scsi_cmnd *scmd`: SCSI command structure to hijack
- `struct scsi_eh_save *ses`: structure to save restore information
- `unsigned char *cmnd`: CDB to send. Can be NULL if no new cmnd is needed
- `int cmnd_size`: size in bytes of **cmnd** (must be \<= MAX_COMMAND_SIZE)
- `unsigned sense_bytes`: size of sense data to copy. or 0 (if != 0 **cmnd** is ignored)

**Description**

This function is used to save a scsi command information before re-execution
as part of the error recovery process.  If **sense_bytes** is 0 the command
sent must be one that does not transfer any data.  If **sense_bytes** != 0
**cmnd** is ignored and this functions sets up a REQUEST_SENSE command
and cmnd buffers to read **sense_bytes** into **scmd->sense_buffer**.

#### <a id="c-scsi_eh_restore_cmnd"></a>`scsi_eh_restore_cmnd()`

```c
void scsi_eh_restore_cmnd(struct scsi_cmnd* scmd, struct scsi_eh_save *ses)
```

Restore a scsi command info as part of error recovery

**Parameters**

- `struct scsi_cmnd* scmd`: SCSI command structure to restore
- `struct scsi_eh_save *ses`: saved information from a coresponding call to scsi_eh_prep_cmnd

**Description**

Undo any damage done by above [`scsi_eh_prep_cmnd()`](#c-scsi_eh_prep_cmnd).

#### <a id="c-scsi_eh_finish_cmd"></a>`scsi_eh_finish_cmd()`

```c
void scsi_eh_finish_cmd(struct scsi_cmnd *scmd, struct list_head *done_q)
```

Handle a cmd that eh is finished with.

**Parameters**

- `struct scsi_cmnd *scmd`: Original SCSI cmd that eh has finished.
- `struct list_head *done_q`: Queue for processed commands.

**Notes**

We don't want to use the normal command completion while we are are
still handling errors - it may cause other commands to be queued,
and that would disturb what we are doing.  Thus we really want to
keep a list of pending commands for final completion, and once we
are ready to leave error handling we handle completion for real.

#### <a id="c-scsi_eh_get_sense"></a>`scsi_eh_get_sense()`

```c
int scsi_eh_get_sense(struct list_head *work_q, struct list_head *done_q)
```

Get device sense data.

**Parameters**

- `struct list_head *work_q`: Queue of commands to process.
- `struct list_head *done_q`: Queue of processed commands.

**Description**

See if we need to request sense information.  if so, then get it
now, so we have a better idea of what to do.

**Notes**

This has the unfortunate side effect that if a shost adapter does
not automatically request sense information, we end up shutting
it down before we request it.

All drivers should request sense information internally these days,
so for now all I have to say is tough noogies if you end up in here.

- XXX: Long term this code should go away, but that needs an audit of

  all LLDDs first.

#### <a id="c-scsi_eh_ready_devs"></a>`scsi_eh_ready_devs()`

```c
void scsi_eh_ready_devs(struct Scsi_Host *shost, struct list_head *work_q, struct list_head *done_q)
```

check device ready state and recover if not.

**Parameters**

- `struct Scsi_Host *shost`: host to be recovered.
- `struct list_head *work_q`: `list_head` for pending commands.
- `struct list_head *done_q`: `list_head` for processed commands.

#### <a id="c-scsi_eh_flush_done_q"></a>`scsi_eh_flush_done_q()`

```c
void scsi_eh_flush_done_q(struct list_head *done_q)
```

finish processed commands or retry them.

**Parameters**

- `struct list_head *done_q`: list_head of processed commands.

#### <a id="c-scsi_report_bus_reset"></a>`scsi_report_bus_reset()`

```c
void scsi_report_bus_reset(struct Scsi_Host *shost, int channel)
```

report bus reset observed

**Parameters**

- `struct Scsi_Host *shost`: Host in question
- `int channel`: channel on which reset was observed.

**Description**

Utility function used by low-level drivers to report that
they have observed a bus reset on the bus being handled.

Lock status: Host lock must be held.

**Return**

Nothing

**Notes**

- This only needs to be called if the reset is one which

  originates from an unknown location.  Resets originated
  by the mid-level itself don't need to call this, but there
  should be no harm.

  The main purpose of this is to make sure that a CHECK_CONDITION
  is properly treated.

#### <a id="c-scsi_report_device_reset"></a>`scsi_report_device_reset()`

```c
void scsi_report_device_reset(struct Scsi_Host *shost, int channel, int target)
```

report device reset observed

**Parameters**

- `struct Scsi_Host *shost`: Host in question
- `int channel`: channel on which reset was observed
- `int target`: target on which reset was observed

**Description**

Utility function used by low-level drivers to report that
they have observed a device reset on the device being handled.

Lock status: Host lock must be held

**Return**

Nothing

**Notes**

- This only needs to be called if the reset is one which

  originates from an unknown location.  Resets originated
  by the mid-level itself don't need to call this, but there
  should be no harm.

  The main purpose of this is to make sure that a CHECK_CONDITION
  is properly treated.

#### <a id="c-scsi_get_sense_info_fld"></a>`scsi_get_sense_info_fld()`

```c
bool scsi_get_sense_info_fld(const u8 *sense_buffer, int sb_len, u64 *info_out)
```

get information field from sense data (either fixed or descriptor format)

**Parameters**

- `const u8 *sense_buffer`: byte array of sense data
- `int sb_len`: number of valid bytes in sense_buffer
- `u64 *info_out`: pointer to 64 integer where 8 or 4 byte information
  field will be placed if found.

**Description**

- Return value:
  true if information field found, false if not found.


<a id="rst-drivers-scsi-scsi-devinfo-c"></a>

#### drivers/scsi/scsi_devinfo.c

Manage scsi_dev_info_list, which tracks blacklisted and whitelisted devices.


#### <a id="c-scsi_dev_info_list_add_keyed"></a>`scsi_dev_info_list_add_keyed()`

```c
int scsi_dev_info_list_add_keyed(int compatible, char *vendor, char *model, char *strflags, blist_flags_t flags, enum scsi_devinfo_key key)
```

add one dev_info list entry.

**Parameters**

- `int compatible`: if true, null terminate short strings.  Otherwise space pad.
- `char *vendor`: vendor string
- `char *model`: model (product) string
- `char *strflags`: integer string
- `blist_flags_t flags`: if strflags NULL, use this flag value
- `enum scsi_devinfo_key key`: specify list to use

**Description**

Create and add one dev_info entry for **vendor**, **model**,
**strflags** or **flag** in list specified by **key**. If **compatible**,
add to the tail of the list, do not space pad, and set
devinfo->compatible. The scsi_static_device_list entries are
added with **compatible** 1 and **clfags** NULL.

**Return**

0 OK, -error on failure.

#### <a id="c-scsi_get_device_flags_keyed"></a>`scsi_get_device_flags_keyed()`

```c
blist_flags_t scsi_get_device_flags_keyed(struct scsi_device *sdev, const unsigned char *vendor, const unsigned char *model, enum scsi_devinfo_key key)
```

get device specific flags from the dynamic device list

**Parameters**

- `struct scsi_device *sdev`: `scsi_device` to get flags for
- `const unsigned char *vendor`: vendor name
- `const unsigned char *model`: model name
- `enum scsi_devinfo_key key`: list to look up

**Description**

Search the scsi_dev_info_list specified by **key** for an entry
matching **vendor** and **model**, if found, return the matching
flags value, else return the host or global default settings.
Called during scan time.

#### <a id="c-scsi_dev_info_add_list"></a>`scsi_dev_info_add_list()`

```c
int scsi_dev_info_add_list(enum scsi_devinfo_key key, const char *name)
```

add a new devinfo list

**Parameters**

- `enum scsi_devinfo_key key`: key of the list to add
- `const char *name`: Name of the list to add (for /proc/scsi/device_info)

**Description**

Adds the requested list, returns zero on success, -EEXIST if the
key is already registered to a list, or other error on failure.

#### <a id="c-scsi_dev_info_remove_list"></a>`scsi_dev_info_remove_list()`

```c
int scsi_dev_info_remove_list(enum scsi_devinfo_key key)
```

destroy an added devinfo list

**Parameters**

- `enum scsi_devinfo_key key`: key of the list to destroy

**Description**

Iterates over the entire list first, freeing all the values, then
frees the list itself.  Returns 0 on success or -EINVAL if the key
can't be found.


<a id="rst-drivers-scsi-scsi-ioctl-c"></a>

#### drivers/scsi/scsi_ioctl.c

Handle ioctl() calls for SCSI devices.


#### <a id="c-scsi_set_medium_removal"></a>`scsi_set_medium_removal()`

```c
int scsi_set_medium_removal(struct scsi_device *sdev, char state)
```

send command to allow or prevent medium removal

**Parameters**

- `struct scsi_device *sdev`: target scsi device
- `char state`: removal state to set (prevent or allow)

**Return**

* `0` if **sdev** is not removable or not lockable or successful.
* non-`0` is a SCSI result code if > 0 or kernel error code if \< 0.
* Sets **sdev->locked** to the new state on success.

#### <a id="c-scsi_cmd_allowed"></a>`scsi_cmd_allowed()`

```c
bool scsi_cmd_allowed(unsigned char *cmd, bool open_for_write)
```

Check if the given command is allowed.

**Parameters**

- `unsigned char *cmd`: SCSI command to check
- `bool open_for_write`: is the file / block device opened for writing?

**Description**

Only a subset of commands are allowed for unprivileged users. Commands used
to format the media, update the firmware, etc. are not permitted.

**Return**

`true` if the cmd is allowed, otherwise **false**.

#### <a id="c-scsi_ioctl"></a>`scsi_ioctl()`

```c
int scsi_ioctl(struct scsi_device *sdev, bool open_for_write, int cmd, void __user *arg)
```

Dispatch ioctl to scsi device

**Parameters**

- `struct scsi_device *sdev`: scsi device receiving ioctl
- `bool open_for_write`: is the file / block device opened for writing?
- `int cmd`: which ioctl is it
- `void __user *arg`: data associated with ioctl

**Description**

The [`scsi_ioctl()`](#c-scsi_ioctl) function differs from most ioctls in that it
does not take a major/minor number as the dev field.  Rather, it takes
a pointer to a `struct scsi_device`.

**Return**

varies depending on the **cmd**

#### <a id="c-scsi_ioctl_block_when_processing_errors"></a>`scsi_ioctl_block_when_processing_errors()`

```c
int scsi_ioctl_block_when_processing_errors(struct scsi_device *sdev, int cmd, bool ndelay)
```

prevent commands from being queued

**Parameters**

- `struct scsi_device *sdev`: target scsi device
- `int cmd`: which ioctl is it
- `bool ndelay`: no delay (non-blocking)

**Description**

We can process a reset even when a device isn't fully operable.

**Return**

`0` on success, \<0 error code.


<a id="rst-drivers-scsi-scsi-lib-c"></a>

#### drivers/scsi/scsi_lib.c

SCSI queuing library.


#### <a id="c-scsi_failures_reset_retries"></a>`scsi_failures_reset_retries()`

```c
void scsi_failures_reset_retries(struct scsi_failures *failures)
```

reset all failures to zero

**Parameters**

- `struct scsi_failures *failures`: `struct scsi_failures` with specific failure modes set

#### <a id="c-scsi_execute_cmd"></a>`scsi_execute_cmd()`

```c
int scsi_execute_cmd(struct scsi_device *sdev, const unsigned char *cmd, blk_opf_t opf, void *buffer, unsigned int bufflen, int timeout, int ml_retries, const struct scsi_exec_args *args)
```

insert request and wait for the result

**Parameters**

- `struct scsi_device *sdev`: scsi_device
- `const unsigned char *cmd`: scsi command
- `blk_opf_t opf`: block layer request cmd_flags
- `void *buffer`: data buffer
- `unsigned int bufflen`: len of buffer
- `int timeout`: request timeout in HZ
- `int ml_retries`: number of times SCSI midlayer will retry request
- `const struct scsi_exec_args *args`: Optional args. See struct definition for field descriptions

**Description**

Returns the scsi_cmnd result field if a command was executed, or a negative
Linux error code if we didn't get that far.

#### <a id="c-scsi_alloc_sgtables"></a>`scsi_alloc_sgtables()`

```c
blk_status_t scsi_alloc_sgtables(struct scsi_cmnd *cmd)
```

Allocate and initialize data and integrity scatterlists

**Parameters**

- `struct scsi_cmnd *cmd`: SCSI command data structure to initialize.

**Description**

Initializes **cmd->sdb** and also **cmd->prot_sdb** if data integrity is enabled
for **cmd**.

**Return**

* BLK_STS_OK       - on success
* BLK_STS_RESOURCE - if the failure is retryable
* BLK_STS_IOERR    - if the failure is fatal

#### <a id="c-scsi_alloc_request"></a>`scsi_alloc_request()`

```c
struct request * scsi_alloc_request(struct request_queue *q, blk_opf_t opf, blk_mq_req_flags_t flags)
```

allocate a block request and partially initialize its `scsi_cmnd`

**Parameters**

- `struct request_queue *q`: the device's request queue
- `blk_opf_t opf`: the request operation code
- `blk_mq_req_flags_t flags`: block layer allocation flags

**Return**

`struct request` pointer on success or `NULL` on failure

#### <a id="c-scsi_get_internal_cmd"></a>`scsi_get_internal_cmd()`

```c
struct scsi_cmnd * scsi_get_internal_cmd(struct scsi_device *sdev, enum dma_data_direction data_direction, blk_mq_req_flags_t flags)
```

Allocate an internal SCSI command.

**Parameters**

- `struct scsi_device *sdev`: SCSI device from which to allocate the command
- `enum dma_data_direction data_direction`: Data direction for the allocated command
- `blk_mq_req_flags_t flags`: request allocation flags, e.g. BLK_MQ_REQ_RESERVED or
  BLK_MQ_REQ_NOWAIT.

**Description**

Allocates a SCSI command for internal LLDD use.

#### <a id="c-scsi_put_internal_cmd"></a>`scsi_put_internal_cmd()`

```c
void scsi_put_internal_cmd(struct scsi_cmnd *scmd)
```

Free an internal SCSI command.

**Parameters**

- `struct scsi_cmnd *scmd`: SCSI command to be freed

#### <a id="c-scsi_device_from_queue"></a>`scsi_device_from_queue()`

```c
struct scsi_device * scsi_device_from_queue(struct request_queue *q)
```

return sdev associated with a request_queue

**Parameters**

- `struct request_queue *q`: The request queue to return the sdev from

**Description**

Return the sdev associated with a request queue or NULL if the
request_queue does not reference a SCSI device.

#### <a id="c-scsi_block_requests"></a>`scsi_block_requests()`

```c
void scsi_block_requests(struct Scsi_Host *shost)
```

Utility function used by low-level drivers to prevent further commands from being queued to the device.

**Parameters**

- `struct Scsi_Host *shost`: host in question

**Description**

There is no timer nor any other means by which the requests get unblocked
other than the low-level driver calling [`scsi_unblock_requests()`](#c-scsi_unblock_requests).

#### <a id="c-scsi_unblock_requests"></a>`scsi_unblock_requests()`

```c
void scsi_unblock_requests(struct Scsi_Host *shost)
```

Utility function used by low-level drivers to allow further commands to be queued to the device.

**Parameters**

- `struct Scsi_Host *shost`: host in question

**Description**

There is no timer nor any other means by which the requests get unblocked
other than the low-level driver calling [`scsi_unblock_requests()`](#c-scsi_unblock_requests). This is done
as an API function so that changes to the internals of the scsi mid-layer
won't require wholesale changes to drivers that use this feature.

#### <a id="c-scsi_mode_select"></a>`scsi_mode_select()`

```c
int scsi_mode_select(struct scsi_device *sdev, int pf, int sp, unsigned char *buffer, int len, int timeout, int retries, struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
```

issue a mode select

**Parameters**

- `struct scsi_device *sdev`: SCSI device to be queried
- `int pf`: Page format bit (1 == standard, 0 == vendor specific)
- `int sp`: Save page bit (0 == don't save, 1 == save)
- `unsigned char *buffer`: request buffer (may not be smaller than eight bytes)
- `int len`: length of request buffer.
- `int timeout`: command timeout
- `int retries`: number of retries before failing
- `struct scsi_mode_data *data`: returns a structure abstracting the mode header data
- `struct scsi_sense_hdr *sshdr`: place to put sense data (or NULL if no sense to be collected).
  must be SCSI_SENSE_BUFFERSIZE big.

**Description**

Returns zero if successful; negative error number or scsi
status on error

#### <a id="c-scsi_mode_sense"></a>`scsi_mode_sense()`

```c
int scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage, int subpage, unsigned char *buffer, int len, int timeout, int retries, struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
```

issue a mode sense, falling back from 10 to six bytes if necessary.

**Parameters**

- `struct scsi_device *sdev`: SCSI device to be queried
- `int dbd`: set to prevent mode sense from returning block descriptors
- `int modepage`: mode page being requested
- `int subpage`: sub-page of the mode page being requested
- `unsigned char *buffer`: request buffer (may not be smaller than eight bytes)
- `int len`: length of request buffer.
- `int timeout`: command timeout
- `int retries`: number of retries before failing
- `struct scsi_mode_data *data`: returns a structure abstracting the mode header data
- `struct scsi_sense_hdr *sshdr`: place to put sense data (or NULL if no sense to be collected).
  must be SCSI_SENSE_BUFFERSIZE big.

**Description**

Returns zero if successful, or a negative error number on failure

#### <a id="c-scsi_test_unit_ready"></a>`scsi_test_unit_ready()`

```c
int scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries, struct scsi_sense_hdr *sshdr)
```

test if unit is ready

**Parameters**

- `struct scsi_device *sdev`: scsi device to change the state of.
- `int timeout`: command timeout
- `int retries`: number of retries before failing
- `struct scsi_sense_hdr *sshdr`: outpout pointer for decoded sense information.

**Description**

Returns zero if successful or an error if TUR failed.  For
removable media, UNIT_ATTENTION sets ->changed flag.

#### <a id="c-scsi_device_set_state"></a>`scsi_device_set_state()`

```c
int scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
```

Take the given device through the device state model.

**Parameters**

- `struct scsi_device *sdev`: scsi device to change the state of.
- `enum scsi_device_state state`: state to change to.

**Description**

Returns zero if successful or an error if the requested
transition is illegal.

#### <a id="c-sdev_evt_send"></a>`sdev_evt_send()`

```c
void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
```

send asserted event to uevent thread

**Parameters**

- `struct scsi_device *sdev`: scsi_device event occurred on
- `struct scsi_event *evt`: event to send

**Description**

Assert scsi device event asynchronously.

#### <a id="c-sdev_evt_alloc"></a>`sdev_evt_alloc()`

```c
struct scsi_event * sdev_evt_alloc(enum scsi_device_event evt_type, gfp_t gfpflags)
```

allocate a new scsi event

**Parameters**

- `enum scsi_device_event evt_type`: type of event to allocate
- `gfp_t gfpflags`: GFP flags for allocation

**Description**

Allocates and returns a new scsi_event.

#### <a id="c-sdev_evt_send_simple"></a>`sdev_evt_send_simple()`

```c
void sdev_evt_send_simple(struct scsi_device *sdev, enum scsi_device_event evt_type, gfp_t gfpflags)
```

send asserted event to uevent thread

**Parameters**

- `struct scsi_device *sdev`: scsi_device event occurred on
- `enum scsi_device_event evt_type`: type of event to send
- `gfp_t gfpflags`: GFP flags for allocation

**Description**

Assert scsi device event asynchronously, given an event type.

#### <a id="c-scsi_device_quiesce"></a>`scsi_device_quiesce()`

```c
int scsi_device_quiesce(struct scsi_device *sdev)
```

Block all commands except power management.

**Parameters**

- `struct scsi_device *sdev`: scsi device to quiesce.

**Description**

This works by trying to transition to the SDEV_QUIESCE state
(which must be a legal transition).  When the device is in this
state, only power management requests will be accepted, all others will
be deferred.

Must be called with user context, may sleep.

Returns zero if successful or an error if not.

#### <a id="c-scsi_device_resume"></a>`scsi_device_resume()`

```c
void scsi_device_resume(struct scsi_device *sdev)
```

Restart user issued commands to a quiesced device.

**Parameters**

- `struct scsi_device *sdev`: scsi device to resume.

**Description**

Moves the device from quiesced back to running and restarts the
queues.

Must be called with user context, may sleep.

#### <a id="c-scsi_internal_device_block_nowait"></a>`scsi_internal_device_block_nowait()`

```c
int scsi_internal_device_block_nowait(struct scsi_device *sdev)
```

try to transition to the SDEV_BLOCK state

**Parameters**

- `struct scsi_device *sdev`: device to block

**Description**

Pause SCSI command processing on the specified device. Does not sleep.

Returns zero if successful or a negative error code upon failure.

**Notes**

This routine transitions the device to the SDEV_BLOCK state (which must be
a legal transition). When the device is in this state, command processing
is paused until the device leaves the SDEV_BLOCK state. See also
[`scsi_internal_device_unblock_nowait()`](#c-scsi_internal_device_unblock_nowait).

#### <a id="c-scsi_internal_device_unblock_nowait"></a>`scsi_internal_device_unblock_nowait()`

```c
int scsi_internal_device_unblock_nowait(struct scsi_device *sdev, enum scsi_device_state new_state)
```

resume a device after a block request

**Parameters**

- `struct scsi_device *sdev`: device to resume
- `enum scsi_device_state new_state`: state to set the device to after unblocking

**Description**

Restart the device queue for a previously suspended SCSI device. Does not
sleep.

Returns zero if successful or a negative error code upon failure.

**Notes**

This routine transitions the device to the SDEV_RUNNING state or to one of
the offline states (which must be a legal transition) allowing the midlayer
to goose the queue for this device.

#### <a id="c-scsi_block_targets"></a>`scsi_block_targets()`

```c
void scsi_block_targets(struct Scsi_Host *shost, struct device *dev)
```

transition all SCSI child devices to SDEV_BLOCK state

**Parameters**

- `struct Scsi_Host *shost`: the Scsi_Host to which this device belongs
- `struct device *dev`: a parent device of one or more scsi_target devices

**Description**

Iterate over all children of **dev**, which should be scsi_target devices,
and switch all subordinate scsi devices to SDEV_BLOCK state. Wait for
ongoing `scsi_queue_rq()` calls to finish. May sleep.

**Note**

**dev** must not itself be a scsi_target device.

#### <a id="c-scsi_host_block"></a>`scsi_host_block()`

```c
int scsi_host_block(struct Scsi_Host *shost)
```

Try to transition all logical units to the SDEV_BLOCK state

**Parameters**

- `struct Scsi_Host *shost`: device to block

**Description**

Pause SCSI command processing for all logical units associated with the SCSI
host and wait until pending `scsi_queue_rq()` calls have finished.

Returns zero if successful or a negative error code upon failure.

#### <a id="c-scsi_kmap_atomic_sg"></a>`scsi_kmap_atomic_sg()`

```c
void * scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count, size_t *offset, size_t *len)
```

find and atomically map an sg-elemnt

**Parameters**

- `struct scatterlist *sgl`: scatter-gather list
- `int sg_count`: number of segments in sg
- `size_t *offset`: offset in bytes into sg, on return offset into the mapped area
- `size_t *len`: bytes to map, on return number of bytes mapped

**Description**

Returns virtual address of the start of the mapped page

#### <a id="c-scsi_kunmap_atomic_sg"></a>`scsi_kunmap_atomic_sg()`

```c
void scsi_kunmap_atomic_sg(void *virt)
```

atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg

**Parameters**

- `void *virt`: virtual address to be unmapped

#### <a id="c-scsi_vpd_lun_id"></a>`scsi_vpd_lun_id()`

```c
int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len)
```

return a unique device identification

**Parameters**

- `struct scsi_device *sdev`: SCSI device
- `char *id`: buffer for the identification
- `size_t id_len`: length of the buffer

**Description**

Copies a unique device identification into **id** based
on the information in the VPD page 0x83 of the device.
The string will be formatted as a SCSI name string.

Returns the length of the identification or error on failure.
If the identifier is longer than the supplied buffer the actual
identifier length is returned and the buffer is not zero-padded.

#### <a id="c-scsi_vpd_tpg_id"></a>`scsi_vpd_tpg_id()`

```c
int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id)
```

return a target port group identifier

**Parameters**

- `struct scsi_device *sdev`: SCSI device
- `int *rel_id`: pointer to return relative target port in if not `NULL`

**Description**

Returns the Target Port Group identifier from the information
from VPD page 0x83 of the device.
Optionally sets **rel_id** to the relative target port on success.

**Return**

the identifier or error on failure.

#### <a id="c-scsi_build_sense"></a>`scsi_build_sense()`

```c
void scsi_build_sense(struct scsi_cmnd *scmd, int desc, u8 key, u8 asc, u8 ascq)
```

build sense data for a command

**Parameters**

- `struct scsi_cmnd *scmd`: scsi command for which the sense should be formatted
- `int desc`: Sense format (non-zero == descriptor format,
  0 == fixed format)
- `u8 key`: Sense key
- `u8 asc`: Additional sense code
- `u8 ascq`: Additional sense code qualifier


<a id="rst-drivers-scsi-scsi-lib-dma-c"></a>

#### drivers/scsi/scsi_lib_dma.c

SCSI library functions depending on DMA (map and unmap scatter-gather lists).


#### <a id="c-scsi_dma_map"></a>`scsi_dma_map()`

```c
int scsi_dma_map(struct scsi_cmnd *cmd)
```

perform DMA mapping against command's sg lists

**Parameters**

- `struct scsi_cmnd *cmd`: scsi command

**Description**

Returns the number of sg lists actually used, zero if the sg lists
is NULL, or -ENOMEM if the mapping failed.

#### <a id="c-scsi_dma_unmap"></a>`scsi_dma_unmap()`

```c
void scsi_dma_unmap(struct scsi_cmnd *cmd)
```

unmap command's sg lists mapped by scsi_dma_map

**Parameters**

- `struct scsi_cmnd *cmd`: scsi command


<a id="rst-drivers-scsi-scsi-proc-c"></a>

#### drivers/scsi/scsi_proc.c

The functions in this file provide an interface between the PROC file system and the SCSI device drivers It is mainly used for debugging, statistics and to pass information directly to the lowlevel driver. I.E. plumbing to manage /proc/scsi/\*


#### <a id="c-struct-scsi_proc_entry"></a>`struct scsi_proc_entry`

(host template, SCSI proc dir) association

**Definition**

```c
struct scsi_proc_entry {
    struct list_head        entry;
    const struct scsi_host_template *sht;
    struct proc_dir_entry   *proc_dir;
    unsigned int            present;
};
```

**Members**

- `entry`: entry in scsi_proc_list.
- `sht`: SCSI host template associated with the procfs directory.
- `proc_dir`: procfs directory associated with the SCSI host template.
- `present`: Number of SCSI hosts instantiated for **sht**.

#### <a id="c-scsi_template_proc_dir"></a>`scsi_template_proc_dir()`

```c
struct proc_dir_entry * scsi_template_proc_dir(const struct scsi_host_template *sht)
```

returns the procfs dir for a SCSI host template

**Parameters**

- `const struct scsi_host_template *sht`: SCSI host template pointer.

#### <a id="c-scsi_proc_hostdir_add"></a>`scsi_proc_hostdir_add()`

```c
int scsi_proc_hostdir_add(const struct scsi_host_template *sht)
```

Create directory in /proc for a scsi host

**Parameters**

- `const struct scsi_host_template *sht`: owner of this directory

**Description**

Sets sht->proc_dir to the new directory.

#### <a id="c-scsi_proc_hostdir_rm"></a>`scsi_proc_hostdir_rm()`

```c
void scsi_proc_hostdir_rm(const struct scsi_host_template *sht)
```

remove directory in /proc for a scsi host

**Parameters**

- `const struct scsi_host_template *sht`: owner of directory

#### <a id="c-scsi_proc_host_add"></a>`scsi_proc_host_add()`

```c
void scsi_proc_host_add(struct Scsi_Host *shost)
```

Add entry for this host to appropriate /proc dir

**Parameters**

- `struct Scsi_Host *shost`: host to add

#### <a id="c-scsi_proc_host_rm"></a>`scsi_proc_host_rm()`

```c
void scsi_proc_host_rm(struct Scsi_Host *shost)
```

remove this host's entry from /proc

**Parameters**

- `struct Scsi_Host *shost`: which host

#### <a id="c-proc_print_scsidevice"></a>`proc_print_scsidevice()`

```c
int proc_print_scsidevice(struct device *dev, void *data)
```

return data about this host

**Parameters**

- `struct device *dev`: A scsi device
- `void *data`: `struct seq_file` to output to.

**Description**

prints Host, Channel, Id, Lun, Vendor, Model, Rev, Type,
and revision.

#### <a id="c-scsi_add_single_device"></a>`scsi_add_single_device()`

```c
int scsi_add_single_device(uint host, uint channel, uint id, uint lun)
```

Respond to user request to probe for/add device

**Parameters**

- `uint host`: user-supplied decimal integer
- `uint channel`: user-supplied decimal integer
- `uint id`: user-supplied decimal integer
- `uint lun`: user-supplied decimal integer

**Description**

called by writing "scsi add-single-device" to /proc/scsi/scsi.

does [`scsi_host_lookup()`](#c-scsi_host_lookup) and either `user_scan()` if that transport
type supports it, or else `scsi_scan_host_selected()`

**Note**

this seems to be aimed exclusively at SCSI parallel busses.

#### <a id="c-scsi_remove_single_device"></a>`scsi_remove_single_device()`

```c
int scsi_remove_single_device(uint host, uint channel, uint id, uint lun)
```

Respond to user request to remove a device

**Parameters**

- `uint host`: user-supplied decimal integer
- `uint channel`: user-supplied decimal integer
- `uint id`: user-supplied decimal integer
- `uint lun`: user-supplied decimal integer

**Description**

called by writing "scsi remove-single-device" to
/proc/scsi/scsi.  Does a [`scsi_device_lookup()`](#c-scsi_device_lookup) and [`scsi_remove_device()`](#c-scsi_remove_device)

#### <a id="c-proc_scsi_write"></a>`proc_scsi_write()`

```c
ssize_t proc_scsi_write(struct file *file, const char __user *buf, size_t length, loff_t *ppos)
```

handle writes to /proc/scsi/scsi

**Parameters**

- `struct file *file`: not used
- `const char __user *buf`: buffer to write
- `size_t length`: length of buf, at most PAGE_SIZE
- `loff_t *ppos`: not used

**Description**

this provides a legacy mechanism to add or remove devices by
Host, Channel, ID, and Lun.  To use,
"echo 'scsi add-single-device 0 1 2 3' > /proc/scsi/scsi" or
"echo 'scsi remove-single-device 0 1 2 3' > /proc/scsi/scsi" with
"0 1 2 3" replaced by the Host, Channel, Id, and Lun.

**Note**

this seems to be aimed at parallel SCSI. Most modern busses (USB,
SATA, Firewire, Fibre Channel, etc) dynamically assign these values to
provide a unique identifier and nothing more.

#### <a id="c-proc_scsi_open"></a>`proc_scsi_open()`

```c
int proc_scsi_open(struct inode *inode, struct file *file)
```

glue function

**Parameters**

- `struct inode *inode`: not used
- `struct file *file`: passed to `single_open()`

**Description**

Associates proc_scsi_show with this file

#### <a id="c-scsi_init_procfs"></a>`scsi_init_procfs()`

```c
int scsi_init_procfs(void)
```

create scsi and scsi/scsi in procfs

**Parameters**

- `void`: no arguments

#### <a id="c-scsi_exit_procfs"></a>`scsi_exit_procfs()`

```c
void scsi_exit_procfs(void)
```

Remove scsi/scsi and scsi from procfs

**Parameters**

- `void`: no arguments


<a id="rst-drivers-scsi-scsi-netlink-c"></a>

#### drivers/scsi/scsi_netlink.c

Infrastructure to provide async events from transports to userspace via netlink, using a single NETLINK_SCSITRANSPORT protocol for all transports. See [the original patch submission](<https://lore.kernel.org/linux-scsi/1155070439.6275.5.camel@localhost.localdomain/>) for more details.


#### <a id="c-scsi_nl_rcv_msg"></a>`scsi_nl_rcv_msg()`

```c
void scsi_nl_rcv_msg(struct sk_buff *skb)
```

Receive message handler.

**Parameters**

- `struct sk_buff *skb`: socket receive buffer

**Description**

- Extracts message from a receive buffer.

  Validates message header and calls appropriate transport message handler

#### <a id="c-scsi_netlink_init"></a>`scsi_netlink_init()`

```c
void scsi_netlink_init(void)
```

Called by SCSI subsystem to initialize the SCSI transport netlink interface

**Parameters**

- `void`: no arguments

#### <a id="c-scsi_netlink_exit"></a>`scsi_netlink_exit()`

```c
void scsi_netlink_exit(void)
```

Called by SCSI subsystem to disable the SCSI transport netlink interface

**Parameters**

- `void`: no arguments


<a id="rst-drivers-scsi-scsi-scan-c"></a>

#### drivers/scsi/scsi_scan.c

Scan a host to determine which (if any) devices are attached. The general scanning/probing algorithm is as follows, exceptions are made to it depending on device specific flags, compilation options, and global variable (boot or module load time) settings. A specific LUN is scanned via an INQUIRY command; if the LUN has a device attached, a scsi_device is allocated and setup for it. For every id of every channel on the given host, start by scanning LUN 0. Skip hosts that don't respond at all to a scan of LUN 0. Otherwise, if LUN 0 has a device attached, allocate and setup a scsi_device for it. If target is SCSI-3 or up, issue a REPORT LUN, and scan all of the LUNs returned by the REPORT LUN; else, sequentially scan LUNs up until some maximum is reached, or a LUN is seen that cannot have a device attached to it.


#### <a id="c-scsi_sanitize_inquiry_string"></a>`scsi_sanitize_inquiry_string()`

```c
void scsi_sanitize_inquiry_string(unsigned char *s, int len)
```

remove non-graphical chars from an INQUIRY result string

**Parameters**

- `unsigned char *s`: INQUIRY result string to sanitize
- `int len`: length of the string

**Description**

The SCSI spec says that INQUIRY vendor, product, and revision
strings must consist entirely of graphic ASCII characters,
padded on the right with spaces.  Since not all devices obey
this rule, we will replace non-graphic or non-ASCII characters
with spaces.  Exception: a NUL character is interpreted as a
string terminator, so all the following characters are set to
spaces.

#### <a id="c-scsi_add_device"></a>`scsi_add_device()`

```c
int scsi_add_device(struct Scsi_Host *host, uint channel, uint target, u64 lun)
```

creates a new SCSI (LU) instance

**Parameters**

- `struct Scsi_Host *host`: the `Scsi_Host` instance where the device is located
- `uint channel`: target channel number (rarely other than `0`)
- `uint target`: target id number
- `u64 lun`: LUN of target device

**Description**

Probe for a specific LUN and add it if found.

**Notes**

This call is usually performed internally during a SCSI
bus scan when an HBA is added (i.e. [`scsi_scan_host()`](#c-scsi_scan_host)). So it
should only be called if the HBA becomes aware of a new SCSI
device (LU) after [`scsi_scan_host()`](#c-scsi_scan_host) has completed. If successful
this call can lead to `sdev_init()` and `sdev_configure()` callbacks
into the LLD.

**Return**

`0` on success or negative error code on failure

#### <a id="c-scsi_scan_target"></a>`scsi_scan_target()`

```c
void scsi_scan_target(struct device *parent, unsigned int channel, unsigned int id, u64 lun, enum scsi_scan_mode rescan)
```

scan a target id, possibly including all LUNs on the target.

**Parameters**

- `struct device *parent`: host to scan
- `unsigned int channel`: channel to scan
- `unsigned int id`: target id to scan
- `u64 lun`: Specific LUN to scan or SCAN_WILD_CARD
- `enum scsi_scan_mode rescan`: passed to LUN scanning routines; SCSI_SCAN_INITIAL for
  no rescan, SCSI_SCAN_RESCAN to rescan existing LUNs,
  and SCSI_SCAN_MANUAL to force scanning even if
  'scan=manual' is set.

**Description**

Scan the target id on **parent**, **channel**, and **id**. Scan at least LUN 0,
and possibly all LUNs on the target id.

First try a REPORT LUN scan, if that does not scan the target, do a
sequential scan of LUNs on the target id.

#### <a id="c-scsi_scan_host"></a>`scsi_scan_host()`

```c
void scsi_scan_host(struct Scsi_Host *shost)
```

scan the given adapter

**Parameters**

- `struct Scsi_Host *shost`: adapter to scan

**Notes**

Should be called after `scsi_add_host()`


<a id="rst-drivers-scsi-scsi-sysctl-c"></a>

#### drivers/scsi/scsi_sysctl.c

Set up the sysctl entry: "/dev/scsi/logging_level" (DEV_SCSI_LOGGING_LEVEL) which sets/returns scsi_logging_level.

<a id="rst-drivers-scsi-scsi-sysfs-c"></a>

#### drivers/scsi/scsi_sysfs.c

SCSI sysfs interface routines.


#### <a id="c-scsi_remove_device"></a>`scsi_remove_device()`

```c
void scsi_remove_device(struct scsi_device *sdev)
```

unregister a device from the scsi bus

**Parameters**

- `struct scsi_device *sdev`: scsi_device to unregister

#### <a id="c-scsi_remove_target"></a>`scsi_remove_target()`

```c
void scsi_remove_target(struct device *dev)
```

try to remove a target and all its devices

**Parameters**

- `struct device *dev`: generic starget or parent of generic stargets to be removed

**Note**

This is slightly racy.  It is possible that if the user
requests the addition of another device then the target won't be
removed.


<a id="rst-drivers-scsi-hosts-c"></a>

#### drivers/scsi/hosts.c

mid to lowlevel SCSI driver interface


#### <a id="c-scsi_remove_host"></a>`scsi_remove_host()`

```c
void scsi_remove_host(struct Scsi_Host *shost)
```

remove a scsi host

**Parameters**

- `struct Scsi_Host *shost`: a pointer to a scsi host to remove

#### <a id="c-scsi_add_host_with_dma"></a>`scsi_add_host_with_dma()`

```c
int scsi_add_host_with_dma(struct Scsi_Host *shost, struct device *dev, struct device *dma_dev)
```

add a scsi host with dma device

**Parameters**

- `struct Scsi_Host *shost`: scsi host pointer to add
- `struct device *dev`: a struct device of type scsi class
- `struct device *dma_dev`: dma device for the host

**Note**

You rarely need to worry about this unless you're in a
virtualised host environments, so use the simpler `scsi_add_host()`
function instead.

- Return value:
  0 on success / != 0 for error

#### <a id="c-scsi_host_alloc"></a>`scsi_host_alloc()`

```c
struct Scsi_Host * scsi_host_alloc(const struct scsi_host_template *sht, int privsize)
```

register a scsi host adapter instance.

**Parameters**

- `const struct scsi_host_template *sht`: pointer to scsi host template
- `int privsize`: extra bytes to allocate for driver

**Note**

Allocate a new Scsi_Host and perform basic initialization.
The host is not published to the scsi midlayer until scsi_add_host
is called.

- Return value:
  Pointer to a new Scsi_Host

#### <a id="c-scsi_host_lookup"></a>`scsi_host_lookup()`

```c
struct Scsi_Host * scsi_host_lookup(unsigned int hostnum)
```

get a reference to a Scsi_Host by host no

**Parameters**

- `unsigned int hostnum`: host number to locate

**Description**

- Return value:
  A pointer to located Scsi_Host or NULL.

  The caller must do a [`scsi_host_put()`](#c-scsi_host_put) to drop the reference
  that [`scsi_host_get()`](#c-scsi_host_get) took. The [`put_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-put_device) below dropped
  the reference from [`class_find_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-class_find_device).

#### <a id="c-scsi_host_get"></a>`scsi_host_get()`

```c
struct Scsi_Host * scsi_host_get(struct Scsi_Host *shost)
```

inc a Scsi_Host ref count

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host to inc.

#### <a id="c-scsi_host_busy"></a>`scsi_host_busy()`

```c
int scsi_host_busy(struct Scsi_Host *shost)
```

Return the count of in-flight commands

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host

#### <a id="c-scsi_host_put"></a>`scsi_host_put()`

```c
void scsi_host_put(struct Scsi_Host *shost)
```

dec a Scsi_Host ref count

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host to dec.

#### <a id="c-scsi_queue_work"></a>`scsi_queue_work()`

```c
int scsi_queue_work(struct Scsi_Host *shost, struct work_struct *work)
```

Queue work to the Scsi_Host workqueue.

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host.
- `struct work_struct *work`: Work to queue for execution.

**Description**

- Return value:
  1 - work queued for execution
  0 - work is already queued
  -EINVAL - work queue doesn't exist

#### <a id="c-scsi_flush_work"></a>`scsi_flush_work()`

```c
void scsi_flush_work(struct Scsi_Host *shost)
```

Flush a Scsi_Host's workqueue.

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host.

#### <a id="c-scsi_host_complete_all_commands"></a>`scsi_host_complete_all_commands()`

```c
void scsi_host_complete_all_commands(struct Scsi_Host *shost, enum scsi_host_status status)
```

Terminate all running commands

**Parameters**

- `struct Scsi_Host *shost`: Scsi Host on which commands should be terminated
- `enum scsi_host_status status`: Status to be set for the terminated commands

**Description**

There is no protection against modification of the number
of outstanding commands. It is the responsibility of the
caller to ensure that concurrent I/O submission and/or
completion is stopped when calling this function.

#### <a id="c-scsi_host_busy_iter"></a>`scsi_host_busy_iter()`

```c
void scsi_host_busy_iter(struct Scsi_Host *shost, bool (*fn)(struct scsi_cmnd *, void *), void *priv)
```

Iterate over all busy commands

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host.
- `bool (*fn)(struct scsi_cmnd *, void *)`: Function to call on each busy command
- `void *priv`: Data pointer passed to **fn**

**Description**

If locking against concurrent command completions is required
ithas to be provided by the caller


<a id="rst-drivers-scsi-scsi-common-c"></a>

#### drivers/scsi/scsi_common.c

general support functions


#### <a id="c-scsi_device_type"></a>`scsi_device_type()`

```c
const char * scsi_device_type(unsigned type)
```

Return 17-char string indicating device type.

**Parameters**

- `unsigned type`: type number to look up

#### <a id="c-scsilun_to_int"></a>`scsilun_to_int()`

```c
u64 scsilun_to_int(struct scsi_lun *scsilun)
```

convert a scsi_lun to an int

**Parameters**

- `struct scsi_lun *scsilun`: struct scsi_lun to be converted.

**Description**

Convert **scsilun** from a struct scsi_lun to a four-byte host byte-ordered
integer, and return the result. The caller must check for
truncation before using this function.

**Notes**

For a description of the LUN format, post SCSI-3 see the SCSI
Architecture Model, for SCSI-3 see the SCSI Controller Commands.

Given a struct scsi_lun of: d2 04 0b 03 00 00 00 00, this function
returns the integer: 0x0b03d204

This encoding will return a standard integer LUN for LUNs smaller
than 256, which typically use a single level LUN structure with
addressing method 0.

#### <a id="c-int_to_scsilun"></a>`int_to_scsilun()`

```c
void int_to_scsilun(u64 lun, struct scsi_lun *scsilun)
```

reverts an int into a scsi_lun

**Parameters**

- `u64 lun`: integer to be reverted
- `struct scsi_lun *scsilun`: struct scsi_lun to be set.

**Description**

Reverts the functionality of the scsilun_to_int, which packed
an 8-byte lun value into an int. This routine unpacks the int
back into the lun value.

**Notes**

Given an integer : 0x0b03d204, this function returns a
struct scsi_lun of: d2 04 0b 03 00 00 00 00

#### <a id="c-scsi_normalize_sense"></a>`scsi_normalize_sense()`

```c
bool scsi_normalize_sense(const u8 *sense_buffer, int sb_len, struct scsi_sense_hdr *sshdr)
```

normalize main elements from either fixed or descriptor sense data format into a common format.

**Parameters**

- `const u8 *sense_buffer`: byte array containing sense data returned by device
- `int sb_len`: number of valid bytes in sense_buffer
- `struct scsi_sense_hdr *sshdr`: pointer to instance of structure that common
  elements are written to.

**Notes**

The "main elements" from sense data are: response_code, sense_key,
asc, ascq and additional_length (only for descriptor format).

Typically this function can be called after a device has
responded to a SCSI command with the CHECK_CONDITION status.

- Return value:
  true if valid sense data information found, else false;

#### <a id="c-scsi_sense_desc_find"></a>`scsi_sense_desc_find()`

```c
const u8 * scsi_sense_desc_find(const u8 * sense_buffer, int sb_len, int desc_type)
```

search for a given descriptor type in descriptor sense data format.

**Parameters**

- `const u8 * sense_buffer`: byte array of descriptor format sense data
- `int sb_len`: number of valid bytes in sense_buffer
- `int desc_type`: value of descriptor type to find
  (e.g. 0 -> information)

**Notes**

only valid when sense data is in descriptor format

- Return value:
  pointer to start of (first) descriptor if found else NULL

#### <a id="c-scsi_build_sense_buffer"></a>`scsi_build_sense_buffer()`

```c
void scsi_build_sense_buffer(int desc, u8 *buf, u8 key, u8 asc, u8 ascq)
```

build sense data in a buffer

**Parameters**

- `int desc`: Sense format (non-zero == descriptor format,
  0 == fixed format)
- `u8 *buf`: Where to build sense data
- `u8 key`: Sense key
- `u8 asc`: Additional sense code
- `u8 ascq`: Additional sense code qualifier

#### <a id="c-scsi_set_sense_information"></a>`scsi_set_sense_information()`

```c
int scsi_set_sense_information(u8 *buf, int buf_len, u64 info)
```

set the information field in a formatted sense data buffer

**Parameters**

- `u8 *buf`: Where to build sense data
- `int buf_len`: buffer length
- `u64 info`: 64-bit information value to be set

**Description**

- Return value:
  0 on success or -EINVAL for invalid sense buffer length

#### <a id="c-scsi_set_sense_field_pointer"></a>`scsi_set_sense_field_pointer()`

```c
int scsi_set_sense_field_pointer(u8 *buf, int buf_len, u16 fp, u8 bp, bool cd)
```

set the field pointer sense key specific information in a formatted sense data buffer

**Parameters**

- `u8 *buf`: Where to build sense data
- `int buf_len`: buffer length
- `u16 fp`: field pointer to be set
- `u8 bp`: bit pointer to be set
- `bool cd`: command/data bit

**Description**

- Return value:
  0 on success or -EINVAL for invalid sense buffer length


<a id="rst-transport-classes"></a>

### Transport classes

Transport classes are service libraries for drivers in the SCSI lower layer, which expose transport attributes in sysfs.

<a id="rst-fibre-channel-transport"></a>

#### Fibre Channel transport

The file drivers/scsi/scsi_transport_fc.c defines transport attributes for Fibre Channel.


#### <a id="c-fc_get_event_number"></a>`fc_get_event_number()`

```c
u32 fc_get_event_number(void)
```

Obtain the next sequential FC event number

**Parameters**

- `void`: no arguments

**Notes**

We could have inlined this, but it would have required fc_event_seq to
be exposed. For now, live with the subroutine call.
Atomic used to avoid lock/unlock...

#### <a id="c-fc_host_post_fc_event"></a>`fc_host_post_fc_event()`

```c
void fc_host_post_fc_event(struct Scsi_Host *shost, u32 event_number, enum fc_host_event_code event_code, u32 data_len, char *data_buf, u64 vendor_id)
```

routine to do the work of posting an event on an fc_host.

**Parameters**

- `struct Scsi_Host *shost`: host the event occurred on
- `u32 event_number`: fc event number obtained from `get_fc_event_number()`
- `enum fc_host_event_code event_code`: fc_host event being posted
- `u32 data_len`: amount, in bytes, of event data
- `char *data_buf`: pointer to event data
- `u64 vendor_id`: value for Vendor id

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_host_post_event"></a>`fc_host_post_event()`

```c
void fc_host_post_event(struct Scsi_Host *shost, u32 event_number, enum fc_host_event_code event_code, u32 event_data)
```

called to post an even on an fc_host.

**Parameters**

- `struct Scsi_Host *shost`: host the event occurred on
- `u32 event_number`: fc event number obtained from `get_fc_event_number()`
- `enum fc_host_event_code event_code`: fc_host event being posted
- `u32 event_data`: 32bits of data for the event being posted

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_host_post_vendor_event"></a>`fc_host_post_vendor_event()`

```c
void fc_host_post_vendor_event(struct Scsi_Host *shost, u32 event_number, u32 data_len, char * data_buf, u64 vendor_id)
```

called to post a vendor unique event on an fc_host

**Parameters**

- `struct Scsi_Host *shost`: host the event occurred on
- `u32 event_number`: fc event number obtained from `get_fc_event_number()`
- `u32 data_len`: amount, in bytes, of vendor unique data
- `char * data_buf`: pointer to vendor unique data
- `u64 vendor_id`: Vendor id

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_find_rport_by_wwpn"></a>`fc_find_rport_by_wwpn()`

```c
struct fc_rport * fc_find_rport_by_wwpn(struct Scsi_Host *shost, u64 wwpn)
```

find the fc_rport pointer for a given wwpn

**Parameters**

- `struct Scsi_Host *shost`: host the fc_rport is associated with
- `u64 wwpn`: wwpn of the fc_rport device

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_host_fpin_rcv"></a>`fc_host_fpin_rcv()`

```c
void fc_host_fpin_rcv(struct Scsi_Host *shost, u32 fpin_len, char *fpin_buf, u8 event_acknowledge)
```

routine to process a received FPIN.

**Parameters**

- `struct Scsi_Host *shost`: host the FPIN was received on
- `u32 fpin_len`: length of FPIN payload, in bytes
- `char *fpin_buf`: pointer to FPIN payload
- `u8 event_acknowledge`: 1, if LLDD handles this event.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_eh_timed_out"></a>`fc_eh_timed_out()`

```c
enum scsi_timeout_action fc_eh_timed_out(struct scsi_cmnd *scmd)
```

FC Transport I/O timeout intercept handler

**Parameters**

- `struct scsi_cmnd *scmd`: The SCSI command which timed out

**Description**

This routine protects against error handlers getting invoked while a
rport is in a blocked state, typically due to a temporarily loss of
connectivity. If the error handlers are allowed to proceed, requests
to abort i/o, reset the target, etc will likely fail as there is no way
to communicate with the device to perform the requested function. These
failures may result in the midlayer taking the device offline, requiring
manual intervention to restore operation.

This routine, called whenever an i/o times out, validates the state of
the underlying rport. If the rport is blocked, it returns
EH_RESET_TIMER, which will continue to reschedule the timeout.
Eventually, either the device will return, or devloss_tmo will fire,
and when the timeout then fires, it will be handled normally.
If the rport is not blocked, normal error handling continues.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_remove_host"></a>`fc_remove_host()`

```c
void fc_remove_host(struct Scsi_Host *shost)
```

called to terminate any fc_transport-related elements for a scsi host.

**Parameters**

- `struct Scsi_Host *shost`: Which `Scsi_Host`

**Description**

This routine is expected to be called immediately preceding the
a driver's call to [`scsi_remove_host()`](#c-scsi_remove_host).

- WARNING: A driver utilizing the fc_transport, which fails to call

  this routine prior to [`scsi_remove_host()`](#c-scsi_remove_host), will leave dangling
  objects in /sys/class/fc_remote_ports. Access to any of these
  objects can result in a system crash !!!

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_remote_port_add"></a>`fc_remote_port_add()`

```c
struct fc_rport * fc_remote_port_add(struct Scsi_Host *shost, int channel, struct fc_rport_identifiers *ids)
```

notify fc transport of the existence of a remote FC port.

**Parameters**

- `struct Scsi_Host *shost`: scsi host the remote port is connected to.
- `int channel`: Channel on shost port connected to.
- `struct fc_rport_identifiers *ids`: The world wide names, fc address, and FC4 port
  roles for the remote port.

**Description**

The LLDD calls this routine to notify the transport of the existence
of a remote port. The LLDD provides the unique identifiers (wwpn,wwn)
of the port, it's FC address (port_id), and the FC4 roles that are
active for the port.

For ports that are FCP targets (aka scsi targets), the FC transport
maintains consistent target id bindings on behalf of the LLDD.
A consistent target id binding is an assignment of a target id to
a remote port identifier, which persists while the scsi host is
attached. The remote port can disappear, then later reappear, and
it's target id assignment remains the same. This allows for shifts
in FC addressing (if binding by wwpn or wwnn) with no apparent
changes to the scsi subsystem which is based on scsi host number and
target id values.  Bindings are only valid during the attachment of
the scsi host. If the host detaches, then later re-attaches, target
id bindings may change.

This routine is responsible for returning a remote port structure.
The routine will search the list of remote ports it maintains
internally on behalf of consistent target id mappings. If found, the
remote port structure will be reused. Otherwise, a new remote port
structure will be allocated.

Whenever a remote port is allocated, a new fc_remote_port class
device is created.

Should not be called from interrupt context.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_remote_port_delete"></a>`fc_remote_port_delete()`

```c
void fc_remote_port_delete(struct fc_rport *rport)
```

notifies the fc transport that a remote port is no longer in existence.

**Parameters**

- `struct fc_rport *rport`: The remote port that no longer exists

**Description**

The LLDD calls this routine to notify the transport that a remote
port is no longer part of the topology. Note: Although a port
may no longer be part of the topology, it may persist in the remote
ports displayed by the fc_host. We do this under 2 conditions:

1) If the port was a scsi target, we delay its deletion by "blocking" it.
   This allows the port to temporarily disappear, then reappear without
   disrupting the SCSI device tree attached to it. During the "blocked"
   period the port will still exist.

2) If the port was a scsi target and disappears for longer than we
   expect, we'll delete the port and the tear down the SCSI device tree
   attached to it. However, we want to semi-persist the target id assigned
   to that port if it eventually does exist. The port structure will
   remain (although with minimal information) so that the target id
   bindings also remain.

If the remote port is not an FCP Target, it will be fully torn down
and deallocated, including the fc_remote_port class device.

If the remote port is an FCP Target, the port will be placed in a
temporary blocked state. From the LLDD's perspective, the rport no
longer exists. From the SCSI midlayer's perspective, the SCSI target
exists, but all sdevs on it are blocked from further I/O. The following
is then expected.

If the remote port does not return (signaled by a LLDD call to
[`fc_remote_port_add()`](#c-fc_remote_port_add)) within the dev_loss_tmo timeout, then the
scsi target is removed - killing all outstanding i/o and removing the
scsi devices attached to it. The port structure will be marked Not
Present and be partially cleared, leaving only enough information to
recognize the remote port relative to the scsi target id binding if
it later appears.  The port will remain as long as there is a valid
binding (e.g. until the user changes the binding type or unloads the
scsi host with the binding).

If the remote port returns within the dev_loss_tmo value (and matches
according to the target id binding type), the port structure will be
reused. If it is no longer a SCSI target, the target will be torn
down. If it continues to be a SCSI target, then the target will be
unblocked (allowing i/o to be resumed), and a scan will be activated
to ensure that all luns are detected.

Called from normal process context only - cannot be called from interrupt.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_remote_port_rolechg"></a>`fc_remote_port_rolechg()`

```c
void fc_remote_port_rolechg(struct fc_rport *rport, u32 roles)
```

notifies the fc transport that the roles on a remote may have changed.

**Parameters**

- `struct fc_rport *rport`: The remote port that changed.
- `u32 roles`: New roles for this port.

**Description**

The LLDD calls this routine to notify the transport that the
roles on a remote port may have changed. The largest effect of this is
if a port now becomes a FCP Target, it must be allocated a
scsi target id.  If the port is no longer a FCP target, any
scsi target id value assigned to it will persist in case the
role changes back to include FCP Target. No changes in the scsi
midlayer will be invoked if the role changes (in the expectation
that the role will be resumed. If it doesn't normal error processing
will take place).

Should not be called from interrupt context.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_block_rport"></a>`fc_block_rport()`

```c
int fc_block_rport(struct fc_rport *rport)
```

Block SCSI eh thread for blocked fc_rport.

**Parameters**

- `struct fc_rport *rport`: Remote port that scsi_eh is trying to recover.

**Description**

This routine can be called from a FC LLD scsi_eh callback. It
blocks the scsi_eh thread until the fc_rport leaves the
FC_PORTSTATE_BLOCKED, or the fast_io_fail_tmo fires. This is
necessary to avoid the scsi_eh failing recovery actions for blocked
rports which would lead to offlined SCSI devices.

**Return**

0 if the fc_rport left the state FC_PORTSTATE_BLOCKED.
FAST_IO_FAIL if the fast_io_fail_tmo fired, this should be
passed back to scsi_eh.

#### <a id="c-fc_block_scsi_eh"></a>`fc_block_scsi_eh()`

```c
int fc_block_scsi_eh(struct scsi_cmnd *cmnd)
```

Block SCSI eh thread for blocked fc_rport

**Parameters**

- `struct scsi_cmnd *cmnd`: SCSI command that scsi_eh is trying to recover

**Description**

This routine can be called from a FC LLD scsi_eh callback. It
blocks the scsi_eh thread until the fc_rport leaves the
FC_PORTSTATE_BLOCKED, or the fast_io_fail_tmo fires. This is
necessary to avoid the scsi_eh failing recovery actions for blocked
rports which would lead to offlined SCSI devices.

**Return**

0 if the fc_rport left the state FC_PORTSTATE_BLOCKED.
FAST_IO_FAIL if the fast_io_fail_tmo fired, this should be
passed back to scsi_eh.

#### <a id="c-fc_vport_create"></a>`fc_vport_create()`

```c
struct fc_vport * fc_vport_create(struct Scsi_Host *shost, int channel, struct fc_vport_identifiers *ids)
```

Admin App or LLDD requests creation of a vport

**Parameters**

- `struct Scsi_Host *shost`: scsi host the virtual port is connected to.
- `int channel`: channel on shost port connected to.
- `struct fc_vport_identifiers *ids`: The world wide names, FC4 port roles, etc for
  the virtual port.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_vport_terminate"></a>`fc_vport_terminate()`

```c
int fc_vport_terminate(struct fc_vport *vport)
```

Admin App or LLDD requests termination of a vport

**Parameters**

- `struct fc_vport *vport`: fc_vport to be terminated

**Description**

Calls the LLDD `vport_delete()` function, then deallocates and removes
the vport from the shost and object tree.

**Notes**

This routine assumes no locks are held on entry.


<a id="rst-iscsi-transport-class"></a>

#### iSCSI transport class

The file drivers/scsi/scsi_transport_iscsi.c defines transport attributes for the iSCSI class, which sends SCSI packets over TCP/IP connections.


#### <a id="c-iscsi_lookup_endpoint"></a>`iscsi_lookup_endpoint()`

```c
struct iscsi_endpoint * iscsi_lookup_endpoint(u64 handle)
```

get ep from handle

**Parameters**

- `u64 handle`: endpoint handle

**Description**

Caller must do a iscsi_put_endpoint.

#### <a id="c-iscsi_create_flashnode_sess"></a>`iscsi_create_flashnode_sess()`

```c
struct iscsi_bus_flash_session * iscsi_create_flashnode_sess(struct Scsi_Host *shost, int index, struct iscsi_transport *transport, int dd_size)
```

Add flashnode session entry in sysfs

**Parameters**

- `struct Scsi_Host *shost`: pointer to host data
- `int index`: index of flashnode to add in sysfs
- `struct iscsi_transport *transport`: pointer to transport data
- `int dd_size`: total size to allocate

**Description**

Adds a sysfs entry for the flashnode session attributes

**Return**

pointer to allocated flashnode sess on success
`NULL` on failure

#### <a id="c-iscsi_create_flashnode_conn"></a>`iscsi_create_flashnode_conn()`

```c
struct iscsi_bus_flash_conn * iscsi_create_flashnode_conn(struct Scsi_Host *shost, struct iscsi_bus_flash_session *fnode_sess, struct iscsi_transport *transport, int dd_size)
```

Add flashnode conn entry in sysfs

**Parameters**

- `struct Scsi_Host *shost`: pointer to host data
- `struct iscsi_bus_flash_session *fnode_sess`: pointer to the parent flashnode session entry
- `struct iscsi_transport *transport`: pointer to transport data
- `int dd_size`: total size to allocate

**Description**

Adds a sysfs entry for the flashnode connection attributes

**Return**

pointer to allocated flashnode conn on success
`NULL` on failure

#### <a id="c-iscsi_find_flashnode_sess"></a>`iscsi_find_flashnode_sess()`

```c
struct device * iscsi_find_flashnode_sess(struct Scsi_Host *shost, const void *data, device_match_t fn)
```

finds flashnode session entry

**Parameters**

- `struct Scsi_Host *shost`: pointer to host data
- `const void *data`: pointer to data containing value to use for comparison
- `device_match_t fn`: function pointer that does actual comparison

**Description**

Finds the flashnode session object comparing the data passed using logic
defined in passed function pointer

**Return**

pointer to found flashnode session device object on success
`NULL` on failure

#### <a id="c-iscsi_find_flashnode_conn"></a>`iscsi_find_flashnode_conn()`

```c
struct device * iscsi_find_flashnode_conn(struct iscsi_bus_flash_session *fnode_sess)
```

finds flashnode connection entry

**Parameters**

- `struct iscsi_bus_flash_session *fnode_sess`: pointer to parent flashnode session entry

**Description**

Finds the flashnode connection object comparing the data passed using logic
defined in passed function pointer

**Return**

pointer to found flashnode connection device object on success
`NULL` on failure

#### <a id="c-iscsi_destroy_flashnode_sess"></a>`iscsi_destroy_flashnode_sess()`

```c
void iscsi_destroy_flashnode_sess(struct iscsi_bus_flash_session *fnode_sess)
```

destroy flashnode session entry

**Parameters**

- `struct iscsi_bus_flash_session *fnode_sess`: pointer to flashnode session entry to be destroyed

**Description**

Deletes the flashnode session entry and all children flashnode connection
entries from sysfs

#### <a id="c-iscsi_destroy_all_flashnode"></a>`iscsi_destroy_all_flashnode()`

```c
void iscsi_destroy_all_flashnode(struct Scsi_Host *shost)
```

destroy all flashnode session entries

**Parameters**

- `struct Scsi_Host *shost`: pointer to host data

**Description**

Destroys all the flashnode session entries and all corresponding children
flashnode connection entries from sysfs

#### <a id="c-iscsi_block_scsi_eh"></a>`iscsi_block_scsi_eh()`

```c
int iscsi_block_scsi_eh(struct scsi_cmnd *cmd)
```

block scsi eh until session state has transistioned

**Parameters**

- `struct scsi_cmnd *cmd`: scsi cmd passed to scsi eh handler

**Description**

If the session is down this function will wait for the recovery
timer to fire or for the session to be logged back in. If the
recovery timer fires then FAST_IO_FAIL is returned. The caller
should pass this error value to the scsi eh.

#### <a id="c-iscsi_unblock_session"></a>`iscsi_unblock_session()`

```c
void iscsi_unblock_session(struct iscsi_cls_session *session)
```

set a session as logged in and start IO.

**Parameters**

- `struct iscsi_cls_session *session`: iscsi session

**Description**

Mark a session as ready to accept IO.

#### <a id="c-iscsi_force_destroy_session"></a>`iscsi_force_destroy_session()`

```c
void iscsi_force_destroy_session(struct iscsi_cls_session *session)
```

destroy a session from the kernel

**Parameters**

- `struct iscsi_cls_session *session`: session to destroy

**Description**

Force the destruction of a session from the kernel. This should only be
used when userspace is no longer running during system shutdown.

#### <a id="c-iscsi_alloc_conn"></a>`iscsi_alloc_conn()`

```c
struct iscsi_cls_conn * iscsi_alloc_conn(struct iscsi_cls_session *session, int dd_size, uint32_t cid)
```

alloc iscsi class connection

**Parameters**

- `struct iscsi_cls_session *session`: iscsi cls session
- `int dd_size`: private driver data size
- `uint32_t cid`: connection id

#### <a id="c-iscsi_add_conn"></a>`iscsi_add_conn()`

```c
int iscsi_add_conn(struct iscsi_cls_conn *conn)
```

add iscsi class connection

**Parameters**

- `struct iscsi_cls_conn *conn`: iscsi cls connection

**Description**

This will expose iscsi_cls_conn to sysfs so make sure the related
resources for sysfs attributes are initialized before calling this.

#### <a id="c-iscsi_remove_conn"></a>`iscsi_remove_conn()`

```c
void iscsi_remove_conn(struct iscsi_cls_conn *conn)
```

remove iscsi class connection from sysfs

**Parameters**

- `struct iscsi_cls_conn *conn`: iscsi cls connection

**Description**

Remove iscsi_cls_conn from sysfs, and wait for previous
read/write of iscsi_cls_conn's attributes in sysfs to finish.

#### <a id="c-iscsi_session_event"></a>`iscsi_session_event()`

```c
int iscsi_session_event(struct iscsi_cls_session *session, enum iscsi_uevent_e event)
```

send session destr. completion event

**Parameters**

- `struct iscsi_cls_session *session`: iscsi class session
- `enum iscsi_uevent_e event`: type of event


<a id="rst-serial-attached-scsi-sas-transport-class"></a>

#### Serial Attached SCSI (SAS) transport class

The file drivers/scsi/scsi_transport_sas.c defines transport attributes for Serial Attached SCSI, a variant of SATA aimed at large high-end systems.

The SAS transport class contains common code to deal with SAS HBAs, an approximated representation of SAS topologies in the driver model, and various sysfs attributes to expose these topologies and management interfaces to userspace.

In addition to the basic SCSI core objects this transport class introduces two additional intermediate objects: The SAS PHY as represented by struct sas_phy defines an "outgoing" PHY on a SAS HBA or Expander, and the SAS remote PHY represented by struct sas_rphy defines an "incoming" PHY on a SAS Expander or end device. Note that this is purely a software concept, the underlying hardware for a PHY and a remote PHY is the exactly the same.

There is no concept of a SAS port in this code, users can see what PHYs form a wide port based on the port_identifier attribute, which is the same for all PHYs in a port.


#### <a id="c-sas_remove_children"></a>`sas_remove_children()`

```c
void sas_remove_children(struct device *dev)
```

tear down a devices SAS data structures

**Parameters**

- `struct device *dev`: device belonging to the sas object

**Description**

Removes all SAS PHYs and remote PHYs for a given object

#### <a id="c-sas_remove_host"></a>`sas_remove_host()`

```c
void sas_remove_host(struct Scsi_Host *shost)
```

tear down a Scsi_Host's SAS data structures

**Parameters**

- `struct Scsi_Host *shost`: Scsi Host that is torn down

**Description**

Removes all SAS PHYs and remote PHYs for a given Scsi_Host and remove the
Scsi_Host as well.

**Note**

Do not call [`scsi_remove_host()`](#c-scsi_remove_host) on the Scsi_Host any more, as it is
already removed.

#### <a id="c-sas_get_address"></a>`sas_get_address()`

```c
u64 sas_get_address(struct scsi_device *sdev)
```

return the SAS address of the device

**Parameters**

- `struct scsi_device *sdev`: scsi device

**Description**

Returns the SAS address of the scsi device

#### <a id="c-sas_tlr_supported"></a>`sas_tlr_supported()`

```c
unsigned int sas_tlr_supported(struct scsi_device *sdev)
```

checking TLR bit in vpd 0x90

**Parameters**

- `struct scsi_device *sdev`: scsi device struct

**Description**

Check Transport Layer Retries are supported or not.
If vpd page 0x90 is present, TRL is supported.

#### <a id="c-sas_disable_tlr"></a>`sas_disable_tlr()`

```c
void sas_disable_tlr(struct scsi_device *sdev)
```

setting TLR flags

**Parameters**

- `struct scsi_device *sdev`: scsi device struct

**Description**

Seting tlr_enabled flag to 0.

#### <a id="c-sas_enable_tlr"></a>`sas_enable_tlr()`

```c
void sas_enable_tlr(struct scsi_device *sdev)
```

setting TLR flags

**Parameters**

- `struct scsi_device *sdev`: scsi device struct

**Description**

Seting tlr_enabled flag 1.

#### <a id="c-sas_ata_ncq_prio_supported"></a>`sas_ata_ncq_prio_supported()`

```c
bool sas_ata_ncq_prio_supported(struct scsi_device *sdev)
```

Check for ATA NCQ command priority support

**Parameters**

- `struct scsi_device *sdev`: SCSI device

**Description**

Check if an ATA device supports NCQ priority using VPD page 89h (ATA
Information). Since this VPD page is implemented only for ATA devices,
this function always returns false for SCSI devices.

#### <a id="c-sas_phy_alloc"></a>`sas_phy_alloc()`

```c
struct sas_phy * sas_phy_alloc(struct device *parent, int number)
```

allocates and initialize a SAS PHY structure

**Parameters**

- `struct device *parent`: Parent device
- `int number`: Phy index

**Description**

Allocates an SAS PHY structure.  It will be added in the device tree
below the device specified by **parent**, which has to be either a Scsi_Host
or sas_rphy.

**Return**

SAS PHY allocated or `NULL` if the allocation failed.

#### <a id="c-sas_phy_add"></a>`sas_phy_add()`

```c
int sas_phy_add(struct sas_phy *phy)
```

add a SAS PHY to the device hierarchy

**Parameters**

- `struct sas_phy *phy`: The PHY to be added

**Description**

Publishes a SAS PHY to the rest of the system.

#### <a id="c-sas_phy_free"></a>`sas_phy_free()`

```c
void sas_phy_free(struct sas_phy *phy)
```

free a SAS PHY

**Parameters**

- `struct sas_phy *phy`: SAS PHY to free

**Description**

Frees the specified SAS PHY.

**Note**

This function must only be called on a PHY that has not
successfully been added using [`sas_phy_add()`](#c-sas_phy_add).

#### <a id="c-sas_phy_delete"></a>`sas_phy_delete()`

```c
void sas_phy_delete(struct sas_phy *phy)
```

remove SAS PHY

**Parameters**

- `struct sas_phy *phy`: SAS PHY to remove

**Description**

Removes the specified SAS PHY.  If the SAS PHY has an
associated remote PHY it is removed before.

#### <a id="c-scsi_is_sas_phy"></a>`scsi_is_sas_phy()`

```c
int scsi_is_sas_phy(const struct device *dev)
```

check if a struct device represents a SAS PHY

**Parameters**

- `const struct device *dev`: device to check

**Return**

`1` if the device represents a SAS PHY, `0` else

#### <a id="c-sas_port_alloc"></a>`sas_port_alloc()`

```c
struct sas_port * sas_port_alloc(struct device *parent, int port_id)
```

allocate and initialize a SAS port structure

**Parameters**

- `struct device *parent`: parent device
- `int port_id`: port number

**Description**

Allocates a SAS port structure.  It will be added to the device tree
below the device specified by **parent** which must be either a Scsi_Host
or a sas_expander_device.

**Return**

`NULL` on error

#### <a id="c-sas_port_alloc_num"></a>`sas_port_alloc_num()`

```c
struct sas_port * sas_port_alloc_num(struct device *parent)
```

allocate and initialize a SAS port structure

**Parameters**

- `struct device *parent`: parent device

**Description**

Allocates a SAS port structure and a number to go with it.  This
interface is really for adapters where the port number has no
meansing, so the sas class should manage them.  It will be added to
the device tree below the device specified by **parent** which must be
either a Scsi_Host or a sas_expander_device.

**Return**

`NULL` on error

#### <a id="c-sas_port_add"></a>`sas_port_add()`

```c
int sas_port_add(struct sas_port *port)
```

add a SAS port to the device hierarchy

**Parameters**

- `struct sas_port *port`: port to be added

**Description**

publishes a port to the rest of the system

#### <a id="c-sas_port_free"></a>`sas_port_free()`

```c
void sas_port_free(struct sas_port *port)
```

free a SAS PORT

**Parameters**

- `struct sas_port *port`: SAS PORT to free

**Description**

Frees the specified SAS PORT.

**Note**

This function must only be called on a PORT that has not
successfully been added using [`sas_port_add()`](#c-sas_port_add).

#### <a id="c-sas_port_delete"></a>`sas_port_delete()`

```c
void sas_port_delete(struct sas_port *port)
```

remove SAS PORT

**Parameters**

- `struct sas_port *port`: SAS PORT to remove

**Description**

Removes the specified SAS PORT.  If the SAS PORT has an
associated phys, unlink them from the port as well.

#### <a id="c-scsi_is_sas_port"></a>`scsi_is_sas_port()`

```c
int scsi_is_sas_port(const struct device *dev)
```

check if a struct device represents a SAS port

**Parameters**

- `const struct device *dev`: device to check

**Return**

`1` if the device represents a SAS Port, `0` else

#### <a id="c-sas_port_get_phy"></a>`sas_port_get_phy()`

```c
struct sas_phy * sas_port_get_phy(struct sas_port *port)
```

try to take a reference on a port member

**Parameters**

- `struct sas_port *port`: port to check

#### <a id="c-sas_port_add_phy"></a>`sas_port_add_phy()`

```c
void sas_port_add_phy(struct sas_port *port, struct sas_phy *phy)
```

add another phy to a port to form a wide port

**Parameters**

- `struct sas_port *port`: port to add the phy to
- `struct sas_phy *phy`: phy to add

**Description**

When a port is initially created, it is empty (has no phys).  All
ports must have at least one phy to operated, and all wide ports
must have at least two.  The current code makes no difference
between ports and wide ports, but the only object that can be
connected to a remote device is a port, so ports must be formed on
all devices with phys if they're connected to anything.

#### <a id="c-sas_port_delete_phy"></a>`sas_port_delete_phy()`

```c
void sas_port_delete_phy(struct sas_port *port, struct sas_phy *phy)
```

remove a phy from a port or wide port

**Parameters**

- `struct sas_port *port`: port to remove the phy from
- `struct sas_phy *phy`: phy to remove

**Description**

This operation is used for tearing down ports again.  It must be
done to every port or wide port before calling sas_port_delete.

#### <a id="c-sas_end_device_alloc"></a>`sas_end_device_alloc()`

```c
struct sas_rphy * sas_end_device_alloc(struct sas_port *parent)
```

allocate an rphy for an end device

**Parameters**

- `struct sas_port *parent`: which port

**Description**

Allocates an SAS remote PHY structure, connected to **parent**.

**Return**

SAS PHY allocated or `NULL` if the allocation failed.

#### <a id="c-sas_expander_alloc"></a>`sas_expander_alloc()`

```c
struct sas_rphy * sas_expander_alloc(struct sas_port *parent, enum sas_device_type type)
```

allocate an rphy for an end device

**Parameters**

- `struct sas_port *parent`: which port
- `enum sas_device_type type`: SAS_EDGE_EXPANDER_DEVICE or SAS_FANOUT_EXPANDER_DEVICE

**Description**

Allocates an SAS remote PHY structure, connected to **parent**.

**Return**

SAS PHY allocated or `NULL` if the allocation failed.

#### <a id="c-sas_rphy_add"></a>`sas_rphy_add()`

```c
int sas_rphy_add(struct sas_rphy *rphy)
```

add a SAS remote PHY to the device hierarchy

**Parameters**

- `struct sas_rphy *rphy`: The remote PHY to be added

**Description**

Publishes a SAS remote PHY to the rest of the system.

#### <a id="c-sas_rphy_free"></a>`sas_rphy_free()`

```c
void sas_rphy_free(struct sas_rphy *rphy)
```

free a SAS remote PHY

**Parameters**

- `struct sas_rphy *rphy`: SAS remote PHY to free

**Description**

Frees the specified SAS remote PHY.

**Note**

This function must only be called on a remote
PHY that has not successfully been added using
[`sas_rphy_add()`](#c-sas_rphy_add) (or has been [`sas_rphy_remove()`](#c-sas_rphy_remove)'d)

#### <a id="c-sas_rphy_delete"></a>`sas_rphy_delete()`

```c
void sas_rphy_delete(struct sas_rphy *rphy)
```

remove and free SAS remote PHY

**Parameters**

- `struct sas_rphy *rphy`: SAS remote PHY to remove and free

**Description**

Removes the specified SAS remote PHY and frees it.

#### <a id="c-sas_rphy_unlink"></a>`sas_rphy_unlink()`

```c
void sas_rphy_unlink(struct sas_rphy *rphy)
```

unlink SAS remote PHY

**Parameters**

- `struct sas_rphy *rphy`: SAS remote phy to unlink from its parent port

**Description**

Removes port reference to an rphy

#### <a id="c-sas_rphy_remove"></a>`sas_rphy_remove()`

```c
void sas_rphy_remove(struct sas_rphy *rphy)
```

remove SAS remote PHY

**Parameters**

- `struct sas_rphy *rphy`: SAS remote phy to remove

**Description**

Removes the specified SAS remote PHY.

#### <a id="c-scsi_is_sas_rphy"></a>`scsi_is_sas_rphy()`

```c
int scsi_is_sas_rphy(const struct device *dev)
```

check if a struct device represents a SAS remote PHY

**Parameters**

- `const struct device *dev`: device to check

**Return**

`1` if the device represents a SAS remote PHY, `0` else

#### <a id="c-sas_attach_transport"></a>`sas_attach_transport()`

```c
struct scsi_transport_template * sas_attach_transport(struct sas_function_template *ft)
```

instantiate SAS transport template

**Parameters**

- `struct sas_function_template *ft`: SAS transport class function template

#### <a id="c-sas_release_transport"></a>`sas_release_transport()`

```c
void sas_release_transport(struct scsi_transport_template *t)
```

release SAS transport template instance

**Parameters**

- `struct scsi_transport_template *t`: transport template instance


<a id="rst-sata-transport-class"></a>

#### SATA transport class

The SATA transport is handled by libata, which has its own book of documentation in this directory.

<a id="rst-parallel-scsi-spi-transport-class"></a>

#### Parallel SCSI (SPI) transport class

The file drivers/scsi/scsi_transport_spi.c defines transport attributes for traditional (fast/wide/ultra) SCSI buses.


#### <a id="c-spi_dv_device"></a>`spi_dv_device()`

```c
void spi_dv_device(struct scsi_device *sdev)
```

Do Domain Validation on the device

**Parameters**

- `struct scsi_device *sdev`: scsi device to validate

**Description**

Performs the domain validation on the given device in the
current execution thread.  Since DV operations may sleep,
the current thread must have user context.  Also no SCSI
related locks that would deadlock I/O issued by the DV may
be held.

#### <a id="c-spi_schedule_dv_device"></a>`spi_schedule_dv_device()`

```c
void spi_schedule_dv_device(struct scsi_device *sdev)
```

schedule domain validation to occur on the device

**Parameters**

- `struct scsi_device *sdev`: The device to validate

**Description**

Identical to [`spi_dv_device()`](#c-spi_dv_device) above, except that the DV will be
scheduled to occur in a workqueue later.  All memory allocations
are atomic, so may be called from any context including those holding
SCSI locks.

#### <a id="c-spi_display_xfer_agreement"></a>`spi_display_xfer_agreement()`

```c
void spi_display_xfer_agreement(struct scsi_target *starget)
```

Print the current target transfer agreement

**Parameters**

- `struct scsi_target *starget`: The target for which to display the agreement

**Description**

Each SPI port is required to maintain a transfer agreement for each
other port on the bus.  This function prints a one-line summary of
the current agreement; more detailed information is available in sysfs.

#### <a id="c-spi_populate_tag_msg"></a>`spi_populate_tag_msg()`

```c
int spi_populate_tag_msg(unsigned char *msg, struct scsi_cmnd *cmd)
```

place a tag message in a buffer

**Parameters**

- `unsigned char *msg`: pointer to the area to place the tag
- `struct scsi_cmnd *cmd`: pointer to the scsi command for the tag

**Notes**

designed to create the correct type of tag message for the
particular request.  Returns the size of the tag message.
May return 0 if TCQ is disabled for this device.


<a id="rst-scsi-rdma-srp-transport-class"></a>

#### SCSI RDMA (SRP) transport class

The file drivers/scsi/scsi_transport_srp.c defines transport attributes for SCSI over Remote Direct Memory Access.


#### <a id="c-srp_tmo_valid"></a>`srp_tmo_valid()`

```c
int srp_tmo_valid(int reconnect_delay, int fast_io_fail_tmo, long dev_loss_tmo)
```

check timeout combination validity

**Parameters**

- `int reconnect_delay`: Reconnect delay in seconds.
- `int fast_io_fail_tmo`: Fast I/O fail timeout in seconds.
- `long dev_loss_tmo`: Device loss timeout in seconds.

**Description**

The combination of the timeout parameters must be such that SCSI commands
are finished in a reasonable time. Hence do not allow the fast I/O fail
timeout to exceed SCSI_DEVICE_BLOCK_MAX_TIMEOUT nor allow dev_loss_tmo to
exceed that limit if failing I/O fast has been disabled. Furthermore, these
parameters must be such that multipath can detect failed paths timely.
Hence do not allow all three parameters to be disabled simultaneously.

#### <a id="c-srp_start_tl_fail_timers"></a>`srp_start_tl_fail_timers()`

```c
void srp_start_tl_fail_timers(struct srp_rport *rport)
```

start the transport layer failure timers

**Parameters**

- `struct srp_rport *rport`: SRP target port.

**Description**

Start the transport layer fast I/O failure and device loss timers. Do not
modify a timer that was already started.

#### <a id="c-srp_reconnect_rport"></a>`srp_reconnect_rport()`

```c
int srp_reconnect_rport(struct srp_rport *rport)
```

reconnect to an SRP target port

**Parameters**

- `struct srp_rport *rport`: SRP target port.

**Description**

Blocks SCSI command queueing before invoking `reconnect()` such that
`queuecommand()` won't be invoked concurrently with `reconnect()` from outside
the SCSI EH. This is important since a `reconnect()` implementation may
reallocate resources needed by `queuecommand()`.

**Notes**

- This function neither waits until outstanding requests have finished nor
  tries to abort these. It is the responsibility of the `reconnect()`
  function to finish outstanding commands before reconnecting to the target
  port.
- It is the responsibility of the caller to ensure that the resources
  reallocated by the `reconnect()` function won't be used while this function
  is in progress. One possible strategy is to invoke this function from
  the context of the SCSI EH thread only. Another possible strategy is to
  lock the rport mutex inside each SCSI LLD callback that can be invoked by
  the SCSI EH (the scsi_host_template.eh_*() functions and also the
  scsi_host_template.`queuecommand()` function).

#### <a id="c-srp_timed_out"></a>`srp_timed_out()`

```c
enum scsi_timeout_action srp_timed_out(struct scsi_cmnd *scmd)
```

SRP transport intercept of the SCSI timeout EH

**Parameters**

- `struct scsi_cmnd *scmd`: SCSI command.

**Description**

If a timeout occurs while an rport is in the blocked state, ask the SCSI
EH to continue waiting (SCSI_EH_RESET_TIMER). Otherwise let the SCSI core
handle the timeout (SCSI_EH_NOT_HANDLED).

**Note**

This function is called from soft-IRQ context and with the request
queue lock held.

#### <a id="c-srp_rport_get"></a>`srp_rport_get()`

```c
void srp_rport_get(struct srp_rport *rport)
```

increment rport reference count

**Parameters**

- `struct srp_rport *rport`: SRP target port.

#### <a id="c-srp_rport_put"></a>`srp_rport_put()`

```c
void srp_rport_put(struct srp_rport *rport)
```

decrement rport reference count

**Parameters**

- `struct srp_rport *rport`: SRP target port.

#### <a id="c-srp_rport_add"></a>`srp_rport_add()`

```c
struct srp_rport * srp_rport_add(struct Scsi_Host *shost, struct srp_rport_identifiers *ids)
```

add a SRP remote port to the device hierarchy

**Parameters**

- `struct Scsi_Host *shost`: scsi host the remote port is connected to.
- `struct srp_rport_identifiers *ids`: The port id for the remote port.

**Description**

Publishes a port to the rest of the system.

#### <a id="c-srp_rport_del"></a>`srp_rport_del()`

```c
void srp_rport_del(struct srp_rport *rport)
```

remove a SRP remote port

**Parameters**

- `struct srp_rport *rport`: SRP remote port to remove

**Description**

Removes the specified SRP remote port.

#### <a id="c-srp_remove_host"></a>`srp_remove_host()`

```c
void srp_remove_host(struct Scsi_Host *shost)
```

tear down a Scsi_Host's SRP data structures

**Parameters**

- `struct Scsi_Host *shost`: Scsi Host that is torn down

**Description**

Removes all SRP remote ports for a given Scsi_Host.
Must be called just before scsi_remove_host for SRP HBAs.

#### <a id="c-srp_stop_rport_timers"></a>`srp_stop_rport_timers()`

```c
void srp_stop_rport_timers(struct srp_rport *rport)
```

stop the transport layer recovery timers

**Parameters**

- `struct srp_rport *rport`: SRP remote port for which to stop the timers.

**Description**

Must be called after [`srp_remove_host()`](#c-srp_remove_host) and [`scsi_remove_host()`](#c-scsi_remove_host). The caller
must hold a reference on the rport (rport->dev) and on the SCSI host
(rport->dev.parent).

#### <a id="c-srp_attach_transport"></a>`srp_attach_transport()`

```c
struct scsi_transport_template * srp_attach_transport(struct srp_function_template *ft)
```

instantiate SRP transport template

**Parameters**

- `struct srp_function_template *ft`: SRP transport class function template

#### <a id="c-srp_release_transport"></a>`srp_release_transport()`

```c
void srp_release_transport(struct scsi_transport_template *t)
```

release SRP transport template instance

**Parameters**

- `struct scsi_transport_template *t`: transport template instance


<a id="rst-scsi-lower-layer"></a>

## SCSI lower layer

<a id="rst-host-bus-adapter-transport-types"></a>

### Host Bus Adapter transport types

Many modern device controllers use the SCSI command set as a protocol to communicate with their devices through many different types of physical connections.

In SCSI language a bus capable of carrying SCSI commands is called a "transport", and a controller connecting to such a bus is called a "host bus adapter" (HBA).

<a id="rst-debug-transport"></a>

#### Debug transport

The file drivers/scsi/scsi_debug.c simulates a host adapter with a variable number of disks (or disk like devices) attached, sharing a common amount of RAM. Does a lot of checking to make sure that we are not getting blocks mixed up, and panics the kernel if anything out of the ordinary is seen.

To be more realistic, the simulated devices have the transport attributes of SAS disks.

For documentation see [http://sg.danny.cz/sg/scsi_debug.html](<http://sg.danny.cz/sg/scsi_debug.html>)

<a id="rst-todo"></a>

#### todo

Parallel (fast/wide/ultra) SCSI, USB, SATA, SAS, Fibre Channel, FireWire, ATAPI devices, Infiniband, Parallel ports, netlink...

---

# Linux kernel SLIMbus support

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> SLIMbus (Serial Low Power Interchip Media Bus) is a specification developed by MIPI (Mobile Industry Processor Interface) alliance. The bus uses master/slave configuration, and is a 2-wire multi-drop implementation (clock, and data).

<a id="rst-linux-kernel-slimbus-support"></a>

<a id="rst-overview"></a>

## Overview

<a id="rst-what-is-slimbus"></a>

## What is SLIMbus?

SLIMbus (Serial Low Power Interchip Media Bus) is a specification developed by MIPI (Mobile Industry Processor Interface) alliance. The bus uses master/slave configuration, and is a 2-wire multi-drop implementation (clock, and data).

Currently, SLIMbus is used to interface between application processors of SoCs (System-on-Chip) and peripheral components (typically codec). SLIMbus uses Time-Division-Multiplexing to accommodate multiple data channels, and a control channel.

The control channel is used for various control functions such as bus management, configuration and status updates. These messages can be unicast (e.g. reading/writing device specific values), or multicast (e.g. data channel reconfiguration sequence is a broadcast message announced to all devices)

A data channel is used for data-transfer between 2 SLIMbus devices. Data channel uses dedicated ports on the device.

<a id="rst-hardware-description"></a>

## Hardware description:

SLIMbus specification has different types of device classifications based on their capabilities. A manager device is responsible for enumeration, configuration, and dynamic channel allocation. Every bus has 1 active manager.

A generic device is a device providing application functionality (e.g. codec).

Framer device is responsible for clocking the bus, and transmitting frame-sync and framing information on the bus.

Each SLIMbus component has an interface device for monitoring physical layer.

Typically each SoC contains SLIMbus component having 1 manager, 1 framer device, 1 generic device (for data channel support), and 1 interface device. External peripheral SLIMbus component usually has 1 generic device (for functionality/data channel support), and an associated interface device. The generic device's registers are mapped as 'value elements' so that they can be written/read using SLIMbus control channel exchanging control/status type of information. In case there are multiple framer devices on the same bus, manager device is responsible to select the active-framer for clocking the bus.

Per specification, SLIMbus uses "clock gears" to do power management based on current frequency and bandwidth requirements. There are 10 clock gears and each gear changes the SLIMbus frequency to be twice its previous gear.

Each device has a 6-byte enumeration-address and the manager assigns every device with a 1-byte logical address after the devices report presence on the bus.

<a id="rst-software-description"></a>

## Software description:

There are 2 types of SLIMbus drivers:

slim_controller represents a 'controller' for SLIMbus. This driver should implement duties needed by the SoC (manager device, associated interface device for monitoring the layers and reporting errors, default framer device).

slim_device represents the 'generic device/component' for SLIMbus, and a slim_driver should implement driver for that slim_device.

<a id="rst-device-notifications-to-the-driver"></a>

## Device notifications to the driver:

Since SLIMbus devices have mechanisms for reporting their presence, the framework allows drivers to bind when corresponding devices report their presence on the bus. However, it is possible that the driver needs to be probed first so that it can enable corresponding SLIMbus device (e.g. power it up and/or take it out of reset). To support that behavior, the framework allows drivers to probe first as well  (e.g. using standard DeviceTree compatibility field). This creates the necessity for the driver to know when the device is functional (i.e. reported present). device_up callback is used for that reason when the device reports present and is assigned a logical address by the controller.

Similarly, SLIMbus devices 'report absent' when they go down. A 'device_down' callback notifies the driver when the device reports absent and its logical address assignment is invalidated by the controller.

Another notification "boot_device" is used to notify the slim_driver when controller resets the bus. This notification allows the driver to take necessary steps to boot the device so that it's functional after the bus has been reset.

<a id="rst-driver-and-controller-apis"></a>

## Driver and Controller APIs:


#### <a id="c-struct-slim_eaddr"></a>`struct slim_eaddr`

Enumeration address for a SLIMbus device

**Definition**

```c
struct slim_eaddr {
    u8 instance;
    u8 dev_index;
    u16 prod_code;
    u16 manf_id;
};
```

**Members**

- `instance`: Instance value
- `dev_index`: Device index
- `prod_code`: Product code
- `manf_id`: Manufacturer Id for the device

#### <a id="c-enum-slim_device_status"></a>`enum slim_device_status`

slim device status

**Constants**

- `SLIM_DEVICE_STATUS_DOWN`: Slim device is absent or not reported yet.
- `SLIM_DEVICE_STATUS_UP`: Slim device is announced on the bus.
- `SLIM_DEVICE_STATUS_RESERVED`: Reserved for future use.

#### <a id="c-struct-slim_device"></a>`struct slim_device`

Slim device handle.

**Definition**

```c
struct slim_device {
    struct device           dev;
    struct slim_eaddr       e_addr;
    struct slim_controller  *ctrl;
    enum slim_device_status status;
    u8 laddr;
    bool is_laddr_valid;
    struct list_head        stream_list;
    spinlock_t stream_list_lock;
};
```

**Members**

- `dev`: Driver model representation of the device.
- `e_addr`: Enumeration address of this device.
- `ctrl`: slim controller instance.
- `status`: slim device status
- `laddr`: 1-byte Logical address of this device.
- `is_laddr_valid`: indicates if the laddr is valid or not
- `stream_list`: List of streams on this device
- `stream_list_lock`: lock to protect the stream list

**Description**

This is the client/device handle returned when a SLIMbus
device is registered with a controller.
Pointer to this structure is used by client-driver as a handle.

#### <a id="c-struct-slim_driver"></a>`struct slim_driver`

SLIMbus 'generic device' (slave) device driver (similar to 'spi_device' on SPI)

**Definition**

```c
struct slim_driver {
    int (*probe)(struct slim_device *sl);
    void (*remove)(struct slim_device *sl);
    void (*shutdown)(struct slim_device *sl);
    int (*device_status)(struct slim_device *sl, enum slim_device_status s);
    struct device_driver            driver;
    const struct slim_device_id     *id_table;
};
```

**Members**

- `probe`: Binds this driver to a SLIMbus device.
- `remove`: Unbinds this driver from the SLIMbus device.
- `shutdown`: Standard shutdown callback used during powerdown/halt.
- `device_status`: This callback is called when
  - The device reports present and gets a laddr assigned
  - The device reports absent, or the bus goes down.
- `driver`: SLIMbus device drivers should initialize name and owner field of
  this structure
- `id_table`: List of SLIMbus devices supported by this driver

#### <a id="c-struct-slim_val_inf"></a>`struct slim_val_inf`

Slimbus value or information element

**Definition**

```c
struct slim_val_inf {
    u16 start_offset;
    u8 num_bytes;
    u8 *rbuf;
    const u8                *wbuf;
    struct completion      *comp;
};
```

**Members**

- `start_offset`: Specifies starting offset in information/value element map
- `num_bytes`: upto 16. This ensures that the message will fit the slicesize
  per SLIMbus spec
- `rbuf`: buffer to read the values
- `wbuf`: buffer to write
- `comp`: completion for asynchronous operations, valid only if TID is
  required for transaction, like REQUEST operations.
  Rest of the transactions are synchronous anyway.

#### <a id="c-struct-slim_stream_config"></a>`struct slim_stream_config`

SLIMbus stream configuration Configuring a stream is done at hw_params or prepare call from audio drivers where they have all the required information regarding rate, number of channels and so on. There is a 1:1 mapping of channel and ports.

**Definition**

```c
struct slim_stream_config {
    unsigned int rate;
    unsigned int bps;
    unsigned int ch_count;
    unsigned int *chs;
    unsigned long port_mask;
    int direction;
};
```

**Members**

- `rate`: data rate
- `bps`: bits per data sample
- `ch_count`: number of channels
- `chs`: pointer to list of channel numbers
- `port_mask`: port mask of ports to use for this stream
- `direction`: direction of the stream, SNDRV_PCM_STREAM_PLAYBACK
  or SNDRV_PCM_STREAM_CAPTURE.

#### <a id="c-module_slim_driver"></a>`module_slim_driver()`

```c
module_slim_driver(__slim_driver)
```

Helper macro for registering a SLIMbus driver

**Parameters**

- `__slim_driver`: slimbus_driver struct

**Description**

Helper macro for SLIMbus drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)



#### <a id="c-struct-slim_framer"></a>`struct slim_framer`

Represents SLIMbus framer. Every controller may have multiple framers. There is 1 active framer device responsible for clocking the bus. Manager is responsible for framer hand-over.

**Definition**

```c
struct slim_framer {
    struct device           dev;
    struct slim_eaddr       e_addr;
    int rootfreq;
    int superfreq;
};
```

**Members**

- `dev`: Driver model representation of the device.
- `e_addr`: Enumeration address of the framer.
- `rootfreq`: Root Frequency at which the framer can run. This is maximum
  frequency ('clock gear 10') at which the bus can operate.
- `superfreq`: Superframes per root frequency. Every frame is 6144 bits.

#### <a id="c-struct-slim_msg_txn"></a>`struct slim_msg_txn`

Message to be sent by the controller. This structure has packet header, payload and buffer to be filled (if any)

**Definition**

```c
struct slim_msg_txn {
    u8 rl;
    u8 mt;
    u8 mc;
    u8 dt;
    u16 ec;
    u8 tid;
    u8 la;
    struct slim_val_inf     *msg;
    struct completion      *comp;
};
```

**Members**

- `rl`: Header field. remaining length.
- `mt`: Header field. Message type.
- `mc`: Header field. LSB is message code for type mt.
- `dt`: Header field. Destination type.
- `ec`: Element code. Used for elemental access APIs.
- `tid`: Transaction ID. Used for messages expecting response.
  (relevant for message-codes involving read operation)
- `la`: Logical address of the device this message is going to.
  (Not used when destination type is broadcast.)
- `msg`: Elemental access message to be read/written
- `comp`: completion if read/write is synchronous, used internally
  for tid based transactions.

#### <a id="c-enum-slim_clk_state"></a>`enum slim_clk_state`

SLIMbus controller's clock state used internally for maintaining current clock state.

**Constants**

- `SLIM_CLK_ACTIVE`: SLIMbus clock is active
- `SLIM_CLK_ENTERING_PAUSE`: SLIMbus clock pause sequence is being sent on the
  bus. If this succeeds, state changes to SLIM_CLK_PAUSED. If the
  transition fails, state changes back to SLIM_CLK_ACTIVE
- `SLIM_CLK_PAUSED`: SLIMbus controller clock has paused.

#### <a id="c-struct-slim_sched"></a>`struct slim_sched`

Framework uses this structure internally for scheduling.

**Definition**

```c
struct slim_sched {
    enum slim_clk_state     clk_state;
    struct completion       pause_comp;
    struct mutex            m_reconf;
};
```

**Members**

- `clk_state`: Controller's clock state from enum slim_clk_state
- `pause_comp`: Signals completion of clock pause sequence. This is useful when
  client tries to call SLIMbus transaction when controller is entering
  clock pause.
- `m_reconf`: This mutex is held until current reconfiguration (data channel
  scheduling, message bandwidth reservation) is done. Message APIs can
  use the bus concurrently when this mutex is held since elemental access
  messages can be sent on the bus when reconfiguration is in progress.

#### <a id="c-enum-slim_port_direction"></a>`enum slim_port_direction`

SLIMbus port direction

**Constants**

- `SLIM_PORT_SINK`: SLIMbus port is a sink
- `SLIM_PORT_SOURCE`: SLIMbus port is a source

#### <a id="c-enum-slim_port_state"></a>`enum slim_port_state`

SLIMbus Port/Endpoint state machine according to SLIMbus Spec 2.0

**Constants**

- `SLIM_PORT_DISCONNECTED`: SLIMbus port is disconnected
  entered from Unconfigure/configured state after
  DISCONNECT_PORT or REMOVE_CHANNEL core command
- `SLIM_PORT_UNCONFIGURED`: SLIMbus port is in unconfigured state.
  entered from disconnect state after CONNECT_SOURCE/SINK core command
- `SLIM_PORT_CONFIGURED`: SLIMbus port is in configured state.
  entered from unconfigured state after DEFINE_CHANNEL, DEFINE_CONTENT
  and ACTIVATE_CHANNEL core commands. Ready for data transmission.

#### <a id="c-enum-slim_channel_state"></a>`enum slim_channel_state`

SLIMbus channel state machine used by core.

**Constants**

- `SLIM_CH_STATE_DISCONNECTED`: SLIMbus channel is disconnected
- `SLIM_CH_STATE_ALLOCATED`: SLIMbus channel is allocated
- `SLIM_CH_STATE_ASSOCIATED`: SLIMbus channel is associated with port
- `SLIM_CH_STATE_DEFINED`: SLIMbus channel parameters are defined
- `SLIM_CH_STATE_CONTENT_DEFINED`: SLIMbus channel content is defined
- `SLIM_CH_STATE_ACTIVE`: SLIMbus channel is active and ready for data
- `SLIM_CH_STATE_REMOVED`: SLIMbus channel is inactive and removed

#### <a id="c-enum-slim_ch_data_fmt"></a>`enum slim_ch_data_fmt`

SLIMbus channel data Type identifiers according to Table 60 of SLIMbus Spec 1.01.01

**Constants**

- `SLIM_CH_DATA_FMT_NOT_DEFINED`: Undefined
- `SLIM_CH_DATA_FMT_LPCM_AUDIO`: LPCM audio
- `SLIM_CH_DATA_FMT_IEC61937_COMP_AUDIO`: IEC61937 Compressed audio
- `SLIM_CH_DATA_FMT_PACKED_PDM_AUDIO`: Packed PDM audio

#### <a id="c-enum-slim_ch_aux_bit_fmt"></a>`enum slim_ch_aux_bit_fmt`

SLIMbus channel Aux Field format IDs according to Table 63 of SLIMbus Spec 2.0

**Constants**

- `SLIM_CH_AUX_FMT_NOT_APPLICABLE`: Undefined
- `SLIM_CH_AUX_FMT_ZCUV_TUNNEL_IEC60958`: ZCUV for tunneling IEC60958
- `SLIM_CH_AUX_FMT_USER_DEFINED`: User defined

#### <a id="c-struct-slim_channel"></a>`struct slim_channel`

SLIMbus channel, used for state machine

**Definition**

```c
struct slim_channel {
    int id;
    int prrate;
    int seg_dist;
    enum slim_ch_data_fmt data_fmt;
    enum slim_ch_aux_bit_fmt aux_fmt;
    enum slim_channel_state state;
};
```

**Members**

- `id`: ID of channel
- `prrate`: Presense rate of channel from Table 66 of SLIMbus 2.0 Specs
- `seg_dist`: segment distribution code from Table 20 of SLIMbus 2.0 Specs
- `data_fmt`: Data format of channel.
- `aux_fmt`: Aux format for this channel.
- `state`: channel state machine

#### <a id="c-struct-slim_port"></a>`struct slim_port`

SLIMbus port

**Definition**

```c
struct slim_port {
    int id;
    enum slim_port_direction direction;
    enum slim_port_state state;
    struct slim_channel ch;
};
```

**Members**

- `id`: Port id
- `direction`: Port direction, Source or Sink.
- `state`: state machine of port.
- `ch`: channel associated with this port.

#### <a id="c-enum-slim_transport_protocol"></a>`enum slim_transport_protocol`

SLIMbus Transport protocol list from Table 47 of SLIMbus 2.0 specs.

**Constants**

- `SLIM_PROTO_ISO`: Isochronous Protocol, no flow control as data rate match
  channel rate flow control embedded in the data.
- `SLIM_PROTO_PUSH`: Pushed Protocol, includes flow control, Used to carry
  data whose rate is equal to, or lower than the channel rate.
- `SLIM_PROTO_PULL`: Pulled Protocol, similar usage as pushed protocol
  but pull is a unicast.
- `SLIM_PROTO_LOCKED`: Locked Protocol
- `SLIM_PROTO_ASYNC_SMPLX`: Asynchronous Protocol-Simplex
- `SLIM_PROTO_ASYNC_HALF_DUP`: Asynchronous Protocol-Half-duplex
- `SLIM_PROTO_EXT_SMPLX`: Extended Asynchronous Protocol-Simplex
- `SLIM_PROTO_EXT_HALF_DUP`: Extended Asynchronous Protocol-Half-duplex

#### <a id="c-struct-slim_stream_runtime"></a>`struct slim_stream_runtime`

SLIMbus stream runtime instance

**Definition**

```c
struct slim_stream_runtime {
    const char *name;
    struct slim_device *dev;
    int direction;
    enum slim_transport_protocol prot;
    unsigned int rate;
    unsigned int bps;
    unsigned int ratem;
    int num_ports;
    struct slim_port *ports;
    struct list_head node;
};
```

**Members**

- `name`: Name of the stream
- `dev`: SLIM Device instance associated with this stream
- `direction`: direction of stream
- `prot`: Transport protocol used in this stream
- `rate`: Data rate of samples *
- `bps`: bits per sample
- `ratem`: rate multipler which is super frame rate/data rate
- `num_ports`: number of ports
- `ports`: pointer to instance of ports
- `node`: list head for stream associated with slim device.

#### <a id="c-struct-slim_controller"></a>`struct slim_controller`

Controls every instance of SLIMbus (similar to 'master' on SPI)

**Definition**

```c
struct slim_controller {
    struct device           *dev;
    unsigned int            id;
    char name[SLIMBUS_NAME_SIZE];
    int min_cg;
    int max_cg;
    int clkgear;
    struct ida              laddr_ida;
    struct slim_framer      *a_framer;
    struct mutex            lock;
    struct list_head        devices;
    struct idr              tid_idr;
    spinlock_t txn_lock;
    struct slim_sched       sched;
    int (*xfer_msg)(struct slim_controller *ctrl, struct slim_msg_txn *tx);
    int (*set_laddr)(struct slim_controller *ctrl, struct slim_eaddr *ea, u8 laddr);
    int (*get_laddr)(struct slim_controller *ctrl, struct slim_eaddr *ea, u8 *laddr);
    int (*enable_stream)(struct slim_stream_runtime *rt);
    int (*disable_stream)(struct slim_stream_runtime *rt);
    int (*wakeup)(struct slim_controller *ctrl);
};
```

**Members**

- `dev`: Device interface to this driver
- `id`: Board-specific number identifier for this controller/bus
- `name`: Name for this controller
- `min_cg`: Minimum clock gear supported by this controller (default value: 1)
- `max_cg`: Maximum clock gear supported by this controller (default value: 10)
- `clkgear`: Current clock gear in which this bus is running
- `laddr_ida`: logical address id allocator
- `a_framer`: Active framer which is clocking the bus managed by this controller
- `lock`: Mutex protecting controller data structures
- `devices`: Slim device list
- `tid_idr`: tid id allocator
- `txn_lock`: Lock to protect table of transactions
- `sched`: scheduler structure used by the controller
- `xfer_msg`: Transfer a message on this controller (this can be a broadcast
  control/status message like data channel setup, or a unicast message
  like value element read/write.
- `set_laddr`: Setup logical address at laddr for the slave with elemental
  address e_addr. Drivers implementing controller will be expected to
  send unicast message to this device with its logical address.
- `get_laddr`: It is possible that controller needs to set fixed logical
  address table and get_laddr can be used in that case so that controller
  can do this assignment. Use case is when the master is on the remote
  processor side, who is resposible for allocating laddr.
- `enable_stream`: This function pointer implements controller-specific procedure
  to enable a stream.
- `disable_stream`: This function pointer implements controller-specific procedure
  to disable stream.
- `wakeup`: This function pointer implements controller-specific procedure
  to wake it up from clock-pause. Framework will call this to bring
  the controller out of clock pause.

**Description**

'Manager device' is responsible for  device management, bandwidth
allocation, channel setup, and port associations per channel.
Device management means Logical address assignment/removal based on
enumeration (report-present, report-absent) of a device.
Bandwidth allocation is done dynamically by the manager based on active
channels on the bus, message-bandwidth requests made by SLIMbus devices.
Based on current bandwidth usage, manager chooses a frequency to run
the bus at (in steps of 'clock-gear', 1 through 10, each clock gear
representing twice the frequency than the previous gear).
Manager is also responsible for entering (and exiting) low-power-mode
(known as 'clock pause').
Manager can do handover of framer if there are multiple framers on the
bus and a certain usecase warrants using certain framer to avoid keeping
previous framer being powered-on.

Controller here performs duties of the manager device, and 'interface
device'. Interface device is responsible for monitoring the bus and
reporting information such as loss-of-synchronization, data
slot-collision.



#### <a id="c-slim_unregister_controller"></a>`slim_unregister_controller()`

```c
int slim_unregister_controller(struct slim_controller *ctrl)
```

Controller tear-down.

**Parameters**

- `struct slim_controller *ctrl`: Controller to tear-down.

#### <a id="c-slim_report_absent"></a>`slim_report_absent()`

```c
void slim_report_absent(struct slim_device *sbdev)
```

Controller calls this function when a device reports absent, OR when the device cannot be communicated with

**Parameters**

- `struct slim_device *sbdev`: Device that cannot be reached, or sent report absent

#### <a id="c-slim_get_device"></a>`slim_get_device()`

```c
struct slim_device * slim_get_device(struct slim_controller *ctrl, struct slim_eaddr *e_addr)
```

get handle to a device.

**Parameters**

- `struct slim_controller *ctrl`: Controller on which this device will be added/queried
- `struct slim_eaddr *e_addr`: Enumeration address of the device to be queried

**Description**

Takes a reference to the embedded struct device which needs to be dropped
after use.

**Return**

pointer to a device if it has already reported. Creates a new
device and returns pointer to it if the device has not yet enumerated.

#### <a id="c-of_slim_get_device"></a>`of_slim_get_device()`

```c
struct slim_device * of_slim_get_device(struct slim_controller *ctrl, struct device_node *np)
```

get handle to a device using dt node.

**Parameters**

- `struct slim_controller *ctrl`: Controller on which this device will be queried
- `struct device_node *np`: node pointer to device

**Description**

Takes a reference to the embedded struct device which needs to be dropped
after use.

**Return**

pointer to a device if it has been registered, otherwise NULL.

#### <a id="c-slim_device_report_present"></a>`slim_device_report_present()`

```c
int slim_device_report_present(struct slim_controller *ctrl, struct slim_eaddr *e_addr, u8 *laddr)
```

Report enumerated device.

**Parameters**

- `struct slim_controller *ctrl`: Controller with which device is enumerated.
- `struct slim_eaddr *e_addr`: Enumeration address of the device.
- `u8 *laddr`: Return logical address (if valid flag is false)

**Description**

Called by controller in response to REPORT_PRESENT. Framework will assign
a logical address to this enumeration address.
Function returns -EXFULL to indicate that all logical addresses are already
taken.

#### <a id="c-slim_get_logical_addr"></a>`slim_get_logical_addr()`

```c
int slim_get_logical_addr(struct slim_device *sbdev)
```

get/allocate logical address of a SLIMbus device.

**Parameters**

- `struct slim_device *sbdev`: client handle requesting the address.

**Return**

zero if a logical address is valid or a new logical address
has been assigned. error code in case of error.


<a id="rst-clock-pause"></a>

## Clock-pause:

SLIMbus mandates that a reconfiguration sequence (known as clock-pause) be broadcast to all active devices on the bus before the bus can enter low-power mode. Controller uses this sequence when it decides to enter low-power mode so that corresponding clocks and/or power-rails can be turned off to save power. Clock-pause is exited by waking up framer device (if controller driver initiates exiting low power mode), or by toggling the data line (if a slave device wants to initiate it).

<a id="rst-clock-pause-apis"></a>

### Clock-pause APIs:


#### <a id="c-slim_ctrl_clk_pause"></a>`slim_ctrl_clk_pause()`

```c
int slim_ctrl_clk_pause(struct slim_controller *ctrl, bool wakeup, u8 restart)
```

Called by slimbus controller to enter/exit 'clock pause'

**Parameters**

- `struct slim_controller *ctrl`: controller requesting bus to be paused or woken up
- `bool wakeup`: Wakeup this controller from clock pause.
- `u8 restart`: Restart time value per spec used for clock pause. This value
  isn't used when controller is to be woken up.

**Description**

Slimbus specification needs this sequence to turn-off clocks for the bus.
The sequence involves sending 3 broadcast messages (reconfiguration
sequence) to inform all devices on the bus.
To exit clock-pause, controller typically wakes up active framer device.
This API executes clock pause reconfiguration sequence if wakeup is false.
If wakeup is true, controller's wakeup is called.
For entering clock-pause, -EBUSY is returned if a message txn in pending.


<a id="rst-messaging"></a>

## Messaging:

The framework supports regmap and read/write apis to exchange control-information with a SLIMbus device. APIs can be synchronous or asynchronous. The header file &lt;linux/slimbus.h&gt; has more documentation about messaging APIs.

<a id="rst-messaging-apis"></a>

### Messaging APIs:


#### <a id="c-slim_msg_response"></a>`slim_msg_response()`

```c
void slim_msg_response(struct slim_controller *ctrl, u8 *reply, u8 tid, u8 len)
```

Deliver Message response received from a device to the framework.

**Parameters**

- `struct slim_controller *ctrl`: Controller handle
- `u8 *reply`: Reply received from the device
- `u8 tid`: Transaction ID received with which framework can associate reply.
- `u8 len`: Length of the reply

**Description**

Called by controller to inform framework about the response received.
This helps in making the API asynchronous, and controller-driver doesn't need
to manage 1 more table other than the one managed by framework mapping TID
with buffers

#### <a id="c-slim_alloc_txn_tid"></a>`slim_alloc_txn_tid()`

```c
int slim_alloc_txn_tid(struct slim_controller *ctrl, struct slim_msg_txn *txn)
```

Allocate a tid to txn

**Parameters**

- `struct slim_controller *ctrl`: Controller handle
- `struct slim_msg_txn *txn`: transaction to be allocated with tid.

**Return**

zero on success with valid txn->tid and error code on failures.

#### <a id="c-slim_free_txn_tid"></a>`slim_free_txn_tid()`

```c
void slim_free_txn_tid(struct slim_controller *ctrl, struct slim_msg_txn *txn)
```

Free tid of txn

**Parameters**

- `struct slim_controller *ctrl`: Controller handle
- `struct slim_msg_txn *txn`: transaction whose tid should be freed

#### <a id="c-slim_do_transfer"></a>`slim_do_transfer()`

```c
int slim_do_transfer(struct slim_controller *ctrl, struct slim_msg_txn *txn)
```

Process a SLIMbus-messaging transaction

**Parameters**

- `struct slim_controller *ctrl`: Controller handle
- `struct slim_msg_txn *txn`: Transaction to be sent over SLIMbus

**Description**

Called by controller to transmit messaging transactions not dealing with
Interface/Value elements. (e.g. transmitting a message to assign logical
address to a slave device

**Return**

-ETIMEDOUT: If transmission of this message timed out
(e.g. due to bus lines not being clocked or driven by controller)

#### <a id="c-slim_xfer_msg"></a>`slim_xfer_msg()`

```c
int slim_xfer_msg(struct slim_device *sbdev, struct slim_val_inf *msg, u8 mc)
```

Transfer a value info message on slim device

**Parameters**

- `struct slim_device *sbdev`: slim device to which this msg has to be transferred
- `struct slim_val_inf *msg`: value info message pointer
- `u8 mc`: message code of the message

**Description**

Called by drivers which want to transfer a vlaue or info elements.

**Return**

-ETIMEDOUT: If transmission of this message timed out

#### <a id="c-slim_read"></a>`slim_read()`

```c
int slim_read(struct slim_device *sdev, u32 addr, size_t count, u8 *val)
```

Read SLIMbus value element

**Parameters**

- `struct slim_device *sdev`: client handle.
- `u32 addr`: address of value element to read.
- `size_t count`: number of bytes to read. Maximum bytes allowed are 16.
- `u8 *val`: will return what the value element value was

**Return**

-EINVAL for Invalid parameters, -ETIMEDOUT If transmission of
this message timed out (e.g. due to bus lines not being clocked
or driven by controller)

#### <a id="c-slim_readb"></a>`slim_readb()`

```c
int slim_readb(struct slim_device *sdev, u32 addr)
```

Read byte from SLIMbus value element

**Parameters**

- `struct slim_device *sdev`: client handle.
- `u32 addr`: address in the value element to read.

**Return**

byte value of value element.

#### <a id="c-slim_write"></a>`slim_write()`

```c
int slim_write(struct slim_device *sdev, u32 addr, size_t count, u8 *val)
```

Write SLIMbus value element

**Parameters**

- `struct slim_device *sdev`: client handle.
- `u32 addr`: address in the value element to write.
- `size_t count`: number of bytes to write. Maximum bytes allowed are 16.
- `u8 *val`: value to write to value element

**Return**

-EINVAL for Invalid parameters, -ETIMEDOUT If transmission of
this message timed out (e.g. due to bus lines not being clocked
or driven by controller)

#### <a id="c-slim_writeb"></a>`slim_writeb()`

```c
int slim_writeb(struct slim_device *sdev, u32 addr, u8 value)
```

Write byte to SLIMbus value element

**Parameters**

- `struct slim_device *sdev`: client handle.
- `u32 addr`: address of value element to write.
- `u8 value`: value to write to value element

**Return**

-EINVAL for Invalid parameters, -ETIMEDOUT If transmission of
this message timed out (e.g. due to bus lines not being clocked
or driven by controller)


<a id="rst-streaming-apis"></a>

### Streaming APIs:


#### <a id="c-slim_stream_allocate"></a>`slim_stream_allocate()`

```c
struct slim_stream_runtime * slim_stream_allocate(struct slim_device *dev, const char *name)
```

Allocate a new SLIMbus Stream

**Parameters**

- `struct slim_device *dev`: Slim device to be associated with
- `const char *name`: name of the stream

**Description**

This is very first call for SLIMbus streaming, this API will allocate
a new SLIMbus stream and return a valid stream runtime pointer for client
to use it in subsequent stream apis. state of stream is set to ALLOCATED

**Return**

valid pointer on success and error code on failure.
From ASoC DPCM framework, this state is linked to `startup()` operation.

#### <a id="c-slim_stream_prepare"></a>`slim_stream_prepare()`

```c
int slim_stream_prepare(struct slim_stream_runtime *rt, struct slim_stream_config *cfg)
```

Prepare a SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *rt`: instance of slim stream runtime to configure
- `struct slim_stream_config *cfg`: new configuration for the stream

**Description**

This API will configure SLIMbus stream with config parameters from cfg.
return zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `hw_params()` operation.

#### <a id="c-slim_stream_enable"></a>`slim_stream_enable()`

```c
int slim_stream_enable(struct slim_stream_runtime *stream)
```

Enable a prepared SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *stream`: instance of slim stream runtime to enable

**Description**

This API will enable all the ports and channels associated with
SLIMbus stream

**Return**

zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `trigger()` start operation.

#### <a id="c-slim_stream_disable"></a>`slim_stream_disable()`

```c
int slim_stream_disable(struct slim_stream_runtime *stream)
```

Disable a SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *stream`: instance of slim stream runtime to disable

**Description**

This API will disable all the ports and channels associated with
SLIMbus stream

**Return**

zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `trigger()` pause operation.

#### <a id="c-slim_stream_unprepare"></a>`slim_stream_unprepare()`

```c
int slim_stream_unprepare(struct slim_stream_runtime *stream)
```

Un-prepare a SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *stream`: instance of slim stream runtime to unprepare

**Description**

This API will un allocate all the ports and channels associated with
SLIMbus stream

**Return**

zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `trigger()` stop operation.

#### <a id="c-slim_stream_free"></a>`slim_stream_free()`

```c
int slim_stream_free(struct slim_stream_runtime *stream)
```

Free a SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *stream`: instance of slim stream runtime to free

**Description**

This API will un allocate all the memory associated with
slim stream runtime, user is not allowed to make an dereference
to stream after this call.

**Return**

zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `shutdown()` operation.

---

# Serial Peripheral Interface (SPI)

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> SPI is the "Serial Peripheral Interface", widely used with embedded systems because it is a simple and efficient interface: basically a multiplexed shift register. Its three signal wires hold a clock (SCK, often in the range of 1-20 MHz),…

<a id="rst-serial-peripheral-interface-spi"></a>

SPI is the "Serial Peripheral Interface", widely used with embedded systems because it is a simple and efficient interface: basically a multiplexed shift register. Its three signal wires hold a clock (SCK, often in the range of 1-20 MHz), a "Master Out, Slave In" (MOSI) data line, and a "Master In, Slave Out" (MISO) data line. SPI is a full duplex protocol; for each bit shifted out the MOSI line (one per clock) another is shifted in on the MISO line. Those bits are assembled into words of various sizes on the way to and from system memory. An additional chipselect line is usually active-low (nCS); four signals are normally used for each peripheral, plus sometimes an interrupt.

The SPI bus facilities listed here provide a generalized interface to declare SPI buses and devices, manage them according to the standard Linux driver model, and perform input/output operations. At this time, only "master" side interfaces are supported, where Linux talks to SPI peripherals and does not implement such a peripheral itself. (Interfaces to support implementing SPI slaves would necessarily look different.)

The programming interface is structured around two kinds of driver, and two kinds of device. A "Controller Driver" abstracts the controller hardware, which may be as simple as a set of GPIO pins or as complex as a pair of FIFOs connected to dual DMA engines on the other side of the SPI shift register (maximizing throughput). Such drivers bridge between whatever bus they sit on (often the platform bus) and SPI, and expose the SPI side of their device as a `struct spi_controller <spi_controller>`. SPI devices are children of that master, represented as a `struct spi_device <spi_device>` and manufactured from `struct spi_board_info <spi_board_info>` descriptors which are usually provided by board-specific initialization code. A `struct spi_driver <spi_driver>` is called a "Protocol Driver", and is bound to a spi_device using normal driver model calls.

The I/O model is a set of queued messages. Protocol drivers submit one or more `struct spi_message <spi_message>` objects, which are processed and completed asynchronously. (There are synchronous wrappers, however.) Messages are built from one or more `struct spi_transfer <spi_transfer>` objects, each of which wraps a full duplex SPI transfer. A variety of protocol tweaking options are needed, because different chips adopt very different policies for how they use the bits transferred with SPI.


#### <a id="c-struct-spi_statistics"></a>`struct spi_statistics`

statistics for spi transfers

**Definition**

```c
struct spi_statistics {
        struct u64_stats_sync   syncp;
        u64_stats_t messages;
        u64_stats_t transfers;
        u64_stats_t errors;
        u64_stats_t timedout;
        u64_stats_t spi_sync;
        u64_stats_t spi_sync_immediate;
        u64_stats_t spi_async;
        u64_stats_t bytes;
        u64_stats_t bytes_rx;
        u64_stats_t bytes_tx;
    #define SPI_STATISTICS_HISTO_SIZE 17;
        u64_stats_t transfer_bytes_histo[SPI_STATISTICS_HISTO_SIZE];
        u64_stats_t transfers_split_maxsize;
};
```

**Members**

- `syncp`: seqcount to protect members in this struct for per-cpu update
  on 32-bit systems
- `messages`: number of spi-messages handled
- `transfers`: number of spi_transfers handled
- `errors`: number of errors during spi_transfer
- `timedout`: number of timeouts during spi_transfer
- `spi_sync`: number of times spi_sync is used
- `spi_sync_immediate`: number of times spi_sync is executed immediately
  in calling context without queuing and scheduling
- `spi_async`: number of times spi_async is used
- `bytes`: number of bytes transferred to/from device
- `bytes_rx`: number of bytes received from device
- `bytes_tx`: number of bytes sent to device
- `transfer_bytes_histo`: transfer bytes histogram
- `transfers_split_maxsize`: number of transfers that have been split because of
  maxsize limit

#### <a id="c-struct-spi_delay"></a>`struct spi_delay`

SPI delay information

**Definition**

```c
struct spi_delay {
    #define SPI_DELAY_UNIT_USECS    0;
    #define SPI_DELAY_UNIT_NSECS    1;
    #define SPI_DELAY_UNIT_SCK      2;
        u16 value;
        u8 unit;
};
```

**Members**

- `value`: Value for the delay
- `unit`: Unit for the delay

#### <a id="c-struct-spi_device"></a>`struct spi_device`

Controller side proxy for an SPI target device

**Definition**

```c
struct spi_device {
        struct device           dev;
        struct spi_controller   *controller;
        u32 max_speed_hz;
        u8 bits_per_word;
        bool rt;
    #define SPI_NO_TX               BIT(31);
    #define SPI_NO_RX               BIT(30);
    #define SPI_TPM_HW_FLOW         BIT(29);
    #define SPI_MODE_KERNEL_MASK    (~(BIT(29) - 1));
        u32 mode;
        int irq;
        void *controller_state;
        void *controller_data;
        char modalias[SPI_NAME_SIZE];
        struct spi_statistics __percpu  *pcpu_statistics;
        struct spi_delay        word_delay;
        struct spi_delay        cs_setup;
        struct spi_delay        cs_hold;
        struct spi_delay        cs_inactive;
        u8 chip_select[SPI_DEVICE_CS_CNT_MAX];
        u8 num_chipselect;
        u32 cs_index_mask : SPI_DEVICE_CS_CNT_MAX;
        struct gpio_desc        *cs_gpiod[SPI_DEVICE_CS_CNT_MAX];
        u8 tx_lane_map[SPI_DEVICE_DATA_LANE_CNT_MAX];
        u8 num_tx_lanes;
        u8 rx_lane_map[SPI_DEVICE_DATA_LANE_CNT_MAX];
        u8 num_rx_lanes;
};
```

**Members**

- `dev`: Driver model representation of the device.
- `controller`: SPI controller used with the device.
- `max_speed_hz`: Maximum clock rate to be used with this chip
  (on this board); may be changed by the device's driver.
  The spi_transfer.speed_hz can override this for each transfer.
- `bits_per_word`: Data transfers involve one or more words; word sizes
  like eight or 12 bits are common.  In-memory wordsizes are
  powers of two bytes (e.g. 20 bit samples use 32 bits).
  This may be changed by the device's driver, or left at the
  default (0) indicating protocol words are eight bit bytes.
  The spi_transfer.bits_per_word can override this for each transfer.
- `rt`: Make the pump thread real time priority.
- `mode`: The spi mode defines how data is clocked out and in.
  This may be changed by the device's driver.
  The "active low" default for chipselect mode can be overridden
  (by specifying SPI_CS_HIGH) as can the "MSB first" default for
  each word in a transfer (by specifying SPI_LSB_FIRST).
- `irq`: Negative, or the number passed to [`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq) to receive
  interrupts from this device.
- `controller_state`: Controller's runtime state
- `controller_data`: Board-specific definitions for controller, such as
  FIFO initialization parameters; from board_info.controller_data
- `modalias`: Name of the driver to use with this device, or an alias
  for that name.  This appears in the sysfs "modalias" attribute
  for driver coldplugging, and in uevents used for hotplugging
- `pcpu_statistics`: statistics for the spi_device
- `word_delay`: delay to be inserted between consecutive
  words of a transfer
- `cs_setup`: delay to be introduced by the controller after CS is asserted
- `cs_hold`: delay to be introduced by the controller before CS is deasserted
- `cs_inactive`: delay to be introduced by the controller after CS is
  deasserted. If **cs_change_delay** is used from **spi_transfer**, then the
  two delays will be added up.
- `chip_select`: Array of physical chipselect, spi->chipselect\[i\] gives
  the corresponding physical CS for logical CS i.
- `num_chipselect`: Number of physical chipselects used.
- `cs_index_mask`: Bit mask of the active chipselect(s) in the chipselect array
- `cs_gpiod`: Array of GPIO descriptors of the corresponding chipselect lines
  (optional, NULL when not using a GPIO line)
- `tx_lane_map`: Map of peripheral lanes (index) to controller lanes (value).
- `num_tx_lanes`: Number of transmit lanes wired up.
- `rx_lane_map`: Map of peripheral lanes (index) to controller lanes (value).
- `num_rx_lanes`: Number of receive lanes wired up.

**Description**

A **spi_device** is used to interchange data between an SPI target device
(usually a discrete chip) and CPU memory.

In **dev**, the platform_data is used to hold information about this
device that's meaningful to the device's protocol driver, but not
to its controller.  One example might be an identifier for a chip
variant with slightly different functionality; another might be
information about how this particular board wires the chip's pins.

#### <a id="c-struct-spi_driver"></a>`struct spi_driver`

Host side "protocol" driver

**Definition**

```c
struct spi_driver {
    const struct spi_device_id *id_table;
    int (*probe)(struct spi_device *spi);
    void (*remove)(struct spi_device *spi);
    void (*shutdown)(struct spi_device *spi);
    struct device_driver    driver;
};
```

**Members**

- `id_table`: List of SPI devices supported by this driver
- `probe`: Binds this driver to the SPI device.  Drivers can verify
  that the device is actually present, and may need to configure
  characteristics (such as bits_per_word) which weren't needed for
  the initial configuration done during system setup.
- `remove`: Unbinds this driver from the SPI device
- `shutdown`: Standard shutdown callback used during system state
  transitions such as powerdown/halt and kexec
- `driver`: SPI device drivers should initialize the name and owner
  field of this structure.

**Description**

This represents the kind of device driver that uses SPI messages to
interact with the hardware at the other end of a SPI link.  It's called
a "protocol" driver because it works through messages rather than talking
directly to SPI hardware (which is what the underlying SPI controller
driver does to pass those messages).  These protocols are defined in the
specification for the device(s) supported by the driver.

As a rule, those device protocols represent the lowest level interface
supported by a driver, and it will support upper level interfaces too.
Examples of such upper levels include frameworks like MTD, networking,
MMC, RTC, filesystem character device nodes, and hardware monitoring.

#### <a id="c-spi_unregister_driver"></a>`spi_unregister_driver()`

```c
void spi_unregister_driver(struct spi_driver *sdrv)
```

reverse effect of spi_register_driver

**Parameters**

- `struct spi_driver *sdrv`: the driver to unregister

**Context**

can sleep

#### <a id="c-module_spi_driver"></a>`module_spi_driver()`

```c
module_spi_driver(__spi_driver)
```

Helper macro for registering a SPI driver

**Parameters**

- `__spi_driver`: spi_driver struct

**Description**

Helper macro for SPI drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)

#### <a id="c-struct-spi_controller"></a>`struct spi_controller`

interface to SPI host or target controller

**Definition**

```c
struct spi_controller {
        struct device   dev;
        struct list_head list;
        s16 bus_num;
        u16 num_chipselect;
        u16 num_data_lanes;
        u16 dma_alignment;
        u32 mode_bits;
        u32 buswidth_override_bits;
        u32 bits_per_word_mask;
    #define SPI_BPW_MASK(bits) BIT((bits) - 1);
    #define SPI_BPW_RANGE_MASK(min, max) GENMASK((max) - 1, (min) - 1);
        u32 min_speed_hz;
        u32 max_speed_hz;
        u16 flags;
    #define SPI_CONTROLLER_HALF_DUPLEX      BIT(0);
    #define SPI_CONTROLLER_NO_RX            BIT(1);
    #define SPI_CONTROLLER_NO_TX            BIT(2);
    #define SPI_CONTROLLER_MUST_RX          BIT(3);
    #define SPI_CONTROLLER_MUST_TX          BIT(4);
    #define SPI_CONTROLLER_GPIO_SS          BIT(5);
    #define SPI_CONTROLLER_SUSPENDED        BIT(6);
    #define SPI_CONTROLLER_MULTI_CS         BIT(7);
        bool devm_allocated;
        union {
            bool slave;
            bool target;
        };
        size_t (*max_transfer_size)(struct spi_device *spi);
        size_t (*max_message_size)(struct spi_device *spi);
        struct mutex            io_mutex;
        struct mutex            add_lock;
        spinlock_t bus_lock_spinlock;
        struct mutex            bus_lock_mutex;
        bool bus_lock_flag;
        int (*setup)(struct spi_device *spi);
        int (*set_cs_timing)(struct spi_device *spi);
        int (*transfer)(struct spi_device *spi, struct spi_message *mesg);
        void (*cleanup)(struct spi_device *spi);
        bool (*can_dma)(struct spi_controller *ctlr, struct spi_device *spi, struct spi_transfer *xfer);
        struct device *dma_map_dev;
        struct device *cur_rx_dma_dev;
        struct device *cur_tx_dma_dev;
        bool queued;
        struct kthread_worker           *kworker;
        struct kthread_work             pump_messages;
        spinlock_t queue_lock;
        struct list_head                queue;
        struct spi_message              *cur_msg;
        struct completion               cur_msg_completion;
        bool cur_msg_incomplete;
        bool cur_msg_need_completion;
        bool busy;
        bool running;
        bool rt;
        bool auto_runtime_pm;
        bool fallback;
        bool last_cs_mode_high;
        s8 last_cs[SPI_DEVICE_CS_CNT_MAX];
        u32 last_cs_index_mask : SPI_DEVICE_CS_CNT_MAX;
        struct completion               xfer_completion;
        size_t max_dma_len;
        int (*optimize_message)(struct spi_message *msg);
        int (*unoptimize_message)(struct spi_message *msg);
        int (*prepare_transfer_hardware)(struct spi_controller *ctlr);
        int (*transfer_one_message)(struct spi_controller *ctlr, struct spi_message *mesg);
        int (*unprepare_transfer_hardware)(struct spi_controller *ctlr);
        int (*prepare_message)(struct spi_controller *ctlr, struct spi_message *message);
        int (*unprepare_message)(struct spi_controller *ctlr, struct spi_message *message);
        int (*target_abort)(struct spi_controller *ctlr);
        void (*set_cs)(struct spi_device *spi, bool enable);
        int (*transfer_one)(struct spi_controller *ctlr, struct spi_device *spi, struct spi_transfer *transfer);
        void (*handle_err)(struct spi_controller *ctlr, struct spi_message *message);
        const struct spi_controller_mem_ops *mem_ops;
        const struct spi_controller_mem_caps *mem_caps;
        bool dtr_caps;
        struct spi_offload *(*get_offload)(struct spi_device *spi, const struct spi_offload_config *config);
        void (*put_offload)(struct spi_offload *offload);
        struct gpio_desc        **cs_gpiods;
        bool use_gpio_descriptors;
        s8 unused_native_cs;
        s8 max_native_cs;
        struct spi_statistics __percpu  *pcpu_statistics;
        struct dma_chan         *dma_tx;
        struct dma_chan         *dma_rx;
        void *dummy_rx;
        void *dummy_tx;
        int (*fw_translate_cs)(struct spi_controller *ctlr, unsigned cs);
        bool ptp_sts_supported;
        unsigned long           irq_flags;
        bool queue_empty;
        bool must_async;
        bool defer_optimize_message;
};
```

**Members**

- `dev`: device interface to this driver
- `list`: link with the global spi_controller list
- `bus_num`: board-specific (and often SOC-specific) identifier for a
  given SPI controller.
- `num_chipselect`: chipselects are used to distinguish individual
  SPI targets, and are numbered from zero to num_chipselects.
  each target has a chipselect signal, but it's common that not
  every chipselect is connected to a target.
- `num_data_lanes`: Number of data lanes supported by this controller. Default is 1.
- `dma_alignment`: SPI controller constraint on DMA buffers alignment.
- `mode_bits`: flags understood by this controller driver
- `buswidth_override_bits`: flags to override for this controller driver
- `bits_per_word_mask`: A mask indicating which values of bits_per_word are
  supported by the driver. Bit n indicates that a bits_per_word n+1 is
  supported. If set, the SPI core will reject any transfer with an
  unsupported bits_per_word. If not set, this value is simply ignored,
  and it's up to the individual driver to perform any validation.
- `min_speed_hz`: Lowest supported transfer speed
- `max_speed_hz`: Highest supported transfer speed
- `flags`: other constraints relevant to this driver
- `devm_allocated`: whether the allocation of this struct is devres-managed
- `{unnamed_union}`: anonymous
- `slave`: indicates that this is an SPI slave controller
- `target`: indicates that this is an SPI target controller
- `max_transfer_size`: function that returns the max transfer size for
  a [`spi_device`](#c-struct-spi_device); may be `NULL`, so the default `SIZE_MAX` will be used.
- `max_message_size`: function that returns the max message size for
  a [`spi_device`](#c-struct-spi_device); may be `NULL`, so the default `SIZE_MAX` will be used.
- `io_mutex`: mutex for physical bus access
- `add_lock`: mutex to avoid adding devices to the same chipselect
- `bus_lock_spinlock`: spinlock for SPI bus locking
- `bus_lock_mutex`: mutex for exclusion of multiple callers
- `bus_lock_flag`: indicates that the SPI bus is locked for exclusive use
- `setup`: updates the device mode and clocking records used by a
  device's SPI controller; protocol code may call this.  This
  must fail if an unrecognized or unsupported mode is requested.
  It's always safe to call this unless transfers are pending on
  the device whose settings are being modified.
- `set_cs_timing`: optional hook for SPI devices to request SPI
  controller for configuring specific CS setup time, hold time and inactive
  delay in terms of clock counts
- `transfer`: adds a message to the controller's transfer queue.
- `cleanup`: frees controller-specific state
- `can_dma`: determine whether this controller supports DMA
- `dma_map_dev`: device which can be used for DMA mapping
- `cur_rx_dma_dev`: device which is currently used for RX DMA mapping
- `cur_tx_dma_dev`: device which is currently used for TX DMA mapping
- `queued`: whether this controller is providing an internal message queue
- `kworker`: pointer to thread struct for message pump
- `pump_messages`: work struct for scheduling work to the message pump
- `queue_lock`: spinlock to synchronise access to message queue
- `queue`: message queue
- `cur_msg`: the currently in-flight message
- `cur_msg_completion`: a completion for the current in-flight message
- `cur_msg_incomplete`: Flag used internally to opportunistically skip
  the **cur_msg_completion**. This flag is used to check if the driver has
  already called [`spi_finalize_current_message()`](#c-spi_finalize_current_message).
- `cur_msg_need_completion`: Flag used internally to opportunistically skip
  the **cur_msg_completion**. This flag is used to signal the context that
  is running [`spi_finalize_current_message()`](#c-spi_finalize_current_message) that it needs to `complete()`
- `busy`: message pump is busy
- `running`: message pump is running
- `rt`: whether this queue is set to run as a realtime task
- `auto_runtime_pm`: the core should ensure a runtime PM reference is held
  while the hardware is prepared, using the parent
  device for the spidev
- `fallback`: fallback to PIO if DMA transfer return failure with
  SPI_TRANS_FAIL_NO_START.
- `last_cs_mode_high`: was (mode & SPI_CS_HIGH) true on the last call to set_cs.
- `last_cs`: the last chip_select that is recorded by set_cs, -1 on non chip
  selected
- `last_cs_index_mask`: bit mask the last chip selects that were used
- `xfer_completion`: used by core `transfer_one_message()`
- `max_dma_len`: Maximum length of a DMA transfer for the device.
- `optimize_message`: optimize the message for reuse
- `unoptimize_message`: release resources allocated by optimize_message
- `prepare_transfer_hardware`: a message will soon arrive from the queue
  so the subsystem requests the driver to prepare the transfer hardware
  by issuing this call
- `transfer_one_message`: the subsystem calls the driver to transfer a single
  message while queuing transfers that arrive in the meantime. When the
  driver is finished with this message, it must call
  [`spi_finalize_current_message()`](#c-spi_finalize_current_message) so the subsystem can issue the next
  message
- `unprepare_transfer_hardware`: there are currently no more messages on the
  queue so the subsystem notifies the driver that it may relax the
  hardware by issuing this call
- `prepare_message`: set up the controller to transfer a single message,
  for example doing DMA mapping.  Called from threaded
  context.
- `unprepare_message`: undo any work done by `prepare_message()`.
- `target_abort`: abort the ongoing transfer request on an SPI target controller
- `set_cs`: set the logic level of the chip select line.  May be called
  from interrupt context.
- `transfer_one`: transfer a single spi_transfer.
- `handle_err`: the subsystem calls the driver to handle an error that occurs
  in the generic implementation of `transfer_one_message()`.
- `mem_ops`: optimized/dedicated operations for interactions with SPI memory.
  This field is optional and should only be implemented if the
  controller has native support for memory like operations.
- `mem_caps`: controller capabilities for the handling of memory operations.
- `dtr_caps`: true if controller has dtr(single/dual transfer rate) capability.
  QSPI based controller should fill this based on controller's capability.
- `get_offload`: callback for controllers with offload support to get matching
  offload instance. Implementations should return -ENODEV if no match is
  found.
- `put_offload`: release the offload instance acquired by **get_offload**.
- `cs_gpiods`: Array of GPIO descriptors to use as chip select lines; one per CS
  number. Any individual value may be NULL for CS lines that
  are not GPIOs (driven by the SPI controller itself).
- `use_gpio_descriptors`: Turns on the code in the SPI core to parse and grab
  GPIO descriptors. This will fill in **cs_gpiods** and SPI devices will have
  the cs_gpiod assigned if a GPIO line is found for the chipselect.
- `unused_native_cs`: When cs_gpiods is used, [`spi_register_controller()`](#c-spi_register_controller) will
  fill in this field with the first unused native CS, to be used by SPI
  controller drivers that need to drive a native CS when using GPIO CS.
- `max_native_cs`: When cs_gpiods is used, and this field is filled in,
  [`spi_register_controller()`](#c-spi_register_controller) will validate all native CS (including the
  unused native CS) against this value.
- `pcpu_statistics`: statistics for the spi_controller
- `dma_tx`: DMA transmit channel
- `dma_rx`: DMA receive channel
- `dummy_rx`: dummy receive buffer for full-duplex devices
- `dummy_tx`: dummy transmit buffer for full-duplex devices
- `fw_translate_cs`: If the boot firmware uses different numbering scheme
  what Linux expects, this optional hook can be used to translate
  between the two.
- `ptp_sts_supported`: If the driver sets this to true, it must provide a
  time snapshot in **spi_transfer->ptp_sts** as close as possible to the
  moment in time when **spi_transfer->ptp_sts_word_pre** and
  **spi_transfer->ptp_sts_word_post** were transmitted.
  If the driver does not set this, the SPI core takes the snapshot as
  close to the driver hand-over as possible.
- `irq_flags`: Interrupt enable state during PTP system timestamping
- `queue_empty`: signal green light for opportunistically skipping the queue
  for spi_sync transfers.
- `must_async`: disable all fast paths in the core
- `defer_optimize_message`: set to true if controller cannot pre-optimize messages
  and needs to defer the optimization step until the message is actually
  being transferred

**Description**

- return 0 if the transfer is finished,
- return 1 if the transfer is still in progress. When
  the driver is finished with this transfer it must
  call [`spi_finalize_current_transfer()`](#c-spi_finalize_current_transfer) so the subsystem
  can issue the next transfer. If the transfer fails, the
  driver must set the flag SPI_TRANS_FAIL_IO to
  spi_transfer->error first, before calling
  [`spi_finalize_current_transfer()`](#c-spi_finalize_current_transfer).

Each SPI controller can communicate with one or more **spi_device**
children.  These make a small bus, sharing MOSI, MISO and SCK signals
but not chip select signals.  Each device may be configured to use a
different clock rate, since those shared signals are ignored unless
the chip is selected.

The driver for an SPI controller manages access to those devices through
a queue of spi_message transactions, copying data between CPU memory and
an SPI target device.  For each such message it queues, it calls the
message's completion function when the transaction completes.

**Note**

- transfer_one and transfer_one_message are mutually

  exclusive; when both are set, the generic subsystem does
  not call your transfer_one callback.

#### <a id="c-struct-spi_res"></a>`struct spi_res`

SPI resource management structure

**Definition**

```c
struct spi_res {
    struct list_head        entry;
    spi_res_release_t release;
    unsigned long long      data[];
};
```

**Members**

- `entry`: list entry
- `release`: release code called prior to freeing this resource
- `data`: extra data allocated for the specific use-case

**Description**

This is based on ideas from devres, but focused on life-cycle
management during spi_message processing.

#### <a id="c-struct-spi_transfer"></a>`struct spi_transfer`

a read/write buffer pair

**Definition**

```c
struct spi_transfer {
        const void      *tx_buf;
        void *rx_buf;
        unsigned len;
    #define SPI_TRANS_FAIL_NO_START BIT(0);
    #define SPI_TRANS_FAIL_IO       BIT(1);
        u16 error;
        bool tx_sg_mapped;
        bool rx_sg_mapped;
        struct sg_table tx_sg;
        struct sg_table rx_sg;
        dma_addr_t tx_dma;
        dma_addr_t rx_dma;
        unsigned dummy_data:1;
        unsigned cs_off:1;
        unsigned cs_change:1;
        unsigned tx_nbits:4;
        unsigned rx_nbits:4;
    #define SPI_MULTI_LANE_MODE_SINGLE      0;
    #define SPI_MULTI_LANE_MODE_STRIPE      1;
    #define SPI_MULTI_LANE_MODE_MIRROR      2;
        unsigned multi_lane_mode: 2;
        unsigned timestamped:1;
        bool dtr_mode;
    #define SPI_NBITS_SINGLE        0x01;
    #define SPI_NBITS_DUAL          0x02;
    #define SPI_NBITS_QUAD          0x04;
    #define SPI_NBITS_OCTAL 0x08;
        u8 bits_per_word;
        struct spi_delay        delay;
        struct spi_delay        cs_change_delay;
        struct spi_delay        word_delay;
        u32 speed_hz;
        u32 effective_speed_hz;
        unsigned int    offload_flags;
        unsigned int    ptp_sts_word_pre;
        unsigned int    ptp_sts_word_post;
        struct ptp_system_timestamp *ptp_sts;
        struct list_head transfer_list;
};
```

**Members**

- `tx_buf`: data to be written (DMA-safe memory), or NULL
- `rx_buf`: data to be read (DMA-safe memory), or NULL
- `len`: size of rx and tx buffers (in bytes)
- `error`: Error status logged by SPI controller driver.
- `tx_sg_mapped`: If true, the **tx_sg** is mapped for DMA
- `rx_sg_mapped`: If true, the **rx_sg** is mapped for DMA
- `tx_sg`: Scatterlist for transmit, currently not for client use
- `rx_sg`: Scatterlist for receive, currently not for client use
- `tx_dma`: DMA address of tx_buf, currently not for client use
- `rx_dma`: DMA address of rx_buf, currently not for client use
- `dummy_data`: indicates transfer is dummy bytes transfer.
- `cs_off`: performs the transfer with chipselect off.
- `cs_change`: affects chipselect after this transfer completes
- `tx_nbits`: number of bits used for writing. If 0 the default
  (SPI_NBITS_SINGLE) is used.
- `rx_nbits`: number of bits used for reading. If 0 the default
  (SPI_NBITS_SINGLE) is used.
- `multi_lane_mode`: How to serialize data on multiple lanes. One of the
  SPI_MULTI_LANE_MODE_* values.
- `timestamped`: true if the transfer has been timestamped
- `dtr_mode`: true if supports double transfer rate.
- `bits_per_word`: select a bits_per_word other than the device default
  for this transfer. If 0 the default (from **spi_device**) is used.
- `delay`: delay to be introduced after this transfer before
  (optionally) changing the chipselect status, then starting
  the next transfer or completing this **spi_message**.
- `cs_change_delay`: delay between cs deassert and assert when
  **cs_change** is set and **spi_transfer** is not the last in **spi_message**
- `word_delay`: inter word delay to be introduced after each word size
  (set by bits_per_word) transmission.
- `speed_hz`: Select a speed other than the device default for this
  transfer. If 0 the default (from **spi_device**) is used.
- `effective_speed_hz`: the effective SCK-speed that was used to
  transfer this transfer. Set to 0 if the SPI bus driver does
  not support it.
- `offload_flags`: Flags that are only applicable to specialized SPI offload
  transfers. See `SPI_OFFLOAD_XFER_*` in spi-offload.h.
- `ptp_sts_word_pre`: The word (subject to bits_per_word semantics) offset
  within **tx_buf** for which the SPI device is requesting that the time
  snapshot for this transfer begins. Upon completing the SPI transfer,
  this value may have changed compared to what was requested, depending
  on the available snapshotting resolution (DMA transfer,
  **ptp_sts_supported** is false, etc).
- `ptp_sts_word_post`: See **ptp_sts_word_post**. The two can be equal (meaning
  that a single byte should be snapshotted).
  If the core takes care of the timestamp (if **ptp_sts_supported** is false
  for this controller), it will set **ptp_sts_word_pre** to 0, and
  **ptp_sts_word_post** to the length of the transfer. This is done
  purposefully (instead of setting to spi_transfer->len - 1) to denote
  that a transfer-level snapshot taken from within the driver may still
  be of higher quality.
- `ptp_sts`: Pointer to a memory location held by the SPI target device where a
  PTP system timestamp structure may lie. If drivers use PIO or their
  hardware has some sort of assist for retrieving exact transfer timing,
  they can (and should) assert **ptp_sts_supported** and populate this
  structure using the ptp_read_system_*ts helper functions.
  The timestamp must represent the time at which the SPI target device has
  processed the word, i.e. the "pre" timestamp should be taken before
  transmitting the "pre" word, and the "post" timestamp after receiving
  transmit confirmation from the controller for the "post" word.
- `transfer_list`: transfers are sequenced through **spi_message.transfers**

**Description**

SPI transfers always write the same number of bytes as they read.
Protocol drivers should always provide **rx_buf** and/or **tx_buf**.
In some cases, they may also want to provide DMA addresses for
the data being transferred; that may reduce overhead, when the
underlying driver uses DMA.

If the transmit buffer is NULL, zeroes will be shifted out
while filling **rx_buf**.  If the receive buffer is NULL, the data
shifted in will be discarded.  Only "len" bytes shift out (or in).
It's an error to try to shift out a partial word.  (For example, by
shifting out three bytes with word size of sixteen or twenty bits;
the former uses two bytes per word, the latter uses four bytes.)

In-memory data values are always in native CPU byte order, translated
from the wire byte order (big-endian except with SPI_LSB_FIRST).  So
for example when bits_per_word is sixteen, buffers are 2N bytes long
(**len** = 2N) and hold N sixteen bit words in CPU byte order.

When the word size of the SPI transfer is not a power-of-two multiple
of eight bits, those in-memory words include extra bits.  In-memory
words are always seen by protocol drivers as right-justified, so the
undefined (rx) or unused (tx) bits are always the most significant bits.

All SPI transfers start with the relevant chipselect active.  Normally
it stays selected until after the last transfer in a message.  Drivers
can affect the chipselect signal using cs_change.

(i) If the transfer isn't the last one in the message, this flag is
used to make the chipselect briefly go inactive in the middle of the
message.  Toggling chipselect in this way may be needed to terminate
a chip command, letting a single spi_message perform all of group of
chip transactions together.

(ii) When the transfer is the last one in the message, the chip may
stay selected until the next transfer.  On multi-device SPI busses
with nothing blocking messages going to other devices, this is just
a performance hint; starting a message to another device deselects
this one.  But in other cases, this can be used to ensure correctness.
Some devices need protocol transactions to be built from a series of
spi_message submissions, where the content of one message is determined
by the results of previous messages and where the whole transaction
ends when the chipselect goes inactive.

When SPI can transfer in 1x,2x or 4x. It can get this transfer information
from device through **tx_nbits** and **rx_nbits**. In Bi-direction, these
two should both be set. User can set transfer mode with SPI_NBITS_SINGLE(1x)
SPI_NBITS_DUAL(2x) and SPI_NBITS_QUAD(4x) to support these three transfer.

User may also set dtr_mode to true to use dual transfer mode if desired. if
not, default considered as single transfer mode.

The code that submits an spi_message (and its spi_transfers)
to the lower layers is responsible for managing its memory.
Zero-initialize every field you don't set up explicitly, to
insulate against future API updates.  After you submit a message
and its transfers, ignore them until its completion callback.

#### <a id="c-struct-spi_message"></a>`struct spi_message`

one multi-segment SPI transaction

**Definition**

```c
struct spi_message {
    struct list_head        transfers;
    struct spi_device       *spi;
    bool pre_optimized;
    bool optimized;
    bool prepared;
    int status;
    void (*complete)(void *context);
    void *context;
    unsigned frame_length;
    unsigned actual_length;
    struct list_head        queue;
    void *state;
    void *opt_state;
    struct spi_offload      *offload;
    struct list_head        resources;
};
```

**Members**

- `transfers`: list of transfer segments in this transaction
- `spi`: SPI device to which the transaction is queued
- `pre_optimized`: peripheral driver pre-optimized the message
- `optimized`: the message is in the optimized state
- `prepared`: spi_prepare_message was called for the this message
- `status`: zero for success, else negative errno
- `complete`: called to report transaction completions
- `context`: the argument to `complete()` when it's called
- `frame_length`: the total number of bytes in the message
- `actual_length`: the total number of bytes that were transferred in all
  successful segments
- `queue`: for use by whichever driver currently owns the message
- `state`: for use by whichever driver currently owns the message
- `opt_state`: for use by whichever driver currently owns the message
- `offload`: (optional) offload instance used by this message
- `resources`: for resource management when the SPI message is processed

**Description**

A **spi_message** is used to execute an atomic sequence of data transfers,
each represented by a struct spi_transfer.  The sequence is "atomic"
in the sense that no other spi_message may use that SPI bus until that
sequence completes.  On some systems, many such sequences can execute as
a single programmed DMA transfer.  On all systems, these messages are
queued, and might complete after transactions to other devices.  Messages
sent to a given spi_device are always executed in FIFO order.

The code that submits an spi_message (and its spi_transfers)
to the lower layers is responsible for managing its memory.
Zero-initialize every field you don't set up explicitly, to
insulate against future API updates.  After you submit a message
and its transfers, ignore them until its completion callback.

#### <a id="c-spi_message_init_with_transfers"></a>`spi_message_init_with_transfers()`

```c
void spi_message_init_with_transfers(struct spi_message *m, struct spi_transfer *xfers, unsigned int num_xfers)
```

Initialize spi_message and append transfers

**Parameters**

- `struct spi_message *m`: spi_message to be initialized
- `struct spi_transfer *xfers`: An array of SPI transfers
- `unsigned int num_xfers`: Number of items in the xfer array

**Description**

This function initializes the given spi_message and adds each spi_transfer in
the given array to the message.

#### <a id="c-spi_is_bpw_supported"></a>`spi_is_bpw_supported()`

```c
bool spi_is_bpw_supported(struct spi_device *spi, u32 bpw)
```

Check if bits per word is supported

**Parameters**

- `struct spi_device *spi`: SPI device
- `u32 bpw`: Bits per word

**Description**

This function checks to see if the SPI controller supports **bpw**.

**Return**

True if **bpw** is supported, false otherwise.

#### <a id="c-spi_bpw_to_bytes"></a>`spi_bpw_to_bytes()`

```c
u32 spi_bpw_to_bytes(u32 bpw)
```

Covert bits per word to bytes

**Parameters**

- `u32 bpw`: Bits per word

**Description**

This function converts the given **bpw** to bytes. The result is always
power-of-two, e.g.,

```text
===============    =================
Input (in bits)    Output (in bytes)
===============    =================
        5                   1
        9                   2
        21                  4
        37                  8
===============    =================
```

It will return 0 for the 0 input.

**Return**

Bytes for the given **bpw**.

#### <a id="c-spi_controller_xfer_timeout"></a>`spi_controller_xfer_timeout()`

```c
unsigned int spi_controller_xfer_timeout(struct spi_controller *ctlr, struct spi_transfer *xfer)
```

Compute a suitable timeout value

**Parameters**

- `struct spi_controller *ctlr`: SPI device
- `struct spi_transfer *xfer`: Transfer descriptor

**Description**

Compute a relevant timeout value for the given transfer. We derive the time
that it would take on a single data line and take twice this amount of time
with a minimum of 500ms to avoid false positives on loaded systems.

**Return**

Transfer timeout value in milliseconds.

#### <a id="c-struct-spi_replaced_transfers"></a>`struct spi_replaced_transfers`

structure describing the spi_transfer replacements that have occurred so that they can get reverted

**Definition**

```c
struct spi_replaced_transfers {
    spi_replaced_release_t release;
    void *extradata;
    struct list_head replaced_transfers;
    struct list_head *replaced_after;
    size_t inserted;
    struct spi_transfer inserted_transfers[];
};
```

**Members**

- `release`: some extra release code to get executed prior to
  releasing this structure
- `extradata`: pointer to some extra data if requested or NULL
- `replaced_transfers`: transfers that have been replaced and which need
  to get restored
- `replaced_after`: the transfer after which the **replaced_transfers**
  are to get re-inserted
- `inserted`: number of transfers inserted
- `inserted_transfers`: array of spi_transfers of array-size **inserted**,
  that have been replacing replaced_transfers

**Note**

that **extradata** will point to **inserted_transfers**\[**inserted**\]
if some extra allocation is requested, so alignment will be the same
as for spi_transfers.

#### <a id="c-spi_sync_transfer"></a>`spi_sync_transfer()`

```c
int spi_sync_transfer(struct spi_device *spi, struct spi_transfer *xfers, unsigned int num_xfers)
```

synchronous SPI data transfer

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `struct spi_transfer *xfers`: An array of spi_transfers
- `unsigned int num_xfers`: Number of items in the xfer array

**Context**

can sleep

**Description**

Does a synchronous SPI data transfer of the given spi_transfer array.

For more specific semantics see [`spi_sync()`](#c-spi_sync).

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_write"></a>`spi_write()`

```c
int spi_write(struct spi_device *spi, const void *buf, size_t len)
```

SPI synchronous write

**Parameters**

- `struct spi_device *spi`: device to which data will be written
- `const void *buf`: data buffer
- `size_t len`: data buffer size

**Context**

can sleep

**Description**

This function writes the buffer **buf**.
Callable only from contexts that can sleep.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_read"></a>`spi_read()`

```c
int spi_read(struct spi_device *spi, void *buf, size_t len)
```

SPI synchronous read

**Parameters**

- `struct spi_device *spi`: device from which data will be read
- `void *buf`: data buffer
- `size_t len`: data buffer size

**Context**

can sleep

**Description**

This function reads the buffer **buf**.
Callable only from contexts that can sleep.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_w8r8"></a>`spi_w8r8()`

```c
ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
```

SPI synchronous 8 bit write followed by 8 bit read

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `u8 cmd`: command to be written before data is read back

**Context**

can sleep

**Description**

Callable only from contexts that can sleep.

**Return**

the (unsigned) eight bit number returned by the
device, or else a negative error code.

#### <a id="c-spi_w8r16"></a>`spi_w8r16()`

```c
ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
```

SPI synchronous 8 bit write followed by 16 bit read

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `u8 cmd`: command to be written before data is read back

**Context**

can sleep

**Description**

The number is returned in wire-order, which is at least sometimes
big-endian.

Callable only from contexts that can sleep.

**Return**

the (unsigned) sixteen bit number returned by the
device, or else a negative error code.

#### <a id="c-spi_w8r16be"></a>`spi_w8r16be()`

```c
ssize_t spi_w8r16be(struct spi_device *spi, u8 cmd)
```

SPI synchronous 8 bit write followed by 16 bit big-endian read

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `u8 cmd`: command to be written before data is read back

**Context**

can sleep

**Description**

This function is similar to spi_w8r16, with the exception that it will
convert the read 16 bit data word from big-endian to native endianness.

Callable only from contexts that can sleep.

**Return**

the (unsigned) sixteen bit number returned by the device in CPU
endianness, or else a negative error code.

#### <a id="c-struct-spi_board_info"></a>`struct spi_board_info`

board-specific template for a SPI device

**Definition**

```c
struct spi_board_info {
    char modalias[SPI_NAME_SIZE];
    const void      *platform_data;
    const struct software_node *swnode;
    void *controller_data;
    int irq;
    u32 max_speed_hz;
    u16 bus_num;
    u16 chip_select;
    u32 mode;
};
```

**Members**

- `modalias`: Initializes spi_device.modalias; identifies the driver.
- `platform_data`: Initializes spi_device.platform_data; the particular
  data stored there is driver-specific.
- `swnode`: Software node for the device.
- `controller_data`: Initializes spi_device.controller_data; some
  controllers need hints about hardware setup, e.g. for DMA.
- `irq`: Initializes spi_device.irq; depends on how the board is wired.
- `max_speed_hz`: Initializes spi_device.max_speed_hz; based on limits
  from the chip datasheet and board-specific signal quality issues.
- `bus_num`: Identifies which spi_controller parents the spi_device; unused
  by [`spi_new_device()`](#c-spi_new_device), and otherwise depends on board wiring.
- `chip_select`: Initializes spi_device.chip_select; depends on how
  the board is wired.
- `mode`: Initializes spi_device.mode; based on the chip datasheet, board
  wiring (some devices support both 3WIRE and standard modes), and
  possibly presence of an inverter in the chipselect path.

**Description**

When adding new SPI devices to the device tree, these structures serve
as a partial device template.  They hold information which can't always
be determined by drivers.  Information that `probe()` can establish (such
as the default transfer wordsize) is not included here.

These structures are used in two places.  Their primary role is to
be stored in tables of board-specific device descriptors, which are
declared early in board initialization and then used (much later) to
populate a controller's device tree after the that controller's driver
initializes.  A secondary (and atypical) role is as a parameter to
[`spi_new_device()`](#c-spi_new_device) call, which happens after those controller drivers
are active in some dynamic board configuration models.



#### <a id="c-spi_register_board_info"></a>`spi_register_board_info()`

```c
int spi_register_board_info(struct spi_board_info const *info, unsigned n)
```

register SPI devices for a given board

**Parameters**

- `struct spi_board_info const *info`: array of chip descriptors
- `unsigned n`: how many descriptors are provided

**Context**

can sleep

**Description**

Board-specific early init code calls this (probably during arch_initcall)
with segments of the SPI device table.  Any device nodes are created later,
after the relevant parent SPI controller (bus_num) is defined.  We keep
this table of devices forever, so that reloading a controller driver will
not make Linux forget about these hard-wired devices.

Other code can also call this, e.g. a particular add-on board might provide
SPI devices through its expansion connector, so code initializing that board
would naturally declare its SPI devices.

The board info passed can safely be __initdata ... but be careful of
any embedded pointers (platform_data, etc), they're copied as-is.

**Return**

zero on success, else a negative error code.



#### <a id="c-__spi_register_driver"></a>`__spi_register_driver()`

```c
int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
```

register a SPI driver

**Parameters**

- `struct module *owner`: owner module of the driver to register
- `struct spi_driver *sdrv`: the driver to register

**Context**

can sleep

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_alloc_device"></a>`spi_alloc_device()`

```c
struct spi_device * spi_alloc_device(struct spi_controller *ctlr)
```

Allocate a new SPI device

**Parameters**

- `struct spi_controller *ctlr`: Controller to which device is connected

**Context**

can sleep

**Description**

Allows a driver to allocate and initialize a spi_device without
registering it immediately.  This allows a driver to directly
fill the spi_device with device parameters before calling
[`spi_add_device()`](#c-spi_add_device) on it.

Caller is responsible to call [`spi_add_device()`](#c-spi_add_device) on the returned
spi_device structure to add it to the SPI controller.  If the caller
needs to discard the spi_device without adding it, then it should
call `spi_dev_put()` on it.

**Return**

a pointer to the new device, or NULL.

#### <a id="c-spi_add_device"></a>`spi_add_device()`

```c
int spi_add_device(struct spi_device *spi)
```

Add spi_device allocated with spi_alloc_device

**Parameters**

- `struct spi_device *spi`: spi_device to register

**Description**

Companion function to spi_alloc_device.  Devices allocated with
spi_alloc_device can be added onto the SPI bus with this function.

**Return**

0 on success; negative errno on failure

#### <a id="c-spi_new_device"></a>`spi_new_device()`

```c
struct spi_device * spi_new_device(struct spi_controller *ctlr, struct spi_board_info *chip)
```

instantiate one new SPI device

**Parameters**

- `struct spi_controller *ctlr`: Controller to which device is connected
- `struct spi_board_info *chip`: Describes the SPI device

**Context**

can sleep

**Description**

On typical mainboards, this is purely internal; and it's not needed
after board init creates the hard-wired devices.  Some development
platforms may not be able to use spi_register_board_info though, and
this is exported so that for example a USB or parport based adapter
driver could add devices (which it would learn about out-of-band).

**Return**

the new device, or NULL.

#### <a id="c-spi_unregister_device"></a>`spi_unregister_device()`

```c
void spi_unregister_device(struct spi_device *spi)
```

unregister a single SPI device

**Parameters**

- `struct spi_device *spi`: spi_device to unregister

**Description**

Start making the passed SPI device vanish. Normally this would be handled
by [`spi_unregister_controller()`](#c-spi_unregister_controller).

#### <a id="c-spi_finalize_current_transfer"></a>`spi_finalize_current_transfer()`

```c
void spi_finalize_current_transfer(struct spi_controller *ctlr)
```

report completion of a transfer

**Parameters**

- `struct spi_controller *ctlr`: the controller reporting completion

**Description**

Called by SPI drivers using the core `transfer_one_message()`
implementation to notify it that the current interrupt driven
transfer has finished and the next one may be scheduled.

#### <a id="c-spi_take_timestamp_pre"></a>`spi_take_timestamp_pre()`

```c
void spi_take_timestamp_pre(struct spi_controller *ctlr, struct spi_transfer *xfer, size_t progress, bool irqs_off)
```

helper to collect the beginning of the TX timestamp

**Parameters**

- `struct spi_controller *ctlr`: Pointer to the spi_controller structure of the driver
- `struct spi_transfer *xfer`: Pointer to the transfer being timestamped
- `size_t progress`: How many words (not bytes) have been transferred so far
- `bool irqs_off`: If true, will disable IRQs and preemption for the duration of the
  transfer, for less jitter in time measurement. Only compatible
  with PIO drivers. If true, must follow up with
  spi_take_timestamp_post or otherwise system will crash.
  WARNING: for fully predictable results, the CPU frequency must
  also be under control (governor).

**Description**

This is a helper for drivers to collect the beginning of the TX timestamp
for the requested byte from the SPI transfer. The frequency with which this
function must be called (once per word, once for the whole transfer, once
per batch of words etc) is arbitrary as long as the **tx** buffer offset is
greater than or equal to the requested byte at the time of the call. The
timestamp is only taken once, at the first such call. It is assumed that
the driver advances its **tx** buffer pointer monotonically.

#### <a id="c-spi_take_timestamp_post"></a>`spi_take_timestamp_post()`

```c
void spi_take_timestamp_post(struct spi_controller *ctlr, struct spi_transfer *xfer, size_t progress, bool irqs_off)
```

helper to collect the end of the TX timestamp

**Parameters**

- `struct spi_controller *ctlr`: Pointer to the spi_controller structure of the driver
- `struct spi_transfer *xfer`: Pointer to the transfer being timestamped
- `size_t progress`: How many words (not bytes) have been transferred so far
- `bool irqs_off`: If true, will re-enable IRQs and preemption for the local CPU.

**Description**

This is a helper for drivers to collect the end of the TX timestamp for
the requested byte from the SPI transfer. Can be called with an arbitrary
frequency: only the first call where **tx** exceeds or is equal to the
requested word will be timestamped.

#### <a id="c-spi_get_next_queued_message"></a>`spi_get_next_queued_message()`

```c
struct spi_message * spi_get_next_queued_message(struct spi_controller *ctlr)
```

called by driver to check for queued messages

**Parameters**

- `struct spi_controller *ctlr`: the controller to check for queued messages

**Description**

If there are more messages in the queue, the next message is returned from
this call.

**Return**

the next message in the queue, else NULL if the queue is empty.

#### <a id="c-spi_finalize_current_message"></a>`spi_finalize_current_message()`

```c
void spi_finalize_current_message(struct spi_controller *ctlr)
```

the current message is complete

**Parameters**

- `struct spi_controller *ctlr`: the controller to return the message to

**Description**

Called by the driver to notify the core that the message in the front of the
queue is complete and can be removed from the queue.

#### <a id="c-spi_new_ancillary_device"></a>`spi_new_ancillary_device()`

```c
struct spi_device * spi_new_ancillary_device(struct spi_device *spi, u8 chip_select)
```

Register ancillary SPI device

**Parameters**

- `struct spi_device *spi`: Pointer to the main SPI device registering the ancillary device
- `u8 chip_select`: Chip Select of the ancillary device

**Description**

Register an ancillary SPI device; for example some chips have a chip-select
for normal device usage and another one for setup/firmware upload.

This may only be called from main SPI device's probe routine.

**Return**

0 on success; negative errno on failure

#### <a id="c-acpi_spi_count_resources"></a>`acpi_spi_count_resources()`

```c
int acpi_spi_count_resources(struct acpi_device *adev)
```

Count the number of SpiSerialBus resources

**Parameters**

- `struct acpi_device *adev`: ACPI device

**Return**

the number of SpiSerialBus resources in the ACPI-device's
resource-list; or a negative error code.

#### <a id="c-acpi_spi_device_alloc"></a>`acpi_spi_device_alloc()`

```c
struct spi_device * acpi_spi_device_alloc(struct spi_controller *ctlr, struct acpi_device *adev, int index)
```

Allocate a spi device, and fill it in with ACPI information

**Parameters**

- `struct spi_controller *ctlr`: controller to which the spi device belongs
- `struct acpi_device *adev`: ACPI Device for the spi device
- `int index`: Index of the spi resource inside the ACPI Node

**Description**

This should be used to allocate a new SPI device from and ACPI Device node.
The caller is responsible for calling spi_add_device to register the SPI device.

If ctlr is set to NULL, the Controller for the SPI device will be looked up
using the resource.
If index is set to -1, index is not used.

**Note**

If index is -1, ctlr must be set.

**Return**

a pointer to the new device, or ERR_PTR on error.

#### <a id="c-spi_target_abort"></a>`spi_target_abort()`

```c
int spi_target_abort(struct spi_device *spi)
```

abort the ongoing transfer request on an SPI target controller

**Parameters**

- `struct spi_device *spi`: device used for the current transfer

#### <a id="c-__spi_alloc_controller"></a>`__spi_alloc_controller()`

```c
struct spi_controller * __spi_alloc_controller(struct device *dev, unsigned int size, bool target)
```

allocate an SPI host or target controller

**Parameters**

- `struct device *dev`: the controller, possibly using the platform_bus
- `unsigned int size`: how much zeroed driver-private data to allocate; the pointer to this
  memory is in the driver_data field of the returned device, accessible
  with `spi_controller_get_devdata()`; the memory is cacheline aligned;
  drivers granting DMA access to portions of their private data need to
  round up **size** using ALIGN(size, `dma_get_cache_alignment()`).
- `bool target`: flag indicating whether to allocate an SPI host (false) or SPI target (true)
  controller

**Context**

can sleep

**Description**

This call is used only by SPI controller drivers, which are the
only ones directly touching chip registers.  It's how they allocate
an spi_controller structure, prior to calling [`spi_register_controller()`](#c-spi_register_controller).

This must be called from context that can sleep.

The caller is responsible for assigning the bus number and initializing the
controller's methods before calling [`spi_register_controller()`](#c-spi_register_controller); and (after
errors adding the device) calling `spi_controller_put()` to prevent a memory
leak.

**Return**

the SPI controller structure on success, else NULL.

#### <a id="c-__devm_spi_alloc_controller"></a>`__devm_spi_alloc_controller()`

```c
struct spi_controller * __devm_spi_alloc_controller(struct device *dev, unsigned int size, bool target)
```

resource-managed [`__spi_alloc_controller()`](#c-__spi_alloc_controller)

**Parameters**

- `struct device *dev`: physical device of SPI controller
- `unsigned int size`: how much zeroed driver-private data to allocate
- `bool target`: whether to allocate an SPI host (false) or SPI target (true) controller

**Context**

can sleep

**Description**

Allocate an SPI controller and automatically release a reference on it
when **dev** is unbound from its driver.  Drivers are thus relieved from
having to call `spi_controller_put()`.

The arguments to this function are identical to [`__spi_alloc_controller()`](#c-__spi_alloc_controller).

**Return**

the SPI controller structure on success, else NULL.

#### <a id="c-spi_register_controller"></a>`spi_register_controller()`

```c
int spi_register_controller(struct spi_controller *ctlr)
```

register SPI host or target controller

**Parameters**

- `struct spi_controller *ctlr`: initialized controller, originally from `spi_alloc_host()` or
  `spi_alloc_target()`

**Context**

can sleep

**Description**

SPI controllers connect to their drivers using some non-SPI bus,
such as the platform bus.  The final stage of `probe()` in that code
includes calling [`spi_register_controller()`](#c-spi_register_controller) to hook up to this SPI bus glue.

SPI controllers use board specific (often SOC specific) bus numbers,
and board-specific addressing for SPI devices combines those numbers
with chip select numbers.  Since SPI does not directly support dynamic
device identification, boards need configuration tables telling which
chip is at which address.

This must be called from context that can sleep.  It returns zero on
success, else a negative error code (dropping the controller's refcount).
After a successful return, the caller is responsible for calling
[`spi_unregister_controller()`](#c-spi_unregister_controller).

**Return**

zero on success, else a negative error code.

#### <a id="c-devm_spi_register_controller"></a>`devm_spi_register_controller()`

```c
int devm_spi_register_controller(struct device *dev, struct spi_controller *ctlr)
```

register managed SPI host or target controller

**Parameters**

- `struct device *dev`: device managing SPI controller
- `struct spi_controller *ctlr`: initialized controller, originally from `spi_alloc_host()` or
  `spi_alloc_target()`

**Context**

can sleep

**Description**

Register a SPI device as with [`spi_register_controller()`](#c-spi_register_controller) which will
automatically be unregistered and freed.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_unregister_controller"></a>`spi_unregister_controller()`

```c
void spi_unregister_controller(struct spi_controller *ctlr)
```

unregister SPI host or target controller

**Parameters**

- `struct spi_controller *ctlr`: the controller being unregistered

**Context**

can sleep

**Description**

This call is used only by SPI controller drivers, which are the
only ones directly touching chip registers.

This must be called from context that can sleep.

Note that this function also drops a reference to the controller.

#### <a id="c-spi_split_transfers_maxsize"></a>`spi_split_transfers_maxsize()`

```c
int spi_split_transfers_maxsize(struct spi_controller *ctlr, struct spi_message *msg, size_t maxsize)
```

split spi transfers into multiple transfers when an individual transfer exceeds a certain size

**Parameters**

- `struct spi_controller *ctlr`: the **spi_controller** for this transfer
- `struct spi_message *msg`: the **spi_message** to transform
- `size_t maxsize`: the maximum when to apply this

**Description**

This function allocates resources that are automatically freed during the
spi message unoptimize phase so this function should only be called from
optimize_message callbacks.

**Return**

status of transformation

#### <a id="c-spi_split_transfers_maxwords"></a>`spi_split_transfers_maxwords()`

```c
int spi_split_transfers_maxwords(struct spi_controller *ctlr, struct spi_message *msg, size_t maxwords)
```

split SPI transfers into multiple transfers when an individual transfer exceeds a certain number of SPI words

**Parameters**

- `struct spi_controller *ctlr`: the **spi_controller** for this transfer
- `struct spi_message *msg`: the **spi_message** to transform
- `size_t maxwords`: the number of words to limit each transfer to

**Description**

This function allocates resources that are automatically freed during the
spi message unoptimize phase so this function should only be called from
optimize_message callbacks.

**Return**

status of transformation

#### <a id="c-spi_setup"></a>`spi_setup()`

```c
int spi_setup(struct spi_device *spi)
```

setup SPI mode and clock rate

**Parameters**

- `struct spi_device *spi`: the device whose settings are being modified

**Context**

can sleep, and no requests are queued to the device

**Description**

SPI protocol drivers may need to update the transfer mode if the
device doesn't work with its default.  They may likewise need
to update clock rates or word sizes from initial values.  This function
changes those settings, and must be called from a context that can sleep.
Except for SPI_CS_HIGH, which takes effect immediately, the changes take
effect the next time the device is selected and data is transferred to
or from it.  When this function returns, the SPI device is deselected.

Note that this call will fail if the protocol driver specifies an option
that the underlying controller or its driver does not support.  For
example, not all hardware supports wire transfers using nine bit words,
LSB-first wire encoding, or active-high chipselects.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_optimize_message"></a>`spi_optimize_message()`

```c
int spi_optimize_message(struct spi_device *spi, struct spi_message *msg)
```

do any one-time validation and setup for a SPI message

**Parameters**

- `struct spi_device *spi`: the device that will be used for the message
- `struct spi_message *msg`: the message to optimize

**Description**

Peripheral drivers that reuse the same message repeatedly may call this to
perform as much message prep as possible once, rather than repeating it each
time a message transfer is performed to improve throughput and reduce CPU
usage.

Once a message has been optimized, it cannot be modified with the exception
of updating the contents of any xfer->tx_buf (the pointer can't be changed,
only the data in the memory it points to).

Calls to this function must be balanced with calls to [`spi_unoptimize_message()`](#c-spi_unoptimize_message)
to avoid leaking resources.

**Context**

can sleep

**Return**

zero on success, else a negative error code

#### <a id="c-spi_unoptimize_message"></a>`spi_unoptimize_message()`

```c
void spi_unoptimize_message(struct spi_message *msg)
```

releases any resources allocated by [`spi_optimize_message()`](#c-spi_optimize_message)

**Parameters**

- `struct spi_message *msg`: the message to unoptimize

**Description**

Calls to this function must be balanced with calls to [`spi_optimize_message()`](#c-spi_optimize_message).

**Context**

can sleep

#### <a id="c-devm_spi_optimize_message"></a>`devm_spi_optimize_message()`

```c
int devm_spi_optimize_message(struct device *dev, struct spi_device *spi, struct spi_message *msg)
```

managed version of [`spi_optimize_message()`](#c-spi_optimize_message)

**Parameters**

- `struct device *dev`: the device that manages **msg** (usually **spi->dev**)
- `struct spi_device *spi`: the device that will be used for the message
- `struct spi_message *msg`: the message to optimize

**Return**

zero on success, else a negative error code

**Description**

[`spi_unoptimize_message()`](#c-spi_unoptimize_message) will automatically be called when the device is
removed.

#### <a id="c-spi_async"></a>`spi_async()`

```c
int spi_async(struct spi_device *spi, struct spi_message *message)
```

asynchronous SPI transfer

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `struct spi_message *message`: describes the data transfers, including completion callback

**Context**

any (IRQs may be blocked, etc)

**Description**

This call may be used in_irq and other contexts which can't sleep,
as well as from task contexts which can sleep.

The completion callback is invoked in a context which can't sleep.
Before that invocation, the value of message->status is undefined.
When the callback is issued, message->status holds either zero (to
indicate complete success) or a negative error code.  After that
callback returns, the driver which issued the transfer request may
deallocate the associated memory; it's no longer in use by any SPI
core or controller driver code.

Note that although all messages to a spi_device are handled in
FIFO order, messages may go to different devices in other orders.
Some device might be higher priority, or have various "hard" access
time requirements, for example.

On detection of any fault during the transfer, processing of
the entire message is aborted, and the device is deselected.
Until returning from the associated message completion callback,
no other spi_message queued to that device will be processed.
(This rule applies equally to all the synchronous transfer calls,
which are wrappers around this core asynchronous primitive.)

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_sync"></a>`spi_sync()`

```c
int spi_sync(struct spi_device *spi, struct spi_message *message)
```

blocking/synchronous SPI data transfers

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `struct spi_message *message`: describes the data transfers

**Context**

can sleep

**Description**

This call may only be used from a context that may sleep.  The sleep
is non-interruptible, and has no timeout.  Low-overhead controller
drivers may DMA directly into and out of the message buffers.

Note that the SPI device's chip select is active during the message,
and then is normally disabled between messages.  Drivers for some
frequently-used devices may want to minimize costs of selecting a chip,
by leaving it selected in anticipation that the next message will go
to the same chip.  (That may increase power usage.)

Also, the caller is guaranteeing that the memory associated with the
message will not be freed before this call returns.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_sync_locked"></a>`spi_sync_locked()`

```c
int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
```

version of spi_sync with exclusive bus usage

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `struct spi_message *message`: describes the data transfers

**Context**

can sleep

**Description**

This call may only be used from a context that may sleep.  The sleep
is non-interruptible, and has no timeout.  Low-overhead controller
drivers may DMA directly into and out of the message buffers.

This call should be used by drivers that require exclusive access to the
SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
be released by a spi_bus_unlock call when the exclusive access is over.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_bus_lock"></a>`spi_bus_lock()`

```c
int spi_bus_lock(struct spi_controller *ctlr)
```

obtain a lock for exclusive SPI bus usage

**Parameters**

- `struct spi_controller *ctlr`: SPI bus controller that should be locked for exclusive bus access

**Context**

can sleep

**Description**

This call may only be used from a context that may sleep.  The sleep
is non-interruptible, and has no timeout.

This call should be used by drivers that require exclusive access to the
SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
exclusive access is over. Data transfer must be done by spi_sync_locked
and spi_async_locked calls when the SPI bus lock is held.

**Return**

always zero.

#### <a id="c-spi_bus_unlock"></a>`spi_bus_unlock()`

```c
int spi_bus_unlock(struct spi_controller *ctlr)
```

release the lock for exclusive SPI bus usage

**Parameters**

- `struct spi_controller *ctlr`: SPI bus controller that was locked for exclusive bus access

**Context**

can sleep

**Description**

This call may only be used from a context that may sleep.  The sleep
is non-interruptible, and has no timeout.

This call releases an SPI bus lock previously obtained by an spi_bus_lock
call.

**Return**

always zero.

#### <a id="c-spi_write_then_read"></a>`spi_write_then_read()`

```c
int spi_write_then_read(struct spi_device *spi, const void *txbuf, unsigned n_tx, void *rxbuf, unsigned n_rx)
```

SPI synchronous write followed by read

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `const void *txbuf`: data to be written (need not be DMA-safe)
- `unsigned n_tx`: size of txbuf, in bytes
- `void *rxbuf`: buffer into which data will be read (need not be DMA-safe)
- `unsigned n_rx`: size of rxbuf, in bytes

**Context**

can sleep

**Description**

This performs a half duplex MicroWire style transaction with the
device, sending txbuf and then reading rxbuf.  The return value
is zero for success, else a negative errno status code.
This call may only be used from a context that may sleep.

Parameters to this routine are always copied using a small buffer.
Performance-sensitive or bulk transfer code should instead use
spi_{async,sync}() calls with DMA-safe buffers.

**Return**

zero on success, else a negative error code.

---

# Linux Switchtec Support

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> Microsemi's "Switchtec" line of PCI switch devices is already supported by the kernel with standard PCI switch drivers. However, the Switchtec device advertises a special management endpoint which enables some additional functionality.…

<a id="rst-linux-switchtec-support"></a>

Microsemi's "Switchtec" line of PCI switch devices is already supported by the kernel with standard PCI switch drivers. However, the Switchtec device advertises a special management endpoint which enables some additional functionality. This includes:

- Packet and Byte Counters

- Firmware Upgrades

- Event and Error logs

- Querying port link status

- Custom user firmware commands

The switchtec kernel module implements this functionality.

<a id="rst-interface"></a>

## Interface

The primary means of communicating with the Switchtec management firmware is through the Memory-mapped Remote Procedure Call (MRPC) interface. Commands are submitted to the interface with a 4-byte command identifier and up to 1KB of command specific data. The firmware will respond with a 4-byte return code and up to 1KB of command-specific data. The interface only processes a single command at a time.

<a id="rst-userspace-interface"></a>

## Userspace Interface

The MRPC interface will be exposed to userspace through a simple char device: /dev/switchtec\#, one for each management endpoint in the system.

The char device has the following semantics:

- A write must consist of at least 4 bytes and no more than 1028 bytes. The first 4 bytes will be interpreted as the Command ID and the remainder will be used as the input data. A write will send the command to the firmware to begin processing.

- Each write must be followed by exactly one read. Any double write will produce an error and any read that doesn't follow a write will produce an error.

- A read will block until the firmware completes the command and return the 4-byte Command Return Value plus up to 1024 bytes of output data. (The length will be specified by the size parameter of the read call -- reading less than 4 bytes will produce an error.)

- The poll call will also be supported for userspace applications that need to do other things while waiting for the command to complete.

The following IOCTLs are also supported by the device:

- SWITCHTEC_IOCTL_FLASH_INFO - Retrieve firmware length and number of partitions in the device.

- SWITCHTEC_IOCTL_FLASH_PART_INFO - Retrieve address and lengeth for any specified partition in flash.

- SWITCHTEC_IOCTL_EVENT_SUMMARY - Read a structure of bitmaps indicating all uncleared events.

- SWITCHTEC_IOCTL_EVENT_CTL - Get the current count, clear and set flags for any event. This ioctl takes in a switchtec_ioctl_event_ctl struct with the event_id, index and flags set (index being the partition or PFF number for non-global events). It returns whether the event has occurred, the number of times and any event specific data. The flags can be used to clear the count or enable and disable actions to happen when the event occurs. By using the SWITCHTEC_IOCTL_EVENT_FLAG_EN_POLL flag, you can set an event to trigger a poll command to return with POLLPRI. In this way, userspace can wait for events to occur.

- SWITCHTEC_IOCTL_PFF_TO_PORT and SWITCHTEC_IOCTL_PORT_TO_PFF convert between PCI Function Framework number (used by the event system) and Switchtec Logic Port ID and Partition number (which is more user friendly).

<a id="rst-non-transparent-bridge-ntb-driver"></a>

## Non-Transparent Bridge (NTB) Driver

An NTB hardware driver is provided for the Switchtec hardware in ntb_hw_switchtec. Currently, it only supports switches configured with exactly 2 NT partitions and zero or more non-NT partitions. It also requires the following configuration settings:

- Both NT partitions must be able to access each other's GAS spaces. Thus, the bits in the GAS Access Vector under Management Settings must be set to support this.

- Kernel configuration MUST include support for NTB (CONFIG_NTB needs to be set)

NT EP BAR 2 will be dynamically configured as a Direct Window, and the configuration file does not need to configure it explicitly.

Please refer to [Documentation/driver-api/ntb.rst](/kernel/hardware/driver-api/buses/ntb.md) in Linux source tree for an overall understanding of the Linux NTB stack. ntb_hw_switchtec works as an NTB Hardware Driver in this stack.

---

# target and iSCSI Interfaces Guide

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> TBD

<a id="rst-target-and-iscsi-interfaces-guide"></a>

<a id="rst-introduction-and-overview"></a>

## Introduction and Overview

TBD

<a id="rst-target-core-device-interfaces"></a>

## Target core device interfaces

This section is blank because no kerneldoc comments have been added to drivers/target/target_core_device.c.

<a id="rst-target-core-transport-interfaces"></a>

## Target core transport interfaces


#### <a id="c-transport_init_session"></a>`transport_init_session()`

```c
void transport_init_session(struct se_session *se_sess)
```

initialize a session object

**Parameters**

- `struct se_session *se_sess`: Session object pointer.

**Description**

The caller must have zero-initialized **se_sess** before calling this function.

#### <a id="c-transport_alloc_session"></a>`transport_alloc_session()`

```c
struct se_session * transport_alloc_session(enum target_prot_op sup_prot_ops)
```

allocate a session object and initialize it

**Parameters**

- `enum target_prot_op sup_prot_ops`: bitmask that defines which T10-PI modes are supported.

#### <a id="c-transport_alloc_session_tags"></a>`transport_alloc_session_tags()`

```c
int transport_alloc_session_tags(struct se_session *se_sess, unsigned int tag_num, unsigned int tag_size)
```

allocate target driver private data

**Parameters**

- `struct se_session *se_sess`: Session pointer.
- `unsigned int tag_num`: Maximum number of in-flight commands between initiator and target.
- `unsigned int tag_size`: Size in bytes of the private data a target driver associates with
  each command.

#### <a id="c-target_init_cmd"></a>`target_init_cmd()`

```c
int target_init_cmd(struct se_cmd *se_cmd, struct se_session *se_sess, unsigned char *sense, u64 unpacked_lun, u32 data_length, int task_attr, int data_dir, int flags)
```

initialize se_cmd

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to init
- `struct se_session *se_sess`: associated se_sess for endpoint
- `unsigned char *sense`: pointer to SCSI sense buffer
- `u64 unpacked_lun`: unpacked LUN to reference for struct se_lun
- `u32 data_length`: fabric expected data transfer length
- `int task_attr`: SAM task attribute
- `int data_dir`: DMA data direction
- `int flags`: flags for command submission from target_sc_flags_tables

**Description**

Task tags are supported if the caller has set **se_cmd->tag**.

If the fabric driver calls target_stop_session, then it must check the
return code and handle failures. This will never fail for other drivers,
and the return code can be ignored.

**Return**

- less than zero to signal active I/O shutdown failure.
- zero on success.

#### <a id="c-target_submit_prep"></a>`target_submit_prep()`

```c
int target_submit_prep(struct se_cmd *se_cmd, unsigned char *cdb, struct scatterlist *sgl, u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count, struct scatterlist *sgl_prot, u32 sgl_prot_count, gfp_t gfp)
```

prepare cmd for submission

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to prep
- `unsigned char *cdb`: pointer to SCSI CDB
- `struct scatterlist *sgl`: struct scatterlist memory for unidirectional mapping
- `u32 sgl_count`: scatterlist count for unidirectional mapping
- `struct scatterlist *sgl_bidi`: struct scatterlist memory for bidirectional READ mapping
- `u32 sgl_bidi_count`: scatterlist count for bidirectional READ mapping
- `struct scatterlist *sgl_prot`: struct scatterlist memory protection information
- `u32 sgl_prot_count`: scatterlist count for protection information
- `gfp_t gfp`: gfp allocation type

**Return**

- less than zero to signal failure.
- zero on success.

**Description**

If failure is returned, lio will the callers queue_status to complete
the cmd.

#### <a id="c-target_submit_cmd"></a>`target_submit_cmd()`

```c
void target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess, unsigned char *cdb, unsigned char *sense, u64 unpacked_lun, u32 data_length, int task_attr, int data_dir, int flags)
```

lookup unpacked lun and submit uninitialized se_cmd

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to submit
- `struct se_session *se_sess`: associated se_sess for endpoint
- `unsigned char *cdb`: pointer to SCSI CDB
- `unsigned char *sense`: pointer to SCSI sense buffer
- `u64 unpacked_lun`: unpacked LUN to reference for struct se_lun
- `u32 data_length`: fabric expected data transfer length
- `int task_attr`: SAM task attribute
- `int data_dir`: DMA data direction
- `int flags`: flags for command submission from target_sc_flags_tables

**Description**

Task tags are supported if the caller has set **se_cmd->tag**.

This may only be called from process context, and also currently
assumes internal allocation of fabric payload buffer by target-core.

It also assumes interal target core SGL memory allocation.

This function must only be used by drivers that do their own
sync during shutdown and does not use target_stop_session. If there
is a failure this function will call into the fabric driver's
queue_status with a CHECK_CONDITION.

#### <a id="c-target_submit"></a>`target_submit()`

```c
int target_submit(struct se_cmd *se_cmd)
```

perform final initialization and submit cmd to LIO core

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to submit

**Description**

target_submit_prep or something similar must have been called on the cmd,
and this must be called from process context.

#### <a id="c-target_submit_tmr"></a>`target_submit_tmr()`

```c
int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess, unsigned char *sense, u64 unpacked_lun, void *fabric_tmr_ptr, unsigned char tm_type, gfp_t gfp, u64 tag, int flags)
```

lookup unpacked lun and submit uninitialized se_cmd for TMR CDBs

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to submit
- `struct se_session *se_sess`: associated se_sess for endpoint
- `unsigned char *sense`: pointer to SCSI sense buffer
- `u64 unpacked_lun`: unpacked LUN to reference for struct se_lun
- `void *fabric_tmr_ptr`: fabric context for TMR req
- `unsigned char tm_type`: Type of TM request
- `gfp_t gfp`: gfp type for caller
- `u64 tag`: referenced task tag for TMR_ABORT_TASK
- `int flags`: submit cmd flags

**Description**

Callable from all contexts.

#### <a id="c-target_get_sess_cmd"></a>`target_get_sess_cmd()`

```c
int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref)
```

Verify the session is accepting cmds and take ref

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to add
- `bool ack_kref`: Signal that fabric will perform an ack [`target_put_sess_cmd()`](#c-target_put_sess_cmd)

#### <a id="c-target_put_sess_cmd"></a>`target_put_sess_cmd()`

```c
int target_put_sess_cmd(struct se_cmd *se_cmd)
```

decrease the command reference count

**Parameters**

- `struct se_cmd *se_cmd`: command to drop a reference from

**Description**

Returns 1 if and only if this [`target_put_sess_cmd()`](#c-target_put_sess_cmd) call caused the
refcount to drop to zero. Returns zero otherwise.

#### <a id="c-target_stop_cmd_counter"></a>`target_stop_cmd_counter()`

```c
void target_stop_cmd_counter(struct target_cmd_counter *cmd_cnt)
```

Stop new IO from being added to the counter.

**Parameters**

- `struct target_cmd_counter *cmd_cnt`: counter to stop

#### <a id="c-target_stop_session"></a>`target_stop_session()`

```c
void target_stop_session(struct se_session *se_sess)
```

Stop new IO from being queued on the session.

**Parameters**

- `struct se_session *se_sess`: session to stop

#### <a id="c-target_wait_for_cmds"></a>`target_wait_for_cmds()`

```c
void target_wait_for_cmds(struct target_cmd_counter *cmd_cnt)
```

Wait for outstanding cmds.

**Parameters**

- `struct target_cmd_counter *cmd_cnt`: counter to wait for active I/O for.

#### <a id="c-target_wait_for_sess_cmds"></a>`target_wait_for_sess_cmds()`

```c
void target_wait_for_sess_cmds(struct se_session *se_sess)
```

Wait for outstanding commands

**Parameters**

- `struct se_session *se_sess`: session to wait for active I/O

#### <a id="c-transport_wait_for_tasks"></a>`transport_wait_for_tasks()`

```c
bool transport_wait_for_tasks(struct se_cmd *cmd)
```

set CMD_T_STOP and wait for t_transport_stop_comp

**Parameters**

- `struct se_cmd *cmd`: command to wait on

#### <a id="c-target_send_busy"></a>`target_send_busy()`

```c
int target_send_busy(struct se_cmd *cmd)
```

Send SCSI BUSY status back to the initiator

**Parameters**

- `struct se_cmd *cmd`: SCSI command for which to send a BUSY reply.

**Note**

Only call this function if target_submit_cmd*() failed.


<a id="rst-target-supported-userspace-i-o"></a>

## Target-supported userspace I/O


**Userspace I/O**

Define a shared-memory interface for LIO to pass SCSI commands and
data to userspace for processing. This is to allow backends that
are too complex for in-kernel support to be possible.

It uses the UIO framework to do a lot of the device-creation and
introspection work for us.

See the .h file for how the ring is laid out. Note that while the
command ring is defined, the particulars of the data area are
not. Offset values in the command entry point to other locations
internal to the mmap-ed area. There is separate space outside the
command ring for data buffers. This leaves maximum flexibility for
moving buffer allocations, or even page flipping or other
allocation techniques, without altering the command ring layout.

SECURITY:
The user process must be assumed to be malicious. There's no way to
prevent it breaking the command ring protocol if it wants, but in
order to prevent other issues we must only ever read *data* from
the shared memory area, not offsets or sizes. This applies to
command ring entries as well as the mailbox. Extra code needed for
this may have a 'UAM' comment.



**Ring Design**

The mmaped area is divided into three parts:
1) The mailbox (struct tcmu_mailbox, below);
2) The command ring;
3) Everything beyond the command ring (data).

The mailbox tells userspace the offset of the command ring from the
start of the shared memory region, and how big the command ring is.

The kernel passes SCSI commands to userspace by putting a struct
tcmu_cmd_entry in the ring, updating mailbox->cmd_head, and poking
userspace via UIO's interrupt mechanism.

tcmu_cmd_entry contains a header. If the header type is PAD,
userspace should skip hdr->length bytes (mod cmdr_size) to find the
next cmd_entry.

Otherwise, the entry will contain offsets into the mmaped area that
contain the cdb and data buffers -- the latter accessible via the
iov array. iov addresses are also offsets into the shared area.

When userspace is completed handling the command, set
entry->rsp.scsi_status, fill in rsp.sense_buffer if appropriate,
and also set mailbox->cmd_tail equal to the old cmd_tail plus
hdr->length, mod cmdr_size. If cmd_tail doesn't equal cmd_head, it
should process the next packet the same way, and so on.


<a id="rst-iscsi-helper-functions"></a>

## iSCSI helper functions


#### <a id="c-iscsi_prep_data_out_pdu"></a>`iscsi_prep_data_out_pdu()`

```c
void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t, struct iscsi_data *hdr)
```

initialize Data-Out

**Parameters**

- `struct iscsi_task *task`: scsi command task
- `struct iscsi_r2t_info *r2t`: R2T info
- `struct iscsi_data *hdr`: iscsi data in pdu

**Notes**

Initialize Data-Out within this R2T sequence and finds
proper data_offset within this SCSI command.

This function is called with connection lock taken.

#### <a id="c-__iscsi_put_task"></a>`__iscsi_put_task()`

```c
void __iscsi_put_task(struct iscsi_task *task)
```

drop the refcount on a task

**Parameters**

- `struct iscsi_task *task`: iscsi_task to drop the refcount on

**Description**

The back_lock must be held when calling in case it frees the task.

#### <a id="c-iscsi_complete_scsi_task"></a>`iscsi_complete_scsi_task()`

```c
void iscsi_complete_scsi_task(struct iscsi_task *task, uint32_t exp_cmdsn, uint32_t max_cmdsn)
```

finish scsi task normally

**Parameters**

- `struct iscsi_task *task`: iscsi task for scsi cmd
- `uint32_t exp_cmdsn`: expected cmd sn in cpu format
- `uint32_t max_cmdsn`: max cmd sn in cpu format

**Description**

This is used when drivers do not need or cannot perform
lower level pdu processing.

Called with session back_lock

#### <a id="c-iscsi_itt_to_task"></a>`iscsi_itt_to_task()`

```c
struct iscsi_task * iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt)
```

look up task by itt

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection
- `itt_t itt`: itt

**Description**

This should be used for mgmt tasks like login and nops, or if
the LDD's itt space does not include the session age.

The session back_lock must be held.

#### <a id="c-__iscsi_complete_pdu"></a>`__iscsi_complete_pdu()`

```c
int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, int datalen)
```

complete pdu

**Parameters**

- `struct iscsi_conn *conn`: iscsi conn
- `struct iscsi_hdr *hdr`: iscsi header
- `char *data`: data buffer
- `int datalen`: len of data buffer

**Description**

Completes pdu processing by freeing any resources allocated at
queuecommand or send generic. session back_lock must be held and verify
itt must have been called.

#### <a id="c-iscsi_itt_to_ctask"></a>`iscsi_itt_to_ctask()`

```c
struct iscsi_task * iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt)
```

look up ctask by itt

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection
- `itt_t itt`: itt

**Description**

This should be used for cmd tasks.

The session back_lock must be held.

#### <a id="c-iscsi_requeue_task"></a>`iscsi_requeue_task()`

```c
void iscsi_requeue_task(struct iscsi_task *task)
```

requeue task to run from session workqueue

**Parameters**

- `struct iscsi_task *task`: task to requeue

**Description**

Callers must have taken a ref to the task that is going to be requeued.

#### <a id="c-iscsi_suspend_queue"></a>`iscsi_suspend_queue()`

```c
void iscsi_suspend_queue(struct iscsi_conn *conn)
```

suspend iscsi_queuecommand

**Parameters**

- `struct iscsi_conn *conn`: iscsi conn to stop queueing IO on

**Description**

This grabs the session frwd_lock to make sure no one is in
xmit_task/queuecommand, and then sets suspend to prevent
new commands from being queued. This only needs to be called
by offload drivers that need to sync a path like ep disconnect
with the iscsi_queuecommand/xmit_task. To start IO again libiscsi
will call iscsi_start_tx and iscsi_unblock_session when in FFP.

#### <a id="c-iscsi_suspend_tx"></a>`iscsi_suspend_tx()`

```c
void iscsi_suspend_tx(struct iscsi_conn *conn)
```

suspend iscsi_data_xmit

**Parameters**

- `struct iscsi_conn *conn`: iscsi conn to stop processing IO on.

**Description**

This function sets the suspend bit to prevent iscsi_data_xmit
from sending new IO, and if work is queued on the xmit thread
it will wait for it to be completed.

#### <a id="c-iscsi_suspend_rx"></a>`iscsi_suspend_rx()`

```c
void iscsi_suspend_rx(struct iscsi_conn *conn)
```

Prevent recvwork from running again.

**Parameters**

- `struct iscsi_conn *conn`: iscsi conn to stop.

#### <a id="c-iscsi_conn_unbind"></a>`iscsi_conn_unbind()`

```c
void iscsi_conn_unbind(struct iscsi_cls_conn *cls_conn, bool is_active)
```

prevent queueing to conn.

**Parameters**

- `struct iscsi_cls_conn *cls_conn`: iscsi conn ep is bound to.
- `bool is_active`: is the conn in use for boot or is this for EH/termination

**Description**

This must be called by drivers implementing the ep_disconnect callout.
It disables queueing to the connection from libiscsi in preparation for
an ep_disconnect call.

#### <a id="c-iscsi_eh_session_reset"></a>`iscsi_eh_session_reset()`

```c
int iscsi_eh_session_reset(struct scsi_cmnd *sc)
```

drop session and attempt relogin

**Parameters**

- `struct scsi_cmnd *sc`: scsi command

**Description**

This function will wait for a relogin, session termination from
userspace, or a recovery/replacement timeout.

#### <a id="c-iscsi_eh_recover_target"></a>`iscsi_eh_recover_target()`

```c
int iscsi_eh_recover_target(struct scsi_cmnd *sc)
```

reset target and possibly the session

**Parameters**

- `struct scsi_cmnd *sc`: scsi command

**Description**

This will attempt to send a warm target reset. If that fails,
we will escalate to ERL0 session recovery.

#### <a id="c-iscsi_host_add"></a>`iscsi_host_add()`

```c
int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev)
```

add host to system

**Parameters**

- `struct Scsi_Host *shost`: scsi host
- `struct device *pdev`: parent device

**Description**

This should be called by partial offload and software iscsi drivers
to add a host to the system.

#### <a id="c-iscsi_host_alloc"></a>`iscsi_host_alloc()`

```c
struct Scsi_Host * iscsi_host_alloc(const struct scsi_host_template *sht, int dd_data_size, bool xmit_can_sleep)
```

allocate a host and driver data

**Parameters**

- `const struct scsi_host_template *sht`: scsi host template
- `int dd_data_size`: driver host data size
- `bool xmit_can_sleep`: bool indicating if LLD will queue IO from a work queue

**Description**

This should be called by partial offload and software iscsi drivers.
To access the driver specific memory use the `iscsi_host_priv()` macro.

#### <a id="c-iscsi_host_remove"></a>`iscsi_host_remove()`

```c
void iscsi_host_remove(struct Scsi_Host *shost, bool is_shutdown)
```

remove host and sessions

**Parameters**

- `struct Scsi_Host *shost`: scsi host
- `bool is_shutdown`: true if called from a driver shutdown callout

**Description**

If there are any sessions left, this will initiate the removal and wait
for the completion.

#### <a id="c-iscsi_session_setup"></a>`iscsi_session_setup()`

```c
struct iscsi_cls_session * iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost, uint16_t cmds_max, int dd_size, int cmd_task_size, uint32_t initial_cmdsn, unsigned int id)
```

create iscsi cls session and host and session

**Parameters**

- `struct iscsi_transport *iscsit`: iscsi transport template
- `struct Scsi_Host *shost`: scsi host
- `uint16_t cmds_max`: session can queue
- `int dd_size`: private driver data size, added to session allocation size
- `int cmd_task_size`: LLD task private data size
- `uint32_t initial_cmdsn`: initial CmdSN
- `unsigned int id`: target ID to add to this session

**Description**

This can be used by software iscsi_transports that allocate
a session per scsi host.

Callers should set cmds_max to the largest total numer (mgmt + scsi) of
tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks
for nop handling and login/logout requests.

#### <a id="c-iscsi_session_free"></a>`iscsi_session_free()`

```c
void iscsi_session_free(struct iscsi_cls_session *cls_session)
```

Free iscsi session and it's resources

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi session

#### <a id="c-iscsi_session_teardown"></a>`iscsi_session_teardown()`

```c
void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
```

destroy session and cls_session

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi session

#### <a id="c-iscsi_conn_setup"></a>`iscsi_conn_setup()`

```c
struct iscsi_cls_conn * iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, uint32_t conn_idx)
```

create iscsi_cls_conn and iscsi_conn

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi_cls_session
- `int dd_size`: private driver data size
- `uint32_t conn_idx`: cid

#### <a id="c-iscsi_conn_teardown"></a>`iscsi_conn_teardown()`

```c
void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
```

teardown iscsi connection

**Parameters**

- `struct iscsi_cls_conn *cls_conn`: iscsi class connection

**Description**

TODO: we may need to make this into a two step process
like scsi-mls remove + put host


<a id="rst-iscsi-boot-information"></a>

## iSCSI boot information


#### <a id="c-iscsi_boot_create_target"></a>`iscsi_boot_create_target()`

```c
struct iscsi_boot_kobj * iscsi_boot_create_target(struct iscsi_boot_kset *boot_kset, int index, void *data, ssize_t (*show) (void *data, int type, char *buf), umode_t (*is_visible) (void *data, int type), void (*release) (void *data))
```

create boot target sysfs dir

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset
- `int index`: the target id
- `void *data`: driver specific data for target
- `ssize_t (*show) (void *data, int type, char *buf)`: attr show function
- `umode_t (*is_visible) (void *data, int type)`: attr visibility function
- `void (*release) (void *data)`: release function

**Note**

The boot sysfs lib will free the data passed in for the caller
when all refs to the target kobject have been released.

#### <a id="c-iscsi_boot_create_initiator"></a>`iscsi_boot_create_initiator()`

```c
struct iscsi_boot_kobj * iscsi_boot_create_initiator(struct iscsi_boot_kset *boot_kset, int index, void *data, ssize_t (*show) (void *data, int type, char *buf), umode_t (*is_visible) (void *data, int type), void (*release) (void *data))
```

create boot initiator sysfs dir

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset
- `int index`: the initiator id
- `void *data`: driver specific data
- `ssize_t (*show) (void *data, int type, char *buf)`: attr show function
- `umode_t (*is_visible) (void *data, int type)`: attr visibility function
- `void (*release) (void *data)`: release function

**Note**

The boot sysfs lib will free the data passed in for the caller
when all refs to the initiator kobject have been released.

#### <a id="c-iscsi_boot_create_ethernet"></a>`iscsi_boot_create_ethernet()`

```c
struct iscsi_boot_kobj * iscsi_boot_create_ethernet(struct iscsi_boot_kset *boot_kset, int index, void *data, ssize_t (*show) (void *data, int type, char *buf), umode_t (*is_visible) (void *data, int type), void (*release) (void *data))
```

create boot ethernet sysfs dir

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset
- `int index`: the ethernet device id
- `void *data`: driver specific data
- `ssize_t (*show) (void *data, int type, char *buf)`: attr show function
- `umode_t (*is_visible) (void *data, int type)`: attr visibility function
- `void (*release) (void *data)`: release function

**Note**

The boot sysfs lib will free the data passed in for the caller
when all refs to the ethernet kobject have been released.

#### <a id="c-iscsi_boot_create_acpitbl"></a>`iscsi_boot_create_acpitbl()`

```c
struct iscsi_boot_kobj * iscsi_boot_create_acpitbl(struct iscsi_boot_kset *boot_kset, int index, void *data, ssize_t (*show)(void *data, int type, char *buf), umode_t (*is_visible)(void *data, int type), void (*release)(void *data))
```

create boot acpi table sysfs dir

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset
- `int index`: not used
- `void *data`: driver specific data
- `ssize_t (*show)(void *data, int type, char *buf)`: attr show function
- `umode_t (*is_visible)(void *data, int type)`: attr visibility function
- `void (*release)(void *data)`: release function

**Note**

The boot sysfs lib will free the data passed in for the caller
when all refs to the acpitbl kobject have been released.

#### <a id="c-iscsi_boot_create_kset"></a>`iscsi_boot_create_kset()`

```c
struct iscsi_boot_kset * iscsi_boot_create_kset(const char *set_name)
```

creates root sysfs tree

**Parameters**

- `const char *set_name`: name of root dir

#### <a id="c-iscsi_boot_create_host_kset"></a>`iscsi_boot_create_host_kset()`

```c
struct iscsi_boot_kset * iscsi_boot_create_host_kset(unsigned int hostno)
```

creates root sysfs tree for a scsi host

**Parameters**

- `unsigned int hostno`: host number of scsi host

#### <a id="c-iscsi_boot_destroy_kset"></a>`iscsi_boot_destroy_kset()`

```c
void iscsi_boot_destroy_kset(struct iscsi_boot_kset *boot_kset)
```

destroy kset and kobjects under it

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset

**Description**

This will remove the kset and kobjects and attrs under it.


<a id="rst-iscsi-tcp-interfaces"></a>

## iSCSI TCP interfaces


#### <a id="c-iscsi_sw_tcp_recv"></a>`iscsi_sw_tcp_recv()`

```c
int iscsi_sw_tcp_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, unsigned int offset, size_t len)
```

TCP receive in sendfile fashion

**Parameters**

- `read_descriptor_t *rd_desc`: read descriptor
- `struct sk_buff *skb`: socket buffer
- `unsigned int offset`: offset in skb
- `size_t len`: skb->len - offset

#### <a id="c-iscsi_sw_sk_state_check"></a>`iscsi_sw_sk_state_check()`

```c
int iscsi_sw_sk_state_check(struct sock *sk)
```

check socket state

**Parameters**

- `struct sock *sk`: socket

**Description**

If the socket is in CLOSE or CLOSE_WAIT we should
not close the connection if there is still some
data pending.

Must be called with sk_callback_lock.

#### <a id="c-iscsi_sw_tcp_write_space"></a>`iscsi_sw_tcp_write_space()`

```c
void iscsi_sw_tcp_write_space(struct sock *sk)
```

Called when more output buffer space is available

**Parameters**

- `struct sock *sk`: socket space is available for

#### <a id="c-iscsi_sw_tcp_xmit_segment"></a>`iscsi_sw_tcp_xmit_segment()`

```c
int iscsi_sw_tcp_xmit_segment(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment)
```

transmit segment

**Parameters**

- `struct iscsi_tcp_conn *tcp_conn`: the iSCSI TCP connection
- `struct iscsi_segment *segment`: the buffer to transmnit

**Description**

This function transmits as much of the buffer as
the network layer will accept, and returns the number of
bytes transmitted.

If CRC hashing is enabled, the function will compute the
hash as it goes. When the entire segment has been transmitted,
it will retrieve the hash value and send it as well.

#### <a id="c-iscsi_sw_tcp_xmit"></a>`iscsi_sw_tcp_xmit()`

```c
int iscsi_sw_tcp_xmit(struct iscsi_conn *conn)
```

TCP transmit

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection

#### <a id="c-iscsi_sw_tcp_xmit_qlen"></a>`iscsi_sw_tcp_xmit_qlen()`

```c
int iscsi_sw_tcp_xmit_qlen(struct iscsi_conn *conn)
```

return the number of bytes queued for xmit

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection



#### <a id="c-iscsi_tcp_segment_done"></a>`iscsi_tcp_segment_done()`

```c
int iscsi_tcp_segment_done(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment, int recv, unsigned copied)
```

check whether the segment is complete

**Parameters**

- `struct iscsi_tcp_conn *tcp_conn`: iscsi tcp connection
- `struct iscsi_segment *segment`: iscsi segment to check
- `int recv`: set to one of this is called from the recv path
- `unsigned copied`: number of bytes copied

**Description**

Check if we're done receiving this segment. If the receive
buffer is full but we expect more data, move on to the
next entry in the scatterlist.

If the amount of data we received isn't a multiple of 4,
we will transparently receive the pad bytes, too.

This function must be re-entrant.

#### <a id="c-iscsi_tcp_hdr_recv_prep"></a>`iscsi_tcp_hdr_recv_prep()`

```c
void iscsi_tcp_hdr_recv_prep(struct iscsi_tcp_conn *tcp_conn)
```

prep segment for hdr reception

**Parameters**

- `struct iscsi_tcp_conn *tcp_conn`: iscsi connection to prep for

**Description**

This function always passes NULL for the crcp argument, because when this
function is called we do not yet know the final size of the header and want
to delay the digest processing until we know that.

#### <a id="c-iscsi_tcp_cleanup_task"></a>`iscsi_tcp_cleanup_task()`

```c
void iscsi_tcp_cleanup_task(struct iscsi_task *task)
```

free tcp_task resources

**Parameters**

- `struct iscsi_task *task`: iscsi task

**Description**

must be called with session back_lock

#### <a id="c-iscsi_tcp_recv_segment_is_hdr"></a>`iscsi_tcp_recv_segment_is_hdr()`

```c
int iscsi_tcp_recv_segment_is_hdr(struct iscsi_tcp_conn *tcp_conn)
```

tests if we are reading in a header

**Parameters**

- `struct iscsi_tcp_conn *tcp_conn`: iscsi tcp conn

**Description**

returns non zero if we are currently processing or setup to process
a header.

#### <a id="c-iscsi_tcp_recv_skb"></a>`iscsi_tcp_recv_skb()`

```c
int iscsi_tcp_recv_skb(struct iscsi_conn *conn, struct sk_buff *skb, unsigned int offset, bool offloaded, int *status)
```

Process skb

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection
- `struct sk_buff *skb`: network buffer with header and/or data segment
- `unsigned int offset`: offset in skb
- `bool offloaded`: bool indicating if transfer was offloaded
- `int *status`: iscsi TCP status result

**Description**

Will return status of transfer in **status**. And will return
number of bytes copied.

#### <a id="c-iscsi_tcp_task_init"></a>`iscsi_tcp_task_init()`

```c
int iscsi_tcp_task_init(struct iscsi_task *task)
```

Initialize iSCSI SCSI_READ or SCSI_WRITE commands

**Parameters**

- `struct iscsi_task *task`: scsi command task

#### <a id="c-iscsi_tcp_task_xmit"></a>`iscsi_tcp_task_xmit()`

```c
int iscsi_tcp_task_xmit(struct iscsi_task *task)
```

xmit normal PDU task

**Parameters**

- `struct iscsi_task *task`: iscsi command task

**Description**

We're expected to return 0 when everything was transmitted successfully,
-EAGAIN if there's still data in the queue, or != 0 for any other kind
of error.

---

# VME Device Drivers

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> As with other subsystems within the Linux kernel, VME device drivers register with the VME subsystem, typically called from the devices init routine. This is achieved via a call to vme_register_driver().

<a id="rst-vme-device-drivers"></a>

<a id="rst-driver-registration"></a>

## Driver registration

As with other subsystems within the Linux kernel, VME device drivers register with the VME subsystem, typically called from the devices init routine.  This is achieved via a call to `vme_register_driver()`.

A pointer to a structure of type `struct vme_driver <vme_driver>` must be provided to the registration function. Along with the maximum number of devices your driver is able to support.

At the minimum, the '.name', '.match' and '.probe' elements of `struct vme_driver <vme_driver>` should be correctly set. The '.name' element is a pointer to a string holding the device driver's name.

The '.match' function allows control over which VME devices should be registered with the driver. The match function should return 1 if a device should be probed and 0 otherwise. This example match function (from vme_user.c) limits the number of devices probed to one:



```c
#define USER_BUS_MAX    1
...
static int vme_user_match(struct vme_dev *vdev)
{
        if (vdev->id.num >= USER_BUS_MAX)
                return 0;
        return 1;
}
```

The '.probe' element should contain a pointer to the probe routine. The probe routine is passed a `struct vme_dev <vme_dev>` pointer as an argument.

Here, the 'num' field refers to the sequential device ID for this specific driver. The bridge number (or bus number) can be accessed using dev-&gt;bridge-&gt;num.

A function is also provided to unregister the driver from the VME core called `vme_unregister_driver()` and should usually be called from the device driver's exit routine.

<a id="rst-resource-management"></a>

## Resource management

Once a driver has registered with the VME core the provided match routine will be called the number of times specified during the registration. If a match succeeds, a non-zero value should be returned. A zero return value indicates failure. For all successful matches, the probe routine of the corresponding driver is called. The probe routine is passed a pointer to the devices device structure. This pointer should be saved, it will be required for requesting VME resources.

The driver can request ownership of one or more master windows (`vme_master_request()`), slave windows (`vme_slave_request()`) and/or dma channels (`vme_dma_request()`). Rather than allowing the device driver to request a specific window or DMA channel (which may be used by a different driver) the API allows a resource to be assigned based on the required attributes of the driver in question. For slave windows these attributes are split into the VME address spaces that need to be accessed in 'aspace' and VME bus cycle types required in 'cycle'. Master windows add a further set of attributes in 'width' specifying the required data transfer widths. These attributes are defined as bitmasks and as such any combination of the attributes can be requested for a single window, the core will assign a window that meets the requirements, returning a pointer of type vme_resource that should be used to identify the allocated resource when it is used. For DMA controllers, the request function requires the potential direction of any transfers to be provided in the route attributes. This is typically VME-to-MEM and/or MEM-to-VME, though some hardware can support VME-to-VME and MEM-to-MEM transfers as well as test pattern generation. If an unallocated window fitting the requirements can not be found a NULL pointer will be returned.

Functions are also provided to free window allocations once they are no longer required. These functions (`vme_master_free()`, `vme_slave_free()` and `vme_dma_free()`) should be passed the pointer to the resource provided during resource allocation.

<a id="rst-master-windows"></a>

## Master windows

Master windows provide access from the local processor\[s\] out onto the VME bus. The number of windows available and the available access modes is dependent on the underlying chipset. A window must be configured before it can be used.

<a id="rst-master-window-configuration"></a>

### Master window configuration

Once a master window has been assigned `vme_master_set()` can be used to configure it and `vme_master_get()` to retrieve the current settings. The address spaces, transfer widths and cycle types are the same as described under resource management, however some of the options are mutually exclusive. For example, only one address space may be specified.

<a id="rst-master-window-access"></a>

### Master window access

The function `vme_master_read()` can be used to read from and `vme_master_write()` used to write to configured master windows.

In addition to simple reads and writes, `vme_master_rmw()` is provided to do a read-modify-write transaction. Parts of a VME window can also be mapped into user space memory using `vme_master_mmap()`.

<a id="rst-slave-windows"></a>

## Slave windows

Slave windows provide devices on the VME bus access into mapped portions of the local memory. The number of windows available and the access modes that can be used is dependent on the underlying chipset. A window must be configured before it can be used.

<a id="rst-slave-window-configuration"></a>

### Slave window configuration

Once a slave window has been assigned `vme_slave_set()` can be used to configure it and `vme_slave_get()` to retrieve the current settings.

The address spaces, transfer widths and cycle types are the same as described under resource management, however some of the options are mutually exclusive. For example, only one address space may be specified.

<a id="rst-slave-window-buffer-allocation"></a>

### Slave window buffer allocation

Functions are provided to allow the user to allocate (`vme_alloc_consistent()`) and free (`vme_free_consistent()`) contiguous buffers which will be accessible by the VME bridge. These functions do not have to be used, other methods can be used to allocate a buffer, though care must be taken to ensure that they are contiguous and accessible by the VME bridge.

<a id="rst-slave-window-access"></a>

### Slave window access

Slave windows map local memory onto the VME bus, the standard methods for accessing memory should be used.

<a id="rst-dma-channels"></a>

## DMA channels

The VME DMA transfer provides the ability to run link-list DMA transfers. The API introduces the concept of DMA lists. Each DMA list is a link-list which can be passed to a DMA controller. Multiple lists can be created, extended, executed, reused and destroyed.

<a id="rst-list-management"></a>

### List Management

The function `vme_new_dma_list()` is provided to create and `vme_dma_list_free()` to destroy DMA lists. Execution of a list will not automatically destroy the list, thus enabling a list to be reused for repetitive tasks.

<a id="rst-list-population"></a>

### List Population

An item can be added to a list using `vme_dma_list_add()` (the source and destination attributes need to be created before calling this function, this is covered under "Transfer Attributes").

> [!NOTE]
>
> The detailed attributes of the transfers source and destination are not checked until an entry is added to a DMA list, the request for a DMA channel purely checks the directions in which the controller is expected to transfer data. As a result it is possible for this call to return an error, for example if the source or destination is in an unsupported VME address space.

<a id="rst-transfer-attributes"></a>

### Transfer Attributes

The attributes for the source and destination are handled separately from adding an item to a list. This is due to the diverse attributes required for each type of source and destination. There are functions to create attributes for PCI, VME and pattern sources and destinations (where appropriate):

> - PCI source or destination: `vme_dma_pci_attribute()`
>
> - VME source or destination: `vme_dma_vme_attribute()`
>
> - Pattern source: `vme_dma_pattern_attribute()`

The function `vme_dma_free_attribute()` should be used to free an attribute.

<a id="rst-list-execution"></a>

### List Execution

The function `vme_dma_list_exec()` queues a list for execution and will return once the list has been executed.

<a id="rst-interrupts"></a>

## Interrupts

The VME API provides functions to attach and detach callbacks to specific VME level and status ID combinations and for the generation of VME interrupts with specific VME level and status IDs.

<a id="rst-attaching-interrupt-handlers"></a>

### Attaching Interrupt Handlers

The function `vme_irq_request()` can be used to attach and `vme_irq_free()` to free a specific VME level and status ID combination. Any given combination can only be assigned a single callback function. A void pointer parameter is provided, the value of which is passed to the callback function, the use of this pointer is user undefined. The callback parameters are as follows. Care must be taken in writing a callback function, callback functions run in interrupt context:



```c
void callback(int level, int statid, void *priv);
```

<a id="rst-interrupt-generation"></a>

### Interrupt Generation

The function `vme_irq_generate()` can be used to generate a VME interrupt at a given VME level and VME status ID.

<a id="rst-location-monitors"></a>

## Location monitors

The VME API provides the following functionality to configure the location monitor.

<a id="rst-location-monitor-management"></a>

### Location Monitor Management

The function `vme_lm_request()` is provided to request the use of a block of location monitors and `vme_lm_free()` to free them after they are no longer required. Each block may provide a number of location monitors, monitoring adjacent locations. The function `vme_lm_count()` can be used to determine how many locations are provided.

<a id="rst-location-monitor-configuration"></a>

### Location Monitor Configuration

Once a bank of location monitors has been allocated, the function `vme_lm_set()` is provided to configure the location and mode of the location monitor. The function `vme_lm_get()` can be used to retrieve existing settings.

<a id="rst-location-monitor-use"></a>

### Location Monitor Use

The function `vme_lm_attach()` enables a callback to be attached and `vme_lm_detach()` allows on to be detached from each location monitor location. Each location monitor can monitor a number of adjacent locations. The callback function is declared as follows.



```c
void callback(void *data);
```

<a id="rst-slot-detection"></a>

## Slot Detection

The function `vme_slot_num()` returns the slot ID of the provided bridge.

<a id="rst-bus-detection"></a>

## Bus Detection

The function `vme_bus_num()` returns the bus ID of the provided bridge.

<a id="rst-vme-api"></a>

## VME API


#### <a id="c-struct-vme_dev"></a>`struct vme_dev`

Structure representing a VME device

**Definition**

```c
struct vme_dev {
    int num;
    struct vme_bridge *bridge;
    struct device dev;
    struct list_head drv_list;
    struct list_head bridge_list;
};
```

**Members**

- `num`: The device number
- `bridge`: Pointer to the bridge device this device is on
- `dev`: Internal device structure
- `drv_list`: List of devices (per driver)
- `bridge_list`: List of devices (per bridge)

#### <a id="c-struct-vme_driver"></a>`struct vme_driver`

Structure representing a VME driver

**Definition**

```c
struct vme_driver {
    const char *name;
    int (*match)(struct vme_dev *vdev);
    int (*probe)(struct vme_dev *vdev);
    void (*remove)(struct vme_dev *vdev);
    struct device_driver driver;
    struct list_head devices;
};
```

**Members**

- `name`: Driver name, should be unique among VME drivers and usually the same
  as the module name.
- `match`: Callback used to determine whether probe should be run.
- `probe`: Callback for device binding, called when new device is detected.
- `remove`: Callback, called on device removal.
- `driver`: Underlying generic device driver structure.
- `devices`: List of VME devices (struct vme_dev) associated with this driver.



#### <a id="c-vme_alloc_consistent"></a>`vme_alloc_consistent()`

```c
void * vme_alloc_consistent(struct vme_resource *resource, size_t size, dma_addr_t *dma)
```

Allocate contiguous memory.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME resource.
- `size_t size`: Size of allocation required.
- `dma_addr_t *dma`: Pointer to variable to store physical address of allocation.

**Description**

Allocate a contiguous block of memory for use by the driver. This is used to
create the buffers for the slave windows.

**Return**

Virtual address of allocation on success, NULL on failure.

#### <a id="c-vme_free_consistent"></a>`vme_free_consistent()`

```c
void vme_free_consistent(struct vme_resource *resource, size_t size, void *vaddr, dma_addr_t dma)
```

Free previously allocated memory.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME resource.
- `size_t size`: Size of allocation to free.
- `void *vaddr`: Virtual address of allocation.
- `dma_addr_t dma`: Physical address of allocation.

**Description**

Free previously allocated block of contiguous memory.

#### <a id="c-vme_get_size"></a>`vme_get_size()`

```c
size_t vme_get_size(struct vme_resource *resource)
```

Helper function returning size of a VME window

**Parameters**

- `struct vme_resource *resource`: Pointer to VME slave or master resource.

**Description**

Determine the size of the VME window provided. This is a helper
function, wrappering the call to vme_master_get or vme_slave_get
depending on the type of window resource handed to it.

**Return**

Size of the window on success, zero on failure.

#### <a id="c-vme_slave_request"></a>`vme_slave_request()`

```c
struct vme_resource * vme_slave_request(struct vme_dev *vdev, u32 address, u32 cycle)
```

Request a VME slave window resource.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `u32 address`: Required VME address space.
- `u32 cycle`: Required VME data transfer cycle type.

**Description**

Request use of a VME window resource capable of being set for the requested
address space and data transfer cycle.

**Return**

Pointer to VME resource on success, NULL on failure.

#### <a id="c-vme_slave_set"></a>`vme_slave_set()`

```c
int vme_slave_set(struct vme_resource *resource, int enabled, unsigned long long vme_base, unsigned long long size, dma_addr_t buf_base, u32 aspace, u32 cycle)
```

Set VME slave window configuration.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME slave resource.
- `int enabled`: State to which the window should be configured.
- `unsigned long long vme_base`: Base address for the window.
- `unsigned long long size`: Size of the VME window.
- `dma_addr_t buf_base`: Based address of buffer used to provide VME slave window storage.
- `u32 aspace`: VME address space for the VME window.
- `u32 cycle`: VME data transfer cycle type for the VME window.

**Description**

Set configuration for provided VME slave window.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device, if an invalid resource has been provided or invalid
attributes are provided. Hardware specific errors may also be
returned.

#### <a id="c-vme_slave_get"></a>`vme_slave_get()`

```c
int vme_slave_get(struct vme_resource *resource, int *enabled, unsigned long long *vme_base, unsigned long long *size, dma_addr_t *buf_base, u32 *aspace, u32 *cycle)
```

Retrieve VME slave window configuration.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME slave resource.
- `int *enabled`: Pointer to variable for storing state.
- `unsigned long long *vme_base`: Pointer to variable for storing window base address.
- `unsigned long long *size`: Pointer to variable for storing window size.
- `dma_addr_t *buf_base`: Pointer to variable for storing slave buffer base address.
- `u32 *aspace`: Pointer to variable for storing VME address space.
- `u32 *cycle`: Pointer to variable for storing VME data transfer cycle type.

**Description**

Return configuration for provided VME slave window.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device or if an invalid resource has been provided.

#### <a id="c-vme_slave_free"></a>`vme_slave_free()`

```c
void vme_slave_free(struct vme_resource *resource)
```

Free VME slave window

**Parameters**

- `struct vme_resource *resource`: Pointer to VME slave resource.

**Description**

Free the provided slave resource so that it may be reallocated.

#### <a id="c-vme_master_request"></a>`vme_master_request()`

```c
struct vme_resource * vme_master_request(struct vme_dev *vdev, u32 address, u32 cycle, u32 dwidth)
```

Request a VME master window resource.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `u32 address`: Required VME address space.
- `u32 cycle`: Required VME data transfer cycle type.
- `u32 dwidth`: Required VME data transfer width.

**Description**

Request use of a VME window resource capable of being set for the requested
address space, data transfer cycle and width.

**Return**

Pointer to VME resource on success, NULL on failure.

#### <a id="c-vme_master_set"></a>`vme_master_set()`

```c
int vme_master_set(struct vme_resource *resource, int enabled, unsigned long long vme_base, unsigned long long size, u32 aspace, u32 cycle, u32 dwidth)
```

Set VME master window configuration.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `int enabled`: State to which the window should be configured.
- `unsigned long long vme_base`: Base address for the window.
- `unsigned long long size`: Size of the VME window.
- `u32 aspace`: VME address space for the VME window.
- `u32 cycle`: VME data transfer cycle type for the VME window.
- `u32 dwidth`: VME data transfer width for the VME window.

**Description**

Set configuration for provided VME master window.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device, if an invalid resource has been provided or invalid
attributes are provided. Hardware specific errors may also be
returned.

#### <a id="c-vme_master_get"></a>`vme_master_get()`

```c
int vme_master_get(struct vme_resource *resource, int *enabled, unsigned long long *vme_base, unsigned long long *size, u32 *aspace, u32 *cycle, u32 *dwidth)
```

Retrieve VME master window configuration.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `int *enabled`: Pointer to variable for storing state.
- `unsigned long long *vme_base`: Pointer to variable for storing window base address.
- `unsigned long long *size`: Pointer to variable for storing window size.
- `u32 *aspace`: Pointer to variable for storing VME address space.
- `u32 *cycle`: Pointer to variable for storing VME data transfer cycle type.
- `u32 *dwidth`: Pointer to variable for storing VME data transfer width.

**Description**

Return configuration for provided VME master window.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device or if an invalid resource has been provided.

#### <a id="c-vme_master_read"></a>`vme_master_read()`

```c
ssize_t vme_master_read(struct vme_resource *resource, void *buf, size_t count, loff_t offset)
```

Read data from VME space into a buffer.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `void *buf`: Pointer to buffer where data should be transferred.
- `size_t count`: Number of bytes to transfer.
- `loff_t offset`: Offset into VME master window at which to start transfer.

**Description**

Perform read of count bytes of data from location on VME bus which maps into
the VME master window at offset to buf.

**Return**

Number of bytes read, -EINVAL if resource is not a VME master
resource or read operation is not supported. -EFAULT returned if
invalid offset is provided. Hardware specific errors may also be
returned.

#### <a id="c-vme_master_write"></a>`vme_master_write()`

```c
ssize_t vme_master_write(struct vme_resource *resource, void *buf, size_t count, loff_t offset)
```

Write data out to VME space from a buffer.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `void *buf`: Pointer to buffer holding data to transfer.
- `size_t count`: Number of bytes to transfer.
- `loff_t offset`: Offset into VME master window at which to start transfer.

**Description**

Perform write of count bytes of data from buf to location on VME bus which
maps into the VME master window at offset.

**Return**

Number of bytes written, -EINVAL if resource is not a VME master
resource or write operation is not supported. -EFAULT returned if
invalid offset is provided. Hardware specific errors may also be
returned.

#### <a id="c-vme_master_rmw"></a>`vme_master_rmw()`

```c
unsigned int vme_master_rmw(struct vme_resource *resource, unsigned int mask, unsigned int compare, unsigned int swap, loff_t offset)
```

Perform read-modify-write cycle.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `unsigned int mask`: Bits to be compared and swapped in operation.
- `unsigned int compare`: Bits to be compared with data read from offset.
- `unsigned int swap`: Bits to be swapped in data read from offset.
- `loff_t offset`: Offset into VME master window at which to perform operation.

**Description**

Perform read-modify-write cycle on provided location:
- Location on VME bus is read.
- Bits selected by mask are compared with compare.
- Where a selected bit matches that in compare and are selected in swap,
the bit is swapped.
- Result written back to location on VME bus.

**Return**

Bytes written on success, -EINVAL if resource is not a VME master
resource or RMW operation is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_master_mmap"></a>`vme_master_mmap()`

```c
int vme_master_mmap(struct vme_resource *resource, struct vm_area_struct *vma)
```

Mmap region of VME master window.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `struct vm_area_struct *vma`: Pointer to definition of user mapping.

**Description**

Memory map a region of the VME master window into user space.

**Return**

Zero on success, -EINVAL if resource is not a VME master
resource or -EFAULT if map exceeds window size. Other generic mmap
errors may also be returned.

#### <a id="c-vme_master_free"></a>`vme_master_free()`

```c
void vme_master_free(struct vme_resource *resource)
```

Free VME master window

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.

**Description**

Free the provided master resource so that it may be reallocated.

#### <a id="c-vme_dma_request"></a>`vme_dma_request()`

```c
struct vme_resource * vme_dma_request(struct vme_dev *vdev, u32 route)
```

Request a DMA controller.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `u32 route`: Required src/destination combination.

**Description**

Request a VME DMA controller with capability to perform transfers between
requested source/destination combination.

**Return**

Pointer to VME DMA resource on success, NULL on failure.

#### <a id="c-vme_new_dma_list"></a>`vme_new_dma_list()`

```c
struct vme_dma_list * vme_new_dma_list(struct vme_resource *resource)
```

Create new VME DMA list.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME DMA resource.

**Description**

Create a new VME DMA list. It is the responsibility of the user to free
the list once it is no longer required with [`vme_dma_list_free()`](#c-vme_dma_list_free).

**Return**

Pointer to new VME DMA list, NULL on allocation failure or invalid
VME DMA resource.

#### <a id="c-vme_dma_pattern_attribute"></a>`vme_dma_pattern_attribute()`

```c
struct vme_dma_attr * vme_dma_pattern_attribute(u32 pattern, u32 type)
```

Create "Pattern" type VME DMA list attribute.

**Parameters**

- `u32 pattern`: Value to use used as pattern
- `u32 type`: Type of pattern to be written.

**Description**

Create VME DMA list attribute for pattern generation. It is the
responsibility of the user to free used attributes using
[`vme_dma_free_attribute()`](#c-vme_dma_free_attribute).

**Return**

Pointer to VME DMA attribute, NULL on failure.

#### <a id="c-vme_dma_pci_attribute"></a>`vme_dma_pci_attribute()`

```c
struct vme_dma_attr * vme_dma_pci_attribute(dma_addr_t address)
```

Create "PCI" type VME DMA list attribute.

**Parameters**

- `dma_addr_t address`: PCI base address for DMA transfer.

**Description**

Create VME DMA list attribute pointing to a location on PCI for DMA
transfers. It is the responsibility of the user to free used attributes
using [`vme_dma_free_attribute()`](#c-vme_dma_free_attribute).

**Return**

Pointer to VME DMA attribute, NULL on failure.

#### <a id="c-vme_dma_vme_attribute"></a>`vme_dma_vme_attribute()`

```c
struct vme_dma_attr * vme_dma_vme_attribute(unsigned long long address, u32 aspace, u32 cycle, u32 dwidth)
```

Create "VME" type VME DMA list attribute.

**Parameters**

- `unsigned long long address`: VME base address for DMA transfer.
- `u32 aspace`: VME address space to use for DMA transfer.
- `u32 cycle`: VME bus cycle to use for DMA transfer.
- `u32 dwidth`: VME data width to use for DMA transfer.

**Description**

Create VME DMA list attribute pointing to a location on the VME bus for DMA
transfers. It is the responsibility of the user to free used attributes
using [`vme_dma_free_attribute()`](#c-vme_dma_free_attribute).

**Return**

Pointer to VME DMA attribute, NULL on failure.

#### <a id="c-vme_dma_free_attribute"></a>`vme_dma_free_attribute()`

```c
void vme_dma_free_attribute(struct vme_dma_attr *attributes)
```

Free DMA list attribute.

**Parameters**

- `struct vme_dma_attr *attributes`: Pointer to DMA list attribute.

**Description**

Free VME DMA list attribute. VME DMA list attributes can be safely freed
once [`vme_dma_list_add()`](#c-vme_dma_list_add) has returned.

#### <a id="c-vme_dma_list_add"></a>`vme_dma_list_add()`

```c
int vme_dma_list_add(struct vme_dma_list *list, struct vme_dma_attr *src, struct vme_dma_attr *dest, size_t count)
```

Add entry to a VME DMA list.

**Parameters**

- `struct vme_dma_list *list`: Pointer to VME list.
- `struct vme_dma_attr *src`: Pointer to DMA list attribute to use as source.
- `struct vme_dma_attr *dest`: Pointer to DMA list attribute to use as destination.
- `size_t count`: Number of bytes to transfer.

**Description**

Add an entry to the provided VME DMA list. Entry requires pointers to source
and destination DMA attributes and a count.

Please note, the attributes supported as source and destinations for
transfers are hardware dependent.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device or if the link list has already been submitted for execution.
Hardware specific errors also possible.

#### <a id="c-vme_dma_list_exec"></a>`vme_dma_list_exec()`

```c
int vme_dma_list_exec(struct vme_dma_list *list)
```

Queue a VME DMA list for execution.

**Parameters**

- `struct vme_dma_list *list`: Pointer to VME list.

**Description**

Queue the provided VME DMA list for execution. The call will return once the
list has been executed.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device. Hardware specific errors also possible.

#### <a id="c-vme_dma_list_free"></a>`vme_dma_list_free()`

```c
int vme_dma_list_free(struct vme_dma_list *list)
```

Free a VME DMA list.

**Parameters**

- `struct vme_dma_list *list`: Pointer to VME list.

**Description**

Free the provided DMA list and all its entries.

**Return**

Zero on success, -EINVAL on invalid VME resource, -EBUSY if resource
is still in use. Hardware specific errors also possible.

#### <a id="c-vme_dma_free"></a>`vme_dma_free()`

```c
int vme_dma_free(struct vme_resource *resource)
```

Free a VME DMA resource.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME DMA resource.

**Description**

Free the provided DMA resource so that it may be reallocated.

**Return**

Zero on success, -EINVAL on invalid VME resource, -EBUSY if resource
is still active.

#### <a id="c-vme_irq_request"></a>`vme_irq_request()`

```c
int vme_irq_request(struct vme_dev *vdev, int level, int statid, void (*callback)(int level, int statid, void *priv_data), void *priv_data)
```

Request a specific VME interrupt.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `int level`: Interrupt priority being requested.
- `int statid`: Interrupt vector being requested.
- `void (*callback)(int level, int statid, void *priv_data)`: Pointer to callback function called when VME interrupt/vector
  received.
- `void *priv_data`: Generic pointer that will be passed to the callback function.

**Description**

Request callback to be attached as a handler for VME interrupts with provided
level and statid.

**Return**

Zero on success, -EINVAL on invalid vme device, level or if the
function is not supported, -EBUSY if the level/statid combination is
already in use. Hardware specific errors also possible.

#### <a id="c-vme_irq_free"></a>`vme_irq_free()`

```c
void vme_irq_free(struct vme_dev *vdev, int level, int statid)
```

Free a VME interrupt.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `int level`: Interrupt priority of interrupt being freed.
- `int statid`: Interrupt vector of interrupt being freed.

**Description**

Remove previously attached callback from VME interrupt priority/vector.

#### <a id="c-vme_irq_generate"></a>`vme_irq_generate()`

```c
int vme_irq_generate(struct vme_dev *vdev, int level, int statid)
```

Generate VME interrupt.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `int level`: Interrupt priority at which to assert the interrupt.
- `int statid`: Interrupt vector to associate with the interrupt.

**Description**

Generate a VME interrupt of the provided level and with the provided
statid.

**Return**

Zero on success, -EINVAL on invalid vme device, level or if the
function is not supported. Hardware specific errors also possible.

#### <a id="c-vme_lm_request"></a>`vme_lm_request()`

```c
struct vme_resource * vme_lm_request(struct vme_dev *vdev)
```

Request a VME location monitor

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.

**Description**

Allocate a location monitor resource to the driver. A location monitor
allows the driver to monitor accesses to a contiguous number of
addresses on the VME bus.

**Return**

Pointer to a VME resource on success or NULL on failure.

#### <a id="c-vme_lm_count"></a>`vme_lm_count()`

```c
int vme_lm_count(struct vme_resource *resource)
```

Determine number of VME Addresses monitored

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.

**Description**

The number of contiguous addresses monitored is hardware dependent.
Return the number of contiguous addresses monitored by the
location monitor.

**Return**

Count of addresses monitored or -EINVAL when provided with an
invalid location monitor resource.

#### <a id="c-vme_lm_set"></a>`vme_lm_set()`

```c
int vme_lm_set(struct vme_resource *resource, unsigned long long lm_base, u32 aspace, u32 cycle)
```

Configure location monitor

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.
- `unsigned long long lm_base`: Base address to monitor.
- `u32 aspace`: VME address space to monitor.
- `u32 cycle`: VME bus cycle type to monitor.

**Description**

Set the base address, address space and cycle type of accesses to be
monitored by the location monitor.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource or function is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_lm_get"></a>`vme_lm_get()`

```c
int vme_lm_get(struct vme_resource *resource, unsigned long long *lm_base, u32 *aspace, u32 *cycle)
```

Retrieve location monitor settings

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.
- `unsigned long long *lm_base`: Pointer used to output the base address monitored.
- `u32 *aspace`: Pointer used to output the address space monitored.
- `u32 *cycle`: Pointer used to output the VME bus cycle type monitored.

**Description**

Retrieve the base address, address space and cycle type of accesses to
be monitored by the location monitor.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource or function is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_lm_attach"></a>`vme_lm_attach()`

```c
int vme_lm_attach(struct vme_resource *resource, int monitor, void (*callback)(void *), void *data)
```

Provide callback for location monitor address

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.
- `int monitor`: Offset to which callback should be attached.
- `void (*callback)(void *)`: Pointer to callback function called when triggered.
- `void *data`: Generic pointer that will be passed to the callback function.

**Description**

Attach a callback to the specified offset into the location monitors
monitored addresses. A generic pointer is provided to allow data to be
passed to the callback when called.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource or function is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_lm_detach"></a>`vme_lm_detach()`

```c
int vme_lm_detach(struct vme_resource *resource, int monitor)
```

Remove callback for location monitor address

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.
- `int monitor`: Offset to which callback should be removed.

**Description**

Remove the callback associated with the specified offset into the
location monitors monitored addresses.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource or function is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_lm_free"></a>`vme_lm_free()`

```c
void vme_lm_free(struct vme_resource *resource)
```

Free allocated VME location monitor

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.

**Description**

Free allocation of a VME location monitor.

- WARNING: This function currently expects that any callbacks that have

  been attached to the location monitor have been removed.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource.

#### <a id="c-vme_slot_num"></a>`vme_slot_num()`

```c
int vme_slot_num(struct vme_dev *vdev)
```

Retrieve slot ID

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.

**Description**

Retrieve the slot ID associated with the provided VME device.

**Return**

The slot ID on success, -EINVAL if VME bridge cannot be determined
or the function is not supported. Hardware specific errors may also
be returned.

#### <a id="c-vme_bus_num"></a>`vme_bus_num()`

```c
int vme_bus_num(struct vme_dev *vdev)
```

Retrieve bus number

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.

**Description**

Retrieve the bus enumeration associated with the provided VME device.

**Return**

The bus number on success, -EINVAL if VME bridge cannot be
determined.

#### <a id="c-vme_register_driver"></a>`vme_register_driver()`

```c
int vme_register_driver(struct vme_driver *drv, unsigned int ndevs)
```

Register a VME driver

**Parameters**

- `struct vme_driver *drv`: Pointer to VME driver structure to register.
- `unsigned int ndevs`: Maximum number of devices to allow to be enumerated.

**Description**

Register a VME device driver with the VME subsystem.

**Return**

Zero on success, error value on registration failure.

#### <a id="c-vme_unregister_driver"></a>`vme_unregister_driver()`

```c
void vme_unregister_driver(struct vme_driver *drv)
```

Unregister a VME driver

**Parameters**

- `struct vme_driver *drv`: Pointer to VME driver structure to unregister.

**Description**

Unregister a VME device driver from the VME subsystem.

---

# W1: Dallas' 1-wire bus

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> W1 kernel API functions.

<a id="rst-w1-dallas-1-wire-bus"></a>

**Author:** David Fries

<a id="rst-w1-api-internal-to-the-kernel"></a>

## W1 API internal to the kernel

<a id="rst-include-linux-w1-h"></a>

### include/linux/w1.h

W1 kernel API functions.


#### <a id="c-struct-w1_reg_num"></a>`struct w1_reg_num`

broken out slave device id

**Definition**

```c
struct w1_reg_num {
    #if defined(__LITTLE_ENDIAN_BITFIELD);
        __u64 family:8, id:48, crc:8;
    #elif defined(__BIG_ENDIAN_BITFIELD);
        __u64 crc:8, id:48, family:8;
    #else;
    #error "Please fix <asm/byteorder.h>";
    #endif;
};
```

**Members**

- `family`: identifies the type of device
- `id`: along with family is the unique device id
- `crc`: checksum of the other bytes
- `crc`: checksum of the other bytes
- `id`: along with family is the unique device id
- `family`: identifies the type of device

#### <a id="c-struct-w1_slave"></a>`struct w1_slave`

holds a single slave device on the bus

**Definition**

```c
struct w1_slave {
    struct module           *owner;
    unsigned char           name[W1_MAXNAMELEN];
    struct list_head        w1_slave_entry;
    struct w1_reg_num       reg_num;
    atomic_t refcnt;
    int ttl;
    unsigned long           flags;
    struct w1_master        *master;
    struct w1_family        *family;
    void *family_data;
    struct device           dev;
    struct device           *hwmon;
};
```

**Members**

- `owner`: Points to the one wire "wire" kernel module.
- `name`: Device id is ascii.
- `w1_slave_entry`: data for the linked list
- `reg_num`: the slave id in binary
- `refcnt`: reference count, delete when 0
- `ttl`: decrement per search this slave isn't found, deatch at 0
- `flags`: bit flags for W1_SLAVE_ACTIVE W1_SLAVE_DETACH
- `master`: bus which this slave is on
- `family`: module for device family type
- `family_data`: pointer for use by the family module
- `dev`: kernel device identifier
- `hwmon`: pointer to hwmon device

#### <a id="c-struct-w1_bus_master"></a>`struct w1_bus_master`

operations available on a bus master

**Definition**

```c
struct w1_bus_master {
    void *data;
    u8 (*read_bit)(void *);
    void (*write_bit)(void *, u8);
    u8 (*touch_bit)(void *, u8);
    u8 (*read_byte)(void *);
    void (*write_byte)(void *, u8);
    u8 (*read_block)(void *, u8 *, int);
    void (*write_block)(void *, const u8 *, int);
    u8 (*triplet)(void *, u8);
    u8 (*reset_bus)(void *);
    u8 (*set_pullup)(void *, int);
    void (*search)(void *, struct w1_master *, u8, w1_slave_found_callback);
    char *dev_id;
};
```

**Members**

- `data`: the first parameter in all the functions below
- `read_bit`: Sample the line level
  **return** the level read (0 or 1)
- `write_bit`: Sets the line level
- `touch_bit`: the lowest-level function for devices that really support the
  1-wire protocol.
  touch_bit(0) = write-0 cycle
  touch_bit(1) = write-1 / read cycle
  **return** the bit read (0 or 1)
- `read_byte`: Reads a byte. Same as 8 touch_bit(1) calls.
  **return** the byte read
- `write_byte`: Writes a byte. Same as 8 touch_bit(x) calls.
- `read_block`: Same as a series of `read_byte()` calls
  **return** the number of bytes read
- `write_block`: Same as a series of `write_byte()` calls
- `triplet`: Combines two reads and a smart write for ROM searches
  **return** bit0=Id bit1=comp_id bit2=dir_taken
- `reset_bus`: long write-0 with a read for the presence pulse detection
  **return** -1=Error, 0=Device present, 1=No device present
- `set_pullup`: Put out a strong pull-up pulse of the specified duration.
  **return** -1=Error, 0=completed
- `search`: Really nice hardware can handle the different types of ROM search
  w1_master* is passed to the slave found callback.
  u8 is search_type, W1_SEARCH or W1_ALARM_SEARCH
- `dev_id`: Optional device id string, which w1 slaves could use for
  creating names, which then give a connection to the w1 master

**Note**

read_bit and write_bit are very low level functions and should only
be used with hardware that doesn't really support 1-wire operations,
like a parallel/serial port.
Either define read_bit and write_bit OR define, at minimum, touch_bit and
reset_bus.

#### <a id="c-enum-w1_master_flags"></a>`enum w1_master_flags`

bitfields used in w1_master.flags

**Constants**

- `W1_ABORT_SEARCH`: abort searching early on shutdown
- `W1_WARN_MAX_COUNT`: limit warning when the maximum count is reached

#### <a id="c-struct-w1_master"></a>`struct w1_master`

one per bus master

**Definition**

```c
struct w1_master {
    struct list_head        w1_master_entry;
    struct module           *owner;
    unsigned char           name[W1_MAXNAMELEN];
    struct mutex            list_mutex;
    struct list_head        slist;
    struct list_head        async_list;
    int max_slave_count, slave_count;
    unsigned long           attempts;
    int slave_ttl;
    int initialized;
    u32 id;
    int search_count;
    u64 search_id;
    atomic_t refcnt;
    void *priv;
    int enable_pullup;
    int pullup_duration;
    long flags;
    struct task_struct      *thread;
    struct mutex            mutex;
    struct mutex            bus_mutex;
    struct device_driver    *driver;
    struct device           dev;
    struct w1_bus_master    *bus_master;
    u32 seq;
};
```

**Members**

- `w1_master_entry`: master linked list
- `owner`: module owner
- `name`: dynamically allocate bus name
- `list_mutex`: protect slist and async_list
- `slist`: linked list of slaves
- `async_list`: linked list of netlink commands to execute
- `max_slave_count`: maximum number of slaves to search for at a time
- `slave_count`: current number of slaves known
- `attempts`: number of searches ran
- `slave_ttl`: number of searches before a slave is timed out
- `initialized`: prevent init/removal race conditions
- `id`: w1 bus number
- `search_count`: number of automatic searches to run, -1 unlimited
- `search_id`: allows continuing a search
- `refcnt`: reference count
- `priv`: private data storage
- `enable_pullup`: allows a strong pullup
- `pullup_duration`: time for the next strong pullup
- `flags`: one of w1_master_flags
- `thread`: thread for bus search and netlink commands
- `mutex`: protect most of w1_master
- `bus_mutex`: pretect concurrent bus access
- `driver`: sysfs driver
- `dev`: sysfs device
- `bus_master`: io operations available
- `seq`: sequence number used for netlink broadcasts

#### <a id="c-struct-w1_family_ops"></a>`struct w1_family_ops`

operations for a family type

**Definition**

```c
struct w1_family_ops {
    int (*add_slave)(struct w1_slave *sl);
    void (*remove_slave)(struct w1_slave *sl);
    const struct attribute_group **groups;
    const struct hwmon_chip_info *chip_info;
};
```

**Members**

- `add_slave`: add_slave
- `remove_slave`: remove_slave
- `groups`: sysfs group
- `chip_info`: pointer to struct hwmon_chip_info

#### <a id="c-struct-w1_family"></a>`struct w1_family`

reference counted family structure.

**Definition**

```c
struct w1_family {
    struct list_head        family_entry;
    u8 fid;
    const struct w1_family_ops *fops;
    const struct of_device_id *of_match_table;
    atomic_t refcnt;
};
```

**Members**

- `family_entry`: family linked list
- `fid`: 8 bit family identifier
- `fops`: operations for this family
- `of_match_table`: open firmware match table
- `refcnt`: reference counter

#### <a id="c-module_w1_family"></a>`module_w1_family()`

```c
module_w1_family(__w1_family)
```

Helper macro for registering a 1-Wire families

**Parameters**

- `__w1_family`: w1_family struct

**Description**

Helper macro for 1-Wire families which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)


<a id="rst-drivers-w1-w1-c"></a>

### drivers/w1/w1.c

W1 core functions.


#### <a id="c-w1_search"></a>`w1_search()`

```c
void w1_search(struct w1_master *dev, u8 search_type, w1_slave_found_callback cb)
```

Performs a ROM Search & registers any devices found.

**Parameters**

- `struct w1_master *dev`: The master device to search
- `u8 search_type`: W1_SEARCH to search all devices, or W1_ALARM_SEARCH
  to return only devices in the alarmed state
- `w1_slave_found_callback cb`: Function to call when a device is found

**Description**

The 1-wire search is a simple binary tree search.
For each bit of the address, we read two bits and write one bit.
The bit written will put to sleep all devies that don't match that bit.
When the two reads differ, the direction choice is obvious.
When both bits are 0, we must choose a path to take.
When we can scan all 64 bits without having to choose a path, we are done.

See "Application note 187 1-wire search algorithm" at www.maxim-ic.com

#### <a id="c-w1_process_callbacks"></a>`w1_process_callbacks()`

```c
int w1_process_callbacks(struct w1_master *dev)
```

execute each dev->async_list callback entry

**Parameters**

- `struct w1_master *dev`: w1_master device

**Description**

The w1 master list_mutex must be held.

**Return**

1 if there were commands to executed 0 otherwise


<a id="rst-drivers-w1-w1-family-c"></a>

### drivers/w1/w1_family.c

Allows registering device family operations.


#### <a id="c-w1_register_family"></a>`w1_register_family()`

```c
int w1_register_family(struct w1_family *newf)
```

register a device family driver

**Parameters**

- `struct w1_family *newf`: family to register

#### <a id="c-w1_unregister_family"></a>`w1_unregister_family()`

```c
void w1_unregister_family(struct w1_family *fent)
```

unregister a device family driver

**Parameters**

- `struct w1_family *fent`: family to unregister


<a id="rst-drivers-w1-w1-internal-h"></a>

### drivers/w1/w1_internal.h

W1 internal initialization for master devices.


#### <a id="c-struct-w1_async_cmd"></a>`struct w1_async_cmd`

execute callback from the w1_process kthread

**Definition**

```c
struct w1_async_cmd {
    struct list_head        async_entry;
    void (*cb)(struct w1_master *dev, struct w1_async_cmd *async_cmd);
};
```

**Members**

- `async_entry`: link entry
- `cb`: callback function, must list_del and destroy this list before
  returning

**Description**

When inserted into the w1_master async_list, w1_process will execute
the callback.  Embed this into the structure with the command details.


<a id="rst-drivers-w1-w1-int-c"></a>

### drivers/w1/w1_int.c

W1 internal initialization for master devices.


#### <a id="c-w1_add_master_device"></a>`w1_add_master_device()`

```c
int w1_add_master_device(struct w1_bus_master *master)
```

registers a new master device

**Parameters**

- `struct w1_bus_master *master`: master bus device to register

#### <a id="c-w1_remove_master_device"></a>`w1_remove_master_device()`

```c
void w1_remove_master_device(struct w1_bus_master *bm)
```

unregister a master device

**Parameters**

- `struct w1_bus_master *bm`: master bus device to remove


<a id="rst-drivers-w1-w1-netlink-h"></a>

### drivers/w1/w1_netlink.h

W1 external netlink API structures and commands.


#### <a id="c-enum-w1_cn_msg_flags"></a>`enum w1_cn_msg_flags`

bitfield flags for struct cn_msg.flags

**Constants**

- `W1_CN_BUNDLE`: Request bundling replies into fewer messagse.  Be prepared
  to handle multiple struct cn_msg, struct w1_netlink_msg, and
  struct w1_netlink_cmd in one packet.

#### <a id="c-enum-w1_netlink_message_types"></a>`enum w1_netlink_message_types`

message type

**Constants**

- `W1_SLAVE_ADD`: notification that a slave device was added
- `W1_SLAVE_REMOVE`: notification that a slave device was removed
- `W1_MASTER_ADD`: notification that a new bus master was added
- `W1_MASTER_REMOVE`: notification that a bus masterwas removed
- `W1_MASTER_CMD`: initiate operations on a specific master
- `W1_SLAVE_CMD`: sends reset, selects the slave, then does a read/write/touch
  operation
- `W1_LIST_MASTERS`: used to determine the bus master identifiers

#### <a id="c-struct-w1_netlink_msg"></a>`struct w1_netlink_msg`

holds w1 message type, id, and result

**Definition**

```c
struct w1_netlink_msg {
    __u8 type;
    __u8 status;
    __u16 len;
    union {
        __u8 id[8];
        struct w1_mst {
            __u32 id;
            __u32 res;
        } mst;
    } id;
    __u8 data[];
};
```

**Members**

- `type`: one of enum w1_netlink_message_types
- `status`: kernel feedback for success 0 or errno failure value
- `len`: length of data following w1_netlink_msg
- `id`: union holding bus master id (msg.id) and slave device id (id\[8\]).
- `id.id`: Slave ID (8 bytes)
- `id.mst`: bus master identification
- `id.mst.id`: bus master ID
- `id.mst.res`: bus master reserved
- `data`: start address of any following data

**Description**

The base message structure for w1 messages over netlink.
The netlink connector data sequence is, struct nlmsghdr, struct cn_msg,
then one or more struct w1_netlink_msg (each with optional data).

#### <a id="c-enum-w1_commands"></a>`enum w1_commands`

commands available for master or slave operations

**Constants**

- `W1_CMD_READ`: read len bytes
- `W1_CMD_WRITE`: write len bytes
- `W1_CMD_SEARCH`: initiate a standard search, returns only the slave
  devices found during that search
- `W1_CMD_ALARM_SEARCH`: search for devices that are currently alarming
- `W1_CMD_TOUCH`: Touches a series of bytes.
- `W1_CMD_RESET`: sends a bus reset on the given master
- `W1_CMD_SLAVE_ADD`: adds a slave to the given master,
  8 byte slave id at data\[0\]
- `W1_CMD_SLAVE_REMOVE`: removes a slave to the given master,
  8 byte slave id at data\[0\]
- `W1_CMD_LIST_SLAVES`: list of slaves registered on this master
- `W1_CMD_MAX`: number of available commands

#### <a id="c-struct-w1_netlink_cmd"></a>`struct w1_netlink_cmd`

holds the command and data

**Definition**

```c
struct w1_netlink_cmd {
    __u8 cmd;
    __u8 res;
    __u16 len;
    __u8 data[];
};
```

**Members**

- `cmd`: one of enum w1_commands
- `res`: reserved
- `len`: length of data following w1_netlink_cmd
- `data`: start address of any following data

**Description**

One or more struct w1_netlink_cmd is placed starting at w1_netlink_msg.data
each with optional data.


<a id="rst-drivers-w1-w1-io-c"></a>

### drivers/w1/w1_io.c

W1 input/output.


#### <a id="c-w1_touch_bit"></a>`w1_touch_bit()`

```c
u8 w1_touch_bit(struct w1_master *dev, int bit)
```

Generates a write-0 or write-1 cycle and samples the level.

**Parameters**

- `struct w1_master *dev`: the master device
- `int bit`: 0 - write a 0, 1 - write a 0 read the level

#### <a id="c-w1_write_8"></a>`w1_write_8()`

```c
void w1_write_8(struct w1_master *dev, u8 byte)
```

Writes 8 bits.

**Parameters**

- `struct w1_master *dev`: the master device
- `u8 byte`: the byte to write

#### <a id="c-w1_triplet"></a>`w1_triplet()`

```c
u8 w1_triplet(struct w1_master *dev, int bdir)
```

* Does a triplet - used for searching ROM addresses.

**Parameters**

- `struct w1_master *dev`: the master device
- `int bdir`: the bit to write if both id_bit and comp_bit are 0

**Description**

- Return bits:
  bit 0 = id_bit
  bit 1 = comp_bit
  bit 2 = dir_taken

If both bits 0 & 1 are set, the search should be restarted.

**Return**

bit fields - see above

#### <a id="c-w1_read_8"></a>`w1_read_8()`

```c
u8 w1_read_8(struct w1_master *dev)
```

Reads 8 bits.

**Parameters**

- `struct w1_master *dev`: the master device

**Return**

the byte read

#### <a id="c-w1_write_block"></a>`w1_write_block()`

```c
void w1_write_block(struct w1_master *dev, const u8 *buf, int len)
```

Writes a series of bytes.

**Parameters**

- `struct w1_master *dev`: the master device
- `const u8 *buf`: pointer to the data to write
- `int len`: the number of bytes to write

#### <a id="c-w1_touch_block"></a>`w1_touch_block()`

```c
void w1_touch_block(struct w1_master *dev, u8 *buf, int len)
```

Touches a series of bytes.

**Parameters**

- `struct w1_master *dev`: the master device
- `u8 *buf`: pointer to the data to write
- `int len`: the number of bytes to write

#### <a id="c-w1_read_block"></a>`w1_read_block()`

```c
u8 w1_read_block(struct w1_master *dev, u8 *buf, int len)
```

Reads a series of bytes.

**Parameters**

- `struct w1_master *dev`: the master device
- `u8 *buf`: pointer to the buffer to fill
- `int len`: the number of bytes to read

**Return**

the number of bytes read

#### <a id="c-w1_reset_bus"></a>`w1_reset_bus()`

```c
int w1_reset_bus(struct w1_master *dev)
```

Issues a reset bus sequence.

**Parameters**

- `struct w1_master *dev`: the master device

**Return**

0=Device present, 1=No device present or error

#### <a id="c-w1_reset_select_slave"></a>`w1_reset_select_slave()`

```c
int w1_reset_select_slave(struct w1_slave *sl)
```

reset and select a slave

**Parameters**

- `struct w1_slave *sl`: the slave to select

**Description**

Resets the bus and then selects the slave by sending either a skip rom
or a rom match.  A skip rom is issued if there is only one device
registered on the bus.
The w1 master lock must be held.

**Return**

0=success, anything else=error

#### <a id="c-w1_reset_resume_command"></a>`w1_reset_resume_command()`

```c
int w1_reset_resume_command(struct w1_master *dev)
```

resume instead of another match ROM

**Parameters**

- `struct w1_master *dev`: the master device

**Description**

When the workflow with a slave amongst many requires several
successive commands a reset between each, this function is similar
to doing a reset then a match ROM for the last matched ROM. The
advantage being that the matched ROM step is skipped in favor of the
resume command. The slave must support the command of course.

If the bus has only one slave, traditionnaly the match ROM is skipped
and a "SKIP ROM" is done for efficiency. On multi-slave busses, this
doesn't work of course, but the resume command is the next best thing.

The w1 master lock must be held.

#### <a id="c-w1_next_pullup"></a>`w1_next_pullup()`

```c
void w1_next_pullup(struct w1_master *dev, int delay)
```

register for a strong pullup

**Parameters**

- `struct w1_master *dev`: the master device
- `int delay`: time in milliseconds

**Description**

Put out a strong pull-up of the specified duration after the next write
operation.  Not all hardware supports strong pullups.  Hardware that
doesn't support strong pullups will sleep for the given time after the
write operation without a strong pullup.  This is a one shot request for
the next write, specifying zero will clear a previous request.
The w1 master lock must be held.

**Return**

0=success, anything else=error



#### <a id="c-w1_write_bit"></a>`w1_write_bit()`

```c
void w1_write_bit(struct w1_master *dev, int bit)
```

Generates a write-0 or write-1 cycle.

**Parameters**

- `struct w1_master *dev`: the master device
- `int bit`: bit to write

**Description**

Only call if dev->bus_master->touch_bit is NULL

#### <a id="c-w1_pre_write"></a>`w1_pre_write()`

```c
void w1_pre_write(struct w1_master *dev)
```

pre-write operations

**Parameters**

- `struct w1_master *dev`: the master device

**Description**

Pre-write operation, currently only supporting strong pullups.
Program the hardware for a strong pullup, if one has been requested and
the hardware supports it.

#### <a id="c-w1_post_write"></a>`w1_post_write()`

```c
void w1_post_write(struct w1_master *dev)
```

post-write options

**Parameters**

- `struct w1_master *dev`: the master device

**Description**

Post-write operation, currently only supporting strong pullups.
If a strong pullup was requested, clear it if the hardware supports
them, or execute the delay otherwise, in either case clear the request.

#### <a id="c-w1_read_bit"></a>`w1_read_bit()`

```c
u8 w1_read_bit(struct w1_master *dev)
```

Generates a write-1 cycle and samples the level.

**Parameters**

- `struct w1_master *dev`: the master device

**Description**

Only call if dev->bus_master->touch_bit is NULL

---

# Xillybus driver for generic FPGA interface

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> An FPGA (Field Programmable Gate Array) is a piece of logic hardware, which can be programmed to become virtually anything that is usually found as a dedicated chipset: For instance, a display adapter, network interface card, or even a…

<a id="rst-xillybus-driver-for-generic-fpga-interface"></a>

**Author:** Eli Billauer, Xillybus Ltd. ([http://xillybus.com](<http://xillybus.com>))

**Email:** [eli.billauer@gmail.com](<mailto:eli.billauer@gmail.com>) or as advertised on Xillybus' site.

<!-- Contents:

- Introduction
 -- Background
 -- Xillybus Overview

- Usage
 -- User interface
 -- Synchronization
 -- Seekable pipes

- Internals
 -- Source code organization
 -- Pipe attributes
 -- Host never reads from the FPGA
 -- Channels, pipes, and the message channel
 -- Data streaming
 -- Data granularity
 -- Probing
 -- Buffer allocation
 -- The "nonempty" message (supporting poll) -->

<a id="rst-introduction"></a>

## Introduction

<a id="rst-background"></a>

### Background

An FPGA (Field Programmable Gate Array) is a piece of logic hardware, which can be programmed to become virtually anything that is usually found as a dedicated chipset: For instance, a display adapter, network interface card, or even a processor with its peripherals. FPGAs are the LEGO of hardware: Based upon certain building blocks, you make your own toys the way you like them. It's usually pointless to reimplement something that is already available on the market as a chipset, so FPGAs are mostly used when some special functionality is needed, and the production volume is relatively low (hence not justifying the development of an ASIC).

The challenge with FPGAs is that everything is implemented at a very low level, even lower than assembly language. In order to allow FPGA designers to focus on their specific project, and not reinvent the wheel over and over again, pre-designed building blocks, IP cores, are often used. These are the FPGA parallels of library functions. IP cores may implement certain mathematical functions, a functional unit (e.g. a USB interface), an entire processor (e.g. ARM) or anything that might come handy. Think of them as a building block, with electrical wires dangling on the sides for connection to other blocks.

One of the daunting tasks in FPGA design is communicating with a fullblown operating system (actually, with the processor running it): Implementing the low-level bus protocol and the somewhat higher-level interface with the host (registers, interrupts, DMA etc.) is a project in itself. When the FPGA's function is a well-known one (e.g. a video adapter card, or a NIC), it can make sense to design the FPGA's interface logic specifically for the project. A special driver is then written to present the FPGA as a well-known interface to the kernel and/or user space. In that case, there is no reason to treat the FPGA differently than any device on the bus.

It's however common that the desired data communication doesn't fit any well- known peripheral function. Also, the effort of designing an elegant abstraction for the data exchange is often considered too big. In those cases, a quicker and possibly less elegant solution is sought: The driver is effectively written as a user space program, leaving the kernel space part with just elementary data transport. This still requires designing some interface logic for the FPGA, and write a simple ad-hoc driver for the kernel.

<a id="rst-xillybus-overview"></a>

### Xillybus Overview

Xillybus is an IP core and a Linux driver. Together, they form a kit for elementary data transport between an FPGA and the host, providing pipe-like data streams with a straightforward user interface. It's intended as a low- effort solution for mixed FPGA-host projects, for which it makes sense to have the project-specific part of the driver running in a user-space program.

Since the communication requirements may vary significantly from one FPGA project to another (the number of data pipes needed in each direction and their attributes), there isn't one specific chunk of logic being the Xillybus IP core. Rather, the IP core is configured and built based upon a specification given by its end user.

Xillybus presents independent data streams, which resemble pipes or TCP/IP communication to the user. At the host side, a character device file is used just like any pipe file. On the FPGA side, hardware FIFOs are used to stream the data. This is contrary to a common method of communicating through fixed- sized buffers (even though such buffers are used by Xillybus under the hood). There may be more than a hundred of these streams on a single IP core, but also no more than one, depending on the configuration.

In order to ease the deployment of the Xillybus IP core, it contains a simple data structure which completely defines the core's configuration. The Linux driver fetches this data structure during its initialization process, and sets up the DMA buffers and character devices accordingly. As a result, a single driver is used to work out of the box with any Xillybus IP core.

The data structure just mentioned should not be confused with PCI's configuration space or the Flattened Device Tree.

<a id="rst-usage"></a>

## Usage

<a id="rst-user-interface"></a>

### User interface

On the host, all interface with Xillybus is done through /dev/xillybus\_\* device files, which are generated automatically as the drivers loads. The names of these files depend on the IP core that is loaded in the FPGA (see Probing below). To communicate with the FPGA, open the device file that corresponds to the hardware FIFO you want to send data or receive data from, and use plain write() or read() calls, just like with a regular pipe. In particular, it makes perfect sense to go:



```text
$ cat mydata > /dev/xillybus_thisfifo

$ cat /dev/xillybus_thatfifo > hisdata
```

possibly pressing CTRL-C as some stage, even though the xillybus\_\* pipes have the capability to send an EOF (but may not use it).

The driver and hardware are designed to behave sensibly as pipes, including:

- Supporting non-blocking I/O (by setting O_NONBLOCK on open() ).

- Supporting poll() and select().

- Being bandwidth efficient under load (using DMA) but also handle small pieces of data sent across (like TCP/IP) by autoflushing.

A device file can be read only, write only or bidirectional. Bidirectional device files are treated like two independent pipes (except for sharing a "channel" structure in the implementation code).

<a id="rst-synchronization"></a>

### Synchronization

Xillybus pipes are configured (on the IP core) to be either synchronous or asynchronous. For a synchronous pipe, write() returns successfully only after some data has been submitted and acknowledged by the FPGA. This slows down bulk data transfers, and is nearly impossible for use with streams that require data at a constant rate: There is no data transmitted to the FPGA between write() calls, in particular when the process loses the CPU.

When a pipe is configured asynchronous, write() returns if there was enough room in the buffers to store any of the data in the buffers.

For FPGA to host pipes, asynchronous pipes allow data transfer from the FPGA as soon as the respective device file is opened, regardless of if the data has been requested by a read() call. On synchronous pipes, only the amount of data requested by a read() call is transmitted.

In summary, for synchronous pipes, data between the host and FPGA is transmitted only to satisfy the read() or write() call currently handled by the driver, and those calls wait for the transmission to complete before returning.

Note that the synchronization attribute has nothing to do with the possibility that read() or write() completes less bytes than requested. There is a separate configuration flag ("allowpartial") that determines whether such a partial completion is allowed.

<a id="rst-seekable-pipes"></a>

### Seekable pipes

A synchronous pipe can be configured to have the stream's position exposed to the user logic at the FPGA. Such a pipe is also seekable on the host API. With this feature, a memory or register interface can be attached on the FPGA side to the seekable stream. Reading or writing to a certain address in the attached memory is done by seeking to the desired address, and calling read() or write() as required.

<a id="rst-internals"></a>

## Internals

<a id="rst-source-code-organization"></a>

### Source code organization

The Xillybus driver consists of a core module, xillybus_core.c, and modules that depend on the specific bus interface (xillybus_of.c and xillybus_pcie.c).

The bus specific modules are those probed when a suitable device is found by the kernel. Since the DMA mapping and synchronization functions, which are bus dependent by their nature, are used by the core module, a xilly_endpoint_hardware structure is passed to the core module on initialization. This structure is populated with pointers to wrapper functions which execute the DMA-related operations on the bus.

<a id="rst-pipe-attributes"></a>

### Pipe attributes

Each pipe has a number of attributes which are set when the FPGA component (IP core) is built. They are fetched from the IDT (the data structure which defines the core's configuration, see Probing below) by xilly_setupchannels() in xillybus_core.c as follows:

- is_writebuf: The pipe's direction. A non-zero value means it's an FPGA to host pipe (the FPGA "writes").

- channelnum: The pipe's identification number in communication between the host and FPGA.

- format: The underlying data width. See Data Granularity below.

- allowpartial: A non-zero value means that a read() or write() (whichever applies) may return with less than the requested number of bytes. The common choice is a non-zero value, to match standard UNIX behavior.

- synchronous: A non-zero value means that the pipe is synchronous. See Synchronization above.

- bufsize: Each DMA buffer's size. Always a power of two.

- bufnum: The number of buffers allocated for this pipe. Always a power of two.

- exclusive_open: A non-zero value forces exclusive opening of the associated device file. If the device file is bidirectional, and already opened only in one direction, the opposite direction may be opened once.

- seekable: A non-zero value indicates that the pipe is seekable. See Seekable pipes above.

- supports_nonempty: A non-zero value (which is typical) indicates that the hardware will send the messages that are necessary to support select() and poll() for this pipe.

<a id="rst-host-never-reads-from-the-fpga"></a>

### Host never reads from the FPGA

Even though PCI Express is hotpluggable in general, a typical motherboard doesn't expect a card to go away all of the sudden. But since the PCIe card is based upon reprogrammable logic, a sudden disappearance from the bus is quite likely as a result of an accidental reprogramming of the FPGA while the host is up. In practice, nothing happens immediately in such a situation. But if the host attempts to read from an address that is mapped to the PCI Express device, that leads to an immediate freeze of the system on some motherboards, even though the PCIe standard requires a graceful recovery.

In order to avoid these freezes, the Xillybus driver refrains completely from reading from the device's register space. All communication from the FPGA to the host is done through DMA. In particular, the Interrupt Service Routine doesn't follow the common practice of checking a status register when it's invoked. Rather, the FPGA prepares a small buffer which contains short messages, which inform the host what the interrupt was about.

This mechanism is used on non-PCIe buses as well for the sake of uniformity.

<a id="rst-channels-pipes-and-the-message-channel"></a>

### Channels, pipes, and the message channel

Each of the (possibly bidirectional) pipes presented to the user is allocated a data channel between the FPGA and the host. The distinction between channels and pipes is necessary only because of channel 0, which is used for interrupt- related messages from the FPGA, and has no pipe attached to it.

<a id="rst-data-streaming"></a>

### Data streaming

Even though a non-segmented data stream is presented to the user at both sides, the implementation relies on a set of DMA buffers which is allocated for each channel. For the sake of illustration, let's take the FPGA to host direction: As data streams into the respective channel's interface in the FPGA, the Xillybus IP core writes it to one of the DMA buffers. When the buffer is full, the FPGA informs the host about that (appending a XILLYMSG_OPCODE_RELEASEBUF message channel 0 and sending an interrupt if necessary). The host responds by making the data available for reading through the character device. When all data has been read, the host writes on the FPGA's buffer control register, allowing the buffer's overwriting. Flow control mechanisms exist on both sides to prevent underflows and overflows.

This is not good enough for creating a TCP/IP-like stream: If the data flow stops momentarily before a DMA buffer is filled, the intuitive expectation is that the partial data in buffer will arrive anyhow, despite the buffer not being completed. This is implemented by adding a field in the XILLYMSG_OPCODE_RELEASEBUF message, through which the FPGA informs not just which buffer is submitted, but how much data it contains.

But the FPGA will submit a partially filled buffer only if directed to do so by the host. This situation occurs when the read() method has been blocking for XILLY_RX_TIMEOUT jiffies (currently 10 ms), after which the host commands the FPGA to submit a DMA buffer as soon as it can. This timeout mechanism balances between bus bandwidth efficiency (preventing a lot of partially filled buffers being sent) and a latency held fairly low for tails of data.

A similar setting is used in the host to FPGA direction. The handling of partial DMA buffers is somewhat different, though. The user can tell the driver to submit all data it has in the buffers to the FPGA, by issuing a write() with the byte count set to zero. This is similar to a flush request, but it doesn't block. There is also an autoflushing mechanism, which triggers an equivalent flush roughly XILLY_RX_TIMEOUT jiffies after the last write(). This allows the user to be oblivious about the underlying buffering mechanism and yet enjoy a stream-like interface.

Note that the issue of partial buffer flushing is irrelevant for pipes having the "synchronous" attribute nonzero, since synchronous pipes don't allow data to lay around in the DMA buffers between read() and write() anyhow.

<a id="rst-data-granularity"></a>

### Data granularity

The data arrives or is sent at the FPGA as 8, 16 or 32 bit wide words, as configured by the "format" attribute. Whenever possible, the driver attempts to hide this when the pipe is accessed differently from its natural alignment. For example, reading single bytes from a pipe with 32 bit granularity works with no issues. Writing single bytes to pipes with 16 or 32 bit granularity will also work, but the driver can't send partially completed words to the FPGA, so the transmission of up to one word may be held until it's fully occupied with user data.

This somewhat complicates the handling of host to FPGA streams, because when a buffer is flushed, it may contain up to 3 bytes don't form a word in the FPGA, and hence can't be sent. To prevent loss of data, these leftover bytes need to be moved to the next buffer. The parts in xillybus_core.c that mention "leftovers" in some way are related to this complication.

<a id="rst-probing"></a>

### Probing

As mentioned earlier, the number of pipes that are created when the driver loads and their attributes depend on the Xillybus IP core in the FPGA. During the driver's initialization, a blob containing configuration info, the Interface Description Table (IDT), is sent from the FPGA to the host. The bootstrap process is done in three phases:

1. Acquire the length of the IDT, so a buffer can be allocated for it. This is done by sending a quiesce command to the device, since the acknowledge for this command contains the IDT's buffer length.

2. Acquire the IDT itself.

3. Create the interfaces according to the IDT.

<a id="rst-buffer-allocation"></a>

### Buffer allocation

In order to simplify the logic that prevents illegal boundary crossings of PCIe packets, the following rule applies: If a buffer is smaller than 4kB, it must not cross a 4kB boundary. Otherwise, it must be 4kB aligned. The xilly_setupchannels() functions allocates these buffers by requesting whole pages from the kernel, and diving them into DMA buffers as necessary. Since all buffers' sizes are powers of two, it's possible to pack any set of such buffers, with a maximal waste of one page of memory.

All buffers are allocated when the driver is loaded. This is necessary, since large continuous physical memory segments are sometimes requested, which are more likely to be available when the system is freshly booted.

The allocation of buffer memory takes place in the same order they appear in the IDT. The driver relies on a rule that the pipes are sorted with decreasing buffer size in the IDT. If a requested buffer is larger or equal to a page, the necessary number of pages is requested from the kernel, and these are used for this buffer. If the requested buffer is smaller than a page, one single page is requested from the kernel, and that page is partially used. Or, if there already is a partially used page at hand, the buffer is packed into that page. It can be shown that all pages requested from the kernel (except possibly for the last) are 100% utilized this way.

<a id="rst-the-nonempty-message-supporting-poll"></a>

### The "nonempty" message (supporting poll)

In order to support the "poll" method (and hence select() ), there is a small catch regarding the FPGA to host direction: The FPGA may have filled a DMA buffer with some data, but not submitted that buffer. If the host waited for the buffer's submission by the FPGA, there would be a possibility that the FPGA side has sent data, but a select() call would still block, because the host has not received any notification about this. This is solved with XILLYMSG_OPCODE_NONEMPTY messages sent by the FPGA when a channel goes from completely empty to containing some data.

These messages are used only to support poll() and select(). The IP core can be configured not to send them for a slight reduction of bandwidth.

---

# Writing Device Drivers for Zorro Devices

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> The Zorro bus is the bus used in the Amiga family of computers. Thanks to AutoConfig(tm), it's 100% Plug-and-Play.

<a id="rst-writing-device-drivers-for-zorro-devices"></a>

**Author:** Written by Geert Uytterhoeven &lt;[geert@linux-m68k.org](<mailto:geert@linux-m68k.org>)&gt;

**Last revised:** September 5, 2003

<a id="rst-introduction"></a>

## Introduction

The Zorro bus is the bus used in the Amiga family of computers. Thanks to AutoConfig(tm), it's 100% Plug-and-Play.

There are two types of Zorro buses, Zorro II and Zorro III:

> - The Zorro II address space is 24-bit and lies within the first 16 MB of the Amiga's address map.
>
> - Zorro III is a 32-bit extension of Zorro II, which is backwards compatible with Zorro II. The Zorro III address space lies outside the first 16 MB.

<a id="rst-probing-for-zorro-devices"></a>

## Probing for Zorro Devices

Zorro devices are found by calling `zorro_find_device()`, which returns a pointer to the `next` Zorro device with the specified Zorro ID. A probe loop for the board with Zorro ID `ZORRO_PROD_xxx` looks like:



```text
struct zorro_dev *z = NULL;

while ((z = zorro_find_device(ZORRO_PROD_xxx, z))) {
    if (!zorro_request_region(z->resource.start+MY_START, MY_SIZE,
                              "My explanation"))
    ...
}
```

`ZORRO_WILDCARD` acts as a wildcard and finds any Zorro device. If your driver supports different types of boards, you can use a construct like:



```text
struct zorro_dev *z = NULL;

while ((z = zorro_find_device(ZORRO_WILDCARD, z))) {
    if (z->id != ZORRO_PROD_xxx1 && z->id != ZORRO_PROD_xxx2 && ...)
        continue;
    if (!zorro_request_region(z->resource.start+MY_START, MY_SIZE,
                              "My explanation"))
    ...
}
```

<a id="rst-zorro-resources"></a>

## Zorro Resources

Before you can access a Zorro device's registers, you have to make sure it's not yet in use. This is done using the I/O memory space resource management functions:



```text
request_mem_region()
release_mem_region()
```

Shortcuts to claim the whole device's address space are provided as well:



```text
zorro_request_device
zorro_release_device
```

<a id="rst-accessing-the-zorro-address-space"></a>

## Accessing the Zorro Address Space

The address regions in the Zorro device resources are Zorro bus address regions. Due to the identity bus-physical address mapping on the Zorro bus, they are CPU physical addresses as well.

The treatment of these regions depends on the type of Zorro space:

> - Zorro II address space is always mapped and does not have to be mapped explicitly using z_ioremap().
>
>   Conversion from bus/physical Zorro II addresses to kernel virtual addresses and vice versa is done using:
>
>
>
>   ```text
>   virt_addr = ZTWO_VADDR(bus_addr);
>   bus_addr = ZTWO_PADDR(virt_addr);
>   ```
>
> - Zorro III address space must be mapped explicitly using z_ioremap() first before it can be accessed:
>
>
>
>   ```text
>   virt_addr = z_ioremap(bus_addr, size);
>   ...
>   z_iounmap(virt_addr);
>   ```

<a id="rst-references"></a>

## References

1. linux/include/linux/zorro.h

2. linux/include/uapi/linux/zorro.h

3. linux/include/uapi/linux/zorro_ids.h

4. linux/arch/m68k/include/asm/zorro.h

5. linux/drivers/zorro

6. /proc/bus/zorro

---

# The Common Clk Framework

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This document endeavours to explain the common clk framework details, and how to port a platform over to this framework. It is not yet a detailed explanation of the clock api in include/linux/clk.h, but perhaps someday it will include that…

<a id="rst-the-common-clk-framework"></a>

**Author:** Mike Turquette &lt;[mturquette@ti.com](<mailto:mturquette@ti.com>)&gt;

This document endeavours to explain the common clk framework details, and how to port a platform over to this framework.  It is not yet a detailed explanation of the clock api in include/linux/clk.h, but perhaps someday it will include that information.

<a id="rst-introduction-and-interface-split"></a>

## Introduction and interface split

The common clk framework is an interface to control the clock nodes available on various devices today.  This may come in the form of clock gating, rate adjustment, muxing or other operations.  This framework is enabled with the CONFIG_COMMON_CLK option.

The interface itself is divided into two halves, each shielded from the details of its counterpart.  First is the common definition of struct clk which unifies the framework-level accounting and infrastructure that has traditionally been duplicated across a variety of platforms.  Second is a common implementation of the clk.h api, defined in drivers/clk/clk.c.  Finally there is struct clk_ops, whose operations are invoked by the clk api implementation.

The second half of the interface is comprised of the hardware-specific callbacks registered with struct clk_ops and the corresponding hardware-specific structures needed to model a particular clock.  For the remainder of this document any reference to a callback in struct clk_ops, such as .enable or .set_rate, implies the hardware-specific implementation of that code.  Likewise, references to struct clk_foo serve as a convenient shorthand for the implementation of the hardware-specific bits for the hypothetical "foo" hardware.

Tying the two halves of this interface together is struct clk_hw, which is defined in struct clk_foo and pointed to within struct clk_core.  This allows for easy navigation between the two discrete halves of the common clock interface.

<a id="rst-common-data-structures-and-api"></a>

## Common data structures and api

Below is the common struct clk_core definition from drivers/clk/clk.c, modified for brevity:



```text
struct clk_core {
        const char              *name;
        const struct clk_ops    *ops;
        struct clk_hw           *hw;
        struct module           *owner;
        struct clk_core         *parent;
        const char              **parent_names;
        struct clk_core         **parents;
        u8                      num_parents;
        u8                      new_parent_index;
        ...
};
```

The members above make up the core of the clk tree topology.  The clk api itself defines several driver-facing functions which operate on struct clk.  That api is documented in include/linux/clk.h.

Platforms and devices utilizing the common struct clk_core use the struct clk_ops pointer in struct clk_core to perform the hardware-specific parts of the operations defined in clk-provider.h:



```text
struct clk_ops {
        int             (*prepare)(struct clk_hw *hw);
        void            (*unprepare)(struct clk_hw *hw);
        int             (*is_prepared)(struct clk_hw *hw);
        void            (*unprepare_unused)(struct clk_hw *hw);
        int             (*enable)(struct clk_hw *hw);
        void            (*disable)(struct clk_hw *hw);
        int             (*is_enabled)(struct clk_hw *hw);
        void            (*disable_unused)(struct clk_hw *hw);
        unsigned long   (*recalc_rate)(struct clk_hw *hw,
                                        unsigned long parent_rate);
        long            (*round_rate)(struct clk_hw *hw,
                                        unsigned long rate,
                                        unsigned long *parent_rate);
        int             (*determine_rate)(struct clk_hw *hw,
                                          struct clk_rate_request *req);
        int             (*set_parent)(struct clk_hw *hw, u8 index);
        u8              (*get_parent)(struct clk_hw *hw);
        int             (*set_rate)(struct clk_hw *hw,
                                    unsigned long rate,
                                    unsigned long parent_rate);
        int             (*set_rate_and_parent)(struct clk_hw *hw,
                                    unsigned long rate,
                                    unsigned long parent_rate,
                                    u8 index);
        unsigned long   (*recalc_accuracy)(struct clk_hw *hw,
                                        unsigned long parent_accuracy);
        int             (*get_phase)(struct clk_hw *hw);
        int             (*set_phase)(struct clk_hw *hw, int degrees);
        void            (*init)(struct clk_hw *hw);
        void            (*debug_init)(struct clk_hw *hw,
                                      struct dentry *dentry);
};
```

<a id="rst-hardware-clk-implementations"></a>

## Hardware clk implementations

The strength of the common struct clk_core comes from its .ops and .hw pointers which abstract the details of struct clk from the hardware-specific bits, and vice versa.  To illustrate consider the simple gateable clk implementation in drivers/clk/clk-gate.c:



```text
struct clk_gate {
        struct clk_hw   hw;
        void __iomem    *reg;
        u8              bit_idx;
        ...
};
```

struct clk_gate contains struct clk_hw hw as well as hardware-specific knowledge about which register and bit controls this clk's gating. Nothing about clock topology or accounting, such as enable_count or notifier_count, is needed here.  That is all handled by the common framework code and struct clk_core.

Let's walk through enabling this clk from driver code:



```text
struct clk *clk;
clk = clk_get(NULL, "my_gateable_clk");

clk_prepare(clk);
clk_enable(clk);
```

The call graph for clk_enable is very simple:



```text
clk_enable(clk);
        clk->ops->enable(clk->hw);
        [resolves to...]
                clk_gate_enable(hw);
                [resolves struct clk gate with to_clk_gate(hw)]
                        clk_gate_set_bit(gate);
```

And the definition of clk_gate_set_bit:



```text
static void clk_gate_set_bit(struct clk_gate *gate)
{
        u32 reg;

        reg = __raw_readl(gate->reg);
        reg |= BIT(gate->bit_idx);
        writel(reg, gate->reg);
}
```

Note that to_clk_gate is defined as:



```text
#define to_clk_gate(_hw) container_of(_hw, struct clk_gate, hw)
```

This pattern of abstraction is used for every clock hardware representation.

<a id="rst-supporting-your-own-clk-hardware"></a>

## Supporting your own clk hardware

When implementing support for a new type of clock it is only necessary to include the following header:



```text
#include <linux/clk-provider.h>
```

To construct a clk hardware structure for your platform you must define the following:



```text
struct clk_foo {
        struct clk_hw hw;
        ... hardware specific data goes here ...
};
```

To take advantage of your data you'll need to support valid operations for your clk:



```text
struct clk_ops clk_foo_ops = {
        .enable         = &clk_foo_enable,
        .disable        = &clk_foo_disable,
};
```

Implement the above functions using container_of:



```text
#define to_clk_foo(_hw) container_of(_hw, struct clk_foo, hw)

int clk_foo_enable(struct clk_hw *hw)
{
        struct clk_foo *foo;

        foo = to_clk_foo(hw);

        ... perform magic on foo ...

        return 0;
};
```

Below is a matrix detailing which clk_ops are mandatory based upon the hardware capabilities of that clock.  A cell marked as "y" means mandatory, a cell marked as "n" implies that either including that callback is invalid or otherwise unnecessary.  Empty cells are either optional or must be evaluated on a case-by-case basis.


<table>
<caption>clock hardware characteristics</caption>
<thead>
<tr>
<th>




</th>
<th>


gate

</th>
<th>


change rate

</th>
<th>


single parent

</th>
<th>


multiplexer

</th>
<th>


root

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


.prepare

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.unprepare

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.enable

</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.disable

</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.is_enabled

</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.recalc_rate

</td>
<td>




</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.round_rate

</td>
<td>




</td>
<td>


y <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.determine_rate

</td>
<td>




</td>
<td>


y <a id="rst-footnote-reference-2"></a>[1](#rst-footnote-1)

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.set_rate

</td>
<td>




</td>
<td>


y

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.set_parent

</td>
<td>




</td>
<td>




</td>
<td>


n

</td>
<td>


y

</td>
<td>


n

</td>
</tr>
<tr>
<td>


.get_parent

</td>
<td>




</td>
<td>




</td>
<td>


n

</td>
<td>


y

</td>
<td>


n

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.recalc_accuracy

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


.init

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
</tbody>
</table>

<a id="rst-footnote-1"></a>



**[1]** either one of round_rate or determine_rate is required.

Finally, register your clock at run-time with a hardware-specific registration function.  This function simply populates struct clk_foo's data and then passes the common struct clk parameters to the framework with a call to:



```text
clk_register(...)
```

See the basic clock types in `drivers/clk/clk-*.c` for examples.

<a id="rst-disabling-clock-gating-of-unused-clocks"></a>

## Disabling clock gating of unused clocks

Sometimes during development it can be useful to be able to bypass the default disabling of unused clocks. For example, if drivers aren't enabling clocks properly but rely on them being on from the bootloader, bypassing the disabling means that the driver will remain functional while the issues are sorted out.

You can see which clocks have been disabled by booting your kernel with these parameters:



```text
tp_printk trace_event=clk:clk_disable
```

To bypass this disabling, include "clk_ignore_unused" in the bootargs to the kernel.

<a id="rst-locking"></a>

## Locking

The common clock framework uses two global locks, the prepare lock and the enable lock.

The enable lock is a spinlock and is held across calls to the .enable, .disable operations. Those operations are thus not allowed to sleep, and calls to the clk_enable(), clk_disable() API functions are allowed in atomic context.

For clk_is_enabled() API, it is also designed to be allowed to be used in atomic context. However, it doesn't really make any sense to hold the enable lock in core, unless you want to do something else with the information of the enable state with that lock held. Otherwise, seeing if a clk is enabled is a one-shot read of the enabled state, which could just as easily change after the function returns because the lock is released. Thus the user of this API needs to handle synchronizing the read of the state with whatever they're using it for to make sure that the enable state doesn't change during that time.

The prepare lock is a mutex and is held across calls to all other operations. All those operations are allowed to sleep, and calls to the corresponding API functions are not allowed in atomic context.

This effectively divides operations in two groups from a locking perspective.

Drivers don't need to manually protect resources shared between the operations of one group, regardless of whether those resources are shared by multiple clocks or not. However, access to resources that are shared between operations of the two groups needs to be protected by the drivers. An example of such a resource would be a register that controls both the clock rate and the clock enable/disable state.

The clock framework is reentrant, in that a driver is allowed to call clock framework functions from within its implementation of clock operations. This can for instance cause a .set_rate operation of one clock being called from within the .set_rate operation of another clock. This case must be considered in the driver implementations, but the code flow is usually controlled by the driver in that case.

Note that locking must also be considered when code outside of the common clock framework needs to access resources used by the clock operations. This is considered out of scope of this document.

---

# Device Frequency Scaling

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This framework provides a standard kernel interface for Dynamic Voltage and Frequency Switching on arbitrary devices.

<a id="rst-device-frequency-scaling"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

This framework provides a standard kernel interface for Dynamic Voltage and Frequency Switching on arbitrary devices.

It exposes controls for adjusting frequency through sysfs files which are similar to the cpufreq subsystem.

Devices for which current usage can be measured can have their frequency automatically adjusted by governors.

<a id="rst-api"></a>

## API

Device drivers need to initialize a `devfreq_profile` and call the `devfreq_add_device()` function to create a `devfreq` instance.


#### <a id="c-struct-devfreq_dev_status"></a>`struct devfreq_dev_status`

Data given from devfreq user device to governors. Represents the performance statistics.

**Definition**

```c
struct devfreq_dev_status {
    unsigned long total_time;
    unsigned long busy_time;
    unsigned long current_frequency;
    void *private_data;
};
```

**Members**

- `total_time`: The total time represented by this instance of
  devfreq_dev_status
- `busy_time`: The time that the device was working among the
  total_time.
- `current_frequency`: The operating frequency.
- `private_data`: An entry not specified by the devfreq framework.
  A device and a specific governor may have their
  own protocol with private_data. However, because
  this is governor-specific, a governor using this
  will be only compatible with devices aware of it.

#### <a id="c-struct-devfreq_dev_profile"></a>`struct devfreq_dev_profile`

Devfreq's user device profile

**Definition**

```c
struct devfreq_dev_profile {
    unsigned long initial_freq;
    unsigned int polling_ms;
    enum devfreq_timer timer;
    int (*target)(struct device *dev, unsigned long *freq, u32 flags);
    int (*get_dev_status)(struct device *dev, struct devfreq_dev_status *stat);
    int (*get_cur_freq)(struct device *dev, unsigned long *freq);
    void (*exit)(struct device *dev);
    unsigned long *freq_table;
    unsigned int max_state;
    bool is_cooling_device;
    const struct attribute_group **dev_groups;
};
```

**Members**

- `initial_freq`: The operating frequency when [`devfreq_add_device()`](#c-devfreq_add_device) is
  called.
- `polling_ms`: The polling interval in ms. 0 disables polling.
- `timer`: Timer type is either deferrable or delayed timer.
- `target`: The device should set its operating frequency at
  freq or lowest-upper-than-freq value. If freq is
  higher than any operable frequency, set maximum.
  Before returning, target function should set
  freq at the current frequency.
  The "flags" parameter's possible values are
  explained above with "DEVFREQ_FLAG_*" macros.
- `get_dev_status`: The device should provide the current performance
  status to devfreq. Governors are recommended not to
  use this directly. Instead, governors are recommended
  to use `devfreq_update_stats()` along with
  devfreq.last_status.
- `get_cur_freq`: The device should provide the current frequency
  at which it is operating.
- `exit`: An optional callback that is called when devfreq
  is removing the devfreq object due to error or
  from [`devfreq_remove_device()`](#c-devfreq_remove_device) call. If the user
  has registered devfreq->nb at a notifier-head,
  this is the time to unregister it.
- `freq_table`: Optional list of frequencies to support statistics
  and freq_table must be generated in ascending order.
- `max_state`: The size of freq_table.
- `is_cooling_device`: A self-explanatory boolean giving the device a
  cooling effect property.
- `dev_groups`: Optional device-specific sysfs attribute groups that to
  be attached to the devfreq device.

#### <a id="c-struct-devfreq_stats"></a>`struct devfreq_stats`

Statistics of devfreq device behavior

**Definition**

```c
struct devfreq_stats {
    unsigned int total_trans;
    unsigned int *trans_table;
    u64 *time_in_state;
    u64 last_update;
};
```

**Members**

- `total_trans`: Number of devfreq transitions.
- `trans_table`: Statistics of devfreq transitions.
- `time_in_state`: Statistics of devfreq states.
- `last_update`: The last time stats were updated.

#### <a id="c-struct-devfreq"></a>`struct devfreq`

Device devfreq structure

**Definition**

```c
struct devfreq {
    struct list_head node;
    struct mutex lock;
    struct device dev;
    struct devfreq_dev_profile *profile;
    const struct devfreq_governor *governor;
    struct opp_table *opp_table;
    struct notifier_block nb;
    struct delayed_work work;
    unsigned long *freq_table;
    unsigned int max_state;
    unsigned long previous_freq;
    struct devfreq_dev_status last_status;
    void *data;
    void *governor_data;
    struct dev_pm_qos_request user_min_freq_req;
    struct dev_pm_qos_request user_max_freq_req;
    unsigned long scaling_min_freq;
    unsigned long scaling_max_freq;
    bool stop_polling;
    unsigned long suspend_freq;
    unsigned long resume_freq;
    atomic_t suspend_count;
    struct devfreq_stats stats;
    struct srcu_notifier_head transition_notifier_list;
    struct thermal_cooling_device *cdev;
    struct notifier_block nb_min;
    struct notifier_block nb_max;
};
```

**Members**

- `node`: list node - contains the devices with devfreq that have been
  registered.
- `lock`: a mutex to protect accessing devfreq.
- `dev`: device registered by devfreq class. dev.parent is the device
  using devfreq.
- `profile`: device-specific devfreq profile
- `governor`: method how to choose frequency based on the usage.
- `opp_table`: Reference to OPP table of dev.parent, if one exists.
- `nb`: notifier block used to notify devfreq object that it should
  reevaluate operable frequencies. Devfreq users may use
  devfreq.nb to the corresponding register notifier call chain.
- `work`: delayed work for load monitoring.
- `freq_table`: current frequency table used by the devfreq driver.
- `max_state`: count of entry present in the frequency table.
- `previous_freq`: previously configured frequency value.
- `last_status`: devfreq user device info, performance statistics
- `data`: devfreq driver pass to governors, governor should not change it.
- `governor_data`: private data for governors, devfreq core doesn't touch it.
- `user_min_freq_req`: PM QoS minimum frequency request from user (via sysfs)
- `user_max_freq_req`: PM QoS maximum frequency request from user (via sysfs)
- `scaling_min_freq`: Limit minimum frequency requested by OPP interface
- `scaling_max_freq`: Limit maximum frequency requested by OPP interface
- `stop_polling`: devfreq polling status of a device.
- `suspend_freq`: frequency of a device set during suspend phase.
- `resume_freq`: frequency of a device set in resume phase.
- `suspend_count`: suspend requests counter for a device.
- `stats`: Statistics of devfreq device behavior
- `transition_notifier_list`: list head of DEVFREQ_TRANSITION_NOTIFIER notifier
- `cdev`: Cooling device pointer if the devfreq has cooling property
- `nb_min`: Notifier block for DEV_PM_QOS_MIN_FREQUENCY
- `nb_max`: Notifier block for DEV_PM_QOS_MAX_FREQUENCY

**Description**

This structure stores the devfreq information for a given device.

Note that when a governor accesses entries in struct devfreq in its
functions except for the context of callbacks defined in struct
devfreq_governor, the governor should protect its access with the
struct mutex lock in struct devfreq. A governor may use this mutex
to protect its own private data in `void *data` as well.

#### <a id="c-struct-devfreq_simple_ondemand_data"></a>`struct devfreq_simple_ondemand_data`

`void *data` fed to struct devfreq and devfreq_add_device

**Definition**

```c
struct devfreq_simple_ondemand_data {
    unsigned int upthreshold;
    unsigned int downdifferential;
};
```

**Members**

- `upthreshold`: If the load is over this value, the frequency jumps.
  Specify 0 to use the default. Valid value = 0 to 100.
- `downdifferential`: If the load is under upthreshold - downdifferential,
  the governor may consider slowing the frequency down.
  Specify 0 to use the default. Valid value = 0 to 100.
  downdifferential \< upthreshold must hold.

**Description**

If the fed devfreq_simple_ondemand_data pointer is NULL to the governor,
the governor uses the default values.

#### <a id="c-struct-devfreq_passive_data"></a>`struct devfreq_passive_data`

`void *data` fed to struct devfreq and devfreq_add_device

**Definition**

```c
struct devfreq_passive_data {
    struct devfreq *parent;
    int (*get_target_freq)(struct devfreq *this, unsigned long *freq);
    enum devfreq_parent_dev_type parent_type;
    struct devfreq *this;
    struct notifier_block nb;
    struct list_head cpu_data_list;
};
```

**Members**

- `parent`: the devfreq instance of parent device.
- `get_target_freq`: Optional callback, Returns desired operating frequency
  for the device using passive governor. That is called
  when passive governor should decide the next frequency
  by using the new frequency of parent devfreq device
  using governors except for passive governor.
  If the devfreq device has the specific method to decide
  the next frequency, should use this callback.
- `parent_type`: the parent type of the device.
- `this`: the devfreq instance of own device.
- `nb`: the notifier block for DEVFREQ_TRANSITION_NOTIFIER or
  CPUFREQ_TRANSITION_NOTIFIER list.
- `cpu_data_list`: the list of cpu frequency data for all cpufreq_policy.

**Description**

The devfreq_passive_data have to set the devfreq instance of parent
device with governors except for the passive governor. But, don't need to
initialize the 'this' and 'nb' field because the devfreq core will handle
them.



#### <a id="c-struct-devfreq_event_dev"></a>`struct devfreq_event_dev`

the devfreq-event device

**Definition**

```c
struct devfreq_event_dev {
    struct list_head node;
    struct device dev;
    struct mutex lock;
    u32 enable_count;
    const struct devfreq_event_desc *desc;
};
```

**Members**

- `node`: Contain the devfreq-event device that have been registered.
- `dev`: the device registered by devfreq-event class. dev.parent is
  the device using devfreq-event.
- `lock`: a mutex to protect accessing devfreq-event.
- `enable_count`: the number of enable function have been called.
- `desc`: the description for devfreq-event device.

**Description**

This structure contains devfreq-event device information.

#### <a id="c-struct-devfreq_event_data"></a>`struct devfreq_event_data`

the devfreq-event data

**Definition**

```c
struct devfreq_event_data {
    unsigned long load_count;
    unsigned long total_count;
};
```

**Members**

- `load_count`: load count of devfreq-event device for the given period.
- `total_count`: total count of devfreq-event device for the given period.
  each count may represent a clock cycle, a time unit
  (ns/us/...), or anything the device driver wants.
  Generally, utilization is load_count / total_count.

**Description**

This structure contains the data of devfreq-event device for polling period.

#### <a id="c-struct-devfreq_event_ops"></a>`struct devfreq_event_ops`

the operations of devfreq-event device

**Definition**

```c
struct devfreq_event_ops {
    int (*enable)(struct devfreq_event_dev *edev);
    int (*disable)(struct devfreq_event_dev *edev);
    int (*reset)(struct devfreq_event_dev *edev);
    int (*set_event)(struct devfreq_event_dev *edev);
    int (*get_event)(struct devfreq_event_dev *edev, struct devfreq_event_data *edata);
};
```

**Members**

- `enable`: Enable the devfreq-event device.
- `disable`: Disable the devfreq-event device.
- `reset`: Reset all setting of the devfreq-event device.
- `set_event`: Set the specific event type for the devfreq-event device.
- `get_event`: Get the result of the devfreq-event devie with specific
  event type.

**Description**

This structure contains devfreq-event device operations which can be
implemented by devfreq-event device drivers.

#### <a id="c-struct-devfreq_event_desc"></a>`struct devfreq_event_desc`

the descriptor of devfreq-event device

**Definition**

```c
struct devfreq_event_desc {
    const char *name;
    u32 event_type;
    void *driver_data;
    const struct devfreq_event_ops *ops;
};
```

**Members**

- `name`: the name of devfreq-event device.
- `event_type`: the type of the event determined and used by driver
- `driver_data`: the private data for devfreq-event driver.
- `ops`: the operation to control devfreq-event device.

**Description**

Each devfreq-event device is described with a this structure.
This structure contains the various data for devfreq-event device.
The event_type describes what is going to be counted in the register.
It might choose to count e.g. read requests, write data in bytes, etc.
The full supported list of types is present in specyfic header in:
include/dt-bindings/pmu/.



#### <a id="c-devfreq_get_freq_range"></a>`devfreq_get_freq_range()`

```c
void devfreq_get_freq_range(struct devfreq *devfreq, unsigned long *min_freq, unsigned long *max_freq)
```

Get the current freq range

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance
- `unsigned long *min_freq`: the min frequency
- `unsigned long *max_freq`: the max frequency

**Description**

This takes into consideration all constraints.

#### <a id="c-devfreq_update_status"></a>`devfreq_update_status()`

```c
int devfreq_update_status(struct devfreq *devfreq, unsigned long freq)
```

Update statistics of devfreq behavior

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance
- `unsigned long freq`: the update target frequency

#### <a id="c-devfreq_update_target"></a>`devfreq_update_target()`

```c
int devfreq_update_target(struct devfreq *devfreq, unsigned long freq)
```

Reevaluate the device and configure frequency on the final stage.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.
- `unsigned long freq`: the new frequency of parent device. This argument
  is only used for devfreq device using passive governor.

**Note**

- Lock devfreq->lock before calling devfreq_update_target. This function

  should be only used by both [`update_devfreq()`](#c-update_devfreq) and devfreq governors.

#### <a id="c-update_devfreq"></a>`update_devfreq()`

```c
int update_devfreq(struct devfreq *devfreq)
```

Reevaluate the device and configure frequency.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Note**

- Lock devfreq->lock before calling update_devfreq

  This function is exported for governors.

#### <a id="c-devfreq_monitor_start"></a>`devfreq_monitor_start()`

```c
void devfreq_monitor_start(struct devfreq *devfreq)
```

Start load monitoring of devfreq instance

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Description**

Helper function for starting devfreq device load monitoring. By default,
deferrable timer is used for load monitoring. But the users can change this
behavior using the "timer" type in devfreq_dev_profile. This function will be
called by devfreq governor in response to the DEVFREQ_GOV_START event
generated while adding a device to the devfreq framework.

#### <a id="c-devfreq_monitor_stop"></a>`devfreq_monitor_stop()`

```c
void devfreq_monitor_stop(struct devfreq *devfreq)
```

Stop load monitoring of a devfreq instance

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Description**

Helper function to stop devfreq device load monitoring. Function
to be called from governor in response to DEVFREQ_GOV_STOP
event when device is removed from devfreq framework.

#### <a id="c-devfreq_monitor_suspend"></a>`devfreq_monitor_suspend()`

```c
void devfreq_monitor_suspend(struct devfreq *devfreq)
```

Suspend load monitoring of a devfreq instance

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Description**

Helper function to suspend devfreq device load monitoring. Function
to be called from governor in response to DEVFREQ_GOV_SUSPEND
event or when polling interval is set to zero.

**Note**

Though this function is same as [`devfreq_monitor_stop()`](#c-devfreq_monitor_stop),
intentionally kept separate to provide hooks for collecting
transition statistics.

#### <a id="c-devfreq_monitor_resume"></a>`devfreq_monitor_resume()`

```c
void devfreq_monitor_resume(struct devfreq *devfreq)
```

Resume load monitoring of a devfreq instance

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.

**Description**

Helper function to resume devfreq device load monitoring. Function
to be called from governor in response to DEVFREQ_GOV_RESUME
event or when polling interval is set to non-zero.

#### <a id="c-devfreq_update_interval"></a>`devfreq_update_interval()`

```c
void devfreq_update_interval(struct devfreq *devfreq, unsigned int *delay)
```

Update device devfreq monitoring interval

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance.
- `unsigned int *delay`: new polling interval to be set.

**Description**

Helper function to set new load monitoring polling interval. Function
to be called from governor in response to DEVFREQ_GOV_UPDATE_INTERVAL event.

#### <a id="c-devfreq_add_device"></a>`devfreq_add_device()`

```c
struct devfreq * devfreq_add_device(struct device *dev, struct devfreq_dev_profile *profile, const char *governor_name, void *data)
```

Add devfreq feature to the device

**Parameters**

- `struct device *dev`: the device to add devfreq feature.
- `struct devfreq_dev_profile *profile`: device-specific profile to run devfreq.
- `const char *governor_name`: name of the policy to choose frequency.
- `void *data`: devfreq driver pass to governors, governor should not change it.

#### <a id="c-devfreq_remove_device"></a>`devfreq_remove_device()`

```c
int devfreq_remove_device(struct devfreq *devfreq)
```

Remove devfreq feature from a device.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance to be removed

**Description**

The opposite of [`devfreq_add_device()`](#c-devfreq_add_device).

#### <a id="c-devm_devfreq_add_device"></a>`devm_devfreq_add_device()`

```c
struct devfreq * devm_devfreq_add_device(struct device *dev, struct devfreq_dev_profile *profile, const char *governor_name, void *data)
```

Resource-managed [`devfreq_add_device()`](#c-devfreq_add_device)

**Parameters**

- `struct device *dev`: the device to add devfreq feature.
- `struct devfreq_dev_profile *profile`: device-specific profile to run devfreq.
- `const char *governor_name`: name of the policy to choose frequency.
- `void *data`: devfreq driver pass to governors, governor should not change it.

**Description**

This function manages automatically the memory of devfreq device using device
resource management and simplify the free operation for memory of devfreq
device.

#### <a id="c-devm_devfreq_remove_device"></a>`devm_devfreq_remove_device()`

```c
void devm_devfreq_remove_device(struct device *dev, struct devfreq *devfreq)
```

Resource-managed [`devfreq_remove_device()`](#c-devfreq_remove_device)

**Parameters**

- `struct device *dev`: the device from which to remove devfreq feature.
- `struct devfreq *devfreq`: the devfreq instance to be removed

#### <a id="c-devfreq_suspend_device"></a>`devfreq_suspend_device()`

```c
int devfreq_suspend_device(struct devfreq *devfreq)
```

Suspend devfreq of a device.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance to be suspended

**Description**

This function is intended to be called by the pm callbacks
(e.g., runtime_suspend, suspend) of the device driver that
holds the devfreq.

#### <a id="c-devfreq_resume_device"></a>`devfreq_resume_device()`

```c
int devfreq_resume_device(struct devfreq *devfreq)
```

Resume devfreq of a device.

**Parameters**

- `struct devfreq *devfreq`: the devfreq instance to be resumed

**Description**

This function is intended to be called by the pm callbacks
(e.g., runtime_resume, resume) of the device driver that
holds the devfreq.

#### <a id="c-devfreq_add_governor"></a>`devfreq_add_governor()`

```c
int devfreq_add_governor(struct devfreq_governor *governor)
```

Add devfreq governor

**Parameters**

- `struct devfreq_governor *governor`: the devfreq governor to be added

#### <a id="c-devm_devfreq_add_governor"></a>`devm_devfreq_add_governor()`

```c
int devm_devfreq_add_governor(struct device *dev, struct devfreq_governor *governor)
```

Add devfreq governor

**Parameters**

- `struct device *dev`: device which adds devfreq governor
- `struct devfreq_governor *governor`: the devfreq governor to be added

**Description**

This is a resource-managed variant of [`devfreq_add_governor()`](#c-devfreq_add_governor).

#### <a id="c-devfreq_remove_governor"></a>`devfreq_remove_governor()`

```c
int devfreq_remove_governor(struct devfreq_governor *governor)
```

Remove devfreq feature from a device.

**Parameters**

- `struct devfreq_governor *governor`: the devfreq governor to be removed

#### <a id="c-devfreq_recommended_opp"></a>`devfreq_recommended_opp()`

```c
struct dev_pm_opp * devfreq_recommended_opp(struct device *dev, unsigned long *freq, u32 flags)
```

Helper function to get proper OPP for the freq value given to target callback.

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `unsigned long *freq`: The frequency given to target function
- `u32 flags`: Flags handed from devfreq framework.

**Description**

The callers are required to call `dev_pm_opp_put()` for the returned OPP after
use.

#### <a id="c-devfreq_register_opp_notifier"></a>`devfreq_register_opp_notifier()`

```c
int devfreq_register_opp_notifier(struct device *dev, struct devfreq *devfreq)
```

Helper function to get devfreq notified for any changes in the OPP availability changes

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.

#### <a id="c-devfreq_unregister_opp_notifier"></a>`devfreq_unregister_opp_notifier()`

```c
int devfreq_unregister_opp_notifier(struct device *dev, struct devfreq *devfreq)
```

Helper function to stop getting devfreq notified for any changes in the OPP availability changes anymore.

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.

**Description**

At `exit()` callback of devfreq_dev_profile, this must be included if
devfreq_recommended_opp is used.

#### <a id="c-devm_devfreq_register_opp_notifier"></a>`devm_devfreq_register_opp_notifier()`

```c
int devm_devfreq_register_opp_notifier(struct device *dev, struct devfreq *devfreq)
```

Resource-managed [`devfreq_register_opp_notifier()`](#c-devfreq_register_opp_notifier)

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.

#### <a id="c-devm_devfreq_unregister_opp_notifier"></a>`devm_devfreq_unregister_opp_notifier()`

```c
void devm_devfreq_unregister_opp_notifier(struct device *dev, struct devfreq *devfreq)
```

Resource-managed [`devfreq_unregister_opp_notifier()`](#c-devfreq_unregister_opp_notifier)

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.

#### <a id="c-devfreq_register_notifier"></a>`devfreq_register_notifier()`

```c
int devfreq_register_notifier(struct devfreq *devfreq, struct notifier_block *nb, unsigned int list)
```

Register a driver with devfreq

**Parameters**

- `struct devfreq *devfreq`: The devfreq object.
- `struct notifier_block *nb`: The notifier block to register.
- `unsigned int list`: DEVFREQ_TRANSITION_NOTIFIER.

#### <a id="c-devm_devfreq_register_notifier"></a>`devm_devfreq_register_notifier()`

```c
int devm_devfreq_register_notifier(struct device *dev, struct devfreq *devfreq, struct notifier_block *nb, unsigned int list)
```

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.
- `struct notifier_block *nb`: The notifier block to be unregistered.
- `unsigned int list`: DEVFREQ_TRANSITION_NOTIFIER.

**Description**

- Resource-managed [`devfreq_register_notifier()`](#c-devfreq_register_notifier)

#### <a id="c-devm_devfreq_unregister_notifier"></a>`devm_devfreq_unregister_notifier()`

```c
void devm_devfreq_unregister_notifier(struct device *dev, struct devfreq *devfreq, struct notifier_block *nb, unsigned int list)
```

**Parameters**

- `struct device *dev`: The devfreq user device. (parent of devfreq)
- `struct devfreq *devfreq`: The devfreq object.
- `struct notifier_block *nb`: The notifier block to be unregistered.
- `unsigned int list`: DEVFREQ_TRANSITION_NOTIFIER.

**Description**

- Resource-managed `devfreq_unregister_notifier()`



#### <a id="c-devfreq_event_enable_edev"></a>`devfreq_event_enable_edev()`

```c
int devfreq_event_enable_edev(struct devfreq_event_dev *edev)
```

Enable the devfreq-event dev and increase the enable_count of devfreq-event dev.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function increase the enable_count and enable the
devfreq-event device. The devfreq-event device should be enabled before
using it by devfreq device.

#### <a id="c-devfreq_event_disable_edev"></a>`devfreq_event_disable_edev()`

```c
int devfreq_event_disable_edev(struct devfreq_event_dev *edev)
```

Disable the devfreq-event dev and decrease the enable_count of the devfreq-event dev.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function decrease the enable_count and disable the
devfreq-event device. After the devfreq-event device is disabled,
devfreq device can't use the devfreq-event device for get/set/reset
operations.

#### <a id="c-devfreq_event_is_enabled"></a>`devfreq_event_is_enabled()`

```c
bool devfreq_event_is_enabled(struct devfreq_event_dev *edev)
```

Check whether devfreq-event dev is enabled or not.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function check whether devfreq-event dev is enabled or not.
If return true, the devfreq-event dev is enabeld. If return false, the
devfreq-event dev is disabled.

#### <a id="c-devfreq_event_set_event"></a>`devfreq_event_set_event()`

```c
int devfreq_event_set_event(struct devfreq_event_dev *edev)
```

Set event to devfreq-event dev to start.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function set the event to the devfreq-event device to start
for getting the event data which could be various event type.

#### <a id="c-devfreq_event_get_event"></a>`devfreq_event_get_event()`

```c
int devfreq_event_get_event(struct devfreq_event_dev *edev, struct devfreq_event_data *edata)
```

Get {load|total}_count from devfreq-event dev.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device
- `struct devfreq_event_data *edata`: the calculated data of devfreq-event device

**Description**

Note that this function get the calculated event data from devfreq-event dev
after stoping the progress of whole sequence of devfreq-event dev.

#### <a id="c-devfreq_event_reset_event"></a>`devfreq_event_reset_event()`

```c
int devfreq_event_reset_event(struct devfreq_event_dev *edev)
```

Reset all opeations of devfreq-event dev.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function stop all operations of devfreq-event dev and reset
the current event data to make the devfreq-event device into initial state.

#### <a id="c-devfreq_event_get_edev_by_phandle"></a>`devfreq_event_get_edev_by_phandle()`

```c
struct devfreq_event_dev * devfreq_event_get_edev_by_phandle(struct device *dev, const char *phandle_name, int index)
```

Get the devfreq-event dev from devicetree.

**Parameters**

- `struct device *dev`: the pointer to the given device
- `const char *phandle_name`: name of property holding a phandle value
- `int index`: the index into list of devfreq-event device

**Description**

Note that this function return the pointer of devfreq-event device.

#### <a id="c-devfreq_event_get_edev_count"></a>`devfreq_event_get_edev_count()`

```c
int devfreq_event_get_edev_count(struct device *dev, const char *phandle_name)
```

Get the count of devfreq-event dev

**Parameters**

- `struct device *dev`: the pointer to the given device
- `const char *phandle_name`: name of property holding a phandle value

**Description**

Note that this function return the count of devfreq-event devices.

#### <a id="c-devfreq_event_add_edev"></a>`devfreq_event_add_edev()`

```c
struct devfreq_event_dev * devfreq_event_add_edev(struct device *dev, struct devfreq_event_desc *desc)
```

Add new devfreq-event device.

**Parameters**

- `struct device *dev`: the device owning the devfreq-event device being created
- `struct devfreq_event_desc *desc`: the devfreq-event device's descriptor which include essential
  data for devfreq-event device.

**Description**

Note that this function add new devfreq-event device to devfreq-event class
list and register the device of the devfreq-event device.

#### <a id="c-devfreq_event_remove_edev"></a>`devfreq_event_remove_edev()`

```c
int devfreq_event_remove_edev(struct devfreq_event_dev *edev)
```

Remove the devfreq-event device registered.

**Parameters**

- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function removes the registered devfreq-event device.

#### <a id="c-devm_devfreq_event_add_edev"></a>`devm_devfreq_event_add_edev()`

```c
struct devfreq_event_dev * devm_devfreq_event_add_edev(struct device *dev, struct devfreq_event_desc *desc)
```

Resource-managed [`devfreq_event_add_edev()`](#c-devfreq_event_add_edev)

**Parameters**

- `struct device *dev`: the device owning the devfreq-event device being created
- `struct devfreq_event_desc *desc`: the devfreq-event device's descriptor which include essential
  data for devfreq-event device.

**Description**

Note that this function manages automatically the memory of devfreq-event
device using device resource management and simplify the free operation
for memory of devfreq-event device.

#### <a id="c-devm_devfreq_event_remove_edev"></a>`devm_devfreq_event_remove_edev()`

```c
void devm_devfreq_event_remove_edev(struct device *dev, struct devfreq_event_dev *edev)
```

Resource-managed [`devfreq_event_remove_edev()`](#c-devfreq_event_remove_edev)

**Parameters**

- `struct device *dev`: the device owning the devfreq-event device being created
- `struct devfreq_event_dev *edev`: the devfreq-event device

**Description**

Note that this function manages automatically the memory of devfreq-event
device using device resource management.

---

# The Linux kernel dpll subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> PLL - Phase Locked Loop is an electronic circuit which syntonizes clock signal of a device with an external clock signal. Effectively enabling device to run on the same clock signal beat as provided on a PLL input.

<a id="rst-the-linux-kernel-dpll-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-dpll"></a>

## DPLL

PLL - Phase Locked Loop is an electronic circuit which syntonizes clock signal of a device with an external clock signal. Effectively enabling device to run on the same clock signal beat as provided on a PLL input.

DPLL - Digital Phase Locked Loop is an integrated circuit which in addition to plain PLL behavior incorporates a digital phase detector and may have digital divider in the loop. As a result, the frequency on DPLL's input and output may be configurable.

<a id="rst-subsystem"></a>

## Subsystem

The main purpose of dpll subsystem is to provide general interface to configure devices that use any kind of Digital PLL and could use different sources of input signal to synchronize to, as well as different types of outputs. The main interface is NETLINK\_GENERIC based protocol with an event monitoring multicast group defined.

<a id="rst-device-object"></a>

## Device object

Single dpll device object means single Digital PLL circuit and bunch of connected pins. It reports the supported modes of operation and current status to the user in response to the `do` request of netlink command `DPLL_CMD_DEVICE_GET` and list of dplls registered in the subsystem with `dump` netlink request of the same command. Changing the configuration of dpll device is done with `do` request of netlink `DPLL_CMD_DEVICE_SET` command. A device handle is `DPLL_A_ID`, it shall be provided to get or set configuration of particular device in the system. It can be obtained with a `DPLL_CMD_DEVICE_GET` `dump` request or a `DPLL_CMD_DEVICE_ID_GET` `do` request, where the one must provide attributes that result in single device match.

<a id="rst-pin-object"></a>

## Pin object

A pin is amorphic object which represents either input or output, it could be internal component of the device, as well as externally connected. The number of pins per dpll vary, but usually multiple pins shall be provided for a single dpll device. Pin's properties, capabilities and status is provided to the user in response to `do` request of netlink `DPLL_CMD_PIN_GET` command. It is also possible to list all the pins that were registered in the system with `dump` request of `DPLL_CMD_PIN_GET` command. Configuration of a pin can be changed by `do` request of netlink `DPLL_CMD_PIN_SET` command. Pin handle is a `DPLL_A_PIN_ID`, it shall be provided to get or set configuration of particular pin in the system. It can be obtained with `DPLL_CMD_PIN_GET` `dump` request or `DPLL_CMD_PIN_ID_GET` `do` request, where user provides attributes that result in single pin match.

<a id="rst-pin-selection"></a>

## Pin selection

In general, selected pin (the one which signal is driving the dpll device) can be obtained from `DPLL_A_PIN_STATE` attribute, and only one pin shall be in `DPLL_PIN_STATE_CONNECTED` state for any dpll device.

Pin selection can be done either manually or automatically, depending on hardware capabilities and active dpll device work mode (`DPLL_A_MODE` attribute). The consequence is that there are differences for each mode in terms of available pin states, as well as for the states the user can request for a dpll device.

In manual mode (`DPLL_MODE_MANUAL`) the user can request or receive one of following pin states:

- `DPLL_PIN_STATE_CONNECTED` - the pin is used to drive dpll device

- `DPLL_PIN_STATE_DISCONNECTED` - the pin is not used to drive dpll device

In automatic mode (`DPLL_MODE_AUTOMATIC`) the user can request or receive one of following pin states:

- `DPLL_PIN_STATE_SELECTABLE` - the pin shall be considered as valid input for automatic selection algorithm

- `DPLL_PIN_STATE_DISCONNECTED` - the pin shall be not considered as a valid input for automatic selection algorithm

In automatic mode (`DPLL_MODE_AUTOMATIC`) the user can only receive pin state `DPLL_PIN_STATE_CONNECTED` once automatic selection algorithm locks a dpll device with one of the inputs.

<a id="rst-shared-pins"></a>

## Shared pins

A single pin object can be attached to multiple dpll devices. Then there are two groups of configuration knobs:

1. Set on a pin - the configuration affects all dpll devices pin is registered to (i.e., `DPLL_A_PIN_FREQUENCY`),

2. Set on a pin-dpll tuple - the configuration affects only selected dpll device (i.e., `DPLL_A_PIN_PRIO`, `DPLL_A_PIN_STATE`, `DPLL_A_PIN_DIRECTION`).

<a id="rst-mux-type-pins"></a>

## MUX-type pins

A pin can be MUX-type, it aggregates child pins and serves as a pin multiplexer. One or more pins are registered with MUX-type instead of being directly registered to a dpll device. Pins registered with a MUX-type pin provide user with additional nested attribute `DPLL_A_PIN_PARENT_PIN` for each parent they were registered with. If a pin was registered with multiple parent pins, they behave like a multiple output multiplexer. In this case output of a `DPLL_CMD_PIN_GET` would contain multiple pin-parent nested attributes with current state related to each parent, like:



```text
'pin': [{{
  'clock-id': 282574471561216,
  'module-name': 'ice',
  'capabilities': 4,
  'id': 13,
  'parent-pin': [
  {'parent-id': 2, 'state': 'connected'},
  {'parent-id': 3, 'state': 'disconnected'}
  ],
  'type': 'synce-eth-port'
  }}]
```

Only one child pin can provide its signal to the parent MUX-type pin at a time, the selection is done by requesting change of a child pin state on desired parent, with the use of `DPLL_A_PIN_PARENT` nested attribute. Example of netlink `set state on parent pin` message format:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> child pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_PIN`
>
> </td>
> <td>
>
>
>
> nested attribute for requesting configuration related to parent pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> parent pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> requested pin state on parent
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-pin-priority"></a>

## Pin priority

Some devices might offer a capability of automatic pin selection mode (enum value `DPLL_MODE_AUTOMATIC` of `DPLL_A_MODE` attribute). Usually, automatic selection is performed on the hardware level, which means only pins directly connected to the dpll can be used for automatic input pin selection. In automatic selection mode, the user cannot manually select a input pin for the device, instead the user shall provide all directly connected pins with a priority `DPLL_A_PIN_PRIO`, the device would pick a highest priority valid signal and use it to control the DPLL device. Example of netlink `set priority on parent pin` message format:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> configured pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_DEVICE`
>
> </td>
> <td>
>
>
>
> nested attribute for requesting configuration related to parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> parent dpll device id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PRIO`
>
> </td>
> <td>
>
>
>
> requested pin prio on parent dpll
>
> </td>
> </tr>
> </tbody>
> </table>

Child pin of MUX-type pin is not capable of automatic input pin selection, in order to configure active input of a MUX-type pin, the user needs to request desired pin state of the child pin on the parent pin, as described in the `MUX-type pins` chapter.

<a id="rst-phase-offset-measurement-and-adjustment"></a>

## Phase offset measurement and adjustment

Device may provide ability to measure a phase difference between signals on a pin and its parent dpll device. If pin-dpll phase offset measurement is supported, it shall be provided with `DPLL_A_PIN_PHASE_OFFSET` attribute for each parent dpll device. The reported phase offset may be computed as the average of prior values and the current measurement, using the following formula:

```math
curr\_avg = prev\_avg * \frac{2^N-1}{2^N} + new\_val * \frac{1}{2^N}
```

where `curr_avg` is the current reported phase offset, `prev_avg` is the previously reported value, `new_val` is the current measurement, and `N` is the averaging factor. Configured averaging factor value is provided with `DPLL_A_PHASE_OFFSET_AVG_FACTOR` attribute of a device and value change can be requested with the same attribute with `DPLL_CMD_DEVICE_SET` command.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PHASE_OFFSET_AVG_FACTOR`
>
> </td>
> <td>
>
>
>
> attr configured value of phase offset averaging factor
>
> </td>
> </tr>
> </tbody>
> </table>

Device may also provide ability to adjust a signal phase on a pin. If pin phase adjustment is supported, minimal and maximal values and granularity that pin handle shall be provided to the user on `DPLL_CMD_PIN_GET` respond with `DPLL_A_PIN_PHASE_ADJUST_MIN`, `DPLL_A_PIN_PHASE_ADJUST_MAX` and `DPLL_A_PIN_PHASE_ADJUST_GRAN` attributes. Configured phase adjust value is provided with `DPLL_A_PIN_PHASE_ADJUST` attribute of a pin, and value change can be requested with the same attribute with `DPLL_CMD_PIN_SET` command.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> configured pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_GRAN`
>
> </td>
> <td>
>
>
>
> attr granularity of phase adjustment value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_MIN`
>
> </td>
> <td>
>
>
>
> attr minimum value of phase adjustment
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_MAX`
>
> </td>
> <td>
>
>
>
> attr maximum value of phase adjustment
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST`
>
> </td>
> <td>
>
>
>
> attr configured value of phase adjustment on parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_DEVICE`
>
> </td>
> <td>
>
>
>
> nested attribute for requesting configuration on given parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> parent dpll device id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_OFFSET`
>
> </td>
> <td>
>
>
>
> attr measured phase difference between a pin and parent dpll device
>
> </td>
> </tr>
> </tbody>
> </table>

All phase related values are provided in pico seconds, which represents time difference between signals phase. The negative value means that phase of signal on pin is earlier in time than dpll's signal. Positive value means that phase of signal on pin is later in time than signal of a dpll.

Phase adjust (also min and max) values are integers, but measured phase offset values are fractional with 3-digit decimal places and shell be divided with `DPLL_PIN_PHASE_OFFSET_DIVIDER` to get integer part and modulo divided to get fractional part.

<a id="rst-phase-offset-monitor"></a>

## Phase offset monitor

Phase offset measurement is typically performed against the current active source. However, some DPLL (Digital Phase-Locked Loop) devices may offer the capability to monitor phase offsets across all available inputs. The attribute and current feature state shall be included in the response message of the `DPLL_CMD_DEVICE_GET` command for supported DPLL devices. In such cases, users can also control the feature using the `DPLL_CMD_DEVICE_SET` command by setting the `enum dpll_feature_state` values for the attribute. Once enabled the phase offset measurements for the input shall be returned in the `DPLL_A_PIN_PHASE_OFFSET` attribute.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PHASE_OFFSET_MONITOR`
>
> </td>
> <td>
>
>
>
> attr state of a feature
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-embedded-sync"></a>

## Embedded SYNC

Device may provide ability to use Embedded SYNC feature. It allows to embed additional SYNC signal into the base frequency of a pin - a one special pulse of base frequency signal every time SYNC signal pulse happens. The user can configure the frequency of Embedded SYNC. The Embedded SYNC capability is always related to a given base frequency and HW capabilities. The user is provided a range of Embedded SYNC frequencies supported, depending on current base frequency configured for the pin.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ESYNC_FREQUENCY`
>
> </td>
> <td>
>
>
>
> current Embedded SYNC frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ESYNC_FREQUENCY_SUPPORTED`
>
> </td>
> <td>
>
>
>
> nest available Embedded SYNC frequency ranges
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY_MIN`
>
> </td>
> <td>
>
>
>
> attr minimum value of frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY_MAX`
>
> </td>
> <td>
>
>
>
> attr maximum value of frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ESYNC_PULSE`
>
> </td>
> <td>
>
>
>
> pulse type of Embedded SYNC
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-reference-sync"></a>

## Reference SYNC

The device may support the Reference SYNC feature, which allows the combination of two inputs into a input pair. In this configuration, clock signals from both inputs are used to synchronize the DPLL device. The higher frequency signal is utilized for the loop bandwidth of the DPLL, while the lower frequency signal is used to syntonize the output signal of the DPLL device. This feature enables the provision of a high-quality loop bandwidth signal from an external source.

A capable input provides a list of inputs that can be bound with to create Reference SYNC. To control this feature, the user must request a desired state for a target pin: use `DPLL_PIN_STATE_CONNECTED` to enable or `DPLL_PIN_STATE_DISCONNECTED` to disable the feature. An input pin can be bound to only one other pin at any given time.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_REFERENCE_SYNC`
>
> </td>
> <td>
>
>
>
> nested attribute for providing info or requesting configuration of the Reference SYNC feature
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> target pin id for Reference SYNC feature
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> state of Reference SYNC connection
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-configuration-commands-group"></a>

## Configuration commands group

Configuration commands are used to get information about registered dpll devices (and pins), as well as set configuration of device or pins. As dpll devices must be abstracted and reflect real hardware, there is no way to add new dpll device via netlink from user space and each device should be registered by its driver.

All netlink commands require `GENL_ADMIN_PERM`. This is to prevent any spamming/DoS from unauthorized userspace applications.

<a id="rst-list-of-netlink-commands-with-possible-attributes"></a>

## List of netlink commands with possible attributes

Constants identifying command types for dpll device uses a `DPLL_CMD_` prefix and suffix according to command purpose. The dpll device related attributes use a `DPLL_A_` prefix and suffix according to attribute purpose.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_ID_GET`
>
> </td>
> <td>
>
>
>
> command to get device ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODULE_NAME`
>
> </td>
> <td>
>
>
>
> attr module name of registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_CLOCK_ID`
>
> </td>
> <td>
>
>
>
> attr Unique Clock Identifier (EUI-64), as defined by the IEEE 1588 standard
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_TYPE`
>
> </td>
> <td>
>
>
>
> attr type of dpll device
>
> </td>
> </tr>
> </tbody>
> </table>
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_GET`
>
> </td>
> <td>
>
>
>
> command to get device info or dump list of available devices
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_ID`
>
> </td>
> <td>
>
>
>
> attr unique dpll device ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODULE_NAME`
>
> </td>
> <td>
>
>
>
> attr module name of registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_CLOCK_ID`
>
> </td>
> <td>
>
>
>
> attr Unique Clock Identifier (EUI-64), as defined by the IEEE 1588 standard
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODE`
>
> </td>
> <td>
>
>
>
> attr selection mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODE_SUPPORTED`
>
> </td>
> <td>
>
>
>
> attr available selection modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_LOCK_STATUS`
>
> </td>
> <td>
>
>
>
> attr dpll device lock status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_TEMP`
>
> </td>
> <td>
>
>
>
> attr device temperature info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_TYPE`
>
> </td>
> <td>
>
>
>
> attr type of dpll device
>
> </td>
> </tr>
> </tbody>
> </table>
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_SET`
>
> </td>
> <td>
>
>
>
> command to set dpll device config
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_ID`
>
> </td>
> <td>
>
>
>
> attr internal dpll device index
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_MODE`
>
> </td>
> <td>
>
>
>
> attr selection mode to configure
>
> </td>
> </tr>
> </tbody>
> </table>

Constants identifying command types for pins uses a `DPLL_CMD_PIN_` prefix and suffix according to command purpose. The pin related attributes use a `DPLL_A_PIN_` prefix and suffix according to attribute purpose.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_ID_GET`
>
> </td>
> <td>
>
>
>
> command to get pin ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_MODULE_NAME`
>
> </td>
> <td>
>
>
>
> attr module name of registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_CLOCK_ID`
>
> </td>
> <td>
>
>
>
> attr Unique Clock Identifier (EUI-64), as defined by the IEEE 1588 standard
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_BOARD_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin board label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PANEL_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin panel label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PACKAGE_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin package label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_TYPE`
>
> </td>
> <td>
>
>
>
> attr type of a pin
>
> </td>
> </tr>
> </tbody>
> </table>
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_GET`
>
> </td>
> <td>
>
>
>
> command to get pin info or dump list of available pins
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> attr unique a pin ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_MODULE_NAME`
>
> </td>
> <td>
>
>
>
> attr module name of registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_CLOCK_ID`
>
> </td>
> <td>
>
>
>
> attr Unique Clock Identifier (EUI-64), as defined by the IEEE 1588 standard
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_BOARD_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin board label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PANEL_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin panel label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PACKAGE_LABEL`
>
> </td>
> <td>
>
>
>
> attr pin package label provided by registerer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_TYPE`
>
> </td>
> <td>
>
>
>
> attr type of a pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY`
>
> </td>
> <td>
>
>
>
> attr current frequency of a pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY_SUPPORTED`
>
> </td>
> <td>
>
>
>
> nested attr provides supported frequencies
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ANY_FREQUENCY_MIN`
>
> </td>
> <td>
>
>
>
> attr minimum value of frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ANY_FREQUENCY_MAX`
>
> </td>
> <td>
>
>
>
> attr maximum value of frequency
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_GRAN`
>
> </td>
> <td>
>
>
>
> attr granularity of phase adjustment value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_MIN`
>
> </td>
> <td>
>
>
>
> attr minimum value of phase adjustment
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST_MAX`
>
> </td>
> <td>
>
>
>
> attr maximum value of phase adjustment
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST`
>
> </td>
> <td>
>
>
>
> attr configured value of phase adjustment on parent device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_DEVICE`
>
> </td>
> <td>
>
>
>
> nested attr for each parent device the pin is connected with
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> attr parent dpll device id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PRIO`
>
> </td>
> <td>
>
>
>
> attr priority of pin on the dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> attr state of pin on the parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_DIRECTION`
>
> </td>
> <td>
>
>
>
> attr direction of a pin on the parent dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_OFFSET`
>
> </td>
> <td>
>
>
>
> attr measured phase difference between a pin and parent dpll
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_PIN`
>
> </td>
> <td>
>
>
>
> nested attr for each parent pin the pin is connected with
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> attr parent pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> attr state of pin on the parent pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_CAPABILITIES`
>
> </td>
> <td>
>
>
>
> attr bitmask of pin capabilities
>
> </td>
> </tr>
> </tbody>
> </table>
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_SET`
>
> </td>
> <td>
>
>
>
> command to set pins configuration
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_ID`
>
> </td>
> <td>
>
>
>
> attr unique a pin ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_FREQUENCY`
>
> </td>
> <td>
>
>
>
> attr requested frequency of a pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PHASE_ADJUST`
>
> </td>
> <td>
>
>
>
> attr requested value of phase adjustment on parent device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_DEVICE`
>
> </td>
> <td>
>
>
>
> nested attr for each parent dpll device configuration request
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> attr parent dpll device id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_DIRECTION`
>
> </td>
> <td>
>
>
>
> attr requested direction of a pin
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PRIO`
>
> </td>
> <td>
>
>
>
> attr requested priority of pin on the dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> attr requested state of pin on the dpll device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_PIN`
>
> </td>
> <td>
>
>
>
> nested attr for each parent pin configuration request
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_PARENT_ID`
>
> </td>
> <td>
>
>
>
> attr parent pin id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_A_PIN_STATE`
>
> </td>
> <td>
>
>
>
> attr requested state of pin on parent pin
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-netlink-dump-requests"></a>

## Netlink dump requests

The `DPLL_CMD_DEVICE_GET` and `DPLL_CMD_PIN_GET` commands are capable of dump type netlink requests, in which case the response is in the same format as for their `do` request, but every device or pin registered in the system is returned.

<a id="rst-set-commands-format"></a>

## SET commands format

`DPLL_CMD_DEVICE_SET` - to target a dpll device, the user provides `DPLL_A_ID`, which is unique identifier of dpll device in the system, as well as parameter being configured (`DPLL_A_MODE`).

`DPLL_CMD_PIN_SET` - to target a pin user must provide a `DPLL_A_PIN_ID`, which is unique identifier of a pin in the system. Also configured pin parameters must be added. If `DPLL_A_PIN_FREQUENCY` is configured, this affects all the dpll devices that are connected with the pin, that is why frequency attribute shall not be enclosed in `DPLL_A_PIN_PARENT_DEVICE`. Other attributes: `DPLL_A_PIN_PRIO`, `DPLL_A_PIN_STATE` or `DPLL_A_PIN_DIRECTION` must be enclosed in `DPLL_A_PIN_PARENT_DEVICE` as their configuration relates to only one of parent dplls, targeted by `DPLL_A_PIN_PARENT_ID` attribute which is also required inside that nest. For MUX-type pins the `DPLL_A_PIN_STATE` attribute is configured in similar way, by enclosing required state in `DPLL_A_PIN_PARENT_PIN` nested attribute and targeted parent pin id in `DPLL_A_PIN_PARENT_ID`.

In general, it is possible to configure multiple parameters at once, but internally each parameter change will be invoked separately, where order of configuration is not guaranteed by any means.

<a id="rst-configuration-pre-defined-enums"></a>

## Configuration pre-defined enums


#### <a id="c-enum-dpll_mode"></a>`enum dpll_mode`

working modes a dpll can support, differentiates if and how dpll selects one of its inputs to syntonize with it, valid values for DPLL_A_MODE attribute

**Constants**

- `DPLL_MODE_MANUAL`: input can be only selected by sending a request to dpll
- `DPLL_MODE_AUTOMATIC`: highest prio input pin auto selected by dpll

#### <a id="c-enum-dpll_lock_status"></a>`enum dpll_lock_status`

provides information of dpll device lock status, valid values for DPLL_A_LOCK_STATUS attribute

**Constants**

- `DPLL_LOCK_STATUS_UNLOCKED`: dpll was not yet locked to any valid input (or
  forced by setting DPLL_A_MODE to DPLL_MODE_DETACHED)
- `DPLL_LOCK_STATUS_LOCKED`: dpll is locked to a valid signal, but no holdover
  available
- `DPLL_LOCK_STATUS_LOCKED_HO_ACQ`: dpll is locked and holdover acquired
- `DPLL_LOCK_STATUS_HOLDOVER`: dpll is in holdover state - lost a valid lock or
  was forced by disconnecting all the pins (latter possible only when dpll
  lock-state was already DPLL_LOCK_STATUS_LOCKED_HO_ACQ, if dpll lock-state
  was not DPLL_LOCK_STATUS_LOCKED_HO_ACQ, the dpll's lock-state shall remain
  DPLL_LOCK_STATUS_UNLOCKED)

#### <a id="c-enum-dpll_lock_status_error"></a>`enum dpll_lock_status_error`

if previous status change was done due to a failure, this provides information of dpll device lock status error. Valid values for DPLL_A_LOCK_STATUS_ERROR attribute

**Constants**

- `DPLL_LOCK_STATUS_ERROR_NONE`: dpll device lock status was changed without
  any error
- `DPLL_LOCK_STATUS_ERROR_UNDEFINED`: dpll device lock status was changed due
  to undefined error. Driver fills this value up in case it is not able to
  obtain suitable exact error type.
- `DPLL_LOCK_STATUS_ERROR_MEDIA_DOWN`: dpll device lock status was changed
  because of associated media got down. This may happen for example if dpll
  device was previously locked on an input pin of type
  PIN_TYPE_SYNCE_ETH_PORT.
- `DPLL_LOCK_STATUS_ERROR_FRACTIONAL_FREQUENCY_OFFSET_TOO_HIGH`: the FFO
  (Fractional Frequency Offset) between the RX and TX symbol rate on the
  media got too high. This may happen for example if dpll device was
  previously locked on an input pin of type PIN_TYPE_SYNCE_ETH_PORT.

#### <a id="c-enum-dpll_type"></a>`enum dpll_type`

type of dpll, valid values for DPLL_A_TYPE attribute

**Constants**

- `DPLL_TYPE_PPS`: dpll produces Pulse-Per-Second signal
- `DPLL_TYPE_EEC`: dpll drives the Ethernet Equipment Clock

#### <a id="c-enum-dpll_pin_type"></a>`enum dpll_pin_type`

defines possible types of a pin, valid values for DPLL_A_PIN_TYPE attribute

**Constants**

- `DPLL_PIN_TYPE_MUX`: aggregates another layer of selectable pins
- `DPLL_PIN_TYPE_EXT`: external input
- `DPLL_PIN_TYPE_SYNCE_ETH_PORT`: ethernet port PHY's recovered clock
- `DPLL_PIN_TYPE_INT_OSCILLATOR`: device internal oscillator
- `DPLL_PIN_TYPE_GNSS`: GNSS recovered clock

#### <a id="c-enum-dpll_pin_direction"></a>`enum dpll_pin_direction`

defines possible direction of a pin, valid values for DPLL_A_PIN_DIRECTION attribute

**Constants**

- `DPLL_PIN_DIRECTION_INPUT`: pin used as a input of a signal
- `DPLL_PIN_DIRECTION_OUTPUT`: pin used to output the signal

#### <a id="c-enum-dpll_pin_state"></a>`enum dpll_pin_state`

defines possible states of a pin, valid values for DPLL_A_PIN_STATE attribute

**Constants**

- `DPLL_PIN_STATE_CONNECTED`: pin connected, active input of phase locked loop
- `DPLL_PIN_STATE_DISCONNECTED`: pin disconnected, not considered as a valid
  input
- `DPLL_PIN_STATE_SELECTABLE`: pin enabled for automatic input selection

#### <a id="c-enum-dpll_pin_capabilities"></a>`enum dpll_pin_capabilities`

defines possible capabilities of a pin, valid flags on DPLL_A_PIN_CAPABILITIES attribute

**Constants**

- `DPLL_PIN_CAPABILITIES_DIRECTION_CAN_CHANGE`: pin direction can be changed
- `DPLL_PIN_CAPABILITIES_PRIORITY_CAN_CHANGE`: pin priority can be changed
- `DPLL_PIN_CAPABILITIES_STATE_CAN_CHANGE`: pin state can be changed

#### <a id="c-enum-dpll_feature_state"></a>`enum dpll_feature_state`

Allow control (enable/disable) and status checking over features.

**Constants**

- `DPLL_FEATURE_STATE_DISABLE`: feature shall be disabled
- `DPLL_FEATURE_STATE_ENABLE`: feature shall be enabled


<a id="rst-notifications"></a>

## Notifications

dpll device can provide notifications regarding status changes of the device, i.e. lock status changes, input/output changes or other alarms. There is one multicast group that is used to notify user-space apps via netlink socket: `DPLL_MCGRP_MONITOR`

Notifications messages:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_CREATE_NTF`
>
> </td>
> <td>
>
>
>
> dpll device was created
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_DELETE_NTF`
>
> </td>
> <td>
>
>
>
> dpll device was deleted
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_DEVICE_CHANGE_NTF`
>
> </td>
> <td>
>
>
>
> dpll device has changed
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_CREATE_NTF`
>
> </td>
> <td>
>
>
>
> dpll pin was created
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_DELETE_NTF`
>
> </td>
> <td>
>
>
>
> dpll pin was deleted
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
> `DPLL_CMD_PIN_CHANGE_NTF`
>
> </td>
> <td>
>
>
>
> dpll pin has changed
>
> </td>
> </tr>
> </tbody>
> </table>

Events format is the same as for the corresponding get command. Format of `DPLL_CMD_DEVICE_` events is the same as response of `DPLL_CMD_DEVICE_GET`. Format of `DPLL_CMD_PIN_` events is same as response of `DPLL_CMD_PIN_GET`.

<a id="rst-device-driver-implementation"></a>

## Device driver implementation

Device is allocated by dpll\_device\_get() call. Second call with the same arguments will not create new object but provides pointer to previously created device for given arguments, it also increases refcount of that object. Device is deallocated by dpll\_device\_put() call, which first decreases the refcount, once refcount is cleared the object is destroyed.

Device should implement set of operations and register device via dpll\_device\_register() at which point it becomes available to the users. Multiple driver instances can obtain reference to it with dpll\_device\_get(), as well as register dpll device with their own ops and priv.

The pins are allocated separately with dpll\_pin\_get(), it works similarly to dpll\_device\_get(). Function first creates object and then for each call with the same arguments only the object refcount increases. Also dpll\_pin\_put() works similarly to dpll\_device\_put().

A pin can be registered with parent dpll device or parent pin, depending on hardware needs. Each registration requires registerer to provide set of pin callbacks, and private data pointer for calling them:

- dpll\_pin\_register() - register pin with a dpll device,

- dpll\_pin\_on\_pin\_register() - register pin with another MUX type pin.

Notifications of adding or removing dpll devices are created within subsystem itself. Notifications about registering/deregistering pins are also invoked by the subsystem. Notifications about status changes either of dpll device or a pin are invoked in two ways:

- after successful change was requested on dpll subsystem, the subsystem calls corresponding notification,

- requested by device driver with dpll\_device\_change\_ntf() or dpll\_pin\_change\_ntf() when driver informs about the status change.

The device driver using dpll interface is not required to implement all the callback operation. Nevertheless, there are few required to be implemented. Required dpll device level callback operations:

- `.mode_get`,

- `.lock_status_get`.

Required pin level callback operations:

- `.state_on_dpll_get` (pins registered with dpll device),

- `.state_on_pin_get` (pins registered with parent pin),

- `.direction_get`.

Every other operation handler is checked for existence and `-EOPNOTSUPP` is returned in case of absence of specific handler.

The simplest implementation is in the OCP TimeCard driver. The ops structures are defined like this:



```c
static const struct dpll_device_ops dpll_ops = {
        .lock_status_get = ptp_ocp_dpll_lock_status_get,
        .mode_get = ptp_ocp_dpll_mode_get,
        .mode_supported = ptp_ocp_dpll_mode_supported,
};

static const struct dpll_pin_ops dpll_pins_ops = {
        .frequency_get = ptp_ocp_dpll_frequency_get,
        .frequency_set = ptp_ocp_dpll_frequency_set,
        .direction_get = ptp_ocp_dpll_direction_get,
        .direction_set = ptp_ocp_dpll_direction_set,
        .state_on_dpll_get = ptp_ocp_dpll_state_get,
};
```

The registration part is then looks like this part:



```c
clkid = pci_get_dsn(pdev);
bp->dpll = dpll_device_get(clkid, 0, THIS_MODULE);
if (IS_ERR(bp->dpll)) {
        err = PTR_ERR(bp->dpll);
        dev_err(&pdev->dev, "dpll_device_alloc failed\n");
        goto out;
}

err = dpll_device_register(bp->dpll, DPLL_TYPE_PPS, &dpll_ops, bp);
if (err)
        goto out;

for (i = 0; i < OCP_SMA_NUM; i++) {
        bp->sma[i].dpll_pin = dpll_pin_get(clkid, i, THIS_MODULE, &bp->sma[i].dpll_prop);
        if (IS_ERR(bp->sma[i].dpll_pin)) {
                err = PTR_ERR(bp->dpll);
                goto out_dpll;
        }

        err = dpll_pin_register(bp->dpll, bp->sma[i].dpll_pin, &dpll_pins_ops,
                                &bp->sma[i]);
        if (err) {
                dpll_pin_put(bp->sma[i].dpll_pin);
                goto out_dpll;
        }
}
```

In the error path we have to rewind every allocation in the reverse order:



```c
while (i) {
        --i;
        dpll_pin_unregister(bp->dpll, bp->sma[i].dpll_pin, &dpll_pins_ops, &bp->sma[i]);
        dpll_pin_put(bp->sma[i].dpll_pin);
}
dpll_device_put(bp->dpll);
```

More complex example can be found in Intel's ICE driver or nVidia's mlx5 driver.

<a id="rst-synce-enablement"></a>

## SyncE enablement

For SyncE enablement it is required to allow control over dpll device for a software application which monitors and configures the inputs of dpll device in response to current state of a dpll device and its inputs. In such scenario, dpll device input signal shall be also configurable to drive dpll with signal recovered from the PHY netdevice. This is done by exposing a pin to the netdevice - attaching pin to the netdevice itself with `dpll_netdev_pin_set(struct net_device *dev, struct dpll_pin *dpll_pin)`. Exposed pin id handle `DPLL_A_PIN_ID` is then identifiable by the user as it is attached to rtnetlink respond to get `RTM_NEWLINK` command in nested attribute `IFLA_DPLL_PIN`.

---

# Error Detection And Correction (EDAC) Devices

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> There are several things to be aware of that aren't at all obvious, like sockets, *socket sets, banks, rows, chip-select rows, channels, etc...

<a id="rst-error-detection-and-correction-edac-devices"></a>

<a id="rst-main-concepts-used-at-the-edac-subsystem"></a>

## Main Concepts used at the EDAC subsystem

There are several things to be aware of that aren't at all obvious, like *sockets, \*socket sets*, *banks*, *rows*, *chip-select rows*, *channels*, etc...

These are some of the many terms that are thrown about that don't always mean what people think they mean (Inconceivable\!).  In the interest of creating a common ground for discussion, terms and their definitions will be established.

- Memory devices

The individual DRAM chips on a memory stick.  These devices commonly output 4 and 8 bits each (x4, x8). Grouping several of these in parallel provides the number of bits that the memory controller expects: typically 72 bits, in order to provide 64 bits + 8 bits of ECC data.

- Memory Stick

A printed circuit board that aggregates multiple memory devices in parallel.  In general, this is the Field Replaceable Unit (FRU) which gets replaced, in the case of excessive errors. Most often it is also called DIMM (Dual Inline Memory Module).

- Memory Socket

A physical connector on the motherboard that accepts a single memory stick. Also called as "slot" on several datasheets.

- Channel

A memory controller channel, responsible to communicate with a group of DIMMs. Each channel has its own independent control (command) and data bus, and can be used independently or grouped with other channels.

- Branch

It is typically the highest hierarchy on a Fully-Buffered DIMM memory controller. Typically, it contains two channels. Two channels at the same branch can be used in single mode or in lockstep mode. When lockstep is enabled, the cacheline is doubled, but it generally brings some performance penalty. Also, it is generally not possible to point to just one memory stick when an error occurs, as the error correction code is calculated using two DIMMs instead of one. Due to that, it is capable of correcting more errors than on single mode.

- Single-channel

The data accessed by the memory controller is contained into one dimm only. E. g. if the data is 64 bits-wide, the data flows to the CPU using one 64 bits parallel access. Typically used with SDR, DDR, DDR2 and DDR3 memories. FB-DIMM and RAMBUS use a different concept for channel, so this concept doesn't apply there.

- Double-channel

The data size accessed by the memory controller is interlaced into two dimms, accessed at the same time. E. g. if the DIMM is 64 bits-wide (72 bits with ECC), the data flows to the CPU using a 128 bits parallel access.

- Chip-select row

This is the name of the DRAM signal used to select the DRAM ranks to be accessed. Common chip-select rows for single channel are 64 bits, for dual channel 128 bits. It may not be visible by the memory controller, as some DIMM types have a memory buffer that can hide direct access to it from the Memory Controller.

- Single-Ranked stick

A Single-ranked stick has 1 chip-select row of memory. Motherboards commonly drive two chip-select pins to a memory stick. A single-ranked stick, will occupy only one of those rows. The other will be unused.

<a id="rst-doubleranked"></a>

- Double-Ranked stick

A double-ranked stick has two chip-select rows which access different sets of memory devices.  The two rows cannot be accessed concurrently.

- Double-sided stick

**DEPRECATED TERM**, see [Double-Ranked stick](<#rst-doubleranked>).

A double-sided stick has two chip-select rows which access different sets of memory devices. The two rows cannot be accessed concurrently. "Double-sided" is irrespective of the memory devices being mounted on both sides of the memory stick.

- Socket set

All of the memory sticks that are required for a single memory access or all of the memory sticks spanned by a chip-select row.  A single socket set has two chip-select rows and if double-sided sticks are used these will occupy those chip-select rows.

- Bank

This term is avoided because it is unclear when needing to distinguish between chip-select rows and socket sets.

- High Bandwidth Memory (HBM)

HBM is a new memory type with low power consumption and ultra-wide communication lanes. It uses vertically stacked memory chips (DRAM dies) interconnected by microscopic wires called "through-silicon vias," or TSVs.

Several stacks of HBM chips connect to the CPU or GPU through an ultra-fast interconnect called the "interposer". Therefore, HBM's characteristics are nearly indistinguishable from on-chip integrated RAM.

<a id="rst-memory-controllers"></a>

## Memory Controllers

Most of the EDAC core is focused on doing Memory Controller error detection. The `edac_mc_alloc()`. It uses internally the struct `mem_ctl_info` to describe the memory controllers, with is an opaque struct for the EDAC drivers. Only the EDAC core is allowed to touch it.


#### <a id="c-enum-dev_type"></a>`enum dev_type`

describe the type of memory DRAM chips used at the stick

**Constants**

- `DEV_UNKNOWN`: Can't be determined, or MC doesn't support detect it
- `DEV_X1`: 1 bit for data
- `DEV_X2`: 2 bits for data
- `DEV_X4`: 4 bits for data
- `DEV_X8`: 8 bits for data
- `DEV_X16`: 16 bits for data
- `DEV_X32`: 32 bits for data
- `DEV_X64`: 64 bits for data

**Description**

Typical values are x4 and x8.

#### <a id="c-enum-hw_event_mc_err_type"></a>`enum hw_event_mc_err_type`

type of the detected error

**Constants**

- `HW_EVENT_ERR_CORRECTED`: Corrected Error - Indicates that an ECC
  corrected error was detected
- `HW_EVENT_ERR_UNCORRECTED`: Uncorrected Error - Indicates an error that
  can't be corrected by ECC, but it is not
  fatal (maybe it is on an unused memory area,
  or the memory controller could recover from
  it for example, by re-trying the operation).
- `HW_EVENT_ERR_DEFERRED`: Deferred Error - Indicates an uncorrectable
  error whose handling is not urgent. This could
  be due to hardware data poisoning where the
  system can continue operation until the poisoned
  data is consumed. Preemptive measures may also
  be taken, e.g. offlining pages, etc.
- `HW_EVENT_ERR_FATAL`: Fatal Error - Uncorrected error that could not
  be recovered.
- `HW_EVENT_ERR_INFO`: Informational - The CPER spec defines a forth
  type of error: informational logs.

#### <a id="c-enum-mem_type"></a>`enum mem_type`

memory types. For a more detailed reference, please see http://en.wikipedia.org/wiki/DRAM

**Constants**

- `MEM_EMPTY`: Empty csrow
- `MEM_RESERVED`: Reserved csrow type
- `MEM_UNKNOWN`: Unknown csrow type
- `MEM_FPM`: FPM - Fast Page Mode, used on systems up to 1995.
- `MEM_EDO`: EDO - Extended data out, used on systems up to 1998.
- `MEM_BEDO`: BEDO - Burst Extended data out, an EDO variant.
- `MEM_SDR`: SDR - Single data rate SDRAM
  http://en.wikipedia.org/wiki/Synchronous_dynamic_random-access_memory
  They use 3 pins for chip select: Pins 0 and 2 are
  for rank 0; pins 1 and 3 are for rank 1, if the memory
  is dual-rank.
- `MEM_RDR`: Registered SDR SDRAM
- `MEM_DDR`: Double data rate SDRAM
  http://en.wikipedia.org/wiki/DDR_SDRAM
- `MEM_RDDR`: Registered Double data rate SDRAM
  This is a variant of the DDR memories.
  A registered memory has a buffer inside it, hiding
  part of the memory details to the memory controller.
- `MEM_RMBS`: Rambus DRAM, used on a few Pentium III/IV controllers.
- `MEM_DDR2`: DDR2 RAM, as described at JEDEC JESD79-2F.
  Those memories are labeled as "PC2-" instead of "PC" to
  differentiate from DDR.
- `MEM_FB_DDR2`: Fully-Buffered DDR2, as described at JEDEC Std No. 205
  and JESD206.
  Those memories are accessed per DIMM slot, and not by
  a chip select signal.
- `MEM_RDDR2`: Registered DDR2 RAM
  This is a variant of the DDR2 memories.
- `MEM_XDR`: Rambus XDR
  It is an evolution of the original RAMBUS memories,
  created to compete with DDR2. Weren't used on any
  x86 arch, but cell_edac PPC memory controller uses it.
- `MEM_DDR3`: DDR3 RAM
- `MEM_RDDR3`: Registered DDR3 RAM
  This is a variant of the DDR3 memories.
- `MEM_LRDDR3`: Load-Reduced DDR3 memory.
- `MEM_LPDDR3`: Low-Power DDR3 memory.
- `MEM_DDR4`: Unbuffered DDR4 RAM
- `MEM_RDDR4`: Registered DDR4 RAM
  This is a variant of the DDR4 memories.
- `MEM_LRDDR4`: Load-Reduced DDR4 memory.
- `MEM_LPDDR4`: Low-Power DDR4 memory.
- `MEM_DDR5`: Unbuffered DDR5 RAM
- `MEM_RDDR5`: Registered DDR5 RAM
- `MEM_LRDDR5`: Load-Reduced DDR5 memory.
- `MEM_NVDIMM`: Non-volatile RAM
- `MEM_WIO2`: Wide I/O 2.
- `MEM_HBM2`: High bandwidth Memory Gen 2.
- `MEM_HBM3`: High bandwidth Memory Gen 3.

#### <a id="c-enum-edac_type"></a>`enum edac_type`

Error Detection and Correction capabilities and mode

**Constants**

- `EDAC_UNKNOWN`: Unknown if ECC is available
- `EDAC_NONE`: Doesn't support ECC
- `EDAC_RESERVED`: Reserved ECC type
- `EDAC_PARITY`: Detects parity errors
- `EDAC_EC`: Error Checking - no correction
- `EDAC_SECDED`: Single bit error correction, Double detection
- `EDAC_S2ECD2ED`: Chipkill x2 devices - do these exist?
- `EDAC_S4ECD4ED`: Chipkill x4 devices
- `EDAC_S8ECD8ED`: Chipkill x8 devices
- `EDAC_S16ECD16ED`: Chipkill x16 devices

#### <a id="c-enum-scrub_type"></a>`enum scrub_type`

scrubbing capabilities

**Constants**

- `SCRUB_UNKNOWN`: Unknown if scrubber is available
- `SCRUB_NONE`: No scrubber
- `SCRUB_SW_PROG`: SW progressive (sequential) scrubbing
- `SCRUB_SW_SRC`: Software scrub only errors
- `SCRUB_SW_PROG_SRC`: Progressive software scrub from an error
- `SCRUB_SW_TUNABLE`: Software scrub frequency is tunable
- `SCRUB_HW_PROG`: HW progressive (sequential) scrubbing
- `SCRUB_HW_SRC`: Hardware scrub only errors
- `SCRUB_HW_PROG_SRC`: Progressive hardware scrub from an error
- `SCRUB_HW_TUNABLE`: Hardware scrub frequency is tunable

#### <a id="c-enum-edac_mc_layer_type"></a>`enum edac_mc_layer_type`

memory controller hierarchy layer

**Constants**

- `EDAC_MC_LAYER_BRANCH`: memory layer is named "branch"
- `EDAC_MC_LAYER_CHANNEL`: memory layer is named "channel"
- `EDAC_MC_LAYER_SLOT`: memory layer is named "slot"
- `EDAC_MC_LAYER_CHIP_SELECT`: memory layer is named "chip select"
- `EDAC_MC_LAYER_ALL_MEM`: memory layout is unknown. All memory is mapped
  as a single memory area. This is used when
  retrieving errors from a firmware driven driver.

**Description**

This enum is used by the drivers to tell edac_mc_sysfs what name should
be used when describing a memory stick location.

#### <a id="c-struct-edac_mc_layer"></a>`struct edac_mc_layer`

describes the memory controller hierarchy

**Definition**

```c
struct edac_mc_layer {
    enum edac_mc_layer_type type;
    unsigned size;
    bool is_virt_csrow;
};
```

**Members**

- `type`: layer type
- `size`: number of components per layer. For example,
  if the channel layer has two channels, size = 2
- `is_virt_csrow`: This layer is part of the "csrow" when old API
  compatibility mode is enabled. Otherwise, it is
  a channel

#### <a id="c-struct-rank_info"></a>`struct rank_info`

contains the information for one DIMM rank

**Definition**

```c
struct rank_info {
    int chan_idx;
    struct csrow_info *csrow;
    struct dimm_info *dimm;
    u32 ce_count;
};
```

**Members**

- `chan_idx`: channel number where the rank is (typically, 0 or 1)
- `csrow`: A pointer to the chip select row structure (the parent
  structure). The location of the rank is given by
  the (csrow->csrow_idx, chan_idx) vector.
- `dimm`: A pointer to the DIMM structure, where the DIMM label
  information is stored.
- `ce_count`: number of correctable errors for this rank

**Description**

- FIXME: Currently, the EDAC core model will assume one DIMM per rank.

  This is a bad assumption, but it makes this patch easier. Later
  patches in this series will fix this issue.

#### <a id="c-struct-edac_raw_error_desc"></a>`struct edac_raw_error_desc`

Raw error report structure

**Definition**

```c
struct edac_raw_error_desc {
    char location[LOCATION_SIZE];
    char label[(EDAC_MC_LABEL_LEN + 1 + sizeof(OTHER_LABEL)) * EDAC_MAX_LABELS];
    long grain;
    u16 error_count;
    enum hw_event_mc_err_type type;
    int top_layer;
    int mid_layer;
    int low_layer;
    unsigned long page_frame_number;
    unsigned long offset_in_page;
    unsigned long syndrome;
    const char *msg;
    const char *other_detail;
};
```

**Members**

- `location`: location of the error
- `label`: label of the affected DIMM(s)
- `grain`: minimum granularity for an error report, in bytes
- `error_count`: number of errors of the same type
- `type`: severity of the error (CE/UE/Fatal)
- `top_layer`: top layer of the error (layer\[0\])
- `mid_layer`: middle layer of the error (layer\[1\])
- `low_layer`: low layer of the error (layer\[2\])
- `page_frame_number`: page where the error happened
- `offset_in_page`: page offset
- `syndrome`: syndrome of the error (or 0 if unknown or if
  the syndrome is not applicable)
- `msg`: error message
- `other_detail`: other driver-specific detail about the error

#### <a id="c-edac_get_dimm"></a>`edac_get_dimm()`

```c
struct dimm_info * edac_get_dimm(struct mem_ctl_info *mci, int layer0, int layer1, int layer2)
```

Get DIMM info from a memory controller given by \[layer0,layer1,layer2\] position

**Parameters**

- `struct mem_ctl_info *mci`: MC descriptor struct mem_ctl_info
- `int layer0`: layer0 position
- `int layer1`: layer1 position. Unused if n_layers \< 2
- `int layer2`: layer2 position. Unused if n_layers \< 3

**Description**

For 1 layer, this function returns "dimms\[layer0\]";

For 2 layers, this function is similar to allocating a two-dimensional
array and returning "dimms\[layer0\]\[layer1\]";

For 3 layers, this function is similar to allocating a tri-dimensional
array and returning "dimms\[layer0\]\[layer1\]\[layer2\]";

#### <a id="c-struct-edac_scrub_ops"></a>`struct edac_scrub_ops`

scrub device operations (all elements optional)

**Definition**

```c
struct edac_scrub_ops {
    int (*read_addr)(struct device *dev, void *drv_data, u64 *base);
    int (*read_size)(struct device *dev, void *drv_data, u64 *size);
    int (*write_addr)(struct device *dev, void *drv_data, u64 base);
    int (*write_size)(struct device *dev, void *drv_data, u64 size);
    int (*get_enabled_bg)(struct device *dev, void *drv_data, bool *enable);
    int (*set_enabled_bg)(struct device *dev, void *drv_data, bool enable);
    int (*get_min_cycle)(struct device *dev, void *drv_data,  u32 *min);
    int (*get_max_cycle)(struct device *dev, void *drv_data,  u32 *max);
    int (*get_cycle_duration)(struct device *dev, void *drv_data, u32 *cycle);
    int (*set_cycle_duration)(struct device *dev, void *drv_data, u32 cycle);
};
```

**Members**

- `read_addr`: read base address of scrubbing range.
- `read_size`: read offset of scrubbing range.
- `write_addr`: set base address of the scrubbing range.
- `write_size`: set offset of the scrubbing range.
- `get_enabled_bg`: check if currently performing background scrub.
- `set_enabled_bg`: start or stop a bg-scrub.
- `get_min_cycle`: get minimum supported scrub cycle duration in seconds.
- `get_max_cycle`: get maximum supported scrub cycle duration in seconds.
- `get_cycle_duration`: get current scrub cycle duration in seconds.
- `set_cycle_duration`: set current scrub cycle duration in seconds.

#### <a id="c-struct-edac_ecs_ops"></a>`struct edac_ecs_ops`

ECS device operations (all elements optional)

**Definition**

```c
struct edac_ecs_ops {
    int (*get_log_entry_type)(struct device *dev, void *drv_data, int fru_id, u32 *val);
    int (*set_log_entry_type)(struct device *dev, void *drv_data, int fru_id, u32 val);
    int (*get_mode)(struct device *dev, void *drv_data, int fru_id, u32 *val);
    int (*set_mode)(struct device *dev, void *drv_data, int fru_id, u32 val);
    int (*reset)(struct device *dev, void *drv_data, int fru_id, u32 val);
    int (*get_threshold)(struct device *dev, void *drv_data, int fru_id, u32 *threshold);
    int (*set_threshold)(struct device *dev, void *drv_data, int fru_id, u32 threshold);
};
```

**Members**

- `get_log_entry_type`: read the log entry type value.
- `set_log_entry_type`: set the log entry type value.
- `get_mode`: read the mode value.
- `set_mode`: set the mode value.
- `reset`: reset the ECS counter.
- `get_threshold`: read the threshold count per gigabits of memory cells.
- `set_threshold`: set the threshold count per gigabits of memory cells.

#### <a id="c-struct-edac_mem_repair_ops"></a>`struct edac_mem_repair_ops`

memory repair operations (all elements are optional except do_repair, set_hpa/set_dpa)

**Definition**

```c
struct edac_mem_repair_ops {
    int (*get_repair_type)(struct device *dev, void *drv_data, const char **type);
    int (*get_persist_mode)(struct device *dev, void *drv_data, bool *persist);
    int (*set_persist_mode)(struct device *dev, void *drv_data, bool persist);
    int (*get_repair_safe_when_in_use)(struct device *dev, void *drv_data, bool *safe);
    int (*get_hpa)(struct device *dev, void *drv_data, u64 *hpa);
    int (*set_hpa)(struct device *dev, void *drv_data, u64 hpa);
    int (*get_min_hpa)(struct device *dev, void *drv_data, u64 *hpa);
    int (*get_max_hpa)(struct device *dev, void *drv_data, u64 *hpa);
    int (*get_dpa)(struct device *dev, void *drv_data, u64 *dpa);
    int (*set_dpa)(struct device *dev, void *drv_data, u64 dpa);
    int (*get_min_dpa)(struct device *dev, void *drv_data, u64 *dpa);
    int (*get_max_dpa)(struct device *dev, void *drv_data, u64 *dpa);
    int (*get_nibble_mask)(struct device *dev, void *drv_data, u32 *val);
    int (*set_nibble_mask)(struct device *dev, void *drv_data, u32 val);
    int (*get_bank_group)(struct device *dev, void *drv_data, u32 *val);
    int (*set_bank_group)(struct device *dev, void *drv_data, u32 val);
    int (*get_bank)(struct device *dev, void *drv_data, u32 *val);
    int (*set_bank)(struct device *dev, void *drv_data, u32 val);
    int (*get_rank)(struct device *dev, void *drv_data, u32 *val);
    int (*set_rank)(struct device *dev, void *drv_data, u32 val);
    int (*get_row)(struct device *dev, void *drv_data, u32 *val);
    int (*set_row)(struct device *dev, void *drv_data, u32 val);
    int (*get_column)(struct device *dev, void *drv_data, u32 *val);
    int (*set_column)(struct device *dev, void *drv_data, u32 val);
    int (*get_channel)(struct device *dev, void *drv_data, u32 *val);
    int (*set_channel)(struct device *dev, void *drv_data, u32 val);
    int (*get_sub_channel)(struct device *dev, void *drv_data, u32 *val);
    int (*set_sub_channel)(struct device *dev, void *drv_data, u32 val);
    int (*do_repair)(struct device *dev, void *drv_data, u32 val);
};
```

**Members**

- `get_repair_type`: get the memory repair type, listed in
  enum edac_mem_repair_function.
- `get_persist_mode`: get the current persist mode.
  false - Soft repair type (temporary repair).
  true - Hard memory repair type (permanent repair).
- `set_persist_mode`: set the persist mode of the memory repair instance.
- `get_repair_safe_when_in_use`: get whether memory media is accessible and
  data is retained during repair operation.
- `get_hpa`: get current host physical address (HPA) of memory to repair.
- `set_hpa`: set host physical address (HPA) of memory to repair.
- `get_min_hpa`: get the minimum supported host physical address (HPA).
- `get_max_hpa`: get the maximum supported host physical address (HPA).
- `get_dpa`: get current device physical address (DPA) of memory to repair.
- `set_dpa`: set device physical address (DPA) of memory to repair.
  In some states of system configuration (e.g. before address decoders
  have been configured), memory devices (e.g. CXL) may not have an active
  mapping in the host physical address map. As such, the memory
  to repair must be identified by a device specific physical addressing
  scheme using a device physical address(DPA). The DPA and other control
  attributes to use for the repair operations will be presented in related
  error records.
- `get_min_dpa`: get the minimum supported device physical address (DPA).
- `get_max_dpa`: get the maximum supported device physical address (DPA).
- `get_nibble_mask`: get current nibble mask of memory to repair.
- `set_nibble_mask`: set nibble mask of memory to repair.
- `get_bank_group`: get current bank group of memory to repair.
- `set_bank_group`: set bank group of memory to repair.
- `get_bank`: get current bank of memory to repair.
- `set_bank`: set bank of memory to repair.
- `get_rank`: get current rank of memory to repair.
- `set_rank`: set rank of memory to repair.
- `get_row`: get current row of memory to repair.
- `set_row`: set row of memory to repair.
- `get_column`: get current column of memory to repair.
- `set_column`: set column of memory to repair.
- `get_channel`: get current channel of memory to repair.
- `set_channel`: set channel of memory to repair.
- `get_sub_channel`: get current subchannel of memory to repair.
- `set_sub_channel`: set subchannel of memory to repair.
- `do_repair`: Issue memory repair operation for the HPA/DPA and
  other control attributes set for the memory to repair.

**Description**

All elements are optional except do_repair and at least one of set_hpa/set_dpa.



#### <a id="c-edac_mc_alloc"></a>`edac_mc_alloc()`

```c
struct mem_ctl_info * edac_mc_alloc(unsigned int mc_num, unsigned int n_layers, struct edac_mc_layer *layers, unsigned int sz_pvt)
```

Allocate and partially fill a struct `mem_ctl_info`.

**Parameters**

- `unsigned int mc_num`: Memory controller number
- `unsigned int n_layers`: Number of MC hierarchy layers
- `struct edac_mc_layer *layers`: Describes each layer as seen by the Memory Controller
- `unsigned int sz_pvt`: size of private storage needed

**Description**

Everything is kmalloc'ed as one big chunk - more efficient.
Only can be used if all structures have the same lifetime - otherwise
you have to allocate and initialize your own structures.

Use [`edac_mc_free()`](#c-edac_mc_free) to free mc structures allocated by this function.

> [!NOTE]
> drivers handle multi-rank memories in different ways: in some
> drivers, one multi-rank memory stick is mapped as one entry, while, in
> others, a single multi-rank memory stick would be mapped into several
> entries. Currently, this function will allocate multiple struct dimm_info
> on such scenarios, as grouping the multiple ranks require drivers change.

**Return**

On success, return a pointer to struct mem_ctl_info pointer;
`NULL` otherwise

#### <a id="c-edac_get_owner"></a>`edac_get_owner()`

```c
const char * edac_get_owner(void)
```

Return the owner's mod_name of EDAC MC

**Parameters**

- `void`: no arguments

**Return**

Pointer to mod_name string when EDAC MC is owned. NULL otherwise.

#### <a id="c-edac_mc_free"></a>`edac_mc_free()`

```c
void edac_mc_free(struct mem_ctl_info *mci)
```

Frees a previously allocated **mci** structure

**Parameters**

- `struct mem_ctl_info *mci`: pointer to a struct mem_ctl_info structure

#### <a id="c-edac_has_mcs"></a>`edac_has_mcs()`

```c
bool edac_has_mcs(void)
```

Check if any MCs have been allocated.

**Parameters**

- `void`: no arguments

**Return**

True if MC instances have been registered successfully.
False otherwise.

#### <a id="c-edac_mc_find"></a>`edac_mc_find()`

```c
struct mem_ctl_info * edac_mc_find(int idx)
```

Search for a mem_ctl_info structure whose index is **idx**.

**Parameters**

- `int idx`: index to be seek

**Description**

If found, return a pointer to the structure.
Else return NULL.

#### <a id="c-find_mci_by_dev"></a>`find_mci_by_dev()`

```c
struct mem_ctl_info * find_mci_by_dev(struct device *dev)
```

Scan list of controllers looking for the one that manages the **dev** device.

**Parameters**

- `struct device *dev`: pointer to a struct device related with the MCI

**Return**

on success, returns a pointer to struct `mem_ctl_info`;
`NULL` otherwise.

#### <a id="c-edac_mc_del_mc"></a>`edac_mc_del_mc()`

```c
struct mem_ctl_info * edac_mc_del_mc(struct device *dev)
```

Remove sysfs entries for mci structure associated with **dev** and remove mci structure from global list.

**Parameters**

- `struct device *dev`: Pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) representing mci structure to remove.

**Return**

pointer to removed mci structure, or `NULL` if device not found.

#### <a id="c-edac_mc_find_csrow_by_page"></a>`edac_mc_find_csrow_by_page()`

```c
int edac_mc_find_csrow_by_page(struct mem_ctl_info *mci, unsigned long page)
```

Ancillary routine to identify what csrow contains a memory page.

**Parameters**

- `struct mem_ctl_info *mci`: pointer to a struct mem_ctl_info structure
- `unsigned long page`: memory page to find

**Return**

on success, returns the csrow. -1 if not found.

#### <a id="c-edac_raw_mc_handle_error"></a>`edac_raw_mc_handle_error()`

```c
void edac_raw_mc_handle_error(struct edac_raw_error_desc *e)
```

Reports a memory event to userspace without doing anything to discover the error location.

**Parameters**

- `struct edac_raw_error_desc *e`: error description

**Description**

This raw function is used internally by [`edac_mc_handle_error()`](#c-edac_mc_handle_error). It should
only be called directly when the hardware error come directly from BIOS,
like in the case of APEI GHES driver.

#### <a id="c-edac_mc_handle_error"></a>`edac_mc_handle_error()`

```c
void edac_mc_handle_error(const enum hw_event_mc_err_type type, struct mem_ctl_info *mci, const u16 error_count, const unsigned long page_frame_number, const unsigned long offset_in_page, const unsigned long syndrome, const int top_layer, const int mid_layer, const int low_layer, const char *msg, const char *other_detail)
```

Reports a memory event to userspace.

**Parameters**

- `const enum hw_event_mc_err_type type`: severity of the error (CE/UE/Fatal)
- `struct mem_ctl_info *mci`: a struct mem_ctl_info pointer
- `const u16 error_count`: Number of errors of the same type
- `const unsigned long page_frame_number`: mem page where the error occurred
- `const unsigned long offset_in_page`: offset of the error inside the page
- `const unsigned long syndrome`: ECC syndrome
- `const int top_layer`: Memory layer\[0\] position
- `const int mid_layer`: Memory layer\[1\] position
- `const int low_layer`: Memory layer\[2\] position
- `const char *msg`: Message meaningful to the end users that
  explains the event
- `const char *other_detail`: Technical details about the event that
  may help hardware manufacturers and
  EDAC developers to analyse the event


<a id="rst-pci-controllers"></a>

## PCI Controllers

The EDAC subsystem provides a mechanism to handle PCI controllers by calling the `edac_pci_alloc_ctl_info()`. It will use the struct `edac_pci_ctl_info` to describe the PCI controllers.


#### <a id="c-edac_pci_alloc_ctl_info"></a>`edac_pci_alloc_ctl_info()`

```c
struct edac_pci_ctl_info * edac_pci_alloc_ctl_info(unsigned int sz_pvt, const char *edac_pci_name)
```

The `alloc()` function for the 'edac_pci' control info structure.

**Parameters**

- `unsigned int sz_pvt`: size of the private info at struct `edac_pci_ctl_info`
- `const char *edac_pci_name`: name of the PCI device

**Description**

The chip driver will allocate one of these for each
edac_pci it is going to control/register with the EDAC CORE.

**Return**

a pointer to struct `edac_pci_ctl_info` on success; `NULL` otherwise.

#### <a id="c-edac_pci_free_ctl_info"></a>`edac_pci_free_ctl_info()`

```c
void edac_pci_free_ctl_info(struct edac_pci_ctl_info *pci)
```

Last action on the pci control structure.

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to struct `edac_pci_ctl_info`

**Description**

Calls the remove sysfs information, which will unregister
this control struct's kobj. When that kobj's ref count
goes to zero, its release function will be call and then
[`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) the memory.

#### <a id="c-edac_pci_alloc_index"></a>`edac_pci_alloc_index()`

```c
int edac_pci_alloc_index(void)
```

Allocate a unique PCI index number

**Parameters**

- `void`: no arguments

**Return**

allocated index number

#### <a id="c-edac_pci_add_device"></a>`edac_pci_add_device()`

```c
int edac_pci_add_device(struct edac_pci_ctl_info *pci, int edac_idx)
```

Insert the 'edac_dev' structure into the edac_pci global list and create sysfs entries associated with edac_pci structure.

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to the edac_device structure to be added to the list
- `int edac_idx`: A unique numeric identifier to be assigned to the
  'edac_pci' structure.

**Return**

0 on Success, or an error code on failure

#### <a id="c-edac_pci_del_device"></a>`edac_pci_del_device()`

```c
struct edac_pci_ctl_info * edac_pci_del_device(struct device *dev)
```

**Parameters**

- `struct device *dev`: Pointer to 'struct device' representing edac_pci structure
  to remove

**Description**

Remove sysfs entries for specified edac_pci structure and
then remove edac_pci structure from global list

**Return**

Pointer to removed edac_pci structure,
or `NULL` if device not found

#### <a id="c-edac_pci_create_generic_ctl"></a>`edac_pci_create_generic_ctl()`

```c
struct edac_pci_ctl_info * edac_pci_create_generic_ctl(struct device *dev, const char *mod_name)
```

**Parameters**

- `struct device *dev`: pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device);
- `const char *mod_name`: name of the PCI device

**Description**

A generic constructor for a PCI parity polling device
Some systems have more than one domain of PCI busses.
For systems with one domain, then this API will
provide for a generic poller.

This routine calls the [`edac_pci_alloc_ctl_info()`](#c-edac_pci_alloc_ctl_info) for
the generic device, with default values

**Return**

Pointer to struct `edac_pci_ctl_info` on success, `NULL` on
failure.

#### <a id="c-edac_pci_release_generic_ctl"></a>`edac_pci_release_generic_ctl()`

```c
void edac_pci_release_generic_ctl(struct edac_pci_ctl_info *pci)
```

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to struct `edac_pci_ctl_info`

**Description**

The release function of a generic EDAC PCI polling device

#### <a id="c-edac_pci_create_sysfs"></a>`edac_pci_create_sysfs()`

```c
int edac_pci_create_sysfs(struct edac_pci_ctl_info *pci)
```

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to struct `edac_pci_ctl_info`

**Description**

Create the controls/attributes for the specified EDAC PCI device

#### <a id="c-edac_pci_remove_sysfs"></a>`edac_pci_remove_sysfs()`

```c
void edac_pci_remove_sysfs(struct edac_pci_ctl_info *pci)
```

**Parameters**

- `struct edac_pci_ctl_info *pci`: pointer to struct `edac_pci_ctl_info`

**Description**

remove the controls and attributes for this EDAC PCI device


<a id="rst-edac-blocks"></a>

## EDAC Blocks

The EDAC subsystem also provides a generic mechanism to report errors on other parts of the hardware via `edac_device_alloc_ctl_info()` function.

The structures `edac_dev_sysfs_block_attribute`, `edac_device_block`, `edac_device_instance` and `edac_device_ctl_info` provide a generic or abstract 'edac_device' representation at sysfs.

This set of structures and the code that implements the APIs for the same, provide for registering EDAC type devices which are NOT standard memory or PCI, like:

- CPU caches (L1 and L2)

- DMA engines

- Core CPU switches

- Fabric switch units

- PCIe interface controllers

- other EDAC/ECC type devices that can be monitored for errors, etc.

It allows for a 2 level set of hierarchy.

For example, a cache could be composed of L1, L2 and L3 levels of cache. Each CPU core would have its own L1 cache, while sharing L2 and maybe L3 caches. On such case, those can be represented via the following sysfs nodes:



```text
/sys/devices/system/edac/..

pci/            <existing pci directory (if available)>
mc/             <existing memory device directory>
cpu/cpu0/..     <L1 and L2 block directory>
        /L1-cache/ce_count
                 /ue_count
        /L2-cache/ce_count
                 /ue_count
cpu/cpu1/..     <L1 and L2 block directory>
        /L1-cache/ce_count
                 /ue_count
        /L2-cache/ce_count
                 /ue_count
...

the L1 and L2 directories would be "edac_device_block's"
```


#### <a id="c-edac_device_add_device"></a>`edac_device_add_device()`

```c
int edac_device_add_device(struct edac_device_ctl_info *edac_dev)
```

Insert the 'edac_dev' structure into the edac_device global list and create sysfs entries associated with edac_device structure.

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to edac_device structure to be added to the list
  'edac_device' structure.

**Return**

0 on Success, or an error code on failure

#### <a id="c-edac_device_del_device"></a>`edac_device_del_device()`

```c
struct edac_device_ctl_info * edac_device_del_device(struct device *dev)
```

Remove sysfs entries for specified edac_device structure and then remove edac_device structure from global list

**Parameters**

- `struct device *dev`: Pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) representing the edac device
  structure to remove.

**Return**

Pointer to removed edac_device structure,
or `NULL` if device not found.

#### <a id="c-edac_device_handle_ce_count"></a>`edac_device_handle_ce_count()`

```c
void edac_device_handle_ce_count(struct edac_device_ctl_info *edac_dev, unsigned int count, int inst_nr, int block_nr, const char *msg)
```

Log correctable errors.

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to struct `edac_device_ctl_info`
- `unsigned int count`: Number of errors to log.
- `int inst_nr`: number of the instance where the CE error happened
- `int block_nr`: number of the block where the CE error happened
- `const char *msg`: message to be printed

#### <a id="c-edac_device_handle_ue_count"></a>`edac_device_handle_ue_count()`

```c
void edac_device_handle_ue_count(struct edac_device_ctl_info *edac_dev, unsigned int count, int inst_nr, int block_nr, const char *msg)
```

Log uncorrectable errors.

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to struct `edac_device_ctl_info`
- `unsigned int count`: Number of errors to log.
- `int inst_nr`: number of the instance where the CE error happened
- `int block_nr`: number of the block where the CE error happened
- `const char *msg`: message to be printed

#### <a id="c-edac_device_handle_ce"></a>`edac_device_handle_ce()`

```c
void edac_device_handle_ce(struct edac_device_ctl_info *edac_dev, int inst_nr, int block_nr, const char *msg)
```

Log a single correctable error

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to struct `edac_device_ctl_info`
- `int inst_nr`: number of the instance where the CE error happened
- `int block_nr`: number of the block where the CE error happened
- `const char *msg`: message to be printed

#### <a id="c-edac_device_handle_ue"></a>`edac_device_handle_ue()`

```c
void edac_device_handle_ue(struct edac_device_ctl_info *edac_dev, int inst_nr, int block_nr, const char *msg)
```

Log a single uncorrectable error

**Parameters**

- `struct edac_device_ctl_info *edac_dev`: pointer to struct `edac_device_ctl_info`
- `int inst_nr`: number of the instance where the UE error happened
- `int block_nr`: number of the block where the UE error happened
- `const char *msg`: message to be printed

#### <a id="c-edac_device_alloc_index"></a>`edac_device_alloc_index()`

```c
int edac_device_alloc_index(void)
```

Allocate a unique device index number

**Parameters**

- `void`: no arguments

**Return**

allocated index number


<a id="rst-heterogeneous-system-support"></a>

## Heterogeneous system support

An AMD heterogeneous system is built by connecting the data fabrics of both CPUs and GPUs via custom xGMI links. Thus, the data fabric on the GPU nodes can be accessed the same way as the data fabric on CPU nodes.

The MI200 accelerators are data center GPUs. They have 2 data fabrics, and each GPU data fabric contains four Unified Memory Controllers (UMC). Each UMC contains eight channels. Each UMC channel controls one 128-bit HBM2e (2GB) channel (equivalent to 8 X 2GB ranks).  This creates a total of 4096-bits of DRAM data bus.

While the UMC is interfacing a 16GB (8high X 2GB DRAM) HBM stack, each UMC channel is interfacing 2GB of DRAM (represented as rank).

Memory controllers on AMD GPU nodes can be represented in EDAC thusly:

> GPU DF / GPU Node -&gt; EDAC MC GPU UMC           -&gt; EDAC CSROW GPU UMC channel   -&gt; EDAC CHANNEL

For example: a heterogeneous system with 1 AMD CPU is connected to 4 MI200 (Aldebaran) GPUs using xGMI.

Some more heterogeneous hardware details:

- The CPU UMC (Unified Memory Controller) is mostly the same as the GPU UMC. They have chip selects (csrows) and channels. However, the layouts are different for performance, physical layout, or other reasons.

- CPU UMCs use 1 channel, In this case UMC = EDAC channel. This follows the marketing speak. CPU has X memory channels, etc.

- CPU UMCs use up to 4 chip selects, So UMC chip select = EDAC CSROW.

- GPU UMCs use 1 chip select, So UMC = EDAC CSROW.

- GPU UMCs use 8 channels, So UMC channel = EDAC channel.

The EDAC subsystem provides a mechanism to handle AMD heterogeneous systems by calling system specific ops for both CPUs and GPUs.

AMD GPU nodes are enumerated in sequential order based on the PCI hierarchy, and the first GPU node is assumed to have a Node ID value following those of the CPU nodes after latter are fully populated:



```text
$ ls /sys/devices/system/edac/mc/
        mc0   - CPU MC node 0
        mc1  |
        mc2  |- GPU card[0] => node 0(mc1), node 1(mc2)
        mc3  |
        mc4  |- GPU card[1] => node 0(mc3), node 1(mc4)
        mc5  |
        mc6  |- GPU card[2] => node 0(mc5), node 1(mc6)
        mc7  |
        mc8  |- GPU card[3] => node 0(mc7), node 1(mc8)
```

For example, a heterogeneous system with one AMD CPU is connected to four MI200 (Aldebaran) GPUs using xGMI. This topology can be represented via the following sysfs entries:



```text
/sys/devices/system/edac/mc/..

CPU                     # CPU node
├── mc 0

GPU Nodes are enumerated sequentially after CPU nodes have been populated
GPU card 1              # Each MI200 GPU has 2 nodes/mcs
├── mc 1                # GPU node 0 == mc1, Each MC node has 4 UMCs/CSROWs
│   ├── csrow 0         # UMC 0
│   │   ├── channel 0   # Each UMC has 8 channels
│   │   ├── channel 1   # size of each channel is 2 GB, so each UMC has 16 GB
│   │   ├── channel 2
│   │   ├── channel 3
│   │   ├── channel 4
│   │   ├── channel 5
│   │   ├── channel 6
│   │   ├── channel 7
│   ├── csrow 1         # UMC 1
│   │   ├── channel 0
│   │   ├── ..
│   │   ├── channel 7
│   ├── ..              ..
│   ├── csrow 3         # UMC 3
│   │   ├── channel 0
│   │   ├── ..
│   │   ├── channel 7
│   ├── rank 0
│   ├── ..              ..
│   ├── rank 31         # total 32 ranks/dimms from 4 UMCs
├
├── mc 2                # GPU node 1 == mc2
│   ├── ..              # each GPU has total 64 GB

GPU card 2
├── mc 3
│   ├── ..
├── mc 4
│   ├── ..

GPU card 3
├── mc 5
│   ├── ..
├── mc 6
│   ├── ..

GPU card 4
├── mc 7
│   ├── ..
├── mc 8
│   ├── ..
```

---

# Extcon Device Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> The Extcon (External Connector) subsystem provides a unified framework for managing external connectors in Linux systems. It allows drivers to report the state of external connectors and provides a standardized interface for userspace to…

<a id="rst-extcon-device-subsystem"></a>

<a id="rst-overview"></a>

## Overview

The Extcon (External Connector) subsystem provides a unified framework for managing external connectors in Linux systems. It allows drivers to report the state of external connectors and provides a standardized interface for userspace to query and monitor these states.

Extcon is particularly useful in modern devices with multiple connectivity options, such as smartphones, tablets, and laptops. It helps manage various types of connectors, including:

1. USB connectors (e.g., USB-C, micro-USB)

2. Charging ports (e.g., fast charging, wireless charging)

3. Audio jacks (e.g., 3.5mm headphone jack)

4. Video outputs (e.g., HDMI, DisplayPort)

5. Docking stations

Real-world examples:

1. Smartphone USB-C port: A single USB-C port on a smartphone can serve multiple functions. Extcon can manage the different states of this port, such as: - USB data connection - Charging (various types like fast charging, USB Power Delivery) - Audio output (USB-C headphones) - Video output (USB-C to HDMI adapter)

2. Laptop docking station: When a laptop is connected to a docking station, multiple connections are made simultaneously. Extcon can handle the state changes for: - Power delivery - External displays - USB hub connections - Ethernet connectivity

3. Wireless charging pad: Extcon can manage the state of a wireless charging connection, allowing the system to respond appropriately when a device is placed on or removed from the charging pad.

4. Smart TV HDMI ports: In a smart TV, Extcon can manage multiple HDMI ports, detecting when devices are connected or disconnected, and potentially identifying the type of device (e.g., gaming console, set-top box, Blu-ray player).

The Extcon framework simplifies the development of drivers for these complex scenarios by providing a standardized way to report and query connector states, handle mutually exclusive connections, and manage connector properties. This allows for more robust and flexible handling of external connections in modern devices.

<a id="rst-key-components"></a>

## Key Components

<a id="rst-extcon-dev"></a>

### extcon_dev

The core structure representing an Extcon device:



```text
struct extcon_dev {
    const char *name;
    const unsigned int *supported_cable;
    const u32 *mutually_exclusive;

    /* Internal data */
    struct device dev;
    unsigned int id;
    struct raw_notifier_head nh_all;
    struct raw_notifier_head *nh;
    struct list_head entry;
    int max_supported;
    spinlock_t lock;
    u32 state;

    /* Sysfs related */
    struct device_type extcon_dev_type;
    struct extcon_cable *cables;
    struct attribute_group attr_g_muex;
    struct attribute **attrs_muex;
    struct device_attribute *d_attrs_muex;
};
```

Key fields:

- `name`: Name of the Extcon device

- `supported_cable`: Array of supported cable types

- `mutually_exclusive`: Array defining mutually exclusive cable types This field is crucial for enforcing hardware constraints. It's an array of 32-bit unsigned integers, where each element represents a set of mutually exclusive cable types. The array should be terminated with a 0.

  For example:



  ```text
  static const u32 mutually_exclusive[] = {
      BIT(0) | BIT(1),  /* Cable 0 and 1 are mutually exclusive */
      BIT(2) | BIT(3) | BIT(4),  /* Cables 2, 3, and 4 are mutually exclusive */
      0  /* Terminator */
  };
  ```

  In this example, cables 0 and 1 cannot be connected simultaneously, and cables 2, 3, and 4 are also mutually exclusive. This is useful for scenarios like a single port that can either be USB or HDMI, but not both at the same time.

  The Extcon core uses this information to prevent invalid combinations of cable states, ensuring that the reported states are always consistent with the hardware capabilities.

- `state`: Current state of the device (bitmap of connected cables)

<a id="rst-extcon-cable"></a>

### extcon_cable

Represents an individual cable managed by an Extcon device:



```text
struct extcon_cable {
    struct extcon_dev *edev;
    int cable_index;
    struct attribute_group attr_g;
    struct device_attribute attr_name;
    struct device_attribute attr_state;
    struct attribute *attrs[3];
    union extcon_property_value usb_propval[EXTCON_PROP_USB_CNT];
    union extcon_property_value chg_propval[EXTCON_PROP_CHG_CNT];
    union extcon_property_value jack_propval[EXTCON_PROP_JACK_CNT];
    union extcon_property_value disp_propval[EXTCON_PROP_DISP_CNT];
    DECLARE_BITMAP(usb_bits, EXTCON_PROP_USB_CNT);
    DECLARE_BITMAP(chg_bits, EXTCON_PROP_CHG_CNT);
    DECLARE_BITMAP(jack_bits, EXTCON_PROP_JACK_CNT);
    DECLARE_BITMAP(disp_bits, EXTCON_PROP_DISP_CNT);
};
```

<a id="rst-core-functions"></a>

## Core Functions


#### <a id="c-extcon_get_state"></a>`extcon_get_state()`

```c
int extcon_get_state(struct extcon_dev *edev, const unsigned int id)
```

Get the state of an external connector.

**Parameters**

- `struct extcon_dev *edev`: the extcon device
- `const unsigned int id`: the unique id indicating an external connector

**Description**

Returns 0 if success or error number if fail.



#### <a id="c-extcon_set_state"></a>`extcon_set_state()`

```c
int extcon_set_state(struct extcon_dev *edev, unsigned int id, bool state)
```

Set the state of an external connector.

**Parameters**

- `struct extcon_dev *edev`: the extcon device
- `unsigned int id`: the unique id indicating an external connector
- `bool state`: the new state of an external connector.
  the default semantics is true: attached / false: detached.

**Description**

Note that this function set the state of an external connector without
a notification. To synchronize the state of an external connector,
have to use [`extcon_set_state_sync()`](#c-extcon_set_state_sync) and `extcon_sync()`.

Returns 0 if success or error number if fail.



#### <a id="c-extcon_set_state_sync"></a>`extcon_set_state_sync()`

```c
int extcon_set_state_sync(struct extcon_dev *edev, unsigned int id, bool state)
```

Set the state of an external connector with sync.

**Parameters**

- `struct extcon_dev *edev`: the extcon device
- `unsigned int id`: the unique id indicating an external connector
- `bool state`: the new state of external connector.
  the default semantics is true: attached / false: detached.

**Description**

Note that this function set the state of external connector
and synchronize the state by sending a notification.

Returns 0 if success or error number if fail.



#### <a id="c-extcon_get_property"></a>`extcon_get_property()`

```c
int extcon_get_property(struct extcon_dev *edev, unsigned int id, unsigned int prop, union extcon_property_value *prop_val)
```

Get the property value of an external connector.

**Parameters**

- `struct extcon_dev *edev`: the extcon device
- `unsigned int id`: the unique id indicating an external connector
- `unsigned int prop`: the property id indicating an extcon property
- `union extcon_property_value *prop_val`: the pointer which store the value of extcon property

**Description**

Note that when getting the property value of external connector,
the external connector should be attached. If detached state, function
return 0 without property value. Also, the each property should be
included in the list of supported properties according to extcon type.

Returns 0 if success or error number if fail.


<a id="rst-sysfs-interface"></a>

## Sysfs Interface

Extcon devices expose the following sysfs attributes:

- `name`: Name of the Extcon device

- `state`: Current state of all supported cables

- `cable.N/name`: Name of the Nth supported cable

- `cable.N/state`: State of the Nth supported cable

<a id="rst-usage-example"></a>

### Usage Example



```c
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/extcon.h>

struct my_extcon_data {
    struct extcon_dev *edev;
    struct device *dev;
};

static const unsigned int my_extcon_cable[] = {
    EXTCON_USB,
    EXTCON_USB_HOST,
    EXTCON_NONE,
};

static int my_extcon_probe(struct platform_device *pdev)
{
    struct my_extcon_data *data;
    int ret;

    data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
    if (!data)
        return -ENOMEM;

    data->dev = &pdev->dev;

    /* Initialize extcon device */
    data->edev = devm_extcon_dev_allocate(data->dev, my_extcon_cable);
    if (IS_ERR(data->edev)) {
        dev_err(data->dev, "Failed to allocate extcon device\n");
        return PTR_ERR(data->edev);
    }

    /* Register extcon device */
    ret = devm_extcon_dev_register(data->dev, data->edev);
    if (ret < 0) {
        dev_err(data->dev, "Failed to register extcon device\n");
        return ret;
    }

    platform_set_drvdata(pdev, data);

    /* Example: Set initial state */
    extcon_set_state_sync(data->edev, EXTCON_USB, true);

    dev_info(data->dev, "My extcon driver probed successfully\n");
    return 0;
}

static int my_extcon_remove(struct platform_device *pdev)
{
    struct my_extcon_data *data = platform_get_drvdata(pdev);

    /* Example: Clear state before removal */
    extcon_set_state_sync(data->edev, EXTCON_USB, false);

    dev_info(data->dev, "My extcon driver removed\n");
    return 0;
}

static const struct of_device_id my_extcon_of_match[] = {
    { .compatible = "my,extcon-device", },
    { },
};
MODULE_DEVICE_TABLE(of, my_extcon_of_match);

static struct platform_driver my_extcon_driver = {
    .driver = {
        .name = "my-extcon-driver",
        .of_match_table = my_extcon_of_match,
    },
    .probe = my_extcon_probe,
    .remove = my_extcon_remove,
};

module_platform_driver(my_extcon_driver);
```

<a id="rst-this-example-demonstrates"></a>

### This example demonstrates:

- Defining supported cable types (USB and USB Host in this case).

- Allocating and registering an extcon device.

- Setting an initial state for a cable (USB connected in this example).

- Clearing the state when the driver is removed.

---

# Generic Counter Interface

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Counter devices are prevalent among a diverse spectrum of industries. The ubiquitous presence of these devices necessitates a common interface and standard of interaction and exposure. This driver API attempts to resolve the issue of…

<a id="rst-generic-counter-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

Counter devices are prevalent among a diverse spectrum of industries. The ubiquitous presence of these devices necessitates a common interface and standard of interaction and exposure. This driver API attempts to resolve the issue of duplicate code found among existing counter device drivers by introducing a generic counter interface for consumption. The Generic Counter interface enables drivers to support and expose a common set of components and functionality present in counter devices.

<a id="rst-theory"></a>

## Theory

Counter devices can vary greatly in design, but regardless of whether some devices are quadrature encoder counters or tally counters, all counter devices consist of a core set of components. This core set of components, shared by all counter devices, is what forms the essence of the Generic Counter interface.

There are three core components to a counter:

- Signal: Stream of data to be evaluated by the counter.

- Synapse: Association of a Signal, and evaluation trigger, with a Count.

- Count: Accumulation of the effects of connected Synapses.

<a id="rst-signal"></a>

### SIGNAL

A Signal represents a stream of data. This is the input data that is evaluated by the counter to determine the count data; e.g. a quadrature signal output line of a rotary encoder. Not all counter devices provide user access to the Signal data, so exposure is optional for drivers.

When the Signal data is available for user access, the Generic Counter interface provides the following available signal values:

- SIGNAL_LOW: Signal line is in a low state.

- SIGNAL_HIGH: Signal line is in a high state.

A Signal may be associated with one or more Counts.

<a id="rst-synapse"></a>

### SYNAPSE

A Synapse represents the association of a Signal with a Count. Signal data affects respective Count data, and the Synapse represents this relationship.

The Synapse action mode specifies the Signal data condition that triggers the respective Count's count function evaluation to update the count data. The Generic Counter interface provides the following available action modes:

- None: Signal does not trigger the count function. In Pulse-Direction count function mode, this Signal is evaluated as Direction.

- Rising Edge: Low state transitions to high state.

- Falling Edge: High state transitions to low state.

- Both Edges: Any state transition.

A counter is defined as a set of input signals associated with count data that are generated by the evaluation of the state of the associated input signals as defined by the respective count functions. Within the context of the Generic Counter interface, a counter consists of Counts each associated with a set of Signals, whose respective Synapse instances represent the count function update conditions for the associated Counts.

A Synapse associates one Signal with one Count.

<a id="rst-count"></a>

### COUNT

A Count represents the accumulation of the effects of connected Synapses; i.e. the count data for a set of Signals. The Generic Counter interface represents the count data as a natural number.

A Count has a count function mode which represents the update behavior for the count data. The Generic Counter interface provides the following available count function modes:

- Increase: Accumulated count is incremented.

- Decrease: Accumulated count is decremented.

- Pulse-Direction: Rising edges on signal A updates the respective count. The input level of signal B determines direction.

- Quadrature: A pair of quadrature encoding signals are evaluated to determine position and direction. The following Quadrature modes are available:

  - x1 A: If direction is forward, rising edges on quadrature pair signal A updates the respective count; if the direction is backward, falling edges on quadrature pair signal A updates the respective count. Quadrature encoding determines the direction.

  - x1 B: If direction is forward, rising edges on quadrature pair signal B updates the respective count; if the direction is backward, falling edges on quadrature pair signal B updates the respective count. Quadrature encoding determines the direction.

  - x2 A: Any state transition on quadrature pair signal A updates the respective count. Quadrature encoding determines the direction.

  - x2 B: Any state transition on quadrature pair signal B updates the respective count. Quadrature encoding determines the direction.

  - x4: Any state transition on either quadrature pair signals updates the respective count. Quadrature encoding determines the direction.

A Count has a set of one or more associated Synapses.

<a id="rst-paradigm"></a>

## Paradigm

The most basic counter device may be expressed as a single Count associated with a single Signal via a single Synapse. Take for example a counter device which simply accumulates a count of rising edges on a source input line:



```text
        Count                Synapse        Signal
        -----                -------        ------
+---------------------+
| Data: Count         |    Rising Edge     ________
| Function: Increase  |  <-------------   / Source \
|                     |                  ____________
+---------------------+
```

In this example, the Signal is a source input line with a pulsing voltage, while the Count is a persistent count value which is repeatedly incremented. The Signal is associated with the respective Count via a Synapse. The increase function is triggered by the Signal data condition specified by the Synapse -- in this case a rising edge condition on the voltage input line. In summary, the counter device existence and behavior is aptly represented by respective Count, Signal, and Synapse components: a rising edge condition triggers an increase function on an accumulating count datum.

A counter device is not limited to a single Signal; in fact, in theory many Signals may be associated with even a single Count. For example, a quadrature encoder counter device can keep track of position based on the states of two input lines:



```text
           Count                 Synapse     Signal
           -----                 -------     ------
+-------------------------+
| Data: Position          |    Both Edges     ___
| Function: Quadrature x4 |  <------------   / A \
|                         |                 _______
|                         |
|                         |    Both Edges     ___
|                         |  <------------   / B \
|                         |                 _______
+-------------------------+
```

In this example, two Signals (quadrature encoder lines A and B) are associated with a single Count: a rising or falling edge on either A or B triggers the "Quadrature x4" function which determines the direction of movement and updates the respective position data. The "Quadrature x4" function is likely implemented in the hardware of the quadrature encoder counter device; the Count, Signals, and Synapses simply represent this hardware behavior and functionality.

Signals associated with the same Count can have differing Synapse action mode conditions. For example, a quadrature encoder counter device operating in a non-quadrature Pulse-Direction mode could have one input line dedicated for movement and a second input line dedicated for direction:



```text
           Count                   Synapse      Signal
           -----                   -------      ------
+---------------------------+
| Data: Position            |    Rising Edge     ___
| Function: Pulse-Direction |  <-------------   / A \ (Movement)
|                           |                  _______
|                           |
|                           |       None         ___
|                           |  <-------------   / B \ (Direction)
|                           |                  _______
+---------------------------+
```

Only Signal A triggers the "Pulse-Direction" update function, but the instantaneous state of Signal B is still required in order to know the direction so that the position data may be properly updated. Ultimately, both Signals are associated with the same Count via two respective Synapses, but only one Synapse has an active action mode condition which triggers the respective count function while the other is left with a "None" condition action mode to indicate its respective Signal's availability for state evaluation despite its non-triggering mode.

Keep in mind that the Signal, Synapse, and Count are abstract representations which do not need to be closely married to their respective physical sources. This allows the user of a counter to divorce themselves from the nuances of physical components (such as whether an input line is differential or single-ended) and instead focus on the core idea of what the data and process represent (e.g. position as interpreted from quadrature encoding data).

<a id="rst-driver-api"></a>

## Driver API

Driver authors may utilize the Generic Counter interface in their code by including the include/linux/counter.h header file. This header file provides several core data structures, function prototypes, and macros for defining a counter device.


#### <a id="c-struct-counter_comp"></a>`struct counter_comp`

Counter component node

**Definition**

```c
struct counter_comp {
    enum counter_comp_type type;
    const char *name;
    void *priv;
    union {
        int (*action_read)(struct counter_device *counter, struct counter_count *count, struct counter_synapse *synapse, enum counter_synapse_action *action);
        int (*device_u8_read)(struct counter_device *counter, u8 *val);
        int (*count_u8_read)(struct counter_device *counter, struct counter_count *count, u8 *val);
        int (*signal_u8_read)(struct counter_device *counter, struct counter_signal *signal, u8 *val);
        int (*device_u32_read)(struct counter_device *counter, u32 *val);
        int (*count_u32_read)(struct counter_device *counter, struct counter_count *count, u32 *val);
        int (*signal_u32_read)(struct counter_device *counter, struct counter_signal *signal, u32 *val);
        int (*device_u64_read)(struct counter_device *counter, u64 *val);
        int (*count_u64_read)(struct counter_device *counter, struct counter_count *count, u64 *val);
        int (*signal_u64_read)(struct counter_device *counter, struct counter_signal *signal, u64 *val);
        int (*signal_array_u32_read)(struct counter_device *counter, struct counter_signal *signal, size_t idx, u32 *val);
        int (*device_array_u64_read)(struct counter_device *counter, size_t idx, u64 *val);
        int (*count_array_u64_read)(struct counter_device *counter, struct counter_count *count, size_t idx, u64 *val);
        int (*signal_array_u64_read)(struct counter_device *counter, struct counter_signal *signal, size_t idx, u64 *val);
    };
    union {
        int (*action_write)(struct counter_device *counter, struct counter_count *count, struct counter_synapse *synapse, enum counter_synapse_action action);
        int (*device_u8_write)(struct counter_device *counter, u8 val);
        int (*count_u8_write)(struct counter_device *counter, struct counter_count *count, u8 val);
        int (*signal_u8_write)(struct counter_device *counter, struct counter_signal *signal, u8 val);
        int (*device_u32_write)(struct counter_device *counter, u32 val);
        int (*count_u32_write)(struct counter_device *counter, struct counter_count *count, u32 val);
        int (*signal_u32_write)(struct counter_device *counter, struct counter_signal *signal, u32 val);
        int (*device_u64_write)(struct counter_device *counter, u64 val);
        int (*count_u64_write)(struct counter_device *counter, struct counter_count *count, u64 val);
        int (*signal_u64_write)(struct counter_device *counter, struct counter_signal *signal, u64 val);
        int (*signal_array_u32_write)(struct counter_device *counter, struct counter_signal *signal, size_t idx, u32 val);
        int (*device_array_u64_write)(struct counter_device *counter, size_t idx, u64 val);
        int (*count_array_u64_write)(struct counter_device *counter, struct counter_count *count, size_t idx, u64 val);
        int (*signal_array_u64_write)(struct counter_device *counter, struct counter_signal *signal, size_t idx, u64 val);
    };
};
```

**Members**

- `type`: Counter component data type
- `name`: device-specific component name
- `priv`: component-relevant data
- `{unnamed_union}`: anonymous
- `action_read`: Synapse action mode read callback. The read value of the
  respective Synapse action mode should be passed back via
  the action parameter.
- `device_u8_read`: Device u8 component read callback. The read value of the
  respective Device u8 component should be passed back via
  the val parameter.
- `count_u8_read`: Count u8 component read callback. The read value of the
  respective Count u8 component should be passed back via
  the val parameter.
- `signal_u8_read`: Signal u8 component read callback. The read value of the
  respective Signal u8 component should be passed back via
  the val parameter.
- `device_u32_read`: Device u32 component read callback. The read value of
  the respective Device u32 component should be passed
  back via the val parameter.
- `count_u32_read`: Count u32 component read callback. The read value of the
  respective Count u32 component should be passed back via
  the val parameter.
- `signal_u32_read`: Signal u32 component read callback. The read value of
  the respective Signal u32 component should be passed
  back via the val parameter.
- `device_u64_read`: Device u64 component read callback. The read value of
  the respective Device u64 component should be passed
  back via the val parameter.
- `count_u64_read`: Count u64 component read callback. The read value of the
  respective Count u64 component should be passed back via
  the val parameter.
- `signal_u64_read`: Signal u64 component read callback. The read value of
  the respective Signal u64 component should be passed
  back via the val parameter.
- `signal_array_u32_read`: Signal u32 array component read callback. The
  index of the respective Count u32 array
  component element is passed via the idx
  parameter. The read value of the respective
  Count u32 array component element should be
  passed back via the val parameter.
- `device_array_u64_read`: Device u64 array component read callback. The
  index of the respective Device u64 array
  component element is passed via the idx
  parameter. The read value of the respective
  Device u64 array component element should be
  passed back via the val parameter.
- `count_array_u64_read`: Count u64 array component read callback. The
  index of the respective Count u64 array
  component element is passed via the idx
  parameter. The read value of the respective
  Count u64 array component element should be
  passed back via the val parameter.
- `signal_array_u64_read`: Signal u64 array component read callback. The
  index of the respective Count u64 array
  component element is passed via the idx
  parameter. The read value of the respective
  Count u64 array component element should be
  passed back via the val parameter.
- `{unnamed_union}`: anonymous
- `action_write`: Synapse action mode write callback. The write value of
  the respective Synapse action mode is passed via the
  action parameter.
- `device_u8_write`: Device u8 component write callback. The write value of
  the respective Device u8 component is passed via the val
  parameter.
- `count_u8_write`: Count u8 component write callback. The write value of
  the respective Count u8 component is passed via the val
  parameter.
- `signal_u8_write`: Signal u8 component write callback. The write value of
  the respective Signal u8 component is passed via the val
  parameter.
- `device_u32_write`: Device u32 component write callback. The write value of
  the respective Device u32 component is passed via the
  val parameter.
- `count_u32_write`: Count u32 component write callback. The write value of
  the respective Count u32 component is passed via the val
  parameter.
- `signal_u32_write`: Signal u32 component write callback. The write value of
  the respective Signal u32 component is passed via the
  val parameter.
- `device_u64_write`: Device u64 component write callback. The write value of
  the respective Device u64 component is passed via the
  val parameter.
- `count_u64_write`: Count u64 component write callback. The write value of
  the respective Count u64 component is passed via the val
  parameter.
- `signal_u64_write`: Signal u64 component write callback. The write value of
  the respective Signal u64 component is passed via the
  val parameter.
- `signal_array_u32_write`: Signal u32 array component write callback. The
  index of the respective Signal u32 array
  component element is passed via the idx
  parameter. The write value of the respective
  Signal u32 array component element is passed via
  the val parameter.
- `device_array_u64_write`: Device u64 array component write callback. The
  index of the respective Device u64 array
  component element is passed via the idx
  parameter. The write value of the respective
  Device u64 array component element is passed via
  the val parameter.
- `count_array_u64_write`: Count u64 array component write callback. The
  index of the respective Count u64 array
  component element is passed via the idx
  parameter. The write value of the respective
  Count u64 array component element is passed via
  the val parameter.
- `signal_array_u64_write`: Signal u64 array component write callback. The
  index of the respective Signal u64 array
  component element is passed via the idx
  parameter. The write value of the respective
  Signal u64 array component element is passed via
  the val parameter.

#### <a id="c-struct-counter_signal"></a>`struct counter_signal`

Counter Signal node

**Definition**

```c
struct counter_signal {
    int id;
    const char *name;
    struct counter_comp *ext;
    size_t num_ext;
};
```

**Members**

- `id`: unique ID used to identify the Signal
- `name`: device-specific Signal name
- `ext`: optional array of Signal extensions
- `num_ext`: number of Signal extensions specified in **ext**

#### <a id="c-struct-counter_synapse"></a>`struct counter_synapse`

Counter Synapse node

**Definition**

```c
struct counter_synapse {
    const enum counter_synapse_action *actions_list;
    size_t num_actions;
    struct counter_signal *signal;
};
```

**Members**

- `actions_list`: array of available action modes
- `num_actions`: number of action modes specified in **actions_list**
- `signal`: pointer to the associated Signal

#### <a id="c-struct-counter_count"></a>`struct counter_count`

Counter Count node

**Definition**

```c
struct counter_count {
    int id;
    const char *name;
    const enum counter_function *functions_list;
    size_t num_functions;
    struct counter_synapse *synapses;
    size_t num_synapses;
    struct counter_comp *ext;
    size_t num_ext;
};
```

**Members**

- `id`: unique ID used to identify the Count
- `name`: device-specific Count name
- `functions_list`: array of available function modes
- `num_functions`: number of function modes specified in **functions_list**
- `synapses`: array of Synapses for initialization
- `num_synapses`: number of Synapses specified in **synapses**
- `ext`: optional array of Count extensions
- `num_ext`: number of Count extensions specified in **ext**

#### <a id="c-struct-counter_event_node"></a>`struct counter_event_node`

Counter Event node

**Definition**

```c
struct counter_event_node {
    struct list_head l;
    u8 event;
    u8 channel;
    struct list_head comp_list;
};
```

**Members**

- `l`: list of current watching Counter events
- `event`: event that triggers
- `channel`: event channel
- `comp_list`: list of components to watch when event triggers

#### <a id="c-struct-counter_ops"></a>`struct counter_ops`

Callbacks from driver

**Definition**

```c
struct counter_ops {
    int (*signal_read)(struct counter_device *counter, struct counter_signal *signal, enum counter_signal_level *level);
    int (*count_read)(struct counter_device *counter, struct counter_count *count, u64 *value);
    int (*count_write)(struct counter_device *counter, struct counter_count *count, u64 value);
    int (*function_read)(struct counter_device *counter, struct counter_count *count, enum counter_function *function);
    int (*function_write)(struct counter_device *counter, struct counter_count *count, enum counter_function function);
    int (*action_read)(struct counter_device *counter, struct counter_count *count, struct counter_synapse *synapse, enum counter_synapse_action *action);
    int (*action_write)(struct counter_device *counter, struct counter_count *count, struct counter_synapse *synapse, enum counter_synapse_action action);
    int (*events_configure)(struct counter_device *counter);
    int (*watch_validate)(struct counter_device *counter, const struct counter_watch *watch);
};
```

**Members**

- `signal_read`: optional read callback for Signals. The read level of
  the respective Signal should be passed back via the
  level parameter.
- `count_read`: read callback for Counts. The read value of the
  respective Count should be passed back via the value
  parameter.
- `count_write`: optional write callback for Counts. The write value for
  the respective Count is passed in via the value
  parameter.
- `function_read`: read callback the Count function modes. The read
  function mode of the respective Count should be passed
  back via the function parameter.
- `function_write`: optional write callback for Count function modes. The
  function mode to write for the respective Count is
  passed in via the function parameter.
- `action_read`: optional read callback the Synapse action modes. The
  read action mode of the respective Synapse should be
  passed back via the action parameter.
- `action_write`: optional write callback for Synapse action modes. The
  action mode to write for the respective Synapse is
  passed in via the action parameter.
- `events_configure`: optional write callback to configure events. The list of
  struct counter_event_node may be accessed via the
  events_list member of the counter parameter.
- `watch_validate`: optional callback to validate a watch. The Counter
  component watch configuration is passed in via the watch
  parameter. A return value of 0 indicates a valid Counter
  component watch configuration.

#### <a id="c-struct-counter_device"></a>`struct counter_device`

Counter data structure

**Definition**

```c
struct counter_device {
    const char *name;
    struct device *parent;
    const struct counter_ops *ops;
    struct counter_signal *signals;
    size_t num_signals;
    struct counter_count *counts;
    size_t num_counts;
    struct counter_comp *ext;
    size_t num_ext;
    struct device dev;
    struct cdev chrdev;
    struct list_head events_list;
    spinlock_t events_list_lock;
    struct list_head next_events_list;
    struct mutex n_events_list_lock;
    struct counter_event *events;
    wait_queue_head_t events_wait;
    spinlock_t events_in_lock;
    struct mutex events_out_lock;
    struct mutex ops_exist_lock;
};
```

**Members**

- `name`: name of the device
- `parent`: optional parent device providing the counters
- `ops`: callbacks from driver
- `signals`: array of Signals
- `num_signals`: number of Signals specified in **signals**
- `counts`: array of Counts
- `num_counts`: number of Counts specified in **counts**
- `ext`: optional array of Counter device extensions
- `num_ext`: number of Counter device extensions specified in **ext**
- `dev`: internal device structure
- `chrdev`: internal character device structure
- `events_list`: list of current watching Counter events
- `events_list_lock`: lock to protect Counter events list operations
- `next_events_list`: list of next watching Counter events
- `n_events_list_lock`: lock to protect Counter next events list operations
- `events`: queue of detected Counter events
- `events_wait`: wait queue to allow blocking reads of Counter events
- `events_in_lock`: lock to protect Counter events queue in operations
- `events_out_lock`: lock to protect Counter events queue out operations
- `ops_exist_lock`: lock to prevent use during removal



#### <a id="c-counter_priv"></a>`counter_priv()`

```c
void * counter_priv(const struct counter_device *const counter)
```

access counter device private data

**Parameters**

- `const struct counter_device *const counter`: counter device

**Description**

Get the counter device private data

#### <a id="c-counter_alloc"></a>`counter_alloc()`

```c
struct counter_device * counter_alloc(size_t sizeof_priv)
```

allocate a counter_device

**Parameters**

- `size_t sizeof_priv`: size of the driver private data

**Description**

This is part one of counter registration. The structure is allocated
dynamically to ensure the right lifetime for the embedded struct device.

If this succeeds, call `counter_put()` to get rid of the counter_device again.

#### <a id="c-counter_add"></a>`counter_add()`

```c
int counter_add(struct counter_device *counter)
```

complete registration of a counter

**Parameters**

- `struct counter_device *counter`: the counter to add

**Description**

This is part two of counter registration.

If this succeeds, call [`counter_unregister()`](#c-counter_unregister) to get rid of the counter_device again.

#### <a id="c-counter_unregister"></a>`counter_unregister()`

```c
void counter_unregister(struct counter_device *const counter)
```

unregister Counter from the system

**Parameters**

- `struct counter_device *const counter`: pointer to Counter to unregister

**Description**

The Counter is unregistered from the system.

#### <a id="c-devm_counter_alloc"></a>`devm_counter_alloc()`

```c
struct counter_device * devm_counter_alloc(struct device *dev, size_t sizeof_priv)
```

allocate a counter_device

**Parameters**

- `struct device *dev`: the device to register the release callback for
- `size_t sizeof_priv`: size of the driver private data

**Description**

This is the device managed version of [`counter_add()`](#c-counter_add). It registers a cleanup
callback to care for calling `counter_put()`.

#### <a id="c-devm_counter_add"></a>`devm_counter_add()`

```c
int devm_counter_add(struct device *dev, struct counter_device *const counter)
```

complete registration of a counter

**Parameters**

- `struct device *dev`: the device to register the release callback for
- `struct counter_device *const counter`: the counter to add

**Description**

This is the device managed version of [`counter_add()`](#c-counter_add). It registers a cleanup
callback to care for calling [`counter_unregister()`](#c-counter_unregister).



#### <a id="c-counter_push_event"></a>`counter_push_event()`

```c
void counter_push_event(struct counter_device *const counter, const u8 event, const u8 channel)
```

queue event for userspace reading

**Parameters**

- `struct counter_device *const counter`: pointer to Counter structure
- `const u8 event`: triggered event
- `const u8 channel`: event channel

**Note**

If no one is watching for the respective event, it is silently
discarded.


<a id="rst-driver-implementation"></a>

## Driver Implementation

To support a counter device, a driver must first allocate the available Counter Signals via counter_signal structures. These Signals should be stored as an array and set to the signals array member of an allocated counter_device structure before the Counter is registered to the system.

Counter Counts may be allocated via counter_count structures, and respective Counter Signal associations (Synapses) made via counter_synapse structures. Associated counter_synapse structures are stored as an array and set to the synapses array member of the respective counter_count structure. These counter_count structures are set to the counts array member of an allocated counter_device structure before the Counter is registered to the system.

Driver callbacks must be provided to the counter_device structure in order to communicate with the device: to read and write various Signals and Counts, and to set and get the "action mode" and "function mode" for various Synapses and Counts respectively.

A counter_device structure is allocated using counter_alloc() and then registered to the system by passing it to the counter_add() function, and unregistered by passing it to the counter_unregister function. There are device managed variants of these functions: devm_counter_alloc() and devm_counter_add().

The struct counter_comp structure is used to define counter extensions for Signals, Synapses, and Counts.

The "type" member specifies the type of high-level data (e.g. BOOL, COUNT_DIRECTION, etc.) handled by this extension. The "`*_read`" and "`*_write`" members can then be set by the counter device driver with callbacks to handle that data using native C data types (i.e. u8, u64, etc.).

Convenience macros such as `COUNTER_COMP_COUNT_U64` are provided for use by driver authors. In particular, driver authors are expected to use the provided macros for standard Counter subsystem attributes in order to maintain a consistent interface for userspace. For example, a counter device driver may define several standard attributes like so:



```text
struct counter_comp count_ext[] = {
        COUNTER_COMP_DIRECTION(count_direction_read),
        COUNTER_COMP_ENABLE(count_enable_read, count_enable_write),
        COUNTER_COMP_CEILING(count_ceiling_read, count_ceiling_write),
};
```

This makes it simple to see, add, and modify the attributes that are supported by this driver ("direction", "enable", and "ceiling") and to maintain this code without getting lost in a web of struct braces.

Callbacks must match the function type expected for the respective component or extension. These function types are defined in the struct counter_comp structure as the "`*_read`" and "`*_write`" union members.

The corresponding callback prototypes for the extensions mentioned in the previous example above would be:



```text
int count_direction_read(struct counter_device *counter,
                         struct counter_count *count,
                         enum counter_count_direction *direction);
int count_enable_read(struct counter_device *counter,
                      struct counter_count *count, u8 *enable);
int count_enable_write(struct counter_device *counter,
                       struct counter_count *count, u8 enable);
int count_ceiling_read(struct counter_device *counter,
                       struct counter_count *count, u64 *ceiling);
int count_ceiling_write(struct counter_device *counter,
                        struct counter_count *count, u64 ceiling);
```

Determining the type of extension to create is a matter of scope.

- Signal extensions are attributes that expose information/control specific to a Signal. These types of attributes will exist under a Signal's directory in sysfs.

  For example, if you have an invert feature for a Signal, you can have a Signal extension called "invert" that toggles that feature: /sys/bus/counter/devices/counterX/signalY/invert

- Count extensions are attributes that expose information/control specific to a Count. These type of attributes will exist under a Count's directory in sysfs.

  For example, if you want to pause/unpause a Count from updating, you can have a Count extension called "enable" that toggles such: /sys/bus/counter/devices/counterX/countY/enable

- Device extensions are attributes that expose information/control non-specific to a particular Count or Signal. This is where you would put your global features or other miscellaneous functionality.

  For example, if your device has an overtemp sensor, you can report the chip overheated via a device extension called "error_overtemp": /sys/bus/counter/devices/counterX/error_overtemp

<a id="rst-subsystem-architecture"></a>

## Subsystem Architecture

Counter drivers pass and take data natively (i.e. `u8`, `u64`, etc.) and the shared counter module handles the translation between the sysfs interface. This guarantees a standard userspace interface for all counter drivers, and enables a Generic Counter chrdev interface via a generalized device driver ABI.

A high-level view of how a count value is passed down from a counter driver is exemplified by the following. The driver callbacks are first registered to the Counter core component for use by the Counter userspace interface components:



```text
Driver callbacks registration:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                +----------------------------+
                | Counter device driver      |
                +----------------------------+
                | Processes data from device |
                +----------------------------+
                        |
                 -------------------
                / driver callbacks /
                -------------------
                        |
                        V
                +----------------------+
                | Counter core         |
                +----------------------+
                | Routes device driver |
                | callbacks to the     |
                | userspace interfaces |
                +----------------------+
                        |
                 -------------------
                / driver callbacks /
                -------------------
                        |
        +---------------+---------------+
        |                               |
        V                               V
+--------------------+          +---------------------+
| Counter sysfs      |          | Counter chrdev      |
+--------------------+          +---------------------+
| Translates to the  |          | Translates to the   |
| standard Counter   |          | standard Counter    |
| sysfs output       |          | character device    |
+--------------------+          +---------------------+
```

Thereafter, data can be transferred directly between the Counter device driver and Counter userspace interface:



```text
Count data request:
~~~~~~~~~~~~~~~~~~~
                 ----------------------
                / Counter device       \
                +----------------------+
                | Count register: 0x28 |
                +----------------------+
                        |
                 -----------------
                / raw count data /
                -----------------
                        |
                        V
                +----------------------------+
                | Counter device driver      |
                +----------------------------+
                | Processes data from device |
                |----------------------------|
                | Type: u64                  |
                | Value: 42                  |
                +----------------------------+
                        |
                 ----------
                / u64     /
                ----------
                        |
        +---------------+---------------+
        |                               |
        V                               V
+--------------------+          +---------------------+
| Counter sysfs      |          | Counter chrdev      |
+--------------------+          +---------------------+
| Translates to the  |          | Translates to the   |
| standard Counter   |          | standard Counter    |
| sysfs output       |          | character device    |
|--------------------|          |---------------------|
| Type: const char * |          | Type: u64           |
| Value: "42"        |          | Value: 42           |
+--------------------+          +---------------------+
        |                               |
 ---------------                 -----------------------
/ const char * /                / struct counter_event /
---------------                 -----------------------
        |                               |
        |                               V
        |                       +-----------+
        |                       | read      |
        |                       +-----------+
        |                       \ Count: 42 /
        |                        -----------
        |
        V
+--------------------------------------------------+
| `/sys/bus/counter/devices/counterX/countY/count` |
+--------------------------------------------------+
\ Count: "42"                                      /
 --------------------------------------------------
```

There are four primary components involved:

<a id="rst-counter-device-driver"></a>

### Counter device driver

Communicates with the hardware device to read/write data; e.g. counter drivers for quadrature encoders, timers, etc.

<a id="rst-counter-core"></a>

### Counter core

Registers the counter device driver to the system so that the respective callbacks are called during userspace interaction.

<a id="rst-counter-sysfs"></a>

### Counter sysfs

Translates counter data to the standard Counter sysfs interface format and vice versa.

Please refer to the Documentation/ABI/testing/sysfs-bus-counter file for a detailed breakdown of the available Generic Counter interface sysfs attributes.

<a id="rst-counter-chrdev"></a>

### Counter chrdev

Translates Counter events to the standard Counter character device; data is transferred via standard character device read calls, while Counter events are configured via ioctl calls.

<a id="rst-sysfs-interface"></a>

## Sysfs Interface

Several sysfs attributes are generated by the Generic Counter interface, and reside under the `/sys/bus/counter/devices/counterX` directory, where `X` is to the respective counter device id. Please see Documentation/ABI/testing/sysfs-bus-counter for detailed information on each Generic Counter interface sysfs attribute.

Through these sysfs attributes, programs and scripts may interact with the Generic Counter paradigm Counts, Signals, and Synapses of respective counter devices.

<a id="rst-counter-character-device"></a>

## Counter Character Device

Counter character device nodes are created under the `/dev` directory as `counterX`, where `X` is the respective counter device id. Defines for the standard Counter data types are exposed via the userspace `include/uapi/linux/counter.h` file.

<a id="rst-counter-events"></a>

### Counter events

Counter device drivers can support Counter events by utilizing the `counter_push_event` function:



```text
void counter_push_event(struct counter_device *const counter, const u8 event,
                        const u8 channel);
```

The event id is specified by the `event` parameter; the event channel id is specified by the `channel` parameter. When this function is called, the Counter data associated with the respective event is gathered, and a `struct counter_event` is generated for each datum and pushed to userspace.

Counter events can be configured by users to report various Counter data of interest. This can be conceptualized as a list of Counter component read calls to perform. For example:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> COUNTER_EVENT_OVERFLOW
>
> </th>
> <th>
>
>
> COUNTER_EVENT_INDEX
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> Channel 0
>
> </td>
> <td>
>
>
> Channel 0
>
> </td>
> </tr>
> <tr>
> <td rowspan="3">
>
>
> - Count 0
>
> - Count 1
>
> - Signal 3
>
> - Count 4 Extension 2
>
> - Signal 5 Extension 0
>
> </td>
> <td>
>
>
> - Signal 0
>
> - Signal 0 Extension 0
>
> - Extension 4
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Channel 1
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> - Signal 4
>
> - Signal 4 Extension 0
>
> - Count 7
>
> </td>
> </tr>
> </tbody>
> </table>

When `counter_push_event(counter, COUNTER_EVENT_INDEX, 1)` is called for example, it will go down the list for the `COUNTER_EVENT_INDEX` event channel 1 and execute the read callbacks for Signal 4, Signal 4 Extension 0, and Count 7 -- the data returned for each is pushed to a kfifo as a `struct counter_event`, which userspace can retrieve via a standard read operation on the respective character device node.

<a id="rst-userspace"></a>

### Userspace

Userspace applications can configure Counter events via ioctl operations on the Counter character device node. There following ioctl codes are supported and provided by the `linux/counter.h` userspace header file:

- `COUNTER_ADD_WATCH_IOCTL`

- `COUNTER_ENABLE_EVENTS_IOCTL`

- `COUNTER_DISABLE_EVENTS_IOCTL`

To configure events to gather Counter data, users first populate a `struct counter_watch` with the relevant event id, event channel id, and the information for the desired Counter component from which to read, and then pass it via the `COUNTER_ADD_WATCH_IOCTL` ioctl command.

Note that an event can be watched without gathering Counter data by setting the `component.type` member equal to `COUNTER_COMPONENT_NONE`. With this configuration the Counter character device will simply populate the event timestamps for those respective `struct counter_event` elements and ignore the component value.

The `COUNTER_ADD_WATCH_IOCTL` command will buffer these Counter watches. When ready, the `COUNTER_ENABLE_EVENTS_IOCTL` ioctl command may be used to activate these Counter watches.

Userspace applications can then execute a `read` operation (optionally calling `poll` first) on the Counter character device node to retrieve `struct counter_event` elements with the desired data.

---

# Recoverable Hardware Error Tracking in vmcoreinfo

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This feature provides a generic infrastructure within the Linux kernel to track and log recoverable hardware errors. These are hardware recoverable errors visible that might not cause immediate panics but may influence health, mainly…

<a id="rst-recoverable-hardware-error-tracking-in-vmcoreinfo"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

This feature provides a generic infrastructure within the Linux kernel to track and log recoverable hardware errors. These are hardware recoverable errors visible that might not cause immediate panics but may influence health, mainly because new code path will be executed in the kernel.

By recording counts and timestamps of recoverable errors into the vmcoreinfo crash dump notes, this infrastructure aids post-mortem crash analysis tools in correlating hardware events with kernel failures. This enables faster triage and better understanding of root causes, especially in large-scale cloud environments where hardware issues are common.

<a id="rst-benefits"></a>

## Benefits

- Facilitates correlation of hardware recoverable errors with kernel panics or unusual code paths that lead to system crashes.

- Provides operators and cloud providers quick insights, improving reliability and reducing troubleshooting time.

- Complements existing full hardware diagnostics without replacing them.

<a id="rst-data-exposure-and-consumption"></a>

## Data Exposure and Consumption

- The tracked error data consists of per-error-type counts and timestamps of last occurrence.

- This data is stored in the `hwerror_data` array, categorized by error source types like CPU, memory, PCI, CXL, and others.

- It is exposed via vmcoreinfo crash dump notes and can be read using tools like `crash`, `drgn`, or other kernel crash analysis utilities.

- There is no other way to read these data other than from crash dumps.

- These errors are divided by area, which includes CPU, Memory, PCI, CXL and others.

Typical usage example (in drgn REPL):



```python
>>> prog['hwerror_data']
(struct hwerror_info[HWERR_RECOV_MAX]){
    {
        .count = (int)844,
        .timestamp = (time64_t)1752852018,
    },
    ...
}
```

<a id="rst-enabling"></a>

## Enabling

- This feature is enabled when CONFIG_VMCORE_INFO is set.

---

# Input Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Reference for Input Subsystem.

<a id="rst-input-subsystem"></a>

<a id="rst-input-core"></a>

## Input core


#### <a id="c-struct-input_value"></a>`struct input_value`

input value representation

**Definition**

```c
struct input_value {
    __u16 type;
    __u16 code;
    __s32 value;
};
```

**Members**

- `type`: type of value (EV_KEY, EV_ABS, etc)
- `code`: the value code
- `value`: the value

#### <a id="c-struct-input_dev"></a>`struct input_dev`

represents an input device

**Definition**

```c
struct input_dev {
    const char *name;
    const char *phys;
    const char *uniq;
    struct input_id id;
    unsigned long propbit[BITS_TO_LONGS(INPUT_PROP_CNT)];
    unsigned long evbit[BITS_TO_LONGS(EV_CNT)];
    unsigned long keybit[BITS_TO_LONGS(KEY_CNT)];
    unsigned long relbit[BITS_TO_LONGS(REL_CNT)];
    unsigned long absbit[BITS_TO_LONGS(ABS_CNT)];
    unsigned long mscbit[BITS_TO_LONGS(MSC_CNT)];
    unsigned long ledbit[BITS_TO_LONGS(LED_CNT)];
    unsigned long sndbit[BITS_TO_LONGS(SND_CNT)];
    unsigned long ffbit[BITS_TO_LONGS(FF_CNT)];
    unsigned long swbit[BITS_TO_LONGS(SW_CNT)];
    unsigned int hint_events_per_packet;
    unsigned int keycodemax;
    unsigned int keycodesize;
    void *keycode;
    int (*setkeycode)(struct input_dev *dev, const struct input_keymap_entry *ke, unsigned int *old_keycode);
    int (*getkeycode)(struct input_dev *dev, struct input_keymap_entry *ke);
    struct ff_device *ff;
    struct input_dev_poller *poller;
    unsigned int repeat_key;
    struct timer_list timer;
    int rep[REP_CNT];
    struct input_mt *mt;
    struct input_absinfo *absinfo;
    unsigned long key[BITS_TO_LONGS(KEY_CNT)];
    unsigned long led[BITS_TO_LONGS(LED_CNT)];
    unsigned long snd[BITS_TO_LONGS(SND_CNT)];
    unsigned long sw[BITS_TO_LONGS(SW_CNT)];
    int (*open)(struct input_dev *dev);
    void (*close)(struct input_dev *dev);
    int (*flush)(struct input_dev *dev, struct file *file);
    int (*event)(struct input_dev *dev, unsigned int type, unsigned int code, int value);
    struct input_handle  *grab;
    spinlock_t event_lock;
    struct mutex mutex;
    unsigned int users;
    bool going_away;
    struct device dev;
    struct list_head        h_list;
    struct list_head        node;
    unsigned int num_vals;
    unsigned int max_vals;
    struct input_value *vals;
    bool devres_managed;
    ktime_t timestamp[INPUT_CLK_MAX];
    bool inhibited;
};
```

**Members**

- `name`: name of the device
- `phys`: physical path to the device in the system hierarchy
- `uniq`: unique identification code for the device (if device has it)
- `id`: id of the device (struct input_id)
- `propbit`: bitmap of device properties and quirks
- `evbit`: bitmap of types of events supported by the device (EV_KEY,
  EV_REL, etc.)
- `keybit`: bitmap of keys/buttons this device has
- `relbit`: bitmap of relative axes for the device
- `absbit`: bitmap of absolute axes for the device
- `mscbit`: bitmap of miscellaneous events supported by the device
- `ledbit`: bitmap of leds present on the device
- `sndbit`: bitmap of sound effects supported by the device
- `ffbit`: bitmap of force feedback effects supported by the device
- `swbit`: bitmap of switches present on the device
- `hint_events_per_packet`: average number of events generated by the
  device in a packet (between EV_SYN/SYN_REPORT events). Used by
  event handlers to estimate size of the buffer needed to hold
  events.
- `keycodemax`: size of keycode table
- `keycodesize`: size of elements in keycode table
- `keycode`: map of scancodes to keycodes for this device
- `setkeycode`: optional method to alter current keymap, used to implement
  sparse keymaps. If not supplied default mechanism will be used.
  The method is being called while holding event_lock and thus must
  not sleep
- `getkeycode`: optional legacy method to retrieve current keymap.
- `ff`: force feedback structure associated with the device if device
  supports force feedback effects
- `poller`: poller structure associated with the device if device is
  set up to use polling mode
- `repeat_key`: stores key code of the last key pressed; used to implement
  software autorepeat
- `timer`: timer for software autorepeat
- `rep`: current values for autorepeat parameters (delay, rate)
- `mt`: pointer to multitouch state
- `absinfo`: array of `struct input_absinfo` elements holding information
  about absolute axes (current value, min, max, flat, fuzz,
  resolution)
- `key`: reflects current state of device's keys/buttons
- `led`: reflects current state of device's LEDs
- `snd`: reflects current state of sound effects
- `sw`: reflects current state of device's switches
- `open`: this method is called when the very first user calls
  [`input_open_device()`](#c-input_open_device). The driver must prepare the device
  to start generating events (start polling thread,
  request an IRQ, submit URB, etc.). The meaning of `open()` is
  to start providing events to the input core.
- `close`: this method is called when the very last user calls
  [`input_close_device()`](#c-input_close_device). The meaning of `close()` is to stop
  providing events to the input core.
- `flush`: purges the device. Most commonly used to get rid of force
  feedback effects loaded into the device when disconnecting
  from it
- `event`: event handler for events sent _to_ the device, like EV_LED
  or EV_SND. The device is expected to carry out the requested
  action (turn on a LED, play sound, etc.) The call is protected
  by **event_lock** and must not sleep
- `grab`: input handle that currently has the device grabbed (via
  EVIOCGRAB ioctl). When a handle grabs a device it becomes sole
  recipient for all input events coming from the device
- `event_lock`: this spinlock is taken when input core receives
  and processes a new event for the device (in [`input_event()`](#c-input_event)).
  Code that accesses and/or modifies parameters of a device
  (such as keymap or absmin, absmax, absfuzz, etc.) after device
  has been registered with input core must take this lock.
- `mutex`: serializes calls to `open()`, `close()` and `flush()` methods
- `users`: stores number of users (input handlers) that opened this
  device. It is used by [`input_open_device()`](#c-input_open_device) and [`input_close_device()`](#c-input_close_device)
  to make sure that dev->`open()` is only called when the first
  user opens device and dev->`close()` is called when the very
  last user closes the device
- `going_away`: marks devices that are in a middle of unregistering and
  causes input_open_device*() fail with -ENODEV.
- `dev`: driver model's view of this device
- `h_list`: list of input handles associated with the device. When
  accessing the list dev->mutex must be held
- `node`: used to place the device onto input_dev_list
- `num_vals`: number of values queued in the current frame
- `max_vals`: maximum number of values queued in a frame
- `vals`: array of values queued in the current frame
- `devres_managed`: indicates that devices is managed with devres framework
  and needs not be explicitly unregistered or freed.
- `timestamp`: storage for a timestamp set by input_set_timestamp called
  by a driver
- `inhibited`: indicates that the input device is inhibited. If that is
  the case then input core ignores any events generated by the device.
  Device's `close()` is called when it is being inhibited and its `open()`
  is called when it is being uninhibited.

#### <a id="c-struct-input_handler"></a>`struct input_handler`

implements one of interfaces for input devices

**Definition**

```c
struct input_handler {
    void *private;
    void (*event)(struct input_handle *handle, unsigned int type, unsigned int code, int value);
    unsigned int (*events)(struct input_handle *handle, struct input_value *vals, unsigned int count);
    bool (*filter)(struct input_handle *handle, unsigned int type, unsigned int code, int value);
    bool (*match)(struct input_handler *handler, struct input_dev *dev);
    int (*connect)(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id);
    void (*disconnect)(struct input_handle *handle);
    void (*start)(struct input_handle *handle);
    bool passive_observer;
    bool legacy_minors;
    int minor;
    const char *name;
    const struct input_device_id *id_table;
    struct list_head        h_list;
    struct list_head        node;
};
```

**Members**

- `private`: driver-specific data
- `event`: event handler. This method is being called by input core with
  interrupts disabled and dev->event_lock spinlock held and so
  it may not sleep
- `events`: event sequence handler. This method is being called by
  input core with interrupts disabled and dev->event_lock
  spinlock held and so it may not sleep. The method must return
  number of events passed to it.
- `filter`: similar to **event**; separates normal event handlers from
  "filters".
- `match`: called after comparing device's id with handler's id_table
  to perform fine-grained matching between device and handler
- `connect`: called when attaching a handler to an input device
- `disconnect`: disconnects a handler from input device
- `start`: starts handler for given handle. This function is called by
  input core right after `connect()` method and also when a process
  that "grabbed" a device releases it
- `passive_observer`: set to `true` by drivers only interested in observing
  data stream from devices if there are other users present. Such
  drivers will not result in starting underlying hardware device
  when [`input_open_device()`](#c-input_open_device) is called for their handles
- `legacy_minors`: set to `true` by drivers using legacy minor ranges
- `minor`: beginning of range of 32 legacy minors for devices this driver
  can provide
- `name`: name of the handler, to be shown in /proc/bus/input/handlers
- `id_table`: pointer to a table of input_device_ids this driver can
  handle
- `h_list`: list of input handles associated with the handler
- `node`: for placing the driver onto input_handler_list

**Description**

Input handlers attach to input devices and create input handles. There
are likely several handlers attached to any given input device at the
same time. All of them will get their copy of input event generated by
the device.

The very same structure is used to implement input filters. Input core
allows filters to run first and will not pass event to regular handlers
if any of the filters indicate that the event should be filtered (by
returning `true` from their `filter()` method).

Note that input core serializes calls to `connect()` and `disconnect()`
methods.

#### <a id="c-struct-input_handle"></a>`struct input_handle`

links input device with an input handler

**Definition**

```c
struct input_handle {
    void *private;
    int open;
    const char *name;
    struct input_dev *dev;
    struct input_handler *handler;
    unsigned int (*handle_events)(struct input_handle *handle, struct input_value *vals, unsigned int count);
    struct list_head        d_node;
    struct list_head        h_node;
};
```

**Members**

- `private`: handler-specific data
- `open`: counter showing whether the handle is 'open', i.e. should deliver
  events from its device
- `name`: name given to the handle by handler that created it
- `dev`: input device the handle is attached to
- `handler`: handler that works with the device through this handle
- `handle_events`: event sequence handler. It is set up by the input core
  according to event handling method specified in the **handler**. See
  `input_handle_setup_event_handler()`.
  This method is being called by the input core with interrupts disabled
  and dev->event_lock spinlock held and so it may not sleep.
- `d_node`: used to put the handle on device's list of attached handles
- `h_node`: used to put the handle on handler's list of handles from which
  it gets events

#### <a id="c-input_set_events_per_packet"></a>`input_set_events_per_packet()`

```c
void input_set_events_per_packet(struct input_dev *dev, int n_events)
```

tell handlers about the driver event rate

**Parameters**

- `struct input_dev *dev`: the input device used by the driver
- `int n_events`: the average number of events between calls to `input_sync()`

**Description**

If the event rate sent from a device is unusually large, use this
function to set the expected event rate. This will allow handlers
to set up an appropriate buffer size for the event stream, in order
to minimize information loss.

#### <a id="c-struct-ff_device"></a>`struct ff_device`

force-feedback part of an input device

**Definition**

```c
struct ff_device {
    int (*upload)(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old);
    int (*erase)(struct input_dev *dev, int effect_id);
    int (*playback)(struct input_dev *dev, int effect_id, int value);
    void (*set_gain)(struct input_dev *dev, u16 gain);
    void (*set_autocenter)(struct input_dev *dev, u16 magnitude);
    void (*destroy)(struct ff_device *);
    void *private;
    unsigned long ffbit[BITS_TO_LONGS(FF_CNT)];
    struct mutex mutex;
    int max_effects;
    struct ff_effect *effects;
    struct file *effect_owners[] ;
};
```

**Members**

- `upload`: Called to upload an new effect into device
- `erase`: Called to erase an effect from device
- `playback`: Called to request device to start playing specified effect
- `set_gain`: Called to set specified gain
- `set_autocenter`: Called to auto-center device
- `destroy`: called by input core when parent input device is being
  destroyed
- `private`: driver-specific data, will be freed automatically
- `ffbit`: bitmap of force feedback capabilities truly supported by
  device (not emulated like ones in input_dev->ffbit)
- `mutex`: mutex for serializing access to the device
- `max_effects`: maximum number of effects supported by device
- `effects`: pointer to an array of effects currently loaded into device
- `effect_owners`: array of effect owners; when file handle owning
  an effect gets closed the effect is automatically erased

**Description**

Every force-feedback device must implement `upload()` and `playback()`
methods; `erase()` is optional. `set_gain()` and `set_autocenter()` need
only be implemented if driver sets up FF_GAIN and FF_AUTOCENTER
bits.

Note that `playback()`, `set_gain()` and `set_autocenter()` are called with
dev->event_lock spinlock held and interrupts off and thus may not
sleep.



#### <a id="c-input_event"></a>`input_event()`

```c
void input_event(struct input_dev *dev, unsigned int type, unsigned int code, int value)
```

report new input event

**Parameters**

- `struct input_dev *dev`: device that generated the event
- `unsigned int type`: type of the event
- `unsigned int code`: event code
- `int value`: value of the event

**Description**

This function should be used by drivers implementing various input
devices to report input events. See also [`input_inject_event()`](#c-input_inject_event).

**NOTE**

[`input_event()`](#c-input_event) may be safely used right after input device was
allocated with [`input_allocate_device()`](#c-input_allocate_device), even before it is registered
with [`input_register_device()`](#c-input_register_device), but the event will not reach any of the
input handlers. Such early invocation of [`input_event()`](#c-input_event) may be used
to 'seed' initial state of a switch or initial position of absolute
axis, etc.

#### <a id="c-input_inject_event"></a>`input_inject_event()`

```c
void input_inject_event(struct input_handle *handle, unsigned int type, unsigned int code, int value)
```

send input event from input handler

**Parameters**

- `struct input_handle *handle`: input handle to send event through
- `unsigned int type`: type of the event
- `unsigned int code`: event code
- `int value`: value of the event

**Description**

Similar to [`input_event()`](#c-input_event) but will ignore event if device is
"grabbed" and handle injecting event is not the one that owns
the device.

#### <a id="c-input_alloc_absinfo"></a>`input_alloc_absinfo()`

```c
void input_alloc_absinfo(struct input_dev *dev)
```

allocates array of input_absinfo structs

**Parameters**

- `struct input_dev *dev`: the input device emitting absolute events

**Description**

If the absinfo struct the caller asked for is already allocated, this
functions will not do anything.

#### <a id="c-input_copy_abs"></a>`input_copy_abs()`

```c
void input_copy_abs(struct input_dev *dst, unsigned int dst_axis, const struct input_dev *src, unsigned int src_axis)
```

Copy absinfo from one input_dev to another

**Parameters**

- `struct input_dev *dst`: Destination input device to copy the abs settings to
- `unsigned int dst_axis`: ABS_* value selecting the destination axis
- `const struct input_dev *src`: Source input device to copy the abs settings from
- `unsigned int src_axis`: ABS_* value selecting the source axis

**Description**

Set absinfo for the selected destination axis by copying it from
the specified source input device's source axis.
This is useful to e.g. setup a pen/stylus input-device for combined
touchscreen/pen hardware where the pen uses the same coordinates as
the touchscreen.

#### <a id="c-input_grab_device"></a>`input_grab_device()`

```c
int input_grab_device(struct input_handle *handle)
```

grabs device for exclusive use

**Parameters**

- `struct input_handle *handle`: input handle that wants to own the device

**Description**

When a device is grabbed by an input handle all events generated by
the device are delivered only to this handle. Also events injected
by other input handles are ignored while device is grabbed.

#### <a id="c-input_release_device"></a>`input_release_device()`

```c
void input_release_device(struct input_handle *handle)
```

release previously grabbed device

**Parameters**

- `struct input_handle *handle`: input handle that owns the device

**Description**

Releases previously grabbed device so that other input handles can
start receiving input events. Upon release all handlers attached
to the device have their `start()` method called so they have a change
to synchronize device state with the rest of the system.

#### <a id="c-input_open_device"></a>`input_open_device()`

```c
int input_open_device(struct input_handle *handle)
```

open input device

**Parameters**

- `struct input_handle *handle`: handle through which device is being accessed

**Description**

This function should be called by input handlers when they
want to start receive events from given input device.

#### <a id="c-input_close_device"></a>`input_close_device()`

```c
void input_close_device(struct input_handle *handle)
```

close input device

**Parameters**

- `struct input_handle *handle`: handle through which device is being accessed

**Description**

This function should be called by input handlers when they
want to stop receive events from given input device.

#### <a id="c-input_scancode_to_scalar"></a>`input_scancode_to_scalar()`

```c
int input_scancode_to_scalar(const struct input_keymap_entry *ke, unsigned int *scancode)
```

converts scancode in `struct input_keymap_entry`

**Parameters**

- `const struct input_keymap_entry *ke`: keymap entry containing scancode to be converted.
- `unsigned int *scancode`: pointer to the location where converted scancode should
  be stored.

**Description**

This function is used to convert scancode stored in `struct keymap_entry`
into scalar form understood by legacy keymap handling methods. These
methods expect scancodes to be represented as 'unsigned int'.

#### <a id="c-input_get_keycode"></a>`input_get_keycode()`

```c
int input_get_keycode(struct input_dev *dev, struct input_keymap_entry *ke)
```

retrieve keycode currently mapped to a given scancode

**Parameters**

- `struct input_dev *dev`: input device which keymap is being queried
- `struct input_keymap_entry *ke`: keymap entry

**Description**

This function should be called by anyone interested in retrieving current
keymap. Presently evdev handlers use it.

#### <a id="c-input_set_keycode"></a>`input_set_keycode()`

```c
int input_set_keycode(struct input_dev *dev, const struct input_keymap_entry *ke)
```

attribute a keycode to a given scancode

**Parameters**

- `struct input_dev *dev`: input device which keymap is being updated
- `const struct input_keymap_entry *ke`: new keymap entry

**Description**

This function should be called by anyone needing to update current
keymap. Presently keyboard and evdev handlers use it.

#### <a id="c-input_reset_device"></a>`input_reset_device()`

```c
void input_reset_device(struct input_dev *dev)
```

reset/restore the state of input device

**Parameters**

- `struct input_dev *dev`: input device whose state needs to be reset

**Description**

This function tries to reset the state of an opened input device and
bring internal state and state if the hardware in sync with each other.
We mark all keys as released, restore LED state, repeat rate, etc.

#### <a id="c-input_allocate_device"></a>`input_allocate_device()`

```c
struct input_dev * input_allocate_device(void)
```

allocate memory for new input device

**Parameters**

- `void`: no arguments

**Description**

Returns prepared struct input_dev or `NULL`.

**NOTE**

Use [`input_free_device()`](#c-input_free_device) to free devices that have not been
registered; [`input_unregister_device()`](#c-input_unregister_device) should be used for already
registered devices.

#### <a id="c-devm_input_allocate_device"></a>`devm_input_allocate_device()`

```c
struct input_dev * devm_input_allocate_device(struct device *dev)
```

allocate managed input device

**Parameters**

- `struct device *dev`: device owning the input device being created

**Description**

Returns prepared struct input_dev or `NULL`.

Managed input devices do not need to be explicitly unregistered or
freed as it will be done automatically when owner device unbinds from
its driver (or binding fails). Once managed input device is allocated,
it is ready to be set up and registered in the same fashion as regular
input device. There are no special devm_input_device_\[un\]`register()`
variants, regular ones work with both managed and unmanaged devices,
should you need them. In most cases however, managed input device need
not be explicitly unregistered or freed.

**NOTE**

the owner device is set up as parent of input device and users
should not override it.

#### <a id="c-input_free_device"></a>`input_free_device()`

```c
void input_free_device(struct input_dev *dev)
```

free memory occupied by input_dev structure

**Parameters**

- `struct input_dev *dev`: input device to free

**Description**

This function should only be used if [`input_register_device()`](#c-input_register_device)
was not called yet or if it failed. Once device was registered
use [`input_unregister_device()`](#c-input_unregister_device) and memory will be freed once last
reference to the device is dropped.

Device should be allocated by [`input_allocate_device()`](#c-input_allocate_device).

**NOTE**

If there are references to the input device then memory
will not be freed until last reference is dropped.

#### <a id="c-input_set_timestamp"></a>`input_set_timestamp()`

```c
void input_set_timestamp(struct input_dev *dev, ktime_t timestamp)
```

set timestamp for input events

**Parameters**

- `struct input_dev *dev`: input device to set timestamp for
- `ktime_t timestamp`: the time at which the event has occurred
  in CLOCK_MONOTONIC

**Description**

This function is intended to provide to the input system a more
accurate time of when an event actually occurred. The driver should
call this function as soon as a timestamp is acquired ensuring
clock conversions in input_set_timestamp are done correctly.

The system entering suspend state between timestamp acquisition and
calling input_set_timestamp can result in inaccurate conversions.

#### <a id="c-input_get_timestamp"></a>`input_get_timestamp()`

```c
ktime_t * input_get_timestamp(struct input_dev *dev)
```

get timestamp for input events

**Parameters**

- `struct input_dev *dev`: input device to get timestamp from

**Description**

A valid timestamp is a timestamp of non-zero value.

#### <a id="c-input_set_capability"></a>`input_set_capability()`

```c
void input_set_capability(struct input_dev *dev, unsigned int type, unsigned int code)
```

mark device as capable of a certain event

**Parameters**

- `struct input_dev *dev`: device that is capable of emitting or accepting event
- `unsigned int type`: type of the event (EV_KEY, EV_REL, etc...)
- `unsigned int code`: event code

**Description**

In addition to setting up corresponding bit in appropriate capability
bitmap the function also adjusts dev->evbit.

#### <a id="c-input_enable_softrepeat"></a>`input_enable_softrepeat()`

```c
void input_enable_softrepeat(struct input_dev *dev, int delay, int period)
```

enable software autorepeat

**Parameters**

- `struct input_dev *dev`: input device
- `int delay`: repeat delay
- `int period`: repeat period

**Description**

Enable software autorepeat on the input device.

#### <a id="c-input_register_device"></a>`input_register_device()`

```c
int input_register_device(struct input_dev *dev)
```

register device with input core

**Parameters**

- `struct input_dev *dev`: device to be registered

**Description**

This function registers device with input core. The device must be
allocated with [`input_allocate_device()`](#c-input_allocate_device) and all it's capabilities
set up before registering.
If function fails the device must be freed with [`input_free_device()`](#c-input_free_device).
Once device has been successfully registered it can be unregistered
with [`input_unregister_device()`](#c-input_unregister_device); [`input_free_device()`](#c-input_free_device) should not be
called in this case.

Note that this function is also used to register managed input devices
(ones allocated with [`devm_input_allocate_device()`](#c-devm_input_allocate_device)). Such managed input
devices need not be explicitly unregistered or freed, their tear down
is controlled by the devres infrastructure. It is also worth noting
that tear down of managed input devices is internally a 2-step process:
registered managed input device is first unregistered, but stays in
memory and can still handle [`input_event()`](#c-input_event) calls (although events will
not be delivered anywhere). The freeing of managed input device will
happen later, when devres stack is unwound to the point where device
allocation was made.

#### <a id="c-input_unregister_device"></a>`input_unregister_device()`

```c
void input_unregister_device(struct input_dev *dev)
```

unregister previously registered device

**Parameters**

- `struct input_dev *dev`: device to be unregistered

**Description**

This function unregisters an input device. Once device is unregistered
the caller should not try to access it as it may get freed at any moment.

#### <a id="c-input_register_handler"></a>`input_register_handler()`

```c
int input_register_handler(struct input_handler *handler)
```

register a new input handler

**Parameters**

- `struct input_handler *handler`: handler to be registered

**Description**

This function registers a new input handler (interface) for input
devices in the system and attaches it to all input devices that
are compatible with the handler.

#### <a id="c-input_unregister_handler"></a>`input_unregister_handler()`

```c
void input_unregister_handler(struct input_handler *handler)
```

unregisters an input handler

**Parameters**

- `struct input_handler *handler`: handler to be unregistered

**Description**

This function disconnects a handler from its input devices and
removes it from lists of known handlers.

#### <a id="c-input_handler_for_each_handle"></a>`input_handler_for_each_handle()`

```c
int input_handler_for_each_handle(struct input_handler *handler, void *data, int (*fn)(struct input_handle *, void *))
```

handle iterator

**Parameters**

- `struct input_handler *handler`: input handler to iterate
- `void *data`: data for the callback
- `int (*fn)(struct input_handle *, void *)`: function to be called for each handle

**Description**

Iterate over **bus**'s list of devices, and call **fn** for each, passing
it **data** and stop when **fn** returns a non-zero value. The function is
using RCU to traverse the list and therefore may be using in atomic
contexts. The **fn** callback is invoked from RCU critical section and
thus must not sleep.

#### <a id="c-input_register_handle"></a>`input_register_handle()`

```c
int input_register_handle(struct input_handle *handle)
```

register a new input handle

**Parameters**

- `struct input_handle *handle`: handle to register

**Description**

This function puts a new input handle onto device's
and handler's lists so that events can flow through
it once it is opened using [`input_open_device()`](#c-input_open_device).

This function is supposed to be called from handler's
`connect()` method.

#### <a id="c-input_unregister_handle"></a>`input_unregister_handle()`

```c
void input_unregister_handle(struct input_handle *handle)
```

unregister an input handle

**Parameters**

- `struct input_handle *handle`: handle to unregister

**Description**

This function removes input handle from device's
and handler's lists.

This function is supposed to be called from handler's
`disconnect()` method.

#### <a id="c-input_get_new_minor"></a>`input_get_new_minor()`

```c
int input_get_new_minor(int legacy_base, unsigned int legacy_num, bool allow_dynamic)
```

allocates a new input minor number

**Parameters**

- `int legacy_base`: beginning or the legacy range to be searched
- `unsigned int legacy_num`: size of legacy range
- `bool allow_dynamic`: whether we can also take ID from the dynamic range

**Description**

This function allocates a new device minor for from input major namespace.
Caller can request legacy minor by specifying **legacy_base** and **legacy_num**
parameters and whether ID can be allocated from dynamic range if there are
no free IDs in legacy range.

#### <a id="c-input_free_minor"></a>`input_free_minor()`

```c
void input_free_minor(unsigned int minor)
```

release previously allocated minor

**Parameters**

- `unsigned int minor`: minor to be released

**Description**

This function releases previously allocated input minor so that it can be
reused later.



#### <a id="c-input_ff_upload"></a>`input_ff_upload()`

```c
int input_ff_upload(struct input_dev *dev, struct ff_effect *effect, struct file *file)
```

upload effect into force-feedback device

**Parameters**

- `struct input_dev *dev`: input device
- `struct ff_effect *effect`: effect to be uploaded
- `struct file *file`: owner of the effect

#### <a id="c-input_ff_erase"></a>`input_ff_erase()`

```c
int input_ff_erase(struct input_dev *dev, int effect_id, struct file *file)
```

erase a force-feedback effect from device

**Parameters**

- `struct input_dev *dev`: input device to erase effect from
- `int effect_id`: id of the effect to be erased
- `struct file *file`: purported owner of the request

**Description**

This function erases a force-feedback effect from specified device.
The effect will only be erased if it was uploaded through the same
file handle that is requesting erase.

#### <a id="c-input_ff_event"></a>`input_ff_event()`

```c
int input_ff_event(struct input_dev *dev, unsigned int type, unsigned int code, int value)
```

generic handler for force-feedback events

**Parameters**

- `struct input_dev *dev`: input device to send the effect to
- `unsigned int type`: event type (anything but EV_FF is ignored)
- `unsigned int code`: event code
- `int value`: event value

#### <a id="c-input_ff_create"></a>`input_ff_create()`

```c
int input_ff_create(struct input_dev *dev, unsigned int max_effects)
```

create force-feedback device

**Parameters**

- `struct input_dev *dev`: input device supporting force-feedback
- `unsigned int max_effects`: maximum number of effects supported by the device

**Description**

This function allocates all necessary memory for a force feedback
portion of an input device and installs all default handlers.
**dev->ffbit** should be already set up before calling this function.
Once ff device is created you need to setup its upload, erase,
playback and other handlers before registering input device

#### <a id="c-input_ff_destroy"></a>`input_ff_destroy()`

```c
void input_ff_destroy(struct input_dev *dev)
```

frees force feedback portion of input device

**Parameters**

- `struct input_dev *dev`: input device supporting force feedback

**Description**

This function is only needed in error path as input core will
automatically free force feedback structures when device is
destroyed.



#### <a id="c-input_ff_create_memless"></a>`input_ff_create_memless()`

```c
int input_ff_create_memless(struct input_dev *dev, void *data, int (*play_effect)(struct input_dev *, void *, struct ff_effect *))
```

create memoryless force-feedback device

**Parameters**

- `struct input_dev *dev`: input device supporting force-feedback
- `void *data`: driver-specific data to be passed into **play_effect**
- `int (*play_effect)(struct input_dev *, void *, struct ff_effect *)`: driver-specific method for playing FF effect


<a id="rst-multitouch-library"></a>

## Multitouch Library


#### <a id="c-struct-input_mt_slot"></a>`struct input_mt_slot`

represents the state of an input MT slot

**Definition**

```c
struct input_mt_slot {
    int abs[ABS_MT_LAST - ABS_MT_FIRST + 1];
    unsigned int frame;
    unsigned int key;
};
```

**Members**

- `abs`: holds current values of ABS_MT axes for this slot
- `frame`: last frame at which [`input_mt_report_slot_state()`](#c-input_mt_report_slot_state) was called
- `key`: optional driver designation of this slot

#### <a id="c-struct-input_mt"></a>`struct input_mt`

state of tracked contacts

**Definition**

```c
struct input_mt {
    int trkid;
    int num_slots;
    int slot;
    unsigned int flags;
    unsigned int frame;
    int *red;
    struct input_mt_slot slots[] ;
};
```

**Members**

- `trkid`: stores MT tracking ID for the next contact
- `num_slots`: number of MT slots the device uses
- `slot`: MT slot currently being transmitted
- `flags`: input_mt operation flags
- `frame`: increases every time [`input_mt_sync_frame()`](#c-input_mt_sync_frame) is called
- `red`: reduced cost matrix for in-kernel tracking
- `slots`: array of slots holding current values of tracked contacts

#### <a id="c-struct-input_mt_pos"></a>`struct input_mt_pos`

contact position

**Definition**

```c
struct input_mt_pos {
    s16 x, y;
};
```

**Members**

- `x`: horizontal coordinate
- `y`: vertical coordinate



#### <a id="c-input_mt_init_slots"></a>`input_mt_init_slots()`

```c
int input_mt_init_slots(struct input_dev *dev, unsigned int num_slots, unsigned int flags)
```

initialize MT input slots

**Parameters**

- `struct input_dev *dev`: input device supporting MT events and finger tracking
- `unsigned int num_slots`: number of slots used by the device
- `unsigned int flags`: mt tasks to handle in core

**Description**

This function allocates all necessary memory for MT slot handling
in the input device, prepares the ABS_MT_SLOT and
ABS_MT_TRACKING_ID events for use and sets up appropriate buffers.
Depending on the flags set, it also performs pointer emulation and
frame synchronization.

May be called repeatedly. Returns -EINVAL if attempting to
reinitialize with a different number of slots.

#### <a id="c-input_mt_destroy_slots"></a>`input_mt_destroy_slots()`

```c
void input_mt_destroy_slots(struct input_dev *dev)
```

frees the MT slots of the input device

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots

**Description**

This function is only needed in error path as the input core will
automatically free the MT slots when the device is destroyed.

#### <a id="c-input_mt_report_slot_state"></a>`input_mt_report_slot_state()`

```c
bool input_mt_report_slot_state(struct input_dev *dev, unsigned int tool_type, bool active)
```

report contact state

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `unsigned int tool_type`: the tool type to use in this slot
- `bool active`: true if contact is active, false otherwise

**Description**

Reports a contact via ABS_MT_TRACKING_ID, and optionally
ABS_MT_TOOL_TYPE. If active is true and the slot is currently
inactive, or if the tool type is changed, a new tracking id is
assigned to the slot. The tool type is only reported if the
corresponding absbit field is set.

Returns true if contact is active.

#### <a id="c-input_mt_report_finger_count"></a>`input_mt_report_finger_count()`

```c
void input_mt_report_finger_count(struct input_dev *dev, int count)
```

report contact count

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `int count`: the number of contacts

**Description**

Reports the contact count via BTN_TOOL_FINGER, BTN_TOOL_DOUBLETAP,
BTN_TOOL_TRIPLETAP and BTN_TOOL_QUADTAP.

The input core ensures only the KEY events already setup for
this device will produce output.

#### <a id="c-input_mt_report_pointer_emulation"></a>`input_mt_report_pointer_emulation()`

```c
void input_mt_report_pointer_emulation(struct input_dev *dev, bool use_count)
```

common pointer emulation

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `bool use_count`: report number of active contacts as finger count

**Description**

Performs legacy pointer emulation via BTN_TOUCH, ABS_X, ABS_Y and
ABS_PRESSURE. Touchpad finger count is emulated if use_count is true.

The input core ensures only the KEY and ABS axes already setup for
this device will produce output.

#### <a id="c-input_mt_drop_unused"></a>`input_mt_drop_unused()`

```c
void input_mt_drop_unused(struct input_dev *dev)
```

Inactivate slots not seen in this frame

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots

**Description**

Lift all slots not seen since the last call to this function.

#### <a id="c-input_mt_sync_frame"></a>`input_mt_sync_frame()`

```c
void input_mt_sync_frame(struct input_dev *dev)
```

synchronize mt frame

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots

**Description**

Close the frame and prepare the internal state for a new one.
Depending on the flags, marks unused slots as inactive and performs
pointer emulation.

#### <a id="c-input_mt_assign_slots"></a>`input_mt_assign_slots()`

```c
int input_mt_assign_slots(struct input_dev *dev, int *slots, const struct input_mt_pos *pos, int num_pos, int dmax)
```

perform a best-match assignment

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `int *slots`: the slot assignment to be filled
- `const struct input_mt_pos *pos`: the position array to match
- `int num_pos`: number of positions
- `int dmax`: maximum ABS_MT_POSITION displacement (zero for infinite)

**Description**

Performs a best match against the current contacts and returns
the slot assignment list. New contacts are assigned to unused
slots.

The assignments are balanced so that all coordinate displacements are
below the euclidian distance dmax. If no such assignment can be found,
some contacts are assigned to unused slots.

Returns zero on success, or negative error in case of failure.

#### <a id="c-input_mt_get_slot_by_key"></a>`input_mt_get_slot_by_key()`

```c
int input_mt_get_slot_by_key(struct input_dev *dev, int key)
```

return slot matching key

**Parameters**

- `struct input_dev *dev`: input device with allocated MT slots
- `int key`: the key of the sought slot

**Description**

Returns the slot of the given key, if it exists, otherwise
set the key on the first unused slot and return.

If no available slot can be found, -1 is returned.
Note that for this function to work properly, [`input_mt_sync_frame()`](#c-input_mt_sync_frame) has
to be called at each frame.


<a id="rst-matrix-keyboards-keypads"></a>

## Matrix keyboards/keypads


#### <a id="c-struct-matrix_keymap_data"></a>`struct matrix_keymap_data`

keymap for matrix keyboards

**Definition**

```c
struct matrix_keymap_data {
    const uint32_t *keymap;
    unsigned int    keymap_size;
};
```

**Members**

- `keymap`: pointer to array of uint32 values encoded with `KEY()` macro
  representing keymap
- `keymap_size`: number of entries (initialized) in this keymap

**Description**

This structure is supposed to be used by platform code to supply
keymaps to drivers that implement matrix-like keypads/keyboards.


<a id="rst-sparse-keymap-support"></a>

## Sparse keymap support


#### <a id="c-struct-key_entry"></a>`struct key_entry`

keymap entry for use in sparse keymap

**Definition**

```c
struct key_entry {
    int type;
    u32 code;
    union {
        u16 keycode;
        struct {
            u8 code;
            u8 value;
        } sw;
    };
};
```

**Members**

- `type`: Type of the key entry (KE_KEY, KE_SW, KE_VSW, KE_END);
  drivers are allowed to extend the list with their own
  private definitions.
- `code`: Device-specific data identifying the button/switch
- `{unnamed_union}`: anonymous
- `keycode`: KEY_* code assigned to a key/button
- `sw`: struct with code/value used by KE_SW and KE_VSW
- `sw.code`: SW_* code assigned to a switch
- `sw.value`: Value that should be sent in an input even when KE_SW
  switch is toggled. KE_VSW switches ignore this field and
  expect driver to supply value for the event.

**Description**

This structure defines an entry in a sparse keymap used by some
input devices for which traditional table-based approach is not
suitable.



#### <a id="c-sparse_keymap_entry_from_scancode"></a>`sparse_keymap_entry_from_scancode()`

```c
struct key_entry * sparse_keymap_entry_from_scancode(struct input_dev *dev, unsigned int code)
```

perform sparse keymap lookup

**Parameters**

- `struct input_dev *dev`: Input device using sparse keymap
- `unsigned int code`: Scan code

**Description**

This function is used to perform [`struct key_entry`](#c-struct-key_entry) lookup in an
input device using sparse keymap.

#### <a id="c-sparse_keymap_entry_from_keycode"></a>`sparse_keymap_entry_from_keycode()`

```c
struct key_entry * sparse_keymap_entry_from_keycode(struct input_dev *dev, unsigned int keycode)
```

perform sparse keymap lookup

**Parameters**

- `struct input_dev *dev`: Input device using sparse keymap
- `unsigned int keycode`: Key code

**Description**

This function is used to perform [`struct key_entry`](#c-struct-key_entry) lookup in an
input device using sparse keymap.

#### <a id="c-sparse_keymap_setup"></a>`sparse_keymap_setup()`

```c
int sparse_keymap_setup(struct input_dev *dev, const struct key_entry *keymap, int (*setup)(struct input_dev *, struct key_entry *))
```

set up sparse keymap for an input device

**Parameters**

- `struct input_dev *dev`: Input device
- `const struct key_entry *keymap`: Keymap in form of array of [`key_entry`](#c-struct-key_entry) structures ending
  with `KE_END` type entry
- `int (*setup)(struct input_dev *, struct key_entry *)`: Function that can be used to adjust keymap entries
  depending on device's needs, may be `NULL`

**Description**

The function calculates size and allocates copy of the original
keymap after which sets up input device event bits appropriately.
The allocated copy of the keymap is automatically freed when it
is no longer needed.

#### <a id="c-sparse_keymap_report_entry"></a>`sparse_keymap_report_entry()`

```c
void sparse_keymap_report_entry(struct input_dev *dev, const struct key_entry *ke, unsigned int value, bool autorelease)
```

report event corresponding to given key entry

**Parameters**

- `struct input_dev *dev`: Input device for which event should be reported
- `const struct key_entry *ke`: key entry describing event
- `unsigned int value`: Value that should be reported (ignored by `KE_SW` entries)
- `bool autorelease`: Signals whether release event should be emitted for `KE_KEY`
  entries right after reporting press event, ignored by all other
  entries

**Description**

This function is used to report input event described by given
[`struct key_entry`](#c-struct-key_entry).

#### <a id="c-sparse_keymap_report_event"></a>`sparse_keymap_report_event()`

```c
bool sparse_keymap_report_event(struct input_dev *dev, unsigned int code, unsigned int value, bool autorelease)
```

report event corresponding to given scancode

**Parameters**

- `struct input_dev *dev`: Input device using sparse keymap
- `unsigned int code`: Scan code
- `unsigned int value`: Value that should be reported (ignored by `KE_SW` entries)
- `bool autorelease`: Signals whether release event should be emitted for `KE_KEY`
  entries right after reporting press event, ignored by all other
  entries

**Description**

This function is used to perform lookup in an input device using sparse
keymap and report corresponding event. Returns `true` if lookup was
successful and `false` otherwise.


<a id="rst-ps-2-protocol-support"></a>

## PS/2 protocol support


#### <a id="c-enum-ps2_disposition"></a>`enum ps2_disposition`

indicates how received byte should be handled

**Constants**

- `PS2_PROCESS`: pass to the main protocol handler, process normally
- `PS2_IGNORE`: skip the byte
- `PS2_ERROR`: do not process the byte, abort command in progress

#### <a id="c-struct-ps2dev"></a>`struct ps2dev`

represents a device using PS/2 protocol

**Definition**

```c
struct ps2dev {
    struct serio *serio;
    struct mutex cmd_mutex;
    wait_queue_head_t wait;
    unsigned long flags;
    u8 cmdbuf[8];
    u8 cmdcnt;
    u8 nak;
    ps2_pre_receive_handler_t pre_receive_handler;
    ps2_receive_handler_t receive_handler;
};
```

**Members**

- `serio`: a serio port used by the PS/2 device
- `cmd_mutex`: a mutex ensuring that only one command is executing at a time
- `wait`: a waitqueue used to signal completion from the serio interrupt handler
- `flags`: various internal flags indicating stages of PS/2 command execution
- `cmdbuf`: buffer holding command response
- `cmdcnt`: outstanding number of bytes of the command response
- `nak`: a byte transmitted by the device when it refuses command
- `pre_receive_handler`: checks communication errors and returns disposition
  ([`enum ps2_disposition`](#c-enum-ps2_disposition)) of the received data byte
- `receive_handler`: main handler of particular PS/2 protocol, such as keyboard
  or mouse protocol



#### <a id="c-ps2_sendbyte"></a>`ps2_sendbyte()`

```c
int ps2_sendbyte(struct ps2dev *ps2dev, u8 byte, unsigned int timeout)
```

sends a byte to the device and wait for acknowledgement

**Parameters**

- `struct ps2dev *ps2dev`: a PS/2 device to send the data to
- `u8 byte`: data to be sent to the device
- `unsigned int timeout`: timeout for sending the data and receiving an acknowledge

**Description**

The function doesn't handle retransmission, the caller is expected to handle
it when needed.

[`ps2_sendbyte()`](#c-ps2_sendbyte) can only be called from a process context.

#### <a id="c-ps2_begin_command"></a>`ps2_begin_command()`

```c
void ps2_begin_command(struct ps2dev *ps2dev)
```

mark beginning of execution of a complex command

**Parameters**

- `struct ps2dev *ps2dev`: a PS/2 device executing the command

**Description**

Serializes a complex/compound command. Once command is finished
[`ps2_end_command()`](#c-ps2_end_command) should be called.

#### <a id="c-ps2_end_command"></a>`ps2_end_command()`

```c
void ps2_end_command(struct ps2dev *ps2dev)
```

mark end of execution of a complex command

**Parameters**

- `struct ps2dev *ps2dev`: a PS/2 device executing the command

#### <a id="c-ps2_drain"></a>`ps2_drain()`

```c
void ps2_drain(struct ps2dev *ps2dev, size_t maxbytes, unsigned int timeout)
```

waits for device to transmit requested number of bytes and discards them

**Parameters**

- `struct ps2dev *ps2dev`: the PS/2 device that should be drained
- `size_t maxbytes`: maximum number of bytes to be drained
- `unsigned int timeout`: time to drain the device

#### <a id="c-ps2_is_keyboard_id"></a>`ps2_is_keyboard_id()`

```c
bool ps2_is_keyboard_id(u8 id_byte)
```

checks received ID byte against the list of known keyboard IDs

**Parameters**

- `u8 id_byte`: data byte that should be checked

#### <a id="c-__ps2_command"></a>`__ps2_command()`

```c
int __ps2_command(struct ps2dev *ps2dev, u8 *param, unsigned int command)
```

send a command to PS/2 device

**Parameters**

- `struct ps2dev *ps2dev`: the PS/2 device that should execute the command
- `u8 *param`: a buffer containing parameters to be sent along with the command,
  or place where the results of the command execution will be deposited,
  or both
- `unsigned int command`: command word that encodes the command itself, as well as number of
  additional parameter bytes that should be sent to the device and expected
  length of the command response

**Description**

Not serialized. Callers should use [`ps2_begin_command()`](#c-ps2_begin_command) and [`ps2_end_command()`](#c-ps2_end_command)
to ensure proper serialization for complex commands.

#### <a id="c-ps2_command"></a>`ps2_command()`

```c
int ps2_command(struct ps2dev *ps2dev, u8 *param, unsigned int command)
```

send a command to PS/2 device

**Parameters**

- `struct ps2dev *ps2dev`: the PS/2 device that should execute the command
- `u8 *param`: a buffer containing parameters to be sent along with the command,
  or place where the results of the command execution will be deposited,
  or both
- `unsigned int command`: command word that encodes the command itself, as well as number of
  additional parameter bytes that should be sent to the device and expected
  length of the command response

**Note**

[`ps2_command()`](#c-ps2_command) serializes the command execution so that only one
command can be executed at a time for either individual port or the entire
8042 controller.

#### <a id="c-ps2_sliced_command"></a>`ps2_sliced_command()`

```c
int ps2_sliced_command(struct ps2dev *ps2dev, u8 command)
```

sends an extended PS/2 command to a mouse

**Parameters**

- `struct ps2dev *ps2dev`: the PS/2 device that should execute the command
- `u8 command`: command byte

**Description**

The command is sent using "sliced" syntax understood by advanced devices,
such as Logitech or Synaptics touchpads. The command is encoded as:
0xE6 0xE8 rr 0xE8 ss 0xE8 tt 0xE8 uu where (rr*64)+(ss*16)+(tt*4)+uu
is the command.

#### <a id="c-ps2_init"></a>`ps2_init()`

```c
void ps2_init(struct ps2dev *ps2dev, struct serio *serio, ps2_pre_receive_handler_t pre_receive_handler, ps2_receive_handler_t receive_handler)
```

initializes ps2dev structure

**Parameters**

- `struct ps2dev *ps2dev`: structure to be initialized
- `struct serio *serio`: serio port associated with the PS/2 device
- `ps2_pre_receive_handler_t pre_receive_handler`: validation handler to check basic communication state
- `ps2_receive_handler_t receive_handler`: main protocol handler

**Description**

Prepares ps2dev structure for use in drivers for PS/2 devices.

#### <a id="c-ps2_interrupt"></a>`ps2_interrupt()`

```c
irqreturn_t ps2_interrupt(struct serio *serio, u8 data, unsigned int flags)
```

common interrupt handler for PS/2 devices

**Parameters**

- `struct serio *serio`: serio port for the device
- `u8 data`: a data byte received from the device
- `unsigned int flags`: flags such as `SERIO_PARITY` or `SERIO_TIMEOUT` indicating state of
  the data transfer

**Description**

[`ps2_interrupt()`](#c-ps2_interrupt) invokes pre-receive handler, optionally handles command
acknowledgement and response from the device, and finally passes the data
to the main protocol handler for future processing.

---

# Generic System Interconnect Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This framework is designed to provide a standard kernel interface to control the settings of the interconnects on an SoC. These settings can be throughput, latency and priority between multiple interconnected devices or functional blocks.…

<a id="rst-generic-system-interconnect-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

This framework is designed to provide a standard kernel interface to control the settings of the interconnects on an SoC. These settings can be throughput, latency and priority between multiple interconnected devices or functional blocks. This can be controlled dynamically in order to save power or provide maximum performance.

The interconnect bus is hardware with configurable parameters, which can be set on a data path according to the requests received from various drivers. An example of interconnect buses are the interconnects between various components or functional blocks in chipsets. There can be multiple interconnects on an SoC that can be multi-tiered.

Below is a simplified diagram of a real-world SoC interconnect bus topology.



```text
+----------------+    +----------------+
| HW Accelerator |--->|      M NoC     |<---------------+
+----------------+    +----------------+                |
                        |      |                    +------------+
 +-----+  +-------------+      V       +------+     |            |
 | DDR |  |                +--------+  | PCIe |     |            |
 +-----+  |                | Slaves |  +------+     |            |
   ^ ^    |                +--------+     |         |   C NoC    |
   | |    V                               V         |            |
+------------------+   +------------------------+   |            |   +-----+
|                  |-->|                        |-->|            |-->| CPU |
|                  |-->|                        |<--|            |   +-----+
|     Mem NoC      |   |         S NoC          |   +------------+
|                  |<--|                        |---------+    |
|                  |<--|                        |<------+ |    |   +--------+
+------------------+   +------------------------+       | |    +-->| Slaves |
  ^  ^    ^    ^          ^                             | |        +--------+
  |  |    |    |          |                             | V
+------+  |  +-----+   +-----+  +---------+   +----------------+   +--------+
| CPUs |  |  | GPU |   | DSP |  | Masters |-->|       P NoC    |-->| Slaves |
+------+  |  +-----+   +-----+  +---------+   +----------------+   +--------+
          |
      +-------+
      | Modem |
      +-------+
```

<a id="rst-terminology"></a>

## Terminology

Interconnect provider is the software definition of the interconnect hardware. The interconnect providers on the above diagram are M NoC, S NoC, C NoC, P NoC and Mem NoC.

Interconnect node is the software definition of the interconnect hardware port. Each interconnect provider consists of multiple interconnect nodes, which are connected to other SoC components including other interconnect providers. The point on the diagram where the CPUs connect to the memory is called an interconnect node, which belongs to the Mem NoC interconnect provider.

Interconnect endpoints are the first or the last element of the path. Every endpoint is a node, but not every node is an endpoint.

Interconnect path is everything between two endpoints including all the nodes that have to be traversed to reach from a source to destination node. It may include multiple master-slave pairs across several interconnect providers.

Interconnect consumers are the entities which make use of the data paths exposed by the providers. The consumers send requests to providers requesting various throughput, latency and priority. Usually the consumers are device drivers, that send request based on their needs. An example for a consumer is a video decoder that supports various formats and image sizes.

<a id="rst-interconnect-providers"></a>

## Interconnect providers

Interconnect provider is an entity that implements methods to initialize and configure interconnect bus hardware. The interconnect provider drivers should be registered with the interconnect provider core.


#### <a id="c-struct-icc_node_data"></a>`struct icc_node_data`

icc node data

**Definition**

```c
struct icc_node_data {
    struct icc_node *node;
    u32 tag;
};
```

**Members**

- `node`: icc node
- `tag`: tag

#### <a id="c-struct-icc_onecell_data"></a>`struct icc_onecell_data`

driver data for onecell interconnect providers

**Definition**

```c
struct icc_onecell_data {
    unsigned int num_nodes;
    struct icc_node *nodes[] ;
};
```

**Members**

- `num_nodes`: number of nodes in this device
- `nodes`: array of pointers to the nodes in this device

#### <a id="c-struct-icc_provider"></a>`struct icc_provider`

interconnect provider (controller) entity that might provide multiple interconnect controls

**Definition**

```c
struct icc_provider {
    struct list_head        provider_list;
    struct list_head        nodes;
    int (*set)(struct icc_node *src, struct icc_node *dst);
    int (*aggregate)(struct icc_node *node, u32 tag, u32 avg_bw, u32 peak_bw, u32 *agg_avg, u32 *agg_peak);
    void (*pre_aggregate)(struct icc_node *node);
    int (*get_bw)(struct icc_node *node, u32 *avg, u32 *peak);
    struct icc_node* (*xlate)(const struct of_phandle_args *spec, void *data);
    struct icc_node_data* (*xlate_extended)(const struct of_phandle_args *spec, void *data);
    struct device           *dev;
    int users;
    bool inter_set;
    void *data;
};
```

**Members**

- `provider_list`: list of the registered interconnect providers
- `nodes`: internal list of the interconnect provider nodes
- `set`: pointer to device specific set operation function
- `aggregate`: pointer to device specific aggregate operation function
- `pre_aggregate`: pointer to device specific function that is called
  before the aggregation begins (optional)
- `get_bw`: pointer to device specific function to get current bandwidth
- `xlate`: provider-specific callback for mapping nodes from phandle arguments
- `xlate_extended`: vendor-specific callback for mapping node data from phandle arguments
- `dev`: the device this interconnect provider belongs to
- `users`: count of active users
- `inter_set`: whether inter-provider pairs will be configured with **set**
- `data`: pointer to private data

#### <a id="c-struct-icc_node"></a>`struct icc_node`

entity that is part of the interconnect topology

**Definition**

```c
struct icc_node {
    int id;
    const char              *name;
    struct icc_node         **links;
    size_t num_links;
    struct icc_provider     *provider;
    struct list_head        node_list;
    struct list_head        search_list;
    struct icc_node         *reverse;
    u8 is_traversed:1;
    struct hlist_head       req_list;
    u32 avg_bw;
    u32 peak_bw;
    u32 init_avg;
    u32 init_peak;
    void *data;
};
```

**Members**

- `id`: platform specific node id
- `name`: node name used in debugfs
- `links`: a list of targets pointing to where we can go next when traversing
- `num_links`: number of links to other interconnect nodes
- `provider`: points to the interconnect provider of this node
- `node_list`: the list entry in the parent provider's "nodes" list
- `search_list`: list used when walking the nodes graph
- `reverse`: pointer to previous node when walking the nodes graph
- `is_traversed`: flag that is used when walking the nodes graph
- `req_list`: a list of QoS constraint requests associated with this node
- `avg_bw`: aggregated value of average bandwidth requests from all consumers
- `peak_bw`: aggregated value of peak bandwidth requests from all consumers
- `init_avg`: average bandwidth value that is read from the hardware during init
- `init_peak`: peak bandwidth value that is read from the hardware during init
- `data`: pointer to private data


<a id="rst-interconnect-consumers"></a>

## Interconnect consumers

Interconnect consumers are the clients which use the interconnect APIs to get paths between endpoints and set their bandwidth/latency/QoS requirements for these interconnect paths.  These interfaces are not currently documented.

<a id="rst-interconnect-debugfs-interfaces"></a>

## Interconnect debugfs interfaces

Like several other subsystems interconnect will create some files for debugging and introspection. Files in debugfs are not considered ABI so application software shouldn't rely on format details change between kernel versions.

`/sys/kernel/debug/interconnect/interconnect_summary`:

Show all interconnect nodes in the system with their aggregated bandwidth request. Indented under each node show bandwidth requests from each device.

`/sys/kernel/debug/interconnect/interconnect_graph`:

Show the interconnect graph in the graphviz dot format. It shows all interconnect nodes and links in the system and groups together nodes from the same provider as subgraphs. The format is human-readable and can also be piped through dot to generate diagrams in many graphical formats:



```text
$ cat /sys/kernel/debug/interconnect/interconnect_graph | \
        dot -Tsvg > interconnect_graph.svg
```

The `test-client` directory provides interfaces for issuing BW requests to any arbitrary path. Note that for safety reasons, this feature is disabled by default without a Kconfig to enable it. Enabling it requires code changes to `#define INTERCONNECT_ALLOW_WRITE_DEBUGFS`. Example usage:



```text
cd /sys/kernel/debug/interconnect/test-client/

# Configure node endpoints for the path from CPU to DDR on
# qcom/sm8550.
echo chm_apps > src_node
echo ebi > dst_node

# Get path between src_node and dst_node. This is only
# necessary after updating the node endpoints.
echo 1 > get

# Set desired BW to 1GBps avg and 2GBps peak.
echo 1000000 > avg_bw
echo 2000000 > peak_bw

# Vote for avg_bw and peak_bw on the latest path from "get".
# Voting for multiple paths is possible by repeating this
# process for different nodes endpoints.
echo 1 > commit
```

---

# IPMB Driver for a Satellite MC

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> The Intelligent Platform Management Bus or IPMB, is an I2C bus that provides a standardized interconnection between different boards within a chassis. This interconnection is between the baseboard management (BMC) and chassis electronics.…

<a id="rst-ipmb-driver-for-a-satellite-mc"></a>

The Intelligent Platform Management Bus or IPMB, is an I2C bus that provides a standardized interconnection between different boards within a chassis. This interconnection is between the baseboard management (BMC) and chassis electronics. IPMB is also associated with the messaging protocol through the IPMB bus.

The devices using the IPMB are usually management controllers that perform management functions such as servicing the front panel interface, monitoring the baseboard, hot-swapping disk drivers in the system chassis, etc...

When an IPMB is implemented in the system, the BMC serves as a controller to give system software access to the IPMB. The BMC sends IPMI requests to a device (usually a Satellite Management Controller or Satellite MC) via IPMB and the device sends a response back to the BMC.

For more information on IPMB and the format of an IPMB message, refer to the IPMB and IPMI specifications.

<a id="rst-ipmb-driver-for-satellite-mc"></a>

## IPMB driver for Satellite MC

ipmb-dev-int - This is the driver needed on a Satellite MC to receive IPMB messages from a BMC and send a response back. This driver works with the I2C driver and a userspace program such as OpenIPMI:

1. It is an I2C slave backend driver. So, it defines a callback function to set the Satellite MC as an I2C slave. This callback function handles the received IPMI requests.

2. It defines the read and write functions to enable a user space program (such as OpenIPMI) to communicate with the kernel.

<a id="rst-load-the-ipmb-driver"></a>

## Load the IPMB driver

The driver needs to be loaded at boot time or manually first. First, make sure you have the following in your config file: CONFIG_IPMB_DEVICE_INTERFACE=y

1. If you want the driver to be loaded at boot time:

- **a)** Add this entry to your ACPI table, under the appropriate SMBus:



  ```text
  Device (SMB0) // Example SMBus host controller
  {
  Name (_HID, "<Vendor-Specific HID>") // Vendor-Specific HID
  Name (_UID, 0) // Unique ID of particular host controller
  :
  :
    Device (IPMB)
    {
      Name (_HID, "IPMB0001") // IPMB device interface
      Name (_UID, 0) // Unique device identifier
    }
  }
  ```

- **b)** Example for device tree:



  ```text
  &i2c2 {
         status = "okay";

         ipmb@10 {
                 compatible = "ipmb-dev";
                 reg = <0x10>;
                 i2c-protocol;
         };
  };
  ```

If xmit of data to be done using raw i2c block vs smbus then "i2c-protocol" needs to be defined as above.

2. Manually from Linux:



   ```text
   modprobe ipmb-dev-int
   ```

<a id="rst-instantiate-the-device"></a>

## Instantiate the device

After loading the driver, you can instantiate the device as described in '[Documentation/i2c/instantiating-devices.rst](/kernel/hardware/i2c/instantiating-devices.md)'. If you have multiple BMCs, each connected to your Satellite MC via a different I2C bus, you can instantiate a device for each of those BMCs.

The name of the instantiated device contains the I2C bus number associated with it as follows:



```text
BMC1 ------ IPMB/I2C bus 1 ---------|   /dev/ipmb-1
                              Satellite MC
BMC1 ------ IPMB/I2C bus 2 ---------|   /dev/ipmb-2
```

For instance, you can instantiate the ipmb-dev-int device from user space at the 7 bit address 0x10 on bus 2:



```text
# echo ipmb-dev 0x1010 > /sys/bus/i2c/devices/i2c-2/new_device
```

This will create the device file /dev/ipmb-2, which can be accessed by the user space program. The device needs to be instantiated before running the user space program.

---

# The Linux IPMI Driver

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> The Intelligent Platform Management Interface, or IPMI, is a standard for controlling intelligent devices that monitor a system. It provides for dynamic discovery of sensors in the system and the ability to monitor the sensors and be…

<a id="rst-the-linux-ipmi-driver"></a>

**Author:** Corey Minyard &lt;[minyard@mvista.com](<mailto:minyard@mvista.com>)&gt; / &lt;[minyard@acm.org](<mailto:minyard@acm.org>)&gt;

The Intelligent Platform Management Interface, or IPMI, is a standard for controlling intelligent devices that monitor a system. It provides for dynamic discovery of sensors in the system and the ability to monitor the sensors and be informed when the sensor's values change or go outside certain boundaries.  It also has a standardized database for field-replaceable units (FRUs) and a watchdog timer.

To use this, you need an interface to an IPMI controller in your system (called a Baseboard Management Controller, or BMC) and management software that can use the IPMI system.

This document describes how to use the IPMI driver for Linux.  If you are not familiar with IPMI itself, see the web site at [https://www.intel.com/design/servers/ipmi/index.htm](<https://www.intel.com/design/servers/ipmi/index.htm>).  IPMI is a big subject and I can't cover it all here\!

<a id="rst-configuration"></a>

## Configuration

The Linux IPMI driver is modular, which means you have to pick several things to have it work right depending on your hardware.  Most of these are available in the 'Character Devices' menu then the IPMI menu.

No matter what, you must pick 'IPMI top-level message handler' to use IPMI.  What you do beyond that depends on your needs and hardware.

The message handler does not provide any user-level interfaces. Kernel code (like the watchdog) can still use it.  If you need access from userland, you need to select 'Device interface for IPMI' if you want access through a device driver.

The driver interface depends on your hardware.  If your system properly provides the SMBIOS info for IPMI, the driver will detect it and just work.  If you have a board with a standard interface (These will generally be either "KCS", "SMIC", or "BT", consult your hardware manual), choose the 'IPMI SI handler' option.  A driver also exists for direct I2C access to the IPMI management controller.  Some boards support this, but it is unknown if it will work on every board.  For this, choose 'IPMI SMBus handler', but be ready to try to do some figuring to see if it will work on your system if the SMBIOS/ACPI information is wrong or not present.  It is fairly safe to have both these enabled and let the drivers auto-detect what is present.

You should generally enable ACPI on your system, as systems with IPMI can have ACPI tables describing them.

If you have a standard interface and the board manufacturer has done their job correctly, the IPMI controller should be automatically detected (via ACPI or SMBIOS tables) and should just work.  Sadly, many boards do not have this information.  The driver attempts standard defaults, but they may not work.  If you fall into this situation, you need to read the section below named 'The SI Driver' or "The SMBus Driver" on how to hand-configure your system.

IPMI defines a standard watchdog timer.  You can enable this with the 'IPMI Watchdog Timer' config option.  If you compile the driver into the kernel, then via a kernel command-line option you can have the watchdog timer start as soon as it initializes.  It also has a lot of other options, see the 'Watchdog' section below for more details. Note that you can also have the watchdog continue to run if it is closed (by default it is disabled on close).  Go into the 'Watchdog Cards' menu, enable 'Watchdog Timer Support', and enable the option 'Disable watchdog shutdown on close'.

IPMI systems can often be powered off using IPMI commands.  Select 'IPMI Poweroff' to do this.  The driver will auto-detect if the system can be powered off by IPMI.  It is safe to enable this even if your system doesn't support this option.  This works on ATCA systems, the Radisys CPI1 card, and any IPMI system that supports standard chassis management commands.

If you want the driver to put an event into the event log on a panic, enable the 'Generate a panic event to all BMCs on a panic' option.  If you want the whole panic string put into the event log using OEM events, enable the 'Generate OEM events containing the panic string' option.  You can also enable these dynamically by setting the module parameter named "panic_op" in the ipmi_msghandler module to "event" or "string".  Setting that parameter to "none" disables this function.

<a id="rst-basic-design"></a>

## Basic Design

The Linux IPMI driver is designed to be very modular and flexible, you only need to take the pieces you need and you can use it in many different ways.  Because of that, it's broken into many chunks of code.  These chunks (by module name) are:

ipmi_msghandler - This is the central piece of software for the IPMI system.  It handles all messages, message timing, and responses.  The IPMI users tie into this, and the IPMI physical interfaces (called System Management Interfaces, or SMIs) also tie in here.  This provides the kernelland interface for IPMI, but does not provide an interface for use by application processes.

ipmi_devintf - This provides a userland IOCTL interface for the IPMI driver, each open file for this device ties in to the message handler as an IPMI user.

ipmi_si - A driver for various system interfaces.  This supports KCS, SMIC, and BT interfaces.  Unless you have an SMBus interface or your own custom interface, you probably need to use this.

ipmi_ssif - A driver for accessing BMCs on the SMBus. It uses the I2C kernel driver's SMBus interfaces to send and receive IPMI messages over the SMBus.

ipmi_powernv - A driver for access BMCs on POWERNV systems.

ipmi_watchdog - IPMI requires systems to have a very capable watchdog timer.  This driver implements the standard Linux watchdog timer interface on top of the IPMI message handler.

ipmi_poweroff - Some systems support the ability to be turned off via IPMI commands.

bt-bmc - This is not part of the main driver, but instead a driver for accessing a BMC-side interface of a BT interface.  It is used on BMCs running Linux to provide an interface to the host.

These are all individually selectable via configuration options.

Much documentation for the interface is in the include files.  The IPMI include files are:

linux/ipmi.h - Contains the user interface and IOCTL interface for IPMI.

linux/ipmi_smi.h - Contains the interface for system management interfaces (things that interface to IPMI controllers) to use.

linux/ipmi_msgdefs.h - General definitions for base IPMI messaging.

<a id="rst-addressing"></a>

## Addressing

The IPMI addressing works much like IP addresses, you have an overlay to handle the different address types.  The overlay is:



```text
struct ipmi_addr
{
      int   addr_type;
      short channel;
      char  data[IPMI_MAX_ADDR_SIZE];
};
```

The addr_type determines what the address really is.  The driver currently understands two different types of addresses.

"System Interface" addresses are defined as:



```text
struct ipmi_system_interface_addr
{
      int   addr_type;
      short channel;
};
```

and the type is IPMI_SYSTEM_INTERFACE_ADDR_TYPE.  This is used for talking straight to the BMC on the current card.  The channel must be IPMI_BMC_CHANNEL.

Messages that are destined to go out on the IPMB bus going through the BMC use the IPMI_IPMB_ADDR_TYPE address type.  The format is:



```text
struct ipmi_ipmb_addr
{
      int           addr_type;
      short         channel;
      unsigned char slave_addr;
      unsigned char lun;
};
```

The "channel" here is generally zero, but some devices support more than one channel, it corresponds to the channel as defined in the IPMI spec.

There is also an IPMB direct address for a situation where the sender is directly on an IPMB bus and doesn't have to go through the BMC. You can send messages to a specific management controller (MC) on the IPMB using the IPMI_IPMB_DIRECT_ADDR_TYPE with the following format:



```text
struct ipmi_ipmb_direct_addr
{
      int           addr_type;
      short         channel;
      unsigned char slave_addr;
      unsigned char rq_lun;
      unsigned char rs_lun;
};
```

The channel is always zero.  You can also receive commands from other MCs that you have registered to handle and respond to them, so you can use this to implement a management controller on a bus..

<a id="rst-messages"></a>

## Messages

Messages are defined as:



```text
struct ipmi_msg
{
      unsigned char netfn;
      unsigned char lun;
      unsigned char cmd;
      unsigned char *data;
      int           data_len;
};
```

The driver takes care of adding/stripping the header information.  The data portion is just the data to be send (do NOT put addressing info here) or the response.  Note that the completion code of a response is the first item in "data", it is not stripped out because that is how all the messages are defined in the spec (and thus makes counting the offsets a little easier :-).

When using the IOCTL interface from userland, you must provide a block of data for "data", fill it, and set data_len to the length of the block of data, even when receiving messages.  Otherwise the driver will have no place to put the message.

Messages coming up from the message handler in kernelland will come in as:



```text
struct ipmi_recv_msg
{
      struct list_head link;

      /* The type of message as defined in the "Receive Types"
         defines above. */
      int         recv_type;

      ipmi_user_t      *user;
      struct ipmi_addr addr;
      long             msgid;
      struct ipmi_msg  msg;

      /* Call this when done with the message.  It will presumably free
         the message and do any other necessary cleanup. */
      void (*done)(struct ipmi_recv_msg *msg);

      /* Place-holder for the data, don't make any assumptions about
         the size or existence of this, since it may change. */
      unsigned char   msg_data[IPMI_MAX_MSG_LENGTH];
};
```

You should look at the receive type and handle the message appropriately.

<a id="rst-the-upper-layer-interface-message-handler"></a>

## The Upper Layer Interface (Message Handler)

The upper layer of the interface provides the users with a consistent view of the IPMI interfaces.  It allows multiple SMI interfaces to be addressed (because some boards actually have multiple BMCs on them) and the user should not have to care what type of SMI is below them.

<a id="rst-watching-for-interfaces"></a>

### Watching For Interfaces

When your code comes up, the IPMI driver may or may not have detected if IPMI devices exist.  So you might have to defer your setup until the device is detected, or you might be able to do it immediately. To handle this, and to allow for discovery, you register an SMI watcher with ipmi_smi_watcher_register() to iterate over interfaces and tell you when they come and go.

<a id="rst-creating-the-user"></a>

### Creating the User

To use the message handler, you must first create a user using ipmi_create_user.  The interface number specifies which SMI you want to connect to, and you must supply callback functions to be called when data comes in.  This also allows to you pass in a piece of data, the handler_data, that will be passed back to you on all calls.

Once you are done, call ipmi_destroy_user() to get rid of the user.

From userland, opening the device automatically creates a user, and closing the device automatically destroys the user.

<a id="rst-messaging"></a>

### Messaging

To send a message from kernel-land, the ipmi_request_settime() call does pretty much all message handling.  Most of the parameter are self-explanatory.  However, it takes a "msgid" parameter.  This is NOT the sequence number of messages.  It is simply a long value that is passed back when the response for the message is returned.  You may use it for anything you like.

Responses come back in the function pointed to by the ipmi_recv_hndl field of the "handler" that you passed in to ipmi_create_user(). Remember to look at the receive type, too.

From userland, you fill out an ipmi_req_t structure and use the IPMICTL_SEND_COMMAND ioctl.  For incoming stuff, you can use select() or poll() to wait for messages to come in.  However, you cannot use read() to get them, you must call the IPMICTL_RECEIVE_MSG with the ipmi_recv_t structure to actually get the message.  Remember that you must supply a pointer to a block of data in the msg.data field, and you must fill in the msg.data_len field with the size of the data. This gives the receiver a place to actually put the message.

If the message cannot fit into the data you provide, you will get an EMSGSIZE error and the driver will leave the data in the receive queue.  If you want to get it and have it truncate the message, use the IPMICTL_RECEIVE_MSG_TRUNC ioctl.

When you send a command (which is defined by the lowest-order bit of the netfn per the IPMI spec) on the IPMB bus, the driver will automatically assign the sequence number to the command and save the command.  If the response is not received in the IPMI-specified 5 seconds, it will generate a response automatically saying the command timed out.  If an unsolicited response comes in (if it was after 5 seconds, for instance), that response will be ignored.

In kernelland, after you receive a message and are done with it, you MUST call ipmi_free_recv_msg() on it, or you will leak messages.  Note that you should NEVER mess with the "done" field of a message, that is required to properly clean up the message.

Note that when sending, there is an ipmi_request_supply_msgs() call that lets you supply the smi and receive message.  This is useful for pieces of code that need to work even if the system is out of buffers (the watchdog timer uses this, for instance).  You supply your own buffer and own free routines.  This is not recommended for normal use, though, since it is tricky to manage your own buffers.

<a id="rst-events-and-incoming-commands"></a>

### Events and Incoming Commands

The driver takes care of polling for IPMI events and receiving commands (commands are messages that are not responses, they are commands that other things on the IPMB bus have sent you).  To receive these, you must register for them, they will not automatically be sent to you.

To receive events, you must call ipmi_set_gets_events() and set the "val" to non-zero.  Any events that have been received by the driver since startup will immediately be delivered to the first user that registers for events.  After that, if multiple users are registered for events, they will all receive all events that come in.

For receiving commands, you have to individually register commands you want to receive.  Call ipmi_register_for_cmd() and supply the netfn and command name for each command you want to receive.  You also specify a bitmask of the channels you want to receive the command from (or use IPMI_CHAN_ALL for all channels if you don't care).  Only one user may be registered for each netfn/cmd/channel, but different users may register for different commands, or the same command if the channel bitmasks do not overlap.

To respond to a received command, set the response bit in the returned netfn, use the address from the received message, and use the same msgid that you got in the received message.

From userland, equivalent IOCTLs are provided to do these functions.

<a id="rst-the-lower-layer-smi-interface"></a>

## The Lower Layer (SMI) Interface

As mentioned before, multiple SMI interfaces may be registered to the message handler, each of these is assigned an interface number when they register with the message handler.  They are generally assigned in the order they register, although if an SMI unregisters and then another one registers, all bets are off.

The ipmi_smi.h defines the interface for management interfaces, see that for more details.

<a id="rst-the-si-driver"></a>

## The SI Driver

The SI driver allows KCS, BT, and SMIC interfaces to be configured in the system.  It discovers interfaces through a host of different methods, depending on the system.

You can specify up to four interfaces on the module load line and control some module parameters:



```text
modprobe ipmi_si.o type=<type1>,<type2>....
     ports=<port1>,<port2>... addrs=<addr1>,<addr2>...
     irqs=<irq1>,<irq2>...
     regspacings=<sp1>,<sp2>,... regsizes=<size1>,<size2>,...
     regshifts=<shift1>,<shift2>,...
     slave_addrs=<addr1>,<addr2>,...
     force_kipmid=<enable1>,<enable2>,...
     kipmid_max_busy_us=<ustime1>,<ustime2>,...
     unload_when_empty=[0|1]
     trydmi=[0|1] tryacpi=[0|1]
     tryplatform=[0|1] trypci=[0|1]
```

Each of these except try... items is a list, the first item for the first interface, second item for the second interface, etc.

The si_type may be either "kcs", "smic", or "bt".  If you leave it blank, it defaults to "kcs".

If you specify addrs as non-zero for an interface, the driver will use the memory address given as the address of the device.  This overrides si_ports.

If you specify ports as non-zero for an interface, the driver will use the I/O port given as the device address.

If you specify irqs as non-zero for an interface, the driver will attempt to use the given interrupt for the device.

The other try... items disable discovery by their corresponding names.  These are all enabled by default, set them to zero to disable them.  The tryplatform disables openfirmware.

The next three parameters have to do with register layout.  The registers used by the interfaces may not appear at successive locations and they may not be in 8-bit registers.  These parameters allow the layout of the data in the registers to be more precisely specified.

The regspacings parameter give the number of bytes between successive register start addresses.  For instance, if the regspacing is set to 4 and the start address is 0xca2, then the address for the second register would be 0xca6.  This defaults to 1.

The regsizes parameter gives the size of a register, in bytes.  The data used by IPMI is 8-bits wide, but it may be inside a larger register.  This parameter allows the read and write type to be specified. It may be 1, 2, 4, or 8.  The default is 1.

Since the register size may be larger than 32 bits, the IPMI data may not be in the lower 8 bits.  The regshifts parameter give the amount to shift the data to get to the actual IPMI data.

The slave_addrs specifies the IPMI address of the local BMC.  This is usually 0x20 and the driver defaults to that, but in case it's not, it can be specified when the driver starts up.

The force_ipmid parameter forcefully enables (if set to 1) or disables (if set to 0) the kernel IPMI daemon.  Normally this is auto-detected by the driver, but systems with broken interrupts might need an enable, or users that don't want the daemon (don't need the performance, don't want the CPU hit) can disable it.

If unload_when_empty is set to 1, the driver will be unloaded if it doesn't find any interfaces or all the interfaces fail to work.  The default is one.  Setting to 0 is useful with the hotmod, but is obviously only useful for modules.

When compiled into the kernel, the parameters can be specified on the kernel command line as:



```text
ipmi_si.type=<type1>,<type2>...
     ipmi_si.ports=<port1>,<port2>... ipmi_si.addrs=<addr1>,<addr2>...
     ipmi_si.irqs=<irq1>,<irq2>...
     ipmi_si.regspacings=<sp1>,<sp2>,...
     ipmi_si.regsizes=<size1>,<size2>,...
     ipmi_si.regshifts=<shift1>,<shift2>,...
     ipmi_si.slave_addrs=<addr1>,<addr2>,...
     ipmi_si.force_kipmid=<enable1>,<enable2>,...
     ipmi_si.kipmid_max_busy_us=<ustime1>,<ustime2>,...
```

It works the same as the module parameters of the same names.

If your IPMI interface does not support interrupts and is a KCS or SMIC interface, the IPMI driver will start a kernel thread for the interface to help speed things up.  This is a low-priority kernel thread that constantly polls the IPMI driver while an IPMI operation is in progress.  The force_kipmid module parameter will allow the user to force this thread on or off.  If you force it off and don't have interrupts, the driver will run VERY slowly.  Don't blame me, these interfaces suck.

Unfortunately, this thread can use a lot of CPU depending on the interface's performance.  This can waste a lot of CPU and cause various issues with detecting idle CPU and using extra power.  To avoid this, the kipmid_max_busy_us sets the maximum amount of time, in microseconds, that kipmid will spin before sleeping for a tick.  This value sets a balance between performance and CPU waste and needs to be tuned to your needs.  Maybe, someday, auto-tuning will be added, but that's not a simple thing and even the auto-tuning would need to be tuned to the user's desired performance.

The driver supports a hot add and remove of interfaces.  This way, interfaces can be added or removed after the kernel is up and running. This is done using /sys/modules/ipmi_si/parameters/hotmod, which is a write-only parameter.  You write a string to this interface.  The string has the format:



```text
<op1>[:op2[:op3...]]
```

The "op"s are:



```text
add|remove,kcs|bt|smic,mem|i/o,<address>[,<opt1>[,<opt2>[,...]]]
```

You can specify more than one interface on the line.  The "opt"s are:



```text
rsp=<regspacing>
rsi=<regsize>
rsh=<regshift>
irq=<irq>
ipmb=<ipmb slave addr>
```

and these have the same meanings as discussed above.  Note that you can also use this on the kernel command line for a more compact format for specifying an interface.  Note that when removing an interface, only the first three parameters (si type, address type, and address) are used for the comparison.  Any options are ignored for removing.

<a id="rst-the-smbus-driver-ssif"></a>

## The SMBus Driver (SSIF)

The SMBus driver allows up to 4 SMBus devices to be configured in the system.  By default, the driver will only register with something it finds in DMI or ACPI tables.  You can change this at module load time (for a module) with:



```text
modprobe ipmi_ssif.o
      addr=<i2caddr1>[,<i2caddr2>[,...]]
      adapter=<adapter1>[,<adapter2>[...]]
      dbg=<flags1>,<flags2>...
      slave_addrs=<addr1>,<addr2>,...
      tryacpi=[0|1] trydmi=[0|1]
      [dbg_probe=1]
      alerts_broken
```

The addresses are normal I2C addresses.  The adapter is the string name of the adapter, as shown in /sys/bus/i2c/devices/i2c-&lt;n&gt;/name. It is *NOT* i2c-&lt;n&gt; itself.  Also, the comparison is done ignoring spaces, so if the name is "This is an I2C chip" you can say adapter_name=ThisisanI2cchip.  This is because it's hard to pass in spaces in kernel parameters.

The debug flags are bit flags for each BMC found, they are: IPMI messages: 1, driver state: 2, timing: 4, I2C probe: 8

The tryxxx parameters can be used to disable detecting interfaces from various sources.

Setting dbg_probe to 1 will enable debugging of the probing and detection process for BMCs on the SMBusses.

The slave_addrs specifies the IPMI address of the local BMC.  This is usually 0x20 and the driver defaults to that, but in case it's not, it can be specified when the driver starts up.

alerts_broken does not enable SMBus alert for SSIF. Otherwise SMBus alert will be enabled on supported hardware.

Discovering the IPMI compliant BMC on the SMBus can cause devices on the I2C bus to fail. The SMBus driver writes a "Get Device ID" IPMI message as a block write to the I2C bus and waits for a response. This action can be detrimental to some I2C devices. It is highly recommended that the known I2C address be given to the SMBus driver in the smb_addr parameter unless you have DMI or ACPI data to tell the driver what to use.

When compiled into the kernel, the addresses can be specified on the kernel command line as:



```text
ipmb_ssif.addr=<i2caddr1>[,<i2caddr2>[...]]
      ipmi_ssif.adapter=<adapter1>[,<adapter2>[...]]
      ipmi_ssif.dbg=<flags1>[,<flags2>[...]]
      ipmi_ssif.dbg_probe=1
      ipmi_ssif.slave_addrs=<addr1>[,<addr2>[...]]
      ipmi_ssif.tryacpi=[0|1] ipmi_ssif.trydmi=[0|1]
```

These are the same options as on the module command line.

The I2C driver does not support non-blocking access or polling, so this driver cannot do IPMI panic events, extend the watchdog at panic time, or other panic-related IPMI functions without special kernel patches and driver modifications.  You can get those at the openipmi web page.

The driver supports a hot add and remove of interfaces through the I2C sysfs interface.

<a id="rst-the-ipmi-ipmb-driver"></a>

## The IPMI IPMB Driver

This driver is for supporting a system that sits on an IPMB bus; it allows the interface to look like a normal IPMI interface.  Sending system interface addressed messages to it will cause the message to go to the registered BMC on the system (default at IPMI address 0x20).

It also allows you to directly address other MCs on the bus using the ipmb direct addressing.  You can receive commands from other MCs on the bus and they will be handled through the normal received command mechanism described above.

Parameters are:



```text
ipmi_ipmb.bmcaddr=<address to use for system interface addresses messages>
      ipmi_ipmb.retry_time_ms=<Time between retries on IPMB>
      ipmi_ipmb.max_retries=<Number of times to retry a message>
```

Loading the module will not result in the driver automatically starting unless there is device tree information setting it up.  If you want to instantiate one of these by hand, do:



```text
echo ipmi-ipmb <addr> > /sys/class/i2c-dev/i2c-<n>/device/new_device
```

Note that the address you give here is the I2C address, not the IPMI address.  So if you want your MC address to be 0x60, you put 0x30 here.  See the I2C driver info for more details.

Command bridging to other IPMB buses through this interface does not work.  The receive message queue is not implemented, by design.  There is only one receive message queue on a BMC, and that is meant for the host drivers, not something on the IPMB bus.

A BMC may have multiple IPMB buses, which bus your device sits on depends on how the system is wired.  You can fetch the channels with "ipmitool channel info &lt;n&gt;" where &lt;n&gt; is the channel, with the channels being 0-7 and try the IPMB channels.

<a id="rst-other-pieces"></a>

## Other Pieces

<a id="rst-get-the-detailed-info-related-with-the-ipmi-device"></a>

## Get the detailed info related with the IPMI device

Some users need more detailed information about a device, like where the address came from or the raw base device for the IPMI interface. You can use the IPMI smi_watcher to catch the IPMI interfaces as they come or go, and to grab the information, you can use the function ipmi_get_smi_info(), which returns the following structure:



```text
struct ipmi_smi_info {
      enum ipmi_addr_src addr_src;
      struct device *dev;
      union {
              struct {
                      void *acpi_handle;
              } acpi_info;
      } addr_info;
};
```

Currently special info for only for SI_ACPI address sources is returned.  Others may be added as necessary.

Note that the dev pointer is included in the above structure, and assuming ipmi_smi_get_info returns success, you must call put_device on the dev pointer.

<a id="rst-watchdog"></a>

## Watchdog

A watchdog timer is provided that implements the Linux-standard watchdog timer interface.  It has three module parameters that can be used to control it:



```text
modprobe ipmi_watchdog timeout=<t> pretimeout=<t> action=<action type>
    preaction=<preaction type> preop=<preop type> start_now=x
    nowayout=x ifnum_to_use=n panic_wdt_timeout=<t>
```

ifnum_to_use specifies which interface the watchdog timer should use. The default is -1, which means to pick the first one registered.

The timeout is the number of seconds to the action, and the pretimeout is the amount of seconds before the reset that the pre-timeout panic will occur (if pretimeout is zero, then pretimeout will not be enabled).  Note that the pretimeout is the time before the final timeout.  So if the timeout is 50 seconds and the pretimeout is 10 seconds, then the pretimeout will occur in 40 second (10 seconds before the timeout). The panic_wdt_timeout is the value of timeout which is set on kernel panic, in order to let actions such as kdump to occur during panic.

The action may be "reset", "power_cycle", or "power_off", and specifies what to do when the timer times out, and defaults to "reset".

The preaction may be "pre_smi" for an indication through the SMI interface, "pre_int" for an indication through the SMI with an interrupts, and "pre_nmi" for a NMI on a preaction.  This is how the driver is informed of the pretimeout.

The preop may be set to "preop_none" for no operation on a pretimeout, "preop_panic" to set the preoperation to panic, or "preop_give_data" to provide data to read from the watchdog device when the pretimeout occurs.  A "pre_nmi" setting CANNOT be used with "preop_give_data" because you can't do data operations from an NMI.

When preop is set to "preop_give_data", one byte comes ready to read on the device when the pretimeout occurs.  Select and fasync work on the device, as well.

If start_now is set to 1, the watchdog timer will start running as soon as the driver is loaded.

If nowayout is set to 1, the watchdog timer will not stop when the watchdog device is closed.  The default value of nowayout is true if the CONFIG_WATCHDOG_NOWAYOUT option is enabled, or false if not.

When compiled into the kernel, the kernel command line is available for configuring the watchdog:



```text
ipmi_watchdog.timeout=<t> ipmi_watchdog.pretimeout=<t>
      ipmi_watchdog.action=<action type>
      ipmi_watchdog.preaction=<preaction type>
      ipmi_watchdog.preop=<preop type>
      ipmi_watchdog.start_now=x
      ipmi_watchdog.nowayout=x
      ipmi_watchdog.panic_wdt_timeout=<t>
```

The options are the same as the module parameter options.

The watchdog will panic and start a 120 second reset timeout if it gets a pre-action.  During a panic or a reboot, the watchdog will start a 120 timer if it is running to make sure the reboot occurs.

Note that if you use the NMI preaction for the watchdog, you MUST NOT use the nmi watchdog.  There is no reasonable way to tell if an NMI comes from the IPMI controller, so it must assume that if it gets an otherwise unhandled NMI, it must be from IPMI and it will panic immediately.

Once you open the watchdog timer, you must write a 'V' character to the device to close it, or the timer will not stop.  This is a new semantic for the driver, but makes it consistent with the rest of the watchdog drivers in Linux.

<a id="rst-panic-timeouts"></a>

## Panic Timeouts

The OpenIPMI driver supports the ability to put semi-custom and custom events in the system event log if a panic occurs.  if you enable the 'Generate a panic event to all BMCs on a panic' option, you will get one event on a panic in a standard IPMI event format.  If you enable the 'Generate OEM events containing the panic string' option, you will also get a bunch of OEM events holding the panic string.

The field settings of the events are:

- Generator ID: 0x21 (kernel)

- EvM Rev: 0x03 (this event is formatting in IPMI 1.0 format)

- Sensor Type: 0x20 (OS critical stop sensor)

- Sensor \#: The first byte of the panic string (0 if no panic string)

- Event Dir \| Event Type: 0x6f (Assertion, sensor-specific event info)

- Event Data 1: 0xa1 (Runtime stop in OEM bytes 2 and 3)

- Event data 2: second byte of panic string

- Event data 3: third byte of panic string

See the IPMI spec for the details of the event layout.  This event is always sent to the local management controller.  It will handle routing the message to the right place

Other OEM events have the following format:

- Record ID (bytes 0-1): Set by the SEL.

- Record type (byte 2): 0xf0 (OEM non-timestamped)

- byte 3: The slave address of the card saving the panic

- byte 4: A sequence number (starting at zero) The rest of the bytes (11 bytes) are the panic string.  If the panic string is longer than 11 bytes, multiple messages will be sent with increasing sequence numbers.

Because you cannot send OEM events using the standard interface, this function will attempt to find an SEL and add the events there.  It will first query the capabilities of the local management controller. If it has an SEL, then they will be stored in the SEL of the local management controller.  If not, and the local management controller is an event generator, the event receiver from the local management controller will be queried and the events sent to the SEL on that device.  Otherwise, the events go nowhere since there is nowhere to send them.

<a id="rst-poweroff"></a>

## Poweroff

If the poweroff capability is selected, the IPMI driver will install a shutdown function into the standard poweroff function pointer.  This is in the ipmi_poweroff module.  When the system requests a powerdown, it will send the proper IPMI commands to do this.  This is supported on several platforms.

There is a module parameter named "poweroff_powercycle" that may either be zero (do a power down) or non-zero (do a power cycle, power the system off, then power it on in a few seconds).  Setting ipmi_poweroff.poweroff_control=x will do the same thing on the kernel command line.  The parameter is also available via the proc filesystem in /proc/sys/dev/ipmi/poweroff_powercycle.  Note that if the system does not support power cycling, it will always do the power off.

The "ifnum_to_use" parameter specifies which interface the poweroff code should use.  The default is -1, which means to pick the first one registered.

Note that if you have ACPI enabled, the system will prefer using ACPI to power off.

---

# The Common Mailbox Framework

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This document aims to help developers write client and controller drivers for the API. But before we start, let us note that the client (especially) and controller drivers are likely going to be very platform specific because the remote…

<a id="rst-the-common-mailbox-framework"></a>

**Author:** Jassi Brar &lt;[jaswinder.singh@linaro.org](<mailto:jaswinder.singh@linaro.org>)&gt;

This document aims to help developers write client and controller drivers for the API. But before we start, let us note that the client (especially) and controller drivers are likely going to be very platform specific because the remote firmware is likely to be proprietary and implement non-standard protocol. So even if two platforms employ, say, PL320 controller, the client drivers can't be shared across them. Even the PL320 driver might need to accommodate some platform specific quirks. So the API is meant mainly to avoid similar copies of code written for each platform. Having said that, nothing prevents the remote f/w to also be Linux based and use the same api there. However none of that helps us locally because we only ever deal at client's protocol level.

Some of the choices made during implementation are the result of this peculiarity of this "common" framework.

<a id="rst-controller-driver-see-include-linux-mailbox-controller-h"></a>

## Controller Driver (See include/linux/mailbox_controller.h)

Allocate mbox_controller and the array of mbox_chan. Populate mbox_chan_ops, except flush() and peek_data() all are mandatory. The controller driver might know a message has been consumed by the remote by getting an IRQ or polling some hardware flag or it can never know (the client knows by way of the protocol). The method in order of preference is IRQ -&gt; Poll -&gt; None, which the controller driver should set via 'txdone_irq' or 'txdone_poll' or neither.

<a id="rst-client-driver-see-include-linux-mailbox-client-h"></a>

## Client Driver (See include/linux/mailbox_client.h)

The client might want to operate in blocking mode (synchronously send a message through before returning) or non-blocking/async mode (submit a message and a callback function to the API and return immediately).



```text
struct demo_client {
        struct mbox_client cl;
        struct mbox_chan *mbox;
        struct completion c;
        bool async;
        /* ... */
};

/*
* This is the handler for data received from remote. The behaviour is purely
* dependent upon the protocol. This is just an example.
*/
static void message_from_remote(struct mbox_client *cl, void *mssg)
{
        struct demo_client *dc = container_of(cl, struct demo_client, cl);
        if (dc->async) {
                if (is_an_ack(mssg)) {
                        /* An ACK to our last sample sent */
                        return; /* Or do something else here */
                } else { /* A new message from remote */
                        queue_req(mssg);
                }
        } else {
                /* Remote f/w sends only ACK packets on this channel */
                return;
        }
}

static void sample_sent(struct mbox_client *cl, void *mssg, int r)
{
        struct demo_client *dc = container_of(cl, struct demo_client, cl);
        complete(&dc->c);
}

static void client_demo(struct platform_device *pdev)
{
        struct demo_client *dc_sync, *dc_async;
        /* The controller already knows async_pkt and sync_pkt */
        struct async_pkt ap;
        struct sync_pkt sp;

        dc_sync = kzalloc(sizeof(*dc_sync), GFP_KERNEL);
        dc_async = kzalloc(sizeof(*dc_async), GFP_KERNEL);

        /* Populate non-blocking mode client */
        dc_async->cl.dev = &pdev->dev;
        dc_async->cl.rx_callback = message_from_remote;
        dc_async->cl.tx_done = sample_sent;
        dc_async->cl.tx_block = false;
        dc_async->cl.tx_tout = 0; /* doesn't matter here */
        dc_async->cl.knows_txdone = false; /* depending upon protocol */
        dc_async->async = true;
        init_completion(&dc_async->c);

        /* Populate blocking mode client */
        dc_sync->cl.dev = &pdev->dev;
        dc_sync->cl.rx_callback = message_from_remote;
        dc_sync->cl.tx_done = NULL; /* operate in blocking mode */
        dc_sync->cl.tx_block = true;
        dc_sync->cl.tx_tout = 500; /* by half a second */
        dc_sync->cl.knows_txdone = false; /* depending upon protocol */
        dc_sync->async = false;

        /* ASync mailbox is listed second in 'mboxes' property */
        dc_async->mbox = mbox_request_channel(&dc_async->cl, 1);
        /* Populate data packet */
        /* ap.xxx = 123; etc */
        /* Send async message to remote */
        mbox_send_message(dc_async->mbox, &ap);

        /* Sync mailbox is listed first in 'mboxes' property */
        dc_sync->mbox = mbox_request_channel(&dc_sync->cl, 0);
        /* Populate data packet */
        /* sp.abc = 123; etc */
        /* Send message to remote in blocking mode */
        mbox_send_message(dc_sync->mbox, &sp);
        /* At this point 'sp' has been sent */

        /* Now wait for async chan to be done */
        wait_for_completion(&dc_async->c);
}
```

---

# NVMEM Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Srinivas Kandagatla <srinivas.kandagatla@linaro.org>

<a id="rst-nvmem-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> Srinivas Kandagatla &lt;[srinivas.kandagatla@linaro.org](<mailto:srinivas.kandagatla@linaro.org>)&gt;

This document explains the NVMEM Framework along with the APIs provided, and how to use it.

<a id="rst-introduction"></a>

## 1. Introduction

*NVMEM* is the abbreviation for Non Volatile Memory layer. It is used to retrieve configuration of SOC or Device specific data from non volatile memories like eeprom, efuses and so on.

Before this framework existed, NVMEM drivers like eeprom were stored in drivers/misc, where they all had to duplicate pretty much the same code to register a sysfs file, allow in-kernel users to access the content of the devices they were driving, etc.

This was also a problem as far as other in-kernel users were involved, since the solutions used were pretty much different from one driver to another, there was a rather big abstraction leak.

This framework aims at solve these problems. It also introduces DT representation for consumer devices to go get the data they require (MAC Addresses, SoC/Revision ID, part numbers, and so on) from the NVMEMs.

<a id="rst-nvmem-providers"></a>

### NVMEM Providers

NVMEM provider refers to an entity that implements methods to initialize, read and write the non-volatile memory.

<a id="rst-registering-unregistering-the-nvmem-provider"></a>

## 2. Registering/Unregistering the NVMEM provider

A NVMEM provider can register with NVMEM core by supplying relevant nvmem configuration to nvmem_register(), on success core would return a valid nvmem_device pointer.

nvmem_unregister() is used to unregister a previously registered provider.

For example, a simple nvram case:



```text
static int brcm_nvram_probe(struct platform_device *pdev)
{
      struct nvmem_config config = {
              .name = "brcm-nvram",
              .reg_read = brcm_nvram_read,
      };
      ...
      config.dev = &pdev->dev;
      config.priv = priv;
      config.size = resource_size(res);

      devm_nvmem_register(&config);
}
```

Device drivers can define and register an nvmem cell using the nvmem_cell_info struct:



```text
static const struct nvmem_cell_info foo_nvmem_cell = {
      {
              .name           = "macaddr",
              .offset         = 0x7f00,
              .bytes          = ETH_ALEN,
      }
};

int nvmem_add_one_cell(nvmem, &foo_nvmem_cell);
```

Additionally it is possible to create nvmem cell lookup entries and register them with the nvmem framework from machine code as shown in the example below:



```text
static struct nvmem_cell_lookup foo_nvmem_lookup = {
      .nvmem_name             = "i2c-eeprom",
      .cell_name              = "macaddr",
      .dev_id                 = "foo_mac.0",
      .con_id                 = "mac-address",
};

nvmem_add_cell_lookups(&foo_nvmem_lookup, 1);
```

<a id="rst-nvmem-consumers"></a>

### NVMEM Consumers

NVMEM consumers are the entities which make use of the NVMEM provider to read from and to NVMEM.

<a id="rst-nvmem-cell-based-consumer-apis"></a>

## 3. NVMEM cell based consumer APIs

NVMEM cells are the data entries/fields in the NVMEM. The NVMEM framework provides 3 APIs to read/write NVMEM cells:



```text
struct nvmem_cell *nvmem_cell_get(struct device *dev, const char *name);
struct nvmem_cell *devm_nvmem_cell_get(struct device *dev, const char *name);

void nvmem_cell_put(struct nvmem_cell *cell);
void devm_nvmem_cell_put(struct device *dev, struct nvmem_cell *cell);

void *nvmem_cell_read(struct nvmem_cell *cell, ssize_t *len);
int nvmem_cell_write(struct nvmem_cell *cell, void *buf, ssize_t len);
```

`*nvmem_cell_get()` apis will get a reference to nvmem cell for a given id, and nvmem_cell_read/write() can then read or write to the cell. Once the usage of the cell is finished the consumer should call `*nvmem_cell_put()` to free all the allocation memory for the cell.

<a id="rst-direct-nvmem-device-based-consumer-apis"></a>

## 4. Direct NVMEM device based consumer APIs

In some instances it is necessary to directly read/write the NVMEM. To facilitate such consumers NVMEM framework provides below apis:



```text
struct nvmem_device *nvmem_device_get(struct device *dev, const char *name);
struct nvmem_device *devm_nvmem_device_get(struct device *dev,
                                         const char *name);
struct nvmem_device *nvmem_device_find(void *data,
                      int (*match)(struct device *dev, const void *data));
void nvmem_device_put(struct nvmem_device *nvmem);
int nvmem_device_read(struct nvmem_device *nvmem, unsigned int offset,
                    size_t bytes, void *buf);
int nvmem_device_write(struct nvmem_device *nvmem, unsigned int offset,
                     size_t bytes, void *buf);
int nvmem_device_cell_read(struct nvmem_device *nvmem,
                         struct nvmem_cell_info *info, void *buf);
int nvmem_device_cell_write(struct nvmem_device *nvmem,
                          struct nvmem_cell_info *info, void *buf);
```

Before the consumers can read/write NVMEM directly, it should get hold of nvmem_controller from one of the `*nvmem_device_get()` api.

The difference between these apis and cell based apis is that these apis always take nvmem_device as parameter.

<a id="rst-releasing-a-reference-to-the-nvmem"></a>

## 5. Releasing a reference to the NVMEM

When a consumer no longer needs the NVMEM, it has to release the reference to the NVMEM it has obtained using the APIs mentioned in the above section. The NVMEM framework provides 2 APIs to release a reference to the NVMEM:



```text
void nvmem_cell_put(struct nvmem_cell *cell);
void devm_nvmem_cell_put(struct device *dev, struct nvmem_cell *cell);
void nvmem_device_put(struct nvmem_device *nvmem);
void devm_nvmem_device_put(struct device *dev, struct nvmem_device *nvmem);
```

Both these APIs are used to release a reference to the NVMEM and devm_nvmem_cell_put and devm_nvmem_device_put destroys the devres associated with this NVMEM.

<a id="rst-userspace"></a>

### Userspace

<a id="rst-userspace-binary-interface"></a>

## 6. Userspace binary interface

Userspace can read/write the raw NVMEM file located at:



```text
/sys/bus/nvmem/devices/*/nvmem
```

ex:



```text
hexdump /sys/bus/nvmem/devices/qfprom0/nvmem

0000000 0000 0000 0000 0000 0000 0000 0000 0000
*
00000a0 db10 2240 0000 e000 0c00 0c00 0000 0c00
0000000 0000 0000 0000 0000 0000 0000 0000 0000
...
*
0001000
```

<a id="rst-devicetree-binding"></a>

## 7. DeviceTree Binding

See [Documentation/devicetree/bindings/nvmem/nvmem.txt](/kernel/hardware/devicetree/bindings-nvmem/nvmem.md)

<a id="rst-nvmem-layouts"></a>

## 8. NVMEM layouts

NVMEM layouts are yet another mechanism to create cells. With the device tree binding it is possible to specify simple cells by using an offset and a length. Sometimes, the cells doesn't have a static offset, but the content is still well defined, e.g. tag-length-values. In this case, the NVMEM device content has to be first parsed and the cells need to be added accordingly. Layouts let you read the content of the NVMEM device and let you add cells dynamically.

Another use case for layouts is the post processing of cells. With layouts, it is possible to associate a custom post processing hook to a cell. It even possible to add this hook to cells not created by the layout itself.

<a id="rst-internal-kernel-api"></a>

## 9. Internal kernel API


#### <a id="c-nvmem_add_one_cell"></a>`nvmem_add_one_cell()`

```c
int nvmem_add_one_cell(struct nvmem_device *nvmem, const struct nvmem_cell_info *info)
```

Add one cell information to an nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to add cells to.
- `const struct nvmem_cell_info *info`: nvmem cell info to add to the device

**Return**

0 or negative error code on failure.

#### <a id="c-nvmem_register_notifier"></a>`nvmem_register_notifier()`

```c
int nvmem_register_notifier(struct notifier_block *nb)
```

Register a notifier block for nvmem events.

**Parameters**

- `struct notifier_block *nb`: notifier block to be called on nvmem events.

**Return**

0 on success, negative error number on failure.

#### <a id="c-nvmem_unregister_notifier"></a>`nvmem_unregister_notifier()`

```c
int nvmem_unregister_notifier(struct notifier_block *nb)
```

Unregister a notifier block for nvmem events.

**Parameters**

- `struct notifier_block *nb`: notifier block to be unregistered.

**Return**

0 on success, negative error number on failure.

#### <a id="c-nvmem_register"></a>`nvmem_register()`

```c
struct nvmem_device * nvmem_register(const struct nvmem_config *config)
```

Register a nvmem device for given nvmem_config. Also creates a binary entry in /sys/bus/nvmem/devices/dev-name/nvmem

**Parameters**

- `const struct nvmem_config *config`: nvmem device configuration with which nvmem device is created.

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to nvmem_device
on success.

#### <a id="c-nvmem_unregister"></a>`nvmem_unregister()`

```c
void nvmem_unregister(struct nvmem_device *nvmem)
```

Unregister previously registered nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: Pointer to previously registered nvmem device.

#### <a id="c-devm_nvmem_register"></a>`devm_nvmem_register()`

```c
struct nvmem_device * devm_nvmem_register(struct device *dev, const struct nvmem_config *config)
```

Register a managed nvmem device for given nvmem_config. Also creates a binary entry in /sys/bus/nvmem/devices/dev-name/nvmem

**Parameters**

- `struct device *dev`: Device that uses the nvmem device.
- `const struct nvmem_config *config`: nvmem device configuration with which nvmem device is created.

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to nvmem_device
on success.

#### <a id="c-of_nvmem_device_get"></a>`of_nvmem_device_get()`

```c
struct nvmem_device * of_nvmem_device_get(struct device_node *np, const char *id)
```

Get nvmem device from a given id

**Parameters**

- `struct device_node *np`: Device tree node that uses the nvmem device.
- `const char *id`: nvmem name from nvmem-names property.

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a struct nvmem_device
on success.

#### <a id="c-nvmem_device_get"></a>`nvmem_device_get()`

```c
struct nvmem_device * nvmem_device_get(struct device *dev, const char *dev_name)
```

Get nvmem device from a given id

**Parameters**

- `struct device *dev`: Device that uses the nvmem device.
- `const char *dev_name`: name of the requested nvmem device.

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a struct nvmem_device
on success.

#### <a id="c-nvmem_device_find"></a>`nvmem_device_find()`

```c
struct nvmem_device * nvmem_device_find(void *data, int (*match)(struct device *dev, const void *data))
```

Find nvmem device with matching function

**Parameters**

- `void *data`: Data to pass to match function
- `int (*match)(struct device *dev, const void *data)`: Callback function to check device

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a struct nvmem_device
on success.

#### <a id="c-devm_nvmem_device_put"></a>`devm_nvmem_device_put()`

```c
void devm_nvmem_device_put(struct device *dev, struct nvmem_device *nvmem)
```

put already got nvmem device

**Parameters**

- `struct device *dev`: Device that uses the nvmem device.
- `struct nvmem_device *nvmem`: pointer to nvmem device allocated by [`devm_nvmem_cell_get()`](#c-devm_nvmem_cell_get),
  that needs to be released.

#### <a id="c-nvmem_device_put"></a>`nvmem_device_put()`

```c
void nvmem_device_put(struct nvmem_device *nvmem)
```

put already got nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: pointer to nvmem device that needs to be released.

#### <a id="c-devm_nvmem_device_get"></a>`devm_nvmem_device_get()`

```c
struct nvmem_device * devm_nvmem_device_get(struct device *dev, const char *id)
```

Get nvmem device of device from a given id

**Parameters**

- `struct device *dev`: Device that requests the nvmem device.
- `const char *id`: name id for the requested nvmem device.

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a struct nvmem_device
on success.  The nvmem_device will be freed by the automatically once the
device is freed.

#### <a id="c-of_nvmem_cell_get"></a>`of_nvmem_cell_get()`

```c
struct nvmem_cell * of_nvmem_cell_get(struct device_node *np, const char *id)
```

Get a nvmem cell from given device node and cell id

**Parameters**

- `struct device_node *np`: Device tree node that uses the nvmem cell.
- `const char *id`: nvmem cell name from nvmem-cell-names property, or NULL
  for the cell at index 0 (the lone cell with no accompanying
  nvmem-cell-names property).

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer
to a struct nvmem_cell.  The nvmem_cell will be freed by the
[`nvmem_cell_put()`](#c-nvmem_cell_put).

#### <a id="c-nvmem_cell_get"></a>`nvmem_cell_get()`

```c
struct nvmem_cell * nvmem_cell_get(struct device *dev, const char *id)
```

Get nvmem cell of device from a given cell name

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *id`: nvmem cell name to get (this corresponds with the name from the
  nvmem-cell-names property for DT systems and with the con_id from
  the lookup entry for non-DT systems).

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer
to a struct nvmem_cell.  The nvmem_cell will be freed by the
[`nvmem_cell_put()`](#c-nvmem_cell_put).

#### <a id="c-devm_nvmem_cell_get"></a>`devm_nvmem_cell_get()`

```c
struct nvmem_cell * devm_nvmem_cell_get(struct device *dev, const char *id)
```

Get nvmem cell of device from a given id

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *id`: nvmem cell name id to get.

**Return**

Will be an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer
to a struct nvmem_cell.  The nvmem_cell will be freed by the
automatically once the device is freed.

#### <a id="c-devm_nvmem_cell_put"></a>`devm_nvmem_cell_put()`

```c
void devm_nvmem_cell_put(struct device *dev, struct nvmem_cell *cell)
```

Release previously allocated nvmem cell from devm_nvmem_cell_get.

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `struct nvmem_cell *cell`: Previously allocated nvmem cell by [`devm_nvmem_cell_get()`](#c-devm_nvmem_cell_get).

#### <a id="c-nvmem_cell_put"></a>`nvmem_cell_put()`

```c
void nvmem_cell_put(struct nvmem_cell *cell)
```

Release previously allocated nvmem cell.

**Parameters**

- `struct nvmem_cell *cell`: Previously allocated nvmem cell by [`nvmem_cell_get()`](#c-nvmem_cell_get).

#### <a id="c-nvmem_cell_read"></a>`nvmem_cell_read()`

```c
void * nvmem_cell_read(struct nvmem_cell *cell, size_t *len)
```

Read a given nvmem cell

**Parameters**

- `struct nvmem_cell *cell`: nvmem cell to be read.
- `size_t *len`: pointer to length of cell which will be populated on successful read;
  can be NULL.

**Return**

[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error or a valid pointer to a buffer on success. The
buffer should be freed by the consumer with a [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

#### <a id="c-nvmem_cell_write"></a>`nvmem_cell_write()`

```c
int nvmem_cell_write(struct nvmem_cell *cell, void *buf, size_t len)
```

Write to a given nvmem cell

**Parameters**

- `struct nvmem_cell *cell`: nvmem cell to be written.
- `void *buf`: Buffer to be written.
- `size_t len`: length of buffer to be written to nvmem cell.

**Return**

length of bytes written or negative on failure.

#### <a id="c-nvmem_cell_read_u8"></a>`nvmem_cell_read_u8()`

```c
int nvmem_cell_read_u8(struct device *dev, const char *cell_id, u8 *val)
```

Read a cell value as a u8

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u8 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_u16"></a>`nvmem_cell_read_u16()`

```c
int nvmem_cell_read_u16(struct device *dev, const char *cell_id, u16 *val)
```

Read a cell value as a u16

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u16 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_u32"></a>`nvmem_cell_read_u32()`

```c
int nvmem_cell_read_u32(struct device *dev, const char *cell_id, u32 *val)
```

Read a cell value as a u32

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u32 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_u64"></a>`nvmem_cell_read_u64()`

```c
int nvmem_cell_read_u64(struct device *dev, const char *cell_id, u64 *val)
```

Read a cell value as a u64

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u64 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_variable_le_u32"></a>`nvmem_cell_read_variable_le_u32()`

```c
int nvmem_cell_read_variable_le_u32(struct device *dev, const char *cell_id, u32 *val)
```

Read up to 32-bits of data as a little endian number.

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u32 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_cell_read_variable_le_u64"></a>`nvmem_cell_read_variable_le_u64()`

```c
int nvmem_cell_read_variable_le_u64(struct device *dev, const char *cell_id, u64 *val)
```

Read up to 64-bits of data as a little endian number.

**Parameters**

- `struct device *dev`: Device that requests the nvmem cell.
- `const char *cell_id`: Name of nvmem cell to read.
- `u64 *val`: pointer to output value.

**Return**

0 on success or negative errno.

#### <a id="c-nvmem_device_cell_read"></a>`nvmem_device_cell_read()`

```c
ssize_t nvmem_device_cell_read(struct nvmem_device *nvmem, struct nvmem_cell_info *info, void *buf)
```

Read a given nvmem device and cell

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to read from.
- `struct nvmem_cell_info *info`: nvmem cell info to be read.
- `void *buf`: buffer pointer which will be populated on successful read.

**Return**

length of successful bytes read on success and negative
error code on error.

#### <a id="c-nvmem_device_cell_write"></a>`nvmem_device_cell_write()`

```c
int nvmem_device_cell_write(struct nvmem_device *nvmem, struct nvmem_cell_info *info, void *buf)
```

Write cell to a given nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to be written to.
- `struct nvmem_cell_info *info`: nvmem cell info to be written.
- `void *buf`: buffer to be written to cell.

**Return**

length of bytes written or negative error code on failure.

#### <a id="c-nvmem_device_read"></a>`nvmem_device_read()`

```c
int nvmem_device_read(struct nvmem_device *nvmem, unsigned int offset, size_t bytes, void *buf)
```

Read from a given nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to read from.
- `unsigned int offset`: offset in nvmem device.
- `size_t bytes`: number of bytes to read.
- `void *buf`: buffer pointer which will be populated on successful read.

**Return**

length of successful bytes read on success and negative
error code on error.

#### <a id="c-nvmem_device_write"></a>`nvmem_device_write()`

```c
int nvmem_device_write(struct nvmem_device *nvmem, unsigned int offset, size_t bytes, void *buf)
```

Write cell to a given nvmem device

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device to be written to.
- `unsigned int offset`: offset in nvmem device.
- `size_t bytes`: number of bytes to write.
- `void *buf`: buffer to be written.

**Return**

length of bytes written or negative error code on failure.

#### <a id="c-nvmem_add_cell_lookups"></a>`nvmem_add_cell_lookups()`

```c
void nvmem_add_cell_lookups(struct nvmem_cell_lookup *entries, size_t nentries)
```

register a list of cell lookup entries

**Parameters**

- `struct nvmem_cell_lookup *entries`: array of cell lookup entries
- `size_t nentries`: number of cell lookup entries in the array

#### <a id="c-nvmem_del_cell_lookups"></a>`nvmem_del_cell_lookups()`

```c
void nvmem_del_cell_lookups(struct nvmem_cell_lookup *entries, size_t nentries)
```

remove a list of previously added cell lookup entries

**Parameters**

- `struct nvmem_cell_lookup *entries`: array of cell lookup entries
- `size_t nentries`: number of cell lookup entries in the array

#### <a id="c-nvmem_dev_name"></a>`nvmem_dev_name()`

```c
const char * nvmem_dev_name(struct nvmem_device *nvmem)
```

Get the name of a given nvmem device.

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device.

**Return**

name of the nvmem device.

#### <a id="c-nvmem_dev_size"></a>`nvmem_dev_size()`

```c
size_t nvmem_dev_size(struct nvmem_device *nvmem)
```

Get the size of a given nvmem device.

**Parameters**

- `struct nvmem_device *nvmem`: nvmem device.

**Return**

size of the nvmem device.

---

# PINCTRL (PIN CONTROL) subsystem

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This document outlines the pin control subsystem in Linux

<a id="rst-pinctrl-pin-control-subsystem"></a>

This document outlines the pin control subsystem in Linux

This subsystem deals with:

- Enumerating and naming controllable pins

- Multiplexing of pins, pads, fingers (etc) see below for details

- Configuration of pins, pads, fingers (etc), such as software-controlled biasing and driving mode specific pins, such as pull-up, pull-down, open drain, load capacitance etc.

<a id="rst-top-level-interface"></a>

## Top-level interface

Definitions:

- A PIN CONTROLLER is a piece of hardware, usually a set of registers, that can control PINs. It may be able to multiplex, bias, set load capacitance, set drive strength, etc. for individual pins or groups of pins.

- PINS are equal to pads, fingers, balls or whatever packaging input or output line you want to control and these are denoted by unsigned integers in the range 0..maxpin. This numberspace is local to each PIN CONTROLLER, so there may be several such number spaces in a system. This pin space may be sparse - i.e. there may be gaps in the space with numbers where no pin exists.

When a PIN CONTROLLER is instantiated, it will register a descriptor to the pin control framework, and this descriptor contains an array of pin descriptors describing the pins handled by this specific pin controller.

Here is an example of a PGA (Pin Grid Array) chip seen from underneath:



```text
     A   B   C   D   E   F   G   H

8    o   o   o   o   o   o   o   o

7    o   o   o   o   o   o   o   o

6    o   o   o   o   o   o   o   o

5    o   o   o   o   o   o   o   o

4    o   o   o   o   o   o   o   o

3    o   o   o   o   o   o   o   o

2    o   o   o   o   o   o   o   o

1    o   o   o   o   o   o   o   o
```

To register a pin controller and name all the pins on this package we can do this in our driver:



```c
#include <linux/pinctrl/pinctrl.h>

const struct pinctrl_pin_desc foo_pins[] = {
        PINCTRL_PIN(0, "A8"),
        PINCTRL_PIN(1, "B8"),
        PINCTRL_PIN(2, "C8"),
        ...
        PINCTRL_PIN(61, "F1"),
        PINCTRL_PIN(62, "G1"),
        PINCTRL_PIN(63, "H1"),
};

static struct pinctrl_desc foo_desc = {
        .name = "foo",
        .pins = foo_pins,
        .npins = ARRAY_SIZE(foo_pins),
        .owner = THIS_MODULE,
};

int __init foo_init(void)
{
        int error;

        struct pinctrl_dev *pctl;

        error = pinctrl_register_and_init(&foo_desc, <PARENT>, NULL, &pctl);
        if (error)
                return error;

        return pinctrl_enable(pctl);
}
```

To enable the pinctrl subsystem and the subgroups for PINMUX and PINCONF and selected drivers, you need to select them from your machine's Kconfig entry, since these are so tightly integrated with the machines they are used on. See `arch/arm/mach-ux500/Kconfig` for an example.

Pins usually have fancier names than this. You can find these in the datasheet for your chip. Notice that the core pinctrl.h file provides a fancy macro called `PINCTRL_PIN()` to create the struct entries. As you can see the pins are enumerated from 0 in the upper left corner to 63 in the lower right corner. This enumeration was arbitrarily chosen, in practice you need to think through your numbering system so that it matches the layout of registers and such things in your driver, or the code may become complicated. You must also consider matching of offsets to the GPIO ranges that may be handled by the pin controller.

For a padding with 467 pads, as opposed to actual pins, the enumeration will be like this, walking around the edge of the chip, which seems to be industry standard too (all these pads had names, too):



```text
  0 ..... 104
466        105
  .        .
  .        .
358        224
 357 .... 225
```

<a id="rst-pin-groups"></a>

## Pin groups

Many controllers need to deal with groups of pins, so the pin controller subsystem has a mechanism for enumerating groups of pins and retrieving the actual enumerated pins that are part of a certain group.

For example, say that we have a group of pins dealing with an SPI interface on \{ 0, 8, 16, 24 \}, and a group of pins dealing with an I2C interface on pins on \{ 24, 25 \}.

These two groups are presented to the pin control subsystem by implementing some generic `pinctrl_ops` like this:



```c
#include <linux/pinctrl/pinctrl.h>

static const unsigned int spi0_pins[] = { 0, 8, 16, 24 };
static const unsigned int i2c0_pins[] = { 24, 25 };

static const struct pingroup foo_groups[] = {
        PINCTRL_PINGROUP("spi0_grp", spi0_pins, ARRAY_SIZE(spi0_pins)),
        PINCTRL_PINGROUP("i2c0_grp", i2c0_pins, ARRAY_SIZE(i2c0_pins)),
};

static int foo_get_groups_count(struct pinctrl_dev *pctldev)
{
        return ARRAY_SIZE(foo_groups);
}

static const char *foo_get_group_name(struct pinctrl_dev *pctldev,
                                      unsigned int selector)
{
        return foo_groups[selector].name;
}

static int foo_get_group_pins(struct pinctrl_dev *pctldev,
                              unsigned int selector,
                              const unsigned int **pins,
                              unsigned int *npins)
{
        *pins = foo_groups[selector].pins;
        *npins = foo_groups[selector].npins;
        return 0;
}

static struct pinctrl_ops foo_pctrl_ops = {
        .get_groups_count = foo_get_groups_count,
        .get_group_name = foo_get_group_name,
        .get_group_pins = foo_get_group_pins,
};

static struct pinctrl_desc foo_desc = {
        ...
        .pctlops = &foo_pctrl_ops,
};
```

The pin control subsystem will call the `.get_groups_count()` function to determine the total number of legal selectors, then it will call the other functions to retrieve the name and pins of the group. Maintaining the data structure of the groups is up to the driver, this is just a simple example - in practice you may need more entries in your group structure, for example specific register ranges associated with each group and so on.

<a id="rst-pin-configuration"></a>

## Pin configuration

Pins can sometimes be software-configured in various ways, mostly related to their electronic properties when used as inputs or outputs. For example you may be able to make an output pin high impedance (Hi-Z), or "tristate" meaning it is effectively disconnected. You may be able to connect an input pin to VDD or GND using a certain resistor value - pull up and pull down - so that the pin has a stable value when nothing is driving the rail it is connected to, or when it's unconnected.

Pin configuration can be programmed by adding configuration entries into the mapping table; see section [Board/machine configuration](<#rst-board-machine-configuration>) below.

The format and meaning of the configuration parameter, PLATFORM_X_PULL_UP above, is entirely defined by the pin controller driver.

The pin configuration driver implements callbacks for changing pin configuration in the pin controller ops like this:



```c
#include <linux/pinctrl/pinconf.h>
#include <linux/pinctrl/pinctrl.h>

#include "platform_x_pindefs.h"

static int foo_pin_config_get(struct pinctrl_dev *pctldev,
                              unsigned int offset,
                              unsigned long *config)
{
        struct my_conftype conf;

        /* ... Find setting for pin @ offset ... */

        *config = (unsigned long) conf;
}

static int foo_pin_config_set(struct pinctrl_dev *pctldev,
                              unsigned int offset,
                              unsigned long config)
{
        struct my_conftype *conf = (struct my_conftype *) config;

        switch (conf) {
                case PLATFORM_X_PULL_UP:
                ...
                break;
        }
}

static int foo_pin_config_group_get(struct pinctrl_dev *pctldev,
                                    unsigned selector,
                                    unsigned long *config)
{
        ...
}

static int foo_pin_config_group_set(struct pinctrl_dev *pctldev,
                                    unsigned selector,
                                    unsigned long config)
{
        ...
}

static struct pinconf_ops foo_pconf_ops = {
        .pin_config_get = foo_pin_config_get,
        .pin_config_set = foo_pin_config_set,
        .pin_config_group_get = foo_pin_config_group_get,
        .pin_config_group_set = foo_pin_config_group_set,
};

/* Pin config operations are handled by some pin controller */
static struct pinctrl_desc foo_desc = {
        ...
        .confops = &foo_pconf_ops,
};
```

<a id="rst-interaction-with-the-gpio-subsystem"></a>

## Interaction with the GPIO subsystem

The GPIO drivers may want to perform operations of various types on the same physical pins that are also registered as pin controller pins.

First and foremost, the two subsystems can be used as completely orthogonal, see the section named [Pin control requests from drivers](<#rst-pin-control-requests-from-drivers>) and [Drivers needing both pin control and GPIOs](<#rst-drivers-needing-both-pin-control-and-gpios>) below for details. But in some situations a cross-subsystem mapping between pins and GPIOs is needed.

Since the pin controller subsystem has its pinspace local to the pin controller we need a mapping so that the pin control subsystem can figure out which pin controller handles control of a certain GPIO pin. Since a single pin controller may be muxing several GPIO ranges (typically SoCs that have one set of pins, but internally several GPIO silicon blocks, each modelled as a struct gpio_chip) any number of GPIO ranges can be added to a pin controller instance like this:



```c
#include <linux/gpio/driver.h>

#include <linux/pinctrl/pinctrl.h>

struct gpio_chip chip_a;
struct gpio_chip chip_b;

static struct pinctrl_gpio_range gpio_range_a = {
        .name = "chip a",
        .id = 0,
        .base = 32,
        .pin_base = 32,
        .npins = 16,
        .gc = &chip_a,
};

static struct pinctrl_gpio_range gpio_range_b = {
        .name = "chip b",
        .id = 0,
        .base = 48,
        .pin_base = 64,
        .npins = 8,
        .gc = &chip_b;
};

int __init foo_init(void)
{
        struct pinctrl_dev *pctl;
        ...
        pinctrl_add_gpio_range(pctl, &gpio_range_a);
        pinctrl_add_gpio_range(pctl, &gpio_range_b);
        ...
}
```

So this complex system has one pin controller handling two different GPIO chips. "chip a" has 16 pins and "chip b" has 8 pins. The "chip a" and "chip b" have different `pin_base`, which means a start pin number of the GPIO range.

The GPIO range of "chip a" starts from the GPIO base of 32 and actual pin range also starts from 32. However "chip b" has different starting offset for the GPIO range and pin range. The GPIO range of "chip b" starts from GPIO number 48, while the pin range of "chip b" starts from 64.

We can convert a gpio number to actual pin number using this `pin_base`. They are mapped in the global GPIO pin space at:

- **chip a:**

  - GPIO range : \[32 .. 47\]

  - pin range  : \[32 .. 47\]

- **chip b:**

  - GPIO range : \[48 .. 55\]

  - pin range  : \[64 .. 71\]

The above examples assume the mapping between the GPIOs and pins is linear. If the mapping is sparse or haphazard, an array of arbitrary pin numbers can be encoded in the range like this:



```c
static const unsigned int range_pins[] = { 14, 1, 22, 17, 10, 8, 6, 2 };

static struct pinctrl_gpio_range gpio_range = {
        .name = "chip",
        .id = 0,
        .base = 32,
        .pins = &range_pins,
        .npins = ARRAY_SIZE(range_pins),
        .gc = &chip,
};
```

In this case the `pin_base` property will be ignored. If the name of a pin group is known, the pins and npins elements of the above structure can be initialised using the function `pinctrl_get_group_pins()`, e.g. for pin group "foo":



```c
pinctrl_get_group_pins(pctl, "foo", &gpio_range.pins, &gpio_range.npins);
```

When GPIO-specific functions in the pin control subsystem are called, these ranges will be used to look up the appropriate pin controller by inspecting and matching the pin to the pin ranges across all controllers. When a pin controller handling the matching range is found, GPIO-specific functions will be called on that specific pin controller.

For all functionalities dealing with pin biasing, pin muxing etc, the pin controller subsystem will look up the corresponding pin number from the passed in gpio number, and use the range's internals to retrieve a pin number. After that, the subsystem passes it on to the pin control driver, so the driver will get a pin number into its handled number range. Further it is also passed the range ID value, so that the pin controller knows which range it should deal with.

Calling `pinctrl_add_gpio_range()` from pinctrl driver is DEPRECATED. Please see section 2.1 of `Documentation/devicetree/bindings/gpio/gpio.txt` on how to bind pinctrl and gpio drivers.

<a id="rst-pinmux-interfaces"></a>

## PINMUX interfaces

These calls use the pinmux\_\* naming prefix.  No other calls should use that prefix.

<a id="rst-what-is-pinmuxing"></a>

## What is pinmuxing?

PINMUX, also known as padmux, ballmux, alternate functions or mission modes is a way for chip vendors producing some kind of electrical packages to use a certain physical pin (ball, pad, finger, etc) for multiple mutually exclusive functions, depending on the application. By "application" in this context we usually mean a way of soldering or wiring the package into an electronic system, even though the framework makes it possible to also change the function at runtime.

Here is an example of a PGA (Pin Grid Array) chip seen from underneath:



```text
     A   B   C   D   E   F   G   H
   +---+
8  | o | o   o   o   o   o   o   o
   |   |
7  | o | o   o   o   o   o   o   o
   |   |
6  | o | o   o   o   o   o   o   o
   +---+---+
5  | o | o | o   o   o   o   o   o
   +---+---+               +---+
4    o   o   o   o   o   o | o | o
                           |   |
3    o   o   o   o   o   o | o | o
                           |   |
2    o   o   o   o   o   o | o | o
   +-------+-------+-------+---+---+
1  | o   o | o   o | o   o | o | o |
   +-------+-------+-------+---+---+
```

This is not tetris. The game to think of is chess. Not all PGA/BGA packages are chessboard-like, big ones have "holes" in some arrangement according to different design patterns, but we're using this as a simple example. Of the pins you see some will be taken by things like a few VCC and GND to feed power to the chip, and quite a few will be taken by large ports like an external memory interface. The remaining pins will often be subject to pin multiplexing.

The example 8x8 PGA package above will have pin numbers 0 through 63 assigned to its physical pins. It will name the pins \{ A1, A2, A3 ... H6, H7, H8 \} using pinctrl_register_pins() and a suitable data set as shown earlier.

In this 8x8 BGA package the pins \{ A8, A7, A6, A5 \} can be used as an SPI port (these are four pins: CLK, RXD, TXD, FRM). In that case, pin B5 can be used as some general-purpose GPIO pin. However, in another setting, pins \{ A5, B5 \} can be used as an I2C port (these are just two pins: SCL, SDA). Needless to say, we cannot use the SPI port and I2C port at the same time. However in the inside of the package the silicon performing the SPI logic can alternatively be routed out on pins \{ G4, G3, G2, G1 \}.

On the bottom row at \{ A1, B1, C1, D1, E1, F1, G1, H1 \} we have something special - it's an external MMC bus that can be 2, 4 or 8 bits wide, and it will consume 2, 4 or 8 pins respectively, so either \{ A1, B1 \} are taken or \{ A1, B1, C1, D1 \} or all of them. If we use all 8 bits, we cannot use the SPI port on pins \{ G4, G3, G2, G1 \} of course.

This way the silicon blocks present inside the chip can be multiplexed "muxed" out on different pin ranges. Often contemporary SoC (systems on chip) will contain several I2C, SPI, SDIO/MMC, etc silicon blocks that can be routed to different pins by pinmux settings.

Since general-purpose I/O pins (GPIO) are typically always in shortage, it is common to be able to use almost any pin as a GPIO pin if it is not currently in use by some other I/O port.

<a id="rst-pinmux-conventions"></a>

## Pinmux conventions

The purpose of the pinmux functionality in the pin controller subsystem is to abstract and provide pinmux settings to the devices you choose to instantiate in your machine configuration. It is inspired by the clk, GPIO and regulator subsystems, so devices will request their mux setting, but it's also possible to request a single pin for e.g. GPIO.

The conventions are:

- FUNCTIONS can be switched in and out by a driver residing with the pin control subsystem in the `drivers/pinctrl` directory of the kernel. The pin control driver knows the possible functions. In the example above you can identify three pinmux functions, one for spi, one for i2c and one for mmc.

- FUNCTIONS are assumed to be enumerable from zero in a one-dimensional array. In this case the array could be something like: \{ spi0, i2c0, mmc0 \} for the three available functions.

- FUNCTIONS have PIN GROUPS as defined on the generic level - so a certain function is *always* associated with a certain set of pin groups, could be just a single one, but could also be many. In the example above the function i2c is associated with the pins \{ A5, B5 \}, enumerated as \{ 24, 25 \} in the controller pin space.

  The Function spi is associated with pin groups \{ A8, A7, A6, A5 \} and \{ G4, G3, G2, G1 \}, which are enumerated as \{ 0, 8, 16, 24 \} and \{ 38, 46, 54, 62 \} respectively.

  Group names must be unique per pin controller, no two groups on the same controller may have the same name.

- The combination of a FUNCTION and a PIN GROUP determine a certain function for a certain set of pins. The knowledge of the functions and pin groups and their machine-specific particulars are kept inside the pinmux driver, from the outside only the enumerators are known, and the driver core can request:

  - The name of a function with a certain selector (&gt;= 0)

  - A list of groups associated with a certain function

  - That a certain group in that list to be activated for a certain function

  As already described above, pin groups are in turn self-descriptive, so the core will retrieve the actual pin range in a certain group from the driver.

- FUNCTIONS and GROUPS on a certain PIN CONTROLLER are MAPPED to a certain device by the board file, device tree or similar machine setup configuration mechanism, similar to how regulators are connected to devices, usually by name. Defining a pin controller, function and group thus uniquely identify the set of pins to be used by a certain device. (If only one possible group of pins is available for the function, no group name need to be supplied - the core will simply select the first and only group available.)

  In the example case we can define that this particular machine shall use device spi0 with pinmux function fspi0 group gspi0 and i2c0 on function fi2c0 group gi2c0, on the primary pin controller, we get mappings like these:



  ```c
  {
          {"map-spi0", spi0, pinctrl0, fspi0, gspi0},
          {"map-i2c0", i2c0, pinctrl0, fi2c0, gi2c0},
  }
  ```

  Every map must be assigned a state name, pin controller, device and function. The group is not compulsory - if it is omitted the first group presented by the driver as applicable for the function will be selected, which is useful for simple cases.

  It is possible to map several groups to the same combination of device, pin controller and function. This is for cases where a certain function on a certain pin controller may use different sets of pins in different configurations.

- PINS for a certain FUNCTION using a certain PIN GROUP on a certain PIN CONTROLLER are provided on a first-come first-serve basis, so if some other device mux setting or GPIO pin request has already taken your physical pin, you will be denied the use of it. To get (activate) a new setting, the old one has to be put (deactivated) first.

Sometimes the documentation and hardware registers will be oriented around pads (or "fingers") rather than pins - these are the soldering surfaces on the silicon inside the package, and may or may not match the actual number of pins/balls underneath the capsule. Pick some enumeration that makes sense to you. Define enumerators only for the pins you can control if that makes sense.

Assumptions:

We assume that the number of possible function maps to pin groups is limited by the hardware. I.e. we assume that there is no system where any function can be mapped to any pin, like in a phone exchange. So the available pin groups for a certain function will be limited to a few choices (say up to eight or so), not hundreds or any amount of choices. This is the characteristic we have found by inspecting available pinmux hardware, and a necessary assumption since we expect pinmux drivers to present *all* possible function vs pin group mappings to the subsystem.

<a id="rst-pinmux-drivers"></a>

## Pinmux drivers

The pinmux core takes care of preventing conflicts on pins and calling the pin controller driver to execute different settings.

It is the responsibility of the pinmux driver to impose further restrictions (say for example infer electronic limitations due to load, etc.) to determine whether or not the requested function can actually be allowed, and in case it is possible to perform the requested mux setting, poke the hardware so that this happens.

Pinmux drivers are required to supply a few callback functions, some are optional. Usually the `.set_mux()` function is implemented, writing values into some certain registers to activate a certain mux setting for a certain pin.

A simple driver for the above example will work by setting bits 0, 1, 2, 3, 4, or 5 into some register named MUX to select a certain function with a certain group of pins would work something like this:



```c
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinmux.h>

static const unsigned int spi0_0_pins[] = { 0, 8, 16, 24 };
static const unsigned int spi0_1_pins[] = { 38, 46, 54, 62 };
static const unsigned int i2c0_pins[] = { 24, 25 };
static const unsigned int mmc0_1_pins[] = { 56, 57 };
static const unsigned int mmc0_2_pins[] = { 58, 59 };
static const unsigned int mmc0_3_pins[] = { 60, 61, 62, 63 };

static const struct pingroup foo_groups[] = {
        PINCTRL_PINGROUP("spi0_0_grp", spi0_0_pins, ARRAY_SIZE(spi0_0_pins)),
        PINCTRL_PINGROUP("spi0_1_grp", spi0_1_pins, ARRAY_SIZE(spi0_1_pins)),
        PINCTRL_PINGROUP("i2c0_grp", i2c0_pins, ARRAY_SIZE(i2c0_pins)),
        PINCTRL_PINGROUP("mmc0_1_grp", mmc0_1_pins, ARRAY_SIZE(mmc0_1_pins)),
        PINCTRL_PINGROUP("mmc0_2_grp", mmc0_2_pins, ARRAY_SIZE(mmc0_2_pins)),
        PINCTRL_PINGROUP("mmc0_3_grp", mmc0_3_pins, ARRAY_SIZE(mmc0_3_pins)),
};

static int foo_get_groups_count(struct pinctrl_dev *pctldev)
{
        return ARRAY_SIZE(foo_groups);
}

static const char *foo_get_group_name(struct pinctrl_dev *pctldev,
                                      unsigned int selector)
{
        return foo_groups[selector].name;
}

static int foo_get_group_pins(struct pinctrl_dev *pctldev, unsigned int selector,
                              const unsigned int **pins,
                              unsigned int *npins)
{
        *pins = foo_groups[selector].pins;
        *npins = foo_groups[selector].npins;
        return 0;
}

static struct pinctrl_ops foo_pctrl_ops = {
        .get_groups_count = foo_get_groups_count,
        .get_group_name = foo_get_group_name,
        .get_group_pins = foo_get_group_pins,
};

static const char * const spi0_groups[] = { "spi0_0_grp", "spi0_1_grp" };
static const char * const i2c0_groups[] = { "i2c0_grp" };
static const char * const mmc0_groups[] = { "mmc0_1_grp", "mmc0_2_grp", "mmc0_3_grp" };

static const struct pinfunction foo_functions[] = {
        PINCTRL_PINFUNCTION("spi0", spi0_groups, ARRAY_SIZE(spi0_groups)),
        PINCTRL_PINFUNCTION("i2c0", i2c0_groups, ARRAY_SIZE(i2c0_groups)),
        PINCTRL_PINFUNCTION("mmc0", mmc0_groups, ARRAY_SIZE(mmc0_groups)),
};

static int foo_get_functions_count(struct pinctrl_dev *pctldev)
{
        return ARRAY_SIZE(foo_functions);
}

static const char *foo_get_fname(struct pinctrl_dev *pctldev, unsigned int selector)
{
        return foo_functions[selector].name;
}

static int foo_get_groups(struct pinctrl_dev *pctldev, unsigned int selector,
                          const char * const **groups,
                          unsigned int * const ngroups)
{
        *groups = foo_functions[selector].groups;
        *ngroups = foo_functions[selector].ngroups;
        return 0;
}

static int foo_set_mux(struct pinctrl_dev *pctldev, unsigned int selector,
                       unsigned int group)
{
        u8 regbit = BIT(group);

        writeb((readb(MUX) | regbit), MUX);
        return 0;
}

static struct pinmux_ops foo_pmxops = {
        .get_functions_count = foo_get_functions_count,
        .get_function_name = foo_get_fname,
        .get_function_groups = foo_get_groups,
        .set_mux = foo_set_mux,
        .strict = true,
};

/* Pinmux operations are handled by some pin controller */
static struct pinctrl_desc foo_desc = {
        ...
        .pctlops = &foo_pctrl_ops,
        .pmxops = &foo_pmxops,
};
```

In the example activating muxing 0 and 2 at the same time setting bits 0 and 2, uses pin 24 in common so they would collide. All the same for the muxes 1 and 5, which have pin 62 in common.

The beauty of the pinmux subsystem is that since it keeps track of all pins and who is using them, it will already have denied an impossible request like that, so the driver does not need to worry about such things - when it gets a selector passed in, the pinmux subsystem makes sure no other device or GPIO assignment is already using the selected pins. Thus bits 0 and 2, or 1 and 5 in the control register will never be set at the same time.

All the above functions are mandatory to implement for a pinmux driver.

<a id="rst-pin-control-interaction-with-the-gpio-subsystem"></a>

## Pin control interaction with the GPIO subsystem

Note that the following implies that the use case is to use a certain pin from the Linux kernel using the API in `<linux/gpio/consumer.h>` with gpiod_get() and similar functions. There are cases where you may be using something that your datasheet calls "GPIO mode", but actually is just an electrical configuration for a certain device. See the section below named [GPIO mode pitfalls](<#rst-gpio-mode-pitfalls>) for more details on this scenario.

The public pinmux API contains two functions named `pinctrl_gpio_request()` and `pinctrl_gpio_free()`. These two functions shall *ONLY* be called from gpiolib-based drivers as part of their `.request()` and `.free()` semantics. Likewise the `pinctrl_gpio_direction_input()` / `pinctrl_gpio_direction_output()` shall only be called from within respective `.direction_input()` / `.direction_output()` gpiolib implementation.

NOTE that platforms and individual drivers shall *NOT* request GPIO pins to be controlled e.g. muxed in. Instead, implement a proper gpiolib driver and have that driver request proper muxing and other control for its pins.

The function list could become long, especially if you can convert every individual pin into a GPIO pin independent of any other pins, and then try the approach to define every pin as a function.

In this case, the function array would become 64 entries for each GPIO setting and then the device functions.

For this reason there are two functions a pin control driver can implement to enable only GPIO on an individual pin: `.gpio_request_enable()` and `.gpio_disable_free()`.

This function will pass in the affected GPIO range identified by the pin controller core, so you know which GPIO pins are being affected by the request operation.

If your driver needs to have an indication from the framework of whether the GPIO pin shall be used for input or output you can implement the `.gpio_set_direction()` function. As described this shall be called from the gpiolib driver and the affected GPIO range, pin offset and desired direction will be passed along to this function.

Alternatively to using these special functions, it is fully allowed to use named functions for each GPIO pin, the `pinctrl_gpio_request()` will attempt to obtain the function "gpioN" where "N" is the global GPIO pin number if no special GPIO-handler is registered.

<a id="rst-gpio-mode-pitfalls"></a>

## GPIO mode pitfalls

Due to the naming conventions used by hardware engineers, where "GPIO" is taken to mean different things than what the kernel does, the developer may be confused by a datasheet talking about a pin being possible to set into "GPIO mode". It appears that what hardware engineers mean with "GPIO mode" is not necessarily the use case that is implied in the kernel interface `<linux/gpio/consumer.h>`: a pin that you grab from kernel code and then either listen for input or drive high/low to assert/deassert some external line.

Rather hardware engineers think that "GPIO mode" means that you can software-control a few electrical properties of the pin that you would not be able to control if the pin was in some other mode, such as muxed in for a device.

The GPIO portions of a pin and its relation to a certain pin controller configuration and muxing logic can be constructed in several ways. Here are two examples.

Example **(A)**:



```text
                  pin config
                  logic regs
                  |               +- SPI
Physical pins --- pad --- pinmux -+- I2C
                          |       +- mmc
                          |       +- GPIO
                          pin
                          multiplex
                          logic regs
```

Here some electrical properties of the pin can be configured no matter whether the pin is used for GPIO or not. If you multiplex a GPIO onto a pin, you can also drive it high/low from "GPIO" registers. Alternatively, the pin can be controlled by a certain peripheral, while still applying desired pin config properties. GPIO functionality is thus orthogonal to any other device using the pin.

In this arrangement the registers for the GPIO portions of the pin controller, or the registers for the GPIO hardware module are likely to reside in a separate memory range only intended for GPIO driving, and the register range dealing with pin config and pin multiplexing get placed into a different memory range and a separate section of the data sheet.

A flag "strict" in struct pinmux_ops is available to check and deny simultaneous access to the same pin from GPIO and pin multiplexing consumers on hardware of this type. The pinctrl driver should set this flag accordingly.

Example **(B)**:



```text
                  pin config
                  logic regs
                  |               +- SPI
Physical pins --- pad --- pinmux -+- I2C
                  |       |       +- mmc
                  |       |
                  GPIO    pin
                          multiplex
                          logic regs
```

In this arrangement, the GPIO functionality can always be enabled, such that e.g. a GPIO input can be used to "spy" on the SPI/I2C/MMC signal while it is pulsed out. It is likely possible to disrupt the traffic on the pin by doing wrong things on the GPIO block, as it is never really disconnected. It is possible that the GPIO, pin config and pin multiplex registers are placed into the same memory range and the same section of the data sheet, although that need not be the case.

In some pin controllers, although the physical pins are designed in the same way as (B), the GPIO function still can't be enabled at the same time as the peripheral functions. So again the "strict" flag should be set, denying simultaneous activation by GPIO and other muxed in devices.

From a kernel point of view, however, these are different aspects of the hardware and shall be put into different subsystems:

- Registers (or fields within registers) that control electrical properties of the pin such as biasing and drive strength should be exposed through the pinctrl subsystem, as "pin configuration" settings.

- Registers (or fields within registers) that control muxing of signals from various other HW blocks (e.g. I2C, MMC, or GPIO) onto pins should be exposed through the pinctrl subsystem, as mux functions.

- Registers (or fields within registers) that control GPIO functionality such as setting a GPIO's output value, reading a GPIO's input value, or setting GPIO pin direction should be exposed through the GPIO subsystem, and if they also support interrupt capabilities, through the irqchip abstraction.

Depending on the exact HW register design, some functions exposed by the GPIO subsystem may call into the pinctrl subsystem in order to coordinate register settings across HW modules. In particular, this may be needed for HW with separate GPIO and pin controller HW modules, where e.g. GPIO direction is determined by a register in the pin controller HW module rather than the GPIO HW module.

Electrical properties of the pin such as biasing and drive strength may be placed at some pin-specific register in all cases or as part of the GPIO register in case (B) especially. This doesn't mean that such properties necessarily pertain to what the Linux kernel calls "GPIO".

Example: a pin is usually muxed in to be used as a UART TX line. But during system sleep, we need to put this pin into "GPIO mode" and ground it.

If you make a 1-to-1 map to the GPIO subsystem for this pin, you may start to think that you need to come up with something really complex, that the pin shall be used for UART TX and GPIO at the same time, that you will grab a pin control handle and set it to a certain state to enable UART TX to be muxed in, then twist it over to GPIO mode and use gpiod_direction_output() to drive it low during sleep, then mux it over to UART TX again when you wake up and maybe even gpiod_get() / gpiod_put() as part of this cycle. This all gets very complicated.

The solution is to not think that what the datasheet calls "GPIO mode" has to be handled by the `<linux/gpio/consumer.h>` interface. Instead view this as a certain pin config setting. Look in e.g. `<linux/pinctrl/pinconf-generic.h>` and you find this in the documentation:

> - **PIN_CONFIG_LEVEL:**
>
>   this will configure the pin in output, use argument 1 to indicate high level, argument 0 to indicate low level.

So it is perfectly possible to push a pin into "GPIO mode" and drive the line low as part of the usual pin control map. So for example your UART driver may look like this:



```c
#include <linux/pinctrl/consumer.h>

struct pinctrl          *pinctrl;
struct pinctrl_state    *pins_default;
struct pinctrl_state    *pins_sleep;

pins_default = pinctrl_lookup_state(uap->pinctrl, PINCTRL_STATE_DEFAULT);
pins_sleep = pinctrl_lookup_state(uap->pinctrl, PINCTRL_STATE_SLEEP);

/* Normal mode */
retval = pinctrl_select_state(pinctrl, pins_default);

/* Sleep mode */
retval = pinctrl_select_state(pinctrl, pins_sleep);
```

And your machine configuration may look like this:



```c
static unsigned long uart_default_mode[] = {
        PIN_CONF_PACKED(PIN_CONFIG_DRIVE_PUSH_PULL, 0),
};

static unsigned long uart_sleep_mode[] = {
        PIN_CONF_PACKED(PIN_CONFIG_LEVEL, 0),
};

static struct pinctrl_map pinmap[] __initdata = {
        PIN_MAP_MUX_GROUP("uart", PINCTRL_STATE_DEFAULT, "pinctrl-foo",
                          "u0_group", "u0"),
        PIN_MAP_CONFIGS_PIN("uart", PINCTRL_STATE_DEFAULT, "pinctrl-foo",
                            "UART_TX_PIN", uart_default_mode),
        PIN_MAP_MUX_GROUP("uart", PINCTRL_STATE_SLEEP, "pinctrl-foo",
                          "u0_group", "gpio-mode"),
        PIN_MAP_CONFIGS_PIN("uart", PINCTRL_STATE_SLEEP, "pinctrl-foo",
                            "UART_TX_PIN", uart_sleep_mode),
};

foo_init(void)
{
        pinctrl_register_mappings(pinmap, ARRAY_SIZE(pinmap));
}
```

Here the pins we want to control are in the "u0_group" and there is some function called "u0" that can be enabled on this group of pins, and then everything is UART business as usual. But there is also some function named "gpio-mode" that can be mapped onto the same pins to move them into GPIO mode.

This will give the desired effect without any bogus interaction with the GPIO subsystem. It is just an electrical configuration used by that device when going to sleep, it might imply that the pin is set into something the datasheet calls "GPIO mode", but that is not the point: it is still used by that UART device to control the pins that pertain to that very UART driver, putting them into modes needed by the UART. GPIO in the Linux kernel sense are just some 1-bit line, and is a different use case.

How the registers are poked to attain the push or pull, and output low configuration and the muxing of the "u0" or "gpio-mode" group onto these pins is a question for the driver.

Some datasheets will be more helpful and refer to the "GPIO mode" as "low power mode" rather than anything to do with GPIO. This often means the same thing electrically speaking, but in this latter case the software engineers will usually quickly identify that this is some specific muxing or configuration rather than anything related to the GPIO API.

<a id="rst-board-machine-configuration"></a>

## Board/machine configuration

Boards and machines define how a certain complete running system is put together, including how GPIOs and devices are muxed, how regulators are constrained and how the clock tree looks. Of course pinmux settings are also part of this.

A pin controller configuration for a machine looks pretty much like a simple regulator configuration, so for the example array above we want to enable i2c and spi on the second function mapping:



```c
#include <linux/pinctrl/machine.h>

static const struct pinctrl_map mapping[] __initconst = {
        {
                .dev_name = "foo-spi.0",
                .name = PINCTRL_STATE_DEFAULT,
                .type = PIN_MAP_TYPE_MUX_GROUP,
                .ctrl_dev_name = "pinctrl-foo",
                .data.mux.function = "spi0",
        },
        {
                .dev_name = "foo-i2c.0",
                .name = PINCTRL_STATE_DEFAULT,
                .type = PIN_MAP_TYPE_MUX_GROUP,
                .ctrl_dev_name = "pinctrl-foo",
                .data.mux.function = "i2c0",
        },
        {
                .dev_name = "foo-mmc.0",
                .name = PINCTRL_STATE_DEFAULT,
                .type = PIN_MAP_TYPE_MUX_GROUP,
                .ctrl_dev_name = "pinctrl-foo",
                .data.mux.function = "mmc0",
        },
};
```

The dev_name here matches to the unique device name that can be used to look up the device struct (just like with clockdev or regulators). The function name must match a function provided by the pinmux driver handling this pin range.

As you can see we may have several pin controllers on the system and thus we need to specify which one of them contains the functions we wish to map.

You register this pinmux mapping to the pinmux subsystem by simply:



```c
ret = pinctrl_register_mappings(mapping, ARRAY_SIZE(mapping));
```

Since the above construct is pretty common there is a helper macro to make it even more compact which assumes you want to use pinctrl-foo and position 0 for mapping, for example:



```c
static struct pinctrl_map mapping[] __initdata = {
        PIN_MAP_MUX_GROUP("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                          "pinctrl-foo", NULL, "i2c0"),
};
```

The mapping table may also contain pin configuration entries. It's common for each pin/group to have a number of configuration entries that affect it, so the table entries for configuration reference an array of config parameters and values. An example using the convenience macros is shown below:



```c
static unsigned long i2c_grp_configs[] = {
        FOO_PIN_DRIVEN,
        FOO_PIN_PULLUP,
};

static unsigned long i2c_pin_configs[] = {
        FOO_OPEN_COLLECTOR,
        FOO_SLEW_RATE_SLOW,
};

static struct pinctrl_map mapping[] __initdata = {
        PIN_MAP_MUX_GROUP("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                          "pinctrl-foo", "i2c0", "i2c0"),
        PIN_MAP_CONFIGS_GROUP("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                              "pinctrl-foo", "i2c0", i2c_grp_configs),
        PIN_MAP_CONFIGS_PIN("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                            "pinctrl-foo", "i2c0scl", i2c_pin_configs),
        PIN_MAP_CONFIGS_PIN("foo-i2c.0", PINCTRL_STATE_DEFAULT,
                            "pinctrl-foo", "i2c0sda", i2c_pin_configs),
};
```

Finally, some devices expect the mapping table to contain certain specific named states. When running on hardware that doesn't need any pin controller configuration, the mapping table must still contain those named states, in order to explicitly indicate that the states were provided and intended to be empty. Table entry macro `PIN_MAP_DUMMY_STATE()` serves the purpose of defining a named state without causing any pin controller to be programmed:



```c
static struct pinctrl_map mapping[] __initdata = {
        PIN_MAP_DUMMY_STATE("foo-i2c.0", PINCTRL_STATE_DEFAULT),
};
```

<a id="rst-complex-mappings"></a>

## Complex mappings

As it is possible to map a function to different groups of pins an optional .group can be specified like this:



```c
...
{
        .dev_name = "foo-spi.0",
        .name = "spi0-pos-A",
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "spi0",
        .group = "spi0_0_grp",
},
{
        .dev_name = "foo-spi.0",
        .name = "spi0-pos-B",
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "spi0",
        .group = "spi0_1_grp",
},
...
```

This example mapping is used to switch between two positions for spi0 at runtime, as described further below under the heading [Runtime pinmuxing](<#rst-runtime-pinmuxing>).

Further it is possible for one named state to affect the muxing of several groups of pins, say for example in the mmc0 example above, where you can additively expand the mmc0 bus from 2 to 4 to 8 pins. If we want to use all three groups for a total of 2 + 2 + 4 = 8 pins (for an 8-bit MMC bus as is the case), we define a mapping like this:



```c
...
{
        .dev_name = "foo-mmc.0",
        .name = "2bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_1_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "4bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_1_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "4bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_2_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "8bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_1_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "8bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_2_grp",
},
{
        .dev_name = "foo-mmc.0",
        .name = "8bit"
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "mmc0",
        .group = "mmc0_3_grp",
},
...
```

The result of grabbing this mapping from the device with something like this (see next paragraph):



```c
p = devm_pinctrl_get(dev);
s = pinctrl_lookup_state(p, "8bit");
ret = pinctrl_select_state(p, s);
```

or more simply:



```c
p = devm_pinctrl_get_select(dev, "8bit");
```

Will be that you activate all the three bottom records in the mapping at once. Since they share the same name, pin controller device, function and device, and since we allow multiple groups to match to a single device, they all get selected, and they all get enabled and disable simultaneously by the pinmux core.

<a id="rst-pin-control-requests-from-drivers"></a>

## Pin control requests from drivers

When a device driver is about to probe, the device core attaches the standard states if they are defined in the device tree by calling `pinctrl_bind_pins()` on these devices. Possible standard state names are: "default", "init", "sleep" and "idle".

- if `default` is defined in the device tree, it is selected before device probe.

- if `init` and `default` are defined in the device tree, the "init" state is selected before the driver probe and the "default" state is selected after the driver probe.

- the `sleep` and `idle` states are for power management and can only be selected with the PM API bellow.

<a id="rst-pm-interfaces"></a>

## PM interfaces

PM runtime suspend/resume might need to execute the same init sequence as during probe. Since the predefined states are already attached to the device, the driver can activate these states explicitly with the following helper functions:

- `pinctrl_pm_select_default_state()`

- `pinctrl_pm_select_init_state()`

- `pinctrl_pm_select_sleep_state()`

- `pinctrl_pm_select_idle_state()`

For example, if resuming the device depend on certain pinmux states



```c
foo_suspend()
{
        /* suspend device */
        ...

        pinctrl_pm_select_sleep_state(dev);
}

foo_resume()
{
        pinctrl_pm_select_init_state(dev);

        /* resuming device */
        ...

        pinctrl_pm_select_default_state(dev);
}
```

This way driver writers do not need to add any of the boilerplate code of the type found below. However when doing fine-grained state selection and not using the "default" state, you may have to do some device driver handling of the pinctrl handles and states.

So if you just want to put the pins for a certain device into the default state and be done with it, there is nothing you need to do besides providing the proper mapping table. The device core will take care of the rest.

Generally it is discouraged to let individual drivers get and enable pin control. So if possible, handle the pin control in platform code or some other place where you have access to all the affected struct device \* pointers. In some cases where a driver needs to e.g. switch between different mux mappings at runtime this is not possible.

A typical case is if a driver needs to switch bias of pins from normal operation and going to sleep, moving from the `PINCTRL_STATE_DEFAULT` to `PINCTRL_STATE_SLEEP` at runtime, re-biasing or even re-muxing pins to save current in sleep mode.

Another case is when the pinctrl needs to switch to a certain mode during probe and then revert to the default state at the end of probe. For example a PINMUX may need to be configured as a GPIO during probe. In this case, use `PINCTRL_STATE_INIT` to switch state before probe, then move to `PINCTRL_STATE_DEFAULT` at the end of probe for normal operation.

A driver may request a certain control state to be activated, usually just the default state like this:



```c
#include <linux/pinctrl/consumer.h>

struct foo_state {
struct pinctrl *p;
struct pinctrl_state *s;
...
};

foo_probe()
{
        /* Allocate a state holder named "foo" etc */
        struct foo_state *foo = ...;
        int ret;

        foo->p = devm_pinctrl_get(&device);
        if (IS_ERR(foo->p)) {
                ret = PTR_ERR(foo->p);
                foo->p = NULL;
                return ret;
        }

        foo->s = pinctrl_lookup_state(foo->p, PINCTRL_STATE_DEFAULT);
        if (IS_ERR(foo->s)) {
                devm_pinctrl_put(foo->p);
                return PTR_ERR(foo->s);
        }

        ret = pinctrl_select_state(foo->p, foo->s);
        if (ret < 0) {
                devm_pinctrl_put(foo->p);
                return ret;
        }
}
```

This get/lookup/select/put sequence can just as well be handled by bus drivers if you don't want each and every driver to handle it and you know the arrangement on your bus.

The semantics of the pinctrl APIs are:

- `pinctrl_get()` is called in process context to obtain a handle to all pinctrl information for a given client device. It will allocate a struct from the kernel memory to hold the pinmux state. All mapping table parsing or similar slow operations take place within this API.

- `devm_pinctrl_get()` is a variant of pinctrl_get() that causes `pinctrl_put()` to be called automatically on the retrieved pointer when the associated device is removed. It is recommended to use this function over plain `pinctrl_get()`.

- `pinctrl_lookup_state()` is called in process context to obtain a handle to a specific state for a client device. This operation may be slow, too.

- `pinctrl_select_state()` programs pin controller hardware according to the definition of the state as given by the mapping table. In theory, this is a fast-path operation, since it only involved blasting some register settings into hardware. However, note that some pin controllers may have their registers on a slow/IRQ-based bus, so client devices should not assume they can call `pinctrl_select_state()` from non-blocking contexts.

- `pinctrl_put()` frees all information associated with a pinctrl handle.

- `devm_pinctrl_put()` is a variant of `pinctrl_put()` that may be used to explicitly destroy a pinctrl object returned by `devm_pinctrl_get()`. However, use of this function will be rare, due to the automatic cleanup that will occur even without calling it.

  `pinctrl_get()` must be paired with a plain `pinctrl_put()`. `pinctrl_get()` may not be paired with `devm_pinctrl_put()`. `devm_pinctrl_get()` can optionally be paired with `devm_pinctrl_put()`. `devm_pinctrl_get()` may not be paired with plain `pinctrl_put()`.

Usually the pin control core handled the get/put pair and call out to the device drivers bookkeeping operations, like checking available functions and the associated pins, whereas `pinctrl_select_state()` pass on to the pin controller driver which takes care of activating and/or deactivating the mux setting by quickly poking some registers.

The pins are allocated for your device when you issue the `devm_pinctrl_get()` call, after this you should be able to see this in the debugfs listing of all pins.

NOTE: the pinctrl system will return `-EPROBE_DEFER` if it cannot find the requested pinctrl handles, for example if the pinctrl driver has not yet registered. Thus make sure that the error path in your driver gracefully cleans up and is ready to retry the probing later in the startup process.

<a id="rst-drivers-needing-both-pin-control-and-gpios"></a>

## Drivers needing both pin control and GPIOs

Again, it is discouraged to let drivers lookup and select pin control states themselves, but again sometimes this is unavoidable.

So say that your driver is fetching its resources like this:



```c
#include <linux/pinctrl/consumer.h>
#include <linux/gpio/consumer.h>

struct pinctrl *pinctrl;
struct gpio_desc *gpio;

pinctrl = devm_pinctrl_get_select_default(&dev);
gpio = devm_gpiod_get(&dev, "foo");
```

Here we first request a certain pin state and then request GPIO "foo" to be used. If you're using the subsystems orthogonally like this, you should nominally always get your pinctrl handle and select the desired pinctrl state BEFORE requesting the GPIO. This is a semantic convention to avoid situations that can be electrically unpleasant, you will certainly want to mux in and bias pins in a certain way before the GPIO subsystems starts to deal with them.

The above can be hidden: using the device core, the pinctrl core may be setting up the config and muxing for the pins right before the device is probing, nevertheless orthogonal to the GPIO subsystem.

But there are also situations where it makes sense for the GPIO subsystem to communicate directly with the pinctrl subsystem, using the latter as a back-end. This is when the GPIO driver may call out to the functions described in the section [Pin control interaction with the GPIO subsystem](<#rst-pin-control-interaction-with-the-gpio-subsystem>) above. This only involves per-pin multiplexing, and will be completely hidden behind the gpiod\_\*() function namespace. In this case, the driver need not interact with the pin control subsystem at all.

If a pin control driver and a GPIO driver is dealing with the same pins and the use cases involve multiplexing, you MUST implement the pin controller as a back-end for the GPIO driver like this, unless your hardware design is such that the GPIO controller can override the pin controller's multiplexing state through hardware without the need to interact with the pin control system.

<a id="rst-system-pin-control-hogging"></a>

## System pin control hogging

Pin control map entries can be hogged by the core when the pin controller is registered. This means that the core will attempt to call `pinctrl_get()`, `pinctrl_lookup_state()` and `pinctrl_select_state()` on it immediately after the pin control device has been registered.

This occurs for mapping table entries where the client device name is equal to the pin controller device name, and the state name is `PINCTRL_STATE_DEFAULT`:



```c
{
        .dev_name = "pinctrl-foo",
        .name = PINCTRL_STATE_DEFAULT,
        .type = PIN_MAP_TYPE_MUX_GROUP,
        .ctrl_dev_name = "pinctrl-foo",
        .function = "power_func",
},
```

Since it may be common to request the core to hog a few always-applicable mux settings on the primary pin controller, there is a convenience macro for this:



```c
PIN_MAP_MUX_GROUP_HOG_DEFAULT("pinctrl-foo", NULL /* group */,
                              "power_func")
```

This gives the exact same result as the above construction.

<a id="rst-runtime-pinmuxing"></a>

## Runtime pinmuxing

It is possible to mux a certain function in and out at runtime, say to move an SPI port from one set of pins to another set of pins. Say for example for spi0 in the example above, we expose two different groups of pins for the same function, but with different named in the mapping as described under "Advanced mapping" above. So that for an SPI device, we have two states named "pos-A" and "pos-B".

This snippet first initializes a state object for both groups (in foo_probe()), then muxes the function in the pins defined by group A, and finally muxes it in on the pins defined by group B:



```c
#include <linux/pinctrl/consumer.h>

struct pinctrl *p;
struct pinctrl_state *s1, *s2;

foo_probe()
{
        /* Setup */
        p = devm_pinctrl_get(&device);
        if (IS_ERR(p))
                ...

        s1 = pinctrl_lookup_state(p, "pos-A");
        if (IS_ERR(s1))
                ...

        s2 = pinctrl_lookup_state(p, "pos-B");
        if (IS_ERR(s2))
                ...
}

foo_switch()
{
        /* Enable on position A */
        ret = pinctrl_select_state(p, s1);
        if (ret < 0)
                ...

        ...

        /* Enable on position B */
        ret = pinctrl_select_state(p, s2);
        if (ret < 0)
                ...

        ...
}
```

The above has to be done from process context. The reservation of the pins will be done when the state is activated, so in effect one specific pin can be used by different functions at different times on a running system.

<a id="rst-debugfs-files"></a>

## Debugfs files

These files are created in `/sys/kernel/debug/pinctrl`:

- `pinctrl-devices`: prints each pin controller device along with columns to indicate support for pinmux and pinconf

- `pinctrl-handles`: prints each configured pin controller handle and the corresponding pinmux maps

- `pinctrl-maps`: prints all pinctrl maps

A sub-directory is created inside of `/sys/kernel/debug/pinctrl` for each pin controller device containing these files:

- `pins`: prints a line for each pin registered on the pin controller. The pinctrl driver may add additional information such as register contents.

- `gpio-ranges`: prints ranges that map gpio lines to pins on the controller

- `pingroups`: prints all pin groups registered on the pin controller

- `pinconf-pins`: prints pin config settings for each pin

- `pinconf-groups`: prints pin config settings per pin group

- `pinmux-functions`: prints each pin function along with the pin groups that map to the pin function

- `pinmux-pins`: iterates through all pins and prints mux owner, gpio owner and if the pin is a hog

- `pinmux-select`: write to this file to activate a pin function for a group:



  ```sh
  echo "<group-name function-name>" > pinmux-select
  ```

---

# PPS - Pulse Per Second

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Copyright (C) 2007 Rodolfo Giometti <giometti@enneenne.com>

<a id="rst-pps-pulse-per-second"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Copyright (C) 2007 Rodolfo Giometti &lt;[giometti@enneenne.com](<mailto:giometti@enneenne.com>)&gt;

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

<a id="rst-overview"></a>

## Overview

LinuxPPS provides a programming interface (API) to define in the system several PPS sources.

PPS means "pulse per second" and a PPS source is just a device which provides a high precision signal each second so that an application can use it to adjust system clock time.

A PPS source can be connected to a serial port (usually to the Data Carrier Detect pin) or to a parallel port (ACK-pin) or to a special CPU's GPIOs (this is the common case in embedded systems) but in each case when a new pulse arrives the system must apply to it a timestamp and record it for userland.

Common use is the combination of the NTPD as userland program, with a GPS receiver as PPS source, to obtain a wallclock-time with sub-millisecond synchronisation to UTC.

<a id="rst-rfc-considerations"></a>

## RFC considerations

While implementing a PPS API as RFC 2783 defines and using an embedded CPU GPIO-Pin as physical link to the signal, I encountered a deeper problem:

> At startup it needs a file descriptor as argument for the function time_pps_create().

This implies that the source has a /dev/... entry. This assumption is OK for the serial and parallel port, where you can do something useful besides(\!) the gathering of timestamps as it is the central task for a PPS API. But this assumption does not work for a single purpose GPIO line. In this case even basic file-related functionality (like read() and write()) makes no sense at all and should not be a precondition for the use of a PPS API.

The problem can be simply solved if you consider that a PPS source is not always connected with a GPS data source.

So your programs should check if the GPS data source (the serial port for instance) is a PPS source too, and if not they should provide the possibility to open another device as PPS source.

In LinuxPPS the PPS sources are simply char devices usually mapped into files /dev/pps0, /dev/pps1, etc.

<a id="rst-pps-with-usb-to-serial-devices"></a>

## PPS with USB to serial devices

It is possible to grab the PPS from an USB to serial device. However, you should take into account the latencies and jitter introduced by the USB stack. Users have reported clock instability around +-1ms when synchronized with PPS through USB. With USB 2.0, jitter may decrease down to the order of 125 microseconds.

This may be suitable for time server synchronization with NTP because of its undersampling and algorithms.

If your device doesn't report PPS, you can check that the feature is supported by its driver. Most of the time, you only need to add a call to usb_serial_handle_dcd_change after checking the DCD status (see ch341 and pl2303 examples).

<a id="rst-coding-example"></a>

## Coding example

To register a PPS source into the kernel you should define a struct pps_source_info as follows:



```text
static struct pps_source_info pps_ktimer_info = {
        .name         = "ktimer",
        .path         = "",
        .mode         = PPS_CAPTUREASSERT | PPS_OFFSETASSERT |
                        PPS_ECHOASSERT |
                        PPS_CANWAIT | PPS_TSFMT_TSPEC,
        .echo         = pps_ktimer_echo,
        .owner        = THIS_MODULE,
};
```

and then calling the function pps_register_source() in your initialization routine as follows:



```text
source = pps_register_source(&pps_ktimer_info,
                    PPS_CAPTUREASSERT | PPS_OFFSETASSERT);
```

The pps_register_source() prototype is:



```text
int pps_register_source(struct pps_source_info *info, int default_params)
```

where "info" is a pointer to a structure that describes a particular PPS source, "default_params" tells the system what the initial default parameters for the device should be (it is obvious that these parameters must be a subset of ones defined in the struct pps_source_info which describe the capabilities of the driver).

Once you have registered a new PPS source into the system you can signal an assert event (for example in the interrupt handler routine) just using:



```text
pps_event(source, &ts, PPS_CAPTUREASSERT, ptr)
```

where "ts" is the event's timestamp.

The same function may also run the defined echo function (pps_ktimer_echo(), passing to it the "ptr" pointer) if the user asked for that... etc..

Please see the file drivers/pps/clients/pps-ktimer.c for example code.

<a id="rst-sysfs-support"></a>

## SYSFS support

If the SYSFS filesystem is enabled in the kernel it provides a new class:



```text
$ ls /sys/class/pps/
pps0/  pps1/  pps2/
```

Every directory is the ID of a PPS sources defined in the system and inside you find several files:



```text
$ ls -F /sys/class/pps/pps0/
assert     dev        mode       path       subsystem@
clear      echo       name       power/     uevent
```

Inside each "assert" and "clear" file you can find the timestamp and a sequence number:



```text
$ cat /sys/class/pps/pps0/assert
1170026870.983207967#8
```

Where before the "\#" is the timestamp in seconds; after it is the sequence number. Other files are:

> - echo: reports if the PPS source has an echo function or not;
>
> - mode: reports available PPS functioning modes;
>
> - name: reports the PPS source's name;
>
> - path: reports the PPS source's device path, that is the device the PPS source is connected to (if it exists).

<a id="rst-testing-the-pps-support"></a>

## Testing the PPS support

In order to test the PPS support even without specific hardware you can use the pps-ktimer driver (see the client subsection in the PPS configuration menu) and the userland tools available in your distribution's pps-tools package, [http://linuxpps.org](<http://linuxpps.org>) , or [https://github.com/redlab-i/pps-tools](<https://github.com/redlab-i/pps-tools>).

Once you have enabled the compilation of pps-ktimer just modprobe it (if not statically compiled):



```text
# modprobe pps-ktimer
```

and the run ppstest as follow:



```text
$ ./ppstest /dev/pps1
trying PPS source "/dev/pps1"
found PPS source "/dev/pps1"
ok, found 1 source(s), now start fetching data...
source 0 - assert 1186592699.388832443, sequence: 364 - clear  0.000000000, sequence: 0
source 0 - assert 1186592700.388931295, sequence: 365 - clear  0.000000000, sequence: 0
source 0 - assert 1186592701.389032765, sequence: 366 - clear  0.000000000, sequence: 0
```

Please note that to compile userland programs, you need the file timepps.h. This is available in the pps-tools repository mentioned above.

<a id="rst-generators"></a>

## Generators

Sometimes one needs to be able not only to catch PPS signals but to produce them also. For example, running a distributed simulation, which requires computers' clock to be synchronized very tightly.

To do so the class pps-gen has been added. PPS generators can be registered in the kernel by defining a struct pps_gen_source_info as follows:



```text
static const struct pps_gen_source_info pps_gen_dummy_info = {
        .use_system_clock       = true,
        .get_time               = pps_gen_dummy_get_time,
        .enable                 = pps_gen_dummy_enable,
};
```

Where the use_system_clock states if the generator uses the system clock to generate its pulses, or they are from a peripheral device clock. Method get_time() is used to query the time stored into the generator clock, while the method enable() is used to enable or disable the PPS pulse generation.

Then calling the function pps_gen_register_source() in your initialization routine as follows creates a new generator in the system:



```text
pps_gen = pps_gen_register_source(&pps_gen_dummy_info);
```

<a id="rst-generators-sysfs-support"></a>

## Generators SYSFS support

If the SYSFS filesystem is enabled in the kernel it provides a new class:



```text
$ ls /sys/class/pps-gen/
pps-gen0/  pps-gen1/  pps-gen2/
```

Every directory is the ID of a PPS generator defined in the system and inside of it you find several files:



```text
$ ls -F /sys/class/pps-gen/pps-gen0/
dev  enable  name  power/  subsystem@  system  time  uevent
```

To enable the PPS signal generation you can use the command below:



```text
$ echo 1 > /sys/class/pps-gen/pps-gen0/enable
```

<a id="rst-parallel-port-generator"></a>

## Parallel port generator

One way to do this is to invent some complicated hardware solutions but it may be neither necessary nor affordable. The cheap way is to load a PPS generator on one of the computers (master) and PPS clients on others (slaves), and use very simple cables to deliver signals using parallel ports, for example.

Parallel port cable pinout:



```text
pin     name    master      slave
1       STROBE    *------     *
2       D0        *     |     *
3       D1        *     |     *
4       D2        *     |     *
5       D3        *     |     *
6       D4        *     |     *
7       D5        *     |     *
8       D6        *     |     *
9       D7        *     |     *
10      ACK       *     ------*
11      BUSY      *           *
12      PE        *           *
13      SEL       *           *
14      AUTOFD    *           *
15      ERROR     *           *
16      INIT      *           *
17      SELIN     *           *
18-25   GND       *-----------*
```

Please note that parallel port interrupt occurs only on high-&gt;low transition, so it is used for PPS assert edge. PPS clear edge can be determined only using polling in the interrupt handler which actually can be done way more precisely because interrupt handling delays can be quite big and random. So current parport PPS generator implementation (pps_gen_parport module) is geared towards using the clear edge for time synchronization.

Clear edge polling is done with disabled interrupts so it's better to select delay between assert and clear edge as small as possible to reduce system latencies. But if it is too small slave won't be able to capture clear edge transition. The default of 30us should be good enough in most situations. The delay can be selected using 'delay' pps_gen_parport module parameter.

<a id="rst-intel-timed-i-o-pps-signal-generator"></a>

## Intel Timed I/O PPS signal generator

Intel Timed I/O is a high precision device, present on 2019 and newer Intel CPUs, that can generate PPS signals.

Timed I/O and system time are both driven by same hardware clock. The signal is generated with a precision of \~20 nanoseconds. The generated PPS signal is used to synchronize an external device with system clock. For example, it can be used to share your clock with a device that receives PPS signal, generated by Timed I/O device. There are dedicated Timed I/O pins to deliver the PPS signal to an external device.

Usage of Intel Timed I/O as PPS generator:

Start generating PPS signal:



```text
$echo 1 > /sys/class/pps-gen/pps-genx/enable
```

Stop generating PPS signal:



```text
$echo 0 > /sys/class/pps-gen/pps-genx/enable
```

---

# PTP hardware clock infrastructure for Linux

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This patch set introduces support for IEEE 1588 PTP clocks in Linux. Together with the SO_TIMESTAMPING socket options, this presents a standardized method for developing PTP user space programs, synchronizing Linux with external clocks,…

<a id="rst-ptp-hardware-clock-infrastructure-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> This patch set introduces support for IEEE 1588 PTP clocks in Linux. Together with the SO_TIMESTAMPING socket options, this presents a standardized method for developing PTP user space programs, synchronizing Linux with external clocks, and using the ancillary features of PTP hardware clocks.
>
> A new class driver exports a kernel interface for specific clock drivers and a user space interface. The infrastructure supports a complete set of PTP hardware clock functionality.
>
> - Basic clock operations - Set time - Get time - Shift the clock by a given offset atomically - Adjust clock frequency
>
> - Ancillary clock features - Time stamp external events - Period output signals configurable from user space - Low Pass Filter (LPF) access from user space - Synchronization of the Linux system time via the PPS subsystem

<a id="rst-ptp-hardware-clock-kernel-api"></a>

## PTP hardware clock kernel API

> A PTP clock driver registers itself with the class driver. The class driver handles all of the dealings with user space. The author of a clock driver need only implement the details of programming the clock hardware. The clock driver notifies the class driver of asynchronous events (alarms and external time stamps) via a simple message passing interface.
>
> The class driver supports multiple PTP clock drivers. In normal use cases, only one PTP clock is needed. However, for testing and development, it can be useful to have more than one clock in a single system, in order to allow performance comparisons.

<a id="rst-ptp-hardware-clock-user-space-api"></a>

## PTP hardware clock user space API

> The class driver also creates a character device for each registered clock. User space can use an open file descriptor from the character device as a POSIX clock id and may call clock_gettime, clock_settime, and clock_adjtime.  These calls implement the basic clock operations.
>
> User space programs may control the clock using standardized ioctls. A program may query, enable, configure, and disable the ancillary clock features. User space can receive time stamped events via blocking read() and poll().

<a id="rst-writing-clock-drivers"></a>

## Writing clock drivers

> Clock drivers include include/linux/ptp_clock_kernel.h and register themselves by presenting a 'struct ptp_clock_info' to the registration method. Clock drivers must implement all of the functions in the interface. If a clock does not offer a particular ancillary feature, then the driver should just return -EOPNOTSUPP from those functions.
>
> Drivers must ensure that all of the methods in interface are reentrant. Since most hardware implementations treat the time value as a 64 bit integer accessed as two 32 bit registers, drivers should use spin_lock_irqsave/spin_unlock_irqrestore to protect against concurrent access. This locking cannot be accomplished in class driver, since the lock may also be needed by the clock driver's interrupt service routine.

<a id="rst-ptp-hardware-clock-requirements-for-adjphase"></a>

### PTP hardware clock requirements for '.adjphase'

> The 'struct ptp_clock_info' interface has a '.adjphase' function. This function has a set of requirements from the PHC in order to be implemented.
>
> > - The PHC implements a servo algorithm internally that is used to correct the offset passed in the '.adjphase' call.
> >
> > - When other PTP adjustment functions are called, the PHC servo algorithm is disabled.
>
> **NOTE:** '.adjphase' is not a simple time adjustment functionality that 'jumps' the PHC clock time based on the provided offset. It should correct the offset provided using an internal algorithm.

<a id="rst-supported-hardware"></a>

## Supported hardware

> - Freescale eTSEC gianfar
>
>   - 2 Time stamp external triggers, programmable polarity (opt. interrupt)
>
>   - 2 Alarm registers (optional interrupt)
>
>   - 3 Periodic signals (optional interrupt)
>
> - National DP83640
>
>   - 6 GPIOs programmable as inputs or outputs
>
>   - 6 GPIOs with dedicated functions (LED/JTAG/clock) can also be used as general inputs or outputs
>
>   - GPIO inputs can time stamp external triggers
>
>   - GPIO outputs can produce periodic signals
>
>   - 1 interrupt pin
>
> - Intel IXP465
>
>   - Auxiliary Slave/Master Mode Snapshot (optional interrupt)
>
>   - Target Time (optional interrupt)
>
> - Renesas (IDT) ClockMatrix™
>
>   - Up to 4 independent PHC channels
>
>   - Integrated low pass filter (LPF), access via .adjPhase (compliant to ITU-T G.8273.2)
>
>   - Programmable output periodic signals
>
>   - Programmable inputs can time stamp external triggers
>
>   - - **Driver and/or hardware configuration through firmware (idtcm.bin)**
>
>       - LPF settings (bandwidth, phase limiting, automatic holdover, physical layer assist (per ITU-T G.8273.2))
>
>       - Programmable output PTP clocks, any frequency up to 1GHz (to other PHY/MAC time stampers, refclk to ASSPs/SoCs/FPGAs)
>
>       - Lock to GNSS input, automatic switching between GNSS and user-space PHC control (optional)
>
> - NVIDIA Mellanox
>
>   - - **GPIO**
>
>       - Certain variants of ConnectX-6 Dx and later products support one GPIO which can time stamp external triggers and one GPIO to produce periodic signals.
>
>       - Certain variants of ConnectX-5 and older products support one GPIO, configured to either time stamp external triggers or produce periodic signals.
>
>   - - **PHC instances**
>
>       - All ConnectX devices have a free-running counter
>
>       - ConnectX-6 Dx and later devices have a UTC format counter

---

# Pulse Width Modulation (PWM) interface

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This provides an overview about the Linux PWM interface

<a id="rst-pulse-width-modulation-pwm-interface"></a>

This provides an overview about the Linux PWM interface

PWMs are commonly used for controlling LEDs, fans or vibrators in cell phones. PWMs with a fixed purpose have no need implementing the Linux PWM API (although they could). However, PWMs are often found as discrete devices on SoCs which have no fixed purpose. It's up to the board designer to connect them to LEDs or fans. To provide this kind of flexibility the generic PWM API exists.

<a id="rst-identifying-pwms"></a>

## Identifying PWMs

Users of the legacy PWM API use unique IDs to refer to PWM devices.

Instead of referring to a PWM device via its unique ID, board setup code should instead register a static mapping that can be used to match PWM consumers to providers, as given in the following example:



```text
static struct pwm_lookup board_pwm_lookup[] = {
        PWM_LOOKUP("tegra-pwm", 0, "pwm-backlight", NULL,
                   50000, PWM_POLARITY_NORMAL),
};

static void __init board_init(void)
{
        ...
        pwm_add_table(board_pwm_lookup, ARRAY_SIZE(board_pwm_lookup));
        ...
}
```

<a id="rst-using-pwms"></a>

## Using PWMs

Consumers use the pwm_get() function and pass to it the consumer device or a consumer name. pwm_put() is used to free the PWM device. Managed variants of the getter, devm_pwm_get() and devm_fwnode_pwm_get(), also exist.

After being requested, a PWM has to be configured using:



```text
int pwm_apply_might_sleep(struct pwm_device *pwm, struct pwm_state *state);
```

This API controls both the PWM period/duty_cycle config and the enable/disable state.

PWM devices can be used from atomic context, if the PWM does not sleep. You can check if this the case with:



```text
bool pwm_might_sleep(struct pwm_device *pwm);
```

If false, the PWM can also be configured from atomic context with:



```text
int pwm_apply_atomic(struct pwm_device *pwm, struct pwm_state *state);
```

As a consumer, don't rely on the output's state for a disabled PWM. If it's easily possible, drivers are supposed to emit the inactive state, but some drivers cannot. If you rely on getting the inactive state, use .duty_cycle=0, .enabled=true.

There is also a usage_power setting: If set, the PWM driver is only required to maintain the power output but has more freedom regarding signal form. If supported by the driver, the signal can be optimized, for example to improve EMI by phase shifting the individual channels of a chip.

The pwm_config(), pwm_enable() and pwm_disable() functions are just wrappers around pwm_apply_might_sleep() and should not be used if the user wants to change several parameter at once. For example, if you see pwm_config() and pwm\_\{enable,disable\}() calls in the same function, this probably means you should switch to pwm_apply_might_sleep().

The PWM user API also allows one to query the PWM state that was passed to the last invocation of pwm_apply_might_sleep() using pwm_get_state(). Note this is different to what the driver has actually implemented if the request cannot be satisfied exactly with the hardware in use. There is currently no way for consumers to get the actually implemented settings.

In addition to the PWM state, the PWM API also exposes PWM arguments, which are the reference PWM config one should use on this PWM. PWM arguments are usually platform-specific and allows the PWM user to only care about dutycycle relatively to the full period (like, duty = 50% of the period). struct pwm_args contains 2 fields (period and polarity) and should be used to set the initial PWM config (usually done in the probe function of the PWM user). PWM arguments are retrieved with pwm_get_args().

All consumers should really be reconfiguring the PWM upon resume as appropriate. This is the only way to ensure that everything is resumed in the proper order.

<a id="rst-using-pwms-with-the-sysfs-interface"></a>

## Using PWMs with the sysfs interface

If CONFIG_SYSFS is enabled in your kernel configuration a simple sysfs interface is provided to use the PWMs from userspace. It is exposed at /sys/class/pwm/. Each probed PWM controller/chip will be exported as pwmchipN, where N is the base of the PWM chip. Inside the directory you will find:

> - **npwm**
>
>   The number of PWM channels this chip supports (read-only).
>
> - **export**
>
>   Exports a PWM channel for use with sysfs (write-only).
>
> - **unexport**
>
>   Unexports a PWM channel from sysfs (write-only).

The PWM channels are numbered using a per-chip index from 0 to npwm-1.

When a PWM channel is exported a pwmX directory will be created in the pwmchipN directory it is associated with, where X is the number of the channel that was exported. The following properties will then be available:

> - **period**
>
>   The total period of the PWM signal (read/write). Value is in nanoseconds and is the sum of the active and inactive time of the PWM.
>
> - **duty_cycle**
>
>   The active time of the PWM signal (read/write). Value is in nanoseconds and must be less than or equal to the period.
>
> - **polarity**
>
>   Changes the polarity of the PWM signal (read/write). Writes to this property only work if the PWM chip supports changing the polarity. Value is the string "normal" or "inversed".
>
> - **enable**
>
>   Enable/disable the PWM signal (read/write).
>
>   > - 0 - disabled
>   >
>   > - 1 - enabled

<a id="rst-implementing-a-pwm-driver"></a>

## Implementing a PWM driver

Currently there are two ways to implement pwm drivers. Traditionally there only has been the barebone API meaning that each driver has to implement the pwm\_\*() functions itself. This means that it's impossible to have multiple PWM drivers in the system. For this reason it's mandatory for new drivers to use the generic PWM framework.

A new PWM controller/chip can be allocated using pwmchip_alloc(), then registered using pwmchip_add() and removed again with pwmchip_remove(). To undo pwmchip_alloc() use pwmchip_put(). pwmchip_add() takes a filled in struct pwm_chip as argument which provides a description of the PWM chip, the number of PWM devices provided by the chip and the chip-specific implementation of the supported PWM operations to the framework.

When implementing polarity support in a PWM driver, make sure to respect the signal conventions in the PWM framework. By definition, normal polarity characterizes a signal starts high for the duration of the duty cycle and goes low for the remainder of the period. Conversely, a signal with inversed polarity starts low for the duration of the duty cycle and goes high for the remainder of the period.

Drivers are encouraged to implement -&gt;apply() instead of the legacy -&gt;enable(), -&gt;disable() and -&gt;config() methods. Doing that should provide atomicity in the PWM config workflow, which is required when the PWM controls a critical device (like a regulator).

The implementation of -&gt;get_state() (a method used to retrieve initial PWM state) is also encouraged for the same reason: letting the PWM user know about the current PWM state would allow him to avoid glitches.

Drivers should not implement any power management. In other words, consumers should implement it as described in the "Using PWMs" section.

<a id="rst-locking"></a>

## Locking

The PWM core list manipulations are protected by a mutex, so pwm_get() and pwm_put() may not be called from an atomic context. Most functions in the PWM consumer API might sleep and so must not be called from atomic context. The notable exception is pwm_apply_atomic() which has the same semantics as pwm_apply_might_sleep() but can be called from atomic context. (The price for that is that it doesn't work for all PWM devices, use pwm_might_sleep() to check if a given PWM supports atomic operation.

Locking in the PWM core ensures that callbacks related to a single chip are serialized.

<a id="rst-helpers"></a>

## Helpers

Currently a PWM can only be configured with period_ns and duty_ns. For several use cases freq_hz and duty_percent might be better. Instead of calculating this in your driver please consider adding appropriate helpers to the framework.

---

# Power Sequencing API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This framework is designed to abstract complex power-up sequences that are shared between multiple logical devices in the Linux kernel.

<a id="rst-power-sequencing-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

<!-- Copyright 2024 Linaro Ltd. -->

**Author:** Bartosz Golaszewski

<a id="rst-introduction"></a>

## Introduction

This framework is designed to abstract complex power-up sequences that are shared between multiple logical devices in the Linux kernel.

The intention is to allow consumers to obtain a power sequencing handle exposed by the power sequence provider and delegate the actual requesting and control of the underlying resources as well as to allow the provider to mitigate any potential conflicts between multiple users behind the scenes.

<a id="rst-glossary"></a>

### Glossary

The power sequencing API uses a number of terms specific to the subsystem:

Unit

> A unit is a discrete chunk of a power sequence. For instance one unit may enable a set of regulators, another may enable a specific GPIO. Units can define dependencies in the form of other units that must be enabled before it itself can be.

Target

> A target is a set of units (composed of the "final" unit and its dependencies) that a consumer selects by its name when requesting a handle to the power sequencer. Via the dependency system, multiple targets may share the same parts of a power sequence but ignore parts that are irrelevant.

Descriptor

> A handle passed by the pwrseq core to every consumer that serves as the entry point to the provider layer. It ensures coherence between different users and keeps reference counting consistent.

<a id="rst-consumer-interface"></a>

## Consumer interface

The consumer API is aimed to be as simple as possible. The driver interested in getting a descriptor from the power sequencer should call pwrseq_get() and specify the name of the target it wants to reach in the sequence after calling pwrseq_power_up(). The descriptor can be released by calling pwrseq_put() and the consumer can request the powering down of its target with pwrseq_power_off(). Note that there is no guarantee that pwrseq_power_off() will have any effect as there may be multiple users of the underlying resources who may keep them active.

<a id="rst-provider-interface"></a>

## Provider interface

The provider API is admittedly not nearly as straightforward as the one for consumers but it makes up for it in flexibility.

Each provider can logically split the power-up sequence into discrete chunks (units) and define their dependencies. They can then expose named targets that consumers may use as the final point in the sequence that they wish to reach.

To that end the providers fill out a set of configuration structures and register with the pwrseq subsystem by calling pwrseq_device_register().

<a id="rst-dynamic-consumer-matching"></a>

### Dynamic consumer matching

The main difference between pwrseq and other Linux kernel providers is the mechanism for dynamic matching of consumers and providers. Every power sequence provider driver must implement the `match()` callback and pass it to the pwrseq core when registering with the subsystems.

When a client requests a sequencer handle, the core will call this callback for every registered provider and let it flexibly figure out whether the proposed client device is indeed its consumer. For example: if the provider binds to the device-tree node representing a power management unit of a chipset and the consumer driver controls one of its modules, the provider driver may parse the relevant regulator supply properties in device tree and see if they lead from the PMU to the consumer.

<a id="rst-api-reference"></a>

## API reference


#### <a id="c-struct-pwrseq_unit_data"></a>`struct pwrseq_unit_data`

Configuration of a single power sequencing unit.

**Definition**

```c
struct pwrseq_unit_data {
    const char *name;
    const struct pwrseq_unit_data **deps;
    pwrseq_power_state_func enable;
    pwrseq_power_state_func disable;
};
```

**Members**

- `name`: Name of the unit.
- `deps`: Units that must be enabled before this one and disabled after it
  in the order they come in this array. Must be NULL-terminated.
- `enable`: Callback running the part of the power-on sequence provided by
  this unit.
- `disable`: Callback running the part of the power-off sequence provided
  by this unit.

#### <a id="c-struct-pwrseq_target_data"></a>`struct pwrseq_target_data`

Configuration of a power sequencing target.

**Definition**

```c
struct pwrseq_target_data {
    const char *name;
    const struct pwrseq_unit_data *unit;
    pwrseq_power_state_func post_enable;
};
```

**Members**

- `name`: Name of the target.
- `unit`: Final unit that this target must reach in order to be considered
  enabled.
- `post_enable`: Callback run after the target unit has been enabled, *after*
  the state lock has been released. It's useful for implementing
  boot-up delays without blocking other users from powering up
  using the same power sequencer.

#### <a id="c-struct-pwrseq_config"></a>`struct pwrseq_config`

Configuration used for registering a new provider.

**Definition**

```c
struct pwrseq_config {
    struct device *parent;
    struct module *owner;
    void *drvdata;
    pwrseq_match_func match;
    const struct pwrseq_target_data **targets;
};
```

**Members**

- `parent`: Parent device for the sequencer. Must be set.
- `owner`: Module providing this device.
- `drvdata`: Private driver data.
- `match`: Provider callback used to match the consumer device to the sequencer.
- `targets`: Array of targets for this power sequencer. Must be NULL-terminated.



#### <a id="c-pwrseq_device_register"></a>`pwrseq_device_register()`

```c
struct pwrseq_device * pwrseq_device_register(const struct pwrseq_config *config)
```

Register a new power sequencer.

**Parameters**

- `const struct pwrseq_config *config`: Configuration of the new power sequencing device.

**Description**

The config structure is only used during the call and can be freed after
the function returns. The config structure *must* have the parent device
as well as the `match()` callback and at least one target set.

**Return**

Returns the address of the new pwrseq device or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure.

#### <a id="c-pwrseq_device_unregister"></a>`pwrseq_device_unregister()`

```c
void pwrseq_device_unregister(struct pwrseq_device *pwrseq)
```

Unregister the power sequencer.

**Parameters**

- `struct pwrseq_device *pwrseq`: Power sequencer to unregister.

#### <a id="c-devm_pwrseq_device_register"></a>`devm_pwrseq_device_register()`

```c
struct pwrseq_device * devm_pwrseq_device_register(struct device *dev, const struct pwrseq_config *config)
```

Managed variant of [`pwrseq_device_register()`](#c-pwrseq_device_register).

**Parameters**

- `struct device *dev`: Managing device.
- `const struct pwrseq_config *config`: Configuration of the new power sequencing device.

**Return**

Returns the address of the new pwrseq device or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure.

#### <a id="c-pwrseq_device_get_drvdata"></a>`pwrseq_device_get_drvdata()`

```c
void * pwrseq_device_get_drvdata(struct pwrseq_device *pwrseq)
```

Get the driver private data associated with this sequencer.

**Parameters**

- `struct pwrseq_device *pwrseq`: Power sequencer object.

**Return**

Address of the private driver data.

#### <a id="c-pwrseq_get"></a>`pwrseq_get()`

```c
struct pwrseq_desc * pwrseq_get(struct device *dev, const char *target)
```

Get the power sequencer associated with this device.

**Parameters**

- `struct device *dev`: Device for which to get the sequencer.
- `const char *target`: Name of the target exposed by the sequencer this device wants to
  reach.

**Return**

New power sequencer descriptor for use by the consumer driver or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)
on failure.

#### <a id="c-pwrseq_put"></a>`pwrseq_put()`

```c
void pwrseq_put(struct pwrseq_desc *desc)
```

Release the power sequencer descriptor.

**Parameters**

- `struct pwrseq_desc *desc`: Descriptor to release.

#### <a id="c-devm_pwrseq_get"></a>`devm_pwrseq_get()`

```c
struct pwrseq_desc * devm_pwrseq_get(struct device *dev, const char *target)
```

Managed variant of [`pwrseq_get()`](#c-pwrseq_get).

**Parameters**

- `struct device *dev`: Device for which to get the sequencer and which also manages its
  lifetime.
- `const char *target`: Name of the target exposed by the sequencer this device wants to
  reach.

**Return**

New power sequencer descriptor for use by the consumer driver or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)
on failure.

#### <a id="c-pwrseq_power_on"></a>`pwrseq_power_on()`

```c
int pwrseq_power_on(struct pwrseq_desc *desc)
```

Issue a power-on request on behalf of the consumer device.

**Parameters**

- `struct pwrseq_desc *desc`: Descriptor referencing the power sequencer.

**Description**

This function tells the power sequencer that the consumer wants to be
powered-up. The sequencer may already have powered-up the device in which
case the function returns 0. If the power-up sequence is already in
progress, the function will block until it's done and return 0. If this is
the first request, the device will be powered up.

**Return**

0 on success, negative error number on failure.

#### <a id="c-pwrseq_power_off"></a>`pwrseq_power_off()`

```c
int pwrseq_power_off(struct pwrseq_desc *desc)
```

Issue a power-off request on behalf of the consumer device.

**Parameters**

- `struct pwrseq_desc *desc`: Descriptor referencing the power sequencer.

**Description**

This undoes the effects of [`pwrseq_power_on()`](#c-pwrseq_power_on). It issues a power-off request
on behalf of the consumer and when the last remaining user does so, the
power-down sequence will be started. If one is in progress, the function
will block until it's complete and then return.

**Return**

0 on success, negative error number on failure.

---

# Voltage and current regulator API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> This framework is designed to provide a standard kernel interface to control voltage and current regulators.

<a id="rst-voltage-and-current-regulator-api"></a>

<!-- Copyright 2007-2008 Wolfson Microelectronics -->

<!-- This documentation is free software; you can redistribute -->

<!-- it and/or modify it under the terms of the GNU General Public -->

<!-- License version 2 as published by the Free Software Foundation. -->

**Author:** Liam Girdwood

**Author:** Mark Brown

<a id="rst-introduction"></a>

## Introduction

This framework is designed to provide a standard kernel interface to control voltage and current regulators.

The intention is to allow systems to dynamically control regulator power output in order to save power and prolong battery life. This applies to both voltage regulators (where voltage output is controllable) and current sinks (where current limit is controllable).

Note that additional (and currently more complete) documentation is available in the Linux kernel source under `Documentation/power/regulator`.

<a id="rst-glossary"></a>

### Glossary

The regulator API uses a number of terms which may not be familiar:

Regulator

> Electronic device that supplies power to other devices. Most regulators can enable and disable their output and some can also control their output voltage or current.

Consumer

> Electronic device which consumes power provided by a regulator. These may either be static, requiring only a fixed supply, or dynamic, requiring active management of the regulator at runtime.

Power Domain

> The electronic circuit supplied by a given regulator, including the regulator and all consumer devices. The configuration of the regulator is shared between all the components in the circuit.

Power Management Integrated Circuit (PMIC)

> An IC which contains numerous regulators and often also other subsystems. In an embedded system the primary PMIC is often equivalent to a combination of the PSU and southbridge in a desktop system.

<a id="rst-consumer-driver-interface"></a>

## Consumer driver interface

This offers a similar API to the kernel clock framework. Consumer drivers use [get](#c-regulator_get) and [put](#c-regulator_put) operations to acquire and release regulators. Functions are provided to [enable](#c-regulator_enable) and [disable](#c-regulator_disable) the regulator and to get and set the runtime parameters of the regulator.

When requesting regulators consumers use symbolic names for their supplies, such as "Vcc", which are mapped into actual regulator devices by the machine interface.

A stub version of this API is provided when the regulator framework is not in use in order to minimise the need to use ifdefs.

<a id="rst-enabling-and-disabling"></a>

### Enabling and disabling

The regulator API provides reference counted enabling and disabling of regulators. Consumer devices use the `regulator_enable()` and `regulator_disable()` functions to enable and disable regulators. Calls to the two functions must be balanced.

Note that since multiple consumers may be using a regulator and machine constraints may not allow the regulator to be disabled there is no guarantee that calling `regulator_disable()` will actually cause the supply provided by the regulator to be disabled. Consumer drivers should assume that the regulator may be enabled at all times.

<a id="rst-configuration"></a>

### Configuration

Some consumer devices may need to be able to dynamically configure their supplies. For example, MMC drivers may need to select the correct operating voltage for their cards. This may be done while the regulator is enabled or disabled.

The `regulator_set_voltage()` and `regulator_set_current_limit()` functions provide the primary interface for this. Both take ranges of voltages and currents, supporting drivers that do not require a specific value (eg, CPU frequency scaling normally permits the CPU to use a wider range of supply voltages at lower frequencies but does not require that the supply voltage be lowered). Where an exact value is required both minimum and maximum values should be identical.

<a id="rst-callbacks"></a>

### Callbacks

Callbacks may also be registered for events such as regulation failures.

<a id="rst-regulator-driver-interface"></a>

## Regulator driver interface

Drivers for regulator chips register the regulators with the regulator core, providing operations structures to the core. A notifier interface allows error conditions to be reported to the core.

Registration should be triggered by explicit setup done by the platform, supplying a struct regulator_init_data for the regulator containing constraint and supply information.

<a id="rst-machine-interface"></a>

## Machine interface

This interface provides a way to define how regulators are connected to consumers on a given system and what the valid operating parameters are for the system.

<a id="rst-supplies"></a>

### Supplies

Regulator supplies are specified using struct `regulator_consumer_supply`. This is done at driver registration time as part of the machine constraints.

<a id="rst-constraints"></a>

### Constraints

As well as defining the connections the machine interface also provides constraints defining the operations that clients are allowed to perform and the parameters that may be set. This is required since generally regulator devices will offer more flexibility than it is safe to use on a given system, for example supporting higher supply voltages than the consumers are rated for.

This is done at driver registration time\` by providing a struct regulation_constraints.

The constraints may also specify an initial configuration for the regulator in the constraints, which is particularly useful for use with static consumers.

<a id="rst-api-reference"></a>

## API reference

Due to limitations of the kernel documentation framework and the existing layout of the source code the entire regulator API is documented here.


#### <a id="c-struct-pre_voltage_change_data"></a>`struct pre_voltage_change_data`

Data sent with PRE_VOLTAGE_CHANGE event

**Definition**

```c
struct pre_voltage_change_data {
    unsigned long old_uV;
    unsigned long min_uV;
    unsigned long max_uV;
};
```

**Members**

- `old_uV`: Current voltage before change.
- `min_uV`: Min voltage we'll change to.
- `max_uV`: Max voltage we'll change to.

#### <a id="c-struct-regulator_bulk_data"></a>`struct regulator_bulk_data`

Data used for bulk regulator operations.

**Definition**

```c
struct regulator_bulk_data {
    const char *supply;
    struct regulator *consumer;
    int init_load_uA;
};
```

**Members**

- `supply`: The name of the supply.  Initialised by the user before
  using the bulk regulator APIs.
- `consumer`: The regulator consumer for the supply.  This will be managed
  by the bulk API.
- `init_load_uA`: After getting the regulator, [`regulator_set_load()`](#c-regulator_set_load) will be
  called with this load.  Initialised by the user before
  using the bulk regulator APIs.

**Description**

The regulator APIs provide a series of `regulator_bulk_()` API calls as
a convenience to consumers which require multiple supplies.  This
structure is used to manage data for these calls.



#### <a id="c-struct-regulator_state"></a>`struct regulator_state`

regulator state during low power system states

**Definition**

```c
struct regulator_state {
    int uV;
    int min_uV;
    int max_uV;
    unsigned int mode;
    int enabled;
    bool changeable;
};
```

**Members**

- `uV`: Default operating voltage during suspend, it can be adjusted
  among \<min_uV, max_uV>.
- `min_uV`: Minimum suspend voltage may be set.
- `max_uV`: Maximum suspend voltage may be set.
- `mode`: Operating mode during suspend.
- `enabled`: operations during suspend.
  - DO_NOTHING_IN_SUSPEND
  - DISABLE_IN_SUSPEND
  - ENABLE_IN_SUSPEND
- `changeable`: Is this state can be switched between enabled/disabled,

**Description**

This describes a regulators state during a system wide low power
state.  One of enabled or disabled must be set for the
configuration to be applied.

#### <a id="c-struct-regulation_constraints"></a>`struct regulation_constraints`

regulator operating constraints.

**Definition**

```c
struct regulation_constraints {
    const char *name;
    int min_uV;
    int max_uV;
    int uV_offset;
    int min_uA;
    int max_uA;
    int ilim_uA;
    int pw_budget_mW;
    int system_load;
    u32 *max_spread;
    int max_uV_step;
    unsigned int valid_modes_mask;
    unsigned int valid_ops_mask;
    int input_uV;
    struct regulator_state state_disk;
    struct regulator_state state_mem;
    struct regulator_state state_standby;
    struct notification_limit over_curr_limits;
    struct notification_limit over_voltage_limits;
    struct notification_limit under_voltage_limits;
    struct notification_limit temp_limits;
    suspend_state_t initial_state;
    unsigned int initial_mode;
    unsigned int ramp_delay;
    unsigned int settling_time;
    unsigned int settling_time_up;
    unsigned int settling_time_down;
    unsigned int enable_time;
    unsigned int uv_less_critical_window_ms;
    unsigned int active_discharge;
    unsigned always_on:1;
    unsigned boot_on:1;
    unsigned apply_uV:1;
    unsigned ramp_disable:1;
    unsigned soft_start:1;
    unsigned pull_down:1;
    unsigned system_critical:1;
    unsigned over_current_protection:1;
    unsigned over_current_detection:1;
    unsigned over_voltage_detection:1;
    unsigned under_voltage_detection:1;
    unsigned over_temp_detection:1;
};
```

**Members**

- `name`: Descriptive name for the constraints, used for display purposes.
- `min_uV`: Smallest voltage consumers may set.
- `max_uV`: Largest voltage consumers may set.
- `uV_offset`: Offset applied to voltages from consumer to compensate for
  voltage drops.
- `min_uA`: Smallest current consumers may set.
- `max_uA`: Largest current consumers may set.
- `ilim_uA`: Maximum input current.
- `pw_budget_mW`: Power budget for the regulator in mW.
- `system_load`: Load that isn't captured by any consumer requests.
- `max_spread`: Max possible spread between coupled regulators
- `max_uV_step`: Max possible step change in voltage
- `valid_modes_mask`: Mask of modes which may be configured by consumers.
- `valid_ops_mask`: Operations which may be performed by consumers.
- `input_uV`: Input voltage for regulator when supplied by another regulator.
- `state_disk`: State for regulator when system is suspended in disk mode.
- `state_mem`: State for regulator when system is suspended in mem mode.
- `state_standby`: State for regulator when system is suspended in standby
  mode.
- `over_curr_limits`: Limits for acting on over current.
- `over_voltage_limits`: Limits for acting on over voltage.
- `under_voltage_limits`: Limits for acting on under voltage.
- `temp_limits`: Limits for acting on over temperature.
- `initial_state`: Suspend state to set by default.
- `initial_mode`: Mode to set at startup.
- `ramp_delay`: Time to settle down after voltage change (unit: uV/us)
- `settling_time`: Time to settle down after voltage change when voltage
  change is non-linear (unit: microseconds).
- `settling_time_up`: Time to settle down after voltage increase when voltage
  change is non-linear (unit: microseconds).
- `settling_time_down`: Time to settle down after voltage decrease when
  voltage change is non-linear (unit: microseconds).
- `enable_time`: Turn-on time of the rails (unit: microseconds)
- `uv_less_critical_window_ms`: Specifies the time window (in milliseconds)
  following a critical under-voltage (UV) event
  during which less critical actions can be
  safely carried out by the system (for example
  logging). After this time window more critical
  actions should be done (for example prevent
  HW damage).
- `active_discharge`: Enable/disable active discharge. The enum
  regulator_active_discharge values are used for
  initialisation.
- `always_on`: Set if the regulator should never be disabled.
- `boot_on`: Set if the regulator is enabled when the system is initially
  started.  If the regulator is not enabled by the hardware or
  bootloader then it will be enabled when the constraints are
  applied.
- `apply_uV`: Apply the voltage constraint when initialising.
- `ramp_disable`: Disable ramp delay when initialising or when setting voltage.
- `soft_start`: Enable soft start so that voltage ramps slowly.
- `pull_down`: Enable pull down when regulator is disabled.
- `system_critical`: Set if the regulator is critical to system stability or
  functionality.
- `over_current_protection`: Auto disable on over current event.
- `over_current_detection`: Configure over current limits.
- `over_voltage_detection`: Configure over voltage limits.
- `under_voltage_detection`: Configure under voltage limits.
- `over_temp_detection`: Configure over temperature limits.

**Description**

This struct describes regulator and board/machine specific constraints.

#### <a id="c-struct-regulator_consumer_supply"></a>`struct regulator_consumer_supply`

supply -> device mapping

**Definition**

```c
struct regulator_consumer_supply {
    const char *dev_name;
    const char *supply;
};
```

**Members**

- `dev_name`: Result of [`dev_name()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-dev_name) for the consumer.
- `supply`: Name for the supply.

**Description**

This maps a supply name to a device. Use of dev_name allows support for
buses which make struct device available late such as I2C.

#### <a id="c-struct-regulator_init_data"></a>`struct regulator_init_data`

regulator platform initialisation data.

**Definition**

```c
struct regulator_init_data {
    const char *supply_regulator;
    struct regulation_constraints constraints;
    int num_consumer_supplies;
    struct regulator_consumer_supply *consumer_supplies;
    void *driver_data;
};
```

**Members**

- `supply_regulator`: Parent regulator.  Specified using the regulator name
  as it appears in the name field in sysfs, which can
  be explicitly set using the constraints field 'name'.
- `constraints`: Constraints.  These must be specified for the regulator to
  be usable.
- `num_consumer_supplies`: Number of consumer device supplies.
- `consumer_supplies`: Consumer device supply configuration.
- `driver_data`: Data passed to regulator_init.

**Description**

Initialisation constraints, our supply and consumers supplies.



#### <a id="c-struct-regulator_ops"></a>`struct regulator_ops`

regulator operations.

**Definition**

```c
struct regulator_ops {
    int (*list_voltage) (struct regulator_dev *, unsigned selector);
    int (*set_voltage) (struct regulator_dev *, int min_uV, int max_uV, unsigned *selector);
    int (*map_voltage)(struct regulator_dev *, int min_uV, int max_uV);
    int (*set_voltage_sel) (struct regulator_dev *, unsigned selector);
    int (*get_voltage) (struct regulator_dev *);
    int (*get_voltage_sel) (struct regulator_dev *);
    int (*set_current_limit) (struct regulator_dev *, int min_uA, int max_uA);
    int (*get_current_limit) (struct regulator_dev *);
    int (*set_input_current_limit) (struct regulator_dev *, int lim_uA);
    int (*set_over_current_protection)(struct regulator_dev *, int lim_uA, int severity, bool enable);
    int (*set_over_voltage_protection)(struct regulator_dev *, int lim_uV, int severity, bool enable);
    int (*set_under_voltage_protection)(struct regulator_dev *, int lim_uV, int severity, bool enable);
    int (*set_thermal_protection)(struct regulator_dev *, int lim, int severity, bool enable);
    int (*set_active_discharge)(struct regulator_dev *, bool enable);
    int (*enable) (struct regulator_dev *);
    int (*disable) (struct regulator_dev *);
    int (*is_enabled) (struct regulator_dev *);
    int (*set_mode) (struct regulator_dev *, unsigned int mode);
    unsigned int (*get_mode) (struct regulator_dev *);
    int (*get_error_flags)(struct regulator_dev *, unsigned int *flags);
    int (*enable_time) (struct regulator_dev *);
    int (*set_ramp_delay) (struct regulator_dev *, int ramp_delay);
    int (*set_voltage_time) (struct regulator_dev *, int old_uV, int new_uV);
    int (*set_voltage_time_sel) (struct regulator_dev *, unsigned int old_selector, unsigned int new_selector);
    int (*set_soft_start) (struct regulator_dev *);
    int (*get_status)(struct regulator_dev *);
    unsigned int (*get_optimum_mode) (struct regulator_dev *, int input_uV, int output_uV, int load_uA);
    int (*set_load)(struct regulator_dev *, int load_uA);
    int (*set_bypass)(struct regulator_dev *dev, bool enable);
    int (*get_bypass)(struct regulator_dev *dev, bool *enable);
    int (*set_suspend_voltage) (struct regulator_dev *, int uV);
    int (*set_suspend_enable) (struct regulator_dev *);
    int (*set_suspend_disable) (struct regulator_dev *);
    int (*set_suspend_mode) (struct regulator_dev *, unsigned int mode);
    int (*resume)(struct regulator_dev *rdev);
    int (*set_pull_down) (struct regulator_dev *);
};
```

**Members**

- `list_voltage`: Return one of the supported voltages, in microvolts; zero
  if the selector indicates a voltage that is unusable on this system;
  or negative errno.  Selectors range from zero to one less than
  regulator_desc.n_voltages.  Voltages may be reported in any order.
- `set_voltage`: Set the voltage for the regulator within the range specified.
  The driver should select the voltage closest to min_uV.
- `map_voltage`: Convert a voltage into a selector
- `set_voltage_sel`: Set the voltage for the regulator using the specified
  selector.
- `get_voltage`: Return the currently configured voltage for the regulator;
  return -ENOTRECOVERABLE if regulator can't be read at
  bootup and hasn't been set yet.
- `get_voltage_sel`: Return the currently configured voltage selector for the
  regulator; return -ENOTRECOVERABLE if regulator can't
  be read at bootup and hasn't been set yet.
- `set_current_limit`: Configure a limit for a current-limited regulator.
  The driver should select the current closest to max_uA.
- `get_current_limit`: Get the configured limit for a current-limited regulator.
- `set_input_current_limit`: Configure an input limit.
- `set_over_current_protection`: Support enabling of and setting limits for over
  current situation detection. Detection can be configured for three
  levels of severity.
- `set_over_voltage_protection`: Support enabling of and setting limits for over
  voltage situation detection. Detection can be configured for same
  severities as over current protection. Units of uV.
- `set_under_voltage_protection`: Support enabling of and setting limits for
  under voltage situation detection. Detection can be configured for same
  severities as over current protection. Units of uV.
- `set_thermal_protection`: Support enabling of and setting limits for over
  temperature situation detection.Detection can be configured for same
  severities as over current protection. Units of degree Kelvin.
- `set_active_discharge`: Set active discharge enable/disable of regulators.
- `enable`: Configure the regulator as enabled.
- `disable`: Configure the regulator as disabled.
- `is_enabled`: Return 1 if the regulator is enabled, 0 if not.
  May also return negative errno.
- `set_mode`: Set the configured operating mode for the regulator.
- `get_mode`: Get the configured operating mode for the regulator.
- `get_error_flags`: Get the current error(s) for the regulator.
- `enable_time`: Time taken for the regulator voltage output voltage to
  stabilise after being enabled, in microseconds.
- `set_ramp_delay`: Set the ramp delay for the regulator. The driver should
  select ramp delay equal to or less than(closest) ramp_delay.
- `set_voltage_time`: Time taken for the regulator voltage output voltage
  to stabilise after being set to a new value, in microseconds.
  The function receives the from and to voltage as input, it
  should return the worst case.
- `set_voltage_time_sel`: Time taken for the regulator voltage output voltage
  to stabilise after being set to a new value, in microseconds.
  The function receives the from and to voltage selector as
  input, it should return the worst case.
- `set_soft_start`: Enable soft start for the regulator.
- `get_status`: Return actual (not as-configured) status of regulator, as a
  REGULATOR_STATUS value (or negative errno)
- `get_optimum_mode`: Get the most efficient operating mode for the regulator
  when running with the specified parameters.
- `set_load`: Set the load for the regulator.
- `set_bypass`: Set the regulator in bypass mode.
- `get_bypass`: Get the regulator bypass mode state.
- `set_suspend_voltage`: Set the voltage for the regulator when the system
  is suspended.
- `set_suspend_enable`: Mark the regulator as enabled when the system is
  suspended.
- `set_suspend_disable`: Mark the regulator as disabled when the system is
  suspended.
- `set_suspend_mode`: Set the operating mode for the regulator when the
  system is suspended.
- `resume`: Resume operation of suspended regulator.
- `set_pull_down`: Configure the regulator to pull down when the regulator
  is disabled.

**Description**

- REGULATOR_SEVERITY_PROT should automatically shut down the regulator(s).

- REGULATOR_SEVERITY_ERR should indicate that over-current situation is
  caused by an unrecoverable error but HW does not perform
  automatic shut down.

- REGULATOR_SEVERITY_WARN should indicate situation where hardware is
  still believed to not be damaged but that a board sepcific
  recovery action is needed. If lim_uA is 0 the limit should not
  be changed but the detection should just be enabled/disabled as
  is requested.

This struct describes regulator operations which can be implemented by
regulator chip drivers.

#### <a id="c-struct-regulator_desc"></a>`struct regulator_desc`

Static regulator descriptor

**Definition**

```c
struct regulator_desc {
    const char *name;
    const char *supply_name;
    const char *of_match;
    bool of_match_full_name;
    const char *regulators_node;
    int (*of_parse_cb)(struct device_node *, const struct regulator_desc *, struct regulator_config *);
    int (*init_cb)(struct regulator_dev *, struct regulator_config *);
    int id;
    unsigned int continuous_voltage_range:1;
    unsigned n_voltages;
    unsigned int n_current_limits;
    const struct regulator_ops *ops;
    int irq;
    enum regulator_type type;
    struct module *owner;
    unsigned int min_uV;
    unsigned int uV_step;
    unsigned int linear_min_sel;
    int fixed_uV;
    unsigned int ramp_delay;
    int min_dropout_uV;
    const struct linear_range *linear_ranges;
    const unsigned int *linear_range_selectors_bitfield;
    int n_linear_ranges;
    const unsigned int *volt_table;
    const unsigned int *curr_table;
    unsigned int vsel_range_reg;
    unsigned int vsel_range_mask;
    bool range_applied_by_vsel;
    unsigned int vsel_reg;
    unsigned int vsel_mask;
    unsigned int vsel_step;
    unsigned int csel_reg;
    unsigned int csel_mask;
    unsigned int apply_reg;
    unsigned int apply_bit;
    unsigned int enable_reg;
    unsigned int enable_mask;
    unsigned int enable_val;
    unsigned int disable_val;
    bool enable_is_inverted;
    unsigned int bypass_reg;
    unsigned int bypass_mask;
    unsigned int bypass_val_on;
    unsigned int bypass_val_off;
    unsigned int active_discharge_on;
    unsigned int active_discharge_off;
    unsigned int active_discharge_mask;
    unsigned int active_discharge_reg;
    unsigned int soft_start_reg;
    unsigned int soft_start_mask;
    unsigned int soft_start_val_on;
    unsigned int pull_down_reg;
    unsigned int pull_down_mask;
    unsigned int pull_down_val_on;
    unsigned int ramp_reg;
    unsigned int ramp_mask;
    const unsigned int *ramp_delay_table;
    unsigned int n_ramp_values;
    unsigned int enable_time;
    unsigned int off_on_delay;
    unsigned int poll_enabled_time;
    unsigned int (*of_map_mode)(unsigned int mode);
};
```

**Members**

- `name`: Identifying name for the regulator.
- `supply_name`: Identifying the regulator supply
- `of_match`: Name used to identify regulator in DT.
- `of_match_full_name`: A flag to indicate that the of_match string, if
  present, should be matched against the node full_name.
- `regulators_node`: Name of node containing regulator definitions in DT.
- `of_parse_cb`: Optional callback called only if of_match is present.
  Will be called for each regulator parsed from DT, during
  init_data parsing.
  The regulator_config passed as argument to the callback will
  be a copy of config passed to regulator_register, valid only
  for this particular call. Callback may freely change the
  config but it cannot store it for later usage.
  Callback should return 0 on success or negative ERRNO
  indicating failure.
- `init_cb`: Optional callback called after the parsing of init_data.
  Allows the regulator to perform runtime init if necessary,
  such as synching the regulator and the parsed constraints.
  Callback should return 0 on success or negative ERRNO
  indicating failure.
- `id`: Numerical identifier for the regulator.
- `continuous_voltage_range`: Indicates if the regulator can set any
  voltage within constrains range.
- `n_voltages`: Number of selectors available for ops.`list_voltage()`.
- `n_current_limits`: Number of selectors available for current limits
- `ops`: Regulator operations table.
- `irq`: Interrupt number for the regulator.
- `type`: Indicates if the regulator is a voltage or current regulator.
- `owner`: Module providing the regulator, used for refcounting.
- `min_uV`: Voltage given by the lowest selector (if linear mapping)
- `uV_step`: Voltage increase with each selector (if linear mapping)
- `linear_min_sel`: Minimal selector for starting linear mapping
- `fixed_uV`: Fixed voltage of rails.
- `ramp_delay`: Time to settle down after voltage change (unit: uV/us)
- `min_dropout_uV`: The minimum dropout voltage this regulator can handle
- `linear_ranges`: A constant table of possible voltage ranges.
- `linear_range_selectors_bitfield`: A constant table of voltage range
  selectors as bitfield values. If
  pickable ranges are used each range
  must have corresponding selector here.
- `n_linear_ranges`: Number of entries in the **linear_ranges** (and in
  linear_range_selectors_bitfield if used) table(s).
- `volt_table`: Voltage mapping table (if table based mapping)
- `curr_table`: Current limit mapping table (if table based mapping)
- `vsel_range_reg`: Register for range selector when using pickable ranges
  and `regulator_map_*_voltage_*_pickable` functions.
- `vsel_range_mask`: Mask for register bitfield used for range selector
- `range_applied_by_vsel`: A flag to indicate that changes to vsel_range_reg
  are only effective after vsel_reg is written
- `vsel_reg`: Register for selector when using `regulator_map_*_voltage_*`
- `vsel_mask`: Mask for register bitfield used for selector
- `vsel_step`: Specify the resolution of selector stepping when setting
  voltage. If 0, then no stepping is done (requested selector is
  set directly), if >0 then the regulator API will ramp the
  voltage up/down gradually each time increasing/decreasing the
  selector by the specified step value.
- `csel_reg`: Register for current limit selector using regmap set_current_limit
- `csel_mask`: Mask for register bitfield used for current limit selector
- `apply_reg`: Register for initiate voltage change on the output when
  using regulator_set_voltage_sel_regmap
- `apply_bit`: Register bitfield used for initiate voltage change on the
  output when using regulator_set_voltage_sel_regmap
- `enable_reg`: Register for control when using regmap enable/disable ops
- `enable_mask`: Mask for control when using regmap enable/disable ops
- `enable_val`: Enabling value for control when using regmap enable/disable ops
- `disable_val`: Disabling value for control when using regmap enable/disable ops
- `enable_is_inverted`: A flag to indicate set enable_mask bits to disable
  when using regulator_enable_regmap and friends APIs.
- `bypass_reg`: Register for control when using regmap set_bypass
- `bypass_mask`: Mask for control when using regmap set_bypass
- `bypass_val_on`: Enabling value for control when using regmap set_bypass
- `bypass_val_off`: Disabling value for control when using regmap set_bypass
- `active_discharge_on`: Disabling value for control when using regmap
  set_active_discharge
- `active_discharge_off`: Enabling value for control when using regmap
  set_active_discharge
- `active_discharge_mask`: Mask for control when using regmap
  set_active_discharge
- `active_discharge_reg`: Register for control when using regmap
  set_active_discharge
- `soft_start_reg`: Register for control when using regmap set_soft_start
- `soft_start_mask`: Mask for control when using regmap set_soft_start
- `soft_start_val_on`: Enabling value for control when using regmap
  set_soft_start
- `pull_down_reg`: Register for control when using regmap set_pull_down
- `pull_down_mask`: Mask for control when using regmap set_pull_down
- `pull_down_val_on`: Enabling value for control when using regmap
  set_pull_down
- `ramp_reg`: Register for controlling the regulator ramp-rate.
- `ramp_mask`: Bitmask for the ramp-rate control register.
- `ramp_delay_table`: Table for mapping the regulator ramp-rate values. Values
  should be given in units of V/S (uV/uS). See the
  `regulator_set_ramp_delay_regmap()`.
- `n_ramp_values`: number of elements at **ramp_delay_table**.
- `enable_time`: Time taken for initial enable of regulator (in uS).
- `off_on_delay`: guard time (in uS), before re-enabling a regulator
- `poll_enabled_time`: The polling interval (in uS) to use while checking that
  the regulator was actually enabled. Max upto enable_time.
- `of_map_mode`: Maps a hardware mode defined in a DeviceTree to a standard mode

**Description**

Each regulator registered with the core is described with a
structure of this type and a struct regulator_config.  This
structure contains the non-varying parts of the regulator
description.

#### <a id="c-struct-regulator_config"></a>`struct regulator_config`

Dynamic regulator descriptor

**Definition**

```c
struct regulator_config {
    struct device *dev;
    const struct regulator_init_data *init_data;
    void *driver_data;
    struct device_node *of_node;
    struct regmap *regmap;
    struct gpio_desc *ena_gpiod;
};
```

**Members**

- `dev`: struct device for the regulator
- `init_data`: platform provided init data, passed through by driver
- `driver_data`: private regulator data
- `of_node`: OpenFirmware node to parse for device tree bindings (may be
  NULL).
- `regmap`: regmap to use for core regmap helpers if `dev_get_regmap()` is
  insufficient.
- `ena_gpiod`: GPIO controlling regulator enable.

**Description**

Each regulator registered with the core is described with a
structure of this type and a struct regulator_desc.  This structure
contains the runtime variable parts of the regulator description.

#### <a id="c-struct-regulator_err_state"></a>`struct regulator_err_state`

regulator error/notification status

**Definition**

```c
struct regulator_err_state {
    struct regulator_dev *rdev;
    unsigned long notifs;
    unsigned long errors;
    int possible_errs;
};
```

**Members**

- `rdev`: Regulator which status the struct indicates.
- `notifs`: Events which have occurred on the regulator.
- `errors`: Errors which are active on the regulator.
- `possible_errs`: Errors which can be signaled (by given IRQ).

#### <a id="c-struct-regulator_irq_data"></a>`struct regulator_irq_data`

regulator error/notification status data

**Definition**

```c
struct regulator_irq_data {
    struct regulator_err_state *states;
    int num_states;
    void *data;
    long opaque;
};
```

**Members**

- `states`: Status structs for each of the associated regulators.
- `num_states`: Amount of associated regulators.
- `data`: Driver data pointer given at regulator_irq_desc.
- `opaque`: Value storage for IC driver. Core does not update this. ICs
  may want to store status register value here at map_event and
  compare contents at 'renable' callback to see if new problems
  have been added to status. If that is the case it may be
  desirable to return REGULATOR_ERROR_CLEARED and not
  REGULATOR_ERROR_ON to allow IRQ fire again and to generate
  notifications also for the new issues.

**Description**

This structure is passed to 'map_event' and 'renable' callbacks for
reporting regulator status to core.

#### <a id="c-struct-regulator_irq_desc"></a>`struct regulator_irq_desc`

notification sender for IRQ based events.

**Definition**

```c
struct regulator_irq_desc {
    const char *name;
    int fatal_cnt;
    int reread_ms;
    int irq_off_ms;
    bool skip_off;
    bool high_prio;
    void *data;
    int (*die)(struct regulator_irq_data *rid);
    int (*map_event)(int irq, struct regulator_irq_data *rid, unsigned long *dev_mask);
    int (*renable)(struct regulator_irq_data *rid);
};
```

**Members**

- `name`: The visible name for the IRQ
- `fatal_cnt`: If this IRQ is used to signal HW damaging condition it may be
  best to shut-down regulator(s) or reboot the SOC if error
  handling is repeatedly failing. If fatal_cnt is given the IRQ
  handling is aborted if it fails for fatal_cnt times and `die()`
  callback (if populated) is called. If `die()` is not populated
  poweroff for the system is attempted in order to prevent any
  further damage.
- `reread_ms`: The time which is waited before attempting to re-read status
  at the worker if IC reading fails. Immediate re-read is done
  if time is not specified.
- `irq_off_ms`: The time which IRQ is kept disabled before re-evaluating the
  status for devices which keep IRQ disabled for duration of the
  error. If this is not given the IRQ is left enabled and renable
  is not called.
- `skip_off`: If set to true the IRQ handler will attempt to check if any of
  the associated regulators are enabled prior to taking other
  actions. If no regulators are enabled and this is set to true
  a spurious IRQ is assumed and IRQ_NONE is returned.
- `high_prio`: Boolean to indicate that high priority WQ should be used.
- `data`: Driver private data pointer which will be passed as such to
  the renable, map_event and die callbacks in regulator_irq_data.
- `die`: Protection callback. If IC status reading or recovery actions
  fail fatal_cnt times this callback is called or system is
  powered off. This callback should implement a final protection
  attempt like disabling the regulator. If protection succeeded
  `die()` may return 0. If anything else is returned the core
  assumes final protection failed and attempts to perform a
  poweroff as a last resort.
- `map_event`: Driver callback to map IRQ status into regulator devices with
  events / errors. NOTE: callback MUST initialize both the
  errors and notifs for all rdevs which it signals having
  active events as core does not clean the map data.
  REGULATOR_FAILED_RETRY can be returned to indicate that the
  status reading from IC failed. If this is repeated for
  fatal_cnt times the core will call `die()` callback or power-off
  the system as a last resort to protect the HW.
- `renable`: Optional callback to check status (if HW supports that) before
  re-enabling IRQ. If implemented this should clear the error
  flags so that errors fetched by [`regulator_get_error_flags()`](#c-regulator_get_error_flags)
  are updated. If callback is not implemented then errors are
  assumed to be cleared and IRQ is re-enabled.
  REGULATOR_FAILED_RETRY can be returned to
  indicate that the status reading from IC failed. If this is
  repeated for 'fatal_cnt' times the core will call `die()`
  callback or if `die()` is not populated then attempt to power-off
  the system as a last resort to protect the HW.
  Returning zero indicates that the problem in HW has been solved
  and IRQ will be re-enabled. Returning REGULATOR_ERROR_ON
  indicates the error condition is still active and keeps IRQ
  disabled. Please note that returning REGULATOR_ERROR_ON does
  not retrigger evaluating what events are active or resending
  notifications. If this is needed you probably want to return
  zero and allow IRQ to retrigger causing events to be
  re-evaluated and re-sent.

**Description**

This structure is used for registering regulator IRQ notification helper.



#### <a id="c-regulator_get"></a>`regulator_get()`

```c
struct regulator * regulator_get(struct device *dev, const char *id)
```

lookup and obtain a reference to a regulator.

**Parameters**

- `struct device *dev`: device for regulator "consumer"
- `const char *id`: Supply name or regulator ID.

**Description**

Use of supply names configured via `set_consumer_device_supply()` is
strongly encouraged.  It is recommended that the supply name used
should match the name used for the supply and/or the relevant
device pins in the datasheet.

**Return**

Pointer to a `struct regulator` corresponding to the regulator
producer, or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded negative error number.

#### <a id="c-regulator_get_exclusive"></a>`regulator_get_exclusive()`

```c
struct regulator * regulator_get_exclusive(struct device *dev, const char *id)
```

obtain exclusive access to a regulator.

**Parameters**

- `struct device *dev`: device for regulator "consumer"
- `const char *id`: Supply name or regulator ID.

**Description**

Other consumers will be unable to obtain this regulator while this
reference is held and the use count for the regulator will be
initialised to reflect the current state of the regulator.

This is intended for use by consumers which cannot tolerate shared
use of the regulator such as those which need to force the
regulator off for correct operation of the hardware they are
controlling.

Use of supply names configured via `set_consumer_device_supply()` is
strongly encouraged.  It is recommended that the supply name used
should match the name used for the supply and/or the relevant
device pins in the datasheet.

**Return**

Pointer to a `struct regulator` corresponding to the regulator
producer, or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded negative error number.

#### <a id="c-regulator_get_optional"></a>`regulator_get_optional()`

```c
struct regulator * regulator_get_optional(struct device *dev, const char *id)
```

obtain optional access to a regulator.

**Parameters**

- `struct device *dev`: device for regulator "consumer"
- `const char *id`: Supply name or regulator ID.

**Description**

This is intended for use by consumers for devices which can have
some supplies unconnected in normal use, such as some MMC devices.
It can allow the regulator core to provide stub supplies for other
supplies requested using normal [`regulator_get()`](#c-regulator_get) calls without
disrupting the operation of drivers that can handle absent
supplies.

Use of supply names configured via `set_consumer_device_supply()` is
strongly encouraged.  It is recommended that the supply name used
should match the name used for the supply and/or the relevant
device pins in the datasheet.

**Return**

Pointer to a `struct regulator` corresponding to the regulator
producer, or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded negative error number.

#### <a id="c-regulator_put"></a>`regulator_put()`

```c
void regulator_put(struct regulator *regulator)
```

"free" the regulator source

**Parameters**

- `struct regulator *regulator`: regulator source

**Note**

drivers must ensure that all regulator_enable calls made on this
regulator source are balanced by regulator_disable calls prior to calling
this function.

#### <a id="c-regulator_register_supply_alias"></a>`regulator_register_supply_alias()`

```c
int regulator_register_supply_alias(struct device *dev, const char *id, struct device *alias_dev, const char *alias_id)
```

Provide device alias for supply lookup

**Parameters**

- `struct device *dev`: device that will be given as the regulator "consumer"
- `const char *id`: Supply name or regulator ID
- `struct device *alias_dev`: device that should be used to lookup the supply
- `const char *alias_id`: Supply name or regulator ID that should be used to lookup the
  supply

**Description**

All lookups for id on dev will instead be conducted for alias_id on
alias_dev.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_unregister_supply_alias"></a>`regulator_unregister_supply_alias()`

```c
void regulator_unregister_supply_alias(struct device *dev, const char *id)
```

Remove device alias

**Parameters**

- `struct device *dev`: device that will be given as the regulator "consumer"
- `const char *id`: Supply name or regulator ID

**Description**

Remove a lookup alias if one exists for id on dev.

#### <a id="c-regulator_bulk_register_supply_alias"></a>`regulator_bulk_register_supply_alias()`

```c
int regulator_bulk_register_supply_alias(struct device *dev, const char *const *id, struct device *alias_dev, const char *const *alias_id, int num_id)
```

register multiple aliases

**Parameters**

- `struct device *dev`: device that will be given as the regulator "consumer"
- `const char *const *id`: List of supply names or regulator IDs
- `struct device *alias_dev`: device that should be used to lookup the supply
- `const char *const *alias_id`: List of supply names or regulator IDs that should be used to
  lookup the supply
- `int num_id`: Number of aliases to register

**Description**

This helper function allows drivers to register several supply
aliases in one operation.  If any of the aliases cannot be
registered any aliases that were registered will be removed
before returning to the caller.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_unregister_supply_alias"></a>`regulator_bulk_unregister_supply_alias()`

```c
void regulator_bulk_unregister_supply_alias(struct device *dev, const char *const *id, int num_id)
```

unregister multiple aliases

**Parameters**

- `struct device *dev`: device that will be given as the regulator "consumer"
- `const char *const *id`: List of supply names or regulator IDs
- `int num_id`: Number of aliases to unregister

**Description**

This helper function allows drivers to unregister several supply
aliases in one operation.

#### <a id="c-regulator_enable"></a>`regulator_enable()`

```c
int regulator_enable(struct regulator *regulator)
```

enable regulator output

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Request that the regulator be enabled with the regulator output at
the predefined voltage or current value.  Calls to [`regulator_enable()`](#c-regulator_enable)
must be balanced with calls to [`regulator_disable()`](#c-regulator_disable).

**NOTE**

the output value can be set by other drivers, boot loader or may be
hardwired in the regulator.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_disable"></a>`regulator_disable()`

```c
int regulator_disable(struct regulator *regulator)
```

disable regulator output

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Disable the regulator output voltage or current.  Calls to
[`regulator_enable()`](#c-regulator_enable) must be balanced with calls to
[`regulator_disable()`](#c-regulator_disable).

**NOTE**

this will only disable the regulator output if no other consumer
devices have it enabled, the regulator device supports disabling and
machine constraints permit this operation.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_force_disable"></a>`regulator_force_disable()`

```c
int regulator_force_disable(struct regulator *regulator)
```

force disable regulator output

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Forcibly disable the regulator output voltage or current.

**NOTE**

this *will* disable the regulator output even if other consumer
devices have it enabled. This should be used for situations when device
damage will likely occur if the regulator is not disabled (e.g. over temp).

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_disable_deferred"></a>`regulator_disable_deferred()`

```c
int regulator_disable_deferred(struct regulator *regulator, int ms)
```

disable regulator output with delay

**Parameters**

- `struct regulator *regulator`: regulator source
- `int ms`: milliseconds until the regulator is disabled

**Description**

Execute [`regulator_disable()`](#c-regulator_disable) on the regulator after a delay.  This
is intended for use with devices that require some time to quiesce.

**NOTE**

this will only disable the regulator output if no other consumer
devices have it enabled, the regulator device supports disabling and
machine constraints permit this operation.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_is_enabled"></a>`regulator_is_enabled()`

```c
int regulator_is_enabled(struct regulator *regulator)
```

is the regulator output enabled

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Note that the device backing this regulator handle can have multiple
users, so it might be enabled even if [`regulator_enable()`](#c-regulator_enable) was never
called for this particular source.

**Return**

Positive if the regulator driver backing the source/client
has requested that the device be enabled, zero if it hasn't,
else a negative error number.

#### <a id="c-regulator_count_voltages"></a>`regulator_count_voltages()`

```c
int regulator_count_voltages(struct regulator *regulator)
```

count [`regulator_list_voltage()`](#c-regulator_list_voltage) selectors

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Number of selectors for **regulator**, or negative error number.

**Description**

Selectors are numbered starting at zero, and typically correspond to
bitfields in hardware registers.

#### <a id="c-regulator_list_voltage"></a>`regulator_list_voltage()`

```c
int regulator_list_voltage(struct regulator *regulator, unsigned selector)
```

enumerate supported voltages

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned selector`: identify voltage to list

**Context**

can sleep

**Return**

Voltage for **selector** that can be passed to [`regulator_set_voltage()`](#c-regulator_set_voltage),
0 if **selector** can't be used on this system, or a negative error
number on failure.

#### <a id="c-regulator_get_regmap"></a>`regulator_get_regmap()`

```c
struct regmap * regulator_get_regmap(struct regulator *regulator)
```

get the regulator's register map

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Pointer to the `struct regmap` for **regulator**, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)
encoded -`EOPNOTSUPP` if **regulator** doesn't use regmap.

#### <a id="c-regulator_get_hardware_vsel_register"></a>`regulator_get_hardware_vsel_register()`

```c
int regulator_get_hardware_vsel_register(struct regulator *regulator, unsigned *vsel_reg, unsigned *vsel_mask)
```

get the HW voltage selector register

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned *vsel_reg`: voltage selector register, output parameter
- `unsigned *vsel_mask`: mask for voltage selector bitfield, output parameter

**Description**

Returns the hardware register offset and bitmask used for setting the
regulator voltage. This might be useful when configuring voltage-scaling
hardware or firmware that can make I2C requests behind the kernel's back,
for example.

On success, the output parameters **vsel_reg** and **vsel_mask** are filled in
and 0 is returned, otherwise a negative error number is returned.

**Return**

0 on success, or -`EOPNOTSUPP` if the regulator does not support
voltage selectors.

#### <a id="c-regulator_list_hardware_vsel"></a>`regulator_list_hardware_vsel()`

```c
int regulator_list_hardware_vsel(struct regulator *regulator, unsigned selector)
```

get the HW-specific register value for a selector

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned selector`: identify voltage to list

**Description**

Converts the selector to a hardware-specific voltage selector that can be
directly written to the regulator registers. The address of the voltage
register can be determined by calling **regulator_get_hardware_vsel_register**.

**Return**

0 on success, -`EINVAL` if the selector is outside the supported
range, or -`EOPNOTSUPP` if the regulator does not support voltage
selectors.

#### <a id="c-regulator_hardware_enable"></a>`regulator_hardware_enable()`

```c
int regulator_hardware_enable(struct regulator *regulator, bool enable)
```

access the HW for enable/disable regulator

**Parameters**

- `struct regulator *regulator`: regulator source
- `bool enable`: true for enable, false for disable

**Description**

Request that the regulator be enabled/disabled with the regulator output at
the predefined voltage or current value.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_get_linear_step"></a>`regulator_get_linear_step()`

```c
unsigned int regulator_get_linear_step(struct regulator *regulator)
```

return the voltage step size between VSEL values

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

The voltage step size between VSEL values for linear regulators,
or 0 if the regulator isn't a linear regulator.

#### <a id="c-regulator_is_supported_voltage"></a>`regulator_is_supported_voltage()`

```c
int regulator_is_supported_voltage(struct regulator *regulator, int min_uV, int max_uV)
```

check if a voltage range can be supported

**Parameters**

- `struct regulator *regulator`: Regulator to check.
- `int min_uV`: Minimum required voltage in uV.
- `int max_uV`: Maximum required voltage in uV.

**Return**

1 if the voltage range is supported, 0 if not, or a negative error
number if **regulator**'s voltage can't be changed and voltage readback
failed.

#### <a id="c-regulator_set_voltage"></a>`regulator_set_voltage()`

```c
int regulator_set_voltage(struct regulator *regulator, int min_uV, int max_uV)
```

set regulator output voltage

**Parameters**

- `struct regulator *regulator`: regulator source
- `int min_uV`: Minimum required voltage in uV
- `int max_uV`: Maximum acceptable voltage in uV

**Description**

Sets a voltage regulator to the desired output voltage. This can be set
during any regulator state. IOW, regulator can be disabled or enabled.

If the regulator is enabled then the voltage will change to the new value
immediately otherwise if the regulator is disabled the regulator will
output at the new voltage when enabled.

**NOTE**

If the regulator is shared between several devices then the lowest
request voltage that meets the system constraints will be used.
Regulator system constraints must be set for this regulator before
calling this function otherwise this call will fail.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_set_voltage_time"></a>`regulator_set_voltage_time()`

```c
int regulator_set_voltage_time(struct regulator *regulator, int old_uV, int new_uV)
```

get raise/fall time

**Parameters**

- `struct regulator *regulator`: regulator source
- `int old_uV`: starting voltage in microvolts
- `int new_uV`: target voltage in microvolts

**Description**

Provided with the starting and ending voltage, this function attempts to
calculate the time in microseconds required to rise or fall to this new
voltage.

**Return**

ramp time in microseconds, or a negative error number if calculation failed.

#### <a id="c-regulator_set_voltage_time_sel"></a>`regulator_set_voltage_time_sel()`

```c
int regulator_set_voltage_time_sel(struct regulator_dev *rdev, unsigned int old_selector, unsigned int new_selector)
```

get raise/fall time

**Parameters**

- `struct regulator_dev *rdev`: regulator source device
- `unsigned int old_selector`: selector for starting voltage
- `unsigned int new_selector`: selector for target voltage

**Description**

Provided with the starting and target voltage selectors, this function
returns time in microseconds required to rise or fall to this new voltage

Drivers providing ramp_delay in regulation_constraints can use this as their
`set_voltage_time_sel()` operation.

**Return**

ramp time in microseconds, or a negative error number if calculation failed.

#### <a id="c-regulator_sync_voltage"></a>`regulator_sync_voltage()`

```c
int regulator_sync_voltage(struct regulator *regulator)
```

re-apply last regulator output voltage

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Re-apply the last configured voltage.  This is intended to be used
where some external control source the consumer is cooperating with
has caused the configured voltage to change.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_get_voltage"></a>`regulator_get_voltage()`

```c
int regulator_get_voltage(struct regulator *regulator)
```

get regulator output voltage

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Current regulator voltage in uV, or a negative error number on failure.

**NOTE**

If the regulator is disabled it will return the voltage value. This
function should not be used to determine regulator state.

#### <a id="c-regulator_set_current_limit"></a>`regulator_set_current_limit()`

```c
int regulator_set_current_limit(struct regulator *regulator, int min_uA, int max_uA)
```

set regulator output current limit

**Parameters**

- `struct regulator *regulator`: regulator source
- `int min_uA`: Minimum supported current in uA
- `int max_uA`: Maximum supported current in uA

**Description**

Sets current sink to the desired output current. This can be set during
any regulator state. IOW, regulator can be disabled or enabled.

If the regulator is enabled then the current will change to the new value
immediately otherwise if the regulator is disabled the regulator will
output at the new current when enabled.

**NOTE**

Regulator system constraints must be set for this regulator before
calling this function otherwise this call will fail.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_get_current_limit"></a>`regulator_get_current_limit()`

```c
int regulator_get_current_limit(struct regulator *regulator)
```

get regulator output current

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Current supplied by the specified current sink in uA,
or a negative error number on failure.

**NOTE**

If the regulator is disabled it will return the current value. This
function should not be used to determine regulator state.

#### <a id="c-regulator_get_unclaimed_power_budget"></a>`regulator_get_unclaimed_power_budget()`

```c
int regulator_get_unclaimed_power_budget(struct regulator *regulator)
```

get regulator unclaimed power budget

**Parameters**

- `struct regulator *regulator`: regulator source

**Return**

Unclaimed power budget of the regulator in mW.

#### <a id="c-regulator_request_power_budget"></a>`regulator_request_power_budget()`

```c
int regulator_request_power_budget(struct regulator *regulator, unsigned int pw_req)
```

request power budget on a regulator

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned int pw_req`: Power requested

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_free_power_budget"></a>`regulator_free_power_budget()`

```c
void regulator_free_power_budget(struct regulator *regulator, unsigned int pw)
```

free power budget on a regulator

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned int pw`: Power to be released.

**Return**

Power budget of the regulator in mW.

#### <a id="c-regulator_set_mode"></a>`regulator_set_mode()`

```c
int regulator_set_mode(struct regulator *regulator, unsigned int mode)
```

set regulator operating mode

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned int mode`: operating mode - one of the REGULATOR_MODE constants

**Description**

Set regulator operating mode to increase regulator efficiency or improve
regulation performance.

**NOTE**

Regulator system constraints must be set for this regulator before
calling this function otherwise this call will fail.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_get_mode"></a>`regulator_get_mode()`

```c
unsigned int regulator_get_mode(struct regulator *regulator)
```

get regulator operating mode

**Parameters**

- `struct regulator *regulator`: regulator source

**Description**

Get the current regulator operating mode.

**Return**

Current operating mode as `REGULATOR_MODE_*` values,
or a negative error number on failure.

#### <a id="c-regulator_get_error_flags"></a>`regulator_get_error_flags()`

```c
int regulator_get_error_flags(struct regulator *regulator, unsigned int *flags)
```

get regulator error information

**Parameters**

- `struct regulator *regulator`: regulator source
- `unsigned int *flags`: pointer to store error flags

**Description**

Get the current regulator error information.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_set_load"></a>`regulator_set_load()`

```c
int regulator_set_load(struct regulator *regulator, int uA_load)
```

set regulator load

**Parameters**

- `struct regulator *regulator`: regulator source
- `int uA_load`: load current

**Description**

Notifies the regulator core of a new device load. This is then used by
DRMS (if enabled by constraints) to set the most efficient regulator
operating mode for the new regulator loading.

Consumer devices notify their supply regulator of the maximum power
they will require (can be taken from device datasheet in the power
consumption tables) when they change operational status and hence power
state. Examples of operational state changes that can affect power
consumption are :-

o Device is opened / closed.
o Device I/O is about to begin or has just finished.
o Device is idling in between work.

This information is also exported via sysfs to userspace.

DRMS will sum the total requested load on the regulator and change
to the most efficient operating mode if platform constraints allow.

**NOTE**

when a regulator consumer requests to have a regulator
disabled then any load that consumer requested no longer counts
toward the total requested load.  If the regulator is re-enabled
then the previously requested load will start counting again.

If a regulator is an always-on regulator then an individual consumer's
load will still be removed if that consumer is fully disabled.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_allow_bypass"></a>`regulator_allow_bypass()`

```c
int regulator_allow_bypass(struct regulator *regulator, bool enable)
```

allow the regulator to go into bypass mode

**Parameters**

- `struct regulator *regulator`: Regulator to configure
- `bool enable`: enable or disable bypass mode

**Description**

Allow the regulator to go into bypass mode if all other consumers
for the regulator also enable bypass mode and the machine
constraints allow this.  Bypass mode means that the regulator is
simply passing the input directly to the output with no regulation.

**Return**

0 on success or if changing bypass is not possible, or
a negative error number on failure.

#### <a id="c-regulator_register_notifier"></a>`regulator_register_notifier()`

```c
int regulator_register_notifier(struct regulator *regulator, struct notifier_block *nb)
```

register regulator event notifier

**Parameters**

- `struct regulator *regulator`: regulator source
- `struct notifier_block *nb`: notifier block

**Description**

Register notifier block to receive regulator events.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_unregister_notifier"></a>`regulator_unregister_notifier()`

```c
int regulator_unregister_notifier(struct regulator *regulator, struct notifier_block *nb)
```

unregister regulator event notifier

**Parameters**

- `struct regulator *regulator`: regulator source
- `struct notifier_block *nb`: notifier block

**Description**

Unregister regulator event notifier block.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_get"></a>`regulator_bulk_get()`

```c
int regulator_bulk_get(struct device *dev, int num_consumers, struct regulator_bulk_data *consumers)
```

get multiple regulator consumers

**Parameters**

- `struct device *dev`: Device to supply
- `int num_consumers`: Number of consumers to register
- `struct regulator_bulk_data *consumers`: Configuration of consumers; clients are stored here.

**Description**

This helper function allows drivers to get several regulator
consumers in one operation.  If any of the regulators cannot be
acquired then any regulators that were allocated will be freed
before returning to the caller.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_enable"></a>`regulator_bulk_enable()`

```c
int regulator_bulk_enable(int num_consumers, struct regulator_bulk_data *consumers)
```

enable multiple regulator consumers

**Parameters**

- `int num_consumers`: Number of consumers
- `struct regulator_bulk_data *consumers`: Consumer data; clients are stored here.

**Description**

This convenience API allows consumers to enable multiple regulator
clients in a single API call.  If any consumers cannot be enabled
then any others that were enabled will be disabled again prior to
return.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_disable"></a>`regulator_bulk_disable()`

```c
int regulator_bulk_disable(int num_consumers, struct regulator_bulk_data *consumers)
```

disable multiple regulator consumers

**Parameters**

- `int num_consumers`: Number of consumers
- `struct regulator_bulk_data *consumers`: Consumer data; clients are stored here.

**Description**

This convenience API allows consumers to disable multiple regulator
clients in a single API call.  If any consumers cannot be disabled
then any others that were disabled will be enabled again prior to
return.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_force_disable"></a>`regulator_bulk_force_disable()`

```c
int regulator_bulk_force_disable(int num_consumers, struct regulator_bulk_data *consumers)
```

force disable multiple regulator consumers

**Parameters**

- `int num_consumers`: Number of consumers
- `struct regulator_bulk_data *consumers`: Consumer data; clients are stored here.

**Description**

This convenience API allows consumers to forcibly disable multiple regulator
clients in a single API call.

**NOTE**

This should be used for situations when device damage will
likely occur if the regulators are not disabled (e.g. over temp).
Although regulator_force_disable function call for some consumers can
return error numbers, the function is called for all consumers.

**Return**

0 on success or a negative error number on failure.

#### <a id="c-regulator_bulk_free"></a>`regulator_bulk_free()`

```c
void regulator_bulk_free(int num_consumers, struct regulator_bulk_data *consumers)
```

free multiple regulator consumers

**Parameters**

- `int num_consumers`: Number of consumers
- `struct regulator_bulk_data *consumers`: Consumer data; clients are stored here.

**Description**

This convenience API allows consumers to free multiple regulator
clients in a single API call.

#### <a id="c-regulator_notifier_call_chain"></a>`regulator_notifier_call_chain()`

```c
int regulator_notifier_call_chain(struct regulator_dev *rdev, unsigned long event, void *data)
```

call regulator event notifier

**Parameters**

- `struct regulator_dev *rdev`: regulator source
- `unsigned long event`: notifier block
- `void *data`: callback-specific data.

**Description**

Called by regulator drivers to notify clients a regulator event has
occurred.

**Return**

`NOTIFY_DONE`.

#### <a id="c-regulator_mode_to_status"></a>`regulator_mode_to_status()`

```c
int regulator_mode_to_status(unsigned int mode)
```

convert a regulator mode into a status

**Parameters**

- `unsigned int mode`: Mode to convert

**Description**

Convert a regulator mode into a status.

**Return**

`REGULATOR_STATUS_*` value corresponding to given mode.

#### <a id="c-regulator_register"></a>`regulator_register()`

```c
struct regulator_dev * regulator_register(struct device *dev, const struct regulator_desc *regulator_desc, const struct regulator_config *cfg)
```

register regulator

**Parameters**

- `struct device *dev`: the device that drive the regulator
- `const struct regulator_desc *regulator_desc`: regulator to register
- `const struct regulator_config *cfg`: runtime configuration for regulator

**Description**

Called by regulator drivers to register a regulator.

**Return**

Pointer to a valid `struct regulator_dev` on success or
an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded negative error number on failure.

#### <a id="c-regulator_unregister"></a>`regulator_unregister()`

```c
void regulator_unregister(struct regulator_dev *rdev)
```

unregister regulator

**Parameters**

- `struct regulator_dev *rdev`: regulator to unregister

**Description**

Called by regulator drivers to unregister a regulator.

#### <a id="c-regulator_has_full_constraints"></a>`regulator_has_full_constraints()`

```c
void regulator_has_full_constraints(void)
```

the system has fully specified constraints

**Parameters**

- `void`: no arguments

**Description**

Calling this function will cause the regulator API to disable all
regulators which have a zero use count and don't have an always_on
constraint in a late_initcall.

The intention is that this will become the default behaviour in a
future kernel release so users are encouraged to use this facility
now.

#### <a id="c-rdev_get_drvdata"></a>`rdev_get_drvdata()`

```c
void * rdev_get_drvdata(struct regulator_dev *rdev)
```

get rdev regulator driver data

**Parameters**

- `struct regulator_dev *rdev`: regulator

**Description**

Get rdev regulator driver private data. This call can be used in the
regulator driver context.

**Return**

Pointer to regulator driver private data.

#### <a id="c-regulator_get_drvdata"></a>`regulator_get_drvdata()`

```c
void * regulator_get_drvdata(struct regulator *regulator)
```

get regulator driver data

**Parameters**

- `struct regulator *regulator`: regulator

**Description**

Get regulator driver private data. This call can be used in the consumer
driver context when non API regulator specific functions need to be called.

**Return**

Pointer to regulator driver private data.

#### <a id="c-regulator_set_drvdata"></a>`regulator_set_drvdata()`

```c
void regulator_set_drvdata(struct regulator *regulator, void *data)
```

set regulator driver data

**Parameters**

- `struct regulator *regulator`: regulator
- `void *data`: data

#### <a id="c-rdev_get_id"></a>`rdev_get_id()`

```c
int rdev_get_id(struct regulator_dev *rdev)
```

get regulator ID

**Parameters**

- `struct regulator_dev *rdev`: regulator

**Return**

Regulator ID for **rdev**.

---

# Reset controller API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Reset controllers are central units that control the reset signals to multiple peripherals. The reset controller API is split into two parts: the consumer driver interface (API reference), which allows peripheral drivers to request control…

<a id="rst-reset-controller-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

<a id="rst-introduction"></a>

## Introduction

Reset controllers are central units that control the reset signals to multiple peripherals. The reset controller API is split into two parts: the [consumer driver interface](<#consumer-driver-interface>) ([API reference](<#reset-consumer-api>)), which allows peripheral drivers to request control over their reset input signals, and the [reset controller driver interface](<#reset-controller-driver-interface>) ([API reference](<#reset-controller-driver-api>)), which is used by drivers for reset controller devices to register their reset controls to provide them to the consumers.

While some reset controller hardware units also implement system restart functionality, restart handlers are out of scope for the reset controller API.

<a id="rst-glossary"></a>

### Glossary

The reset controller API uses these terms with a specific meaning:

Reset line

> Physical reset line carrying a reset signal from a reset controller hardware unit to a peripheral module.

Reset control

> Control method that determines the state of one or multiple reset lines. Most commonly this is a single bit in reset controller register space that either allows direct control over the physical state of the reset line, or is self-clearing and can be used to trigger a predetermined pulse on the reset line. In more complicated reset controls, a single trigger action can launch a carefully timed sequence of pulses on multiple reset lines.

Reset controller

> A hardware module that provides a number of reset controls to control a number of reset lines.

Reset consumer

> Peripheral module or external IC that is put into reset by the signal on a reset line.

<a id="rst-consumer-driver-interface"></a>

## Consumer driver interface

This interface provides an API that is similar to the kernel clock framework. Consumer drivers use get and put operations to acquire and release reset controls. Functions are provided to assert and deassert the controlled reset lines, trigger reset pulses, or to query reset line status.

When requesting reset controls, consumers can use symbolic names for their reset inputs, which are mapped to an actual reset control on an existing reset controller device by the core.

A stub version of this API is provided when the reset controller framework is not in use in order to minimize the need to use ifdefs.

<a id="rst-shared-and-exclusive-resets"></a>

### Shared and exclusive resets

The reset controller API provides either reference counted deassertion and assertion or direct, exclusive control. The distinction between shared and exclusive reset controls is made at the time the reset control is requested, either via devm_reset_control_get_shared() or via devm_reset_control_get_exclusive(). This choice determines the behavior of the API calls made with the reset control.

Shared resets behave similarly to clocks in the kernel clock framework. They provide reference counted deassertion, where only the first deassert, which increments the deassertion reference count to one, and the last assert which decrements the deassertion reference count back to zero, have a physical effect on the reset line.

Exclusive resets on the other hand guarantee direct control. That is, an assert causes the reset line to be asserted immediately, and a deassert causes the reset line to be deasserted immediately.

<a id="rst-assertion-and-deassertion"></a>

### Assertion and deassertion

Consumer drivers use the reset_control_assert() and reset_control_deassert() functions to assert and deassert reset lines. For shared reset controls, calls to the two functions must be balanced.

Note that since multiple consumers may be using a shared reset control, there is no guarantee that calling reset_control_assert() on a shared reset control will actually cause the reset line to be asserted. Consumer drivers using shared reset controls should assume that the reset line may be kept deasserted at all times. The API only guarantees that the reset line can not be asserted as long as any consumer has requested it to be deasserted.

<a id="rst-triggering"></a>

### Triggering

Consumer drivers use reset_control_reset() to trigger a reset pulse on a self-deasserting reset control. In general, these resets can not be shared between multiple consumers, since requesting a pulse from any consumer driver will reset all connected peripherals.

The reset controller API allows requesting self-deasserting reset controls as shared, but for those only the first trigger request causes an actual pulse to be issued on the reset line. All further calls to this function have no effect until all consumers have called reset_control_rearm(). For shared reset controls, calls to the two functions must be balanced. This allows devices that only require an initial reset at any point before the driver is probed or resumed to share a pulsed reset line.

<a id="rst-querying"></a>

### Querying

Only some reset controllers support querying the current status of a reset line, via reset_control_status(). If supported, this function returns a positive non-zero value if the given reset line is asserted. The reset_control_status() function does not accept a [reset control array](<#reset-control-arrays>) handle as its input parameter.

<a id="rst-optional-resets"></a>

### Optional resets

Often peripherals require a reset line on some platforms but not on others. For this, reset controls can be requested as optional using devm_reset_control_get_optional_exclusive() or devm_reset_control_get_optional_shared(). These functions return a NULL pointer instead of an error when the requested reset control is not specified in the device tree. Passing a NULL pointer to the reset_control functions causes them to return quietly without an error.

<a id="rst-reset-control-arrays"></a>

### Reset control arrays

Some drivers need to assert a bunch of reset lines in no particular order. devm_reset_control_array_get() returns an opaque reset control handle that can be used to assert, deassert, or trigger all specified reset controls at once. The reset control API does not guarantee the order in which the individual controls therein are handled.

<a id="rst-reset-controller-driver-interface"></a>

## Reset controller driver interface

Drivers for reset controller modules provide the functionality necessary to assert or deassert reset signals, to trigger a reset pulse on a reset line, or to query its current state. All functions are optional.

<a id="rst-initialization"></a>

### Initialization

Drivers fill a struct `reset_controller_dev` and register it with reset_controller_register() in their probe function. The actual functionality is implemented in callback functions via a struct `reset_control_ops`.

<a id="rst-api-reference"></a>

## API reference

The reset controller API is documented here in two parts: the [reset consumer API](<#reset-consumer-api>) and the [reset controller driver API](<#reset-controller-driver-api>).

<a id="rst-reset-consumer-api"></a>

### Reset consumer API

Reset consumers can control a reset line using an opaque reset control handle, which can be obtained from devm_reset_control_get_exclusive() or devm_reset_control_get_shared(). Given the reset control, consumers can call reset_control_assert() and reset_control_deassert(), trigger a reset pulse using reset_control_reset(), or query the reset line status using reset_control_status().


#### <a id="c-struct-reset_control_bulk_data"></a>`struct reset_control_bulk_data`

Data used for bulk reset control operations.

**Definition**

```c
struct reset_control_bulk_data {
    const char                      *id;
    struct reset_control            *rstc;
};
```

**Members**

- `id`: reset control consumer ID
- `rstc`: struct reset_control * to store the associated reset control

**Description**

The reset APIs provide a series of reset_control_bulk_*() API calls as
a convenience to consumers which require multiple reset controls.
This structure is used to manage data for these calls.

#### <a id="c-enum-reset_control_flags"></a>`enum reset_control_flags`

Flags that can be passed to the reset_control_get functions to determine the type of reset control. These values cannot be OR'd.

**Constants**

- `RESET_CONTROL_EXCLUSIVE`: exclusive, acquired,
- `RESET_CONTROL_EXCLUSIVE_DEASSERTED`: exclusive, acquired, deasserted
- `RESET_CONTROL_EXCLUSIVE_RELEASED`: exclusive, released,
- `RESET_CONTROL_SHARED`: shared
- `RESET_CONTROL_SHARED_DEASSERTED`: shared, deasserted
- `RESET_CONTROL_OPTIONAL_EXCLUSIVE`: optional, exclusive, acquired
- `RESET_CONTROL_OPTIONAL_EXCLUSIVE_DEASSERTED`: optional, exclusive, acquired, deasserted
- `RESET_CONTROL_OPTIONAL_EXCLUSIVE_RELEASED`: optional, exclusive, released
- `RESET_CONTROL_OPTIONAL_SHARED`: optional, shared
- `RESET_CONTROL_OPTIONAL_SHARED_DEASSERTED`: optional, shared, deasserted

#### <a id="c-reset_control_get_exclusive"></a>`reset_control_get_exclusive()`

```c
struct reset_control * reset_control_get_exclusive(struct device *dev, const char *id)
```

Lookup and obtain an exclusive reference to a reset controller.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.
If this function is called more than once for the same reset_control it will
return -EBUSY.

See [`reset_control_get_shared()`](#c-reset_control_get_shared) for details on shared references to
reset-controls.

Use of id names is optional.

#### <a id="c-reset_control_bulk_get_exclusive"></a>`reset_control_bulk_get_exclusive()`

```c
int reset_control_bulk_get_exclusive(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

Lookup and obtain exclusive references to multiple reset controllers.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Fills the rstcs array with pointers to exclusive reset controls and
returns 0, or an [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

#### <a id="c-reset_control_get_exclusive_released"></a>`reset_control_get_exclusive_released()`

```c
struct reset_control * reset_control_get_exclusive_released(struct device *dev, const char *id)
```

Lookup and obtain a temoprarily exclusive reference to a reset controller.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.
reset-controls returned by this function must be acquired via
[`reset_control_acquire()`](#c-reset_control_acquire) before they can be used and should be released
via [`reset_control_release()`](#c-reset_control_release) afterwards.

Use of id names is optional.

#### <a id="c-reset_control_bulk_get_exclusive_released"></a>`reset_control_bulk_get_exclusive_released()`

```c
int reset_control_bulk_get_exclusive_released(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

Lookup and obtain temporarily exclusive references to multiple reset controllers.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Fills the rstcs array with pointers to exclusive reset controls and
returns 0, or an [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.
reset-controls returned by this function must be acquired via
`reset_control_bulk_acquire()` before they can be used and should be released
via `reset_control_bulk_release()` afterwards.

#### <a id="c-reset_control_bulk_get_optional_exclusive_released"></a>`reset_control_bulk_get_optional_exclusive_released()`

```c
int reset_control_bulk_get_optional_exclusive_released(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

Lookup and obtain optional temporarily exclusive references to multiple reset controllers.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Optional variant of [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released). If the
requested reset is not specified in the device tree, this function returns 0
instead of an error and missing rtsc is set to NULL.

See [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released) for more information.

#### <a id="c-reset_control_get_shared"></a>`reset_control_get_shared()`

```c
struct reset_control * reset_control_get_shared(struct device *dev, const char *id)
```

Lookup and obtain a shared reference to a reset controller.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.
This function is intended for use with reset-controls which are shared
between hardware blocks.

When a reset-control is shared, the behavior of reset_control_assert /
deassert is changed, the reset-core will keep track of a deassert_count
and only (re-)assert the reset after reset_control_assert has been called
as many times as reset_control_deassert was called. Also see the remark
about shared reset-controls in the reset_control_assert docs.

Calling reset_control_assert without first calling reset_control_deassert
is not allowed on a shared reset control. Calling reset_control_reset is
also not allowed on a shared reset control.

Use of id names is optional.

#### <a id="c-reset_control_bulk_get_shared"></a>`reset_control_bulk_get_shared()`

```c
int reset_control_bulk_get_shared(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

Lookup and obtain shared references to multiple reset controllers.

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Fills the rstcs array with pointers to shared reset controls and
returns 0, or an [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

#### <a id="c-reset_control_get_optional_exclusive"></a>`reset_control_get_optional_exclusive()`

```c
struct reset_control * reset_control_get_optional_exclusive(struct device *dev, const char *id)
```

optional [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Optional variant of [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive). If the requested reset
is not specified in the device tree, this function returns NULL instead of
an error.

See [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) for more information.

#### <a id="c-reset_control_bulk_get_optional_exclusive"></a>`reset_control_bulk_get_optional_exclusive()`

```c
int reset_control_bulk_get_optional_exclusive(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

optional [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Optional variant of [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive). If any of the
requested resets are not specified in the device tree, this function sets
them to NULL instead of returning an error.

See [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive) for more information.

#### <a id="c-reset_control_get_optional_shared"></a>`reset_control_get_optional_shared()`

```c
struct reset_control * reset_control_get_optional_shared(struct device *dev, const char *id)
```

optional [`reset_control_get_shared()`](#c-reset_control_get_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Optional variant of [`reset_control_get_shared()`](#c-reset_control_get_shared). If the requested reset
is not specified in the device tree, this function returns NULL instead of
an error.

See [`reset_control_get_shared()`](#c-reset_control_get_shared) for more information.

#### <a id="c-reset_control_bulk_get_optional_shared"></a>`reset_control_bulk_get_optional_shared()`

```c
int reset_control_bulk_get_optional_shared(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

optional [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Optional variant of [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared). If the requested resets
are not specified in the device tree, this function sets them to NULL
instead of returning an error.

See [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared) for more information.

#### <a id="c-of_reset_control_get_exclusive"></a>`of_reset_control_get_exclusive()`

```c
struct reset_control * of_reset_control_get_exclusive(struct device_node *node, const char *id)
```

Lookup and obtain an exclusive reference to a reset controller.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

Use of id names is optional.

#### <a id="c-of_reset_control_get_optional_exclusive"></a>`of_reset_control_get_optional_exclusive()`

```c
struct reset_control * of_reset_control_get_optional_exclusive(struct device_node *node, const char *id)
```

Lookup and obtain an optional exclusive reference to a reset controller.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Optional variant of [`of_reset_control_get_exclusive()`](#c-of_reset_control_get_exclusive). If the requested reset
is not specified in the device tree, this function returns NULL instead of
an error.

Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

Use of id names is optional.

#### <a id="c-of_reset_control_get_shared"></a>`of_reset_control_get_shared()`

```c
struct reset_control * of_reset_control_get_shared(struct device_node *node, const char *id)
```

Lookup and obtain a shared reference to a reset controller.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

When a reset-control is shared, the behavior of reset_control_assert /
deassert is changed, the reset-core will keep track of a deassert_count
and only (re-)assert the reset after reset_control_assert has been called
as many times as reset_control_deassert was called. Also see the remark
about shared reset-controls in the reset_control_assert docs.

Calling reset_control_assert without first calling reset_control_deassert
is not allowed on a shared reset control. Calling reset_control_reset is
also not allowed on a shared reset control.
Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

Use of id names is optional.

#### <a id="c-of_reset_control_get_exclusive_by_index"></a>`of_reset_control_get_exclusive_by_index()`

```c
struct reset_control * of_reset_control_get_exclusive_by_index(struct device_node *node, int index)
```

Lookup and obtain an exclusive reference to a reset controller by index.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `int index`: index of the reset controller

**Description**

This is to be used to perform a list of resets for a device or power domain
in whatever order. Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition
containing errno.

#### <a id="c-of_reset_control_get_shared_by_index"></a>`of_reset_control_get_shared_by_index()`

```c
struct reset_control * of_reset_control_get_shared_by_index(struct device_node *node, int index)
```

Lookup and obtain a shared reference to a reset controller by index.

**Parameters**

- `struct device_node *node`: device to be reset by the controller
- `int index`: index of the reset controller

**Description**

When a reset-control is shared, the behavior of reset_control_assert /
deassert is changed, the reset-core will keep track of a deassert_count
and only (re-)assert the reset after reset_control_assert has been called
as many times as reset_control_deassert was called. Also see the remark
about shared reset-controls in the reset_control_assert docs.

Calling reset_control_assert without first calling reset_control_deassert
is not allowed on a shared reset control. Calling reset_control_reset is
also not allowed on a shared reset control.
Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing errno.

This is to be used to perform a list of resets for a device or power domain
in whatever order. Returns a struct reset_control or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition
containing errno.

#### <a id="c-devm_reset_control_get_exclusive"></a>`devm_reset_control_get_exclusive()`

```c
struct reset_control * devm_reset_control_get_exclusive(struct device *dev, const char *id)
```

resource managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive). For reset controllers returned
from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) for more information.

#### <a id="c-devm_reset_control_get_exclusive_deasserted"></a>`devm_reset_control_get_exclusive_deasserted()`

```c
struct reset_control * devm_reset_control_get_exclusive_deasserted(struct device *dev, const char *id)
```

resource managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) + [`reset_control_deassert()`](#c-reset_control_deassert)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) + [`reset_control_deassert()`](#c-reset_control_deassert). For reset
controllers returned from this function, [`reset_control_assert()`](#c-reset_control_assert) +
[`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.

See [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) for more information.

#### <a id="c-devm_reset_control_bulk_get_exclusive"></a>`devm_reset_control_bulk_get_exclusive()`

```c
int devm_reset_control_bulk_get_exclusive(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive). For reset controllers returned
from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_bulk_get_exclusive()`](#c-reset_control_bulk_get_exclusive) for more information.

#### <a id="c-devm_reset_control_get_exclusive_released"></a>`devm_reset_control_get_exclusive_released()`

```c
struct reset_control * devm_reset_control_get_exclusive_released(struct device *dev, const char *id)
```

resource managed [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released) for more information.

#### <a id="c-devm_reset_control_bulk_get_exclusive_released"></a>`devm_reset_control_bulk_get_exclusive_released()`

```c
int devm_reset_control_bulk_get_exclusive_released(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_bulk_get_exclusive_released()`](#c-reset_control_bulk_get_exclusive_released) for more information.

#### <a id="c-devm_reset_control_get_optional_exclusive_released"></a>`devm_reset_control_get_optional_exclusive_released()`

```c
struct reset_control * devm_reset_control_get_optional_exclusive_released(struct device *dev, const char *id)
```

resource managed `reset_control_get_optional_exclusive_released()`

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed-and-optional variant of [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released). For
reset controllers returned from this function, [`reset_control_put()`](#c-reset_control_put) is called
automatically on driver detach.

See [`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released) for more information.

#### <a id="c-devm_reset_control_bulk_get_optional_exclusive_released"></a>`devm_reset_control_bulk_get_optional_exclusive_released()`

```c
int devm_reset_control_bulk_get_optional_exclusive_released(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed `reset_control_bulk_optional_get_exclusive_released()`

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed `reset_control_bulk_optional_get_exclusive_released()`. For reset
controllers returned from this function, [`reset_control_put()`](#c-reset_control_put) is called
automatically on driver detach.

See `reset_control_bulk_optional_get_exclusive_released()` for more information.

#### <a id="c-devm_reset_control_get_shared"></a>`devm_reset_control_get_shared()`

```c
struct reset_control * devm_reset_control_get_shared(struct device *dev, const char *id)
```

resource managed [`reset_control_get_shared()`](#c-reset_control_get_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_shared()`](#c-reset_control_get_shared). For reset controllers returned from
this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.
See [`reset_control_get_shared()`](#c-reset_control_get_shared) for more information.

#### <a id="c-devm_reset_control_get_shared_deasserted"></a>`devm_reset_control_get_shared_deasserted()`

```c
struct reset_control * devm_reset_control_get_shared_deasserted(struct device *dev, const char *id)
```

resource managed [`reset_control_get_shared()`](#c-reset_control_get_shared) + [`reset_control_deassert()`](#c-reset_control_deassert)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_shared()`](#c-reset_control_get_shared) + [`reset_control_deassert()`](#c-reset_control_deassert). For reset
controllers returned from this function, [`reset_control_assert()`](#c-reset_control_assert) +
[`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.

See [`devm_reset_control_get_shared()`](#c-devm_reset_control_get_shared) for more information.

#### <a id="c-devm_reset_control_bulk_get_shared"></a>`devm_reset_control_bulk_get_shared()`

```c
int devm_reset_control_bulk_get_shared(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared). For reset controllers returned
from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared) for more information.

#### <a id="c-devm_reset_control_bulk_get_shared_deasserted"></a>`devm_reset_control_bulk_get_shared_deasserted()`

```c
int devm_reset_control_bulk_get_shared_deasserted(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared) + `reset_control_bulk_deassert()`

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_shared()`](#c-reset_control_bulk_get_shared) + `reset_control_bulk_deassert()`. For
reset controllers returned from this function, `reset_control_bulk_assert()` +
`reset_control_bulk_put()` are called automatically on driver detach.

See [`devm_reset_control_bulk_get_shared()`](#c-devm_reset_control_bulk_get_shared) for more information.

#### <a id="c-devm_reset_control_get_optional_exclusive"></a>`devm_reset_control_get_optional_exclusive()`

```c
struct reset_control * devm_reset_control_get_optional_exclusive(struct device *dev, const char *id)
```

resource managed [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive) for more information.

#### <a id="c-devm_reset_control_get_optional_exclusive_deasserted"></a>`devm_reset_control_get_optional_exclusive_deasserted()`

```c
struct reset_control * devm_reset_control_get_optional_exclusive_deasserted(struct device *dev, const char *id)
```

resource managed [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive) + [`reset_control_deassert()`](#c-reset_control_deassert)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_optional_exclusive()`](#c-reset_control_get_optional_exclusive) + [`reset_control_deassert()`](#c-reset_control_deassert).
For reset controllers returned from this function, [`reset_control_assert()`](#c-reset_control_assert) +
[`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.

See [`devm_reset_control_get_optional_exclusive()`](#c-devm_reset_control_get_optional_exclusive) for more information.

#### <a id="c-devm_reset_control_bulk_get_optional_exclusive"></a>`devm_reset_control_bulk_get_optional_exclusive()`

```c
int devm_reset_control_bulk_get_optional_exclusive(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_optional_exclusive()`](#c-reset_control_bulk_get_optional_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_optional_exclusive()`](#c-reset_control_bulk_get_optional_exclusive). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_bulk_get_optional_exclusive()`](#c-reset_control_bulk_get_optional_exclusive) for more information.

#### <a id="c-devm_reset_control_get_optional_shared"></a>`devm_reset_control_get_optional_shared()`

```c
struct reset_control * devm_reset_control_get_optional_shared(struct device *dev, const char *id)
```

resource managed [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared). For reset controllers returned
from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared) for more information.

#### <a id="c-devm_reset_control_get_optional_shared_deasserted"></a>`devm_reset_control_get_optional_shared_deasserted()`

```c
struct reset_control * devm_reset_control_get_optional_shared_deasserted(struct device *dev, const char *id)
```

resource managed [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared) + [`reset_control_deassert()`](#c-reset_control_deassert)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `const char *id`: reset line name

**Description**

Managed [`reset_control_get_optional_shared()`](#c-reset_control_get_optional_shared) + [`reset_control_deassert()`](#c-reset_control_deassert). For
reset controllers returned from this function, [`reset_control_assert()`](#c-reset_control_assert) +
[`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.

See [`devm_reset_control_get_optional_shared()`](#c-devm_reset_control_get_optional_shared) for more information.

#### <a id="c-devm_reset_control_bulk_get_optional_shared"></a>`devm_reset_control_bulk_get_optional_shared()`

```c
int devm_reset_control_bulk_get_optional_shared(struct device *dev, int num_rstcs, struct reset_control_bulk_data *rstcs)
```

resource managed [`reset_control_bulk_get_optional_shared()`](#c-reset_control_bulk_get_optional_shared)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int num_rstcs`: number of entries in rstcs array
- `struct reset_control_bulk_data *rstcs`: array of struct reset_control_bulk_data with reset line names set

**Description**

Managed [`reset_control_bulk_get_optional_shared()`](#c-reset_control_bulk_get_optional_shared). For reset controllers
returned from this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on
driver detach.

See [`reset_control_bulk_get_optional_shared()`](#c-reset_control_bulk_get_optional_shared) for more information.

#### <a id="c-devm_reset_control_get_exclusive_by_index"></a>`devm_reset_control_get_exclusive_by_index()`

```c
struct reset_control * devm_reset_control_get_exclusive_by_index(struct device *dev, int index)
```

resource managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive)

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int index`: index of the reset controller

**Description**

Managed [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive). For reset controllers returned from
this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver
detach.

See [`reset_control_get_exclusive()`](#c-reset_control_get_exclusive) for more information.

#### <a id="c-devm_reset_control_get_shared_by_index"></a>`devm_reset_control_get_shared_by_index()`

```c
struct reset_control * devm_reset_control_get_shared_by_index(struct device *dev, int index)
```

resource managed reset_control_get_shared

**Parameters**

- `struct device *dev`: device to be reset by the controller
- `int index`: index of the reset controller

**Description**

Managed [`reset_control_get_shared()`](#c-reset_control_get_shared). For reset controllers returned from
this function, [`reset_control_put()`](#c-reset_control_put) is called automatically on driver detach.
See [`reset_control_get_shared()`](#c-reset_control_get_shared) for more information.



#### <a id="c-reset_control_reset"></a>`reset_control_reset()`

```c
int reset_control_reset(struct reset_control *rstc)
```

reset the controlled device

**Parameters**

- `struct reset_control *rstc`: reset controller

**Description**

On a shared reset line the actual reset pulse is only triggered once for the
lifetime of the reset_control instance: for all but the first caller this is
a no-op.
Consumers must not use reset_control_(de)assert on shared reset lines when
reset_control_reset has been used.

If rstc is NULL it is an optional reset and the function will just
return 0.

#### <a id="c-reset_control_rearm"></a>`reset_control_rearm()`

```c
int reset_control_rearm(struct reset_control *rstc)
```

allow shared reset line to be re-triggered"

**Parameters**

- `struct reset_control *rstc`: reset controller

**Description**

On a shared reset line the actual reset pulse is only triggered once for the
lifetime of the reset_control instance, except if this call is used.

Calls to this function must be balanced with calls to reset_control_reset,
a warning is thrown in case triggered_count ever dips below 0.

Consumers must not use reset_control_(de)assert on shared reset lines when
reset_control_reset or reset_control_rearm have been used.

If rstc is NULL the function will just return 0.

#### <a id="c-reset_control_assert"></a>`reset_control_assert()`

```c
int reset_control_assert(struct reset_control *rstc)
```

asserts the reset line

**Parameters**

- `struct reset_control *rstc`: reset controller

**Description**

Calling this on an exclusive reset controller guarantees that the reset
will be asserted. When called on a shared reset controller the line may
still be deasserted, as long as other users keep it so.

For shared reset controls a driver cannot expect the hw's registers and
internal state to be reset, but must be prepared for this to happen.
Consumers must not use reset_control_reset on shared reset lines when
reset_control_(de)assert has been used.

If rstc is NULL it is an optional reset and the function will just
return 0.

#### <a id="c-reset_control_deassert"></a>`reset_control_deassert()`

```c
int reset_control_deassert(struct reset_control *rstc)
```

deasserts the reset line

**Parameters**

- `struct reset_control *rstc`: reset controller

**Description**

After calling this function, the reset is guaranteed to be deasserted.
Consumers must not use reset_control_reset on shared reset lines when
reset_control_(de)assert has been used.

If rstc is NULL it is an optional reset and the function will just
return 0.

#### <a id="c-reset_control_status"></a>`reset_control_status()`

```c
int reset_control_status(struct reset_control *rstc)
```

returns a negative errno if not supported, a positive value if the reset line is asserted, or zero if the reset line is not asserted or if the desc is NULL (optional reset).

**Parameters**

- `struct reset_control *rstc`: reset controller

#### <a id="c-reset_control_acquire"></a>`reset_control_acquire()`

```c
int reset_control_acquire(struct reset_control *rstc)
```

acquires a reset control for exclusive use

**Parameters**

- `struct reset_control *rstc`: reset control

**Description**

This is used to explicitly acquire a reset control for exclusive use. Note
that exclusive resets are requested as acquired by default. In order for a
second consumer to be able to control the reset, the first consumer has to
release it first. Typically the easiest way to achieve this is to call the
[`reset_control_get_exclusive_released()`](#c-reset_control_get_exclusive_released) to obtain an instance of the reset
control. Such reset controls are not acquired by default.

Consumers implementing shared access to an exclusive reset need to follow
a specific protocol in order to work together. Before consumers can change
a reset they must acquire exclusive access using [`reset_control_acquire()`](#c-reset_control_acquire).
After they are done operating the reset, they must release exclusive access
with a call to [`reset_control_release()`](#c-reset_control_release). Consumers are not granted exclusive
access to the reset as long as another consumer hasn't released a reset.

See also: [`reset_control_release()`](#c-reset_control_release)

#### <a id="c-reset_control_release"></a>`reset_control_release()`

```c
void reset_control_release(struct reset_control *rstc)
```

releases exclusive access to a reset control

**Parameters**

- `struct reset_control *rstc`: reset control

**Description**

Releases exclusive access right to a reset control previously obtained by a
call to [`reset_control_acquire()`](#c-reset_control_acquire). Until a consumer calls this function, no
other consumers will be granted exclusive access.

See also: [`reset_control_acquire()`](#c-reset_control_acquire)

#### <a id="c-reset_control_put"></a>`reset_control_put()`

```c
void reset_control_put(struct reset_control *rstc)
```

free the reset controller

**Parameters**

- `struct reset_control *rstc`: reset controller

#### <a id="c-of_reset_control_get_count"></a>`of_reset_control_get_count()`

```c
int of_reset_control_get_count(struct device_node *node)
```

Count number of resets available with a device

**Parameters**

- `struct device_node *node`: device node that contains 'resets'.

**Description**

Returns positive reset count on success, or error number on failure and
on count being zero.

#### <a id="c-of_reset_control_array_get"></a>`of_reset_control_array_get()`

```c
struct reset_control * of_reset_control_array_get(struct device_node *np, enum reset_control_flags flags)
```

Get a list of reset controls using device node.

**Parameters**

- `struct device_node *np`: device node for the device that requests the reset controls array
- `enum reset_control_flags flags`: whether reset controls are shared, optional, acquired

**Description**

Returns pointer to allocated reset_control on success or error on failure

#### <a id="c-devm_reset_control_array_get"></a>`devm_reset_control_array_get()`

```c
struct reset_control * devm_reset_control_array_get(struct device *dev, enum reset_control_flags flags)
```

Resource managed reset control array get

**Parameters**

- `struct device *dev`: device that requests the list of reset controls
- `enum reset_control_flags flags`: whether reset controls are shared, optional, acquired

**Description**

The reset control array APIs are intended for a list of resets
that just have to be asserted or deasserted, without any
requirements on the order.

Returns pointer to allocated reset_control on success or error on failure

#### <a id="c-reset_control_get_count"></a>`reset_control_get_count()`

```c
int reset_control_get_count(struct device *dev)
```

Count number of resets available with a device

**Parameters**

- `struct device *dev`: device for which to return the number of resets

**Description**

Returns positive reset count on success, or error number on failure and
on count being zero.


<a id="rst-reset-controller-driver-api"></a>

### Reset controller driver API

Reset controller drivers are supposed to implement the necessary functions in a static constant structure `reset_control_ops`, allocate and fill out a struct `reset_controller_dev`, and register it using devm_reset_controller_register().


#### <a id="c-struct-reset_control_ops"></a>`struct reset_control_ops`

reset controller driver callbacks

**Definition**

```c
struct reset_control_ops {
    int (*reset)(struct reset_controller_dev *rcdev, unsigned long id);
    int (*assert)(struct reset_controller_dev *rcdev, unsigned long id);
    int (*deassert)(struct reset_controller_dev *rcdev, unsigned long id);
    int (*status)(struct reset_controller_dev *rcdev, unsigned long id);
};
```

**Members**

- `reset`: for self-deasserting resets, does all necessary
  things to reset the device
- `assert`: manually assert the reset line, if supported
- `deassert`: manually deassert the reset line, if supported
- `status`: return the status of the reset line, if supported

#### <a id="c-struct-reset_controller_dev"></a>`struct reset_controller_dev`

reset controller entity that might provide multiple reset controls

**Definition**

```c
struct reset_controller_dev {
    const struct reset_control_ops *ops;
    struct module *owner;
    struct list_head list;
    struct list_head reset_control_head;
    struct device *dev;
    struct device_node *of_node;
    const struct of_phandle_args *of_args;
    int of_reset_n_cells;
    int (*of_xlate)(struct reset_controller_dev *rcdev, const struct of_phandle_args *reset_spec);
    unsigned int nr_resets;
};
```

**Members**

- `ops`: a pointer to device specific struct reset_control_ops
- `owner`: kernel module of the reset controller driver
- `list`: internal list of reset controller devices
- `reset_control_head`: head of internal list of requested reset controls
- `dev`: corresponding driver model device struct
- `of_node`: corresponding device tree node as phandle target
- `of_args`: for reset-gpios controllers: corresponding phandle args with
  of_node and GPIO number complementing of_node; either this or
  of_node should be present
- `of_reset_n_cells`: number of cells in reset line specifiers
- `of_xlate`: translation function to translate from specifier as found in the
  device tree to id as given to the reset control ops, defaults
  to [`of_reset_simple_xlate()`](#c-of_reset_simple_xlate).
- `nr_resets`: number of reset controls in this reset controller device



#### <a id="c-of_reset_simple_xlate"></a>`of_reset_simple_xlate()`

```c
int of_reset_simple_xlate(struct reset_controller_dev *rcdev, const struct of_phandle_args *reset_spec)
```

translate reset_spec to the reset line number

**Parameters**

- `struct reset_controller_dev *rcdev`: a pointer to the reset controller device
- `const struct of_phandle_args *reset_spec`: reset line specifier as found in the device tree

**Description**

This static translation function is used by default if of_xlate in
[`reset_controller_dev`](#c-struct-reset_controller_dev) is not set. It is useful for all reset
controllers with 1:1 mapping, where reset lines can be indexed by number
without gaps.

#### <a id="c-reset_controller_register"></a>`reset_controller_register()`

```c
int reset_controller_register(struct reset_controller_dev *rcdev)
```

register a reset controller device

**Parameters**

- `struct reset_controller_dev *rcdev`: a pointer to the initialized reset controller device

#### <a id="c-reset_controller_unregister"></a>`reset_controller_unregister()`

```c
void reset_controller_unregister(struct reset_controller_dev *rcdev)
```

unregister a reset controller device

**Parameters**

- `struct reset_controller_dev *rcdev`: a pointer to the reset controller device

#### <a id="c-devm_reset_controller_register"></a>`devm_reset_controller_register()`

```c
int devm_reset_controller_register(struct device *dev, struct reset_controller_dev *rcdev)
```

resource managed [`reset_controller_register()`](#c-reset_controller_register)

**Parameters**

- `struct device *dev`: device that is registering this reset controller
- `struct reset_controller_dev *rcdev`: a pointer to the initialized reset controller device

**Description**

Managed [`reset_controller_register()`](#c-reset_controller_register). For reset controllers registered by
this function, [`reset_controller_unregister()`](#c-reset_controller_unregister) is automatically called on
driver detach. See [`reset_controller_register()`](#c-reset_controller_register) for more information.

---

# rfkill - RF kill switch support

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Introduction

<a id="rst-rfkill-rf-kill-switch-support"></a>

<a id="rst-contents"></a>



<a id="rst-introduction"></a>

## Introduction

The rfkill subsystem provides a generic interface for disabling any radio transmitter in the system. When a transmitter is blocked, it shall not radiate any power.

The subsystem also provides the ability to react on button presses and disable all transmitters of a certain type (or all). This is intended for situations where transmitters need to be turned off, for example on aircraft.

The rfkill subsystem has a concept of "hard" and "soft" block, which differ little in their meaning (block == transmitters off) but rather in whether they can be changed or not:

> - - **hard block**
>
>     read-only radio block that cannot be overridden by software
>
> - - **soft block**
>
>     writable radio block (need not be readable) that is set by the system software.

The rfkill subsystem has two parameters, rfkill.default_state and rfkill.master_switch_mode, which are documented in admin-guide/kernel-parameters.rst.

<a id="rst-implementation-details"></a>

## Implementation details

The rfkill subsystem is composed of three main components:

> - the rfkill core,
>
> - the deprecated rfkill-input module (an input layer handler, being replaced by userspace policy code) and
>
> - the rfkill drivers.

The rfkill core provides API for kernel drivers to register their radio transmitter with the kernel, methods for turning it on and off, and letting the system know about hardware-disabled states that may be implemented on the device.

The rfkill core code also notifies userspace of state changes, and provides ways for userspace to query the current states. See the "Userspace support" section below.

When the device is hard-blocked (either by a call to rfkill_set_hw_state() or from query_hw_block), set_block() will be invoked for additional software block, but drivers can ignore the method call since they can use the return value of the function rfkill_set_hw_state() to sync the software state instead of keeping track of calls to set_block(). In fact, drivers should use the return value of rfkill_set_hw_state() unless the hardware actually keeps track of soft and hard block separately.

<a id="rst-kernel-api"></a>

## Kernel API

Drivers for radio transmitters normally implement an rfkill driver.

Platform drivers might implement input devices if the rfkill button is just that, a button. If that button influences the hardware then you need to implement an rfkill driver instead. This also applies if the platform provides a way to turn on/off the transmitter(s).

For some platforms, it is possible that the hardware state changes during suspend/hibernation, in which case it will be necessary to update the rfkill core with the current state at resume time.

To create an rfkill driver, driver's Kconfig needs to have:



```text
depends on RFKILL || !RFKILL
```

to ensure the driver cannot be built-in when rfkill is modular. The \!RFKILL case allows the driver to be built when rfkill is not configured, in which case all rfkill API can still be used but will be provided by static inlines which compile to almost nothing.

Calling rfkill_set_hw_state() when a state change happens is required from rfkill drivers that control devices that can be hard-blocked unless they also assign the poll_hw_block() callback (then the rfkill core will poll the device). Don't do this unless you cannot get the event in any other way.

rfkill provides per-switch LED triggers, which can be used to drive LEDs according to the switch state (LED_FULL when blocked, LED_OFF otherwise).

<a id="rst-userspace-support"></a>

## Userspace support

The recommended userspace interface to use is /dev/rfkill, which is a misc character device that allows userspace to obtain and set the state of rfkill devices and sets of devices. It also notifies userspace about device addition and removal. The API is a simple read/write API that is defined in linux/rfkill.h, with one ioctl that allows turning off the deprecated input handler in the kernel for the transition period.

Except for the one ioctl, communication with the kernel is done via read() and write() of instances of 'struct rfkill_event'. In this structure, the soft and hard block are properly separated (unlike sysfs, see below) and userspace is able to get a consistent snapshot of all rfkill devices in the system. Also, it is possible to switch all rfkill drivers (or all drivers of a specified type) into a state which also updates the default state for hotplugged devices.

After an application opens /dev/rfkill, it can read the current state of all devices. Changes can be obtained by either polling the descriptor for hotplug or state change events or by listening for uevents emitted by the rfkill core framework.

Additionally, each rfkill device is registered in sysfs and emits uevents.

rfkill devices issue uevents (with an action of "change"), with the following environment variables set:



```text
RFKILL_NAME
RFKILL_STATE
RFKILL_TYPE
```

The content of these variables corresponds to the "name", "state" and "type" sysfs files explained above.

For further details consult Documentation/ABI/stable/sysfs-class-rfkill.

---

# TEE (Trusted Execution Environment) driver API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Kernel provides a TEE bus infrastructure where a Trusted Application is represented as a device identified via Universally Unique Identifier (UUID) and client drivers register a table of supported device UUIDs.

<a id="rst-tee-trusted-execution-environment-driver-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Kernel provides a TEE bus infrastructure where a Trusted Application is represented as a device identified via Universally Unique Identifier (UUID) and client drivers register a table of supported device UUIDs.

TEE bus infrastructure registers following APIs:

- **match():**

  iterates over the client driver UUID table to find a corresponding match for device UUID. If a match is found, then this particular device is probed via corresponding probe API registered by the client driver. This process happens whenever a device or a client driver is registered with TEE bus.

- **uevent():**

  notifies user-space (udev) whenever a new device is registered on TEE bus for auto-loading of modularized client drivers.

TEE bus device enumeration is specific to underlying TEE implementation, so it is left open for TEE drivers to provide corresponding implementation.

Then TEE client driver can talk to a matched Trusted Application using APIs listed in include/linux/tee_drv.h.

<a id="rst-tee-client-driver-example"></a>

## TEE client driver example

Suppose a TEE client driver needs to communicate with a Trusted Application having UUID: `ac6a4085-0e82-4c33-bf98-8eb8e118b6c2`, so driver registration snippet would look like:



```text
static const struct tee_client_device_id client_id_table[] = {
        {UUID_INIT(0xac6a4085, 0x0e82, 0x4c33,
                   0xbf, 0x98, 0x8e, 0xb8, 0xe1, 0x18, 0xb6, 0xc2)},
        {}
};

MODULE_DEVICE_TABLE(tee, client_id_table);

static struct tee_client_driver client_driver = {
        .probe          = client_probe,
        .remove         = client_remove,
        .id_table       = client_id_table,
        .driver         = {
                .name           = DRIVER_NAME,
        },
};

module_tee_client_driver(client_driver);
```

---

# WBRF - Wifi Band RFI Mitigations

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> Due to electrical and mechanical constraints in certain platform designs there may be likely interference of relatively high-powered harmonics of the GPU memory clocks with local radio module frequency bands used by certain Wifi bands.

<a id="rst-wbrf-wifi-band-rfi-mitigations"></a>

<!-- SPDX-License-Identifier: GPL-2.0-or-later -->

Due to electrical and mechanical constraints in certain platform designs there may be likely interference of relatively high-powered harmonics of the GPU memory clocks with local radio module frequency bands used by certain Wifi bands.

To mitigate possible RFI interference producers can advertise the frequencies in use and consumers can use this information to avoid using these frequencies for sensitive features.

When a platform is known to have this issue with any contained devices, the platform designer will advertise the availability of this feature via ACPI devices with a device specific method (\_DSM). \* Producers with this \_DSM will be able to advertise the frequencies in use. \* Consumers with this \_DSM will be able to register for notifications of frequencies in use.

<a id="rst-some-general-terms"></a>

## Some general terms

Producer: such component who can produce high-powered radio frequency Consumer: such component who can adjust its in-use frequency in response to the radio frequencies of other components to mitigate the possible RFI.

To make the mechanism function, those producers should notify active use of their particular frequencies so that other consumers can make relative internal adjustments as necessary to avoid this resonance.

<a id="rst-acpi-interface"></a>

## ACPI interface

Although initially used by for wifi + dGPU use cases, the ACPI interface can be scaled to any type of device that a platform designer discovers can cause interference.

The GUID used for the \_DSM is 7B7656CF-DC3D-4C1C-83E9-66E721DE3070.

3 functions are available in this \_DSM:

- 0: discover \# of functions available

- 1: record RF bands in use

- 2: retrieve RF bands in use

<a id="rst-driver-programming-interface"></a>

## Driver programming interface


#### <a id="c-acpi_amd_wbrf_add_remove"></a>`acpi_amd_wbrf_add_remove()`

```c
int acpi_amd_wbrf_add_remove(struct device *dev, uint8_t action, struct wbrf_ranges_in_out *in)
```

add or remove the frequency band the device is using

**Parameters**

- `struct device *dev`: device pointer
- `uint8_t action`: remove or add the frequency band into bios
- `struct wbrf_ranges_in_out *in`: input structure containing the frequency band the device is using

**Description**

Broadcast to other consumers the frequency band the device starts
to use. Underneath the surface the information is cached into an
internal buffer first. Then a notification is sent to all those
registered consumers. So then they can retrieve that buffer to
know the latest active frequency bands. Consumers that haven't
yet been registered can retrieve the information from the cache
when they register.

**Return**

0 for success add/remove wifi frequency band.
Returns a negative error code for failure.

#### <a id="c-acpi_amd_wbrf_supported_producer"></a>`acpi_amd_wbrf_supported_producer()`

```c
bool acpi_amd_wbrf_supported_producer(struct device *dev)
```

determine if the WBRF can be enabled for the device as a producer

**Parameters**

- `struct device *dev`: device pointer

**Description**

Check if the platform equipped with necessary implementations to
support WBRF for the device as a producer.

**Return**

true if WBRF is supported, otherwise returns false

#### <a id="c-acpi_amd_wbrf_supported_consumer"></a>`acpi_amd_wbrf_supported_consumer()`

```c
bool acpi_amd_wbrf_supported_consumer(struct device *dev)
```

determine if the WBRF can be enabled for the device as a consumer

**Parameters**

- `struct device *dev`: device pointer

**Description**

Determine if the platform equipped with necessary implementations to
support WBRF for the device as a consumer.

**Return**

true if WBRF is supported, otherwise returns false.

#### <a id="c-amd_wbrf_retrieve_freq_band"></a>`amd_wbrf_retrieve_freq_band()`

```c
int amd_wbrf_retrieve_freq_band(struct device *dev, struct wbrf_ranges_in_out *out)
```

retrieve current active frequency bands

**Parameters**

- `struct device *dev`: device pointer
- `struct wbrf_ranges_in_out *out`: output structure containing all the active frequency bands

**Description**

Retrieve the current active frequency bands which were broadcasted
by other producers. The consumer who calls this API should take
proper actions if any of the frequency band may cause RFI with its
own frequency band used.

**Return**

0 for getting wifi freq band successfully.
Returns a negative error code for failure.

#### <a id="c-amd_wbrf_register_notifier"></a>`amd_wbrf_register_notifier()`

```c
int amd_wbrf_register_notifier(struct notifier_block *nb)
```

register for notifications of frequency band update

**Parameters**

- `struct notifier_block *nb`: driver notifier block

**Description**

The consumer should register itself via this API so that it can get
notified on the frequency band updates from other producers.

**Return**

0 for registering a consumer driver successfully.
Returns a negative error code for failure.

#### <a id="c-amd_wbrf_unregister_notifier"></a>`amd_wbrf_unregister_notifier()`

```c
int amd_wbrf_unregister_notifier(struct notifier_block *nb)
```

unregister for notifications of frequency band update

**Parameters**

- `struct notifier_block *nb`: driver notifier block

**Description**

The consumer should call this API when it is longer interested with
the frequency band updates from other producers. Usually, this should
be performed during driver cleanup.

**Return**

0 for unregistering a consumer driver.
Returns a negative error code for failure.


<a id="rst-sample-usage"></a>

## Sample Usage

The expected flow for the producers: 1. During probe, call `acpi_amd_wbrf_supported_producer` to check if WBRF can be enabled for the device. 2. On using some frequency band, call `acpi_amd_wbrf_add_remove` with 'add' param to get other consumers properly notified. 3. Or on stopping using some frequency band, call `acpi_amd_wbrf_add_remove` with 'remove' param to get other consumers notified.

The expected flow for the consumers: 1. During probe, call `acpi_amd_wbrf_supported_consumer` to check if WBRF can be enabled for the device. 2. Call `amd_wbrf_register_notifier` to register for notification of frequency band change(add or remove) from other producers. 3. Call the `amd_wbrf_retrieve_freq_band` initially to retrieve current active frequency bands considering some producers may broadcast such information before the consumer is up. 4. On receiving a notification for frequency band change, run `amd_wbrf_retrieve_freq_band` again to retrieve the latest active frequency bands. 5. During driver cleanup, call `amd_wbrf_unregister_notifier` to unregister the notifier.

---

# WMI Driver API

_Peios Kernel / Hardware and drivers / Driver development / Clocks, signals and platform services_

> The WMI driver core supports a more modern bus-based interface for interacting with WMI devices, and an older GUID-based interface. The latter interface is considered to be deprecated, so new WMI drivers should generally avoid it since it…

<a id="rst-wmi-driver-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0-or-later -->

The WMI driver core supports a more modern bus-based interface for interacting with WMI devices, and an older GUID-based interface. The latter interface is considered to be deprecated, so new WMI drivers should generally avoid it since it has some issues with multiple WMI devices sharing the same GUID. The modern bus-based interface instead maps each WMI device to a `struct wmi_device <wmi_device>`, so it supports WMI devices sharing the same GUID. Drivers can then register a `struct wmi_driver <wmi_driver>` which will be bound to compatible WMI devices by the driver core.


#### <a id="c-struct-wmi_device"></a>`struct wmi_device`

WMI device structure

**Definition**

```c
struct wmi_device {
    struct device dev;
    bool setable;
    const char *driver_override;
};
```

**Members**

- `dev`: Device associated with this WMI device
- `setable`: True for devices implementing the Set Control Method
- `driver_override`: Driver name to force a match; do not set directly,
  because core frees it; use [`driver_set_override()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-driver_set_override) to
  set or clear it.

**Description**

This represents WMI devices discovered by the WMI driver core.

#### <a id="c-to_wmi_device"></a>`to_wmi_device()`

```c
to_wmi_device(device)
```

Helper macro to cast a device to a wmi_device

**Parameters**

- `device`: device struct

**Description**

Cast a struct device to a struct wmi_device.

#### <a id="c-struct-wmi_buffer"></a>`struct wmi_buffer`

WMI data buffer

**Definition**

```c
struct wmi_buffer {
    size_t length;
    void *data;
};
```

**Members**

- `length`: Buffer length in bytes
- `data`: Pointer to the buffer content

**Description**

This structure is used to exchange data with the WMI driver core.

#### <a id="c-struct-wmi_string"></a>`struct wmi_string`

WMI string representation

**Definition**

```c
struct wmi_string {
    __le16 length;
    __le16 chars[];
};
```

**Members**

- `length`: Size of **chars** in bytes
- `chars`: UTF16-LE characters with optional nul termination and padding

**Description**

This structure is used when exchanging string data over the WMI interface.

#### <a id="c-struct-wmi_driver"></a>`struct wmi_driver`

WMI driver structure

**Definition**

```c
struct wmi_driver {
    struct device_driver driver;
    const struct wmi_device_id *id_table;
    bool no_notify_data;
    bool no_singleton;
    int (*probe)(struct wmi_device *wdev, const void *context);
    void (*remove)(struct wmi_device *wdev);
    void (*shutdown)(struct wmi_device *wdev);
    void (*notify)(struct wmi_device *device, union acpi_object *data);
    void (*notify_new)(struct wmi_device *device, const struct wmi_buffer *data);
};
```

**Members**

- `driver`: Driver model structure
- `id_table`: List of WMI GUIDs supported by this driver
- `no_notify_data`: Driver supports WMI events which provide no event data
- `no_singleton`: Driver can be instantiated multiple times
- `probe`: Callback for device binding
- `remove`: Callback for device unbinding
- `shutdown`: Callback for device shutdown
- `notify`: Callback for receiving WMI events (deprecated)
- `notify_new`: Callback for receiving WMI events

**Description**

This represents WMI drivers which handle WMI devices. The data inside the buffer
passed to the **notify_new** callback is guaranteed to be aligned on a 8-byte boundary.

#### <a id="c-to_wmi_driver"></a>`to_wmi_driver()`

```c
to_wmi_driver(drv)
```

Helper macro to cast a driver to a wmi_driver

**Parameters**

- `drv`: driver struct

**Description**

Cast a struct device_driver to a struct wmi_driver.

#### <a id="c-wmi_driver_register"></a>`wmi_driver_register()`

```c
wmi_driver_register(driver)
```

Helper macro to register a WMI driver

**Parameters**

- `driver`: wmi_driver struct

**Description**

Helper macro for registering a WMI driver. It automatically passes
THIS_MODULE to the underlying function.

#### <a id="c-module_wmi_driver"></a>`module_wmi_driver()`

```c
module_wmi_driver(__wmi_driver)
```

Helper macro to register/unregister a WMI driver

**Parameters**

- `__wmi_driver`: wmi_driver struct

**Description**

Helper macro for WMI drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit).



#### <a id="c-wmi_string_to_utf8s"></a>`wmi_string_to_utf8s()`

```c
ssize_t wmi_string_to_utf8s(const struct wmi_string *str, u8 *dst, size_t length)
```

Convert a WMI string into a UTF8 string.

**Parameters**

- `const struct wmi_string *str`: WMI string representation
- `u8 *dst`: Buffer to fill with UTF8 characters
- `size_t length`: Length of the destination buffer

**Description**

Convert as WMI string into a standard UTF8 string. The conversion will stop
once a NUL character is detected or when the buffer is full. Any invalid UTF16
characters will be ignored. The resulting UTF8 string will always be NUL-terminated
when this function returns successfully.

**Return**

Length of the resulting UTF8 string or negative errno code on failure.

#### <a id="c-wmi_string_from_utf8s"></a>`wmi_string_from_utf8s()`

```c
ssize_t wmi_string_from_utf8s(struct wmi_string *str, size_t max_chars, const u8 *src, size_t src_length)
```

Convert a UTF8 string into a WMI string.

**Parameters**

- `struct wmi_string *str`: WMI string representation
- `size_t max_chars`: Maximum number of UTF16 code points to store inside the WMI string
- `const u8 *src`: UTF8 string to convert
- `size_t src_length`: Length of the source string without any trailing NUL-characters

**Description**

Convert a UTF8 string into a WMI string. The conversion will stop when the WMI string is
full. The resulting WMI string will always be NUL-terminated and have its length field set
to and appropriate value when this function returns successfully.

**Return**

Number of UTF16 code points inside the WMI string or negative errno code on failure.



#### <a id="c-wmi_instance_count"></a>`wmi_instance_count()`

```c
int wmi_instance_count(const char *guid_string)
```

Get number of WMI object instances

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba

**Description**

Get the number of WMI object instances.

**Return**

Number of WMI object instances or negative error code.

#### <a id="c-wmidev_instance_count"></a>`wmidev_instance_count()`

```c
u8 wmidev_instance_count(struct wmi_device *wdev)
```

Get number of WMI object instances

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver

**Description**

Get the number of WMI object instances.

**Return**

Number of WMI object instances.

#### <a id="c-wmi_evaluate_method"></a>`wmi_evaluate_method()`

```c
acpi_status wmi_evaluate_method(const char *guid_string, u8 instance, u32 method_id, const struct acpi_buffer *in, struct acpi_buffer *out)
```

Evaluate a WMI method (deprecated)

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
- `u8 instance`: Instance index
- `u32 method_id`: Method ID to call
- `const struct acpi_buffer *in`: Mandatory buffer containing input for the method call
- `struct acpi_buffer *out`: Empty buffer to return the method results

**Description**

Call an ACPI-WMI method, the caller must free **out**.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmidev_evaluate_method"></a>`wmidev_evaluate_method()`

```c
acpi_status wmidev_evaluate_method(struct wmi_device *wdev, u8 instance, u32 method_id, const struct acpi_buffer *in, struct acpi_buffer *out)
```

Evaluate a WMI method (deprecated)

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `u32 method_id`: Method ID to call
- `const struct acpi_buffer *in`: Mandatory buffer containing input for the method call
- `struct acpi_buffer *out`: Empty buffer to return the method results

**Description**

Call an ACPI-WMI method, the caller must free **out**.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmidev_invoke_method"></a>`wmidev_invoke_method()`

```c
int wmidev_invoke_method(struct wmi_device *wdev, u8 instance, u32 method_id, const struct wmi_buffer *in, struct wmi_buffer *out)
```

Invoke a WMI method

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `u32 method_id`: Method ID to call
- `const struct wmi_buffer *in`: Mandatory WMI buffer containing input for the method call
- `struct wmi_buffer *out`: Optional WMI buffer to return the method results

**Description**

Invoke a WMI method, the caller must free the resulting data inside **out**.
Said data is guaranteed to be aligned on a 8-byte boundary.

**Return**

0 on success or negative error code on failure.

#### <a id="c-wmi_query_block"></a>`wmi_query_block()`

```c
acpi_status wmi_query_block(const char *guid_string, u8 instance, struct acpi_buffer *out)
```

Return contents of a WMI block (deprecated)

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
- `u8 instance`: Instance index
- `struct acpi_buffer *out`: Empty buffer to return the contents of the data block to

**Description**

Query a ACPI-WMI block, the caller must free **out**.

**Return**

ACPI object containing the content of the WMI block.

#### <a id="c-wmidev_block_query"></a>`wmidev_block_query()`

```c
union acpi_object * wmidev_block_query(struct wmi_device *wdev, u8 instance)
```

Return contents of a WMI block (deprectated)

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index

**Description**

Query an ACPI-WMI block, the caller must free the result.

**Return**

ACPI object containing the content of the WMI block.

#### <a id="c-wmidev_query_block"></a>`wmidev_query_block()`

```c
int wmidev_query_block(struct wmi_device *wdev, u8 instance, struct wmi_buffer *out)
```

Return contents of a WMI data block

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `struct wmi_buffer *out`: WMI buffer to fill

**Description**

Query a WMI data block, the caller must free the resulting data inside **out**.
Said data is guaranteed to be aligned on a 8-byte boundary.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-wmi_set_block"></a>`wmi_set_block()`

```c
acpi_status wmi_set_block(const char *guid_string, u8 instance, const struct acpi_buffer *in)
```

Write to a WMI block (deprecated)

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
- `u8 instance`: Instance index
- `const struct acpi_buffer *in`: Buffer containing new values for the data block

**Description**

Write the contents of the input buffer to an ACPI-WMI data block.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmidev_block_set"></a>`wmidev_block_set()`

```c
acpi_status wmidev_block_set(struct wmi_device *wdev, u8 instance, const struct acpi_buffer *in)
```

Write to a WMI block (deprecated)

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `const struct acpi_buffer *in`: Buffer containing new values for the data block

**Description**

Write contents of the input buffer to an ACPI-WMI data block.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmidev_set_block"></a>`wmidev_set_block()`

```c
int wmidev_set_block(struct wmi_device *wdev, u8 instance, const struct wmi_buffer *in)
```

Write to a WMI data block

**Parameters**

- `struct wmi_device *wdev`: A wmi bus device from a driver
- `u8 instance`: Instance index
- `const struct wmi_buffer *in`: WMI buffer containing new values for the data block

**Description**

Write the content of **in** into a WMI data block.

**Return**

0 on success or negative error code on failure.

#### <a id="c-wmi_install_notify_handler"></a>`wmi_install_notify_handler()`

```c
acpi_status wmi_install_notify_handler(const char *guid, wmi_notify_handler handler, void *data)
```

Register handler for WMI events (deprecated)

**Parameters**

- `const char *guid`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
- `wmi_notify_handler handler`: Function to handle notifications
- `void *data`: Data to be returned to handler when event is fired

**Description**

Register a handler for events sent to the ACPI-WMI mapper device.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmi_remove_notify_handler"></a>`wmi_remove_notify_handler()`

```c
acpi_status wmi_remove_notify_handler(const char *guid)
```

Unregister handler for WMI events (deprecated)

**Parameters**

- `const char *guid`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba

**Description**

Unregister handler for events sent to the ACPI-WMI mapper device.

**Return**

acpi_status signaling success or error.

#### <a id="c-wmi_has_guid"></a>`wmi_has_guid()`

```c
bool wmi_has_guid(const char *guid_string)
```

Check if a GUID is available

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba

**Description**

Check if a given GUID is defined by _WDG.

**Return**

True if GUID is available, false otherwise.

#### <a id="c-wmi_get_acpi_device_uid"></a>`wmi_get_acpi_device_uid()`

```c
char * wmi_get_acpi_device_uid(const char *guid_string)
```

Get _UID name of ACPI device that defines GUID (deprecated)

**Parameters**

- `const char *guid_string`: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba

**Description**

Find the _UID of ACPI device associated with this WMI GUID.

**Return**

The ACPI _UID field value or NULL if the WMI GUID was not found.

#### <a id="c-wmi_driver_unregister"></a>`wmi_driver_unregister()`

```c
void wmi_driver_unregister(struct wmi_driver *driver)
```

Unregister a WMI driver

**Parameters**

- `struct wmi_driver *driver`: WMI driver to unregister

**Description**

Unregisters a WMI driver from the WMI bus.

---

# DMAEngine documentation

_Peios Kernel / Hardware and drivers / Driver development / DMA engines_

> DMAEngine documentation provides documents for various aspects of DMAEngine framework.

<a id="rst-dmaengine-documentation"></a>

DMAEngine documentation provides documents for various aspects of DMAEngine framework.

<a id="rst-dmaengine-development-documentation"></a>

## DMAEngine development documentation

This book helps with DMAengine internal APIs and guide for DMAEngine device driver writers.

- [DMAengine controller documentation](</kernel/hardware/driver-api/dmaengine/provider.md>)

<a id="rst-dmaengine-client-documentation"></a>

## DMAEngine client documentation

This book is a guide to device driver writers on how to use the Slave-DMA API of the DMAEngine. This is applicable only for slave DMA usage only.

- [DMA Engine API Guide](</kernel/hardware/driver-api/dmaengine/client.md>)

<a id="rst-dma-test-documentation"></a>

## DMA Test documentation

This book introduces how to test DMA drivers using dmatest module.

- [DMA Test Guide](</kernel/hardware/driver-api/dmaengine/dmatest.md>)

<a id="rst-pxa-dma-documentation"></a>

## PXA DMA documentation

This book adds some notes about PXA DMA

- [PXA/MMP - DMA Slave controller](</kernel/hardware/driver-api/dmaengine/pxa-dma.md>)

---

# DMA Engine API Guide

_Peios Kernel / Hardware and drivers / Driver development / DMA engines_

> Vinod Koul <vinod dot koul at intel.com>

<a id="rst-dma-engine-api-guide"></a>

Vinod Koul &lt;vinod dot koul at intel.com&gt;

> [!NOTE]
>
> For DMA Engine usage in async_tx please see: `Documentation/crypto/async-tx-api.rst`

Below is a guide to device driver writers on how to use the Slave-DMA API of the DMA Engine. This is applicable only for slave DMA usage only.

<a id="rst-dma-usage"></a>

## DMA usage

The slave DMA usage consists of following steps:

- Allocate a DMA slave channel

- Set slave and controller specific parameters

- Get a descriptor for transaction

- Submit the transaction

- Issue pending requests and wait for callback notification

The details of these operations are:

1. Allocate a DMA slave channel

   Channel allocation is slightly different in the slave DMA context, client drivers typically need a channel from a particular DMA controller only and even in some cases a specific channel is desired. To request a channel dma_request_chan() API is used.

   Interface:



   ```c
   struct dma_chan *dma_request_chan(struct device *dev, const char *name);
   ```

   Which will find and return the `name` DMA channel associated with the 'dev' device. The association is done via DT, ACPI or board file based dma_slave_map matching table.

   A channel allocated via this interface is exclusive to the caller, until dma_release_channel() is called.

2. Set slave and controller specific parameters

   Next step is always to pass some specific information to the DMA driver. Most of the generic information which a slave DMA can use is in struct dma_slave_config. This allows the clients to specify DMA direction, DMA addresses, bus widths, DMA burst lengths etc for the peripheral.

   If some DMA controllers have more parameters to be sent then they should try to embed struct dma_slave_config in their controller specific structure. That gives flexibility to client to pass more parameters, if required.

   Interface:



   ```c
   int dmaengine_slave_config(struct dma_chan *chan,
                     struct dma_slave_config *config)
   ```

   Please see the dma_slave_config structure definition in dmaengine.h for a detailed explanation of the struct members. Please note that the 'direction' member will be going away as it duplicates the direction given in the prepare call.

3. Get a descriptor for transaction

> For slave usage the various modes of slave transfers supported by the DMA-engine are:
>
> - slave_sg: DMA a list of scatter gather buffers from/to a peripheral
>
> - peripheral_dma_vec: DMA an array of scatter gather buffers from/to a peripheral. Similar to slave_sg, but uses an array of dma_vec structures instead of a scatterlist.
>
> - dma_cyclic: Perform a cyclic DMA operation from/to a peripheral till the operation is explicitly stopped.
>
> - interleaved_dma: This is common to Slave as well as M2M clients. For slave address of devices' fifo could be already known to the driver. Various types of operations could be expressed by setting appropriate values to the 'dma_interleaved_template' members. Cyclic interleaved DMA transfers are also possible if supported by the channel by setting the DMA_PREP_REPEAT transfer flag.
>
> A non-NULL return of this transfer API represents a "descriptor" for the given transaction.
>
> Interface:
>
>
>
> ```c
> struct dma_async_tx_descriptor *dmaengine_prep_slave_sg(
>            struct dma_chan *chan, struct scatterlist *sgl,
>            unsigned int sg_len, enum dma_data_direction direction,
>            unsigned long flags);
>
> struct dma_async_tx_descriptor *dmaengine_prep_peripheral_dma_vec(
>            struct dma_chan *chan, const struct dma_vec *vecs,
>            size_t nents, enum dma_data_direction direction,
>            unsigned long flags);
>
> struct dma_async_tx_descriptor *dmaengine_prep_dma_cyclic(
>            struct dma_chan *chan, dma_addr_t buf_addr, size_t buf_len,
>            size_t period_len, enum dma_data_direction direction);
>
> struct dma_async_tx_descriptor *dmaengine_prep_interleaved_dma(
>            struct dma_chan *chan, struct dma_interleaved_template *xt,
>            unsigned long flags);
> ```
>
> The peripheral driver is expected to have mapped the scatterlist for the DMA operation prior to calling dmaengine_prep_slave_sg(), and must keep the scatterlist mapped until the DMA operation has completed. The scatterlist must be mapped using the DMA struct device. If a mapping needs to be synchronized later, dma_sync\_\*\_for\_\*() must be called using the DMA struct device, too. So, normal setup should look like this:
>
>
>
> ```c
> struct device *dma_dev = dmaengine_get_dma_device(chan);
>
> nr_sg = dma_map_sg(dma_dev, sgl, sg_len);
>    if (nr_sg == 0)
>            /* error */
>
>    desc = dmaengine_prep_slave_sg(chan, sgl, nr_sg, direction, flags);
> ```
>
> Once a descriptor has been obtained, the callback information can be added and the descriptor must then be submitted. Some DMA engine drivers may hold a spinlock between a successful preparation and submission so it is important that these two operations are closely paired.
>
> > [!NOTE]
> >
> > Although the async_tx API specifies that completion callback routines cannot submit any new operations, this is not the case for slave/cyclic DMA.
> >
> > For slave DMA, the subsequent transaction may not be available for submission prior to callback function being invoked, so slave DMA callbacks are permitted to prepare and submit a new transaction.
> >
> > For cyclic DMA, a callback function may wish to terminate the DMA via dmaengine_terminate_async().
> >
> > Therefore, it is important that DMA engine drivers drop any locks before calling the callback function which may cause a deadlock.
> >
> > Note that callbacks will always be invoked from the DMA engines tasklet, never from interrupt context.
>
> **Optional: per descriptor metadata**
>
> DMAengine provides two ways for metadata support.
>
> DESC_METADATA_CLIENT
>
> > The metadata buffer is allocated/provided by the client driver and it is attached to the descriptor.
>
>
>
> ```c
> int dmaengine_desc_attach_metadata(struct dma_async_tx_descriptor *desc,
>                               void *data, size_t len);
> ```
>
> DESC_METADATA_ENGINE
>
> > The metadata buffer is allocated/managed by the DMA driver. The client driver can ask for the pointer, maximum size and the currently used size of the metadata and can directly update or read it.
> >
> > Because the DMA driver manages the memory area containing the metadata, clients must make sure that they do not try to access or get the pointer after their transfer completion callback has run for the descriptor. If no completion callback has been defined for the transfer, then the metadata must not be accessed after issue_pending. In other words: if the aim is to read back metadata after the transfer is completed, then the client must use completion callback.
>
>
>
> ```c
> void *dmaengine_desc_get_metadata_ptr(struct dma_async_tx_descriptor *desc,
>            size_t *payload_len, size_t *max_len);
>
> int dmaengine_desc_set_metadata_len(struct dma_async_tx_descriptor *desc,
>            size_t payload_len);
> ```
>
> Client drivers can query if a given mode is supported with:
>
>
>
> ```c
> bool dmaengine_is_metadata_mode_supported(struct dma_chan *chan,
>            enum dma_desc_metadata_mode mode);
> ```
>
> Depending on the used mode client drivers must follow different flow.
>
> DESC_METADATA_CLIENT
>
> > - DMA_MEM_TO_DEV / DEV_MEM_TO_MEM:
> >
> >   1. prepare the descriptor (dmaengine_prep\_\*) construct the metadata in the client's buffer
> >
> >   2. use dmaengine_desc_attach_metadata() to attach the buffer to the descriptor
> >
> >   3. submit the transfer
> >
> > - DMA_DEV_TO_MEM:
> >
> >   1. prepare the descriptor (dmaengine_prep\_\*)
> >
> >   2. use dmaengine_desc_attach_metadata() to attach the buffer to the descriptor
> >
> >   3. submit the transfer
> >
> >   4. when the transfer is completed, the metadata should be available in the attached buffer
>
> DESC_METADATA_ENGINE
>
> > - DMA_MEM_TO_DEV / DEV_MEM_TO_MEM:
> >
> >   1. prepare the descriptor (dmaengine_prep\_\*)
> >
> >   2. use dmaengine_desc_get_metadata_ptr() to get the pointer to the engine's metadata area
> >
> >   3. update the metadata at the pointer
> >
> >   4. use dmaengine_desc_set_metadata_len()  to tell the DMA engine the amount of data the client has placed into the metadata buffer
> >
> >   5. submit the transfer
> >
> > - DMA_DEV_TO_MEM:
> >
> >   1. prepare the descriptor (dmaengine_prep\_\*)
> >
> >   2. submit the transfer
> >
> >   3. on transfer completion, use dmaengine_desc_get_metadata_ptr() to get the pointer to the engine's metadata area
> >
> >   4. read out the metadata from the pointer
>
> > [!NOTE]
> >
> > When DESC_METADATA_ENGINE mode is used the metadata area for the descriptor is no longer valid after the transfer has been completed (valid up to the point when the completion callback returns if used).
> >
> > Mixed use of DESC_METADATA_CLIENT / DESC_METADATA_ENGINE is not allowed, client drivers must use either of the modes per descriptor.

4. Submit the transaction

   Once the descriptor has been prepared and the callback information added, it must be placed on the DMA engine drivers pending queue.

   Interface:



   ```c
   dma_cookie_t dmaengine_submit(struct dma_async_tx_descriptor *desc)
   ```

   This returns a cookie can be used to check the progress of DMA engine activity via other DMA engine calls not covered in this document.

   dmaengine_submit() will not start the DMA operation, it merely adds it to the pending queue. For this, see step 5, dma_async_issue_pending.

   > [!NOTE]
   >
   > After calling `dmaengine_submit()` the submitted transfer descriptor (`struct dma_async_tx_descriptor`) belongs to the DMA engine. Consequently, the client must consider invalid the pointer to that descriptor.

5. Issue pending DMA requests and wait for callback notification

   The transactions in the pending queue can be activated by calling the issue_pending API. If channel is idle then the first transaction in queue is started and subsequent ones queued up.

   On completion of each DMA operation, the next in queue is started and a tasklet triggered. The tasklet will then call the client driver completion callback routine for notification, if set.

   Interface:



   ```c
   void dma_async_issue_pending(struct dma_chan *chan);
   ```

<a id="rst-further-apis"></a>

### Further APIs

1. Terminate APIs



   ```c
   int dmaengine_terminate_sync(struct dma_chan *chan)
   int dmaengine_terminate_async(struct dma_chan *chan)
   int dmaengine_terminate_all(struct dma_chan *chan) /* DEPRECATED */
   ```

   This causes all activity for the DMA channel to be stopped, and may discard data in the DMA FIFO which hasn't been fully transferred. No callback functions will be called for any incomplete transfers.

   Two variants of this function are available.

   dmaengine_terminate_async() might not wait until the DMA has been fully stopped or until any running complete callbacks have finished. But it is possible to call dmaengine_terminate_async() from atomic context or from within a complete callback. dmaengine_synchronize() must be called before it is safe to free the memory accessed by the DMA transfer or free resources accessed from within the complete callback.

   dmaengine_terminate_sync() will wait for the transfer and any running complete callbacks to finish before it returns. But the function must not be called from atomic context or from within a complete callback.

   dmaengine_terminate_all() is deprecated and should not be used in new code.

2. Pause API



   ```c
   int dmaengine_pause(struct dma_chan *chan)
   ```

   This pauses activity on the DMA channel without data loss.

3. Resume API



   ```c
   int dmaengine_resume(struct dma_chan *chan)
   ```

   Resume a previously paused DMA channel. It is invalid to resume a channel which is not currently paused.

4. Check Txn complete



   ```c
   enum dma_status dma_async_is_tx_complete(struct dma_chan *chan,
             dma_cookie_t cookie, dma_cookie_t *last, dma_cookie_t *used)
   ```

   This can be used to check the status of the channel. Please see the documentation in include/linux/dmaengine.h for a more complete description of this API.

   This can be used in conjunction with dma_async_is_complete() and the cookie returned from dmaengine_submit() to check for completion of a specific DMA transaction.

   > [!NOTE]
   >
   > Not all DMA engine drivers can return reliable information for a running DMA channel. It is recommended that DMA engine users pause or stop (via dmaengine_terminate_all()) the channel before using this API.

5. Synchronize termination API



   ```c
   void dmaengine_synchronize(struct dma_chan *chan)
   ```

   Synchronize the termination of the DMA channel to the current context.

   This function should be used after dmaengine_terminate_async() to synchronize the termination of the DMA channel to the current context. The function will wait for the transfer and any running complete callbacks to finish before it returns.

   If dmaengine_terminate_async() is used to stop the DMA channel this function must be called before it is safe to free memory accessed by previously submitted descriptors or to free any resources accessed within the complete callback of previously submitted descriptors.

   The behavior of this function is undefined if dma_async_issue_pending() has been called between dmaengine_terminate_async() and this function.

---

# DMA Test Guide

_Peios Kernel / Hardware and drivers / Driver development / DMA engines_

> Andy Shevchenko <andriy.shevchenko@linux.intel.com>

<a id="rst-dma-test-guide"></a>

Andy Shevchenko &lt;[andriy.shevchenko@linux.intel.com](<mailto:andriy.shevchenko@linux.intel.com>)&gt;

This small document introduces how to test DMA drivers using dmatest module.

The dmatest module tests DMA memcpy, memset, XOR and RAID6 P+Q operations using various lengths and various offsets into the source and destination buffers. It will initialize both buffers with a repeatable pattern and verify that the DMA engine copies the requested region and nothing more. It will also verify that the bytes aren't swapped around, and that the source buffer isn't modified.

The dmatest module can be configured to test a specific channel. It can also test multiple channels at the same time, and it can start multiple threads competing for the same channel.

> [!NOTE]
>
> The test suite works only on the channels that have at least one capability of the following: DMA_MEMCPY (memory-to-memory), DMA_MEMSET (const-to-memory or memory-to-memory, when emulated), DMA_XOR, DMA_PQ.

> [!NOTE]
>
> In case of any related questions use the official mailing list [dmaengine@vger.kernel.org](<mailto:dmaengine@vger.kernel.org>).

<a id="rst-part-1-how-to-build-the-test-module"></a>

## Part 1 - How to build the test module

The menuconfig contains an option that could be found by following path:

> Device Drivers -&gt; DMA Engine support -&gt; DMA Test client

In the configuration file the option called CONFIG_DMATEST. The dmatest could be built as module or inside kernel. Let's consider those cases.

<a id="rst-part-2-when-dmatest-is-built-as-a-module"></a>

## Part 2 - When dmatest is built as a module

Example of usage:



```text
% modprobe dmatest timeout=2000 iterations=1 channel=dma0chan0 run=1
```

...or:



```text
% modprobe dmatest
% echo 2000 > /sys/module/dmatest/parameters/timeout
% echo 1 > /sys/module/dmatest/parameters/iterations
% echo dma0chan0 > /sys/module/dmatest/parameters/channel
% echo 1 > /sys/module/dmatest/parameters/run
```

...or on the kernel command line:



```text
dmatest.timeout=2000 dmatest.iterations=1 dmatest.channel=dma0chan0 dmatest.run=1
```

Example of multi-channel test usage (new in the 5.0 kernel):



```text
% modprobe dmatest
% echo 2000 > /sys/module/dmatest/parameters/timeout
% echo 1 > /sys/module/dmatest/parameters/iterations
% echo dma0chan0 > /sys/module/dmatest/parameters/channel
% echo dma0chan1 > /sys/module/dmatest/parameters/channel
% echo dma0chan2 > /sys/module/dmatest/parameters/channel
% echo 1 > /sys/module/dmatest/parameters/run
```

> [!NOTE]
>
> For all tests, starting in the 5.0 kernel, either single- or multi-channel, the channel parameter(s) must be set after all other parameters. It is at that time that the existing parameter values are acquired for use by the thread(s). All other parameters are shared. Therefore, if changes are made to any of the other parameters, and an additional channel specified, the (shared) parameters used for all threads will use the new values. After the channels are specified, each thread is set as pending. All threads begin execution when the run parameter is set to 1.

> [!TIP]
>
> A list of available channels can be found by running the following command:
>
>
>
> ```text
> % ls -1 /sys/class/dma/
> ```

Once started a message like " dmatest: Added 1 threads using dma0chan0" is emitted. A thread for that specific channel is created and is now pending, the pending thread is started once run is to 1.

Note that running a new test will not stop any in progress test.

The following command returns the state of the test.



```text
% cat /sys/module/dmatest/parameters/run
```

To wait for test completion userspace can poll 'run' until it is false, or use the wait parameter. Specifying 'wait=1' when loading the module causes module initialization to pause until a test run has completed, while reading /sys/module/dmatest/parameters/wait waits for any running test to complete before returning. For example, the following scripts wait for 42 tests to complete before exiting. Note that if 'iterations' is set to 'infinite' then waiting is disabled.

Example:



```text
% modprobe dmatest run=1 iterations=42 wait=1
% modprobe -r dmatest
```

...or:



```text
% modprobe dmatest run=1 iterations=42
% cat /sys/module/dmatest/parameters/wait
% modprobe -r dmatest
```

<a id="rst-part-3-when-built-in-in-the-kernel"></a>

## Part 3 - When built-in in the kernel

The module parameters that is supplied to the kernel command line will be used for the first performed test. After user gets a control, the test could be re-run with the same or different parameters. For the details see the above section [Part 2 - When dmatest is built as a module](<#rst-part-2-when-dmatest-is-built-as-a-module>).

In both cases the module parameters are used as the actual values for the test case. You always could check them at run-time by running



```text
% grep -H . /sys/module/dmatest/parameters/*
```

<a id="rst-part-4-gathering-the-test-results"></a>

## Part 4 - Gathering the test results

Test results are printed to the kernel log buffer with the format:



```text
"dmatest: result <channel>: <test id>: '<error msg>' with src_off=<val> dst_off=<val> len=<val> (<err code>)"
```

Example of output:



```text
% dmesg | tail -n 1
dmatest: result dma0chan0-copy0: #1: No errors with src_off=0x7bf dst_off=0x8ad len=0x3fea (0)
```

The message format is unified across the different types of errors. A number in the parentheses represents additional information, e.g. error code, error counter, or status. A test thread also emits a summary line at completion listing the number of tests executed, number that failed, and a result code.

Example:



```text
% dmesg | tail -n 1
dmatest: dma0chan0-copy0: summary 1 test, 0 failures 1000 iops 100000 KB/s (0)
```

The details of a data miscompare error are also emitted, but do not follow the above format.

<a id="rst-part-5-handling-channel-allocation"></a>

## Part 5 - Handling channel allocation

<a id="rst-allocating-channels"></a>

### Allocating Channels

Channels do not need to be configured prior to starting a test run. Attempting to run the test without configuring the channels will result in testing any channels that are available.

Example:



```text
% echo 1 > /sys/module/dmatest/parameters/run
dmatest: No channels configured, continue with any
```

Channels are registered using the "channel" parameter. Channels can be requested by their name, once requested, the channel is registered and a pending thread is added to the test list.

Example:



```text
% echo dma0chan2 > /sys/module/dmatest/parameters/channel
dmatest: Added 1 threads using dma0chan2
```

More channels can be added by repeating the example above. Reading back the channel parameter will return the name of last channel that was added successfully.

Example:



```text
% echo dma0chan1 > /sys/module/dmatest/parameters/channel
dmatest: Added 1 threads using dma0chan1
% echo dma0chan2 > /sys/module/dmatest/parameters/channel
dmatest: Added 1 threads using dma0chan2
% cat /sys/module/dmatest/parameters/channel
dma0chan2
```

Another method of requesting channels is to request a channel with an empty string, Doing so will request all channels available to be tested:

Example:



```text
% echo "" > /sys/module/dmatest/parameters/channel
dmatest: Added 1 threads using dma0chan0
dmatest: Added 1 threads using dma0chan3
dmatest: Added 1 threads using dma0chan4
dmatest: Added 1 threads using dma0chan5
dmatest: Added 1 threads using dma0chan6
dmatest: Added 1 threads using dma0chan7
dmatest: Added 1 threads using dma0chan8
```

At any point during the test configuration, reading the "test_list" parameter will print the list of currently pending tests.

Example:



```text
% cat /sys/module/dmatest/parameters/test_list
dmatest: 1 threads using dma0chan0
dmatest: 1 threads using dma0chan3
dmatest: 1 threads using dma0chan4
dmatest: 1 threads using dma0chan5
dmatest: 1 threads using dma0chan6
dmatest: 1 threads using dma0chan7
dmatest: 1 threads using dma0chan8
```

Note: Channels will have to be configured for each test run as channel configurations do not carry across to the next test run.

<a id="rst-releasing-channels"></a>

### Releasing Channels

Channels can be freed by setting run to 0.

Example:



```text
% echo dma0chan1 > /sys/module/dmatest/parameters/channel
dmatest: Added 1 threads using dma0chan1
% cat /sys/class/dma/dma0chan1/in_use
1
% echo 0 > /sys/module/dmatest/parameters/run
% cat /sys/class/dma/dma0chan1/in_use
0
```

Channels allocated by previous test runs are automatically freed when a new channel is requested after completing a successful test run.

---

# DMAengine controller documentation

_Peios Kernel / Hardware and drivers / Driver development / DMA engines_

> Most of the Slave DMA controllers have the same general principles of operations.

<a id="rst-dmaengine-controller-documentation"></a>

<a id="rst-hardware-introduction"></a>

## Hardware Introduction

Most of the Slave DMA controllers have the same general principles of operations.

They have a given number of channels to use for the DMA transfers, and a given number of requests lines.

Requests and channels are pretty much orthogonal. Channels can be used to serve several to any requests. To simplify, channels are the entities that will be doing the copy, and requests what endpoints are involved.

The request lines actually correspond to physical lines going from the DMA-eligible devices to the controller itself. Whenever the device will want to start a transfer, it will assert a DMA request (DRQ) by asserting that request line.

A very simple DMA controller would only take into account a single parameter: the transfer size. At each clock cycle, it would transfer a byte of data from one buffer to another, until the transfer size has been reached.

That wouldn't work well in the real world, since slave devices might require a specific number of bits to be transferred in a single cycle. For example, we may want to transfer as much data as the physical bus allows to maximize performances when doing a simple memory copy operation, but our audio device could have a narrower FIFO that requires data to be written exactly 16 or 24 bits at a time. This is why most if not all of the DMA controllers can adjust this, using a parameter called the transfer width.

Moreover, some DMA controllers, whenever the RAM is used as a source or destination, can group the reads or writes in memory into a buffer, so instead of having a lot of small memory accesses, which is not really efficient, you'll get several bigger transfers. This is done using a parameter called the burst size, that defines how many single reads/writes it's allowed to do without the controller splitting the transfer into smaller sub-transfers.

Our theoretical DMA controller would then only be able to do transfers that involve a single contiguous block of data. However, some of the transfers we usually have are not, and want to copy data from non-contiguous buffers to a contiguous buffer, which is called scatter-gather.

DMAEngine, at least for mem2dev transfers, require support for scatter-gather. So we're left with two cases here: either we have a quite simple DMA controller that doesn't support it, and we'll have to implement it in software, or we have a more advanced DMA controller, that implements in hardware scatter-gather.

The latter are usually programmed using a collection of chunks to transfer, and whenever the transfer is started, the controller will go over that collection, doing whatever we programmed there.

This collection is usually either a table or a linked list. You will then push either the address of the table and its number of elements, or the first item of the list to one channel of the DMA controller, and whenever a DRQ will be asserted, it will go through the collection to know where to fetch the data from.

Either way, the format of this collection is completely dependent on your hardware. Each DMA controller will require a different structure, but all of them will require, for every chunk, at least the source and destination addresses, whether it should increment these addresses or not and the three parameters we saw earlier: the burst size, the transfer width and the transfer size.

The one last thing is that usually, slave devices won't issue DRQ by default, and you have to enable this in your slave device driver first whenever you're willing to use DMA.

These were just the general memory-to-memory (also called mem2mem) or memory-to-device (mem2dev) kind of transfers. Most devices often support other kind of transfers or memory operations that dmaengine support and will be detailed later in this document.

<a id="rst-dma-support-in-linux"></a>

## DMA Support in Linux

Historically, DMA controller drivers have been implemented using the async TX API, to offload operations such as memory copy, XOR, cryptography, etc., basically any memory to memory operation.

Over time, the need for memory to device transfers arose, and dmaengine was extended. Nowadays, the async TX API is written as a layer on top of dmaengine, and acts as a client. Still, dmaengine accommodates that API in some cases, and made some design choices to ensure that it stayed compatible.

For more information on the Async TX API, please look the relevant documentation file in [Documentation/crypto/async-tx-api.rst](/kernel/internals/crypto/async-tx-api.md).

<a id="rst-dmaengine-apis"></a>

## DMAEngine APIs

<a id="rst-struct-dma-device-initialization"></a>

### `struct dma_device` Initialization

Just like any other kernel framework, the whole DMAEngine registration relies on the driver filling a structure and registering against the framework. In our case, that structure is dma_device.

The first thing you need to do in your driver is to allocate this structure. Any of the usual memory allocators will do, but you'll also need to initialize a few fields in there:

- `channels`: should be initialized as a list using the INIT_LIST_HEAD macro for example

- `src_addr_widths`: should contain a bitmask of the supported source transfer width

- `dst_addr_widths`: should contain a bitmask of the supported destination transfer width

- `directions`: should contain a bitmask of the supported slave directions (i.e. excluding mem2mem transfers)

- `residue_granularity`: granularity of the transfer residue reported to dma_set_residue. This can be either:

  - Descriptor: your device doesn't support any kind of residue reporting. The framework will only know that a particular transaction descriptor is done.

  - Segment: your device is able to report which chunks have been transferred

  - Burst: your device is able to report which burst have been transferred

- `dev`: should hold the pointer to the `struct device` associated to your current driver instance.

<a id="rst-supported-transaction-types"></a>

### Supported transaction types

The next thing you need is to set which transaction types your device (and driver) supports.

Our `dma_device structure` has a field called cap_mask that holds the various types of transaction supported, and you need to modify this mask using the dma_cap_set function, with various flags depending on transaction types you support as an argument.

All those capabilities are defined in the `dma_transaction_type enum`, in `include/linux/dmaengine.h`

Currently, the types available are:

- DMA_MEMCPY

  - The device is able to do memory to memory copies

  - No matter what the overall size of the combined chunks for source and destination is, only as many bytes as the smallest of the two will be transmitted. That means the number and size of the scatter-gather buffers in both lists need not be the same, and that the operation functionally is equivalent to a `strncpy` where the `count` argument equals the smallest total size of the two scatter-gather list buffers.

  - It's usually used for copying pixel data between host memory and memory-mapped GPU device memory, such as found on modern PCI video graphics cards. The most immediate example is the OpenGL API function `glReadPixels()`, which might require a verbatim copy of a huge framebuffer from local device memory onto host memory.

- DMA_XOR

  - The device is able to perform XOR operations on memory areas

  - Used to accelerate XOR intensive tasks, such as RAID5

- DMA_XOR_VAL

  - The device is able to perform parity check using the XOR algorithm against a memory buffer.

- DMA_PQ

  - The device is able to perform RAID6 P+Q computations, P being a simple XOR, and Q being a Reed-Solomon algorithm.

- DMA_PQ_VAL

  - The device is able to perform parity check using RAID6 P+Q algorithm against a memory buffer.

- DMA_MEMSET

  - The device is able to fill memory with the provided pattern

  - The pattern is treated as a single byte signed value.

- DMA_INTERRUPT

  - The device is able to trigger a dummy transfer that will generate periodic interrupts

  - Used by the client drivers to register a callback that will be called on a regular basis through the DMA controller interrupt

- DMA_PRIVATE

  - The devices only supports slave transfers, and as such isn't available for async transfers.

- DMA_ASYNC_TX

  - The device supports asynchronous memory-to-memory operations, including memcpy, memset, xor, pq, xor_val, and pq_val.

  - This capability is automatically set by the DMA engine framework and must not be configured manually by device drivers.

- DMA_SLAVE

  - The device can handle device to memory transfers, including scatter-gather transfers.

  - While in the mem2mem case we were having two distinct types to deal with a single chunk to copy or a collection of them, here, we just have a single transaction type that is supposed to handle both.

  - If you want to transfer a single contiguous memory buffer, simply build a scatter list with only one item.

- DMA_CYCLIC

  - The device can handle cyclic transfers.

  - A cyclic transfer is a transfer where the chunk collection will loop over itself, with the last item pointing to the first.

  - It's usually used for audio transfers, where you want to operate on a single ring buffer that you will fill with your audio data.

- DMA_INTERLEAVE

  - The device supports interleaved transfer.

  - These transfers can transfer data from a non-contiguous buffer to a non-contiguous buffer, opposed to DMA_SLAVE that can transfer data from a non-contiguous data set to a continuous destination buffer.

  - It's usually used for 2d content transfers, in which case you want to transfer a portion of uncompressed data directly to the display to print it

- DMA_COMPLETION_NO_ORDER

  - The device does not support in order completion.

  - The driver should return DMA_OUT_OF_ORDER for device_tx_status if the device is setting this capability.

  - All cookie tracking and checking API should be treated as invalid if the device exports this capability.

  - At this point, this is incompatible with polling option for dmatest.

  - If this cap is set, the user is recommended to provide an unique identifier for each descriptor sent to the DMA device in order to properly track the completion.

- DMA_REPEAT

  - The device supports repeated transfers. A repeated transfer, indicated by the DMA_PREP_REPEAT transfer flag, is similar to a cyclic transfer in that it gets automatically repeated when it ends, but can additionally be replaced by the client.

  - This feature is limited to interleaved transfers, this flag should thus not be set if the DMA_INTERLEAVE flag isn't set. This limitation is based on the current needs of DMA clients, support for additional transfer types should be added in the future if and when the need arises.

- DMA_LOAD_EOT

  - The device supports replacing repeated transfers at end of transfer (EOT) by queuing a new transfer with the DMA_PREP_LOAD_EOT flag set.

  - Support for replacing a currently running transfer at another point (such as end of burst instead of end of transfer) will be added in the future based on DMA clients needs, if and when the need arises.

These various types will also affect how the source and destination addresses change over time.

Addresses pointing to RAM are typically incremented (or decremented) after each transfer. In case of a ring buffer, they may loop (DMA_CYCLIC). Addresses pointing to a device's register (e.g. a FIFO) are typically fixed.

<a id="rst-per-descriptor-metadata-support"></a>

### Per descriptor metadata support

Some data movement architecture (DMA controller and peripherals) uses metadata associated with a transaction. The DMA controller role is to transfer the payload and the metadata alongside. The metadata itself is not used by the DMA engine itself, but it contains parameters, keys, vectors, etc for peripheral or from the peripheral.

The DMAengine framework provides a generic ways to facilitate the metadata for descriptors. Depending on the architecture the DMA driver can implement either or both of the methods and it is up to the client driver to choose which one to use.

- DESC_METADATA_CLIENT

  The metadata buffer is allocated/provided by the client driver and it is attached (via the dmaengine_desc_attach_metadata() helper to the descriptor.

  From the DMA driver the following is expected for this mode:

  - DMA_MEM_TO_DEV / DEV_MEM_TO_MEM

    The data from the provided metadata buffer should be prepared for the DMA controller to be sent alongside of the payload data. Either by copying to a hardware descriptor, or highly coupled packet.

  - DMA_DEV_TO_MEM

    On transfer completion the DMA driver must copy the metadata to the client provided metadata buffer before notifying the client about the completion. After the transfer completion, DMA drivers must not touch the metadata buffer provided by the client.

- DESC_METADATA_ENGINE

  The metadata buffer is allocated/managed by the DMA driver. The client driver can ask for the pointer, maximum size and the currently used size of the metadata and can directly update or read it. dmaengine_desc_get_metadata_ptr() and dmaengine_desc_set_metadata_len() is provided as helper functions.

  From the DMA driver the following is expected for this mode:

  - get_metadata_ptr()

    Should return a pointer for the metadata buffer, the maximum size of the metadata buffer and the currently used / valid (if any) bytes in the buffer.

  - set_metadata_len()

    It is called by the clients after it have placed the metadata to the buffer to let the DMA driver know the number of valid bytes provided.

  Note: since the client will ask for the metadata pointer in the completion callback (in DMA_DEV_TO_MEM case) the DMA driver must ensure that the descriptor is not freed up prior the callback is called.

<a id="rst-device-operations"></a>

### Device operations

Our dma_device structure also requires a few function pointers in order to implement the actual logic, now that we described what operations we were able to perform.

The functions that we have to fill in there, and hence have to implement, obviously depend on the transaction types you reported as supported.

- `device_alloc_chan_resources`

- `device_free_chan_resources`

  - These functions will be called whenever a driver will call `dma_request_channel` or `dma_release_channel` for the first/last time on the channel associated to that driver.

  - They are in charge of allocating/freeing all the needed resources in order for that channel to be useful for your driver.

  - These functions can sleep.

- `device_prep_dma_*`

  - These functions are matching the capabilities you registered previously.

  - These functions all take the buffer or the scatterlist relevant for the transfer being prepared, and should create a hardware descriptor or a list of hardware descriptors from it

  - These functions can be called from an interrupt context

  - Any allocation you might do should be using the GFP_NOWAIT flag, in order not to potentially sleep, but without depleting the emergency pool either.

  - Drivers should try to pre-allocate any memory they might need during the transfer setup at probe time to avoid putting to much pressure on the nowait allocator.

  - It should return a unique instance of the `dma_async_tx_descriptor structure`, that further represents this particular transfer.

  - This structure can be initialized using the function `dma_async_tx_descriptor_init`.

  - You'll also need to set following fields in this structure:

    - flags: TODO: Can it be modified by the driver itself, or should it be always the flags passed in the arguments

    - tx_submit: A pointer to a function you have to implement, that is supposed to push the current transaction descriptor to a pending queue, waiting for issue_pending to be called.

    - phys: Physical address of the descriptor which is used later by the dma engine to read the descriptor and initiate transfer.

  - In this structure the function pointer callback_result can be initialized in order for the submitter to be notified that a transaction has completed. In the earlier code the function pointer callback has been used. However it does not provide any status to the transaction and will be deprecated. The result structure defined as `dmaengine_result` that is passed in to callback_result has two fields:

    - result: This provides the transfer result defined by `dmaengine_tx_result`. Either success or some error condition.

    - residue: Provides the residue bytes of the transfer for those that support residue.

- `device_prep_peripheral_dma_vec`

  - Similar to `device_prep_slave_sg`, but it takes a pointer to a array of `dma_vec` structures, which (in the long run) will replace scatterlists.

- `device_issue_pending`

  - Takes the first transaction descriptor in the pending queue, and starts the transfer. Whenever that transfer is done, it should move to the next transaction in the list.

  - This function can be called in an interrupt context

- `device_tx_status`

  - Should report the bytes left to go over on the given channel

  - Should only care about the transaction descriptor passed as argument, not the currently active one on a given channel

  - The tx_state argument might be NULL

  - Should use dma_set_residue to report it

  - In the case of a cyclic transfer, it should only take into account the total size of the cyclic buffer.

  - Should return DMA_OUT_OF_ORDER if the device does not support in order completion and is completing the operation out of order.

  - This function can be called in an interrupt context.

- device_config

  - Reconfigures the channel with the configuration given as argument

  - This command should NOT perform synchronously, or on any currently queued transfers, but only on subsequent ones

  - In this case, the function will receive a `dma_slave_config` structure pointer as an argument, that will detail which configuration to use.

  - Even though that structure contains a direction field, this field is deprecated in favor of the direction argument given to the prep\_\* functions

  - This call is mandatory for slave operations only. This should NOT be set or expected to be set for memcpy operations. If a driver support both, it should use this call for slave operations only and not for memcpy ones.

- device_pause

  - Pauses a transfer on the channel

  - This command should operate synchronously on the channel, pausing right away the work of the given channel

- device_resume

  - Resumes a transfer on the channel

  - This command should operate synchronously on the channel, resuming right away the work of the given channel

- device_terminate_all

  - Aborts all the pending and ongoing transfers on the channel

  - For aborted transfers the complete callback should not be called

  - Can be called from atomic context or from within a complete callback of a descriptor. Must not sleep. Drivers must be able to handle this correctly.

  - Termination may be asynchronous. The driver does not have to wait until the currently active transfer has completely stopped. See device_synchronize.

- device_synchronize

  - Must synchronize the termination of a channel to the current context.

  - Must make sure that memory for previously submitted descriptors is no longer accessed by the DMA controller.

  - Must make sure that all complete callbacks for previously submitted descriptors have finished running and none are scheduled to run.

  - May sleep.

<a id="rst-misc-notes"></a>

## Misc notes

(stuff that should be documented, but don't really know where to put them)

`dma_run_dependencies`

- Should be called at the end of an async TX transfer, and can be ignored in the slave transfers case.

- Makes sure that dependent operations are run before marking it as complete.

dma_cookie_t

- it's a DMA transaction ID that will increment over time.

- Not really relevant any more since the introduction of `virt-dma` that abstracts it away.

dma_vec

- A small structure that contains a DMA address and length.

DMA_CTRL_ACK

- If clear, the descriptor cannot be reused by provider until the client acknowledges receipt, i.e. has a chance to establish any dependency chains

- This can be acked by invoking async_tx_ack()

- If set, does not mean descriptor can be reused

DMA_CTRL_REUSE

- If set, the descriptor can be reused after being completed. It should not be freed by provider if this flag is set.

- The descriptor should be prepared for reuse by invoking `dmaengine_desc_set_reuse()` which will set DMA_CTRL_REUSE.

- `dmaengine_desc_set_reuse()` will succeed only when channel support reusable descriptor as exhibited by capabilities

- As a consequence, if a device driver wants to skip the `dma_map_sg()` and `dma_unmap_sg()` in between 2 transfers, because the DMA'd data wasn't used, it can resubmit the transfer right after its completion.

- Descriptor can be freed in few ways

  - Clearing DMA_CTRL_REUSE by invoking `dmaengine_desc_clear_reuse()` and submitting for last txn

  - Explicitly invoking `dmaengine_desc_free()`, this can succeed only when DMA_CTRL_REUSE is already set

  - Terminating the channel

- DMA_PREP_CMD

  - If set, the client driver tells DMA controller that passed data in DMA API is command data.

  - Interpretation of command data is DMA controller specific. It can be used for issuing commands to other peripherals/register reads/register writes for which the descriptor should be in different format from normal data descriptors.

- DMA_PREP_REPEAT

  - If set, the transfer will be automatically repeated when it ends until a new transfer is queued on the same channel with the DMA_PREP_LOAD_EOT flag. If the next transfer to be queued on the channel does not have the DMA_PREP_LOAD_EOT flag set, the current transfer will be repeated until the client terminates all transfers.

  - This flag is only supported if the channel reports the DMA_REPEAT capability.

- DMA_PREP_LOAD_EOT

  - If set, the transfer will replace the transfer currently being executed at the end of the transfer.

  - This is the default behaviour for non-repeated transfers, specifying DMA_PREP_LOAD_EOT for non-repeated transfers will thus make no difference.

  - When using repeated transfers, DMA clients will usually need to set the DMA_PREP_LOAD_EOT flag on all transfers, otherwise the channel will keep repeating the last repeated transfer and ignore the new transfers being queued. Failure to set DMA_PREP_LOAD_EOT will appear as if the channel was stuck on the previous transfer.

  - This flag is only supported if the channel reports the DMA_LOAD_EOT capability.

<a id="rst-general-design-notes"></a>

## General Design Notes

Most of the DMAEngine drivers you'll see are based on a similar design that handles the end of transfer interrupts in the handler, but defer most work to a tasklet, including the start of a new transfer whenever the previous transfer ended.

This is a rather inefficient design though, because the inter-transfer latency will be not only the interrupt latency, but also the scheduling latency of the tasklet, which will leave the channel idle in between, which will slow down the global transfer rate.

You should avoid this kind of practice, and instead of electing a new transfer in your tasklet, move that part to the interrupt handler in order to have a shorter idle window (that we can't really avoid anyway).

<a id="rst-glossary"></a>

## Glossary

- Burst: A number of consecutive read or write operations that can be queued to buffers before being flushed to memory.

- Chunk: A contiguous collection of bursts

- Transfer: A collection of chunks (be it contiguous or not)

---

# PXA/MMP - DMA Slave controller

_Peios Kernel / Hardware and drivers / Driver development / DMA engines_

> a) Transfers hot queuing A driver submitting a transfer and issuing it should be granted the transfer is queued even on a running DMA channel. This implies that the queuing doesn't wait for the previous transfer end, and that the…

<a id="rst-pxa-mmp-dma-slave-controller"></a>

<a id="rst-constraints"></a>

## Constraints

a) Transfers hot queuing A driver submitting a transfer and issuing it should be granted the transfer is queued even on a running DMA channel. This implies that the queuing doesn't wait for the previous transfer end, and that the descriptor chaining is not only done in the irq/tasklet code triggered by the end of the transfer. A transfer which is submitted and issued on a phy doesn't wait for a phy to stop and restart, but is submitted on a "running channel". The other drivers, especially mmp_pdma waited for the phy to stop before relaunching a new transfer.

b) All transfers having asked for confirmation should be signaled Any issued transfer with DMA_PREP_INTERRUPT should trigger a callback call. This implies that even if an irq/tasklet is triggered by end of tx1, but at the time of irq/dma tx2 is already finished, tx1-&gt;complete() and tx2-&gt;complete() should be called.

c) Channel running state A driver should be able to query if a channel is running or not. For the multimedia case, such as video capture, if a transfer is submitted and then a check of the DMA channel reports a "stopped channel", the transfer should not be issued until the next "start of frame interrupt", hence the need to know if a channel is in running or stopped state.

d) Bandwidth guarantee The PXA architecture has 4 levels of DMAs priorities : high, normal, low. The high priorities get twice as much bandwidth as the normal, which get twice as much as the low priorities. A driver should be able to request a priority, especially the real-time ones such as pxa_camera with (big) throughputs.

<a id="rst-design"></a>

## Design

a) Virtual channels Same concept as in sa11x0 driver, ie. a driver was assigned a "virtual channel" linked to the requestor line, and the physical DMA channel is assigned on the fly when the transfer is issued.

- **b)** Transfer anatomy for a scatter-gather transfer



```text
+------------+-----+---------------+----------------+-----------------+
| desc-sg[0] | ... | desc-sg[last] | status updater | finisher/linker |
+------------+-----+---------------+----------------+-----------------+
```

This structure is pointed by dma-&gt;sg_cpu. The descriptors are used as follows :

> - desc-sg\[i\]: i-th descriptor, transferring the i-th sg element to the video buffer scatter gather
>
> - status updater Transfers a single u32 to a well known dma coherent memory to leave a trace that this transfer is done. The "well known" is unique per physical channel, meaning that a read of this value will tell which is the last finished transfer at that point in time.
>
> - finisher: has ddadr=DADDR_STOP, dcmd=ENDIRQEN
>
> - linker: has ddadr= desc-sg\[0\] of next transfer, dcmd=0

c) Transfers hot-chaining Suppose the running chain is:



```text
Buffer 1              Buffer 2
+---------+----+---+  +----+----+----+---+
| d0 | .. | dN | l |  | d0 | .. | dN | f |
+---------+----+-|-+  ^----+----+----+---+
                 |    |
                 +----+
```

After a call to dmaengine_submit(b3), the chain will look like:



```text
Buffer 1              Buffer 2              Buffer 3
+---------+----+---+  +----+----+----+---+  +----+----+----+---+
| d0 | .. | dN | l |  | d0 | .. | dN | l |  | d0 | .. | dN | f |
+---------+----+-|-+  ^----+----+----+-|-+  ^----+----+----+---+
                 |    |                |    |
                 +----+                +----+
                                      new_link
```

If while new_link was created the DMA channel stopped, it is \_not\_ restarted. Hot-chaining doesn't break the assumption that dma_async_issue_pending() is to be used to ensure the transfer is actually started.

One exception to this rule :

- if Buffer1 and Buffer2 had all their addresses 8 bytes aligned

- and if Buffer3 has at least one address not 4 bytes aligned

- then hot-chaining cannot happen, as the channel must be stopped, the "align bit" must be set, and the channel restarted As a consequence, such a transfer tx_submit() will be queued on the submitted queue, and this specific case if the DMA is already running in aligned mode.

d) Transfers completion updater Each time a transfer is completed on a channel, an interrupt might be generated or not, up to the client's request. But in each case, the last descriptor of a transfer, the "status updater", will write the latest transfer being completed into the physical channel's completion mark.

This will speed up residue calculation, for large transfers such as video buffers which hold around 6k descriptors or more. This also allows without any lock to find out what is the latest completed transfer in a running DMA chain.

e) Transfers completion, irq and tasklet When a transfer flagged as "DMA_PREP_INTERRUPT" is finished, the dma irq is raised. Upon this interrupt, a tasklet is scheduled for the physical channel.

The tasklet is responsible for :

- reading the physical channel last updater mark

- calling all the transfer callbacks of finished transfers, based on that mark, and each transfer flags.

If a transfer is completed while this handling is done, a dma irq will be raised, and the tasklet will be scheduled once again, having a new updater mark.

f) Residue Residue granularity will be descriptor based. The issued but not completed transfers will be scanned for all of their descriptors against the currently running descriptor.

g) Most complicated case of driver's tx queues The most tricky situation is when :

> - there are not "acked" transfers (tx0)
>
> - a driver submitted an aligned tx1, not chained
>
> - a driver submitted an aligned tx2 =&gt; tx2 is cold chained to tx1
>
> - a driver issued tx1+tx2 =&gt; channel is running in aligned mode
>
> - a driver submitted an aligned tx3 =&gt; tx3 is hot-chained
>
> - a driver submitted an unaligned tx4 =&gt; tx4 is put in submitted queue, not chained
>
> - a driver issued tx4 =&gt; tx4 is put in issued queue, not chained
>
> - a driver submitted an aligned tx5 =&gt; tx5 is put in submitted queue, not chained
>
> - a driver submitted an aligned tx6 =&gt; tx6 is put in submitted queue, cold chained to tx5
>
> This translates into (after tx4 is issued) :
>
> - issued queue
>
>
>
> ```text
> +-----+ +-----+ +-----+ +-----+
> | tx1 | | tx2 | | tx3 | | tx4 |
> +---|-+ ^---|-+ ^-----+ +-----+
>     |   |   |   |
>     +---+   +---+
>   - submitted queue
> +-----+ +-----+
> | tx5 | | tx6 |
> +---|-+ ^-----+
>     |   |
>     +---+
> ```

- completed queue : empty

- allocated queue : tx0

It should be noted that after tx3 is completed, the channel is stopped, and restarted in "unaligned mode" to handle tx4.

Author: Robert Jarzmik &lt;[robert.jarzmik@free.fr](<mailto:robert.jarzmik@free.fr>)&gt;

---

# Driver Model

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> Reference for Driver Model.

<a id="rst-driver-model"></a>

- [Driver Binding](</kernel/hardware/driver-api/driver-model/binding.md>)
- [Bus Types](</kernel/hardware/driver-api/driver-model/bus.md>)
- [Device Driver Design Patterns](</kernel/hardware/driver-api/driver-model/design-patterns.md>)
- [The Basic Device Structure](</kernel/hardware/driver-api/driver-model/device.md>)
- [Devres - Managed Device Resource](</kernel/hardware/driver-api/driver-model/devres.md>)
- [Device Drivers](</kernel/hardware/driver-api/driver-model/driver.md>)
- [The Linux Kernel Device Model](</kernel/hardware/driver-api/driver-model/overview.md>)
- [Platform Devices and Drivers](</kernel/hardware/driver-api/driver-model/platform.md>)
- [Porting Drivers to the New Driver Model](</kernel/hardware/driver-api/driver-model/porting.md>)

---

# Driver Binding

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> Driver binding is the process of associating a device with a device driver that can control it. Bus drivers have typically handled this because there have been bus-specific structures to represent the devices and the drivers. With generic…

<a id="rst-driver-binding"></a>

Driver binding is the process of associating a device with a device driver that can control it. Bus drivers have typically handled this because there have been bus-specific structures to represent the devices and the drivers. With generic device and device driver structures, most of the binding can take place using common code.

<a id="rst-bus"></a>

## Bus

The bus type structure contains a list of all devices that are on that bus type in the system. When device_register is called for a device, it is inserted into the end of this list. The bus object also contains a list of all drivers of that bus type. When driver_register is called for a driver, it is inserted at the end of this list. These are the two events which trigger driver binding.

<a id="rst-device-register"></a>

## device_register

When a new device is added, the bus's list of drivers is iterated over to find one that supports it. In order to determine that, the device ID of the device must match one of the device IDs that the driver supports. The format and semantics for comparing IDs is bus-specific. Instead of trying to derive a complex state machine and matching algorithm, it is up to the bus driver to provide a callback to compare a device against the IDs of a driver. The bus returns 1 if a match was found; 0 otherwise.

int match(struct device \* dev, struct device_driver \* drv);

If a match is found, the device's driver field is set to the driver and the driver's probe callback is called. This gives the driver a chance to verify that it really does support the hardware, and that it's in a working state.

<a id="rst-device-class"></a>

## Device Class

Upon the successful completion of probe, the device is registered with the class to which it belongs. Device drivers belong to one and only one class, and that is set in the driver's devclass field. devclass_add_device is called to enumerate the device within the class and actually register it with the class, which happens with the class's register_dev callback.

<a id="rst-driver"></a>

## Driver

When a driver is attached to a device, the driver's probe() function is called. Within probe(), the driver initializes the device and allocates and initializes per-device data structures. This per-device state is associated with the device object for as long as the driver remains bound to it. Conceptually, this per-device data together with the binding to the device can be thought of as an instance of the driver.

<a id="rst-sysfs"></a>

## sysfs

A symlink is created in the bus's 'devices' directory that points to the device's directory in the physical hierarchy.

A symlink is created in the driver's 'devices' directory that points to the device's directory in the physical hierarchy.

A directory for the device is created in the class's directory. A symlink is created in that directory that points to the device's physical location in the sysfs tree.

A symlink can be created (though this isn't done yet) in the device's physical directory to either its class directory, or the class's top-level directory. One can also be created to point to its driver's directory also.

<a id="rst-driver-register"></a>

## driver_register

The process is almost identical for when a new driver is added. The bus's list of devices is iterated over to find a match. Devices that already have a driver are skipped. All the devices are iterated over, to bind as many devices as possible to the driver.

<a id="rst-removal"></a>

## Removal

When a device is removed, the reference count for it will eventually go to 0. When it does, the remove callback of the driver is called. It is removed from the driver's list of devices and the reference count of the driver is decremented. All symlinks between the two are removed.

When a driver is removed, the list of devices that it supports is iterated over, and the driver's remove callback is called for each one. The device is removed from that list and the symlinks removed.

<a id="rst-driver-override"></a>

## Driver Override

Userspace may override the standard matching by writing a driver name to a device's `driver_override` sysfs attribute.  When set, only a driver whose name matches the override will be considered during binding.  This bypasses all bus-specific matching (OF, ACPI, ID tables, etc.).

The override may be cleared by writing an empty string, which returns the device to standard matching rules.  Writing to `driver_override` does not automatically unbind the device from its current driver or make any attempt to load the specified driver.

Buses opt into this mechanism by setting the `driver_override` flag in their `struct bus_type`:



```text
const struct bus_type example_bus_type = {
    ...
    .driver_override = true,
};
```

When the flag is set, the driver core automatically creates the `driver_override` sysfs attribute for every device on that bus.

The bus's `match()` callback should check the override before performing its own matching, using `device_match_driver_override()`:



```text
static int example_match(struct device *dev, const struct device_driver *drv)
{
    int ret;

    ret = device_match_driver_override(dev, drv);
    if (ret >= 0)
        return ret;

    /* Fall through to bus-specific matching... */
}
```

`device_match_driver_override()` returns &gt; 0 if the override matches the given driver, 0 if the override is set but does not match, or &lt; 0 if no override is set at all.

Additional helpers are available:

- `device_set_driver_override()` - set or clear the override from kernel code.

- `device_has_driver_override()` - check whether an override is set.

---

# Bus Types

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> See the kerneldoc for the struct bus_type.

<a id="rst-bus-types"></a>

<a id="rst-definition"></a>

## Definition

See the kerneldoc for the struct bus_type.

int bus_register(struct bus_type \* bus);

<a id="rst-declaration"></a>

## Declaration

Each bus type in the kernel (PCI, USB, etc) should declare one static object of this type. They must initialize the name field, and may optionally initialize the match callback:



```text
struct bus_type pci_bus_type = {
       .name = "pci",
       .match        = pci_bus_match,
};
```

The structure should be exported to drivers in a header file:

extern struct bus_type pci_bus_type;

<a id="rst-registration"></a>

## Registration

When a bus driver is initialized, it calls bus_register. This initializes the rest of the fields in the bus object and inserts it into a global list of bus types. Once the bus object is registered, the fields in it are usable by the bus driver.

<a id="rst-callbacks"></a>

## Callbacks

<a id="rst-match-attaching-drivers-to-devices"></a>

## match(): Attaching Drivers to Devices

The format of device ID structures and the semantics for comparing them are inherently bus-specific. Drivers typically declare an array of device IDs of devices they support that reside in a bus-specific driver structure.

The purpose of the match callback is to give the bus an opportunity to determine if a particular driver supports a particular device by comparing the device IDs the driver supports with the device ID of a particular device, without sacrificing bus-specific functionality or type-safety.

When a driver is registered with the bus, the bus's list of devices is iterated over, and the match callback is called for each device that does not have a driver associated with it.

<a id="rst-device-and-driver-lists"></a>

## Device and Driver Lists

The lists of devices and drivers are intended to replace the local lists that many buses keep. They are lists of struct devices and struct device_drivers, respectively. Bus drivers are free to use the lists as they please, but conversion to the bus-specific type may be necessary.

The LDM core provides helper functions for iterating over each list:



```text
int bus_for_each_dev(struct bus_type * bus, struct device * start,
                     void * data,
                     int (*fn)(struct device *, void *));

int bus_for_each_drv(struct bus_type * bus, struct device_driver * start,
                     void * data, int (*fn)(struct device_driver *, void *));
```

These helpers iterate over the respective list, and call the callback for each device or driver in the list. All list accesses are synchronized by taking the bus's lock (read currently). The reference count on each object in the list is incremented before the callback is called; it is decremented after the next object has been obtained. The lock is not held when calling the callback.

<a id="rst-sysfs"></a>

## sysfs

There is a top-level directory named 'bus'.

Each bus gets a directory in the bus directory, along with two default directories:



```text
/sys/bus/pci/
|-- devices
`-- drivers
```

Drivers registered with the bus get a directory in the bus's drivers directory:



```text
/sys/bus/pci/
|-- devices
`-- drivers
    |-- Intel ICH
    |-- Intel ICH Joystick
    |-- agpgart
    `-- e100
```

Each device that is discovered on a bus of that type gets a symlink in the bus's devices directory to the device's directory in the physical hierarchy:



```text
/sys/bus/pci/
|-- devices
|   |-- 00:00.0 -> ../../../root/pci0/00:00.0
|   |-- 00:01.0 -> ../../../root/pci0/00:01.0
|   `-- 00:02.0 -> ../../../root/pci0/00:02.0
`-- drivers
```

<a id="rst-exporting-attributes"></a>

## Exporting Attributes



```text
struct bus_attribute {
      struct attribute        attr;
      ssize_t (*show)(const struct bus_type *, char * buf);
      ssize_t (*store)(const struct bus_type *, const char * buf, size_t count);
};
```

Bus drivers can export attributes using the BUS_ATTR_RW macro that works similarly to the DEVICE_ATTR_RW macro for devices. For example, a definition like this:



```text
static BUS_ATTR_RW(debug);
```

is equivalent to declaring:



```text
static bus_attribute bus_attr_debug;
```

This can then be used to add and remove the attribute from the bus's sysfs directory using:



```text
int bus_create_file(struct bus_type *, struct bus_attribute *);
void bus_remove_file(struct bus_type *, struct bus_attribute *);
```

---

# Device Driver Design Patterns

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> This document describes a few common design patterns found in device drivers. It is likely that subsystem maintainers will ask driver developers to conform to these design patterns.

<a id="rst-device-driver-design-patterns"></a>

This document describes a few common design patterns found in device drivers. It is likely that subsystem maintainers will ask driver developers to conform to these design patterns.

1. State Container

2. container_of()

<a id="rst-state-container"></a>

## 1. State Container

While the kernel contains a few device drivers that assume that they will only be probed() once on a certain system (singletons), it is custom to assume that the device the driver binds to will appear in several instances. This means that the probe() function and all callbacks need to be reentrant.

The most common way to achieve this is to use the state container design pattern. It usually has this form:



```text
struct foo {
    spinlock_t lock; /* Example member */
    (...)
};

static int foo_probe(...)
{
    struct foo *foo;

    foo = devm_kzalloc(dev, sizeof(*foo), GFP_KERNEL);
    if (!foo)
        return -ENOMEM;
    spin_lock_init(&foo->lock);
    (...)
}
```

This will create an instance of struct foo in memory every time probe() is called. This is our state container for this instance of the device driver. Of course it is then necessary to always pass this instance of the state around to all functions that need access to the state and its members.

For example, if the driver is registering an interrupt handler, you would pass around a pointer to struct foo like this:



```text
static irqreturn_t foo_handler(int irq, void *arg)
{
    struct foo *foo = arg;
    (...)
}

static int foo_probe(...)
{
    struct foo *foo;

    (...)
    ret = request_irq(irq, foo_handler, 0, "foo", foo);
}
```

This way you always get a pointer back to the correct instance of foo in your interrupt handler.

<a id="rst-container-of"></a>

## 2. container_of()

Continuing on the above example we add an offloaded work:



```text
struct foo {
    spinlock_t lock;
    struct workqueue_struct *wq;
    struct work_struct offload;
    (...)
};

static void foo_work(struct work_struct *work)
{
    struct foo *foo = container_of(work, struct foo, offload);

    (...)
}

static irqreturn_t foo_handler(int irq, void *arg)
{
    struct foo *foo = arg;

    queue_work(foo->wq, &foo->offload);
    (...)
}

static int foo_probe(...)
{
    struct foo *foo;

    foo->wq = create_singlethread_workqueue("foo-wq");
    INIT_WORK(&foo->offload, foo_work);
    (...)
}
```

The design pattern is the same for an hrtimer or something similar that will return a single argument which is a pointer to a struct member in the callback.

container_of() is a macro defined in &lt;linux/container_of.h&gt;

What container_of() does is to obtain a pointer to the containing struct from a pointer to a member by a simple subtraction using the offsetof() macro from standard C, which allows something similar to object oriented behaviours. Notice that the contained member must not be a pointer, but an actual member for this to work.

We can see here that we avoid having global pointers to our struct foo \* instance this way, while still keeping the number of parameters passed to the work function to a single pointer.

---

# The Basic Device Structure

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> See the kerneldoc for the struct device.

<a id="rst-the-basic-device-structure"></a>

See the kerneldoc for the struct device.

<a id="rst-programming-interface"></a>

## Programming Interface

The bus driver that discovers the device uses this to register the device with the core:



```text
int device_register(struct device * dev);
```

The bus should initialize the following fields:

> - parent
>
> - name
>
> - bus_id
>
> - bus

A device is removed from the core when its reference count goes to 0. The reference count can be adjusted using:



```text
struct device * get_device(struct device * dev);
void put_device(struct device * dev);
```

get_device() will return a pointer to the struct device passed to it if the reference is not already 0 (if it's in the process of being removed already).

A driver can access the lock in the device structure using:



```text
void lock_device(struct device * dev);
void unlock_device(struct device * dev);
```

<a id="rst-attributes"></a>

## Attributes



```text
struct device_attribute {
      struct attribute        attr;
      ssize_t (*show)(struct device *dev, struct device_attribute *attr,
                      char *buf);
      ssize_t (*store)(struct device *dev, struct device_attribute *attr,
                       const char *buf, size_t count);
};
```

Attributes of devices can be exported by a device driver through sysfs.

Please see [Documentation/filesystems/sysfs.rst](/kernel/internals/filesystems/sysfs.md) for more information on how sysfs works.

As explained in [Documentation/core-api/kobject.rst](/kernel/internals/core-api/kobject.md), device attributes must be created before the KOBJ_ADD uevent is generated. The only way to realize that is by defining an attribute group.

Attributes are declared using a macro called DEVICE_ATTR:



```text
#define DEVICE_ATTR(name,mode,show,store)
```

Example::



```text
static DEVICE_ATTR(type, 0444, type_show, NULL);
static DEVICE_ATTR(power, 0644, power_show, power_store);
```

Helper macros are available for common values of mode, so the above examples can be simplified to::



```text
static DEVICE_ATTR_RO(type);
static DEVICE_ATTR_RW(power);
```

This declares two structures of type struct device_attribute with respective names 'dev_attr_type' and 'dev_attr_power'. These two attributes can be organized as follows into a group:



```text
static struct attribute *dev_attrs[] = {
      &dev_attr_type.attr,
      &dev_attr_power.attr,
      NULL,
};

static struct attribute_group dev_group = {
      .attrs = dev_attrs,
};

static const struct attribute_group *dev_groups[] = {
      &dev_group,
      NULL,
};
```

A helper macro is available for the common case of a single group, so the above two structures can be declared using::



```text
ATTRIBUTE_GROUPS(dev);
```

This array of groups can then be associated with a device by setting the group pointer in struct device before device_register() is invoked:



```text
dev->groups = dev_groups;
device_register(dev);
```

The device_register() function will use the 'groups' pointer to create the device attributes and the device_unregister() function will use this pointer to remove the device attributes.

Word of warning:  While the kernel allows device_create_file() and device_remove_file() to be called on a device at any time, userspace has strict expectations on when attributes get created.  When a new device is registered in the kernel, a uevent is generated to notify userspace (like udev) that a new device is available.  If attributes are added after the device is registered, then userspace won't get notified and userspace will not know about the new attributes.

This is important for device driver that need to publish additional attributes for a device at driver probe time.  If the device driver simply calls device_create_file() on the device structure passed to it, then userspace will never be notified of the new attributes.

---

# Devres - Managed Device Resource

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> Tejun Heo <teheo@suse.de>

<a id="rst-devres-managed-device-resource"></a>

Tejun Heo       &lt;[teheo@suse.de](<mailto:teheo@suse.de>)&gt;

First draft     10 January 2007

<!-- contents

1. Intro                     : Huh? Devres?
2. Devres                    : Devres in a nutshell
3. Devres Group              : Group devres'es and release them together
4. Details                   : Life time rules, calling context, ...
5. Overhead                  : How much do we have to pay for this?
6. List of managed interfaces: Currently implemented managed interfaces -->

<a id="rst-intro"></a>

## 1. Intro

devres came up while trying to convert libata to use iomap.  Each iomapped address should be kept and unmapped on driver detach.  For example, a plain SFF ATA controller (that is, good old PCI IDE) in native mode makes use of 5 PCI BARs and all of them should be maintained.

As with many other device drivers, libata low level drivers have sufficient bugs in -&gt;remove and -&gt;probe failure path.  Well, yes, that's probably because libata low level driver developers are lazy bunch, but aren't all low level driver developers?  After spending a day fiddling with braindamaged hardware with no document or braindamaged document, if it's finally working, well, it's working.

For one reason or another, low level drivers don't receive as much attention or testing as core code, and bugs on driver detach or initialization failure don't happen often enough to be noticeable. Init failure path is worse because it's much less travelled while needs to handle multiple entry points.

So, many low level drivers end up leaking resources on driver detach and having half broken failure path implementation in -&gt;probe() which would leak resources or even cause oops when failure occurs.  iomap adds more to this mix.  So do msi and msix.

<a id="rst-devres"></a>

## 2. Devres

devres is basically linked list of arbitrarily sized memory areas associated with a struct device.  Each devres entry is associated with a release function.  A devres can be released in several ways.  No matter what, all devres entries are released on driver detach.  On release, the associated release function is invoked and then the devres entry is freed.

Managed interface is created for resources commonly used by device drivers using devres.  For example, coherent DMA memory is acquired using dma_alloc_coherent().  The managed version is called dmam_alloc_coherent().  It is identical to dma_alloc_coherent() except for the DMA memory allocated using it is managed and will be automatically released on driver detach.  Implementation looks like the following:



```text
struct dma_devres {
      size_t          size;
      void            *vaddr;
      dma_addr_t      dma_handle;
};

static void dmam_coherent_release(struct device *dev, void *res)
{
      struct dma_devres *this = res;

      dma_free_coherent(dev, this->size, this->vaddr, this->dma_handle);
}

dmam_alloc_coherent(dev, size, dma_handle, gfp)
{
      struct dma_devres *dr;
      void *vaddr;

      dr = devres_alloc(dmam_coherent_release, sizeof(*dr), gfp);
      ...

      /* alloc DMA memory as usual */
      vaddr = dma_alloc_coherent(...);
      ...

      /* record size, vaddr, dma_handle in dr */
      dr->vaddr = vaddr;
      ...

      devres_add(dev, dr);

      return vaddr;
}
```

If a driver uses dmam_alloc_coherent(), the area is guaranteed to be freed whether initialization fails half-way or the device gets detached.  If most resources are acquired using managed interface, a driver can have much simpler init and exit code.  Init path basically looks like the following:



```text
my_init_one()
{
      struct mydev *d;

      d = devm_kzalloc(dev, sizeof(*d), GFP_KERNEL);
      if (!d)
              return -ENOMEM;

      d->ring = dmam_alloc_coherent(...);
      if (!d->ring)
              return -ENOMEM;

      if (check something)
              return -EINVAL;
      ...

      return register_to_upper_layer(d);
}
```

And exit path:



```text
my_remove_one()
{
      unregister_from_upper_layer(d);
      shutdown_my_hardware();
}
```

As shown above, low level drivers can be simplified a lot by using devres.  Complexity is shifted from less maintained low level drivers to better maintained higher layer.  Also, as init failure path is shared with exit path, both can get more testing.

Note though that when converting current calls or assignments to managed devm\_\* versions it is up to you to check if internal operations like allocating memory, have failed. Managed resources pertains to the freeing of these resources *only* - all other checks needed are still on you. In some cases this may mean introducing checks that were not necessary before moving to the managed devm\_\* calls.

<a id="rst-devres-group"></a>

## 3. Devres group

Devres entries can be grouped using devres group.  When a group is released, all contained normal devres entries and properly nested groups are released.  One usage is to rollback series of acquired resources on failure.  For example:



```text
 if (!devres_open_group(dev, NULL, GFP_KERNEL))
       return -ENOMEM;

 acquire A;
 if (failed)
       goto err;

 acquire B;
 if (failed)
       goto err;
 ...

 devres_remove_group(dev, NULL);
 return 0;

err:
 devres_release_group(dev, NULL);
 return err_code;
```

As resource acquisition failure usually means probe failure, constructs like above are usually useful in midlayer driver (e.g. libata core layer) where interface function shouldn't have side effect on failure. For LLDs, just returning error code suffices in most cases.

Each group is identified by `void *id`.  It can either be explicitly specified by @id argument to devres_open_group() or automatically created by passing NULL as @id as in the above example.  In both cases, devres_open_group() returns the group's id.  The returned id can be passed to other devres functions to select the target group. If NULL is given to those functions, the latest open group is selected.

For example, you can do something like the following:



```text
int my_midlayer_create_something()
{
      if (!devres_open_group(dev, my_midlayer_create_something, GFP_KERNEL))
              return -ENOMEM;

      ...

      devres_close_group(dev, my_midlayer_create_something);
      return 0;
}

void my_midlayer_destroy_something()
{
      devres_release_group(dev, my_midlayer_create_something);
}
```

<a id="rst-details"></a>

## 4. Details

Lifetime of a devres entry begins on devres allocation and finishes when it is released or destroyed (removed and freed) - no reference counting.

devres core guarantees atomicity to all basic devres operations and has support for single-instance devres types (atomic lookup-and-add-if-not-found).  Other than that, synchronizing concurrent accesses to allocated devres data is caller's responsibility.  This is usually non-issue because bus ops and resource allocations already do the job.

For an example of single-instance devres type, read pcim_iomap_table() in lib/devres.c.

All devres interface functions can be called without context if the right gfp mask is given.

<a id="rst-overhead"></a>

## 5. Overhead

Each devres bookkeeping info is allocated together with requested data area.  With debug option turned off, bookkeeping info occupies 16 bytes on 32bit machines and 24 bytes on 64bit (three pointers rounded up to ull alignment).  If singly linked list is used, it can be reduced to two pointers (8 bytes on 32bit, 16 bytes on 64bit).

Each devres group occupies 8 pointers.  It can be reduced to 6 if singly linked list is used.

Memory space overhead on ahci controller with two ports is between 300 and 400 bytes on 32bit machine after naive conversion (we can certainly invest a bit more effort into libata core layer).

<a id="rst-list-of-managed-interfaces"></a>

## 6. List of managed interfaces

- **CLOCK**

  devm_clk_get() devm_clk_get_optional() devm_clk_put() devm_clk_bulk_get() devm_clk_bulk_get_all() devm_clk_bulk_get_optional() devm_get_clk_from_child() devm_clk_hw_register() devm_of_clk_add_hw_provider() devm_clk_hw_register_clkdev()

- **DMA**

  dmaenginem_async_device_register() dmam_alloc_coherent() dmam_alloc_attrs() dmam_free_coherent() dmam_pool_create() dmam_pool_destroy()

- **DRM**

  devm_drm_dev_alloc()

- **GPIO**

  devm_gpiod_get() devm_gpiod_get_array() devm_gpiod_get_array_optional() devm_gpiod_get_index() devm_gpiod_get_index_optional() devm_gpiod_get_optional() devm_gpiod_put() devm_gpiod_unhinge() devm_gpiochip_add_data() devm_gpio_request_one()

- **I2C**

  devm_i2c_add_adapter() devm_i2c_new_dummy_device()

- **IIO**

  devm_iio_device_alloc() devm_iio_device_register() devm_iio_dmaengine_buffer_setup() devm_iio_kfifo_buffer_setup() devm_iio_kfifo_buffer_setup_ext() devm_iio_map_array_register() devm_iio_triggered_buffer_setup() devm_iio_triggered_buffer_setup_ext() devm_iio_trigger_alloc() devm_iio_trigger_register() devm_iio_channel_get() devm_iio_channel_get_all() devm_iio_hw_consumer_alloc() devm_fwnode_iio_channel_get_by_name()

- **INPUT**

  devm_input_allocate_device()

- **IO region**

  devm_release_mem_region() devm_release_region() devm_release_resource() devm_request_mem_region() devm_request_free_mem_region() devm_request_region() devm_request_resource()

- **IOMAP**

  devm_ioport_map() devm_ioport_unmap() devm_ioremap() devm_ioremap_uc() devm_ioremap_wc() devm_ioremap_resource() : checks resource, requests memory region, ioremaps devm_ioremap_resource_wc() devm_platform_ioremap_resource() : calls devm_ioremap_resource() for platform device devm_platform_ioremap_resource_byname() devm_platform_get_and_ioremap_resource() devm_iounmap()

  Note: For the PCI devices the specific pcim\_\*() functions may be used, see below.

- **IRQ**

  devm_free_irq() devm_request_any_context_irq() devm_request_irq() devm_request_threaded_irq() devm_irq_alloc_descs() devm_irq_alloc_desc() devm_irq_alloc_desc_at() devm_irq_alloc_desc_from() devm_irq_alloc_descs_from() devm_irq_alloc_generic_chip() devm_irq_setup_generic_chip() devm_irq_domain_create_sim()

- **LED**

  devm_led_classdev_register() devm_led_classdev_register_ext() devm_led_classdev_unregister() devm_led_trigger_register() devm_of_led_get()

- **MDIO**

  devm_mdiobus_alloc() devm_mdiobus_alloc_size() devm_mdiobus_register() devm_of_mdiobus_register()

- **MEM**

  devm_free_pages() devm_get_free_pages() devm_kasprintf() devm_kcalloc() devm_kfree() devm_kmalloc() devm_kmalloc_array() devm_kmemdup() devm_krealloc() devm_krealloc_array() devm_kstrdup() devm_kstrdup_const() devm_kvasprintf() devm_kzalloc()

- **MFD**

  devm_mfd_add_devices()

- **MUX**

  devm_mux_chip_alloc() devm_mux_chip_register() devm_mux_control_get() devm_mux_state_get()

- **NET**

  devm_alloc_etherdev() devm_alloc_etherdev_mqs() devm_register_netdev()

- **PER-CPU MEM**

  devm_alloc_percpu()

- **PCI**

  devm_pci_alloc_host_bridge()  : managed PCI host bridge allocation devm_pci_remap_cfgspace()     : ioremap PCI configuration space devm_pci_remap_cfg_resource() : ioremap PCI configuration space resource

  pcim_enable_device()          : after success, the PCI device gets disabled automatically on driver detach pcim_iomap()                  : do iomap() on a single BAR pcim_iomap_regions()          : do request_region() and iomap() on multiple BARs pcim_iomap_table()            : array of mapped addresses indexed by BAR pcim_iounmap()                : do iounmap() on a single BAR pcim_pin_device()             : keep PCI device enabled after release pcim_set_mwi()                : enable Memory-Write-Invalidate PCI transaction

- **PHY**

  devm_usb_get_phy() devm_usb_get_phy_by_node() devm_usb_get_phy_by_phandle()

- **PINCTRL**

  devm_pinctrl_get() devm_pinctrl_put() devm_pinctrl_get_select() devm_pinctrl_register() devm_pinctrl_register_and_init()

- **POWER**

  devm_reboot_mode_register() devm_reboot_mode_unregister()

- **PWM**

  devm_pwmchip_alloc() devm_pwmchip_add() devm_pwm_get() devm_fwnode_pwm_get()

- **REGULATOR**

  devm_regulator_bulk_register_supply_alias() devm_regulator_bulk_get() devm_regulator_bulk_get_const() devm_regulator_bulk_get_enable() devm_regulator_bulk_put() devm_regulator_get() devm_regulator_get_enable() devm_regulator_get_enable_read_voltage() devm_regulator_get_enable_optional() devm_regulator_get_exclusive() devm_regulator_get_optional() devm_regulator_irq_helper() devm_regulator_put() devm_regulator_register() devm_regulator_register_notifier() devm_regulator_register_supply_alias() devm_regulator_unregister_notifier()

- **RESET**

  devm_reset_control_get() devm_reset_controller_register()

- **RTC**

  devm_rtc_device_register() devm_rtc_allocate_device() devm_rtc_register_device() devm_rtc_nvmem_register()

- **SERDEV**

  devm_serdev_device_open()

- **SLAVE DMA ENGINE**

  devm_acpi_dma_controller_register()

- **SPI**

  devm_spi_alloc_host() devm_spi_alloc_target() devm_spi_optimize_message() devm_spi_register_controller() devm_spi_register_host() devm_spi_register_target()

- **WATCHDOG**

  devm_watchdog_register_device()

---

# Device Drivers

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> See the kerneldoc for the struct device_driver.

<a id="rst-device-drivers"></a>

See the kerneldoc for the struct device_driver.

<a id="rst-allocation"></a>

## Allocation

Device drivers are statically allocated structures. Though there may be multiple devices in a system that a driver supports, struct device_driver represents the driver as a whole (not a particular device instance).

<a id="rst-initialization"></a>

## Initialization

The driver must initialize at least the name and bus fields. It should also initialize the devclass field (when it arrives), so it may obtain the proper linkage internally. It should also initialize as many of the callbacks as possible, though each is optional.

<a id="rst-declaration"></a>

## Declaration

As stated above, struct device_driver objects are statically allocated. Below is an example declaration of the eepro100 driver. This declaration is hypothetical only; it relies on the driver being converted completely to the new model:



```text
static struct device_driver eepro100_driver = {
       .name          = "eepro100",
       .bus           = &pci_bus_type,

       .probe         = eepro100_probe,
       .remove                = eepro100_remove,
       .suspend               = eepro100_suspend,
       .resume                = eepro100_resume,
};
```

Most drivers will not be able to be converted completely to the new model because the bus they belong to has a bus-specific structure with bus-specific fields that cannot be generalized.

The most common example of this are device ID structures. A driver typically defines an array of device IDs that it supports. The format of these structures and the semantics for comparing device IDs are completely bus-specific. Defining them as bus-specific entities would sacrifice type-safety, so we keep bus-specific structures around.

Bus-specific drivers should include a generic struct device_driver in the definition of the bus-specific driver. Like this:



```text
struct pci_driver {
       const struct pci_device_id *id_table;
       struct device_driver     driver;
};
```

A definition that included bus-specific fields would look like (using the eepro100 driver again):



```text
static struct pci_driver eepro100_driver = {
       .id_table       = eepro100_pci_tbl,
       .driver               = {
              .name           = "eepro100",
              .bus            = &pci_bus_type,
              .probe          = eepro100_probe,
              .remove         = eepro100_remove,
              .suspend        = eepro100_suspend,
              .resume         = eepro100_resume,
       },
};
```

Some may find the syntax of embedded struct initialization awkward or even a bit ugly. So far, it's the best way we've found to do what we want...

<a id="rst-registration"></a>

## Registration



```text
int driver_register(struct device_driver *drv);
```

The driver registers the structure on startup. For drivers that have no bus-specific fields (i.e. don't have a bus-specific driver structure), they would use driver_register and pass a pointer to their struct device_driver object.

Most drivers, however, will have a bus-specific structure and will need to register with the bus using something like pci_driver_register.

It is important that drivers register their driver structure as early as possible. Registration with the core initializes several fields in the struct device_driver object, including the reference count and the lock. These fields are assumed to be valid at all times and may be used by the device model core or the bus driver.

<a id="rst-transition-bus-drivers"></a>

## Transition Bus Drivers

By defining wrapper functions, the transition to the new model can be made easier. Drivers can ignore the generic structure altogether and let the bus wrapper fill in the fields. For the callbacks, the bus can define generic callbacks that forward the call to the bus-specific callbacks of the drivers.

This solution is intended to be only temporary. In order to get class information in the driver, the drivers must be modified anyway. Since converting drivers to the new model should reduce some infrastructural complexity and code size, it is recommended that they are converted as class information is added.

<a id="rst-access"></a>

## Access

Once the object has been registered, it may access the common fields of the object, like the lock and the list of devices:



```text
int driver_for_each_dev(struct device_driver *drv, void *data,
                        int (*callback)(struct device *dev, void *data));
```

The devices field is a list of all the devices that have been bound to the driver. The LDM core provides a helper function to operate on all the devices a driver controls. This helper locks the driver on each node access, and does proper reference counting on each device as it accesses it.

<a id="rst-sysfs"></a>

## sysfs

When a driver is registered, a sysfs directory is created in its bus's directory. In this directory, the driver can export an interface to userspace to control operation of the driver on a global basis; e.g. toggling debugging output in the driver.

A future feature of this directory will be a 'devices' directory. This directory will contain symlinks to the directories of devices it supports.

<a id="rst-callbacks"></a>

## Callbacks



```text
int     (*probe)        (struct device *dev);
```

The probe() entry is called in task context, with the bus's rwsem locked and the driver partially bound to the device.  Drivers commonly use container_of() to convert "dev" to a bus-specific type, both in probe() and other routines.  That type often provides device resource data, such as pci_dev.resource\[\] or platform_device.resources, which is used in addition to dev-&gt;platform_data to initialize the driver.

This callback holds the driver-specific logic to bind the driver to a given device.  That includes verifying that the device is present, that it's a version the driver can handle, that driver data structures can be allocated and initialized, and that any hardware can be initialized. Drivers often store a pointer to their state with dev_set_drvdata(). When the driver has successfully bound itself to that device, then probe() returns zero and the driver model code will finish its part of binding the driver to that device.

A driver's probe() may return a negative errno value to indicate that the driver did not bind to this device, in which case it should have released all resources it allocated.

Optionally, probe() may return -EPROBE_DEFER if the driver depends on resources that are not yet available (e.g., supplied by a driver that hasn't initialized yet).  The driver core will put the device onto the deferred probe list and will try to call it again later. If a driver must defer, it should return -EPROBE_DEFER as early as possible to reduce the amount of time spent on setup work that will need to be unwound and reexecuted at a later time.

> [!WARNING]
>
> -EPROBE_DEFER must not be returned if probe() has already created child devices, even if those child devices are removed again in a cleanup path. If -EPROBE_DEFER is returned after a child device has been registered, it may result in an infinite loop of .probe() calls to the same driver.



```text
void    (*sync_state)   (struct device *dev);
```

sync_state is called only once for a device. It's called when all the consumer devices of the device have successfully probed. The list of consumers of the device is obtained by looking at the device links connecting that device to its consumer devices.

The first attempt to call sync_state() is made during late_initcall_sync() to give firmware and drivers time to link devices to each other. During the first attempt at calling sync_state(), if all the consumers of the device at that point in time have already probed successfully, sync_state() is called right away. If there are no consumers of the device during the first attempt, that too is considered as "all consumers of the device have probed" and sync_state() is called right away.

If during the first attempt at calling sync_state() for a device, there are still consumers that haven't probed successfully, the sync_state() call is postponed and reattempted in the future only when one or more consumers of the device probe successfully. If during the reattempt, the driver core finds that there are one or more consumers of the device that haven't probed yet, then sync_state() call is postponed again.

A typical use case for sync_state() is to have the kernel cleanly take over management of devices from the bootloader. For example, if a device is left on and at a particular hardware configuration by the bootloader, the device's driver might need to keep the device in the boot configuration until all the consumers of the device have probed. Once all the consumers of the device have probed, the device's driver can synchronize the hardware state of the device to match the aggregated software state requested by all the consumers. Hence the name sync_state().

While obvious examples of resources that can benefit from sync_state() include resources such as regulator, sync_state() can also be useful for complex resources like IOMMUs. For example, IOMMUs with multiple consumers (devices whose addresses are remapped by the IOMMU) might need to keep their mappings fixed at (or additive to) the boot configuration until all its consumers have probed.

While the typical use case for sync_state() is to have the kernel cleanly take over management of devices from the bootloader, the usage of sync_state() is not restricted to that. Use it whenever it makes sense to take an action after all the consumers of a device have probed:



```text
int     (*remove)       (struct device *dev);
```

remove is called to unbind a driver from a device. This may be called if a device is physically removed from the system, if the driver module is being unloaded, during a reboot sequence, or in other cases.

It is up to the driver to determine if the device is present or not. It should free any resources allocated specifically for the device; i.e. anything in the device's driver_data field.

If the device is still present, it should quiesce the device and place it into a supported low-power state.



```text
int     (*suspend)      (struct device *dev, pm_message_t state);
```

suspend is called to put the device in a low power state.



```text
int     (*resume)       (struct device *dev);
```

Resume is used to bring a device back from a low power state.

<a id="rst-attributes"></a>

## Attributes



```text
struct driver_attribute {
        struct attribute        attr;
        ssize_t (*show)(struct device_driver *driver, char *buf);
        ssize_t (*store)(struct device_driver *, const char *buf, size_t count);
};
```

Device drivers can export attributes via their sysfs directories. Drivers can declare attributes using a DRIVER_ATTR_RW and DRIVER_ATTR_RO macro that works identically to the DEVICE_ATTR_RW and DEVICE_ATTR_RO macros.

Example:



```text
DRIVER_ATTR_RW(debug);
```

This is equivalent to declaring:



```text
struct driver_attribute driver_attr_debug;
```

This can then be used to add and remove the attribute from the driver's directory using:



```text
int driver_create_file(struct device_driver *, const struct driver_attribute *);
void driver_remove_file(struct device_driver *, const struct driver_attribute *);
```

---

# The Linux Kernel Device Model

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> Patrick Mochel <mochel@digitalimplant.org>

<a id="rst-the-linux-kernel-device-model"></a>

Patrick Mochel  &lt;[mochel@digitalimplant.org](<mailto:mochel@digitalimplant.org>)&gt;

Drafted 26 August 2002 Updated 31 January 2006

<a id="rst-overview"></a>

## Overview

The Linux Kernel Driver Model is a unification of all the disparate driver models that were previously used in the kernel. It is intended to augment the bus-specific drivers for bridges and devices by consolidating a set of data and operations into globally accessible data structures.

Traditional driver models implemented some sort of tree-like structure (sometimes just a list) for the devices they control. There wasn't any uniformity across the different bus types.

The current driver model provides a common, uniform data model for describing a bus and the devices that can appear under the bus. The unified bus model includes a set of common attributes which all buses carry, and a set of common callbacks, such as device discovery during bus probing, bus shutdown, bus power management, etc.

The common device and bridge interface reflects the goals of the modern computer: namely the ability to do seamless device "plug and play", power management, and hot plug. In particular, the model dictated by Intel and Microsoft (namely ACPI) ensures that almost every device on almost any bus on an x86-compatible system can work within this paradigm.  Of course, not every bus is able to support all such operations, although most buses support most of those operations.

<a id="rst-downstream-access"></a>

## Downstream Access

Common data fields have been moved out of individual bus layers into a common data structure. These fields must still be accessed by the bus layers, and sometimes by the device-specific drivers.

Other bus layers are encouraged to do what has been done for the PCI layer. struct pci_dev now looks like this:



```text
struct pci_dev {
      ...

      struct device dev;     /* Generic device interface */
      ...
};
```

Note first that the struct device dev within the struct pci_dev is statically allocated. This means only one allocation on device discovery.

Note also that that struct device dev is not necessarily defined at the front of the pci_dev structure.  This is to make people think about what they're doing when switching between the bus driver and the global driver, and to discourage meaningless and incorrect casts between the two.

The PCI bus layer freely accesses the fields of struct device. It knows about the structure of struct pci_dev, and it should know the structure of struct device. Individual PCI device drivers that have been converted to the current driver model generally do not and should not touch the fields of struct device, unless there is a compelling reason to do so.

The above abstraction prevents unnecessary pain during transitional phases. If it were not done this way, then when a field was renamed or removed, every downstream driver would break.  On the other hand, if only the bus layer (and not the device layer) accesses the struct device, it is only the bus layer that needs to change.

<a id="rst-user-interface"></a>

## User Interface

By virtue of having a complete hierarchical view of all the devices in the system, exporting a complete hierarchical view to userspace becomes relatively easy. This has been accomplished by implementing a special purpose virtual file system named sysfs.

Almost all mainstream Linux distros mount this filesystem automatically; you can see some variation of the following in the output of the "mount" command:



```text
$ mount
...
none on /sys type sysfs (rw,noexec,nosuid,nodev)
...
$
```

The auto-mounting of sysfs is typically accomplished by an entry similar to the following in the /etc/fstab file:



```text
none          /sys    sysfs    defaults               0 0
```

or something similar in the /lib/init/fstab file on Debian-based systems:



```text
none            /sys    sysfs    nodev,noexec,nosuid    0 0
```

If sysfs is not automatically mounted, you can always do it manually with:



```text
# mount -t sysfs sysfs /sys
```

Whenever a device is inserted into the tree, a directory is created for it. This directory may be populated at each layer of discovery - the global layer, the bus layer, or the device layer.

The global layer currently creates two files - 'name' and 'power'. The former only reports the name of the device. The latter reports the current power state of the device. It will also be used to set the current power state.

The bus layer may also create files for the devices it finds while probing the bus. For example, the PCI layer currently creates 'irq' and 'resource' files for each PCI device.

A device-specific driver may also export files in its directory to expose device-specific data or tunable interfaces.

More information about the sysfs directory layout can be found in the other documents in this directory and in the file [Documentation/filesystems/sysfs.rst](/kernel/internals/filesystems/sysfs.md).

---

# Platform Devices and Drivers

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> See <linux/platform_device.h> for the driver model interface to the platform bus: platform_device, and platform_driver. This pseudo-bus is used to connect devices on buses with minimal infrastructure, like those used to integrate…

<a id="rst-platform-devices-and-drivers"></a>

See &lt;linux/platform_device.h&gt; for the driver model interface to the platform bus:  platform_device, and platform_driver.  This pseudo-bus is used to connect devices on buses with minimal infrastructure, like those used to integrate peripherals on many system-on-chip processors, or some "legacy" PC interconnects; as opposed to large formally specified ones like PCI or USB.

<a id="rst-platform-devices"></a>

## Platform devices

Platform devices are devices that typically appear as autonomous entities in the system. This includes legacy port-based devices and host bridges to peripheral buses, and most controllers integrated into system-on-chip platforms.  What they usually have in common is direct addressing from a CPU bus.  Rarely, a platform_device will be connected through a segment of some other kind of bus; but its registers will still be directly addressable.

Platform devices are given a name, used in driver binding, and a list of resources such as addresses and IRQs:



```text
struct platform_device {
      const char      *name;
      u32             id;
      struct device   dev;
      u32             num_resources;
      struct resource *resource;
};
```

<a id="rst-platform-drivers"></a>

## Platform drivers

Platform drivers follow the standard driver model convention, where discovery/enumeration is handled outside the drivers, and drivers provide probe() and remove() methods.  They support power management and shutdown notifications using the standard conventions:



```text
struct platform_driver {
      int (*probe)(struct platform_device *);
      void (*remove)(struct platform_device *);
      void (*shutdown)(struct platform_device *);
      int (*suspend)(struct platform_device *, pm_message_t state);
      int (*resume)(struct platform_device *);
      struct device_driver driver;
      const struct platform_device_id *id_table;
      bool prevent_deferred_probe;
      bool driver_managed_dma;
};
```

Note that probe() should in general verify that the specified device hardware actually exists; sometimes platform setup code can't be sure.  The probing can use device resources, including clocks, and device platform_data.

Platform drivers register themselves the normal way:



```text
int platform_driver_register(struct platform_driver *drv);
```

Or, in common situations where the device is known not to be hot-pluggable, the probe() routine can live in an init section to reduce the driver's runtime memory footprint:



```text
int platform_driver_probe(struct platform_driver *drv,
                  int (*probe)(struct platform_device *))
```

Kernel modules can be composed of several platform drivers. The platform core provides helpers to register and unregister an array of drivers:



```text
int __platform_register_drivers(struct platform_driver * const *drivers,
                              unsigned int count, struct module *owner);
void platform_unregister_drivers(struct platform_driver * const *drivers,
                                 unsigned int count);
```

If one of the drivers fails to register, all drivers registered up to that point will be unregistered in reverse order. Note that there is a convenience macro that passes THIS_MODULE as owner parameter:



```text
#define platform_register_drivers(drivers, count)
```

<a id="rst-device-enumeration"></a>

## Device Enumeration

As a rule, platform specific (and often board-specific) setup code will register platform devices:



```text
int platform_device_register(struct platform_device *pdev);

int platform_add_devices(struct platform_device **pdevs, int ndev);
```

The general rule is to register only those devices that actually exist, but in some cases extra devices might be registered.  For example, a kernel might be configured to work with an external network adapter that might not be populated on all boards, or likewise to work with an integrated controller that some boards might not hook up to any peripherals.

In some cases, boot firmware will export tables describing the devices that are populated on a given board.   Without such tables, often the only way for system setup code to set up the correct devices is to build a kernel for a specific target board.  Such board-specific kernels are common with embedded and custom systems development.

In many cases, the memory and IRQ resources associated with the platform device are not enough to let the device's driver work.  Board setup code will often provide additional information using the device's platform_data field to hold additional information.

Embedded systems frequently need one or more clocks for platform devices, which are normally kept off until they're actively needed (to save power). System setup also associates those clocks with the device, so that calls to clk_get(&amp;pdev-&gt;dev, clock_name) return them as needed.

<a id="rst-legacy-drivers-device-probing"></a>

## Legacy Drivers:  Device Probing

Some drivers are not fully converted to the driver model, because they take on a non-driver role:  the driver registers its platform device, rather than leaving that for system infrastructure.  Such drivers can't be hotplugged or coldplugged, since those mechanisms require device creation to be in a different system component than the driver.

The only "good" reason for this is to handle older system designs which, like original IBM PCs, rely on error-prone "probe-the-hardware" models for hardware configuration.  Newer systems have largely abandoned that model, in favor of bus-level support for dynamic configuration (PCI, USB), or device tables provided by the boot firmware (e.g. PNPACPI on x86).  There are too many conflicting options about what might be where, and even educated guesses by an operating system will be wrong often enough to make trouble.

This style of driver is discouraged.  If you're updating such a driver, please try to move the device enumeration to a more appropriate location, outside the driver.  This will usually be cleanup, since such drivers tend to already have "normal" modes, such as ones using device nodes that were created by PNP or by platform device setup.

None the less, there are some APIs to support such legacy drivers.  Avoid using these calls except with such hotplug-deficient drivers:



```text
struct platform_device *platform_device_alloc(
                const char *name, int id);
```

You can use platform_device_alloc() to dynamically allocate a device, which you will then initialize with resources and platform_device_register(). A better solution is usually:



```text
struct platform_device *platform_device_register_simple(
                const char *name, int id,
                struct resource *res, unsigned int nres);
```

You can use platform_device_register_simple() as a one-step call to allocate and register a device.

<a id="rst-device-naming-and-driver-binding"></a>

## Device Naming and Driver Binding

The platform_device.dev.bus_id is the canonical name for the devices. It's built from two components:

> - platform_device.name ... which is also used to for driver matching.
>
> - platform_device.id ... the device instance number, or else "-1" to indicate there's only one.

These are concatenated, so name/id "serial"/0 indicates bus_id "serial.0", and "serial/3" indicates bus_id "serial.3"; both would use the platform_driver named "serial".  While "my_rtc"/-1 would be bus_id "my_rtc" (no instance id) and use the platform_driver called "my_rtc".

Driver binding is performed automatically by the driver core, invoking driver probe() after finding a match between device and driver.  If the probe() succeeds, the driver and device are bound as usual.  There are three different ways to find such a match:

> - Whenever a device is registered, the drivers for that bus are checked for matches.  Platform devices should be registered very early during system boot.
>
> - When a driver is registered using platform_driver_register(), all unbound devices on that bus are checked for matches.  Drivers usually register later during booting, or by module loading.
>
> - Registering a driver using platform_driver_probe() works just like using platform_driver_register(), except that the driver won't be probed later if another device registers.  (Which is OK, since this interface is only for use with non-hotpluggable devices.)

<a id="rst-early-platform-devices-and-drivers"></a>

## Early Platform Devices and Drivers

The early platform interfaces provide platform data to platform device drivers early on during the system boot. The code is built on top of the early_param() command line parsing and can be executed very early on.

Example: "earlyprintk" class early serial console in 6 steps

<a id="rst-registering-early-platform-device-data"></a>

## 1. Registering early platform device data

The architecture code registers platform device data using the function early_platform_add_devices(). In the case of early serial console this should be hardware configuration for the serial port. Devices registered at this point will later on be matched against early platform drivers.

<a id="rst-parsing-kernel-command-line"></a>

## 2. Parsing kernel command line

The architecture code calls parse_early_param() to parse the kernel command line. This will execute all matching early_param() callbacks. User specified early platform devices will be registered at this point. For the early serial console case the user can specify port on the kernel command line as "earlyprintk=serial.0" where "earlyprintk" is the class string, "serial" is the name of the platform driver and 0 is the platform device id. If the id is -1 then the dot and the id can be omitted.

<a id="rst-installing-early-platform-drivers-belonging-to-a-certain-class"></a>

## 3. Installing early platform drivers belonging to a certain class

The architecture code may optionally force registration of all early platform drivers belonging to a certain class using the function early_platform_driver_register_all(). User specified devices from step 2 have priority over these. This step is omitted by the serial driver example since the early serial driver code should be disabled unless the user has specified port on the kernel command line.

<a id="rst-early-platform-driver-registration"></a>

## 4. Early platform driver registration

Compiled-in platform drivers making use of early_platform_init() are automatically registered during step 2 or 3. The serial driver example should use early_platform_init("earlyprintk", &amp;platform_driver).

<a id="rst-probing-of-early-platform-drivers-belonging-to-a-certain-class"></a>

## 5. Probing of early platform drivers belonging to a certain class

The architecture code calls early_platform_driver_probe() to match registered early platform devices associated with a certain class with registered early platform drivers. Matched devices will get probed(). This step can be executed at any point during the early boot. As soon as possible may be good for the serial port case.

<a id="rst-inside-the-early-platform-driver-probe"></a>

## 6. Inside the early platform driver probe()

The driver code needs to take special care during early boot, especially when it comes to memory allocation and interrupt registration. The code in the probe() function can use is_early_platform_device() to check if it is called at early platform device or at the regular platform device time. The early serial driver performs register_console() at this point.

For further information, see &lt;linux/platform_device.h&gt;.

---

# Porting Drivers to the New Driver Model

_Peios Kernel / Hardware and drivers / Driver development / Device and driver model_

> Patrick Mochel

<a id="rst-porting-drivers-to-the-new-driver-model"></a>

Patrick Mochel

7 January 2003

Overview

Please refer to `Documentation/driver-api/driver-model/*.rst` for definitions of various driver types and concepts.

Most of the work of porting devices drivers to the new model happens at the bus driver layer. This was intentional, to minimize the negative effect on kernel drivers, and to allow a gradual transition of bus drivers.

In a nutshell, the driver model consists of a set of objects that can be embedded in larger, bus-specific objects. Fields in these generic objects can replace fields in the bus-specific objects.

The generic objects must be registered with the driver model core. By doing so, they will exported via the sysfs filesystem. sysfs can be mounted by doing:



```text
# mount -t sysfs sysfs /sys
```

The Process

Step 0: Read include/linux/device.h for object and function definitions.

Step 1: Registering the bus driver.

- Define a struct bus_type for the bus driver:



  ```text
  struct bus_type pci_bus_type = {
        .name           = "pci",
  };
  ```

- Register the bus type.

  This should be done in the initialization function for the bus type, which is usually the module_init(), or equivalent, function:



  ```text
  static int __init pci_driver_init(void)
  {
          return bus_register(&pci_bus_type);
  }

  subsys_initcall(pci_driver_init);
  ```

  The bus type may be unregistered (if the bus driver may be compiled as a module) by doing:



  ```text
  bus_unregister(&pci_bus_type);
  ```

- Export the bus type for others to use.

  Other code may wish to reference the bus type, so declare it in a shared header file and export the symbol.

From include/linux/pci.h:



```text
extern struct bus_type pci_bus_type;
```

From file the above code appears in:



```text
EXPORT_SYMBOL(pci_bus_type);
```

- This will cause the bus to show up in /sys/bus/pci/ with two subdirectories: 'devices' and 'drivers':



  ```text
  # tree -d /sys/bus/pci/
  /sys/bus/pci/
  |-- devices
  `-- drivers
  ```

Step 2: Registering Devices.

struct device represents a single device. It mainly contains metadata describing the relationship the device has to other entities.

- Embed a struct device in the bus-specific device type:



  ```text
  struct pci_dev {
         ...
         struct  device  dev;            /* Generic device interface */
         ...
  };
  ```

  It is recommended that the generic device not be the first item in the struct to discourage programmers from doing mindless casts between the object types. Instead macros, or inline functions, should be created to convert from the generic object type:



  ```text
  #define to_pci_dev(n) container_of(n, struct pci_dev, dev)

  or

  static inline struct pci_dev * to_pci_dev(struct kobject * kobj)
  {
      return container_of(n, struct pci_dev, dev);
  }
  ```

  This allows the compiler to verify type-safety of the operations that are performed (which is Good).

- Initialize the device on registration.

  When devices are discovered or registered with the bus type, the bus driver should initialize the generic device. The most important things to initialize are the bus_id, parent, and bus fields.

  The bus_id is an ASCII string that contains the device's address on the bus. The format of this string is bus-specific. This is necessary for representing devices in sysfs.

  parent is the physical parent of the device. It is important that the bus driver sets this field correctly.

  The driver model maintains an ordered list of devices that it uses for power management. This list must be in order to guarantee that devices are shutdown before their physical parents, and vice versa. The order of this list is determined by the parent of registered devices.

  Also, the location of the device's sysfs directory depends on a device's parent. sysfs exports a directory structure that mirrors the device hierarchy. Accurately setting the parent guarantees that sysfs will accurately represent the hierarchy.

  The device's bus field is a pointer to the bus type the device belongs to. This should be set to the bus_type that was declared and initialized before.

  Optionally, the bus driver may set the device's name and release fields.

  The name field is an ASCII string describing the device, like

  > "ATI Technologies Inc Radeon QD"

  The release field is a callback that the driver model core calls when the device has been removed, and all references to it have been released. More on this in a moment.

- Register the device.

  Once the generic device has been initialized, it can be registered with the driver model core by doing:



  ```text
  device_register(&dev->dev);
  ```

  It can later be unregistered by doing:



  ```text
  device_unregister(&dev->dev);
  ```

  This should happen on buses that support hotpluggable devices. If a bus driver unregisters a device, it should not immediately free it. It should instead wait for the driver model core to call the device's release method, then free the bus-specific object. (There may be other code that is currently referencing the device structure, and it would be rude to free the device while that is happening).

  When the device is registered, a directory in sysfs is created. The PCI tree in sysfs looks like:



  ```text
  /sys/devices/pci0/
  |-- 00:00.0
  |-- 00:01.0
  |   `-- 01:00.0
  |-- 00:02.0
  |   `-- 02:1f.0
  |       `-- 03:00.0
  |-- 00:1e.0
  |   `-- 04:04.0
  |-- 00:1f.0
  |-- 00:1f.1
  |   |-- ide0
  |   |   |-- 0.0
  |   |   `-- 0.1
  |   `-- ide1
  |       `-- 1.0
  |-- 00:1f.2
  |-- 00:1f.3
  `-- 00:1f.5
  ```

  Also, symlinks are created in the bus's 'devices' directory that point to the device's directory in the physical hierarchy:



  ```text
  /sys/bus/pci/devices/
  |-- 00:00.0 -> ../../../devices/pci0/00:00.0
  |-- 00:01.0 -> ../../../devices/pci0/00:01.0
  |-- 00:02.0 -> ../../../devices/pci0/00:02.0
  |-- 00:1e.0 -> ../../../devices/pci0/00:1e.0
  |-- 00:1f.0 -> ../../../devices/pci0/00:1f.0
  |-- 00:1f.1 -> ../../../devices/pci0/00:1f.1
  |-- 00:1f.2 -> ../../../devices/pci0/00:1f.2
  |-- 00:1f.3 -> ../../../devices/pci0/00:1f.3
  |-- 00:1f.5 -> ../../../devices/pci0/00:1f.5
  |-- 01:00.0 -> ../../../devices/pci0/00:01.0/01:00.0
  |-- 02:1f.0 -> ../../../devices/pci0/00:02.0/02:1f.0
  |-- 03:00.0 -> ../../../devices/pci0/00:02.0/02:1f.0/03:00.0
  `-- 04:04.0 -> ../../../devices/pci0/00:1e.0/04:04.0
  ```

Step 3: Registering Drivers.

struct device_driver is a simple driver structure that contains a set of operations that the driver model core may call.

- Embed a struct device_driver in the bus-specific driver.

  Just like with devices, do something like:



  ```text
  struct pci_driver {
         ...
         struct device_driver    driver;
  };
  ```

- Initialize the generic driver structure.

  When the driver registers with the bus (e.g. doing pci_register_driver()), initialize the necessary fields of the driver: the name and bus fields.

- Register the driver.

  After the generic driver has been initialized, call:



  ```text
  driver_register(&drv->driver);
  ```

  to register the driver with the core.

  When the driver is unregistered from the bus, unregister it from the core by doing:



  ```text
  driver_unregister(&drv->driver);
  ```

  Note that this will block until all references to the driver have gone away. Normally, there will not be any.

- Sysfs representation.

  Drivers are exported via sysfs in their bus's 'driver's directory. For example:



  ```text
  /sys/bus/pci/drivers/
  |-- 3c59x
  |-- Ensoniq AudioPCI
  |-- agpgart-amdk7
  |-- e100
  `-- serial
  ```

Step 4: Define Generic Methods for Drivers.

struct device_driver defines a set of operations that the driver model core calls. Most of these operations are probably similar to operations the bus already defines for drivers, but taking different parameters.

It would be difficult and tedious to force every driver on a bus to simultaneously convert their drivers to generic format. Instead, the bus driver should define single instances of the generic methods that forward call to the bus-specific drivers. For instance:



```text
static int pci_device_remove(struct device * dev)
{
        struct pci_dev * pci_dev = to_pci_dev(dev);
        struct pci_driver * drv = pci_dev->driver;

        if (drv) {
                if (drv->remove)
                        drv->remove(pci_dev);
                pci_dev->driver = NULL;
        }
        return 0;
}
```

The generic driver should be initialized with these methods before it is registered:



```text
/* initialize common driver fields */
drv->driver.name = drv->name;
drv->driver.bus = &pci_bus_type;
drv->driver.probe = pci_device_probe;
drv->driver.resume = pci_device_resume;
drv->driver.suspend = pci_device_suspend;
drv->driver.remove = pci_device_remove;

/* register with core */
driver_register(&drv->driver);
```

Ideally, the bus should only initialize the fields if they are not already set. This allows the drivers to implement their own generic methods.

Step 5: Support generic driver binding.

The model assumes that a device or driver can be dynamically registered with the bus at any time. When registration happens, devices must be bound to a driver, or drivers must be bound to all devices that it supports.

A driver typically contains a list of device IDs that it supports. The bus driver compares these IDs to the IDs of devices registered with it. The format of the device IDs, and the semantics for comparing them are bus-specific, so the generic model does attempt to generalize them.

Instead, a bus may supply a method in struct bus_type that does the comparison:



```text
int (*match)(struct device * dev, struct device_driver * drv);
```

match should return positive value if the driver supports the device, and zero otherwise. It may also return error code (for example -EPROBE_DEFER) if determining that given driver supports the device is not possible.

When a device is registered, the bus's list of drivers is iterated over. bus-&gt;match() is called for each one until a match is found.

When a driver is registered, the bus's list of devices is iterated over. bus-&gt;match() is called for each device that is not already claimed by a driver.

When a device is successfully bound to a driver, device-&gt;driver is set, the device is added to a per-driver list of devices, and a symlink is created in the driver's sysfs directory that points to the device's physical directory:



```text
/sys/bus/pci/drivers/
|-- 3c59x
|   `-- 00:0b.0 -> ../../../../devices/pci0/00:0b.0
|-- Ensoniq AudioPCI
|-- agpgart-amdk7
|   `-- 00:00.0 -> ../../../../devices/pci0/00:00.0
|-- e100
|   `-- 00:0c.0 -> ../../../../devices/pci0/00:0c.0
`-- serial
```

This driver binding should replace the existing driver binding mechanism the bus currently uses.

Step 6: Supply a hotplug callback.

Whenever a device is registered with the driver model core, the userspace program /sbin/hotplug is called to notify userspace. Users can define actions to perform when a device is inserted or removed.

The driver model core passes several arguments to userspace via environment variables, including

- ACTION: set to 'add' or 'remove'

- DEVPATH: set to the device's physical path in sysfs.

A bus driver may also supply additional parameters for userspace to consume. To do this, a bus must implement the 'hotplug' method in struct bus_type:



```text
int (*hotplug) (struct device *dev, char **envp,
                int num_envp, char *buffer, int buffer_size);
```

This is called immediately before /sbin/hotplug is executed.

Step 7: Cleaning up the bus driver.

The generic bus, device, and driver structures provide several fields that can replace those defined privately to the bus driver.

- Device list.

struct bus_type contains a list of all devices registered with the bus type. This includes all devices on all instances of that bus type. An internal list that the bus uses may be removed, in favor of using this one.

The core provides an iterator to access these devices:



```text
int bus_for_each_dev(struct bus_type * bus, struct device * start,
                     void * data, int (*fn)(struct device *, void *));
```

- Driver list.

struct bus_type also contains a list of all drivers registered with it. An internal list of drivers that the bus driver maintains may be removed in favor of using the generic one.

The drivers may be iterated over, like devices:



```text
int bus_for_each_drv(struct bus_type * bus, struct device_driver * start,
                     void * data, int (*fn)(struct device_driver *, void *));
```

Please see drivers/base/bus.c for more information.

- rwsem

struct bus_type contains an rwsem that protects all core accesses to the device and driver lists. This can be used by the bus driver internally, and should be used when accessing the device or driver lists the bus maintains.

- Device and driver fields.

Some of the fields in struct device and struct device_driver duplicate fields in the bus-specific representations of these objects. Feel free to remove the bus-specific ones and favor the generic ones. Note though, that this will likely mean fixing up all the drivers that reference the bus-specific fields (though those should all be 1-line changes).

---

# Early Userspace

_Peios Kernel / Hardware and drivers / Driver development / early-userspace_

> Reference for Early Userspace.

<a id="rst-early-userspace"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Early userspace support](</kernel/hardware/driver-api/early-userspace/early-userspace-support.md>)
- [initramfs buffer format](</kernel/hardware/driver-api/early-userspace/buffer-format.md>)

---

# initramfs buffer format

_Peios Kernel / Hardware and drivers / Driver development / early-userspace_

> Al Viro, H. Peter Anvin

<a id="rst-initramfs-buffer-format"></a>

Al Viro, H. Peter Anvin

With kernel 2.5.x, the old "initial ramdisk" protocol was complemented with an "initial ramfs" protocol.  The initramfs content is passed using the same memory buffer protocol used by initrd, but the content is different.  The initramfs buffer contains an archive which is expanded into a ramfs filesystem; this document details the initramfs buffer format.

The initramfs buffer format is based around the "newc" or "crc" CPIO formats, and can be created with the cpio(1) utility.  The cpio archive can be compressed using gzip(1), or any other algorithm provided via CONFIG_DECOMPRESS\_\*.  One valid version of an initramfs buffer is thus a single .cpio.gz file.

The full format of the initramfs buffer is defined by the following grammar, where:



```text
*       is used to indicate "0 or more occurrences of"
(|)     indicates alternatives
+       indicates concatenation
GZIP()  indicates gzip compression of the operand
BZIP2() indicates bzip2 compression of the operand
LZMA()  indicates lzma compression of the operand
XZ()    indicates xz compression of the operand
LZO()   indicates lzo compression of the operand
LZ4()   indicates lz4 compression of the operand
ZSTD()  indicates zstd compression of the operand
ALGN(n) means padding with null bytes to an n-byte boundary

initramfs := ("\0" | cpio_archive | cpio_compressed_archive)*

cpio_compressed_archive := (GZIP(cpio_archive) | BZIP2(cpio_archive)
        | LZMA(cpio_archive) | XZ(cpio_archive) | LZO(cpio_archive)
        | LZ4(cpio_archive) | ZSTD(cpio_archive))

cpio_archive := cpio_file* + (<nothing> | cpio_trailer)

cpio_file := ALGN(4) + cpio_header + filename + "\0" + ALGN(4) + data

cpio_trailer := ALGN(4) + cpio_header + "TRAILER!!!\0" + ALGN(4)
```

In human terms, the initramfs buffer contains a collection of compressed and/or uncompressed cpio archives (in the "newc" or "crc" formats); arbitrary amounts zero bytes (for padding) can be added between members.

The cpio "TRAILER\!\!\!" entry (cpio end-of-archive) is optional, but is not ignored; see "handling of hard links" below.

The structure of the cpio_header is as follows (all fields contain hexadecimal ASCII numbers fully padded with '0' on the left to the full width of the field, for example, the integer 4780 is represented by the ASCII string "000012ac"):


<table>
<thead>
<tr>
<th>


Field name

</th>
<th>


Field size

</th>
<th>


Meaning

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


c_magic

</td>
<td>


6 bytes

</td>
<td>


The string "070701" or "070702"

</td>
</tr>
<tr>
<td>


c_ino

</td>
<td>


8 bytes

</td>
<td>


File inode number

</td>
</tr>
<tr>
<td>


c_mode

</td>
<td>


8 bytes

</td>
<td>


File mode and permissions

</td>
</tr>
<tr>
<td>


c_uid

</td>
<td>


8 bytes

</td>
<td>


File uid

</td>
</tr>
<tr>
<td>


c_gid

</td>
<td>


8 bytes

</td>
<td>


File gid

</td>
</tr>
<tr>
<td>


c_nlink

</td>
<td>


8 bytes

</td>
<td>


Number of links

</td>
</tr>
<tr>
<td>


c_mtime

</td>
<td>


8 bytes

</td>
<td>


Modification time

</td>
</tr>
<tr>
<td>


c_filesize

</td>
<td>


8 bytes

</td>
<td>


Size of data field

</td>
</tr>
<tr>
<td>


c_maj

</td>
<td>


8 bytes

</td>
<td>


Major part of file device number

</td>
</tr>
<tr>
<td>


c_min

</td>
<td>


8 bytes

</td>
<td>


Minor part of file device number

</td>
</tr>
<tr>
<td>


c_rmaj

</td>
<td>


8 bytes

</td>
<td>


Major part of device node reference

</td>
</tr>
<tr>
<td>


c_rmin

</td>
<td>


8 bytes

</td>
<td>


Minor part of device node reference

</td>
</tr>
<tr>
<td>


c_namesize

</td>
<td>


8 bytes

</td>
<td>


Length of filename, including final 0

</td>
</tr>
<tr>
<td>


c_chksum

</td>
<td>


8 bytes

</td>
<td>


Checksum of data field if c_magic is 070702; otherwise zero

</td>
</tr>
</tbody>
</table>

The c_mode field matches the contents of st_mode returned by stat(2) on Linux, and encodes the file type and file permissions.

c_mtime is ignored unless CONFIG_INITRAMFS_PRESERVE_MTIME=y is set.

The c_filesize should be zero for any file which is not a regular file or symlink.

c_namesize may account for more than one trailing '0', as long as the value doesn't exceed PATH_MAX.  This can be useful for ensuring that a subsequent file data segment is aligned, e.g. to a filesystem block boundary.

The c_chksum field contains a simple 32-bit unsigned sum of all the bytes in the data field.  cpio(1) refers to this as "crc", which is clearly incorrect (a cyclic redundancy check is a different and significantly stronger integrity check), however, this is the algorithm used.

If the filename is "TRAILER\!\!\!" this is actually an end-of-archive marker; the c_filesize for an end-of-archive marker must be zero.

<a id="rst-handling-of-hard-links"></a>

## Handling of hard links

When a nondirectory with c_nlink &gt; 1 is seen, the (c_maj,c_min,c_ino) tuple is looked up in a tuple buffer.  If not found, it is entered in the tuple buffer and the entry is created as usual; if found, a hard link rather than a second copy of the file is created.  It is not necessary (but permitted) to include a second copy of the file contents; if the file contents is not included, the c_filesize field should be set to zero to indicate no data section follows.  If data is present, the previous instance of the file is overwritten; this allows the data-carrying instance of a file to occur anywhere in the sequence (GNU cpio is reported to attach the data to the last instance of a file only.)

c_filesize must not be zero for a symlink.

When a "TRAILER\!\!\!" end-of-archive marker is seen, the tuple buffer is reset.  This permits archives which are generated independently to be concatenated.

To combine file data from different sources (without having to regenerate the (c_maj,c_min,c_ino) fields), therefore, either one of the following techniques can be used:

- **a)** Separate the different file data sources with a "TRAILER\!\!\!" end-of-archive marker, or

- **b)** Make sure c_nlink == 1 for all nondirectory entries.

---

# Early userspace support

_Peios Kernel / Hardware and drivers / Driver development / early-userspace_

> Last update: 2004-12-20 tlh

<a id="rst-early-userspace-support"></a>

Last update: 2004-12-20 tlh

"Early userspace" is a set of libraries and programs that provide various pieces of functionality that are important enough to be available while a Linux kernel is coming up, but that don't need to be run inside the kernel itself.

It consists of several major infrastructure components:

- gen_init_cpio, a program that builds a cpio-format archive containing a root filesystem image.  This archive is compressed, and the compressed image is linked into the kernel image.

- initramfs, a chunk of code that unpacks the compressed cpio image midway through the kernel boot process.

- klibc, a userspace C library, currently packaged separately, that is optimized for correctness and small size.

The cpio file format used by initramfs is the "newc" (aka "cpio -H newc") format, and is documented in the file "buffer-format.txt".  There are two ways to add an early userspace image: specify an existing cpio archive to be used as the image or have the kernel build process build the image from specifications.

<a id="rst-cpio-archive-method"></a>

## CPIO ARCHIVE method

You can create a cpio archive that contains the early userspace image. Your cpio archive should be specified in CONFIG_INITRAMFS_SOURCE and it will be used directly.  Only a single cpio file may be specified in CONFIG_INITRAMFS_SOURCE and directory and file names are not allowed in combination with a cpio archive.

<a id="rst-image-building-method"></a>

## IMAGE BUILDING method

The kernel build process can also build an early userspace image from source parts rather than supplying a cpio archive.  This method provides a way to create images with root-owned files even though the image was built by an unprivileged user.

The image is specified as one or more sources in CONFIG_INITRAMFS_SOURCE.  Sources can be either directories or files - cpio archives are *not* allowed when building from sources.

A source directory will have it and all of its contents packaged.  The specified directory name will be mapped to '/'.  When packaging a directory, limited user and group ID translation can be performed. INITRAMFS_ROOT_UID can be set to a user ID that needs to be mapped to user root (0).  INITRAMFS_ROOT_GID can be set to a group ID that needs to be mapped to group root (0).

A source file must be directives in the format required by the usr/gen_init_cpio utility (run 'usr/gen_init_cpio -h' to get the file format).  The directives in the file will be passed directly to usr/gen_init_cpio.

When a combination of directories and files are specified then the initramfs image will be an aggregate of all of them.  In this way a user can create a 'root-image' directory and install all files into it. Because device-special files cannot be created by a unprivileged user, special files can be listed in a 'root-files' file.  Both 'root-image' and 'root-files' can be listed in CONFIG_INITRAMFS_SOURCE and a complete early userspace image can be built by an unprivileged user.

As a technical note, when directories and files are specified, the entire CONFIG_INITRAMFS_SOURCE is passed to usr/gen_initramfs.sh.  This means that CONFIG_INITRAMFS_SOURCE can really be interpreted as any legal argument to gen_initramfs.sh.  If a directory is specified as an argument then the contents are scanned, uid/gid translation is performed, and usr/gen_init_cpio file directives are output.  If a directory is specified as an argument to usr/gen_initramfs.sh then the contents of the file are simply copied to the output.  All of the output directives from directory scanning and file contents copying are processed by usr/gen_init_cpio.

See also 'usr/gen_initramfs.sh -h'.

<a id="rst-where-s-this-all-leading"></a>

### Where's this all leading?

The klibc distribution contains some of the necessary software to make early userspace useful.  The klibc distribution is currently maintained separately from the kernel.

You can obtain somewhat infrequent snapshots of klibc from [https://www.kernel.org/pub/linux/libs/klibc/](<https://www.kernel.org/pub/linux/libs/klibc/>)

For active users, you are better off using the klibc git repository, at [https://git.kernel.org/?p=libs/klibc/klibc.git](<https://git.kernel.org/?p=libs/klibc/klibc.git>)

The standalone klibc distribution currently provides three components, in addition to the klibc library:

- ipconfig, a program that configures network interfaces.  It can configure them statically, or use DHCP to obtain information dynamically (aka "IP autoconfiguration").

- nfsmount, a program that can mount an NFS filesystem.

- kinit, the "glue" that uses ipconfig and nfsmount to replace the old support for IP autoconfig, mount a filesystem over NFS, and continue system boot using that filesystem as root.

kinit is built as a single statically linked binary to save space.

Eventually, several more chunks of kernel functionality will hopefully move to early userspace:

- Almost all of init/do_mounts\* (the beginning of this is already in place)

- ACPI table parsing

- Insert unwieldy subsystem that doesn't really need to be in kernel space here

If kinit doesn't meet your current needs and you've got bytes to burn, the klibc distribution includes a small Bourne-compatible shell (ash) and a number of other utilities, so you can replace kinit and build custom initramfs images that meet your needs exactly.

For questions and help, you can sign up for the early userspace mailing list at [https://www.zytor.com/mailman/listinfo/klibc](<https://www.zytor.com/mailman/listinfo/klibc>)

<a id="rst-how-does-it-work"></a>

### How does it work?

The kernel has currently 3 ways to mount the root filesystem:

- **a)** all required device and filesystem drivers compiled into the kernel, no initrd.  init/main.c:init() will call prepare_namespace() to mount the final root filesystem, based on the root= option and optional init= to run some other init binary than listed at the end of init/main.c:init().

- **b)** some device and filesystem drivers built as modules and stored in an initrd.  The initrd must contain a binary '/linuxrc' which is supposed to load these driver modules.  It is also possible to mount the final root filesystem via linuxrc and use the pivot_root syscall.  The initrd is mounted and executed via prepare_namespace().

- **c)** using initramfs.  The call to prepare_namespace() must be skipped. This means that a binary must do all the work.  Said binary can be stored into initramfs either via modifying usr/gen_init_cpio.c or via the new initrd format, an cpio archive.  It must be called "/init".  This binary is responsible to do all the things prepare_namespace() would do.

  To maintain backwards compatibility, the /init binary will only run if it comes via an initramfs cpio archive.  If this is not the case, init/main.c:init() will run prepare_namespace() to mount the final root and exec one of the predefined init binaries.

Bryan O'Sullivan &lt;[bos@serpentine.com](<mailto:bos@serpentine.com>)&gt;

---

# Compute Express Link

_Peios Kernel / Hardware and drivers / Driver development / Compute Express Link (CXL)_

> CXL device configuration has a complex handoff between platform (Hardware, BIOS, EFI), OS (early boot, core kernel, driver), and user policy decisions that have impacts on each other. The docs here break up configurations steps.

<a id="rst-compute-express-link"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

CXL device configuration has a complex handoff between platform (Hardware, BIOS, EFI), OS (early boot, core kernel, driver), and user policy decisions that have impacts on each other.  The docs here break up configurations steps.

**Overview**

- [Compute Express Link Driver Theory of Operation](</kernel/hardware/driver-api/cxl/theory-of-operation.md>)
- [Compute Express Link Subsystem Maturity Map](</kernel/hardware/driver-api/cxl/maturity-map.md>)
- [Compute Express Link: Linux Conventions](</kernel/hardware/driver-api/cxl/conventions.md>)

**Device Reference**

- [Devices and Protocols](</kernel/hardware/driver-api/cxl-devices/device-types.md>)

**Platform Configuration**

- [BIOS/EFI Configuration](</kernel/hardware/driver-api/cxl-platform/bios-and-efi.md>)
- [ACPI Tables](</kernel/hardware/driver-api/cxl-platform/acpi.md>)
- [Coherent Device Attribute Table (CDAT)](</kernel/hardware/driver-api/cxl-platform/cdat.md>)
- [Example Platform Configurations](</kernel/hardware/driver-api/cxl-platform/example-configs.md>)
- [CXL Device Hotplug](</kernel/hardware/driver-api/cxl-platform/device-hotplug.md>)

**Linux Kernel Configuration**

- [Overview](</kernel/hardware/driver-api/cxl-linux/overview.md>)
- [Linux Init (Early Boot)](</kernel/hardware/driver-api/cxl-linux/early-boot.md>)
- [CXL Driver Operation](</kernel/hardware/driver-api/cxl-linux/cxl-driver.md>)
- [DAX Driver Operation](</kernel/hardware/driver-api/cxl-linux/dax-driver.md>)
- [Memory Hotplug](</kernel/hardware/driver-api/cxl-linux/memory-hotplug.md>)
- [CXL Access Coordinates Computation](</kernel/hardware/driver-api/cxl-linux/access-coordinates.md>)

**Memory Allocation**

- [DAX Devices](</kernel/hardware/driver-api/cxl-allocation/dax.md>)
- [The Page Allocator](</kernel/hardware/driver-api/cxl-allocation/page-allocator.md>)
- [Reclaim](</kernel/hardware/driver-api/cxl-allocation/reclaim.md>)
- [Huge Pages](</kernel/hardware/driver-api/cxl-allocation/hugepages.md>)

---

# Compute Express Link: Linux Conventions

_Peios Kernel / Hardware and drivers / Driver development / Compute Express Link (CXL)_

> There exists shipping platforms that bend or break CXL specification expectations. Record the details and the rationale for those deviations. Borrow the ACPI Code First template format to capture the assumptions and tradeoffs such that…

<a id="rst-compute-express-link-linux-conventions"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

There exists shipping platforms that bend or break CXL specification expectations. Record the details and the rationale for those deviations. Borrow the ACPI Code First template format to capture the assumptions and tradeoffs such that multiple platform implementations can follow the same convention.

**Contents**

- [Resolve conflict between CFMWS, Platform Memory Holes, and Endpoint Decoders](</kernel/hardware/driver-api/cxl-conventions/cxl-lmh.md>)
- [ACPI PRM CXL Address Translation](</kernel/hardware/driver-api/cxl-conventions/cxl-atl.md>)
- [Template File](</kernel/hardware/driver-api/cxl-conventions/template.md>)

---

# Compute Express Link Subsystem Maturity Map

_Peios Kernel / Hardware and drivers / Driver development / Compute Express Link (CXL)_

> The Linux CXL subsystem tracks the dynamic CXL specification that continues to respond to new use cases with new features, capability updates and fixes. At any given point some aspects of the subsystem are more mature than others. While…

<a id="rst-compute-express-link-subsystem-maturity-map"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

The Linux CXL subsystem tracks the dynamic [CXL specification](<https://computeexpresslink.org/cxl-specification-landing-page>)<a id="rst-cxl-specification"></a> that continues to respond to new use cases with new features, capability updates and fixes. At any given point some aspects of the subsystem are more mature than others. While the periodic pull requests summarize the [work being incorporated each merge window](<https://lore.kernel.org/linux-cxl/?q=s%3APULL+s%3ACXL+tc%3Atorvalds+NOT+s%3ARe>)<a id="rst-work-being-incorporated-each-merge-window"></a>, those do not always convey progress relative to a starting point and a future end goal.

What follows is a coarse breakdown of the subsystem's major responsibilities along with a maturity score. The expectation is that the change-history of this document provides an overview summary of the subsystem maturation over time.

The maturity scores are:

- \[3\] Mature: Work in this area is complete and no changes on the horizon. Note that this score can regress from one kernel release to the next based on new test results or end user reports.

- \[2\] Stabilizing: Major functionality operational, common cases are mature, but known corner cases are still a work in progress.

- \[1\] Initial: Capability that has exited the Proof of Concept phase, but may still have significant gaps to close and fixes to apply as real world testing occurs.

- \[0\] Known gap: Feature is on a medium to long term horizon to implement.  If the specification has a feature that does not even have a '0' score in this document, there is a good chance that no one in the [linux-cxl@vger.kernel.org](<mailto:linux-cxl@vger.kernel.org>) community has started to look at it.

- X: Out of scope for kernel enabling, or kernel enabling not required

<a id="rst-feature-and-capabilities"></a>

## Feature and Capabilities

<a id="rst-enumeration-provisioning"></a>

### Enumeration / Provisioning

All of the fundamental enumeration an object model of the subsystem is in place, but there are several corner cases that are pending closure.

- \[2\] CXL Window Enumeration

  - \[2\] [Extended-linear memory-side cache](<#rst-extended-linear>)

  - \[0\] Low Memory-hole

  - \[X\] Hetero-interleave

- \[2\] Switch Enumeration

  - \[0\] CXL register enumeration link-up dependency

- \[2\] HDM Decoder Configuration

  - \[0\] Decoder target and granularity constraints

- \[2\] Performance enumeration

  - \[3\] Endpoint CDAT

  - \[3\] Switch CDAT

  - \[1\] CDAT to Core-mm integration

    - \[1\] x86

    - \[0\] Arm64

    - \[0\] All other arch.

  - \[0\] Shared link

- \[2\] Hotplug (see CXL Window Enumeration)

  - \[0\] Handle Soft Reserved conflicts

- \[0\] [RCH link status](<#rst-rch-link-status>)

- \[0\] Fabrics / G-FAM (chapter 7)

- \[0\] Global Access Endpoint

<a id="rst-ras"></a>

### RAS

In many ways CXL can be seen as a standardization of what would normally be handled by custom EDAC drivers. The open development here is mainly caused by the enumeration corner cases above.

- \[3\] Component events (OS)

- \[2\] Component events (FFM)

- \[1\] Endpoint protocol errors (OS)

- \[1\] Endpoint protocol errors (FFM)

- \[0\] Switch protocol errors (OS)

- \[1\] Switch protocol errors (FFM)

- \[2\] DPA-&gt;HPA Address translation

  > - \[1\] XOR Interleave translation (see CXL Window Enumeration)

- \[1\] Memory Failure coordination

- \[0\] Scrub control

- \[2\] ACPI error injection EINJ

  - \[0\] EINJ v2

  - \[X\] Compliance DOE

- \[2\] Native error injection

- \[3\] RCH error handling

- \[1\] VH error handling

- \[0\] PPR

- \[0\] Sparing

- \[0\] Device built in test

<a id="rst-mailbox-commands"></a>

### Mailbox commands

- \[3\] Firmware update

- \[3\] Health / Alerts

- \[1\] [Background commands](<#rst-background-commands>)

- \[3\] Sanitization

- \[3\] Security commands

- \[3\] RAW Command Debug Passthrough

- \[0\] CEL-only-validation Passthrough

- \[0\] Switch CCI

- \[3\] Timestamp

- \[1\] PMEM labels

- \[3\] PMEM GPF / Dirty Shutdown

- \[0\] Scan Media

<a id="rst-pmu"></a>

### PMU

- \[1\] Type 3 PMU

- \[0\] Switch USP/ DSP, Root Port

<a id="rst-security"></a>

### Security

- \[X\] CXL Trusted Execution Environment Security Protocol (TSP)

- \[X\] CXL IDE (subsumed by TSP)

<a id="rst-memory-pooling"></a>

### Memory-pooling

- \[1\] Hotplug of LDs (via PCI hotplug)

- \[0\] Dynamic Capacity Device (DCD) Support

<a id="rst-multi-host-sharing"></a>

### Multi-host sharing

- \[0\] Hardware coherent shared memory

- \[0\] Software managed coherency shared memory

<a id="rst-multi-host-memory"></a>

### Multi-host memory

- \[0\] Dynamic Capacity Device Support

- \[0\] Sharing

<a id="rst-accelerator"></a>

### Accelerator

- \[0\] Accelerator memory enumeration HDM-D (CXL 1.1/2.0 Type-2)

- \[0\] Accelerator memory enumeration HDM-DB (CXL 3.0 Type-2)

- \[0\] CXL.cache 68b (CXL 2.0)

- \[0\] CXL.cache 256b Cache IDs (CXL 3.0)

<a id="rst-user-flow-support"></a>

### User Flow Support

- \[2\] Inject &amp; clear poison by region offset

<a id="rst-details"></a>

## Details

<a id="rst-extended-linear"></a>

- **Extended-linear memory-side cache**: An HMAT proposal to enumerate the presence of a memory-side cache where the cache capacity extends the SRAT address range capacity. [See the ECN](<https://lore.kernel.org/linux-cxl/6650e4f835a0e_195e294a8@dwillia2-mobl3.amr.corp.intel.com.notmuch/>)<a id="rst-see-the-ecn"></a> for more details:

<a id="rst-rch-link-status"></a>

- **RCH Link Status**: RCH (Restricted CXL Host) topologies, end up hiding some standard registers like PCIe Link Status / Capabilities in the CXL RCRB (Root Complex Register Block).

<a id="rst-background-commands"></a>

- **Background commands**: The CXL background command mechanism is awkward as the single slot is monopolized potentially indefinitely by various commands. A [cancel on conflict](<http://lore.kernel.org/r/66035c2e8ba17_770232948b@dwillia2-xfh.jf.intel.com.notmuch>)<a id="rst-cancel-on-conflict"></a> facility is needed to make sure the kernel can ensure forward progress of priority commands.

---

# Compute Express Link Driver Theory of Operation

_Peios Kernel / Hardware and drivers / Driver development / Compute Express Link (CXL)_

> A Compute Express Link Memory Device is a CXL component that implements the CXL.mem protocol. It contains some amount of volatile memory, persistent memory, or both. It is enumerated as a PCI device for configuration and passing messages…

<a id="rst-compute-express-link-driver-theory-of-operation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

A Compute Express Link Memory Device is a CXL component that implements the CXL.mem protocol. It contains some amount of volatile memory, persistent memory, or both. It is enumerated as a PCI device for configuration and passing messages over an MMIO mailbox. Its contribution to the System Physical Address space is handled via HDM (Host Managed Device Memory) decoders that optionally define a device's contribution to an interleaved address range across multiple devices underneath a host-bridge or interleaved across host-bridges.

<a id="rst-the-cxl-bus"></a>

## The CXL Bus

Similar to how a RAID driver takes disk objects and assembles them into a new logical device, the CXL subsystem is tasked to take PCIe and ACPI objects and assemble them into a CXL.mem decode topology. The need for runtime configuration of the CXL.mem topology is also similar to RAID in that different environments with the same hardware configuration may decide to assemble the topology in contrasting ways. One may choose performance (RAID0) striping memory across multiple Host Bridges and endpoints while another may opt for fault tolerance and disable any striping in the CXL.mem topology.

Platform firmware enumerates a menu of interleave options at the "CXL root port" (Linux term for the top of the CXL decode topology). From there, PCIe topology dictates which endpoints can participate in which Host Bridge decode regimes. Each PCIe Switch in the path between the root and an endpoint introduces a point at which the interleave can be split. For example, platform firmware may say a given range only decodes to one Host Bridge, but that Host Bridge may in turn interleave cycles across multiple Root Ports. An intervening Switch between a port and an endpoint may interleave cycles across multiple Downstream Switch Ports, etc.

Here is a sample listing of a CXL topology defined by 'cxl_test'. The 'cxl_test' module generates an emulated CXL topology of 2 Host Bridges each with 2 Root Ports. Each of those Root Ports are connected to 2-way switches with endpoints connected to those downstream ports for a total of 8 endpoints:



```text
# cxl list -BEMPu -b cxl_test
{
  "bus":"root3",
  "provider":"cxl_test",
  "ports:root3":[
    {
      "port":"port5",
      "host":"cxl_host_bridge.1",
      "ports:port5":[
        {
          "port":"port8",
          "host":"cxl_switch_uport.1",
          "endpoints:port8":[
            {
              "endpoint":"endpoint9",
              "host":"mem2",
              "memdev":{
                "memdev":"mem2",
                "pmem_size":"256.00 MiB (268.44 MB)",
                "ram_size":"256.00 MiB (268.44 MB)",
                "serial":"0x1",
                "numa_node":1,
                "host":"cxl_mem.1"
              }
            },
            {
              "endpoint":"endpoint15",
              "host":"mem6",
              "memdev":{
                "memdev":"mem6",
                "pmem_size":"256.00 MiB (268.44 MB)",
                "ram_size":"256.00 MiB (268.44 MB)",
                "serial":"0x5",
                "numa_node":1,
                "host":"cxl_mem.5"
              }
            }
          ]
        },
        {
          "port":"port12",
          "host":"cxl_switch_uport.3",
          "endpoints:port12":[
            {
              "endpoint":"endpoint17",
              "host":"mem8",
              "memdev":{
                "memdev":"mem8",
                "pmem_size":"256.00 MiB (268.44 MB)",
                "ram_size":"256.00 MiB (268.44 MB)",
                "serial":"0x7",
                "numa_node":1,
                "host":"cxl_mem.7"
              }
            },
            {
              "endpoint":"endpoint13",
              "host":"mem4",
              "memdev":{
                "memdev":"mem4",
                "pmem_size":"256.00 MiB (268.44 MB)",
                "ram_size":"256.00 MiB (268.44 MB)",
                "serial":"0x3",
                "numa_node":1,
                "host":"cxl_mem.3"
              }
            }
          ]
        }
      ]
    },
    {
      "port":"port4",
      "host":"cxl_host_bridge.0",
      "ports:port4":[
        {
          "port":"port6",
          "host":"cxl_switch_uport.0",
          "endpoints:port6":[
            {
              "endpoint":"endpoint7",
              "host":"mem1",
              "memdev":{
                "memdev":"mem1",
                "pmem_size":"256.00 MiB (268.44 MB)",
                "ram_size":"256.00 MiB (268.44 MB)",
                "serial":"0",
                "numa_node":0,
                "host":"cxl_mem.0"
              }
            },
            {
              "endpoint":"endpoint14",
              "host":"mem5",
              "memdev":{
                "memdev":"mem5",
                "pmem_size":"256.00 MiB (268.44 MB)",
                "ram_size":"256.00 MiB (268.44 MB)",
                "serial":"0x4",
                "numa_node":0,
                "host":"cxl_mem.4"
              }
            }
          ]
        },
        {
          "port":"port10",
          "host":"cxl_switch_uport.2",
          "endpoints:port10":[
            {
              "endpoint":"endpoint16",
              "host":"mem7",
              "memdev":{
                "memdev":"mem7",
                "pmem_size":"256.00 MiB (268.44 MB)",
                "ram_size":"256.00 MiB (268.44 MB)",
                "serial":"0x6",
                "numa_node":0,
                "host":"cxl_mem.6"
              }
            },
            {
              "endpoint":"endpoint11",
              "host":"mem3",
              "memdev":{
                "memdev":"mem3",
                "pmem_size":"256.00 MiB (268.44 MB)",
                "ram_size":"256.00 MiB (268.44 MB)",
                "serial":"0x2",
                "numa_node":0,
                "host":"cxl_mem.2"
              }
            }
          ]
        }
      ]
    }
  ]
}
```

In that listing each "root", "port", and "endpoint" object correspond a kernel 'struct cxl_port' object. A 'cxl_port' is a device that can decode CXL.mem to its descendants. So "root" claims non-PCIe enumerable platform decode ranges and decodes them to "ports", "ports" decode to "endpoints", and "endpoints" represent the decode from SPA (System Physical Address) to DPA (Device Physical Address).

Continuing the RAID analogy, disks have both topology metadata and on-device metadata that determine RAID set assembly. CXL Port topology and CXL Port link status is metadata for CXL.mem set assembly. The CXL Port topology is enumerated by the arrival of a CXL.mem device. I.e. unless and until the PCIe core attaches the cxl_pci driver to a CXL Memory Expander there is no role for CXL Port objects. Conversely for hot-unplug / removal scenarios, there is no need for the Linux PCI core to tear down switch-level CXL resources because the endpoint -&gt;remove() event cleans up the port data that was established to support that Memory Expander.

The port metadata and potential decode schemes that a given memory device may participate can be determined via a command like:



```text
# cxl list -BDMu -d root -m mem3
{
  "bus":"root3",
  "provider":"cxl_test",
  "decoders:root3":[
    {
      "decoder":"decoder3.1",
      "resource":"0x8030000000",
      "size":"512.00 MiB (536.87 MB)",
      "volatile_capable":true,
      "nr_targets":2
    },
    {
      "decoder":"decoder3.3",
      "resource":"0x8060000000",
      "size":"512.00 MiB (536.87 MB)",
      "pmem_capable":true,
      "nr_targets":2
    },
    {
      "decoder":"decoder3.0",
      "resource":"0x8020000000",
      "size":"256.00 MiB (268.44 MB)",
      "volatile_capable":true,
      "nr_targets":1
    },
    {
      "decoder":"decoder3.2",
      "resource":"0x8050000000",
      "size":"256.00 MiB (268.44 MB)",
      "pmem_capable":true,
      "nr_targets":1
    }
  ],
  "memdevs:root3":[
    {
      "memdev":"mem3",
      "pmem_size":"256.00 MiB (268.44 MB)",
      "ram_size":"256.00 MiB (268.44 MB)",
      "serial":"0x2",
      "numa_node":0,
      "host":"cxl_mem.2"
    }
  ]
}
```

...which queries the CXL topology to ask "given CXL Memory Expander with a kernel device name of 'mem3' which platform level decode ranges may this device participate". A given expander can participate in multiple CXL.mem interleave sets simultaneously depending on how many decoder resources it has. In this example mem3 can participate in one or more of a PMEM interleave that spans two Host Bridges, a PMEM interleave that targets a single Host Bridge, a Volatile memory interleave that spans 2 Host Bridges, and a Volatile memory interleave that only targets a single Host Bridge.

Conversely the memory devices that can participate in a given platform level decode scheme can be determined via a command like the following:



```text
# cxl list -MDu -d 3.2
[
  {
    "memdevs":[
      {
        "memdev":"mem1",
        "pmem_size":"256.00 MiB (268.44 MB)",
        "ram_size":"256.00 MiB (268.44 MB)",
        "serial":"0",
        "numa_node":0,
        "host":"cxl_mem.0"
      },
      {
        "memdev":"mem5",
        "pmem_size":"256.00 MiB (268.44 MB)",
        "ram_size":"256.00 MiB (268.44 MB)",
        "serial":"0x4",
        "numa_node":0,
        "host":"cxl_mem.4"
      },
      {
        "memdev":"mem7",
        "pmem_size":"256.00 MiB (268.44 MB)",
        "ram_size":"256.00 MiB (268.44 MB)",
        "serial":"0x6",
        "numa_node":0,
        "host":"cxl_mem.6"
      },
      {
        "memdev":"mem3",
        "pmem_size":"256.00 MiB (268.44 MB)",
        "ram_size":"256.00 MiB (268.44 MB)",
        "serial":"0x2",
        "numa_node":0,
        "host":"cxl_mem.2"
      }
    ]
  },
  {
    "root decoders":[
      {
        "decoder":"decoder3.2",
        "resource":"0x8050000000",
        "size":"256.00 MiB (268.44 MB)",
        "pmem_capable":true,
        "nr_targets":1
      }
    ]
  }
]
```

...where the naming scheme for decoders is "decoder&lt;port_id&gt;.&lt;instance_id&gt;".

<a id="rst-driver-infrastructure"></a>

## Driver Infrastructure

This section covers the driver infrastructure for a CXL memory device.

<a id="rst-cxl-memory-device"></a>

### CXL Memory Device


This implements the PCI exclusive functionality for a CXL device as it is
defined by the Compute Express Link specification. CXL devices may surface
certain functionality even if it isn't CXL enabled. While this driver is
focused around the PCI specific aspects of a CXL device, it binds to the
specific CXL memory device class code, and therefore the implementation of
cxl_pci is focused around CXL memory devices.

- The driver has several responsibilities, mainly:
  - Create the memX device and register on the CXL bus.
  - Enumerate device's register interface and map them.
  - Registers nvdimm bridge device with cxl_core.
  - Registers a CXL mailbox with cxl_core.



#### <a id="c-__cxl_pci_mbox_send_cmd"></a>`__cxl_pci_mbox_send_cmd()`

```c
int __cxl_pci_mbox_send_cmd(struct cxl_mailbox *cxl_mbox, struct cxl_mbox_cmd *mbox_cmd)
```

Execute a mailbox command

**Parameters**

- `struct cxl_mailbox *cxl_mbox`: CXL mailbox context
- `struct cxl_mbox_cmd *mbox_cmd`: Command to send to the memory device.

**Context**

Any context. Expects mbox_mutex to be held.

**Return**

-ETIMEDOUT if timeout occurred waiting for completion. 0 on success.
Caller should check the return code in **mbox_cmd** to make sure it
succeeded.

**Description**

This is a generic form of the CXL mailbox send command thus only using the
registers defined by the mailbox capability ID - CXL 2.0 8.2.8.4. Memory
devices, and perhaps other types of CXL devices may have further information
available upon error conditions. Driver facilities wishing to send mailbox
commands should use the wrapper command.

The CXL spec allows for up to two mailboxes. The intention is for the primary
mailbox to be OS controlled and the secondary mailbox to be used by system
firmware. This allows the OS and firmware to communicate with the device and
not need to coordinate with each other. The driver only uses the primary
mailbox.



CXL memory endpoint devices and switches are CXL capable devices that are
participating in CXL.mem protocol. Their functionality builds on top of the
CXL.io protocol that allows enumerating and configuring components via
standard PCI mechanisms.

The cxl_mem driver owns kicking off the enumeration of this CXL.mem
capability. With the detection of a CXL capable endpoint, the driver will
walk up to find the platform specific port it is connected to, and determine
if there are intervening switches in the path. If there are switches, a
secondary action is to enumerate those (implemented in cxl_core). Finally the
cxl_mem driver adds the device it is bound to as a CXL endpoint-port for use
in higher level operations.



#### <a id="c-struct-cxl_memdev"></a>`struct cxl_memdev`

CXL bus object representing a Type-3 Memory Device

**Definition**

```c
struct cxl_memdev {
    struct device dev;
    struct cdev cdev;
    struct cxl_dev_state *cxlds;
    struct work_struct detach_work;
    struct cxl_nvdimm_bridge *cxl_nvb;
    struct cxl_nvdimm *cxl_nvd;
    struct cxl_port *endpoint;
    const struct cxl_memdev_attach *attach;
    int id;
    int depth;
    u8 scrub_cycle;
    int scrub_region_id;
    struct cxl_mem_err_rec *err_rec_array;
};
```

**Members**

- `dev`: driver core device object
- `cdev`: char dev core object for ioctl operations
- `cxlds`: The device state backing this device
- `detach_work`: active memdev lost a port in its ancestry
- `cxl_nvb`: coordinate removal of **cxl_nvd** if present
- `cxl_nvd`: optional bridge to an nvdimm if the device supports pmem
- `endpoint`: connection to the CXL port topology for this memory device
- `attach`: creator of this memdev depends on CXL link attach to operate
- `id`: id number of this memdev instance.
- `depth`: endpoint port depth
- `scrub_cycle`: current scrub cycle set for this device
- `scrub_region_id`: id number of a backed region (if any) for which current scrub cycle set
- `err_rec_array`: List of xarrarys to store the memdev error records to
  check attributes for a memory repair operation are from
  current boot.

#### <a id="c-struct-cxl_event_state"></a>`struct cxl_event_state`

Event log driver state

**Definition**

```c
struct cxl_event_state {
    struct cxl_get_event_payload *buf;
    struct mutex log_lock;
};
```

**Members**

- `buf`: Buffer to receive event data
- `log_lock`: Serialize event_buf and log use

#### <a id="c-struct-cxl_poison_state"></a>`struct cxl_poison_state`

Driver poison state info

**Definition**

```c
struct cxl_poison_state {
    u32 max_errors;
    unsigned long enabled_cmds[BITS_TO_LONGS(CXL_POISON_ENABLED_MAX)];
    struct cxl_mbox_poison_out *list_out;
    struct mutex mutex;
};
```

**Members**

- `max_errors`: Maximum media error records held in device cache
- `enabled_cmds`: All poison commands enabled in the CEL
- `list_out`: The poison list payload returned by device
- `mutex`: Protect reads of the poison list

**Description**

Reads of the poison list are synchronized to ensure that a reader
does not get an incomplete list because their request overlapped
(was interrupted or preceded by) another read request of the same
DPA range. CXL Spec 3.0 Section 8.2.9.8.4.1

#### <a id="c-struct-cxl_fw_state"></a>`struct cxl_fw_state`

Firmware upload / activation state

**Definition**

```c
struct cxl_fw_state {
    unsigned long state[BITS_TO_LONGS(CXL_FW_STATE_BITS)];
    bool oneshot;
    int num_slots;
    int cur_slot;
    int next_slot;
};
```

**Members**

- `state`: fw_uploader state bitmask
- `oneshot`: whether the fw upload fits in a single transfer
- `num_slots`: Number of FW slots available
- `cur_slot`: Slot number currently active
- `next_slot`: Slot number for the new firmware

#### <a id="c-struct-cxl_security_state"></a>`struct cxl_security_state`

Device security state

**Definition**

```c
struct cxl_security_state {
    unsigned long state;
    unsigned long enabled_cmds[BITS_TO_LONGS(CXL_SEC_ENABLED_MAX)];
    int poll_tmo_secs;
    bool sanitize_active;
    struct delayed_work poll_dwork;
    struct kernfs_node *sanitize_node;
};
```

**Members**

- `state`: state of last security operation
- `enabled_cmds`: All security commands enabled in the CEL
- `poll_tmo_secs`: polling timeout
- `sanitize_active`: sanitize completion pending
- `poll_dwork`: polling work item
- `sanitize_node`: sanitation sysfs file to notify

#### <a id="c-struct-cxl_dpa_perf"></a>`struct cxl_dpa_perf`

DPA performance property entry

**Definition**

```c
struct cxl_dpa_perf {
    struct range dpa_range;
    struct access_coordinate coord[ACCESS_COORDINATE_MAX];
    struct access_coordinate cdat_coord[ACCESS_COORDINATE_MAX];
    int qos_class;
};
```

**Members**

- `dpa_range`: range for DPA address
- `coord`: QoS performance data (i.e. latency, bandwidth)
- `cdat_coord`: raw QoS performance data from CDAT
- `qos_class`: QoS Class cookies

#### <a id="c-struct-cxl_dpa_partition"></a>`struct cxl_dpa_partition`

DPA partition descriptor

**Definition**

```c
struct cxl_dpa_partition {
    struct resource res;
    struct cxl_dpa_perf perf;
    enum cxl_partition_mode mode;
};
```

**Members**

- `res`: shortcut to the partition in the DPA resource tree (cxlds->dpa_res)
- `perf`: performance attributes of the partition from CDAT
- `mode`: operation mode for the DPA capacity, e.g. ram, pmem, dynamic...

#### <a id="c-struct-cxl_dev_state"></a>`struct cxl_dev_state`

The driver device state

**Definition**

```c
struct cxl_dev_state {
        struct device *dev;
        struct cxl_memdev *cxlmd;
        struct cxl_register_map reg_map;
        struct cxl_device_regs regs;
        int cxl_dvsec;
        bool rcd;
        bool media_ready;
        struct resource dpa_res;
        struct cxl_dpa_partition part[CXL_NR_PARTITIONS_MAX];
        unsigned int nr_partitions;
        u64 serial;
        enum cxl_devtype type;
        struct cxl_mailbox cxl_mbox;
    #ifdef CONFIG_CXL_FEATURES;
        struct cxl_features_state *cxlfs;
    #endif;
};
```

**Members**

- `dev`: The device associated with this CXL state
- `cxlmd`: The device representing the CXL.mem capabilities of **dev**
- `reg_map`: component and ras register mapping parameters
- `regs`: Class device "Device" registers
- `cxl_dvsec`: Offset to the PCIe device DVSEC
- `rcd`: operating in RCD mode (CXL 3.0 9.11.8 CXL Devices Attached to an RCH)
- `media_ready`: Indicate whether the device media is usable
- `dpa_res`: Overall DPA resource tree for the device
- `part`: DPA partition array
- `nr_partitions`: Number of DPA partitions
- `serial`: PCIe Device Serial Number
- `type`: Generic Memory Class device or Vendor Specific Memory device
- `cxl_mbox`: CXL mailbox context
- `cxlfs`: CXL features context

**Description**

cxl_dev_state represents the CXL driver/device state.  It provides an
interface to mailbox commands as well as some cached data about the device.
Currently only memory devices are represented.

#### <a id="c-struct-cxl_memdev_state"></a>`struct cxl_memdev_state`

Generic Type-3 Memory Device Class driver data

**Definition**

```c
struct cxl_memdev_state {
    struct cxl_dev_state cxlds;
    size_t lsa_size;
    char firmware_version[0x10];
    u64 total_bytes;
    u64 volatile_only_bytes;
    u64 persistent_only_bytes;
    u64 partition_align_bytes;
    u64 active_volatile_bytes;
    u64 active_persistent_bytes;
    struct cxl_event_state event;
    struct cxl_poison_state poison;
    struct cxl_security_state security;
    struct cxl_fw_state fw;
    struct notifier_block mce_notifier;
};
```

**Members**

- `cxlds`: Core driver state common across Type-2 and Type-3 devices
- `lsa_size`: Size of Label Storage Area
  (CXL 2.0 8.2.9.5.1.1 Identify Memory Device)
- `firmware_version`: Firmware version for the memory device.
- `total_bytes`: sum of all possible capacities
- `volatile_only_bytes`: hard volatile capacity
- `persistent_only_bytes`: hard persistent capacity
- `partition_align_bytes`: alignment size for partition-able capacity
- `active_volatile_bytes`: sum of hard + soft volatile
- `active_persistent_bytes`: sum of hard + soft persistent
- `event`: event log driver state
- `poison`: poison driver state info
- `security`: security driver state info
- `fw`: firmware upload / activation state
- `mce_notifier`: MCE notifier

**Description**

CXL 8.1.12.1 PCI Header - Class Code Register Memory Device defines
common memory device functionality like the presence of a mailbox and
the functionality related to that like Identify Memory Device and Get
Partition Info

See CXL 3.0 8.2.9.8.2 Capacity Configuration and Label Storage for
details on capacity parameters.

#### <a id="c-struct-cxl_mem_command"></a>`struct cxl_mem_command`

Driver representation of a memory device command

**Definition**

```c
struct cxl_mem_command {
        struct cxl_command_info info;
        enum cxl_opcode opcode;
        u32 flags;
    #define CXL_CMD_FLAG_FORCE_ENABLE BIT(0);
};
```

**Members**

- `info`: Command information as it exists for the UAPI
- `opcode`: The actual bits used for the mailbox protocol
- `flags`: Set of flags effecting driver behavior.

**Description**

* `CXL_CMD_FLAG_FORCE_ENABLE`: In cases of error, commands with this flag
  will be enabled by the driver regardless of what hardware may have
  advertised.

The cxl_mem_command is the driver's internal representation of commands that
are supported by the driver. Some of these commands may not be supported by
the hardware. The driver will use **info** to validate the fields passed in by
the user then submit the **opcode** to the hardware.

See struct cxl_command_info.

#### <a id="c-struct-cxl_hdm"></a>`struct cxl_hdm`

HDM Decoder registers and cached / decoded capabilities

**Definition**

```c
struct cxl_hdm {
    struct cxl_component_regs regs;
    unsigned int decoder_count;
    unsigned int target_count;
    unsigned int interleave_mask;
    unsigned long iw_cap_mask;
    struct cxl_port *port;
};
```

**Members**

- `regs`: mapped registers, see [`devm_cxl_setup_hdm()`](#c-devm_cxl_setup_hdm)
- `decoder_count`: number of decoders for this port
- `target_count`: for switch decoders, max downstream port targets
- `interleave_mask`: interleave granularity capability, see `check_interleave_cap()`
- `iw_cap_mask`: bitmask of supported interleave ways, see `check_interleave_cap()`
- `port`: mapped cxl_port, see [`devm_cxl_setup_hdm()`](#c-devm_cxl_setup_hdm)



#### <a id="c-set_exclusive_cxl_commands"></a>`set_exclusive_cxl_commands()`

```c
void set_exclusive_cxl_commands(struct cxl_memdev_state *mds, unsigned long *cmds)
```

atomically disable user cxl commands

**Parameters**

- `struct cxl_memdev_state *mds`: The device state to operate on
- `unsigned long *cmds`: bitmap of commands to mark exclusive

**Description**

Grab the cxl_memdev_rwsem in write mode to flush in-flight
invocations of the ioctl path and then disable future execution of
commands with the command ids set in **cmds**.

#### <a id="c-clear_exclusive_cxl_commands"></a>`clear_exclusive_cxl_commands()`

```c
void clear_exclusive_cxl_commands(struct cxl_memdev_state *mds, unsigned long *cmds)
```

atomically enable user cxl commands

**Parameters**

- `struct cxl_memdev_state *mds`: The device state to modify
- `unsigned long *cmds`: bitmap of commands to mark available for userspace

#### <a id="c-cxl_mem_get_fw_info"></a>`cxl_mem_get_fw_info()`

```c
int cxl_mem_get_fw_info(struct cxl_memdev_state *mds)
```

Get Firmware info

**Parameters**

- `struct cxl_memdev_state *mds`: The device data for the operation

**Description**

Retrieve firmware info for the device specified.

See CXL-3.0 8.2.9.3.1 Get FW Info

**Return**

0 if no error: or the result of the mailbox command.

#### <a id="c-cxl_mem_activate_fw"></a>`cxl_mem_activate_fw()`

```c
int cxl_mem_activate_fw(struct cxl_memdev_state *mds, int slot)
```

Activate Firmware

**Parameters**

- `struct cxl_memdev_state *mds`: The device data for the operation
- `int slot`: slot number to activate

**Description**

Activate firmware in a given slot for the device specified.

See CXL-3.0 8.2.9.3.3 Activate FW

**Return**

0 if no error: or the result of the mailbox command.

#### <a id="c-cxl_mem_abort_fw_xfer"></a>`cxl_mem_abort_fw_xfer()`

```c
int cxl_mem_abort_fw_xfer(struct cxl_memdev_state *mds)
```

Abort an in-progress FW transfer

**Parameters**

- `struct cxl_memdev_state *mds`: The device data for the operation

**Description**

Abort an in-progress firmware transfer for the device specified.

See CXL-3.0 8.2.9.3.2 Transfer FW

**Return**

0 if no error: or the result of the mailbox command.


<a id="rst-cxl-port"></a>

### CXL Port


The port driver enumerates dport via PCI and scans for HDM
(Host-managed-Device-Memory) decoder resources via the
**component_reg_phys** value passed in by the agent that registered the
port. All descendant ports of a CXL root port (described by platform
firmware) are managed in this drivers context. Each driver instance
is responsible for tearing down the driver context of immediate
descendant ports. The locking for this is validated by
CONFIG_PROVE_CXL_LOCKING.

The primary service this driver provides is presenting APIs to other
drivers to utilize the decoders, and indicating to userspace (via bind
status) the connectivity of the CXL.mem protocol throughout the
PCIe topology.


<a id="rst-cxl-core"></a>

### CXL Core


The CXL core objects like ports, decoders, and regions are shared
between the subsystem drivers cxl_acpi, cxl_pci, and core drivers
(port-driver, region-driver, nvdimm object-drivers... etc).



#### <a id="c-struct-cxl_register_map"></a>`struct cxl_register_map`

DVSEC harvested register block mapping parameters

**Definition**

```c
struct cxl_register_map {
    struct device *host;
    void __iomem *base;
    resource_size_t resource;
    resource_size_t max_size;
    u8 reg_type;
    union {
        struct cxl_component_reg_map component_map;
        struct cxl_device_reg_map device_map;
        struct cxl_pmu_reg_map pmu_map;
    };
};
```

**Members**

- `host`: device for devm operations and logging
- `base`: virtual base of the register-block-BAR + **block_offset**
- `resource`: physical resource base of the register block
- `max_size`: maximum mapping size to perform register search
- `reg_type`: see enum cxl_regloc_type
- `{unnamed_union}`: anonymous
- `component_map`: cxl_reg_map for component registers
- `device_map`: cxl_reg_maps for device registers
- `pmu_map`: cxl_reg_maps for CXL Performance Monitoring Units

#### <a id="c-struct-cxl_decoder"></a>`struct cxl_decoder`

Common CXL HDM Decoder Attributes

**Definition**

```c
struct cxl_decoder {
    struct device dev;
    int id;
    struct range hpa_range;
    int interleave_ways;
    int interleave_granularity;
    enum cxl_decoder_type target_type;
    struct cxl_region *region;
    unsigned long flags;
    u32 target_map[CXL_DECODER_MAX_INTERLEAVE];
    int (*commit)(struct cxl_decoder *cxld);
    void (*reset)(struct cxl_decoder *cxld);
};
```

**Members**

- `dev`: this decoder's device
- `id`: kernel device name id
- `hpa_range`: Host physical address range mapped by this decoder
- `interleave_ways`: number of cxl_dports in this decode
- `interleave_granularity`: data stride per dport
- `target_type`: accelerator vs expander (type2 vs type3) selector
- `region`: currently assigned region for this decoder
- `flags`: memory type capabilities and locking
- `target_map`: cached copy of hardware port-id list, available at init
  before all **dport** objects have been instantiated. While
  dport id is 8bit, CFMWS interleave targets are 32bits.
- `commit`: device/decoder-type specific callback to commit settings to hw
- `reset`: device/decoder-type specific callback to reset hw settings

#### <a id="c-struct-cxl_endpoint_decoder"></a>`struct cxl_endpoint_decoder`

Endpoint / SPA to DPA decoder

**Definition**

```c
struct cxl_endpoint_decoder {
    struct cxl_decoder cxld;
    struct resource *dpa_res;
    resource_size_t skip;
    enum cxl_decoder_state state;
    int part;
    int pos;
};
```

**Members**

- `cxld`: base cxl_decoder_object
- `dpa_res`: actively claimed DPA span of this decoder
- `skip`: offset into **dpa_res** where **cxld.hpa_range** maps
- `state`: autodiscovery state
- `part`: partition index this decoder maps
- `pos`: interleave position in **cxld.region**

#### <a id="c-struct-cxl_switch_decoder"></a>`struct cxl_switch_decoder`

Switch specific CXL HDM Decoder

**Definition**

```c
struct cxl_switch_decoder {
    struct cxl_decoder cxld;
    int nr_targets;
    struct cxl_dport *target[];
};
```

**Members**

- `cxld`: base cxl_decoder object
- `nr_targets`: number of elements in **target**
- `target`: active ordered target list in current decoder configuration

**Description**

The 'switch' decoder type represents the decoder instances of cxl_port's that
route from the root of a CXL memory decode topology to the endpoints. They
come in two flavors, root-level decoders, statically defined by platform
firmware, and mid-level decoders, where interleave-granularity,
interleave-width, and the target list are mutable.

#### <a id="c-struct-cxl_rd_ops"></a>`struct cxl_rd_ops`

CXL root decoder callback operations

**Definition**

```c
struct cxl_rd_ops {
    u64 (*hpa_to_spa)(struct cxl_root_decoder *cxlrd, u64 hpa);
    u64 (*spa_to_hpa)(struct cxl_root_decoder *cxlrd, u64 spa);
};
```

**Members**

- `hpa_to_spa`: Convert host physical address to system physical address
- `spa_to_hpa`: Convert system physical address to host physical address

#### <a id="c-struct-cxl_root_decoder"></a>`struct cxl_root_decoder`

Static platform CXL address decoder

**Definition**

```c
struct cxl_root_decoder {
    struct resource *res;
    resource_size_t cache_size;
    atomic_t region_id;
    void *platform_data;
    struct mutex range_lock;
    int qos_class;
    struct cxl_rd_ops ops;
    struct cxl_switch_decoder cxlsd;
};
```

**Members**

- `res`: host / parent resource for region allocations
- `cache_size`: extended linear cache size if exists, otherwise zero.
- `region_id`: region id for next region provisioning event
- `platform_data`: platform specific configuration data
- `range_lock`: sync region autodiscovery by address range
- `qos_class`: QoS performance class cookie
- `ops`: CXL root decoder operations
- `cxlsd`: base cxl switch decoder

#### <a id="c-struct-cxl_region_params"></a>`struct cxl_region_params`

region settings

**Definition**

```c
struct cxl_region_params {
    enum cxl_config_state state;
    uuid_t uuid;
    int interleave_ways;
    int interleave_granularity;
    struct resource *res;
    struct cxl_endpoint_decoder *targets[CXL_DECODER_MAX_INTERLEAVE];
    int nr_targets;
    resource_size_t cache_size;
};
```

**Members**

- `state`: allow the driver to lockdown further parameter changes
- `uuid`: unique id for persistent regions
- `interleave_ways`: number of endpoints in the region
- `interleave_granularity`: capacity each endpoint contributes to a stripe
- `res`: allocated iomem capacity for this region
- `targets`: active ordered targets in current decoder configuration
- `nr_targets`: number of targets
- `cache_size`: extended linear cache size if exists, otherwise zero.

**Description**

State transitions are protected by cxl_rwsem.region

#### <a id="c-struct-cxl_region"></a>`struct cxl_region`

CXL region

**Definition**

```c
struct cxl_region {
    struct device dev;
    int id;
    struct cxl_root_decoder *cxlrd;
    struct range hpa_range;
    enum cxl_partition_mode mode;
    enum cxl_decoder_type type;
    struct cxl_nvdimm_bridge *cxl_nvb;
    struct cxl_pmem_region *cxlr_pmem;
    unsigned long flags;
    struct cxl_region_params params;
    struct access_coordinate coord[ACCESS_COORDINATE_MAX];
    struct notifier_block node_notifier;
    struct notifier_block adist_notifier;
};
```

**Members**

- `dev`: This region's device
- `id`: This region's id. Id is globally unique across all regions
- `cxlrd`: Region's root decoder
- `hpa_range`: Address range occupied by the region
- `mode`: Operational mode of the mapped capacity
- `type`: Endpoint decoder target type
- `cxl_nvb`: nvdimm bridge for coordinating **cxlr_pmem** setup / shutdown
- `cxlr_pmem`: (for pmem regions) cached copy of the nvdimm bridge
- `flags`: Region state flags
- `params`: active + config params for the region
- `coord`: QoS access coordinates for the region
- `node_notifier`: notifier for setting the access coordinates to node
- `adist_notifier`: notifier for calculating the abstract distance of node

#### <a id="c-struct-cxl_port"></a>`struct cxl_port`

logical collection of upstream port devices and downstream port devices to construct a CXL memory decode hierarchy.

**Definition**

```c
struct cxl_port {
    struct device dev;
    struct device *uport_dev;
    struct device *host_bridge;
    int id;
    struct xarray dports;
    struct xarray endpoints;
    struct xarray regions;
    struct cxl_dport *parent_dport;
    struct ida decoder_ida;
    struct cxl_register_map reg_map;
    struct cxl_component_regs regs;
    int nr_dports;
    int hdm_end;
    int commit_end;
    bool dead;
    unsigned int depth;
    struct cxl_cdat {
        void *table;
        size_t length;
    } cdat;
    bool cdat_available;
    long pci_latency;
    resource_size_t component_reg_phys;
};
```

**Members**

- `dev`: this port's device
- `uport_dev`: PCI or platform device implementing the upstream port capability
- `host_bridge`: Shortcut to the platform attach point for this port
- `id`: id for port device-name
- `dports`: cxl_dport instances referenced by decoders
- `endpoints`: cxl_ep instances, endpoints that are a descendant of this port
- `regions`: cxl_region_ref instances, regions mapped by this port
- `parent_dport`: dport that points to this port in the parent
- `decoder_ida`: allocator for decoder ids
- `reg_map`: component and ras register mapping parameters
- `regs`: mapped component registers
- `nr_dports`: number of entries in **dports**
- `hdm_end`: track last allocated HDM decoder instance for allocation ordering
- `commit_end`: cursor to track highest committed decoder for commit ordering
- `dead`: last ep has been removed, force port re-creation
- `depth`: How deep this port is relative to the root. depth 0 is the root.
- `cdat`: Cached CDAT data
- `cdat_available`: Should a CDAT attribute be available in sysfs
- `pci_latency`: Upstream latency in picoseconds
- `component_reg_phys`: Physical address of component register

#### <a id="c-struct-cxl_root"></a>`struct cxl_root`

logical collection of root cxl_port items

**Definition**

```c
struct cxl_root {
    struct cxl_port port;
    struct cxl_root_ops ops;
};
```

**Members**

- `port`: cxl_port member
- `ops`: cxl root operations

#### <a id="c-struct-cxl_dport"></a>`struct cxl_dport`

CXL downstream port

**Definition**

```c
struct cxl_dport {
    struct device *dport_dev;
    struct cxl_register_map reg_map;
    int port_id;
    struct cxl_rcrb_info rcrb;
    bool rch;
    struct cxl_port *port;
    struct cxl_regs regs;
    struct access_coordinate coord[ACCESS_COORDINATE_MAX];
    long link_latency;
    int gpf_dvsec;
};
```

**Members**

- `dport_dev`: PCI bridge or firmware device representing the downstream link
- `reg_map`: component and ras register mapping parameters
- `port_id`: unique hardware identifier for dport in decoder target list
- `rcrb`: Data about the Root Complex Register Block layout
- `rch`: Indicate whether this dport was enumerated in RCH or VH mode
- `port`: reference to cxl_port that contains this downstream port
- `regs`: Dport parsed register blocks
- `coord`: access coordinates (bandwidth and latency performance attributes)
- `link_latency`: calculated PCIe downstream latency
- `gpf_dvsec`: Cached GPF port DVSEC

#### <a id="c-struct-cxl_ep"></a>`struct cxl_ep`

track an endpoint's interest in a port

**Definition**

```c
struct cxl_ep {
    struct device *ep;
    struct cxl_dport *dport;
    struct cxl_port *next;
};
```

**Members**

- `ep`: device that hosts a generic CXL endpoint (expander or accelerator)
- `dport`: which dport routes to this endpoint on **port**
- `next`: cxl switch port across the link attached to **dport** NULL if
  attached to an endpoint

#### <a id="c-struct-cxl_region_ref"></a>`struct cxl_region_ref`

track a region's interest in a port

**Definition**

```c
struct cxl_region_ref {
    struct cxl_port *port;
    struct cxl_decoder *decoder;
    struct cxl_region *region;
    struct xarray endpoints;
    int nr_targets_set;
    int nr_eps;
    int nr_targets;
};
```

**Members**

- `port`: point in topology to install this reference
- `decoder`: decoder assigned for **region** in **port**
- `region`: region for this reference
- `endpoints`: cxl_ep references for region members beneath **port**
- `nr_targets_set`: track how many targets have been programmed during setup
- `nr_eps`: number of endpoints beneath **port**
- `nr_targets`: number of distinct targets needed to reach **nr_eps**

#### <a id="c-struct-cxl_endpoint_dvsec_info"></a>`struct cxl_endpoint_dvsec_info`

Cached DVSEC info

**Definition**

```c
struct cxl_endpoint_dvsec_info {
    bool mem_enabled;
    int ranges;
    struct cxl_port *port;
    struct range dvsec_range[2];
};
```

**Members**

- `mem_enabled`: cached value of mem_enabled in the DVSEC at init time
- `ranges`: Number of active HDM ranges this device uses.
- `port`: endpoint port associated with this info instance
- `dvsec_range`: cached attributes of the ranges in the DVSEC, PCIE_DEVICE



#### <a id="c-add_cxl_resources"></a>`add_cxl_resources()`

```c
int add_cxl_resources(struct resource *cxl_res)
```

reflect CXL fixed memory windows in iomem_resource

**Parameters**

- `struct resource *cxl_res`: A standalone resource tree where each CXL window is a sibling

**Description**

Walk each CXL window in **cxl_res** and add it to iomem_resource potentially
expanding its boundaries to ensure that any conflicting resources become
children. If a window is expanded it may then conflict with a another window
entry and require the window to be truncated or trimmed. Consider this
situation:

```text
|-- "CXL Window 0" --||----- "CXL Window 1" -----|
|--------------- "System RAM" -------------|
```

...where platform firmware has established as System RAM resource across 2
windows, but has left some portion of window 1 for dynamic CXL region
provisioning. In this case "Window 0" will span the entirety of the "System
RAM" span, and "CXL Window 1" is truncated to the remaining tail past the end
of that "System RAM" resource.



Compute Express Link Host Managed Device Memory, starting with the
CXL 2.0 specification, is managed by an array of HDM Decoder register
instances per CXL port and per CXL endpoint. Define common helpers
for enumerating these registers and capabilities.



#### <a id="c-devm_cxl_setup_hdm"></a>`devm_cxl_setup_hdm()`

```c
struct cxl_hdm * devm_cxl_setup_hdm(struct cxl_port *port, struct cxl_endpoint_dvsec_info *info)
```

map HDM decoder component registers

**Parameters**

- `struct cxl_port *port`: cxl_port to map
- `struct cxl_endpoint_dvsec_info *info`: cached DVSEC range register info

#### <a id="c-request_skip"></a>`request_skip()`

```c
int request_skip(struct cxl_dev_state *cxlds, struct cxl_endpoint_decoder *cxled, const resource_size_t skip_base, const resource_size_t skip_len)
```

Track DPA 'skip' in **cxlds->dpa_res** resource tree

**Parameters**

- `struct cxl_dev_state *cxlds`: CXL.mem device context that parents **cxled**
- `struct cxl_endpoint_decoder *cxled`: Endpoint decoder establishing new allocation that skips lower DPA
- `const resource_size_t skip_base`: DPA \< start of new DPA allocation (DPAnew)
- `const resource_size_t skip_len`:

  **skip_base** + **skip_len** == DPAnew

**Description**

DPA 'skip' arises from out-of-sequence DPA allocation events relative
to free capacity across multiple partitions. It is a wasteful event
as usable DPA gets thrown away, but if a deployment has, for example,
a dual RAM+PMEM device, wants to use PMEM, and has unallocated RAM
DPA, the free RAM DPA must be sacrificed to start allocating PMEM.
See third "Implementation Note" in CXL 3.1 8.2.4.19.13 "Decoder
Protection" for more details.

A 'skip' always covers the last allocated DPA in a previous partition
to the start of the current partition to allocate.  Allocations never
start in the middle of a partition, and allocations are always
de-allocated in reverse order (see `cxl_dpa_free()`, or natural devm
unwind order from forced in-order allocation).

If **cxlds->nr_partitions** was guaranteed to be \<= 2 then the 'skip'
would always be contained to a single partition. Given
**cxlds->nr_partitions** may be > 2 it results in cases where the 'skip'
might span "tail capacity of partition\[0\], all of partition\[1\], ...,
all of partition\[N-1\]" to support allocating from partition\[N\]. That
in turn interacts with the partition 'struct resource' boundaries
within **cxlds->dpa_res** whereby 'skip' requests need to be divided by
partition. I.e. this is a quirk of using a 'struct resource' tree to
detect range conflicts while also tracking partition boundaries in
**cxlds->dpa_res**.

#### <a id="c-devm_cxl_enumerate_decoders"></a>`devm_cxl_enumerate_decoders()`

```c
int devm_cxl_enumerate_decoders(struct cxl_hdm *cxlhdm, struct cxl_endpoint_dvsec_info *info)
```

add decoder objects per HDM register set

**Parameters**

- `struct cxl_hdm *cxlhdm`: Structure to populate with HDM capabilities
- `struct cxl_endpoint_dvsec_info *info`: cached DVSEC range register info

#### <a id="c-devm_cxl_switch_port_decoders_setup"></a>`devm_cxl_switch_port_decoders_setup()`

```c
int devm_cxl_switch_port_decoders_setup(struct cxl_port *port)
```

allocate and setup switch decoders

**Parameters**

- `struct cxl_port *port`: CXL port context

**Description**

Return 0 or -errno on error

#### <a id="c-devm_cxl_endpoint_decoders_setup"></a>`devm_cxl_endpoint_decoders_setup()`

```c
int devm_cxl_endpoint_decoders_setup(struct cxl_port *port)
```

allocate and setup endpoint decoders

**Parameters**

- `struct cxl_port *port`: CXL port context

**Description**

Return 0 or -errno on error



#### <a id="c-cxl_coordinates_combine"></a>`cxl_coordinates_combine()`

```c
void cxl_coordinates_combine(struct access_coordinate *out, struct access_coordinate *c1, struct access_coordinate *c2)
```

Combine the two input coordinates

**Parameters**

- `struct access_coordinate *out`: Output coordinate of c1 and c2 combined
- `struct access_coordinate *c1`: input coordinates
- `struct access_coordinate *c2`: input coordinates

#### <a id="c-cxl_endpoint_gather_bandwidth"></a>`cxl_endpoint_gather_bandwidth()`

```c
int cxl_endpoint_gather_bandwidth(struct cxl_region *cxlr, struct cxl_endpoint_decoder *cxled, struct xarray *usp_xa, bool *gp_is_root)
```

collect all the endpoint bandwidth in an xarray

**Parameters**

- `struct cxl_region *cxlr`: CXL region for the bandwidth calculation
- `struct cxl_endpoint_decoder *cxled`: endpoint decoder to start on
- `struct xarray *usp_xa`: (output) the xarray that collects all the bandwidth coordinates
  indexed by the upstream device with data of 'struct cxl_perf_ctx'.
- `bool *gp_is_root`: (output) bool of whether the grandparent is cxl root.

**Return**

0 for success or -errno

**Description**

Collects aggregated endpoint bandwidth and store the bandwidth in
an xarray indexed by the upstream device of the switch or the RP
device. Each endpoint consists the minimum of the bandwidth from DSLBIS
from the endpoint CDAT, the endpoint upstream link bandwidth, and the
bandwidth from the SSLBIS of the switch CDAT for the switch upstream port to
the downstream port that's associated with the endpoint. If the
device is directly connected to a RP, then no SSLBIS is involved.

#### <a id="c-cxl_switch_gather_bandwidth"></a>`cxl_switch_gather_bandwidth()`

```c
struct xarray * cxl_switch_gather_bandwidth(struct cxl_region *cxlr, struct xarray *input_xa, bool *gp_is_root)
```

collect all the bandwidth at switch level in an xarray

**Parameters**

- `struct cxl_region *cxlr`: The region being operated on
- `struct xarray *input_xa`: xarray indexed by upstream device of a switch with data of 'struct
  cxl_perf_ctx'
- `bool *gp_is_root`: (output) bool of whether the grandparent is cxl root.

**Return**

a xarray of resulting cxl_perf_ctx per parent switch or root port
or ERR_PTR(-errno)

**Description**

Iterate through the xarray. Take the minimum of the downstream calculated
bandwidth, the upstream link bandwidth, and the SSLBIS of the upstream
switch if exists. Sum the resulting bandwidth under the switch upstream
device or a RP device. The function can be iterated over multiple switches
if the switches are present.

#### <a id="c-cxl_rp_gather_bandwidth"></a>`cxl_rp_gather_bandwidth()`

```c
struct xarray * cxl_rp_gather_bandwidth(struct xarray *xa)
```

handle the root port level bandwidth collection

**Parameters**

- `struct xarray *xa`: the xarray that holds the cxl_perf_ctx that has the bandwidth calculated
  below each root port device.

**Return**

xarray that holds cxl_perf_ctx per host bridge or ERR_PTR(-errno)

#### <a id="c-cxl_hb_gather_bandwidth"></a>`cxl_hb_gather_bandwidth()`

```c
struct xarray * cxl_hb_gather_bandwidth(struct xarray *xa)
```

handle the host bridge level bandwidth collection

**Parameters**

- `struct xarray *xa`: the xarray that holds the cxl_perf_ctx that has the bandwidth calculated
  below each host bridge.

**Return**

xarray that holds cxl_perf_ctx per ACPI0017 device or ERR_PTR(-errno)

#### <a id="c-cxl_region_update_bandwidth"></a>`cxl_region_update_bandwidth()`

```c
void cxl_region_update_bandwidth(struct cxl_region *cxlr, struct xarray *input_xa)
```

Update the bandwidth access coordinates of a region

**Parameters**

- `struct cxl_region *cxlr`: The region being operated on
- `struct xarray *input_xa`: xarray holds cxl_perf_ctx with calculated bandwidth per ACPI0017 instance

#### <a id="c-cxl_region_shared_upstream_bandwidth_update"></a>`cxl_region_shared_upstream_bandwidth_update()`

```c
void cxl_region_shared_upstream_bandwidth_update(struct cxl_region *cxlr)
```

Recalculate the bandwidth for the region

**Parameters**

- `struct cxl_region *cxlr`: the cxl region to recalculate

**Description**

The function walks the topology from bottom up and calculates the bandwidth. It
starts at the endpoints, processes at the switches if any, processes at the rootport
level, at the host bridge level, and finally aggregates at the region.



The CXL core provides a set of interfaces that can be consumed by CXL aware
drivers. The interfaces allow for creation, modification, and destruction of
regions, memory devices, ports, and decoders. CXL aware drivers must register
with the CXL core via these interfaces in order to be able to participate in
cross-device interleave coordination. The CXL core also establishes and
maintains the bridge to the nvdimm subsystem.

CXL core introduces sysfs hierarchy to control the devices that are
instantiated by the core.



#### <a id="c-devm_cxl_add_port"></a>`devm_cxl_add_port()`

```c
struct cxl_port * devm_cxl_add_port(struct device *host, struct device *uport_dev, resource_size_t component_reg_phys, struct cxl_dport *parent_dport)
```

register a cxl_port in CXL memory decode hierarchy

**Parameters**

- `struct device *host`: host device for devm operations
- `struct device *uport_dev`: "physical" device implementing this upstream port
- `resource_size_t component_reg_phys`: (optional) for configurable cxl_port instances
- `struct cxl_dport *parent_dport`: next hop up in the CXL memory decode hierarchy

#### <a id="c-devm_cxl_add_dport"></a>`devm_cxl_add_dport()`

```c
struct cxl_dport * devm_cxl_add_dport(struct cxl_port *port, struct device *dport_dev, int port_id, resource_size_t component_reg_phys)
```

append VH downstream port data to a cxl_port

**Parameters**

- `struct cxl_port *port`: the cxl_port that references this dport
- `struct device *dport_dev`: firmware or PCI device representing the dport
- `int port_id`: identifier for this dport in a decoder's target list
- `resource_size_t component_reg_phys`: optional location of CXL component registers

**Description**

Note that dports are appended to the devm release action's of the
either the port's host (for root ports), or the port itself (for
switch ports)

#### <a id="c-devm_cxl_add_rch_dport"></a>`devm_cxl_add_rch_dport()`

```c
struct cxl_dport * devm_cxl_add_rch_dport(struct cxl_port *port, struct device *dport_dev, int port_id, resource_size_t rcrb)
```

append RCH downstream port data to a cxl_port

**Parameters**

- `struct cxl_port *port`: the cxl_port that references this dport
- `struct device *dport_dev`: firmware or PCI device representing the dport
- `int port_id`: identifier for this dport in a decoder's target list
- `resource_size_t rcrb`: mandatory location of a Root Complex Register Block

**Description**

See CXL 3.0 9.11.8 CXL Devices Attached to an RCH

#### <a id="c-cxl_add_ep"></a>`cxl_add_ep()`

```c
int cxl_add_ep(struct cxl_dport *dport, struct device *ep_dev)
```

register an endpoint's interest in a port

**Parameters**

- `struct cxl_dport *dport`: the dport that routes to **ep_dev**
- `struct device *ep_dev`: device representing the endpoint

**Description**

Intermediate CXL ports are scanned based on the arrival of endpoints.
When those endpoints depart the port can be destroyed once all
endpoints that care about that port have been removed.

#### <a id="c-find_cxl_port_by_uport"></a>`find_cxl_port_by_uport()`

```c
struct cxl_port * find_cxl_port_by_uport(struct device *uport_dev)
```

Find a CXL port device companion

**Parameters**

- `struct device *uport_dev`: Device that acts as a switch or endpoint in the CXL hierarchy

**Description**

In the case of endpoint ports recall that port->uport_dev points to a 'struct
cxl_memdev' device. So, the **uport_dev** argument is the parent device of the
'struct cxl_memdev' in that case.

Function takes a device reference on the port device. Caller should do a
[`put_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-put_device) when done.

#### <a id="c-cxl_decoder_init"></a>`cxl_decoder_init()`

```c
int cxl_decoder_init(struct cxl_port *port, struct cxl_decoder *cxld)
```

Common decoder setup / initialization

**Parameters**

- `struct cxl_port *port`: owning port of this decoder
- `struct cxl_decoder *cxld`: common decoder properties to initialize

**Description**

A port may contain one or more decoders. Each of those decoders
enable some address space for CXL.mem utilization. A decoder is
expected to be configured by the caller before registering via
[`cxl_decoder_add()`](#c-cxl_decoder_add)

#### <a id="c-cxl_root_decoder_alloc"></a>`cxl_root_decoder_alloc()`

```c
struct cxl_root_decoder * cxl_root_decoder_alloc(struct cxl_port *port, unsigned int nr_targets)
```

Allocate a root level decoder

**Parameters**

- `struct cxl_port *port`: owning CXL root of this decoder
- `unsigned int nr_targets`: static number of downstream targets

**Return**

A new cxl decoder to be registered by [`cxl_decoder_add()`](#c-cxl_decoder_add). A
'CXL root' decoder is one that decodes from a top-level / static platform
firmware description of CXL resources into a CXL standard decode
topology.

#### <a id="c-cxl_switch_decoder_alloc"></a>`cxl_switch_decoder_alloc()`

```c
struct cxl_switch_decoder * cxl_switch_decoder_alloc(struct cxl_port *port, unsigned int nr_targets)
```

Allocate a switch level decoder

**Parameters**

- `struct cxl_port *port`: owning CXL switch port of this decoder
- `unsigned int nr_targets`: max number of dynamically addressable downstream targets

**Return**

A new cxl decoder to be registered by [`cxl_decoder_add()`](#c-cxl_decoder_add). A
'switch' decoder is any decoder that can be enumerated by PCIe
topology and the HDM Decoder Capability. This includes the decoders
that sit between Switch Upstream Ports / Switch Downstream Ports and
Host Bridges / Root Ports.

#### <a id="c-cxl_endpoint_decoder_alloc"></a>`cxl_endpoint_decoder_alloc()`

```c
struct cxl_endpoint_decoder * cxl_endpoint_decoder_alloc(struct cxl_port *port)
```

Allocate an endpoint decoder

**Parameters**

- `struct cxl_port *port`: owning port of this decoder

**Return**

A new cxl decoder to be registered by [`cxl_decoder_add()`](#c-cxl_decoder_add)

#### <a id="c-cxl_decoder_add_locked"></a>`cxl_decoder_add_locked()`

```c
int cxl_decoder_add_locked(struct cxl_decoder *cxld)
```

Add a decoder with targets

**Parameters**

- `struct cxl_decoder *cxld`: The cxl decoder allocated by cxl_\<type>`_decoder_alloc()`

**Description**

Certain types of decoders may not have any targets. The main example of this
is an endpoint device. A more awkward example is a hostbridge whose root
ports get hot added (technically possible, though unlikely).

This is the locked variant of [`cxl_decoder_add()`](#c-cxl_decoder_add).

**Context**

Process context. Expects the device lock of the port that owns the
**cxld** to be held.

**Return**

Negative error code if the decoder wasn't properly configured; else
returns 0.

#### <a id="c-cxl_decoder_add"></a>`cxl_decoder_add()`

```c
int cxl_decoder_add(struct cxl_decoder *cxld)
```

Add a decoder with targets

**Parameters**

- `struct cxl_decoder *cxld`: The cxl decoder allocated by cxl_\<type>`_decoder_alloc()`

**Description**

This is the unlocked variant of [`cxl_decoder_add_locked()`](#c-cxl_decoder_add_locked).
See [`cxl_decoder_add_locked()`](#c-cxl_decoder_add_locked).

**Context**

Process context. Takes and releases the device lock of the port that
owns the **cxld**.

#### <a id="c-__cxl_driver_register"></a>`__cxl_driver_register()`

```c
int __cxl_driver_register(struct cxl_driver *cxl_drv, struct module *owner, const char *modname)
```

register a driver for the cxl bus

**Parameters**

- `struct cxl_driver *cxl_drv`: cxl driver structure to attach
- `struct module *owner`: owning module/driver
- `const char *modname`: KBUILD_MODNAME for parent driver

#### <a id="c-cxl_endpoint_get_perf_coordinates"></a>`cxl_endpoint_get_perf_coordinates()`

```c
int cxl_endpoint_get_perf_coordinates(struct cxl_port *port, struct access_coordinate *coord)
```

Retrieve performance numbers stored in dports of CXL path

**Parameters**

- `struct cxl_port *port`: endpoint cxl_port
- `struct access_coordinate *coord`: output performance data

**Return**

errno on failure, 0 on success.



Compute Express Link protocols are layered on top of PCIe. CXL core provides
a set of helpers for CXL interactions which occur via PCIe.



#### <a id="c-devm_cxl_add_dport_by_dev"></a>`devm_cxl_add_dport_by_dev()`

```c
struct cxl_dport * devm_cxl_add_dport_by_dev(struct cxl_port *port, struct device *dport_dev)
```

allocate a dport by dport device

**Parameters**

- `struct cxl_port *port`: cxl_port that hosts the dport
- `struct device *dport_dev`: 'struct device' of the dport

**Description**

Returns the allocated dport on success or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) of -errno on error

#### <a id="c-cxl_hdm_decode_init"></a>`cxl_hdm_decode_init()`

```c
int cxl_hdm_decode_init(struct cxl_dev_state *cxlds, struct cxl_hdm *cxlhdm, struct cxl_endpoint_dvsec_info *info)
```

Setup HDM decoding for the endpoint

**Parameters**

- `struct cxl_dev_state *cxlds`: Device state
- `struct cxl_hdm *cxlhdm`: Mapped HDM decoder Capability
- `struct cxl_endpoint_dvsec_info *info`: Cached DVSEC range registers info

**Description**

Try to enable the endpoint's HDM Decoder Capability

#### <a id="c-read_cdat_data"></a>`read_cdat_data()`

```c
void read_cdat_data(struct cxl_port *port)
```

Read the CDAT data on this port

**Parameters**

- `struct cxl_port *port`: Port to read data from

**Description**

This call will sleep waiting for responses from the DOE mailbox.

#### <a id="c-cxl_pci_get_latency"></a>`cxl_pci_get_latency()`

```c
long cxl_pci_get_latency(struct pci_dev *pdev)
```

calculate the link latency for the PCIe link

**Parameters**

- `struct pci_dev *pdev`: PCI device

**Return**

calculated latency or 0 for no latency

**Description**

CXL Memory Device SW Guide v1.0 2.11.4 Link latency calculation
Link latency = LinkPropagationLatency + FlitLatency + RetimerLatency
LinkProgationLatency is negligible, so 0 will be used
RetimerLatency is assumed to be negligible and 0 will be used
FlitLatency = FlitSize / LinkBandwidth
FlitSize is defined by spec. CXL rev3.0 4.2.1.
68B flit is used up to 32GT/s. >32GT/s, 256B flit size is used.
The FlitLatency is converted to picoseconds.



The core CXL PMEM infrastructure supports persistent memory
provisioning and serves as a bridge to the LIBNVDIMM subsystem. A CXL
'bridge' device is added at the root of a CXL device topology if
platform firmware advertises at least one persistent memory capable
CXL window. That root-level bridge corresponds to a LIBNVDIMM 'bus'
device. Then for each cxl_memdev in the CXL device topology a bridge
device is added to host a LIBNVDIMM dimm object. When these bridges
are registered native LIBNVDIMM uapis are translated to CXL
operations, for example, namespace label access commands.



#### <a id="c-cxl_find_nvdimm_bridge"></a>`cxl_find_nvdimm_bridge()`

```c
struct cxl_nvdimm_bridge * cxl_find_nvdimm_bridge(struct cxl_port *port)
```

find a bridge device relative to a port

**Parameters**

- `struct cxl_port *port`: any descendant port of an nvdimm-bridge associated
  root-cxl-port

#### <a id="c-devm_cxl_add_nvdimm"></a>`devm_cxl_add_nvdimm()`

```c
int devm_cxl_add_nvdimm(struct device *host, struct cxl_port *port, struct cxl_memdev *cxlmd)
```

add a bridge between a cxl_memdev and an nvdimm

**Parameters**

- `struct device *host`: host device for devm operations
- `struct cxl_port *port`: any port in the CXL topology to find the nvdimm-bridge device
- `struct cxl_memdev *cxlmd`: parent of the to be created cxl_nvdimm device

**Return**

0 on success negative error code on failure.



CXL device capabilities are enumerated by PCI DVSEC (Designated
Vendor-specific) and / or descriptors provided by platform firmware.
They can be defined as a set like the device and component registers
mandated by CXL Section 8.1.12.2 Memory Device PCIe Capabilities and
Extended Capabilities, or they can be individual capabilities
appended to bridged and endpoint devices.

Provide common infrastructure for enumerating and mapping these
discrete capabilities.



#### <a id="c-cxl_probe_component_regs"></a>`cxl_probe_component_regs()`

```c
void cxl_probe_component_regs(struct device *dev, void __iomem *base, struct cxl_component_reg_map *map)
```

Detect CXL Component register blocks

**Parameters**

- `struct device *dev`: Host device of the **base** mapping
- `void __iomem *base`: Mapping containing the HDM Decoder Capability Header
- `struct cxl_component_reg_map *map`: Map object describing the register block information found

**Description**

See CXL 2.0 8.2.4 Component Register Layout and Definition
See CXL 2.0 8.2.5.5 CXL Device Register Interface

Probe for component register information and return it in map object.

#### <a id="c-cxl_probe_device_regs"></a>`cxl_probe_device_regs()`

```c
void cxl_probe_device_regs(struct device *dev, void __iomem *base, struct cxl_device_reg_map *map)
```

Detect CXL Device register blocks

**Parameters**

- `struct device *dev`: Host device of the **base** mapping
- `void __iomem *base`: Mapping of CXL 2.0 8.2.8 CXL Device Register Interface
- `struct cxl_device_reg_map *map`: Map object describing the register block information found

**Description**

Probe for device register information and return it in map object.

#### <a id="c-cxl_find_regblock_instance"></a>`cxl_find_regblock_instance()`

```c
int cxl_find_regblock_instance(struct pci_dev *pdev, enum cxl_regloc_type type, struct cxl_register_map *map, unsigned int index)
```

Locate a register block by type / index

**Parameters**

- `struct pci_dev *pdev`: The CXL PCI device to enumerate.
- `enum cxl_regloc_type type`: Register Block Indicator id
- `struct cxl_register_map *map`: Enumeration output, clobbered on error
- `unsigned int index`: Index into which particular instance of a regblock wanted in the
  order found in register locator DVSEC.

**Return**

0 if register block enumerated, negative error code otherwise

**Description**

A CXL DVSEC may point to one or more register blocks, search for them
by **type** and **index**.

#### <a id="c-cxl_find_regblock"></a>`cxl_find_regblock()`

```c
int cxl_find_regblock(struct pci_dev *pdev, enum cxl_regloc_type type, struct cxl_register_map *map)
```

Locate register blocks by type

**Parameters**

- `struct pci_dev *pdev`: The CXL PCI device to enumerate.
- `enum cxl_regloc_type type`: Register Block Indicator id
- `struct cxl_register_map *map`: Enumeration output, clobbered on error

**Return**

0 if register block enumerated, negative error code otherwise

**Description**

A CXL DVSEC may point to one or more register blocks, search for them
by **type**.

#### <a id="c-cxl_count_regblock"></a>`cxl_count_regblock()`

```c
int cxl_count_regblock(struct pci_dev *pdev, enum cxl_regloc_type type)
```

Count instances of a given regblock type.

**Parameters**

- `struct pci_dev *pdev`: The CXL PCI device to enumerate.
- `enum cxl_regloc_type type`: Register Block Indicator id

**Description**

Some regblocks may be repeated. Count how many instances.

**Return**

non-negative count of matching regblocks, negative error code otherwise.



Core implementation of the CXL 2.0 Type-3 Memory Device Mailbox. The
implementation is used by the cxl_pci driver to initialize the device
and implement the cxl_mem.h IOCTL UAPI. It also implements the
backend of the `cxl_pmem_ctl()` transport for LIBNVDIMM.



#### <a id="c-cxl_internal_send_cmd"></a>`cxl_internal_send_cmd()`

```c
int cxl_internal_send_cmd(struct cxl_mailbox *cxl_mbox, struct cxl_mbox_cmd *mbox_cmd)
```

Kernel internal interface to send a mailbox command

**Parameters**

- `struct cxl_mailbox *cxl_mbox`: CXL mailbox context
- `struct cxl_mbox_cmd *mbox_cmd`: initialized command to execute

**Context**

Any context.

**Return**

* %>=0      - Number of bytes returned in **out**.
* `-E2BIG`   - Payload is too large for hardware.
* `-EBUSY`   - Couldn't acquire exclusive mailbox access.
* `-EFAULT`  - Hardware error occurred.
* `-ENXIO`   - Command completed, but device reported an error.
* `-EIO`     - Unexpected output size.

**Description**

Mailbox commands may execute successfully yet the device itself reported an
error. While this distinction can be useful for commands from userspace, the
kernel will only be able to use results when both are successful.

#### <a id="c-cxl_payload_from_user_allowed"></a>`cxl_payload_from_user_allowed()`

```c
bool cxl_payload_from_user_allowed(u16 opcode, void *payload_in, size_t in_size)
```

Check contents of in_payload.

**Parameters**

- `u16 opcode`: The mailbox command opcode.
- `void *payload_in`: Pointer to the input payload passed in from user space.
- `size_t in_size`: Size of **payload_in** in bytes.

**Return**

* true      - payload_in passes check for **opcode**.
* false     - payload_in contains invalid or unsupported values.

**Description**

The driver may inspect payload contents before sending a mailbox
command from user space to the device. The intent is to reject
commands with input payloads that are known to be unsafe. This
check is not intended to replace the users careful selection of
mailbox command parameters and makes no guarantee that the user
command will succeed, nor that it is appropriate.

The specific checks are determined by the opcode.

#### <a id="c-cxl_validate_cmd_from_user"></a>`cxl_validate_cmd_from_user()`

```c
int cxl_validate_cmd_from_user(struct cxl_mbox_cmd *mbox_cmd, struct cxl_mailbox *cxl_mbox, const struct cxl_send_command *send_cmd)
```

Check fields for CXL_MEM_SEND_COMMAND.

**Parameters**

- `struct cxl_mbox_cmd *mbox_cmd`: Sanitized and populated `struct cxl_mbox_cmd`.
- `struct cxl_mailbox *cxl_mbox`: CXL mailbox context
- `const struct cxl_send_command *send_cmd`: [`struct cxl_send_command`](#c-struct-cxl_send_command) copied in from userspace.

**Return**

* `0`        - **out_cmd** is ready to send.
* `-ENOTTY`  - Invalid command specified.
* `-EINVAL`  - Reserved fields or invalid values were used.
* `-ENOMEM`  - Input or output buffer wasn't sized properly.
* `-EPERM`   - Attempted to use a protected command.
* `-EBUSY`   - Kernel has claimed exclusive access to this opcode

**Description**

The result of this command is a fully validated command in **mbox_cmd** that is
safe to send to the hardware.

#### <a id="c-handle_mailbox_cmd_from_user"></a>`handle_mailbox_cmd_from_user()`

```c
int handle_mailbox_cmd_from_user(struct cxl_mailbox *cxl_mbox, struct cxl_mbox_cmd *mbox_cmd, u64 out_payload, s32 *size_out, u32 *retval)
```

Dispatch a mailbox command for userspace.

**Parameters**

- `struct cxl_mailbox *cxl_mbox`: The mailbox context for the operation.
- `struct cxl_mbox_cmd *mbox_cmd`: The validated mailbox command.
- `u64 out_payload`: Pointer to userspace's output payload.
- `s32 *size_out`: (Input) Max payload size to copy out.
  (Output) Payload size hardware generated.
- `u32 *retval`: Hardware generated return code from the operation.

**Return**

* `0`        - Mailbox transaction succeeded. This implies the mailbox
  protocol completed successfully not that the operation itself
  was successful.
* `-ENOMEM`  - Couldn't allocate a bounce buffer.
* `-EFAULT`  - Something happened with copy_to/from_user.
* `-EINTR`   - Mailbox acquisition interrupted.
* `-EXXX`    - Transaction level failures.

**Description**

Dispatches a mailbox command on behalf of a userspace request.
The output payload is copied to userspace.

See `cxl_send_cmd()`.

#### <a id="c-cxl_walk_cel"></a>`cxl_walk_cel()`

```c
void cxl_walk_cel(struct cxl_memdev_state *mds, size_t size, u8 *cel)
```

Walk through the Command Effects Log.

**Parameters**

- `struct cxl_memdev_state *mds`: The driver data for the operation
- `size_t size`: Length of the Command Effects Log.
- `u8 *cel`: CEL

**Description**

Iterate over each entry in the CEL and determine if the driver supports the
command. If so, the command is enabled for the device and can be used later.

#### <a id="c-cxl_enumerate_cmds"></a>`cxl_enumerate_cmds()`

```c
int cxl_enumerate_cmds(struct cxl_memdev_state *mds)
```

Enumerate commands for a device.

**Parameters**

- `struct cxl_memdev_state *mds`: The driver data for the operation

**Description**

Returns 0 if enumerate completed successfully.

CXL devices have optional support for certain commands. This function will
determine the set of supported commands for the hardware and update the
enabled_cmds bitmap in the **mds**.

#### <a id="c-cxl_mem_get_event_records"></a>`cxl_mem_get_event_records()`

```c
void cxl_mem_get_event_records(struct cxl_memdev_state *mds, u32 status)
```

Get Event Records from the device

**Parameters**

- `struct cxl_memdev_state *mds`: The driver data for the operation
- `u32 status`: Event Status register value identifying which events are available.

**Description**

Retrieve all event records available on the device, report them as trace
events, and clear them.

See CXL rev 3.0 **8.2.9.2.2** Get Event Records
See CXL rev 3.0 **8.2.9.2.3** Clear Event Records

#### <a id="c-cxl_mem_get_partition_info"></a>`cxl_mem_get_partition_info()`

```c
int cxl_mem_get_partition_info(struct cxl_memdev_state *mds)
```

Get partition info

**Parameters**

- `struct cxl_memdev_state *mds`: The driver data for the operation

**Description**

Retrieve the current partition info for the device specified.  The active
values are the current capacity in bytes.  If not 0, the 'next' values are
the pending values, in bytes, which take affect on next cold reset.

See CXL **8.2.9.5.2.1** Get Partition Info

**Return**

0 if no error: or the result of the mailbox command.

#### <a id="c-cxl_dev_state_identify"></a>`cxl_dev_state_identify()`

```c
int cxl_dev_state_identify(struct cxl_memdev_state *mds)
```

Send the IDENTIFY command to the device.

**Parameters**

- `struct cxl_memdev_state *mds`: The driver data for the operation

**Return**

0 if identify was executed successfully or media not ready.

**Description**

This will dispatch the identify command to the device and on success populate
structures to be exported to sysfs.

#### <a id="c-cxl_mem_sanitize"></a>`cxl_mem_sanitize()`

```c
int cxl_mem_sanitize(struct cxl_memdev *cxlmd, u16 cmd)
```

Send a sanitization command to the device.

**Parameters**

- `struct cxl_memdev *cxlmd`: The device for the operation
- `u16 cmd`: The specific sanitization command opcode

**Return**

0 if the command was executed successfully, regardless of
whether or not the actual security operation is done in the background,
such as for the Sanitize case.
Error return values can be the result of the mailbox command, -EINVAL
when security requirements are not met or invalid contexts, or -EBUSY
if the sanitize operation is already in flight.

**Description**

See CXL 3.0 **8.2.9.8.5.1** Sanitize and **8.2.9.8.5.2** Secure Erase.



CXL Features:
A CXL device that includes a mailbox supports commands that allows
listing, getting, and setting of optionally defined features such
as memory sparing or post package sparing. Vendors may define custom
features for the device.


See `devm_cxl_setup_features()` for API details.

<a id="rst-cxl-regions"></a>

### CXL Regions


CXL Regions represent mapped memory capacity in system physical address
space. Whereas the CXL Root Decoders identify the bounds of potential CXL
Memory ranges, Regions represent the active mapped capacity by the HDM
Decoder Capability structures throughout the Host Bridges, Switches, and
Endpoints in the topology.

Region configuration has ordering constraints. UUID may be set at any time
but is only visible for persistent regions.
1. Interleave granularity
2. Interleave size
3. Decoder targets



#### <a id="c-cxl_port_pick_region_decoder"></a>`cxl_port_pick_region_decoder()`

```c
struct cxl_decoder * cxl_port_pick_region_decoder(struct cxl_port *port, struct cxl_endpoint_decoder *cxled, struct cxl_region *cxlr)
```

assign or lookup a decoder for a region

**Parameters**

- `struct cxl_port *port`: a port in the ancestry of the endpoint implied by **cxled**
- `struct cxl_endpoint_decoder *cxled`: endpoint decoder to be, or currently, mapped by **port**
- `struct cxl_region *cxlr`: region to establish, or validate, decode **port**

**Description**

In the region creation path [`cxl_port_pick_region_decoder()`](#c-cxl_port_pick_region_decoder) is an
allocator to find a free port. In the region assembly path, it is
recalling the decoder that platform firmware picked for validation
purposes.

The result is recorded in a 'struct cxl_region_ref' in **port**.

#### <a id="c-cxl_port_attach_region"></a>`cxl_port_attach_region()`

```c
int cxl_port_attach_region(struct cxl_port *port, struct cxl_region *cxlr, struct cxl_endpoint_decoder *cxled, int pos)
```

track a region's interest in a port by endpoint

**Parameters**

- `struct cxl_port *port`: port to add a new region reference 'struct cxl_region_ref'
- `struct cxl_region *cxlr`: region to attach to **port**
- `struct cxl_endpoint_decoder *cxled`: endpoint decoder used to create or further pin a region reference
- `int pos`: interleave position of **cxled** in **cxlr**

**Description**

The attach event is an opportunity to validate CXL decode setup
constraints and record metadata needed for programming HDM decoders,
in particular decoder target lists.

The steps are:

- validate that there are no other regions with a higher HPA already
  associated with **port**
- establish a region reference if one is not already present

  - additionally allocate a decoder instance that will host **cxlr** on
    **port**

- pin the region reference by the endpoint
- account for how many entries in **port**'s target list are needed to
  cover all of the added endpoints.

#### <a id="c-cxl_calc_interleave_pos"></a>`cxl_calc_interleave_pos()`

```c
int cxl_calc_interleave_pos(struct cxl_endpoint_decoder *cxled, struct range *hpa_range)
```

calculate an endpoint position in a region

**Parameters**

- `struct cxl_endpoint_decoder *cxled`: endpoint decoder member of given region
- `struct range *hpa_range`: translated HPA range of the endpoint

**Description**

The endpoint position is calculated by traversing the topology from
the endpoint to the root decoder and iteratively applying this
calculation:

position = position * parent_ways + parent_pos;

...where **position** is inferred from switch and root decoder target lists.

**Return**

position >= 0 on success
-ENXIO on failure

#### <a id="c-devm_cxl_add_region"></a>`devm_cxl_add_region()`

```c
struct cxl_region * devm_cxl_add_region(struct cxl_root_decoder *cxlrd, int id, enum cxl_partition_mode mode, enum cxl_decoder_type type)
```

Adds a region to a decoder

**Parameters**

- `struct cxl_root_decoder *cxlrd`: root decoder
- `int id`: memregion id to create, or `memregion_free()` on failure
- `enum cxl_partition_mode mode`: mode for the endpoint decoders of this region
- `enum cxl_decoder_type type`: select whether this is an expander or accelerator (type-2 or type-3)

**Description**

This is the second step of region initialization. Regions exist within an
address space which is mapped by a **cxlrd**.

**Return**

0 if the region was added to the **cxlrd**, else returns negative error
code. The region will be named "regionZ" where Z is the unique region number.

#### <a id="c-cxl_validate_translation_params"></a>`cxl_validate_translation_params()`

```c
int cxl_validate_translation_params(u8 eiw, u16 eig, int pos)
```

**Parameters**

- `u8 eiw`: encoded interleave ways
- `u16 eig`: encoded interleave granularity
- `int pos`: position in interleave

**Description**

Callers pass CXL_POS_ZERO when no position parameter needs validating.

**Return**

0 on success, -EINVAL on first invalid parameter

#### <a id="c-devm_cxl_add_pmem_region"></a>`devm_cxl_add_pmem_region()`

```c
int devm_cxl_add_pmem_region(struct cxl_region *cxlr)
```

add a cxl_region-to-nd_region bridge

**Parameters**

- `struct cxl_region *cxlr`: parent CXL region for this pmem region bridge device

**Return**

0 on success negative error code on failure.


<a id="rst-external-interfaces"></a>

## External Interfaces

<a id="rst-cxl-ioctl-interface"></a>

### CXL IOCTL Interface


Not all of the commands that the driver supports are available for use by
userspace at all times.  Userspace can check the result of the QUERY command
to determine the live set of commands.  Alternatively, it can issue the
command and check for failure.



#### <a id="c-struct-cxl_command_info"></a>`struct cxl_command_info`

Command information returned from a query.

**Definition**

```c
struct cxl_command_info {
        __u32 id;
        __u32 flags;
    #define CXL_MEM_COMMAND_FLAG_MASK               GENMASK(1, 0);
    #define CXL_MEM_COMMAND_FLAG_ENABLED            BIT(0);
    #define CXL_MEM_COMMAND_FLAG_EXCLUSIVE          BIT(1);
        __u32 size_in;
        __u32 size_out;
};
```

**Members**

- `id`: ID number for the command.
- `flags`: Flags that specify command behavior.
- `size_in`: Expected input size, or ~0 if variable length.
- `size_out`: Expected output size, or ~0 if variable length.

**Description**

CXL_MEM_COMMAND_FLAG_USER_ENABLED

The given command id is supported by the driver and is supported by
a related opcode on the device.

CXL_MEM_COMMAND_FLAG_EXCLUSIVE

Requests with the given command id will terminate with EBUSY as the
kernel actively owns management of the given resource. For example,
the label-storage-area can not be written while the kernel is
actively managing that space.

Represents a single command that is supported by both the driver and the
hardware. This is returned as part of an array from the query ioctl. The
following would be a command that takes a variable length input and returns 0
bytes of output.

- **id** = 10
- **flags** = CXL_MEM_COMMAND_FLAG_ENABLED
- **size_in** = ~0
- **size_out** = 0

See struct cxl_mem_query_commands.

#### <a id="c-struct-cxl_mem_query_commands"></a>`struct cxl_mem_query_commands`

Query supported commands.

**Definition**

```c
struct cxl_mem_query_commands {
    __u32 n_commands;
    __u32 rsvd;
    struct cxl_command_info __user commands[];
};
```

**Members**

- `n_commands`: In/out parameter. When **n_commands** is > 0, the driver will
  return min(num_support_commands, n_commands). When **n_commands**
  is 0, driver will return the number of total supported commands.
- `rsvd`: Reserved for future use.
- `commands`: Output array of supported commands. This array must be allocated
  by userspace to be at least min(num_support_commands, **n_commands**)

**Description**

Allow userspace to query the available commands supported by both the driver,
and the hardware. Commands that aren't supported by either the driver, or the
hardware are not returned in the query.

**Examples**

- { .n_commands = 0 } // Get number of supported commands
- { .n_commands = 15, .commands = buf } // Return first 15 (or less)
  supported commands

See struct cxl_command_info.

#### <a id="c-struct-cxl_send_command"></a>`struct cxl_send_command`

Send a command to a memory device.

**Definition**

```c
struct cxl_send_command {
    __u32 id;
    __u32 flags;
    union {
        struct {
            __u16 opcode;
            __u16 rsvd;
        } raw;
        __u32 rsvd;
    };
    __u32 retval;
    struct {
        __u32 size;
        __u32 rsvd;
        __u64 payload;
    } in;
    struct {
        __u32 size;
        __u32 rsvd;
        __u64 payload;
    } out;
};
```

**Members**

- `id`: The command to send to the memory device. This must be one of the
  commands returned by the query command.
- `flags`: Flags for the command (input).
- `{unnamed_union}`: anonymous
- `raw`: Special fields for raw commands
- `raw.opcode`: Opcode passed to hardware when using the RAW command.
- `raw.rsvd`: Must be zero.
- `rsvd`: Must be zero.
- `retval`: Return value from the memory device (output).
- `in`: Parameters associated with input payload.
- `in.size`: Size of the payload to provide to the device (input).
- `in.rsvd`: Must be zero.
- `in.payload`: Pointer to memory for payload input, payload is little endian.
- `out`: Parameters associated with output payload.
- `out.size`: Size of the payload received from the device (input/output). This
  field is filled in by userspace to let the driver know how much
  space was allocated for output. It is populated by the driver to
  let userspace know how large the output payload actually was.
- `out.rsvd`: Must be zero.
- `out.payload`: Pointer to memory for payload output, payload is little endian.

**Description**

Mechanism for userspace to send a command to the hardware for processing. The
driver will do basic validation on the command sizes. In some cases even the
payload may be introspected. Userspace is required to allocate large enough
buffers for size_out which can be variable length in certain situations.

---

# DAX Devices

_Peios Kernel / Hardware and drivers / Driver development / cxl: allocation_

> CXL capacity exposed as a DAX device can be accessed directly via mmap. Users may wish to use this interface mechanism to write their own userland CXL allocator, or to managed shared or persistent memory regions across multiple hosts.

<a id="rst-dax-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

CXL capacity exposed as a DAX device can be accessed directly via mmap. Users may wish to use this interface mechanism to write their own userland CXL allocator, or to managed shared or persistent memory regions across multiple hosts.

If the capacity is shared across hosts or persistent, appropriate flushing mechanisms must be employed unless the region supports Snoop Back-Invalidate.

Note that mappings must be aligned (size and base) to the dax device's base alignment, which is typically 2MB - but maybe be configured larger.



```text
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>

#define DEVICE_PATH "/dev/dax0.0" // Replace DAX device path
#define DEVICE_SIZE (4ULL * 1024 * 1024 * 1024) // 4GB

int main() {
    int fd;
    void* mapped_addr;

    /* Open the DAX device */
    fd = open(DEVICE_PATH, O_RDWR);
    if (fd < 0) {
        perror("open");
        return -1;
    }

    /* Map the device into memory */
    mapped_addr = mmap(NULL, DEVICE_SIZE, PROT_READ | PROT_WRITE,
                       MAP_SHARED, fd, 0);
    if (mapped_addr == MAP_FAILED) {
        perror("mmap");
        close(fd);
        return -1;
    }

    printf("Mapped address: %p\n", mapped_addr);

    /* You can now access the device through the mapped address */
    uint64_t* ptr = (uint64_t*)mapped_addr;
    *ptr = 0x1234567890abcdef; // Write a value to the device
    printf("Value at address %p: 0x%016llx\n", ptr, *ptr);

    /* Clean up */
    munmap(mapped_addr, DEVICE_SIZE);
    close(fd);
    return 0;
}
```

---

# Huge Pages

_Peios Kernel / Hardware and drivers / Driver development / cxl: allocation_

> CXL Memory onlined as SystemRAM during early boot is eligible for use by CMA, as the NUMA node hosting that capacity will be Online at the time CMA carves out contiguous capacity.

<a id="rst-huge-pages"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contiguous-memory-allocator"></a>

## Contiguous Memory Allocator

CXL Memory onlined as SystemRAM during early boot is eligible for use by CMA, as the NUMA node hosting that capacity will be `Online` at the time CMA carves out contiguous capacity.

CXL Memory deferred to the CXL Driver for configuration cannot have its capacity allocated by CMA - as the NUMA node hosting the capacity is `Offline` at `__init` time - when CMA carves out contiguous capacity.

<a id="rst-hugetlb"></a>

## HugeTLB

Different huge page sizes allow different memory configurations.

<a id="rst-mb-huge-pages"></a>

### 2MB Huge Pages

All CXL capacity regardless of configuration time or memory zone is eligible for use as 2MB huge pages.

<a id="rst-gb-huge-pages"></a>

### 1GB Huge Pages

CXL capacity onlined in `ZONE_NORMAL` is eligible for 1GB Gigantic Page allocation.

CXL capacity onlined in `ZONE_MOVABLE` is not eligible for 1GB Gigantic Page allocation.

---

# The Page Allocator

_Peios Kernel / Hardware and drivers / Driver development / cxl: allocation_

> The kernel page allocator services all general page allocation requests, such as kmalloc. CXL configuration steps affect the behavior of the page allocator based on the selected Memory Zone and NUMA node the capacity is placed in.

<a id="rst-the-page-allocator"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The kernel page allocator services all general page allocation requests, such as `kmalloc`.  CXL configuration steps affect the behavior of the page allocator based on the selected `Memory Zone` and `NUMA node` the capacity is placed in.

This section mostly focuses on how these configurations affect the page allocator (as of Linux v6.15) rather than the overall page allocator behavior.

<a id="rst-numa-nodes-and-mempolicy"></a>

## NUMA nodes and mempolicy

Unless a task explicitly registers a mempolicy, the default memory policy of the linux kernel is to allocate memory from the `local NUMA node` first, and fall back to other nodes only if the local node is pressured.

Generally, we expect to see local DRAM and CXL memory on separate NUMA nodes, with the CXL memory being non-local.  Technically, however, it is possible for a compute node to have no local DRAM, and for CXL memory to be the `local` capacity for that compute node.

<a id="rst-memory-zones"></a>

## Memory Zones

CXL capacity may be onlined in `ZONE_NORMAL` or `ZONE_MOVABLE`.

As of v6.15, the page allocator attempts to allocate from the highest available and compatible ZONE for an allocation from the local node first.

An example of a `zone incompatibility` is attempting to service an allocation marked `GFP_KERNEL` from `ZONE_MOVABLE`.  Kernel allocations are typically not migratable, and as a result can only be serviced from `ZONE_NORMAL` or lower.

To simplify this, the page allocator will prefer `ZONE_MOVABLE` over `ZONE_NORMAL` by default, but if `ZONE_MOVABLE` is depleted, it will fallback to allocate from `ZONE_NORMAL`.

<a id="rst-cgroups-and-cpusets"></a>

## CGroups and CPUSets

Finally, assuming CXL memory is reachable via the page allocation (i.e. onlined in `ZONE_NORMAL`), the `cpusets.mems_allowed` may be used by containers to limit the accessibility of certain NUMA nodes for tasks in that container.  Users may wish to utilize this in multi-tenant systems where some tasks prefer not to use slower memory.

In the reclaim section we'll discuss some limitations of this interface to prevent demotions of shared data to CXL memory (if demotions are enabled).

---

# Reclaim

_Peios Kernel / Hardware and drivers / Driver development / cxl: allocation_

> Another way CXL memory can be utilized indirectly is via the reclaim system in mm/vmscan.c. Reclaim is engaged when memory capacity on the system becomes pressured based on global and cgroup-local watermark settings.

<a id="rst-reclaim"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Another way CXL memory can be utilized *indirectly* is via the reclaim system in `mm/vmscan.c`.  Reclaim is engaged when memory capacity on the system becomes pressured based on global and cgroup-local `watermark` settings.

In this section we won't discuss the `watermark` configurations, just how CXL memory can be consumed by various pieces of reclaim system.

<a id="rst-demotion"></a>

## Demotion

By default, the reclaim system will prefer swap (or zswap) when reclaiming memory.  Enabling `kernel/mm/numa/demotion_enabled` will cause vmscan to opportunistically prefer distant NUMA nodes to swap or zswap, if capacity is available.

Demotion engages the `mm/memory_tier.c` component to determine the next demotion node.  The next demotion node is based on the `HMAT` or `CDAT` performance data.

<a id="rst-cpusets-mems-allowed-quirk"></a>

### cpusets.mems_allowed quirk

In Linux v6.15 and below, demotion does not respect `cpusets.mems_allowed` when migrating pages.  As a result, if demotion is enabled, vmscan cannot guarantee isolation of a container's memory from nodes not set in mems_allowed.

In Linux v6.XX and up, demotion does attempt to respect `cpusets.mems_allowed`; however, certain classes of shared memory originally instantiated by another cgroup (such as common libraries - e.g. libc) may still be demoted.  As a result, the mems_allowed interface still cannot provide perfect isolation from the remote nodes.

<a id="rst-zswap-and-node-preference"></a>

## ZSwap and Node Preference

In Linux v6.15 and below, ZSwap allocates memory from the local node of the processor for the new pages being compressed.  Since pages being compressed are typically cold, the result is a cold page becomes promoted - only to be later demoted as it ages off the LRU.

In Linux v6.XX, ZSwap tries to prefer the node of the page being compressed as the allocation target for the compression page.  This helps prevent thrashing.

<a id="rst-demotion-with-zswap"></a>

## Demotion with ZSwap

When enabling both Demotion and ZSwap, you create a situation where ZSwap will prefer the slowest form of CXL memory by default until that tier of memory is exhausted.

---

# ACPI PRM CXL Address Translation

_Peios Kernel / Hardware and drivers / Driver development / cxl: conventions_

> CXL Revision 3.2, Version 1.0

<a id="rst-acpi-prm-cxl-address-translation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-document"></a>

## Document

CXL Revision 3.2, Version 1.0

<a id="rst-license"></a>

## License

SPDX-License Identifier: CC-BY-4.0

<a id="rst-creator-contributors"></a>

## Creator/Contributors

- Robert Richter, AMD et al.

<a id="rst-summary-of-the-change"></a>

## Summary of the Change

The CXL Fixed Memory Window Structures (CFMWS) describe zero or more Host Physical Address (HPA) windows associated with one or more CXL Host Bridges. Each HPA range of a CXL Host Bridge is represented by a CFMWS entry. An HPA range may include addresses currently assigned to CXL.mem devices, or an OS may assign ranges from an address window to a device.

Host-managed Device Memory is Device-attached memory that is mapped to system coherent address space and accessible to the Host using standard write-back semantics. The managed address range is configured in the CXL HDM Decoder registers of the device. An HDM Decoder in a device is responsible for converting HPA into DPA by stripping off specific address bits.

CXL devices and CXL bridges use the same HPA space. It is common across all components that belong to the same host domain. The view of the address region must be consistent on the CXL.mem path between the Host and the Device.

This is described in the *CXL 3.2 specification* (Table 1-1, 3.3.1, 8.2.4.20, 9.13.1, 9.18.1.3). <a id="rst-footnote-reference-1"></a>[1](#rst-cxl-spec-3-2)

Depending on the interconnect architecture of the platform, components attached to a host may not share the same host physical address space. Those platforms need address translation to convert an HPA between the host and the attached component, such as a CXL device. The translation mechanism is host-specific and implementation dependent.

For example, x86 AMD platforms use a Data Fabric that manages access to physical memory. Devices have their own memory space and can be configured to use 'Normalized addresses' different from System Physical Addresses (SPA). Address translation is then needed. For details, see [x86 AMD Address Translation](</kernel/administration/admin-guide/ras/address-translation.md>).

Those AMD platforms provide PRM <a id="rst-footnote-reference-2"></a>[3](#rst-prm-spec) handlers in firmware to perform various types of address translation, including for CXL endpoints. AMD Zen5 systems implement the ACPI PRM CXL Address Translation firmware call. The ACPI PRM handler has a specific GUID to uniquely identify platforms with support for Normalized addressing. This is documented in the *ACPI v6.5 Porting Guide* (Address Translation - CXL DPA to System Physical Address). <a id="rst-footnote-reference-3"></a>[2](#rst-amd-ppr-58088)

When in Normalized address mode, HDM decoder address ranges must be configured and handled differently. Hardware addresses used in the HDM decoder configurations of an endpoint are not SPA and need to be translated from the address range of the endpoint to that of the CXL host bridge. This is especially important for finding an endpoint's associated CXL Host Bridge and HPA window described in the CFMWS. Additionally, the interleave decoding is done by the Data Fabric and the endpoint does not perform decoding when converting HPA to DPA. Instead, interleaving is switched off for the endpoint (1-way). Finally, address translation might also be needed to inspect the endpoint's hardware addresses, such as during profiling, tracing, or error handling.

For example, with Normalized addressing the HDM decoders could look as follows:



```text
                         -------------------------------
                         | Root Decoder (CFMWS)        |
                         | SPA Range: 0x850000000      |
                         | Size: 0x8000000000 (512 GB) |
                         | Interleave Ways: 1          |
                         -------------------------------
                                       |
                                       v
                         -------------------------------
                         | Host Bridge Decoder (HDM)   |
                         | SPA Range: 0x850000000      |
                         | Size: 0x8000000000 (512 GB) |
                         | Interleave Ways: 4          |
                         | Targets: endpoint5,8,11,13  |
                         | Granularity: 256            |
                         -------------------------------
                                       |
          -----------------------------+------------------------------
          |                  |                   |                   |
          v                  v                   v                   v
------------------- ------------------- ------------------- -------------------
| endpoint5       | | endpoint8       | | endpoint11      | | endpoint13      |
| decoder5.0      | | decoder8.0      | | decoder11.0     | | decoder13.0     |
| PCIe:           | | PCIe:           | | PCIe:           | | PCIe:           |
|   0000:e2:00.0  | |   0000:e3:00.0  | |   0000:e4:00.0  | |   0000:e1:00.0  |
| DPA:            | | DPA:            | | DPA:            | | DPA:            |
|   Start: 0x0    | |   Start: 0x0    | |   Start: 0x0    | |   Start: 0x0    |
|   Size:         | |   Size:         | |   Size:         | |   Size:         |
|    0x2000000000 | |    0x2000000000 | |    0x2000000000 | |    0x2000000000 |
|    (128 GB)     | |    (128 GB)     | |    (128 GB)     | |    (128 GB)     |
| Interleaving:   | | Interleaving:   | | Interleaving:   | | Interleaving:   |
|   Ways: 1       | |   Ways: 1       | |   Ways: 1       | |   Ways: 1       |
|   Gran: 256     | |   Gran: 256     | |   Gran: 256     | |   Gran: 256     |
------------------- ------------------- ------------------- -------------------
         |                   |                   |                   |
         v                   v                   v                   v
        DPA                 DPA                 DPA                 DPA
```

This shows the representation in sysfs:



```none
/sys/bus/cxl/devices/endpoint5/decoder5.0/interleave_granularity:256
/sys/bus/cxl/devices/endpoint5/decoder5.0/interleave_ways:1
/sys/bus/cxl/devices/endpoint5/decoder5.0/size:0x2000000000
/sys/bus/cxl/devices/endpoint5/decoder5.0/start:0x0
/sys/bus/cxl/devices/endpoint8/decoder8.0/interleave_granularity:256
/sys/bus/cxl/devices/endpoint8/decoder8.0/interleave_ways:1
/sys/bus/cxl/devices/endpoint8/decoder8.0/size:0x2000000000
/sys/bus/cxl/devices/endpoint8/decoder8.0/start:0x0
/sys/bus/cxl/devices/endpoint11/decoder11.0/interleave_granularity:256
/sys/bus/cxl/devices/endpoint11/decoder11.0/interleave_ways:1
/sys/bus/cxl/devices/endpoint11/decoder11.0/size:0x2000000000
/sys/bus/cxl/devices/endpoint11/decoder11.0/start:0x0
/sys/bus/cxl/devices/endpoint13/decoder13.0/interleave_granularity:256
/sys/bus/cxl/devices/endpoint13/decoder13.0/interleave_ways:1
/sys/bus/cxl/devices/endpoint13/decoder13.0/size:0x2000000000
/sys/bus/cxl/devices/endpoint13/decoder13.0/start:0x0
```

Note that the endpoint interleaving configurations use direct mapping (1-way).

With PRM calls, the kernel can determine the following mappings:



```none
cxl decoder5.0: address mapping found for 0000:e2:00.0 (hpa -> spa):
  0x0+0x2000000000 -> 0x850000000+0x8000000000 ways:4 granularity:256
cxl decoder8.0: address mapping found for 0000:e3:00.0 (hpa -> spa):
  0x0+0x2000000000 -> 0x850000000+0x8000000000 ways:4 granularity:256
cxl decoder11.0: address mapping found for 0000:e4:00.0 (hpa -> spa):
  0x0+0x2000000000 -> 0x850000000+0x8000000000 ways:4 granularity:256
cxl decoder13.0: address mapping found for 0000:e1:00.0 (hpa -> spa):
  0x0+0x2000000000 -> 0x850000000+0x8000000000 ways:4 granularity:256
```

The corresponding CXL host bridge (HDM) decoders and root decoder (CFMWS) match the calculated endpoint mappings shown:



```none
/sys/bus/cxl/devices/port1/decoder1.0/interleave_granularity:256
/sys/bus/cxl/devices/port1/decoder1.0/interleave_ways:4
/sys/bus/cxl/devices/port1/decoder1.0/size:0x8000000000
/sys/bus/cxl/devices/port1/decoder1.0/start:0x850000000
/sys/bus/cxl/devices/port1/decoder1.0/target_list:0,1,2,3
/sys/bus/cxl/devices/port1/decoder1.0/target_type:expander
/sys/bus/cxl/devices/root0/decoder0.0/interleave_granularity:256
/sys/bus/cxl/devices/root0/decoder0.0/interleave_ways:1
/sys/bus/cxl/devices/root0/decoder0.0/size:0x8000000000
/sys/bus/cxl/devices/root0/decoder0.0/start:0x850000000
/sys/bus/cxl/devices/root0/decoder0.0/target_list:7
```

The following changes to the specification are needed:

- Allow a CXL device to be in an HPA space other than the host's address space.

- Allow the platform to use implementation-specific address translation when crossing memory domains on the CXL.mem path between the host and the device.

- Define a PRM handler method for converting device addresses to SPAs.

- Specify that the platform shall provide the PRM handler method to the Operating System to detect Normalized addressing and for determining Endpoint SPA ranges and interleaving configurations.

- Add reference to:

  Platform Runtime Mechanism Specification, Version 1.1 – November 2020  
  [https://uefi.org/sites/default/files/resources/PRM_Platform_Runtime_Mechanism_1_1_release_candidate.pdf](<https://uefi.org/sites/default/files/resources/PRM_Platform_Runtime_Mechanism_1_1_release_candidate.pdf>)

<a id="rst-benefits-of-the-change"></a>

## Benefits of the Change

Without the change, the Operating System may be unable to determine the memory region and Root Decoder for an Endpoint and its corresponding HDM decoder. Region creation would fail. Platforms with a different interconnect architecture would fail to set up and use CXL.

<a id="rst-references"></a>

## References

<a id="rst-cxl-spec-3-2"></a>



**[1]** Compute Express Link Specification, Revision 3.2, Version 1.0, [https://www.computeexpresslink.org/](<https://www.computeexpresslink.org/>)

<a id="rst-amd-ppr-58088"></a>



**[2]** AMD Family 1Ah Models 00h–0Fh and Models 10h–1Fh, ACPI v6.5 Porting Guide, Publication \# 58088, [https://www.amd.com/en/search/documentation/hub.html](<https://www.amd.com/en/search/documentation/hub.html>)

<a id="rst-prm-spec"></a>



**[3]** Platform Runtime Mechanism, Version: 1.1, [https://uefi.org/sites/default/files/resources/PRM_Platform_Runtime_Mechanism_1_1_release_candidate.pdf](<https://uefi.org/sites/default/files/resources/PRM_Platform_Runtime_Mechanism_1_1_release_candidate.pdf>)

<a id="rst-detailed-description-of-the-change"></a>

## Detailed Description of the Change

The following describes the necessary changes to the *CXL 3.2 specification* <a id="rst-footnote-reference-4"></a>[1](#rst-cxl-spec-3-2):

Add the following reference to the table:

Table 1-2. Reference Documents


<table>
<thead>
<tr>
<th>


Document

</th>
<th>


Chapter Reference

</th>
<th>


Document No./Location

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Platform Runtime Mechanism Version: 1.1

</td>
<td>


Chapter 8, 9

</td>
<td>


[https://www.uefi.org/acpi](<https://www.uefi.org/acpi>)

</td>
</tr>
</tbody>
</table>

Add the following paragraphs to the end of the section:

**8.2.4.20 CXL HDM Decoder Capability Structure**

"A device may use an HPA space that is not common to other components of the host domain. The platform is responsible for address translation when crossing HPA spaces. The Operating System must determine the interleaving configuration and perform address translation to the HPA ranges of the HDM decoders as needed. The translation mechanism is host-specific and implementation dependent.

The platform indicates support of independent HPA spaces and the need for address translation by providing a Platform Runtime Mechanism (PRM) handler. The OS shall use that handler to perform the necessary translations from the DPA space to the HPA space. The handler is defined in Section 9.18.4 *PRM Handler for CXL DPA to System Physical Address Translation*."

Add the following section and sub-section including tables:

**9.18.4 PRM Handler for CXL DPA to System Physical Address Translation**

"A platform may be configured to use 'Normalized addresses'. Host physical address (HPA) spaces are component-specific and differ from system physical addresses (SPAs). The endpoint has its own physical address space. All requests presented to the device already use Device Physical Addresses (DPAs). The CXL endpoint decoders have interleaving disabled (1-way interleaving) and the device does not perform HPA decoding to determine a DPA.

The platform provides a PRM handler for CXL DPA to System Physical Address Translation. The PRM handler translates a Device Physical Address (DPA) to a System Physical Address (SPA) for a specified CXL endpoint. In the address space of the host, SPA and HPA are equivalent, and the OS shall use this handler to determine the HPA that corresponds to a device address, for example when configuring HDM decoders on platforms with Normalized addressing. The GUID and the parameter buffer format of the handler are specified in section 9.18.4.1. If the OS identifies the PRM handler, the platform supports Normalized addressing and the OS must perform DPA address translation as needed."

**9.18.4.1 PRM Handler Invocation**

"The OS calls the PRM handler for CXL DPA to System Physical Address Translation using the direct invocation mechanism. Details of calling a PRM handler are described in the Platform Runtime Mechanism (PRM) specification.

The PRM handler is identified by the following GUID:

> EE41B397-25D4-452C-AD54-48C6E3480B94

The caller allocates and prepares a Parameter Buffer, then passes the PRM handler GUID and a pointer to the Parameter Buffer to invoke the handler. The Parameter Buffer is described in Table 9-32."

**Table 9-32. PRM Parameter Buffer used for CXL DPA to System Physical Address Translation**


<table>
<thead>
<tr>
<th>


Byte Offset

</th>
<th>


- **Length in**

  Bytes

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


00h

</td>
<td>


8

</td>
<td>


**CXL Device Physical Address (DPA)**: CXL DPA (e.g., from CXL Component Event Log)

</td>
</tr>
<tr>
<td>


08h

</td>
<td>


4

</td>
<td>


**CXL Endpoint SBDF**:

- Byte 3 - PCIe Segment

- Byte 2 - Bus Number

- - **Byte 1:**

    - Device Number Bits\[7:3\]

    - Function Number Bits\[2:0\]

- Byte 0 - RESERVED (MBZ)

</td>
</tr>
<tr>
<td>


0Ch

</td>
<td>


8

</td>
<td>


**Output Buffer**: Virtual Address Pointer to the buffer, as defined in Table 9-33.

</td>
</tr>
</tbody>
</table>

**Table 9-33. PRM Output Buffer used for CXL DPA to System Physical Address Translation**


<table>
<thead>
<tr>
<th>


Byte Offset

</th>
<th>


- **Length in**

  Bytes

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


00h

</td>
<td>


8

</td>
<td>


**System Physical Address (SPA)**: The SPA converted from the CXL DPA.

</td>
</tr>
</tbody>
</table>

---

# Resolve conflict between CFMWS, Platform Memory Holes, and Endpoint Decoders

_Peios Kernel / Hardware and drivers / Driver development / cxl: conventions_

> CXL Revision 3.2, Version 1.0

<a id="rst-resolve-conflict-between-cfmws-platform-memory-holes-and-endpoint-decoders"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-document"></a>

## Document

CXL Revision 3.2, Version 1.0

<a id="rst-license"></a>

## License

SPDX-License Identifier: CC-BY-4.0

<a id="rst-creator-contributors"></a>

## Creator/Contributors

- Fabio M. De Francesco, Intel

- Dan J. Williams, Intel

- Mahesh Natu, Intel

<a id="rst-summary-of-the-change"></a>

## Summary of the Change

According to the current Compute Express Link (CXL) Specifications (Revision 3.2, Version 1.0), the CXL Fixed Memory Window Structure (CFMWS) describes zero or more Host Physical Address (HPA) windows associated with each CXL Host Bridge. Each window represents a contiguous HPA range that may be interleaved across one or more targets, including CXL Host Bridges. Each window has a set of restrictions that govern its usage. It is the Operating System-directed configuration and Power Management (OSPM) responsibility to utilize each window for the specified use.

Table 9-22 of the current CXL Specifications states that the Window Size field contains the total number of consecutive bytes of HPA this window describes. This value must be a multiple of the Number of Interleave Ways (NIW) \* 256 MB.

Platform Firmware (BIOS) might reserve physical addresses below 4 GB where a memory gap such as the Low Memory Hole for PCIe MMIO may exist. In such cases, the CFMWS Range Size may not adhere to the NIW \* 256 MB rule.

The HPA represents the actual physical memory address space that the CXL devices can decode and respond to, while the System Physical Address (SPA), a related but distinct concept, represents the system-visible address space that users can direct transaction to and so it excludes reserved regions.

BIOS publishes CFMWS to communicate the active SPA ranges that, on platforms with LMH's, map to a strict subset of the HPA. The SPA range trims out the hole, resulting in lost capacity in the Endpoints with no SPA to map to that part of the HPA range that intersects the hole.

E.g, an x86 platform with two CFMWS and an LMH starting at 2 GB:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Window
>
> </th>
> <th>
>
>
> CFMWS Base
>
> </th>
> <th>
>
>
> CFMWS Size
>
> </th>
> <th>
>
>
> HDM Decoder Base
>
> </th>
> <th>
>
>
> HDM Decoder Size
>
> </th>
> <th>
>
>
> Ways
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> 0 GB
>
> </td>
> <td>
>
>
> 2 GB
>
> </td>
> <td>
>
>
> 0 GB
>
> </td>
> <td>
>
>
> 3 GB
>
> </td>
> <td>
>
>
> 12
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 4 GB
>
> </td>
> <td>
>
>
> NIW\*256MB Aligned
>
> </td>
> <td>
>
>
> 4 GB
>
> </td>
> <td>
>
>
> NIW\*256MB Aligned
>
> </td>
> <td>
>
>
> 12
>
> </td>
> </tr>
> </tbody>
> </table>

HDM decoder base and HDM decoder size represent all the 12 Endpoint Decoders of a 12 ways region and all the intermediate Switch Decoders. They are configured by the BIOS according to the NIW \* 256MB rule, resulting in a HPA range size of 3GB. Instead, the CFMWS Base and CFMWS Size are used to configure the Root Decoder HPA range that results smaller (2GB) than that of the Switch and Endpoint Decoders in the hierarchy (3GB).

This creates 2 issues which lead to a failure to construct a region:

1. A mismatch in region size between root and any HDM decoder. The root decoders will always be smaller due to the trim.

2. The trim causes the root decoder to violate the (NIW \* 256MB) rule.

This change allows a region with a base address of 0GB to bypass these checks to allow for region creation with the trimmed root decoder address range.

This change does not allow for any other arbitrary region to violate these checks - it is intended exclusively to enable x86 platforms which map CXL memory under 4GB.

Despite the HDM decoders covering the PCIE hole HPA region, it is expected that the platform will never route address accesses to the CXL complex because the root decoder only covers the trimmed region (which excludes this). This is outside the ability of Linux to enforce.

On the example platform, only the first 2GB will be potentially usable, but Linux, aiming to adhere to the current specifications, fails to construct Regions and attach Endpoint and intermediate Switch Decoders to them.

There are several points of failure that due to the expectation that the Root Decoder HPA size, that is equal to the CFMWS from which it is configured, has to be greater or equal to the matching Switch and Endpoint HDM Decoders.

In order to succeed with construction and attachment, Linux must construct a Region with Root Decoder HPA range size, and then attach to that all the intermediate Switch Decoders and Endpoint Decoders that belong to the hierarchy regardless of their range sizes.

<a id="rst-benefits-of-the-change"></a>

## Benefits of the Change

Without the change, the OSPM wouldn't match intermediate Switch and Endpoint Decoders with Root Decoders configured with CFMWS HPA sizes that don't align with the NIW \* 256MB constraint, and so it leads to lost memdev capacity.

This change allows the OSPM to construct Regions and attach intermediate Switch and Endpoint Decoders to them, so that the addressable part of the memory devices total capacity is made available to the users.

<a id="rst-references"></a>

## References

Compute Express Link Specification Revision 3.2, Version 1.0 &lt;[https://www.computeexpresslink.org/](<https://www.computeexpresslink.org/>)&gt;

<a id="rst-detailed-description-of-the-change"></a>

## Detailed Description of the Change

The description of the Window Size field in table 9-22 needs to account for platforms with Low Memory Holes, where SPA ranges might be subsets of the endpoints HPA. Therefore, it has to be changed to the following:

"The total number of consecutive bytes of HPA this window represents. This value shall be a multiple of NIW \* 256 MB.

On platforms that reserve physical addresses below 4 GB, such as the Low Memory Hole for PCIe MMIO on x86, an instance of CFMWS whose Base HPA range is 0 might have a size that doesn't align with the NIW \* 256 MB constraint.

Note that the matching intermediate Switch Decoders and the Endpoint Decoders HPA range sizes must still align to the above-mentioned rule, but the memory capacity that exceeds the CFMWS window size won't be accessible.".

---

# Template File

_Peios Kernel / Hardware and drivers / Driver development / cxl: conventions_

> CXL Revision <rev>, Version <ver>

<a id="rst-template-file"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- :: Template Title here: -->

<a id="rst-document"></a>

## Document

CXL Revision &lt;rev&gt;, Version &lt;ver&gt;

<a id="rst-license"></a>

## License

SPDX-License Identifier: CC-BY-4.0

<a id="rst-creator-contributors"></a>

## Creator/Contributors

<a id="rst-summary-of-the-change"></a>

## Summary of the Change

&lt;Detail the conflict with the specification and where available the assumptions and tradeoffs taken by the hardware platform.&gt;

<a id="rst-benefits-of-the-change"></a>

## Benefits of the Change

&lt;Detail what happens if platforms and Linux do not adopt this convention.&gt;

<a id="rst-references"></a>

## References

<a id="rst-detailed-description-of-the-change"></a>

## Detailed Description of the Change

&lt;Propose spec language that corrects the conflict.&gt;

---

# Devices and Protocols

_Peios Kernel / Hardware and drivers / Driver development / cxl: devices_

> The type of CXL device (Memory, Accelerator, etc) dictates many configuration steps. This section covers some basic background on device types and on-device resources used by the platform and OS which impact configuration.

<a id="rst-devices-and-protocols"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The type of CXL device (Memory, Accelerator, etc) dictates many configuration steps. This section covers some basic background on device types and on-device resources used by the platform and OS which impact configuration.

<a id="rst-protocols"></a>

## Protocols

There are three core protocols to CXL.  For the purpose of this documentation, we will only discuss very high level definitions as the specific hardware details are largely abstracted away from Linux.  See the CXL specification for more details.

<a id="rst-cxl-io"></a>

### CXL.io

The basic interaction protocol, similar to PCIe configuration mechanisms. Typically used for initialization, configuration, and I/O access for anything other than memory (CXL.mem) or cache (CXL.cache) operations.

The Linux CXL driver exposes access to .io functionality via the various sysfs interfaces and /dev/cxl/ devices (which exposes direct access to device mailboxes).

<a id="rst-cxl-cache"></a>

### CXL.cache

The mechanism by which a device may coherently access and cache host memory.

Largely transparent to Linux once configured.

<a id="rst-cxl-mem"></a>

### CXL.mem

The mechanism by which the CPU may coherently access and cache device memory.

Largely transparent to Linux once configured.

<a id="rst-device-types"></a>

## Device Types

<a id="rst-type-1"></a>

### Type-1

A Type-1 CXL device:

- Supports cxl.io and cxl.cache protocols

- Implements a fully coherent cache

- Allows Device-to-Host coherence and Host-to-Device snoops.

- Does NOT have host-managed device memory (HDM)

Typical examples of type-1 devices is a Smart NIC - which may want to directly operate on host-memory (DMA) to store incoming packets. These devices largely rely on CPU-attached memory.

<a id="rst-type-2"></a>

### Type-2

A Type-2 CXL Device:

- Supports cxl.io, cxl.cache, and cxl.mem protocols

- Optionally implements coherent cache and Host-Managed Device Memory

- Is typically an accelerator device with high bandwidth memory.

The primary difference between a type-1 and type-2 device is the presence of host-managed device memory, which allows the device to operate on a local memory bank - while the CPU still has coherent DMA to the same memory.

This allows things like GPUs to expose their memory via DAX devices or file descriptors, allows drivers and programs direct access to device memory rather than use block-transfer semantics.

<a id="rst-type-3"></a>

### Type-3

A Type-3 CXL Device

- Supports cxl.io and cxl.mem

- Implements Host-Managed Device Memory

- May provide either Volatile or Persistent memory capacity (or both).

A basic example of a type-3 device is a simple memory expander, whose local memory capacity is exposed to the CPU for access directly via basic coherent DMA.

<a id="rst-switch"></a>

### Switch

A CXL switch is a device capable of routing any CXL (and by extension, PCIe) protocol between an upstream, downstream, or peer devices.  Many devices, such as Multi-Logical Devices, imply the presence of switching in some manner.

<a id="rst-logical-devices-and-heads"></a>

### Logical Devices and Heads

A CXL device may present one or more "Logical Devices" to one or more hosts (via physical "Heads").

A Single-Logical Device (SLD) is a device which presents a single device to one or more heads.

A Multi-Logical Device (MLD) is a device which may present multiple devices to one or more upstream devices.

A Single-Headed Device exposes only a single physical connection.

A Multi-Headed Device exposes multiple physical connections.

<a id="rst-mhsld"></a>

#### MHSLD

A Multi-Headed Single-Logical Device (MHSLD) exposes a single logical device to multiple heads which may be connected to one or more discrete hosts.  An example of this would be a simple memory-pool which may be statically configured (prior to boot) to expose portions of its memory to Linux via [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>).

<a id="rst-mhmld"></a>

#### MHMLD

A Multi-Headed Multi-Logical Device (MHMLD) exposes multiple logical devices to multiple heads which may be connected to one or more discrete hosts.  An example of this would be a Dynamic Capacity Device or which may be configured at runtime to expose portions of its memory to Linux.

<a id="rst-example-devices"></a>

## Example Devices

<a id="rst-memory-expander"></a>

### Memory Expander

The simplest form of Type-3 device is a memory expander.  A memory expander exposes Host-Managed Device Memory (HDM) to Linux.  This memory may be Volatile or Non-Volatile (Persistent).

Memory Expanders will typically be considered a form of Single-Headed, Single-Logical Device - as its form factor will typically be an add-in-card (AIC) or some other similar form-factor.

The Linux CXL driver provides support for static or dynamic configuration of basic memory expanders.  The platform may program decoders prior to OS init (e.g. auto-decoders), or the user may program the fabric if the platform defers these operations to the OS.

Multiple Memory Expanders may be added to an external chassis and exposed to a host via a head attached to a CXL switch.  This is a "memory pool", and would be considered an MHSLD or MHMLD depending on the management capabilities provided by the switch platform.

As of v6.14, Linux does not provide a formalized interface to manage non-DCD MHSLD or MHMLD devices.

<a id="rst-dynamic-capacity-device-dcd"></a>

### Dynamic Capacity Device (DCD)

A Dynamic Capacity Device is a Type-3 device which provides dynamic management of memory capacity. The basic premise of a DCD to provide an allocator-like interface for physical memory capacity to a "Fabric Manager" (an external, privileged host with privileges to change configurations for other hosts).

A DCD manages "Memory Extents", which may be volatile or persistent. Extents may also be exclusive to a single host or shared across multiple hosts.

As of v6.14, Linux does not provide a formalized interface to manage DCD devices, however there is active work on LKML targeting future release.

---

# CXL Access Coordinates Computation

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux_

> A memory region performance coordinates (latency and bandwidth) are typically provided via ACPI tables SRAT <../platform/acpi/srat> and HMAT <../platform/acpi/hmat>. However, the platform firmware (BIOS) is not able to annotate those for…

<a id="rst-cxl-access-coordinates-computation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

<a id="rst-latency-and-bandwidth-calculation"></a>

## Latency and Bandwidth Calculation

A memory region performance coordinates (latency and bandwidth) are typically provided via ACPI tables [SRAT](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>) and [HMAT](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>). However, the platform firmware (BIOS) is not able to annotate those for CXL devices that are hot-plugged since they do not exist during platform firmware initialization. The CXL driver can compute the performance coordinates by retrieving data from several components.

The [SRAT](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>) provides a Generic Port Affinity subtable that ties a proximity domain to a device handle, which in this case would be the CXL hostbridge. Using this association, the performance coordinates for the Generic Port can be retrieved from the [HMAT](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>) subtable. This piece represents the performance coordinates between a CPU and a Generic Port (CXL hostbridge).

The [CDAT](</kernel/hardware/driver-api/cxl-platform/cdat.md>) provides the performance coordinates for the CXL device itself. That is the bandwidth and latency to access that device's memory region. The DSMAS subtable provides a DSMADHandle that is tied to a Device Physical Address (DPA) range. The DSLBIS subtable provides the performance coordinates that's tied to a DSMADhandle and this ties the two table entries together to provide the performance coordinates for each DPA region. For example, if a device exports a DRAM region and a PMEM region, then there would be different performance characteristsics for each of those regions.

If there's a CXL switch in the topology, then the performance coordinates for the switch is provided by SSLBIS subtable. This provides the bandwidth and latency for traversing the switch between the switch upstream port and the switch downstream port that points to the endpoint device.

Simple topology example:



```text
GP0/HB0/ACPI0016-0
       RP0
        |
        | L0
        |
    SW 0 / USP0
    SW 0 / DSP0
        |
        | L1
        |
       EP0
```

In this example, there is a CXL switch between an endpoint and a root port. Latency in this example is calculated as such: L(EP0) - Latency from EP0 CDAT DSMAS+DSLBIS L(L1) - Link latency between EP0 and SW0DSP0 L(SW0) - Latency for the switch from SW0 CDAT SSLBIS. L(L0) - Link latency between SW0 and RP0 L(RP0) - Latency from root port to CPU via SRAT and HMAT (Generic Port). Total read and write latencies are the sum of all these parts.

Bandwidth in this example is calculated as such: B(EP0) - Bandwidth from EP0 CDAT DSMAS+DSLBIS B(L1) - Link bandwidth between EP0 and SW0DSP0 B(SW0) - Bandwidth for the switch from SW0 CDAT SSLBIS. B(L0) - Link bandwidth between SW0 and RP0 B(RP0) - Bandwidth from root port to CPU via SRAT and HMAT (Generic Port). The total read and write bandwidth is the min() of all these parts.

To calculate the link bandwidth: LinkOperatingFrequency (GT/s) is the current negotiated link speed. DataRatePerLink (MB/s) = LinkOperatingFrequency / 8 Bandwidth (MB/s) = PCIeCurrentLinkWidth \* DataRatePerLink Where PCIeCurrentLinkWidth is the number of lanes in the link.

To calculate the link latency: LinkLatency (picoseconds) = FlitSize / LinkBandwidth (MB/s)

See [CXL Memory Device SW Guide r1.0](<https://www.intel.com/content/www/us/en/content-details/643805/cxl-memory-device-software-guide.html>)<a id="rst-cxl-memory-device-sw-guide-r1-0"></a>, section 2.11.3 and 2.11.4 for details.

In the end, the access coordinates for a constructed memory region is calculated from one or more memory partitions from each of the CXL device(s).

<a id="rst-shared-upstream-link-calculation"></a>

## Shared Upstream Link Calculation

For certain CXL region construction with endpoints behind CXL switches (SW) or Root Ports (RP), there is the possibility of the total bandwidth for all the endpoints behind a switch being more than the switch upstream link. A similar situation can occur within the host, upstream of the root ports. The CXL driver performs an additional pass after all the targets have arrived for a region in order to recalculate the bandwidths with possible upstream link being a limiting factor in mind.

The algorithm assumes the configuration is a symmetric topology as that maximizes performance. When asymmetric topology is detected, the calculation is aborted. An asymmetric topology is detected during topology walk where the number of RPs detected as a grandparent is not equal to the number of devices iterated in the same iteration loop. The assumption is made that subtle asymmetry in properties does not happen and all paths to EPs are equal.

There can be multiple switches under an RP. There can be multiple RPs under a CXL Host Bridge (HB). There can be multiple HBs under a CXL Fixed Memory Window Structure (CFMWS) in the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>).

An example hierarchy:



```text
               CFMWS 0
                 |
        _________|_________
       |                   |
   ACPI0017-0          ACPI0017-1
GP0/HB0/ACPI0016-0   GP1/HB1/ACPI0016-1
   |          |        |           |
  RP0        RP1      RP2         RP3
   |          |        |           |
 SW 0       SW 1     SW 2        SW 3
 |   |      |   |    |   |       |   |
EP0 EP1    EP2 EP3  EP4  EP5    EP6 EP7
```

Computation for the example hierarchy:

- **Min (GP0 to CPU BW,**

  - **Min(SW 0 Upstream Link to RP0 BW,**

    Min(SW0SSLBIS for SW0DSP0 (EP0), EP0 DSLBIS, EP0 Upstream Link) + Min(SW0SSLBIS for SW0DSP1 (EP1), EP1 DSLBIS, EP1 Upstream link)) +

  - **Min(SW 1 Upstream Link to RP1 BW,**

    Min(SW1SSLBIS for SW1DSP0 (EP2), EP2 DSLBIS, EP2 Upstream Link) + Min(SW1SSLBIS for SW1DSP1 (EP3), EP3 DSLBIS, EP3 Upstream link))) +

- **Min (GP1 to CPU BW,**

  - **Min(SW 2 Upstream Link to RP2 BW,**

    Min(SW2SSLBIS for SW2DSP0 (EP4), EP4 DSLBIS, EP4 Upstream Link) + Min(SW2SSLBIS for SW2DSP1 (EP5), EP5 DSLBIS, EP5 Upstream link)) +

  - **Min(SW 3 Upstream Link to RP3 BW,**

    Min(SW3SSLBIS for SW3DSP0 (EP6), EP6 DSLBIS, EP6 Upstream Link) + Min(SW3SSLBIS for SW3DSP1 (EP7), EP7 DSLBIS, EP7 Upstream link))))

The calculation starts at cxl_region_shared_upstream_perf_update(). A xarray is created to collect all the endpoint bandwidths via the cxl_endpoint_gather_bandwidth() function. The min() of bandwidth from the endpoint CDAT and the upstream link bandwidth is calculated. If the endpoint has a CXL switch as a parent, then min() of calculated bandwidth and the bandwidth from the SSLBIS for the switch downstream port that is associated with the endpoint is calculated. The final bandwidth is stored in a 'struct cxl_perf_ctx' in the xarray indexed by a device pointer. If the endpoint is direct attached to a root port (RP), the device pointer would be an RP device. If the endpoint is behind a switch, the device pointer would be the upstream device of the parent switch.

At the next stage, the code walks through one or more switches if they exist in the topology. For endpoints directly attached to RPs, this step is skipped. If there is another switch upstream, the code takes the min() of the current gathered bandwidth and the upstream link bandwidth. If there's a switch upstream, then the SSLBIS of the upstream switch.

Once the topology walk reaches the RP, whether it's direct attached endpoints or walking through the switch(es), cxl_rp_gather_bandwidth() is called. At this point all the bandwidths are aggregated per each host bridge, which is also the index for the resulting xarray.

The next step is to take the min() of the per host bridge bandwidth and the bandwidth from the Generic Port (GP). The bandwidths for the GP are retrieved via ACPI tables ([SRAT](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>) and [HMAT](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>)). The minimum bandwidth are aggregated under the same ACPI0017 device to form a new xarray.

Finally, the cxl_region_update_bandwidth() is called and the aggregated bandwidth from all the members of the last xarray is updated for the access coordinates residing in the cxl region (cxlr) context.

<a id="rst-qtg-id"></a>

## QTG ID

Each [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>) has a QTG ID field. This field provides the ID that associates with a QoS Throttling Group (QTG) for the CFMWS window. Once the access coordinates are calculated, an ACPI Device Specific Method can be issued to the ACPI0016 device to retrieve the QTG ID depends on the access coordinates provided. The QTG ID for the device can be used as guidance to match to the CFMWS to setup the best Linux root decoder for the device performance.

---

# CXL Driver Operation

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux_

> The devices described in this section are present in

<a id="rst-cxl-driver-operation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The devices described in this section are present in



```text
/sys/bus/cxl/devices/
/dev/cxl/
```

The `cxl-cli` library, maintained as part of the NDTCL project, may be used to script interactions with these devices.

<a id="rst-drivers"></a>

## Drivers

The CXL driver is split into a number of drivers.

- cxl_core  - fundamental init interface and core object creation

- cxl_port  - initializes root and provides port enumeration interface.

- cxl_acpi  - initializes root decoders and interacts with ACPI data.

- cxl_p/mem - initializes memory devices

- cxl_pci   - uses cxl_port to enumerate the actual fabric hierarchy.

<a id="rst-driver-devices"></a>

## Driver Devices

Here is an example from a single-socket system with 4 host bridges. Two host bridges have a single memory device attached, and the devices are interleaved into a single memory region. The memory region has been converted to dax.



```text
# ls /sys/bus/cxl/devices/
  dax_region0  decoder3.0  decoder6.0  mem0   port3
  decoder0.0   decoder4.0  decoder6.1  mem1   port4
  decoder1.0   decoder5.0  endpoint5   port1  region0
  decoder2.0   decoder5.1  endpoint6   port2  root0
```

```mermaid
flowchart TB
  n0(["root0"])
  n1(["port1"])
  n2(["port3"])
  n3(["decoder0.0"])
  n4(["endpoint5"])
  n5(["endpoint6"])
  n6(["decoder1.0"])
  n7(["decoder3.0"])
  n8(["decoder5.0"])
  n9(["decoder6.0"])
  n10(["region0"])
  n11(["dax_region0"])
  n12(["dax0.0"])
  n0 --> n1
  n0 --> n2
  n0 --> n3
  n1 --> n4
  n2 --> n5
  n1 --> n6
  n2 --> n7
  n4 --> n8
  n5 --> n9
  n3 --> n10
  n3 --> n6
  n3 --> n7
  n6 --> n8
  n7 --> n9
  n8 --> n10
  n9 --> n10
  n10 --> n11
  n11 --> n12
```

Diagraph of CXL fabric with a host-bridge interleave memory region

For this section we'll explore the devices present in this configuration, but we'll explore more configurations in-depth in example configurations below.

<a id="rst-base-devices"></a>

### Base Devices

Most devices in a CXL fabric are a `port` of some kind (because each device mostly routes request from one device to the next, rather than provide a direct service).

<a id="rst-root"></a>

#### Root

The `CXL Root` is logical object created by the `cxl_acpi` driver during `cxl_acpi_probe` - if the `ACPI0017` `Compute Express Link Root Object` Device Class is found.

The Root contains links to:

- `Host Bridge Ports` defined by CHBS in the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>)

- `Downstream Ports` typically connected to `Host Bridge Ports`.

- `Root Decoders` defined by CFMWS the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>)



```text
# ls /sys/bus/cxl/devices/root0
  decoder0.0          dport0  dport5    port2  subsystem
  decoders_committed  dport1  modalias  port3  uevent
  devtype             dport4  port1     port4  uport

# cat /sys/bus/cxl/devices/root0/devtype
  cxl_port

# cat port1/devtype
  cxl_port

# cat decoder0.0/devtype
  cxl_decoder_root
```

The root is first `logical port` in the CXL fabric, as presented by the Linux CXL driver.  The `CXL root` is a special type of `switch port`, in that it only has downstream port connections.

<a id="rst-port"></a>

#### Port

A `port` object is better described as a `switch port`.  It may represent a host bridge to the root or an actual switch port on a switch. A `switch port` contains one or more decoders used to route memory requests downstream ports, which may be connected to another `switch port` or an `endpoint port`.



```text
# ls /sys/bus/cxl/devices/port1
  decoder1.0          dport0    driver     parent_dport  uport
  decoders_committed  dport113  endpoint5  subsystem
  devtype             dport2    modalias   uevent

# cat devtype
  cxl_port

# cat decoder1.0/devtype
  cxl_decoder_switch

# cat endpoint5/devtype
  cxl_port
```

CXL `Host Bridges` in the fabric are probed during `cxl_acpi_probe` at the time the `CXL Root` is probed.  The allows for the immediate logical connection to between the root and host bridge.

- The root has a downstream port connection to a host bridge

- The host bridge has an upstream port connection to the root.

- The host bridge has one or more downstream port connections to switch or endpoint ports.

A `Host Bridge` is a special type of CXL `switch port`. It is explicitly defined in the ACPI specification via `ACPI0016` ID.  `Host Bridge` ports will be probed at `acpi_probe` time, while similar ports on an actual switch will be probed later.  Otherwise, switch and host bridge ports look very similar - the both contain switch decoders which route accesses between upstream and downstream ports.

<a id="rst-endpoint"></a>

#### Endpoint

An `endpoint` is a terminal port in the fabric.  This is a `logical device`, and may be one of many `logical devices` presented by a memory device. It is still considered a type of `port` in the fabric.

An `endpoint` contains `endpoint decoders` and the device's Coherent Device Attribute Table (which describes the device's capabilities).



```text
# ls /sys/bus/cxl/devices/endpoint5
  CDAT        decoders_committed  modalias      uevent
  decoder5.0  devtype             parent_dport  uport
  decoder5.1  driver              subsystem

# cat /sys/bus/cxl/devices/endpoint5/devtype
  cxl_port

# cat /sys/bus/cxl/devices/endpoint5/decoder5.0/devtype
  cxl_decoder_endpoint
```

<a id="rst-memory-device-memdev"></a>

#### Memory Device (memdev)

A `memdev` is probed and added by the `cxl_pci` driver in `cxl_pci_probe` and is managed by the `cxl_mem` driver. It primarily provides the `IOCTL` interface to a memory device, via `/dev/cxl/memN`, and exposes various device configuration data.



```text
# ls /sys/bus/cxl/devices/mem0
  dev       firmware_version    payload_max  security   uevent
  driver    label_storage_size  pmem         serial
  firmware  numa_node           ram          subsystem
```

A Memory Device is a discrete base object that is not a port.  While the physical device it belongs to may also host an `endpoint`, the relationship between an `endpoint` and a `memdev` is not captured in sysfs.

<a id="rst-port-relationships"></a>

#### Port Relationships

In our example described above, there are four host bridges attached to the root, and two of the host bridges have one endpoint attached.

```mermaid
flowchart TB
  n0(["root0"])
  n1(["port1"])
  n2(["port2"])
  n3(["port3"])
  n4(["port4"])
  n5(["endpoint5"])
  n6(["endpoint6"])
  n0 --> n1
  n0 --> n2
  n0 --> n3
  n0 --> n4
  n1 --> n5
  n3 --> n6
```

Diagraph of CXL fabric with a host-bridge interleave memory region

<a id="rst-decoders"></a>

### Decoders

A `Decoder` is short for a CXL Host-Managed Device Memory (HDM) Decoder. It is a device that routes accesses through the CXL fabric to an endpoint, and at the endpoint translates a `Host Physical` to `Device Physical` Addressing.

The CXL 3.1 specification heavily implies that only endpoint decoders should engage in translation of `Host Physical Address` to `Device Physical Address`.



```text
8.2.4.20 CXL HDM Decoder Capability Structure

IMPLEMENTATION NOTE
CXL Host Bridge and Upstream Switch Port Decode Flow

IMPLEMENTATION NOTE
Device Decode Logic
```

These notes imply that there are two logical groups of decoders.

- Routing Decoder - a decoder which routes accesses but does not translate addresses from HPA to DPA.

- Translating Decoder - a decoder which translates accesses from HPA to DPA for an endpoint to service.

The CXL drivers distinguish 3 decoder types: root, switch, and endpoint. Only endpoint decoders are Translating Decoders, all others are Routing Decoders.

> [!NOTE]
>
> PLATFORM VENDORS BE AWARE
>
> Linux makes a strong assumption that endpoint decoders are the only decoder in the fabric that actively translates HPA to DPA.  Linux assumes routing decoders pass the HPA unchanged to the next decoder in the fabric.
>
> It is therefore assumed that any given decoder in the fabric will have an address range that is a subset of its upstream port decoder. Any deviation from this scheme undefined per the specification.  Linux prioritizes spec-defined / architectural behavior.

Decoders may have one or more `Downstream Targets` if configured to interleave memory accesses.  This will be presented in sysfs via the `target_list` parameter.

<a id="rst-root-decoder"></a>

#### Root Decoder

A `Root Decoder` is logical construct of the physical address and interleave configurations present in the CFMWS field of the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>). Linux presents this information as a decoder present in the `CXL Root`.  We consider this a `Root Decoder`, though technically it exists on the boundary of the CXL specification and platform-specific CXL root implementations.

Linux considers these logical decoders a type of `Routing Decoder`, and is the first decoder in the CXL fabric to receive a memory access from the platform's memory controllers.

`Root Decoders` are created during `cxl_acpi_probe`.  One root decoder is created per CFMWS entry in the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>).

The `target_list` parameter is filled by the CFMWS target fields. Targets of a root decoder are `Host Bridges`, which means interleave done at the root decoder level is an `Inter-Host-Bridge Interleave`.

Only root decoders are capable of `Inter-Host-Bridge Interleave`.

Such interleaves must be configured by the platform and described in the ACPI CEDT CFMWS, as the target CXL host bridge UIDs in the CFMWS must match the CXL host bridge UIDs in the CHBS field of the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>) and the UID field of CXL Host Bridges defined in the [DSDT](</kernel/hardware/driver-api/cxl-platform-acpi/dsdt.md>).

Interleave settings in a root decoder describe how to interleave accesses among the *immediate downstream targets*, not the entire interleave set.

The memory range described in the root decoder is used to

1. Create a memory region (`region0` in this example), and

2. Associate the region with an IO Memory Resource (`kernel/resource.c`)



```text
# ls /sys/bus/cxl/devices/decoder0.0/
  cap_pmem           devtype                 region0
  cap_ram            interleave_granularity  size
  cap_type2          interleave_ways         start
  cap_type3          locked                  subsystem
  create_ram_region  modalias                target_list
  delete_region      qos_class               uevent

# cat /sys/bus/cxl/devices/decoder0.0/region0/resource
  0xc050000000
```

The IO Memory Resource is created during early boot when the CFMWS region is identified in the EFI Memory Map or E820 table (on x86).

Root decoders are defined as a separate devtype, but are also a type of `Switch Decoder` due to having downstream targets.



```text
# cat /sys/bus/cxl/devices/decoder0.0/devtype
  cxl_decoder_root
```

<a id="rst-switch-decoder"></a>

#### Switch Decoder

Any non-root, translating decoder is considered a `Switch Decoder`, and will present with the type `cxl_decoder_switch`. Both `Host Bridge` and `CXL Switch` (device) decoders are of type `cxl_decoder_switch`.



```text
# ls /sys/bus/cxl/devices/decoder1.0/
  devtype                 locked    size       target_list
  interleave_granularity  modalias  start      target_type
  interleave_ways         region    subsystem  uevent

# cat /sys/bus/cxl/devices/decoder1.0/devtype
  cxl_decoder_switch

# cat /sys/bus/cxl/devices/decoder1.0/region
  region0
```

A `Switch Decoder` has associations between a region defined by a root decoder and downstream target ports.  Interleaving done within a switch decoder is a multi-downstream-port interleave (or `Intra-Host-Bridge Interleave` for host bridges).

Interleave settings in a switch decoder describe how to interleave accesses among the *immediate downstream targets*, not the entire interleave set.

Switch decoders are created during `cxl_switch_port_probe` in the `cxl_port` driver, and is created based on a PCI device's DVSEC registers.

Switch decoder programming is validated during probe if the platform programs them during boot (See `Auto Decoders` below), or on commit if programmed at runtime (See `Runtime Programming` below).

<a id="rst-endpoint-decoder"></a>

#### Endpoint Decoder

Any decoder attached to a *terminal* point in the CXL fabric (`An Endpoint`) is considered an `Endpoint Decoder`. Endpoint decoders are of type `cxl_decoder_endpoint`.



```text
# ls /sys/bus/cxl/devices/decoder5.0
  devtype                 locked    start
  dpa_resource            modalias  subsystem
  dpa_size                mode      target_type
  interleave_granularity  region    uevent
  interleave_ways         size

# cat /sys/bus/cxl/devices/decoder5.0/devtype
  cxl_decoder_endpoint

# cat /sys/bus/cxl/devices/decoder5.0/region
  region0
```

An `Endpoint Decoder` has an association with a region defined by a root decoder and describes the device-local resource associated with this region.

Unlike root and switch decoders, endpoint decoders translate `Host Physical` to `Device Physical` address ranges.  The interleave settings on an endpoint therefore describe the entire *interleave set*.

`Device Physical Address` regions must be committed in-order. For example, the DPA region starting at 0x80000000 cannot be committed before the DPA region starting at 0x0.

As of Linux v6.15, Linux does not support *imbalanced* interleave setups, all endpoints in an interleave set are expected to have the same interleave settings (granularity and ways must be the same).

Endpoint decoders are created during `cxl_endpoint_port_probe` in the `cxl_port` driver, and is created based on a PCI device's DVSEC registers.

<a id="rst-decoder-relationships"></a>

#### Decoder Relationships

In our example described above, there is one root decoder which routes memory accesses over two host bridges.  Each host bridge has a decoder which routes access to their singular endpoint targets.  Each endpoint has a decoder which translates HPA to DPA and services the memory request.

The driver validates relationships between ports by decoder programming, so we can think of decoders being related in a similarly hierarchical fashion to ports.

```mermaid
flowchart TB
  n0(["root0"])
  n1(["decoder0.0"])
  n2(["decoder1.0"])
  n3(["decoder3.0"])
  n4(["decoder5.0"])
  n5(["decoder6.0"])
  n0 --> n1
  n1 --> n2
  n1 --> n3
  n2 --> n4
  n3 --> n5
```

Diagraph of CXL root, switch, and endpoint decoders.

<a id="rst-regions"></a>

### Regions

<a id="rst-memory-region"></a>

#### Memory Region

A `Memory Region` is a logical construct that connects a set of CXL ports in the fabric to an IO Memory Resource.  It is ultimately used to expose the memory on these devices to the DAX subsystem via a `DAX Region`.

An example RAM region:



```text
# ls /sys/bus/cxl/devices/region0/
  access0      devtype                 modalias  subsystem  uuid
  access1      driver                  mode      target0
  commit       interleave_granularity  resource  target1
  dax_region0  interleave_ways         size      uevent
```

A memory region can be constructed during endpoint probe, if decoders were programmed by BIOS/EFI (see `Auto Decoders`), or by creating a region manually via a `Root Decoder`'s `create_ram_region` or `create_pmem_region` interfaces.

The interleave settings in a `Memory Region` describe the configuration of the `Interleave Set` - and are what can be expected to be seen in the endpoint interleave settings.

```mermaid
flowchart TB
  n0(["root0"])
  n1(["decoder0.0"])
  n2(["region0"])
  n3(["decoder5.0"])
  n4(["decoder6.0"])
  n0 --> n1
  n1 --> n2
  n2 --> n3
  n2 --> n4
```

Regions are created based on root decoder configurations. Endpoint decoders
must be programmed with the same interleave settings as the region.

<a id="rst-dax-region"></a>

#### DAX Region

A `DAX Region` is used to convert a CXL `Memory Region` to a DAX device. A DAX device may then be accessed directly via a file descriptor interface, or converted to System RAM via the DAX kmem driver.  See the DAX driver section for more details.



```text
# ls /sys/bus/cxl/devices/dax_region0/
  dax0.0      devtype  modalias   uevent
  dax_region  driver   subsystem
```

<a id="rst-mailbox-interfaces"></a>

### Mailbox Interfaces

A mailbox command interface for each device is exposed in



```text
/dev/cxl/mem0
/dev/cxl/mem1
```

These mailboxes may receive any specification-defined command. Raw commands (custom commands) can only be sent to these interfaces if the build config `CXL_MEM_RAW_COMMANDS` is set.  This is considered a debug and/or development interface, not an officially supported mechanism for creation of vendor-specific commands (see the `fwctl` subsystem for that).

<a id="rst-decoder-programming"></a>

## Decoder Programming

<a id="rst-runtime-programming"></a>

### Runtime Programming

During probe, the only decoders *required* to be programmed are `Root Decoders`. In reality, `Root Decoders` are a logical construct to describe the memory region and interleave configuration at the host bridge level - as described in the ACPI CEDT CFMWS.

All other `Switch` and `Endpoint` decoders may be programmed by the user at runtime - if the platform supports such configurations.

This interaction is what creates a `Software Defined Memory` environment.

See the `cxl-cli` documentation for more information about how to configure CXL decoders at runtime.

<a id="rst-auto-decoders"></a>

### Auto Decoders

Auto Decoders are decoders programmed by BIOS/EFI at boot time, and are almost always locked (cannot be changed).  This is done by a platform which may have a static configuration - or certain quirks which may prevent dynamic runtime changes to the decoders (such as requiring additional controller programming within the CPU complex outside the scope of CXL).

Auto Decoders are probed automatically as long as the devices and memory regions they are associated with probe without issue.  When probing Auto Decoders, the driver's primary responsibility is to ensure the fabric is sane - as-if validating runtime programmed regions and decoders.

If Linux cannot validate auto-decoder configuration, the memory will not be surfaced as a DAX device - and therefore not be exposed to the page allocator - effectively stranding it.

<a id="rst-interleave"></a>

### Interleave

The Linux CXL driver supports `Cross-Link First` interleave. This dictates how interleave is programmed at each decoder step, as the driver validates the relationships between a decoder and it's parent.

For example, in a `Cross-Link First` interleave setup with 16 endpoints attached to 4 host bridges, linux expects the following ways/granularity across the root, host bridge, and endpoints respectively.


<table>
<caption>4x4 cross-link first interleave settings</caption>
<tbody>
<tr>
<td>


decoder

</td>
<td>


ways

</td>
<td>


granularity

</td>
</tr>
<tr>
<td>


root

</td>
<td>


4

</td>
<td>


256

</td>
</tr>
<tr>
<td>


host bridge

</td>
<td>


4

</td>
<td>


1024

</td>
</tr>
<tr>
<td>


endpoint

</td>
<td>


16

</td>
<td>


256

</td>
</tr>
</tbody>
</table>

At the root, every a given access will be routed to the `((HPA / 256) % 4)th` target host bridge. Within a host bridge, every `((HPA / 1024) % 4)th` target endpoint.  Each endpoint translates based on the entire 16 device interleave set.

Unbalanced interleave sets are not supported - decoders at a similar point in the hierarchy (e.g. all host bridge decoders) must have the same ways and granularity configuration.

<a id="rst-at-root"></a>

#### At Root

Root decoder interleave is defined by CFMWS field of the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>).  The CEDT may actually define multiple CFMWS configurations to describe the same physical capacity, with the intent to allow users to decide at runtime whether to online memory as interleaved or non-interleaved.



```text
           Subtable Type : 01 [CXL Fixed Memory Window Structure]
     Window base address : 0000000100000000
             Window size : 0000000100000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
            First Target : 00000007

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
     Window base address : 0000000200000000
             Window size : 0000000100000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
            First Target : 00000006

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
     Window base address : 0000000300000000
             Window size : 0000000200000000
Interleave Members (2^n) : 01
   Interleave Arithmetic : 00
            First Target : 00000007
             Next Target : 00000006
```

In this example, the CFMWS defines two discrete non-interleaved 4GB regions for each host bridge, and one interleaved 8GB region that targets both. This would result in 3 root decoders presenting in the root.



```text
# ls /sys/bus/cxl/devices/root0/decoder*
  decoder0.0  decoder0.1  decoder0.2

# cat /sys/bus/cxl/devices/decoder0.0/target_list start size
  7
  0x100000000
  0x100000000

# cat /sys/bus/cxl/devices/decoder0.1/target_list start size
  6
  0x200000000
  0x100000000

# cat /sys/bus/cxl/devices/decoder0.2/target_list start size
  7,6
  0x300000000
  0x200000000
```

These decoders are not runtime programmable.  They are used to generate a `Memory Region` to bring this memory online with runtime programmed settings at the `Switch` and `Endpoint` decoders.

<a id="rst-at-host-bridge-or-switch"></a>

#### At Host Bridge or Switch

`Host Bridge` and `Switch` decoders are programmable via the following fields:

- `start` - the HPA region associated with the memory region

- `size` - the size of the region

- `target_list` - the list of downstream ports

- `interleave_ways` - the number downstream ports to interleave across

- `interleave_granularity` - the granularity to interleave at.

Linux expects the `interleave_granularity` of switch decoders to be derived from their upstream port connections. In `Cross-Link First` interleave configurations, the `interleave_granularity` of a decoder is equal to `parent_interleave_granularity * parent_interleave_ways`.

<a id="rst-at-endpoint"></a>

#### At Endpoint

`Endpoint Decoders` are programmed similar to Host Bridge and Switch decoders, with the exception that the ways and granularity are defined by the interleave set (e.g. the interleave settings defined by the associated `Memory Region`).

- `start` - the HPA region associated with the memory region

- `size` - the size of the region

- `interleave_ways` - the number endpoints in the interleave set

- `interleave_granularity` - the granularity to interleave at.

These settings are used by endpoint decoders to *Translate* memory requests from HPA to DPA.  This is why they must be aware of the entire interleave set.

Linux does not support unbalanced interleave configurations.  As a result, all endpoints in an interleave set must have the same ways and granularity.

<a id="rst-example-configurations"></a>

## Example Configurations

- [Single Device](</kernel/hardware/driver-api/cxl-linux-example-configurations/single-device.md>)
- [Inter-Host-Bridge Interleave](</kernel/hardware/driver-api/cxl-linux-example-configurations/hb-interleave.md>)
- [Intra-Host-Bridge Interleave](</kernel/hardware/driver-api/cxl-linux-example-configurations/intra-hb-interleave.md>)
- [Multi-Level Interleave](</kernel/hardware/driver-api/cxl-linux-example-configurations/multi-interleave.md>)

---

# DAX Driver Operation

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux_

> The Direct Access Device driver was originally designed to provide a memory-like access mechanism to memory-like block-devices. It was extended to support CXL Memory Devices, which provide user-configured memory devices.

<a id="rst-dax-driver-operation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The `Direct Access Device` driver was originally designed to provide a memory-like access mechanism to memory-like block-devices.  It was extended to support CXL Memory Devices, which provide user-configured memory devices.

The CXL subsystem depends on the DAX subsystem to either:

- Generate a file-like interface to userland via `/dev/daxN.Y`, or

- Engage the memory-hotplug interface to add CXL memory to page allocator.

The DAX subsystem exposes this ability through the `cxl_dax_region` driver. A `dax_region` provides the translation between a CXL `memory_region` and a `DAX Device`.

<a id="rst-dax-device"></a>

## DAX Device

A `DAX Device` is a file-like interface exposed in `/dev/daxN.Y`. A memory region exposed via dax device can be accessed via userland software via the `mmap()` system-call.  The result is direct mappings to the CXL capacity in the task's page tables.

Users wishing to manually handle allocation of CXL memory should use this interface.

<a id="rst-kmem-conversion"></a>

## kmem conversion

The `dax_kmem` driver converts a `DAX Device` into a series of `hotplug memory blocks` managed by `kernel/memory-hotplug.c`.  This capacity will be exposed to the kernel page allocator in the user-selected memory zone.

The `memmap_on_memory` setting (both global and DAX device local) dictates where the kernell will allocate the `struct folio` descriptors for this memory will come from.  If `memmap_on_memory` is set, memory hotplug will set aside a portion of the memory block capacity to allocate folios. If unset, the memory is allocated via a normal `GFP_KERNEL` allocation - and as a result will most likely land on the local NUM node of the CPU executing the hotplug operation.

---

# Linux Init (Early Boot)

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux_

> Linux configuration is split into two major steps: Early-Boot and everything else.

<a id="rst-linux-init-early-boot"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Linux configuration is split into two major steps: Early-Boot and everything else.

During early boot, Linux sets up immutable resources (such as numa nodes), while later operations include things like driver probe and memory hotplug.  Linux may read EFI and ACPI information throughout this process to configure logical representations of the devices.

During Linux Early Boot stage (functions in the kernel that have the \__init decorator), the system takes the resources created by EFI/BIOS ([ACPI tables](</kernel/hardware/driver-api/cxl-platform/acpi.md>)) and turns them into resources that the kernel can consume.

<a id="rst-bios-build-and-boot-options"></a>

## BIOS, Build and Boot Options

There are 4 pre-boot options that need to be considered during kernel build which dictate how memory will be managed by Linux during early boot.

- EFI_MEMORY_SP

  - BIOS/EFI Option that dictates whether memory is SystemRAM or Specific Purpose.  Specific Purpose memory will be deferred to drivers to manage - and not immediately exposed as system RAM.

- CONFIG_EFI_SOFT_RESERVE

  - Linux Build config option that dictates whether the kernel supports Specific Purpose memory.

- CONFIG_MHP_DEFAULT_ONLINE_TYPE

  - Linux Build config that dictates whether and how Specific Purpose memory converted to a dax device should be managed (left as DAX or onlined as SystemRAM in ZONE_NORMAL or ZONE_MOVABLE).

- nosoftreserve

  - Linux kernel boot option that dictates whether Soft Reserve should be supported.  Similar to CONFIG_EFI_SOFT_RESERVE.

<a id="rst-memory-map-creation"></a>

## Memory Map Creation

While the kernel parses the EFI memory map, if `Specific Purpose` memory is supported and detected, it will set this region aside as `SOFT_RESERVED`.

If `EFI_MEMORY_SP=0`, `CONFIG_EFI_SOFT_RESERVE=n`, or `nosoftreserve=y` - Linux will default a CXL device memory region to SystemRAM.  This will expose the memory to the kernel page allocator in `ZONE_NORMAL`, making it available for use for most allocations (including `struct page` and page tables).

If `Specific Purpose` is set and supported, `CONFIG_MHP_DEFAULT_ONLINE_TYPE_*` dictates whether the memory is onlined by default (`_OFFLINE` or `_ONLINE_*`), and if online which zone to online this memory to by default (`_NORMAL` or `_MOVABLE`).

If placed in `ZONE_MOVABLE`, the memory will not be available for most kernel allocations (such as `struct page` or page tables).  This may significant impact performance depending on the memory capacity of the system.

<a id="rst-numa-node-reservation"></a>

## NUMA Node Reservation

Linux refers to the proximity domains (`PXM`) defined in the [SRAT](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>) to create NUMA nodes in `acpi_numa_init`. Typically, there is a 1:1 relation between `PXM` and NUMA node IDs.

The SRAT is the only ACPI defined way of defining Proximity Domains. Linux chooses to, at most, map those 1:1 with NUMA nodes. [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>) adds a description of SPA ranges which Linux may map to one or more NUMA nodes.

If there are CXL ranges in the CFMWS but not in SRAT, then a fake `PXM` is created (as of v6.15). In the future, Linux may reject CFMWS not described by SRAT due to the ambiguity of proximity domain association.

It is important to note that NUMA node creation cannot be done at runtime. All possible NUMA nodes are identified at `__init` time, more specifically during `mm_init`. The CEDT and SRAT must contain sufficient `PXM` data for Linux to identify NUMA nodes their associated memory regions.

The relevant code exists in: `linux/drivers/acpi/numa/srat.c`.

See [Example Platform Configurations](</kernel/hardware/driver-api/cxl-platform/example-configs.md>) for more info.

<a id="rst-memory-tiers-creation"></a>

## Memory Tiers Creation

Memory tiers are a collection of NUMA nodes grouped by performance characteristics. During `__init`, Linux initializes the system with a default memory tier that contains all nodes marked `N_MEMORY`.

`memory_tier_init` is called at boot for all nodes with memory online by default. `memory_tier_late_init` is called during late-init for nodes setup during driver configuration.

Nodes are only marked `N_MEMORY` if they have *online* memory.

Tier membership can be inspected in



```text
/sys/devices/virtual/memory_tiering/memory_tierN/nodelist
0-1
```

If nodes are grouped which have clear difference in performance, check the [HMAT](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>) and CDAT information for the CXL nodes. All nodes default to the DRAM tier, unless HMAT/CDAT information is reported to the memory_tier component via `access_coordinates`.

For more, see [CXL access coordinates documentation](</kernel/hardware/driver-api/cxl-linux/access-coordinates.md>).

<a id="rst-contiguous-memory-allocation"></a>

## Contiguous Memory Allocation

The contiguous memory allocator (CMA) enables reservation of contiguous memory regions on NUMA nodes during early boot.  However, CMA cannot reserve memory on NUMA nodes that are not online during early boot.



```text
void __init hugetlb_cma_reserve(void) {
  if (!node_online(nid))
    /* do not allow reservations */
}
```

This means if users intend to defer management of CXL memory to the driver, CMA cannot be used to guarantee huge page allocations.  If enabling CXL memory as SystemRAM in `ZONE_NORMAL` during early boot, CMA reservations per-node can be made with the `cma_pernuma` or `numa_cma` kernel command line parameters.

---

# Memory Hotplug

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux_

> The final phase of surfacing CXL memory to the kernel page allocator is for the DAX driver to surface a Driver Managed memory region via the memory-hotplug component.

<a id="rst-memory-hotplug"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The final phase of surfacing CXL memory to the kernel page allocator is for the `DAX` driver to surface a `Driver Managed` memory region via the memory-hotplug component.

There are four major configurations to consider:

1. Default Online Behavior (on/off and zone)

2. Hotplug Memory Block size

3. Memory Map Resource location

4. Driver-Managed Memory Designation

<a id="rst-default-online-behavior"></a>

## Default Online Behavior

The default-online behavior of hotplug memory is dictated by the following, in order of precedence:

- `CONFIG_MHP_DEFAULT_ONLINE_TYPE` Build Configuration

- `memhp_default_state` Boot parameter

- `/sys/devices/system/memory/auto_online_blocks` value

These dictate whether hotplugged memory blocks arrive in one of three states:

1. Offline

2. Online in `ZONE_NORMAL`

3. Online in `ZONE_MOVABLE`

`ZONE_NORMAL` implies this capacity may be used for almost any allocation, while `ZONE_MOVABLE` implies this capacity should only be used for migratable allocations.

`ZONE_MOVABLE` attempts to retain the hotplug-ability of a memory block so that it the entire region may be hot-unplugged at a later time.  Any capacity onlined into `ZONE_NORMAL` should be considered permanently attached to the page allocator.

<a id="rst-hotplug-memory-block-size"></a>

## Hotplug Memory Block Size

By default, on most architectures, the Hotplug Memory Block Size is either 128MB or 256MB.  On x86, the block size increases up to 2GB as total memory capacity exceeds 64GB.  As of v6.15, Linux does not take into account the size and alignment of the ACPI CEDT CFMWS regions (see Early Boot docs) when deciding the Hotplug Memory Block Size.

<a id="rst-memory-map"></a>

## Memory Map

The location of `struct folio` allocations to represent the hotplugged memory capacity are dictated by the following system settings:

- `/sys_module/memory_hotplug/parameters/memmap_on_memory`

- `/sys/bus/dax/devices/daxN.Y/memmap_on_memory`

If both of these parameters are set to true, `struct folio` for this capacity will be carved out of the memory block being onlined.  This has performance implications if the memory is particularly high-latency and its `struct folio` becomes hotly contended.

If either parameter is set to false, `struct folio` for this capacity will be allocated from the local node of the processor running the hotplug procedure.  This capacity will be allocated from `ZONE_NORMAL` on that node, as it is a `GFP_KERNEL` allocation.

Systems with extremely large amounts of `ZONE_MOVABLE` memory (e.g. CXL memory pools) must ensure that there is sufficient local `ZONE_NORMAL` capacity to host the memory map for the hotplugged capacity.

<a id="rst-driver-managed-memory"></a>

## Driver Managed Memory

The DAX driver surfaces this memory to memory-hotplug as "Driver Managed". This is not a configurable setting, but it's important to note that driver managed memory is explicitly excluded from use during kexec.  This is required to ensure any reset or out-of-band operations that the CXL device may be subject to during a functional system-reboot (such as a reset-on-probe) will not cause portions of the kexec kernel to be overwritten.

---

# Overview

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux_

> This section presents the configuration process of a CXL Type-3 memory device, and how it is ultimately exposed to users as either a DAX device or normal memory pages via the kernel's page allocator.

<a id="rst-overview"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This section presents the configuration process of a CXL Type-3 memory device, and how it is ultimately exposed to users as either a `DAX` device or normal memory pages via the kernel's page allocator.

Portions marked with a bullet are points at which certain kernel objects are generated.

1. Early Boot

> - **a)** BIOS, Build, and Boot Parameters
>
> > - **i)** EFI_MEMORY_SP
> >
> > - **ii)** CONFIG_EFI_SOFT_RESERVE
> >
> > - **iii)** CONFIG_MHP_DEFAULT_ONLINE_TYPE
> >
> > - **iv)** nosoftreserve
>
> - **b)** Memory Map Creation
>
> > - **i)** EFI Memory Map / E820 Consulted for Soft-Reserved
> >
> > > - CXL Memory is set aside to be handled by the CXL driver
> > >
> > > - Soft-Reserved IO Resource created for CFMWS entry
>
> - **c)** NUMA Node Creation
>
> > - Nodes created from ACPI CEDT CFMWS and SRAT Proximity domains (PXM)
>
> - **d)** Memory Tier Creation
>
> > - A default memory_tier is created with all nodes.
>
> - **e)** Contiguous Memory Allocation
>
> > - Any requested CMA is allocated from Online nodes
>
> - **f)** Init Finishes, Drivers start probing

2. ACPI and PCI Drivers

> - **a)** Detects PCI device is CXL, marking it for probe by CXL driver

3. CXL Driver Operation

> - **a)** Base device creation
>
> > - root, port, and memdev devices created
> >
> > - CEDT CFMWS IO Resource creation
>
> - **b)** Decoder creation
>
> > - root, switch, and endpoint decoders created
>
> - **c)** Logical device creation
>
> > - memory_region and endpoint devices created
>
> - **d)** Devices are associated with each other
>
> > - If auto-decoder (BIOS-programmed decoders), driver validates configurations, builds associations, and locks configs at probe time.
> >
> > - If user-configured, validation and associations are built at decoder-commit time.
>
> - **e)** Regions surfaced as DAX region
>
> > - dax_region created
> >
> > - DAX device created via DAX driver

4. DAX Driver Operation

> - **a)** DAX driver surfaces DAX region as one of two dax device modes
>
> > - kmem - dax device is converted to hotplug memory blocks
> >
> >   - DAX kmem IO Resource creation
> >
> > - hmem - dax device is left as daxdev to be accessed as a file.
> >
> >   - If hmem, journey ends here.
>
> - **b)** DAX kmem surfaces memory region to Memory Hotplug to add to page allocator as "driver managed memory"

5. Memory Hotplug

> - **a)** mhp component surfaces a dax device memory region as multiple memory blocks to the page allocator
>
> > - blocks appear in `/sys/bus/memory/devices` and linked to a NUMA node
>
> - **b)** blocks are onlined into the requested zone (NORMAL or MOVABLE)
>
> > - Memory is marked "Driver Managed" to avoid kexec from using it as region for kernel updates

---

# Inter-Host-Bridge Interleave

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux: example-configurations_

> This cxl-cli configuration dump shows the following host configuration:

<a id="rst-inter-host-bridge-interleave"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This cxl-cli configuration dump shows the following host configuration:

- A single socket system with one CXL root

- CXL Root has Four (4) CXL Host Bridges

- Two CXL Host Bridges have a single CXL Memory Expander Attached

- The CXL root is configured to interleave across the two host bridges.

This output is generated by `cxl list -v` and describes the relationships between objects exposed in `/sys/bus/cxl/devices/`.



```text
[
  {
      "bus":"root0",
      "provider":"ACPI.CXL",
      "nr_dports":4,
      "dports":[
          {
              "dport":"pci0000:00",
              "alias":"ACPI0016:01",
              "id":0
          },
          {
              "dport":"pci0000:a8",
              "alias":"ACPI0016:02",
              "id":4
          },
          {
              "dport":"pci0000:2a",
              "alias":"ACPI0016:03",
              "id":1
          },
          {
              "dport":"pci0000:d2",
              "alias":"ACPI0016:00",
              "id":5
          }
      ],
```

This chunk shows the CXL "bus" (root0) has 4 downstream ports attached to CXL Host Bridges.  The `Root` can be considered the singular upstream port attached to the platform's memory controller - which routes memory requests to it.

The `ports:root0` section lays out how each of these downstream ports are configured.  If a port is not configured (id's 0 and 1), they are omitted.



```text
"ports:root0":[
    {
        "port":"port1",
        "host":"pci0000:d2",
        "depth":1,
        "nr_dports":3,
        "dports":[
            {
                "dport":"0000:d2:01.1",
                "alias":"device:02",
                "id":0
            },
            {
                "dport":"0000:d2:01.3",
                "alias":"device:05",
                "id":2
            },
            {
                "dport":"0000:d2:07.1",
                "alias":"device:0d",
                "id":113
            }
        ],
```

This chunk shows the available downstream ports associated with the CXL Host Bridge `port1`.  In this case, `port1` has 3 available downstream ports: `dport1`, `dport2`, and `dport113`..



```text
"endpoints:port1":[
    {
        "endpoint":"endpoint5",
        "host":"mem0",
        "parent_dport":"0000:d2:01.1",
        "depth":2,
        "memdev":{
            "memdev":"mem0",
            "ram_size":137438953472,
            "serial":0,
            "numa_node":0,
            "host":"0000:d3:00.0"
        },
        "decoders:endpoint5":[
            {
                "decoder":"decoder5.0",
                "resource":825975898112,
                "size":274877906944,
                "interleave_ways":2,
                "interleave_granularity":256,
                "region":"region0",
                "dpa_resource":0,
                "dpa_size":137438953472,
                "mode":"ram"
            }
        ]
    }
],
```

This chunk shows the endpoints attached to the host bridge `port1`.

`endpoint5` contains a single configured decoder `decoder5.0` which has the same interleave configuration as `region0` (shown later).

Next we have the decodesr belonging to the host bridge:



```text
    "decoders:port1":[
        {
            "decoder":"decoder1.0",
            "resource":825975898112,
            "size":274877906944,
            "interleave_ways":1,
            "region":"region0",
            "nr_targets":1,
            "targets":[
                {
                    "target":"0000:d2:01.1",
                    "alias":"device:02",
                    "position":0,
                    "id":0
                }
            ]
        }
    ]
},
```

Host Bridge `port1` has a single decoder (`decoder1.0`), whose only target is `dport1` - which is attached to `endpoint5`.

The following chunk shows a similar configuration for Host Bridge `port3`, the second host bridge with a memory device attached.



```text
{
    "port":"port3",
    "host":"pci0000:a8",
    "depth":1,
    "nr_dports":1,
    "dports":[
        {
            "dport":"0000:a8:01.1",
            "alias":"device:c3",
            "id":0
        }
    ],
    "endpoints:port3":[
        {
            "endpoint":"endpoint6",
            "host":"mem1",
            "parent_dport":"0000:a8:01.1",
            "depth":2,
            "memdev":{
                "memdev":"mem1",
                "ram_size":137438953472,
                "serial":0,
                "numa_node":0,
                "host":"0000:a9:00.0"
            },
            "decoders:endpoint6":[
                {
                    "decoder":"decoder6.0",
                    "resource":825975898112,
                    "size":274877906944,
                    "interleave_ways":2,
                    "interleave_granularity":256,
                    "region":"region0",
                    "dpa_resource":0,
                    "dpa_size":137438953472,
                    "mode":"ram"
                }
            ]
        }
    ],
    "decoders:port3":[
        {
            "decoder":"decoder3.0",
            "resource":825975898112,
            "size":274877906944,
            "interleave_ways":1,
            "region":"region0",
            "nr_targets":1,
            "targets":[
                {
                    "target":"0000:a8:01.1",
                    "alias":"device:c3",
                    "position":0,
                    "id":0
                }
            ]
        }
    ]
},
```

The next chunk shows the two CXL host bridges without attached endpoints.



```text
    {
        "port":"port2",
        "host":"pci0000:00",
        "depth":1,
        "nr_dports":2,
        "dports":[
            {
                "dport":"0000:00:01.3",
                "alias":"device:55",
                "id":2
            },
            {
                "dport":"0000:00:07.1",
                "alias":"device:5d",
                "id":113
            }
        ]
    },
    {
        "port":"port4",
        "host":"pci0000:2a",
        "depth":1,
        "nr_dports":1,
        "dports":[
            {
                "dport":"0000:2a:01.1",
                "alias":"device:d0",
                "id":0
            }
        ]
    }
],
```

Next we have the `Root Decoders` belonging to `root0`.  This root decoder applies the interleave across the downstream ports `port1` and `port3` - with a granularity of 256 bytes.

This information is generated by the CXL driver reading the ACPI CEDT CMFWS.



```text
"decoders:root0":[
    {
        "decoder":"decoder0.0",
        "resource":825975898112,
        "size":274877906944,
        "interleave_ways":2,
        "interleave_granularity":256,
        "max_available_extent":0,
        "volatile_capable":true,
        "nr_targets":2,
        "targets":[
            {
                "target":"pci0000:a8",
                "alias":"ACPI0016:02",
                "position":1,
                "id":4
            },
            {
                "target":"pci0000:d2",
                "alias":"ACPI0016:00",
                "position":0,
                "id":5
            }
        ],
```

Finally we have the `Memory Region` associated with the `Root Decoder` `decoder0.0`.  This region describes the overall interleave configuration of the interleave set.



```text
              "regions:decoder0.0":[
                  {
                      "region":"region0",
                      "resource":825975898112,
                      "size":274877906944,
                      "type":"ram",
                      "interleave_ways":2,
                      "interleave_granularity":256,
                      "decode_state":"commit",
                      "mappings":[
                          {
                              "position":1,
                              "memdev":"mem1",
                              "decoder":"decoder6.0"
                          },
                          {
                              "position":0,
                              "memdev":"mem0",
                              "decoder":"decoder5.0"
                          }
                      ]
                  }
              ]
          }
      ]
  }
]
```

---

# Intra-Host-Bridge Interleave

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux: example-configurations_

> This cxl-cli configuration dump shows the following host configuration:

<a id="rst-intra-host-bridge-interleave"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This cxl-cli configuration dump shows the following host configuration:

- A single socket system with one CXL root

- CXL Root has Four (4) CXL Host Bridges

- One (1) CXL Host Bridges has two CXL Memory Expanders Attached

- The Host bridge decoder is programmed to interleave across the expanders.

This output is generated by `cxl list -v` and describes the relationships between objects exposed in `/sys/bus/cxl/devices/`.



```text
[
  {
      "bus":"root0",
      "provider":"ACPI.CXL",
      "nr_dports":4,
      "dports":[
          {
              "dport":"pci0000:00",
              "alias":"ACPI0016:01",
              "id":0
          },
          {
              "dport":"pci0000:a8",
              "alias":"ACPI0016:02",
              "id":4
          },
          {
              "dport":"pci0000:2a",
              "alias":"ACPI0016:03",
              "id":1
          },
          {
              "dport":"pci0000:d2",
              "alias":"ACPI0016:00",
              "id":5
          }
      ],
```

This chunk shows the CXL "bus" (root0) has 4 downstream ports attached to CXL Host Bridges.  The `Root` can be considered the singular upstream port attached to the platform's memory controller - which routes memory requests to it.

The `ports:root0` section lays out how each of these downstream ports are configured.  If a port is not configured (id's 0 and 1), they are omitted.



```text
"ports:root0":[
    {
        "port":"port1",
        "host":"pci0000:d2",
        "depth":1,
        "nr_dports":3,
        "dports":[
            {
                "dport":"0000:d2:01.1",
                "alias":"device:02",
                "id":0
            },
            {
                "dport":"0000:d2:01.3",
                "alias":"device:05",
                "id":2
            },
            {
                "dport":"0000:d2:07.1",
                "alias":"device:0d",
                "id":113
            }
        ],
```

This chunk shows the available downstream ports associated with the CXL Host Bridge `port1`.  In this case, `port1` has 3 available downstream ports: `dport1`, `dport2`, and `dport113`..



```text
"endpoints:port1":[
    {
        "endpoint":"endpoint5",
        "host":"mem0",
        "parent_dport":"0000:d2:01.1",
        "depth":2,
        "memdev":{
            "memdev":"mem0",
            "ram_size":137438953472,
            "serial":0,
            "numa_node":0,
            "host":"0000:d3:00.0"
        },
        "decoders:endpoint5":[
            {
                "decoder":"decoder5.0",
                "resource":825975898112,
                "size":274877906944,
                "interleave_ways":2,
                "interleave_granularity":256,
                "region":"region0",
                "dpa_resource":0,
                "dpa_size":137438953472,
                "mode":"ram"
            }
        ]
    },
    {
        "endpoint":"endpoint6",
        "host":"mem1",
        "parent_dport":"0000:d2:01.3,
        "depth":2,
        "memdev":{
            "memdev":"mem1",
            "ram_size":137438953472,
            "serial":0,
            "numa_node":0,
            "host":"0000:a9:00.0"
        },
        "decoders:endpoint6":[
            {
                "decoder":"decoder6.0",
                "resource":825975898112,
                "size":274877906944,
                "interleave_ways":2,
                "interleave_granularity":256,
                "region":"region0",
                "dpa_resource":0,
                "dpa_size":137438953472,
                "mode":"ram"
            }
        ]
    }
],
```

This chunk shows the endpoints attached to the host bridge `port1`.

`endpoint5` contains a single configured decoder `decoder5.0` which has the same interleave configuration memory region they belong to (show later).

Next we have the decoders belonging to the host bridge:



```text
    "decoders:port1":[
        {
            "decoder":"decoder1.0",
            "resource":825975898112,
            "size":274877906944,
            "interleave_ways":2,
            "interleave_granularity":256,
            "region":"region0",
            "nr_targets":2,
            "targets":[
                {
                    "target":"0000:d2:01.1",
                    "alias":"device:02",
                    "position":0,
                    "id":0
                },
                {
                    "target":"0000:d2:01.3",
                    "alias":"device:05",
                    "position":1,
                    "id":0
                }
            ]
        }
    ]
},
```

Host Bridge `port1` has a single decoder (`decoder1.0`) with two targets: `dport1` and `dport3` - which are attached to `endpoint5` and `endpoint6` respectively.

The host bridge decoder interleaves these devices at a 256 byte granularity.

The next chunk shows the three CXL host bridges without attached endpoints.



```text
    {
        "port":"port2",
        "host":"pci0000:00",
        "depth":1,
        "nr_dports":2,
        "dports":[
            {
                "dport":"0000:00:01.3",
                "alias":"device:55",
                "id":2
            },
            {
                "dport":"0000:00:07.1",
                "alias":"device:5d",
                "id":113
            }
        ]
    },
    {
        "port":"port3",
        "host":"pci0000:a8",
        "depth":1,
        "nr_dports":1,
        "dports":[
            {
                "dport":"0000:a8:01.1",
                "alias":"device:c3",
                "id":0
            }
        ],
    },
    {
        "port":"port4",
        "host":"pci0000:2a",
        "depth":1,
        "nr_dports":1,
        "dports":[
            {
                "dport":"0000:2a:01.1",
                "alias":"device:d0",
                "id":0
            }
        ]
    }
],
```

Next we have the `Root Decoders` belonging to `root0`.  This root decoder applies the interleave across the downstream ports `port1` and `port3` - with a granularity of 256 bytes.

This information is generated by the CXL driver reading the ACPI CEDT CMFWS.



```text
"decoders:root0":[
    {
        "decoder":"decoder0.0",
        "resource":825975898112,
        "size":274877906944,
        "interleave_ways":1,
        "max_available_extent":0,
        "volatile_capable":true,
        "nr_targets":2,
        "targets":[
            {
                "target":"pci0000:a8",
                "alias":"ACPI0016:02",
                "position":1,
                "id":4
            },
        ],
```

Finally we have the `Memory Region` associated with the `Root Decoder` `decoder0.0`.  This region describes the overall interleave configuration of the interleave set.



```text
              "regions:decoder0.0":[
                  {
                      "region":"region0",
                      "resource":825975898112,
                      "size":274877906944,
                      "type":"ram",
                      "interleave_ways":2,
                      "interleave_granularity":256,
                      "decode_state":"commit",
                      "mappings":[
                          {
                              "position":1,
                              "memdev":"mem1",
                              "decoder":"decoder6.0"
                          },
                          {
                              "position":0,
                              "memdev":"mem0",
                              "decoder":"decoder5.0"
                          }
                      ]
                  }
              ]
          }
      ]
  }
]
```

---

# Multi-Level Interleave

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux: example-configurations_

> This cxl-cli configuration dump shows the following host configuration:

<a id="rst-multi-level-interleave"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This cxl-cli configuration dump shows the following host configuration:

- A single socket system with one CXL root

- CXL Root has Four (4) CXL Host Bridges

- Two CXL Host Bridges have a two CXL Memory Expanders Attached each.

- The CXL root is configured to interleave across the two host bridges.

- Each host bridge with expanders interleaves across two endpoints.

This output is generated by `cxl list -v` and describes the relationships between objects exposed in `/sys/bus/cxl/devices/`.



```text
[
  {
      "bus":"root0",
      "provider":"ACPI.CXL",
      "nr_dports":4,
      "dports":[
          {
              "dport":"pci0000:00",
              "alias":"ACPI0016:01",
              "id":0
          },
          {
              "dport":"pci0000:a8",
              "alias":"ACPI0016:02",
              "id":4
          },
          {
              "dport":"pci0000:2a",
              "alias":"ACPI0016:03",
              "id":1
          },
          {
              "dport":"pci0000:d2",
              "alias":"ACPI0016:00",
              "id":5
          }
      ],
```

This chunk shows the CXL "bus" (root0) has 4 downstream ports attached to CXL Host Bridges.  The `Root` can be considered the singular upstream port attached to the platform's memory controller - which routes memory requests to it.

The `ports:root0` section lays out how each of these downstream ports are configured.  If a port is not configured (id's 0 and 1), they are omitted.



```text
"ports:root0":[
    {
        "port":"port1",
        "host":"pci0000:d2",
        "depth":1,
        "nr_dports":3,
        "dports":[
            {
                "dport":"0000:d2:01.1",
                "alias":"device:02",
                "id":0
            },
            {
                "dport":"0000:d2:01.3",
                "alias":"device:05",
                "id":2
            },
            {
                "dport":"0000:d2:07.1",
                "alias":"device:0d",
                "id":113
            }
        ],
```

This chunk shows the available downstream ports associated with the CXL Host Bridge `port1`.  In this case, `port1` has 3 available downstream ports: `dport0`, `dport2`, and `dport113`.



```text
"endpoints:port1":[
    {
        "endpoint":"endpoint5",
        "host":"mem0",
        "parent_dport":"0000:d2:01.1",
        "depth":2,
        "memdev":{
            "memdev":"mem0",
            "ram_size":137438953472,
            "serial":0,
            "numa_node":0,
            "host":"0000:d3:00.0"
        },
        "decoders:endpoint5":[
            {
                "decoder":"decoder5.0",
                "resource":825975898112,
                "size":549755813888,
                "interleave_ways":4,
                "interleave_granularity":256,
                "region":"region0",
                "dpa_resource":0,
                "dpa_size":137438953472,
                "mode":"ram"
            }
        ]
    },
    {
        "endpoint":"endpoint6",
        "host":"mem1",
        "parent_dport":"0000:d2:01.3",
        "depth":2,
        "memdev":{
            "memdev":"mem1",
            "ram_size":137438953472,
            "serial":0,
            "numa_node":0,
            "host":"0000:d3:00.0"
        },
        "decoders:endpoint6":[
            {
                "decoder":"decoder6.0",
                "resource":825975898112,
                "size":549755813888,
                "interleave_ways":4,
                "interleave_granularity":256,
                "region":"region0",
                "dpa_resource":0,
                "dpa_size":137438953472,
                "mode":"ram"
            }
        ]
    }
],
```

This chunk shows the endpoints attached to the host bridge `port1`.

`endpoint5` contains a single configured decoder `decoder5.0` which has the same interleave configuration as `region0` (shown later).

`endpoint6` contains a single configured decoder `decoder5.0` which has the same interleave configuration as `region0` (shown later).

Next we have the decoders belonging to the host bridge:



```text
    "decoders:port1":[
        {
            "decoder":"decoder1.0",
            "resource":825975898112,
            "size":549755813888,
            "interleave_ways":2,
            "interleave_granularity":512,
            "region":"region0",
            "nr_targets":2,
            "targets":[
                {
                    "target":"0000:d2:01.1",
                    "alias":"device:02",
                    "position":0,
                    "id":0
                },
                {
                    "target":"0000:d2:01.3",
                    "alias":"device:05",
                    "position":2,
                    "id":0
                }
            ]
        }
    ]
},
```

Host Bridge `port1` has a single decoder (`decoder1.0`), whose targets are `dport0` and `dport2` - which are attached to `endpoint5` and `endpoint6` respectively.

The following chunk shows a similar configuration for Host Bridge `port3`, the second host bridge with a memory device attached.



```text
{
    "port":"port3",
    "host":"pci0000:a8",
    "depth":1,
    "nr_dports":1,
    "dports":[
        {
            "dport":"0000:a8:01.1",
            "alias":"device:c3",
            "id":0
        },
        {
            "dport":"0000:a8:01.3",
            "alias":"device:c5",
            "id":0
        }
    ],
    "endpoints:port3":[
        {
            "endpoint":"endpoint7",
            "host":"mem2",
            "parent_dport":"0000:a8:01.1",
            "depth":2,
            "memdev":{
                "memdev":"mem2",
                "ram_size":137438953472,
                "serial":0,
                "numa_node":0,
                "host":"0000:a9:00.0"
            },
            "decoders:endpoint7":[
                {
                    "decoder":"decoder7.0",
                    "resource":825975898112,
                    "size":549755813888,
                    "interleave_ways":4,
                    "interleave_granularity":256,
                    "region":"region0",
                    "dpa_resource":0,
                    "dpa_size":137438953472,
                    "mode":"ram"
                }
            ]
        },
        {
            "endpoint":"endpoint8",
            "host":"mem3",
            "parent_dport":"0000:a8:01.3",
            "depth":2,
            "memdev":{
                "memdev":"mem3",
                "ram_size":137438953472,
                "serial":0,
                "numa_node":0,
                "host":"0000:a9:00.0"
            },
            "decoders:endpoint8":[
                {
                    "decoder":"decoder8.0",
                    "resource":825975898112,
                    "size":549755813888,
                    "interleave_ways":4,
                    "interleave_granularity":256,
                    "region":"region0",
                    "dpa_resource":0,
                    "dpa_size":137438953472,
                    "mode":"ram"
                }
            ]
        }
    ],
    "decoders:port3":[
        {
            "decoder":"decoder3.0",
            "resource":825975898112,
            "size":549755813888,
            "interleave_ways":2,
            "interleave_granularity":512,
            "region":"region0",
            "nr_targets":1,
            "targets":[
                {
                    "target":"0000:a8:01.1",
                    "alias":"device:c3",
                    "position":1,
                    "id":0
                },
                {
                    "target":"0000:a8:01.3",
                    "alias":"device:c5",
                    "position":3,
                    "id":0
                }
            ]
        }
    ]
},
```

The next chunk shows the two CXL host bridges without attached endpoints.



```text
    {
        "port":"port2",
        "host":"pci0000:00",
        "depth":1,
        "nr_dports":2,
        "dports":[
            {
                "dport":"0000:00:01.3",
                "alias":"device:55",
                "id":2
            },
            {
                "dport":"0000:00:07.1",
                "alias":"device:5d",
                "id":113
            }
        ]
    },
    {
        "port":"port4",
        "host":"pci0000:2a",
        "depth":1,
        "nr_dports":1,
        "dports":[
            {
                "dport":"0000:2a:01.1",
                "alias":"device:d0",
                "id":0
            }
        ]
    }
],
```

Next we have the `Root Decoders` belonging to `root0`.  This root decoder applies the interleave across the downstream ports `port1` and `port3` - with a granularity of 256 bytes.

This information is generated by the CXL driver reading the ACPI CEDT CMFWS.



```text
"decoders:root0":[
    {
        "decoder":"decoder0.0",
        "resource":825975898112,
        "size":549755813888,
        "interleave_ways":2,
        "interleave_granularity":256,
        "max_available_extent":0,
        "volatile_capable":true,
        "nr_targets":2,
        "targets":[
            {
                "target":"pci0000:a8",
                "alias":"ACPI0016:02",
                "position":1,
                "id":4
            },
            {
                "target":"pci0000:d2",
                "alias":"ACPI0016:00",
                "position":0,
                "id":5
            }
        ],
```

Finally we have the `Memory Region` associated with the `Root Decoder` `decoder0.0`.  This region describes the overall interleave configuration of the interleave set.  So we see there are a total of `4` interleave targets across 4 endpoint decoders.



```text
              "regions:decoder0.0":[
                  {
                      "region":"region0",
                      "resource":825975898112,
                      "size":549755813888,
                      "type":"ram",
                      "interleave_ways":4,
                      "interleave_granularity":256,
                      "decode_state":"commit",
                      "mappings":[
                          {
                              "position":3,
                              "memdev":"mem3",
                              "decoder":"decoder8.0"
                          },
                          {
                              "position":2,
                              "memdev":"mem1",
                              "decoder":"decoder6.0"
                          }
                          {
                              "position":1,
                              "memdev":"mem2",
                              "decoder":"decoder7.0"
                          },
                          {
                              "position":0,
                              "memdev":"mem0",
                              "decoder":"decoder5.0"
                          }
                      ]
                  }
              ]
          }
      ]
  }
]
```

---

# Single Device

_Peios Kernel / Hardware and drivers / Driver development / cxl: linux: example-configurations_

> This cxl-cli configuration dump shows the following host configuration:

<a id="rst-single-device"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This cxl-cli configuration dump shows the following host configuration:

- A single socket system with one CXL root

- CXL Root has Four (4) CXL Host Bridges

- One CXL Host Bridges has a single CXL Memory Expander Attached

- No interleave is present.

This output is generated by `cxl list -v` and describes the relationships between objects exposed in `/sys/bus/cxl/devices/`.



```text
[
  {
      "bus":"root0",
      "provider":"ACPI.CXL",
      "nr_dports":4,
      "dports":[
          {
              "dport":"pci0000:00",
              "alias":"ACPI0016:01",
              "id":0
          },
          {
              "dport":"pci0000:a8",
              "alias":"ACPI0016:02",
              "id":4
          },
          {
              "dport":"pci0000:2a",
              "alias":"ACPI0016:03",
              "id":1
          },
          {
              "dport":"pci0000:d2",
              "alias":"ACPI0016:00",
              "id":5
          }
      ],
```

This chunk shows the CXL "bus" (root0) has 4 downstream ports attached to CXL Host Bridges.  The `Root` can be considered the singular upstream port attached to the platform's memory controller - which routes memory requests to it.

The `ports:root0` section lays out how each of these downstream ports are configured.  If a port is not configured (id's 0, 1, and 4), they are omitted.



```text
"ports:root0":[
    {
        "port":"port1",
        "host":"pci0000:d2",
        "depth":1,
        "nr_dports":3,
        "dports":[
            {
                "dport":"0000:d2:01.1",
                "alias":"device:02",
                "id":0
            },
            {
                "dport":"0000:d2:01.3",
                "alias":"device:05",
                "id":2
            },
            {
                "dport":"0000:d2:07.1",
                "alias":"device:0d",
                "id":113
            }
        ],
```

This chunk shows the available downstream ports associated with the CXL Host Bridge `port1`.  In this case, `port1` has 3 available downstream ports: `dport1`, `dport2`, and `dport113`..



```text
"endpoints:port1":[
    {
        "endpoint":"endpoint5",
        "host":"mem0",
        "parent_dport":"0000:d2:01.1",
        "depth":2,
        "memdev":{
            "memdev":"mem0",
            "ram_size":137438953472,
            "serial":0,
            "numa_node":0,
            "host":"0000:d3:00.0"
        },
        "decoders:endpoint5":[
            {
                "decoder":"decoder5.0",
                "resource":825975898112,
                "size":137438953472,
                "interleave_ways":1,
                "region":"region0",
                "dpa_resource":0,
                "dpa_size":137438953472,
                "mode":"ram"
            }
        ]
    }
],
```

This chunk shows the endpoints attached to the host bridge `port1`.

`endpoint5` contains a single configured decoder `decoder5.0` which has the same interleave configuration as `region0` (shown later).

Next we have the decoders belonging to the host bridge:



```text
    "decoders:port1":[
        {
            "decoder":"decoder1.0",
            "resource":825975898112,
            "size":137438953472,
            "interleave_ways":1,
            "region":"region0",
            "nr_targets":1,
            "targets":[
                {
                    "target":"0000:d2:01.1",
                    "alias":"device:02",
                    "position":0,
                    "id":0
                }
            ]
        }
    ]
},
```

Host Bridge `port1` has a single decoder (`decoder1.0`), whose only target is `dport1` - which is attached to `endpoint5`.

The next chunk shows the three CXL host bridges without attached endpoints.



```text
    {
        "port":"port2",
        "host":"pci0000:00",
        "depth":1,
        "nr_dports":2,
        "dports":[
            {
                "dport":"0000:00:01.3",
                "alias":"device:55",
                "id":2
            },
            {
                "dport":"0000:00:07.1",
                "alias":"device:5d",
                "id":113
            }
        ]
    },
    {
        "port":"port3",
        "host":"pci0000:a8",
        "depth":1,
        "nr_dports":1,
        "dports":[
            {
                "dport":"0000:a8:01.1",
                "alias":"device:c3",
                "id":0
            }
        ]
    },
    {
        "port":"port4",
        "host":"pci0000:2a",
        "depth":1,
        "nr_dports":1,
        "dports":[
            {
                "dport":"0000:2a:01.1",
                "alias":"device:d0",
                "id":0
            }
        ]
    }
],
```

Next we have the `Root Decoders` belonging to `root0`.  This root decoder is a pass-through decoder because `interleave_ways` is set to `1`.

This information is generated by the CXL driver reading the ACPI CEDT CMFWS.



```text
"decoders:root0":[
    {
        "decoder":"decoder0.0",
        "resource":825975898112,
        "size":137438953472,
        "interleave_ways":1,
        "max_available_extent":0,
        "volatile_capable":true,
        "nr_targets":1,
        "targets":[
            {
                "target":"pci0000:d2",
                "alias":"ACPI0016:00",
                "position":0,
                "id":5
            }
        ],
```

Finally we have the `Memory Region` associated with the `Root Decoder` `decoder0.0`.  This region describes the discrete region associated with the lone device.



```text
              "regions:decoder0.0":[
                  {
                      "region":"region0",
                      "resource":825975898112,
                      "size":137438953472,
                      "type":"ram",
                      "interleave_ways":1,
                      "decode_state":"commit",
                      "mappings":[
                          {
                              "position":0,
                              "memdev":"mem0",
                              "decoder":"decoder5.0"
                          }
                      ]
                  }
              ]
          }
      ]
  }
]
```

---

# ACPI Tables

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform_

> ACPI is the "Advanced Configuration and Power Interface", which is a standard that defines how platforms and OS manage power and configure computer hardware. For the purpose of this theory of operation, when referring to "ACPI" we will…

<a id="rst-acpi-tables"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

ACPI is the "Advanced Configuration and Power Interface", which is a standard that defines how platforms and OS manage power and configure computer hardware. For the purpose of this theory of operation, when referring to "ACPI" we will usually refer to "ACPI Tables" - which are the way a platform (BIOS/EFI) communicates static configuration information to the operation system.

The Following ACPI tables contain *static* configuration and performance data about CXL devices.

- [CEDT - CXL Early Discovery Table](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>)
- [SRAT - Static Resource Affinity Table](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>)
- [HMAT - Heterogeneous Memory Attribute Table](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>)
- [SLIT - System Locality Information Table](</kernel/hardware/driver-api/cxl-platform-acpi/slit.md>)
- [DSDT - Differentiated system Description Table](</kernel/hardware/driver-api/cxl-platform-acpi/dsdt.md>)

The SRAT table may also contain generic port/initiator content that is intended to describe the generic port, but not information about the rest of the path to the endpoint.

Linux uses these tables to configure kernel resources for statically configured (by BIOS/EFI) CXL devices, such as:

- NUMA nodes

- Memory Tiers

- NUMA Abstract Distances

- SystemRAM Memory Regions

- Weighted Interleave Node Weights

<a id="rst-acpi-debugging"></a>

## ACPI Debugging

The `acpidump -b` command dumps the ACPI tables into binary format.

The `iasl -d` command disassembles the files into human readable format.

Example `acpidump -b && iasl -d cedt.dat`



```text
[000h 0000   4]   Signature : "CEDT"    [CXL Early Discovery Table]
```

<a id="rst-common-issues"></a>

### Common Issues

Most failures described here result in a failure of the driver to surface memory as a DAX device and/or kmem.

- CEDT CFMWS targets list UIDs do not match CEDT CHBS UIDs.

- CEDT CFMWS targets list UIDs do not match DSDT CXL Host Bridge UIDs.

- CEDT CFMWS Restriction Bits are not correct.

- CEDT CFMWS Memory regions are poorly aligned.

- CEDT CFMWS Memory regions spans a platform memory hole.

- CEDT CHBS UIDs do not match DSDT CXL Host Bridge UIDs.

- CEDT CHBS Specification version is incorrect.

- SRAT is missing regions described in CEDT CFMWS.

  - Result: failure to create a NUMA node for the region, or region is placed in wrong node.

- HMAT is missing data for regions described in CEDT CFMWS.

  - Result: NUMA node being placed in the wrong memory tier.

- SLIT has bad data.

  - Result: Lots of performance mechanisms in the kernel will be very unhappy.

All of these issues will appear to users as if the driver is failing to support CXL - when in reality they are all the failure of a platform to configure the ACPI tables correctly.

---

# BIOS/EFI Configuration

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform_

> BIOS and EFI are largely responsible for configuring static information about devices (or potential future devices) such that Linux can build the appropriate logical representations of these devices.

<a id="rst-bios-efi-configuration"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

BIOS and EFI are largely responsible for configuring static information about devices (or potential future devices) such that Linux can build the appropriate logical representations of these devices.

At a high level, this is what occurs during this phase of configuration.

- The bootloader starts the BIOS/EFI.

- BIOS/EFI do early device probe to determine static configuration

- BIOS/EFI creates ACPI Tables that describe static config for the OS

- BIOS/EFI create the system memory map (EFI Memory Map, E820, etc)

- BIOS/EFI calls `start_kernel` and begins the Linux Early Boot process.

Much of what this section is concerned with is ACPI Table production and static memory map configuration. More detail on these tables can be found at [ACPI Tables](</kernel/hardware/driver-api/cxl-platform/acpi.md>).

> [!NOTE]
>
> Platform Vendors should read carefully, as this sections has recommendations on physical memory region size and alignment, memory holes, HDM interleave, and what linux expects of HDM decoders trying to work with these features.

<a id="rst-linux-expectations-of-bios-efi-software"></a>

## Linux Expectations of BIOS/EFI Software

Linux expects BIOS/EFI software to construct sufficient ACPI tables (such as CEDT, SRAT, HMAT, etc) and platform-specific configurations (such as HPA spaces and host-bridge interleave configurations) to allow the Linux driver to subsequently configure the devices in the CXL fabric at runtime.

Programming of HDM decoders and switch ports is not required, and may be deferred to the CXL driver based on admin policy (e.g. udev rules).

Some platforms may require pre-programming HDM decoders and locking them due to quirks (see: Zen5 address translation), but this is not the normal, "expected" configuration path.  This should be avoided if possible.

Some platforms may wish to pre-configure these resources to bring memory up without requiring CXL driver support.  These platform vendors should test their configurations with the existing CXL driver and provide driver support for their auto-configurations if features like RAS are required.

Platforms requiring boot-time programming and/or locking of CXL fabric components may prevent features, such as device hot-plug, from working.

<a id="rst-uefi-settings"></a>

## UEFI Settings

If your platform supports it, the `uefisettings` command can be used to read/write EFI settings. Changes will be reflected on the next reboot. Kexec is not a sufficient reboot.

One notable configuration here is the EFI_MEMORY_SP (Specific Purpose) bit. When this is enabled, this bit tells linux to defer management of a memory region to a driver (in this case, the CXL driver). Otherwise, the memory is treated as "normal memory", and is exposed to the page allocator during `__init`.

<a id="rst-uefisettings-examples"></a>

### uefisettings examples

`uefisettings identify`



```text
uefisettings identify

bios_vendor: xxx
bios_version: xxx
bios_release: xxx
bios_date: xxx
product_name: xxx
product_family: xxx
product_version: xxx
```

On some AMD platforms, the `EFI_MEMORY_SP` bit is set via the `CXL Memory Attribute` field.  This may be called something else on your platform.

`uefisettings get "CXL Memory Attribute"`



```text
selector: xxx
...
question: Question {
    name: "CXL Memory Attribute",
    answer: "Enabled",
    ...
}
```

<a id="rst-physical-memory-map"></a>

## Physical Memory Map

<a id="rst-physical-address-region-alignment"></a>

### Physical Address Region Alignment

As of Linux v6.14, the hotplug memory system requires memory regions to be uniform in size and alignment.  While the CXL specification allows for memory regions as small as 256MB, the supported memory block size and alignment for hotplugged memory is architecture-defined.

A Linux memory blocks may be as small as 128MB and increase in powers of two.

- On ARM, the default block size and alignment is either 128MB or 256MB.

- On x86, the default block size is 256MB, and increases to 2GB as the capacity of the system increases up to 64GB.

For best support across versions, platform vendors should place CXL memory at a 2GB aligned base address, and regions should be 2GB aligned.  This also helps prevent the creating thousands of memory devices (one per block).

<a id="rst-memory-holes"></a>

### Memory Holes

Holes in the memory map are tricky.  Consider a 4GB device located at base address 0x100000000, but with the following memory map



```text
---------------------
|    0x100000000    |
|        CXL        |
|    0x1BFFFFFFF    |
---------------------
|    0x1C0000000    |
|    MEMORY HOLE    |
|    0x1FFFFFFFF    |
---------------------
|    0x200000000    |
|     CXL CONT.     |
|    0x23FFFFFFF    |
---------------------
```

There are two issues to consider:

- decoder programming, and

- memory block alignment.

If your architecture requires 2GB uniform size and aligned memory blocks, the only capacity Linux is capable of mapping (as of v6.14) would be the capacity from `0x100000000-0x180000000`.  The remaining capacity will be stranded, as they are not of 2GB aligned length.

Assuming your architecture and memory configuration allows 1GB memory blocks, this memory map is supported and this should be presented as multiple CFMWS in the CEDT that describe each side of the memory hole separately - along with matching decoders.

Multiple decoders can (and should) be used to manage such a memory hole (see below), but each chunk of a memory hole should be aligned to a reasonable block size (larger alignment is always better).  If you intend to have memory holes in the memory map, expect to use one decoder per contiguous chunk of host physical memory.

As of v6.14, Linux does provide support for memory hotplug of multiple physical memory regions separated by a memory hole described by a single HDM decoder.

<a id="rst-decoder-programming"></a>

## Decoder Programming

If BIOS/EFI intends to program the decoders to be statically configured, there are a few things to consider to avoid major pitfalls that will prevent Linux compatibility.  Some of these recommendations are not required "per the specification", but Linux makes no guarantees of support otherwise.

<a id="rst-translation-point"></a>

### Translation Point

Per the specification, the only decoders which **TRANSLATE** Host Physical Address (HPA) to Device Physical Address (DPA) are the **Endpoint Decoders**. All other decoders in the fabric are intended to route accesses without translating the addresses.

This is heavily implied by the specification, see:



```text
CXL Specification 3.1
8.2.4.20: CXL HDM Decoder Capability Structure
- Implementation Note: CXL Host Bridge and Upstream Switch Port Decoder Flow
- Implementation Note: Device Decoder Logic
```

Given this, Linux makes a strong assumption that decoders between CPU and endpoint will all be programmed with addresses ranges that are subsets of their parent decoder.

Due to some ambiguity in how Architecture, ACPI, PCI, and CXL specifications "hand off" responsibility between domains, some early adopting platforms attempted to do translation at the originating memory controller or host bridge.  This configuration requires a platform specific extension to the driver and is not officially endorsed - despite being supported.

It is *highly recommended* **NOT** to do this; otherwise, you are on your own to implement driver support for your platform.

<a id="rst-interleave-and-configuration-flexibility"></a>

### Interleave and Configuration Flexibility

If providing cross-host-bridge interleave, a CFMWS entry in the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>) must be presented with target host-bridges for the interleaved device sets (there may be multiple behind each host bridge).

If providing intra-host-bridge interleaving, only 1 CFMWS entry in the CEDT is required for that host bridge - if it covers the entire capacity of the devices behind the host bridge.

If intending to provide users flexibility in programming decoders beyond the root, you may want to provide multiple CFMWS entries in the CEDT intended for different purposes.  For example, you may want to consider adding:

1. A CFMWS entry to cover all interleavable host bridges.

2. A CFMWS entry to cover all devices on a single host bridge.

3. A CFMWS entry to cover each device.

A platform may choose to add all of these, or change the mode based on a BIOS setting.  For each CFMWS entry, Linux expects descriptions of the described memory regions in the [SRAT](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>) to determine the number of NUMA nodes it should reserve during early boot / init.

As of v6.14, Linux will create a NUMA node for each CEDT CFMWS entry, even if a matching SRAT entry does not exist; however, this is not guaranteed in the future and such a configuration should be avoided.

<a id="rst-memory-holes-1"></a>

### Memory Holes

If your platform includes memory holes interspersed between your CXL memory, it is recommended to utilize multiple decoders to cover these regions of memory, rather than try to program the decoders to accept the entire range and expect Linux to manage the overlap.

For example, consider the Memory Hole described above



```text
---------------------
|    0x100000000    |
|        CXL        |
|    0x1BFFFFFFF    |
---------------------
|    0x1C0000000    |
|    MEMORY HOLE    |
|    0x1FFFFFFFF    |
---------------------
|    0x200000000    |
|     CXL CONT.     |
|    0x23FFFFFFF    |
---------------------
```

Assuming this is provided by a single device attached directly to a host bridge, Linux would expect the following decoder programming



```text
-----------------------   -----------------------
| root-decoder-0      |   | root-decoder-1      |
|   base: 0x100000000 |   |   base: 0x200000000 |
|   size:  0xC0000000 |   |   size:  0x40000000 |
-----------------------   -----------------------
           |                         |
-----------------------   -----------------------
| HB-decoder-0        |   | HB-decoder-1        |
|   base: 0x100000000 |   |   base: 0x200000000 |
|   size:  0xC0000000 |   |   size:  0x40000000 |
-----------------------   -----------------------
           |                         |
-----------------------   -----------------------
| ep-decoder-0        |   | ep-decoder-1        |
|   base: 0x100000000 |   |   base: 0x200000000 |
|   size:  0xC0000000 |   |   size:  0x40000000 |
-----------------------   -----------------------
```

With a CEDT configuration with two CFMWS describing the above root decoders.

Linux makes no guarantee of support for strange memory hole situations.

<a id="rst-multi-media-devices"></a>

### Multi-Media Devices

The CFMWS field of the CEDT has special restriction bits which describe whether the described memory region allows volatile or persistent memory (or both). If the platform intends to support either:

1. A device with multiple medias, or

2. Using a persistent memory device as normal memory

A platform may wish to create multiple CEDT CFMWS entries to describe the same memory, with the intent of allowing the end user flexibility in how that memory is configured. Linux does not presently have strong requirements in this area.

---

# Coherent Device Attribute Table (CDAT)

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform_

> The CDAT provides functional and performance attributes of devices such as CXL accelerators, switches, or endpoints. The table formatting is similar to ACPI tables. CDAT data may be parsed by BIOS at boot or may be enumerated at runtime…

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-coherent-device-attribute-table-cdat"></a>

## Coherent Device Attribute Table (CDAT)

The CDAT provides functional and performance attributes of devices such as CXL accelerators, switches, or endpoints.  The table formatting is similar to ACPI tables. CDAT data may be parsed by BIOS at boot or may be enumerated at runtime (after device hotplug, for example).

Terminology: DPA - Device Physical Address, used by the CXL device to denote the address it supports for that device.

DSMADHandle - A device unique handle that is associated with a DPA range defined by the DSMAS table.

<a id="rst-device-scoped-memory-affinity-structure-dsmas"></a>

## Device Scoped Memory Affinity Structure (DSMAS)

The DSMAS contains information such as DSMADHandle, the DPA Base, and DPA Length.

This table is used by Linux in conjunction with the Device Scoped Latency and Bandwidth Information Structure (DSLBIS) to determine the performance attributes of the CXL device itself.

Example



```text
Structure Type : 00 [DSMAS]
      Reserved : 00
        Length : 0018              <- 24d, size of structure
   DSMADHandle : 01
         Flags : 00
      Reserved : 0000
      DPA Base : 0000000040000000  <- 1GiB base
    DPA Length : 0000000080000000  <- 2GiB size
```

<a id="rst-device-scoped-latency-and-bandwidth-information-structure-dslbis"></a>

## Device Scoped Latency and Bandwidth Information Structure (DSLBIS)

This table is used by Linux in conjunction with DSMAS to determine the performance attributes of a CXL device.  The DSLBIS contains latency and bandwidth information based on DSMADHandle matching.

Example



```text
  Structure Type : 01 [DSLBIS]
        Reserved : 00
          Length : 18                     <- 24d, size of structure
          Handle : 0001                   <- DSMAS handle
           Flags : 00                     <- Matches flag field for HMAT SLLBIS
       Data Type : 00                     <- Latency
Entry Basee Unit : 0000000000001000       <- Entry Base Unit field in HMAT SSLBIS
           Entry : 010000000000           <- First byte used here, CXL LTC
        Reserved : 0000

  Structure Type : 01 [DSLBIS]
        Reserved : 00
          Length : 18                     <- 24d, size of structure
          Handle : 0001                   <- DSMAS handle
           Flags : 00                     <- Matches flag field for HMAT SLLBIS
       Data Type : 03                     <- Bandwidth
Entry Basee Unit : 0000000000001000       <- Entry Base Unit field in HMAT SSLBIS
           Entry : 020000000000           <- First byte used here, CXL BW
        Reserved : 0000
```

<a id="rst-switch-scoped-latency-and-bandwidth-information-structure-sslbis"></a>

## Switch Scoped Latency and Bandwidth Information Structure (SSLBIS)

The SSLBIS contains information about the latency and bandwidth of a switch.

The table is used by Linux to compute the performance coordinates of a CXL path from the device to the root port where a switch is part of the path.

Example



```text
 Structure Type : 05 [SSLBIS]
       Reserved : 00
         Length : 20                           <- 32d, length of record, including SSLB entries
      Data Type : 00                           <- Latency
       Reserved : 000000
Entry Base Unit : 00000000000000001000         <- Matches Entry Base Unit in HMAT SSLBIS

                                               <- SSLB Entry 0
      Port X ID : 0100                         <- First port, 0100h represents an upstream port
      Port Y ID : 0000                         <- Second port, downstream port 0
        Latency : 0100                         <- Port latency
       Reserved : 0000
                                               <- SSLB Entry 1
      Port X ID : 0100
      Port Y ID : 0001
        Latency : 0100
       Reserved : 0000


 Structure Type : 05 [SSLBIS]
       Reserved : 00
         Length : 18                           <- 24d, length of record, including SSLB entry
      Data Type : 03                           <- Bandwidth
       Reserved : 000000
Entry Base Unit : 00000000000000001000         <- Matches Entry Base Unit in HMAT SSLBIS

                                               <- SSLB Entry 0
      Port X ID : 0100                         <- First port, 0100h represents an upstream port
      Port Y ID : FFFF                         <- Second port, FFFFh indicates any port
      Bandwidth : 1200                         <- Port bandwidth
       Reserved : 0000
```

The CXL driver uses a combination of CDAT, HMAT, SRAT, and other data to generate "whole path performance" data for a CXL device.

---

# CXL Device Hotplug

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform_

> Device hotplug refers to physical hotplug of a device (addition or removal of a physical device from the machine).

<a id="rst-cxl-device-hotplug"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Device hotplug refers to *physical* hotplug of a device (addition or removal of a physical device from the machine).

BIOS/EFI software is expected to configure sufficient resources **at boot time** to allow hotplugged devices to be configured by software (such as proximity domains, HPA regions, and host-bridge configurations).

BIOS/EFI is not expected (**nor suggested**) to configure hotplugged devices at hotplug time (i.e. HDM decoders should be left unprogrammed).

This document covers some examples of those resources, but should not be considered exhaustive.

<a id="rst-hot-remove"></a>

## Hot-Remove

Hot removal of a device typically requires careful removal of software constructs (memory regions, associated drivers) which manage these devices.

Hard-removing a CXL.mem device without carefully tearing down driver stacks is likely to cause the system to machine-check (or at least SIGBUS if memory access is limited to user space).

<a id="rst-memory-device-hot-add"></a>

## Memory Device Hot-Add

A device present at boot may be associated with a CXL Fixed Memory Window reported in [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>).  That CFMWS may match the size of the device, but the construction of the CEDT CFMWS is platform-defined.

Hot-adding a memory device requires this pre-defined, **static** CFMWS to have sufficient HPA space to describe that device.

There are a few common scenarios to consider.

<a id="rst-single-endpoint-memory-device-present-at-boot"></a>

### Single-Endpoint Memory Device Present at Boot

A device present at boot likely had its capacity reported in the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>).  If a device is removed and a new device hotplugged, the capacity of the new device will be limited to the original CFMWS capacity.

Adding capacity larger than the original device will cause memory region creation to fail if the region size is greater than the CFMWS size.

The CFMWS is **static** and cannot be adjusted.  Platforms which may expect different sized devices to be hotplugged must allocate sufficient CFMWS space **at boot time** to cover all future expected devices.

<a id="rst-multi-endpoint-memory-device-present-at-boot"></a>

### Multi-Endpoint Memory Device Present at Boot

Non-switch-based Multi-Endpoint devices are outside the scope of what the CXL specification describes, but they are technically possible. We describe them here for instructive reasons only - this does not imply Linux support.

A hot-plug capable CXL memory device, such as one which presents multiple expanders as a single large-capacity device, should report the **maximum possible capacity** for the device at boot.



```text
             HB0
             RP0
              |
[Multi-Endpoint Memory Device]
         _____|_____
        |          |
   [Endpoint0]   [Empty]
```

Limiting the size to the capacity preset at boot will limit hot-add support to replacing capacity that was present at boot.

<a id="rst-no-cxl-device-present-at-boot"></a>

### No CXL Device Present at Boot

When no CXL memory device is present on boot, some platforms omit the CFMWS in the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>).  When this occurs, hot-add is not possible.

This describes the base case for any given device not being present at boot. If a future possible device is not described in the CEDT at boot, hot-add of that device is either limited or not possible.

For a platform to support hot-add of a full memory device, it must allocate a CEDT CFMWS region with sufficient memory capacity to cover all future potentially added capacity (along with any relevant CEDT CHBS entry).

To support memory hotplug directly on the host bridge/root port, or on a switch downstream of the host bridge, a platform must construct a CEDT CFMWS at boot with sufficient resources to support the max possible (or expected) hotplug memory capacity.



```text
    HB0                 HB1
 RP0    RP1             RP2
  |      |               |
Empty  Empty            USP
                 ________|________
                 |    |    |     |
                DSP  DSP  DSP   DSP
                 |    |    |    |
                    All  Empty
```

For example, a BIOS/EFI may expose an option to configure a CEDT CFMWS with a pre-configured amount of memory capacity (per host bridge, or host bridge interleave set), even if no device is attached to Root Ports or Downstream Ports at boot (as depicted in the figure above).

<a id="rst-interleave-sets"></a>

## Interleave Sets

<a id="rst-host-bridge-interleave"></a>

### Host Bridge Interleave

Host-bridge interleaved memory regions are defined **statically** in the [CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>).  To apply cross-host-bridge interleave, a CFMWS entry describing that interleave must have been provided **at boot**.  Hotplugged devices cannot add host-bridge interleave capabilities at hotplug time.

See the [Flexible CEDT Configuration](</kernel/hardware/driver-api/cxl-platform-example-configurations/flexible.md>) example to see how a platform can provide this kind of flexibility regarding hotplugged memory devices.  BIOS/EFI software should consider options to present flexible CEDT configurations with hotplug support.

<a id="rst-hdm-interleave"></a>

### HDM Interleave

Decoder-applied interleave can flexibly handle hotplugged devices, as decoders can be re-programmed after hotplug.

To add or remove a device to/from an existing HDM-applied interleaved region, that region must be torn down an re-created.

---

# Example Platform Configurations

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform_

> Reference for Example Platform Configurations.

<a id="rst-example-platform-configurations"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Contents**

- [One Device per Host Bridge](</kernel/hardware/driver-api/cxl-platform-example-configurations/one-dev-per-hb.md>)
- [Multiple Devices per Host Bridge](</kernel/hardware/driver-api/cxl-platform-example-configurations/multi-dev-per-hb.md>)
- [Cross-Host-Bridge Interleave](</kernel/hardware/driver-api/cxl-platform-example-configurations/hb-interleave.md>)
- [Flexible Presentation](</kernel/hardware/driver-api/cxl-platform-example-configurations/flexible.md>)

---

# CEDT - CXL Early Discovery Table

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform: acpi_

> The CXL Early Discovery Table is generated by BIOS to describe the CXL memory regions configured at boot by the BIOS.

<a id="rst-cedt-cxl-early-discovery-table"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The CXL Early Discovery Table is generated by BIOS to describe the CXL memory regions configured at boot by the BIOS.

<a id="rst-chbs"></a>

## CHBS

The CXL Host Bridge Structure describes CXL host bridges.  Other than describing device register information, it reports the specific host bridge UID for this host bridge.  These host bridge ID's will be referenced in other tables.

Example



```text
         Subtable Type : 00 [CXL Host Bridge Structure]
              Reserved : 00
                Length : 0020
Associated host bridge : 00000007    <- Host bridge _UID
 Specification version : 00000001
              Reserved : 00000000
         Register base : 0000010370400000
       Register length : 0000000000010000
```

<a id="rst-cfmws"></a>

## CFMWS

The CXL Fixed Memory Window structure describes a memory region associated with one or more CXL host bridges (as described by the CHBS).  It additionally describes any inter-host-bridge interleave configuration that may have been programmed by BIOS.

Example



```text
           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 000000C050000000   <- Memory Region
             Window size : 0000003CA0000000
Interleave Members (2^n) : 01                 <- Interleave configuration
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000007           <- Host Bridge _UID
             Next Target : 00000006           <- Host Bridge _UID
```

The restriction field dictates what this SPA range may be used for (memory type, voltile vs persistent, etc). One or more bits may be set.



```text
Bit[0]: CXL Type 2 Memory
Bit[1]: CXL Type 3 Memory
Bit[2]: Volatile Memory
Bit[3]: Persistent Memory
Bit[4]: Fixed Config (HPA cannot be re-used)
```

INTRA-host-bridge interleave (multiple devices on one host bridge) is NOT reported in this structure, and is solely defined via CXL device decoder programming (host bridge and endpoint decoders).

---

# DSDT - Differentiated system Description Table

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform: acpi_

> This table describes what peripherals a machine has.

<a id="rst-dsdt-differentiated-system-description-table"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This table describes what peripherals a machine has.

This table's UIDs for CXL devices - specifically host bridges, must be consistent with the contents of the CEDT, otherwise the CXL driver will fail to probe correctly.

Example Compute Express Link Host Bridge



```text
Scope (_SB)
{
    Device (S0D0)
    {
        Name (_HID, "ACPI0016" /* Compute Express Link Host Bridge */)  // _HID: Hardware ID
        Name (_CID, Package (0x02)  // _CID: Compatible ID
        {
            EisaId ("PNP0A08") /* PCI Express Bus */,
            EisaId ("PNP0A03") /* PCI Bus */
        })
        ...
        Name (_UID, 0x05)  // _UID: Unique ID
        ...
  }
```

---

# HMAT - Heterogeneous Memory Attribute Table

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform: acpi_

> The Heterogeneous Memory Attributes Table contains information such as cache attributes and bandwidth and latency details for memory proximity domains. For the purpose of this document, we will only discuss the SSLIB entry.

<a id="rst-hmat-heterogeneous-memory-attribute-table"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The Heterogeneous Memory Attributes Table contains information such as cache attributes and bandwidth and latency details for memory proximity domains. For the purpose of this document, we will only discuss the SSLIB entry.

<a id="rst-sllbi"></a>

## SLLBI

The System Locality Latency and Bandwidth Information records latency and bandwidth information for proximity domains.

This table is used by Linux to configure interleave weights and memory tiers.

Example (Heavily truncated for brevity)



```text
              Structure Type : 0001 [SLLBI]
                   Data Type : 00         <- Latency
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
                       Entry : 0080       <- DRAM LTC
                       Entry : 0100       <- CXL LTC

              Structure Type : 0001 [SLLBI]
                   Data Type : 03         <- Bandwidth
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
                       Entry : 1200       <- DRAM BW
                       Entry : 0200       <- CXL BW
```

---

# SLIT - System Locality Information Table

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform: acpi_

> The system locality information table provides "abstract distances" between accessor and memory nodes. Node without initiators (cpus) are infinitely (FF) distance away from all other nodes.

<a id="rst-slit-system-locality-information-table"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The system locality information table provides "abstract distances" between accessor and memory nodes.  Node without initiators (cpus) are infinitely (FF) distance away from all other nodes.

The abstract distance described in this table does not describe any real latency of bandwidth information.

Example



```text
   Signature : "SLIT"    [System Locality Information Table]
  Localities : 0000000000000004
Locality   0 : 10 20 20 30
Locality   1 : 20 10 30 20
Locality   2 : FF FF 0A FF
Locality   3 : FF FF FF 0A
```

---

# SRAT - Static Resource Affinity Table

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform: acpi_

> The System/Static Resource Affinity Table describes resource (CPU, Memory) affinity to "Proximity Domains". This table is technically optional, but for performance information (see "HMAT") to be enumerated by linux it must be present.

<a id="rst-srat-static-resource-affinity-table"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The System/Static Resource Affinity Table describes resource (CPU, Memory) affinity to "Proximity Domains". This table is technically optional, but for performance information (see "HMAT") to be enumerated by linux it must be present.

There is a careful dance between the CEDT and SRAT tables and how NUMA nodes are created.  If things don't look quite the way you expect - check the SRAT Memory Affinity entries and CEDT CFMWS to determine what your platform actually supports in terms of flexible topologies.

The SRAT may statically assign portions of a CFMWS SPA range to a specific proximity domains.  See linux numa creation for more information about how this presents in the NUMA topology.

<a id="rst-proximity-domain"></a>

## Proximity Domain

A proximity domain is ROUGHLY equivalent to "NUMA Node" - though a 1-to-1 mapping is not guaranteed.  There are scenarios where "Proximity Domain 4" may map to "NUMA Node 3", for example.  (See "NUMA Node Creation")

<a id="rst-memory-affinity"></a>

## Memory Affinity

Generally speaking, if a host does any amount of CXL fabric (decoder) programming in BIOS - an SRAT entry for that memory needs to be present.

Example



```text
        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000001          <- NUMA Node 1
            Reserved1 : 0000
         Base Address : 000000C050000000  <- Physical Memory Region
       Address Length : 0000003CA0000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
             Enabled : 1
       Hot Pluggable : 1
        Non-Volatile : 0
```

<a id="rst-generic-port-affinity"></a>

## Generic Port Affinity

The Generic Port Affinity subtable provides an association between a proximity domain and a device handle representing a Generic Port such as a CXL host bridge. With the association, latency and bandwidth numbers can be retrieved from the SRAT for the path between CPU(s) (initiator) and the Generic Port. This is used to construct performance coordinates for hotplugged CXL DEVICES, which cannot be enumerated at boot by platform firmware.

Example



```text
     Subtable Type : 06 [Generic Port Affinity]
            Length : 20               <- 32d, length of table
          Reserved : 00
Device Handle Type : 00               <- 0 - ACPI, 1 - PCI
  Proximity Domain : 00000001
     Device Handle : ACPI0016:01
             Flags : 00000001         <- Bit 0 (Enabled)
          Reserved : 00000000
```

The Proximity Domain is matched up to the [HMAT](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>) SSLBI Target Proximity Domain List for the related latency or bandwidth numbers. Those performance numbers are tied to a CXL host bridge via the Device Handle. The driver uses the association to retrieve the Generic Port performance numbers for the whole CXL path access coordinates calculation.

---

# Flexible Presentation

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform: example-configurations_

> This system has a single socket with two CXL host bridges. Each host bridge has two CXL memory expanders with a 4GB of memory (32GB total).

<a id="rst-flexible-presentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This system has a single socket with two CXL host bridges. Each host bridge has two CXL memory expanders with a 4GB of memory (32GB total).

On this system, the platform designer wanted to provide the user flexibility to configure the memory devices in various interleave or NUMA node configurations.  So they provided every combination.

Things to note:

- Cross-Bridge interleave is described in one CFMWS that covers all capacity.

- One CFMWS is also described per-host bridge.

- One CFMWS is also described per-device.

- This SRAT describes one node for each of the above CFMWS.

- The HMAT describes performance for each node in the SRAT.

[CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>):



```text
           Subtable Type : 00 [CXL Host Bridge Structure]
                Reserved : 00
                  Length : 0020
  Associated host bridge : 00000007
   Specification version : 00000001
                Reserved : 00000000
           Register base : 0000010370400000
         Register length : 0000000000010000

           Subtable Type : 00 [CXL Host Bridge Structure]
                Reserved : 00
                  Length : 0020
  Associated host bridge : 00000006
   Specification version : 00000001
                Reserved : 00000000
           Register base : 0000010380800000
         Register length : 0000000000010000

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000001000000000
             Window size : 0000000400000000
Interleave Members (2^n) : 01
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000007
           Second Target : 00000006

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000002000000000
             Window size : 0000000200000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000007

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000002200000000
             Window size : 0000000200000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000006

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000003000000000
             Window size : 0000000100000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000007

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000003100000000
             Window size : 0000000100000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000007

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000003200000000
             Window size : 0000000100000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000006

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000003300000000
             Window size : 0000000100000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000006
```

[SRAT](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>):



```text
        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000001
            Reserved1 : 0000
         Base Address : 0000001000000000
       Address Length : 0000000400000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0

        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000002
            Reserved1 : 0000
         Base Address : 0000002000000000
       Address Length : 0000000200000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0

        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000003
            Reserved1 : 0000
         Base Address : 0000002200000000
       Address Length : 0000000200000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0

        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000004
            Reserved1 : 0000
         Base Address : 0000003000000000
       Address Length : 0000000100000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0

        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000005
            Reserved1 : 0000
         Base Address : 0000003100000000
       Address Length : 0000000100000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0

        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000006
            Reserved1 : 0000
         Base Address : 0000003200000000
       Address Length : 0000000100000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0

        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000007
            Reserved1 : 0000
         Base Address : 0000003300000000
       Address Length : 0000000100000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0
```

[HMAT](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>):



```text
              Structure Type : 0001 [SLLBI]
                   Data Type : 00   [Latency]
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
Target Proximity Domain List : 00000002
Target Proximity Domain List : 00000003
Target Proximity Domain List : 00000004
Target Proximity Domain List : 00000005
Target Proximity Domain List : 00000006
Target Proximity Domain List : 00000007
                       Entry : 0080
                       Entry : 0100
                       Entry : 0100
                       Entry : 0100
                       Entry : 0100
                       Entry : 0100
                       Entry : 0100
                       Entry : 0100

              Structure Type : 0001 [SLLBI]
                   Data Type : 03   [Bandwidth]
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
Target Proximity Domain List : 00000002
Target Proximity Domain List : 00000003
Target Proximity Domain List : 00000004
Target Proximity Domain List : 00000005
Target Proximity Domain List : 00000006
Target Proximity Domain List : 00000007
                       Entry : 1200
                       Entry : 0400
                       Entry : 0200
                       Entry : 0200
                       Entry : 0100
                       Entry : 0100
                       Entry : 0100
                       Entry : 0100
```

[SLIT](</kernel/hardware/driver-api/cxl-platform-acpi/slit.md>):



```text
   Signature : "SLIT"    [System Locality Information Table]
  Localities : 0000000000000003
Locality   0 : 10 20 20 20 20 20 20 20
Locality   1 : FF 0A FF FF FF FF FF FF
Locality   2 : FF FF 0A FF FF FF FF FF
Locality   3 : FF FF FF 0A FF FF FF FF
Locality   4 : FF FF FF FF 0A FF FF FF
Locality   5 : FF FF FF FF FF 0A FF FF
Locality   6 : FF FF FF FF FF FF 0A FF
Locality   7 : FF FF FF FF FF FF FF 0A
```

[DSDT](</kernel/hardware/driver-api/cxl-platform-acpi/dsdt.md>):



```text
Scope (_SB)
{
  Device (S0D0)
  {
      Name (_HID, "ACPI0016" /* Compute Express Link Host Bridge */)  // _HID: Hardware ID
      ...
      Name (_UID, 0x07)  // _UID: Unique ID
  }
  ...
  Device (S0D5)
  {
      Name (_HID, "ACPI0016" /* Compute Express Link Host Bridge */)  // _HID: Hardware ID
      ...
      Name (_UID, 0x06)  // _UID: Unique ID
  }
}
```

---

# Cross-Host-Bridge Interleave

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform: example-configurations_

> This system has a single socket with two CXL host bridges. Each host bridge has a single CXL memory expander with a 4GB of memory.

<a id="rst-cross-host-bridge-interleave"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This system has a single socket with two CXL host bridges. Each host bridge has a single CXL memory expander with a 4GB of memory.

Things to note:

- Cross-Bridge interleave is described.

- The expanders are described by a single CFMWS.

- This SRAT describes one node for both host bridges.

- The HMAT describes a single node's performance.

[CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>):



```text
           Subtable Type : 00 [CXL Host Bridge Structure]
                Reserved : 00
                  Length : 0020
  Associated host bridge : 00000007
   Specification version : 00000001
                Reserved : 00000000
           Register base : 0000010370400000
         Register length : 0000000000010000

           Subtable Type : 00 [CXL Host Bridge Structure]
                Reserved : 00
                  Length : 0020
  Associated host bridge : 00000006
   Specification version : 00000001
                Reserved : 00000000
           Register base : 0000010380800000
         Register length : 0000000000010000

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000001000000000
             Window size : 0000000200000000
Interleave Members (2^n) : 01
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000007
           Second Target : 00000006
```

[SRAT](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>):



```text
        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000001
            Reserved1 : 0000
         Base Address : 0000001000000000
       Address Length : 0000000200000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0
```

[HMAT](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>):



```text
              Structure Type : 0001 [SLLBI]
                   Data Type : 00   [Latency]
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
Target Proximity Domain List : 00000002
                       Entry : 0080
                       Entry : 0100

              Structure Type : 0001 [SLLBI]
                   Data Type : 03   [Bandwidth]
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
Target Proximity Domain List : 00000002
                       Entry : 1200
                       Entry : 0400
```

[SLIT](</kernel/hardware/driver-api/cxl-platform-acpi/slit.md>):



```text
   Signature : "SLIT"    [System Locality Information Table]
  Localities : 0000000000000003
Locality   0 : 10 20
Locality   1 : FF 0A
```

[DSDT](</kernel/hardware/driver-api/cxl-platform-acpi/dsdt.md>):



```text
Scope (_SB)
{
  Device (S0D0)
  {
      Name (_HID, "ACPI0016" /* Compute Express Link Host Bridge */)  // _HID: Hardware ID
      ...
      Name (_UID, 0x07)  // _UID: Unique ID
  }
  ...
  Device (S0D5)
  {
      Name (_HID, "ACPI0016" /* Compute Express Link Host Bridge */)  // _HID: Hardware ID
      ...
      Name (_UID, 0x06)  // _UID: Unique ID
  }
}
```

---

# Multiple Devices per Host Bridge

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform: example-configurations_

> In this example system we will have a single socket and one CXL host bridge. There are two CXL memory expanders with 4GB attached to the host bridge.

<a id="rst-multiple-devices-per-host-bridge"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

In this example system we will have a single socket and one CXL host bridge. There are two CXL memory expanders with 4GB attached to the host bridge.

Things to note:

- Intra-Bridge interleave is not described here.

- The expanders are described by a single CEDT/CFMWS.

- This CEDT/SRAT describes one node for both devices.

- There is only one proximity domain the HMAT for both devices.

[CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>):



```text
           Subtable Type : 00 [CXL Host Bridge Structure]
                Reserved : 00
                  Length : 0020
  Associated host bridge : 00000007
   Specification version : 00000001
                Reserved : 00000000
           Register base : 0000010370400000
         Register length : 0000000000010000

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000001000000000
             Window size : 0000000200000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000007
```

[SRAT](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>):



```text
        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000001
            Reserved1 : 0000
         Base Address : 0000001000000000
       Address Length : 0000000200000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0
```

[HMAT](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>):



```text
              Structure Type : 0001 [SLLBI]
                   Data Type : 00   [Latency]
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
                       Entry : 0080
                       Entry : 0100

              Structure Type : 0001 [SLLBI]
                   Data Type : 03   [Bandwidth]
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
                       Entry : 1200
                       Entry : 0200
```

[SLIT](</kernel/hardware/driver-api/cxl-platform-acpi/slit.md>):



```text
   Signature : "SLIT"    [System Locality Information Table]
  Localities : 0000000000000003
Locality   0 : 10 20
Locality   1 : FF 0A
```

[DSDT](</kernel/hardware/driver-api/cxl-platform-acpi/dsdt.md>):



```text
Scope (_SB)
{
  Device (S0D0)
  {
      Name (_HID, "ACPI0016" /* Compute Express Link Host Bridge */)  // _HID: Hardware ID
      ...
      Name (_UID, 0x07)  // _UID: Unique ID
  }
  ...
}
```

---

# One Device per Host Bridge

_Peios Kernel / Hardware and drivers / Driver development / cxl: platform: example-configurations_

> This system has a single socket with two CXL host bridges. Each host bridge has a single CXL memory expander with a 4GB of memory.

<a id="rst-one-device-per-host-bridge"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This system has a single socket with two CXL host bridges. Each host bridge has a single CXL memory expander with a 4GB of memory.

Things to note:

- Cross-Bridge interleave is not being used.

- The expanders are in two separate but adjacent memory regions.

- This CEDT/SRAT describes one node per device

- The expanders have the same performance and will be in the same memory tier.

[CEDT](</kernel/hardware/driver-api/cxl-platform-acpi/cedt.md>):



```text
           Subtable Type : 00 [CXL Host Bridge Structure]
                Reserved : 00
                  Length : 0020
  Associated host bridge : 00000007
   Specification version : 00000001
                Reserved : 00000000
           Register base : 0000010370400000
         Register length : 0000000000010000

           Subtable Type : 00 [CXL Host Bridge Structure]
                Reserved : 00
                  Length : 0020
  Associated host bridge : 00000006
   Specification version : 00000001
                Reserved : 00000000
           Register base : 0000010380800000
         Register length : 0000000000010000

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000001000000000
             Window size : 0000000100000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000007

           Subtable Type : 01 [CXL Fixed Memory Window Structure]
                Reserved : 00
                  Length : 002C
                Reserved : 00000000
     Window base address : 0000001100000000
             Window size : 0000000100000000
Interleave Members (2^n) : 00
   Interleave Arithmetic : 00
                Reserved : 0000
             Granularity : 00000000
            Restrictions : 0006
                   QtgId : 0001
            First Target : 00000006
```

[SRAT](</kernel/hardware/driver-api/cxl-platform-acpi/srat.md>):



```text
        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000001
            Reserved1 : 0000
         Base Address : 0000001000000000
       Address Length : 0000000100000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0

        Subtable Type : 01 [Memory Affinity]
               Length : 28
     Proximity Domain : 00000002
            Reserved1 : 0000
         Base Address : 0000001100000000
       Address Length : 0000000100000000
            Reserved2 : 00000000
Flags (decoded below) : 0000000B
            Enabled : 1
      Hot Pluggable : 1
       Non-Volatile : 0
```

[HMAT](</kernel/hardware/driver-api/cxl-platform-acpi/hmat.md>):



```text
              Structure Type : 0001 [SLLBI]
                   Data Type : 00   [Latency]
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
Target Proximity Domain List : 00000002
                       Entry : 0080
                       Entry : 0100
                       Entry : 0100

              Structure Type : 0001 [SLLBI]
                   Data Type : 03   [Bandwidth]
Target Proximity Domain List : 00000000
Target Proximity Domain List : 00000001
Target Proximity Domain List : 00000002
                       Entry : 1200
                       Entry : 0200
                       Entry : 0200
```

[SLIT](</kernel/hardware/driver-api/cxl-platform-acpi/slit.md>):



```text
   Signature : "SLIT"    [System Locality Information Table]
  Localities : 0000000000000003
Locality   0 : 10 20 20
Locality   1 : FF 0A FF
Locality   2 : FF FF 0A
```

[DSDT](</kernel/hardware/driver-api/cxl-platform-acpi/dsdt.md>):



```text
Scope (_SB)
{
  Device (S0D0)
  {
      Name (_HID, "ACPI0016" /* Compute Express Link Host Bridge */)  // _HID: Hardware ID
      ...
      Name (_UID, 0x07)  // _UID: Unique ID
  }
  ...
  Device (S0D5)
  {
      Name (_HID, "ACPI0016" /* Compute Express Link Host Bridge */)  // _HID: Hardware ID
      ...
      Name (_UID, 0x06)  // _UID: Unique ID
  }
}
```

---

# Kernel driver lp855x

_Peios Kernel / Hardware and drivers / Driver development / backlight_

> Backlight driver for LP855x ICs

<a id="rst-kernel-driver-lp855x"></a>

Backlight driver for LP855x ICs

Supported chips:

> Texas Instruments LP8550, LP8551, LP8552, LP8553, LP8555, LP8556 and LP8557

Author: Milo(Woogyom) Kim &lt;[milo.kim@ti.com](<mailto:milo.kim@ti.com>)&gt;

<a id="rst-description"></a>

## Description

- Brightness control

  Brightness can be controlled by the pwm input or the i2c command. The lp855x driver supports both cases.

- Device attributes

  1. bl_ctl_mode

  Backlight control mode.

  Value: pwm based or register based

  2. chip_id

  The lp855x chip id.

  Value: lp8550/lp8551/lp8552/lp8553/lp8555/lp8556/lp8557

<a id="rst-platform-data-for-lp855x"></a>

## Platform data for lp855x

For supporting platform specific data, the lp855x platform data can be used.

- - **name:**

    Backlight driver name. If it is not defined, default name is set.

- - **device_control:**

    Value of DEVICE CONTROL register.

- - **initial_brightness:**

    Initial value of backlight brightness.

- - **period_ns:**

    Platform specific PWM period value. unit is nano. Only valid when brightness is pwm input mode.

- - **size_program:**

    Total size of lp855x_rom_data.

- - **rom_data:**

    List of new eeprom/eprom registers.

<a id="rst-examples"></a>

### Examples

1. lp8552 platform data: i2c register mode with new eeprom data:



   ```text
   #define EEPROM_A5_ADDR      0xA5
   #define EEPROM_A5_VAL       0x4f    /* EN_VSYNC=0 */

   static struct lp855x_rom_data lp8552_eeprom_arr[] = {
       {EEPROM_A5_ADDR, EEPROM_A5_VAL},
   };

   static struct lp855x_platform_data lp8552_pdata = {
       .name = "lcd-bl",
       .device_control = I2C_CONFIG(LP8552),
       .initial_brightness = INITIAL_BRT,
       .size_program = ARRAY_SIZE(lp8552_eeprom_arr),
       .rom_data = lp8552_eeprom_arr,
   };
   ```

2. lp8556 platform data: pwm input mode with default rom data:



   ```text
   static struct lp855x_platform_data lp8556_pdata = {
       .device_control = PWM_CONFIG(LP8556),
       .initial_brightness = INITIAL_BRT,
       .period_ns = 1000000,
   };
   ```

---

# Media subsystem kernel internal API

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> This section contains usage information about media subsystem and its supported drivers.

<a id="rst-media-subsystem-kernel-internal-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

This section contains usage information about media subsystem and its supported drivers.

Please see:

[Documentation/admin-guide/media/index.rst](/kernel/administration/admin-guide/media/index.md)

> - for usage information about media subsystem and supported drivers;

[Documentation/userspace-api/media/index.rst](/kernel/userspace/userspace-api/media/index.md)

> - for the userspace APIs used on media devices.

**Table of Contents**

1. [Media Subsystem Profile](</kernel/hardware/driver-api/media/maintainer-entry-profile.md>)
2. [Video4Linux devices](</kernel/hardware/driver-api/media/v4l2-core.md>)
3. [Digital TV (DVB) devices](</kernel/hardware/driver-api/media/dtv-core.md>)
4. [Remote Controller devices](</kernel/hardware/driver-api/media/rc-core.md>)
5. [Media Controller devices](</kernel/hardware/driver-api/media/mc-core.md>)
6. [CEC Kernel Support](</kernel/hardware/driver-api/media/cec-core.md>)
7. [Pixel data transmitter and receiver drivers](</kernel/hardware/driver-api/media/tx-rx.md>)
8. [Writing camera sensor drivers](</kernel/hardware/driver-api/media/camera-sensor.md>)
9. [Media driver-specific documentation](</kernel/hardware/driver-api/media-drivers/index.md>)

**Copyright** © 2009-2020 : LinuxTV Developers



```text
This documentation is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option) any
later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.

For more details see the file COPYING in the source distribution of Linux.
```

---

# Writing camera sensor drivers

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> This document covers the in-kernel APIs only. For the best practices on userspace API implementation in camera sensor drivers, please see media_using_camera_sensor_drivers.

<a id="rst-writing-camera-sensor-drivers"></a>
<a id="rst-media-writing-camera-sensor-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document covers the in-kernel APIs only. For the best practices on userspace API implementation in camera sensor drivers, please see [Using camera sensor drivers](</kernel/userspace/userspace-api/media-drivers/camera-sensor.md#rst-media-using-camera-sensor-drivers>).

<a id="rst-csi-2-parallel-and-bt-656-buses"></a>

## CSI-2, parallel and BT.656 buses

Please see [Pixel data transmitter and receiver drivers](</kernel/hardware/driver-api/media/tx-rx.md#rst-transmitter-receiver>).

<a id="rst-handling-clocks"></a>

## Handling clocks

Camera sensors have an internal clock tree including a PLL and a number of divisors. The clock tree is generally configured by the driver based on a few input parameters that are specific to the hardware: the external clock frequency and the link frequency. The two parameters generally are obtained from system firmware. **No other frequencies should be used in any circumstances.**

The reason why the clock frequencies are so important is that the clock signals come out of the SoC, and in many cases a specific frequency is designed to be used in the system. Using another frequency may cause harmful effects elsewhere. Therefore only the pre-determined frequencies are configurable by the user.

The external clock frequency shall be retrieved by obtaining the external clock using the `devm_v4l2_sensor_clk_get()` helper function, and then getting its frequency with `clk_get_rate()`. Usage of the helper function guarantees correct behaviour regardless of whether the sensor is integrated in a DT-based or ACPI-based system.

<a id="rst-acpi"></a>

### ACPI

ACPI-based systems typically don't register the sensor external clock with the kernel, but specify the external clock frequency in the `clock-frequency` \_DSD property. The `devm_v4l2_sensor_clk_get()` helper creates and returns a fixed clock set at that rate.

<a id="rst-devicetree"></a>

### Devicetree

Devicetree-based systems declare the sensor external clock in the device tree and reference it from the sensor node. The preferred way to select the external clock frequency is to use the `assigned-clocks`, `assigned-clock-parents` and `assigned-clock-rates` properties in the sensor node to set the clock rate. See the [clock device tree bindings](<https://github.com/devicetree-org/dt-schema/blob/main/dtschema/schemas/clock/clock.yaml>)<a id="rst-clock-device-tree-bindings"></a> for more information. The `devm_v4l2_sensor_clk_get()` helper retrieves and returns that clock.

This approach has the drawback that there's no guarantee that the frequency hasn't been modified directly or indirectly by another driver, or supported by the board's clock tree to begin with. Changes to the Common Clock Framework API are required to ensure reliability.

<a id="rst-power-management"></a>

## Power management

Camera sensors are used in conjunction with other devices to form a camera pipeline. They must obey the rules listed herein to ensure coherent power management over the pipeline.

Camera sensor drivers are responsible for controlling the power state of the device they otherwise control as well. They shall use runtime PM to manage power states. Runtime PM shall be enabled at probe time and disabled at remove time. Drivers should enable runtime PM autosuspend. Also see [async sub-device registration](</kernel/hardware/driver-api/media/v4l2-subdev.md#rst-media-registering-async-subdevs>).

The runtime PM handlers shall handle clocks, regulators, GPIOs, and other system resources required to power the sensor up and down. For drivers that don't use any of those resources (such as drivers that support ACPI systems only), the runtime PM handlers may be left unimplemented.

In general, the device shall be powered on at least when its registers are being accessed and when it is streaming. Drivers should use `pm_runtime_resume_and_get()` when starting streaming and `pm_runtime_put()` or `pm_runtime_put_autosuspend()` when stopping streaming. They may power the device up at probe time (for example to read identification registers), but should not keep it powered unconditionally after probe.

At system suspend time, the whole camera pipeline must stop streaming, and restart when the system is resumed. This requires coordination between the camera sensor and the rest of the camera pipeline. Bridge drivers are responsible for this coordination, and instruct camera sensors to stop and restart streaming by calling the appropriate subdev operations (`.enable_streams()` or `.disable_streams()`). Camera sensor drivers shall therefore **not** keep track of the streaming state to stop streaming in the PM suspend handler and restart it in the resume handler. Drivers should in general not implement the system PM handlers.

Camera sensor drivers shall **not** implement the subdev `.s_power()` operation, as it is deprecated. While this operation is implemented in some existing drivers as they predate the deprecation, new drivers shall use runtime PM instead. If you feel you need to begin calling `.s_power()` from an ISP or a bridge driver, instead add runtime PM support to the sensor driver you are using and drop its `.s_power()` handler.

Please also see [examples](<#rst-media-camera-sensor-examples>).

<a id="rst-control-framework"></a>

### Control framework

`v4l2_ctrl_handler_setup()` function may not be used in the device's runtime PM `runtime_resume` callback, as it has no way to figure out the power state of the device. This is because the power state of the device is only changed after the power state transition has taken place. The `s_ctrl` callback can be used to obtain device's power state after the power state transition:





<a id="c-pm_runtime_get_if_in_use"></a>

```c
int pm_runtime_get_if_in_use(struct device *dev);
```

The function returns a non-zero value if it succeeded getting the power count or runtime PM was disabled, in either of which cases the driver may proceed to access the device.

<a id="rst-rotation-orientation-and-flipping"></a>

## Rotation, orientation and flipping

Use `v4l2_fwnode_device_parse()` to obtain rotation and orientation information from system firmware and `v4l2_ctrl_new_fwnode_properties()` to register the appropriate controls.

<a id="rst-example-drivers"></a>
<a id="rst-media-camera-sensor-examples"></a>

## Example drivers

Features implemented by sensor drivers vary, and depending on the set of supported features and other qualities, particular sensor drivers better serve the purpose of an example. The following drivers are known to be good examples:


<table>
<caption>Example sensor drivers</caption>
<tbody>
<tr>
<td>


Driver name

</td>
<td>


File(s)

</td>
<td>


Driver type

</td>
<td>


Example topic

</td>
</tr>
<tr>
<td>


CCS

</td>
<td>


`drivers/media/i2c/ccs/`

</td>
<td>


Freely configurable

</td>
<td>


Power management (ACPI and DT), UAPI

</td>
</tr>
<tr>
<td>


imx219

</td>
<td>


`drivers/media/i2c/imx219.c`

</td>
<td>


Register list based

</td>
<td>


Power management (DT), UAPI, mode selection

</td>
</tr>
<tr>
<td>


imx319

</td>
<td>


`drivers/media/i2c/imx319.c`

</td>
<td>


Register list based

</td>
<td>


Power management (ACPI and DT)

</td>
</tr>
</tbody>
</table>

---

# CEC Kernel Support

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The CEC framework provides a unified kernel interface for use with HDMI CEC hardware. It is designed to handle a multiple types of hardware (receivers, transmitters, USB dongles). The framework also gives the option to decide what to do in…

<a id="rst-cec-kernel-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The CEC framework provides a unified kernel interface for use with HDMI CEC hardware. It is designed to handle a multiple types of hardware (receivers, transmitters, USB dongles). The framework also gives the option to decide what to do in the kernel driver and what should be handled by userspace applications. In addition it integrates the remote control passthrough feature into the kernel's remote control framework.

<a id="rst-the-cec-protocol"></a>

## The CEC Protocol

The CEC protocol enables consumer electronic devices to communicate with each other through the HDMI connection. The protocol uses logical addresses in the communication. The logical address is strictly connected with the functionality provided by the device. The TV acting as the communication hub is always assigned address 0. The physical address is determined by the physical connection between devices.

The CEC framework described here is up to date with the CEC 2.0 specification. It is documented in the HDMI 1.4 specification with the new 2.0 bits documented in the HDMI 2.0 specification. But for most of the features the freely available HDMI 1.3a specification is sufficient:

[https://www.hdmi.org/spec/index](<https://www.hdmi.org/spec/index>)

<a id="rst-cec-adapter-interface"></a>

## CEC Adapter Interface

The struct cec_adapter represents the CEC adapter hardware. It is created by calling cec_allocate_adapter() and deleted by calling cec_delete_adapter():





<a id="c-cec_allocate_adapter"></a>

```c
struct cec_adapter *cec_allocate_adapter(const struct cec_adap_ops *ops, \
                                         void *priv, const char *name, \
                                         u32 caps, u8 available_las);
```





<a id="c-cec_delete_adapter"></a>

```c
void cec_delete_adapter(struct cec_adapter *adap);
```

To create an adapter you need to pass the following information:

- **ops:**

  adapter operations which are called by the CEC framework and that you have to implement.

- **priv:**

  will be stored in adap-&gt;priv and can be used by the adapter ops. Use cec_get_drvdata(adap) to get the priv pointer.

- **name:**

  the name of the CEC adapter. Note: this name will be copied.

- **caps:**

  capabilities of the CEC adapter. These capabilities determine the capabilities of the hardware and which parts are to be handled by userspace and which parts are handled by kernelspace. The capabilities are returned by CEC_ADAP_G_CAPS.

- **available_las:**

  the number of simultaneous logical addresses that this adapter can handle. Must be 1 &lt;= available_las &lt;= CEC_MAX_LOG_ADDRS.

To obtain the priv pointer use this helper function:





<a id="c-cec_get_drvdata"></a>

```c
void *cec_get_drvdata(const struct cec_adapter *adap);
```

To register the /dev/cecX device node and the remote control device (if CEC_CAP_RC is set) you call:





<a id="c-cec_register_adapter"></a>

```c
int cec_register_adapter(struct cec_adapter *adap, \
                         struct device *parent);
```

where parent is the parent device.

To unregister the devices call:





<a id="c-cec_unregister_adapter"></a>

```c
void cec_unregister_adapter(struct cec_adapter *adap);
```

Note: if cec_register_adapter() fails, then call cec_delete_adapter() to clean up. But if cec_register_adapter() succeeded, then only call cec_unregister_adapter() to clean up, never cec_delete_adapter(). The unregister function will delete the adapter automatically once the last user of that /dev/cecX device has closed its file handle.

<a id="rst-implementing-the-low-level-cec-adapter"></a>

## Implementing the Low-Level CEC Adapter

The following low-level adapter operations have to be implemented in your driver:





<a id="c-struct-cec_adap_ops"></a>

```c
cec_adap_ops
```



```none
struct cec_adap_ops
{
        /* Low-level callbacks */
        int (*adap_enable)(struct cec_adapter *adap, bool enable);
        int (*adap_monitor_all_enable)(struct cec_adapter *adap, bool enable);
        int (*adap_monitor_pin_enable)(struct cec_adapter *adap, bool enable);
        int (*adap_log_addr)(struct cec_adapter *adap, u8 logical_addr);
        void (*adap_unconfigured)(struct cec_adapter *adap);
        int (*adap_transmit)(struct cec_adapter *adap, u8 attempts,
                              u32 signal_free_time, struct cec_msg *msg);
        void (*adap_nb_transmit_canceled)(struct cec_adapter *adap,
                                          const struct cec_msg *msg);
        void (*adap_status)(struct cec_adapter *adap, struct seq_file *file);
        void (*adap_free)(struct cec_adapter *adap);

        /* Error injection callbacks */
        ...

        /* High-level callback */
        ...
};
```

These low-level ops deal with various aspects of controlling the CEC adapter hardware. They are all called with the mutex adap-&gt;lock held.

To enable/disable the hardware:



```text
int (*adap_enable)(struct cec_adapter *adap, bool enable);
```

This callback enables or disables the CEC hardware. Enabling the CEC hardware means powering it up in a state where no logical addresses are claimed. The physical address will always be valid if CEC_CAP_NEEDS_HPD is set. If that capability is not set, then the physical address can change while the CEC hardware is enabled. CEC drivers should not set CEC_CAP_NEEDS_HPD unless the hardware design requires that as this will make it impossible to wake up displays that pull the HPD low when in standby mode.  The initial state of the CEC adapter after calling cec_allocate_adapter() is disabled.

Note that adap_enable must return 0 if enable is false.

To enable/disable the 'monitor all' mode:



```text
int (*adap_monitor_all_enable)(struct cec_adapter *adap, bool enable);
```

If enabled, then the adapter should be put in a mode to also monitor messages that are not for us. Not all hardware supports this and this function is only called if the CEC_CAP_MONITOR_ALL capability is set. This callback is optional (some hardware may always be in 'monitor all' mode).

Note that adap_monitor_all_enable must return 0 if enable is false.

To enable/disable the 'monitor pin' mode:



```text
int (*adap_monitor_pin_enable)(struct cec_adapter *adap, bool enable);
```

If enabled, then the adapter should be put in a mode to also monitor CEC pin changes. Not all hardware supports this and this function is only called if the CEC_CAP_MONITOR_PIN capability is set. This callback is optional (some hardware may always be in 'monitor pin' mode).

Note that adap_monitor_pin_enable must return 0 if enable is false.

To program a new logical address:



```text
int (*adap_log_addr)(struct cec_adapter *adap, u8 logical_addr);
```

If logical_addr == CEC_LOG_ADDR_INVALID then all programmed logical addresses are to be erased. Otherwise the given logical address should be programmed. If the maximum number of available logical addresses is exceeded, then it should return -ENXIO. Once a logical address is programmed the CEC hardware can receive directed messages to that address.

Note that adap_log_addr must return 0 if logical_addr is CEC_LOG_ADDR_INVALID.

Called when the adapter is unconfigured:



```text
void (*adap_unconfigured)(struct cec_adapter *adap);
```

The adapter is unconfigured. If the driver has to take specific actions after unconfiguration, then that can be done through this optional callback.

To transmit a new message:



```text
int (*adap_transmit)(struct cec_adapter *adap, u8 attempts,
                     u32 signal_free_time, struct cec_msg *msg);
```

This transmits a new message. The attempts argument is the suggested number of attempts for the transmit.

The signal_free_time is the number of data bit periods that the adapter should wait when the line is free before attempting to send a message. This value depends on whether this transmit is a retry, a message from a new initiator or a new message for the same initiator. Most hardware will handle this automatically, but in some cases this information is needed.

The CEC_FREE_TIME_TO_USEC macro can be used to convert signal_free_time to microseconds (one data bit period is 2.4 ms).

To pass on the result of a canceled non-blocking transmit:



```text
void (*adap_nb_transmit_canceled)(struct cec_adapter *adap,
                                  const struct cec_msg *msg);
```

This optional callback can be used to obtain the result of a canceled non-blocking transmit with sequence number msg-&gt;sequence. This is called if the transmit was aborted, the transmit timed out (i.e. the hardware never signaled that the transmit finished), or the transmit was successful, but the wait for the expected reply was either aborted or it timed out.

To log the current CEC hardware status:



```text
void (*adap_status)(struct cec_adapter *adap, struct seq_file *file);
```

This optional callback can be used to show the status of the CEC hardware. The status is available through debugfs: cat /sys/kernel/debug/cec/cecX/status

To free any resources when the adapter is deleted:



```text
void (*adap_free)(struct cec_adapter *adap);
```

This optional callback can be used to free any resources that might have been allocated by the driver. It's called from cec_delete_adapter.

Your adapter driver will also have to react to events (typically interrupt driven) by calling into the framework in the following situations:

When a transmit finished (successfully or otherwise):



```text
void cec_transmit_done(struct cec_adapter *adap, u8 status,
                       u8 arb_lost_cnt,  u8 nack_cnt, u8 low_drive_cnt,
                       u8 error_cnt);
```

or:



```text
void cec_transmit_attempt_done(struct cec_adapter *adap, u8 status);
```

The status can be one of:

- **CEC_TX_STATUS_OK:**

  the transmit was successful.

- **CEC_TX_STATUS_ARB_LOST:**

  arbitration was lost: another CEC initiator took control of the CEC line and you lost the arbitration.

- **CEC_TX_STATUS_NACK:**

  the message was nacked (for a directed message) or acked (for a broadcast message). A retransmission is needed.

- **CEC_TX_STATUS_LOW_DRIVE:**

  low drive was detected on the CEC bus. This indicates that a follower detected an error on the bus and requested a retransmission.

- **CEC_TX_STATUS_ERROR:**

  some unspecified error occurred: this can be one of ARB_LOST or LOW_DRIVE if the hardware cannot differentiate or something else entirely. Some hardware only supports OK and FAIL as the result of a transmit, i.e. there is no way to differentiate between the different possible errors. In that case map FAIL to CEC_TX_STATUS_NACK and not to CEC_TX_STATUS_ERROR.

- **CEC_TX_STATUS_MAX_RETRIES:**

  could not transmit the message after trying multiple times. Should only be set by the driver if it has hardware support for retrying messages. If set, then the framework assumes that it doesn't have to make another attempt to transmit the message since the hardware did that already.

The hardware must be able to differentiate between OK, NACK and 'something else'.

The \*\_cnt arguments are the number of error conditions that were seen. This may be 0 if no information is available. Drivers that do not support hardware retry can just set the counter corresponding to the transmit error to 1, if the hardware does support retry then either set these counters to 0 if the hardware provides no feedback of which errors occurred and how many times, or fill in the correct values as reported by the hardware.

Be aware that calling these functions can immediately start a new transmit if there is one pending in the queue. So make sure that the hardware is in a state where new transmits can be started *before* calling these functions.

The cec_transmit_attempt_done() function is a helper for cases where the hardware never retries, so the transmit is always for just a single attempt. It will call cec_transmit_done() in turn, filling in 1 for the count argument corresponding to the status. Or all 0 if the status was OK.

When a CEC message was received:





<a id="c-cec_received_msg"></a>

```c
void cec_received_msg(struct cec_adapter *adap, struct cec_msg *msg);
```

Speaks for itself.

<a id="rst-implementing-the-interrupt-handler"></a>

## Implementing the interrupt handler

Typically the CEC hardware provides interrupts that signal when a transmit finished and whether it was successful or not, and it provides and interrupt when a CEC message was received.

The CEC driver should always process the transmit interrupts first before handling the receive interrupt. The framework expects to see the cec_transmit_done call before the cec_received_msg call, otherwise it can get confused if the received message was in reply to the transmitted message.

<a id="rst-optional-implementing-error-injection-support"></a>

## Optional: Implementing Error Injection Support

If the CEC adapter supports Error Injection functionality, then that can be exposed through the Error Injection callbacks:



```none
struct cec_adap_ops {
        /* Low-level callbacks */
        ...

        /* Error injection callbacks */
        int (*error_inj_show)(struct cec_adapter *adap, struct seq_file *sf);
        bool (*error_inj_parse_line)(struct cec_adapter *adap, char *line);

        /* High-level CEC message callback */
        ...
};
```

If both callbacks are set, then an `error-inj` file will appear in debugfs. The basic syntax is as follows:

Leading spaces/tabs are ignored. If the next character is a `#` or the end of the line was reached, then the whole line is ignored. Otherwise a command is expected.

This basic parsing is done in the CEC Framework. It is up to the driver to decide what commands to implement. The only requirement is that the command `clear` without any arguments must be implemented and that it will remove all current error injection commands.

This ensures that you can always do `echo clear >error-inj` to clear any error injections without having to know the details of the driver-specific commands.

Note that the output of `error-inj` shall be valid as input to `error-inj`. So this must work:



```none
$ cat error-inj >einj.txt
$ cat einj.txt >error-inj
```

The first callback is called when this file is read and it should show the current error injection state:



```text
int (*error_inj_show)(struct cec_adapter *adap, struct seq_file *sf);
```

It is recommended that it starts with a comment block with basic usage information. It returns 0 for success and an error otherwise.

The second callback will parse commands written to the `error-inj` file:



```text
bool (*error_inj_parse_line)(struct cec_adapter *adap, char *line);
```

The `line` argument points to the start of the command. Any leading spaces or tabs have already been skipped. It is a single line only (so there are no embedded newlines) and it is 0-terminated. The callback is free to modify the contents of the buffer. It is only called for lines containing a command, so this callback is never called for empty lines or comment lines.

Return true if the command was valid or false if there were syntax errors.

<a id="rst-implementing-the-high-level-cec-adapter"></a>

## Implementing the High-Level CEC Adapter

The low-level operations drive the hardware, the high-level operations are CEC protocol driven. The high-level callbacks are called without the adap-&gt;lock mutex being held. The following high-level callbacks are available:



```none
struct cec_adap_ops {
        /* Low-level callbacks */
        ...

        /* Error injection callbacks */
        ...

        /* High-level CEC message callback */
        void (*configured)(struct cec_adapter *adap);
        int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
};
```

Called when the adapter is configured:



```text
void (*configured)(struct cec_adapter *adap);
```

The adapter is fully configured, i.e. all logical addresses have been successfully claimed. If the driver has to take specific actions after configuration, then that can be done through this optional callback.

The received() callback allows the driver to optionally handle a newly received CEC message:



```text
int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
```

If the driver wants to process a CEC message, then it can implement this callback. If it doesn't want to handle this message, then it should return -ENOMSG, otherwise the CEC framework assumes it processed this message and it will not do anything with it.

<a id="rst-cec-framework-functions"></a>

## CEC framework functions

CEC Adapter drivers can call the following CEC framework functions:





<a id="c-cec_transmit_msg"></a>

```c
int cec_transmit_msg(struct cec_adapter *adap, struct cec_msg *msg, \
                     bool block);
```

Transmit a CEC message. If block is true, then wait until the message has been transmitted, otherwise just queue it and return.





<a id="c-cec_s_phys_addr"></a>

```c
void cec_s_phys_addr(struct cec_adapter *adap, u16 phys_addr, bool block);
```

Change the physical address. This function will set adap-&gt;phys_addr and send an event if it has changed. If cec_s_log_addrs() has been called and the physical address has become valid, then the CEC framework will start claiming the logical addresses. If block is true, then this function won't return until this process has finished.

When the physical address is set to a valid value the CEC adapter will be enabled (see the adap_enable op). When it is set to CEC_PHYS_ADDR_INVALID, then the CEC adapter will be disabled. If you change a valid physical address to another valid physical address, then this function will first set the address to CEC_PHYS_ADDR_INVALID before enabling the new physical address.





<a id="c-cec_s_phys_addr_from_edid"></a>

```c
void cec_s_phys_addr_from_edid(struct cec_adapter *adap, \
                               const struct edid *edid);
```

A helper function that extracts the physical address from the edid struct and calls cec_s_phys_addr() with that address, or CEC_PHYS_ADDR_INVALID if the EDID did not contain a physical address or edid was a NULL pointer.





<a id="c-cec_s_log_addrs"></a>

```c
int cec_s_log_addrs(struct cec_adapter *adap, \
                    struct cec_log_addrs *log_addrs, bool block);
```

Claim the CEC logical addresses. Should never be called if CEC_CAP_LOG_ADDRS is set. If block is true, then wait until the logical addresses have been claimed, otherwise just queue it and return. To unconfigure all logical addresses call this function with log_addrs set to NULL or with log_addrs-&gt;num_log_addrs set to 0. The block argument is ignored when unconfiguring. This function will just return if the physical address is invalid. Once the physical address becomes valid, then the framework will attempt to claim these logical addresses.

<a id="rst-cec-pin-framework"></a>

## CEC Pin framework

Most CEC hardware operates on full CEC messages where the software provides the message and the hardware handles the low-level CEC protocol. But some hardware only drives the CEC pin and software has to handle the low-level CEC protocol. The CEC pin framework was created to handle such devices.

Note that due to the close-to-realtime requirements it can never be guaranteed to work 100%. This framework uses highres timers internally, but if a timer goes off too late by more than 300 microseconds wrong results can occur. In reality it appears to be fairly reliable.

One advantage of this low-level implementation is that it can be used as a cheap CEC analyser, especially if interrupts can be used to detect CEC pin transitions from low to high or vice versa.


#### <a id="c-struct-cec_pin_ops"></a>`struct cec_pin_ops`

low-level CEC pin operations

**Definition**

```c
struct cec_pin_ops {
    int (*read)(struct cec_adapter *adap);
    void (*low)(struct cec_adapter *adap);
    void (*high)(struct cec_adapter *adap);
    bool (*enable_irq)(struct cec_adapter *adap);
    void (*disable_irq)(struct cec_adapter *adap);
    void (*free)(struct cec_adapter *adap);
    void (*status)(struct cec_adapter *adap, struct seq_file *file);
    int (*read_hpd)(struct cec_adapter *adap);
    int (*read_5v)(struct cec_adapter *adap);
    int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
};
```

**Members**

- `read`: read the CEC pin. Returns > 0 if high, 0 if low, or an error
  if negative.
- `low`: drive the CEC pin low.
- `high`: stop driving the CEC pin. The pull-up will drive the pin
  high, unless someone else is driving the pin low.
- `enable_irq`: optional, enable the interrupt to detect pin voltage changes.
- `disable_irq`: optional, disable the interrupt.
- `free`: optional. Free any allocated resources. Called when the
  adapter is deleted.
- `status`: optional, log status information.
- `read_hpd`: optional. Read the HPD pin. Returns > 0 if high, 0 if low or
  an error if negative.
- `read_5v`: optional. Read the 5V pin. Returns > 0 if high, 0 if low or
  an error if negative.
- `received`: optional. High-level CEC message callback. Allows the driver
  to process CEC messages.

**Description**

These operations (except for the **received** op) are used by the
cec pin framework to manipulate the CEC pin.

#### <a id="c-cec_pin_changed"></a>`cec_pin_changed()`

```c
void cec_pin_changed(struct cec_adapter *adap, bool value)
```

update pin state from interrupt

**Parameters**

- `struct cec_adapter *adap`: pointer to the cec adapter
- `bool value`: when true the pin is high, otherwise it is low

**Description**

If changes of the CEC voltage are detected via an interrupt, then
cec_pin_changed is called from the interrupt with the new value.

#### <a id="c-cec_pin_allocate_adapter"></a>`cec_pin_allocate_adapter()`

```c
struct cec_adapter * cec_pin_allocate_adapter(const struct cec_pin_ops *pin_ops, void *priv, const char *name, u32 caps)
```

allocate a pin-based cec adapter

**Parameters**

- `const struct cec_pin_ops *pin_ops`: low-level pin operations
- `void *priv`: will be stored in adap->priv and can be used by the adapter ops.
  Use cec_get_drvdata(adap) to get the priv pointer.
- `const char *name`: the name of the CEC adapter. Note: this name will be copied.
- `u32 caps`: capabilities of the CEC adapter. This will be ORed with
  CEC_CAP_MONITOR_ALL and CEC_CAP_MONITOR_PIN.

**Description**

Allocate a cec adapter using the cec pin framework.

**Return**

a pointer to the cec adapter or an error pointer


<a id="rst-cec-notifier-framework"></a>

## CEC Notifier framework

Most drm HDMI implementations have an integrated CEC implementation and no notifier support is needed. But some have independent CEC implementations that have their own driver. This could be an IP block for an SoC or a completely separate chip that deals with the CEC pin. For those cases a drm driver can install a notifier and use the notifier to inform the CEC driver about changes in the physical address.


#### <a id="c-cec_notifier_conn_register"></a>`cec_notifier_conn_register()`

```c
struct cec_notifier * cec_notifier_conn_register(struct device *hdmi_dev, const char *port_name, const struct cec_connector_info *conn_info)
```

find or create a new cec_notifier for the given HDMI device and connector tuple.

**Parameters**

- `struct device *hdmi_dev`: HDMI device that sends the events.
- `const char *port_name`: the connector name from which the event occurs. May be NULL
  if there is always only one HDMI connector created by the HDMI device.
- `const struct cec_connector_info *conn_info`: the connector info from which the event occurs (may be NULL)

**Description**

If a notifier for device **dev** and connector **port_name** already exists, then
increase the refcount and return that notifier.

If it doesn't exist, then allocate a new notifier struct and return a
pointer to that new struct.

Return NULL if the memory could not be allocated.

#### <a id="c-cec_notifier_conn_unregister"></a>`cec_notifier_conn_unregister()`

```c
void cec_notifier_conn_unregister(struct cec_notifier *n)
```

decrease refcount and delete when the refcount reaches 0.

**Parameters**

- `struct cec_notifier *n`: notifier. If NULL, then this function does nothing.

#### <a id="c-cec_notifier_cec_adap_register"></a>`cec_notifier_cec_adap_register()`

```c
struct cec_notifier * cec_notifier_cec_adap_register(struct device *hdmi_dev, const char *port_name, struct cec_adapter *adap)
```

find or create a new cec_notifier for the given device.

**Parameters**

- `struct device *hdmi_dev`: HDMI device that sends the events.
- `const char *port_name`: the connector name from which the event occurs. May be NULL
  if there is always only one HDMI connector created by the HDMI device.
- `struct cec_adapter *adap`: the cec adapter that registered this notifier.

**Description**

If a notifier for device **dev** and connector **port_name** already exists, then
increase the refcount and return that notifier.

If it doesn't exist, then allocate a new notifier struct and return a
pointer to that new struct.

Return NULL if the memory could not be allocated.

#### <a id="c-cec_notifier_cec_adap_unregister"></a>`cec_notifier_cec_adap_unregister()`

```c
void cec_notifier_cec_adap_unregister(struct cec_notifier *n, struct cec_adapter *adap)
```

decrease refcount and delete when the refcount reaches 0.

**Parameters**

- `struct cec_notifier *n`: notifier. If NULL, then this function does nothing.
- `struct cec_adapter *adap`: the cec adapter that registered this notifier.

#### <a id="c-cec_notifier_set_phys_addr"></a>`cec_notifier_set_phys_addr()`

```c
void cec_notifier_set_phys_addr(struct cec_notifier *n, u16 pa)
```

set a new physical address.

**Parameters**

- `struct cec_notifier *n`: the CEC notifier
- `u16 pa`: the CEC physical address

**Description**

Set a new CEC physical address.
Does nothing if **n** == NULL.

#### <a id="c-cec_notifier_set_phys_addr_from_edid"></a>`cec_notifier_set_phys_addr_from_edid()`

```c
void cec_notifier_set_phys_addr_from_edid(struct cec_notifier *n, const struct edid *edid)
```

set parse the PA from the EDID.

**Parameters**

- `struct cec_notifier *n`: the CEC notifier
- `const struct edid *edid`: the struct edid pointer

**Description**

Parses the EDID to obtain the new CEC physical address and set it.
Does nothing if **n** == NULL.

#### <a id="c-cec_notifier_parse_hdmi_phandle"></a>`cec_notifier_parse_hdmi_phandle()`

```c
struct device * cec_notifier_parse_hdmi_phandle(struct device *dev)
```

find the hdmi device from "hdmi-phandle"

**Parameters**

- `struct device *dev`: the device with the "hdmi-phandle" device tree property

**Description**

Returns the device pointer referenced by the "hdmi-phandle" property.
Note that the refcount of the returned device is not incremented.
This device pointer is only used as a key value in the notifier
list, but it is never accessed by the CEC driver.

#### <a id="c-cec_notifier_phys_addr_invalidate"></a>`cec_notifier_phys_addr_invalidate()`

```c
void cec_notifier_phys_addr_invalidate(struct cec_notifier *n)
```

set the physical address to INVALID

**Parameters**

- `struct cec_notifier *n`: the CEC notifier

**Description**

This is a simple helper function to invalidate the physical
address. Does nothing if **n** == NULL.

---

# Digital TV Conditional Access kABI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Digital TV Conditional Access kABI.

<a id="rst-digital-tv-conditional-access-kabi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-dvb_ca_en50221"></a>`struct dvb_ca_en50221`

Structure describing a CA interface

**Definition**

```c
struct dvb_ca_en50221 {
    struct module *owner;
    int (*read_attribute_mem)(struct dvb_ca_en50221 *ca, int slot, int address);
    int (*write_attribute_mem)(struct dvb_ca_en50221 *ca, int slot, int address, u8 value);
    int (*read_cam_control)(struct dvb_ca_en50221 *ca, int slot, u8 address);
    int (*write_cam_control)(struct dvb_ca_en50221 *ca, int slot, u8 address, u8 value);
    int (*read_data)(struct dvb_ca_en50221 *ca, int slot, u8 *ebuf, int ecount);
    int (*write_data)(struct dvb_ca_en50221 *ca, int slot, u8 *ebuf, int ecount);
    int (*slot_reset)(struct dvb_ca_en50221 *ca, int slot);
    int (*slot_shutdown)(struct dvb_ca_en50221 *ca, int slot);
    int (*slot_ts_enable)(struct dvb_ca_en50221 *ca, int slot);
    int (*poll_slot_status)(struct dvb_ca_en50221 *ca, int slot, int open);
    void *data;
    void *private;
};
```

**Members**

- `owner`: the module owning this structure
- `read_attribute_mem`: function for reading attribute memory on the CAM
- `write_attribute_mem`: function for writing attribute memory on the CAM
- `read_cam_control`: function for reading the control interface on the CAM
- `write_cam_control`: function for reading the control interface on the CAM
- `read_data`: function for reading data (block mode)
- `write_data`: function for writing data (block mode)
- `slot_reset`: function to reset the CAM slot
- `slot_shutdown`: function to shutdown a CAM slot
- `slot_ts_enable`: function to enable the Transport Stream on a CAM slot
- `poll_slot_status`: function to poll slot status. Only necessary if
  DVB_CA_FLAG_EN50221_IRQ_CAMCHANGE is not set.
- `data`: private data, used by caller.
- `private`: Opaque data used by the dvb_ca core. Do not modify!

**NOTE**

the read_*, write_* and poll_slot_status functions will be
called for different slots concurrently and need to use locks where
and if appropriate. There will be no concurrent access to one slot.

#### <a id="c-dvb_ca_en50221_camchange_irq"></a>`dvb_ca_en50221_camchange_irq()`

```c
void dvb_ca_en50221_camchange_irq(struct dvb_ca_en50221 *pubca, int slot, int change_type)
```

A CAMCHANGE IRQ has occurred.

**Parameters**

- `struct dvb_ca_en50221 *pubca`: CA instance.
- `int slot`: Slot concerned.
- `int change_type`: One of the DVB_CA_CAMCHANGE_* values

#### <a id="c-dvb_ca_en50221_camready_irq"></a>`dvb_ca_en50221_camready_irq()`

```c
void dvb_ca_en50221_camready_irq(struct dvb_ca_en50221 *pubca, int slot)
```

A CAMREADY IRQ has occurred.

**Parameters**

- `struct dvb_ca_en50221 *pubca`: CA instance.
- `int slot`: Slot concerned.

#### <a id="c-dvb_ca_en50221_frda_irq"></a>`dvb_ca_en50221_frda_irq()`

```c
void dvb_ca_en50221_frda_irq(struct dvb_ca_en50221 *ca, int slot)
```

An FR or a DA IRQ has occurred.

**Parameters**

- `struct dvb_ca_en50221 *ca`: CA instance.
- `int slot`: Slot concerned.

#### <a id="c-dvb_ca_en50221_init"></a>`dvb_ca_en50221_init()`

```c
int dvb_ca_en50221_init(struct dvb_adapter *dvb_adapter, struct dvb_ca_en50221 *ca, int flags, int slot_count)
```

Initialise a new DVB CA device.

**Parameters**

- `struct dvb_adapter *dvb_adapter`: DVB adapter to attach the new CA device to.
- `struct dvb_ca_en50221 *ca`: The dvb_ca instance.
- `int flags`: Flags describing the CA device (DVB_CA_EN50221_FLAG_*).
- `int slot_count`: Number of slots supported.

**Description**

**return** 0 on success, nonzero on failure

#### <a id="c-dvb_ca_en50221_release"></a>`dvb_ca_en50221_release()`

```c
void dvb_ca_en50221_release(struct dvb_ca_en50221 *ca)
```

Release a DVB CA device.

**Parameters**

- `struct dvb_ca_en50221 *ca`: The associated dvb_ca instance.

---

# Digital TV Common functions

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Those functions are responsible for handling the DVB device nodes.

<a id="rst-digital-tv-common-functions"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-dvb-devices"></a>

## DVB devices

Those functions are responsible for handling the DVB device nodes.


#### <a id="c-enum-dvb_device_type"></a>`enum dvb_device_type`

type of the Digital TV device

**Constants**

- `DVB_DEVICE_SEC`: Digital TV standalone Common Interface (CI)
- `DVB_DEVICE_FRONTEND`: Digital TV frontend.
- `DVB_DEVICE_DEMUX`: Digital TV demux.
- `DVB_DEVICE_DVR`: Digital TV digital video record (DVR).
- `DVB_DEVICE_CA`: Digital TV Conditional Access (CA).
- `DVB_DEVICE_NET`: Digital TV network.
- `DVB_DEVICE_VIDEO`: Digital TV video decoder.
  Deprecated. Used only on av7110-av.
- `DVB_DEVICE_AUDIO`: Digital TV audio decoder.
  Deprecated. Used only on av7110-av.
- `DVB_DEVICE_OSD`: Digital TV On Screen Display (OSD).
  Deprecated. Used only on av7110.

#### <a id="c-struct-dvb_adapter"></a>`struct dvb_adapter`

represents a Digital TV adapter using Linux DVB API

**Definition**

```c
struct dvb_adapter {
        int num;
        struct list_head list_head;
        struct list_head device_list;
        const char *name;
        u8 proposed_mac [6];
        void* priv;
        struct device *device;
        struct module *module;
        int mfe_shared;
        struct dvb_device *mfe_dvbdev;
        struct mutex mfe_lock;
    #if defined(CONFIG_MEDIA_CONTROLLER_DVB);
        struct mutex mdev_lock;
        struct media_device *mdev;
        struct media_entity *conn;
        struct media_pad *conn_pads;
    #endif;
};
```

**Members**

- `num`: Number of the adapter
- `list_head`: List with the DVB adapters
- `device_list`: List with the DVB devices
- `name`: Name of the adapter
- `proposed_mac`: proposed MAC address for the adapter
- `priv`: private data
- `device`: pointer to struct device
- `module`: pointer to struct module
- `mfe_shared`: indicates mutually exclusive frontends.
  1 = legacy exclusion behavior: blocking any `open()` call
  2 = enhanced exclusion behavior, emulating the standard
  behavior of busy frontends: allowing read-only sharing
  and otherwise returning immediately with -EBUSY when any
  of the frontends is already opened with write access.
- `mfe_dvbdev`: Frontend device in use, in the case of MFE
- `mfe_lock`: Lock to prevent using the other frontends when MFE is
  used.
- `mdev_lock`: Protect access to the mdev pointer.
- `mdev`: pointer to struct media_device, used when the media
  controller is used.
- `conn`: RF connector. Used only if the device has no separate
  tuner.
- `conn_pads`: pointer to struct media_pad associated with **conn**;

#### <a id="c-struct-dvb_device"></a>`struct dvb_device`

represents a DVB device node

**Definition**

```c
struct dvb_device {
        struct list_head list_head;
        struct kref ref;
        const struct file_operations *fops;
        struct dvb_adapter *adapter;
        enum dvb_device_type type;
        int minor;
        u32 id;
        int readers;
        int writers;
        int users;
        wait_queue_head_t wait_queue;
        int (*kernel_ioctl)(struct file *file, unsigned int cmd, void *arg);
    #if defined(CONFIG_MEDIA_CONTROLLER_DVB);
        const char *name;
        struct media_intf_devnode *intf_devnode;
        unsigned tsout_num_entities;
        struct media_entity *entity, *tsout_entity;
        struct media_pad *pads, *tsout_pads;
    #endif;
        void *priv;
};
```

**Members**

- `list_head`: List head with all DVB devices
- `ref`: reference count for this device
- `fops`: pointer to struct file_operations
- `adapter`: pointer to the adapter that holds this device node
- `type`: type of the device, as defined by [`enum dvb_device_type`](#c-enum-dvb_device_type).
- `minor`: devnode minor number. Major number is always DVB_MAJOR.
- `id`: device ID number, inside the adapter
- `readers`: Initialized by the caller. Each call to `open()` in Read Only mode
  decreases this counter by one.
- `writers`: Initialized by the caller. Each call to `open()` in Read/Write
  mode decreases this counter by one.
- `users`: Initialized by the caller. Each call to `open()` in any mode
  decreases this counter by one.
- `wait_queue`: wait queue, used to wait for certain events inside one of
  the DVB API callers
- `kernel_ioctl`: callback function used to handle ioctl calls from userspace.
- `name`: Name to be used for the device at the Media Controller
- `intf_devnode`: Pointer to media_intf_devnode. Used by the dvbdev core to
  store the MC device node interface
- `tsout_num_entities`: Number of Transport Stream output entities
- `entity`: pointer to struct media_entity associated with the device node
- `tsout_entity`: array with MC entities associated to each TS output node
- `pads`: pointer to struct media_pad associated with **entity**;
- `tsout_pads`: array with the source pads for each **tsout_entity**
- `priv`: private data

**Description**

This structure is used by the DVB core (frontend, CA, net, demux) in
order to create the device nodes. Usually, driver should not initialize
this struct diretly.

#### <a id="c-struct-dvbdevfops_node"></a>`struct dvbdevfops_node`

fops nodes registered in dvbdevfops_list

**Definition**

```c
struct dvbdevfops_node {
    struct file_operations *fops;
    enum dvb_device_type type;
    const struct dvb_device *template;
    struct list_head list_head;
};
```

**Members**

- `fops`: Dynamically allocated fops for ->owner registration
- `type`: type of dvb_device
- `template`: dvb_device used for registration
- `list_head`: list_head for dvbdevfops_list

#### <a id="c-dvb_device_get"></a>`dvb_device_get()`

```c
struct dvb_device * dvb_device_get(struct dvb_device *dvbdev)
```

Increase dvb_device reference

**Parameters**

- `struct dvb_device *dvbdev`: pointer to struct dvb_device

#### <a id="c-dvb_device_put"></a>`dvb_device_put()`

```c
void dvb_device_put(struct dvb_device *dvbdev)
```

Decrease dvb_device reference

**Parameters**

- `struct dvb_device *dvbdev`: pointer to struct dvb_device

#### <a id="c-dvb_register_adapter"></a>`dvb_register_adapter()`

```c
int dvb_register_adapter(struct dvb_adapter *adap, const char *name, struct module *module, struct device *device, short *adapter_nums)
```

Registers a new DVB adapter

**Parameters**

- `struct dvb_adapter *adap`: pointer to struct dvb_adapter
- `const char *name`: Adapter's name
- `struct module *module`: initialized with THIS_MODULE at the caller
- `struct device *device`: pointer to struct device that corresponds to the device driver
- `short *adapter_nums`: Array with a list of the numbers for **dvb_register_adapter**;
  to select among them. Typically, initialized with:
  DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nums)

#### <a id="c-dvb_unregister_adapter"></a>`dvb_unregister_adapter()`

```c
int dvb_unregister_adapter(struct dvb_adapter *adap)
```

Unregisters a DVB adapter

**Parameters**

- `struct dvb_adapter *adap`: pointer to struct dvb_adapter

#### <a id="c-dvb_register_device"></a>`dvb_register_device()`

```c
int dvb_register_device(struct dvb_adapter *adap, struct dvb_device **pdvbdev, const struct dvb_device *template, void *priv, enum dvb_device_type type, int demux_sink_pads)
```

Registers a new DVB device

**Parameters**

- `struct dvb_adapter *adap`: pointer to struct dvb_adapter
- `struct dvb_device **pdvbdev`: pointer to the place where the new struct dvb_device will be
  stored
- `const struct dvb_device *template`: Template used to create `pdvbdev`;
- `void *priv`: private data
- `enum dvb_device_type type`: type of the device, as defined by [`enum dvb_device_type`](#c-enum-dvb_device_type).
- `int demux_sink_pads`: Number of demux outputs, to be used to create the TS
  outputs via the Media Controller.

#### <a id="c-dvb_remove_device"></a>`dvb_remove_device()`

```c
void dvb_remove_device(struct dvb_device *dvbdev)
```

Remove a registered DVB device

**Parameters**

- `struct dvb_device *dvbdev`: pointer to struct dvb_device

**Description**

This does not free memory. `dvb_free_device()` will do that when
reference counter is empty

#### <a id="c-dvb_unregister_device"></a>`dvb_unregister_device()`

```c
void dvb_unregister_device(struct dvb_device *dvbdev)
```

Unregisters a DVB device

**Parameters**

- `struct dvb_device *dvbdev`: pointer to struct dvb_device

#### <a id="c-dvb_create_media_graph"></a>`dvb_create_media_graph()`

```c
int dvb_create_media_graph(struct dvb_adapter *adap, bool create_rf_connector)
```

Creates media graph for the Digital TV part of the device.

**Parameters**

- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](#c-struct-dvb_adapter)
- `bool create_rf_connector`: if true, it creates the RF connector too

**Description**

This function checks all DVB-related functions at the media controller
entities and creates the needed links for the media graph. It is
capable of working with multiple tuners or multiple frontends, but it
won't create links if the device has multiple tuners and multiple frontends
or if the device has multiple muxes. In such case, the caller driver should
manually create the remaining links.

#### <a id="c-dvb_register_media_controller"></a>`dvb_register_media_controller()`

```c
void dvb_register_media_controller(struct dvb_adapter *adap, struct media_device *mdev)
```

registers a media controller at DVB adapter

**Parameters**

- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](#c-struct-dvb_adapter)
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device)

#### <a id="c-dvb_get_media_controller"></a>`dvb_get_media_controller()`

```c
struct media_device * dvb_get_media_controller(struct dvb_adapter *adap)
```

gets the associated media controller

**Parameters**

- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](#c-struct-dvb_adapter)

#### <a id="c-dvb_generic_open"></a>`dvb_generic_open()`

```c
int dvb_generic_open(struct inode *inode, struct file *file)
```

Digital TV open function, used by DVB devices

**Parameters**

- `struct inode *inode`: pointer to `struct inode`.
- `struct file *file`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).

**Description**

Checks if a DVB devnode is still valid, and if the permissions are
OK and increment negative use count.

#### <a id="c-dvb_generic_release"></a>`dvb_generic_release()`

```c
int dvb_generic_release(struct inode *inode, struct file *file)
```

Digital TV close function, used by DVB devices

**Parameters**

- `struct inode *inode`: pointer to `struct inode`.
- `struct file *file`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).

**Description**

Checks if a DVB devnode is still valid, and if the permissions are
OK and decrement negative use count.

#### <a id="c-dvb_generic_ioctl"></a>`dvb_generic_ioctl()`

```c
long dvb_generic_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
```

Digital TV close function, used by DVB devices

**Parameters**

- `struct file *file`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long arg`: Ioctl argument.

**Description**

Checks if a DVB devnode and struct dvbdev.kernel_ioctl is still valid.
If so, calls [`dvb_usercopy()`](#c-dvb_usercopy).

#### <a id="c-dvb_usercopy"></a>`dvb_usercopy()`

```c
int dvb_usercopy(struct file *file, unsigned int cmd, unsigned long arg, int (*func)(struct file *file, unsigned int cmd, void *arg))
```

copies data from/to userspace memory when an ioctl is issued.

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long arg`: Ioctl argument.
- `int (*func)(struct file *file, unsigned int cmd, void *arg)`: function that will actually handle the ioctl

**Description**

Ancillary function that uses ioctl direction and size to copy from
userspace. Then, it calls **func**, and, if needed, data is copied back
to userspace.

#### <a id="c-dvb_module_probe"></a>`dvb_module_probe()`

```c
struct i2c_client * dvb_module_probe(const char *module_name, const char *name, struct i2c_adapter *adap, unsigned char addr, void *platform_data)
```

helper routine to probe an I2C module

**Parameters**

- `const char *module_name`: Name of the I2C module to be probed
- `const char *name`: Optional name for the I2C module. Used for debug purposes.
  If `NULL`, defaults to **module_name**.
- `struct i2c_adapter *adap`: pointer to `struct i2c_adapter` that describes the I2C adapter where
  the module will be bound.
- `unsigned char addr`: I2C address of the adapter, in 7-bit notation.
- `void *platform_data`: Platform data to be passed to the I2C module probed.

**Description**

This function binds an I2C device into the DVB core. Should be used by
all drivers that use I2C bus to control the hardware. A module bound
with [`dvb_module_probe()`](#c-dvb_module_probe) should use [`dvb_module_release()`](#c-dvb_module_release) to unbind.

> [!NOTE]
> In the past, DVB modules (mainly, frontends) were bound via [`dvb_attach()`](#c-dvb_attach)
> macro, with does an ugly hack, using I2C low level functions. Such
> usage is deprecated and will be removed soon. Instead, use this routine.

**Return**

On success, return an [`struct i2c_client`](/kernel/hardware/driver-api/buses/i2c.md#c-struct-i2c_client), pointing to the bound
I2C device. `NULL` otherwise.

#### <a id="c-dvb_module_release"></a>`dvb_module_release()`

```c
void dvb_module_release(struct i2c_client *client)
```

releases an I2C device allocated with [`dvb_module_probe()`](#c-dvb_module_probe).

**Parameters**

- `struct i2c_client *client`: pointer to [`struct i2c_client`](/kernel/hardware/driver-api/buses/i2c.md#c-struct-i2c_client) with the I2C client to be released.
  can be `NULL`.

**Description**

This function should be used to free all resources reserved by
[`dvb_module_probe()`](#c-dvb_module_probe) and unbinding the I2C hardware.

#### <a id="c-dvb_attach"></a>`dvb_attach()`

```c
dvb_attach(FUNCTION, ARGS...)
```

attaches a DVB frontend into the DVB core.

**Parameters**

- `FUNCTION`: function on a frontend module to be called.
- `ARGS...`:

  **FUNCTION** arguments.

**Description**

This ancillary function loads a frontend module in runtime and runs
the **FUNCTION** function there, with **ARGS**.
As it increments symbol usage cont, at unregister, [`dvb_detach()`](#c-dvb_detach)
should be called.

> [!NOTE]
> In the past, DVB modules (mainly, frontends) were bound via [`dvb_attach()`](#c-dvb_attach)
> macro, with does an ugly hack, using I2C low level functions. Such
> usage is deprecated and will be removed soon. Instead, you should use
> [`dvb_module_probe()`](#c-dvb_module_probe).

#### <a id="c-dvb_detach"></a>`dvb_detach()`

```c
dvb_detach(FUNC)
```

detaches a DVB frontend loaded via [`dvb_attach()`](#c-dvb_attach)

**Parameters**

- `FUNC`: attach function

**Description**

Decrements usage count for a function previously called via [`dvb_attach()`](#c-dvb_attach).


<a id="rst-digital-tv-ring-buffer"></a>

## Digital TV Ring buffer

Those routines implement ring buffers used to handle digital TV data and copy it from/to userspace.

> [!NOTE]
>
> 1. For performance reasons read and write routines don't check buffer sizes and/or number of bytes free/available. This has to be done before these routines are called. For example:
>
> >
> >
> > ```c
> > /* write @buflen: bytes */
> > free = dvb_ringbuffer_free(rbuf);
> > if (free >= buflen)
> >         count = dvb_ringbuffer_write(rbuf, buffer, buflen);
> > else
> >         /* do something */
> >
> > /* read min. 1000, max. @bufsize: bytes */
> > avail = dvb_ringbuffer_avail(rbuf);
> > if (avail >= 1000)
> >         count = dvb_ringbuffer_read(rbuf, buffer, min(avail, bufsize));
> > else
> >         /* do something */
> > ```
>
> 2. If there is exactly one reader and one writer, there is no need to lock read or write operations. Two or more readers must be locked against each other. Flushing the buffer counts as a read operation. Resetting the buffer counts as a read and write operation. Two or more writers must be locked against each other.


#### <a id="c-struct-dvb_ringbuffer"></a>`struct dvb_ringbuffer`

Describes a ring buffer used at DVB framework

**Definition**

```c
struct dvb_ringbuffer {
    u8 *data;
    ssize_t size;
    ssize_t pread;
    ssize_t pwrite;
    int error;
    wait_queue_head_t queue;
    spinlock_t lock;
};
```

**Members**

- `data`: Area were the ringbuffer data is written
- `size`: size of the ringbuffer
- `pread`: next position to read
- `pwrite`: next position to write
- `error`: used by ringbuffer clients to indicate that an error happened.
- `queue`: Wait queue used by ringbuffer clients to indicate when buffer
  was filled
- `lock`: Spinlock used to protect the ringbuffer

#### <a id="c-dvb_ringbuffer_init"></a>`dvb_ringbuffer_init()`

```c
void dvb_ringbuffer_init(struct dvb_ringbuffer *rbuf, void *data, size_t len)
```

initialize ring buffer, lock and queue

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `void *data`: pointer to the buffer where the data will be stored
- `size_t len`: bytes from ring buffer into **buf**

#### <a id="c-dvb_ringbuffer_empty"></a>`dvb_ringbuffer_empty()`

```c
int dvb_ringbuffer_empty(struct dvb_ringbuffer *rbuf)
```

test whether buffer is empty

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

#### <a id="c-dvb_ringbuffer_free"></a>`dvb_ringbuffer_free()`

```c
ssize_t dvb_ringbuffer_free(struct dvb_ringbuffer *rbuf)
```

returns the number of free bytes in the buffer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

**Return**

number of free bytes in the buffer

#### <a id="c-dvb_ringbuffer_avail"></a>`dvb_ringbuffer_avail()`

```c
ssize_t dvb_ringbuffer_avail(struct dvb_ringbuffer *rbuf)
```

returns the number of bytes waiting in the buffer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

**Return**

number of bytes waiting in the buffer

#### <a id="c-dvb_ringbuffer_reset"></a>`dvb_ringbuffer_reset()`

```c
void dvb_ringbuffer_reset(struct dvb_ringbuffer *rbuf)
```

resets the ringbuffer to initial state

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

**Description**

Resets the read and write pointers to zero and flush the buffer.

This counts as a read and write operation

#### <a id="c-dvb_ringbuffer_flush"></a>`dvb_ringbuffer_flush()`

```c
void dvb_ringbuffer_flush(struct dvb_ringbuffer *rbuf)
```

flush buffer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

#### <a id="c-dvb_ringbuffer_flush_spinlock_wakeup"></a>`dvb_ringbuffer_flush_spinlock_wakeup()`

```c
void dvb_ringbuffer_flush_spinlock_wakeup(struct dvb_ringbuffer *rbuf)
```

flush buffer protected by spinlock and wake-up waiting task(s)

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer

#### <a id="c-DVB_RINGBUFFER_PEEK"></a>`DVB_RINGBUFFER_PEEK()`

```c
DVB_RINGBUFFER_PEEK(rbuf, offs)
```

peek at byte **offs** in the buffer

**Parameters**

- `rbuf`: pointer to struct dvb_ringbuffer
- `offs`: offset inside the ringbuffer

#### <a id="c-DVB_RINGBUFFER_SKIP"></a>`DVB_RINGBUFFER_SKIP()`

```c
DVB_RINGBUFFER_SKIP(rbuf, num)
```

advance read ptr by **num** bytes

**Parameters**

- `rbuf`: pointer to struct dvb_ringbuffer
- `num`: number of bytes to advance

#### <a id="c-dvb_ringbuffer_read_user"></a>`dvb_ringbuffer_read_user()`

```c
ssize_t dvb_ringbuffer_read_user(struct dvb_ringbuffer *rbuf, u8 __user *buf, size_t len)
```

Reads a buffer into a user pointer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `u8 __user *buf`: pointer to the buffer where the data will be stored
- `size_t len`: bytes from ring buffer into **buf**

**Description**

This variant assumes that the buffer is a memory at the userspace. So,
it will internally call `copy_to_user()`.

**Return**

number of bytes transferred or -EFAULT

#### <a id="c-dvb_ringbuffer_read"></a>`dvb_ringbuffer_read()`

```c
void dvb_ringbuffer_read(struct dvb_ringbuffer *rbuf, u8 *buf, size_t len)
```

Reads a buffer into a pointer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `u8 *buf`: pointer to the buffer where the data will be stored
- `size_t len`: bytes from ring buffer into **buf**

**Description**

This variant assumes that the buffer is a memory at the Kernel space

**Return**

number of bytes transferred or -EFAULT

#### <a id="c-DVB_RINGBUFFER_WRITE_BYTE"></a>`DVB_RINGBUFFER_WRITE_BYTE()`

```c
DVB_RINGBUFFER_WRITE_BYTE(rbuf, byte)
```

write single byte to ring buffer

**Parameters**

- `rbuf`: pointer to struct dvb_ringbuffer
- `byte`: byte to write

#### <a id="c-dvb_ringbuffer_write"></a>`dvb_ringbuffer_write()`

```c
ssize_t dvb_ringbuffer_write(struct dvb_ringbuffer *rbuf, const u8 *buf, size_t len)
```

Writes a buffer into the ringbuffer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `const u8 *buf`: pointer to the buffer where the data will be read
- `size_t len`: bytes from ring buffer into **buf**

**Description**

This variant assumes that the buffer is a memory at the Kernel space

**Return**

number of bytes transferred or -EFAULT

#### <a id="c-dvb_ringbuffer_write_user"></a>`dvb_ringbuffer_write_user()`

```c
ssize_t dvb_ringbuffer_write_user(struct dvb_ringbuffer *rbuf, const u8 __user *buf, size_t len)
```

Writes a buffer received via a user pointer

**Parameters**

- `struct dvb_ringbuffer *rbuf`: pointer to struct dvb_ringbuffer
- `const u8 __user *buf`: pointer to the buffer where the data will be read
- `size_t len`: bytes from ring buffer into **buf**

**Description**

This variant assumes that the buffer is a memory at the userspace. So,
it will internally call `copy_from_user()`.

**Return**

number of bytes transferred or -EFAULT

#### <a id="c-dvb_ringbuffer_pkt_write"></a>`dvb_ringbuffer_pkt_write()`

```c
ssize_t dvb_ringbuffer_pkt_write(struct dvb_ringbuffer *rbuf, u8 *buf, size_t len)
```

Write a packet into the ringbuffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ringbuffer to write to.
- `u8 *buf`: Buffer to write.
- `size_t len`: Length of buffer (currently limited to 65535 bytes max).

**Return**

Number of bytes written, or -EFAULT, -ENOMEM, -EINVAL.

#### <a id="c-dvb_ringbuffer_pkt_read_user"></a>`dvb_ringbuffer_pkt_read_user()`

```c
ssize_t dvb_ringbuffer_pkt_read_user(struct dvb_ringbuffer *rbuf, size_t idx, int offset, u8 __user *buf, size_t len)
```

Read from a packet in the ringbuffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ringbuffer concerned.
- `size_t idx`: Packet index as returned by [`dvb_ringbuffer_pkt_next()`](#c-dvb_ringbuffer_pkt_next).
- `int offset`: Offset into packet to read from.
- `u8 __user *buf`: Destination buffer for data.
- `size_t len`: Size of destination buffer.

**Return**

Number of bytes read, or -EFAULT.

**Description**

> [!NOTE]
> unlike [`dvb_ringbuffer_read()`](#c-dvb_ringbuffer_read), this does **NOT** update the read pointer
> in the ringbuffer. You must use [`dvb_ringbuffer_pkt_dispose()`](#c-dvb_ringbuffer_pkt_dispose) to mark a
> packet as no longer required.

#### <a id="c-dvb_ringbuffer_pkt_read"></a>`dvb_ringbuffer_pkt_read()`

```c
ssize_t dvb_ringbuffer_pkt_read(struct dvb_ringbuffer *rbuf, size_t idx, int offset, u8 *buf, size_t len)
```

Read from a packet in the ringbuffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ringbuffer concerned.
- `size_t idx`: Packet index as returned by [`dvb_ringbuffer_pkt_next()`](#c-dvb_ringbuffer_pkt_next).
- `int offset`: Offset into packet to read from.
- `u8 *buf`: Destination buffer for data.
- `size_t len`: Size of destination buffer.

**Note**

unlike [`dvb_ringbuffer_read_user()`](#c-dvb_ringbuffer_read_user), this DOES update the read pointer
in the ringbuffer.

**Return**

Number of bytes read, or -EFAULT.

#### <a id="c-dvb_ringbuffer_pkt_dispose"></a>`dvb_ringbuffer_pkt_dispose()`

```c
void dvb_ringbuffer_pkt_dispose(struct dvb_ringbuffer *rbuf, size_t idx)
```

Dispose of a packet in the ring buffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ring buffer concerned.
- `size_t idx`: Packet index as returned by [`dvb_ringbuffer_pkt_next()`](#c-dvb_ringbuffer_pkt_next).

#### <a id="c-dvb_ringbuffer_pkt_next"></a>`dvb_ringbuffer_pkt_next()`

```c
ssize_t dvb_ringbuffer_pkt_next(struct dvb_ringbuffer *rbuf, size_t idx, size_t *pktlen)
```

Get the index of the next packet in a ringbuffer.

**Parameters**

- `struct dvb_ringbuffer *rbuf`: Ringbuffer concerned.
- `size_t idx`: Previous packet index, or -1 to return the first packet index.
- `size_t *pktlen`: On success, will be updated to contain the length of the packet
  in bytes.
  returns Packet index (if >=0), or -1 if no packets available.


<a id="rst-digital-tv-vb2-handler"></a>

## Digital TV VB2 handler


#### <a id="c-enum-dvb_buf_type"></a>`enum dvb_buf_type`

types of Digital TV memory-mapped buffers

**Constants**

- `DVB_BUF_TYPE_CAPTURE`: buffer is filled by the Kernel,
  with a received Digital TV stream

#### <a id="c-enum-dvb_vb2_states"></a>`enum dvb_vb2_states`

states to control VB2 state machine

**Constants**

- `DVB_VB2_STATE_NONE`: VB2 engine not initialized yet, init failed or VB2 was released.
- `DVB_VB2_STATE_INIT`: VB2 engine initialized.
- `DVB_VB2_STATE_REQBUFS`: Buffers were requested
- `DVB_VB2_STATE_STREAMON`: VB2 is streaming. Callers should not check it directly. Instead,
  they should use [`dvb_vb2_is_streaming()`](#c-dvb_vb2_is_streaming).

**Note**

Callers should not touch at the state machine directly. This
is handled inside dvb_vb2.c.

#### <a id="c-struct-dvb_buffer"></a>`struct dvb_buffer`

video buffer information for v4l2.

**Definition**

```c
struct dvb_buffer {
    struct vb2_buffer       vb;
    struct list_head        list;
};
```

**Members**

- `vb`: embedded struct [`vb2_buffer`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_buffer).
- `list`: list of [`struct dvb_buffer`](#c-struct-dvb_buffer).

#### <a id="c-struct-dvb_vb2_ctx"></a>`struct dvb_vb2_ctx`

control struct for VB2 handler

**Definition**

```c
struct dvb_vb2_ctx {
    struct vb2_queue        vb_q;
    spinlock_t slock;
    struct list_head        dvb_q;
    struct dvb_buffer       *buf;
    int offset;
    int remain;
    int state;
    int buf_siz;
    int buf_cnt;
    int nonblocking;
    enum dmx_buffer_flags flags;
    u32 count;
    char name[DVB_VB2_NAME_MAX + 1];
};
```

**Members**

- `vb_q`: pointer to [`struct vb2_queue`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_queue) with videobuf2 queue.
- `slock`: spin lock used to protect buffer filling at dvb_vb2.c.
- `dvb_q`: List of buffers that are not filled yet.
- `buf`: Pointer to the buffer that are currently being filled.
- `offset`: index to the next position at the **buf** to be filled.
- `remain`: How many bytes are left to be filled at **buf**.
- `state`: bitmask of buffer states as defined by [`enum dvb_vb2_states`](#c-enum-dvb_vb2_states).
- `buf_siz`: size of each VB2 buffer.
- `buf_cnt`: number of VB2 buffers.
- `nonblocking`: If different than zero, device is operating on non-blocking
  mode.
- `flags`: buffer flags as defined by [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).
  Filled only at `DMX_DQBUF`. `DMX_QBUF` should zero this field.
- `count`: monotonic counter for filled buffers. Helps to identify
  data stream loses. Filled only at `DMX_DQBUF`. `DMX_QBUF` should
  zero this field.
- `name`: name of the device type. Currently, it can either be
  "dvr" or "demux_filter".

#### <a id="c-dvb_vb2_init"></a>`dvb_vb2_init()`

```c
int dvb_vb2_init(struct dvb_vb2_ctx *ctx, const char *name, struct mutex *mutex, int non_blocking)
```

initializes VB2 handler

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `const char *name`: name for the VB2 handler
- `struct mutex *mutex`: pointer to the mutex that serializes vb2 ioctls
- `int non_blocking`: if not zero, it means that the device is at non-blocking mode

#### <a id="c-dvb_vb2_release"></a>`dvb_vb2_release()`

```c
int dvb_vb2_release(struct dvb_vb2_ctx *ctx)
```

Releases the VB2 handler allocated resources and put **ctx** at DVB_VB2_STATE_NONE state.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler

#### <a id="c-dvb_vb2_is_streaming"></a>`dvb_vb2_is_streaming()`

```c
int dvb_vb2_is_streaming(struct dvb_vb2_ctx *ctx)
```

checks if the VB2 handler is streaming

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler

**Return**

0 if not streaming, 1 otherwise.

#### <a id="c-dvb_vb2_fill_buffer"></a>`dvb_vb2_fill_buffer()`

```c
int dvb_vb2_fill_buffer(struct dvb_vb2_ctx *ctx, const unsigned char *src, int len, enum dmx_buffer_flags *buffer_flags, bool flush)
```

fills a VB2 buffer

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `const unsigned char *src`: place where the data is stored
- `int len`: number of bytes to be copied from **src**
- `enum dmx_buffer_flags *buffer_flags`: pointer to buffer flags as defined by [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).
  can be NULL.
- `bool flush`: flush the buffer, even if it isn't full.

#### <a id="c-dvb_vb2_poll"></a>`dvb_vb2_poll()`

```c
__poll_t dvb_vb2_poll(struct dvb_vb2_ctx *ctx, struct file *file, poll_table *wait)
```

Wrapper to [`vb2_core_streamon()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_streamon) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct file *file`: [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) argument passed to the poll
  file operation handler.
- `poll_table *wait`: `poll_table` wait argument passed to the poll
  file operation handler.

**Description**

Implements poll `syscall()` logic.

#### <a id="c-dvb_vb2_stream_on"></a>`dvb_vb2_stream_on()`

```c
int dvb_vb2_stream_on(struct dvb_vb2_ctx *ctx)
```

Wrapper to [`vb2_core_streamon()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_streamon) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler

**Description**

Starts dvb streaming

#### <a id="c-dvb_vb2_stream_off"></a>`dvb_vb2_stream_off()`

```c
int dvb_vb2_stream_off(struct dvb_vb2_ctx *ctx)
```

Wrapper to [`vb2_core_streamoff()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_streamoff) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler

**Description**

Stops dvb streaming

#### <a id="c-dvb_vb2_reqbufs"></a>`dvb_vb2_reqbufs()`

```c
int dvb_vb2_reqbufs(struct dvb_vb2_ctx *ctx, struct dmx_requestbuffers *req)
```

Wrapper to [`vb2_core_reqbufs()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_reqbufs) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_requestbuffers *req`: [`struct dmx_requestbuffers`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_requestbuffers) passed from userspace in
  order to handle `DMX_REQBUFS`.

**Description**

Initiate streaming by requesting a number of buffers. Also used to
free previously requested buffers, is `req->count` is zero.

#### <a id="c-dvb_vb2_querybuf"></a>`dvb_vb2_querybuf()`

```c
int dvb_vb2_querybuf(struct dvb_vb2_ctx *ctx, struct dmx_buffer *b)
```

Wrapper to [`vb2_core_querybuf()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_querybuf) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_buffer *b`: [`struct dmx_buffer`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_buffer) passed from userspace in
  order to handle `DMX_QUERYBUF`.

#### <a id="c-dvb_vb2_expbuf"></a>`dvb_vb2_expbuf()`

```c
int dvb_vb2_expbuf(struct dvb_vb2_ctx *ctx, struct dmx_exportbuffer *exp)
```

Wrapper to [`vb2_core_expbuf()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_expbuf) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_exportbuffer *exp`: [`struct dmx_exportbuffer`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_exportbuffer) passed from userspace in
  order to handle `DMX_EXPBUF`.

**Description**

Export a buffer as a file descriptor.

#### <a id="c-dvb_vb2_qbuf"></a>`dvb_vb2_qbuf()`

```c
int dvb_vb2_qbuf(struct dvb_vb2_ctx *ctx, struct dmx_buffer *b)
```

Wrapper to [`vb2_core_qbuf()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_qbuf) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_buffer *b`: [`struct dmx_buffer`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_buffer) passed from userspace in
  order to handle `DMX_QBUF`.

**Description**

Queue a Digital TV buffer as requested by userspace

#### <a id="c-dvb_vb2_dqbuf"></a>`dvb_vb2_dqbuf()`

```c
int dvb_vb2_dqbuf(struct dvb_vb2_ctx *ctx, struct dmx_buffer *b)
```

Wrapper to [`vb2_core_dqbuf()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_core_dqbuf) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct dmx_buffer *b`: [`struct dmx_buffer`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_buffer) passed from userspace in
  order to handle `DMX_DQBUF`.

**Description**

Dequeue a Digital TV buffer to the userspace

#### <a id="c-dvb_vb2_mmap"></a>`dvb_vb2_mmap()`

```c
int dvb_vb2_mmap(struct dvb_vb2_ctx *ctx, struct vm_area_struct *vma)
```

Wrapper to [`vb2_mmap()`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-vb2_mmap) for Digital TV buffer handling.

**Parameters**

- `struct dvb_vb2_ctx *ctx`: control struct for VB2 handler
- `struct vm_area_struct *vma`: pointer to `struct vm_area_struct` with the vma passed
  to the mmap file operation handler in the driver.

**Description**

map Digital TV video buffers into application address space.

---

# Digital TV (DVB) devices

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Digital TV devices are implemented by several different drivers:

<a id="rst-digital-tv-dvb-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Digital TV devices are implemented by several different drivers:

- A bridge driver that is responsible to talk with the bus where the other devices are connected (PCI, USB, SPI), bind to the other drivers and implement the digital demux logic (either in software or in hardware);

- Frontend drivers that are usually implemented as two separate drivers:

  - A tuner driver that implements the logic which commands the part of the hardware responsible for tuning into a digital TV transponder or physical channel. The output of a tuner is usually a baseband or Intermediate Frequency (IF) signal;

  - A demodulator driver (a.k.a "demod") that implements the logic which commands the digital TV decoding hardware. The output of a demod is a digital stream, with multiple audio, video and data channels typically multiplexed using MPEG Transport Stream <a id="rst-footnote-reference-1"></a>[1](#rst-f1).

On most hardware, the frontend drivers talk with the bridge driver using an I2C bus.

<a id="rst-f1"></a>



**[1]** Some standards use TCP/IP for multiplexing data, like DVB-H (an abandoned standard, not used anymore) and ATSC version 3.0 current proposals. Currently, the DVB subsystem doesn't implement those standards.

- [Digital TV Common functions](</kernel/hardware/driver-api/media/dtv-common.md>)
- [Digital TV Frontend kABI](</kernel/hardware/driver-api/media/dtv-frontend.md>)
- [Digital TV Demux kABI](</kernel/hardware/driver-api/media/dtv-demux.md>)
- [Digital TV Conditional Access kABI](</kernel/hardware/driver-api/media/dtv-ca.md>)
- [Digital TV Network kABI](</kernel/hardware/driver-api/media/dtv-net.md>)

---

# Digital TV Demux kABI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The Kernel Digital TV Demux kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent demux layer. It is only of interest for Digital TV device driver writers. The header file…

<a id="rst-digital-tv-demux-kabi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-digital-tv-demux"></a>

## Digital TV Demux

The Kernel Digital TV Demux kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent demux layer. It is only of interest for Digital TV device driver writers. The header file for this kABI is named `demux.h` and located in `include/media`.

The demux kABI should be implemented for each demux in the system. It is used to select the TS source of a demux and to manage the demux resources. When the demux client allocates a resource via the demux kABI, it receives a pointer to the kABI of that resource.

Each demux receives its TS input from a DVB front-end or from memory, as set via this demux kABI. In a system with more than one front-end, the kABI can be used to select one of the DVB front-ends as a TS source for a demux, unless this is fixed in the HW platform.

The demux kABI only controls front-ends regarding to their connections with demuxes; the kABI used to set the other front-end parameters, such as tuning, are defined via the Digital TV Frontend kABI.

The functions that implement the abstract interface demux should be defined static or module private and registered to the Demux core for external access. It is not necessary to implement every function in the struct `dmx_demux`. For example, a demux interface might support Section filtering, but not PES filtering. The kABI client is expected to check the value of any function pointer before calling the function: the value of `NULL` means that the function is not available.

Whenever the functions of the demux API modify shared data, the possibilities of lost update and race condition problems should be addressed, e.g. by protecting parts of code with mutexes.

Note that functions called from a bottom half context must not sleep. Even a simple memory allocation without using `GFP_ATOMIC` can result in a kernel thread being put to sleep if swapping is needed. For example, the Linux Kernel calls the functions of a network device interface from a bottom half context. Thus, if a demux kABI function is called from network device code, the function must not sleep.

<a id="rst-demux-callback-api"></a>

## Demux Callback API

This kernel-space API comprises the callback functions that deliver filtered data to the demux client. Unlike the other DVB kABIs, these functions are provided by the client and called from the demux code.

The function pointers of this abstract interface are not packed into a structure as in the other demux APIs, because the callback functions are registered and used independent of each other. As an example, it is possible for the API client to provide several callback functions for receiving TS packets and no callbacks for PES packets or sections.

The functions that implement the callback API need not be re-entrant: when a demux driver calls one of these functions, the driver is not allowed to call the function again before the original call returns. If a callback is triggered by a hardware interrupt, it is recommended to use the Linux bottom half mechanism or start a tasklet instead of making the callback function call directly from a hardware interrupt.

This mechanism is implemented by `dmx_ts_cb()` and `dmx_section_cb()` callbacks.

<a id="rst-digital-tv-demux-device-registration-functions-and-data-structures"></a>

## Digital TV Demux device registration functions and data structures


#### <a id="c-enum-dmxdev_type"></a>`enum dmxdev_type`

type of demux filter type.

**Constants**

- `DMXDEV_TYPE_NONE`: no filter set.
- `DMXDEV_TYPE_SEC`: section filter.
- `DMXDEV_TYPE_PES`: Program Elementary Stream (PES) filter.

#### <a id="c-enum-dmxdev_state"></a>`enum dmxdev_state`

state machine for the dmxdev.

**Constants**

- `DMXDEV_STATE_FREE`: indicates that the filter is freed.
- `DMXDEV_STATE_ALLOCATED`: indicates that the filter was allocated
  to be used.
- `DMXDEV_STATE_SET`: indicates that the filter parameters are set.
- `DMXDEV_STATE_GO`: indicates that the filter is running.
- `DMXDEV_STATE_DONE`: indicates that a packet was already filtered
  and the filter is now disabled.
  Set only if `DMX_ONESHOT`. See
  [`dmx_sct_filter_params`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_sct_filter_params).
- `DMXDEV_STATE_TIMEDOUT`: Indicates a timeout condition.

#### <a id="c-struct-dmxdev_feed"></a>`struct dmxdev_feed`

digital TV dmxdev feed

**Definition**

```c
struct dmxdev_feed {
    u16 pid;
    struct dmx_ts_feed *ts;
    struct list_head next;
};
```

**Members**

- `pid`: Program ID to be filtered
- `ts`: pointer to [`struct dmx_ts_feed`](#c-struct-dmx_ts_feed)
- `next`: `struct list_head` pointing to the next feed.

#### <a id="c-struct-dmxdev_filter"></a>`struct dmxdev_filter`

digital TV dmxdev filter

**Definition**

```c
struct dmxdev_filter {
    union {
        struct dmx_section_filter *sec;
    } filter;
    union {
        struct list_head ts;
        struct dmx_section_feed *sec;
    } feed;
    union {
        struct dmx_sct_filter_params sec;
        struct dmx_pes_filter_params pes;
    } params;
    enum dmxdev_type type;
    enum dmxdev_state state;
    struct dmxdev *dev;
    struct dvb_ringbuffer buffer;
    struct dvb_vb2_ctx vb2_ctx;
    struct mutex mutex;
    struct timer_list timer;
    int todo;
    u8 secheader[3];
};
```

**Members**

- `filter`: a union describing a dmxdev filter.
  Currently used only for section filters.
- `filter.sec`: a [`struct dmx_section_filter`](#c-struct-dmx_section_filter) pointer.
  For section filter only.
- `feed`: a union describing a dmxdev feed.
  Depending on the filter type, it can be either
  **feed.ts** or **feed.sec**.
- `feed.ts`: a `struct list_head` list.
  For TS and PES feeds.
- `feed.sec`: a [`struct dmx_section_feed`](#c-struct-dmx_section_feed) pointer.
  For section feed only.
- `params`: a union describing dmxdev filter parameters.
  Depending on the filter type, it can be either
  **params.sec** or **params.pes**.
- `params.sec`: a [`struct dmx_sct_filter_params`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_sct_filter_params) embedded struct.
  For section filter only.
- `params.pes`: a [`struct dmx_pes_filter_params`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-struct-dmx_pes_filter_params) embedded struct.
  For PES filter only.
- `type`: type of the dmxdev filter, as defined by [`enum dmxdev_type`](#c-enum-dmxdev_type).
- `state`: state of the dmxdev filter, as defined by [`enum dmxdev_state`](#c-enum-dmxdev_state).
- `dev`: pointer to [`struct dmxdev`](#c-struct-dmxdev).
- `buffer`: an embedded [`struct dvb_ringbuffer`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_ringbuffer) buffer.
- `vb2_ctx`: control struct for VB2 handler
- `mutex`: protects the access to [`struct dmxdev_filter`](#c-struct-dmxdev_filter).
- `timer`: `struct timer_list` embedded timer, used to check for
  feed timeouts.
  Only for section filter.
- `todo`: index for the **secheader**.
  Only for section filter.
- `secheader`: buffer cache to parse the section header.
  Only for section filter.

#### <a id="c-struct-dmxdev"></a>`struct dmxdev`

Describes a digital TV demux device.

**Definition**

```c
struct dmxdev {
        struct dvb_device *dvbdev;
        struct dvb_device *dvr_dvbdev;
        struct dmxdev_filter *filter;
        struct dmx_demux *demux;
        int filternum;
        int capabilities;
        unsigned int may_do_mmap:1;
        unsigned int exit:1;
    #define DMXDEV_CAP_DUPLEX 1;
        struct dmx_frontend *dvr_orig_fe;
        struct dvb_ringbuffer dvr_buffer;
    #define DVR_BUFFER_SIZE (10*188*1024);
        struct dvb_vb2_ctx dvr_vb2_ctx;
        struct mutex mutex;
        spinlock_t lock;
};
```

**Members**

- `dvbdev`: pointer to [`struct dvb_device`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_device) associated with
  the demux device node.
- `dvr_dvbdev`: pointer to [`struct dvb_device`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_device) associated with
  the dvr device node.
- `filter`: pointer to [`struct dmxdev_filter`](#c-struct-dmxdev_filter).
- `demux`: pointer to [`struct dmx_demux`](#c-struct-dmx_demux).
- `filternum`: number of filters.
- `capabilities`: demux capabilities as defined by [`enum dmx_demux_caps`](#c-enum-dmx_demux_caps).
- `may_do_mmap`: flag used to indicate if the device may do mmap.
- `exit`: flag to indicate that the demux is being released.
- `dvr_orig_fe`: pointer to [`struct dmx_frontend`](#c-struct-dmx_frontend).
- `dvr_buffer`: embedded [`struct dvb_ringbuffer`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_ringbuffer) for DVB output.
- `dvr_vb2_ctx`: control struct for VB2 handler
- `mutex`: protects the usage of this structure.
- `lock`: protects access to [`dmxdev->filter`](#c-struct-dmxdev)->data.

#### <a id="c-dvb_dmxdev_init"></a>`dvb_dmxdev_init()`

```c
int dvb_dmxdev_init(struct dmxdev *dmxdev, struct dvb_adapter *adap)
```

initializes a digital TV demux and registers both demux and DVR devices.

**Parameters**

- `struct dmxdev *dmxdev`: pointer to [`struct dmxdev`](#c-struct-dmxdev).
- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_adapter).

#### <a id="c-dvb_dmxdev_release"></a>`dvb_dmxdev_release()`

```c
void dvb_dmxdev_release(struct dmxdev *dmxdev)
```

releases a digital TV demux and unregisters it.

**Parameters**

- `struct dmxdev *dmxdev`: pointer to [`struct dmxdev`](#c-struct-dmxdev).


<a id="rst-high-level-digital-tv-demux-interface"></a>

## High-level Digital TV demux interface


#### <a id="c-enum-dvb_dmx_filter_type"></a>`enum dvb_dmx_filter_type`

type of demux feed.

**Constants**

- `DMX_TYPE_TS`: feed is in TS mode.
- `DMX_TYPE_SEC`: feed is in Section mode.

#### <a id="c-enum-dvb_dmx_state"></a>`enum dvb_dmx_state`

state machine for a demux filter.

**Constants**

- `DMX_STATE_FREE`: indicates that the filter is freed.
- `DMX_STATE_ALLOCATED`: indicates that the filter was allocated
  to be used.
- `DMX_STATE_READY`: indicates that the filter is ready
  to be used.
- `DMX_STATE_GO`: indicates that the filter is running.

#### <a id="c-struct-dvb_demux_filter"></a>`struct dvb_demux_filter`

Describes a DVB demux section filter.

**Definition**

```c
struct dvb_demux_filter {
    struct dmx_section_filter filter;
    u8 maskandmode[DMX_MAX_FILTER_SIZE];
    u8 maskandnotmode[DMX_MAX_FILTER_SIZE];
    bool doneq;
    struct dvb_demux_filter *next;
    struct dvb_demux_feed *feed;
    int index;
    enum dvb_dmx_state state;
    enum dvb_dmx_filter_type type;
};
```

**Members**

- `filter`: Section filter as defined by [`struct dmx_section_filter`](#c-struct-dmx_section_filter).
- `maskandmode`: logical `and` bit mask.
- `maskandnotmode`: logical `and not` bit mask.
- `doneq`: flag that indicates when a filter is ready.
- `next`: pointer to the next section filter.
- `feed`: [`struct dvb_demux_feed`](#c-struct-dvb_demux_feed) pointer.
- `index`: index of the used demux filter.
- `state`: state of the filter as described by [`enum dvb_dmx_state`](#c-enum-dvb_dmx_state).
- `type`: type of the filter as described
  by [`enum dvb_dmx_filter_type`](#c-enum-dvb_dmx_filter_type).

#### <a id="c-struct-dvb_demux_feed"></a>`struct dvb_demux_feed`

describes a DVB field

**Definition**

```c
struct dvb_demux_feed {
    union {
        struct dmx_ts_feed ts;
        struct dmx_section_feed sec;
    } feed;
    union {
        dmx_ts_cb ts;
        dmx_section_cb sec;
    } cb;
    struct dvb_demux *demux;
    void *priv;
    enum dvb_dmx_filter_type type;
    enum dvb_dmx_state state;
    u16 pid;
    ktime_t timeout;
    struct dvb_demux_filter *filter;
    u32 buffer_flags;
    enum ts_filter_type ts_type;
    enum dmx_ts_pes pes_type;
    int cc;
    bool pusi_seen;
    u16 peslen;
    struct list_head list_head;
    unsigned int index;
};
```

**Members**

- `feed`: a union describing a digital TV feed.
  Depending on the feed type, it can be either
  **feed.ts** or **feed.sec**.
- `feed.ts`: a [`struct dmx_ts_feed`](#c-struct-dmx_ts_feed) pointer.
  For TS feed only.
- `feed.sec`: a [`struct dmx_section_feed`](#c-struct-dmx_section_feed) pointer.
  For section feed only.
- `cb`: a union describing digital TV callbacks.
  Depending on the feed type, it can be either
  **cb.ts** or **cb.sec**.
- `cb.ts`: a [`dmx_ts_cb()`](#c-dmx_ts_cb) calback function pointer.
  For TS feed only.
- `cb.sec`: a [`dmx_section_cb()`](#c-dmx_section_cb) callback function pointer.
  For section feed only.
- `demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux).
- `priv`: private data that can optionally be used by a DVB driver.
- `type`: type of the filter, as defined by [`enum dvb_dmx_filter_type`](#c-enum-dvb_dmx_filter_type).
- `state`: state of the filter as defined by [`enum dvb_dmx_state`](#c-enum-dvb_dmx_state).
- `pid`: PID to be filtered.
- `timeout`: feed timeout.
- `filter`: pointer to [`struct dvb_demux_filter`](#c-struct-dvb_demux_filter).
- `buffer_flags`: Buffer flags used to report discontinuity users via DVB
  memory mapped API, as defined by [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).
- `ts_type`: type of TS, as defined by [`enum ts_filter_type`](#c-enum-ts_filter_type).
- `pes_type`: type of PES, as defined by [`enum dmx_ts_pes`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_ts_pes).
- `cc`: MPEG-TS packet continuity counter
- `pusi_seen`: if true, indicates that a discontinuity was detected.
  it is used to prevent feeding of garbage from previous section.
- `peslen`: length of the PES (Packet Elementary Stream).
- `list_head`: head for the list of digital TV demux feeds.
- `index`: a unique index for each feed. Can be used as hardware
  pid filter index.

#### <a id="c-struct-dvb_demux"></a>`struct dvb_demux`

represents a digital TV demux

**Definition**

```c
struct dvb_demux {
        struct dmx_demux dmx;
        void *priv;
        int filternum;
        int feednum;
        int (*start_feed)(struct dvb_demux_feed *feed);
        int (*stop_feed)(struct dvb_demux_feed *feed);
        int (*write_to_decoder)(struct dvb_demux_feed *feed, const u8 *buf, size_t len);
        u32 (*check_crc32)(struct dvb_demux_feed *feed, const u8 *buf, size_t len);
        void (*memcopy)(struct dvb_demux_feed *feed, u8 *dst, const u8 *src, size_t len);
        int users;
    #define MAX_DVB_DEMUX_USERS 10;
        struct dvb_demux_filter *filter;
        struct dvb_demux_feed *feed;
        struct list_head frontend_list;
        struct dvb_demux_feed *pesfilter[DMX_PES_OTHER];
        u16 pids[DMX_PES_OTHER];
    #define DMX_MAX_PID 0x2000;
        struct list_head feed_list;
        u8 tsbuf[204];
        int tsbufp;
        struct mutex mutex;
        spinlock_t lock;
        uint8_t *cnt_storage;
        ktime_t speed_last_time;
        uint32_t speed_pkts_cnt;
};
```

**Members**

- `dmx`: embedded [`struct dmx_demux`](#c-struct-dmx_demux) with demux capabilities
  and callbacks.
- `priv`: private data that can optionally be used by
  a DVB driver.
- `filternum`: maximum amount of DVB filters.
- `feednum`: maximum amount of DVB feeds.
- `start_feed`: callback routine to be called in order to start
  a DVB feed.
- `stop_feed`: callback routine to be called in order to stop
  a DVB feed.
- `write_to_decoder`: callback routine to be called if the feed is TS and
  it is routed to an A/V decoder, when a new TS packet
  is received.
  Used only on av7110-av.c.
- `check_crc32`: callback routine to check CRC. If not initialized,
  dvb_demux will use an internal one.
- `memcopy`: callback routine to memcopy received data.
  If not initialized, dvb_demux will default to [`memcpy()`](/kernel/internals/core-api/kernel-api.md#c-memcpy).
- `users`: counter for the number of demux opened file descriptors.
  Currently, it is limited to 10 users.
- `filter`: pointer to [`struct dvb_demux_filter`](#c-struct-dvb_demux_filter).
- `feed`: pointer to [`struct dvb_demux_feed`](#c-struct-dvb_demux_feed).
- `frontend_list`: `struct list_head` with frontends used by the demux.
- `pesfilter`: array of [`struct dvb_demux_feed`](#c-struct-dvb_demux_feed) with the PES types
  that will be filtered.
- `pids`: list of filtered program IDs.
- `feed_list`: `struct list_head` with feeds.
- `tsbuf`: temporary buffer used internally to store TS packets.
- `tsbufp`: temporary buffer index used internally.
- `mutex`: pointer to `struct mutex` used to protect feed set
  logic.
- `lock`: pointer to `spinlock_t`, used to protect buffer handling.
- `cnt_storage`: buffer used for TS/TEI continuity check.
- `speed_last_time`: `ktime_t` used for TS speed check.
- `speed_pkts_cnt`: packets count used for TS speed check.

#### <a id="c-dvb_dmx_init"></a>`dvb_dmx_init()`

```c
int dvb_dmx_init(struct dvb_demux *demux)
```

initialize a digital TV demux struct.

**Parameters**

- `struct dvb_demux *demux`: [`struct dvb_demux`](#c-struct-dvb_demux) to be initialized.

**Description**

Before being able to register a digital TV demux struct, drivers
should call this routine. On its typical usage, some fields should
be initialized at the driver before calling it.

A typical usecase is:

```text
dvb->demux.dmx.capabilities =
        DMX_TS_FILTERING | DMX_SECTION_FILTERING |
        DMX_MEMORY_BASED_FILTERING;
dvb->demux.priv       = dvb;
dvb->demux.filternum  = 256;
dvb->demux.feednum    = 256;
dvb->demux.start_feed = driver_start_feed;
dvb->demux.stop_feed  = driver_stop_feed;
ret = dvb_dmx_init(&dvb->demux);
if (ret < 0)
        return ret;
```

#### <a id="c-dvb_dmx_release"></a>`dvb_dmx_release()`

```c
void dvb_dmx_release(struct dvb_demux *demux)
```

releases a digital TV demux internal buffers.

**Parameters**

- `struct dvb_demux *demux`: [`struct dvb_demux`](#c-struct-dvb_demux) to be released.

**Description**

The DVB core internally allocates data at **demux**. This routine
releases those data. Please notice that the struct itelf is not
released, as it can be embedded on other structs.

#### <a id="c-dvb_dmx_swfilter_packets"></a>`dvb_dmx_swfilter_packets()`

```c
void dvb_dmx_swfilter_packets(struct dvb_demux *demux, const u8 *buf, size_t count)
```

use dvb software filter for a buffer with multiple MPEG-TS packets with 188 bytes each.

**Parameters**

- `struct dvb_demux *demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux)
- `const u8 *buf`: buffer with data to be filtered
- `size_t count`: number of MPEG-TS packets with size of 188.

**Description**

The routine will discard a DVB packet that don't start with 0x47.

Use this routine if the DVB demux fills MPEG-TS buffers that are
already aligned.

**NOTE**

The **buf** size should have size equal to `count * 188`.

#### <a id="c-dvb_dmx_swfilter"></a>`dvb_dmx_swfilter()`

```c
void dvb_dmx_swfilter(struct dvb_demux *demux, const u8 *buf, size_t count)
```

use dvb software filter for a buffer with multiple MPEG-TS packets with 188 bytes each.

**Parameters**

- `struct dvb_demux *demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux)
- `const u8 *buf`: buffer with data to be filtered
- `size_t count`: number of MPEG-TS packets with size of 188.

**Description**

If a DVB packet doesn't start with 0x47, it will seek for the first
byte that starts with 0x47.

Use this routine if the DVB demux fill buffers that may not start with
a packet start mark (0x47).

**NOTE**

The **buf** size should have size equal to `count * 188`.

#### <a id="c-dvb_dmx_swfilter_204"></a>`dvb_dmx_swfilter_204()`

```c
void dvb_dmx_swfilter_204(struct dvb_demux *demux, const u8 *buf, size_t count)
```

use dvb software filter for a buffer with multiple MPEG-TS packets with 204 bytes each.

**Parameters**

- `struct dvb_demux *demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux)
- `const u8 *buf`: buffer with data to be filtered
- `size_t count`: number of MPEG-TS packets with size of 204.

**Description**

If a DVB packet doesn't start with 0x47, it will seek for the first
byte that starts with 0x47.

Use this routine if the DVB demux fill buffers that may not start with
a packet start mark (0x47).

**NOTE**

The **buf** size should have size equal to `count * 204`.

#### <a id="c-dvb_dmx_swfilter_raw"></a>`dvb_dmx_swfilter_raw()`

```c
void dvb_dmx_swfilter_raw(struct dvb_demux *demux, const u8 *buf, size_t count)
```

make the raw data available to userspace without filtering

**Parameters**

- `struct dvb_demux *demux`: pointer to [`struct dvb_demux`](#c-struct-dvb_demux)
- `const u8 *buf`: buffer with data
- `size_t count`: number of packets to be passed. The actual size of each packet
  depends on the [`dvb_demux->feed`](#c-struct-dvb_demux)->cb.ts logic.

**Description**

Use it if the driver needs to deliver the raw payload to userspace without
passing through the kernel demux. That is meant to support some
delivery systems that aren't based on MPEG-TS.

This function relies on [`dvb_demux->feed`](#c-struct-dvb_demux)->cb.ts to actually handle the
buffer.


<a id="rst-driver-internal-low-level-hardware-specific-driver-demux-interface"></a>

## Driver-internal low-level hardware specific driver demux interface


#### <a id="c-enum-ts_filter_type"></a>`enum ts_filter_type`

filter type bitmap for dmx_ts_feed.set\(\)

**Constants**

- `TS_PACKET`: Send TS packets (188 bytes) to callback (default).
- `TS_PAYLOAD_ONLY`: In case TS_PACKET is set, only send the TS payload
  (\<=184 bytes per packet) to callback
- `TS_DECODER`: Send stream to built-in decoder (if present).
- `TS_DEMUX`: In case TS_PACKET is set, send the TS to the demux
  device, not to the dvr device

#### <a id="c-struct-dmx_ts_feed"></a>`struct dmx_ts_feed`

Structure that contains a TS feed filter

**Definition**

```c
struct dmx_ts_feed {
    int is_filtering;
    struct dmx_demux *parent;
    void *priv;
    int (*set)(struct dmx_ts_feed *feed, u16 pid, int type, enum dmx_ts_pes pes_type, ktime_t timeout);
    int (*start_filtering)(struct dmx_ts_feed *feed);
    int (*stop_filtering)(struct dmx_ts_feed *feed);
};
```

**Members**

- `is_filtering`: Set to non-zero when filtering in progress
- `parent`: pointer to struct dmx_demux
- `priv`: pointer to private data of the API client
- `set`: sets the TS filter
- `start_filtering`: starts TS filtering
- `stop_filtering`: stops TS filtering

**Description**

A TS feed is typically mapped to a hardware PID filter on the demux chip.
Using this API, the client can set the filtering properties to start/stop
filtering TS packets on a particular TS feed.

#### <a id="c-struct-dmx_section_filter"></a>`struct dmx_section_filter`

Structure that describes a section filter

**Definition**

```c
struct dmx_section_filter {
    u8 filter_value[DMX_MAX_FILTER_SIZE];
    u8 filter_mask[DMX_MAX_FILTER_SIZE];
    u8 filter_mode[DMX_MAX_FILTER_SIZE];
    struct dmx_section_feed *parent;
    void *priv;
};
```

**Members**

- `filter_value`: Contains up to 16 bytes (128 bits) of the TS section header
  that will be matched by the section filter
- `filter_mask`: Contains a 16 bytes (128 bits) filter mask with the bits
  specified by **filter_value** that will be used on the filter
  match logic.
- `filter_mode`: Contains a 16 bytes (128 bits) filter mode.
- `parent`: Back-pointer to struct dmx_section_feed.
- `priv`: Pointer to private data of the API client.

**Description**

The **filter_mask** controls which bits of **filter_value** are compared with
the section headers/payload. On a binary value of 1 in filter_mask, the
corresponding bits are compared. The filter only accepts sections that are
equal to filter_value in all the tested bit positions.

#### <a id="c-struct-dmx_section_feed"></a>`struct dmx_section_feed`

Structure that contains a section feed filter

**Definition**

```c
struct dmx_section_feed {
    int is_filtering;
    struct dmx_demux *parent;
    void *priv;
    int check_crc;
    int (*set)(struct dmx_section_feed *feed, u16 pid, int check_crc);
    int (*allocate_filter)(struct dmx_section_feed *feed, struct dmx_section_filter **filter);
    int (*release_filter)(struct dmx_section_feed *feed, struct dmx_section_filter *filter);
    int (*start_filtering)(struct dmx_section_feed *feed);
    int (*stop_filtering)(struct dmx_section_feed *feed);
};
```

**Members**

- `is_filtering`: Set to non-zero when filtering in progress
- `parent`: pointer to struct dmx_demux
- `priv`: pointer to private data of the API client
- `check_crc`: If non-zero, check the CRC values of filtered sections.
- `set`: sets the section filter
- `allocate_filter`: This function is used to allocate a section filter on
  the demux. It should only be called when no filtering
  is in progress on this section feed. If a filter cannot
  be allocated, the function fails with -ENOSPC.
- `release_filter`: This function releases all the resources of a
  previously allocated section filter. The function
  should not be called while filtering is in progress
  on this section feed. After calling this function,
  the caller should not try to dereference the filter
  pointer.
- `start_filtering`: starts section filtering
- `stop_filtering`: stops section filtering

**Description**

A TS feed is typically mapped to a hardware PID filter on the demux chip.
Using this API, the client can set the filtering properties to start/stop
filtering TS packets on a particular TS feed.

#### <a id="c-dmx_ts_cb"></a>`dmx_ts_cb()`

```c
typedef int dmx_ts_cb(const u8 *buffer1, size_t buffer1_length, const u8 *buffer2, size_t buffer2_length, struct dmx_ts_feed *source, u32 *buffer_flags)
```

DVB demux TS filter callback function prototype

**Parameters**

- `const u8 *buffer1`: Pointer to the start of the filtered TS packets.
- `size_t buffer1_length`: Length of the TS data in buffer1.
- `const u8 *buffer2`: Pointer to the tail of the filtered TS packets, or NULL.
- `size_t buffer2_length`: Length of the TS data in buffer2.
- `struct dmx_ts_feed *source`: Indicates which TS feed is the source of the callback.
- `u32 *buffer_flags`: Address where buffer flags are stored. Those are
  used to report discontinuity users via DVB
  memory mapped API, as defined by
  [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).

**Description**

This function callback prototype, provided by the client of the demux API,
is called from the demux code. The function is only called when filtering
on a TS feed has been enabled using the start_filtering\(\) function at
the [`dmx_demux`](#c-struct-dmx_demux).
Any TS packets that match the filter settings are copied to a circular
buffer. The filtered TS packets are delivered to the client using this
callback function.
It is expected that the **buffer1** and **buffer2** callback parameters point to
addresses within the circular buffer, but other implementations are also
possible. Note that the called party should not try to free the memory
the **buffer1** and **buffer2** parameters point to.

When this function is called, the **buffer1** parameter typically points to
the start of the first undelivered TS packet within a circular buffer.
The **buffer2** buffer parameter is normally NULL, except when the received
TS packets have crossed the last address of the circular buffer and
"wrapped" to the beginning of the buffer. In the latter case the **buffer1**
parameter would contain an address within the circular buffer, while the
**buffer2** parameter would contain the first address of the circular buffer.
The number of bytes delivered with this function (i.e. **buffer1_length** +
**buffer2_length**) is usually equal to the value of callback_length parameter
given in the `set()` function, with one exception: if a timeout occurs before
receiving callback_length bytes of TS data, any undelivered packets are
immediately delivered to the client by calling this function. The timeout
duration is controlled by the `set()` function in the TS Feed API.

If a TS packet is received with errors that could not be fixed by the
TS-level forward error correction (FEC), the Transport_error_indicator
flag of the TS packet header should be set. The TS packet should not be
discarded, as the error can possibly be corrected by a higher layer
protocol. If the called party is slow in processing the callback, it
is possible that the circular buffer eventually fills up. If this happens,
the demux driver should discard any TS packets received while the buffer
is full and return -EOVERFLOW.

The type of data returned to the callback can be selected by the
[`dmx_ts_feed`](#c-struct-dmx_ts_feed).**set** function. The type parameter decides if the raw
TS packet (TS_PACKET) or just the payload (TS_PACKET|TS_PAYLOAD_ONLY)
should be returned. If additionally the TS_DECODER bit is set the stream
will also be sent to the hardware MPEG decoder.

- 0, on success;

- -EOVERFLOW, on buffer overflow.

#### <a id="c-dmx_section_cb"></a>`dmx_section_cb()`

```c
typedef int dmx_section_cb(const u8 *buffer1, size_t buffer1_len, const u8 *buffer2, size_t buffer2_len, struct dmx_section_filter *source, u32 *buffer_flags)
```

DVB demux TS filter callback function prototype

**Parameters**

- `const u8 *buffer1`: Pointer to the start of the filtered section, e.g.
  within the circular buffer of the demux driver.
- `size_t buffer1_len`: Length of the filtered section data in **buffer1**,
  including headers and CRC.
- `const u8 *buffer2`: Pointer to the tail of the filtered section data,
  or NULL. Useful to handle the wrapping of a
  circular buffer.
- `size_t buffer2_len`: Length of the filtered section data in **buffer2**,
  including headers and CRC.
- `struct dmx_section_filter *source`: Indicates which section feed is the source of the
  callback.
- `u32 *buffer_flags`: Address where buffer flags are stored. Those are
  used to report discontinuity users via DVB
  memory mapped API, as defined by
  [`enum dmx_buffer_flags`](/kernel/userspace/userspace-api/media-dvb/dmx-types.md#c-enum-dmx_buffer_flags).

**Description**

This function callback prototype, provided by the client of the demux API,
is called from the demux code. The function is only called when
filtering of sections has been enabled using the function
[`dmx_ts_feed`](#c-struct-dmx_ts_feed).**start_filtering**. When the demux driver has received a
complete section that matches at least one section filter, the client
is notified via this callback function. Normally this function is called
for each received section; however, it is also possible to deliver
multiple sections with one callback, for example when the system load
is high. If an error occurs while receiving a section, this
function should be called with the corresponding error type set in the
success field, whether or not there is data to deliver. The Section Feed
implementation should maintain a circular buffer for received sections.
However, this is not necessary if the Section Feed API is implemented as
a client of the TS Feed API, because the TS Feed implementation then
buffers the received data. The size of the circular buffer can be
configured using the [`dmx_ts_feed`](#c-struct-dmx_ts_feed).**set** function in the Section Feed API.
If there is no room in the circular buffer when a new section is received,
the section must be discarded. If this happens, the value of the success
parameter should be DMX_OVERRUN_ERROR on the next callback.

#### <a id="c-enum-dmx_frontend_source"></a>`enum dmx_frontend_source`

Used to identify the type of frontend

**Constants**

- `DMX_MEMORY_FE`: The source of the demux is memory. It means that
  the MPEG-TS to be filtered comes from userspace,
  via `write()` syscall.
- `DMX_FRONTEND_0`: The source of the demux is a frontend connected
  to the demux.

#### <a id="c-struct-dmx_frontend"></a>`struct dmx_frontend`

Structure that lists the frontends associated with a demux

**Definition**

```c
struct dmx_frontend {
    struct list_head connectivity_list;
    enum dmx_frontend_source source;
};
```

**Members**

- `connectivity_list`: List of front-ends that can be connected to a
  particular demux;
- `source`: Type of the frontend.

**Description**

- FIXME: this structure should likely be replaced soon by some

  media-controller based logic.

#### <a id="c-enum-dmx_demux_caps"></a>`enum dmx_demux_caps`

MPEG-2 TS Demux capabilities bitmap

**Constants**

- `DMX_TS_FILTERING`: set if TS filtering is supported;
- `DMX_SECTION_FILTERING`: set if section filtering is supported;
- `DMX_MEMORY_BASED_FILTERING`: set if `write()` available.

**Description**

Those flags are OR'ed in the [`dmx_demux.capabilities`](#c-struct-dmx_demux) field

#### <a id="c-DMX_FE_ENTRY"></a>`DMX_FE_ENTRY()`

```c
DMX_FE_ENTRY(list)
```

Casts elements in the list of registered front-ends from the generic type struct list_head to the type * struct dmx_frontend

**Parameters**

- `list`: list of struct dmx_frontend

#### <a id="c-struct-dmx_demux"></a>`struct dmx_demux`

Structure that contains the demux capabilities and callbacks.

**Definition**

```c
struct dmx_demux {
    enum dmx_demux_caps capabilities;
    struct dmx_frontend *frontend;
    void *priv;
    int (*open)(struct dmx_demux *demux);
    int (*close)(struct dmx_demux *demux);
    int (*write)(struct dmx_demux *demux, const char __user *buf, size_t count);
    int (*allocate_ts_feed)(struct dmx_demux *demux, struct dmx_ts_feed **feed, dmx_ts_cb callback);
    int (*release_ts_feed)(struct dmx_demux *demux, struct dmx_ts_feed *feed);
    int (*allocate_section_feed)(struct dmx_demux *demux, struct dmx_section_feed **feed, dmx_section_cb callback);
    int (*release_section_feed)(struct dmx_demux *demux, struct dmx_section_feed *feed);
    int (*add_frontend)(struct dmx_demux *demux, struct dmx_frontend *frontend);
    int (*remove_frontend)(struct dmx_demux *demux, struct dmx_frontend *frontend);
    struct list_head *(*get_frontends)(struct dmx_demux *demux);
    int (*connect_frontend)(struct dmx_demux *demux, struct dmx_frontend *frontend);
    int (*disconnect_frontend)(struct dmx_demux *demux);
    int (*get_pes_pids)(struct dmx_demux *demux, u16 *pids);
};
```

**Members**

- `capabilities`: Bitfield of capability flags.
- `frontend`: Front-end connected to the demux
- `priv`: Pointer to private data of the API client
- `open`: This function reserves the demux for use by the caller and, if
  necessary, initializes the demux. When the demux is no longer needed,
  the function **close** should be called. It should be possible for
  multiple clients to access the demux at the same time. Thus, the
  function implementation should increment the demux usage count when
  **open** is called and decrement it when **close** is called.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  It returns:
  0 on success;
  -EUSERS, if maximum usage count was reached;
  -EINVAL, on bad parameter.
- `close`: This function reserves the demux for use by the caller and, if
  necessary, initializes the demux. When the demux is no longer needed,
  the function **close** should be called. It should be possible for
  multiple clients to access the demux at the same time. Thus, the
  function implementation should increment the demux usage count when
  **open** is called and decrement it when **close** is called.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  It returns:
  0 on success;
  -ENODEV, if demux was not in use (e. g. no users);
  -EINVAL, on bad parameter.
- `write`: This function provides the demux driver with a memory buffer
  containing TS packets. Instead of receiving TS packets from the DVB
  front-end, the demux driver software will read packets from memory.
  Any clients of this demux with active TS, PES or Section filters will
  receive filtered data via the Demux callback API (see 0). The function
  returns when all the data in the buffer has been consumed by the demux.
  Demux hardware typically cannot read TS from memory. If this is the
  case, memory-based filtering has to be implemented entirely in software.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **buf** function parameter contains a pointer to the TS data in
  kernel-space memory.
  The **count** function parameter contains the length of the TS data.
  It returns:
  0 on success;
  -ERESTARTSYS, if mutex lock was interrupted;
  -EINTR, if a signal handling is pending;
  -ENODEV, if demux was removed;
  -EINVAL, on bad parameter.
- `allocate_ts_feed`: Allocates a new TS feed, which is used to filter the TS
  packets carrying a certain PID. The TS feed normally corresponds to a
  hardware PID filter on the demux chip.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **feed** function parameter contains a pointer to the TS feed API and
  instance data.
  The **callback** function parameter contains a pointer to the callback
  function for passing received TS packet.
  It returns:
  0 on success;
  -ERESTARTSYS, if mutex lock was interrupted;
  -EBUSY, if no more TS feeds is available;
  -EINVAL, on bad parameter.
- `release_ts_feed`: Releases the resources allocated with **allocate_ts_feed**.
  Any filtering in progress on the TS feed should be stopped before
  calling this function.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **feed** function parameter contains a pointer to the TS feed API and
  instance data.
  It returns:
  0 on success;
  -EINVAL on bad parameter.
- `allocate_section_feed`: Allocates a new section feed, i.e. a demux resource
  for filtering and receiving sections. On platforms with hardware
  support for section filtering, a section feed is directly mapped to
  the demux HW. On other platforms, TS packets are first PID filtered in
  hardware and a hardware section filter then emulated in software. The
  caller obtains an API pointer of type dmx_section_feed_t as an out
  parameter. Using this API the caller can set filtering parameters and
  start receiving sections.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **feed** function parameter contains a pointer to the TS feed API and
  instance data.
  The **callback** function parameter contains a pointer to the callback
  function for passing received TS packet.
  It returns:
  0 on success;
  -EBUSY, if no more TS feeds is available;
  -EINVAL, on bad parameter.
- `release_section_feed`: Releases the resources allocated with
  **allocate_section_feed**, including allocated filters. Any filtering in
  progress on the section feed should be stopped before calling this
  function.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **feed** function parameter contains a pointer to the TS feed API and
  instance data.
  It returns:
  0 on success;
  -EINVAL, on bad parameter.
- `add_frontend`: Registers a connectivity between a demux and a front-end,
  i.e., indicates that the demux can be connected via a call to
  **connect_frontend** to use the given front-end as a TS source. The
  client of this function has to allocate dynamic or static memory for
  the frontend structure and initialize its fields before calling this
  function. This function is normally called during the driver
  initialization. The caller must not free the memory of the frontend
  struct before successfully calling **remove_frontend**.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **frontend** function parameter contains a pointer to the front-end
  instance data.
  It returns:
  0 on success;
  -EINVAL, on bad parameter.
- `remove_frontend`: Indicates that the given front-end, registered by a call
  to **add_frontend**, can no longer be connected as a TS source by this
  demux. The function should be called when a front-end driver or a demux
  driver is removed from the system. If the front-end is in use, the
  function fails with the return value of -EBUSY. After successfully
  calling this function, the caller can free the memory of the frontend
  struct if it was dynamically allocated before the **add_frontend**
  operation.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **frontend** function parameter contains a pointer to the front-end
  instance data.
  It returns:
  0 on success;
  -ENODEV, if the front-end was not found,
  -EINVAL, on bad parameter.
- `get_frontends`: Provides the APIs of the front-ends that have been
  registered for this demux. Any of the front-ends obtained with this
  call can be used as a parameter for **connect_frontend**. The include
  file demux.h contains the macro [`DMX_FE_ENTRY()`](#c-DMX_FE_ENTRY) for converting an
  element of the generic type struct `list_head` * to the type
  struct [`dmx_frontend`](#c-struct-dmx_frontend) *. The caller must not free the memory of any of
  the elements obtained via this function call.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  It returns a struct list_head pointer to the list of front-end
  interfaces, or NULL in the case of an empty list.
- `connect_frontend`: Connects the TS output of the front-end to the input of
  the demux. A demux can only be connected to a front-end registered to
  the demux with the function **add_frontend**. It may or may not be
  possible to connect multiple demuxes to the same front-end, depending
  on the capabilities of the HW platform. When not used, the front-end
  should be released by calling **disconnect_frontend**.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **frontend** function parameter contains a pointer to the front-end
  instance data.
  It returns:
  0 on success;
  -EINVAL, on bad parameter.
- `disconnect_frontend`: Disconnects the demux and a front-end previously
  connected by a **connect_frontend** call.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  It returns:
  0 on success;
  -EINVAL on bad parameter.
- `get_pes_pids`: Get the PIDs for DMX_PES_AUDIO0, DMX_PES_VIDEO0,
  DMX_PES_TELETEXT0, DMX_PES_SUBTITLE0 and DMX_PES_PCR0.
  The **demux** function parameter contains a pointer to the demux API and
  instance data.
  The **pids** function parameter contains an array with five u16 elements
  where the PIDs will be stored.
  It returns:
  0 on success;
  -EINVAL on bad parameter.

---

# Digital TV Frontend kABI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The Digital TV Frontend kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent frontend layer. It is only of interest for Digital TV device driver writers. The header file for…

<a id="rst-digital-tv-frontend-kabi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-digital-tv-frontend"></a>

## Digital TV Frontend

The Digital TV Frontend kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent frontend layer. It is only of interest for Digital TV device driver writers. The header file for this API is named `dvb_frontend.h` and located in `include/media/`.

<a id="rst-demodulator-driver"></a>

### Demodulator driver

The demodulator driver is responsible for talking with the decoding part of the hardware. Such driver should implement `dvb_frontend_ops`, which tells what type of digital TV standards are supported, and points to a series of functions that allow the DVB core to command the hardware via the code under `include/media/dvb_frontend.c`.

A typical example of such struct in a driver `foo` is:



```text
static struct dvb_frontend_ops foo_ops = {
        .delsys = { SYS_DVBT, SYS_DVBT2, SYS_DVBC_ANNEX_A },
        .info = {
                .name   = "foo DVB-T/T2/C driver",
                .caps = FE_CAN_FEC_1_2 |
                        FE_CAN_FEC_2_3 |
                        FE_CAN_FEC_3_4 |
                        FE_CAN_FEC_5_6 |
                        FE_CAN_FEC_7_8 |
                        FE_CAN_FEC_AUTO |
                        FE_CAN_QPSK |
                        FE_CAN_QAM_16 |
                        FE_CAN_QAM_32 |
                        FE_CAN_QAM_64 |
                        FE_CAN_QAM_128 |
                        FE_CAN_QAM_256 |
                        FE_CAN_QAM_AUTO |
                        FE_CAN_TRANSMISSION_MODE_AUTO |
                        FE_CAN_GUARD_INTERVAL_AUTO |
                        FE_CAN_HIERARCHY_AUTO |
                        FE_CAN_MUTE_TS |
                        FE_CAN_2G_MODULATION,
                .frequency_min = 42000000, /* Hz */
                .frequency_max = 1002000000, /* Hz */
                .symbol_rate_min = 870000,
                .symbol_rate_max = 11700000
        },
        .init = foo_init,
        .sleep = foo_sleep,
        .release = foo_release,
        .set_frontend = foo_set_frontend,
        .get_frontend = foo_get_frontend,
        .read_status = foo_get_status_and_stats,
        .tune = foo_tune,
        .i2c_gate_ctrl = foo_i2c_gate_ctrl,
        .get_frontend_algo = foo_get_algo,
};
```

A typical example of such struct in a driver `bar` meant to be used on Satellite TV reception is:



```text
static const struct dvb_frontend_ops bar_ops = {
        .delsys = { SYS_DVBS, SYS_DVBS2 },
        .info = {
                .name           = "Bar DVB-S/S2 demodulator",
                .frequency_min  = 500000, /* KHz */
                .frequency_max  = 2500000, /* KHz */
                .frequency_stepsize     = 0,
                .symbol_rate_min = 1000000,
                .symbol_rate_max = 45000000,
                .symbol_rate_tolerance = 500,
                .caps = FE_CAN_INVERSION_AUTO |
                        FE_CAN_FEC_AUTO |
                        FE_CAN_QPSK,
        },
        .init = bar_init,
        .sleep = bar_sleep,
        .release = bar_release,
        .set_frontend = bar_set_frontend,
        .get_frontend = bar_get_frontend,
        .read_status = bar_get_status_and_stats,
        .i2c_gate_ctrl = bar_i2c_gate_ctrl,
        .get_frontend_algo = bar_get_algo,
        .tune = bar_tune,

        /* Satellite-specific */
        .diseqc_send_master_cmd = bar_send_diseqc_msg,
        .diseqc_send_burst = bar_send_burst,
        .set_tone = bar_set_tone,
        .set_voltage = bar_set_voltage,
};
```

> [!NOTE]
>
> 1. For satellite digital TV standards (DVB-S, DVB-S2, ISDB-S), the frequencies are specified in kHz, while, for terrestrial and cable standards, they're specified in Hz. Due to that, if the same frontend supports both types, you'll need to have two separate `dvb_frontend_ops` structures, one for each standard.
>
> 2. The `.i2c_gate_ctrl` field is present only when the hardware has allows controlling an I2C gate (either directly of via some GPIO pin), in order to remove the tuner from the I2C bus after a channel is tuned.
>
> 3. All new drivers should implement the [DVBv5 statistics](<#rst-dvbv5-stats>) via `.read_status`. Yet, there are a number of callbacks meant to get statistics for signal strength, S/N and UCB. Those are there to provide backward compatibility with legacy applications that don't support the DVBv5 API. Implementing those callbacks are optional. Those callbacks may be removed in the future, after we have all existing drivers supporting DVBv5 stats.
>
> 4. Other callbacks are required for satellite TV standards, in order to control LNBf and DiSEqC: `.diseqc_send_master_cmd`, `.diseqc_send_burst`, `.set_tone`, `.set_voltage`.

The `include/media/dvb_frontend.c` has a kernel thread which is responsible for tuning the device. It supports multiple algorithms to detect a channel, as defined at enum `dvbfe_algo()`.

The algorithm to be used is obtained via `.get_frontend_algo`. If the driver doesn't fill its field at struct dvb_frontend_ops, it will default to `DVBFE_ALGO_SW`, meaning that the dvb-core will do a zigzag when tuning, e. g. it will try first to use the specified center frequency `f`, then, it will do `f` + Δ, `f` - Δ, `f` + 2 x Δ, `f` - 2 x Δ and so on.

If the hardware has internally a some sort of zigzag algorithm, you should define a `.get_frontend_algo` function that would return `DVBFE_ALGO_HW`.

> [!NOTE]
>
> The core frontend support also supports a third type (`DVBFE_ALGO_CUSTOM`), in order to allow the driver to define its own hardware-assisted algorithm. Very few hardware need to use it nowadays. Using `DVBFE_ALGO_CUSTOM` require to provide other function callbacks at struct dvb_frontend_ops.

<a id="rst-attaching-frontend-driver-to-the-bridge-driver"></a>

### Attaching frontend driver to the bridge driver

Before using the Digital TV frontend core, the bridge driver should attach the frontend demod, tuner and SEC devices and call `dvb_register_frontend()`, in order to register the new frontend at the subsystem. At device detach/removal, the bridge driver should call `dvb_unregister_frontend()` to remove the frontend from the core and then `dvb_frontend_detach()` to free the memory allocated by the frontend drivers.

The drivers should also call `dvb_frontend_suspend()` as part of their handler for the `device_driver`.`suspend()`, and `dvb_frontend_resume()` as part of their handler for `device_driver`.`resume()`.

A few other optional functions are provided to handle some special cases.

<a id="rst-digital-tv-frontend-statistics"></a>
<a id="rst-dvbv5-stats"></a>

## Digital TV Frontend statistics

<a id="rst-introduction"></a>

### Introduction

Digital TV frontends provide a range of [statistics](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-frontend-stat-properties>) meant to help tuning the device and measuring the quality of service.

For each statistics measurement, the driver should set the type of scale used, or `FE_SCALE_NOT_AVAILABLE` if the statistics is not available on a given time. Drivers should also provide the number of statistics for each type. that's usually 1 for most video standards <a id="rst-footnote-reference-1"></a>[1](#rst-f2).

Drivers should initialize each statistic counters with length and scale at its init code. For example, if the frontend provides signal strength, it should have, on its init code:



```text
struct dtv_frontend_properties *c = &state->fe.dtv_property_cache;

c->strength.len = 1;
c->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
```

And, when the statistics got updated, set the scale:



```text
c->strength.stat[0].scale = FE_SCALE_DECIBEL;
c->strength.stat[0].uvalue = strength;
```

<a id="rst-f2"></a>



**[1]** For ISDB-T, it may provide both a global statistics and a per-layer set of statistics. On such cases, len should be equal to 4. The first value corresponds to the global stat; the other ones to each layer, e. g.:

- c-&gt;cnr.stat\[0\] for global S/N carrier ratio,

- c-&gt;cnr.stat\[1\] for Layer A S/N carrier ratio,

- c-&gt;cnr.stat\[2\] for layer B S/N carrier ratio,

- c-&gt;cnr.stat\[3\] for layer C S/N carrier ratio.

> [!NOTE]
>
> Please prefer to use `FE_SCALE_DECIBEL` instead of `FE_SCALE_RELATIVE` for signal strength and CNR measurements.

<a id="rst-groups-of-statistics"></a>

### Groups of statistics

There are several groups of statistics currently supported:

- **Signal strength ([DTV_STAT_SIGNAL_STRENGTH](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-signal-strength>))**

  - Measures the signal strength level at the analog part of the tuner or demod.

  - Typically obtained from the gain applied to the tuner and/or frontend in order to detect the carrier. When no carrier is detected, the gain is at the maximum value (so, strength is on its minimal).

  - As the gain is visible through the set of registers that adjust the gain, typically, this statistics is always available <a id="rst-footnote-reference-2"></a>[2](#rst-f3).

  - Drivers should try to make it available all the times, as these statistics can be used when adjusting an antenna position and to check for troubles at the cabling.

  <a id="rst-f3"></a>



  **[2]** On a few devices, the gain keeps floating if there is no carrier. On such devices, strength report should check first if carrier is detected at the tuner (`FE_HAS_CARRIER`, see `fe_status`), and otherwise return the lowest possible value.

- **Carrier Signal to Noise ratio ([DTV_STAT_CNR](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-cnr>))**

  - Signal to Noise ratio for the main carrier.

  - Signal to Noise measurement depends on the device. On some hardware, it is available when the main carrier is detected. On those hardware, CNR measurement usually comes from the tuner (e. g. after `FE_HAS_CARRIER`, see `fe_status`).

    On other devices, it requires inner FEC decoding, as the frontend measures it indirectly from other parameters (e. g. after `FE_HAS_VITERBI`, see `fe_status`).

    Having it available after inner FEC is more common.

- **Bit counts post-FEC ([DTV_STAT_POST_ERROR_BIT_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-post-error-bit-count>) and [DTV_STAT_POST_TOTAL_BIT_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-post-total-bit-count>))**

  - Those counters measure the number of bits and bit errors after the forward error correction (FEC) on the inner coding block (after Viterbi, LDPC or other inner code).

  - Due to its nature, those statistics depend on full coding lock (e. g. after `FE_HAS_SYNC` or after `FE_HAS_LOCK`, see `fe_status`).

- **Bit counts pre-FEC ([DTV_STAT_PRE_ERROR_BIT_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-pre-error-bit-count>) and [DTV_STAT_PRE_TOTAL_BIT_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-pre-total-bit-count>))**

  - Those counters measure the number of bits and bit errors before the forward error correction (FEC) on the inner coding block (before Viterbi, LDPC or other inner code).

  - Not all frontends provide this kind of statistics.

  - Due to its nature, those statistics depend on inner coding lock (e. g. after `FE_HAS_VITERBI`, see `fe_status`).

- **Block counts ([DTV_STAT_ERROR_BLOCK_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-error-block-count>) and [DTV-STAT_TOTAL_BLOCK_COUNT](</kernel/userspace/userspace-api/media-dvb/frontend-stat-properties.md#rst-dtv-stat-total-block-count>))**

  - Those counters measure the number of blocks and block errors after the forward error correction (FEC) on the inner coding block (before Viterbi, LDPC or other inner code).

  - Due to its nature, those statistics depend on full coding lock (e. g. after `FE_HAS_SYNC` or after `FE_HAS_LOCK`, see `fe_status`).

> [!NOTE]
>
> All counters should be monotonically increased as they're collected from the hardware.

A typical example of the logic that handle status and statistics is:



```text
static int foo_get_status_and_stats(struct dvb_frontend *fe)
{
        struct foo_state *state = fe->demodulator_priv;
        struct dtv_frontend_properties *c = &fe->dtv_property_cache;

        int rc;
        enum fe_status *status;

        /* Both status and strength are always available */
        rc = foo_read_status(fe, &status);
        if (rc < 0)
                return rc;

        rc = foo_read_strength(fe);
        if (rc < 0)
                return rc;

        /* Check if CNR is available */
        if (!(fe->status & FE_HAS_CARRIER))
                return 0;

        rc = foo_read_cnr(fe);
        if (rc < 0)
                return rc;

        /* Check if pre-BER stats are available */
        if (!(fe->status & FE_HAS_VITERBI))
                return 0;

        rc = foo_get_pre_ber(fe);
        if (rc < 0)
                return rc;

        /* Check if post-BER stats are available */
        if (!(fe->status & FE_HAS_SYNC))
                return 0;

        rc = foo_get_post_ber(fe);
        if (rc < 0)
                return rc;
}

static const struct dvb_frontend_ops ops = {
        /* ... */
        .read_status = foo_get_status_and_stats,
};
```

<a id="rst-statistics-collection"></a>

### Statistics collection

On almost all frontend hardware, the bit and byte counts are stored by the hardware after a certain amount of time or after the total bit/block counter reaches a certain value (usually programmable), for example, on every 1000 ms or after receiving 1,000,000 bits.

So, if you read the registers too soon, you'll end by reading the same value as in the previous reading, causing the monotonic value to be incremented too often.

Drivers should take the responsibility to avoid too often reads. That can be done using two approaches:

<a id="rst-if-the-driver-have-a-bit-that-indicates-when-a-collected-data-is-ready"></a>

#### if the driver have a bit that indicates when a collected data is ready

Driver should check such bit before making the statistics available.

An example of such behavior can be found at this code snippet (adapted from mb86a20s driver's logic):



```text
static int foo_get_pre_ber(struct dvb_frontend *fe)
{
        struct foo_state *state = fe->demodulator_priv;
        struct dtv_frontend_properties *c = &fe->dtv_property_cache;
        int rc, bit_error;

        /* Check if the BER measures are already available */
        rc = foo_read_u8(state, 0x54);
        if (rc < 0)
                return rc;

        if (!rc)
                return 0;

        /* Read Bit Error Count */
        bit_error = foo_read_u32(state, 0x55);
        if (bit_error < 0)
                return bit_error;

        /* Read Total Bit Count */
        rc = foo_read_u32(state, 0x51);
        if (rc < 0)
                return rc;

        c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
        c->pre_bit_error.stat[0].uvalue += bit_error;
        c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
        c->pre_bit_count.stat[0].uvalue += rc;

        return 0;
}
```

<a id="rst-if-the-driver-doesn-t-provide-a-statistics-available-check-bit"></a>

#### If the driver doesn't provide a statistics available check bit

A few devices, however, may not provide a way to check if the stats are available (or the way to check it is unknown). They may not even provide a way to directly read the total number of bits or blocks.

On those devices, the driver need to ensure that it won't be reading from the register too often and/or estimate the total number of bits/blocks.

On such drivers, a typical routine to get statistics would be like (adapted from dib8000 driver's logic):



```text
struct foo_state {
        /* ... */

        unsigned long per_jiffies_stats;
}

static int foo_get_pre_ber(struct dvb_frontend *fe)
{
        struct foo_state *state = fe->demodulator_priv;
        struct dtv_frontend_properties *c = &fe->dtv_property_cache;
        int rc, bit_error;
        u64 bits;

        /* Check if time for stats was elapsed */
        if (!time_after(jiffies, state->per_jiffies_stats))
                return 0;

        /* Next stat should be collected in 1000 ms */
        state->per_jiffies_stats = jiffies + msecs_to_jiffies(1000);

        /* Read Bit Error Count */
        bit_error = foo_read_u32(state, 0x55);
        if (bit_error < 0)
                return bit_error;

        /*
         * On this particular frontend, there's no register that
         * would provide the number of bits per 1000ms sample. So,
         * some function would calculate it based on DTV properties
         */
        bits = get_number_of_bits_per_1000ms(fe);

        c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
        c->pre_bit_error.stat[0].uvalue += bit_error;
        c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
        c->pre_bit_count.stat[0].uvalue += bits;

        return 0;
}
```

Please notice that, on both cases, we're getting the statistics using the `dvb_frontend_ops` `.read_status` callback. The rationale is that the frontend core will automatically call this function periodically (usually, 3 times per second, when the frontend is locked).

That warrants that we won't miss to collect a counter and increment the monotonic stats at the right time.

<a id="rst-digital-tv-frontend-functions-and-types"></a>

## Digital TV Frontend functions and types


#### <a id="c-struct-dvb_frontend_tune_settings"></a>`struct dvb_frontend_tune_settings`

parameters to adjust frontend tuning

**Definition**

```c
struct dvb_frontend_tune_settings {
    int min_delay_ms;
    int step_size;
    int max_drift;
};
```

**Members**

- `min_delay_ms`: minimum delay for tuning, in ms
- `step_size`: step size between two consecutive frequencies
- `max_drift`: maximum drift

**NOTE**

step_size is in Hz, for terrestrial/cable or kHz for satellite

#### <a id="c-struct-dvb_tuner_info"></a>`struct dvb_tuner_info`

Frontend name and min/max ranges/bandwidths

**Definition**

```c
struct dvb_tuner_info {
    char name[128];
    u32 frequency_min_hz;
    u32 frequency_max_hz;
    u32 frequency_step_hz;
    u32 bandwidth_min;
    u32 bandwidth_max;
    u32 bandwidth_step;
};
```

**Members**

- `name`: name of the Frontend
- `frequency_min_hz`: minimal frequency supported in Hz
- `frequency_max_hz`: maximum frequency supported in Hz
- `frequency_step_hz`: frequency step in Hz
- `bandwidth_min`: minimal frontend bandwidth supported
- `bandwidth_max`: maximum frontend bandwidth supported
- `bandwidth_step`: frontend bandwidth step

#### <a id="c-struct-analog_parameters"></a>`struct analog_parameters`

Parameters to tune into an analog/radio channel

**Definition**

```c
struct analog_parameters {
    unsigned int frequency;
    unsigned int mode;
    unsigned int audmode;
    u64 std;
};
```

**Members**

- `frequency`: Frequency used by analog TV tuner (either in 62.5 kHz step,
  for TV, or 62.5 Hz for radio)
- `mode`: Tuner mode, as defined on enum v4l2_tuner_type
- `audmode`: Audio mode as defined for the rxsubchans field at videodev2.h,
  e. g. V4L2_TUNER_MODE_*
- `std`: TV standard bitmap as defined at videodev2.h, e. g. V4L2_STD_*

**Description**

Hybrid tuners should be supported by both V4L2 and DVB APIs. This
struct contains the data that are used by the V4L2 side. To avoid
dependencies from V4L2 headers, all enums here are declared as integers.

#### <a id="c-enum-dvbfe_algo"></a>`enum dvbfe_algo`

defines the algorithm used to tune into a channel

**Constants**

- `DVBFE_ALGO_HW`: Hardware Algorithm -
  Devices that support this algorithm do everything in hardware
  and no software support is needed to handle them.
  Requesting these devices to LOCK is the only thing required,
  device is supposed to do everything in the hardware.
- `DVBFE_ALGO_SW`: Software Algorithm -
  These are dumb devices, that require software to do everything
- `DVBFE_ALGO_CUSTOM`: Customizable Agorithm -
  Devices having this algorithm can be customized to have specific
  algorithms in the frontend driver, rather than simply doing a
  software zig-zag. In this case the zigzag maybe hardware assisted
  or it maybe completely done in hardware. In all cases, usage of
  this algorithm, in conjunction with the search and track
  callbacks, utilizes the driver specific algorithm.
- `DVBFE_ALGO_RECOVERY`: Recovery Algorithm -
  These devices have AUTO recovery capabilities from LOCK failure

#### <a id="c-enum-dvbfe_search"></a>`enum dvbfe_search`

search callback possible return status

**Constants**

- `DVBFE_ALGO_SEARCH_SUCCESS`: The frontend search algorithm completed and returned successfully
- `DVBFE_ALGO_SEARCH_ASLEEP`: The frontend search algorithm is sleeping
- `DVBFE_ALGO_SEARCH_FAILED`: The frontend search for a signal failed
- `DVBFE_ALGO_SEARCH_INVALID`: The frontend search algorithm was probably supplied with invalid
  parameters and the search is an invalid one
- `DVBFE_ALGO_SEARCH_AGAIN`: The frontend search algorithm was requested to search again
- `DVBFE_ALGO_SEARCH_ERROR`: The frontend search algorithm failed due to some error

#### <a id="c-struct-dvb_tuner_ops"></a>`struct dvb_tuner_ops`

Tuner information and callbacks

**Definition**

```c
struct dvb_tuner_ops {
        struct dvb_tuner_info info;
        void (*release)(struct dvb_frontend *fe);
        int (*init)(struct dvb_frontend *fe);
        int (*sleep)(struct dvb_frontend *fe);
        int (*suspend)(struct dvb_frontend *fe);
        int (*resume)(struct dvb_frontend *fe);
        int (*set_params)(struct dvb_frontend *fe);
        int (*set_analog_params)(struct dvb_frontend *fe, struct analog_parameters *p);
        int (*set_config)(struct dvb_frontend *fe, void *priv_cfg);
        int (*get_frequency)(struct dvb_frontend *fe, u32 *frequency);
        int (*get_bandwidth)(struct dvb_frontend *fe, u32 *bandwidth);
        int (*get_if_frequency)(struct dvb_frontend *fe, u32 *frequency);
    #define TUNER_STATUS_LOCKED 1;
    #define TUNER_STATUS_STEREO 2;
        int (*get_status)(struct dvb_frontend *fe, u32 *status);
        int (*get_rf_strength)(struct dvb_frontend *fe, u16 *strength);
        int (*get_afc)(struct dvb_frontend *fe, s32 *afc);
        int (*calc_regs)(struct dvb_frontend *fe, u8 *buf, int buf_len);
        int (*set_frequency)(struct dvb_frontend *fe, u32 frequency);
        int (*set_bandwidth)(struct dvb_frontend *fe, u32 bandwidth);
};
```

**Members**

- `info`: embedded [`struct dvb_tuner_info`](#c-struct-dvb_tuner_info) with tuner properties
- `release`: callback function called when frontend is detached.
  drivers should free any allocated memory.
- `init`: callback function used to initialize the tuner device.
- `sleep`: callback function used to put the tuner to sleep.
- `suspend`: callback function used to inform that the Kernel will
  suspend.
- `resume`: callback function used to inform that the Kernel is
  resuming from suspend.
- `set_params`: callback function used to inform the tuner to tune
  into a digital TV channel. The properties to be used
  are stored at [`struct dvb_frontend`](#c-struct-dvb_frontend).dtv_property_cache.
  The tuner demod can change the parameters to reflect
  the changes needed for the channel to be tuned, and
  update statistics. This is the recommended way to set
  the tuner parameters and should be used on newer
  drivers.
- `set_analog_params`: callback function used to tune into an analog TV
  channel on hybrid tuners. It passes **analog_parameters**
  to the driver.
- `set_config`: callback function used to send some tuner-specific
  parameters.
- `get_frequency`: get the actual tuned frequency
- `get_bandwidth`: get the bandwidth used by the low pass filters
- `get_if_frequency`: get the Intermediate Frequency, in Hz. For baseband,
  should return 0.
- `get_status`: returns the frontend lock status
- `get_rf_strength`: returns the RF signal strength. Used mostly to support
  analog TV and radio. Digital TV should report, instead,
  via DVBv5 API ([`struct dvb_frontend`](#c-struct-dvb_frontend).dtv_property_cache).
- `get_afc`: Used only by analog TV core. Reports the frequency
  drift due to AFC.
- `calc_regs`: callback function used to pass register data settings
  for simple tuners.  Shouldn't be used on newer drivers.
- `set_frequency`: Set a new frequency. Shouldn't be used on newer drivers.
- `set_bandwidth`: Set a new frequency. Shouldn't be used on newer drivers.

**NOTE**

frequencies used on **get_frequency** and **set_frequency** are in Hz for
terrestrial/cable or kHz for satellite.

#### <a id="c-struct-analog_demod_info"></a>`struct analog_demod_info`

Information struct for analog TV part of the demod

**Definition**

```c
struct analog_demod_info {
    char *name;
};
```

**Members**

- `name`: Name of the analog TV demodulator

#### <a id="c-struct-analog_demod_ops"></a>`struct analog_demod_ops`

Demodulation information and callbacks for analog TV and radio

**Definition**

```c
struct analog_demod_ops {
    struct analog_demod_info info;
    void (*set_params)(struct dvb_frontend *fe, struct analog_parameters *params);
    int (*has_signal)(struct dvb_frontend *fe, u16 *signal);
    int (*get_afc)(struct dvb_frontend *fe, s32 *afc);
    void (*tuner_status)(struct dvb_frontend *fe);
    void (*standby)(struct dvb_frontend *fe);
    void (*release)(struct dvb_frontend *fe);
    int (*i2c_gate_ctrl)(struct dvb_frontend *fe, int enable);
    int (*set_config)(struct dvb_frontend *fe, void *priv_cfg);
};
```

**Members**

- `info`: pointer to struct analog_demod_info
- `set_params`: callback function used to inform the demod to set the
  demodulator parameters needed to decode an analog or
  radio channel. The properties are passed via
  `struct analog_params`.
- `has_signal`: returns 0xffff if has signal, or 0 if it doesn't.
- `get_afc`: Used only by analog TV core. Reports the frequency
  drift due to AFC.
- `tuner_status`: callback function that returns tuner status bits, e. g.
  `TUNER_STATUS_LOCKED` and `TUNER_STATUS_STEREO`.
- `standby`: set the tuner to standby mode.
- `release`: callback function called when frontend is detached.
  drivers should free any allocated memory.
- `i2c_gate_ctrl`: controls the I2C gate. Newer drivers should use I2C
  mux support instead.
- `set_config`: callback function used to send some tuner-specific
  parameters.

#### <a id="c-struct-dvb_frontend_internal_info"></a>`struct dvb_frontend_internal_info`

Frontend properties and capabilities

**Definition**

```c
struct dvb_frontend_internal_info {
    char name[128];
    u32 frequency_min_hz;
    u32 frequency_max_hz;
    u32 frequency_stepsize_hz;
    u32 frequency_tolerance_hz;
    u32 symbol_rate_min;
    u32 symbol_rate_max;
    u32 symbol_rate_tolerance;
    enum fe_caps caps;
};
```

**Members**

- `name`: Name of the frontend
- `frequency_min_hz`: Minimal frequency supported by the frontend.
- `frequency_max_hz`: Minimal frequency supported by the frontend.
- `frequency_stepsize_hz`: All frequencies are multiple of this value.
- `frequency_tolerance_hz`: Frequency tolerance.
- `symbol_rate_min`: Minimal symbol rate, in bauds
  (for Cable/Satellite systems).
- `symbol_rate_max`: Maximal symbol rate, in bauds
  (for Cable/Satellite systems).
- `symbol_rate_tolerance`: Maximal symbol rate tolerance, in ppm
  (for Cable/Satellite systems).
- `caps`: Capabilities supported by the frontend,
  as specified in [`enum fe_caps`](/kernel/userspace/userspace-api/media-dvb/frontend-header.md#c-enum-fe_caps).

#### <a id="c-struct-dvb_frontend_ops"></a>`struct dvb_frontend_ops`

Demodulation information and callbacks for ditialt TV

**Definition**

```c
struct dvb_frontend_ops {
    struct dvb_frontend_internal_info info;
    u8 delsys[MAX_DELSYS];
    void (*detach)(struct dvb_frontend *fe);
    void (*release)(struct dvb_frontend* fe);
    void (*release_sec)(struct dvb_frontend* fe);
    int (*init)(struct dvb_frontend* fe);
    int (*sleep)(struct dvb_frontend* fe);
    int (*suspend)(struct dvb_frontend *fe);
    int (*resume)(struct dvb_frontend *fe);
    int (*write)(struct dvb_frontend* fe, const u8 buf[], int len);
    int (*tune)(struct dvb_frontend* fe, bool re_tune, unsigned int mode_flags, unsigned int *delay, enum fe_status *status);
    enum dvbfe_algo (*get_frontend_algo)(struct dvb_frontend *fe);
    int (*set_frontend)(struct dvb_frontend *fe);
    int (*get_tune_settings)(struct dvb_frontend* fe, struct dvb_frontend_tune_settings* settings);
    int (*get_frontend)(struct dvb_frontend *fe, struct dtv_frontend_properties *props);
    int (*read_status)(struct dvb_frontend *fe, enum fe_status *status);
    int (*read_ber)(struct dvb_frontend* fe, u32* ber);
    int (*read_signal_strength)(struct dvb_frontend* fe, u16* strength);
    int (*read_snr)(struct dvb_frontend* fe, u16* snr);
    int (*read_ucblocks)(struct dvb_frontend* fe, u32* ucblocks);
    int (*diseqc_reset_overload)(struct dvb_frontend* fe);
    int (*diseqc_send_master_cmd)(struct dvb_frontend* fe, struct dvb_diseqc_master_cmd* cmd);
    int (*diseqc_recv_slave_reply)(struct dvb_frontend* fe, struct dvb_diseqc_slave_reply* reply);
    int (*diseqc_send_burst)(struct dvb_frontend *fe, enum fe_sec_mini_cmd minicmd);
    int (*set_tone)(struct dvb_frontend *fe, enum fe_sec_tone_mode tone);
    int (*set_voltage)(struct dvb_frontend *fe, enum fe_sec_voltage voltage);
    int (*enable_high_lnb_voltage)(struct dvb_frontend* fe, long arg);
    int (*dishnetwork_send_legacy_command)(struct dvb_frontend* fe, unsigned long cmd);
    int (*i2c_gate_ctrl)(struct dvb_frontend* fe, int enable);
    int (*ts_bus_ctrl)(struct dvb_frontend* fe, int acquire);
    int (*set_lna)(struct dvb_frontend *);
    enum dvbfe_search (*search)(struct dvb_frontend *fe);
    struct dvb_tuner_ops tuner_ops;
    struct analog_demod_ops analog_ops;
};
```

**Members**

- `info`: embedded [`struct dvb_tuner_info`](#c-struct-dvb_tuner_info) with tuner properties
- `delsys`: Delivery systems supported by the frontend
- `detach`: callback function called when frontend is detached.
  drivers should clean up, but not yet free the [`struct dvb_frontend`](#c-struct-dvb_frontend) allocation.
- `release`: callback function called when frontend is ready to be
  freed.
  drivers should free any allocated memory.
- `release_sec`: callback function requesting that the Satellite Equipment
  Control (SEC) driver to release and free any memory
  allocated by the driver.
- `init`: callback function used to initialize the tuner device.
- `sleep`: callback function used to put the tuner to sleep.
- `suspend`: callback function used to inform that the Kernel will
  suspend.
- `resume`: callback function used to inform that the Kernel is
  resuming from suspend.
- `write`: callback function used by some demod legacy drivers to
  allow other drivers to write data into their registers.
  Should not be used on new drivers.
- `tune`: callback function used by demod drivers that use
  **DVBFE_ALGO_HW** to tune into a frequency.
- `get_frontend_algo`: returns the desired hardware algorithm.
- `set_frontend`: callback function used to inform the demod to set the
  parameters for demodulating a digital TV channel.
  The properties to be used are stored at [`struct dvb_frontend`](#c-struct-dvb_frontend).dtv_property_cache. The demod can change
  the parameters to reflect the changes needed for the
  channel to be decoded, and update statistics.
- `get_tune_settings`: callback function
- `get_frontend`: callback function used to inform the parameters
  actuall in use. The properties to be used are stored at
  [`struct dvb_frontend`](#c-struct-dvb_frontend).dtv_property_cache and update
  statistics. Please notice that it should not return
  an error code if the statistics are not available
  because the demog is not locked.
- `read_status`: returns the locking status of the frontend.
- `read_ber`: legacy callback function to return the bit error rate.
  Newer drivers should provide such info via DVBv5 API,
  e. g. **set_frontend**;/**get_frontend**, implementing this
  callback only if DVBv3 API compatibility is wanted.
- `read_signal_strength`: legacy callback function to return the signal
  strength. Newer drivers should provide such info via
  DVBv5 API, e. g. **set_frontend**/**get_frontend**,
  implementing this callback only if DVBv3 API
  compatibility is wanted.
- `read_snr`: legacy callback function to return the Signal/Noise
  rate. Newer drivers should provide such info via
  DVBv5 API, e. g. **set_frontend**/**get_frontend**,
  implementing this callback only if DVBv3 API
  compatibility is wanted.
- `read_ucblocks`: legacy callback function to return the Uncorrected Error
  Blocks. Newer drivers should provide such info via
  DVBv5 API, e. g. **set_frontend**/**get_frontend**,
  implementing this callback only if DVBv3 API
  compatibility is wanted.
- `diseqc_reset_overload`: callback function to implement the
  `FE_DISEQC_RESET_OVERLOAD()` ioctl (only Satellite)
- `diseqc_send_master_cmd`: callback function to implement the
  `FE_DISEQC_SEND_MASTER_CMD()` ioctl (only Satellite).
- `diseqc_recv_slave_reply`: callback function to implement the
  `FE_DISEQC_RECV_SLAVE_REPLY()` ioctl (only Satellite)
- `diseqc_send_burst`: callback function to implement the
  `FE_DISEQC_SEND_BURST()` ioctl (only Satellite).
- `set_tone`: callback function to implement the
  `FE_SET_TONE()` ioctl (only Satellite).
- `set_voltage`: callback function to implement the
  `FE_SET_VOLTAGE()` ioctl (only Satellite).
- `enable_high_lnb_voltage`: callback function to implement the
  `FE_ENABLE_HIGH_LNB_VOLTAGE()` ioctl (only Satellite).
- `dishnetwork_send_legacy_command`: callback function to implement the
  `FE_DISHNETWORK_SEND_LEGACY_CMD()` ioctl (only Satellite).
  Drivers should not use this, except when the DVB
  core emulation fails to provide proper support (e.g.
  if **set_voltage** takes more than 8ms to work), and
  when backward compatibility with this legacy API is
  required.
- `i2c_gate_ctrl`: controls the I2C gate. Newer drivers should use I2C
  mux support instead.
- `ts_bus_ctrl`: callback function used to take control of the TS bus.
- `set_lna`: callback function to power on/off/auto the LNA.
- `search`: callback function used on some custom algo search algos.
- `tuner_ops`: pointer to [`struct dvb_tuner_ops`](#c-struct-dvb_tuner_ops)
- `analog_ops`: pointer to [`struct analog_demod_ops`](#c-struct-analog_demod_ops)

#### <a id="c-struct-dtv_frontend_properties"></a>`struct dtv_frontend_properties`

contains a list of properties that are specific to a digital TV standard.

**Definition**

```c
struct dtv_frontend_properties {
    u32 frequency;
    enum fe_modulation      modulation;
    enum fe_sec_voltage     voltage;
    enum fe_sec_tone_mode   sectone;
    enum fe_spectral_inversion inversion;
    enum fe_code_rate       fec_inner;
    enum fe_transmit_mode   transmission_mode;
    u32 bandwidth_hz;
    enum fe_guard_interval  guard_interval;
    enum fe_hierarchy       hierarchy;
    u32 symbol_rate;
    enum fe_code_rate       code_rate_HP;
    enum fe_code_rate       code_rate_LP;
    enum fe_pilot           pilot;
    enum fe_rolloff         rolloff;
    enum fe_delivery_system delivery_system;
    enum fe_interleaving    interleaving;
    u8 isdbt_partial_reception;
    u8 isdbt_sb_mode;
    u8 isdbt_sb_subchannel;
    u32 isdbt_sb_segment_idx;
    u32 isdbt_sb_segment_count;
    u8 isdbt_layer_enabled;
    struct {
        u8 segment_count;
        enum fe_code_rate   fec;
        enum fe_modulation  modulation;
        u8 interleaving;
    } layer[3];
    u32 stream_id;
    u32 scrambling_sequence_index;
    u8 atscmh_fic_ver;
    u8 atscmh_parade_id;
    u8 atscmh_nog;
    u8 atscmh_tnog;
    u8 atscmh_sgn;
    u8 atscmh_prc;
    u8 atscmh_rs_frame_mode;
    u8 atscmh_rs_frame_ensemble;
    u8 atscmh_rs_code_mode_pri;
    u8 atscmh_rs_code_mode_sec;
    u8 atscmh_sccc_block_mode;
    u8 atscmh_sccc_code_mode_a;
    u8 atscmh_sccc_code_mode_b;
    u8 atscmh_sccc_code_mode_c;
    u8 atscmh_sccc_code_mode_d;
    u32 lna;
    struct dtv_fe_stats     strength;
    struct dtv_fe_stats     cnr;
    struct dtv_fe_stats     pre_bit_error;
    struct dtv_fe_stats     pre_bit_count;
    struct dtv_fe_stats     post_bit_error;
    struct dtv_fe_stats     post_bit_count;
    struct dtv_fe_stats     block_error;
    struct dtv_fe_stats     block_count;
};
```

**Members**

- `frequency`: frequency in Hz for terrestrial/cable or in kHz for
  Satellite
- `modulation`: Frontend modulation type
- `voltage`: SEC voltage (only Satellite)
- `sectone`: SEC tone mode (only Satellite)
- `inversion`: Spectral inversion
- `fec_inner`: Forward error correction inner Code Rate
- `transmission_mode`: Transmission Mode
- `bandwidth_hz`: Bandwidth, in Hz. A zero value means that userspace
  wants to autodetect.
- `guard_interval`: Guard Interval
- `hierarchy`: Hierarchy
- `symbol_rate`: Symbol Rate
- `code_rate_HP`: high priority stream code rate
- `code_rate_LP`: low priority stream code rate
- `pilot`: Enable/disable/autodetect pilot tones
- `rolloff`: Rolloff factor (alpha)
- `delivery_system`: FE delivery system (e. g. digital TV standard)
- `interleaving`: interleaving
- `isdbt_partial_reception`: ISDB-T partial reception (only ISDB standard)
- `isdbt_sb_mode`: ISDB-T Sound Broadcast (SB) mode (only ISDB standard)
- `isdbt_sb_subchannel`: ISDB-T SB subchannel (only ISDB standard)
- `isdbt_sb_segment_idx`: ISDB-T SB segment index (only ISDB standard)
- `isdbt_sb_segment_count`: ISDB-T SB segment count (only ISDB standard)
- `isdbt_layer_enabled`: ISDB Layer enabled (only ISDB standard)
- `layer`: ISDB per-layer data (only ISDB standard)
- `layer.segment_count`: Segment Count;
- `layer.fec`: per layer code rate;
- `layer.modulation`: per layer modulation;
- `layer.interleaving`: per layer interleaving.
- `stream_id`: If different than zero, enable substream filtering, if
  hardware supports (DVB-S2 and DVB-T2).
- `scrambling_sequence_index`: Carries the index of the DVB-S2 physical layer
  scrambling sequence.
- `atscmh_fic_ver`: Version number of the FIC (Fast Information Channel)
  signaling data (only ATSC-M/H)
- `atscmh_parade_id`: Parade identification number (only ATSC-M/H)
- `atscmh_nog`: Number of MH groups per MH subframe for a designated
  parade (only ATSC-M/H)
- `atscmh_tnog`: Total number of MH groups including all MH groups
  belonging to all MH parades in one MH subframe
  (only ATSC-M/H)
- `atscmh_sgn`: Start group number (only ATSC-M/H)
- `atscmh_prc`: Parade repetition cycle (only ATSC-M/H)
- `atscmh_rs_frame_mode`: Reed Solomon (RS) frame mode (only ATSC-M/H)
- `atscmh_rs_frame_ensemble`: RS frame ensemble (only ATSC-M/H)
- `atscmh_rs_code_mode_pri`: RS code mode pri (only ATSC-M/H)
- `atscmh_rs_code_mode_sec`: RS code mode sec (only ATSC-M/H)
- `atscmh_sccc_block_mode`: Series Concatenated Convolutional Code (SCCC)
  Block Mode (only ATSC-M/H)
- `atscmh_sccc_code_mode_a`: SCCC code mode A (only ATSC-M/H)
- `atscmh_sccc_code_mode_b`: SCCC code mode B (only ATSC-M/H)
- `atscmh_sccc_code_mode_c`: SCCC code mode C (only ATSC-M/H)
- `atscmh_sccc_code_mode_d`: SCCC code mode D (only ATSC-M/H)
- `lna`: Power ON/OFF/AUTO the Linear Now-noise Amplifier (LNA)
- `strength`: DVBv5 API statistics: Signal Strength
- `cnr`: DVBv5 API statistics: Signal to Noise ratio of the
  (main) carrier
- `pre_bit_error`: DVBv5 API statistics: pre-Viterbi bit error count
- `pre_bit_count`: DVBv5 API statistics: pre-Viterbi bit count
- `post_bit_error`: DVBv5 API statistics: post-Viterbi bit error count
- `post_bit_count`: DVBv5 API statistics: post-Viterbi bit count
- `block_error`: DVBv5 API statistics: block error count
- `block_count`: DVBv5 API statistics: block count

**NOTE**

derivated statistics like Uncorrected Error blocks (UCE) are
calculated on userspace.

Only a subset of the properties are needed for a given delivery system.
For more info, consult the media_api.html with the documentation of the
Userspace API.

#### <a id="c-struct-dvb_frontend"></a>`struct dvb_frontend`

Frontend structure to be used on drivers.

**Definition**

```c
struct dvb_frontend {
        struct kref refcount;
        struct dvb_frontend_ops ops;
        struct dvb_adapter *dvb;
        void *demodulator_priv;
        void *tuner_priv;
        void *frontend_priv;
        void *sec_priv;
        void *analog_demod_priv;
        struct dtv_frontend_properties dtv_property_cache;
    #define DVB_FRONTEND_COMPONENT_TUNER 0;
    #define DVB_FRONTEND_COMPONENT_DEMOD 1;
        int (*callback)(void *adapter_priv, int component, int cmd, int arg);
        int id;
        unsigned int exit;
};
```

**Members**

- `refcount`: refcount to keep track of [`struct dvb_frontend`](#c-struct-dvb_frontend)
  references
- `ops`: embedded [`struct dvb_frontend_ops`](#c-struct-dvb_frontend_ops)
- `dvb`: pointer to [`struct dvb_adapter`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_adapter)
- `demodulator_priv`: demod private data
- `tuner_priv`: tuner private data
- `frontend_priv`: frontend private data
- `sec_priv`: SEC private data
- `analog_demod_priv`: Analog demod private data
- `dtv_property_cache`: embedded [`struct dtv_frontend_properties`](#c-struct-dtv_frontend_properties)
- `callback`: callback function used on some drivers to call
  either the tuner or the demodulator.
- `id`: Frontend ID
- `exit`: Used to inform the DVB core that the frontend
  thread should exit (usually, means that the hardware
  got disconnected.

#### <a id="c-dvb_register_frontend"></a>`dvb_register_frontend()`

```c
int dvb_register_frontend(struct dvb_adapter *dvb, struct dvb_frontend *fe)
```

Registers a DVB frontend at the adapter

**Parameters**

- `struct dvb_adapter *dvb`: pointer to [`struct dvb_adapter`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_adapter)
- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

Allocate and initialize the private data needed by the frontend core to
manage the frontend and calls [`dvb_register_device()`](/kernel/hardware/driver-api/media/dtv-common.md#c-dvb_register_device) to register a new
frontend. It also cleans the property cache that stores the frontend
parameters and selects the first available delivery system.

#### <a id="c-dvb_unregister_frontend"></a>`dvb_unregister_frontend()`

```c
int dvb_unregister_frontend(struct dvb_frontend *fe)
```

Unregisters a DVB frontend

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

Stops the frontend kthread, calls [`dvb_unregister_device()`](/kernel/hardware/driver-api/media/dtv-common.md#c-dvb_unregister_device) and frees the
private frontend data allocated by [`dvb_register_frontend()`](#c-dvb_register_frontend).

**NOTE**

This function doesn't frees the memory allocated by the demod,
by the SEC driver and by the tuner. In order to free it, an explicit call to
[`dvb_frontend_detach()`](#c-dvb_frontend_detach) is needed, after calling this function.

#### <a id="c-dvb_frontend_detach"></a>`dvb_frontend_detach()`

```c
void dvb_frontend_detach(struct dvb_frontend *fe)
```

Detaches and frees frontend specific data

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

This function should be called after [`dvb_unregister_frontend()`](#c-dvb_unregister_frontend). It
calls the SEC, tuner and demod release functions:
[`dvb_frontend_ops.release_sec`](#c-struct-dvb_frontend_ops), [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).release,
[`dvb_frontend_ops.analog_ops`](#c-struct-dvb_frontend_ops).release and [`dvb_frontend_ops.release`](#c-struct-dvb_frontend_ops).

If the driver is compiled with `CONFIG_MEDIA_ATTACH`, it also decreases
the module reference count, needed to allow userspace to remove the
previously used DVB frontend modules.

#### <a id="c-dvb_frontend_suspend"></a>`dvb_frontend_suspend()`

```c
int dvb_frontend_suspend(struct dvb_frontend *fe)
```

Suspends a Digital TV frontend

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

This function prepares a Digital TV frontend to suspend.

In order to prepare the tuner to suspend, if
[`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).suspend\(\) is available, it calls it. Otherwise,
it will call [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).sleep\(\), if available.

It will also call [`dvb_frontend_ops.suspend`](#c-struct-dvb_frontend_ops)\(\) to put the demod to suspend,
if available. Otherwise it will call [`dvb_frontend_ops.sleep`](#c-struct-dvb_frontend_ops)\(\).

The drivers should also call dvb_frontend_suspend\(\) as part of their
handler for the [`device_driver.suspend`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device_driver)\(\).

#### <a id="c-dvb_frontend_resume"></a>`dvb_frontend_resume()`

```c
int dvb_frontend_resume(struct dvb_frontend *fe)
```

Resumes a Digital TV frontend

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

This function resumes the usual operation of the tuner after resume.

In order to resume the frontend, it calls the demod
[`dvb_frontend_ops.resume`](#c-struct-dvb_frontend_ops)\(\) if available. Otherwise it calls demod
[`dvb_frontend_ops.init`](#c-struct-dvb_frontend_ops)\(\).

If [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).resume\(\) is available, It, it calls it.
Otherwise,t will call [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).init\(\), if available.

Once tuner and demods are resumed, it will enforce that the SEC voltage and
tone are restored to their previous values and wake up the frontend's
kthread in order to retune the frontend.

The drivers should also call [`dvb_frontend_resume()`](#c-dvb_frontend_resume) as part of their
handler for the [`device_driver.resume`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device_driver)\(\).

#### <a id="c-dvb_frontend_reinitialise"></a>`dvb_frontend_reinitialise()`

```c
void dvb_frontend_reinitialise(struct dvb_frontend *fe)
```

forces a reinitialisation at the frontend

**Parameters**

- `struct dvb_frontend *fe`: pointer to [`struct dvb_frontend`](#c-struct-dvb_frontend)

**Description**

Calls [`dvb_frontend_ops.init`](#c-struct-dvb_frontend_ops)\(\) and [`dvb_frontend_ops.tuner_ops`](#c-struct-dvb_frontend_ops).init\(\),
and resets SEC tone and voltage (for Satellite systems).

**NOTE**

Currently, this function is used only by one driver (budget-av).
It seems to be due to address some special issue with that specific
frontend.

#### <a id="c-dvb_frontend_sleep_until"></a>`dvb_frontend_sleep_until()`

```c
void dvb_frontend_sleep_until(ktime_t *waketime, u32 add_usec)
```

Sleep for the amount of time given by add_usec parameter

**Parameters**

- `ktime_t *waketime`: pointer to `struct ktime_t`
- `u32 add_usec`: time to sleep, in microseconds

**Description**

This function is used to measure the time required for the
`FE_DISHNETWORK_SEND_LEGACY_CMD()` ioctl to work. It needs to be as precise
as possible, as it affects the detection of the dish tone command at the
satellite subsystem.

Its used internally by the DVB frontend core, in order to emulate
`FE_DISHNETWORK_SEND_LEGACY_CMD()` using the [`dvb_frontend_ops.set_voltage`](#c-struct-dvb_frontend_ops)\(\)
callback.

**NOTE**

it should not be used at the drivers, as the emulation for the
legacy callback is provided by the Kernel. The only situation where this
should be at the drivers is when there are some bugs at the hardware that
would prevent the core emulation to work. On such cases, the driver would
be writing a [`dvb_frontend_ops.dishnetwork_send_legacy_command`](#c-struct-dvb_frontend_ops)\(\) and
calling this function directly.

---

# Digital TV Network kABI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Digital TV Network kABI.

<a id="rst-digital-tv-network-kabi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-dvb_net"></a>`struct dvb_net`

describes a DVB network interface

**Definition**

```c
struct dvb_net {
    struct dvb_device *dvbdev;
    struct net_device *device[DVB_NET_DEVICES_MAX];
    int state[DVB_NET_DEVICES_MAX];
    unsigned int exit:1;
    struct dmx_demux *demux;
    struct mutex ioctl_mutex;
    struct mutex remove_mutex;
};
```

**Members**

- `dvbdev`: pointer to [`struct dvb_device`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_device).
- `device`: array of pointers to [`struct net_device`](/kernel/internals/networking/kapi.md#c-struct-net_device).
- `state`: array of integers to each net device. A value
  different than zero means that the interface is
  in usage.
- `exit`: flag to indicate when the device is being removed.
- `demux`: pointer to [`struct dmx_demux`](/kernel/hardware/driver-api/media/dtv-demux.md#c-struct-dmx_demux).
- `ioctl_mutex`: protect access to this struct.
- `remove_mutex`: mutex that avoids a race condition between a callback
  called when the hardware is disconnected and the
  file_operations of dvb_net.

**Description**

Currently, the core supports up to `DVB_NET_DEVICES_MAX` (10) network
devices.

#### <a id="c-dvb_net_init"></a>`dvb_net_init()`

```c
int dvb_net_init(struct dvb_adapter *adap, struct dvb_net *dvbnet, struct dmx_demux *dmxdemux)
```

nitializes a digital TV network device and registers it.

**Parameters**

- `struct dvb_adapter *adap`: pointer to [`struct dvb_adapter`](/kernel/hardware/driver-api/media/dtv-common.md#c-struct-dvb_adapter).
- `struct dvb_net *dvbnet`: pointer to [`struct dvb_net`](#c-struct-dvb_net).
- `struct dmx_demux *dmxdemux`: pointer to [`struct dmx_demux`](/kernel/hardware/driver-api/media/dtv-demux.md#c-struct-dmx_demux).

#### <a id="c-dvb_net_release"></a>`dvb_net_release()`

```c
void dvb_net_release(struct dvb_net *dvbnet)
```

releases a digital TV network device and unregisters it.

**Parameters**

- `struct dvb_net *dvbnet`: pointer to [`struct dvb_net`](#c-struct-dvb_net).

---

# Media Subsystem Profile

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The media subsystem covers support for a variety of devices: stream capture, analog and digital TV streams, cameras, remote controllers, HDMI CEC and media pipeline control.

<a id="rst-media-subsystem-profile"></a>

<a id="rst-overview"></a>

## Overview

The media subsystem covers support for a variety of devices: stream capture, analog and digital TV streams, cameras, remote controllers, HDMI CEC and media pipeline control.

It covers, mainly, the contents of those directories:

> - drivers/media
>
> - drivers/staging/media
>
> - Documentation/admin-guide/media
>
> - Documentation/driver-api/media
>
> - Documentation/userspace-api/media
>
> - Documentation/devicetree/bindings/media/<a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)
>
> - include/media

<a id="rst-footnote-1"></a>



**[1]** Device tree bindings are maintained by the OPEN FIRMWARE AND FLATTENED DEVICE TREE BINDINGS maintainers (see the MAINTAINERS file). So, changes there must be reviewed by them before being merged via the media subsystem's development tree.

Both media userspace and Kernel APIs are documented and the documentation must be kept in sync with the API changes. It means that all patches that add new features to the subsystem must also bring changes to the corresponding API files.

Due to the size and wide scope of the media subsystem, media's maintainership model is to have sub-maintainers that have a broad knowledge of a specific aspect of the subsystem. It is the sub-maintainers' task to review the patches, providing feedback to users if the patches are following the subsystem rules and are properly using the media kernel and userspace APIs.

Patches for the media subsystem must be sent to the media mailing list at [linux-media@vger.kernel.org](<mailto:linux-media@vger.kernel.org>) as plain text only e-mail. Emails with HTML will be automatically rejected by the mail server. It could be wise to also copy the sub-maintainer(s).

Media's workflow is heavily based on Patchwork, meaning that, once a patch is submitted, the e-mail will first be accepted by the mailing list server, and, after a while, it should appear at:

> - [https://patchwork.linuxtv.org/project/linux-media/list/](<https://patchwork.linuxtv.org/project/linux-media/list/>)

If it doesn't automatically appear there after a few minutes, then probably something went wrong on your submission. Please check if the email is in plain text<a id="rst-footnote-reference-2"></a>[2](#rst-footnote-2) only and if your emailer is not mangling whitespaces before complaining or submitting them again.

You can check if the mailing list server accepted your patch, by looking at:

> - [https://lore.kernel.org/linux-media/](<https://lore.kernel.org/linux-media/>)

<a id="rst-footnote-2"></a>



**[2]** If your email contains HTML, the mailing list server will simply drop it, without any further notice.

<a id="rst-media-maintainers"></a>

### Media maintainers

At the media subsystem, we have a group of senior developers that are responsible for doing the code reviews at the drivers (also known as sub-maintainers), and another senior developer responsible for the subsystem as a whole. For core changes, whenever possible, multiple media maintainers do the review.

The media maintainers that work on specific areas of the subsystem are:

- - **Remote Controllers (infrared):**

    Sean Young &lt;[sean@mess.org](<mailto:sean@mess.org>)&gt;

- - **HDMI CEC:**

    Hans Verkuil &lt;[hverkuil@kernel.org](<mailto:hverkuil@kernel.org>)&gt;

- - **Media controller drivers:**

    Laurent Pinchart &lt;[laurent.pinchart@ideasonboard.com](<mailto:laurent.pinchart@ideasonboard.com>)&gt;

- - **ISP, v4l2-async, v4l2-fwnode, v4l2-flash-led-class and Sensor drivers:**

    Sakari Ailus &lt;[sakari.ailus@linux.intel.com](<mailto:sakari.ailus@linux.intel.com>)&gt;

- - **V4L2 drivers and core V4L2 frameworks:**

    Hans Verkuil &lt;[hverkuil@kernel.org](<mailto:hverkuil@kernel.org>)&gt;

- **The subsystem maintainer is:**

  Mauro Carvalho Chehab &lt;[mchehab@kernel.org](<mailto:mchehab@kernel.org>)&gt;

Media maintainers may delegate a patch to other media maintainers as needed. On such case, checkpatch's `delegate` field indicates who's currently responsible for reviewing a patch.

<a id="rst-submit-checklist-addendum"></a>

## Submit Checklist Addendum

Patches that change the Open Firmware/Device Tree bindings must be reviewed by the Device Tree maintainers. So, DT maintainers should be Cc:ed when those are submitted via devicetree@vger.kernel.org mailing list.

There is a set of compliance tools at [https://git.linuxtv.org/v4l-utils.git/](<https://git.linuxtv.org/v4l-utils.git/>) that should be used in order to check if the drivers are properly implementing the media APIs:


<table>
<thead>
<tr>
<th>


Type

</th>
<th>


Tool

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


V4L2 drivers<a id="rst-footnote-reference-3"></a>[3](#rst-footnote-3)

</td>
<td>


`v4l2-compliance`

</td>
</tr>
<tr>
<td>


V4L2 virtual drivers

</td>
<td>


`contrib/test/test-media`

</td>
</tr>
<tr>
<td>


CEC drivers

</td>
<td>


`cec-compliance`

</td>
</tr>
</tbody>
</table>

<a id="rst-footnote-3"></a>



**[3]** The `v4l2-compliance` also covers the media controller usage inside V4L2 drivers.

Other compliance tools are under development to check other parts of the subsystem.

Those tests need to pass before the patches go upstream.

Also, please notice that we build the Kernel with:



```text
make CF=-D__CHECK_ENDIAN__ CONFIG_DEBUG_SECTION_MISMATCH=y C=1 W=1 CHECK=check_script
```

Where the check script is:



```text
#!/bin/bash
/devel/smatch/smatch -p=kernel $@ >&2
/devel/sparse/sparse $@ >&2
```

Be sure to not introduce new warnings on your patches without a very good reason.

<a id="rst-style-cleanup-patches"></a>

### Style Cleanup Patches

Style cleanups are welcome when they come together with other changes at the files where the style changes will affect.

We may accept pure standalone style cleanups, but they should ideally be one patch for the whole subsystem (if the cleanup is low volume), or at least be grouped per directory. So, for example, if you're doing a big cleanup change set at drivers under drivers/media, please send a single patch for all drivers under drivers/media/pci, another one for drivers/media/usb and so on.

<a id="rst-coding-style-addendum"></a>

### Coding Style Addendum

Media development uses `checkpatch.pl` on strict mode to verify the code style, e.g.:



```text
$ ./scripts/checkpatch.pl --strict --max-line-length=80
```

In principle, patches should follow the coding style rules, but exceptions are allowed if there are good reasons. On such case, maintainers and reviewers may question about the rationale for not addressing the `checkpatch.pl`.

Please notice that the goal here is to improve code readability. On a few cases, `checkpatch.pl` may actually point to something that would look worse. So, you should use good sense.

Note that addressing one `checkpatch.pl` issue (of any kind) alone may lead to having longer lines than 80 characters per line. While this is not strictly prohibited, efforts should be made towards staying within 80 characters per line. This could include using re-factoring code that leads to less indentation, shorter variable or function names and last but not least, simply wrapping the lines.

In particular, we accept lines with more than 80 columns:

> - on strings, as they shouldn't be broken due to line length limits;
>
> - when a function or variable name need to have a big identifier name, which keeps hard to honor the 80 columns limit;
>
> - on arithmetic expressions, when breaking lines makes them harder to read;
>
> - when they avoid a line to end with an open parenthesis or an open bracket.

<a id="rst-key-cycle-dates"></a>

## Key Cycle Dates

New submissions can be sent at any time, but if they intend to hit the next merge window they should be sent before -rc5, and ideally stabilized in the linux-media branch by -rc6.

<a id="rst-review-cadence"></a>

## Review Cadence

Provided that your patch is at [https://patchwork.linuxtv.org](<https://patchwork.linuxtv.org>), it should be sooner or later handled, so you don't need to re-submit a patch.

Except for bug fixes, we don't usually add new patches to the development tree between -rc6 and the next -rc1.

Please notice that the media subsystem is a high traffic one, so it could take a while for us to be able to review your patches. Feel free to ping if you don't get a feedback in a couple of weeks or to ask other developers to publicly add Reviewed-by and, more importantly, `Tested-by:` tags.

Please note that we expect a detailed description for `Tested-by:`, identifying what boards were used at the test and what it was tested.

---

# Media Controller devices

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The media controller userspace API is documented in the Media Controller uAPI book <media_controller>. This document focus on the kernel-side implementation of the media framework.

<a id="rst-media-controller-devices"></a>

<a id="rst-media-controller"></a>

## Media Controller

<!-- SPDX-License-Identifier: GPL-2.0 -->

The media controller userspace API is documented in [the Media Controller uAPI book](</kernel/userspace/userspace-api/media-mediactl/media-controller.md#rst-media-controller>). This document focus on the kernel-side implementation of the media framework.

<a id="rst-abstract-media-device-model"></a>

## Abstract media device model

Discovering a device internal topology, and configuring it at runtime, is one of the goals of the media framework. To achieve this, hardware devices are modelled as an oriented graph of building blocks called entities connected through pads.

An entity is a basic media hardware building block. It can correspond to a large variety of logical blocks such as physical hardware devices (CMOS sensor for instance), logical hardware devices (a building block in a System-on-Chip image processing pipeline), DMA channels or physical connectors.

A pad is a connection endpoint through which an entity can interact with other entities. Data (not restricted to video) produced by an entity flows from the entity's output to one or more entity inputs. Pads should not be confused with physical pins at chip boundaries.

A link is a point-to-point oriented connection between two pads, either on the same entity or on different entities. Data flows from a source pad to a sink pad.

<a id="rst-media-device"></a>

## Media device

A media device is represented by a struct media_device instance, defined in `include/media/media-device.h`. Allocation of the structure is handled by the media device driver, usually by embedding the `media_device` instance in a larger driver-specific structure.

Drivers initialise media device instances by calling `media_device_init()`. After initialising a media device instance, it is registered by calling `__media_device_register()` via the macro `media_device_register()` and unregistered by calling `media_device_unregister()`. An initialised media device must be eventually cleaned up by calling `media_device_cleanup()`.

Note that it is not allowed to unregister a media device instance that was not previously registered, or clean up a media device instance that was not previously initialised.

<a id="rst-entities"></a>

## Entities

Entities are represented by a struct media_entity instance, defined in `include/media/media-entity.h`. The structure is usually embedded into a higher-level structure, such as `v4l2_subdev` or `video_device` instances, although drivers can allocate entities directly.

Drivers initialize entity pads by calling `media_entity_pads_init()`.

Drivers register entities with a media device by calling `media_device_register_entity()` and unregistered by calling `media_device_unregister_entity()`.

<a id="rst-interfaces"></a>

## Interfaces

Interfaces are represented by a struct media_interface instance, defined in `include/media/media-entity.h`. Currently, only one type of interface is defined: a device node. Such interfaces are represented by a struct media_intf_devnode.

Drivers initialize and create device node interfaces by calling `media_devnode_create()` and remove them by calling: `media_devnode_remove()`.

<a id="rst-pads"></a>

## Pads

Pads are represented by a struct media_pad instance, defined in `include/media/media-entity.h`. Each entity stores its pads in a pads array managed by the entity driver. Drivers usually embed the array in a driver-specific structure.

Pads are identified by their entity and their 0-based index in the pads array.

Both information are stored in the struct media_pad, making the struct media_pad pointer the canonical way to store and pass link references.

Pads have flags that describe the pad capabilities and state.

`MEDIA_PAD_FL_SINK` indicates that the pad supports sinking data. `MEDIA_PAD_FL_SOURCE` indicates that the pad supports sourcing data.

> [!NOTE]
>
> One and only one of `MEDIA_PAD_FL_SINK` or `MEDIA_PAD_FL_SOURCE` must be set for each pad.

<a id="rst-links"></a>

## Links

Links are represented by a struct media_link instance, defined in `include/media/media-entity.h`. There are two types of links:

**1. pad to pad links**:

Associate two entities via their PADs. Each entity has a list that points to all links originating at or targeting any of its pads. A given link is thus stored twice, once in the source entity and once in the target entity.

Drivers create pad to pad links by calling: `media_create_pad_link()` and remove with `media_entity_remove_links()`.

**2. interface to entity links**:

Associate one interface to a Link.

Drivers create interface to entity links by calling: `media_create_intf_link()` and remove with `media_remove_intf_links()`.

> [!NOTE]
>
> Links can only be created after having both ends already created.

Links have flags that describe the link capabilities and state. The valid values are described at `media_create_pad_link()` and `media_create_intf_link()`.

<a id="rst-graph-traversal"></a>

## Graph traversal

The media framework provides APIs to traverse media graphs, locating connected entities and links.

To iterate over all entities belonging to a media device, drivers can use the media_device_for_each_entity macro, defined in `include/media/media-device.h`.



```c
struct media_entity *entity;

media_device_for_each_entity(entity, mdev) {
// entity will point to each entity in turn
...
}
```

Helper functions can be used to find a link between two given pads, or a pad connected to another pad through an enabled link (`media_entity_find_link()`, `media_pad_remote_pad_first()`, `media_entity_remote_source_pad_unique()` and `media_pad_remote_pad_unique()`).

<a id="rst-use-count-and-power-handling"></a>

## Use count and power handling

Due to the wide differences between drivers regarding power management needs, the media controller does not implement power management. However, the struct media_entity includes a `use_count` field that media drivers can use to track the number of users of every entity for power management needs.

The `media_entity<media_entity>`.`use_count` field is owned by media drivers and must not be touched by entity drivers. Access to the field must be protected by the `media_device`.`graph_mutex` lock.

<a id="rst-links-setup"></a>

## Links setup

Link properties can be modified at runtime by calling `media_entity_setup_link()`.

<a id="rst-pipelines-and-media-streams"></a>

## Pipelines and media streams

A media stream is a stream of pixels or metadata originating from one or more source devices (such as a sensors) and flowing through media entity pads towards the final sinks. The stream can be modified on the route by the devices (e.g. scaling or pixel format conversions), or it can be split into multiple branches, or multiple branches can be merged.

A media pipeline is a set of media streams which are interdependent. This interdependency can be caused by the hardware (e.g. configuration of a second stream cannot be changed if the first stream has been enabled) or by the driver due to the software design. Most commonly a media pipeline consists of a single stream which does not branch.

When starting streaming, drivers must notify all entities in the pipeline to prevent link states from being modified during streaming by calling `media_pipeline_start()`.

The function will mark all the pads which are part of the pipeline as streaming.

The struct media_pipeline instance pointed to by the pipe argument will be stored in every pad in the pipeline. Drivers should embed the struct media_pipeline in higher-level pipeline structures and can then access the pipeline through the struct media_pad pipe field.

Calls to `media_pipeline_start()` can be nested. The pipeline pointer must be identical for all nested calls to the function.

`media_pipeline_start()` may return an error. In that case, it will clean up any of the changes it did by itself.

When stopping the stream, drivers must notify the entities with `media_pipeline_stop()`.

If multiple calls to `media_pipeline_start()` have been made the same number of `media_pipeline_stop()` calls are required to stop streaming. The `media_entity`.`pipe` field is reset to `NULL` on the last nested stop call.

Link configuration will fail with `-EBUSY` by default if either end of the link is a streaming entity. Links that can be modified while streaming must be marked with the `MEDIA_LNK_FL_DYNAMIC` flag.

If other operations need to be disallowed on streaming entities (such as changing entities configuration parameters) drivers can explicitly check the media_entity stream_count field to find out if an entity is streaming. This operation must be done with the media_device graph_mutex held.

<a id="rst-link-validation"></a>

## Link validation

Link validation is performed by `media_pipeline_start()` for any entity which has sink pads in the pipeline. The `media_entity`.`link_validate()` callback is used for that purpose. In `link_validate()` callback, entity driver should check that the properties of the source pad of the connected entity and its own sink pad match. It is up to the type of the entity (and in the end, the properties of the hardware) what matching actually means.

Subsystems should facilitate link validation by providing subsystem specific helper functions to provide easy access for commonly needed information, and in the end provide a way to use driver-specific callbacks.

<a id="rst-pipeline-traversal"></a>

## Pipeline traversal

Once a pipeline has been constructed with `media_pipeline_start()`, drivers can iterate over entities or pads in the pipeline with the :c:macro:´media_pipeline_for_each_entity\` and :c:macro:´media_pipeline_for_each_pad\` macros. Iterating over pads is straightforward:



```c
media_pipeline_pad_iter iter;
struct media_pad *pad;

media_pipeline_for_each_pad(pipe, &iter, pad) {
    /* 'pad' will point to each pad in turn */
    ...
}
```

To iterate over entities, the iterator needs to be initialized and cleaned up as an additional steps:



```c
media_pipeline_entity_iter iter;
struct media_entity *entity;
int ret;

ret = media_pipeline_entity_iter_init(pipe, &iter);
if (ret)
    ...;

media_pipeline_for_each_entity(pipe, &iter, entity) {
    /* 'entity' will point to each entity in turn */
    ...
}

media_pipeline_entity_iter_cleanup(&iter);
```

<a id="rst-media-controller-device-allocator-api"></a>

## Media Controller Device Allocator API

When the media device belongs to more than one driver, the shared media device is allocated with the shared struct device as the key for look ups.

The shared media device should stay in registered state until the last driver unregisters it. In addition, the media device should be released when all the references are released. Each driver gets a reference to the media device during probe, when it allocates the media device. If media device is already allocated, the allocate API bumps up the refcount and returns the existing media device. The driver puts the reference back in its disconnect routine when it calls `media_device_delete()`.

The media device is unregistered and cleaned up from the kref put handler to ensure that the media device stays in registered state until the last driver unregisters the media device.

**Driver Usage**

Drivers should use the appropriate media-core routines to manage the shared media device life-time handling the two states: 1. allocate -&gt; register -&gt; delete 2. get reference to already registered device -&gt; delete

call `media_device_delete()` routine to make sure the shared media device delete is handled correctly.

**driver probe:** Call `media_device_usb_allocate()` to allocate or get a reference Call `media_device_register()`, if media devnode isn't registered

**driver disconnect:** Call `media_device_delete()` to free the media_device. Freeing is handled by the kref put handler.

<a id="rst-api-definitions"></a>

## API Definitions


#### <a id="c-struct-media_entity_notify"></a>`struct media_entity_notify`

Media Entity Notify

**Definition**

```c
struct media_entity_notify {
    struct list_head list;
    void *notify_data;
    void (*notify)(struct media_entity *entity, void *notify_data);
};
```

**Members**

- `list`: List head
- `notify_data`: Input data to invoke the callback
- `notify`: Callback function pointer

**Description**

Drivers may register a callback to take action when new entities get
registered with the media device. This handler is intended for creating
links between existing entities and should not create entities and register
them.

#### <a id="c-struct-media_device_ops"></a>`struct media_device_ops`

Media device operations

**Definition**

```c
struct media_device_ops {
    int (*link_notify)(struct media_link *link, u32 flags, unsigned int notification);
    struct media_request *(*req_alloc)(struct media_device *mdev);
    void (*req_free)(struct media_request *req);
    int (*req_validate)(struct media_request *req);
    void (*req_queue)(struct media_request *req);
};
```

**Members**

- `link_notify`: Link state change notification callback. This callback is
  called with the graph_mutex held.
- `req_alloc`: Allocate a request. Set this if you need to allocate a struct
  larger then struct media_request. **req_alloc** and **req_free** must
  either both be set or both be NULL.
- `req_free`: Free a request. Set this if **req_alloc** was set as well, leave
  to NULL otherwise.
- `req_validate`: Validate a request, but do not queue yet. The req_queue_mutex
  lock is held when this op is called.
- `req_queue`: Queue a validated request, cannot fail. If something goes
  wrong when queueing this request then it should be marked
  as such internally in the driver and any related buffers
  must eventually return to vb2 with state VB2_BUF_STATE_ERROR.
  The req_queue_mutex lock is held when this op is called.
  It is important that vb2 buffer objects are queued last after
  all other object types are queued: queueing a buffer kickstarts
  the request processing, so all other objects related to the
  request (and thus the buffer) must be available to the driver.
  And once a buffer is queued, then the driver can complete
  or delete objects from the request before req_queue exits.

#### <a id="c-struct-media_device"></a>`struct media_device`

Media device

**Definition**

```c
struct media_device {
    struct device *dev;
    struct media_devnode *devnode;
    char model[32];
    char driver_name[32];
    char serial[40];
    char bus_info[32];
    u32 hw_revision;
    u64 topology_version;
    u32 id;
    struct ida entity_internal_idx;
    int entity_internal_idx_max;
    struct list_head entities;
    struct list_head interfaces;
    struct list_head pads;
    struct list_head links;
    struct list_head entity_notify;
    struct mutex graph_mutex;
    struct media_graph pm_count_walk;
    void *source_priv;
    int (*enable_source)(struct media_entity *entity, struct media_pipeline *pipe);
    void (*disable_source)(struct media_entity *entity);
    const struct media_device_ops *ops;
    struct mutex req_queue_mutex;
    atomic_t num_requests;
    atomic_t num_request_objects;
    struct dentry *media_dir;
    atomic_t request_id;
};
```

**Members**

- `dev`: Parent device
- `devnode`: Media device node
- `model`: Device model name
- `driver_name`: Optional device driver name. If not set, calls to
  `MEDIA_IOC_DEVICE_INFO` will return `dev->driver->name`.
  This is needed for USB drivers for example, as otherwise
  they'll all appear as if the driver name was "usb".
- `serial`: Device serial number (optional)
- `bus_info`: Unique and stable device location identifier
- `hw_revision`: Hardware device revision
- `topology_version`: Monotonic counter for storing the version of the graph
  topology. Should be incremented each time the topology changes.
- `id`: Unique ID used on the last registered graph object
- `entity_internal_idx`: Unique internal entity ID used by the graph traversal
  algorithms
- `entity_internal_idx_max`: Allocated internal entity indices
- `entities`: List of registered entities
- `interfaces`: List of registered interfaces
- `pads`: List of registered pads
- `links`: List of registered links
- `entity_notify`: List of registered entity_notify callbacks
- `graph_mutex`: Protects access to struct media_device data
- `pm_count_walk`: Graph walk for power state walk. Access serialised using
  graph_mutex.
- `source_priv`: Driver Private data for enable/disable source handlers
- `enable_source`: Enable Source Handler function pointer
- `disable_source`: Disable Source Handler function pointer
- `ops`: Operation handler callbacks
- `req_queue_mutex`: Serialise the MEDIA_REQUEST_IOC_QUEUE ioctl w.r.t.
  other operations that stop or start streaming.
- `num_requests`: number of associated requests
- `num_request_objects`: number of associated request objects
- `media_dir`: DebugFS media directory
- `request_id`: Used to generate unique request IDs

**Description**

This structure represents an abstract high-level media device. It allows easy
access to entities and provides basic media device-level support. The
structure can be allocated directly or embedded in a larger structure.

The parent **dev** is a physical device. It must be set before registering the
media device.

**model** is a descriptive model name exported through sysfs. It doesn't have to
be unique.

**enable_source** is a handler to find source entity for the
sink entity  and activate the link between them if source
entity is free. Drivers should call this handler before
accessing the source.

**disable_source** is a handler to find source entity for the
sink entity  and deactivate the link between them. Drivers
should call this handler to release the source.

Use-case: find tuner entity connected to the decoder
entity and check if it is available, and activate the
link between them from **enable_source** and deactivate
from **disable_source**.

> [!NOTE]
> Bridge driver is expected to implement and set the
> handler when [`media_device`](#c-struct-media_device) is registered or when
> bridge driver finds the media_device during probe.
> Bridge driver sets source_priv with information
> necessary to run **enable_source** and **disable_source** handlers.
> Callers should hold graph_mutex to access and call **enable_source**
> and **disable_source** handlers.

#### <a id="c-media_device_init"></a>`media_device_init()`

```c
void media_device_init(struct media_device *mdev)
```

Initializes a media device element

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)

**Description**

This function initializes the media device prior to its registration.
The media device initialization and registration is split in two functions
to avoid race conditions and make the media device available to user-space
before the media graph has been completed.

So drivers need to first initialize the media device, register any entity
within the media device, create pad to pad links and then finally register
the media device by calling [`media_device_register()`](#c-media_device_register) as a final step.

The caller is responsible for initializing the media device before
registration. The following fields must be set:

- dev must point to the parent device
- model must be filled with the device model name

The bus_info field is set by [`media_device_init()`](#c-media_device_init) for PCI and platform devices
if the field begins with '\0'.

#### <a id="c-media_device_cleanup"></a>`media_device_cleanup()`

```c
void media_device_cleanup(struct media_device *mdev)
```

Cleanups a media device element

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)

**Description**

This function that will destroy the graph_mutex that is
initialized in [`media_device_init()`](#c-media_device_init).

#### <a id="c-__media_device_register"></a>`__media_device_register()`

```c
int __media_device_register(struct media_device *mdev, struct module *owner)
```

Registers a media device element

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `struct module *owner`: should be filled with `THIS_MODULE`

**Description**

Users, should, instead, call the [`media_device_register()`](#c-media_device_register) macro.

The caller is responsible for initializing the [`media_device`](#c-struct-media_device) structure
before registration. The following fields of [`media_device`](#c-struct-media_device) must be set:

- [`media_device.model`](#c-struct-media_device) must be filled with the device model name as a
  NUL-terminated UTF-8 string. The device/model revision must not be
  stored in this field.

The following fields are optional:

- [`media_device.serial`](#c-struct-media_device) is a unique serial number stored as a
  NUL-terminated ASCII string. The field is big enough to store a GUID
  in text form. If the hardware doesn't provide a unique serial number
  this field must be left empty.

- [`media_device.bus_info`](#c-struct-media_device) represents the location of the device in the
  system as a NUL-terminated ASCII string. For PCI/PCIe devices
  [`media_device.bus_info`](#c-struct-media_device) must be set to "PCI:" (or "PCIe:") followed by
  the value of `pci_name()`. For USB devices,the [`usb_make_path()`](/kernel/hardware/driver-api/usb/usb.md#c-usb_make_path) function
  must be used. This field is used by applications to distinguish between
  otherwise identical devices that don't provide a serial number.

- [`media_device.hw_revision`](#c-struct-media_device) is the hardware device revision in a
  driver-specific format. When possible the revision should be formatted
  with the `KERNEL_VERSION()` macro.

> [!NOTE]
> \#) Upon successful registration a character device named media\[0-9\]+ is created. The device major and minor numbers are dynamic. The model name is exported as a sysfs attribute.
>
> \#) Unregistering a media device that hasn't been registered is **NOT** safe.

**Return**

returns zero on success or a negative error code.

#### <a id="c-media_device_register"></a>`media_device_register()`

```c
media_device_register(mdev)
```

Registers a media device element

**Parameters**

- `mdev`: pointer to struct [`media_device`](#c-struct-media_device)

**Description**

This macro calls [`__media_device_register()`](#c-__media_device_register) passing `THIS_MODULE` as
the [`__media_device_register()`](#c-__media_device_register) second argument (**owner**).

#### <a id="c-media_device_unregister"></a>`media_device_unregister()`

```c
void media_device_unregister(struct media_device *mdev)
```

Unregisters a media device element

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)

**Description**

It is safe to call this function on an unregistered (but initialised)
media device.

#### <a id="c-media_device_register_entity"></a>`media_device_register_entity()`

```c
int media_device_register_entity(struct media_device *mdev, struct media_entity *entity)
```

registers a media entity inside a previously registered media device.

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `struct media_entity *entity`: pointer to struct [`media_entity`](#c-struct-media_entity) to be registered

**Description**

Entities are identified by a unique positive integer ID. The media
controller framework will such ID automatically. IDs are not guaranteed
to be contiguous, and the ID number can change on newer Kernel versions.
So, neither the driver nor userspace should hardcode ID numbers to refer
to the entities, but, instead, use the framework to find the ID, when
needed.

The media_entity name, type and flags fields should be initialized before
calling [`media_device_register_entity()`](#c-media_device_register_entity). Entities embedded in higher-level
standard structures can have some of those fields set by the higher-level
framework.

If the device has pads, [`media_entity_pads_init()`](#c-media_entity_pads_init) should be called before
this function. Otherwise, the [`media_entity.pad`](#c-struct-media_entity) and [`media_entity.num_pads`](#c-struct-media_entity)
should be zeroed before calling this function.

Entities have flags that describe the entity capabilities and state:

- `MEDIA_ENT_FL_DEFAULT`:
  indicates the default entity for a given type.
  This can be used to report the default audio and video devices or the
  default camera sensor.

> [!NOTE]
> Drivers should set the entity function before calling this function.
> Please notice that the values `MEDIA_ENT_F_V4L2_SUBDEV_UNKNOWN` and
> `MEDIA_ENT_F_UNKNOWN` should not be used by the drivers.

#### <a id="c-media_device_unregister_entity"></a>`media_device_unregister_entity()`

```c
void media_device_unregister_entity(struct media_entity *entity)
```

unregisters a media entity.

**Parameters**

- `struct media_entity *entity`: pointer to struct [`media_entity`](#c-struct-media_entity) to be unregistered

**Description**

All links associated with the entity and all PADs are automatically
unregistered from the media_device when this function is called.

Unregistering an entity will not change the IDs of the other entities and
the previoully used ID will never be reused for a newly registered entities.

When a media device is unregistered, all its entities are unregistered
automatically. No manual entities unregistration is then required.

> [!NOTE]
> The media_entity instance itself must be freed explicitly by
> the driver if required.

#### <a id="c-media_device_register_entity_notify"></a>`media_device_register_entity_notify()`

```c
void media_device_register_entity_notify(struct media_device *mdev, struct media_entity_notify *nptr)
```

Registers a media entity_notify callback

**Parameters**

- `struct media_device *mdev`: The media device
- `struct media_entity_notify *nptr`: The media_entity_notify

**Description**

> [!NOTE]
> When a new entity is registered, all the registered
> media_entity_notify callbacks are invoked.

#### <a id="c-media_device_unregister_entity_notify"></a>`media_device_unregister_entity_notify()`

```c
void media_device_unregister_entity_notify(struct media_device *mdev, struct media_entity_notify *nptr)
```

Unregister a media entity notify callback

**Parameters**

- `struct media_device *mdev`: The media device
- `struct media_entity_notify *nptr`: The media_entity_notify

#### <a id="c-media_device_pci_init"></a>`media_device_pci_init()`

```c
void media_device_pci_init(struct media_device *mdev, struct pci_dev *pci_dev, const char *name)
```

create and initialize a struct [`media_device`](#c-struct-media_device) from a PCI device.

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `struct pci_dev *pci_dev`: pointer to struct pci_dev
- `const char *name`: media device name. If `NULL`, the routine will use the default
  name for the pci device, given by `pci_name()` macro.

#### <a id="c-__media_device_usb_init"></a>`__media_device_usb_init()`

```c
void __media_device_usb_init(struct media_device *mdev, struct usb_device *udev, const char *board_name, const char *driver_name)
```

create and initialize a struct [`media_device`](#c-struct-media_device) from a PCI device.

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `struct usb_device *udev`: pointer to struct usb_device
- `const char *board_name`: media device name. If `NULL`, the routine will use the usb
  product name, if available.
- `const char *driver_name`: name of the driver. if `NULL`, the routine will use the name
  given by `udev->dev->driver->name`, with is usually the wrong
  thing to do.

**Description**

> [!NOTE]
> It is better to call [`media_device_usb_init()`](#c-media_device_usb_init) instead, as
> such macro fills driver_name with `KBUILD_MODNAME`.

#### <a id="c-media_device_usb_init"></a>`media_device_usb_init()`

```c
media_device_usb_init(mdev, udev, name)
```

create and initialize a struct [`media_device`](#c-struct-media_device) from a PCI device.

**Parameters**

- `mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `udev`: pointer to struct usb_device
- `name`: media device name. If `NULL`, the routine will use the usb
  product name, if available.

**Description**

This macro calls [`media_device_usb_init()`](#c-media_device_usb_init) passing the
[`media_device_usb_init()`](#c-media_device_usb_init) **driver_name** parameter filled with
`KBUILD_MODNAME`.

#### <a id="c-media_set_bus_info"></a>`media_set_bus_info()`

```c
void media_set_bus_info(char *bus_info, size_t bus_info_size, struct device *dev)
```

Set bus_info field

**Parameters**

- `char *bus_info`: Variable where to write the bus info (char array)
- `size_t bus_info_size`: Length of the bus_info
- `struct device *dev`: Related struct device

**Description**

Sets bus information based on `dev`. This is currently done for PCI and
platform devices. dev is required to be non-NULL for this to happen.

This function is not meant to be called from drivers.



#### <a id="c-struct-media_file_operations"></a>`struct media_file_operations`

Media device file operations

**Definition**

```c
struct media_file_operations {
    struct module *owner;
    ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
    ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
    __poll_t (*poll) (struct file *, struct poll_table_struct *);
    long (*ioctl) (struct file *, unsigned int, unsigned long);
    long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
    int (*open) (struct file *);
    int (*release) (struct file *);
};
```

**Members**

- `owner`: should be filled with `THIS_MODULE`
- `read`: pointer to the function that implements `read()` syscall
- `write`: pointer to the function that implements `write()` syscall
- `poll`: pointer to the function that implements `poll()` syscall
- `ioctl`: pointer to the function that implements `ioctl()` syscall
- `compat_ioctl`: pointer to the function that will handle 32 bits userspace
  calls to the `ioctl()` syscall on a Kernel compiled with 64 bits.
- `open`: pointer to the function that implements `open()` syscall
- `release`: pointer to the function that will release the resources allocated
  by the **open** function.

#### <a id="c-struct-media_devnode"></a>`struct media_devnode`

Media device node

**Definition**

```c
struct media_devnode {
    struct media_device *media_dev;
    const struct media_file_operations *fops;
    struct device dev;
    struct cdev cdev;
    struct device *parent;
    int minor;
    unsigned long flags;
    void (*release)(struct media_devnode *devnode);
};
```

**Members**

- `media_dev`: pointer to struct [`media_device`](#c-struct-media_device)
- `fops`: pointer to struct [`media_file_operations`](#c-struct-media_file_operations) with media device ops
- `dev`: pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) containing the media controller device
- `cdev`: struct cdev pointer character device
- `parent`: parent device
- `minor`: device node minor number
- `flags`: flags, combination of the `MEDIA_FLAG_*` constants
- `release`: release callback called at the end of `media_devnode_release()`
  routine at media-device.c.

**Description**

This structure represents a media-related device node.

The **parent** is a physical device. It must be set by core or device drivers
before registering the node.

#### <a id="c-media_devnode_register"></a>`media_devnode_register()`

```c
int media_devnode_register(struct media_device *mdev, struct media_devnode *devnode, struct module *owner)
```

register a media device node

**Parameters**

- `struct media_device *mdev`: struct media_device we want to register a device node
- `struct media_devnode *devnode`: media device node structure we want to register
- `struct module *owner`: should be filled with `THIS_MODULE`

**Description**

The registration code assigns minor numbers and registers the new device node
with the kernel. An error is returned if no free minor number can be found,
or if the registration of the device node fails.

Zero is returned on success.

Note that if the media_devnode_register call fails, the `release()` callback of
the media_devnode structure is *not* called, so the caller is responsible for
freeing any data.

#### <a id="c-media_devnode_unregister_prepare"></a>`media_devnode_unregister_prepare()`

```c
void media_devnode_unregister_prepare(struct media_devnode *devnode)
```

clear the media device node register bit

**Parameters**

- `struct media_devnode *devnode`: the device node to prepare for unregister

**Description**

This clears the passed device register bit. Future open calls will be met
with errors. Should be called before [`media_devnode_unregister()`](#c-media_devnode_unregister) to avoid
races with unregister and device file open calls.

This function can safely be called if the device node has never been
registered or has already been unregistered.

#### <a id="c-media_devnode_unregister"></a>`media_devnode_unregister()`

```c
void media_devnode_unregister(struct media_devnode *devnode)
```

unregister a media device node

**Parameters**

- `struct media_devnode *devnode`: the device node to unregister

**Description**

This unregisters the passed device. Future open calls will be met with
errors.

Should be called after [`media_devnode_unregister_prepare()`](#c-media_devnode_unregister_prepare)

#### <a id="c-media_devnode_data"></a>`media_devnode_data()`

```c
struct media_devnode * media_devnode_data(struct file *filp)
```

returns a pointer to the [`media_devnode`](#c-struct-media_devnode)

**Parameters**

- `struct file *filp`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)

#### <a id="c-media_devnode_is_registered"></a>`media_devnode_is_registered()`

```c
int media_devnode_is_registered(struct media_devnode *devnode)
```

returns true if [`media_devnode`](#c-struct-media_devnode) is registered; false otherwise.

**Parameters**

- `struct media_devnode *devnode`: pointer to struct [`media_devnode`](#c-struct-media_devnode).

**Note**

If mdev is NULL, it also returns false.



#### <a id="c-enum-media_gobj_type"></a>`enum media_gobj_type`

type of a graph object

**Constants**

- `MEDIA_GRAPH_ENTITY`: Identify a media entity
- `MEDIA_GRAPH_PAD`: Identify a media pad
- `MEDIA_GRAPH_LINK`: Identify a media link
- `MEDIA_GRAPH_INTF_DEVNODE`: Identify a media Kernel API interface via
  a device node

#### <a id="c-struct-media_gobj"></a>`struct media_gobj`

Define a graph object.

**Definition**

```c
struct media_gobj {
    struct media_device     *mdev;
    u32 id;
    struct list_head        list;
};
```

**Members**

- `mdev`: Pointer to the struct [`media_device`](#c-struct-media_device) that owns the object
- `id`: Non-zero object ID identifier. The ID should be unique
  inside a media_device, as it is composed by
  `MEDIA_BITS_PER_TYPE` to store the type plus
  `MEDIA_BITS_PER_ID` to store the ID
- `list`: List entry stored in one of the per-type mdev object lists

**Description**

All objects on the media graph should have this struct embedded

#### <a id="c-struct-media_entity_enum"></a>`struct media_entity_enum`

An enumeration of media entities.

**Definition**

```c
struct media_entity_enum {
    unsigned long *bmap;
    int idx_max;
};
```

**Members**

- `bmap`: Bit map in which each bit represents one entity at struct
  media_entity->internal_idx.
- `idx_max`: Number of bits in bmap

#### <a id="c-struct-media_graph"></a>`struct media_graph`

Media graph traversal state

**Definition**

```c
struct media_graph {
    struct {
        struct media_entity *entity;
        struct list_head *link;
    } stack[MEDIA_ENTITY_ENUM_MAX_DEPTH];
    struct media_entity_enum ent_enum;
    int top;
};
```

**Members**

- `stack`: Graph traversal stack; the stack contains information
  on the path the media entities to be walked and the
  links through which they were reached.
- `stack.entity`: pointer to [`struct media_entity`](#c-struct-media_entity) at the graph.
- `stack.link`: pointer to `struct list_head`.
- `ent_enum`: Visited entities
- `top`: The top of the stack

#### <a id="c-struct-media_pipeline"></a>`struct media_pipeline`

Media pipeline related information

**Definition**

```c
struct media_pipeline {
    bool allocated;
    struct media_device *mdev;
    struct list_head pads;
    int start_count;
};
```

**Members**

- `allocated`: Media pipeline allocated and freed by the framework
- `mdev`: The media device the pipeline is part of
- `pads`: List of media_pipeline_pad
- `start_count`: Media pipeline start - stop count

#### <a id="c-struct-media_pipeline_pad"></a>`struct media_pipeline_pad`

A pad part of a media pipeline

**Definition**

```c
struct media_pipeline_pad {
    struct list_head list;
    struct media_pipeline *pipe;
    struct media_pad *pad;
};
```

**Members**

- `list`: Entry in the media_pad pads list
- `pipe`: The media_pipeline that the pad is part of
- `pad`: The media pad

**Description**

This structure associate a pad with a media pipeline. Instances of
media_pipeline_pad are created by [`media_pipeline_start()`](#c-media_pipeline_start) when it builds the
pipeline, and stored in the [`media_pad.pads`](#c-struct-media_pad) list. [`media_pipeline_stop()`](#c-media_pipeline_stop)
removes the entries from the list and deletes them.

#### <a id="c-struct-media_pipeline_pad_iter"></a>`struct media_pipeline_pad_iter`

Iterator for media_pipeline_for_each_pad

**Definition**

```c
struct media_pipeline_pad_iter {
    struct list_head *cursor;
};
```

**Members**

- `cursor`: The current element

#### <a id="c-struct-media_pipeline_entity_iter"></a>`struct media_pipeline_entity_iter`

Iterator for media_pipeline_for_each_entity

**Definition**

```c
struct media_pipeline_entity_iter {
    struct media_entity_enum ent_enum;
    struct list_head *cursor;
};
```

**Members**

- `ent_enum`: The entity enumeration tracker
- `cursor`: The current element

#### <a id="c-struct-media_link"></a>`struct media_link`

A link object part of a media graph.

**Definition**

```c
struct media_link {
    struct media_gobj graph_obj;
    struct list_head list;
    union {
        struct media_gobj *gobj0;
        struct media_pad *source;
        struct media_interface *intf;
    };
    union {
        struct media_gobj *gobj1;
        struct media_pad *sink;
        struct media_entity *entity;
    };
    struct media_link *reverse;
    unsigned long flags;
    bool is_backlink;
};
```

**Members**

- `graph_obj`: Embedded structure containing the media object common data
- `list`: Linked list associated with an entity or an interface that
  owns the link.
- `{unnamed_union}`: anonymous
- `gobj0`: Part of a union. Used to get the pointer for the first
  graph_object of the link.
- `source`: Part of a union. Used only if the first object (gobj0) is
  a pad. In that case, it represents the source pad.
- `intf`: Part of a union. Used only if the first object (gobj0) is
  an interface.
- `{unnamed_union}`: anonymous
- `gobj1`: Part of a union. Used to get the pointer for the second
  graph_object of the link.
- `sink`: Part of a union. Used only if the second object (gobj1) is
  a pad. In that case, it represents the sink pad.
- `entity`: Part of a union. Used only if the second object (gobj1) is
  an entity.
- `reverse`: Pointer to the link for the reverse direction of a pad to pad
  link.
- `flags`: Link flags, as defined in uapi/media.h (MEDIA_LNK_FL_*)
- `is_backlink`: Indicate if the link is a backlink.

#### <a id="c-enum-media_pad_signal_type"></a>`enum media_pad_signal_type`

type of the signal inside a media pad

**Constants**

- `PAD_SIGNAL_DEFAULT`: Default signal. Use this when all inputs or all outputs are
  uniquely identified by the pad number.
- `PAD_SIGNAL_ANALOG`: The pad contains an analog signal. It can be Radio Frequency,
  Intermediate Frequency, a baseband signal or sub-carriers.
  Tuner inputs, IF-PLL demodulators, composite and s-video signals
  should use it.
- `PAD_SIGNAL_DV`: Contains a digital video signal, with can be a bitstream of samples
  taken from an analog TV video source. On such case, it usually
  contains the VBI data on it.
- `PAD_SIGNAL_AUDIO`: Contains an Intermediate Frequency analog signal from an audio
  sub-carrier or an audio bitstream. IF signals are provided by tuners
  and consumed by audio AM/FM decoders. Bitstream audio is provided by
  an audio decoder.

#### <a id="c-struct-media_pad"></a>`struct media_pad`

A media pad graph object.

**Definition**

```c
struct media_pad {
    struct media_gobj graph_obj;
    struct media_entity *entity;
    u16 index;
    u16 num_links;
    enum media_pad_signal_type sig_type;
    unsigned long flags;
    struct media_pipeline *pipe;
};
```

**Members**

- `graph_obj`: Embedded structure containing the media object common data
- `entity`: Entity this pad belongs to
- `index`: Pad index in the entity pads array, numbered from 0 to n
- `num_links`: Number of links connected to this pad
- `sig_type`: Type of the signal inside a media pad
- `flags`: Pad flags, as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_PAD_FL_*`)
- `pipe`: Pipeline this pad belongs to. Use [`media_entity_pipeline()`](#c-media_entity_pipeline) to
  access this field.

#### <a id="c-struct-media_entity_operations"></a>`struct media_entity_operations`

Media entity operations

**Definition**

```c
struct media_entity_operations {
    int (*get_fwnode_pad)(struct media_entity *entity, struct fwnode_endpoint *endpoint);
    int (*link_setup)(struct media_entity *entity, const struct media_pad *local, const struct media_pad *remote, u32 flags);
    int (*link_validate)(struct media_link *link);
    bool (*has_pad_interdep)(struct media_entity *entity, unsigned int pad0, unsigned int pad1);
};
```

**Members**

- `get_fwnode_pad`: Return the pad number based on a fwnode endpoint or
  a negative value on error. This operation can be used
  to map a fwnode to a media pad number. Optional.
- `link_setup`: Notify the entity of link changes. The operation can
  return an error, in which case link setup will be
  cancelled. Optional.
- `link_validate`: Return whether a link is valid from the entity point of
  view. The [`media_pipeline_start()`](#c-media_pipeline_start) function
  validates all links by calling this operation. Optional.
- `has_pad_interdep`: Return whether two pads of the entity are
  interdependent. If two pads are interdependent they are
  part of the same pipeline and enabling one of the pads
  means that the other pad will become "locked" and
  doesn't allow configuration changes. pad0 and pad1 are
  guaranteed to not both be sinks or sources. Never call
  the .`has_pad_interdep()` operation directly, always use
  `media_entity_has_pad_interdep()`.
  Optional: If the operation isn't implemented all pads
  will be considered as interdependent.

**Description**

> [!NOTE]
> Those these callbacks are called with struct [`media_device.graph_mutex`](#c-struct-media_device)
> mutex held.

#### <a id="c-enum-media_entity_type"></a>`enum media_entity_type`

Media entity type

**Constants**

- `MEDIA_ENTITY_TYPE_BASE`: The entity isn't embedded in another subsystem structure.
- `MEDIA_ENTITY_TYPE_VIDEO_DEVICE`: The entity is embedded in a struct video_device instance.
- `MEDIA_ENTITY_TYPE_V4L2_SUBDEV`: The entity is embedded in a struct v4l2_subdev instance.

**Description**

Media entity objects are often not instantiated directly, but the media
entity structure is inherited by (through embedding) other subsystem-specific
structures. The media entity type identifies the type of the subclass
structure that implements a media entity instance.

This allows runtime type identification of media entities and safe casting to
the correct object type. For instance, a media entity structure instance
embedded in a v4l2_subdev structure instance will have the type
`MEDIA_ENTITY_TYPE_V4L2_SUBDEV` and can safely be cast to a [`v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
structure using the [`container_of()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-container_of) macro.

#### <a id="c-struct-media_entity"></a>`struct media_entity`

A media entity graph object.

**Definition**

```c
struct media_entity {
    struct media_gobj graph_obj;
    const char *name;
    enum media_entity_type obj_type;
    u32 function;
    unsigned long flags;
    u16 num_pads;
    u16 num_links;
    u16 num_backlinks;
    int internal_idx;
    struct media_pad *pads;
    struct list_head links;
    const struct media_entity_operations *ops;
    int use_count;
    union {
        struct {
            u32 major;
            u32 minor;
        } dev;
    } info;
};
```

**Members**

- `graph_obj`: Embedded structure containing the media object common data.
- `name`: Entity name.
- `obj_type`: Type of the object that implements the media_entity.
- `function`: Entity main function, as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_ENT_F_*`)
- `flags`: Entity flags, as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_ENT_FL_*`)
- `num_pads`: Number of sink and source pads.
- `num_links`: Total number of links, forward and back, enabled and disabled.
- `num_backlinks`: Number of backlinks
- `internal_idx`: An unique internal entity specific number. The numbers are
  re-used if entities are unregistered or registered again.
- `pads`: Pads array with the size defined by **num_pads**.
- `links`: List of data links.
- `ops`: Entity operations.
- `use_count`: Use count for the entity.
- `info`: Union with devnode information.  Kept just for backward
  compatibility.
- `info.dev`: Contains device major and minor info.
- `info.dev.major`: device node major, if the device is a devnode.
- `info.dev.minor`: device node minor, if the device is a devnode.

**Description**

> [!NOTE]
> The **use_count** reference count must never be negative, but is a signed
> integer on purpose: a simple `WARN_ON(<0)` check can be used to detect
> reference count bugs that would make it negative.

#### <a id="c-media_entity_for_each_pad"></a>`media_entity_for_each_pad()`

```c
media_entity_for_each_pad(entity, iter)
```

Iterate on all pads in an entity

**Parameters**

- `entity`: The entity the pads belong to
- `iter`: The iterator pad

**Description**

Iterate on all pads in a media entity.

#### <a id="c-struct-media_interface"></a>`struct media_interface`

A media interface graph object.

**Definition**

```c
struct media_interface {
    struct media_gobj               graph_obj;
    struct list_head                links;
    u32 type;
    u32 flags;
};
```

**Members**

- `graph_obj`: embedded graph object
- `links`: List of links pointing to graph entities
- `type`: Type of the interface as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_INTF_T_*`)
- `flags`: Interface flags as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_INTF_FL_*`)

**Description**

> [!NOTE]
> Currently, no flags for [`media_interface`](#c-struct-media_interface) is defined.

#### <a id="c-struct-media_intf_devnode"></a>`struct media_intf_devnode`

A media interface via a device node.

**Definition**

```c
struct media_intf_devnode {
    struct media_interface          intf;
    u32 major;
    u32 minor;
};
```

**Members**

- `intf`: embedded interface object
- `major`: Major number of a device node
- `minor`: Minor number of a device node

#### <a id="c-media_entity_id"></a>`media_entity_id()`

```c
u32 media_entity_id(struct media_entity *entity)
```

return the media entity graph object id

**Parameters**

- `struct media_entity *entity`: pointer to [`media_entity`](#c-struct-media_entity)

#### <a id="c-media_type"></a>`media_type()`

```c
enum media_gobj_type media_type(struct media_gobj *gobj)
```

return the media object type

**Parameters**

- `struct media_gobj *gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-media_id"></a>`media_id()`

```c
u32 media_id(struct media_gobj *gobj)
```

return the media object ID

**Parameters**

- `struct media_gobj *gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-media_gobj_gen_id"></a>`media_gobj_gen_id()`

```c
u32 media_gobj_gen_id(enum media_gobj_type type, u64 local_id)
```

encapsulates type and ID on at the object ID

**Parameters**

- `enum media_gobj_type type`: object type as define at enum [`media_gobj_type`](#c-enum-media_gobj_type).
- `u64 local_id`: next ID, from struct [`media_device.id`](#c-struct-media_device).

#### <a id="c-is_media_entity_v4l2_video_device"></a>`is_media_entity_v4l2_video_device()`

```c
bool is_media_entity_v4l2_video_device(struct media_entity *entity)
```

Check if the entity is a video_device

**Parameters**

- `struct media_entity *entity`: pointer to entity

**Return**

`true` if the entity is an instance of a video_device object and can
safely be cast to a struct video_device using the [`container_of()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-container_of) macro, or
`false` otherwise.

#### <a id="c-is_media_entity_v4l2_subdev"></a>`is_media_entity_v4l2_subdev()`

```c
bool is_media_entity_v4l2_subdev(struct media_entity *entity)
```

Check if the entity is a v4l2_subdev

**Parameters**

- `struct media_entity *entity`: pointer to entity

**Return**

`true` if the entity is an instance of a [`v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) object and can
safely be cast to a struct [`v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) using the [`container_of()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-container_of) macro, or
`false` otherwise.

#### <a id="c-media_entity_enum_init"></a>`media_entity_enum_init()`

```c
int media_entity_enum_init(struct media_entity_enum *ent_enum, struct media_device *mdev)
```

Initialise an entity enumeration

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration to be initialised
- `struct media_device *mdev`: The related media device

**Return**

zero on success or a negative error code.

#### <a id="c-media_entity_enum_cleanup"></a>`media_entity_enum_cleanup()`

```c
void media_entity_enum_cleanup(struct media_entity_enum *ent_enum)
```

Release resources of an entity enumeration

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration to be released

#### <a id="c-media_entity_enum_zero"></a>`media_entity_enum_zero()`

```c
void media_entity_enum_zero(struct media_entity_enum *ent_enum)
```

Clear the entire enum

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration to be cleared

#### <a id="c-media_entity_enum_set"></a>`media_entity_enum_set()`

```c
void media_entity_enum_set(struct media_entity_enum *ent_enum, struct media_entity *entity)
```

Mark a single entity in the enum

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration
- `struct media_entity *entity`: Entity to be marked

#### <a id="c-media_entity_enum_clear"></a>`media_entity_enum_clear()`

```c
void media_entity_enum_clear(struct media_entity_enum *ent_enum, struct media_entity *entity)
```

Unmark a single entity in the enum

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration
- `struct media_entity *entity`: Entity to be unmarked

#### <a id="c-media_entity_enum_test"></a>`media_entity_enum_test()`

```c
bool media_entity_enum_test(struct media_entity_enum *ent_enum, struct media_entity *entity)
```

Test whether the entity is marked

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration
- `struct media_entity *entity`: Entity to be tested

**Description**

Returns `true` if the entity was marked.

#### <a id="c-media_entity_enum_test_and_set"></a>`media_entity_enum_test_and_set()`

```c
bool media_entity_enum_test_and_set(struct media_entity_enum *ent_enum, struct media_entity *entity)
```

Test whether the entity is marked, and mark it

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration
- `struct media_entity *entity`: Entity to be tested

**Description**

Returns `true` if the entity was marked, and mark it before doing so.

#### <a id="c-media_entity_enum_empty"></a>`media_entity_enum_empty()`

```c
bool media_entity_enum_empty(struct media_entity_enum *ent_enum)
```

Test whether the entire enum is empty

**Parameters**

- `struct media_entity_enum *ent_enum`: Entity enumeration

**Return**

`true` if the entity was empty.

#### <a id="c-media_entity_enum_intersects"></a>`media_entity_enum_intersects()`

```c
bool media_entity_enum_intersects(struct media_entity_enum *ent_enum1, struct media_entity_enum *ent_enum2)
```

Test whether two enums intersect

**Parameters**

- `struct media_entity_enum *ent_enum1`: First entity enumeration
- `struct media_entity_enum *ent_enum2`: Second entity enumeration

**Return**

`true` if entity enumerations **ent_enum1** and **ent_enum2** intersect,
otherwise `false`.

#### <a id="c-gobj_to_entity"></a>`gobj_to_entity()`

```c
gobj_to_entity(gobj)
```

returns the struct [`media_entity`](#c-struct-media_entity) pointer from the **gobj** contained on it.

**Parameters**

- `gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-gobj_to_pad"></a>`gobj_to_pad()`

```c
gobj_to_pad(gobj)
```

returns the struct [`media_pad`](#c-struct-media_pad) pointer from the **gobj** contained on it.

**Parameters**

- `gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-gobj_to_link"></a>`gobj_to_link()`

```c
gobj_to_link(gobj)
```

returns the struct [`media_link`](#c-struct-media_link) pointer from the **gobj** contained on it.

**Parameters**

- `gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-gobj_to_intf"></a>`gobj_to_intf()`

```c
gobj_to_intf(gobj)
```

returns the struct [`media_interface`](#c-struct-media_interface) pointer from the **gobj** contained on it.

**Parameters**

- `gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

#### <a id="c-intf_to_devnode"></a>`intf_to_devnode()`

```c
intf_to_devnode(intf)
```

returns the struct media_intf_devnode pointer from the **intf** contained on it.

**Parameters**

- `intf`: Pointer to struct [`media_intf_devnode`](#c-struct-media_intf_devnode)

#### <a id="c-media_gobj_create"></a>`media_gobj_create()`

```c
void media_gobj_create(struct media_device *mdev, enum media_gobj_type type, struct media_gobj *gobj)
```

Initialize a graph object

**Parameters**

- `struct media_device *mdev`: Pointer to the [`media_device`](#c-struct-media_device) that contains the object
- `enum media_gobj_type type`: Type of the object
- `struct media_gobj *gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

**Description**

This routine initializes the embedded struct [`media_gobj`](#c-struct-media_gobj) inside a
media graph object. It is called automatically if `media_*_create`
function calls are used. However, if the object (entity, link, pad,
interface) is embedded on some other object, this function should be
called before registering the object at the media controller.

#### <a id="c-media_gobj_destroy"></a>`media_gobj_destroy()`

```c
void media_gobj_destroy(struct media_gobj *gobj)
```

Stop using a graph object on a media device

**Parameters**

- `struct media_gobj *gobj`: Pointer to the struct [`media_gobj`](#c-struct-media_gobj) graph object

**Description**

This should be called by all routines like [`media_device_unregister()`](#c-media_device_unregister)
that remove/destroy media graph objects.

#### <a id="c-media_entity_pads_init"></a>`media_entity_pads_init()`

```c
int media_entity_pads_init(struct media_entity *entity, u16 num_pads, struct media_pad *pads)
```

Initialize the entity pads

**Parameters**

- `struct media_entity *entity`: entity where the pads belong
- `u16 num_pads`: total number of sink and source pads
- `struct media_pad *pads`: Array of **num_pads** pads.

**Description**

The pads array is managed by the entity driver and passed to
[`media_entity_pads_init()`](#c-media_entity_pads_init) where its pointer will be stored in the
[`media_entity`](#c-struct-media_entity) structure.

If no pads are needed, drivers could either directly fill
[`media_entity->num_pads`](#c-struct-media_entity) with 0 and [`media_entity->pads`](#c-struct-media_entity) with `NULL` or call
this function that will do the same.

As the number of pads is known in advance, the pads array is not allocated
dynamically but is managed by the entity driver. Most drivers will embed the
pads array in a driver-specific structure, avoiding dynamic allocation.

Drivers must set the direction of every pad in the pads array before calling
[`media_entity_pads_init()`](#c-media_entity_pads_init). The function will initialize the other pads fields.

#### <a id="c-media_entity_cleanup"></a>`media_entity_cleanup()`

```c
void media_entity_cleanup(struct media_entity *entity)
```

free resources associated with an entity

**Parameters**

- `struct media_entity *entity`: entity where the pads belong

**Description**

This function must be called during the cleanup phase after unregistering
the entity (currently, it does nothing).

Calling [`media_entity_cleanup()`](#c-media_entity_cleanup) on a media_entity whose memory has been
zeroed but that has not been initialized with `media_entity_pad_init()` is
valid and is a no-op.

#### <a id="c-media_get_pad_index"></a>`media_get_pad_index()`

```c
int media_get_pad_index(struct media_entity *entity, u32 pad_type, enum media_pad_signal_type sig_type)
```

retrieves a pad index from an entity

**Parameters**

- `struct media_entity *entity`: entity where the pads belong
- `u32 pad_type`: the type of the pad, one of MEDIA_PAD_FL_* pad types
- `enum media_pad_signal_type sig_type`: type of signal of the pad to be search

**Description**

This helper function finds the first pad index inside an entity that
satisfies both **is_sink** and **sig_type** conditions.

On success, return the pad number. If the pad was not found or the media
entity is a NULL pointer, return -EINVAL.

#### <a id="c-media_create_pad_link"></a>`media_create_pad_link()`

```c
int media_create_pad_link(struct media_entity *source, u16 source_pad, struct media_entity *sink, u16 sink_pad, u32 flags)
```

creates a link between two entities.

**Parameters**

- `struct media_entity *source`: pointer to [`media_entity`](#c-struct-media_entity) of the source pad.
- `u16 source_pad`: number of the source pad in the pads array
- `struct media_entity *sink`: pointer to [`media_entity`](#c-struct-media_entity) of the sink pad.
- `u16 sink_pad`: number of the sink pad in the pads array.
- `u32 flags`: Link flags, as defined in
  include/uapi/linux/media.h
  ( seek for `MEDIA_LNK_FL_*`)

**Description**

Valid values for flags:

- `MEDIA_LNK_FL_ENABLED`:
  Indicates that the link is enabled and can be used to transfer media data.
  When two or more links target a sink pad, only one of them can be
  enabled at a time.

- `MEDIA_LNK_FL_IMMUTABLE`:
  Indicates that the link enabled state can't be modified at runtime. If
  `MEDIA_LNK_FL_IMMUTABLE` is set, then `MEDIA_LNK_FL_ENABLED` must also be
  set, since an immutable link is always enabled.

> [!NOTE]
> Before calling this function, [`media_entity_pads_init()`](#c-media_entity_pads_init) and
> [`media_device_register_entity()`](#c-media_device_register_entity) should be called previously for both ends.

#### <a id="c-media_create_pad_links"></a>`media_create_pad_links()`

```c
int media_create_pad_links(const struct media_device *mdev, const u32 source_function, struct media_entity *source, const u16 source_pad, const u32 sink_function, struct media_entity *sink, const u16 sink_pad, u32 flags, const bool allow_both_undefined)
```

creates a link between two entities.

**Parameters**

- `const struct media_device *mdev`: Pointer to the media_device that contains the object
- `const u32 source_function`: Function of the source entities. Used only if **source** is
  NULL.
- `struct media_entity *source`: pointer to [`media_entity`](#c-struct-media_entity) of the source pad. If NULL, it will use
  all entities that matches the **sink_function**.
- `const u16 source_pad`: number of the source pad in the pads array
- `const u32 sink_function`: Function of the sink entities. Used only if **sink** is NULL.
- `struct media_entity *sink`: pointer to [`media_entity`](#c-struct-media_entity) of the sink pad. If NULL, it will use
  all entities that matches the **sink_function**.
- `const u16 sink_pad`: number of the sink pad in the pads array.
- `u32 flags`: Link flags, as defined in include/uapi/linux/media.h.
- `const bool allow_both_undefined`: if `true`, then both **source** and **sink** can be NULL.
  In such case, it will create a crossbar between all entities that
  matches **source_function** to all entities that matches **sink_function**.
  If `false`, it will return 0 and won't create any link if both **source**
  and **sink** are NULL.

**Description**

Valid values for flags:

- A `MEDIA_LNK_FL_ENABLED` flag indicates that the link is enabled and can be

  used to transfer media data. If multiple links are created and this
  flag is passed as an argument, only the first created link will have
  this flag.

- A `MEDIA_LNK_FL_IMMUTABLE` flag indicates that the link enabled state can't

  be modified at runtime. If `MEDIA_LNK_FL_IMMUTABLE` is set, then
  `MEDIA_LNK_FL_ENABLED` must also be set since an immutable link is
  always enabled.

It is common for some devices to have multiple source and/or sink entities
of the same type that should be linked. While [`media_create_pad_link()`](#c-media_create_pad_link)
creates link by link, this function is meant to allow 1:n, n:1 and even
cross-bar (n:n) links.

> [!NOTE]
> Before calling this function, [`media_entity_pads_init()`](#c-media_entity_pads_init) and
> [`media_device_register_entity()`](#c-media_device_register_entity) should be called previously for the
> entities to be linked.

#### <a id="c-media_entity_remove_links"></a>`media_entity_remove_links()`

```c
void media_entity_remove_links(struct media_entity *entity)
```

remove all links associated with an entity

**Parameters**

- `struct media_entity *entity`: pointer to [`media_entity`](#c-struct-media_entity)

**Description**

> [!NOTE]
> This is called automatically when an entity is unregistered via
> [`media_device_register_entity()`](#c-media_device_register_entity).

#### <a id="c-__media_entity_setup_link"></a>`__media_entity_setup_link()`

```c
int __media_entity_setup_link(struct media_link *link, u32 flags)
```

Configure a media link without locking

**Parameters**

- `struct media_link *link`: The link being configured
- `u32 flags`: Link configuration flags

**Description**

The bulk of link setup is handled by the two entities connected through the
link. This function notifies both entities of the link configuration change.

If the link is immutable or if the current and new configuration are
identical, return immediately.

The user is expected to hold link->source->parent->mutex. If not,
[`media_entity_setup_link()`](#c-media_entity_setup_link) should be used instead.

#### <a id="c-media_entity_setup_link"></a>`media_entity_setup_link()`

```c
int media_entity_setup_link(struct media_link *link, u32 flags)
```

changes the link flags properties in runtime

**Parameters**

- `struct media_link *link`: pointer to [`media_link`](#c-struct-media_link)
- `u32 flags`: the requested new link flags

**Description**

The only configurable property is the `MEDIA_LNK_FL_ENABLED` link flag
to enable/disable a link. Links marked with the
`MEDIA_LNK_FL_IMMUTABLE` link flag can not be enabled or disabled.

When a link is enabled or disabled, the media framework calls the
link_setup operation for the two entities at the source and sink of the
link, in that order. If the second link_setup call fails, another
link_setup call is made on the first entity to restore the original link
flags.

Media device drivers can be notified of link setup operations by setting the
[`media_device.link_notify`](#c-struct-media_device) pointer to a callback function. If provided, the
notification callback will be called before enabling and after disabling
links.

Entity drivers must implement the link_setup operation if any of their links
is non-immutable. The operation must either configure the hardware or store
the configuration information to be applied later.

Link configuration must not have any side effect on other links. If an
enabled link at a sink pad prevents another link at the same pad from
being enabled, the link_setup operation must return `-EBUSY` and can't
implicitly disable the first enabled link.

> [!NOTE]
> The valid values of the flags for the link is the same as described
> on [`media_create_pad_link()`](#c-media_create_pad_link), for pad to pad links or the same as described
> on [`media_create_intf_link()`](#c-media_create_intf_link), for interface to entity links.

#### <a id="c-media_entity_find_link"></a>`media_entity_find_link()`

```c
struct media_link * media_entity_find_link(struct media_pad *source, struct media_pad *sink)
```

Find a link between two pads

**Parameters**

- `struct media_pad *source`: Source pad
- `struct media_pad *sink`: Sink pad

**Return**

returns a pointer to the link between the two entities. If no
such link exists, return `NULL`.

#### <a id="c-media_pad_remote_pad_first"></a>`media_pad_remote_pad_first()`

```c
struct media_pad * media_pad_remote_pad_first(const struct media_pad *pad)
```

Find the first pad at the remote end of a link

**Parameters**

- `const struct media_pad *pad`: Pad at the local end of the link

**Description**

Search for a remote pad connected to the given pad by iterating over all
links originating or terminating at that pad until an enabled link is found.

**Return**

returns a pointer to the pad at the remote end of the first found
enabled link, or `NULL` if no enabled link has been found.

#### <a id="c-media_pad_remote_pad_unique"></a>`media_pad_remote_pad_unique()`

```c
struct media_pad * media_pad_remote_pad_unique(const struct media_pad *pad)
```

Find a remote pad connected to a pad

**Parameters**

- `const struct media_pad *pad`: The pad

**Description**

Search for and return a remote pad connected to **pad** through an enabled
link. If multiple (or no) remote pads are found, an error is returned.

The uniqueness constraint makes this helper function suitable for entities
that support a single active source at a time on a given pad.

* -ENOTUNIQ - Multiple links are enabled
* -ENOLINK - No connected pad found

**Return**

A pointer to the remote pad, or one of the following error pointers
if an error occurs:

#### <a id="c-media_entity_remote_pad_unique"></a>`media_entity_remote_pad_unique()`

```c
struct media_pad * media_entity_remote_pad_unique(const struct media_entity *entity, unsigned int type)
```

Find a remote pad connected to an entity

**Parameters**

- `const struct media_entity *entity`: The entity
- `unsigned int type`: The type of pad to find (MEDIA_PAD_FL_SINK or MEDIA_PAD_FL_SOURCE)

**Description**

Search for and return a remote pad of **type** connected to **entity** through an
enabled link. If multiple (or no) remote pads match these criteria, an error
is returned.

The uniqueness constraint makes this helper function suitable for entities
that support a single active source or sink at a time.

* -ENOTUNIQ - Multiple links are enabled
* -ENOLINK - No connected pad found

**Return**

A pointer to the remote pad, or one of the following error pointers
if an error occurs:

#### <a id="c-media_entity_remote_source_pad_unique"></a>`media_entity_remote_source_pad_unique()`

```c
struct media_pad * media_entity_remote_source_pad_unique(const struct media_entity *entity)
```

Find a remote source pad connected to an entity

**Parameters**

- `const struct media_entity *entity`: The entity

**Description**

Search for and return a remote source pad connected to **entity** through an
enabled link. If multiple (or no) remote pads match these criteria, an error
is returned.

The uniqueness constraint makes this helper function suitable for entities
that support a single active source at a time.

* -ENOTUNIQ - Multiple links are enabled
* -ENOLINK - No connected pad found

**Return**

A pointer to the remote pad, or one of the following error pointers
if an error occurs:

#### <a id="c-media_pad_is_streaming"></a>`media_pad_is_streaming()`

```c
bool media_pad_is_streaming(const struct media_pad *pad)
```

Test if a pad is part of a streaming pipeline

**Parameters**

- `const struct media_pad *pad`: The pad

**Return**

True if the pad is part of a pipeline started with the
[`media_pipeline_start()`](#c-media_pipeline_start) function, false otherwise.

#### <a id="c-media_entity_is_streaming"></a>`media_entity_is_streaming()`

```c
bool media_entity_is_streaming(const struct media_entity *entity)
```

Test if an entity is part of a streaming pipeline

**Parameters**

- `const struct media_entity *entity`: The entity

**Return**

True if the entity is part of a pipeline started with the
[`media_pipeline_start()`](#c-media_pipeline_start) function, false otherwise.

#### <a id="c-media_entity_pipeline"></a>`media_entity_pipeline()`

```c
struct media_pipeline * media_entity_pipeline(struct media_entity *entity)
```

Get the media pipeline an entity is part of

**Parameters**

- `struct media_entity *entity`: The entity

**Description**

DEPRECATED: use [`media_pad_pipeline()`](#c-media_pad_pipeline) instead.

This function returns the media pipeline that an entity has been associated
with when constructing the pipeline with [`media_pipeline_start()`](#c-media_pipeline_start). The pointer
remains valid until [`media_pipeline_stop()`](#c-media_pipeline_stop) is called.

In general, entities can be part of multiple pipelines, when carrying
multiple streams (either on different pads, or on the same pad using
multiplexed streams). This function is to be used only for entities that
do not support multiple pipelines.

**Return**

The media_pipeline the entity is part of, or NULL if the entity is
not part of any pipeline.

#### <a id="c-media_pad_pipeline"></a>`media_pad_pipeline()`

```c
struct media_pipeline * media_pad_pipeline(struct media_pad *pad)
```

Get the media pipeline a pad is part of

**Parameters**

- `struct media_pad *pad`: The pad

**Description**

This function returns the media pipeline that a pad has been associated
with when constructing the pipeline with [`media_pipeline_start()`](#c-media_pipeline_start). The pointer
remains valid until [`media_pipeline_stop()`](#c-media_pipeline_stop) is called.

**Return**

The media_pipeline the pad is part of, or NULL if the pad is
not part of any pipeline.

#### <a id="c-media_entity_get_fwnode_pad"></a>`media_entity_get_fwnode_pad()`

```c
int media_entity_get_fwnode_pad(struct media_entity *entity, const struct fwnode_handle *fwnode, unsigned long direction_flags)
```

Get pad number from fwnode

**Parameters**

- `struct media_entity *entity`: The entity
- `const struct fwnode_handle *fwnode`: Pointer to the fwnode_handle which should be used to find the pad
- `unsigned long direction_flags`: Expected direction of the pad, as defined in
  include/uapi/linux/media.h
  (seek for `MEDIA_PAD_FL_*`)

**Description**

This function can be used to resolve the media pad number from
a fwnode. This is useful for devices which use more complex
mappings of media pads.

If the entity does not implement the `get_fwnode_pad()` operation
then this function searches the entity for the first pad that
matches the **direction_flags**.

**Return**

returns the pad number on success or a negative error code.

#### <a id="c-media_graph_walk_init"></a>`media_graph_walk_init()`

```c
int media_graph_walk_init(struct media_graph *graph, struct media_device *mdev)
```

Allocate resources used by graph walk.

**Parameters**

- `struct media_graph *graph`: Media graph structure that will be used to walk the graph
- `struct media_device *mdev`: Pointer to the [`media_device`](#c-struct-media_device) that contains the object

**Description**

This function is deprecated, use [`media_pipeline_for_each_pad()`](#c-media_pipeline_for_each_pad) instead.

The caller is required to hold the media_device graph_mutex during the graph
walk until the graph state is released.

Returns zero on success or a negative error code otherwise.

#### <a id="c-media_graph_walk_cleanup"></a>`media_graph_walk_cleanup()`

```c
void media_graph_walk_cleanup(struct media_graph *graph)
```

Release resources used by graph walk.

**Parameters**

- `struct media_graph *graph`: Media graph structure that will be used to walk the graph

**Description**

This function is deprecated, use [`media_pipeline_for_each_pad()`](#c-media_pipeline_for_each_pad) instead.

#### <a id="c-media_graph_walk_start"></a>`media_graph_walk_start()`

```c
void media_graph_walk_start(struct media_graph *graph, struct media_entity *entity)
```

Start walking the media graph at a given entity

**Parameters**

- `struct media_graph *graph`: Media graph structure that will be used to walk the graph
- `struct media_entity *entity`: Starting entity

**Description**

This function is deprecated, use [`media_pipeline_for_each_pad()`](#c-media_pipeline_for_each_pad) instead.

Before using this function, [`media_graph_walk_init()`](#c-media_graph_walk_init) must be
used to allocate resources used for walking the graph. This
function initializes the graph traversal structure to walk the
entities graph starting at the given entity. The traversal
structure must not be modified by the caller during graph
traversal. After the graph walk, the resources must be released
using [`media_graph_walk_cleanup()`](#c-media_graph_walk_cleanup).

#### <a id="c-media_graph_walk_next"></a>`media_graph_walk_next()`

```c
struct media_entity * media_graph_walk_next(struct media_graph *graph)
```

Get the next entity in the graph

**Parameters**

- `struct media_graph *graph`: Media graph structure

**Description**

This function is deprecated, use [`media_pipeline_for_each_pad()`](#c-media_pipeline_for_each_pad) instead.

Perform a depth-first traversal of the given media entities graph.

The graph structure must have been previously initialized with a call to
[`media_graph_walk_start()`](#c-media_graph_walk_start).

**Return**

returns the next entity in the graph or `NULL` if the whole graph
have been traversed.

#### <a id="c-media_pipeline_start"></a>`media_pipeline_start()`

```c
int media_pipeline_start(struct media_pad *origin, struct media_pipeline *pipe)
```

Mark a pipeline as streaming

**Parameters**

- `struct media_pad *origin`: Starting pad
- `struct media_pipeline *pipe`: Media pipeline to be assigned to all pads in the pipeline.

**Description**

Mark all pads connected to pad **origin** through enabled links, either
directly or indirectly, as streaming. The given pipeline object is assigned
to every pad in the pipeline and stored in the media_pad pipe field.

Calls to this function can be nested, in which case the same number of
[`media_pipeline_stop()`](#c-media_pipeline_stop) calls will be required to stop streaming. The
pipeline pointer must be identical for all nested calls to
[`media_pipeline_start()`](#c-media_pipeline_start).

#### <a id="c-__media_pipeline_start"></a>`__media_pipeline_start()`

```c
int __media_pipeline_start(struct media_pad *origin, struct media_pipeline *pipe)
```

Mark a pipeline as streaming

**Parameters**

- `struct media_pad *origin`: Starting pad
- `struct media_pipeline *pipe`: Media pipeline to be assigned to all pads in the pipeline.

**Description**

..note:: This is the non-locking version of [`media_pipeline_start()`](#c-media_pipeline_start)

#### <a id="c-media_pipeline_stop"></a>`media_pipeline_stop()`

```c
void media_pipeline_stop(struct media_pad *pad)
```

Mark a pipeline as not streaming

**Parameters**

- `struct media_pad *pad`: Starting pad

**Description**

Mark all pads connected to a given pad through enabled links, either
directly or indirectly, as not streaming. The media_pad pipe field is
reset to `NULL`.

If multiple calls to [`media_pipeline_start()`](#c-media_pipeline_start) have been made, the same
number of calls to this function are required to mark the pipeline as not
streaming.

#### <a id="c-__media_pipeline_stop"></a>`__media_pipeline_stop()`

```c
void __media_pipeline_stop(struct media_pad *pad)
```

Mark a pipeline as not streaming

**Parameters**

- `struct media_pad *pad`: Starting pad

**Description**

> [!NOTE]
> This is the non-locking version of [`media_pipeline_stop()`](#c-media_pipeline_stop)

#### <a id="c-media_pipeline_for_each_pad"></a>`media_pipeline_for_each_pad()`

```c
media_pipeline_for_each_pad(pipe, iter, pad)
```

Iterate on all pads in a media pipeline

**Parameters**

- `pipe`: The pipeline
- `iter`: The iterator (struct media_pipeline_pad_iter)
- `pad`: The iterator pad

**Description**

Iterate on all pads in a media pipeline. This is only valid after the
pipeline has been built with [`media_pipeline_start()`](#c-media_pipeline_start) and before it gets
destroyed with [`media_pipeline_stop()`](#c-media_pipeline_stop).

#### <a id="c-media_pipeline_entity_iter_init"></a>`media_pipeline_entity_iter_init()`

```c
int media_pipeline_entity_iter_init(struct media_pipeline *pipe, struct media_pipeline_entity_iter *iter)
```

Initialize a pipeline entity iterator

**Parameters**

- `struct media_pipeline *pipe`: The pipeline
- `struct media_pipeline_entity_iter *iter`: The iterator

**Description**

This function must be called to initialize the iterator before using it in a
[`media_pipeline_for_each_entity()`](#c-media_pipeline_for_each_entity) loop. The iterator must be destroyed by a
call to media_pipeline_entity_iter_cleanup after the loop (including in code
paths that break from the loop).

The same iterator can be used in multiple consecutive loops without being
destroyed and reinitialized.

**Return**

0 on success or a negative error code otherwise.

#### <a id="c-media_pipeline_entity_iter_cleanup"></a>`media_pipeline_entity_iter_cleanup()`

```c
void media_pipeline_entity_iter_cleanup(struct media_pipeline_entity_iter *iter)
```

Destroy a pipeline entity iterator

**Parameters**

- `struct media_pipeline_entity_iter *iter`: The iterator

**Description**

This function must be called to destroy iterators initialized with
[`media_pipeline_entity_iter_init()`](#c-media_pipeline_entity_iter_init).

#### <a id="c-media_pipeline_for_each_entity"></a>`media_pipeline_for_each_entity()`

```c
media_pipeline_for_each_entity(pipe, iter, entity)
```

Iterate on all entities in a media pipeline

**Parameters**

- `pipe`: The pipeline
- `iter`: The iterator (struct media_pipeline_entity_iter)
- `entity`: The iterator entity

**Description**

Iterate on all entities in a media pipeline. This is only valid after the
pipeline has been built with [`media_pipeline_start()`](#c-media_pipeline_start) and before it gets
destroyed with [`media_pipeline_stop()`](#c-media_pipeline_stop). The iterator must be initialized with
[`media_pipeline_entity_iter_init()`](#c-media_pipeline_entity_iter_init) before iteration, and destroyed with
[`media_pipeline_entity_iter_cleanup()`](#c-media_pipeline_entity_iter_cleanup) after (including in code paths that
break from the loop).

#### <a id="c-media_pipeline_alloc_start"></a>`media_pipeline_alloc_start()`

```c
int media_pipeline_alloc_start(struct media_pad *pad)
```

Mark a pipeline as streaming

**Parameters**

- `struct media_pad *pad`: Starting pad

**Description**

[`media_pipeline_alloc_start()`](#c-media_pipeline_alloc_start) is similar to [`media_pipeline_start()`](#c-media_pipeline_start) but instead
of working on a given pipeline the function will use an existing pipeline if
the pad is already part of a pipeline, or allocate a new pipeline.

Calls to [`media_pipeline_alloc_start()`](#c-media_pipeline_alloc_start) must be matched with
[`media_pipeline_stop()`](#c-media_pipeline_stop).

#### <a id="c-media_devnode_create"></a>`media_devnode_create()`

```c
struct media_intf_devnode * media_devnode_create(struct media_device *mdev, u32 type, u32 flags, u32 major, u32 minor)
```

creates and initializes a device node interface

**Parameters**

- `struct media_device *mdev`: pointer to struct [`media_device`](#c-struct-media_device)
- `u32 type`: type of the interface, as given by
  include/uapi/linux/media.h
  ( seek for `MEDIA_INTF_T_*`) macros.
- `u32 flags`: Interface flags, as defined in
  include/uapi/linux/media.h
  ( seek for `MEDIA_INTF_FL_*`)
- `u32 major`: Device node major number.
- `u32 minor`: Device node minor number.

**Return**

if succeeded, returns a pointer to the newly allocated
[`media_intf_devnode`](#c-struct-media_intf_devnode) pointer.

**Description**

> [!NOTE]
> Currently, no flags for [`media_interface`](#c-struct-media_interface) is defined.

#### <a id="c-media_devnode_remove"></a>`media_devnode_remove()`

```c
void media_devnode_remove(struct media_intf_devnode *devnode)
```

removes a device node interface

**Parameters**

- `struct media_intf_devnode *devnode`: pointer to [`media_intf_devnode`](#c-struct-media_intf_devnode) to be freed.

**Description**

When a device node interface is removed, all links to it are automatically
removed.

#### <a id="c-media_create_intf_link"></a>`media_create_intf_link()`

```c
struct media_link * media_create_intf_link(struct media_entity *entity, struct media_interface *intf, u32 flags)
```

creates a link between an entity and an interface

**Parameters**

- `struct media_entity *entity`: pointer to `media_entity`
- `struct media_interface *intf`: pointer to `media_interface`
- `u32 flags`: Link flags, as defined in
  include/uapi/linux/media.h
  ( seek for `MEDIA_LNK_FL_*`)

**Description**

Valid values for flags:

- `MEDIA_LNK_FL_ENABLED`:
  Indicates that the interface is connected to the entity hardware.
  That's the default value for interfaces. An interface may be disabled if
  the hardware is busy due to the usage of some other interface that it is
  currently controlling the hardware.

  A typical example is an hybrid TV device that handle only one type of
  stream on a given time. So, when the digital TV is streaming,
  the V4L2 interfaces won't be enabled, as such device is not able to
  also stream analog TV or radio.

> [!NOTE]
> Before calling this function, [`media_devnode_create()`](#c-media_devnode_create) should be called for
> the interface and [`media_device_register_entity()`](#c-media_device_register_entity) should be called for the
> interface that will be part of the link.

#### <a id="c-__media_remove_intf_link"></a>`__media_remove_intf_link()`

```c
void __media_remove_intf_link(struct media_link *link)
```

remove a single interface link

**Parameters**

- `struct media_link *link`: pointer to [`media_link`](#c-struct-media_link).

**Description**

> [!NOTE]
> This is an unlocked version of [`media_remove_intf_link()`](#c-media_remove_intf_link)

#### <a id="c-media_remove_intf_link"></a>`media_remove_intf_link()`

```c
void media_remove_intf_link(struct media_link *link)
```

remove a single interface link

**Parameters**

- `struct media_link *link`: pointer to [`media_link`](#c-struct-media_link).

**Description**

> [!NOTE]
> Prefer to use this one, instead of [`__media_remove_intf_link()`](#c-__media_remove_intf_link)

#### <a id="c-__media_remove_intf_links"></a>`__media_remove_intf_links()`

```c
void __media_remove_intf_links(struct media_interface *intf)
```

remove all links associated with an interface

**Parameters**

- `struct media_interface *intf`: pointer to [`media_interface`](#c-struct-media_interface)

**Description**

> [!NOTE]
> This is an unlocked version of [`media_remove_intf_links()`](#c-media_remove_intf_links).

#### <a id="c-media_remove_intf_links"></a>`media_remove_intf_links()`

```c
void media_remove_intf_links(struct media_interface *intf)
```

remove all links associated with an interface

**Parameters**

- `struct media_interface *intf`: pointer to [`media_interface`](#c-struct-media_interface)

**Description**

> [!NOTE]
> - #) This is called automatically when an entity is unregistered via
>
>   [`media_device_register_entity()`](#c-media_device_register_entity) and by [`media_devnode_remove()`](#c-media_devnode_remove).
>
> \#) Prefer to use this one, instead of [`__media_remove_intf_links()`](#c-__media_remove_intf_links).

#### <a id="c-media_entity_call"></a>`media_entity_call()`

```c
media_entity_call(entity, operation, args...)
```

Calls a struct media_entity_operations operation on an entity

**Parameters**

- `entity`: entity where the **operation** will be called
- `operation`: type of the operation. Should be the name of a member of
  struct [`media_entity_operations`](#c-struct-media_entity_operations).
- `args...`: variable arguments

**Description**

This helper function will check if **operation** is not `NULL`. On such case,
it will issue a call to **operation**\(**entity**, **args**\).

#### <a id="c-media_create_ancillary_link"></a>`media_create_ancillary_link()`

```c
struct media_link * media_create_ancillary_link(struct media_entity *primary, struct media_entity *ancillary)
```

create an ancillary link between two instances of [`media_entity`](#c-struct-media_entity)

**Parameters**

- `struct media_entity *primary`: pointer to the primary [`media_entity`](#c-struct-media_entity)
- `struct media_entity *ancillary`: pointer to the ancillary [`media_entity`](#c-struct-media_entity)

**Description**

Create an ancillary link between two entities, indicating that they
represent two connected pieces of hardware that form a single logical unit.
A typical example is a camera lens controller being linked to the sensor that
it is supporting.

The function sets both MEDIA_LNK_FL_ENABLED and MEDIA_LNK_FL_IMMUTABLE for
the new link.

#### <a id="c-__media_entity_next_link"></a>`__media_entity_next_link()`

```c
struct media_link * __media_entity_next_link(struct media_entity *entity, struct media_link *link, unsigned long link_type)
```

Iterate through a [`media_entity`](#c-struct-media_entity)'s links

**Parameters**

- `struct media_entity *entity`: pointer to the [`media_entity`](#c-struct-media_entity)
- `struct media_link *link`: pointer to a [`media_link`](#c-struct-media_link) to hold the iterated values
- `unsigned long link_type`: one of the MEDIA_LNK_FL_LINK_TYPE flags

**Description**

Return the next link against an entity matching a specific link type. This
allows iteration through an entity's links whilst guaranteeing all of the
returned links are of the given type.

#### <a id="c-for_each_media_entity_data_link"></a>`for_each_media_entity_data_link()`

```c
for_each_media_entity_data_link(entity, link)
```

Iterate through an entity's data links

**Parameters**

- `entity`: pointer to the [`media_entity`](#c-struct-media_entity)
- `link`: pointer to a [`media_link`](#c-struct-media_link) to hold the iterated values

**Description**

Iterate over a [`media_entity`](#c-struct-media_entity)'s data links



#### <a id="c-enum-media_request_state"></a>`enum media_request_state`

media request state

**Constants**

- `MEDIA_REQUEST_STATE_IDLE`: Idle
- `MEDIA_REQUEST_STATE_VALIDATING`: Validating the request, no state changes
  allowed
- `MEDIA_REQUEST_STATE_QUEUED`: Queued
- `MEDIA_REQUEST_STATE_COMPLETE`: Completed, the request is done
- `MEDIA_REQUEST_STATE_CLEANING`: Cleaning, the request is being re-inited
- `MEDIA_REQUEST_STATE_UPDATING`: The request is being updated, i.e.
  request objects are being added,
  modified or removed
- `NR_OF_MEDIA_REQUEST_STATE`: The number of media request states, used
  internally for sanity check purposes

#### <a id="c-struct-media_request"></a>`struct media_request`

Media device request

**Definition**

```c
struct media_request {
    struct media_device *mdev;
    struct kref kref;
    char debug_str[TASK_COMM_LEN + 11];
    enum media_request_state state;
    unsigned int updating_count;
    unsigned int access_count;
    struct list_head objects;
    unsigned int num_incomplete_objects;
    bool manual_completion;
    wait_queue_head_t poll_wait;
    spinlock_t lock;
};
```

**Members**

- `mdev`: Media device this request belongs to
- `kref`: Reference count
- `debug_str`: Prefix for debug messages (process name:fd)
- `state`: The state of the request
- `updating_count`: count the number of request updates that are in progress
- `access_count`: count the number of request accesses that are in progress
- `objects`: List of **struct** media_request_object request objects
- `num_incomplete_objects`: The number of incomplete objects in the request
- `manual_completion`: if true, then the request won't be marked as completed
  when **num_incomplete_objects** reaches 0. Call [`media_request_manual_complete()`](#c-media_request_manual_complete)
  to complete the request after **num_incomplete_objects** == 0.
- `poll_wait`: Wait queue for poll
- `lock`: Serializes access to this struct

#### <a id="c-media_request_lock_for_access"></a>`media_request_lock_for_access()`

```c
int media_request_lock_for_access(struct media_request *req)
```

Lock the request to access its objects

**Parameters**

- `struct media_request *req`: The media request

**Description**

Use before accessing a completed request. A reference to the request must
be held during the access. This usually takes place automatically through
a file handle. Use **media_request_unlock_for_access** when done.

#### <a id="c-media_request_unlock_for_access"></a>`media_request_unlock_for_access()`

```c
void media_request_unlock_for_access(struct media_request *req)
```

Unlock a request previously locked for access

**Parameters**

- `struct media_request *req`: The media request

**Description**

Unlock a request that has previously been locked using
**media_request_lock_for_access**.

#### <a id="c-media_request_lock_for_update"></a>`media_request_lock_for_update()`

```c
int media_request_lock_for_update(struct media_request *req)
```

Lock the request for updating its objects

**Parameters**

- `struct media_request *req`: The media request

**Description**

Use before updating a request, i.e. adding, modifying or removing a request
object in it. A reference to the request must be held during the update. This
usually takes place automatically through a file handle. Use
**media_request_unlock_for_update** when done.

#### <a id="c-media_request_unlock_for_update"></a>`media_request_unlock_for_update()`

```c
void media_request_unlock_for_update(struct media_request *req)
```

Unlock a request previously locked for update

**Parameters**

- `struct media_request *req`: The media request

**Description**

Unlock a request that has previously been locked using
**media_request_lock_for_update**.

#### <a id="c-media_request_get"></a>`media_request_get()`

```c
void media_request_get(struct media_request *req)
```

Get the media request

**Parameters**

- `struct media_request *req`: The media request

**Description**

Get the media request.

#### <a id="c-media_request_put"></a>`media_request_put()`

```c
void media_request_put(struct media_request *req)
```

Put the media request

**Parameters**

- `struct media_request *req`: The media request

**Description**

Put the media request. The media request will be released
when the refcount reaches 0.

#### <a id="c-media_request_get_by_fd"></a>`media_request_get_by_fd()`

```c
struct media_request * media_request_get_by_fd(struct media_device *mdev, int request_fd)
```

Get a media request by fd

**Parameters**

- `struct media_device *mdev`: Media device this request belongs to
- `int request_fd`: The file descriptor of the request

**Description**

Get the request represented by **request_fd** that is owned
by the media device.

Return a -EBADR error pointer if requests are not supported
by this driver. Return -EINVAL if the request was not found.
Return the pointer to the request if found: the caller will
have to call **media_request_put** when it finished using the
request.

#### <a id="c-media_request_alloc"></a>`media_request_alloc()`

```c
int media_request_alloc(struct media_device *mdev, int *alloc_fd)
```

Allocate the media request

**Parameters**

- `struct media_device *mdev`: Media device this request belongs to
- `int *alloc_fd`: Store the request's file descriptor in this int

**Description**

Allocated the media request and put the fd in **alloc_fd**.

#### <a id="c-media_request_mark_manual_completion"></a>`media_request_mark_manual_completion()`

```c
void media_request_mark_manual_completion(struct media_request *req)
```

Enable manual completion

**Parameters**

- `struct media_request *req`: The request

**Description**

Mark that the request has to be manually completed by calling
[`media_request_manual_complete()`](#c-media_request_manual_complete).

This function shall be called in the req_queue callback.

#### <a id="c-media_request_manual_complete"></a>`media_request_manual_complete()`

```c
void media_request_manual_complete(struct media_request *req)
```

Mark the request as completed

**Parameters**

- `struct media_request *req`: The request

**Description**

This function completes a request that was marked for manual completion by an
earlier call to [`media_request_mark_manual_completion()`](#c-media_request_mark_manual_completion). The request's
**manual_completion** field is reset to false.

All objects contained in the request must have been completed previously. It
is an error to call this function otherwise. If such an error occurred, the
function will WARN and the object completion will be delayed until
**num_incomplete_objects** is 0.

#### <a id="c-struct-media_request_object_ops"></a>`struct media_request_object_ops`

Media request object operations

**Definition**

```c
struct media_request_object_ops {
    int (*prepare)(struct media_request_object *object);
    void (*unprepare)(struct media_request_object *object);
    void (*queue)(struct media_request_object *object);
    void (*unbind)(struct media_request_object *object);
    void (*release)(struct media_request_object *object);
};
```

**Members**

- `prepare`: Validate and prepare the request object, optional.
- `unprepare`: Unprepare the request object, optional.
- `queue`: Queue the request object, optional.
- `unbind`: Unbind the request object, optional.
- `release`: Release the request object, required.

#### <a id="c-struct-media_request_object"></a>`struct media_request_object`

An opaque object that belongs to a media request

**Definition**

```c
struct media_request_object {
    struct media_device *mdev;
    const struct media_request_object_ops *ops;
    void *priv;
    struct media_request *req;
    struct list_head list;
    struct kref kref;
    bool completed;
};
```

**Members**

- `mdev`: Media device this object belongs to
- `ops`: object's operations
- `priv`: object's priv pointer
- `req`: the request this object belongs to (can be NULL)
- `list`: List entry of the object for **struct** media_request
- `kref`: Reference count of the object, acquire before releasing req->lock
- `completed`: If true, then this object was completed.

**Description**

An object related to the request. This struct is always embedded in
another struct that contains the actual data for this request object.

#### <a id="c-media_request_object_get"></a>`media_request_object_get()`

```c
void media_request_object_get(struct media_request_object *obj)
```

Get a media request object

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Get a media request object.

#### <a id="c-media_request_object_put"></a>`media_request_object_put()`

```c
void media_request_object_put(struct media_request_object *obj)
```

Put a media request object

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Put a media request object. Once all references are gone, the
object's memory is released.

#### <a id="c-media_request_object_find"></a>`media_request_object_find()`

```c
struct media_request_object * media_request_object_find(struct media_request *req, const struct media_request_object_ops *ops, void *priv)
```

Find an object in a request

**Parameters**

- `struct media_request *req`: The media request
- `const struct media_request_object_ops *ops`: Find an object with this ops value
- `void *priv`: Find an object with this priv value

**Description**

Both **ops** and **priv** must be non-NULL.

Returns the object pointer or NULL if not found. The caller must
call [`media_request_object_put()`](#c-media_request_object_put) once it finished using the object.

Since this function needs to walk the list of objects it takes
the **req->lock** spin lock to make this safe.

#### <a id="c-media_request_object_init"></a>`media_request_object_init()`

```c
void media_request_object_init(struct media_request_object *obj)
```

Initialise a media request object

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Initialise a media request object. The object will be released using the
release callback of the ops once it has no references (this function
initialises references to one).

#### <a id="c-media_request_object_bind"></a>`media_request_object_bind()`

```c
int media_request_object_bind(struct media_request *req, const struct media_request_object_ops *ops, void *priv, bool is_buffer, struct media_request_object *obj)
```

Bind a media request object to a request

**Parameters**

- `struct media_request *req`: The media request
- `const struct media_request_object_ops *ops`: The object ops for this object
- `void *priv`: A driver-specific priv pointer associated with this object
- `bool is_buffer`: Set to true if the object is a buffer object.
- `struct media_request_object *obj`: The object

**Description**

Bind this object to the request and set the ops and priv values of
the object so it can be found later with [`media_request_object_find()`](#c-media_request_object_find).

Every bound object must be unbound or completed by the kernel at some
point in time, otherwise the request will never complete. When the
request is released all completed objects will be unbound by the
request core code.

Buffer objects will be added to the end of the request's object
list, non-buffer objects will be added to the front of the list.
This ensures that all buffer objects are at the end of the list
and that all non-buffer objects that they depend on are processed
first.

#### <a id="c-media_request_object_unbind"></a>`media_request_object_unbind()`

```c
void media_request_object_unbind(struct media_request_object *obj)
```

Unbind a media request object

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Unbind the media request object from the request.

#### <a id="c-media_request_object_complete"></a>`media_request_object_complete()`

```c
void media_request_object_complete(struct media_request_object *obj)
```

Mark the media request object as complete

**Parameters**

- `struct media_request_object *obj`: The object

**Description**

Mark the media request object as complete. Only bound objects can
be completed.



#### <a id="c-media_device_usb_allocate"></a>`media_device_usb_allocate()`

```c
struct media_device * media_device_usb_allocate(struct usb_device *udev, const char *module_name, struct module *owner)
```

Allocate and return struct `media` device

**Parameters**

- `struct usb_device *udev`: struct [`usb_device`](/kernel/hardware/driver-api/usb/usb.md#c-struct-usb_device) pointer
- `const char *module_name`: should be filled with `KBUILD_MODNAME`
- `struct module *owner`: struct module pointer `THIS_MODULE` for the driver.
  `THIS_MODULE` is null for a built-in driver.
  It is safe even when `THIS_MODULE` is null.

**Description**

This interface should be called to allocate a Media Device when multiple
drivers share usb_device and the media device. This interface allocates
[`media_device`](#c-struct-media_device) structure and calls [`media_device_usb_init()`](#c-media_device_usb_init) to initialize
it.

#### <a id="c-media_device_delete"></a>`media_device_delete()`

```c
void media_device_delete(struct media_device *mdev, const char *module_name, struct module *owner)
```

Release media device. Calls [`kref_put()`](/kernel/internals/core-api/kref.md#c-kref_put).

**Parameters**

- `struct media_device *mdev`: struct [`media_device`](#c-struct-media_device) pointer
- `const char *module_name`: should be filled with `KBUILD_MODNAME`
- `struct module *owner`: struct module pointer `THIS_MODULE` for the driver.
  `THIS_MODULE` is null for a built-in driver.
  It is safe even when `THIS_MODULE` is null.

**Description**

This interface should be called to put Media Device Instance kref.

---

# Remote Controller devices

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The remote controller core implements infrastructure to receive and send remote controller keyboard keystrokes and mouse events.

<a id="rst-remote-controller-devices"></a>

<a id="rst-remote-controller-core"></a>

## Remote Controller core

<!-- SPDX-License-Identifier: GPL-2.0 -->

The remote controller core implements infrastructure to receive and send remote controller keyboard keystrokes and mouse events.

Every time a key is pressed on a remote controller, a scan code is produced. Also, on most hardware, keeping a key pressed for more than a few dozens of milliseconds produce a repeat key event. That's somewhat similar to what a normal keyboard or mouse is handled internally on Linux<a id="rst-footnote-reference-1"></a>[1](#rst-f1). So, the remote controller core is implemented on the top of the linux input/evdev interface.

<a id="rst-f1"></a>



**[1]** The main difference is that, on keyboard events, the keyboard controller produces one event for a key press and another one for key release. On infrared-based remote controllers, there's no key release event. Instead, an extra code is produced to indicate key repeats.

However, most of the remote controllers use infrared (IR) to transmit signals. As there are several protocols used to modulate infrared signals, one important part of the core is dedicated to adjust the driver and the core system to support the infrared protocol used by the emitter.

The infrared transmission is done by blinking a infrared emitter using a carrier. The carrier can be switched on or off by the IR transmitter hardware. When the carrier is switched on, it is called *PULSE*. When the carrier is switched off, it is called *SPACE*.

In other words, a typical IR transmission can be viewed as a sequence of *PULSE* and *SPACE* events, each with a given duration.

The carrier parameters (frequency, duty cycle) and the intervals for *PULSE* and *SPACE* events depend on the protocol. For example, the NEC protocol uses a carrier of 38kHz, and transmissions start with a 9ms *PULSE* and a 4.5ms SPACE. It then transmits 16 bits of scan code, being 8 bits for address (usually it is a fixed number for a given remote controller), followed by 8 bits of code. A bit "1" is modulated with 560µs *PULSE* followed by 1690µs *SPACE* and a bit "0"  is modulated with 560µs *PULSE* followed by 560µs *SPACE*.

At receiver, a simple low-pass filter can be used to convert the received signal in a sequence of *PULSE/SPACE* events, filtering out the carrier frequency. Due to that, the receiver doesn't care about the carrier's actual frequency parameters: all it has to do is to measure the amount of time it receives *PULSE/SPACE* events. So, a simple IR receiver hardware will just provide a sequence of timings for those events to the Kernel. The drivers for hardware with such kind of receivers are identified by  `RC_DRIVER_IR_RAW`, as defined by `rc_driver_type`<a id="rst-footnote-reference-2"></a>[2](#rst-f2). Other hardware come with a microcontroller that decode the *PULSE/SPACE* sequence and return scan codes to the Kernel. Such kind of receivers are identified by `RC_DRIVER_SCANCODE`.

<a id="rst-f2"></a>



**[2]** The RC core also supports devices that have just IR emitters, without any receivers. Right now, all such devices work only in raw TX mode. Such kind of hardware is identified as `RC_DRIVER_IR_RAW_TX`.

When the RC core receives events produced by `RC_DRIVER_IR_RAW` IR receivers, it needs to decode the IR protocol, in order to obtain the corresponding scan code. The protocols supported by the RC core are defined at enum `rc_proto`.

When the RC code receives a scan code (either directly, by a driver of the type `RC_DRIVER_SCANCODE`, or via its IR decoders), it needs to convert into a Linux input event code. This is done via a mapping table.

The Kernel has support for mapping tables available on most media devices. It also supports loading a table in runtime, via some sysfs nodes. See the [RC userspace API](</kernel/userspace/userspace-api/media-rc/rc-intro.md#rst-remote-controllers-intro>) for more details.

<a id="rst-remote-controller-data-structures-and-functions"></a>

## Remote controller data structures and functions


#### <a id="c-enum-rc_driver_type"></a>`enum rc_driver_type`

type of the RC driver.

**Constants**

- `RC_DRIVER_SCANCODE`: Driver or hardware generates a scancode.
- `RC_DRIVER_IR_RAW`: Driver or hardware generates pulse/space sequences.
  It needs a Infra-Red pulse/space decoder
- `RC_DRIVER_IR_RAW_TX`: Device transmitter only,
  driver requires pulse/space data sequence.

#### <a id="c-struct-rc_scancode_filter"></a>`struct rc_scancode_filter`

Filter scan codes.

**Definition**

```c
struct rc_scancode_filter {
    u32 data;
    u32 mask;
};
```

**Members**

- `data`: Scancode data to match.
- `mask`: Mask of bits of scancode to compare.

#### <a id="c-enum-rc_filter_type"></a>`enum rc_filter_type`

Filter type constants.

**Constants**

- `RC_FILTER_NORMAL`: Filter for normal operation.
- `RC_FILTER_WAKEUP`: Filter for waking from suspend.
- `RC_FILTER_MAX`: Number of filter types.

#### <a id="c-struct-lirc_fh"></a>`struct lirc_fh`

represents an open lirc file

**Definition**

```c
struct lirc_fh {
    struct list_head list;
    struct rc_dev *rc;
    unsigned int *rawir;
    struct lirc_scancode *scancodes;
    wait_queue_head_t wait_poll;
    u32 carrier_low;
    u8 send_mode;
    u8 rec_mode;
};
```

**Members**

- `list`: list of open file handles
- `rc`: rcdev for this lirc chardev
- `rawir`: queue for incoming raw IR
- `scancodes`: queue for incoming decoded scancodes
- `wait_poll`: poll struct for lirc device
- `carrier_low`: when setting the carrier range, first the low end must be
  set with an ioctl and then the high end with another ioctl
- `send_mode`: lirc mode for sending, either LIRC_MODE_SCANCODE or
  LIRC_MODE_PULSE
- `rec_mode`: lirc mode for receiving, either LIRC_MODE_SCANCODE or
  LIRC_MODE_MODE2

#### <a id="c-struct-rc_dev"></a>`struct rc_dev`

represents a remote control device

**Definition**

```c
struct rc_dev {
        struct device                   dev;
        bool managed_alloc;
        bool registered;
        bool idle;
        bool encode_wakeup;
        unsigned int                    minor;
        const struct attribute_group    *sysfs_groups[5];
        const char                      *device_name;
        const char                      *input_phys;
        struct input_id                 input_id;
        const char                      *driver_name;
        const char                      *map_name;
        struct rc_map                   rc_map;
        struct mutex                    lock;
        struct ir_raw_event_ctrl        *raw;
        struct input_dev                *input_dev;
        enum rc_driver_type             driver_type;
        u32 users;
        u64 allowed_protocols;
        u64 enabled_protocols;
        u64 allowed_wakeup_protocols;
        enum rc_proto                   wakeup_protocol;
        struct rc_scancode_filter       scancode_filter;
        struct rc_scancode_filter       scancode_wakeup_filter;
        u32 scancode_mask;
        void *priv;
        spinlock_t keylock;
        bool keypressed;
        u8 last_toggle;
        u32 last_keycode;
        enum rc_proto                   last_protocol;
        u64 last_scancode;
        unsigned long                   keyup_jiffies;
        struct timer_list               timer_keyup;
        struct timer_list               timer_repeat;
        u32 timeout;
        u32 min_timeout;
        u32 max_timeout;
        u32 rx_resolution;
    #ifdef CONFIG_LIRC;
        struct device                   lirc_dev;
        struct cdev                     lirc_cdev;
        ktime_t gap_start;
        spinlock_t lirc_fh_lock;
        struct list_head                lirc_fh;
    #endif;
        int (*change_protocol)(struct rc_dev *dev, u64 *rc_proto);
        int (*open)(struct rc_dev *dev);
        void (*close)(struct rc_dev *dev);
        int (*s_tx_mask)(struct rc_dev *dev, u32 mask);
        int (*s_tx_carrier)(struct rc_dev *dev, u32 carrier);
        int (*s_tx_duty_cycle)(struct rc_dev *dev, u32 duty_cycle);
        int (*s_rx_carrier_range)(struct rc_dev *dev, u32 min, u32 max);
        int (*tx_ir)(struct rc_dev *dev, unsigned *txbuf, unsigned n);
        void (*s_idle)(struct rc_dev *dev, bool enable);
        int (*s_wideband_receiver)(struct rc_dev *dev, int enable);
        int (*s_carrier_report) (struct rc_dev *dev, int enable);
        int (*s_filter)(struct rc_dev *dev, struct rc_scancode_filter *filter);
        int (*s_wakeup_filter)(struct rc_dev *dev, struct rc_scancode_filter *filter);
        int (*s_timeout)(struct rc_dev *dev, unsigned int timeout);
};
```

**Members**

- `dev`: driver model's view of this device
- `managed_alloc`: devm_rc_allocate_device was used to create rc_dev
- `registered`: set to true by [`rc_register_device()`](#c-rc_register_device), false by
  rc_unregister_device
- `idle`: used to keep track of RX state
- `encode_wakeup`: wakeup filtering uses IR encode API, therefore the allowed
  wakeup protocols is the set of all raw encoders
- `minor`: unique minor remote control device number
- `sysfs_groups`: sysfs attribute groups
- `device_name`: name of the rc child device
- `input_phys`: physical path to the input child device
- `input_id`: id of the input child device (struct input_id)
- `driver_name`: name of the hardware driver which registered this device
- `map_name`: name of the default keymap
- `rc_map`: current scan/key table
- `lock`: used to ensure we've filled in all protocol details before
  anyone can call show_protocols or store_protocols
- `raw`: additional data for raw pulse/space devices
- `input_dev`: the input child device used to communicate events to userspace
- `driver_type`: specifies if protocol decoding is done in hardware or software
- `users`: number of current users of the device
- `allowed_protocols`: bitmask with the supported RC_PROTO_BIT_* protocols
- `enabled_protocols`: bitmask with the enabled RC_PROTO_BIT_* protocols
- `allowed_wakeup_protocols`: bitmask with the supported RC_PROTO_BIT_* wakeup
  protocols
- `wakeup_protocol`: the enabled RC_PROTO_* wakeup protocol or
  RC_PROTO_UNKNOWN if disabled.
- `scancode_filter`: scancode filter
- `scancode_wakeup_filter`: scancode wakeup filters
- `scancode_mask`: some hardware decoders are not capable of providing the full
  scancode to the application. As this is a hardware limit, we can't do
  anything with it. Yet, as the same keycode table can be used with other
  devices, a mask is provided to allow its usage. Drivers should generally
  leave this field in blank
- `priv`: driver-specific data
- `keylock`: protects the remaining members of the struct
- `keypressed`: whether a key is currently pressed
- `last_toggle`: toggle value of last command
- `last_keycode`: keycode of last keypress
- `last_protocol`: protocol of last keypress
- `last_scancode`: scancode of last keypress
- `keyup_jiffies`: time (in jiffies) when the current keypress should be released
- `timer_keyup`: timer for releasing a keypress
- `timer_repeat`: timer for autorepeat events. This is needed for CEC, which
  has non-standard repeats.
- `timeout`: optional time after which device stops sending data
- `min_timeout`: minimum timeout supported by device
- `max_timeout`: maximum timeout supported by device
- `rx_resolution`: resolution (in us) of input sampler
- `lirc_dev`: lirc device
- `lirc_cdev`: lirc char cdev
- `gap_start`: start time for gap after timeout if non-zero
- `lirc_fh_lock`: protects lirc_fh list
- `lirc_fh`: list of open files
- `change_protocol`: allow changing the protocol used on hardware decoders
- `open`: callback to allow drivers to enable polling/irq when IR input device
  is opened.
- `close`: callback to allow drivers to disable polling/irq when IR input device
  is opened.
- `s_tx_mask`: set transmitter mask (for devices with multiple tx outputs)
- `s_tx_carrier`: set transmit carrier frequency
- `s_tx_duty_cycle`: set transmit duty cycle (0% - 100%)
- `s_rx_carrier_range`: inform driver about carrier it is expected to handle
- `tx_ir`: transmit IR
- `s_idle`: enable/disable hardware idle mode, upon which,
  device doesn't interrupt host until it sees IR pulses
- `s_wideband_receiver`: enable wide band receiver used for learning
- `s_carrier_report`: enable carrier reports
- `s_filter`: set the scancode filter
- `s_wakeup_filter`: set the wakeup scancode filter. If the mask is zero
  then wakeup should be disabled. wakeup_protocol will be set to
  a valid protocol if mask is nonzero.
- `s_timeout`: set hardware timeout in us

#### <a id="c-rc_allocate_device"></a>`rc_allocate_device()`

```c
struct rc_dev * rc_allocate_device(enum rc_driver_type)
```

Allocates a RC device

**Parameters**

- `enum rc_driver_type`: specifies the type of the RC output to be allocated
  returns a pointer to struct rc_dev.

#### <a id="c-devm_rc_allocate_device"></a>`devm_rc_allocate_device()`

```c
struct rc_dev * devm_rc_allocate_device(struct device *dev, enum rc_driver_type)
```

Managed RC device allocation

**Parameters**

- `struct device *dev`: pointer to struct device
- `enum rc_driver_type`: specifies the type of the RC output to be allocated
  returns a pointer to struct rc_dev.

#### <a id="c-rc_free_device"></a>`rc_free_device()`

```c
void rc_free_device(struct rc_dev *dev)
```

Frees a RC device

**Parameters**

- `struct rc_dev *dev`: pointer to struct rc_dev.

#### <a id="c-rc_register_device"></a>`rc_register_device()`

```c
int rc_register_device(struct rc_dev *dev)
```

Registers a RC device

**Parameters**

- `struct rc_dev *dev`: pointer to struct rc_dev.

#### <a id="c-devm_rc_register_device"></a>`devm_rc_register_device()`

```c
int devm_rc_register_device(struct device *parent, struct rc_dev *dev)
```

Manageded registering of a RC device

**Parameters**

- `struct device *parent`: pointer to struct device.
- `struct rc_dev *dev`: pointer to struct rc_dev.

#### <a id="c-rc_unregister_device"></a>`rc_unregister_device()`

```c
void rc_unregister_device(struct rc_dev *dev)
```

Unregisters a RC device

**Parameters**

- `struct rc_dev *dev`: pointer to struct rc_dev.



#### <a id="c-struct-rc_map_table"></a>`struct rc_map_table`

represents a scancode/keycode pair

**Definition**

```c
struct rc_map_table {
    u64 scancode;
    u32 keycode;
};
```

**Members**

- `scancode`: scan code (u64)
- `keycode`: Linux input keycode

#### <a id="c-struct-rc_map"></a>`struct rc_map`

represents a keycode map table

**Definition**

```c
struct rc_map {
    struct rc_map_table     *scan;
    unsigned int            size;
    unsigned int            len;
    unsigned int            alloc;
    enum rc_proto           rc_proto;
    const char              *name;
    spinlock_t lock;
};
```

**Members**

- `scan`: pointer to struct [`rc_map_table`](#c-struct-rc_map_table)
- `size`: Max number of entries
- `len`: Number of entries that are in use
- `alloc`: size of \*scan, in bytes
- `rc_proto`: type of the remote controller protocol, as defined at
  enum [`rc_proto`](/kernel/userspace/userspace-api/media-rc/lirc-dev-intro.md#c-enum-rc_proto)
- `name`: name of the key map table
- `lock`: lock to protect access to this structure

#### <a id="c-struct-rc_map_list"></a>`struct rc_map_list`

list of the registered [`rc_map`](#c-struct-rc_map) maps

**Definition**

```c
struct rc_map_list {
    struct list_head         list;
    struct rc_map map;
};
```

**Members**

- `list`: pointer to struct `list_head`
- `map`: pointer to struct [`rc_map`](#c-struct-rc_map)

#### <a id="c-rc_map_register"></a>`rc_map_register()`

```c
int rc_map_register(struct rc_map_list *map)
```

Registers a Remote Controller scancode map

**Parameters**

- `struct rc_map_list *map`: pointer to struct rc_map_list

#### <a id="c-rc_map_unregister"></a>`rc_map_unregister()`

```c
void rc_map_unregister(struct rc_map_list *map)
```

Unregisters a Remote Controller scancode map

**Parameters**

- `struct rc_map_list *map`: pointer to struct rc_map_list

#### <a id="c-rc_map_get"></a>`rc_map_get()`

```c
struct rc_map * rc_map_get(const char *name)
```

gets an RC map from its name

**Parameters**

- `const char *name`: name of the RC scancode map

---

# Pixel data transmitter and receiver drivers

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> V4L2 supports various devices that transmit and receive pixel data. Examples of these devices include a camera sensor, a TV tuner and a parallel, a BT.656 or a CSI-2 receiver in an SoC.

<a id="rst-pixel-data-transmitter-and-receiver-drivers"></a>
<a id="rst-transmitter-receiver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

V4L2 supports various devices that transmit and receive pixel data. Examples of these devices include a camera sensor, a TV tuner and a parallel, a BT.656 or a CSI-2 receiver in an SoC.

<a id="rst-bus-types"></a>

## Bus types

The following buses are the most common. This section discusses these two only.

<a id="rst-mipi-csi-2"></a>

### MIPI CSI-2

CSI-2 is a data bus intended for transferring images from cameras to the host SoC. It is defined by the [MIPI alliance](<https://www.mipi.org/>).

<a id="rst-mipi-alliance"></a>



<a id="rst-parallel-and-bt-656"></a>

### Parallel and BT.656

The parallel and [BT.656](<https://en.wikipedia.org/wiki/ITU-R_BT.656>) buses transport one bit of data on each clock cycle per data line. The parallel bus uses synchronisation and other additional signals whereas BT.656 embeds synchronisation.

<a id="rst-bt-656"></a>



<a id="rst-transmitter-drivers"></a>

## Transmitter drivers

Transmitter drivers generally need to provide the receiver drivers with the configuration of the transmitter. What is required depends on the type of the bus. These are common for both buses.

<a id="rst-media-bus-pixel-code"></a>

### Media bus pixel code

See [v4l2-mbus-pixelcode](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/userspace-api/media/v4l/subdev-formats.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>).

<a id="rst-link-frequency"></a>

### Link frequency

The [V4L2_CID_LINK_FREQ](</kernel/userspace/userspace-api/media-v4l/ext-ctrls-image-process.md#rst-v4l2-cid-link-freq>) control is used to tell the receiver the frequency of the bus (i.e. it is not the same as the symbol rate).

Drivers that do not have user-configurable link frequency should report it through the `.get_mbus_config()` subdev pad operation, in the `link_freq` field of struct v4l2_mbus_config, instead of through controls.

Receiver drivers should use `v4l2_get_link_freq()` helper to obtain the link frequency from the transmitter sub-device.

<a id="rst-enable-streams-and-disable-streams-callbacks"></a>

### `.enable_streams()` and `.disable_streams()` callbacks

The struct v4l2_subdev_pad_ops-&gt;enable_streams() and struct v4l2_subdev_pad_ops-&gt;disable_streams() callbacks are used by the receiver driver to control the transmitter driver's streaming state. These callbacks may not be called directly, but by using `v4l2_subdev_enable_streams()` and `v4l2_subdev_disable_streams()`.

<a id="rst-stopping-the-transmitter"></a>

### Stopping the transmitter

A transmitter stops sending the stream of images as a result of calling the `.disable_streams()` callback. Some transmitters may stop the stream at a frame boundary whereas others stop immediately, effectively leaving the current frame unfinished. The receiver driver should not make assumptions either way, but function properly in both cases.

<a id="rst-csi-2-transmitter-drivers"></a>

## CSI-2 transmitter drivers

<a id="rst-pixel-rate"></a>

### Pixel rate

The pixel rate on the bus is calculated as follows:



```text
pixel_rate = link_freq * 2 * nr_of_lanes * 16 / k / bits_per_sample
```

where


<table>
<caption>variables in pixel rate calculation</caption>
<thead>
<tr>
<th>


variable or constant

</th>
<th>


description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


link_freq

</td>
<td>


The value of the `V4L2_CID_LINK_FREQ` integer64 menu item.

</td>
</tr>
<tr>
<td>


nr_of_lanes

</td>
<td>


Number of data lanes used on the CSI-2 link.

</td>
</tr>
<tr>
<td>


2

</td>
<td>


Data is transferred on both rising and falling edge of the signal.

</td>
</tr>
<tr>
<td>


bits_per_sample

</td>
<td>


Number of bits per sample.

</td>
</tr>
<tr>
<td>


k

</td>
<td>


16 for D-PHY and 7 for C-PHY.

</td>
</tr>
</tbody>
</table>

Information on whether D-PHY or C-PHY is used, and the value of `nr_of_lanes`, can be obtained from the OF endpoint configuration.

> [!NOTE]
>
> The pixel rate calculated this way is **not** the same thing as the pixel rate on the camera sensor's pixel array which is indicated by the [V4L2_CID_PIXEL_RATE](</kernel/userspace/userspace-api/media-v4l/ext-ctrls-image-process.md#rst-v4l2-cid-pixel-rate>) control.

<a id="rst-lp-11-and-lp-111-states"></a>

### LP-11 and LP-111 states

As part of transitioning to high speed mode, a CSI-2 transmitter typically briefly sets the bus to LP-11 or LP-111 state, depending on the PHY. This period may be as short as 100 µs, during which the receiver observes this state and proceeds its own part of high speed mode transition.

Most receivers are capable of autonomously handling this once the software has configured them to do so, but there are receivers which require software involvement in observing LP-11 or LP-111 state. 100 µs is a brief period to hit in software, especially when there is no interrupt telling something is happening.

One way to address this is to configure the transmitter side explicitly to LP-11 or LP-111 state, which requires support from the transmitter hardware. This is not universally available. Many devices return to this state once streaming is stopped while the state after power-on is LP-00 or LP-000.

The `.pre_streamon()` callback may be used to prepare a transmitter for transitioning to streaming state, but not yet start streaming. Similarly, the `.post_streamoff()` callback is used to undo what was done by the `.pre_streamon()` callback. The caller of `.pre_streamon()` is thus required to call `.post_streamoff()` for each successful call of `.pre_streamon()`.

In the context of CSI-2, the `.pre_streamon()` callback is used to transition the transmitter to the LP-11 or LP-111 state. This also requires powering on the device, so this should be only done when it is needed.

Receiver drivers that do not need explicit LP-11 or LP-111 state setup are waived from calling the two callbacks.

---

# V4L2 async kAPI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 async kAPI.

<a id="rst-v4l2-async-kapi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-v4l2_async_match_type"></a>`enum v4l2_async_match_type`

type of asynchronous subdevice logic to be used in order to identify a match

**Constants**

- `V4L2_ASYNC_MATCH_TYPE_I2C`: Match will check for I2C adapter ID and address
- `V4L2_ASYNC_MATCH_TYPE_FWNODE`: Match will use firmware node

**Description**

This enum is used by the asynchronous connection logic to define the
algorithm that will be used to match an asynchronous device.

#### <a id="c-struct-v4l2_async_match_desc"></a>`struct v4l2_async_match_desc`

async connection match information

**Definition**

```c
struct v4l2_async_match_desc {
    enum v4l2_async_match_type type;
    union {
        struct fwnode_handle *fwnode;
        struct {
            int adapter_id;
            unsigned short address;
        } i2c;
    };
};
```

**Members**

- `type`: type of match that will be used
- `{unnamed_union}`: anonymous
- `fwnode`: pointer to `struct fwnode_handle` to be matched.
  Used if **match_type** is `V4L2_ASYNC_MATCH_TYPE_FWNODE`.
- `i2c`: embedded struct with I2C parameters to be matched.
  Both **match.i2c.adapter_id** and **match.i2c.address**
  should be matched.
  Used if **match_type** is `V4L2_ASYNC_MATCH_TYPE_I2C`.
- `i2c.adapter_id`: I2C adapter ID to be matched.
  Used if **match_type** is `V4L2_ASYNC_MATCH_TYPE_I2C`.
- `i2c.address`: I2C address to be matched.
  Used if **match_type** is `V4L2_ASYNC_MATCH_TYPE_I2C`.

#### <a id="c-struct-v4l2_async_connection"></a>`struct v4l2_async_connection`

sub-device connection descriptor, as known to a bridge

**Definition**

```c
struct v4l2_async_connection {
    struct v4l2_async_match_desc match;
    struct v4l2_async_notifier *notifier;
    struct list_head asc_entry;
    struct list_head asc_subdev_entry;
    struct v4l2_subdev *sd;
};
```

**Members**

- `match`: struct of match type and per-bus type matching data sets
- `notifier`: the async notifier the connection is related to
- `asc_entry`: used to add struct v4l2_async_connection objects to the
  notifier **waiting_list** or **done_list**
- `asc_subdev_entry`: entry in struct v4l2_async_subdev.asc_list list
- `sd`: the related sub-device

**Description**

When this struct is used as a member in a driver specific struct, the driver
specific struct shall contain the [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) as its first
member.

#### <a id="c-struct-v4l2_async_notifier_operations"></a>`struct v4l2_async_notifier_operations`

Asynchronous V4L2 notifier operations

**Definition**

```c
struct v4l2_async_notifier_operations {
    int (*bound)(struct v4l2_async_notifier *notifier, struct v4l2_subdev *subdev, struct v4l2_async_connection *asc);
    int (*complete)(struct v4l2_async_notifier *notifier);
    void (*unbind)(struct v4l2_async_notifier *notifier, struct v4l2_subdev *subdev, struct v4l2_async_connection *asc);
    void (*destroy)(struct v4l2_async_connection *asc);
};
```

**Members**

- `bound`: a sub-device has been bound by the given connection
- `complete`: All connections have been bound successfully. The complete
  callback is only executed for the root notifier.
- `unbind`: a subdevice is leaving
- `destroy`: the asc is about to be freed

#### <a id="c-struct-v4l2_async_notifier"></a>`struct v4l2_async_notifier`

v4l2_device notifier data

**Definition**

```c
struct v4l2_async_notifier {
    const struct v4l2_async_notifier_operations *ops;
    struct v4l2_device *v4l2_dev;
    struct v4l2_subdev *sd;
    struct v4l2_async_notifier *parent;
    struct list_head waiting_list;
    struct list_head done_list;
    struct list_head notifier_entry;
};
```

**Members**

- `ops`: notifier operations
- `v4l2_dev`: v4l2_device of the root notifier, NULL otherwise
- `sd`: sub-device that registered the notifier, NULL otherwise
- `parent`: parent notifier
- `waiting_list`: list of struct v4l2_async_connection, waiting for their
  drivers
- `done_list`: list of struct v4l2_subdev, already probed
- `notifier_entry`: member in a global list of notifiers

#### <a id="c-struct-v4l2_async_subdev_endpoint"></a>`struct v4l2_async_subdev_endpoint`

Entry in sub-device's fwnode list

**Definition**

```c
struct v4l2_async_subdev_endpoint {
    struct list_head async_subdev_endpoint_entry;
    struct fwnode_handle *endpoint;
};
```

**Members**

- `async_subdev_endpoint_entry`: An entry in async_subdev_endpoint_list of
  [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `endpoint`: Endpoint fwnode agains which to match the sub-device

#### <a id="c-v4l2_async_debug_init"></a>`v4l2_async_debug_init()`

```c
void v4l2_async_debug_init(struct dentry *debugfs_dir)
```

Initialize debugging tools.

**Parameters**

- `struct dentry *debugfs_dir`: pointer to the parent debugfs `struct dentry`

#### <a id="c-v4l2_async_nf_init"></a>`v4l2_async_nf_init()`

```c
void v4l2_async_nf_init(struct v4l2_async_notifier *notifier, struct v4l2_device *v4l2_dev)
```

Initialize a notifier.

**Parameters**

- `struct v4l2_async_notifier *notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `struct v4l2_device *v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device)

**Description**

This function initializes the notifier **asc_entry**. It must be called
before adding a subdevice to a notifier, using one of:
[`v4l2_async_nf_add_fwnode_remote()`](#c-v4l2_async_nf_add_fwnode_remote),
[`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode) or
[`v4l2_async_nf_add_i2c()`](#c-v4l2_async_nf_add_i2c).

#### <a id="c-v4l2_async_subdev_nf_init"></a>`v4l2_async_subdev_nf_init()`

```c
void v4l2_async_subdev_nf_init(struct v4l2_async_notifier *notifier, struct v4l2_subdev *sd)
```

Initialize a sub-device notifier.

**Parameters**

- `struct v4l2_async_notifier *notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

This function initializes the notifier **asc_list**. It must be called
before adding a subdevice to a notifier, using one of:
[`v4l2_async_nf_add_fwnode_remote()`](#c-v4l2_async_nf_add_fwnode_remote), [`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode) or
[`v4l2_async_nf_add_i2c()`](#c-v4l2_async_nf_add_i2c).

#### <a id="c-v4l2_async_nf_add_fwnode"></a>`v4l2_async_nf_add_fwnode()`

```c
v4l2_async_nf_add_fwnode(notifier, fwnode, type)
```

Allocate and add a fwnode async subdev to the notifier's master asc_list.

**Parameters**

- `notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `fwnode`: fwnode handle of the sub-device to be matched, pointer to
  `struct fwnode_handle`
- `type`: Type of the driver's async sub-device or connection struct. The
  [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) shall be the first member of the
  driver's async struct, i.e. both begin at the same memory address.

**Description**

Allocate a fwnode-matched asc of size asc_struct_size, and add it to the
notifiers **asc_list**. The function also gets a reference of the fwnode which
is released later at notifier cleanup time.

#### <a id="c-v4l2_async_nf_add_fwnode_remote"></a>`v4l2_async_nf_add_fwnode_remote()`

```c
v4l2_async_nf_add_fwnode_remote(notifier, ep, type)
```

Allocate and add a fwnode remote async subdev to the notifier's master asc_list.

**Parameters**

- `notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `ep`: local endpoint pointing to the remote connection to be matched,
  pointer to `struct fwnode_handle`
- `type`: Type of the driver's async connection struct. The [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) shall be the first member of the driver's async
  connection struct, i.e. both begin at the same memory address.

**Description**

Gets the remote endpoint of a given local endpoint, set it up for fwnode
matching and adds the async connection to the notifier's **asc_list**. The
function also gets a reference of the fwnode which is released later at
notifier cleanup time.

This is just like [`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode), but with the
exception that the fwnode refers to a local endpoint, not the remote one.

#### <a id="c-v4l2_async_nf_add_i2c"></a>`v4l2_async_nf_add_i2c()`

```c
v4l2_async_nf_add_i2c(notifier, adapter, address, type)
```

Allocate and add an i2c async subdev to the notifier's master asc_list.

**Parameters**

- `notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)
- `adapter`: I2C adapter ID to be matched
- `address`: I2C address of connection to be matched
- `type`: Type of the driver's async connection struct. The [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) shall be the first member of the driver's async
  connection struct, i.e. both begin at the same memory address.

**Description**

Same as [`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode) but for I2C matched
connections.

#### <a id="c-v4l2_async_subdev_endpoint_add"></a>`v4l2_async_subdev_endpoint_add()`

```c
int v4l2_async_subdev_endpoint_add(struct v4l2_subdev *sd, struct fwnode_handle *fwnode)
```

Add an endpoint fwnode to async sub-device matching list

**Parameters**

- `struct v4l2_subdev *sd`: the sub-device
- `struct fwnode_handle *fwnode`: the endpoint fwnode to match

**Description**

Add a fwnode to the async sub-device's matching list. This allows registering
multiple async sub-devices from a single device.

Note that calling [`v4l2_subdev_cleanup()`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-v4l2_subdev_cleanup) as part of the sub-device's cleanup
if endpoints have been added to the sub-device's fwnode matching list.

Returns an error on failure, 0 on success.

#### <a id="c-v4l2_async_connection_unique"></a>`v4l2_async_connection_unique()`

```c
struct v4l2_async_connection * v4l2_async_connection_unique(struct v4l2_subdev *sd)
```

return a unique [`struct v4l2_async_connection`](#c-struct-v4l2_async_connection) for a sub-device

**Parameters**

- `struct v4l2_subdev *sd`: the sub-device

**Description**

Return an async connection for a sub-device, when there is a single
one only.

#### <a id="c-v4l2_async_nf_register"></a>`v4l2_async_nf_register()`

```c
int v4l2_async_nf_register(struct v4l2_async_notifier *notifier)
```

registers a subdevice asynchronous notifier

**Parameters**

- `struct v4l2_async_notifier *notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)

#### <a id="c-v4l2_async_nf_unregister"></a>`v4l2_async_nf_unregister()`

```c
void v4l2_async_nf_unregister(struct v4l2_async_notifier *notifier)
```

unregisters a subdevice asynchronous notifier

**Parameters**

- `struct v4l2_async_notifier *notifier`: pointer to [`struct v4l2_async_notifier`](#c-struct-v4l2_async_notifier)

#### <a id="c-v4l2_async_nf_cleanup"></a>`v4l2_async_nf_cleanup()`

```c
void v4l2_async_nf_cleanup(struct v4l2_async_notifier *notifier)
```

clean up notifier resources

**Parameters**

- `struct v4l2_async_notifier *notifier`: the notifier the resources of which are to be cleaned up

**Description**

Release memory resources related to a notifier, including the async
connections allocated for the purposes of the notifier but not the notifier
itself. The user is responsible for calling this function to clean up the
notifier after calling [`v4l2_async_nf_add_fwnode_remote()`](#c-v4l2_async_nf_add_fwnode_remote),
[`v4l2_async_nf_add_fwnode()`](#c-v4l2_async_nf_add_fwnode) or [`v4l2_async_nf_add_i2c()`](#c-v4l2_async_nf_add_i2c).

There is no harm from calling [`v4l2_async_nf_cleanup()`](#c-v4l2_async_nf_cleanup) in other
cases as long as its memory has been zeroed after it has been
allocated.

#### <a id="c-v4l2_async_register_subdev"></a>`v4l2_async_register_subdev()`

```c
v4l2_async_register_subdev(sd)
```

registers a sub-device to the asynchronous subdevice framework

**Parameters**

- `sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l2_async_register_subdev_sensor"></a>`v4l2_async_register_subdev_sensor()`

```c
int v4l2_async_register_subdev_sensor(struct v4l2_subdev *sd)
```

registers a sensor sub-device to the asynchronous sub-device framework and parse set up common sensor related devices

**Parameters**

- `struct v4l2_subdev *sd`: pointer to struct [`v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

This function is just like [`v4l2_async_register_subdev()`](#c-v4l2_async_register_subdev) with the exception
that calling it will also parse firmware interfaces for remote references
using `v4l2_async_nf_parse_fwnode_sensor()` and registers the
async sub-devices. The sub-device is similarly unregistered by calling
[`v4l2_async_unregister_subdev()`](#c-v4l2_async_unregister_subdev).

While registered, the subdev module is marked as in-use.

An error is returned if the module is no longer loaded on any attempts
to register it.

#### <a id="c-v4l2_async_unregister_subdev"></a>`v4l2_async_unregister_subdev()`

```c
void v4l2_async_unregister_subdev(struct v4l2_subdev *sd)
```

unregisters a sub-device to the asynchronous subdevice framework

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

---

# V4L2 CCI kAPI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 CCI kAPI.

<a id="rst-v4l2-cci-kapi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-cci_reg_sequence"></a>`struct cci_reg_sequence`

An individual write from a sequence of CCI writes

**Definition**

```c
struct cci_reg_sequence {
    u32 reg;
    u64 val;
};
```

**Members**

- `reg`: Register address, use CCI_REG#() macros to encode reg width
- `val`: Register value

**Description**

Register/value pairs for sequences of writes.

#### <a id="c-cci_read"></a>`cci_read()`

```c
int cci_read(struct regmap *map, u32 reg, u64 *val, int *err)
```

Read a value from a single CCI register

**Parameters**

- `struct regmap *map`: Register map to read from
- `u32 reg`: Register address to read, use CCI_REG#() macros to encode reg width
- `u64 *val`: Pointer to store read value
- `int *err`: Optional pointer to store errors, if a previous error is set
  then the read will be skipped

**Return**

`0` on success or a negative error code on failure.

#### <a id="c-cci_write"></a>`cci_write()`

```c
int cci_write(struct regmap *map, u32 reg, u64 val, int *err)
```

Write a value to a single CCI register

**Parameters**

- `struct regmap *map`: Register map to write to
- `u32 reg`: Register address to write, use CCI_REG#() macros to encode reg width
- `u64 val`: Value to be written
- `int *err`: Optional pointer to store errors, if a previous error is set
  then the write will be skipped

**Return**

`0` on success or a negative error code on failure.

#### <a id="c-cci_update_bits"></a>`cci_update_bits()`

```c
int cci_update_bits(struct regmap *map, u32 reg, u64 mask, u64 val, int *err)
```

Perform a read/modify/write cycle on a single CCI register

**Parameters**

- `struct regmap *map`: Register map to update
- `u32 reg`: Register address to update, use CCI_REG#() macros to encode reg width
- `u64 mask`: Bitmask to change
- `u64 val`: New value for bitmask
- `int *err`: Optional pointer to store errors, if a previous error is set
  then the update will be skipped

**Description**

Note this uses read-modify-write to update the bits, atomicity with regards
to other cci_*() register access functions is NOT guaranteed.

**Return**

`0` on success or a negative error code on failure.

#### <a id="c-cci_multi_reg_write"></a>`cci_multi_reg_write()`

```c
int cci_multi_reg_write(struct regmap *map, const struct cci_reg_sequence *regs, unsigned int num_regs, int *err)
```

Write multiple registers to the device

**Parameters**

- `struct regmap *map`: Register map to write to
- `const struct cci_reg_sequence *regs`: Array of structures containing register-address, -value pairs to be
  written, register-addresses use CCI_REG#() macros to encode reg width
- `unsigned int num_regs`: Number of registers to write
- `int *err`: Optional pointer to store errors, if a previous error is set
  then the write will be skipped

**Description**

Write multiple registers to the device where the set of register, value
pairs are supplied in any order, possibly not all in a single range.

Use of the CCI_REG#() macros to encode reg width is mandatory.

For raw lists of register-address, -value pairs with only 8 bit
wide writes `regmap_multi_reg_write()` can be used instead.

**Return**

`0` on success or a negative error code on failure.

#### <a id="c-devm_cci_regmap_init_i2c"></a>`devm_cci_regmap_init_i2c()`

```c
struct regmap * devm_cci_regmap_init_i2c(struct i2c_client *client, int reg_addr_bits)
```

Create regmap to use with cci_*() register access functions

**Parameters**

- `struct i2c_client *client`: i2c_client to create the regmap for
- `int reg_addr_bits`: register address width to use (8 or 16)

**Description**

Note the memory for the created regmap is `devm()` managed, tied to the client.

**Return**

`0` on success or a negative error code on failure.

---

# V4L2 common functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 common functions and data structures.

<a id="rst-v4l2-common-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-v4l2_ctrl_query_fill"></a>`v4l2_ctrl_query_fill()`

```c
int v4l2_ctrl_query_fill(struct v4l2_queryctrl *qctrl, s32 min, s32 max, s32 step, s32 def)
```

Fill in a struct v4l2_queryctrl

**Parameters**

- `struct v4l2_queryctrl *qctrl`: pointer to the [`struct v4l2_queryctrl`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_queryctrl) to be filled
- `s32 min`: minimum value for the control
- `s32 max`: maximum value for the control
- `s32 step`: control step
- `s32 def`: default value for the control

**Description**

Fills the [`struct v4l2_queryctrl`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_queryctrl) fields for the query control.

> [!NOTE]
> This function assumes that the **qctrl->id** field is filled.

Returns -EINVAL if the control is not known by the V4L2 core, 0 on success.

#### <a id="c-enum-v4l2_i2c_tuner_type"></a>`enum v4l2_i2c_tuner_type`

specifies the range of tuner address that should be used when seeking for I2C devices.

**Constants**

- `ADDRS_RADIO`: Radio tuner addresses.
  Represent the following I2C addresses:
  0x10 (if compiled with tea5761 support)
  and 0x60.
- `ADDRS_DEMOD`: Demod tuner addresses.
  Represent the following I2C addresses:
  0x42, 0x43, 0x4a and 0x4b.
- `ADDRS_TV`: TV tuner addresses.
  Represent the following I2C addresses:
  0x42, 0x43, 0x4a, 0x4b, 0x60, 0x61, 0x62,
  0x63 and 0x64.
- `ADDRS_TV_WITH_DEMOD`: TV tuner addresses if demod is present, this
  excludes addresses used by the demodulator
  from the list of candidates.
  Represent the following I2C addresses:
  0x60, 0x61, 0x62, 0x63 and 0x64.

**NOTE**

All I2C addresses above use the 7-bit notation.

#### <a id="c-v4l2_i2c_new_subdev"></a>`v4l2_i2c_new_subdev()`

```c
struct v4l2_subdev * v4l2_i2c_new_subdev(struct v4l2_device *v4l2_dev, struct i2c_adapter *adapter, const char *client_type, u8 addr, const unsigned short *probe_addrs)
```

Load an i2c module and return an initialized [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev).

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device)
- `struct i2c_adapter *adapter`: pointer to struct i2c_adapter
- `const char *client_type`: name of the chip that's on the adapter.
- `u8 addr`: I2C address. If zero, it will use **probe_addrs**
- `const unsigned short *probe_addrs`: array with a list of address. The last entry at such
  array should be `I2C_CLIENT_END`.

**Description**

returns a [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer.

#### <a id="c-v4l2_i2c_new_subdev_board"></a>`v4l2_i2c_new_subdev_board()`

```c
struct v4l2_subdev * v4l2_i2c_new_subdev_board(struct v4l2_device *v4l2_dev, struct i2c_adapter *adapter, struct i2c_board_info *info, const unsigned short *probe_addrs)
```

Load an i2c module and return an initialized [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev).

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device)
- `struct i2c_adapter *adapter`: pointer to struct i2c_adapter
- `struct i2c_board_info *info`: pointer to struct i2c_board_info used to replace the irq,
  platform_data and addr arguments.
- `const unsigned short *probe_addrs`: array with a list of address. The last entry at such
  array should be `I2C_CLIENT_END`.

**Description**

returns a [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer.

#### <a id="c-v4l2_i2c_subdev_set_name"></a>`v4l2_i2c_subdev_set_name()`

```c
void v4l2_i2c_subdev_set_name(struct v4l2_subdev *sd, struct i2c_client *client, const char *devname, const char *postfix)
```

Set name for an I²C sub-device

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct i2c_client *client`: pointer to struct i2c_client
- `const char *devname`: the name of the device; if NULL, the I²C device drivers's name
  will be used
- `const char *postfix`: sub-device specific string to put right after the I²C device name;
  may be NULL

#### <a id="c-v4l2_i2c_subdev_init"></a>`v4l2_i2c_subdev_init()`

```c
void v4l2_i2c_subdev_init(struct v4l2_subdev *sd, struct i2c_client *client, const struct v4l2_subdev_ops *ops)
```

Initializes a [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) with data from an i2c_client struct.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct i2c_client *client`: pointer to struct i2c_client
- `const struct v4l2_subdev_ops *ops`: pointer to [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops)

#### <a id="c-v4l2_i2c_subdev_addr"></a>`v4l2_i2c_subdev_addr()`

```c
unsigned short v4l2_i2c_subdev_addr(struct v4l2_subdev *sd)
```

returns i2c client address of [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev).

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

Returns the address of an I2C sub-device

#### <a id="c-v4l2_i2c_tuner_addrs"></a>`v4l2_i2c_tuner_addrs()`

```c
const unsigned short * v4l2_i2c_tuner_addrs(enum v4l2_i2c_tuner_type type)
```

Return a list of I2C tuner addresses to probe.

**Parameters**

- `enum v4l2_i2c_tuner_type type`: type of the tuner to seek, as defined by
  [`enum v4l2_i2c_tuner_type`](#c-enum-v4l2_i2c_tuner_type).

**NOTE**

Use only if the tuner addresses are unknown.

#### <a id="c-v4l2_i2c_subdev_unregister"></a>`v4l2_i2c_subdev_unregister()`

```c
void v4l2_i2c_subdev_unregister(struct v4l2_subdev *sd)
```

Unregister a v4l2_subdev

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l2_spi_new_subdev"></a>`v4l2_spi_new_subdev()`

```c
struct v4l2_subdev * v4l2_spi_new_subdev(struct v4l2_device *v4l2_dev, struct spi_controller *ctlr, struct spi_board_info *info)
```

Load an spi module and return an initialized [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev).

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device).
- `struct spi_controller *ctlr`: pointer to struct spi_controller.
- `struct spi_board_info *info`: pointer to struct spi_board_info.

**Description**

returns a [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer.

#### <a id="c-v4l2_spi_subdev_init"></a>`v4l2_spi_subdev_init()`

```c
void v4l2_spi_subdev_init(struct v4l2_subdev *sd, struct spi_device *spi, const struct v4l2_subdev_ops *ops)
```

Initialize a v4l2_subdev with data from an spi_device struct.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct spi_device *spi`: pointer to struct spi_device.
- `const struct v4l2_subdev_ops *ops`: pointer to [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops)

#### <a id="c-v4l2_spi_subdev_unregister"></a>`v4l2_spi_subdev_unregister()`

```c
void v4l2_spi_subdev_unregister(struct v4l2_subdev *sd)
```

Unregister a v4l2_subdev

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l_bound_align_image"></a>`v4l_bound_align_image()`

```c
void v4l_bound_align_image(unsigned int *width, unsigned int wmin, unsigned int wmax, unsigned int walign, unsigned int *height, unsigned int hmin, unsigned int hmax, unsigned int halign, unsigned int salign)
```

adjust video dimensions according to a given constraints.

**Parameters**

- `unsigned int *width`: pointer to width that will be adjusted if needed.
- `unsigned int wmin`: minimum width.
- `unsigned int wmax`: maximum width.
- `unsigned int walign`: least significant bit on width.
- `unsigned int *height`: pointer to height that will be adjusted if needed.
- `unsigned int hmin`: minimum height.
- `unsigned int hmax`: maximum height.
- `unsigned int halign`: least significant bit on height.
- `unsigned int salign`: least significant bit for the image size (e. g.
  width * height).

**Description**

Clip an image to have **width** between **wmin** and **wmax**, and **height** between
**hmin** and **hmax**, inclusive.

Additionally, the **width** will be a multiple of 2^{walign},
the **height** will be a multiple of 2^{halign}, and the overall
size width * height will be a multiple of 2^{salign}.

> [!NOTE]
> 1. The clipping rectangle may be shrunk or enlarged to fit the alignment
>    constraints.
> 1. **wmax** must not be smaller than **wmin**.
> 1. **hmax** must not be smaller than **hmin**.
> 1. The alignments must not be so high there are no possible image
>    sizes within the allowed bounds.
> 1. **wmin** and **hmin** must be at least 1 (don't use 0).
> 1. For **walign**, **halign** and **salign**, if you don't care about a certain
>    alignment, specify `0`, as 2^0 = 1 and one byte alignment
>    is equivalent to no alignment.
> 1. If you only want to adjust downward, specify a maximum that's the
>    same as the initial value.

#### <a id="c-v4l2_find_nearest_size_conditional"></a>`v4l2_find_nearest_size_conditional()`

```c
v4l2_find_nearest_size_conditional(array, array_size, width_field, height_field, width, height, func, context)
```

Find the nearest size among a discrete set of resolutions contained in an array of a driver specific struct, with conditionally exlusion of certain modes

**Parameters**

- `array`: a driver specific array of image sizes
- `array_size`: the length of the driver specific array of image sizes
- `width_field`: the name of the width field in the driver specific struct
- `height_field`: the name of the height field in the driver specific struct
- `width`: desired width
- `height`: desired height
- `func`: ignores mode if returns false
- `context`: context for the function

**Description**

Finds the closest resolution to minimize the width and height differences
between what requested and the supported resolutions. The size of the width
and height fields in the driver specific must equal to that of u32, i.e. four
bytes. **func** is called for each mode considered, a mode is ignored if **func**
returns false for it.

Returns the best match or NULL if the length of the array is zero.

#### <a id="c-v4l2_find_nearest_size"></a>`v4l2_find_nearest_size()`

```c
v4l2_find_nearest_size(array, array_size, width_field, height_field, width, height)
```

Find the nearest size among a discrete set of resolutions contained in an array of a driver specific struct

**Parameters**

- `array`: a driver specific array of image sizes
- `array_size`: the length of the driver specific array of image sizes
- `width_field`: the name of the width field in the driver specific struct
- `height_field`: the name of the height field in the driver specific struct
- `width`: desired width
- `height`: desired height

**Description**

Finds the closest resolution to minimize the width and height differences
between what requested and the supported resolutions. The size of the width
and height fields in the driver specific must equal to that of u32, i.e. four
bytes.

Returns the best match or NULL if the length of the array is zero.

#### <a id="c-v4l2_g_parm_cap"></a>`v4l2_g_parm_cap()`

```c
int v4l2_g_parm_cap(struct video_device *vdev, struct v4l2_subdev *sd, struct v4l2_streamparm *a)
```

helper routine for vidioc_g_parm to fill this in by calling the get_frame_interval op of the given subdev. It only works for V4L2_BUF_TYPE_VIDEO_CAPTURE(_MPLANE), hence the _cap in the function name.

**Parameters**

- `struct video_device *vdev`: the struct video_device pointer. Used to determine the device caps.
- `struct v4l2_subdev *sd`: the sub-device pointer.
- `struct v4l2_streamparm *a`: the VIDIOC_G_PARM argument.

#### <a id="c-v4l2_s_parm_cap"></a>`v4l2_s_parm_cap()`

```c
int v4l2_s_parm_cap(struct video_device *vdev, struct v4l2_subdev *sd, struct v4l2_streamparm *a)
```

helper routine for vidioc_s_parm to fill this in by calling the set_frame_interval op of the given subdev. It only works for V4L2_BUF_TYPE_VIDEO_CAPTURE(_MPLANE), hence the _cap in the function name.

**Parameters**

- `struct video_device *vdev`: the struct video_device pointer. Used to determine the device caps.
- `struct v4l2_subdev *sd`: the sub-device pointer.
- `struct v4l2_streamparm *a`: the VIDIOC_S_PARM argument.

#### <a id="c-enum-v4l2_pixel_encoding"></a>`enum v4l2_pixel_encoding`

specifies the pixel encoding value

**Constants**

- `V4L2_PIXEL_ENC_UNKNOWN`: Pixel encoding is unknown/un-initialized
- `V4L2_PIXEL_ENC_YUV`: Pixel encoding is YUV
- `V4L2_PIXEL_ENC_RGB`: Pixel encoding is RGB
- `V4L2_PIXEL_ENC_BAYER`: Pixel encoding is Bayer

#### <a id="c-struct-v4l2_format_info"></a>`struct v4l2_format_info`

information about a V4L2 format

**Definition**

```c
struct v4l2_format_info {
    u32 format;
    u8 pixel_enc;
    u8 mem_planes;
    u8 comp_planes;
    u8 bpp[4];
    u8 bpp_div[4];
    u8 hdiv;
    u8 vdiv;
    u8 block_w[4];
    u8 block_h[4];
};
```

**Members**

- `format`: 4CC format identifier (V4L2_PIX_FMT_*)
- `pixel_enc`: Pixel encoding (see enum v4l2_pixel_encoding above)
- `mem_planes`: Number of memory planes, which includes the alpha plane (1 to 4).
- `comp_planes`: Number of component planes, which includes the alpha plane (1 to 4).
- `bpp`: Array of per-plane bytes per pixel
- `bpp_div`: Array of per-plane bytes per pixel divisors to support fractional pixel sizes.
- `hdiv`: Horizontal chroma subsampling factor
- `vdiv`: Vertical chroma subsampling factor
- `block_w`: Per-plane macroblock pixel width (optional)
- `block_h`: Per-plane macroblock pixel height (optional)

#### <a id="c-v4l2_get_link_freq"></a>`v4l2_get_link_freq()`

```c
s64 v4l2_get_link_freq(const struct media_pad *pad, unsigned int mul, unsigned int div)
```

Get link rate from transmitter

**Parameters**

- `const struct media_pad *pad`: The transmitter's media pad
- `unsigned int mul`: The multiplier between pixel rate and link frequency. Bits per pixel on
  D-PHY, samples per clock on parallel. 0 otherwise.
- `unsigned int div`: The divisor between pixel rate and link frequency. Number of data lanes
  times two on D-PHY, 1 on parallel. 0 otherwise.

**Description**

This function obtains and returns the link frequency from the transmitter
sub-device's pad. The link frequency is retrieved using the get_mbus_config
sub-device pad operation. If this fails, the function falls back to obtaining
the frequency either directly from the V4L2_CID_LINK_FREQ control if
implemented by the transmitter, or by calculating it from the pixel rate
obtained from the V4L2_CID_PIXEL_RATE control.

**Return**

* >0: Link frequency
* `-ENOENT`: Link frequency or pixel rate control not found
* `-EINVAL`: Invalid link frequency value

#### <a id="c-v4l2_get_active_data_lanes"></a>`v4l2_get_active_data_lanes()`

```c
int v4l2_get_active_data_lanes(const struct media_pad *pad, unsigned int max_data_lanes)
```

Get number of active data lanes from driver

**Parameters**

- `const struct media_pad *pad`: The transmitter's media pad.
- `unsigned int max_data_lanes`: The maximum number of active data lanes supported by
  the MIPI CSI link in hardware.

**Description**

This function is intended for obtaining the number of data lanes that are
actively being used by the driver for a MIPI CSI-2 device on a given media pad.
This information is derived from a mbus_config fetched from a device driver
using the get_mbus_config v4l2_subdev pad op.

**Return**

* >0: Number of active data lanes
* `-EINVAL`: Number of active data lanes is invalid, as it exceeds the maximum
  supported data lanes.

#### <a id="c-v4l2_link_freq_to_bitmap"></a>`v4l2_link_freq_to_bitmap()`

```c
int v4l2_link_freq_to_bitmap(struct device *dev, const u64 *fw_link_freqs, unsigned int num_of_fw_link_freqs, const s64 *driver_link_freqs, unsigned int num_of_driver_link_freqs, unsigned long *bitmap)
```

Figure out platform-supported link frequencies

**Parameters**

- `struct device *dev`: The struct device
- `const u64 *fw_link_freqs`: Array of link frequencies from firmware
- `unsigned int num_of_fw_link_freqs`: Number of entries in **fw_link_freqs**
- `const s64 *driver_link_freqs`: Array of link frequencies supported by the driver
- `unsigned int num_of_driver_link_freqs`: Number of entries in **driver_link_freqs**
- `unsigned long *bitmap`: Bitmap of driver-supported link frequencies found in **fw_link_freqs**

**Description**

This function checks which driver-supported link frequencies are enabled in
system firmware and sets the corresponding bits in **bitmap** (after first
zeroing it).

**Return**

* `0`: Success
* `-ENOENT`: No match found between driver-supported link frequencies and
  those available in firmware.
* `-ENODATA`: No link frequencies were specified in firmware.

#### <a id="c-devm_v4l2_sensor_clk_get"></a>`devm_v4l2_sensor_clk_get()`

```c
struct clk * devm_v4l2_sensor_clk_get(struct device *dev, const char *id)
```

lookup and obtain a reference to a clock producer for a camera sensor

**Parameters**

- `struct device *dev`: device for v4l2 sensor clock "consumer"
- `const char *id`: clock consumer ID

**Description**

This function behaves the same way as [`devm_clk_get()`](/kernel/internals/core-api/kernel-api.md#c-devm_clk_get) except where there
is no clock producer like in ACPI-based platforms.

For ACPI-based platforms, the function will read the "clock-frequency"
ACPI _DSD property and register a fixed-clock with the frequency indicated
in the property.

This function also handles the special ACPI-based system case where:

* The clock-frequency _DSD property is present.
* A reference to the clock producer is present, where the clock is provided
  by a camera sensor PMIC driver (e.g. int3472/tps68470.c)

In this case try to set the clock-frequency value to the provided clock.

As the name indicates, this function may only be used on camera sensor
devices. This is because generally only camera sensors do need a clock to
query the frequency from, due to the requirement to configure the PLL for a
given CSI-2 interface frequency where the sensor's external clock frequency
is a factor. Additionally, the clock frequency tends to be available on ACPI
firmware based systems for camera sensors specifically (if e.g. DisCo for
Imaging compliant).

Returns a pointer to a struct clk on success or an error pointer on failure.

#### <a id="c-devm_v4l2_sensor_clk_get_legacy"></a>`devm_v4l2_sensor_clk_get_legacy()`

```c
struct clk * devm_v4l2_sensor_clk_get_legacy(struct device *dev, const char *id, bool fixed_rate, unsigned long clk_rate)
```

lookup and obtain a reference to a clock producer for a camera sensor.

**Parameters**

- `struct device *dev`: device for v4l2 sensor clock "consumer"
- `const char *id`: clock consumer ID
- `bool fixed_rate`: interpret the **clk_rate** as a fixed rate or default rate
- `unsigned long clk_rate`: the clock rate

**Description**

This function behaves the same way as [`devm_v4l2_sensor_clk_get()`](#c-devm_v4l2_sensor_clk_get) except that
it extends the behaviour on ACPI platforms to all platforms.

The function also provides the ability to set the clock rate to a fixed
frequency by setting **fixed_rate** to true and specifying the fixed frequency
in **clk_rate**, or to use a default clock rate when the "clock-frequency"
property is absent by setting **fixed_rate** to false and specifying the default
frequency in **clk_rate**. Setting **fixed_rate** to true and **clk_rate** to 0 is an
error.

This function is meant to support legacy behaviour in existing drivers only.
It must not be used in any new driver.

Returns a pointer to a struct clk on success or an error pointer on failure.



#### <a id="c-struct-v4l2_ioctl_ops"></a>`struct v4l2_ioctl_ops`

describe operations for each V4L2 ioctl

**Definition**

```c
struct v4l2_ioctl_ops {
        int (*vidioc_querycap)(struct file *file, void *priv, struct v4l2_capability *cap);
        int (*vidioc_enum_fmt_vid_cap)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_vid_overlay)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_vid_out)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_sdr_cap)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_sdr_out)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_meta_cap)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_enum_fmt_meta_out)(struct file *file, void *priv, struct v4l2_fmtdesc *f);
        int (*vidioc_g_fmt_vid_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_out_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_sliced_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_sliced_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_cap_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_vid_out_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_sdr_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_sdr_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_meta_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_g_fmt_meta_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_out_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_sliced_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_sliced_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_cap_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_vid_out_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_sdr_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_sdr_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_meta_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_s_fmt_meta_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_out_overlay)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_sliced_vbi_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_sliced_vbi_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_cap_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_vid_out_mplane)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_sdr_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_sdr_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_meta_cap)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_try_fmt_meta_out)(struct file *file, void *priv, struct v4l2_format *f);
        int (*vidioc_reqbufs)(struct file *file, void *priv, struct v4l2_requestbuffers *b);
        int (*vidioc_querybuf)(struct file *file, void *priv, struct v4l2_buffer *b);
        int (*vidioc_qbuf)(struct file *file, void *priv, struct v4l2_buffer *b);
        int (*vidioc_expbuf)(struct file *file, void *priv, struct v4l2_exportbuffer *e);
        int (*vidioc_dqbuf)(struct file *file, void *priv, struct v4l2_buffer *b);
        int (*vidioc_create_bufs)(struct file *file, void *priv, struct v4l2_create_buffers *b);
        int (*vidioc_prepare_buf)(struct file *file, void *priv, struct v4l2_buffer *b);
        int (*vidioc_remove_bufs)(struct file *file, void *priv, struct v4l2_remove_buffers *d);
        int (*vidioc_overlay)(struct file *file, void *priv, unsigned int i);
        int (*vidioc_g_fbuf)(struct file *file, void *priv, struct v4l2_framebuffer *a);
        int (*vidioc_s_fbuf)(struct file *file, void *priv, const struct v4l2_framebuffer *a);
        int (*vidioc_streamon)(struct file *file, void *priv, enum v4l2_buf_type i);
        int (*vidioc_streamoff)(struct file *file, void *priv, enum v4l2_buf_type i);
        int (*vidioc_g_std)(struct file *file, void *priv, v4l2_std_id *norm);
        int (*vidioc_s_std)(struct file *file, void *priv, v4l2_std_id norm);
        int (*vidioc_querystd)(struct file *file, void *priv, v4l2_std_id *a);
        int (*vidioc_enum_input)(struct file *file, void *priv, struct v4l2_input *inp);
        int (*vidioc_g_input)(struct file *file, void *priv, unsigned int *i);
        int (*vidioc_s_input)(struct file *file, void *priv, unsigned int i);
        int (*vidioc_enum_output)(struct file *file, void *priv, struct v4l2_output *a);
        int (*vidioc_g_output)(struct file *file, void *priv, unsigned int *i);
        int (*vidioc_s_output)(struct file *file, void *priv, unsigned int i);
        int (*vidioc_query_ext_ctrl)(struct file *file, void *priv, struct v4l2_query_ext_ctrl *a);
        int (*vidioc_g_ext_ctrls)(struct file *file, void *priv, struct v4l2_ext_controls *a);
        int (*vidioc_s_ext_ctrls)(struct file *file, void *priv, struct v4l2_ext_controls *a);
        int (*vidioc_try_ext_ctrls)(struct file *file, void *priv, struct v4l2_ext_controls *a);
        int (*vidioc_querymenu)(struct file *file, void *priv, struct v4l2_querymenu *a);
        int (*vidioc_enumaudio)(struct file *file, void *priv, struct v4l2_audio *a);
        int (*vidioc_g_audio)(struct file *file, void *priv, struct v4l2_audio *a);
        int (*vidioc_s_audio)(struct file *file, void *priv, const struct v4l2_audio *a);
        int (*vidioc_enumaudout)(struct file *file, void *priv, struct v4l2_audioout *a);
        int (*vidioc_g_audout)(struct file *file, void *priv, struct v4l2_audioout *a);
        int (*vidioc_s_audout)(struct file *file, void *priv, const struct v4l2_audioout *a);
        int (*vidioc_g_modulator)(struct file *file, void *priv, struct v4l2_modulator *a);
        int (*vidioc_s_modulator)(struct file *file, void *priv, const struct v4l2_modulator *a);
        int (*vidioc_g_pixelaspect)(struct file *file, void *priv, int buf_type, struct v4l2_fract *aspect);
        int (*vidioc_g_selection)(struct file *file, void *priv, struct v4l2_selection *s);
        int (*vidioc_s_selection)(struct file *file, void *priv, struct v4l2_selection *s);
        int (*vidioc_g_jpegcomp)(struct file *file, void *priv, struct v4l2_jpegcompression *a);
        int (*vidioc_s_jpegcomp)(struct file *file, void *priv, const struct v4l2_jpegcompression *a);
        int (*vidioc_g_enc_index)(struct file *file, void *priv, struct v4l2_enc_idx *a);
        int (*vidioc_encoder_cmd)(struct file *file, void *priv, struct v4l2_encoder_cmd *a);
        int (*vidioc_try_encoder_cmd)(struct file *file, void *priv, struct v4l2_encoder_cmd *a);
        int (*vidioc_decoder_cmd)(struct file *file, void *priv, struct v4l2_decoder_cmd *a);
        int (*vidioc_try_decoder_cmd)(struct file *file, void *priv, struct v4l2_decoder_cmd *a);
        int (*vidioc_g_parm)(struct file *file, void *priv, struct v4l2_streamparm *a);
        int (*vidioc_s_parm)(struct file *file, void *priv, struct v4l2_streamparm *a);
        int (*vidioc_g_tuner)(struct file *file, void *priv, struct v4l2_tuner *a);
        int (*vidioc_s_tuner)(struct file *file, void *priv, const struct v4l2_tuner *a);
        int (*vidioc_g_frequency)(struct file *file, void *priv, struct v4l2_frequency *a);
        int (*vidioc_s_frequency)(struct file *file, void *priv, const struct v4l2_frequency *a);
        int (*vidioc_enum_freq_bands)(struct file *file, void *priv, struct v4l2_frequency_band *band);
        int (*vidioc_g_sliced_vbi_cap)(struct file *file, void *priv, struct v4l2_sliced_vbi_cap *a);
        int (*vidioc_log_status)(struct file *file, void *priv);
        int (*vidioc_s_hw_freq_seek)(struct file *file, void *priv, const struct v4l2_hw_freq_seek *a);
    #ifdef CONFIG_VIDEO_ADV_DEBUG;
        int (*vidioc_g_register)(struct file *file, void *priv, struct v4l2_dbg_register *reg);
        int (*vidioc_s_register)(struct file *file, void *priv, const struct v4l2_dbg_register *reg);
        int (*vidioc_g_chip_info)(struct file *file, void *priv, struct v4l2_dbg_chip_info *chip);
    #endif;
        int (*vidioc_enum_framesizes)(struct file *file, void *priv, struct v4l2_frmsizeenum *fsize);
        int (*vidioc_enum_frameintervals)(struct file *file, void *priv, struct v4l2_frmivalenum *fival);
        int (*vidioc_s_dv_timings)(struct file *file, void *priv, struct v4l2_dv_timings *timings);
        int (*vidioc_g_dv_timings)(struct file *file, void *priv, struct v4l2_dv_timings *timings);
        int (*vidioc_query_dv_timings)(struct file *file, void *priv, struct v4l2_dv_timings *timings);
        int (*vidioc_enum_dv_timings)(struct file *file, void *priv, struct v4l2_enum_dv_timings *timings);
        int (*vidioc_dv_timings_cap)(struct file *file, void *priv, struct v4l2_dv_timings_cap *cap);
        int (*vidioc_g_edid)(struct file *file, void *priv, struct v4l2_edid *edid);
        int (*vidioc_s_edid)(struct file *file, void *priv, struct v4l2_edid *edid);
        int (*vidioc_subscribe_event)(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub);
        int (*vidioc_unsubscribe_event)(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub);
        long (*vidioc_default)(struct file *file, void *priv, bool valid_prio, unsigned int cmd, void *arg);
};
```

**Members**

- `vidioc_querycap`: pointer to the function that implements
  VIDIOC_QUERYCAP ioctl
- `vidioc_enum_fmt_vid_cap`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for video capture in single and multi plane mode
- `vidioc_enum_fmt_vid_overlay`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for video overlay
- `vidioc_enum_fmt_vid_out`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for video output in single and multi plane mode
- `vidioc_enum_fmt_sdr_cap`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for Software Defined Radio capture
- `vidioc_enum_fmt_sdr_out`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for Software Defined Radio output
- `vidioc_enum_fmt_meta_cap`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for metadata capture
- `vidioc_enum_fmt_meta_out`: pointer to the function that implements
  VIDIOC_ENUM_FMT ioctl logic
  for metadata output
- `vidioc_g_fmt_vid_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video capture
  in single plane mode
- `vidioc_g_fmt_vid_overlay`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video overlay
- `vidioc_g_fmt_vid_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video out
  in single plane mode
- `vidioc_g_fmt_vid_out_overlay`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video overlay output
- `vidioc_g_fmt_vbi_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for raw VBI capture
- `vidioc_g_fmt_vbi_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for raw VBI output
- `vidioc_g_fmt_sliced_vbi_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for sliced VBI capture
- `vidioc_g_fmt_sliced_vbi_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for sliced VBI output
- `vidioc_g_fmt_vid_cap_mplane`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video capture
  in multiple plane mode
- `vidioc_g_fmt_vid_out_mplane`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for video out
  in multiplane plane mode
- `vidioc_g_fmt_sdr_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for Software Defined
  Radio capture
- `vidioc_g_fmt_sdr_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for Software Defined
  Radio output
- `vidioc_g_fmt_meta_cap`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for metadata capture
- `vidioc_g_fmt_meta_out`: pointer to the function that implements
  VIDIOC_G_FMT ioctl logic for metadata output
- `vidioc_s_fmt_vid_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video capture
  in single plane mode
- `vidioc_s_fmt_vid_overlay`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video overlay
- `vidioc_s_fmt_vid_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video out
  in single plane mode
- `vidioc_s_fmt_vid_out_overlay`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video overlay output
- `vidioc_s_fmt_vbi_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for raw VBI capture
- `vidioc_s_fmt_vbi_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for raw VBI output
- `vidioc_s_fmt_sliced_vbi_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for sliced VBI capture
- `vidioc_s_fmt_sliced_vbi_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for sliced VBI output
- `vidioc_s_fmt_vid_cap_mplane`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video capture
  in multiple plane mode
- `vidioc_s_fmt_vid_out_mplane`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for video out
  in multiplane plane mode
- `vidioc_s_fmt_sdr_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for Software Defined
  Radio capture
- `vidioc_s_fmt_sdr_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for Software Defined
  Radio output
- `vidioc_s_fmt_meta_cap`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for metadata capture
- `vidioc_s_fmt_meta_out`: pointer to the function that implements
  VIDIOC_S_FMT ioctl logic for metadata output
- `vidioc_try_fmt_vid_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video capture
  in single plane mode
- `vidioc_try_fmt_vid_overlay`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video overlay
- `vidioc_try_fmt_vid_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video out
  in single plane mode
- `vidioc_try_fmt_vid_out_overlay`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video overlay
  output
- `vidioc_try_fmt_vbi_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for raw VBI capture
- `vidioc_try_fmt_vbi_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for raw VBI output
- `vidioc_try_fmt_sliced_vbi_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for sliced VBI
  capture
- `vidioc_try_fmt_sliced_vbi_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for sliced VBI output
- `vidioc_try_fmt_vid_cap_mplane`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video capture
  in multiple plane mode
- `vidioc_try_fmt_vid_out_mplane`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for video out
  in multiplane plane mode
- `vidioc_try_fmt_sdr_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for Software Defined
  Radio capture
- `vidioc_try_fmt_sdr_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for Software Defined
  Radio output
- `vidioc_try_fmt_meta_cap`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for metadata capture
- `vidioc_try_fmt_meta_out`: pointer to the function that implements
  VIDIOC_TRY_FMT ioctl logic for metadata output
- `vidioc_reqbufs`: pointer to the function that implements
  VIDIOC_REQBUFS ioctl
- `vidioc_querybuf`: pointer to the function that implements
  VIDIOC_QUERYBUF ioctl
- `vidioc_qbuf`: pointer to the function that implements
  VIDIOC_QBUF ioctl
- `vidioc_expbuf`: pointer to the function that implements
  VIDIOC_EXPBUF ioctl
- `vidioc_dqbuf`: pointer to the function that implements
  VIDIOC_DQBUF ioctl
- `vidioc_create_bufs`: pointer to the function that implements
  VIDIOC_CREATE_BUFS ioctl
- `vidioc_prepare_buf`: pointer to the function that implements
  VIDIOC_PREPARE_BUF ioctl
- `vidioc_remove_bufs`: pointer to the function that implements
  VIDIOC_REMOVE_BUFS ioctl
- `vidioc_overlay`: pointer to the function that implements
  VIDIOC_OVERLAY ioctl
- `vidioc_g_fbuf`: pointer to the function that implements
  VIDIOC_G_FBUF ioctl
- `vidioc_s_fbuf`: pointer to the function that implements
  VIDIOC_S_FBUF ioctl
- `vidioc_streamon`: pointer to the function that implements
  VIDIOC_STREAMON ioctl
- `vidioc_streamoff`: pointer to the function that implements
  VIDIOC_STREAMOFF ioctl
- `vidioc_g_std`: pointer to the function that implements
  VIDIOC_G_STD ioctl
- `vidioc_s_std`: pointer to the function that implements
  VIDIOC_S_STD ioctl
- `vidioc_querystd`: pointer to the function that implements
  VIDIOC_QUERYSTD ioctl
- `vidioc_enum_input`: pointer to the function that implements
  VIDIOC_ENUM_INPUT ioctl
- `vidioc_g_input`: pointer to the function that implements
  VIDIOC_G_INPUT ioctl
- `vidioc_s_input`: pointer to the function that implements
  VIDIOC_S_INPUT ioctl
- `vidioc_enum_output`: pointer to the function that implements
  VIDIOC_ENUM_OUTPUT ioctl
- `vidioc_g_output`: pointer to the function that implements
  VIDIOC_G_OUTPUT ioctl
- `vidioc_s_output`: pointer to the function that implements
  VIDIOC_S_OUTPUT ioctl
- `vidioc_query_ext_ctrl`: pointer to the function that implements
  VIDIOC_QUERY_EXT_CTRL ioctl
- `vidioc_g_ext_ctrls`: pointer to the function that implements
  VIDIOC_G_EXT_CTRLS ioctl
- `vidioc_s_ext_ctrls`: pointer to the function that implements
  VIDIOC_S_EXT_CTRLS ioctl
- `vidioc_try_ext_ctrls`: pointer to the function that implements
  VIDIOC_TRY_EXT_CTRLS ioctl
- `vidioc_querymenu`: pointer to the function that implements
  VIDIOC_QUERYMENU ioctl
- `vidioc_enumaudio`: pointer to the function that implements
  VIDIOC_ENUMAUDIO ioctl
- `vidioc_g_audio`: pointer to the function that implements
  VIDIOC_G_AUDIO ioctl
- `vidioc_s_audio`: pointer to the function that implements
  VIDIOC_S_AUDIO ioctl
- `vidioc_enumaudout`: pointer to the function that implements
  VIDIOC_ENUMAUDOUT ioctl
- `vidioc_g_audout`: pointer to the function that implements
  VIDIOC_G_AUDOUT ioctl
- `vidioc_s_audout`: pointer to the function that implements
  VIDIOC_S_AUDOUT ioctl
- `vidioc_g_modulator`: pointer to the function that implements
  VIDIOC_G_MODULATOR ioctl
- `vidioc_s_modulator`: pointer to the function that implements
  VIDIOC_S_MODULATOR ioctl
- `vidioc_g_pixelaspect`: pointer to the function that implements
  the pixelaspect part of the VIDIOC_CROPCAP ioctl
- `vidioc_g_selection`: pointer to the function that implements
  VIDIOC_G_SELECTION ioctl
- `vidioc_s_selection`: pointer to the function that implements
  VIDIOC_S_SELECTION ioctl
- `vidioc_g_jpegcomp`: pointer to the function that implements
  VIDIOC_G_JPEGCOMP ioctl
- `vidioc_s_jpegcomp`: pointer to the function that implements
  VIDIOC_S_JPEGCOMP ioctl
- `vidioc_g_enc_index`: pointer to the function that implements
  VIDIOC_G_ENC_INDEX ioctl
- `vidioc_encoder_cmd`: pointer to the function that implements
  VIDIOC_ENCODER_CMD ioctl
- `vidioc_try_encoder_cmd`: pointer to the function that implements
  VIDIOC_TRY_ENCODER_CMD ioctl
- `vidioc_decoder_cmd`: pointer to the function that implements
  VIDIOC_DECODER_CMD ioctl
- `vidioc_try_decoder_cmd`: pointer to the function that implements
  VIDIOC_TRY_DECODER_CMD ioctl
- `vidioc_g_parm`: pointer to the function that implements
  VIDIOC_G_PARM ioctl
- `vidioc_s_parm`: pointer to the function that implements
  VIDIOC_S_PARM ioctl
- `vidioc_g_tuner`: pointer to the function that implements
  VIDIOC_G_TUNER ioctl
- `vidioc_s_tuner`: pointer to the function that implements
  VIDIOC_S_TUNER ioctl
- `vidioc_g_frequency`: pointer to the function that implements
  VIDIOC_G_FREQUENCY ioctl
- `vidioc_s_frequency`: pointer to the function that implements
  VIDIOC_S_FREQUENCY ioctl
- `vidioc_enum_freq_bands`: pointer to the function that implements
  VIDIOC_ENUM_FREQ_BANDS ioctl
- `vidioc_g_sliced_vbi_cap`: pointer to the function that implements
  VIDIOC_G_SLICED_VBI_CAP ioctl
- `vidioc_log_status`: pointer to the function that implements
  VIDIOC_LOG_STATUS ioctl
- `vidioc_s_hw_freq_seek`: pointer to the function that implements
  VIDIOC_S_HW_FREQ_SEEK ioctl
- `vidioc_g_register`: pointer to the function that implements
  VIDIOC_DBG_G_REGISTER ioctl
- `vidioc_s_register`: pointer to the function that implements
  VIDIOC_DBG_S_REGISTER ioctl
- `vidioc_g_chip_info`: pointer to the function that implements
  VIDIOC_DBG_G_CHIP_INFO ioctl
- `vidioc_enum_framesizes`: pointer to the function that implements
  VIDIOC_ENUM_FRAMESIZES ioctl
- `vidioc_enum_frameintervals`: pointer to the function that implements
  VIDIOC_ENUM_FRAMEINTERVALS ioctl
- `vidioc_s_dv_timings`: pointer to the function that implements
  VIDIOC_S_DV_TIMINGS ioctl
- `vidioc_g_dv_timings`: pointer to the function that implements
  VIDIOC_G_DV_TIMINGS ioctl
- `vidioc_query_dv_timings`: pointer to the function that implements
  VIDIOC_QUERY_DV_TIMINGS ioctl
- `vidioc_enum_dv_timings`: pointer to the function that implements
  VIDIOC_ENUM_DV_TIMINGS ioctl
- `vidioc_dv_timings_cap`: pointer to the function that implements
  VIDIOC_DV_TIMINGS_CAP ioctl
- `vidioc_g_edid`: pointer to the function that implements
  VIDIOC_G_EDID ioctl
- `vidioc_s_edid`: pointer to the function that implements
  VIDIOC_S_EDID ioctl
- `vidioc_subscribe_event`: pointer to the function that implements
  VIDIOC_SUBSCRIBE_EVENT ioctl
- `vidioc_unsubscribe_event`: pointer to the function that implements
  VIDIOC_UNSUBSCRIBE_EVENT ioctl
- `vidioc_default`: pointed used to allow other ioctls

#### <a id="c-v4l2_norm_to_name"></a>`v4l2_norm_to_name()`

```c
const char * v4l2_norm_to_name(v4l2_std_id id)
```

Ancillary routine to analog TV standard name from its ID.

**Parameters**

- `v4l2_std_id id`: analog TV standard ID.

**Return**

returns a string with the name of the analog TV standard.
If the standard is not found or if **id** points to multiple standard,
it returns "Unknown".

#### <a id="c-v4l2_video_std_frame_period"></a>`v4l2_video_std_frame_period()`

```c
void v4l2_video_std_frame_period(int id, struct v4l2_fract *frameperiod)
```

Ancillary routine that fills a struct `v4l2_fract` pointer with the default framerate fraction.

**Parameters**

- `int id`: analog TV standard ID.
- `struct v4l2_fract *frameperiod`: struct `v4l2_fract` pointer to be filled

#### <a id="c-v4l2_video_std_construct"></a>`v4l2_video_std_construct()`

```c
int v4l2_video_std_construct(struct v4l2_standard *vs, int id, const char *name)
```

Ancillary routine that fills in the fields of a `v4l2_standard` structure according to the **id** parameter.

**Parameters**

- `struct v4l2_standard *vs`: struct `v4l2_standard` pointer to be filled
- `int id`: analog TV standard ID.
- `const char *name`: name of the standard to be used

**Description**

> [!NOTE]
> This ancillary routine is obsolete. Shouldn't be used on newer drivers.

#### <a id="c-v4l_video_std_enumstd"></a>`v4l_video_std_enumstd()`

```c
int v4l_video_std_enumstd(struct v4l2_standard *vs, v4l2_std_id id)
```

Ancillary routine that fills in the fields of a `v4l2_standard` structure according to the **id** and **vs->index** parameters.

**Parameters**

- `struct v4l2_standard *vs`: struct `v4l2_standard` pointer to be filled.
- `v4l2_std_id id`: analog TV standard ID.

#### <a id="c-v4l_printk_ioctl"></a>`v4l_printk_ioctl()`

```c
void v4l_printk_ioctl(const char *prefix, unsigned int cmd)
```

Ancillary routine that prints the ioctl in a human-readable format.

**Parameters**

- `const char *prefix`: prefix to be added at the ioctl prints.
- `unsigned int cmd`: ioctl name

**Description**

> [!NOTE]
> If prefix != `NULL`, then it will issue a
> `printk(KERN_DEBUG "%s: ", prefix)` first.

#### <a id="c-v4l2_field_names"></a>`v4l2_field_names`

```c
extern const char *v4l2_field_names[];
```

Helper array mapping `V4L2_FIELD_*` to strings.

**Initialization**

default: `v4l2_field_names`

**Description**

Specially when printing debug messages, it is interesting to output
the field order at the V4L2 buffers. This array associates all possible
values of field pix format from V4L2 API into a string.

#### <a id="c-v4l2_type_names"></a>`v4l2_type_names`

```c
extern const char *v4l2_type_names[];
```

Helper array mapping `V4L2_BUF_TYPE_*` to strings.

**Initialization**

default: `v4l2_type_names`

**Description**

When printing debug messages, it is interesting to output the V4L2 buffer
type number with a name that represents its content.

#### <a id="c-v4l2_compat_ioctl32"></a>`v4l2_compat_ioctl32()`

```c
long int v4l2_compat_ioctl32(struct file *file, unsigned int cmd, unsigned long arg)
```

32 Bits compatibility layer for 64 bits processors

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long arg`: Ioctl argument.

#### <a id="c-v4l2_kioctl"></a>`v4l2_kioctl()`

```c
typedef long v4l2_kioctl(struct file *file, unsigned int cmd, void *arg)
```

Typedef used to pass an ioctl handler.

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `void *arg`: Ioctl argument.

#### <a id="c-video_usercopy"></a>`video_usercopy()`

```c
long int video_usercopy(struct file *file, unsigned int cmd, unsigned long int arg, v4l2_kioctl func)
```

copies data from/to userspace memory when an ioctl is issued.

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long int arg`: Ioctl argument.
- `v4l2_kioctl func`: function that will handle the ioctl

**Description**

> [!NOTE]
> This routine should be used only inside the V4L2 core.

#### <a id="c-video_ioctl2"></a>`video_ioctl2()`

```c
long int video_ioctl2(struct file *file, unsigned int cmd, unsigned long int arg)
```

Handles a V4L2 ioctl.

**Parameters**

- `struct file *file`: Pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file).
- `unsigned int cmd`: Ioctl name.
- `unsigned long int arg`: Ioctl argument.

**Description**

Method used to hancle an ioctl. Should be used to fill the
[`v4l2_ioctl_ops.unlocked_ioctl`](#c-struct-v4l2_ioctl_ops) on all V4L2 drivers.

---

# V4L2 Controls

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The V4L2 control API seems simple enough, but quickly becomes very hard to implement correctly in drivers. But much of the code needed to handle controls is actually not driver specific and can be moved to the V4L core framework.

<a id="rst-v4l2-controls"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The V4L2 control API seems simple enough, but quickly becomes very hard to implement correctly in drivers. But much of the code needed to handle controls is actually not driver specific and can be moved to the V4L core framework.

After all, the only part that a driver developer is interested in is:

1. How do I add a control?

2. How do I set the control's value? (i.e. s_ctrl)

And occasionally:

3. How do I get the control's value? (i.e. g_volatile_ctrl)

4. How do I validate the user's proposed control value? (i.e. try_ctrl)

All the rest is something that can be done centrally.

The control framework was created in order to implement all the rules of the V4L2 specification with respect to controls in a central place. And to make life as easy as possible for the driver developer.

Note that the control framework relies on the presence of a struct `v4l2_device` for V4L2 drivers and struct v4l2_subdev for sub-device drivers.

<a id="rst-objects-in-the-framework"></a>

## Objects in the framework

There are two main objects:

The `v4l2_ctrl` object describes the control properties and keeps track of the control's value (both the current value and the proposed new value).

`v4l2_ctrl_handler` is the object that keeps track of controls. It maintains a list of v4l2_ctrl objects that it owns and another list of references to controls, possibly to controls owned by other handlers.

<a id="rst-basic-usage-for-v4l2-and-sub-device-drivers"></a>

## Basic usage for V4L2 and sub-device drivers

1. Prepare the driver:



```c
#include <media/v4l2-ctrls.h>
```

1.1) Add the handler to your driver's top-level struct:

For V4L2 drivers:



```c
struct foo_dev {
        ...
        struct v4l2_device v4l2_dev;
        ...
        struct v4l2_ctrl_handler ctrl_handler;
        ...
};
```

For sub-device drivers:



```c
struct foo_dev {
        ...
        struct v4l2_subdev sd;
        ...
        struct v4l2_ctrl_handler ctrl_handler;
        ...
};
```

1.2) Initialize the handler:



```c
v4l2_ctrl_handler_init(&foo->ctrl_handler, nr_of_controls);
```

The second argument is a hint telling the function how many controls this handler is expected to handle. It will allocate a hashtable based on this information. It is a hint only.

1.3) Hook the control handler into the driver:

For V4L2 drivers:



```c
foo->v4l2_dev.ctrl_handler = &foo->ctrl_handler;
```

For sub-device drivers:



```c
foo->sd.ctrl_handler = &foo->ctrl_handler;
```

1.4) Clean up the handler at the end:



```c
v4l2_ctrl_handler_free(&foo->ctrl_handler);
```

`v4l2_ctrl_handler_free()` does not touch the handler's `error` field.

2. Add controls:

You add non-menu controls by calling `v4l2_ctrl_new_std()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_std(struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops,
                u32 id, s32 min, s32 max, u32 step, s32 def);
```

Menu and integer menu controls are added by calling `v4l2_ctrl_new_std_menu()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_std_menu(struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops,
                u32 id, s32 max, s32 skip_mask, s32 def);
```

Menu controls with a driver specific menu are added by calling `v4l2_ctrl_new_std_menu_items()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_std_menu_items(
                struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops, u32 id, s32 max,
                s32 skip_mask, s32 def, const char * const *qmenu);
```

Standard compound controls can be added by calling `v4l2_ctrl_new_std_compound()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_std_compound(struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops, u32 id,
                const union v4l2_ctrl_ptr p_def);
```

Integer menu controls with a driver specific menu can be added by calling `v4l2_ctrl_new_int_menu()`:



```c
struct v4l2_ctrl *v4l2_ctrl_new_int_menu(struct v4l2_ctrl_handler *hdl,
                const struct v4l2_ctrl_ops *ops,
                u32 id, s32 max, s32 def, const s64 *qmenu_int);
```

These functions are typically called right after the `v4l2_ctrl_handler_init()`:



```c
static const s64 exp_bias_qmenu[] = {
       -2, -1, 0, 1, 2
};
static const char * const test_pattern[] = {
        "Disabled",
        "Vertical Bars",
        "Solid Black",
        "Solid White",
};

v4l2_ctrl_handler_init(&foo->ctrl_handler, nr_of_controls);
v4l2_ctrl_new_std(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_BRIGHTNESS, 0, 255, 1, 128);
v4l2_ctrl_new_std(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_CONTRAST, 0, 255, 1, 128);
v4l2_ctrl_new_std_menu(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_POWER_LINE_FREQUENCY,
                V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 0,
                V4L2_CID_POWER_LINE_FREQUENCY_DISABLED);
v4l2_ctrl_new_int_menu(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_EXPOSURE_BIAS,
                ARRAY_SIZE(exp_bias_qmenu) - 1,
                ARRAY_SIZE(exp_bias_qmenu) / 2 - 1,
                exp_bias_qmenu);
v4l2_ctrl_new_std_menu_items(&foo->ctrl_handler, &foo_ctrl_ops,
                V4L2_CID_TEST_PATTERN, ARRAY_SIZE(test_pattern) - 1, 0,
                0, test_pattern);
...
if (foo->ctrl_handler.error)
        return v4l2_ctrl_handler_free(&foo->ctrl_handler);
```

The `v4l2_ctrl_new_std()` function returns the v4l2_ctrl pointer to the new control, but if you do not need to access the pointer outside the control ops, then there is no need to store it.

The `v4l2_ctrl_new_std()` function will fill in most fields based on the control ID except for the min, max, step and default values. These are passed in the last four arguments. These values are driver specific while control attributes like type, name, flags are all global. The control's current value will be set to the default value.

The `v4l2_ctrl_new_std_menu()` function is very similar but it is used for menu controls. There is no min argument since that is always 0 for menu controls, and instead of a step there is a skip_mask argument: if bit X is 1, then menu item X is skipped.

The `v4l2_ctrl_new_int_menu()` function creates a new standard integer menu control with driver-specific items in the menu. It differs from v4l2_ctrl_new_std_menu in that it doesn't have the mask argument and takes as the last argument an array of signed 64-bit integers that form an exact menu item list.

The `v4l2_ctrl_new_std_menu_items()` function is very similar to v4l2_ctrl_new_std_menu but takes an extra parameter qmenu, which is the driver specific menu for an otherwise standard menu control. A good example for this control is the test pattern control for capture/display/sensors devices that have the capability to generate test patterns. These test patterns are hardware specific, so the contents of the menu will vary from device to device.

Note that if something fails, the function will return NULL or an error and set ctrl_handler-&gt;error to the error code. If ctrl_handler-&gt;error was already set, then it will just return and do nothing. This is also true for v4l2_ctrl_handler_init if it cannot allocate the internal data structure.

This makes it easy to init the handler and just add all controls and only check the error code at the end. Saves a lot of repetitive error checking.

It is recommended to add controls in ascending control ID order: it will be a bit faster that way.

3. Optionally force initial control setup:



```c
v4l2_ctrl_handler_setup(&foo->ctrl_handler);
```

This will call s_ctrl for all controls unconditionally. Effectively this initializes the hardware to the default control values. It is recommended that you do this as this ensures that both the internal data structures and the hardware are in sync.

4. Finally: implement the `v4l2_ctrl_ops`



```c
static const struct v4l2_ctrl_ops foo_ctrl_ops = {
        .s_ctrl = foo_s_ctrl,
};
```

Usually all you need is s_ctrl:



```c
static int foo_s_ctrl(struct v4l2_ctrl *ctrl)
{
        struct foo *state = container_of(ctrl->handler, struct foo, ctrl_handler);

        switch (ctrl->id) {
        case V4L2_CID_BRIGHTNESS:
                write_reg(0x123, ctrl->val);
                break;
        case V4L2_CID_CONTRAST:
                write_reg(0x456, ctrl->val);
                break;
        }
        return 0;
}
```

The control ops are called with the v4l2_ctrl pointer as argument. The new control value has already been validated, so all you need to do is to actually update the hardware registers.

You're done\! And this is sufficient for most of the drivers we have. No need to do any validation of control values, or implement QUERYCTRL, QUERY_EXT_CTRL and QUERYMENU. And G/S_CTRL as well as G/TRY/S_EXT_CTRLS are automatically supported.

> [!NOTE]
>
> The remainder sections deal with more advanced controls topics and scenarios. In practice the basic usage as described above is sufficient for most drivers.

<a id="rst-inheriting-sub-device-controls"></a>

## Inheriting Sub-device Controls

When a sub-device is registered with a V4L2 driver by calling v4l2_device_register_subdev() and the ctrl_handler fields of both v4l2_subdev and v4l2_device are set, then the controls of the subdev will become automatically available in the V4L2 driver as well. If the subdev driver contains controls that already exist in the V4L2 driver, then those will be skipped (so a V4L2 driver can always override a subdev control).

What happens here is that v4l2_device_register_subdev() calls v4l2_ctrl_add_handler() adding the controls of the subdev to the controls of v4l2_device.

<a id="rst-accessing-control-values"></a>

## Accessing Control Values

The following union is used inside the control framework to access control values:



```c
union v4l2_ctrl_ptr {
        s32 *p_s32;
        s64 *p_s64;
        char *p_char;
        void *p;
};
```

The v4l2_ctrl struct contains these fields that can be used to access both current and new values:



```c
s32 val;
struct {
        s32 val;
} cur;


union v4l2_ctrl_ptr p_new;
union v4l2_ctrl_ptr p_cur;
```

If the control has a simple s32 type, then:



```c
&ctrl->val == ctrl->p_new.p_s32
&ctrl->cur.val == ctrl->p_cur.p_s32
```

For all other types use ctrl-&gt;p_cur.p&lt;something&gt;. Basically the val and cur.val fields can be considered an alias since these are used so often.

Within the control ops you can freely use these. The val and cur.val speak for themselves. The p_char pointers point to character buffers of length ctrl-&gt;maximum + 1, and are always 0-terminated.

Unless the control is marked volatile the p_cur field points to the current cached control value. When you create a new control this value is made identical to the default value. After calling v4l2_ctrl_handler_setup() this value is passed to the hardware. It is generally a good idea to call this function.

Whenever a new value is set that new value is automatically cached. This means that most drivers do not need to implement the g_volatile_ctrl() op. The exception is for controls that return a volatile register such as a signal strength read-out that changes continuously. In that case you will need to implement g_volatile_ctrl like this:



```c
static int foo_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
{
        switch (ctrl->id) {
        case V4L2_CID_BRIGHTNESS:
                ctrl->val = read_reg(0x123);
                break;
        }
}
```

Note that you use the 'new value' union as well in g_volatile_ctrl. In general controls that need to implement g_volatile_ctrl are read-only controls. If they are not, a V4L2_EVENT_CTRL_CH_VALUE will not be generated when the control changes.

To mark a control as volatile you have to set V4L2_CTRL_FLAG_VOLATILE:



```c
ctrl = v4l2_ctrl_new_std(&sd->ctrl_handler, ...);
if (ctrl)
        ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE;
```

For try/s_ctrl the new values (i.e. as passed by the user) are filled in and you can modify them in try_ctrl or set them in s_ctrl. The 'cur' union contains the current value, which you can use (but not change\!) as well.

If s_ctrl returns 0 (OK), then the control framework will copy the new final values to the 'cur' union.

While in g_volatile/s/try_ctrl you can access the value of all controls owned by the same handler since the handler's lock is held. If you need to access the value of controls owned by other handlers, then you have to be very careful not to introduce deadlocks.

Outside of the control ops you have to go through to helper functions to get or set a single control value safely in your driver:



```c
s32 v4l2_ctrl_g_ctrl(struct v4l2_ctrl *ctrl);
int v4l2_ctrl_s_ctrl(struct v4l2_ctrl *ctrl, s32 val);
```

These functions go through the control framework just as VIDIOC_G/S_CTRL ioctls do. Don't use these inside the control ops g_volatile/s/try_ctrl, though, that will result in a deadlock since these helpers lock the handler as well.

You can also take the handler lock yourself:



```c
mutex_lock(&state->ctrl_handler.lock);
pr_info("String value is '%s'\n", ctrl1->p_cur.p_char);
pr_info("Integer value is '%s'\n", ctrl2->cur.val);
mutex_unlock(&state->ctrl_handler.lock);
```

<a id="rst-menu-controls"></a>

## Menu Controls

The v4l2_ctrl struct contains this union:



```c
union {
        u32 step;
        u32 menu_skip_mask;
};
```

For menu controls menu_skip_mask is used. What it does is that it allows you to easily exclude certain menu items. This is used in the VIDIOC_QUERYMENU implementation where you can return -EINVAL if a certain menu item is not present. Note that VIDIOC_QUERYCTRL always returns a step value of 1 for menu controls.

A good example is the MPEG Audio Layer II Bitrate menu control where the menu is a list of standardized possible bitrates. But in practice hardware implementations will only support a subset of those. By setting the skip mask you can tell the framework which menu items should be skipped. Setting it to 0 means that all menu items are supported.

You set this mask either through the v4l2_ctrl_config struct for a custom control, or by calling v4l2_ctrl_new_std_menu().

<a id="rst-custom-controls"></a>

## Custom Controls

Driver specific controls can be created using v4l2_ctrl_new_custom():



```c
static const struct v4l2_ctrl_config ctrl_filter = {
        .ops = &ctrl_custom_ops,
        .id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER,
        .name = "Spatial Filter",
        .type = V4L2_CTRL_TYPE_INTEGER,
        .flags = V4L2_CTRL_FLAG_SLIDER,
        .max = 15,
        .step = 1,
};

ctrl = v4l2_ctrl_new_custom(&foo->ctrl_handler, &ctrl_filter, NULL);
```

The last argument is the priv pointer which can be set to driver-specific private data.

The v4l2_ctrl_config struct also has a field to set the is_private flag.

If the name field is not set, then the framework will assume this is a standard control and will fill in the name, type and flags fields accordingly.

<a id="rst-active-and-grabbed-controls"></a>

## Active and Grabbed Controls

If you get more complex relationships between controls, then you may have to activate and deactivate controls. For example, if the Chroma AGC control is on, then the Chroma Gain control is inactive. That is, you may set it, but the value will not be used by the hardware as long as the automatic gain control is on. Typically user interfaces can disable such input fields.

You can set the 'active' status using v4l2_ctrl_activate(). By default all controls are active. Note that the framework does not check for this flag. It is meant purely for GUIs. The function is typically called from within s_ctrl.

The other flag is the 'grabbed' flag. A grabbed control means that you cannot change it because it is in use by some resource. Typical examples are MPEG bitrate controls that cannot be changed while capturing is in progress.

If a control is set to 'grabbed' using v4l2_ctrl_grab(), then the framework will return -EBUSY if an attempt is made to set this control. The v4l2_ctrl_grab() function is typically called from the driver when it starts or stops streaming.

<a id="rst-control-clusters"></a>

## Control Clusters

By default all controls are independent from the others. But in more complex scenarios you can get dependencies from one control to another. In that case you need to 'cluster' them:



```c
struct foo {
        struct v4l2_ctrl_handler ctrl_handler;
#define AUDIO_CL_VOLUME (0)
#define AUDIO_CL_MUTE   (1)
        struct v4l2_ctrl *audio_cluster[2];
        ...
};

state->audio_cluster[AUDIO_CL_VOLUME] =
        v4l2_ctrl_new_std(&state->ctrl_handler, ...);
state->audio_cluster[AUDIO_CL_MUTE] =
        v4l2_ctrl_new_std(&state->ctrl_handler, ...);
v4l2_ctrl_cluster(ARRAY_SIZE(state->audio_cluster), state->audio_cluster);
```

From now on whenever one or more of the controls belonging to the same cluster is set (or 'gotten', or 'tried'), only the control ops of the first control ('volume' in this example) is called. You effectively create a new composite control. Similar to how a 'struct' works in C.

So when s_ctrl is called with V4L2_CID_AUDIO_VOLUME as argument, you should set all two controls belonging to the audio_cluster:



```c
static int foo_s_ctrl(struct v4l2_ctrl *ctrl)
{
        struct foo *state = container_of(ctrl->handler, struct foo, ctrl_handler);

        switch (ctrl->id) {
        case V4L2_CID_AUDIO_VOLUME: {
                struct v4l2_ctrl *mute = ctrl->cluster[AUDIO_CL_MUTE];

                write_reg(0x123, mute->val ? 0 : ctrl->val);
                break;
        }
        case V4L2_CID_CONTRAST:
                write_reg(0x456, ctrl->val);
                break;
        }
        return 0;
}
```

In the example above the following are equivalent for the VOLUME case:



```c
ctrl == ctrl->cluster[AUDIO_CL_VOLUME] == state->audio_cluster[AUDIO_CL_VOLUME]
ctrl->cluster[AUDIO_CL_MUTE] == state->audio_cluster[AUDIO_CL_MUTE]
```

In practice using cluster arrays like this becomes very tiresome. So instead the following equivalent method is used:



```c
struct {
        /* audio cluster */
        struct v4l2_ctrl *volume;
        struct v4l2_ctrl *mute;
};
```

The anonymous struct is used to clearly 'cluster' these two control pointers, but it serves no other purpose. The effect is the same as creating an array with two control pointers. So you can just do:



```c
state->volume = v4l2_ctrl_new_std(&state->ctrl_handler, ...);
state->mute = v4l2_ctrl_new_std(&state->ctrl_handler, ...);
v4l2_ctrl_cluster(2, &state->volume);
```

And in foo_s_ctrl you can use these pointers directly: state-&gt;mute-&gt;val.

Note that controls in a cluster may be NULL. For example, if for some reason mute was never added (because the hardware doesn't support that particular feature), then mute will be NULL. So in that case we have a cluster of 2 controls, of which only 1 is actually instantiated. The only restriction is that the first control of the cluster must always be present, since that is the 'master' control of the cluster. The master control is the one that identifies the cluster and that provides the pointer to the v4l2_ctrl_ops struct that is used for that cluster.

Obviously, all controls in the cluster array must be initialized to either a valid control or to NULL.

In rare cases you might want to know which controls of a cluster actually were set explicitly by the user. For this you can check the 'is_new' flag of each control. For example, in the case of a volume/mute cluster the 'is_new' flag of the mute control would be set if the user called VIDIOC_S_CTRL for mute only. If the user would call VIDIOC_S_EXT_CTRLS for both mute and volume controls, then the 'is_new' flag would be 1 for both controls.

The 'is_new' flag is always 1 when called from v4l2_ctrl_handler_setup().

<a id="rst-handling-autogain-gain-type-controls-with-auto-clusters"></a>

## Handling autogain/gain-type Controls with Auto Clusters

A common type of control cluster is one that handles 'auto-foo/foo'-type controls. Typical examples are autogain/gain, autoexposure/exposure, autowhitebalance/red balance/blue balance. In all cases you have one control that determines whether another control is handled automatically by the hardware, or whether it is under manual control from the user.

If the cluster is in automatic mode, then the manual controls should be marked inactive and volatile. When the volatile controls are read the g_volatile_ctrl operation should return the value that the hardware's automatic mode set up automatically.

If the cluster is put in manual mode, then the manual controls should become active again and the volatile flag is cleared (so g_volatile_ctrl is no longer called while in manual mode). In addition just before switching to manual mode the current values as determined by the auto mode are copied as the new manual values.

Finally the V4L2_CTRL_FLAG_UPDATE should be set for the auto control since changing that control affects the control flags of the manual controls.

In order to simplify this a special variation of v4l2_ctrl_cluster was introduced:



```c
void v4l2_ctrl_auto_cluster(unsigned ncontrols, struct v4l2_ctrl **controls,
                            u8 manual_val, bool set_volatile);
```

The first two arguments are identical to v4l2_ctrl_cluster. The third argument tells the framework which value switches the cluster into manual mode. The last argument will optionally set V4L2_CTRL_FLAG_VOLATILE for the non-auto controls. If it is false, then the manual controls are never volatile. You would typically use that if the hardware does not give you the option to read back to values as determined by the auto mode (e.g. if autogain is on, the hardware doesn't allow you to obtain the current gain value).

The first control of the cluster is assumed to be the 'auto' control.

Using this function will ensure that you don't need to handle all the complex flag and volatile handling.

<a id="rst-vidioc-log-status-support"></a>

## VIDIOC_LOG_STATUS Support

This ioctl allow you to dump the current status of a driver to the kernel log. The v4l2_ctrl_handler_log_status(ctrl_handler, prefix) can be used to dump the value of the controls owned by the given handler to the log. You can supply a prefix as well. If the prefix didn't end with a space, then ': ' will be added for you.

<a id="rst-different-handlers-for-different-video-nodes"></a>

## Different Handlers for Different Video Nodes

Usually the V4L2 driver has just one control handler that is global for all video nodes. But you can also specify different control handlers for different video nodes. You can do that by manually setting the ctrl_handler field of struct video_device.

That is no problem if there are no subdevs involved but if there are, then you need to block the automatic merging of subdev controls to the global control handler. You do that by simply setting the ctrl_handler field in struct v4l2_device to NULL. Now v4l2_device_register_subdev() will no longer merge subdev controls.

After each subdev was added, you will then have to call v4l2_ctrl_add_handler manually to add the subdev's control handler (sd-&gt;ctrl_handler) to the desired control handler. This control handler may be specific to the video_device or for a subset of video_device's. For example: the radio device nodes only have audio controls, while the video and vbi device nodes share the same control handler for the audio and video controls.

If you want to have one handler (e.g. for a radio device node) have a subset of another handler (e.g. for a video device node), then you should first add the controls to the first handler, add the other controls to the second handler and finally add the first handler to the second. For example:



```c
v4l2_ctrl_new_std(&radio_ctrl_handler, &radio_ops, V4L2_CID_AUDIO_VOLUME, ...);
v4l2_ctrl_new_std(&radio_ctrl_handler, &radio_ops, V4L2_CID_AUDIO_MUTE, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &video_ops, V4L2_CID_BRIGHTNESS, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &video_ops, V4L2_CID_CONTRAST, ...);
v4l2_ctrl_add_handler(&video_ctrl_handler, &radio_ctrl_handler, NULL);
```

The last argument to v4l2_ctrl_add_handler() is a filter function that allows you to filter which controls will be added. Set it to NULL if you want to add all controls.

Or you can add specific controls to a handler:



```c
volume = v4l2_ctrl_new_std(&video_ctrl_handler, &ops, V4L2_CID_AUDIO_VOLUME, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &ops, V4L2_CID_BRIGHTNESS, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &ops, V4L2_CID_CONTRAST, ...);
```

What you should not do is make two identical controls for two handlers. For example:



```c
v4l2_ctrl_new_std(&radio_ctrl_handler, &radio_ops, V4L2_CID_AUDIO_MUTE, ...);
v4l2_ctrl_new_std(&video_ctrl_handler, &video_ops, V4L2_CID_AUDIO_MUTE, ...);
```

This would be bad since muting the radio would not change the video mute control. The rule is to have one control for each hardware 'knob' that you can twiddle.

<a id="rst-finding-controls"></a>

## Finding Controls

Normally you have created the controls yourself and you can store the struct v4l2_ctrl pointer into your own struct.

But sometimes you need to find a control from another handler that you do not own. For example, if you have to find a volume control from a subdev.

You can do that by calling v4l2_ctrl_find:



```c
struct v4l2_ctrl *volume;

volume = v4l2_ctrl_find(sd->ctrl_handler, V4L2_CID_AUDIO_VOLUME);
```

Since v4l2_ctrl_find will lock the handler you have to be careful where you use it. For example, this is not a good idea:



```c
struct v4l2_ctrl_handler ctrl_handler;

v4l2_ctrl_new_std(&ctrl_handler, &video_ops, V4L2_CID_BRIGHTNESS, ...);
v4l2_ctrl_new_std(&ctrl_handler, &video_ops, V4L2_CID_CONTRAST, ...);
```

...and in video_ops.s_ctrl:



```c
case V4L2_CID_BRIGHTNESS:
        contrast = v4l2_find_ctrl(&ctrl_handler, V4L2_CID_CONTRAST);
        ...
```

When s_ctrl is called by the framework the ctrl_handler.lock is already taken, so attempting to find another control from the same handler will deadlock.

It is recommended not to use this function from inside the control ops.

<a id="rst-preventing-controls-inheritance"></a>

## Preventing Controls inheritance

When one control handler is added to another using v4l2_ctrl_add_handler, then by default all controls from one are merged to the other. But a subdev might have low-level controls that make sense for some advanced embedded system, but not when it is used in consumer-level hardware. In that case you want to keep those low-level controls local to the subdev. You can do this by simply setting the 'is_private' flag of the control to 1:



```c
static const struct v4l2_ctrl_config ctrl_private = {
        .ops = &ctrl_custom_ops,
        .id = V4L2_CID_...,
        .name = "Some Private Control",
        .type = V4L2_CTRL_TYPE_INTEGER,
        .max = 15,
        .step = 1,
        .is_private = 1,
};

ctrl = v4l2_ctrl_new_custom(&foo->ctrl_handler, &ctrl_private, NULL);
```

These controls will now be skipped when v4l2_ctrl_add_handler is called.

<a id="rst-v4l2-ctrl-type-ctrl-class-controls"></a>

## V4L2_CTRL_TYPE_CTRL_CLASS Controls

Controls of this type can be used by GUIs to get the name of the control class. A fully featured GUI can make a dialog with multiple tabs with each tab containing the controls belonging to a particular control class. The name of each tab can be found by querying a special control with ID &lt;control class \| 1&gt;.

Drivers do not have to care about this. The framework will automatically add a control of this type whenever the first control belonging to a new control class is added.

<a id="rst-adding-notify-callbacks"></a>

## Adding Notify Callbacks

Sometimes the platform or bridge driver needs to be notified when a control from a sub-device driver changes. You can set a notify callback by calling this function:



```c
void v4l2_ctrl_notify(struct v4l2_ctrl *ctrl,
        void (*notify)(struct v4l2_ctrl *ctrl, void *priv), void *priv);
```

Whenever the give control changes value the notify callback will be called with a pointer to the control and the priv pointer that was passed with v4l2_ctrl_notify. Note that the control's handler lock is held when the notify function is called.

There can be only one notify function per control handler. Any attempt to set another notify function will cause a WARN_ON.

<a id="rst-v4l2-ctrl-functions-and-data-structures"></a>

## v4l2_ctrl functions and data structures


#### <a id="c-union-v4l2_ctrl_ptr"></a>`union v4l2_ctrl_ptr`

A pointer to a control value.

**Definition**

```c
union v4l2_ctrl_ptr {
    s32 *p_s32;
    s64 *p_s64;
    u8 *p_u8;
    u16 *p_u16;
    u32 *p_u32;
    char *p_char;
    struct v4l2_ctrl_mpeg2_sequence *p_mpeg2_sequence;
    struct v4l2_ctrl_mpeg2_picture *p_mpeg2_picture;
    struct v4l2_ctrl_mpeg2_quantisation *p_mpeg2_quantisation;
    struct v4l2_ctrl_fwht_params *p_fwht_params;
    struct v4l2_ctrl_h264_sps *p_h264_sps;
    struct v4l2_ctrl_h264_pps *p_h264_pps;
    struct v4l2_ctrl_h264_scaling_matrix *p_h264_scaling_matrix;
    struct v4l2_ctrl_h264_slice_params *p_h264_slice_params;
    struct v4l2_ctrl_h264_decode_params *p_h264_decode_params;
    struct v4l2_ctrl_h264_pred_weights *p_h264_pred_weights;
    struct v4l2_ctrl_vp8_frame *p_vp8_frame;
    struct v4l2_ctrl_hevc_sps *p_hevc_sps;
    struct v4l2_ctrl_hevc_pps *p_hevc_pps;
    struct v4l2_ctrl_hevc_slice_params *p_hevc_slice_params;
    struct v4l2_ctrl_vp9_compressed_hdr *p_vp9_compressed_hdr_probs;
    struct v4l2_ctrl_vp9_frame *p_vp9_frame;
    struct v4l2_ctrl_hdr10_cll_info *p_hdr10_cll;
    struct v4l2_ctrl_hdr10_mastering_display *p_hdr10_mastering;
    struct v4l2_area *p_area;
    struct v4l2_ctrl_av1_sequence *p_av1_sequence;
    struct v4l2_ctrl_av1_tile_group_entry *p_av1_tile_group_entry;
    struct v4l2_ctrl_av1_frame *p_av1_frame;
    struct v4l2_ctrl_av1_film_grain *p_av1_film_grain;
    struct v4l2_rect *p_rect;
    void *p;
    const void *p_const;
};
```

**Members**

- `p_s32`: Pointer to a 32-bit signed value.
- `p_s64`: Pointer to a 64-bit signed value.
- `p_u8`: Pointer to a 8-bit unsigned value.
- `p_u16`: Pointer to a 16-bit unsigned value.
- `p_u32`: Pointer to a 32-bit unsigned value.
- `p_char`: Pointer to a string.
- `p_mpeg2_sequence`: Pointer to a MPEG2 sequence structure.
- `p_mpeg2_picture`: Pointer to a MPEG2 picture structure.
- `p_mpeg2_quantisation`: Pointer to a MPEG2 quantisation data structure.
- `p_fwht_params`: Pointer to a FWHT stateless parameters structure.
- `p_h264_sps`: Pointer to a struct v4l2_ctrl_h264_sps.
- `p_h264_pps`: Pointer to a struct v4l2_ctrl_h264_pps.
- `p_h264_scaling_matrix`: Pointer to a struct v4l2_ctrl_h264_scaling_matrix.
- `p_h264_slice_params`: Pointer to a struct v4l2_ctrl_h264_slice_params.
- `p_h264_decode_params`: Pointer to a struct v4l2_ctrl_h264_decode_params.
- `p_h264_pred_weights`: Pointer to a struct v4l2_ctrl_h264_pred_weights.
- `p_vp8_frame`: Pointer to a VP8 frame params structure.
- `p_hevc_sps`: Pointer to an HEVC sequence parameter set structure.
- `p_hevc_pps`: Pointer to an HEVC picture parameter set structure.
- `p_hevc_slice_params`: Pointer to an HEVC slice parameters structure.
- `p_vp9_compressed_hdr_probs`: Pointer to a VP9 frame compressed header probs structure.
- `p_vp9_frame`: Pointer to a VP9 frame params structure.
- `p_hdr10_cll`: Pointer to an HDR10 Content Light Level structure.
- `p_hdr10_mastering`: Pointer to an HDR10 Mastering Display structure.
- `p_area`: Pointer to an area.
- `p_av1_sequence`: Pointer to an AV1 sequence structure.
- `p_av1_tile_group_entry`: Pointer to an AV1 tile group entry structure.
- `p_av1_frame`: Pointer to an AV1 frame structure.
- `p_av1_film_grain`: Pointer to an AV1 film grain structure.
- `p_rect`: Pointer to a rectangle.
- `p`: Pointer to a compound value.
- `p_const`: Pointer to a constant compound value.

#### <a id="c-v4l2_ctrl_ptr_create"></a>`v4l2_ctrl_ptr_create()`

```c
union v4l2_ctrl_ptr v4l2_ctrl_ptr_create(void *ptr)
```

Helper function to return a v4l2_ctrl_ptr from a void pointer

**Parameters**

- `void *ptr`: The void pointer

#### <a id="c-struct-v4l2_ctrl_ops"></a>`struct v4l2_ctrl_ops`

The control operations that the driver has to provide.

**Definition**

```c
struct v4l2_ctrl_ops {
    int (*g_volatile_ctrl)(struct v4l2_ctrl *ctrl);
    int (*try_ctrl)(struct v4l2_ctrl *ctrl);
    int (*s_ctrl)(struct v4l2_ctrl *ctrl);
};
```

**Members**

- `g_volatile_ctrl`: Get a new value for this control. Generally only relevant
  for volatile (and usually read-only) controls such as a control
  that returns the current signal strength which changes
  continuously.
  If not set, then the currently cached value will be returned.
- `try_ctrl`: Test whether the control's value is valid. Only relevant when
  the usual min/max/step checks are not sufficient.
- `s_ctrl`: Actually set the new control value. s_ctrl is compulsory. The
  ctrl->handler->lock is held when these ops are called, so no
  one else can access controls owned by that handler.

#### <a id="c-struct-v4l2_ctrl_type_ops"></a>`struct v4l2_ctrl_type_ops`

The control type operations that the driver has to provide.

**Definition**

```c
struct v4l2_ctrl_type_ops {
    bool (*equal)(const struct v4l2_ctrl *ctrl, union v4l2_ctrl_ptr ptr1, union v4l2_ctrl_ptr ptr2);
    void (*init)(const struct v4l2_ctrl *ctrl, u32 from_idx, union v4l2_ctrl_ptr ptr);
    void (*minimum)(const struct v4l2_ctrl *ctrl, u32 idx, union v4l2_ctrl_ptr ptr);
    void (*maximum)(const struct v4l2_ctrl *ctrl, u32 idx, union v4l2_ctrl_ptr ptr);
    void (*log)(const struct v4l2_ctrl *ctrl);
    int (*validate)(const struct v4l2_ctrl *ctrl, union v4l2_ctrl_ptr ptr);
};
```

**Members**

- `equal`: return true if all ctrl->elems array elements are equal.
- `init`: initialize the value for array elements from from_idx to ctrl->elems.
- `minimum`: set the value to the minimum value of the control.
- `maximum`: set the value to the maximum value of the control.
- `log`: log the value.
- `validate`: validate the value for ctrl->new_elems array elements.
  Return 0 on success and a negative value otherwise.

#### <a id="c-v4l2_ctrl_notify_fnc"></a>`v4l2_ctrl_notify_fnc()`

```c
typedef void v4l2_ctrl_notify_fnc(struct v4l2_ctrl *ctrl, void *priv)
```

typedef for a notify argument with a function that should be called when a control value has changed.

**Parameters**

- `struct v4l2_ctrl *ctrl`: pointer to struct [`v4l2_ctrl`](#c-struct-v4l2_ctrl)
- `void *priv`: control private data

**Description**

This typedef definition is used as an argument to [`v4l2_ctrl_notify()`](#c-v4l2_ctrl_notify)
and as an argument at struct [`v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler).

#### <a id="c-struct-v4l2_ctrl"></a>`struct v4l2_ctrl`

The control structure.

**Definition**

```c
struct v4l2_ctrl {
    struct list_head node;
    struct list_head ev_subs;
    struct v4l2_ctrl_handler *handler;
    struct v4l2_ctrl **cluster;
    unsigned int ncontrols;
    unsigned int done:1;
    unsigned int is_new:1;
    unsigned int has_changed:1;
    unsigned int is_private:1;
    unsigned int is_auto:1;
    unsigned int is_int:1;
    unsigned int is_string:1;
    unsigned int is_ptr:1;
    unsigned int is_array:1;
    unsigned int is_dyn_array:1;
    unsigned int has_volatiles:1;
    unsigned int call_notify:1;
    unsigned int manual_mode_value:8;
    const struct v4l2_ctrl_ops *ops;
    const struct v4l2_ctrl_type_ops *type_ops;
    u32 id;
    const char *name;
    enum v4l2_ctrl_type type;
    s64 minimum, maximum, default_value;
    u32 elems;
    u32 elem_size;
    u32 new_elems;
    u32 dims[V4L2_CTRL_MAX_DIMS];
    u32 nr_of_dims;
    union {
        u64 step;
        u64 menu_skip_mask;
    };
    union {
        const char * const *qmenu;
        const s64 *qmenu_int;
    };
    unsigned long flags;
    void *priv;
    void *p_array;
    u32 p_array_alloc_elems;
    s32 val;
    struct {
        s32 val;
    } cur;
    union v4l2_ctrl_ptr p_def;
    union v4l2_ctrl_ptr p_min;
    union v4l2_ctrl_ptr p_max;
    union v4l2_ctrl_ptr p_new;
    union v4l2_ctrl_ptr p_cur;
};
```

**Members**

- `node`: The list node.
- `ev_subs`: The list of control event subscriptions.
- `handler`: The handler that owns the control.
- `cluster`: Point to start of cluster array.
- `ncontrols`: Number of controls in cluster array.
- `done`: Internal flag: set for each processed control.
- `is_new`: Set when the user specified a new value for this control. It
  is also set when called from [`v4l2_ctrl_handler_setup()`](#c-v4l2_ctrl_handler_setup). Drivers
  should never set this flag.
- `has_changed`: Set when the current value differs from the new value. Drivers
  should never use this flag.
- `is_private`: If set, then this control is private to its handler and it
  will not be added to any other handlers. Drivers can set
  this flag.
- `is_auto`: If set, then this control selects whether the other cluster
  members are in 'automatic' mode or 'manual' mode. This is
  used for autogain/gain type clusters. Drivers should never
  set this flag directly.
- `is_int`: If set, then this control has a simple integer value (i.e. it
  uses ctrl->val).
- `is_string`: If set, then this control has type `V4L2_CTRL_TYPE_STRING`.
- `is_ptr`: If set, then this control is an array and/or has type >=
  `V4L2_CTRL_COMPOUND_TYPES`
  and/or has type `V4L2_CTRL_TYPE_STRING`. In other words, [`struct v4l2_ext_control`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ext-ctrls.md#c-v4l2_ext_control) uses field p to point to the data.
- `is_array`: If set, then this control contains an N-dimensional array.
- `is_dyn_array`: If set, then this control contains a dynamically sized 1-dimensional array.
  If this is set, then **is_array** is also set.
- `has_volatiles`: If set, then one or more members of the cluster are volatile.
  Drivers should never touch this flag.
- `call_notify`: If set, then call the handler's notify function whenever the
  control's value changes.
- `manual_mode_value`: If the is_auto flag is set, then this is the value
  of the auto control that determines if that control is in
  manual mode. So if the value of the auto control equals this
  value, then the whole cluster is in manual mode. Drivers should
  never set this flag directly.
- `ops`: The control ops.
- `type_ops`: The control type ops.
- `id`: The control ID.
- `name`: The control name.
- `type`: The control type.
- `minimum`: The control's minimum value.
- `maximum`: The control's maximum value.
- `default_value`: The control's default value.
- `elems`: The number of elements in the N-dimensional array.
- `elem_size`: The size in bytes of the control.
- `new_elems`: The number of elements in p_new. This is the same as **elems**,
  except for dynamic arrays. In that case it is in the range of
  1 to **p_array_alloc_elems**.
- `dims`: The size of each dimension.
- `nr_of_dims`: The number of dimensions in **dims**.
- `{unnamed_union}`: anonymous
- `step`: The control's step value for non-menu controls.
- `menu_skip_mask`: The control's skip mask for menu controls. This makes it
  easy to skip menu items that are not valid. If bit X is set,
  then menu item X is skipped. Of course, this only works for
  menus with \<= 32 menu items. There are no menus that come
  close to that number, so this is OK. Should we ever need more,
  then this will have to be extended to a u64 or a bit array.
- `{unnamed_union}`: anonymous
- `qmenu`: A const char * array for all menu items. Array entries that are
  empty strings ("") correspond to non-existing menu items (this
  is in addition to the menu_skip_mask above). The last entry
  must be NULL.
  Used only if the **type** is `V4L2_CTRL_TYPE_MENU`.
- `qmenu_int`: A 64-bit integer array for with integer menu items.
  The size of array must be equal to the menu size, e. g.:
  ceil(\frac{maximum - minimum}{step}) + 1.
  Used only if the **type** is `V4L2_CTRL_TYPE_INTEGER_MENU`.
- `flags`: The control's flags.
- `priv`: The control's private pointer. For use by the driver. It is
  untouched by the control framework. Note that this pointer is
  not freed when the control is deleted. Should this be needed
  then a new internal bitfield can be added to tell the framework
  to free this pointer.
- `p_array`: Pointer to the allocated array. Only valid if **is_array** is true.
- `p_array_alloc_elems`: The number of elements in the allocated
  array for both the cur and new values. So **p_array** is actually
  sized for 2 * **p_array_alloc_elems** * **elem_size**. Only valid if
  **is_array** is true.
- `val`: The control's new s32 value.
- `cur`: Structure to store the current value.
- `cur.val`: The control's current value, if the **type** is represented via
  a u32 integer (see [`enum v4l2_ctrl_type`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-v4l2_ctrl_type)).
- `p_def`: The control's default value represented via a union which
  provides a standard way of accessing control types
  through a pointer (for compound controls only).
- `p_min`: The control's minimum value represented via a union which
  provides a standard way of accessing control types
  through a pointer (for compound controls only).
- `p_max`: The control's maximum value represented via a union which
  provides a standard way of accessing control types
  through a pointer (for compound controls only).
- `p_new`: The control's new value represented via a union which provides
  a standard way of accessing control types
  through a pointer.
- `p_cur`: The control's current value represented via a union which
  provides a standard way of accessing control types
  through a pointer.

#### <a id="c-struct-v4l2_ctrl_ref"></a>`struct v4l2_ctrl_ref`

The control reference.

**Definition**

```c
struct v4l2_ctrl_ref {
    struct list_head node;
    struct v4l2_ctrl_ref *next;
    struct v4l2_ctrl *ctrl;
    struct v4l2_ctrl_helper *helper;
    bool from_other_dev;
    bool req_done;
    bool p_req_valid;
    bool p_req_array_enomem;
    u32 p_req_array_alloc_elems;
    u32 p_req_elems;
    union v4l2_ctrl_ptr p_req;
};
```

**Members**

- `node`: List node for the sorted list.
- `next`: Single-link list node for the hash.
- `ctrl`: The actual control information.
- `helper`: Pointer to helper struct. Used internally in
  `prepare_ext_ctrls` function at `v4l2-ctrl.c`.
- `from_other_dev`: If true, then **ctrl** was defined in another
  device than the [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler).
- `req_done`: Internal flag: if the control handler containing this control
  reference is bound to a media request, then this is set when
  the control has been applied. This prevents applying controls
  from a cluster with multiple controls twice (when the first
  control of a cluster is applied, they all are).
- `p_req_valid`: If set, then p_req contains the control value for the request.
- `p_req_array_enomem`: If set, then p_req is invalid since allocating space for
  an array failed. Attempting to read this value shall
  result in ENOMEM. Only valid if ctrl->is_array is true.
- `p_req_array_alloc_elems`: The number of elements allocated for the
  array. Only valid if **p_req_valid** and ctrl->is_array are
  true.
- `p_req_elems`: The number of elements in **p_req**. This is the same as
  ctrl->elems, except for dynamic arrays. In that case it is in
  the range of 1 to **p_req_array_alloc_elems**. Only valid if
  **p_req_valid** is true.
- `p_req`: If the control handler containing this control reference
  is bound to a media request, then this points to the
  value of the control that must be applied when the request
  is executed, or to the value of the control at the time
  that the request was completed. If **p_req_valid** is false,
  then this control was never set for this request and the
  control will not be updated when this request is applied.

**Description**

Each control handler has a list of these refs. The list_head is used to
keep a sorted-by-control-ID list of all controls, while the next pointer
is used to link the control in the hash's bucket.

#### <a id="c-struct-v4l2_ctrl_handler"></a>`struct v4l2_ctrl_handler`

The control handler keeps track of all the controls: both the controls owned by the handler and those inherited from other handlers.

**Definition**

```c
struct v4l2_ctrl_handler {
    struct mutex _lock;
    struct mutex *lock;
    struct list_head ctrls;
    struct list_head ctrl_refs;
    struct v4l2_ctrl_ref *cached;
    struct v4l2_ctrl_ref **buckets;
    v4l2_ctrl_notify_fnc notify;
    void *notify_priv;
    u16 nr_of_buckets;
    int error;
    bool request_is_queued;
    struct list_head requests;
    struct list_head requests_queued;
    struct media_request_object req_obj;
};
```

**Members**

- `_lock`: Default for "lock".
- `lock`: Lock to control access to this handler and its controls.
  May be replaced by the user right after init.
- `ctrls`: The list of controls owned by this handler.
- `ctrl_refs`: The list of control references.
- `cached`: The last found control reference. It is common that the same
  control is needed multiple times, so this is a simple
  optimization.
- `buckets`: Buckets for the hashing. Allows for quick control lookup.
- `notify`: A notify callback that is called whenever the control changes
  value.
  Note that the handler's lock is held when the notify function
  is called!
- `notify_priv`: Passed as argument to the v4l2_ctrl notify callback.
- `nr_of_buckets`: Total number of buckets in the array.
- `error`: The error code of the first failed control addition.
- `request_is_queued`: True if the request was queued.
- `requests`: List to keep track of open control handler request objects.
  For the parent control handler (**req_obj.ops** == NULL) this
  is the list header. When the parent control handler is
  removed, it has to unbind and put all these requests since
  they refer to the parent.
- `requests_queued`: List of the queued requests. This determines the order
  in which these controls are applied. Once the request is
  completed it is removed from this list.
- `req_obj`: The [`struct media_request_object`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_request_object), used to link into a
  [`struct media_request`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_request). This request object has a refcount.

#### <a id="c-struct-v4l2_ctrl_config"></a>`struct v4l2_ctrl_config`

Control configuration structure.

**Definition**

```c
struct v4l2_ctrl_config {
    const struct v4l2_ctrl_ops *ops;
    const struct v4l2_ctrl_type_ops *type_ops;
    u32 id;
    const char *name;
    enum v4l2_ctrl_type type;
    s64 min;
    s64 max;
    u64 step;
    s64 def;
    union v4l2_ctrl_ptr p_def;
    union v4l2_ctrl_ptr p_min;
    union v4l2_ctrl_ptr p_max;
    u32 dims[V4L2_CTRL_MAX_DIMS];
    u32 elem_size;
    u32 flags;
    u64 menu_skip_mask;
    const char * const *qmenu;
    const s64 *qmenu_int;
    unsigned int is_private:1;
};
```

**Members**

- `ops`: The control ops.
- `type_ops`: The control type ops. Only needed for compound controls.
- `id`: The control ID.
- `name`: The control name.
- `type`: The control type.
- `min`: The control's minimum value.
- `max`: The control's maximum value.
- `step`: The control's step value for non-menu controls.
- `def`: The control's default value.
- `p_def`: The control's default value for compound controls.
- `p_min`: The control's minimum value for compound controls.
- `p_max`: The control's maximum value for compound controls.
- `dims`: The size of each dimension.
- `elem_size`: The size in bytes of the control.
- `flags`: The control's flags.
- `menu_skip_mask`: The control's skip mask for menu controls. This makes it
  easy to skip menu items that are not valid. If bit X is set,
  then menu item X is skipped. Of course, this only works for
  menus with \<= 64 menu items. There are no menus that come
  close to that number, so this is OK. Should we ever need more,
  then this will have to be extended to a bit array.
- `qmenu`: A const char * array for all menu items. Array entries that are
  empty strings ("") correspond to non-existing menu items (this
  is in addition to the menu_skip_mask above). The last entry
  must be NULL.
- `qmenu_int`: A const s64 integer array for all menu items of the type
  V4L2_CTRL_TYPE_INTEGER_MENU.
- `is_private`: If set, then this control is private to its handler and it
  will not be added to any other handlers.

#### <a id="c-v4l2_ctrl_fill"></a>`v4l2_ctrl_fill()`

```c
void v4l2_ctrl_fill(u32 id, const char **name, enum v4l2_ctrl_type *type, s64 *min, s64 *max, u64 *step, s64 *def, u32 *flags)
```

Fill in the control fields based on the control ID.

**Parameters**

- `u32 id`: ID of the control
- `const char **name`: pointer to be filled with a string with the name of the control
- `enum v4l2_ctrl_type *type`: pointer for storing the type of the control
- `s64 *min`: pointer for storing the minimum value for the control
- `s64 *max`: pointer for storing the maximum value for the control
- `u64 *step`: pointer for storing the control step
- `s64 *def`: pointer for storing the default value for the control
- `u32 *flags`: pointer for storing the flags to be used on the control

**Description**

This works for all standard V4L2 controls.
For non-standard controls it will only fill in the given arguments
and **name** content will be set to `NULL`.

This function will overwrite the contents of **name**, **type** and **flags**.
The contents of **min**, **max**, **step** and **def** may be modified depending on
the type.

> [!NOTE]
> Do not use in drivers! It is used internally for backwards compatibility
> control handling only. Once all drivers are converted to use the new
> control framework this function will no longer be exported.

#### <a id="c-v4l2_ctrl_handler_init_class"></a>`v4l2_ctrl_handler_init_class()`

```c
int v4l2_ctrl_handler_init_class(struct v4l2_ctrl_handler *hdl, unsigned int nr_of_controls_hint, struct lock_class_key *key, const char *name)
```

Initialize the control handler.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `unsigned int nr_of_controls_hint`: A hint of how many controls this handler is
  expected to refer to. This is the total number, so including
  any inherited controls. It doesn't have to be precise, but if
  it is way off, then you either waste memory (too many buckets
  are allocated) or the control lookup becomes slower (not enough
  buckets are allocated, so there are more slow list lookups).
  It will always work, though.
- `struct lock_class_key *key`: Used by the lock validator if CONFIG_LOCKDEP is set.
- `const char *name`: Used by the lock validator if CONFIG_LOCKDEP is set.

**Description**

> [!IMPORTANT]
> Never use this call directly, always use the [`v4l2_ctrl_handler_init()`](#c-v4l2_ctrl_handler_init)
> macro that hides the **key** and **name** arguments.

**Return**

returns an error if the buckets could not be allocated. This
error will also be stored in **hdl->error**.

#### <a id="c-v4l2_ctrl_handler_init"></a>`v4l2_ctrl_handler_init()`

```c
v4l2_ctrl_handler_init(hdl, nr_of_controls_hint)
```

helper function to create a static struct `lock_class_key` and calls [`v4l2_ctrl_handler_init_class()`](#c-v4l2_ctrl_handler_init_class)

**Parameters**

- `hdl`: The control handler.
- `nr_of_controls_hint`: A hint of how many controls this handler is
  expected to refer to. This is the total number, so including
  any inherited controls. It doesn't have to be precise, but if
  it is way off, then you either waste memory (too many buckets
  are allocated) or the control lookup becomes slower (not enough
  buckets are allocated, so there are more slow list lookups).
  It will always work, though.

**Description**

This helper function creates a static struct `lock_class_key` and
calls [`v4l2_ctrl_handler_init_class()`](#c-v4l2_ctrl_handler_init_class), providing a proper name for the lock
validador.

Use this helper function to initialize a control handler.

#### <a id="c-v4l2_ctrl_handler_free"></a>`v4l2_ctrl_handler_free()`

```c
int v4l2_ctrl_handler_free(struct v4l2_ctrl_handler *hdl)
```

Free all controls owned by the handler and free the control list.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.

**Description**

Does nothing if **hdl** == NULL.

**Return**

**hdl**'s error field or 0 if **hdl** is NULL.

#### <a id="c-v4l2_ctrl_lock"></a>`v4l2_ctrl_lock()`

```c
void v4l2_ctrl_lock(struct v4l2_ctrl *ctrl)
```

Helper function to lock the handler associated with the control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to lock.

#### <a id="c-v4l2_ctrl_unlock"></a>`v4l2_ctrl_unlock()`

```c
void v4l2_ctrl_unlock(struct v4l2_ctrl *ctrl)
```

Helper function to unlock the handler associated with the control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to unlock.

#### <a id="c-__v4l2_ctrl_handler_setup"></a>`__v4l2_ctrl_handler_setup()`

```c
int __v4l2_ctrl_handler_setup(struct v4l2_ctrl_handler *hdl)
```

Call the s_ctrl op for all controls belonging to the handler to initialize the hardware to the current control values. The caller is responsible for acquiring the control handler mutex on behalf of [`__v4l2_ctrl_handler_setup()`](#c-__v4l2_ctrl_handler_setup).

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.

**Description**

Button controls will be skipped, as are read-only controls.

If **hdl** == NULL, then this just returns 0.

#### <a id="c-v4l2_ctrl_handler_setup"></a>`v4l2_ctrl_handler_setup()`

```c
int v4l2_ctrl_handler_setup(struct v4l2_ctrl_handler *hdl)
```

Call the s_ctrl op for all controls belonging to the handler to initialize the hardware to the current control values.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.

**Description**

Button controls will be skipped, as are read-only controls.

If **hdl** == NULL, then this just returns 0.

#### <a id="c-v4l2_ctrl_handler_log_status"></a>`v4l2_ctrl_handler_log_status()`

```c
void v4l2_ctrl_handler_log_status(struct v4l2_ctrl_handler *hdl, const char *prefix)
```

Log all controls owned by the handler.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const char *prefix`: The prefix to use when logging the control values. If the
  prefix does not end with a space, then ": " will be added
  after the prefix. If **prefix** == NULL, then no prefix will be
  used.

**Description**

For use with VIDIOC_LOG_STATUS.

Does nothing if **hdl** == NULL.

#### <a id="c-v4l2_ctrl_new_custom"></a>`v4l2_ctrl_new_custom()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_custom(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_config *cfg, void *priv)
```

Allocate and initialize a new custom V4L2 control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_config *cfg`: The control's configuration data.
- `void *priv`: The control's driver-specific private data.

**Description**

If the [`v4l2_ctrl`](#c-struct-v4l2_ctrl) struct could not be allocated then NULL is returned
and **hdl->error** is set to the error code (if it wasn't set already).

#### <a id="c-v4l2_ctrl_new_std"></a>`v4l2_ctrl_new_std()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_std(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, s64 min, s64 max, u64 step, s64 def)
```

Allocate and initialize a new standard V4L2 non-menu control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `s64 min`: The control's minimum value.
- `s64 max`: The control's maximum value.
- `u64 step`: The control's step value
- `s64 def`: The control's default value.

**Description**

If the [`v4l2_ctrl`](#c-struct-v4l2_ctrl) struct could not be allocated, or the control
ID is not known, then NULL is returned and **hdl->error** is set to the
appropriate error code (if it wasn't set already).

If **id** refers to a menu control, then this function will return NULL.

Use [`v4l2_ctrl_new_std_menu()`](#c-v4l2_ctrl_new_std_menu) when adding menu controls.

#### <a id="c-v4l2_ctrl_new_std_menu"></a>`v4l2_ctrl_new_std_menu()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_std_menu(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, u8 max, u64 mask, u8 def)
```

Allocate and initialize a new standard V4L2 menu control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `u8 max`: The control's maximum value.
- `u64 mask`: The control's skip mask for menu controls. This makes it
  easy to skip menu items that are not valid. If bit X is set,
  then menu item X is skipped. Of course, this only works for
  menus with \<= 64 menu items. There are no menus that come
  close to that number, so this is OK. Should we ever need more,
  then this will have to be extended to a bit array.
- `u8 def`: The control's default value.

**Description**

Same as [`v4l2_ctrl_new_std()`](#c-v4l2_ctrl_new_std), but **min** is set to 0 and the **mask** value
determines which menu items are to be skipped.

If **id** refers to a non-menu control, then this function will return NULL.

#### <a id="c-v4l2_ctrl_new_std_menu_items"></a>`v4l2_ctrl_new_std_menu_items()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_std_menu_items(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, u8 max, u64 mask, u8 def, const char * const *qmenu)
```

Create a new standard V4L2 menu control with driver specific menu.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `u8 max`: The control's maximum value.
- `u64 mask`: The control's skip mask for menu controls. This makes it
  easy to skip menu items that are not valid. If bit X is set,
  then menu item X is skipped. Of course, this only works for
  menus with \<= 64 menu items. There are no menus that come
  close to that number, so this is OK. Should we ever need more,
  then this will have to be extended to a bit array.
- `u8 def`: The control's default value.
- `const char * const *qmenu`: The new menu.

**Description**

Same as [`v4l2_ctrl_new_std_menu()`](#c-v4l2_ctrl_new_std_menu), but **qmenu** will be the driver specific
menu of this control.

#### <a id="c-v4l2_ctrl_new_std_compound"></a>`v4l2_ctrl_new_std_compound()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_std_compound(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, const union v4l2_ctrl_ptr p_def, const union v4l2_ctrl_ptr p_min, const union v4l2_ctrl_ptr p_max)
```

Allocate and initialize a new standard V4L2 compound control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `const union v4l2_ctrl_ptr p_def`: The control's default value.
- `const union v4l2_ctrl_ptr p_min`: The control's minimum value.
- `const union v4l2_ctrl_ptr p_max`: The control's maximum value.

**Description**

Same as [`v4l2_ctrl_new_std()`](#c-v4l2_ctrl_new_std), but with support for compound controls.
To fill in the **p_def**, **p_min** and **p_max** fields, use [`v4l2_ctrl_ptr_create()`](#c-v4l2_ctrl_ptr_create)
to convert a pointer to a const union v4l2_ctrl_ptr.
Use v4l2_ctrl_ptr_create(NULL) if you want the default, minimum or maximum
value of the compound control to be all zeroes.
If the compound control does not set the `V4L2_CTRL_FLAG_HAS_WHICH_MIN_MAX`
flag, then it does not has minimum and maximum values. In that case just use
v4l2_ctrl_ptr_create(NULL) for the **p_min** and **p_max** arguments.

#### <a id="c-v4l2_ctrl_new_int_menu"></a>`v4l2_ctrl_new_int_menu()`

```c
struct v4l2_ctrl * v4l2_ctrl_new_int_menu(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ops, u32 id, u8 max, u8 def, const s64 *qmenu_int)
```

Create a new standard V4L2 integer menu control.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `const struct v4l2_ctrl_ops *ops`: The control ops.
- `u32 id`: The control ID.
- `u8 max`: The control's maximum value.
- `u8 def`: The control's default value.
- `const s64 *qmenu_int`: The control's menu entries.

**Description**

Same as [`v4l2_ctrl_new_std_menu()`](#c-v4l2_ctrl_new_std_menu), but **mask** is set to 0 and it additionally
takes as an argument an array of integers determining the menu items.

If **id** refers to a non-integer-menu control, then this function will
return `NULL`.

#### <a id="c-v4l2_ctrl_filter"></a>`v4l2_ctrl_filter()`

```c
typedef bool v4l2_ctrl_filter(const struct v4l2_ctrl *ctrl)
```

Typedef to define the filter function to be used when adding a control handler.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: pointer to struct [`v4l2_ctrl`](#c-struct-v4l2_ctrl).

#### <a id="c-v4l2_ctrl_add_handler"></a>`v4l2_ctrl_add_handler()`

```c
int v4l2_ctrl_add_handler(struct v4l2_ctrl_handler *hdl, struct v4l2_ctrl_handler *add, v4l2_ctrl_filter filter, bool from_other_dev)
```

Add all controls from handler **add** to handler **hdl**.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `struct v4l2_ctrl_handler *add`: The control handler whose controls you want to add to
  the **hdl** control handler.
- `v4l2_ctrl_filter filter`: This function will filter which controls should be added.
- `bool from_other_dev`: If true, then the controls in **add** were defined in another
  device than **hdl**.

**Description**

Does nothing if either of the two handlers is a NULL pointer.
If **filter** is NULL, then all controls are added. Otherwise only those
controls for which **filter** returns true will be added.
In case of an error **hdl->error** will be set to the error code (if it
wasn't set already).

#### <a id="c-v4l2_ctrl_radio_filter"></a>`v4l2_ctrl_radio_filter()`

```c
bool v4l2_ctrl_radio_filter(const struct v4l2_ctrl *ctrl)
```

Standard filter for radio controls.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The control that is filtered.

**Description**

This will return true for any controls that are valid for radio device
nodes. Those are all of the V4L2_CID_AUDIO_* user controls and all FM
transmitter class controls.

This function is to be used with [`v4l2_ctrl_add_handler()`](#c-v4l2_ctrl_add_handler).

#### <a id="c-v4l2_ctrl_cluster"></a>`v4l2_ctrl_cluster()`

```c
void v4l2_ctrl_cluster(unsigned int ncontrols, struct v4l2_ctrl **controls)
```

Mark all controls in the cluster as belonging to that cluster.

**Parameters**

- `unsigned int ncontrols`: The number of controls in this cluster.
- `struct v4l2_ctrl **controls`: The cluster control array of size **ncontrols**.

#### <a id="c-v4l2_ctrl_auto_cluster"></a>`v4l2_ctrl_auto_cluster()`

```c
void v4l2_ctrl_auto_cluster(unsigned int ncontrols, struct v4l2_ctrl **controls, u8 manual_val, bool set_volatile)
```

Mark all controls in the cluster as belonging to that cluster and set it up for autofoo/foo-type handling.

**Parameters**

- `unsigned int ncontrols`: The number of controls in this cluster.
- `struct v4l2_ctrl **controls`: The cluster control array of size **ncontrols**. The first control
  must be the 'auto' control (e.g. autogain, autoexposure, etc.)
- `u8 manual_val`: The value for the first control in the cluster that equals the
  manual setting.
- `bool set_volatile`: If true, then all controls except the first auto control will
  be volatile.

**Description**

Use for control groups where one control selects some automatic feature and
the other controls are only active whenever the automatic feature is turned
off (manual mode). Typical examples: autogain vs gain, auto-whitebalance vs
red and blue balance, etc.

The behavior of such controls is as follows:

When the autofoo control is set to automatic, then any manual controls
are set to inactive and any reads will call g_volatile_ctrl (if the control
was marked volatile).

When the autofoo control is set to manual, then any manual controls will
be marked active, and any reads will just return the current value without
going through g_volatile_ctrl.

In addition, this function will set the `V4L2_CTRL_FLAG_UPDATE` flag
on the autofoo control and `V4L2_CTRL_FLAG_INACTIVE` on the foo control(s)
if autofoo is in auto mode.

#### <a id="c-v4l2_ctrl_find"></a>`v4l2_ctrl_find()`

```c
struct v4l2_ctrl * v4l2_ctrl_find(struct v4l2_ctrl_handler *hdl, u32 id)
```

Find a control with the given ID.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler.
- `u32 id`: The control ID to find.

**Description**

If **hdl** == NULL this will return NULL as well. Will lock the handler so
do not use from inside [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops).

#### <a id="c-v4l2_ctrl_activate"></a>`v4l2_ctrl_activate()`

```c
void v4l2_ctrl_activate(struct v4l2_ctrl *ctrl, bool active)
```

Make the control active or inactive.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to (de)activate.
- `bool active`: True if the control should become active.

**Description**

This sets or clears the V4L2_CTRL_FLAG_INACTIVE flag atomically.
Does nothing if **ctrl** == NULL.
This will usually be called from within the s_ctrl op.
The V4L2_EVENT_CTRL event will be generated afterwards.

This function assumes that the control handler is locked.

#### <a id="c-__v4l2_ctrl_grab"></a>`__v4l2_ctrl_grab()`

```c
void __v4l2_ctrl_grab(struct v4l2_ctrl *ctrl, bool grabbed)
```

Unlocked variant of v4l2_ctrl_grab.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to (de)activate.
- `bool grabbed`: True if the control should become grabbed.

**Description**

This sets or clears the V4L2_CTRL_FLAG_GRABBED flag atomically.
Does nothing if **ctrl** == NULL.
The V4L2_EVENT_CTRL event will be generated afterwards.
This will usually be called when starting or stopping streaming in the
driver.

This function assumes that the control handler is locked by the caller.

#### <a id="c-v4l2_ctrl_grab"></a>`v4l2_ctrl_grab()`

```c
void v4l2_ctrl_grab(struct v4l2_ctrl *ctrl, bool grabbed)
```

Mark the control as grabbed or not grabbed.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to (de)activate.
- `bool grabbed`: True if the control should become grabbed.

**Description**

This sets or clears the V4L2_CTRL_FLAG_GRABBED flag atomically.
Does nothing if **ctrl** == NULL.
The V4L2_EVENT_CTRL event will be generated afterwards.
This will usually be called when starting or stopping streaming in the
driver.

This function assumes that the control handler is not locked and will
take the lock itself.

#### <a id="c-__v4l2_ctrl_modify_range"></a>`__v4l2_ctrl_modify_range()`

```c
int __v4l2_ctrl_modify_range(struct v4l2_ctrl *ctrl, s64 min, s64 max, u64 step, s64 def)
```

Unlocked variant of [`v4l2_ctrl_modify_range()`](#c-v4l2_ctrl_modify_range)

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to update.
- `s64 min`: The control's minimum value.
- `s64 max`: The control's maximum value.
- `u64 step`: The control's step value
- `s64 def`: The control's default value.

**Description**

Update the range of a control on the fly. This works for control types
INTEGER, BOOLEAN, MENU, INTEGER MENU and BITMASK. For menu controls the
**step** value is interpreted as a menu_skip_mask.

An error is returned if one of the range arguments is invalid for this
control type.

The caller is responsible for acquiring the control handler mutex on behalf
of [`__v4l2_ctrl_modify_range()`](#c-__v4l2_ctrl_modify_range).

#### <a id="c-v4l2_ctrl_modify_range"></a>`v4l2_ctrl_modify_range()`

```c
int v4l2_ctrl_modify_range(struct v4l2_ctrl *ctrl, s64 min, s64 max, u64 step, s64 def)
```

Update the range of a control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to update.
- `s64 min`: The control's minimum value.
- `s64 max`: The control's maximum value.
- `u64 step`: The control's step value
- `s64 def`: The control's default value.

**Description**

Update the range of a control on the fly. This works for control types
INTEGER, BOOLEAN, MENU, INTEGER MENU and BITMASK. For menu controls the
**step** value is interpreted as a menu_skip_mask.

An error is returned if one of the range arguments is invalid for this
control type.

This function assumes that the control handler is not locked and will
take the lock itself.

#### <a id="c-__v4l2_ctrl_modify_dimensions"></a>`__v4l2_ctrl_modify_dimensions()`

```c
int __v4l2_ctrl_modify_dimensions(struct v4l2_ctrl *ctrl, u32 dims[V4L2_CTRL_MAX_DIMS])
```

Unlocked variant of [`v4l2_ctrl_modify_dimensions()`](#c-v4l2_ctrl_modify_dimensions)

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to update.
- `u32 dims[V4L2_CTRL_MAX_DIMS]`: The control's new dimensions.

**Description**

Update the dimensions of an array control on the fly. The elements of the
array are reset to their default value, even if the dimensions are
unchanged.

An error is returned if **dims** is invalid for this control.

The caller is responsible for acquiring the control handler mutex on behalf
of [`__v4l2_ctrl_modify_dimensions()`](#c-__v4l2_ctrl_modify_dimensions).

**Note**

calling this function when the same control is used in pending requests
is untested. It should work (a request with the wrong size of the control
will drop that control silently), but it will be very confusing.

#### <a id="c-v4l2_ctrl_modify_dimensions"></a>`v4l2_ctrl_modify_dimensions()`

```c
int v4l2_ctrl_modify_dimensions(struct v4l2_ctrl *ctrl, u32 dims[V4L2_CTRL_MAX_DIMS])
```

Update the dimensions of an array control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control to update.
- `u32 dims[V4L2_CTRL_MAX_DIMS]`: The control's new dimensions.

**Description**

Update the dimensions of an array control on the fly. The elements of the
array are reset to their default value, even if the dimensions are
unchanged.

An error is returned if **dims** is invalid for this control type.

This function assumes that the control handler is not locked and will
take the lock itself.

**Note**

calling this function when the same control is used in pending requests
is untested. It should work (a request with the wrong size of the control
will drop that control silently), but it will be very confusing.

#### <a id="c-v4l2_ctrl_notify"></a>`v4l2_ctrl_notify()`

```c
void v4l2_ctrl_notify(struct v4l2_ctrl *ctrl, v4l2_ctrl_notify_fnc notify, void *priv)
```

Function to set a notify callback for a control.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `v4l2_ctrl_notify_fnc notify`: The callback function.
- `void *priv`: The callback private handle, passed as argument to the callback.

**Description**

This function sets a callback function for the control. If **ctrl** is NULL,
then it will do nothing. If **notify** is NULL, then the notify callback will
be removed.

There can be only one notify. If another already exists, then a WARN_ON
will be issued and the function will do nothing.

#### <a id="c-v4l2_ctrl_get_name"></a>`v4l2_ctrl_get_name()`

```c
const char * v4l2_ctrl_get_name(u32 id)
```

Get the name of the control

**Parameters**

- `u32 id`: The control ID.

**Description**

This function returns the name of the given control ID or NULL if it isn't
a known control.

#### <a id="c-v4l2_ctrl_get_menu"></a>`v4l2_ctrl_get_menu()`

```c
const char * const * v4l2_ctrl_get_menu(u32 id)
```

Get the menu string array of the control

**Parameters**

- `u32 id`: The control ID.

**Description**

This function returns the NULL-terminated menu string array name of the
given control ID or NULL if it isn't a known menu control.

#### <a id="c-v4l2_ctrl_get_int_menu"></a>`v4l2_ctrl_get_int_menu()`

```c
const s64 * v4l2_ctrl_get_int_menu(u32 id, u32 *len)
```

Get the integer menu array of the control

**Parameters**

- `u32 id`: The control ID.
- `u32 *len`: The size of the integer array.

**Description**

This function returns the integer array of the given control ID or NULL if it
if it isn't a known integer menu control.

#### <a id="c-v4l2_ctrl_g_ctrl"></a>`v4l2_ctrl_g_ctrl()`

```c
s32 v4l2_ctrl_g_ctrl(struct v4l2_ctrl *ctrl)
```

Helper function to get the control's value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.

**Description**

This returns the control's value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for integer type controls only.

#### <a id="c-__v4l2_ctrl_s_ctrl"></a>`__v4l2_ctrl_s_ctrl()`

```c
int __v4l2_ctrl_s_ctrl(struct v4l2_ctrl *ctrl, s32 val)
```

Unlocked variant of [`v4l2_ctrl_s_ctrl()`](#c-v4l2_ctrl_s_ctrl).

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `s32 val`: The new value.

**Description**

This sets the control's new value safely by going through the control
framework. This function assumes the control's handler is already locked,
allowing it to be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for integer type controls only.

#### <a id="c-v4l2_ctrl_s_ctrl"></a>`v4l2_ctrl_s_ctrl()`

```c
int v4l2_ctrl_s_ctrl(struct v4l2_ctrl *ctrl, s32 val)
```

Helper function to set the control's value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `s32 val`: The new value.

**Description**

This sets the control's new value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for integer type controls only.

#### <a id="c-v4l2_ctrl_g_ctrl_int64"></a>`v4l2_ctrl_g_ctrl_int64()`

```c
s64 v4l2_ctrl_g_ctrl_int64(struct v4l2_ctrl *ctrl)
```

Helper function to get a 64-bit control's value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.

**Description**

This returns the control's value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for 64-bit integer type controls only.

#### <a id="c-__v4l2_ctrl_s_ctrl_int64"></a>`__v4l2_ctrl_s_ctrl_int64()`

```c
int __v4l2_ctrl_s_ctrl_int64(struct v4l2_ctrl *ctrl, s64 val)
```

Unlocked variant of [`v4l2_ctrl_s_ctrl_int64()`](#c-v4l2_ctrl_s_ctrl_int64).

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `s64 val`: The new value.

**Description**

This sets the control's new value safely by going through the control
framework. This function assumes the control's handler is already locked,
allowing it to be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for 64-bit integer type controls only.

#### <a id="c-v4l2_ctrl_s_ctrl_int64"></a>`v4l2_ctrl_s_ctrl_int64()`

```c
int v4l2_ctrl_s_ctrl_int64(struct v4l2_ctrl *ctrl, s64 val)
```

Helper function to set a 64-bit control's value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `s64 val`: The new value.

**Description**

This sets the control's new value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for 64-bit integer type controls only.

#### <a id="c-__v4l2_ctrl_s_ctrl_string"></a>`__v4l2_ctrl_s_ctrl_string()`

```c
int __v4l2_ctrl_s_ctrl_string(struct v4l2_ctrl *ctrl, const char *s)
```

Unlocked variant of [`v4l2_ctrl_s_ctrl_string()`](#c-v4l2_ctrl_s_ctrl_string).

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `const char *s`: The new string.

**Description**

This sets the control's new string safely by going through the control
framework. This function assumes the control's handler is already locked,
allowing it to be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for string type controls only.

#### <a id="c-v4l2_ctrl_s_ctrl_string"></a>`v4l2_ctrl_s_ctrl_string()`

```c
int v4l2_ctrl_s_ctrl_string(struct v4l2_ctrl *ctrl, const char *s)
```

Helper function to set a control's string value from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `const char *s`: The new string.

**Description**

This sets the control's new string safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for string type controls only.

#### <a id="c-__v4l2_ctrl_s_ctrl_compound"></a>`__v4l2_ctrl_s_ctrl_compound()`

```c
int __v4l2_ctrl_s_ctrl_compound(struct v4l2_ctrl *ctrl, enum v4l2_ctrl_type type, const void *p)
```

Unlocked variant to set a compound control

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `enum v4l2_ctrl_type type`: The type of the data.
- `const void *p`: The new compound payload.

**Description**

This sets the control's new compound payload safely by going through the
control framework. This function assumes the control's handler is already
locked, allowing it to be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for compound type controls only.

#### <a id="c-v4l2_ctrl_s_ctrl_compound"></a>`v4l2_ctrl_s_ctrl_compound()`

```c
int v4l2_ctrl_s_ctrl_compound(struct v4l2_ctrl *ctrl, enum v4l2_ctrl_type type, const void *p)
```

Helper function to set a compound control from within a driver.

**Parameters**

- `struct v4l2_ctrl *ctrl`: The control.
- `enum v4l2_ctrl_type type`: The type of the data.
- `const void *p`: The new compound payload.

**Description**

This sets the control's new compound payload safely by going through the
control framework. This function will lock the control's handler, so it
cannot be used from within the [`v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) functions.

This function is for compound type controls only.

#### <a id="c-v4l2_ctrl_replace"></a>`v4l2_ctrl_replace()`

```c
void v4l2_ctrl_replace(struct v4l2_event *old, const struct v4l2_event *new)
```

Function to be used as a callback to [`struct v4l2_subscribed_event_ops`](/kernel/hardware/driver-api/media/v4l2-event.md#c-struct-v4l2_subscribed_event_ops) replace\(\)

**Parameters**

- `struct v4l2_event *old`: pointer to struct `v4l2_event` with the reported
  event;
- `const struct v4l2_event *new`: pointer to struct `v4l2_event` with the modified
  event;

#### <a id="c-v4l2_ctrl_merge"></a>`v4l2_ctrl_merge()`

```c
void v4l2_ctrl_merge(const struct v4l2_event *old, struct v4l2_event *new)
```

Function to be used as a callback to [`struct v4l2_subscribed_event_ops`](/kernel/hardware/driver-api/media/v4l2-event.md#c-struct-v4l2_subscribed_event_ops) merge(\)

**Parameters**

- `const struct v4l2_event *old`: pointer to struct `v4l2_event` with the reported
  event;
- `struct v4l2_event *new`: pointer to struct `v4l2_event` with the merged
  event;

#### <a id="c-v4l2_ctrl_log_status"></a>`v4l2_ctrl_log_status()`

```c
int v4l2_ctrl_log_status(struct file *file, void *priv)
```

helper function to implement `VIDIOC_LOG_STATUS` ioctl

**Parameters**

- `struct file *file`: pointer to struct file
- `void *priv`: unused. Kept just to be compatible to the arguments expected by
  [`struct v4l2_ioctl_ops`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops).vidioc_log_status.

**Description**

Can be used as a vidioc_log_status function that just dumps all controls
associated with the filehandle.

#### <a id="c-v4l2_ctrl_subscribe_event"></a>`v4l2_ctrl_subscribe_event()`

```c
int v4l2_ctrl_subscribe_event(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub)
```

Subscribes to an event

**Parameters**

- `struct v4l2_fh *fh`: pointer to struct v4l2_fh
- `const struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

**Description**

Can be used as a vidioc_subscribe_event function that just subscribes
control events.

#### <a id="c-v4l2_ctrl_poll"></a>`v4l2_ctrl_poll()`

```c
__poll_t v4l2_ctrl_poll(struct file *file, struct poll_table_struct *wait)
```

function to be used as a callback to the `poll()` That just polls for control events.

**Parameters**

- `struct file *file`: pointer to struct file
- `struct poll_table_struct *wait`: pointer to struct poll_table_struct

#### <a id="c-v4l2_ctrl_request_setup"></a>`v4l2_ctrl_request_setup()`

```c
int v4l2_ctrl_request_setup(struct media_request *req, struct v4l2_ctrl_handler *parent)
```

helper function to apply control values in a request

**Parameters**

- `struct media_request *req`: The request
- `struct v4l2_ctrl_handler *parent`: The parent control handler ('priv' in [`media_request_object_find()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_request_object_find))

**Description**

This is a helper function to call the control handler's s_ctrl callback with
the control values contained in the request. Do note that this approach of
applying control values in a request is only applicable to memory-to-memory
devices.

#### <a id="c-v4l2_ctrl_request_complete"></a>`v4l2_ctrl_request_complete()`

```c
void v4l2_ctrl_request_complete(struct media_request *req, struct v4l2_ctrl_handler *parent)
```

Complete a control handler request object

**Parameters**

- `struct media_request *req`: The request
- `struct v4l2_ctrl_handler *parent`: The parent control handler ('priv' in [`media_request_object_find()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_request_object_find))

**Description**

This function is to be called on each control handler that may have had a
request object associated with it, i.e. control handlers of a driver that
supports requests.

The function first obtains the values of any volatile controls in the control
handler and attach them to the request. Then, the function completes the
request object.

#### <a id="c-v4l2_ctrl_request_hdl_find"></a>`v4l2_ctrl_request_hdl_find()`

```c
struct v4l2_ctrl_handler * v4l2_ctrl_request_hdl_find(struct media_request *req, struct v4l2_ctrl_handler *parent)
```

Find the control handler in the request

**Parameters**

- `struct media_request *req`: The request
- `struct v4l2_ctrl_handler *parent`: The parent control handler ('priv' in [`media_request_object_find()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_request_object_find))

**Description**

This function finds the control handler in the request. It may return
NULL if not found. When done, you must call [`v4l2_ctrl_request_hdl_put()`](#c-v4l2_ctrl_request_hdl_put)
with the returned handler pointer.

If the request is not in state VALIDATING or QUEUED, then this function
will always return NULL.

Note that in state VALIDATING the req_queue_mutex is held, so
no objects can be added or deleted from the request.

In state QUEUED it is the driver that will have to ensure this.

#### <a id="c-v4l2_ctrl_request_hdl_put"></a>`v4l2_ctrl_request_hdl_put()`

```c
void v4l2_ctrl_request_hdl_put(struct v4l2_ctrl_handler *hdl)
```

Put the control handler

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: Put this control handler

**Description**

This function released the control handler previously obtained from'
[`v4l2_ctrl_request_hdl_find()`](#c-v4l2_ctrl_request_hdl_find).

#### <a id="c-v4l2_ctrl_request_hdl_ctrl_find"></a>`v4l2_ctrl_request_hdl_ctrl_find()`

```c
struct v4l2_ctrl * v4l2_ctrl_request_hdl_ctrl_find(struct v4l2_ctrl_handler *hdl, u32 id)
```

Find a control with the given ID.

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: The control handler from the request.
- `u32 id`: The ID of the control to find.

**Description**

This function returns a pointer to the control if this control is
part of the request or NULL otherwise.

#### <a id="c-v4l2_queryctrl"></a>`v4l2_queryctrl()`

```c
int v4l2_queryctrl(struct v4l2_ctrl_handler *hdl, struct v4l2_queryctrl *qc)
```

Helper function to implement VIDIOC_QUERYCTRL ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_queryctrl *qc`: pointer to [`struct v4l2_queryctrl`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_queryctrl)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_query_ext_ctrl_to_v4l2_queryctrl"></a>`v4l2_query_ext_ctrl_to_v4l2_queryctrl()`

```c
void v4l2_query_ext_ctrl_to_v4l2_queryctrl(struct v4l2_queryctrl *to, const struct v4l2_query_ext_ctrl *from)
```

Convert a qec to qe.

**Parameters**

- `struct v4l2_queryctrl *to`: The v4l2_queryctrl to write to.
- `const struct v4l2_query_ext_ctrl *from`: The v4l2_query_ext_ctrl to read from.

**Description**

This function is a helper to convert a v4l2_query_ext_ctrl into a
v4l2_queryctrl.

#### <a id="c-v4l2_query_ext_ctrl"></a>`v4l2_query_ext_ctrl()`

```c
int v4l2_query_ext_ctrl(struct v4l2_ctrl_handler *hdl, struct v4l2_query_ext_ctrl *qc)
```

Helper function to implement VIDIOC_QUERY_EXT_CTRL ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_query_ext_ctrl *qc`: pointer to [`struct v4l2_query_ext_ctrl`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_query_ext_ctrl)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_querymenu"></a>`v4l2_querymenu()`

```c
int v4l2_querymenu(struct v4l2_ctrl_handler *hdl, struct v4l2_querymenu *qm)
```

Helper function to implement VIDIOC_QUERYMENU ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_querymenu *qm`: pointer to [`struct v4l2_querymenu`](/kernel/userspace/userspace-api/media-v4l/vidioc-queryctrl.md#c-struct-v4l2_querymenu)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_g_ctrl"></a>`v4l2_g_ctrl()`

```c
int v4l2_g_ctrl(struct v4l2_ctrl_handler *hdl, struct v4l2_control *ctrl)
```

Helper function to implement VIDIOC_G_CTRL ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_control *ctrl`: pointer to [`struct v4l2_control`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ctrl.md#c-v4l2_control)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_s_ctrl"></a>`v4l2_s_ctrl()`

```c
int v4l2_s_ctrl(struct v4l2_fh *fh, struct v4l2_ctrl_handler *hdl, struct v4l2_control *ctrl)
```

Helper function to implement VIDIOC_S_CTRL ioctl

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct v4l2_control *ctrl`: pointer to [`struct v4l2_control`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ctrl.md#c-v4l2_control)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_g_ext_ctrls"></a>`v4l2_g_ext_ctrls()`

```c
int v4l2_g_ext_ctrls(struct v4l2_ctrl_handler *hdl, struct video_device *vdev, struct media_device *mdev, struct v4l2_ext_controls *c)
```

Helper function to implement VIDIOC_G_EXT_CTRLS ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device)
- `struct v4l2_ext_controls *c`: pointer to [`struct v4l2_ext_controls`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ext-ctrls.md#c-v4l2_ext_controls)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_try_ext_ctrls"></a>`v4l2_try_ext_ctrls()`

```c
int v4l2_try_ext_ctrls(struct v4l2_ctrl_handler *hdl, struct video_device *vdev, struct media_device *mdev, struct v4l2_ext_controls *c)
```

Helper function to implement VIDIOC_TRY_EXT_CTRLS ioctl

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device)
- `struct v4l2_ext_controls *c`: pointer to [`struct v4l2_ext_controls`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ext-ctrls.md#c-v4l2_ext_controls)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_s_ext_ctrls"></a>`v4l2_s_ext_ctrls()`

```c
int v4l2_s_ext_ctrls(struct v4l2_fh *fh, struct v4l2_ctrl_handler *hdl, struct video_device *vdev, struct media_device *mdev, struct v4l2_ext_controls *c)
```

Helper function to implement VIDIOC_S_EXT_CTRLS ioctl

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler)
- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device)
- `struct v4l2_ext_controls *c`: pointer to [`struct v4l2_ext_controls`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-ext-ctrls.md#c-v4l2_ext_controls)

**Description**

If hdl == NULL then they will all return -EINVAL.

#### <a id="c-v4l2_ctrl_subdev_subscribe_event"></a>`v4l2_ctrl_subdev_subscribe_event()`

```c
int v4l2_ctrl_subdev_subscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub)
```

Helper function to implement as a [`struct v4l2_subdev_core_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_core_ops) subscribe_event function that just subscribes control events.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

#### <a id="c-v4l2_ctrl_subdev_log_status"></a>`v4l2_ctrl_subdev_log_status()`

```c
int v4l2_ctrl_subdev_log_status(struct v4l2_subdev *sd)
```

Log all controls owned by subdev's control handler.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l2_ctrl_new_fwnode_properties"></a>`v4l2_ctrl_new_fwnode_properties()`

```c
int v4l2_ctrl_new_fwnode_properties(struct v4l2_ctrl_handler *hdl, const struct v4l2_ctrl_ops *ctrl_ops, const struct v4l2_fwnode_device_properties *p)
```

Register controls for the device properties

**Parameters**

- `struct v4l2_ctrl_handler *hdl`: pointer to [`struct v4l2_ctrl_handler`](#c-struct-v4l2_ctrl_handler) to register controls on
- `const struct v4l2_ctrl_ops *ctrl_ops`: pointer to [`struct v4l2_ctrl_ops`](#c-struct-v4l2_ctrl_ops) to register controls with
- `const struct v4l2_fwnode_device_properties *p`: pointer to [`struct v4l2_fwnode_device_properties`](/kernel/hardware/driver-api/media/v4l2-fwnode.md#c-struct-v4l2_fwnode_device_properties)

**Description**

This function registers controls associated to device properties, using the
property values contained in **p** parameter, if the property has been set to
a value.

Currently the following v4l2 controls are parsed and registered:
- V4L2_CID_CAMERA_ORIENTATION
- V4L2_CID_CAMERA_SENSOR_ROTATION;

Controls already registered by the caller with the **hdl** control handler are
not overwritten. Callers should register the controls they want to handle
themselves before calling this function.

This function will set the control handler's error field on failure, just as
other functions adding controls to the handler.

**Return**

0 on success, a negative error code on failure.

#### <a id="c-v4l2_ctrl_type_op_equal"></a>`v4l2_ctrl_type_op_equal()`

```c
bool v4l2_ctrl_type_op_equal(const struct v4l2_ctrl *ctrl, union v4l2_ctrl_ptr ptr1, union v4l2_ctrl_ptr ptr2)
```

Default v4l2_ctrl_type_ops equal callback.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The v4l2_ctrl pointer.
- `union v4l2_ctrl_ptr ptr1`: A v4l2 control value.
- `union v4l2_ctrl_ptr ptr2`: A v4l2 control value.

**Return**

true if values are equal, otherwise false.

#### <a id="c-v4l2_ctrl_type_op_init"></a>`v4l2_ctrl_type_op_init()`

```c
void v4l2_ctrl_type_op_init(const struct v4l2_ctrl *ctrl, u32 from_idx, union v4l2_ctrl_ptr ptr)
```

Default v4l2_ctrl_type_ops init callback.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The v4l2_ctrl pointer.
- `u32 from_idx`: Starting element index.
- `union v4l2_ctrl_ptr ptr`: The v4l2 control value.

**Return**

void

#### <a id="c-v4l2_ctrl_type_op_log"></a>`v4l2_ctrl_type_op_log()`

```c
void v4l2_ctrl_type_op_log(const struct v4l2_ctrl *ctrl)
```

Default v4l2_ctrl_type_ops log callback.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The v4l2_ctrl pointer.

**Return**

void

#### <a id="c-v4l2_ctrl_type_op_validate"></a>`v4l2_ctrl_type_op_validate()`

```c
int v4l2_ctrl_type_op_validate(const struct v4l2_ctrl *ctrl, union v4l2_ctrl_ptr ptr)
```

Default v4l2_ctrl_type_ops validate callback.

**Parameters**

- `const struct v4l2_ctrl *ctrl`: The v4l2_ctrl pointer.
- `union v4l2_ctrl_ptr ptr`: The v4l2 control value.

**Return**

0 on success, a negative error code on failure.

---

# Video4Linux devices

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Video4Linux devices.

<a id="rst-video4linux-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Introduction](</kernel/hardware/driver-api/media/v4l2-intro.md>)
- [Video device' s internal representation](</kernel/hardware/driver-api/media/v4l2-dev.md>)
- [V4L2 device instance](</kernel/hardware/driver-api/media/v4l2-device.md>)
- [V4L2 File handles](</kernel/hardware/driver-api/media/v4l2-fh.md>)
- [V4L2 sub-devices](</kernel/hardware/driver-api/media/v4l2-subdev.md>)
- [V4L2 events](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/media/v4l2-event.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [V4L2 Controls](</kernel/hardware/driver-api/media/v4l2-controls.md>)
- [V4L2 videobuf2 functions and data structures](</kernel/hardware/driver-api/media/v4l2-videobuf2.md>)
- [V4L2 DV Timings functions](</kernel/hardware/driver-api/media/v4l2-dv-timings.md>)
- [V4L2 flash functions and data structures](</kernel/hardware/driver-api/media/v4l2-flash-led-class.md>)
- [V4L2 Media Controller functions and data structures](</kernel/hardware/driver-api/media/v4l2-mc.md>)
- [V4L2 Media Bus functions and data structures](</kernel/hardware/driver-api/media/v4l2-mediabus.md>)
- [V4L2 Memory to Memory functions and data structures](</kernel/hardware/driver-api/media/v4l2-mem2mem.md>)
- [V4L2 async kAPI](</kernel/hardware/driver-api/media/v4l2-async.md>)
- [V4L2 fwnode kAPI](</kernel/hardware/driver-api/media/v4l2-fwnode.md>)
- [V4L2 CCI kAPI](</kernel/hardware/driver-api/media/v4l2-cci.md>)
- [V4L2 rect helper functions](</kernel/hardware/driver-api/media/v4l2-rect.md>)
- [Tuner functions and data structures](</kernel/hardware/driver-api/media/v4l2-tuner.md>)
- [V4L2 common functions and data structures](</kernel/hardware/driver-api/media/v4l2-common.md>)
- [Hauppauge TV EEPROM functions and data structures](</kernel/hardware/driver-api/media/v4l2-tveeprom.md>)
- [V4L2 JPEG header related functions and data structures](</kernel/hardware/driver-api/media/v4l2-jpeg.md>)
- [V4L2 generic ISP parameters and statistics support](</kernel/hardware/driver-api/media/v4l2-isp.md>)

---

# Video device' s internal representation

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The actual device nodes in the /dev directory are created using the video_device struct (v4l2-dev.h). This struct can either be allocated dynamically or embedded in a larger struct.

<a id="rst-video-device-s-internal-representation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The actual device nodes in the `/dev` directory are created using the `video_device` struct (`v4l2-dev.h`). This struct can either be allocated dynamically or embedded in a larger struct.

To allocate it dynamically use `video_device_alloc()`:



```c
struct video_device *vdev = video_device_alloc();

if (vdev == NULL)
        return -ENOMEM;

vdev->release = video_device_release;
```

If you embed it in a larger struct, then you must set the `release()` callback to your own function:



```c
struct video_device *vdev = &my_vdev->vdev;

vdev->release = my_vdev_release;
```

The `release()` callback must be set and it is called when the last user of the video device exits.

The default `video_device_release()` callback currently just calls `kfree` to free the allocated memory.

There is also a `video_device_release_empty()` function that does nothing (is empty) and should be used if the struct is embedded and there is nothing to do when it is released.

You should also set these fields of `video_device`:

- `video_device`-&gt;v4l2_dev: must be set to the `v4l2_device` parent device.

- `video_device`-&gt;name: set to something descriptive and unique.

- `video_device`-&gt;vfl_dir: set this to `VFL_DIR_RX` for capture devices (`VFL_DIR_RX` has value 0, so this is normally already the default), set to `VFL_DIR_TX` for output devices and `VFL_DIR_M2M` for mem2mem (codec) devices.

- `video_device`-&gt;fops: set to the `v4l2_file_operations` struct.

- `video_device`-&gt;ioctl_ops: if you use the `v4l2_ioctl_ops` to simplify ioctl maintenance (highly recommended to use this and it might become compulsory in the future\!), then set this to your `v4l2_ioctl_ops` struct. The `video_device`-&gt;vfl_type and `video_device`-&gt;vfl_dir fields are used to disable ops that do not match the type/dir combination. E.g. VBI ops are disabled for non-VBI nodes, and output ops  are disabled for a capture device. This makes it possible to provide just one `v4l2_ioctl_ops` struct for both vbi and video nodes.

- `video_device`-&gt;lock: leave to `NULL` if you want to do all the locking  in the driver. Otherwise you give it a pointer to a struct `mutex_lock` and before the `video_device`-&gt;unlocked_ioctl file operation is called this lock will be taken by the core and released afterwards. See the next section for more details.

- `video_device`-&gt;queue: a pointer to the struct vb2_queue associated with this device node. If queue is not `NULL`, and queue-&gt;lock is not `NULL`, then queue-&gt;lock is used for the queuing ioctls (`VIDIOC_REQBUFS`, `CREATE_BUFS`, `QBUF`, `DQBUF`,  `QUERYBUF`, `PREPARE_BUF`, `STREAMON` and `STREAMOFF`) instead of the lock above. That way the [vb2](</kernel/hardware/driver-api/media/v4l2-videobuf2.md#rst-vb2-framework>) queuing framework does not have to wait for other ioctls.   This queue pointer is also used by the [vb2](</kernel/hardware/driver-api/media/v4l2-videobuf2.md#rst-vb2-framework>) helper functions to check for queuing ownership (i.e. is the filehandle calling it allowed to do the operation).

- `video_device`-&gt;prio: keeps track of the priorities. Used to implement `VIDIOC_G_PRIORITY` and `VIDIOC_S_PRIORITY`. If left to `NULL`, then it will use the struct v4l2_prio_state in `v4l2_device`. If you want to have a separate priority state per (group of) device node(s),   then you can point it to your own struct `v4l2_prio_state`.

- `video_device`-&gt;dev_parent: you only set this if v4l2_device was registered with `NULL` as the parent `device` struct. This only happens in cases where one hardware device has multiple PCI devices that all share the same `v4l2_device` core.

  The cx88 driver is an example of this: one core `v4l2_device` struct, but   it is used by both a raw video PCI device (cx8800) and a MPEG PCI device (cx8802). Since the `v4l2_device` cannot be associated with two PCI devices at the same time it is setup without a parent device. But when the struct video_device is initialized you **do** know which parent PCI device to use and so you set `dev_device` to the correct PCI device.

If you use `v4l2_ioctl_ops`, then you should set `video_device`-&gt;unlocked_ioctl to `video_ioctl2()` in your `v4l2_file_operations` struct.

In some cases you want to tell the core that a function you had specified in your `v4l2_ioctl_ops` should be ignored. You can mark such ioctls by calling this function before `video_register_device()` is called:

> `v4l2_disable_ioctl <v4l2_disable_ioctl>()` (`vdev <video_device>`, cmd).

This tends to be needed if based on external factors (e.g. which card is being used) you want to turns off certain features in `v4l2_ioctl_ops` without having to make a new struct.

The `v4l2_file_operations` struct is a subset of file_operations. The main difference is that the inode argument is omitted since it is never used.

If integration with the media framework is needed, you must initialize the `media_entity` struct embedded in the `video_device` struct (entity field) by calling `media_entity_pads_init()`:



```c
struct media_pad *pad = &my_vdev->pad;
int err;

err = media_entity_pads_init(&vdev->entity, 1, pad);
```

The pads array must have been previously initialized. There is no need to manually set the struct media_entity type and name fields.

A reference to the entity will be automatically acquired/released when the video device is opened/closed.

<a id="rst-ioctls-and-locking"></a>

## ioctls and locking

The V4L core provides optional locking services. The main service is the lock field in struct video_device, which is a pointer to a mutex. If you set this pointer, then that will be used by unlocked_ioctl to serialize all ioctls.

If you are using the [videobuf2 framework](</kernel/hardware/driver-api/media/v4l2-videobuf2.md#rst-vb2-framework>), then there is a second lock that you can set: `video_device`-&gt;queue-&gt;lock. If set, then this lock will be used instead of `video_device`-&gt;lock to serialize all queuing ioctls (see the previous section for the full list of those ioctls).

The advantage of using a different lock for the queuing ioctls is that for some drivers (particularly USB drivers) certain commands such as setting controls can take a long time, so you want to use a separate lock for the buffer queuing ioctls. That way your `VIDIOC_DQBUF` doesn't stall because the driver is busy changing the e.g. exposure of the webcam.

Of course, you can always do all the locking yourself by leaving both lock pointers at `NULL`.

In the case of [videobuf2](</kernel/hardware/driver-api/media/v4l2-videobuf2.md#rst-vb2-framework>) you must set the `queue->lock` pointer to the lock you use to serialize the queuing ioctls. This ensures that that lock is released while waiting in `VIDIOC_DQBUF` for a buffer to arrive, and it is retaken afterwards.

The implementation of a hotplug disconnect should also take the lock from `video_device` before calling v4l2_device_disconnect. If you are also using `video_device`-&gt;queue-&gt;lock, then you have to first lock `video_device`-&gt;queue-&gt;lock followed by `video_device`-&gt;lock. That way you can be sure no ioctl is running when you call `v4l2_device_disconnect()`.

<a id="rst-video-device-registration"></a>

## Video device registration

Next you register the video device with `video_register_device()`. This will create the character device for you.



```c
err = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
if (err) {
        video_device_release(vdev); /* or kfree(my_vdev); */
        return err;
}
```

If the `v4l2_device` parent device has a not `NULL` mdev field, the video device entity will be automatically registered with the media device.

Which device is registered depends on the type argument. The following types exist:


<table>
<thead>
<tr>
<th>


`vfl_devnode_type`

</th>
<th>


Device name

</th>
<th>


Usage

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`VFL_TYPE_VIDEO`

</td>
<td>


`/dev/videoX`

</td>
<td>


for video input/output devices

</td>
</tr>
<tr>
<td>


`VFL_TYPE_VBI`

</td>
<td>


`/dev/vbiX`

</td>
<td>


for vertical blank data (i.e. closed captions, teletext)

</td>
</tr>
<tr>
<td>


`VFL_TYPE_RADIO`

</td>
<td>


`/dev/radioX`

</td>
<td>


for radio tuners

</td>
</tr>
<tr>
<td>


`VFL_TYPE_SUBDEV`

</td>
<td>


`/dev/v4l-subdevX`

</td>
<td>


for V4L2 subdevices

</td>
</tr>
<tr>
<td>


`VFL_TYPE_SDR`

</td>
<td>


`/dev/swradioX`

</td>
<td>


for Software Defined Radio (SDR) tuners

</td>
</tr>
<tr>
<td>


`VFL_TYPE_TOUCH`

</td>
<td>


`/dev/v4l-touchX`

</td>
<td>


for touch sensors

</td>
</tr>
</tbody>
</table>

The last argument gives you a certain amount of control over the device node number used (i.e. the X in `videoX`). Normally you will pass -1 to let the v4l2 framework pick the first free number. But sometimes users want to select a specific node number. It is common that drivers allow the user to select a specific device node number through a driver module option. That number is then passed to this function and video_register_device will attempt to select that device node number. If that number was already in use, then the next free device node number will be selected and it will send a warning to the kernel log.

Another use-case is if a driver creates many devices. In that case it can be useful to place different video devices in separate ranges. For example, video capture devices start at 0, video output devices start at 16. So you can use the last argument to specify a minimum device node number and the v4l2 framework will try to pick the first free number that is equal or higher to what you passed. If that fails, then it will just pick the first free number.

Since in this case you do not care about a warning about not being able to select the specified device node number, you can call the function `video_register_device_no_warn()` instead.

Whenever a device node is created some attributes are also created for you. If you look in `/sys/class/video4linux` you see the devices. Go into e.g. `video0` and you will see 'name', 'dev_debug' and 'index' attributes. The 'name' attribute is the 'name' field of the video_device struct. The 'dev_debug' attribute can be used to enable core debugging. See the next section for more detailed information on this.

The 'index' attribute is the index of the device node: for each call to `video_register_device()` the index is just increased by 1. The first video device node you register always starts with index 0.

Users can setup udev rules that utilize the index attribute to make fancy device names (e.g. '`mpegX`' for MPEG video capture device nodes).

After the device was successfully registered, then you can use these fields:

- `video_device`-&gt;vfl_type: the device type passed to `video_register_device()`.

- `video_device`-&gt;minor: the assigned device minor number.

- `video_device`-&gt;num: the device node number (i.e. the X in `videoX`).

- `video_device`-&gt;index: the device index number.

If the registration failed, then you need to call `video_device_release()` to free the allocated `video_device` struct, or free your own struct if the `video_device` was embedded in it. The `vdev->release()` callback will never be called if the registration failed, nor should you ever attempt to unregister the device if the registration failed.

<a id="rst-video-device-debugging"></a>

## video device debugging

The 'dev_debug' attribute that is created for each video, vbi, radio or swradio device in `/sys/class/video4linux/<devX>/` allows you to enable logging of file operations.

It is a bitmask and the following bits can be set:

<!-- tabularcolumns: |p{5ex}|L| -->


<table>
<thead>
<tr>
<th>


Mask

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x01

</td>
<td>


Log the ioctl name and error code. VIDIOC\_(D)QBUF ioctls are only logged if bit 0x08 is also set.

</td>
</tr>
<tr>
<td>


0x02

</td>
<td>


Log the ioctl name arguments and error code. VIDIOC\_(D)QBUF ioctls are only logged if bit 0x08 is also set.

</td>
</tr>
<tr>
<td>


0x04

</td>
<td>


Log the file operations open, release, read, write, mmap and get_unmapped_area. The read and write operations are only logged if bit 0x08 is also set.

</td>
</tr>
<tr>
<td>


0x08

</td>
<td>


Log the read and write file operations and the VIDIOC_QBUF and VIDIOC_DQBUF ioctls.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


Log the poll file operation.

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


Log error and messages in the control operations.

</td>
</tr>
</tbody>
</table>

<a id="rst-video-device-cleanup"></a>

## Video device cleanup

When the video device nodes have to be removed, either during the unload of the driver or because the USB device was disconnected, then you should unregister them with:

> `video_unregister_device()` (`vdev <video_device>`);

This will remove the device nodes from sysfs (causing udev to remove them from `/dev`).

After `video_unregister_device()` returns no new opens can be done. However, in the case of USB devices some application might still have one of these device nodes open. So after the unregister all file operations (except release, of course) will return an error as well.

When the last user of the video device node exits, then the `vdev->release()` callback is called and you can do the final cleanup there.

Don't forget to cleanup the media entity associated with the video device if it has been initialized:

> `media_entity_cleanup <media_entity_cleanup>()` (&amp;vdev-&gt;entity);

This can be done from the release callback.

<a id="rst-helper-functions"></a>

## helper functions

There are a few useful helper functions:

- file and `video_device` private data

You can set/get driver private data in the video_device struct using:

> `video_get_drvdata <video_get_drvdata>()` (`vdev <video_device>`);
>
> `video_set_drvdata <video_set_drvdata>()` (`vdev <video_device>`);

Note that you can safely call `video_set_drvdata()` before calling `video_register_device()`.

And this function:

> `video_devdata <video_devdata>()` (struct file \*file);

returns the video_device belonging to the file struct.

The `video_devdata()` function combines `video_get_drvdata()` with `video_devdata()`:

> `video_drvdata <video_drvdata>()` (struct file \*file);

You can go from a `video_device` struct to the v4l2_device struct using:



```c
struct v4l2_device *v4l2_dev = vdev->v4l2_dev;
```

- Device node name

The `video_device` node kernel name can be retrieved using:

> `video_device_node_name <video_device_node_name>()` (`vdev <video_device>`);

The name is used as a hint by userspace tools such as udev. The function should be used where possible instead of accessing the video_device::num and video_device::minor fields.

<a id="rst-video-device-functions-and-data-structures"></a>

## video_device functions and data structures


#### <a id="c-enum-vfl_devnode_type"></a>`enum vfl_devnode_type`

type of V4L2 device node

**Constants**

- `VFL_TYPE_VIDEO`: for video input/output devices
- `VFL_TYPE_VBI`: for vertical blank data (i.e. closed captions, teletext)
- `VFL_TYPE_RADIO`: for radio tuners
- `VFL_TYPE_SUBDEV`: for V4L2 subdevices
- `VFL_TYPE_SDR`: for Software Defined Radio tuners
- `VFL_TYPE_TOUCH`: for touch sensors
- `VFL_TYPE_MAX`: number of VFL types, must always be last in the enum

#### <a id="c-enum-vfl_devnode_direction"></a>`enum vfl_devnode_direction`

Identifies if a [`struct video_device`](#c-struct-video_device) corresponds to a receiver, a transmitter or a mem-to-mem device.

**Constants**

- `VFL_DIR_RX`: device is a receiver.
- `VFL_DIR_TX`: device is a transmitter.
- `VFL_DIR_M2M`: device is a memory to memory device.

**Note**

Ignored if [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type) is `VFL_TYPE_SUBDEV`.

#### <a id="c-enum-v4l2_video_device_flags"></a>`enum v4l2_video_device_flags`

Flags used by [`struct video_device`](#c-struct-video_device)

**Constants**

- `V4L2_FL_REGISTERED`: indicates that a [`struct video_device`](#c-struct-video_device) is registered.
  Drivers can clear this flag if they want to block all future
  device access. It is cleared by video_unregister_device.
- `V4L2_FL_USES_V4L2_FH`: indicates that file->private_data points to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh).
  This flag is set by the core when [`v4l2_fh_init()`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-v4l2_fh_init) is called.
  All drivers must use it.
- `V4L2_FL_QUIRK_INVERTED_CROP`: some old M2M drivers use g/s_crop/cropcap incorrectly: crop and
  compose are swapped. If this flag is set, then the selection
  targets are swapped in the g/s_crop/cropcap functions in v4l2-ioctl.c.
  This allows those drivers to correctly implement the selection API,
  but the old crop API will still work as expected in order to preserve
  backwards compatibility.
  Never set this flag for new drivers.
- `V4L2_FL_SUBDEV_RO_DEVNODE`: indicates that the video device node is registered in read-only mode.
  The flag only applies to device nodes registered for sub-devices, it is
  set by the core when the sub-devices device nodes are registered with
  [`v4l2_device_register_ro_subdev_nodes()`](/kernel/hardware/driver-api/media/v4l2-device.md#c-v4l2_device_register_ro_subdev_nodes) and used by the sub-device ioctl
  handler to restrict access to some ioctl calls.

#### <a id="c-struct-v4l2_prio_state"></a>`struct v4l2_prio_state`

stores the priority states

**Definition**

```c
struct v4l2_prio_state {
    atomic_t prios[4];
};
```

**Members**

- `prios`: array with elements to store the array priorities

**Description**

> [!NOTE]
> The size of **prios** array matches the number of priority types defined
> by enum `v4l2_priority`.

#### <a id="c-v4l2_prio_init"></a>`v4l2_prio_init()`

```c
void v4l2_prio_init(struct v4l2_prio_state *global)
```

initializes a struct v4l2_prio_state

**Parameters**

- `struct v4l2_prio_state *global`: pointer to [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state)

#### <a id="c-v4l2_prio_change"></a>`v4l2_prio_change()`

```c
int v4l2_prio_change(struct v4l2_prio_state *global, enum v4l2_priority *local, enum v4l2_priority new)
```

changes the v4l2 file handler priority

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.
- `enum v4l2_priority *local`: pointer to the desired priority, as defined by enum `v4l2_priority`
- `enum v4l2_priority new`: Priority type requested, as defined by enum `v4l2_priority`.

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-v4l2_prio_open"></a>`v4l2_prio_open()`

```c
void v4l2_prio_open(struct v4l2_prio_state *global, enum v4l2_priority *local)
```

Implements the priority logic for a file handler open

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.
- `enum v4l2_priority *local`: pointer to the desired priority, as defined by enum `v4l2_priority`

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-v4l2_prio_close"></a>`v4l2_prio_close()`

```c
void v4l2_prio_close(struct v4l2_prio_state *global, enum v4l2_priority local)
```

Implements the priority logic for a file handler close

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.
- `enum v4l2_priority local`: priority to be released, as defined by enum `v4l2_priority`

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-v4l2_prio_max"></a>`v4l2_prio_max()`

```c
enum v4l2_priority v4l2_prio_max(struct v4l2_prio_state *global)
```

Return the maximum priority, as stored at the **global** array.

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-v4l2_prio_check"></a>`v4l2_prio_check()`

```c
int v4l2_prio_check(struct v4l2_prio_state *global, enum v4l2_priority local)
```

Implements the priority logic for a file handler close

**Parameters**

- `struct v4l2_prio_state *global`: pointer to the [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) of the device node.
- `enum v4l2_priority local`: desired priority, as defined by enum `v4l2_priority` local

**Description**

> [!NOTE]
> This function should be used only by the V4L2 core.

#### <a id="c-struct-v4l2_file_operations"></a>`struct v4l2_file_operations`

fs operations used by a V4L2 device

**Definition**

```c
struct v4l2_file_operations {
        struct module *owner;
        ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
        ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
        __poll_t (*poll) (struct file *, struct poll_table_struct *);
        long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
    #ifdef CONFIG_COMPAT;
        long (*compat_ioctl32) (struct file *, unsigned int, unsigned long);
    #endif;
        unsigned long (*get_unmapped_area) (struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
        int (*mmap) (struct file *, struct vm_area_struct *);
        int (*open) (struct file *);
        int (*release) (struct file *);
};
```

**Members**

- `owner`: pointer to struct module
- `read`: operations needed to implement the `read()` syscall
- `write`: operations needed to implement the `write()` syscall
- `poll`: operations needed to implement the `poll()` syscall
- `unlocked_ioctl`: operations needed to implement the `ioctl()` syscall
- `compat_ioctl32`: operations needed to implement the `ioctl()` syscall for
  the special case where the Kernel uses 64 bits instructions, but
  the userspace uses 32 bits.
- `get_unmapped_area`: called by the `mmap()` syscall, used when %!CONFIG_MMU
- `mmap`: operations needed to implement the `mmap()` syscall
- `open`: operations needed to implement the `open()` syscall
- `release`: operations needed to implement the `release()` syscall

**Description**

> [!NOTE]
> Those operations are used to implemente the fs struct file_operations
> at the V4L2 drivers. The V4L2 core overrides the fs ops with some
> extra logic needed by the subsystem.

#### <a id="c-struct-video_device"></a>`struct video_device`

Structure used to create and manage the V4L2 device nodes.

**Definition**

```c
struct video_device {
    #if defined(CONFIG_MEDIA_CONTROLLER);
        struct media_entity entity;
        struct media_intf_devnode *intf_devnode;
        struct media_pipeline pipe;
    #endif;
        const struct v4l2_file_operations *fops;
        u32 device_caps;
        struct device dev;
        struct cdev *cdev;
        struct v4l2_device *v4l2_dev;
        struct device *dev_parent;
        struct v4l2_ctrl_handler *ctrl_handler;
        struct vb2_queue *queue;
        struct v4l2_prio_state *prio;
        char name[64];
        enum vfl_devnode_type vfl_type;
        enum vfl_devnode_direction vfl_dir;
        int minor;
        u16 num;
        unsigned long flags;
        int index;
        spinlock_t fh_lock;
        struct list_head        fh_list;
        int dev_debug;
        v4l2_std_id tvnorms;
        void (*release)(struct video_device *vdev);
        const struct v4l2_ioctl_ops *ioctl_ops;
        unsigned long valid_ioctls[BITS_TO_LONGS(BASE_VIDIOC_PRIVATE)];
        struct mutex *lock;
};
```

**Members**

- `entity`: [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity)
- `intf_devnode`: pointer to [`struct media_intf_devnode`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_intf_devnode)
- `pipe`: [`struct media_pipeline`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_pipeline)
- `fops`: pointer to [`struct v4l2_file_operations`](#c-struct-v4l2_file_operations) for the video device
- `device_caps`: device capabilities as used in v4l2_capabilities
- `dev`: [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) for the video device
- `cdev`: character device
- `v4l2_dev`: pointer to [`struct v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device) parent
- `dev_parent`: pointer to [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) parent
- `ctrl_handler`: Control handler associated with this device node.
  May be NULL.
- `queue`: [`struct vb2_queue`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_queue) associated with this device node. May be NULL.
- `prio`: pointer to [`struct v4l2_prio_state`](#c-struct-v4l2_prio_state) with device's Priority state.
  If NULL, then v4l2_dev->prio will be used.
- `name`: video device name
- `vfl_type`: V4L device type, as defined by [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type)
- `vfl_dir`: V4L receiver, transmitter or m2m
- `minor`: device node 'minor'. It is set to -1 if the registration failed
- `num`: number of the video device node
- `flags`: video device flags. Use bitops to set/clear/test flags.
  Contains a set of [`enum v4l2_video_device_flags`](#c-enum-v4l2_video_device_flags).
- `index`: attribute to differentiate multiple indices on one physical device
- `fh_lock`: Lock for all v4l2_fhs
- `fh_list`: List of [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `dev_debug`: Internal device debug flags, not for use by drivers
- `tvnorms`: Supported tv norms
- `release`: video device `release()` callback
- `ioctl_ops`: pointer to [`struct v4l2_ioctl_ops`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) with ioctl callbacks
- `valid_ioctls`: bitmap with the valid ioctls for this device
- `lock`: pointer to `struct mutex` serialization lock

**Description**

> [!NOTE]
> Only set **dev_parent** if that can't be deduced from **v4l2_dev**.

#### <a id="c-media_entity_to_video_device"></a>`media_entity_to_video_device()`

```c
media_entity_to_video_device(__entity)
```

Returns a [`struct video_device`](#c-struct-video_device) from the [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity) embedded on it.

**Parameters**

- `__entity`: pointer to [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity), may be NULL

#### <a id="c-to_video_device"></a>`to_video_device()`

```c
to_video_device(cd)
```

Returns a [`struct video_device`](#c-struct-video_device) from the [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) embedded on it.

**Parameters**

- `cd`: pointer to [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device)

#### <a id="c-__video_register_device"></a>`__video_register_device()`

```c
int __video_register_device(struct video_device *vdev, enum vfl_devnode_type type, int nr, int warn_if_nr_in_use, struct module *owner)
```

register video4linux devices

**Parameters**

- `struct video_device *vdev`: struct video_device to register
- `enum vfl_devnode_type type`: type of device to register, as defined by [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type)
- `int nr`: which device node number is desired:
  (0 == /dev/video0, 1 == /dev/video1, ..., -1 == first free)
- `int warn_if_nr_in_use`: warn if the desired device node number
  was already in use and another number was chosen instead.
- `struct module *owner`: module that owns the video device node

**Description**

The registration code assigns minor numbers and device node numbers
based on the requested type and registers the new device node with
the kernel.

This function assumes that struct video_device was zeroed when it
was allocated and does not contain any stale date.

An error is returned if no free minor or device node number could be
found, or if the registration of the device node failed.

Returns 0 on success.

> [!NOTE]
> This function is meant to be used only inside the V4L2 core.
> Drivers should use [`video_register_device()`](#c-video_register_device) or
> [`video_register_device_no_warn()`](#c-video_register_device_no_warn).

#### <a id="c-video_register_device"></a>`video_register_device()`

```c
int video_register_device(struct video_device *vdev, enum vfl_devnode_type type, int nr)
```

register video4linux devices

**Parameters**

- `struct video_device *vdev`: struct video_device to register
- `enum vfl_devnode_type type`: type of device to register, as defined by [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type)
- `int nr`: which device node number is desired:
  (0 == /dev/video0, 1 == /dev/video1, ..., -1 == first free)

**Description**

Internally, it calls [`__video_register_device()`](#c-__video_register_device). Please see its
documentation for more details.

> [!NOTE]
> if video_register_device fails, the `release()` callback of
> [`struct video_device`](#c-struct-video_device) structure is *not* called, so the caller
> is responsible for freeing any data. Usually that means that
> you [`video_device_release()`](#c-video_device_release) should be called on failure.

#### <a id="c-video_register_device_no_warn"></a>`video_register_device_no_warn()`

```c
int video_register_device_no_warn(struct video_device *vdev, enum vfl_devnode_type type, int nr)
```

register video4linux devices

**Parameters**

- `struct video_device *vdev`: struct video_device to register
- `enum vfl_devnode_type type`: type of device to register, as defined by [`enum vfl_devnode_type`](#c-enum-vfl_devnode_type)
- `int nr`: which device node number is desired:
  (0 == /dev/video0, 1 == /dev/video1, ..., -1 == first free)

**Description**

This function is identical to [`video_register_device()`](#c-video_register_device) except that no
warning is issued if the desired device node number was already in use.

Internally, it calls [`__video_register_device()`](#c-__video_register_device). Please see its
documentation for more details.

> [!NOTE]
> if video_register_device fails, the `release()` callback of
> [`struct video_device`](#c-struct-video_device) structure is *not* called, so the caller
> is responsible for freeing any data. Usually that means that
> you [`video_device_release()`](#c-video_device_release) should be called on failure.

#### <a id="c-video_unregister_device"></a>`video_unregister_device()`

```c
void video_unregister_device(struct video_device *vdev)
```

Unregister video devices.

**Parameters**

- `struct video_device *vdev`: [`struct video_device`](#c-struct-video_device) to register

**Description**

Does nothing if vdev == NULL or if [`video_is_registered()`](#c-video_is_registered) returns false.

#### <a id="c-video_device_alloc"></a>`video_device_alloc()`

```c
struct video_device * video_device_alloc(void)
```

helper function to alloc [`struct video_device`](#c-struct-video_device)

**Parameters**

- `void`: no arguments

**Description**

Returns NULL if `-ENOMEM` or a [`struct video_device`](#c-struct-video_device) on success.

#### <a id="c-video_device_release"></a>`video_device_release()`

```c
void video_device_release(struct video_device *vdev)
```

helper function to release [`struct video_device`](#c-struct-video_device)

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

**Description**

Can also be used for video_device->release\(\).

#### <a id="c-video_device_release_empty"></a>`video_device_release_empty()`

```c
void video_device_release_empty(struct video_device *vdev)
```

helper function to implement the video_device->release\(\) callback.

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

**Description**

This release function does nothing.

It should be used when the video_device is a static global struct.

> [!NOTE]
> Having a static video_device is a dubious construction at best.

#### <a id="c-v4l2_disable_ioctl"></a>`v4l2_disable_ioctl()`

```c
void v4l2_disable_ioctl(struct video_device *vdev, unsigned int cmd)
```

mark that a given command isn't implemented. shouldn't use core locking

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)
- `unsigned int cmd`: ioctl command

**Description**

This function allows drivers to provide just one v4l2_ioctl_ops struct, but
disable ioctls based on the specific card that is actually found.

> [!NOTE]
> This must be called before video_register_device.
> See also the comments for `determine_valid_ioctls()`.

#### <a id="c-video_get_drvdata"></a>`video_get_drvdata()`

```c
void * video_get_drvdata(struct video_device *vdev)
```

gets private data from [`struct video_device`](#c-struct-video_device).

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

**Description**

returns a pointer to the private data

#### <a id="c-video_set_drvdata"></a>`video_set_drvdata()`

```c
void video_set_drvdata(struct video_device *vdev, void *data)
```

sets private data from [`struct video_device`](#c-struct-video_device).

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)
- `void *data`: private data pointer

#### <a id="c-video_devdata"></a>`video_devdata()`

```c
struct video_device * video_devdata(struct file *file)
```

gets [`struct video_device`](#c-struct-video_device) from struct file.

**Parameters**

- `struct file *file`: pointer to struct file

#### <a id="c-video_drvdata"></a>`video_drvdata()`

```c
void * video_drvdata(struct file *file)
```

gets private data from [`struct video_device`](#c-struct-video_device) using the struct file.

**Parameters**

- `struct file *file`: pointer to struct file

**Description**

This is function combines both [`video_get_drvdata()`](#c-video_get_drvdata) and [`video_devdata()`](#c-video_devdata)
as this is used very often.

#### <a id="c-video_device_node_name"></a>`video_device_node_name()`

```c
const char * video_device_node_name(struct video_device *vdev)
```

returns the video device name

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

**Description**

Returns the device name string

#### <a id="c-video_is_registered"></a>`video_is_registered()`

```c
int video_is_registered(struct video_device *vdev)
```

returns true if the [`struct video_device`](#c-struct-video_device) is registered.

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](#c-struct-video_device)

#### <a id="c-v4l2_debugfs_root"></a>`v4l2_debugfs_root()`

```c
struct dentry * v4l2_debugfs_root(void)
```

returns the dentry of the top-level "v4l2" debugfs dir

**Parameters**

- `void`: no arguments

**Description**

If this directory does not yet exist, then it will be created.

#### <a id="c-video_device_pipeline_start"></a>`video_device_pipeline_start()`

```c
int video_device_pipeline_start(struct video_device *vdev, struct media_pipeline *pipe)
```

Mark a pipeline as streaming

**Parameters**

- `struct video_device *vdev`: Starting video device
- `struct media_pipeline *pipe`: Media pipeline to be assigned to all entities in the pipeline.

**Description**

Mark all entities connected to a given video device through enabled links,
either directly or indirectly, as streaming. The given pipeline object is
assigned to every pad in the pipeline and stored in the media_pad pipe
field.

Calls to this function can be nested, in which case the same number of
[`video_device_pipeline_stop()`](#c-video_device_pipeline_stop) calls will be required to stop streaming. The
pipeline pointer must be identical for all nested calls to
[`video_device_pipeline_start()`](#c-video_device_pipeline_start).

The video device must contain a single pad.

This is a convenience wrapper around [`media_pipeline_start()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_pipeline_start).

#### <a id="c-__video_device_pipeline_start"></a>`__video_device_pipeline_start()`

```c
int __video_device_pipeline_start(struct video_device *vdev, struct media_pipeline *pipe)
```

Mark a pipeline as streaming

**Parameters**

- `struct video_device *vdev`: Starting video device
- `struct media_pipeline *pipe`: Media pipeline to be assigned to all entities in the pipeline.

**Description**

..note:: This is the non-locking version of [`video_device_pipeline_start()`](#c-video_device_pipeline_start)

The video device must contain a single pad.

This is a convenience wrapper around [`__media_pipeline_start()`](/kernel/hardware/driver-api/media/mc-core.md#c-__media_pipeline_start).

#### <a id="c-video_device_pipeline_stop"></a>`video_device_pipeline_stop()`

```c
void video_device_pipeline_stop(struct video_device *vdev)
```

Mark a pipeline as not streaming

**Parameters**

- `struct video_device *vdev`: Starting video device

**Description**

Mark all entities connected to a given video device through enabled links,
either directly or indirectly, as not streaming. The media_pad pipe field
is reset to `NULL`.

If multiple calls to [`media_pipeline_start()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_pipeline_start) have been made, the same
number of calls to this function are required to mark the pipeline as not
streaming.

The video device must contain a single pad.

This is a convenience wrapper around [`media_pipeline_stop()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_pipeline_stop).

#### <a id="c-__video_device_pipeline_stop"></a>`__video_device_pipeline_stop()`

```c
void __video_device_pipeline_stop(struct video_device *vdev)
```

Mark a pipeline as not streaming

**Parameters**

- `struct video_device *vdev`: Starting video device

**Description**

> [!NOTE]
> This is the non-locking version of [`media_pipeline_stop()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_pipeline_stop)

The video device must contain a single pad.

This is a convenience wrapper around [`__media_pipeline_stop()`](/kernel/hardware/driver-api/media/mc-core.md#c-__media_pipeline_stop).

#### <a id="c-video_device_pipeline_alloc_start"></a>`video_device_pipeline_alloc_start()`

```c
int video_device_pipeline_alloc_start(struct video_device *vdev)
```

Mark a pipeline as streaming

**Parameters**

- `struct video_device *vdev`: Starting video device

**Description**

[`video_device_pipeline_alloc_start()`](#c-video_device_pipeline_alloc_start) is similar to [`video_device_pipeline_start()`](#c-video_device_pipeline_start)
but instead of working on a given pipeline the function will use an
existing pipeline if the video device is already part of a pipeline, or
allocate a new pipeline.

Calls to [`video_device_pipeline_alloc_start()`](#c-video_device_pipeline_alloc_start) must be matched with
[`video_device_pipeline_stop()`](#c-video_device_pipeline_stop).

#### <a id="c-video_device_pipeline"></a>`video_device_pipeline()`

```c
struct media_pipeline * video_device_pipeline(struct video_device *vdev)
```

Get the media pipeline a video device is part of

**Parameters**

- `struct video_device *vdev`: The video device

**Description**

This function returns the media pipeline that a video device has been
associated with when constructing the pipeline with
[`video_device_pipeline_start()`](#c-video_device_pipeline_start). The pointer remains valid until
[`video_device_pipeline_stop()`](#c-video_device_pipeline_stop) is called.

The video device must contain a single pad.

This is a convenience wrapper around [`media_entity_pipeline()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_entity_pipeline).

**Return**

The media_pipeline the video device is part of, or NULL if the video
device is not part of any pipeline.

---

# V4L2 device instance

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Each device instance is represented by a struct v4l2_device. Very simple devices can just allocate this struct, but most of the time you would embed this struct inside a larger struct.

<a id="rst-v4l2-device-instance"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Each device instance is represented by a struct v4l2_device. Very simple devices can just allocate this struct, but most of the time you would embed this struct inside a larger struct.

You must register the device instance by calling:

> `v4l2_device_register <v4l2_device_register>()` (dev, `v4l2_dev <v4l2_device>`).

Registration will initialize the `v4l2_device` struct. If the dev-&gt;driver_data field is `NULL`, it will be linked to `v4l2_dev <v4l2_device>` argument.

Drivers that want integration with the media device framework need to set dev-&gt;driver_data manually to point to the driver-specific device structure that embed the struct v4l2_device instance. This is achieved by a `dev_set_drvdata()` call before registering the V4L2 device instance. They must also set the struct v4l2_device mdev field to point to a properly initialized and registered `media_device` instance.

If `v4l2_dev <v4l2_device>`-&gt;name is empty then it will be set to a value derived from dev (driver name followed by the bus_id, to be precise). If you set it up before  calling `v4l2_device_register()` then it will be untouched. If dev is `NULL`, then you **must** setup `v4l2_dev <v4l2_device>`-&gt;name before calling `v4l2_device_register()`.

You can use `v4l2_device_set_name()` to set the name based on a driver name and a driver-global atomic_t instance. This will generate names like `ivtv0`, `ivtv1`, etc. If the name ends with a digit, then it will insert a dash: `cx18-0`, `cx18-1`, etc. This function returns the instance number.

The first `dev` argument is normally the `struct device` pointer of a `pci_dev`, `usb_interface` or `platform_device`. It is rare for dev to be `NULL`, but it happens with ISA devices or when one device creates multiple PCI devices, thus making it impossible to associate `v4l2_dev <v4l2_device>` with a particular parent.

You can also supply a `notify()` callback that can be called by sub-devices to notify you of events. Whether you need to set this depends on the sub-device. Any notifications a sub-device supports must be defined in a header in `include/media/subdevice.h`.

V4L2 devices are unregistered by calling:

> `v4l2_device_unregister()` (`v4l2_dev <v4l2_device>`).

If the dev-&gt;driver_data field points to `v4l2_dev <v4l2_device>`, it will be reset to `NULL`. Unregistering will also automatically unregister all subdevs from the device.

If you have a hotpluggable device (e.g. a USB device), then when a disconnect happens the parent device becomes invalid. Since `v4l2_device` has a pointer to that parent device it has to be cleared as well to mark that the parent is gone. To do this call:

> `v4l2_device_disconnect()` (`v4l2_dev <v4l2_device>`).

This does *not* unregister the subdevs, so you still need to call the `v4l2_device_unregister()` function for that. If your driver is not hotpluggable, then there is no need to call `v4l2_device_disconnect()`.

Sometimes you need to iterate over all devices registered by a specific driver. This is usually the case if multiple device drivers use the same hardware. E.g. the ivtvfb driver is a framebuffer driver that uses the ivtv hardware. The same is true for alsa drivers for example.

You can iterate over all registered devices as follows:



```c
static int callback(struct device *dev, void *p)
{
        struct v4l2_device *v4l2_dev = dev_get_drvdata(dev);

        /* test if this device was inited */
        if (v4l2_dev == NULL)
                return 0;
        ...
        return 0;
}

int iterate(void *p)
{
        struct device_driver *drv;
        int err;

        /* Find driver 'ivtv' on the PCI bus.
        pci_bus_type is a global. For USB buses use usb_bus_type. */
        drv = driver_find("ivtv", &pci_bus_type);
        /* iterate over all ivtv device instances */
        err = driver_for_each_device(drv, NULL, p, callback);
        put_driver(drv);
        return err;
}
```

Sometimes you need to keep a running counter of the device instance. This is commonly used to map a device instance to an index of a module option array.

The recommended approach is as follows:



```c
static atomic_t drv_instance = ATOMIC_INIT(0);

static int drv_probe(struct pci_dev *pdev, const struct pci_device_id *pci_id)
{
        ...
        state->instance = atomic_inc_return(&drv_instance) - 1;
}
```

If you have multiple device nodes then it can be difficult to know when it is safe to unregister `v4l2_device` for hotpluggable devices. For this purpose `v4l2_device` has refcounting support. The refcount is increased whenever `video_register_device()` is called and it is decreased whenever that device node is released. When the refcount reaches zero, then the `v4l2_device` release() callback is called. You can do your final cleanup there.

If other device nodes (e.g. ALSA) are created, then you can increase and decrease the refcount manually as well by calling:

> `v4l2_device_get()` (`v4l2_dev <v4l2_device>`).

or:

> `v4l2_device_put()` (`v4l2_dev <v4l2_device>`).

Since the initial refcount is 1 you also need to call `v4l2_device_put()` in the `disconnect()` callback (for USB devices) or in the `remove()` callback (for e.g. PCI devices), otherwise the refcount will never reach 0.

<a id="rst-v4l2-device-functions-and-data-structures"></a>

## v4l2_device functions and data structures


#### <a id="c-struct-v4l2_device"></a>`struct v4l2_device`

main struct to for V4L2 device drivers

**Definition**

```c
struct v4l2_device {
    struct device *dev;
    struct media_device *mdev;
    struct list_head subdevs;
    spinlock_t lock;
    char name[36];
    void (*notify)(struct v4l2_subdev *sd, unsigned int notification, void *arg);
    struct v4l2_ctrl_handler *ctrl_handler;
    struct v4l2_prio_state prio;
    struct kref ref;
    void (*release)(struct v4l2_device *v4l2_dev);
};
```

**Members**

- `dev`: pointer to struct device.
- `mdev`: pointer to struct media_device, may be NULL.
- `subdevs`: used to keep track of the registered subdevs
- `lock`: lock this struct; can be used by the driver as well
  if this struct is embedded into a larger struct.
- `name`: unique device name, by default the driver name + bus ID
- `notify`: notify operation called by some sub-devices.
- `ctrl_handler`: The control handler. May be `NULL`.
- `prio`: Device's priority state
- `ref`: Keep track of the references to this struct.
- `release`: Release function that is called when the ref count
  goes to 0.

**Description**

Each instance of a V4L2 device should create the v4l2_device struct,
either stand-alone or embedded in a larger struct.

It allows easy access to sub-devices (see v4l2-subdev.h) and provides
basic V4L2 device-level support.

> [!NOTE]
> \#) **dev->driver_data** points to this struct.
> \#) **dev** might be `NULL` if there is no parent device

#### <a id="c-v4l2_device_get"></a>`v4l2_device_get()`

```c
void v4l2_device_get(struct v4l2_device *v4l2_dev)
```

gets a V4L2 device reference

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)

**Description**

This is an ancillary routine meant to increment the usage for the
struct [`v4l2_device`](#c-struct-v4l2_device) pointed by **v4l2_dev**.

#### <a id="c-v4l2_device_put"></a>`v4l2_device_put()`

```c
int v4l2_device_put(struct v4l2_device *v4l2_dev)
```

puts a V4L2 device reference

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)

**Description**

This is an ancillary routine meant to decrement the usage for the
struct [`v4l2_device`](#c-struct-v4l2_device) pointed by **v4l2_dev**.

#### <a id="c-v4l2_device_register"></a>`v4l2_device_register()`

```c
int v4l2_device_register(struct device *dev, struct v4l2_device *v4l2_dev)
```

Initialize v4l2_dev and make **dev->driver_data** point to **v4l2_dev**.

**Parameters**

- `struct device *dev`: pointer to struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device)
- `struct v4l2_device *v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)

**Description**

> [!NOTE]
> **dev** may be `NULL` in rare cases (ISA devices).
> In such case the caller must fill in the **v4l2_dev->name** field
> before calling this function.

#### <a id="c-v4l2_device_set_name"></a>`v4l2_device_set_name()`

```c
int v4l2_device_set_name(struct v4l2_device *v4l2_dev, const char *basename, atomic_t *instance)
```

Optional function to initialize the name field of struct [`v4l2_device`](#c-struct-v4l2_device)

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)
- `const char *basename`: base name for the device name
- `atomic_t *instance`: pointer to a static atomic_t var with the instance usage for
  the device driver.

**Description**

[`v4l2_device_set_name()`](#c-v4l2_device_set_name) initializes the name field of struct [`v4l2_device`](#c-struct-v4l2_device)
using the driver name and a driver-global atomic_t instance.

This function will increment the instance counter and returns the
instance value used in the name.

**Example**

static atomic_t drv_instance = ATOMIC_INIT(0);

\...

instance = v4l2_device_set_name(&\ v4l2_dev, "foo", &\ drv_instance);

The first time this is called the name field will be set to foo0 and
this function returns 0. If the name ends with a digit (e.g. cx18),
then the name will be set to cx18-0 since cx180 would look really odd.

#### <a id="c-v4l2_device_disconnect"></a>`v4l2_device_disconnect()`

```c
void v4l2_device_disconnect(struct v4l2_device *v4l2_dev)
```

Change V4L2 device state to disconnected.

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

**Description**

Should be called when the USB parent disconnects.
Since the parent disappears, this ensures that **v4l2_dev** doesn't have
an invalid parent pointer.

> [!NOTE]
> This function sets **v4l2_dev->dev** to NULL.

#### <a id="c-v4l2_device_unregister"></a>`v4l2_device_unregister()`

```c
void v4l2_device_unregister(struct v4l2_device *v4l2_dev)
```

Unregister all sub-devices and any other resources related to **v4l2_dev**.

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

#### <a id="c-v4l2_device_register_subdev"></a>`v4l2_device_register_subdev()`

```c
v4l2_device_register_subdev(v4l2_dev, sd)
```

Registers a subdev with a v4l2 device.

**Parameters**

- `v4l2_dev`: pointer to struct [`v4l2_device`](#c-struct-v4l2_device)
- `sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

While registered, the subdev module is marked as in-use.

An error is returned if the module is no longer loaded on any attempts
to register it.

#### <a id="c-v4l2_device_unregister_subdev"></a>`v4l2_device_unregister_subdev()`

```c
void v4l2_device_unregister_subdev(struct v4l2_subdev *sd)
```

Unregisters a subdev with a v4l2 device.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

**Description**

#### <a id="c-__v4l2_device_register_subdev_nodes"></a>`__v4l2_device_register_subdev_nodes()`

```c
int __v4l2_device_register_subdev_nodes(struct v4l2_device *v4l2_dev, bool read_only)
```

Registers device nodes for all subdevs of the v4l2 device that are marked with the `V4L2_SUBDEV_FL_HAS_DEVNODE` flag.

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device
- `bool read_only`: subdevices read-only flag. True to register the subdevices
  device nodes in read-only mode, false to allow full access to the
  subdevice userspace API.

#### <a id="c-v4l2_device_register_subdev_nodes"></a>`v4l2_device_register_subdev_nodes()`

```c
int v4l2_device_register_subdev_nodes(struct v4l2_device *v4l2_dev)
```

Registers subdevices device nodes with unrestricted access to the subdevice userspace operations

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

**Description**

Internally calls [`__v4l2_device_register_subdev_nodes()`](#c-__v4l2_device_register_subdev_nodes). See its documentation
for more details.

#### <a id="c-v4l2_device_register_ro_subdev_nodes"></a>`v4l2_device_register_ro_subdev_nodes()`

```c
int v4l2_device_register_ro_subdev_nodes(struct v4l2_device *v4l2_dev)
```

Registers subdevices device nodes in read-only mode

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

**Description**

Internally calls [`__v4l2_device_register_subdev_nodes()`](#c-__v4l2_device_register_subdev_nodes). See its documentation
for more details.

#### <a id="c-v4l2_subdev_notify"></a>`v4l2_subdev_notify()`

```c
void v4l2_subdev_notify(struct v4l2_subdev *sd, unsigned int notification, void *arg)
```

Sends a notification to v4l2_device.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `unsigned int notification`: type of notification. Please notice that the notification
  type is driver-specific.
- `void *arg`: arguments for the notification. Those are specific to each
  notification type.

#### <a id="c-v4l2_device_supports_requests"></a>`v4l2_device_supports_requests()`

```c
bool v4l2_device_supports_requests(struct v4l2_device *v4l2_dev)
```

Test if requests are supported.

**Parameters**

- `struct v4l2_device *v4l2_dev`: pointer to struct v4l2_device

#### <a id="c-v4l2_device_for_each_subdev"></a>`v4l2_device_for_each_subdev()`

```c
v4l2_device_for_each_subdev(sd, v4l2_dev)
```

Helper macro that interates over all sub-devices of a given [`v4l2_device`](#c-struct-v4l2_device).

**Parameters**

- `sd`: pointer that will be filled by the macro with all
  [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer used as an iterator by the loop.
- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.

**Description**

This macro iterates over all sub-devices owned by the **v4l2_dev** device.
It acts as a for loop iterator and executes the next statement with
the **sd** variable pointing to each sub-device in turn.

#### <a id="c-__v4l2_device_call_subdevs_p"></a>`__v4l2_device_call_subdevs_p()`

```c
__v4l2_device_call_subdevs_p(v4l2_dev, sd, cond, o, f, args...)
```

Calls the specified operation for all subdevs matching the condition.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `sd`: pointer that will be filled by the macro with all
  [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) pointer used as an iterator by the loop.
- `cond`: condition to be match
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

Ignore any errors.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-__v4l2_device_call_subdevs"></a>`__v4l2_device_call_subdevs()`

```c
__v4l2_device_call_subdevs(v4l2_dev, cond, o, f, args...)
```

Calls the specified operation for all subdevs matching the condition.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `cond`: condition to be match
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

Ignore any errors.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-__v4l2_device_call_subdevs_until_err_p"></a>`__v4l2_device_call_subdevs_until_err_p()`

```c
__v4l2_device_call_subdevs_until_err_p(v4l2_dev, sd, cond, o, f, args...)
```

Calls the specified operation for all subdevs matching the condition.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `sd`: pointer that will be filled by the macro with all
  [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) sub-devices associated with **v4l2_dev**.
- `cond`: condition to be match
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

If the operation returns an error other than 0 or `-ENOIOCTLCMD`
for any subdevice, then abort and return with that error code, zero
otherwise.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-__v4l2_device_call_subdevs_until_err"></a>`__v4l2_device_call_subdevs_until_err()`

```c
__v4l2_device_call_subdevs_until_err(v4l2_dev, cond, o, f, args...)
```

Calls the specified operation for all subdevs matching the condition.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `cond`: condition to be match
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

If the operation returns an error other than 0 or `-ENOIOCTLCMD`
for any subdevice, then abort and return with that error code,
zero otherwise.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_call_all"></a>`v4l2_device_call_all()`

```c
v4l2_device_call_all(v4l2_dev, grpid, o, f, args...)
```

Calls the specified operation for all subdevs matching the [`v4l2_subdev.grp_id`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev), as assigned by the bridge driver.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpid`: [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id group ID to match.
  Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

Ignore any errors.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_call_until_err"></a>`v4l2_device_call_until_err()`

```c
v4l2_device_call_until_err(v4l2_dev, grpid, o, f, args...)
```

Calls the specified operation for all subdevs matching the [`v4l2_subdev.grp_id`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev), as assigned by the bridge driver, until an error occurs.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpid`: [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id group ID to match.
  Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

If the operation returns an error other than 0 or `-ENOIOCTLCMD`
for any subdevice, then abort and return with that error code,
zero otherwise.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_mask_call_all"></a>`v4l2_device_mask_call_all()`

```c
v4l2_device_mask_call_all(v4l2_dev, grpmsk, o, f, args...)
```

Calls the specified operation for all subdevices where a group ID matches a specified bitmask.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpmsk`: bitmask to be checked against [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id
  group ID to be matched. Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

Ignore any errors.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_mask_call_until_err"></a>`v4l2_device_mask_call_until_err()`

```c
v4l2_device_mask_call_until_err(v4l2_dev, grpmsk, o, f, args...)
```

Calls the specified operation for all subdevices where a group ID matches a specified bitmask.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpmsk`: bitmask to be checked against [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id
  group ID to be matched. Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

If the operation returns an error other than 0 or `-ENOIOCTLCMD`
for any subdevice, then abort and return with that error code,
zero otherwise.

**Note**

subdevs cannot be added or deleted while walking
the subdevs list.

#### <a id="c-v4l2_device_has_op"></a>`v4l2_device_has_op()`

```c
v4l2_device_has_op(v4l2_dev, grpid, o, f)
```

checks if any subdev with matching grpid has a given ops.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpid`: [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id group ID to match.
  Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).

#### <a id="c-v4l2_device_mask_has_op"></a>`v4l2_device_mask_has_op()`

```c
v4l2_device_mask_has_op(v4l2_dev, grpmsk, o, f)
```

checks if any subdev with matching group mask has a given ops.

**Parameters**

- `v4l2_dev`: [`struct v4l2_device`](#c-struct-v4l2_device) owning the sub-devices to iterate over.
- `grpmsk`: bitmask to be checked against [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)->grp_id
  group ID to be matched. Use 0 to match them all.
- `o`: name of the element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of operations functions.
- `f`: operation function that will be called if **cond** matches.
  The operation functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_ops).

---

# V4L2 DV Timings functions

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 DV Timings functions.

<a id="rst-v4l2-dv-timings-functions"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-v4l2_calc_timeperframe"></a>`v4l2_calc_timeperframe()`

```c
struct v4l2_fract v4l2_calc_timeperframe(const struct v4l2_dv_timings *t)
```

helper function to calculate timeperframe based v4l2_dv_timings fields.

**Parameters**

- `const struct v4l2_dv_timings *t`: Timings for the video mode.

**Description**

Calculates the expected timeperframe using the pixel clock value and
horizontal/vertical measures. This means that v4l2_dv_timings structure
must be correctly and fully filled.

#### <a id="c-v4l2_check_dv_timings_fnc"></a>`v4l2_check_dv_timings_fnc()`

```c
typedef bool v4l2_check_dv_timings_fnc(const struct v4l2_dv_timings *t, void *handle)
```

timings check callback

**Parameters**

- `const struct v4l2_dv_timings *t`: the v4l2_dv_timings struct.
- `void *handle`: a handle from the driver.

**Description**

Returns true if the given timings are valid.

#### <a id="c-v4l2_valid_dv_timings"></a>`v4l2_valid_dv_timings()`

```c
bool v4l2_valid_dv_timings(const struct v4l2_dv_timings *t, const struct v4l2_dv_timings_cap *cap, v4l2_check_dv_timings_fnc fnc, void *fnc_handle)
```

are these timings valid?

**Parameters**

- `const struct v4l2_dv_timings *t`: the v4l2_dv_timings struct.
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `v4l2_check_dv_timings_fnc fnc`: callback to check if this timing is OK. May be NULL.
- `void *fnc_handle`: a handle that is passed on to **fnc**.

**Description**

Returns true if the given dv_timings struct is supported by the
hardware capabilities and the callback function (if non-NULL), returns
false otherwise.

#### <a id="c-v4l2_enum_dv_timings_cap"></a>`v4l2_enum_dv_timings_cap()`

```c
int v4l2_enum_dv_timings_cap(struct v4l2_enum_dv_timings *t, const struct v4l2_dv_timings_cap *cap, v4l2_check_dv_timings_fnc fnc, void *fnc_handle)
```

Helper function to enumerate possible DV timings based on capabilities

**Parameters**

- `struct v4l2_enum_dv_timings *t`: the v4l2_enum_dv_timings struct.
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `v4l2_check_dv_timings_fnc fnc`: callback to check if this timing is OK. May be NULL.
- `void *fnc_handle`: a handle that is passed on to **fnc**.

**Description**

This enumerates dv_timings using the full list of possible CEA-861 and DMT
timings, filtering out any timings that are not supported based on the
hardware capabilities and the callback function (if non-NULL).

If a valid timing for the given index is found, it will fill in **t** and
return 0, otherwise it returns -EINVAL.

#### <a id="c-v4l2_find_dv_timings_cap"></a>`v4l2_find_dv_timings_cap()`

```c
bool v4l2_find_dv_timings_cap(struct v4l2_dv_timings *t, const struct v4l2_dv_timings_cap *cap, unsigned pclock_delta, v4l2_check_dv_timings_fnc fnc, void *fnc_handle)
```

Find the closest timings struct

**Parameters**

- `struct v4l2_dv_timings *t`: the v4l2_enum_dv_timings struct.
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `unsigned pclock_delta`: maximum delta between t->pixelclock and the timing struct
  under consideration.
- `v4l2_check_dv_timings_fnc fnc`: callback to check if a given timings struct is OK. May be NULL.
- `void *fnc_handle`: a handle that is passed on to **fnc**.

**Description**

This function tries to map the given timings to an entry in the
full list of possible CEA-861 and DMT timings, filtering out any timings
that are not supported based on the hardware capabilities and the callback
function (if non-NULL).

On success it will fill in **t** with the found timings and it returns true.
On failure it will return false.

#### <a id="c-v4l2_find_dv_timings_cea861_vic"></a>`v4l2_find_dv_timings_cea861_vic()`

```c
bool v4l2_find_dv_timings_cea861_vic(struct v4l2_dv_timings *t, u8 vic)
```

find timings based on CEA-861 VIC

**Parameters**

- `struct v4l2_dv_timings *t`: the timings data.
- `u8 vic`: CEA-861 VIC code

**Description**

On success it will fill in **t** with the found timings and it returns true.
On failure it will return false.

#### <a id="c-v4l2_match_dv_timings"></a>`v4l2_match_dv_timings()`

```c
bool v4l2_match_dv_timings(const struct v4l2_dv_timings *measured, const struct v4l2_dv_timings *standard, unsigned pclock_delta, bool match_reduced_fps)
```

do two timings match?

**Parameters**

- `const struct v4l2_dv_timings *measured`: the measured timings data.
- `const struct v4l2_dv_timings *standard`: the timings according to the standard.
- `unsigned pclock_delta`: maximum delta in Hz between standard->pixelclock and
  the measured timings.
- `bool match_reduced_fps`: if true, then fail if V4L2_DV_FL_REDUCED_FPS does not
  match.

**Description**

Returns true if the two timings match, returns false otherwise.

#### <a id="c-v4l2_print_dv_timings"></a>`v4l2_print_dv_timings()`

```c
void v4l2_print_dv_timings(const char *dev_prefix, const char *prefix, const struct v4l2_dv_timings *t, bool detailed)
```

log the contents of a dv_timings struct

**Parameters**

- `const char *dev_prefix`: device prefix for each log line.
- `const char *prefix`: additional prefix for each log line, may be NULL.
- `const struct v4l2_dv_timings *t`: the timings data.
- `bool detailed`: if true, give a detailed log.

#### <a id="c-v4l2_detect_cvt"></a>`v4l2_detect_cvt()`

```c
bool v4l2_detect_cvt(unsigned int frame_height, unsigned int hfreq, unsigned int vsync, unsigned int active_width, u32 polarities, bool interlaced, const struct v4l2_dv_timings_cap *cap, struct v4l2_dv_timings *fmt)
```

detect if the given timings follow the CVT standard

**Parameters**

- `unsigned int frame_height`: the total height of the frame (including blanking) in lines.
- `unsigned int hfreq`: the horizontal frequency in Hz.
- `unsigned int vsync`: the height of the vertical sync in lines.
- `unsigned int active_width`: active width of image (does not include blanking). This
  information is needed only in case of version 2 of reduced blanking.
  In other cases, this parameter does not have any effect on timings.
- `u32 polarities`: the horizontal and vertical polarities (same as struct
  v4l2_bt_timings polarities).
- `bool interlaced`: if this flag is true, it indicates interlaced format
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `struct v4l2_dv_timings *fmt`: the resulting timings.

**Description**

This function will attempt to detect if the given values correspond to a
valid CVT format. If so, then it will return true, and fmt will be filled
in with the found CVT timings.

#### <a id="c-v4l2_detect_gtf"></a>`v4l2_detect_gtf()`

```c
bool v4l2_detect_gtf(unsigned int frame_height, unsigned int hfreq, unsigned int vsync, u32 polarities, bool interlaced, struct v4l2_fract aspect, const struct v4l2_dv_timings_cap *cap, struct v4l2_dv_timings *fmt)
```

detect if the given timings follow the GTF standard

**Parameters**

- `unsigned int frame_height`: the total height of the frame (including blanking) in lines.
- `unsigned int hfreq`: the horizontal frequency in Hz.
- `unsigned int vsync`: the height of the vertical sync in lines.
- `u32 polarities`: the horizontal and vertical polarities (same as struct
  v4l2_bt_timings polarities).
- `bool interlaced`: if this flag is true, it indicates interlaced format
- `struct v4l2_fract aspect`: preferred aspect ratio. GTF has no method of determining the
  aspect ratio in order to derive the image width from the
  image height, so it has to be passed explicitly. Usually
  the native screen aspect ratio is used for this. If it
  is not filled in correctly, then 16:9 will be assumed.
- `const struct v4l2_dv_timings_cap *cap`: the v4l2_dv_timings_cap capabilities.
- `struct v4l2_dv_timings *fmt`: the resulting timings.

**Description**

This function will attempt to detect if the given values correspond to a
valid GTF format. If so, then it will return true, and fmt will be filled
in with the found GTF timings.

#### <a id="c-v4l2_calc_aspect_ratio"></a>`v4l2_calc_aspect_ratio()`

```c
struct v4l2_fract v4l2_calc_aspect_ratio(u8 hor_landscape, u8 vert_portrait)
```

calculate the aspect ratio based on bytes 0x15 and 0x16 from the EDID.

**Parameters**

- `u8 hor_landscape`: byte 0x15 from the EDID.
- `u8 vert_portrait`: byte 0x16 from the EDID.

**Description**

Determines the aspect ratio from the EDID.
See VESA Enhanced EDID standard, release A, rev 2, section 3.6.2:
"Horizontal and Vertical Screen Size or Aspect Ratio"

#### <a id="c-v4l2_dv_timings_aspect_ratio"></a>`v4l2_dv_timings_aspect_ratio()`

```c
struct v4l2_fract v4l2_dv_timings_aspect_ratio(const struct v4l2_dv_timings *t)
```

calculate the aspect ratio based on the v4l2_dv_timings information.

**Parameters**

- `const struct v4l2_dv_timings *t`: the timings data.

#### <a id="c-can_reduce_fps"></a>`can_reduce_fps()`

```c
bool can_reduce_fps(struct v4l2_bt_timings *bt)
```

check if conditions for reduced fps are true.

**Parameters**

- `struct v4l2_bt_timings *bt`: v4l2 timing structure

**Description**

For different timings reduced fps is allowed if the following conditions
are met:

- For CVT timings: if reduced blanking v2 (vsync == 8) is true.
- For CEA861 timings: if `V4L2_DV_FL_CAN_REDUCE_FPS` flag is true.

#### <a id="c-struct-v4l2_hdmi_colorimetry"></a>`struct v4l2_hdmi_colorimetry`

describes the HDMI colorimetry information

**Definition**

```c
struct v4l2_hdmi_colorimetry {
    enum v4l2_colorspace colorspace;
    enum v4l2_ycbcr_encoding ycbcr_enc;
    enum v4l2_quantization quantization;
    enum v4l2_xfer_func xfer_func;
};
```

**Members**

- `colorspace`: enum v4l2_colorspace, the colorspace
- `ycbcr_enc`: enum v4l2_ycbcr_encoding, Y'CbCr encoding
- `quantization`: enum v4l2_quantization, colorspace quantization
- `xfer_func`: enum v4l2_xfer_func, colorspace transfer function

---

# V4L2 events

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The V4L2 events provide a generic way to pass events to user space. The driver must use v4l2_fh to be able to support V4L2 events.

<a id="rst-v4l2-events"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The V4L2 events provide a generic way to pass events to user space. The driver must use `v4l2_fh` to be able to support V4L2 events.

Events are subscribed per-filehandle. An event specification consists of a `type` and is optionally associated with an object identified through the `id` field. If unused, then the `id` is 0. So an event is uniquely identified by the `(type, id)` tuple.

The `v4l2_fh` struct has a list of subscribed events on its `subscribed` field.

When the user subscribes to an event, a `v4l2_subscribed_event` struct is added to `v4l2_fh`<!-- -->`.subscribed`, one for every subscribed event.

Each `v4l2_subscribed_event` struct ends with a `v4l2_kevent` ringbuffer, with the size given by the caller of `v4l2_event_subscribe()`. This ringbuffer is used to store any events raised by the driver.

So every `(type, ID)` event tuple will have its own `v4l2_kevent` ringbuffer. This guarantees that if a driver is generating lots of events of one type in a short time, then that will not overwrite events of another type.

But if you get more events of one type than the size of the `v4l2_kevent` ringbuffer, then the oldest event will be dropped and the new one added.

The `v4l2_kevent` struct links into the `available` list of the `v4l2_fh` struct so [vidioc\_dqevent](</kernel/userspace/userspace-api/media-v4l/vidioc-dqevent.md#rst-vidioc-dqevent>) will know which event to dequeue first.

Finally, if the event subscription is associated with a particular object such as a V4L2 control, then that object needs to know about that as well so that an event can be raised by that object. So the `node` field can be used to link the `v4l2_subscribed_event` struct into a list of such objects.

So to summarize:

- struct v4l2\_fh has two lists: one of the `subscribed` events, and one of the `available` events.

- struct v4l2\_subscribed\_event has a ringbuffer of raised (pending) events of that particular type.

- If struct v4l2\_subscribed\_event is associated with a specific object, then that object will have an internal list of struct v4l2\_subscribed\_event so it knows who subscribed an event to that object.

Furthermore, the internal struct v4l2\_subscribed\_event has `merge()` and `replace()` callbacks which drivers can set. These callbacks are called when a new event is raised and there is no more room.

The `replace()` callback allows you to replace the payload of the old event with that of the new event, merging any relevant data from the old payload into the new payload that replaces it. It is called when this event type has a ringbuffer with size is one, i.e. only one event can be stored in the ringbuffer.

The `merge()` callback allows you to merge the oldest event payload into that of the second-oldest event payload. It is called when the ringbuffer has size is greater than one.

This way no status information is lost, just the intermediate steps leading up to that state.

A good example of these `replace`/`merge` callbacks is in v4l2-event.c: `ctrls_replace()` and `ctrls_merge()` callbacks for the control event.

> [!NOTE]
>
> these callbacks can be called from interrupt context, so they must be fast.

In order to queue events to video device, drivers should call:

> `v4l2_event_queue <v4l2_event_queue>()` (`vdev <video_device>`, `ev <v4l2_event>`)

The driver's only responsibility is to fill in the type and the data fields. The other fields will be filled in by V4L2.

<a id="rst-event-subscription"></a>

## Event subscription

Subscribing to an event is via:

> `v4l2_event_subscribe <v4l2_event_subscribe>()` (`fh <v4l2_fh>`, `sub <v4l2_event_subscription>` , elems, `ops <v4l2_subscribed_event_ops>`)

This function is used to implement `video_device`-&gt; `ioctl_ops <v4l2_ioctl_ops>`-&gt; `vidioc_subscribe_event`, but the driver must check first if the driver is able to produce events with specified event id, and then should call `v4l2_event_subscribe()` to subscribe the event.

The elems argument is the size of the event queue for this event. If it is 0, then the framework will fill in a default value (this depends on the event type).

The ops argument allows the driver to specify a number of callbacks:

<!-- tabularcolumns: |p{1.5cm}|p{16.0cm}| -->


<table>
<thead>
<tr>
<th>


Callback

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


add

</td>
<td>


called when a new listener gets added (subscribing to the same event twice will only cause this callback to get called once)

</td>
</tr>
<tr>
<td>


del

</td>
<td>


called when a listener stops listening

</td>
</tr>
<tr>
<td>


replace

</td>
<td>


replace event 'old' with event 'new'.

</td>
</tr>
<tr>
<td>


merge

</td>
<td>


merge event 'old' into event 'new'.

</td>
</tr>
</tbody>
</table>

All 4 callbacks are optional, if you don't want to specify any callbacks the ops argument itself maybe `NULL`.

<a id="rst-unsubscribing-an-event"></a>

## Unsubscribing an event

Unsubscribing to an event is via:

> `v4l2_event_unsubscribe <v4l2_event_unsubscribe>()` (`fh <v4l2_fh>`, `sub <v4l2_event_subscription>`)

This function is used to implement `video_device`-&gt; `ioctl_ops <v4l2_ioctl_ops>`-&gt; `vidioc_unsubscribe_event`. A driver may call `v4l2_event_unsubscribe()` directly unless it wants to be involved in unsubscription process.

The special type `V4L2_EVENT_ALL` may be used to unsubscribe all events. The drivers may want to handle this in a special way.

<a id="rst-check-if-there-s-a-pending-event"></a>

## Check if there's a pending event

Checking if there's a pending event is via:

> `v4l2_event_pending <v4l2_event_pending>()` (`fh <v4l2_fh>`)

This function returns the number of pending events. Useful when implementing poll.

<a id="rst-how-events-work"></a>

## How events work

Events are delivered to user space through the poll system call. The driver can use `v4l2_fh`-&gt;wait (a wait\_queue\_head\_t) as the argument for `poll_wait()`.

There are standard and private events. New standard events must use the smallest available event type. The drivers must allocate their events from their own class starting from class base. Class base is `V4L2_EVENT_PRIVATE_START` + n \* 1000 where n is the lowest available number. The first event type in the class is reserved for future use, so the first available event type is 'class base + 1'.

An example on how the V4L2 events may be used can be found in the OMAP 3 ISP driver (`drivers/media/platform/ti/omap3isp`).

A subdev can directly send an event to the `v4l2_device` notify function with `V4L2_DEVICE_NOTIFY_EVENT`. This allows the bridge to map the subdev that sends the event to the video node(s) associated with the subdev that need to be informed about such an event.

<a id="rst-v4l2-event-functions-and-data-structures"></a>

### V4L2 event functions and data structures


#### <a id="c-struct-v4l2_kevent"></a>`struct v4l2_kevent`

Internal kernel event struct.

**Definition**

```c
struct v4l2_kevent {
    struct list_head        list;
    struct v4l2_subscribed_event *sev;
    struct v4l2_event       event;
    u64 ts;
};
```

**Members**

- `list`: List node for the v4l2_fh->available list.
- `sev`: Pointer to parent v4l2_subscribed_event.
- `event`: The event itself.
- `ts`: The timestamp of the event.

#### <a id="c-struct-v4l2_subscribed_event_ops"></a>`struct v4l2_subscribed_event_ops`

Subscribed event operations.

**Definition**

```c
struct v4l2_subscribed_event_ops {
    int (*add)(struct v4l2_subscribed_event *sev, unsigned int elems);
    void (*del)(struct v4l2_subscribed_event *sev);
    void (*replace)(struct v4l2_event *old, const struct v4l2_event *new);
    void (*merge)(const struct v4l2_event *old, struct v4l2_event *new);
};
```

**Members**

- `add`: Optional callback, called when a new listener is added
- `del`: Optional callback, called when a listener stops listening
- `replace`: Optional callback that can replace event 'old' with event 'new'.
- `merge`: Optional callback that can merge event 'old' into event 'new'.

#### <a id="c-struct-v4l2_subscribed_event"></a>`struct v4l2_subscribed_event`

Internal struct representing a subscribed event.

**Definition**

```c
struct v4l2_subscribed_event {
    struct list_head        list;
    u32 type;
    u32 id;
    u32 flags;
    struct v4l2_fh          *fh;
    struct list_head        node;
    const struct v4l2_subscribed_event_ops *ops;
    unsigned int            elems;
    unsigned int            first;
    unsigned int            in_use;
    struct v4l2_kevent      events[] ;
};
```

**Members**

- `list`: List node for the v4l2_fh->subscribed list.
- `type`: Event type.
- `id`: Associated object ID (e.g. control ID). 0 if there isn't any.
- `flags`: Copy of v4l2_event_subscription->flags.
- `fh`: Filehandle that subscribed to this event.
- `node`: List node that hooks into the object's event list
  (if there is one).
- `ops`: v4l2_subscribed_event_ops
- `elems`: The number of elements in the events array.
- `first`: The index of the events containing the oldest available event.
- `in_use`: The number of queued events.
- `events`: An array of **elems** events.

#### <a id="c-v4l2_event_dequeue"></a>`v4l2_event_dequeue()`

```c
int v4l2_event_dequeue(struct v4l2_fh *fh, struct v4l2_event *event, int nonblocking)
```

Dequeue events from video device.

**Parameters**

- `struct v4l2_fh *fh`: pointer to struct v4l2_fh
- `struct v4l2_event *event`: pointer to struct v4l2_event
- `int nonblocking`: if not zero, waits for an event to arrive

#### <a id="c-v4l2_event_queue"></a>`v4l2_event_queue()`

```c
void v4l2_event_queue(struct video_device *vdev, const struct v4l2_event *ev)
```

Queue events to video device.

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `const struct v4l2_event *ev`: pointer to [`struct v4l2_event`](/kernel/userspace/userspace-api/media-v4l/vidioc-dqevent.md#c-v4l2_event)

**Description**

The event will be queued for all [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh) file handlers.

> [!NOTE]
> The driver's only responsibility is to fill in the type and the data
> fields. The other fields will be filled in by V4L2.

#### <a id="c-v4l2_event_queue_fh"></a>`v4l2_event_queue_fh()`

```c
void v4l2_event_queue_fh(struct v4l2_fh *fh, const struct v4l2_event *ev)
```

Queue events to video device.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `const struct v4l2_event *ev`: pointer to [`struct v4l2_event`](/kernel/userspace/userspace-api/media-v4l/vidioc-dqevent.md#c-v4l2_event)

**Description**

The event will be queued only for the specified [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh) file handler.

> [!NOTE]
> The driver's only responsibility is to fill in the type and the data
> fields. The other fields will be filled in by V4L2.

#### <a id="c-v4l2_event_wake_all"></a>`v4l2_event_wake_all()`

```c
void v4l2_event_wake_all(struct video_device *vdev)
```

Wake all filehandles.

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)

**Description**

Used when unregistering a video device.

#### <a id="c-v4l2_event_pending"></a>`v4l2_event_pending()`

```c
int v4l2_event_pending(struct v4l2_fh *fh)
```

Check if an event is available

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)

**Description**

Returns the number of pending events.

#### <a id="c-v4l2_event_subscribe"></a>`v4l2_event_subscribe()`

```c
int v4l2_event_subscribe(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub, unsigned int elems, const struct v4l2_subscribed_event_ops *ops)
```

Subscribes to an event

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `const struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)
- `unsigned int elems`: size of the events queue
- `const struct v4l2_subscribed_event_ops *ops`: pointer to [`v4l2_subscribed_event_ops`](#c-struct-v4l2_subscribed_event_ops)

**Description**

> [!NOTE]
> if **elems** is zero, the framework will fill in a default value,
> with is currently 1 element.

#### <a id="c-v4l2_event_unsubscribe"></a>`v4l2_event_unsubscribe()`

```c
int v4l2_event_unsubscribe(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub)
```

Unsubscribes to an event

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `const struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

#### <a id="c-v4l2_event_unsubscribe_all"></a>`v4l2_event_unsubscribe_all()`

```c
void v4l2_event_unsubscribe_all(struct v4l2_fh *fh)
```

Unsubscribes to all events

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)

#### <a id="c-v4l2_event_subdev_unsubscribe"></a>`v4l2_event_subdev_unsubscribe()`

```c
int v4l2_event_subdev_unsubscribe(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub)
```

Subdev variant of [`v4l2_event_unsubscribe()`](#c-v4l2_event_unsubscribe)

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

**Description**

> [!NOTE]
> This function should be used for the [`struct v4l2_subdev_core_ops`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev_core_ops)
> `unsubscribe_event` field.

#### <a id="c-v4l2_src_change_event_subscribe"></a>`v4l2_src_change_event_subscribe()`

```c
int v4l2_src_change_event_subscribe(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub)
```

helper function that calls [`v4l2_event_subscribe()`](#c-v4l2_event_subscribe) if the event is `V4L2_EVENT_SOURCE_CHANGE`.

**Parameters**

- `struct v4l2_fh *fh`: pointer to struct v4l2_fh
- `const struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

#### <a id="c-v4l2_src_change_event_subdev_subscribe"></a>`v4l2_src_change_event_subdev_subscribe()`

```c
int v4l2_src_change_event_subdev_subscribe(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub)
```

Variant of [`v4l2_event_subscribe()`](#c-v4l2_event_subscribe), meant to subscribe only events of the type `V4L2_EVENT_SOURCE_CHANGE`.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)
- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `struct v4l2_event_subscription *sub`: pointer to [`struct v4l2_event_subscription`](/kernel/userspace/userspace-api/media-v4l/vidioc-subscribe-event.md#c-v4l2_event_subscription)

---

# V4L2 File handles

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> struct v4l2_fh provides a way to easily keep file handle specific data that is used by the V4L2 framework. Its usage is mandatory in all drivers.

<a id="rst-v4l2-file-handles"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

struct v4l2_fh provides a way to easily keep file handle specific data that is used by the V4L2 framework. Its usage is mandatory in all drivers.

struct v4l2_fh is allocated in the driver's `open()` file operation handler. It is typically embedded in a larger driver-specific structure. The `v4l2_fh` must be initialized with a call to `v4l2_fh_init()`, and added to the video device with `v4l2_fh_add()`. This associates the `v4l2_fh` with the `file` by setting `file->private_data` to point to the `v4l2_fh`.

Similarly, the struct v4l2_fh is freed in the driver's `release()` file operation handler. It must be removed from the video device with `v4l2_fh_del()` and cleaned up with `v4l2_fh_exit()` before being freed.

Drivers must not access `file->private_data` directly. They can retrieve the `v4l2_fh` associated with a `file` by calling `file_to_v4l2_fh()`. Drivers can extract their own file handle structure by using the container_of macro.

Example:



```c
struct my_fh {
        int blah;
        struct v4l2_fh fh;
};

...

int my_open(struct file *file)
{
        struct my_fh *my_fh;
        struct video_device *vfd;
        int ret;

        ...

        my_fh = kzalloc(sizeof(*my_fh), GFP_KERNEL);

        ...

        v4l2_fh_init(&my_fh->fh, vfd);

        ...

        v4l2_fh_add(&my_fh->fh, file);
        return 0;
}

int my_release(struct file *file)
{
        struct v4l2_fh *fh = file_to_v4l2_fh(file);
        struct my_fh *my_fh = container_of(fh, struct my_fh, fh);

        ...
        v4l2_fh_del(&my_fh->fh, file);
        v4l2_fh_exit(&my_fh->fh);
        kfree(my_fh);
        return 0;
}
```

Below is a short description of the `v4l2_fh` functions used:

`v4l2_fh_init <v4l2_fh_init>()` (`fh <v4l2_fh>`, `vdev <video_device>`)

- Initialise the file handle. This **MUST** be performed in the driver's `v4l2_file_operations`-&gt;open() handler.

`v4l2_fh_add <v4l2_fh_add>()` (`fh <v4l2_fh>`, struct file \*filp)

- Add a `v4l2_fh` to `video_device` file handle list. Must be called once the file handle is completely initialized.

`v4l2_fh_del <v4l2_fh_del>()` (`fh <v4l2_fh>`, struct file \*filp)

- Unassociate the file handle from `video_device`. The file handle exit function may now be called.

`v4l2_fh_exit <v4l2_fh_exit>()` (`fh <v4l2_fh>`)

- Uninitialise the file handle. After uninitialisation the `v4l2_fh` memory can be freed.

`file_to_v4l2_fh <file_to_v4l2_fh>()` (struct file \*filp)

- Retrieve the `v4l2_fh` instance associated with a `file`.

If struct v4l2_fh is not embedded, then you can use these helper functions:

`v4l2_fh_open <v4l2_fh_open>()` (struct file \*filp)

- This allocates a struct v4l2_fh, initializes it and adds it to the struct video_device associated with the file struct.

`v4l2_fh_release <v4l2_fh_release>()` (struct file \*filp)

- This deletes it from the struct video_device associated with the file struct, uninitialised the `v4l2_fh` and frees it.

These two functions can be plugged into the v4l2_file_operation's `open()` and `release()` ops.

Several drivers need to do something when the first file handle is opened and when the last file handle closes. Two helper functions were added to check whether the `v4l2_fh` struct is the only open filehandle of the associated device node:

`v4l2_fh_is_singular <v4l2_fh_is_singular>()` (`fh <v4l2_fh>`)

- Returns 1 if the file handle is the only open file handle, else 0.

`v4l2_fh_is_singular_file <v4l2_fh_is_singular_file>()` (struct file \*filp)

- Same, but it calls v4l2_fh_is_singular with filp-&gt;private_data.

<a id="rst-v4l2-fh-functions-and-data-structures"></a>

## V4L2 fh functions and data structures


#### <a id="c-struct-v4l2_fh"></a>`struct v4l2_fh`

Describes a V4L2 file handler

**Definition**

```c
struct v4l2_fh {
    struct list_head        list;
    struct video_device     *vdev;
    struct v4l2_ctrl_handler *ctrl_handler;
    enum v4l2_priority      prio;
    wait_queue_head_t wait;
    struct mutex            subscribe_lock;
    struct list_head        subscribed;
    struct list_head        available;
    unsigned int            navailable;
    u32 sequence;
    struct v4l2_m2m_ctx     *m2m_ctx;
};
```

**Members**

- `list`: list of file handlers
- `vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
- `ctrl_handler`: pointer to [`struct v4l2_ctrl_handler`](/kernel/hardware/driver-api/media/v4l2-controls.md#c-struct-v4l2_ctrl_handler)
- `prio`: priority of the file handler, as defined by [`enum v4l2_priority`](/kernel/userspace/userspace-api/media-v4l/vidioc-g-priority.md#c-v4l2_priority)
- `wait`: event' s wait queue
- `subscribe_lock`: serialise changes to the subscribed list; guarantee that
  the add and del event callbacks are orderly called
- `subscribed`: list of subscribed events
- `available`: list of events waiting to be dequeued
- `navailable`: number of available events at **available** list
- `sequence`: event sequence number
- `m2m_ctx`: pointer to [`struct v4l2_m2m_ctx`](/kernel/hardware/driver-api/media/v4l2-mem2mem.md#c-struct-v4l2_m2m_ctx)

#### <a id="c-file_to_v4l2_fh"></a>`file_to_v4l2_fh()`

```c
struct v4l2_fh * file_to_v4l2_fh(struct file *filp)
```

Return the v4l2_fh associated with a struct file

**Parameters**

- `struct file *filp`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)

**Description**

This function should be used by drivers to retrieve the [`struct v4l2_fh`](#c-struct-v4l2_fh)
instance pointer stored in the file private_data instead of accessing the
private_data field directly.

#### <a id="c-v4l2_fh_init"></a>`v4l2_fh_init()`

```c
void v4l2_fh_init(struct v4l2_fh *fh, struct video_device *vdev)
```

Initialise the file handle.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)
- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)

**Description**

Parts of the V4L2 framework using the
file handles should be initialised in this function. Must be called
from driver's v4l2_file_operations->open\(\) handler if the driver
uses [`struct v4l2_fh`](#c-struct-v4l2_fh).

#### <a id="c-v4l2_fh_add"></a>`v4l2_fh_add()`

```c
void v4l2_fh_add(struct v4l2_fh *fh, struct file *filp)
```

Add the fh to the list of file handles on a video_device.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)
- `struct file *filp`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) associated with **fh**

**Description**

The function sets filp->private_data to point to **fh**.

> [!NOTE]
> The **fh** file handle must be initialised first.

#### <a id="c-v4l2_fh_open"></a>`v4l2_fh_open()`

```c
int v4l2_fh_open(struct file *filp)
```

Ancillary routine that can be used as the open\(\) op of v4l2_file_operations.

**Parameters**

- `struct file *filp`: pointer to struct file

**Description**

It allocates a v4l2_fh and inits and adds it to the [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)
associated with the file pointer.

On error filp->private_data will be `NULL`, otherwise it will point to
the [`struct v4l2_fh`](#c-struct-v4l2_fh).

#### <a id="c-v4l2_fh_del"></a>`v4l2_fh_del()`

```c
void v4l2_fh_del(struct v4l2_fh *fh, struct file *filp)
```

Remove file handle from the list of file handles.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)
- `struct file *filp`: pointer to [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) associated with **fh**

**Description**

The function resets filp->private_data to NULL.

> [!NOTE]
> Must be called in v4l2_file_operations->release\(\) handler if the driver
> uses [`struct v4l2_fh`](#c-struct-v4l2_fh).

#### <a id="c-v4l2_fh_exit"></a>`v4l2_fh_exit()`

```c
void v4l2_fh_exit(struct v4l2_fh *fh)
```

Release resources related to a file handle.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)

**Description**

Parts of the V4L2 framework using the v4l2_fh must release their
resources here, too.

> [!NOTE]
> Must be called in v4l2_file_operations->release\(\) handler if the
> driver uses [`struct v4l2_fh`](#c-struct-v4l2_fh).

#### <a id="c-v4l2_fh_release"></a>`v4l2_fh_release()`

```c
int v4l2_fh_release(struct file *filp)
```

Ancillary routine that can be used as the release\(\) op of v4l2_file_operations.

**Parameters**

- `struct file *filp`: pointer to struct file

**Description**

It deletes and exits the v4l2_fh associated with the file pointer and
frees it. It will do nothing if filp->private_data (the pointer to the
v4l2_fh struct) is `NULL`.

This function always returns 0.

#### <a id="c-v4l2_fh_is_singular"></a>`v4l2_fh_is_singular()`

```c
int v4l2_fh_is_singular(struct v4l2_fh *fh)
```

Returns 1 if this filehandle is the only filehandle opened for the associated video_device.

**Parameters**

- `struct v4l2_fh *fh`: pointer to [`struct v4l2_fh`](#c-struct-v4l2_fh)

**Description**

If **fh** is NULL, then it returns 0.

#### <a id="c-v4l2_fh_is_singular_file"></a>`v4l2_fh_is_singular_file()`

```c
int v4l2_fh_is_singular_file(struct file *filp)
```

Returns 1 if this filehandle is the only filehandle opened for the associated video_device.

**Parameters**

- `struct file *filp`: pointer to struct file

**Description**

This is a helper function variant of [`v4l2_fh_is_singular()`](#c-v4l2_fh_is_singular) with uses
struct file as argument.

If filp->private_data is `NULL`, then it will return 0.

---

# V4L2 flash functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 flash functions and data structures.

<a id="rst-v4l2-flash-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-v4l2_flash_ctrl_data"></a>`struct v4l2_flash_ctrl_data`

flash control initialization data, filled basing on the features declared by the LED flash class driver in the v4l2_flash_config

**Definition**

```c
struct v4l2_flash_ctrl_data {
    struct v4l2_ctrl_config config;
    u32 cid;
};
```

**Members**

- `config`: initialization data for a control
- `cid`: contains v4l2 flash control id if the config
  field was initialized, 0 otherwise

#### <a id="c-struct-v4l2_flash_ops"></a>`struct v4l2_flash_ops`

V4L2 flash operations

**Definition**

```c
struct v4l2_flash_ops {
    int (*external_strobe_set)(struct v4l2_flash *v4l2_flash, bool enable);
    enum led_brightness (*intensity_to_led_brightness) (struct v4l2_flash *v4l2_flash, s32 intensity);
    s32 (*led_brightness_to_intensity) (struct v4l2_flash *v4l2_flash, enum led_brightness);
};
```

**Members**

- `external_strobe_set`: Setup strobing the flash by hardware pin state
  assertion.
- `intensity_to_led_brightness`: Convert intensity to brightness in a device
  specific manner
- `led_brightness_to_intensity`: convert brightness to intensity in a device
  specific manner.

#### <a id="c-struct-v4l2_flash_config"></a>`struct v4l2_flash_config`

V4L2 Flash sub-device initialization data

**Definition**

```c
struct v4l2_flash_config {
    char dev_name[32];
    struct led_flash_setting intensity;
    u32 flash_faults;
    unsigned int has_external_strobe:1;
};
```

**Members**

- `dev_name`: the name of the media entity,
  unique in the system
- `intensity`: non-flash strobe constraints for the LED
- `flash_faults`: bitmask of flash faults that the LED flash class
  device can report; corresponding LED_FAULT* bit
  definitions are available in the header file
  \<linux/led-class-flash.h>
- `has_external_strobe`: external strobe capability

#### <a id="c-struct-v4l2_flash"></a>`struct v4l2_flash`

Flash sub-device context

**Definition**

```c
struct v4l2_flash {
    struct led_classdev_flash *fled_cdev;
    struct led_classdev *iled_cdev;
    const struct v4l2_flash_ops *ops;
    struct v4l2_subdev sd;
    struct v4l2_ctrl_handler hdl;
    struct v4l2_ctrl **ctrls;
};
```

**Members**

- `fled_cdev`: LED flash class device controlled by this sub-device
- `iled_cdev`: LED class device representing indicator LED associated
  with the LED flash class device
- `ops`: V4L2 specific flash ops
- `sd`: V4L2 sub-device
- `hdl`: flash controls handler
- `ctrls`: array of pointers to controls, whose values define
  the sub-device state

#### <a id="c-v4l2_subdev_to_v4l2_flash"></a>`v4l2_subdev_to_v4l2_flash()`

```c
struct v4l2_flash * v4l2_subdev_to_v4l2_flash(struct v4l2_subdev *sd)
```

Returns a [`struct v4l2_flash`](#c-struct-v4l2_flash) from the [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev) embedded on it.

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](/kernel/hardware/driver-api/media/v4l2-subdev.md#c-struct-v4l2_subdev)

#### <a id="c-v4l2_ctrl_to_v4l2_flash"></a>`v4l2_ctrl_to_v4l2_flash()`

```c
struct v4l2_flash * v4l2_ctrl_to_v4l2_flash(struct v4l2_ctrl *c)
```

Returns a [`struct v4l2_flash`](#c-struct-v4l2_flash) from the [`struct v4l2_ctrl`](/kernel/hardware/driver-api/media/v4l2-controls.md#c-struct-v4l2_ctrl) embedded on it.

**Parameters**

- `struct v4l2_ctrl *c`: pointer to [`struct v4l2_ctrl`](/kernel/hardware/driver-api/media/v4l2-controls.md#c-struct-v4l2_ctrl)

#### <a id="c-v4l2_flash_init"></a>`v4l2_flash_init()`

```c
struct v4l2_flash * v4l2_flash_init(struct device *dev, struct fwnode_handle *fwn, struct led_classdev_flash *fled_cdev, const struct v4l2_flash_ops *ops, struct v4l2_flash_config *config)
```

initialize V4L2 flash led sub-device

**Parameters**

- `struct device *dev`: flash device, e.g. an I2C device
- `struct fwnode_handle *fwn`: fwnode_handle of the LED, may be NULL if the same as device's
- `struct led_classdev_flash *fled_cdev`: LED flash class device to wrap
- `const struct v4l2_flash_ops *ops`: V4L2 Flash device ops
- `struct v4l2_flash_config *config`: initialization data for V4L2 Flash sub-device

**Description**

Create V4L2 Flash sub-device wrapping given LED subsystem device.
The ops pointer is stored by the V4L2 flash framework. No
references are held to config nor its contents once this function
has returned.

**Return**

A valid pointer, or, when an error occurs, the return
value is encoded using [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR). Use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) to check and
[`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) to obtain the numeric return value.

#### <a id="c-v4l2_flash_indicator_init"></a>`v4l2_flash_indicator_init()`

```c
struct v4l2_flash * v4l2_flash_indicator_init(struct device *dev, struct fwnode_handle *fwn, struct led_classdev *iled_cdev, struct v4l2_flash_config *config)
```

initialize V4L2 indicator sub-device

**Parameters**

- `struct device *dev`: flash device, e.g. an I2C device
- `struct fwnode_handle *fwn`: fwnode_handle of the LED, may be NULL if the same as device's
- `struct led_classdev *iled_cdev`: LED flash class device representing the indicator LED
- `struct v4l2_flash_config *config`: initialization data for V4L2 Flash sub-device

**Description**

Create V4L2 Flash sub-device wrapping given LED subsystem device.
The ops pointer is stored by the V4L2 flash framework. No
references are held to config nor its contents once this function
has returned.

**Return**

A valid pointer, or, when an error occurs, the return
value is encoded using [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR). Use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) to check and
[`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) to obtain the numeric return value.

#### <a id="c-v4l2_flash_release"></a>`v4l2_flash_release()`

```c
void v4l2_flash_release(struct v4l2_flash *v4l2_flash)
```

release V4L2 Flash sub-device

**Parameters**

- `struct v4l2_flash *v4l2_flash`: the V4L2 Flash sub-device to release

**Description**

Release V4L2 Flash sub-device.

---

# V4L2 fwnode kAPI

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 fwnode kAPI.

<a id="rst-v4l2-fwnode-kapi"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-v4l2_fwnode_endpoint"></a>`struct v4l2_fwnode_endpoint`

the endpoint data structure

**Definition**

```c
struct v4l2_fwnode_endpoint {
    struct fwnode_endpoint base;
    enum v4l2_mbus_type bus_type;
    struct {
        struct v4l2_mbus_config_parallel parallel;
        struct v4l2_mbus_config_mipi_csi1 mipi_csi1;
        struct v4l2_mbus_config_mipi_csi2 mipi_csi2;
    } bus;
    u64 *link_frequencies;
    unsigned int nr_of_link_frequencies;
};
```

**Members**

- `base`: fwnode endpoint of the v4l2_fwnode
- `bus_type`: bus type
- `bus`: bus configuration data structure
- `bus.parallel`: embedded [`struct v4l2_mbus_config_parallel`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-struct-v4l2_mbus_config_parallel).
  Used if the bus is parallel.
- `bus.mipi_csi1`: embedded [`struct v4l2_mbus_config_mipi_csi1`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-struct-v4l2_mbus_config_mipi_csi1).
  Used if the bus is MIPI Alliance's Camera Serial
  Interface version 1 (MIPI CSI1) or Standard
  Mobile Imaging Architecture's Compact Camera Port 2
  (SMIA CCP2).
- `bus.mipi_csi2`: embedded [`struct v4l2_mbus_config_mipi_csi2`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-struct-v4l2_mbus_config_mipi_csi2).
  Used if the bus is MIPI Alliance's Camera Serial
  Interface version 2 (MIPI CSI2).
- `link_frequencies`: array of supported link frequencies
- `nr_of_link_frequencies`: number of elements in link_frequenccies array

#### <a id="c-V4L2_FWNODE_PROPERTY_UNSET"></a>`V4L2_FWNODE_PROPERTY_UNSET`

```c
V4L2_FWNODE_PROPERTY_UNSET
```

identify a non initialized property

**Description**

All properties in [`struct v4l2_fwnode_device_properties`](#c-struct-v4l2_fwnode_device_properties) are initialized
to this value.

#### <a id="c-enum-v4l2_fwnode_orientation"></a>`enum v4l2_fwnode_orientation`

possible device orientation

**Constants**

- `V4L2_FWNODE_ORIENTATION_FRONT`: device installed on the front side
- `V4L2_FWNODE_ORIENTATION_BACK`: device installed on the back side
- `V4L2_FWNODE_ORIENTATION_EXTERNAL`: device externally located

#### <a id="c-struct-v4l2_fwnode_device_properties"></a>`struct v4l2_fwnode_device_properties`

fwnode device properties

**Definition**

```c
struct v4l2_fwnode_device_properties {
    enum v4l2_fwnode_orientation orientation;
    unsigned int rotation;
};
```

**Members**

- `orientation`: device orientation. See [`enum v4l2_fwnode_orientation`](#c-enum-v4l2_fwnode_orientation)
- `rotation`: device rotation

#### <a id="c-struct-v4l2_fwnode_link"></a>`struct v4l2_fwnode_link`

a link between two endpoints

**Definition**

```c
struct v4l2_fwnode_link {
    struct fwnode_handle *local_node;
    unsigned int local_port;
    unsigned int local_id;
    struct fwnode_handle *remote_node;
    unsigned int remote_port;
    unsigned int remote_id;
};
```

**Members**

- `local_node`: pointer to device_node of this endpoint
- `local_port`: identifier of the port this endpoint belongs to
- `local_id`: identifier of the id this endpoint belongs to
- `remote_node`: pointer to device_node of the remote endpoint
- `remote_port`: identifier of the port the remote endpoint belongs to
- `remote_id`: identifier of the id the remote endpoint belongs to

#### <a id="c-enum-v4l2_connector_type"></a>`enum v4l2_connector_type`

connector type

**Constants**

- `V4L2_CONN_UNKNOWN`: unknown connector type, no V4L2 connector configuration
- `V4L2_CONN_COMPOSITE`: analog composite connector
- `V4L2_CONN_SVIDEO`: analog svideo connector

#### <a id="c-struct-v4l2_connector_link"></a>`struct v4l2_connector_link`

connector link data structure

**Definition**

```c
struct v4l2_connector_link {
    struct list_head head;
    struct v4l2_fwnode_link fwnode_link;
};
```

**Members**

- `head`: structure to be used to add the link to the
  [`struct v4l2_fwnode_connector`](#c-struct-v4l2_fwnode_connector)
- `fwnode_link`: [`struct v4l2_fwnode_link`](#c-struct-v4l2_fwnode_link) link between the connector and the
  device the connector belongs to.

#### <a id="c-struct-v4l2_fwnode_connector_analog"></a>`struct v4l2_fwnode_connector_analog`

analog connector data structure

**Definition**

```c
struct v4l2_fwnode_connector_analog {
    v4l2_std_id sdtv_stds;
};
```

**Members**

- `sdtv_stds`: sdtv standards this connector supports, set to V4L2_STD_ALL
  if no restrictions are specified.

#### <a id="c-struct-v4l2_fwnode_connector"></a>`struct v4l2_fwnode_connector`

the connector data structure

**Definition**

```c
struct v4l2_fwnode_connector {
    const char *name;
    const char *label;
    enum v4l2_connector_type type;
    struct list_head links;
    unsigned int nr_of_links;
    union {
        struct v4l2_fwnode_connector_analog analog;
    } connector;
};
```

**Members**

- `name`: the connector device name
- `label`: optional connector label
- `type`: connector type
- `links`: list of all connector [`struct v4l2_connector_link`](#c-struct-v4l2_connector_link) links
- `nr_of_links`: total number of links
- `connector`: connector configuration
- `connector.analog`: analog connector configuration
  [`struct v4l2_fwnode_connector_analog`](#c-struct-v4l2_fwnode_connector_analog)

#### <a id="c-enum-v4l2_fwnode_bus_type"></a>`enum v4l2_fwnode_bus_type`

Video bus types defined by firmware properties

**Constants**

- `V4L2_FWNODE_BUS_TYPE_GUESS`: Default value if no bus-type fwnode property
- `V4L2_FWNODE_BUS_TYPE_CSI2_CPHY`: MIPI CSI-2 bus, C-PHY physical layer
- `V4L2_FWNODE_BUS_TYPE_CSI1`: MIPI CSI-1 bus
- `V4L2_FWNODE_BUS_TYPE_CCP2`: SMIA Compact Camera Port 2 bus
- `V4L2_FWNODE_BUS_TYPE_CSI2_DPHY`: MIPI CSI-2 bus, D-PHY physical layer
- `V4L2_FWNODE_BUS_TYPE_PARALLEL`: Camera Parallel Interface bus
- `V4L2_FWNODE_BUS_TYPE_BT656`: BT.656 video format bus-type
- `V4L2_FWNODE_BUS_TYPE_DPI`: Video Parallel Interface bus
- `NR_OF_V4L2_FWNODE_BUS_TYPE`: Number of bus-types

#### <a id="c-v4l2_fwnode_endpoint_parse"></a>`v4l2_fwnode_endpoint_parse()`

```c
int v4l2_fwnode_endpoint_parse(struct fwnode_handle *fwnode, struct v4l2_fwnode_endpoint *vep)
```

parse all fwnode node properties

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the endpoint's fwnode handle (may be NULL)
- `struct v4l2_fwnode_endpoint *vep`: pointer to the V4L2 fwnode data structure

**Description**

This function parses the V4L2 fwnode endpoint specific parameters from the
firmware. There are two ways to use this function, either by letting it
obtain the type of the bus (by setting the **vep.bus_type** field to
V4L2_MBUS_UNKNOWN) or specifying the bus type explicitly to one of the [`enum v4l2_mbus_type`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-enum-v4l2_mbus_type) types.

When **vep.bus_type** is V4L2_MBUS_UNKNOWN, the function will use the "bus-type"
property to determine the type when it is available. The caller is
responsible for validating the contents of **vep.bus_type** field after the call
returns.

As a deprecated functionality to support older DT bindings without "bus-type"
property for devices that support multiple types, if the "bus-type" property
does not exist, the function will attempt to guess the type based on the
endpoint properties available. NEVER RELY ON GUESSING THE BUS TYPE IN NEW
DRIVERS OR BINDINGS.

It is also possible to set **vep.bus_type** corresponding to an actual bus. In
this case the function will only attempt to parse properties related to this
bus, and it will return an error if the value of the "bus-type" property
corresponds to a different bus.

The caller is required to initialise all fields of **vep**, either with
explicitly values, or by zeroing them.

The function does not change the V4L2 fwnode endpoint state if it fails.

**NOTE**

This function does not parse "link-frequencies" property as its size is
not known in advance. Please use [`v4l2_fwnode_endpoint_alloc_parse()`](#c-v4l2_fwnode_endpoint_alloc_parse) if you
need properties of variable size.

**Return**

`0` on success or a negative error code on failure:
`-ENOMEM` on memory allocation failure
`-EINVAL` on parsing failure, including **fwnode** == NULL
`-ENXIO` on mismatching bus types

#### <a id="c-v4l2_fwnode_endpoint_free"></a>`v4l2_fwnode_endpoint_free()`

```c
void v4l2_fwnode_endpoint_free(struct v4l2_fwnode_endpoint *vep)
```

free the V4L2 fwnode acquired by [`v4l2_fwnode_endpoint_alloc_parse()`](#c-v4l2_fwnode_endpoint_alloc_parse)

**Parameters**

- `struct v4l2_fwnode_endpoint *vep`: the V4L2 fwnode the resources of which are to be released

**Description**

It is safe to call this function with NULL argument or on a V4L2 fwnode the
parsing of which failed.

#### <a id="c-v4l2_fwnode_endpoint_alloc_parse"></a>`v4l2_fwnode_endpoint_alloc_parse()`

```c
int v4l2_fwnode_endpoint_alloc_parse(struct fwnode_handle *fwnode, struct v4l2_fwnode_endpoint *vep)
```

parse all fwnode node properties

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the endpoint's fwnode handle (may be NULL)
- `struct v4l2_fwnode_endpoint *vep`: pointer to the V4L2 fwnode data structure

**Description**

This function parses the V4L2 fwnode endpoint specific parameters from the
firmware. There are two ways to use this function, either by letting it
obtain the type of the bus (by setting the **vep.bus_type** field to
V4L2_MBUS_UNKNOWN) or specifying the bus type explicitly to one of the [`enum v4l2_mbus_type`](/kernel/hardware/driver-api/media/v4l2-mediabus.md#c-enum-v4l2_mbus_type) types.

When **vep.bus_type** is V4L2_MBUS_UNKNOWN, the function will use the "bus-type"
property to determine the type when it is available. The caller is
responsible for validating the contents of **vep.bus_type** field after the call
returns.

As a deprecated functionality to support older DT bindings without "bus-type"
property for devices that support multiple types, if the "bus-type" property
does not exist, the function will attempt to guess the type based on the
endpoint properties available. NEVER RELY ON GUESSING THE BUS TYPE IN NEW
DRIVERS OR BINDINGS.

It is also possible to set **vep.bus_type** corresponding to an actual bus. In
this case the function will only attempt to parse properties related to this
bus, and it will return an error if the value of the "bus-type" property
corresponds to a different bus.

The caller is required to initialise all fields of **vep**, either with
explicitly values, or by zeroing them.

The function does not change the V4L2 fwnode endpoint state if it fails.

[`v4l2_fwnode_endpoint_alloc_parse()`](#c-v4l2_fwnode_endpoint_alloc_parse) has two important differences to
[`v4l2_fwnode_endpoint_parse()`](#c-v4l2_fwnode_endpoint_parse):

1. It also parses variable size data.

2. The memory it has allocated to store the variable size data must be freed
   using [`v4l2_fwnode_endpoint_free()`](#c-v4l2_fwnode_endpoint_free) when no longer needed.

**Return**

`0` on success or a negative error code on failure:
`-ENOMEM` on memory allocation failure
`-EINVAL` on parsing failure, including **fwnode** == NULL
`-ENXIO` on mismatching bus types

#### <a id="c-v4l2_fwnode_parse_link"></a>`v4l2_fwnode_parse_link()`

```c
int v4l2_fwnode_parse_link(struct fwnode_handle *fwnode, struct v4l2_fwnode_link *link)
```

parse a link between two endpoints

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the endpoint's fwnode at the local end of the link
- `struct v4l2_fwnode_link *link`: pointer to the V4L2 fwnode link data structure

**Description**

Fill the link structure with the local and remote nodes and port numbers.
The local_node and remote_node fields are set to point to the local and
remote port's parent nodes respectively (the port parent node being the
parent node of the port node if that node isn't a 'ports' node, or the
grand-parent node of the port node otherwise).

A reference is taken to both the local and remote nodes, the caller must use
[`v4l2_fwnode_put_link()`](#c-v4l2_fwnode_put_link) to drop the references when done with the
link.

**Return**

0 on success, or -ENOLINK if the remote endpoint fwnode can't be
found.

#### <a id="c-v4l2_fwnode_put_link"></a>`v4l2_fwnode_put_link()`

```c
void v4l2_fwnode_put_link(struct v4l2_fwnode_link *link)
```

drop references to nodes in a link

**Parameters**

- `struct v4l2_fwnode_link *link`: pointer to the V4L2 fwnode link data structure

**Description**

Drop references to the local and remote nodes in the link. This function
must be called on every link parsed with [`v4l2_fwnode_parse_link()`](#c-v4l2_fwnode_parse_link).

#### <a id="c-v4l2_fwnode_connector_free"></a>`v4l2_fwnode_connector_free()`

```c
void v4l2_fwnode_connector_free(struct v4l2_fwnode_connector *connector)
```

free the V4L2 connector acquired memory

**Parameters**

- `struct v4l2_fwnode_connector *connector`: the V4L2 connector resources of which are to be released

**Description**

Free all allocated memory and put all links acquired by
[`v4l2_fwnode_connector_parse()`](#c-v4l2_fwnode_connector_parse) and [`v4l2_fwnode_connector_add_link()`](#c-v4l2_fwnode_connector_add_link).

It is safe to call this function with NULL argument or on a V4L2 connector
the parsing of which failed.

#### <a id="c-v4l2_fwnode_connector_parse"></a>`v4l2_fwnode_connector_parse()`

```c
int v4l2_fwnode_connector_parse(struct fwnode_handle *fwnode, struct v4l2_fwnode_connector *connector)
```

initialize the 'struct v4l2_fwnode_connector'

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the subdev endpoint's fwnode handle where the connector
  is connected to or to the connector endpoint fwnode handle.
- `struct v4l2_fwnode_connector *connector`: pointer to the V4L2 fwnode connector data structure

**Description**

Fill the [`struct v4l2_fwnode_connector`](#c-struct-v4l2_fwnode_connector) with the connector type, label and
all [`enum v4l2_connector_type`](#c-enum-v4l2_connector_type) specific connector data. The label is optional
so it is set to `NULL` if no one was found. The function initialize the links
to zero. Adding links to the connector is done by calling
[`v4l2_fwnode_connector_add_link()`](#c-v4l2_fwnode_connector_add_link).

The memory allocated for the label must be freed when no longer needed.
Freeing the memory is done by [`v4l2_fwnode_connector_free()`](#c-v4l2_fwnode_connector_free).

**Return**

* `0` on success or a negative error code on failure:
* `-EINVAL` if **fwnode** is invalid
* `-ENOTCONN` if connector type is unknown or connector device can't be found

#### <a id="c-v4l2_fwnode_connector_add_link"></a>`v4l2_fwnode_connector_add_link()`

```c
int v4l2_fwnode_connector_add_link(struct fwnode_handle *fwnode, struct v4l2_fwnode_connector *connector)
```

add a link between a connector node and a v4l2-subdev node.

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the subdev endpoint's fwnode handle where the connector
  is connected to
- `struct v4l2_fwnode_connector *connector`: pointer to the V4L2 fwnode connector data structure

**Description**

Add a new [`struct v4l2_connector_link`](#c-struct-v4l2_connector_link) link to the
[`struct v4l2_fwnode_connector`](#c-struct-v4l2_fwnode_connector) connector links list. The link local_node
points to the connector node, the remote_node to the host v4l2 (sub)dev.

The taken references to remote_node and local_node must be dropped and the
allocated memory must be freed when no longer needed. Both is done by calling
[`v4l2_fwnode_connector_free()`](#c-v4l2_fwnode_connector_free).

**Return**

* `0` on success or a negative error code on failure:
* `-EINVAL` if **fwnode** or **connector** is invalid or **connector** type is unknown
* `-ENOMEM` on link memory allocation failure
* `-ENOTCONN` if remote connector device can't be found
* `-ENOLINK` if link parsing between v4l2 (sub)dev and connector fails

#### <a id="c-v4l2_fwnode_device_parse"></a>`v4l2_fwnode_device_parse()`

```c
int v4l2_fwnode_device_parse(struct device *dev, struct v4l2_fwnode_device_properties *props)
```

parse fwnode device properties

**Parameters**

- `struct device *dev`: pointer to [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device)
- `struct v4l2_fwnode_device_properties *props`: pointer to [`struct v4l2_fwnode_device_properties`](#c-struct-v4l2_fwnode_device_properties) where to store the
  parsed properties values

**Description**

This function parses and validates the V4L2 fwnode device properties from the
firmware interface, and fills the **struct** v4l2_fwnode_device_properties
provided by the caller.

**Return**

% 0 on success
`-EINVAL` if a parsed property value is not valid

---

# Introduction

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> The V4L2 drivers tend to be very complex due to the complexity of the hardware: most devices have multiple ICs, export multiple device nodes in /dev, and create also non-V4L2 devices such as DVB, ALSA, FB, I2C and input (IR) devices.

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The V4L2 drivers tend to be very complex due to the complexity of the hardware: most devices have multiple ICs, export multiple device nodes in /dev, and create also non-V4L2 devices such as DVB, ALSA, FB, I2C and input (IR) devices.

Especially the fact that V4L2 drivers have to setup supporting ICs to do audio/video muxing/encoding/decoding makes it more complex than most. Usually these ICs are connected to the main bridge driver through one or more I2C buses, but other buses can also be used. Such devices are called 'sub-devices'.

For a long time the framework was limited to the video_device struct for creating V4L device nodes and video_buf for handling the video buffers (note that this document does not discuss the video_buf framework).

This meant that all drivers had to do the setup of device instances and connecting to sub-devices themselves. Some of this is quite complicated to do right and many drivers never did do it correctly.

There is also a lot of common code that could never be refactored due to the lack of a framework.

So this framework sets up the basic building blocks that all drivers need and this same framework should make it much easier to refactor common code into utility functions shared by all drivers.

A good example to look at as a reference is the v4l2-pci-skeleton.c source that is available in samples/v4l/. It is a skeleton driver for a PCI capture card, and demonstrates how to use the V4L2 driver framework. It can be used as a template for real PCI video capture driver.

<a id="rst-structure-of-a-v4l-driver"></a>

## Structure of a V4L driver

All drivers have the following structure:

1. A struct for each device instance containing the device state.

2. A way of initializing and commanding sub-devices (if any).

3. Creating V4L2 device nodes (/dev/videoX, /dev/vbiX and /dev/radioX) and keeping track of device-node specific data.

4. Filehandle-specific structs containing per-filehandle data;

5. video buffer handling.

This is a rough schematic of how it all relates:



```none
device instances
  |
  +-sub-device instances
  |
  \-V4L2 device nodes
      |
      \-filehandle instances
```

<a id="rst-structure-of-the-v4l2-framework"></a>

## Structure of the V4L2 framework

The framework closely resembles the driver structure: it has a v4l2_device struct for the device instance data, a v4l2_subdev struct to refer to sub-device instances, the video_device struct stores V4L2 device node data and the v4l2_fh struct keeps track of filehandle instances.

The V4L2 framework also optionally integrates with the media framework. If a driver sets the struct v4l2_device mdev field, sub-devices and video nodes will automatically appear in the media framework as entities.

---

# V4L2 generic ISP parameters and statistics support

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> ISP configuration parameters and statistics are processed and collected by drivers and exchanged with userspace through data types that usually reflect the ISP peripheral registers layout.

<a id="rst-v4l2-generic-isp-parameters-and-statistics-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-design-rationale"></a>

## Design rationale

ISP configuration parameters and statistics are processed and collected by drivers and exchanged with userspace through data types that usually reflect the ISP peripheral registers layout.

Each ISP driver defines its own metadata output format for parameters and a metadata capture format for statistics. The buffer layout is realized by a set of C structures that reflects the registers layout. The number and types of C structures is fixed by the format definition and becomes part of the Linux kernel uAPI/uABI interface.

Because of the hard requirement of backward compatibility when extending the user API/ABI interface, modifying an ISP driver capture or output metadata format after it has been accepted by mainline is very hard if not impossible.

It generally happens, in fact, that after the first accepted revision of an ISP driver the buffers layout need to be modified, either to support new hardware blocks, to fix bugs or to support different revisions of the hardware.

Each of these situations would require defining a new metadata format, making it really hard to maintain and extend drivers and requiring userspace to use the correct format depending on the kernel revision in use.

<a id="rst-v4l2-isp-configuration-parameters"></a>

## V4L2 ISP configuration parameters

For these reasons, Video4Linux2 defines generic types for ISP configuration parameters and statistics. Drivers are still expected to define their own formats for their metadata output and capture nodes, but the buffers layout can be defined using the extensible and versioned types defined by include/uapi/linux/media/v4l2-isp.h.

Drivers are expected to provide the definitions of their supported ISP blocks and the expected maximum size of a buffer.

For driver developers a set of helper functions to assist them with validation of the buffer received from userspace is available in drivers/media/v4l2-core/v4l2-isp.c

<a id="rst-v4l2-isp-support-driver-documentation"></a>

## V4L2 ISP support driver documentation


#### <a id="c-v4l2_isp_params_buffer_size"></a>`v4l2_isp_params_buffer_size()`

```c
v4l2_isp_params_buffer_size(max_params_size)
```

Calculate size of v4l2_isp_params_buffer

**Parameters**

- `max_params_size`: The total size of the ISP configuration blocks

**Description**

Users of the v4l2 extensible parameters will have differing sized data arrays
depending on their specific parameter buffers. Drivers and userspace will
need to be able to calculate the appropriate size of the struct to
accommodate all ISP configuration blocks provided by the platform.
This macro provides a convenient tool for the calculation.

#### <a id="c-v4l2_isp_params_validate_buffer_size"></a>`v4l2_isp_params_validate_buffer_size()`

```c
int v4l2_isp_params_validate_buffer_size(struct device *dev, struct vb2_buffer *vb, size_t max_size)
```

Validate a V4L2 ISP buffer sizes

**Parameters**

- `struct device *dev`: the driver's device pointer
- `struct vb2_buffer *vb`: the videobuf2 buffer
- `size_t max_size`: the maximum allowed buffer size

**Description**

This function performs validation of the size of a V4L2 ISP parameters buffer
before the driver can access the actual data buffer content.

After the sizes validation, drivers should copy the buffer content to a
kernel-only memory area to prevent userspace from modifying it,
before completing validation using [`v4l2_isp_params_validate_buffer()`](#c-v4l2_isp_params_validate_buffer).

The **vb** buffer as received from the vb2 .`buf_prepare()` operation is checked
against **max_size** and it's validated to be large enough to accommodate at
least one ISP configuration block.

#### <a id="c-struct-v4l2_isp_params_block_type_info"></a>`struct v4l2_isp_params_block_type_info`

V4L2 ISP per-block-type info

**Definition**

```c
struct v4l2_isp_params_block_type_info {
    size_t size;
};
```

**Members**

- `size`: the block type expected size

**Description**

The v4l2_isp_params_block_type_info collects information of the ISP
configuration block types for validation purposes. It currently only contains
the expected block type size.

Drivers shall prepare a list of block type info, indexed by block type, one
for each supported ISP block type and correctly populate them with the
expected block type size.

#### <a id="c-v4l2_isp_params_validate_buffer"></a>`v4l2_isp_params_validate_buffer()`

```c
int v4l2_isp_params_validate_buffer(struct device *dev, struct vb2_buffer *vb, const struct v4l2_isp_params_buffer *buffer, const struct v4l2_isp_params_block_type_info *type_info, size_t num_block_types)
```

Validate a V4L2 ISP parameters buffer

**Parameters**

- `struct device *dev`: the driver's device pointer
- `struct vb2_buffer *vb`: the videobuf2 buffer
- `const struct v4l2_isp_params_buffer *buffer`: the V4L2 ISP parameters buffer
- `const struct v4l2_isp_params_block_type_info *type_info`: the array of per-block-type validation info
- `size_t num_block_types`: the number of block types in the type_info array

**Description**

This function completes the validation of a V4L2 ISP parameters buffer,
verifying each configuration block correctness before the driver can use
them to program the hardware.

Drivers should use this function after having validated the correctness of
the vb2 buffer sizes by using the [`v4l2_isp_params_validate_buffer_size()`](#c-v4l2_isp_params_validate_buffer_size)
helper first. Once the buffer size has been validated, drivers should
perform a copy of the user provided buffer into a kernel-only memory buffer
to prevent userspace from modifying its content after it has been submitted
to the driver, and then call this function to complete validation.

---

# V4L2 JPEG header related functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 JPEG header related functions and data structures.

<a id="rst-v4l2-jpeg-header-related-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-v4l2_jpeg_reference"></a>`struct v4l2_jpeg_reference`

reference into the JPEG buffer

**Definition**

```c
struct v4l2_jpeg_reference {
    u8 *start;
    size_t length;
};
```

**Members**

- `start`: pointer to the start of the referenced segment or table
- `length`: size of the referenced segment or table

**Description**

Wnen referencing marker segments, start points right after the marker code,
and length is the size of the segment parameters, excluding the marker code.

#### <a id="c-struct-v4l2_jpeg_frame_component_spec"></a>`struct v4l2_jpeg_frame_component_spec`

frame component-specification

**Definition**

```c
struct v4l2_jpeg_frame_component_spec {
    u8 component_identifier;
    u8 horizontal_sampling_factor;
    u8 vertical_sampling_factor;
    u8 quantization_table_selector;
};
```

**Members**

- `component_identifier`: C\[i\]
- `horizontal_sampling_factor`: H\[i\]
- `vertical_sampling_factor`: V\[i\]
- `quantization_table_selector`: quantization table destination selector Tq\[i\]

#### <a id="c-struct-v4l2_jpeg_frame_header"></a>`struct v4l2_jpeg_frame_header`

JPEG frame header

**Definition**

```c
struct v4l2_jpeg_frame_header {
    u16 height;
    u16 width;
    u8 precision;
    u8 num_components;
    struct v4l2_jpeg_frame_component_spec component[V4L2_JPEG_MAX_COMPONENTS];
    enum v4l2_jpeg_chroma_subsampling subsampling;
};
```

**Members**

- `height`: Y
- `width`: X
- `precision`: P
- `num_components`: Nf
- `component`: component-specification, see v4l2_jpeg_frame_component_spec
- `subsampling`: decoded subsampling from component-specification

#### <a id="c-struct-v4l2_jpeg_scan_component_spec"></a>`struct v4l2_jpeg_scan_component_spec`

scan component-specification

**Definition**

```c
struct v4l2_jpeg_scan_component_spec {
    u8 component_selector;
    u8 dc_entropy_coding_table_selector;
    u8 ac_entropy_coding_table_selector;
};
```

**Members**

- `component_selector`: Cs\[j\]
- `dc_entropy_coding_table_selector`: Td\[j\]
- `ac_entropy_coding_table_selector`: Ta\[j\]

#### <a id="c-struct-v4l2_jpeg_scan_header"></a>`struct v4l2_jpeg_scan_header`

JPEG scan header

**Definition**

```c
struct v4l2_jpeg_scan_header {
    u8 num_components;
    struct v4l2_jpeg_scan_component_spec component[V4L2_JPEG_MAX_COMPONENTS];
};
```

**Members**

- `num_components`: Ns
- `component`: component-specification, see v4l2_jpeg_scan_component_spec

#### <a id="c-enum-v4l2_jpeg_app14_tf"></a>`enum v4l2_jpeg_app14_tf`

APP14 transform flag According to Rec. ITU-T T.872 (06/2012) 6.5.3 APP14 segment is for color encoding, it contains a transform flag, which may have values of 0, 1 and 2 and are interpreted as follows:

**Constants**

- `V4L2_JPEG_APP14_TF_CMYK_RGB`: CMYK for images encoded with four components
  RGB for images encoded with three components
- `V4L2_JPEG_APP14_TF_YCBCR`: an image encoded with three components using YCbCr
- `V4L2_JPEG_APP14_TF_YCCK`: an image encoded with four components using YCCK
- `V4L2_JPEG_APP14_TF_UNKNOWN`: indicate app14 is not present

#### <a id="c-struct-v4l2_jpeg_header"></a>`struct v4l2_jpeg_header`

parsed JPEG header

**Definition**

```c
struct v4l2_jpeg_header {
    struct v4l2_jpeg_reference sof;
    struct v4l2_jpeg_reference sos;
    unsigned int num_dht;
    struct v4l2_jpeg_reference dht[V4L2_JPEG_MAX_TABLES];
    unsigned int num_dqt;
    struct v4l2_jpeg_reference dqt[V4L2_JPEG_MAX_TABLES];
    struct v4l2_jpeg_frame_header frame;
    struct v4l2_jpeg_scan_header *scan;
    struct v4l2_jpeg_reference *quantization_tables;
    struct v4l2_jpeg_reference *huffman_tables;
    u16 restart_interval;
    size_t ecs_offset;
    enum v4l2_jpeg_app14_tf app14_tf;
};
```

**Members**

- `sof`: pointer to frame header and size
- `sos`: pointer to scan header and size
- `num_dht`: number of entries in **dht**
- `dht`: pointers to huffman tables and sizes
- `num_dqt`: number of entries in **dqt**
- `dqt`: pointers to quantization tables and sizes
- `frame`: parsed frame header
- `scan`: pointer to parsed scan header, optional
- `quantization_tables`: references to four quantization tables, optional
- `huffman_tables`: references to four Huffman tables in DC0, DC1, AC0, AC1
  order, optional
- `restart_interval`: number of MCU per restart interval, Ri
- `ecs_offset`: buffer offset in bytes to the entropy coded segment
- `app14_tf`: transform flag from app14 data

**Description**

When this structure is passed to v4l2_jpeg_parse_header, the optional scan,
quantization_tables, and huffman_tables pointers must be initialized to NULL
or point at valid memory.



#### <a id="c-v4l2_jpeg_parse_header"></a>`v4l2_jpeg_parse_header()`

```c
int v4l2_jpeg_parse_header(void *buf, size_t len, struct v4l2_jpeg_header *out)
```

locate marker segments and optionally parse headers

**Parameters**

- `void *buf`: address of the JPEG buffer, should start with a SOI marker
- `size_t len`: length of the JPEG buffer
- `struct v4l2_jpeg_header *out`: returns marker segment positions and optionally parsed headers

**Description**

The out->scan_header pointer must be initialized to NULL or point to a valid
v4l2_jpeg_scan_header structure. The out->huffman_tables and
out->quantization_tables pointers must be initialized to NULL or point to a
valid array of 4 v4l2_jpeg_reference structures each.

Returns 0 or negative error if parsing failed.

---

# V4L2 Media Controller functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 Media Controller functions and data structures.

<a id="rst-v4l2-media-controller-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-v4l2_mc_create_media_graph"></a>`v4l2_mc_create_media_graph()`

```c
int v4l2_mc_create_media_graph(struct media_device *mdev)
```

create Media Controller links at the graph.

**Parameters**

- `struct media_device *mdev`: pointer to the [`media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device) struct.

**Description**

Add links between the entities commonly found on PC customer's hardware at
the V4L2 side: camera sensors, audio and video PLL-IF decoders, tuners,
analog TV decoder and I/O entities (video, VBI and Software Defined Radio).

> [!NOTE]
> Webcams are modelled on a very simple way: the sensor is
> connected directly to the I/O entity. All dirty details, like
> scaler and crop HW are hidden. While such mapping is enough for v4l2
> interface centric PC-consumer's hardware, V4L2 subdev centric camera
> hardware should not use this routine, as it will not build the right graph.

#### <a id="c-v4l_enable_media_source"></a>`v4l_enable_media_source()`

```c
int v4l_enable_media_source(struct video_device *vdev)
```

Hold media source for exclusive use if free

**Parameters**

- `struct video_device *vdev`: pointer to struct video_device

**Description**

This interface calls enable_source handler to determine if
media source is free for use. The enable_source handler is
responsible for checking is the media source is free and
start a pipeline between the media source and the media
entity associated with the video device. This interface
should be called from v4l2-core and dvb-core interfaces
that change the source configuration.

**Return**

returns zero on success or a negative error code.

#### <a id="c-v4l_disable_media_source"></a>`v4l_disable_media_source()`

```c
void v4l_disable_media_source(struct video_device *vdev)
```

Release media source

**Parameters**

- `struct video_device *vdev`: pointer to struct video_device

**Description**

This interface calls disable_source handler to release
the media source. The disable_source handler stops the
active media pipeline between the media source and the
media entity associated with the video device.

**Return**

returns zero on success or a negative error code.

#### <a id="c-v4l2_create_fwnode_links_to_pad"></a>`v4l2_create_fwnode_links_to_pad()`

```c
int v4l2_create_fwnode_links_to_pad(struct v4l2_subdev *src_sd, struct media_pad *sink, u32 flags)
```

Create fwnode-based links from a source subdev to a sink pad.

**Parameters**

- `struct v4l2_subdev *src_sd`: pointer to a source subdev
- `struct media_pad *sink`: pointer to a sink pad
- `u32 flags`: the link flags

**Description**

This function searches for fwnode endpoint connections from a source
subdevice to a single sink pad, and if suitable connections are found,
translates them into media links to that pad. The function can be
called by the sink, in its v4l2-async notifier bound callback, to create
links from a bound source subdevice.

The **flags** argument specifies the link flags. The caller shall ensure that
the flags are valid regardless of the number of links that may be created.
For instance, setting the MEDIA_LNK_FL_ENABLED flag will cause all created
links to be enabled, which isn't valid if more than one link is created.

> [!NOTE]
> Any sink subdevice that calls this function must implement the
> .get_fwnode_pad media operation in order to verify endpoints passed
> to the sink are owned by the sink.

Return 0 on success or a negative error code on failure.

#### <a id="c-v4l2_create_fwnode_links"></a>`v4l2_create_fwnode_links()`

```c
int v4l2_create_fwnode_links(struct v4l2_subdev *src_sd, struct v4l2_subdev *sink_sd)
```

Create fwnode-based links from a source subdev to a sink subdev.

**Parameters**

- `struct v4l2_subdev *src_sd`: pointer to a source subdevice
- `struct v4l2_subdev *sink_sd`: pointer to a sink subdevice

**Description**

This function searches for any and all fwnode endpoint connections
between source and sink subdevices, and translates them into media
links. The function can be called by the sink subdevice, in its
v4l2-async notifier subdev bound callback, to create all links from
a bound source subdevice.

> [!NOTE]
> Any sink subdevice that calls this function must implement the
> .get_fwnode_pad media operation in order to verify endpoints passed
> to the sink are owned by the sink.

Return 0 on success or a negative error code on failure.

#### <a id="c-v4l2_pipeline_pm_get"></a>`v4l2_pipeline_pm_get()`

```c
int v4l2_pipeline_pm_get(struct media_entity *entity)
```

Increase the use count of a pipeline

**Parameters**

- `struct media_entity *entity`: The root entity of a pipeline

**Description**

THIS FUNCTION IS DEPRECATED. DO NOT USE IN NEW DRIVERS. USE RUNTIME PM
ON SUB-DEVICE DRIVERS INSTEAD.

Update the use count of all entities in the pipeline and power entities on.

This function is intended to be called in video node open. It uses
struct media_entity.use_count to track the power status. The use
of this function should be paired with [`v4l2_pipeline_link_notify()`](#c-v4l2_pipeline_link_notify).

Return 0 on success or a negative error code on failure.

#### <a id="c-v4l2_pipeline_pm_put"></a>`v4l2_pipeline_pm_put()`

```c
void v4l2_pipeline_pm_put(struct media_entity *entity)
```

Decrease the use count of a pipeline

**Parameters**

- `struct media_entity *entity`: The root entity of a pipeline

**Description**

THIS FUNCTION IS DEPRECATED. DO NOT USE IN NEW DRIVERS. USE RUNTIME PM
ON SUB-DEVICE DRIVERS INSTEAD.

Update the use count of all entities in the pipeline and power entities off.

This function is intended to be called in video node release. It uses
struct media_entity.use_count to track the power status. The use
of this function should be paired with [`v4l2_pipeline_link_notify()`](#c-v4l2_pipeline_link_notify).

#### <a id="c-v4l2_pipeline_link_notify"></a>`v4l2_pipeline_link_notify()`

```c
int v4l2_pipeline_link_notify(struct media_link *link, u32 flags, unsigned int notification)
```

Link management notification callback

**Parameters**

- `struct media_link *link`: The link
- `u32 flags`: New link flags that will be applied
- `unsigned int notification`: The link's state change notification type (MEDIA_DEV_NOTIFY_*)

**Description**

THIS FUNCTION IS DEPRECATED. DO NOT USE IN NEW DRIVERS. USE RUNTIME PM
ON SUB-DEVICE DRIVERS INSTEAD.

React to link management on powered pipelines by updating the use count of
all entities in the source and sink sides of the link. Entities are powered
on or off accordingly. The use of this function should be paired
with v4l2_pipeline_pm_{get,put}().

Return 0 on success or a negative error code on failure. Powering entities
off is assumed to never fail. This function will not fail for disconnection
events.

---

# V4L2 Media Bus functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 Media Bus functions and data structures.

<a id="rst-v4l2-media-bus-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-v4l2_mbus_csi2_cphy_line_orders_type"></a>`enum v4l2_mbus_csi2_cphy_line_orders_type`

CSI-2 C-PHY line order

**Constants**

- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_ABC`: C-PHY line order ABC (default)
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_ACB`: C-PHY line order ACB
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_BAC`: C-PHY line order BAC
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_BCA`: C-PHY line order BCA
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_CAB`: C-PHY line order CAB
- `V4L2_MBUS_CSI2_CPHY_LINE_ORDER_CBA`: C-PHY line order CBA

#### <a id="c-struct-v4l2_mbus_config_mipi_csi2"></a>`struct v4l2_mbus_config_mipi_csi2`

MIPI CSI-2 data bus configuration

**Definition**

```c
struct v4l2_mbus_config_mipi_csi2 {
    unsigned int flags;
    unsigned char data_lanes[V4L2_MBUS_CSI2_MAX_DATA_LANES];
    unsigned char clock_lane;
    unsigned char num_data_lanes;
    bool lane_polarities[1 + V4L2_MBUS_CSI2_MAX_DATA_LANES];
    enum v4l2_mbus_csi2_cphy_line_orders_type line_orders[V4L2_MBUS_CSI2_MAX_DATA_LANES];
};
```

**Members**

- `flags`: media bus (V4L2_MBUS_*) flags
- `data_lanes`: an array of physical data lane indexes
- `clock_lane`: physical lane index of the clock lane
- `num_data_lanes`: number of data lanes
- `lane_polarities`: polarity of the lanes. The order is the same of
  the physical lanes.
- `line_orders`: line order of the data lanes. The order is the same of the
  physical lanes.

#### <a id="c-struct-v4l2_mbus_config_parallel"></a>`struct v4l2_mbus_config_parallel`

parallel data bus configuration

**Definition**

```c
struct v4l2_mbus_config_parallel {
    unsigned int flags;
    unsigned char bus_width;
    unsigned char data_shift;
};
```

**Members**

- `flags`: media bus (V4L2_MBUS_*) flags
- `bus_width`: bus width in bits
- `data_shift`: data shift in bits

#### <a id="c-struct-v4l2_mbus_config_mipi_csi1"></a>`struct v4l2_mbus_config_mipi_csi1`

CSI-1/CCP2 data bus configuration

**Definition**

```c
struct v4l2_mbus_config_mipi_csi1 {
    unsigned char clock_inv:1;
    unsigned char strobe:1;
    bool lane_polarity[2];
    unsigned char data_lane;
    unsigned char clock_lane;
};
```

**Members**

- `clock_inv`: polarity of clock/strobe signal
  false - not inverted, true - inverted
- `strobe`: false - data/clock, true - data/strobe
- `lane_polarity`: the polarities of the clock (index 0) and data lanes
  index (1)
- `data_lane`: the number of the data lane
- `clock_lane`: the number of the clock lane

#### <a id="c-enum-v4l2_mbus_type"></a>`enum v4l2_mbus_type`

media bus type

**Constants**

- `V4L2_MBUS_UNKNOWN`: unknown bus type, no V4L2 mediabus configuration
- `V4L2_MBUS_PARALLEL`: parallel interface with hsync and vsync
- `V4L2_MBUS_BT656`: parallel interface with embedded synchronisation, can
  also be used for BT.1120
- `V4L2_MBUS_CSI1`: MIPI CSI-1 serial interface
- `V4L2_MBUS_CCP2`: CCP2 (Compact Camera Port 2)
- `V4L2_MBUS_CSI2_DPHY`: MIPI CSI-2 serial interface, with D-PHY
- `V4L2_MBUS_CSI2_CPHY`: MIPI CSI-2 serial interface, with C-PHY
- `V4L2_MBUS_DPI`: MIPI VIDEO DPI interface
- `V4L2_MBUS_INVALID`: invalid bus type (keep as last)

#### <a id="c-struct-v4l2_mbus_config"></a>`struct v4l2_mbus_config`

media bus configuration

**Definition**

```c
struct v4l2_mbus_config {
    enum v4l2_mbus_type type;
    u64 link_freq;
    union {
        struct v4l2_mbus_config_parallel parallel;
        struct v4l2_mbus_config_mipi_csi1 mipi_csi1;
        struct v4l2_mbus_config_mipi_csi2 mipi_csi2;
    } bus;
};
```

**Members**

- `type`: interface type
- `link_freq`: The link frequency. See also V4L2_CID_LINK_FREQ control.
- `bus`: bus configuration data structure
- `bus.parallel`: embedded [`struct v4l2_mbus_config_parallel`](#c-struct-v4l2_mbus_config_parallel).
  Used if the bus is parallel or BT.656.
- `bus.mipi_csi1`: embedded [`struct v4l2_mbus_config_mipi_csi1`](#c-struct-v4l2_mbus_config_mipi_csi1).
  Used if the bus is MIPI Alliance's Camera Serial
  Interface version 1 (MIPI CSI1) or Standard
  Mobile Imaging Architecture's Compact Camera Port 2
  (SMIA CCP2).
- `bus.mipi_csi2`: embedded [`struct v4l2_mbus_config_mipi_csi2`](#c-struct-v4l2_mbus_config_mipi_csi2).
  Used if the bus is MIPI Alliance's Camera Serial
  Interface version 2 (MIPI CSI2).

#### <a id="c-v4l2_fill_pix_format"></a>`v4l2_fill_pix_format()`

```c
void v4l2_fill_pix_format(struct v4l2_pix_format *pix_fmt, const struct v4l2_mbus_framefmt *mbus_fmt)
```

Ancillary routine that fills a [`struct v4l2_pix_format`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2.md#c-v4l2_pix_format) fields from a [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt).

**Parameters**

- `struct v4l2_pix_format *pix_fmt`: pointer to [`struct v4l2_pix_format`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2.md#c-v4l2_pix_format) to be filled
- `const struct v4l2_mbus_framefmt *mbus_fmt`: pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) to be used as model

#### <a id="c-v4l2_fill_mbus_format"></a>`v4l2_fill_mbus_format()`

```c
void v4l2_fill_mbus_format(struct v4l2_mbus_framefmt *mbus_fmt, const struct v4l2_pix_format *pix_fmt, u32 code)
```

Ancillary routine that fills a [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) from a [`struct v4l2_pix_format`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2.md#c-v4l2_pix_format) and a data format code.

**Parameters**

- `struct v4l2_mbus_framefmt *mbus_fmt`: pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) to be filled
- `const struct v4l2_pix_format *pix_fmt`: pointer to [`struct v4l2_pix_format`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2.md#c-v4l2_pix_format) to be used as model
- `u32 code`: data format code (from `enum v4l2_mbus_pixelcode`)

#### <a id="c-v4l2_fill_pix_format_mplane"></a>`v4l2_fill_pix_format_mplane()`

```c
void v4l2_fill_pix_format_mplane(struct v4l2_pix_format_mplane *pix_mp_fmt, const struct v4l2_mbus_framefmt *mbus_fmt)
```

Ancillary routine that fills a [`struct v4l2_pix_format_mplane`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2-mplane.md#c-v4l2_pix_format_mplane) fields from a media bus structure.

**Parameters**

- `struct v4l2_pix_format_mplane *pix_mp_fmt`: pointer to [`struct v4l2_pix_format_mplane`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2-mplane.md#c-v4l2_pix_format_mplane) to be filled
- `const struct v4l2_mbus_framefmt *mbus_fmt`: pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) to be used as model

#### <a id="c-v4l2_fill_mbus_format_mplane"></a>`v4l2_fill_mbus_format_mplane()`

```c
void v4l2_fill_mbus_format_mplane(struct v4l2_mbus_framefmt *mbus_fmt, const struct v4l2_pix_format_mplane *pix_mp_fmt)
```

Ancillary routine that fills a [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) from a [`struct v4l2_pix_format_mplane`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2-mplane.md#c-v4l2_pix_format_mplane).

**Parameters**

- `struct v4l2_mbus_framefmt *mbus_fmt`: pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) to be filled
- `const struct v4l2_pix_format_mplane *pix_mp_fmt`: pointer to [`struct v4l2_pix_format_mplane`](/kernel/userspace/userspace-api/media-v4l/pixfmt-v4l2-mplane.md#c-v4l2_pix_format_mplane) to be used as model

---

# V4L2 Memory to Memory functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 Memory to Memory functions and data structures.

<a id="rst-v4l2-memory-to-memory-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-v4l2_m2m_ops"></a>`struct v4l2_m2m_ops`

mem-to-mem device driver callbacks

**Definition**

```c
struct v4l2_m2m_ops {
    void (*device_run)(void *priv);
    int (*job_ready)(void *priv);
    void (*job_abort)(void *priv);
};
```

**Members**

- `device_run`: required. Begin the actual job (transaction) inside this
  callback.
  The job does NOT have to end before this callback returns
  (and it will be the usual case). When the job finishes,
  [`v4l2_m2m_job_finish()`](#c-v4l2_m2m_job_finish) or [`v4l2_m2m_buf_done_and_job_finish()`](#c-v4l2_m2m_buf_done_and_job_finish)
  has to be called.
- `job_ready`: optional. Should return 0 if the driver does not have a job
  fully prepared to run yet (i.e. it will not be able to finish a
  transaction without sleeping). If not provided, it will be
  assumed that one source and one destination buffer are all
  that is required for the driver to perform one full transaction.
  This method may not sleep.
- `job_abort`: optional. Informs the driver that it has to abort the currently
  running transaction as soon as possible (i.e. as soon as it can
  stop the device safely; e.g. in the next interrupt handler),
  even if the transaction would not have been finished by then.
  After the driver performs the necessary steps, it has to call
  [`v4l2_m2m_job_finish()`](#c-v4l2_m2m_job_finish) or [`v4l2_m2m_buf_done_and_job_finish()`](#c-v4l2_m2m_buf_done_and_job_finish) as
  if the transaction ended normally.
  This function does not have to (and will usually not) wait
  until the device enters a state when it can be stopped.

#### <a id="c-struct-v4l2_m2m_queue_ctx"></a>`struct v4l2_m2m_queue_ctx`

represents a queue for buffers ready to be processed

**Definition**

```c
struct v4l2_m2m_queue_ctx {
    struct vb2_queue        q;
    struct list_head        rdy_queue;
    spinlock_t rdy_spinlock;
    u8 num_rdy;
    bool buffered;
};
```

**Members**

- `q`: pointer to struct [`vb2_queue`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_queue)
- `rdy_queue`: List of V4L2 mem-to-mem queues
- `rdy_spinlock`: spin lock to protect the struct usage
- `num_rdy`: number of buffers ready to be processed
- `buffered`: is the queue buffered?

**Description**

Queue for buffers ready to be processed as soon as this
instance receives access to the device.

#### <a id="c-struct-v4l2_m2m_ctx"></a>`struct v4l2_m2m_ctx`

Memory to memory context structure

**Definition**

```c
struct v4l2_m2m_ctx {
    struct mutex                    *q_lock;
    bool new_frame;
    bool is_draining;
    struct vb2_v4l2_buffer          *last_src_buf;
    bool next_buf_last;
    bool has_stopped;
    bool ignore_cap_streaming;
    struct v4l2_m2m_dev             *m2m_dev;
    struct v4l2_m2m_queue_ctx       cap_q_ctx;
    struct v4l2_m2m_queue_ctx       out_q_ctx;
    struct list_head                queue;
    unsigned long                   job_flags;
    wait_queue_head_t finished;
    void *priv;
};
```

**Members**

- `q_lock`: struct `mutex` lock
- `new_frame`: valid in the device_run callback: if true, then this
  starts a new frame; if false, then this is a new slice
  for an existing frame. This is always true unless
  V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF is set, which
  indicates slicing support.
- `is_draining`: indicates device is in draining phase
- `last_src_buf`: indicate the last source buffer for draining
- `next_buf_last`: next capture queud buffer will be tagged as last
- `has_stopped`: indicate the device has been stopped
- `ignore_cap_streaming`: If true, job_ready can be called even if the CAPTURE
  queue is not streaming. This allows firmware to
  analyze the bitstream header which arrives on the
  OUTPUT queue. The driver must implement the job_ready
  callback correctly to make sure that the requirements
  for actual decoding are met.
- `m2m_dev`: opaque pointer to the internal data to handle M2M context
- `cap_q_ctx`: Capture (output to memory) queue context
- `out_q_ctx`: Output (input from memory) queue context
- `queue`: List of memory to memory contexts
- `job_flags`: Job queue flags, used internally by v4l2-mem2mem.c:
  `TRANS_QUEUED`, `TRANS_RUNNING` and `TRANS_ABORT`.
- `finished`: Wait queue used to signalize when a job queue finished.
- `priv`: Instance private data

**Description**

The memory to memory context is specific to a file handle, NOT to e.g.
a device.

#### <a id="c-struct-v4l2_m2m_buffer"></a>`struct v4l2_m2m_buffer`

Memory to memory buffer

**Definition**

```c
struct v4l2_m2m_buffer {
    struct vb2_v4l2_buffer  vb;
    struct list_head        list;
};
```

**Members**

- `vb`: pointer to struct [`vb2_v4l2_buffer`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_v4l2_buffer)
- `list`: list of m2m buffers

#### <a id="c-v4l2_m2m_get_curr_priv"></a>`v4l2_m2m_get_curr_priv()`

```c
void * v4l2_m2m_get_curr_priv(struct v4l2_m2m_dev *m2m_dev)
```

return driver private data for the currently running instance or NULL if no instance is running

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

#### <a id="c-v4l2_m2m_get_vq"></a>`v4l2_m2m_get_vq()`

```c
struct vb2_queue * v4l2_m2m_get_vq(struct v4l2_m2m_ctx *m2m_ctx, enum v4l2_buf_type type)
```

return vb2_queue for the given type

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `enum v4l2_buf_type type`: type of the V4L2 buffer, as defined by enum `v4l2_buf_type`

**Description**

This function returns the capture queue when **type** is a capture type, and the
output queue otherwise. It never returns a NULL pointer.

#### <a id="c-v4l2_m2m_try_schedule"></a>`v4l2_m2m_try_schedule()`

```c
void v4l2_m2m_try_schedule(struct v4l2_m2m_ctx *m2m_ctx)
```

check whether an instance is ready to be added to the pending job queue and add it if so.

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

**Description**

There are three basic requirements an instance has to meet to be able to run:
1) at least one source buffer has to be queued,
2) at least one destination buffer has to be queued,
3) streaming has to be on.

If a queue is buffered (for example a decoder hardware ringbuffer that has
to be drained before doing streamoff), allow scheduling without v4l2 buffers
on that queue.

There may also be additional, custom requirements. In such case the driver
should supply a custom callback (job_ready in v4l2_m2m_ops) that should
return 1 if the instance is ready.
An example of the above could be an instance that requires more than one
src/dst buffer per transaction.

#### <a id="c-v4l2_m2m_job_finish"></a>`v4l2_m2m_job_finish()`

```c
void v4l2_m2m_job_finish(struct v4l2_m2m_dev *m2m_dev, struct v4l2_m2m_ctx *m2m_ctx)
```

inform the framework that a job has been finished and have it clean up

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

**Description**

Called by a driver to yield back the device after it has finished with it.
Should be called as soon as possible after reaching a state which allows
other instances to take control of the device.

This function has to be called only after [`v4l2_m2m_ops->device_run`](#c-struct-v4l2_m2m_ops)
callback has been called on the driver.

#### <a id="c-v4l2_m2m_buf_done_and_job_finish"></a>`v4l2_m2m_buf_done_and_job_finish()`

```c
void v4l2_m2m_buf_done_and_job_finish(struct v4l2_m2m_dev *m2m_dev, struct v4l2_m2m_ctx *m2m_ctx, enum vb2_buffer_state state)
```

return source/destination buffers with state and inform the framework that a job has been finished and have it clean up

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `enum vb2_buffer_state state`: vb2 buffer state passed to `v4l2_m2m_buf_done()`.

**Description**

Drivers that set V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF must use this
function instead of `job_finish()` to take held buffers into account. It is
optional for other drivers.

This function removes the source buffer from the ready list and returns
it with the given state. The same is done for the destination buffer, unless
it is marked 'held'. In that case the buffer is kept on the ready list.

After that the job is finished (see `job_finish()`).

This allows for multiple output buffers to be used to fill in a single
capture buffer. This is typically used by stateless decoders where
multiple e.g. H.264 slices contribute to a single decoded frame.

#### <a id="c-v4l2_m2m_clear_state"></a>`v4l2_m2m_clear_state()`

```c
void v4l2_m2m_clear_state(struct v4l2_m2m_ctx *m2m_ctx)
```

clear encoding/decoding state

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_mark_stopped"></a>`v4l2_m2m_mark_stopped()`

```c
void v4l2_m2m_mark_stopped(struct v4l2_m2m_ctx *m2m_ctx)
```

set current encoding/decoding state as stopped

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_dst_buf_is_last"></a>`v4l2_m2m_dst_buf_is_last()`

```c
bool v4l2_m2m_dst_buf_is_last(struct v4l2_m2m_ctx *m2m_ctx)
```

return the current encoding/decoding session draining management state of next queued capture buffer

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

**Description**

This last capture buffer should be tagged with V4L2_BUF_FLAG_LAST to notify
the end of the capture session.

#### <a id="c-v4l2_m2m_has_stopped"></a>`v4l2_m2m_has_stopped()`

```c
bool v4l2_m2m_has_stopped(struct v4l2_m2m_ctx *m2m_ctx)
```

return the current encoding/decoding session stopped state

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_is_last_draining_src_buf"></a>`v4l2_m2m_is_last_draining_src_buf()`

```c
bool v4l2_m2m_is_last_draining_src_buf(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

return the output buffer draining state in the current encoding/decoding session

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: pointer to struct `v4l2_buffer`

**Description**

This will identify the last output buffer queued before a session stop
was required, leading to an actual encoding/decoding session stop state
in the encoding/decoding process after being processed.

#### <a id="c-v4l2_m2m_last_buffer_done"></a>`v4l2_m2m_last_buffer_done()`

```c
void v4l2_m2m_last_buffer_done(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

marks the buffer with LAST flag and DONE

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: pointer to struct `v4l2_buffer`

#### <a id="c-v4l2_m2m_suspend"></a>`v4l2_m2m_suspend()`

```c
void v4l2_m2m_suspend(struct v4l2_m2m_dev *m2m_dev)
```

stop new jobs from being run and wait for current job to finish

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

Called by a driver in the suspend hook. Stop new jobs from being run, and
wait for current running job to finish.

#### <a id="c-v4l2_m2m_resume"></a>`v4l2_m2m_resume()`

```c
void v4l2_m2m_resume(struct v4l2_m2m_dev *m2m_dev)
```

resume job running and try to run a queued job

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

Called by a driver in the resume hook. This reverts the operation of
[`v4l2_m2m_suspend()`](#c-v4l2_m2m_suspend) and allows job to be run. Also try to run a queued job if
there is any.

#### <a id="c-v4l2_m2m_reqbufs"></a>`v4l2_m2m_reqbufs()`

```c
int v4l2_m2m_reqbufs(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_requestbuffers *reqbufs)
```

multi-queue-aware REQBUFS multiplexer

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_requestbuffers *reqbufs`: pointer to struct `v4l2_requestbuffers`

#### <a id="c-v4l2_m2m_querybuf"></a>`v4l2_m2m_querybuf()`

```c
int v4l2_m2m_querybuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_buffer *buf)
```

multi-queue-aware QUERYBUF multiplexer

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_buffer *buf`: pointer to struct `v4l2_buffer`

**Description**

See [`v4l2_m2m_mmap()`](#c-v4l2_m2m_mmap) documentation for details.

#### <a id="c-v4l2_m2m_qbuf"></a>`v4l2_m2m_qbuf()`

```c
int v4l2_m2m_qbuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_buffer *buf)
```

enqueue a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_buffer *buf`: pointer to struct `v4l2_buffer`

#### <a id="c-v4l2_m2m_dqbuf"></a>`v4l2_m2m_dqbuf()`

```c
int v4l2_m2m_dqbuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_buffer *buf)
```

dequeue a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_buffer *buf`: pointer to struct `v4l2_buffer`

#### <a id="c-v4l2_m2m_prepare_buf"></a>`v4l2_m2m_prepare_buf()`

```c
int v4l2_m2m_prepare_buf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_buffer *buf)
```

prepare a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_buffer *buf`: pointer to struct `v4l2_buffer`

#### <a id="c-v4l2_m2m_create_bufs"></a>`v4l2_m2m_create_bufs()`

```c
int v4l2_m2m_create_bufs(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_create_buffers *create)
```

create a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_create_buffers *create`: pointer to struct `v4l2_create_buffers`

#### <a id="c-v4l2_m2m_expbuf"></a>`v4l2_m2m_expbuf()`

```c
int v4l2_m2m_expbuf(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_exportbuffer *eb)
```

export a source or destination buffer, depending on the type

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_exportbuffer *eb`: pointer to struct `v4l2_exportbuffer`

#### <a id="c-v4l2_m2m_streamon"></a>`v4l2_m2m_streamon()`

```c
int v4l2_m2m_streamon(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, enum v4l2_buf_type type)
```

turn on streaming for a video queue

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `enum v4l2_buf_type type`: type of the V4L2 buffer, as defined by enum `v4l2_buf_type`

#### <a id="c-v4l2_m2m_streamoff"></a>`v4l2_m2m_streamoff()`

```c
int v4l2_m2m_streamoff(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, enum v4l2_buf_type type)
```

turn off streaming for a video queue

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `enum v4l2_buf_type type`: type of the V4L2 buffer, as defined by enum `v4l2_buf_type`

#### <a id="c-v4l2_m2m_update_start_streaming_state"></a>`v4l2_m2m_update_start_streaming_state()`

```c
void v4l2_m2m_update_start_streaming_state(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_queue *q)
```

update the encoding/decoding session state when a start of streaming of a video queue is requested

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_queue *q`: queue

#### <a id="c-v4l2_m2m_update_stop_streaming_state"></a>`v4l2_m2m_update_stop_streaming_state()`

```c
void v4l2_m2m_update_stop_streaming_state(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_queue *q)
```

update the encoding/decoding session state when a stop of streaming of a video queue is requested

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_queue *q`: queue

#### <a id="c-v4l2_m2m_encoder_cmd"></a>`v4l2_m2m_encoder_cmd()`

```c
int v4l2_m2m_encoder_cmd(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_encoder_cmd *ec)
```

execute an encoder command

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_encoder_cmd *ec`: pointer to the encoder command

#### <a id="c-v4l2_m2m_decoder_cmd"></a>`v4l2_m2m_decoder_cmd()`

```c
int v4l2_m2m_decoder_cmd(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct v4l2_decoder_cmd *dc)
```

execute a decoder command

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct v4l2_decoder_cmd *dc`: pointer to the decoder command

#### <a id="c-v4l2_m2m_poll"></a>`v4l2_m2m_poll()`

```c
__poll_t v4l2_m2m_poll(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct poll_table_struct *wait)
```

poll replacement, for destination buffers only

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct poll_table_struct *wait`: pointer to struct `poll_table_struct`

**Description**

Call from the driver's `poll()` function. Will poll both queues. If a buffer
is available to dequeue (with dqbuf) from the source queue, this will
indicate that a non-blocking write can be performed, while read will be
returned in case of the destination queue.

#### <a id="c-v4l2_m2m_mmap"></a>`v4l2_m2m_mmap()`

```c
int v4l2_m2m_mmap(struct file *file, struct v4l2_m2m_ctx *m2m_ctx, struct vm_area_struct *vma)
```

source and destination queues-aware mmap multiplexer

**Parameters**

- `struct file *file`: pointer to struct [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)
- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vm_area_struct *vma`: pointer to struct `vm_area_struct`

**Description**

Call from driver's `mmap()` function. Will handle `mmap()` for both queues
seamlessly for the video buffer, which will receive normal per-queue offsets
and proper vb2 queue pointers. The differentiation is made outside
vb2 by adding a predefined offset to buffers from one of the queues
and subtracting it before passing it back to vb2. Only drivers (and
thus applications) receive modified offsets.

#### <a id="c-v4l2_m2m_init"></a>`v4l2_m2m_init()`

```c
struct v4l2_m2m_dev * v4l2_m2m_init(const struct v4l2_m2m_ops *m2m_ops)
```

initialize per-driver m2m data

**Parameters**

- `const struct v4l2_m2m_ops *m2m_ops`: pointer to struct v4l2_m2m_ops

**Description**

Usually called from driver's `probe()` function.

**Return**

returns an opaque pointer to the internal data to handle M2M context

#### <a id="c-v4l2_m2m_release"></a>`v4l2_m2m_release()`

```c
void v4l2_m2m_release(struct v4l2_m2m_dev *m2m_dev)
```

cleans up and frees a m2m_dev structure

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

Usually called from driver's `remove()` function.

#### <a id="c-v4l2_m2m_get"></a>`v4l2_m2m_get()`

```c
void v4l2_m2m_get(struct v4l2_m2m_dev *m2m_dev)
```

take a reference to the m2m_dev structure

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

This is used to share the M2M device across multiple devices. This
can be used to avoid scheduling two hardware nodes concurrently.

#### <a id="c-v4l2_m2m_put"></a>`v4l2_m2m_put()`

```c
void v4l2_m2m_put(struct v4l2_m2m_dev *m2m_dev)
```

remove a reference to the m2m_dev structure

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context

**Description**

Once the M2M device has no more references, [`v4l2_m2m_release()`](#c-v4l2_m2m_release) will be
called automatically. Users of this method should never call
[`v4l2_m2m_release()`](#c-v4l2_m2m_release) directly. See [`v4l2_m2m_get()`](#c-v4l2_m2m_get) for more details.

#### <a id="c-v4l2_m2m_ctx_init"></a>`v4l2_m2m_ctx_init()`

```c
struct v4l2_m2m_ctx * v4l2_m2m_ctx_init(struct v4l2_m2m_dev *m2m_dev, void *drv_priv, int (*queue_init)(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq))
```

allocate and initialize a m2m context

**Parameters**

- `struct v4l2_m2m_dev *m2m_dev`: opaque pointer to the internal data to handle M2M context
- `void *drv_priv`: driver's instance private data
- `int (*queue_init)(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq)`: a callback for queue type-specific initialization function
  to be used for initializing vb2_queues

**Description**

Usually called from driver's `open()` function.

#### <a id="c-v4l2_m2m_ctx_release"></a>`v4l2_m2m_ctx_release()`

```c
void v4l2_m2m_ctx_release(struct v4l2_m2m_ctx *m2m_ctx)
```

release m2m context

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

**Description**

Usually called from driver's `release()` function.

#### <a id="c-v4l2_m2m_buf_queue"></a>`v4l2_m2m_buf_queue()`

```c
void v4l2_m2m_buf_queue(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

add a buffer to the proper ready buffers list.

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: pointer to struct [`vb2_v4l2_buffer`](/kernel/hardware/driver-api/media/v4l2-videobuf2.md#c-struct-vb2_v4l2_buffer)

**Description**

Call from vb2_queue_ops->ops->buf_queue, vb2_queue_ops callback.

#### <a id="c-v4l2_m2m_num_src_bufs_ready"></a>`v4l2_m2m_num_src_bufs_ready()`

```c
unsigned int v4l2_m2m_num_src_bufs_ready(struct v4l2_m2m_ctx *m2m_ctx)
```

return the number of source buffers ready for use

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_num_dst_bufs_ready"></a>`v4l2_m2m_num_dst_bufs_ready()`

```c
unsigned int v4l2_m2m_num_dst_bufs_ready(struct v4l2_m2m_ctx *m2m_ctx)
```

return the number of destination buffers ready for use

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_next_buf"></a>`v4l2_m2m_next_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_next_buf(struct v4l2_m2m_queue_ctx *q_ctx)
```

return next buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_queue_ctx *q_ctx`: pointer to struct **v4l2_m2m_queue_ctx**

#### <a id="c-v4l2_m2m_next_src_buf"></a>`v4l2_m2m_next_src_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_next_src_buf(struct v4l2_m2m_ctx *m2m_ctx)
```

return next source buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_next_dst_buf"></a>`v4l2_m2m_next_dst_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_next_dst_buf(struct v4l2_m2m_ctx *m2m_ctx)
```

return next destination buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_last_buf"></a>`v4l2_m2m_last_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_last_buf(struct v4l2_m2m_queue_ctx *q_ctx)
```

return last buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_queue_ctx *q_ctx`: pointer to struct **v4l2_m2m_queue_ctx**

#### <a id="c-v4l2_m2m_last_src_buf"></a>`v4l2_m2m_last_src_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_last_src_buf(struct v4l2_m2m_ctx *m2m_ctx)
```

return last source buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_last_dst_buf"></a>`v4l2_m2m_last_dst_buf()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_last_dst_buf(struct v4l2_m2m_ctx *m2m_ctx)
```

return last destination buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_for_each_dst_buf"></a>`v4l2_m2m_for_each_dst_buf()`

```c
v4l2_m2m_for_each_dst_buf(m2m_ctx, b)
```

iterate over a list of destination ready buffers

**Parameters**

- `m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `b`: current buffer of type struct v4l2_m2m_buffer

#### <a id="c-v4l2_m2m_for_each_src_buf"></a>`v4l2_m2m_for_each_src_buf()`

```c
v4l2_m2m_for_each_src_buf(m2m_ctx, b)
```

iterate over a list of source ready buffers

**Parameters**

- `m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `b`: current buffer of type struct v4l2_m2m_buffer

#### <a id="c-v4l2_m2m_for_each_dst_buf_safe"></a>`v4l2_m2m_for_each_dst_buf_safe()`

```c
v4l2_m2m_for_each_dst_buf_safe(m2m_ctx, b, n)
```

iterate over a list of destination ready buffers safely

**Parameters**

- `m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `b`: current buffer of type struct v4l2_m2m_buffer
- `n`: used as temporary storage

#### <a id="c-v4l2_m2m_for_each_src_buf_safe"></a>`v4l2_m2m_for_each_src_buf_safe()`

```c
v4l2_m2m_for_each_src_buf_safe(m2m_ctx, b, n)
```

iterate over a list of source ready buffers safely

**Parameters**

- `m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `b`: current buffer of type struct v4l2_m2m_buffer
- `n`: used as temporary storage

#### <a id="c-v4l2_m2m_get_src_vq"></a>`v4l2_m2m_get_src_vq()`

```c
struct vb2_queue * v4l2_m2m_get_src_vq(struct v4l2_m2m_ctx *m2m_ctx)
```

return vb2_queue for source buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_get_dst_vq"></a>`v4l2_m2m_get_dst_vq()`

```c
struct vb2_queue * v4l2_m2m_get_dst_vq(struct v4l2_m2m_ctx *m2m_ctx)
```

return vb2_queue for destination buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_buf_remove"></a>`v4l2_m2m_buf_remove()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_buf_remove(struct v4l2_m2m_queue_ctx *q_ctx)
```

take off a buffer from the list of ready buffers and return it

**Parameters**

- `struct v4l2_m2m_queue_ctx *q_ctx`: pointer to struct **v4l2_m2m_queue_ctx**

#### <a id="c-v4l2_m2m_src_buf_remove"></a>`v4l2_m2m_src_buf_remove()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_src_buf_remove(struct v4l2_m2m_ctx *m2m_ctx)
```

take off a source buffer from the list of ready buffers and return it

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_dst_buf_remove"></a>`v4l2_m2m_dst_buf_remove()`

```c
struct vb2_v4l2_buffer * v4l2_m2m_dst_buf_remove(struct v4l2_m2m_ctx *m2m_ctx)
```

take off a destination buffer from the list of ready buffers and return it

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)

#### <a id="c-v4l2_m2m_buf_remove_by_buf"></a>`v4l2_m2m_buf_remove_by_buf()`

```c
void v4l2_m2m_buf_remove_by_buf(struct v4l2_m2m_queue_ctx *q_ctx, struct vb2_v4l2_buffer *vbuf)
```

take off exact buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_queue_ctx *q_ctx`: pointer to struct **v4l2_m2m_queue_ctx**
- `struct vb2_v4l2_buffer *vbuf`: the buffer to be removed

#### <a id="c-v4l2_m2m_src_buf_remove_by_buf"></a>`v4l2_m2m_src_buf_remove_by_buf()`

```c
void v4l2_m2m_src_buf_remove_by_buf(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

take off exact source buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: the buffer to be removed

#### <a id="c-v4l2_m2m_dst_buf_remove_by_buf"></a>`v4l2_m2m_dst_buf_remove_by_buf()`

```c
void v4l2_m2m_dst_buf_remove_by_buf(struct v4l2_m2m_ctx *m2m_ctx, struct vb2_v4l2_buffer *vbuf)
```

take off exact destination buffer from the list of ready buffers

**Parameters**

- `struct v4l2_m2m_ctx *m2m_ctx`: m2m context assigned to the instance given by struct [`v4l2_m2m_ctx`](#c-struct-v4l2_m2m_ctx)
- `struct vb2_v4l2_buffer *vbuf`: the buffer to be removed

#### <a id="c-v4l2_m2m_buf_copy_metadata"></a>`v4l2_m2m_buf_copy_metadata()`

```c
void v4l2_m2m_buf_copy_metadata(const struct vb2_v4l2_buffer *out_vb, struct vb2_v4l2_buffer *cap_vb)
```

copy buffer metadata from the output buffer to the capture buffer

**Parameters**

- `const struct vb2_v4l2_buffer *out_vb`: the output buffer that is the source of the metadata.
- `struct vb2_v4l2_buffer *cap_vb`: the capture buffer that will receive the metadata.

**Description**

This helper function copies the timestamp, timecode (if the TIMECODE
buffer flag was set), field, and the TIMECODE and TSTAMP_SRC_MASK flags from
**out_vb** to **cap_vb**.

---

# V4L2 rect helper functions

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 rect helper functions.

<a id="rst-v4l2-rect-helper-functions"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-v4l2_rect_set_size_to"></a>`v4l2_rect_set_size_to()`

```c
void v4l2_rect_set_size_to(struct v4l2_rect *r, const struct v4l2_rect *size)
```

copy the width/height values.

**Parameters**

- `struct v4l2_rect *r`: rect whose width and height fields will be set
- `const struct v4l2_rect *size`: rect containing the width and height fields you need.

#### <a id="c-v4l2_rect_set_min_size"></a>`v4l2_rect_set_min_size()`

```c
void v4l2_rect_set_min_size(struct v4l2_rect *r, const struct v4l2_rect *min_size)
```

width and height of r should be >= min_size.

**Parameters**

- `struct v4l2_rect *r`: rect whose width and height will be modified
- `const struct v4l2_rect *min_size`: rect containing the minimal width and height

#### <a id="c-v4l2_rect_set_max_size"></a>`v4l2_rect_set_max_size()`

```c
void v4l2_rect_set_max_size(struct v4l2_rect *r, const struct v4l2_rect *max_size)
```

width and height of r should be \<= max_size

**Parameters**

- `struct v4l2_rect *r`: rect whose width and height will be modified
- `const struct v4l2_rect *max_size`: rect containing the maximum width and height

#### <a id="c-v4l2_rect_map_inside"></a>`v4l2_rect_map_inside()`

```c
void v4l2_rect_map_inside(struct v4l2_rect *r, const struct v4l2_rect *boundary)
```

r should be inside boundary.

**Parameters**

- `struct v4l2_rect *r`: rect that will be modified
- `const struct v4l2_rect *boundary`: rect containing the boundary for **r**

#### <a id="c-v4l2_rect_same_size"></a>`v4l2_rect_same_size()`

```c
bool v4l2_rect_same_size(const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

return true if r1 has the same size as r2

**Parameters**

- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

**Description**

Return true if both rectangles have the same size.

#### <a id="c-v4l2_rect_same_position"></a>`v4l2_rect_same_position()`

```c
bool v4l2_rect_same_position(const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

return true if r1 has the same position as r2

**Parameters**

- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

**Description**

Return true if both rectangles have the same position

#### <a id="c-v4l2_rect_equal"></a>`v4l2_rect_equal()`

```c
bool v4l2_rect_equal(const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

return true if r1 equals r2

**Parameters**

- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

**Description**

Return true if both rectangles have the same size and position.

#### <a id="c-v4l2_rect_intersect"></a>`v4l2_rect_intersect()`

```c
void v4l2_rect_intersect(struct v4l2_rect *r, const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

calculate the intersection of two rects.

**Parameters**

- `struct v4l2_rect *r`: intersection of **r1** and **r2**.
- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

#### <a id="c-v4l2_rect_scale"></a>`v4l2_rect_scale()`

```c
void v4l2_rect_scale(struct v4l2_rect *r, const struct v4l2_rect *from, const struct v4l2_rect *to)
```

scale rect r by to/from

**Parameters**

- `struct v4l2_rect *r`: rect to be scaled.
- `const struct v4l2_rect *from`: from rectangle.
- `const struct v4l2_rect *to`: to rectangle.

**Description**

This scales rectangle **r** horizontally by **to->width** / **from->width** and
vertically by **to->height** / **from->height**.

Typically **r** is a rectangle inside **from** and you want the rectangle as
it would appear after scaling **from** to **to**. So the resulting **r** will
be the scaled rectangle inside **to**.

#### <a id="c-v4l2_rect_overlap"></a>`v4l2_rect_overlap()`

```c
bool v4l2_rect_overlap(const struct v4l2_rect *r1, const struct v4l2_rect *r2)
```

do r1 and r2 overlap?

**Parameters**

- `const struct v4l2_rect *r1`: rectangle.
- `const struct v4l2_rect *r2`: rectangle.

**Description**

Returns true if **r1** and **r2** overlap.

#### <a id="c-v4l2_rect_enclosed"></a>`v4l2_rect_enclosed()`

```c
bool v4l2_rect_enclosed(struct v4l2_rect *r1, struct v4l2_rect *r2)
```

is r1 enclosed in r2?

**Parameters**

- `struct v4l2_rect *r1`: rectangle.
- `struct v4l2_rect *r2`: rectangle.

**Description**

Returns true if **r1** is enclosed in **r2**.

---

# V4L2 sub-devices

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Many drivers need to communicate with sub-devices. These devices can do all sort of tasks, but most commonly they handle audio and/or video muxing, encoding or decoding. For webcams common sub-devices are sensors and camera controllers.

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-v4l2-sub-devices"></a>

## V4L2 sub-devices

Many drivers need to communicate with sub-devices. These devices can do all sort of tasks, but most commonly they handle audio and/or video muxing, encoding or decoding. For webcams common sub-devices are sensors and camera controllers.

Usually these are I2C devices, but not necessarily. In order to provide the driver with a consistent interface to these sub-devices the `v4l2_subdev` struct (v4l2-subdev.h) was created.

Each sub-device driver must have a `v4l2_subdev` struct. This struct can be stand-alone for simple sub-devices or it might be embedded in a larger struct if more state information needs to be stored. Usually there is a low-level device struct (e.g. `i2c_client`) that contains the device data as setup by the kernel. It is recommended to store that pointer in the private data of `v4l2_subdev` using `v4l2_set_subdevdata()`. That makes it easy to go from a `v4l2_subdev` to the actual low-level bus-specific device data.

You also need a way to go from the low-level struct to `v4l2_subdev`. For the common i2c_client struct the i2c_set_clientdata() call is used to store a `v4l2_subdev` pointer, for other buses you may have to use other methods.

Bridges might also need to store per-subdev private data, such as a pointer to bridge-specific per-subdev private data. The `v4l2_subdev` structure provides host private data for that purpose that can be accessed with `v4l2_get_subdev_hostdata()` and `v4l2_set_subdev_hostdata()`.

From the bridge driver perspective, you load the sub-device module and somehow obtain the `v4l2_subdev` pointer. For i2c devices this is easy: you call `i2c_get_clientdata()`. For other buses something similar needs to be done. Helper functions exist for sub-devices on an I2C bus that do most of this tricky work for you.

Each `v4l2_subdev` contains function pointers that sub-device drivers can implement (or leave `NULL` if it is not applicable). Since sub-devices can do so many different things and you do not want to end up with a huge ops struct of which only a handful of ops are commonly implemented, the function pointers are sorted according to category and each category has its own ops struct.

The top-level ops struct contains pointers to the category ops structs, which may be NULL if the subdev driver does not support anything from that category.

It looks like this:



```c
struct v4l2_subdev_core_ops {
        int (*log_status)(struct v4l2_subdev *sd);
        int (*init)(struct v4l2_subdev *sd, u32 val);
        ...
};

struct v4l2_subdev_tuner_ops {
        ...
};

struct v4l2_subdev_audio_ops {
        ...
};

struct v4l2_subdev_video_ops {
        ...
};

struct v4l2_subdev_pad_ops {
        ...
};

struct v4l2_subdev_ops {
        const struct v4l2_subdev_core_ops  *core;
        const struct v4l2_subdev_tuner_ops *tuner;
        const struct v4l2_subdev_audio_ops *audio;
        const struct v4l2_subdev_video_ops *video;
        const struct v4l2_subdev_pad_ops *video;
};
```

The core ops are common to all subdevs, the other categories are implemented depending on the sub-device. E.g. a video device is unlikely to support the audio ops and vice versa.

This setup limits the number of function pointers while still making it easy to add new ops and categories.

A sub-device driver initializes the `v4l2_subdev` struct using:

> `v4l2_subdev_init <v4l2_subdev_init>()` (`sd <v4l2_subdev>`, &amp;`ops <v4l2_subdev_ops>`).

Afterwards you need to initialize `sd <v4l2_subdev>`-&gt;name with a unique name and set the module owner. This is done for you if you use the i2c helper functions.

If integration with the media framework is needed, you must initialize the `media_entity` struct embedded in the `v4l2_subdev` struct (entity field) by calling `media_entity_pads_init()`, if the entity has pads:



```c
struct media_pad *pads = &my_sd->pads;
int err;

err = media_entity_pads_init(&sd->entity, npads, pads);
```

The pads array must have been previously initialized. There is no need to manually set the struct media_entity function and name fields, but the revision field must be initialized if needed.

A reference to the entity will be automatically acquired/released when the subdev device node (if any) is opened/closed.

Don't forget to cleanup the media entity before the sub-device is destroyed:



```c
media_entity_cleanup(&sd->entity);
```

If a sub-device driver implements sink pads, the subdev driver may set the link_validate field in `v4l2_subdev_pad_ops` to provide its own link validation function. For every link in the pipeline, the link_validate pad operation of the sink end of the link is called. In both cases the driver is still responsible for validating the correctness of the format configuration between sub-devices and video nodes.

If link_validate op is not set, the default function `v4l2_subdev_link_validate_default()` is used instead. This function ensures that width, height and the media bus pixel code are equal on both source and sink of the link. Subdev drivers are also free to use this function to perform the checks mentioned above in addition to their own checks.

<a id="rst-subdev-registration"></a>

### Subdev registration

There are currently two ways to register subdevices with the V4L2 core. The first (traditional) possibility is to have subdevices registered by bridge drivers. This can be done when the bridge driver has the complete information about subdevices connected to it and knows exactly when to register them. This is typically the case for internal subdevices, like video data processing units within SoCs or complex PCI(e) boards, camera sensors in USB cameras or connected to SoCs, which pass information about them to bridge drivers, usually in their platform data.

There are however also situations where subdevices have to be registered asynchronously to bridge devices. An example of such a configuration is a Device Tree based system where information about subdevices is made available to the system independently from the bridge devices, e.g. when subdevices are defined in DT as I2C device nodes. The API used in this second case is described further below.

Using one or the other registration method only affects the probing process, the run-time bridge-subdevice interaction is in both cases the same.

<a id="rst-registering-synchronous-sub-devices"></a>

#### Registering synchronous sub-devices

In the **synchronous** case a device (bridge) driver needs to register the `v4l2_subdev` with the v4l2_device:

> `v4l2_device_register_subdev <v4l2_device_register_subdev>()` (`v4l2_dev <v4l2_device>`, `sd <v4l2_subdev>`).

This can fail if the subdev module disappeared before it could be registered. After this function was called successfully the subdev-&gt;dev field points to the `v4l2_device`.

If the v4l2_device parent device has a non-NULL mdev field, the sub-device entity will be automatically registered with the media device.

You can unregister a sub-device using:

> `v4l2_device_unregister_subdev <v4l2_device_unregister_subdev>()` (`sd <v4l2_subdev>`).

Afterwards the subdev module can be unloaded and `sd <v4l2_subdev>`-&gt;dev == `NULL`.

<a id="rst-registering-asynchronous-sub-devices"></a>
<a id="rst-media-registering-async-subdevs"></a>

#### Registering asynchronous sub-devices

In the **asynchronous** case subdevice probing can be invoked independently of the bridge driver availability. The subdevice driver then has to verify whether all the requirements for a successful probing are satisfied. This can include a check for a master clock availability. If any of the conditions aren't satisfied the driver might decide to return `-EPROBE_DEFER` to request further reprobing attempts. Once all conditions are met the subdevice shall be registered using the `v4l2_async_register_subdev()` function. Unregistration is performed using the `v4l2_async_unregister_subdev()` call. Subdevices registered this way are stored in a global list of subdevices, ready to be picked up by bridge drivers.

Drivers must complete all initialization of the sub-device before registering it using `v4l2_async_register_subdev()`, including enabling runtime PM. This is because the sub-device becomes accessible as soon as it gets registered.

<a id="rst-asynchronous-sub-device-notifiers"></a>

#### Asynchronous sub-device notifiers

Bridge drivers in turn have to register a notifier object. This is performed using the `v4l2_async_nf_register()` call. To unregister the notifier the driver has to call `v4l2_async_nf_unregister()`. Before releasing memory of an unregister notifier, it must be cleaned up by calling `v4l2_async_nf_cleanup()`.

Before registering the notifier, bridge drivers must do two things: first, the notifier must be initialized using the `v4l2_async_nf_init()`.  Second, bridge drivers can then begin to form a list of async connection descriptors that the bridge device needs for its operation. `v4l2_async_nf_add_fwnode()`, `v4l2_async_nf_add_fwnode_remote()` and `v4l2_async_nf_add_i2c()`

Async connection descriptors describe connections to external sub-devices the drivers for which are not yet probed. Based on an async connection, a media data or ancillary link may be created when the related sub-device becomes available. There may be one or more async connections to a given sub-device but this is not known at the time of adding the connections to the notifier. Async connections are bound as matching async sub-devices are found, one by one.

<a id="rst-asynchronous-sub-device-notifier-for-sub-devices"></a>

#### Asynchronous sub-device notifier for sub-devices

A driver that registers an asynchronous sub-device may also register an asynchronous notifier. This is called an asynchronous sub-device notifier and the process is similar to that of a bridge driver apart from that the notifier is initialised using `v4l2_async_subdev_nf_init()` instead. A sub-device notifier may complete only after the V4L2 device becomes available, i.e. there's a path via async sub-devices and notifiers to a notifier that is not an asynchronous sub-device notifier.

<a id="rst-asynchronous-sub-device-registration-helper-for-camera-sensor-drivers"></a>

#### Asynchronous sub-device registration helper for camera sensor drivers

`v4l2_async_register_subdev_sensor()` is a helper function for sensor drivers registering their own async connection, but it also registers a notifier and further registers async connections for lens and flash devices found in firmware. The notifier for the sub-device is unregistered and cleaned up with the async sub-device, using `v4l2_async_unregister_subdev()`.

<a id="rst-asynchronous-sub-device-notifier-example"></a>

#### Asynchronous sub-device notifier example

These functions allocate an async connection descriptor which is of type struct `v4l2_async_connection` embedded in a driver-specific struct. The &amp;struct `v4l2_async_connection` shall be the first member of this struct:



```c
struct my_async_connection {
        struct v4l2_async_connection asc;
        ...
};

struct my_async_connection *my_asc;
struct fwnode_handle *ep;

...

my_asc = v4l2_async_nf_add_fwnode_remote(&notifier, ep,
                                         struct my_async_connection);
fwnode_handle_put(ep);

if (IS_ERR(my_asc))
        return PTR_ERR(my_asc);
```

<a id="rst-asynchronous-sub-device-notifier-callbacks"></a>

#### Asynchronous sub-device notifier callbacks

The V4L2 core will then use these connection descriptors to match asynchronously registered subdevices to them. If a match is detected the `.bound()` notifier callback is called. After all connections have been bound the .complete() callback is called. When a connection is removed from the system the `.unbind()` method is called. All three callbacks are optional.

Drivers can store any type of custom data in their driver-specific `v4l2_async_connection` wrapper. If any of that data requires special handling when the structure is freed, drivers must implement the `.destroy()` notifier callback. The framework will call it right before freeing the `v4l2_async_connection`.

<a id="rst-calling-subdev-operations"></a>

### Calling subdev operations

The advantage of using `v4l2_subdev` is that it is a generic struct and does not contain any knowledge about the underlying hardware. So a driver might contain several subdevs that use an I2C bus, but also a subdev that is controlled through GPIO pins. This distinction is only relevant when setting up the device, but once the subdev is registered it is completely transparent.

Once the subdev has been registered you can call an ops function either directly:



```c
err = sd->ops->core->g_std(sd, &norm);
```

but it is better and easier to use this macro:



```c
err = v4l2_subdev_call(sd, core, g_std, &norm);
```

The macro will do the right `NULL` pointer checks and returns `-ENODEV` if `sd <v4l2_subdev>` is `NULL`, `-ENOIOCTLCMD` if either `sd <v4l2_subdev>`-&gt;core or `sd <v4l2_subdev>`-&gt;core-&gt;g_std is `NULL`, or the actual result of the `sd <v4l2_subdev>`-&gt;ops-&gt;core-&gt;g_std ops.

It is also possible to call all or a subset of the sub-devices:



```c
v4l2_device_call_all(v4l2_dev, 0, core, g_std, &norm);
```

Any subdev that does not support this ops is skipped and error results are ignored. If you want to check for errors use this:



```c
err = v4l2_device_call_until_err(v4l2_dev, 0, core, g_std, &norm);
```

Any error except `-ENOIOCTLCMD` will exit the loop with that error. If no errors (except `-ENOIOCTLCMD`) occurred, then 0 is returned.

The second argument to both calls is a group ID. If 0, then all subdevs are called. If non-zero, then only those whose group ID match that value will be called. Before a bridge driver registers a subdev it can set `sd <v4l2_subdev>`-&gt;grp_id to whatever value it wants (it's 0 by default). This value is owned by the bridge driver and the sub-device driver will never modify or use it.

The group ID gives the bridge driver more control how callbacks are called. For example, there may be multiple audio chips on a board, each capable of changing the volume. But usually only one will actually be used when the user want to change the volume. You can set the group ID for that subdev to e.g. AUDIO_CONTROLLER and specify that as the group ID value when calling `v4l2_device_call_all()`. That ensures that it will only go to the subdev that needs it.

If the sub-device needs to notify its v4l2_device parent of an event, then it can call `v4l2_subdev_notify(sd, notification, arg)`. This macro checks whether there is a `notify()` callback defined and returns `-ENODEV` if not. Otherwise the result of the `notify()` call is returned.

<a id="rst-v4l2-sub-device-userspace-api"></a>

## V4L2 sub-device userspace API

Bridge drivers traditionally expose one or multiple video nodes to userspace, and control subdevices through the `v4l2_subdev_ops` operations in response to video node operations. This hides the complexity of the underlying hardware from applications. For complex devices, finer-grained control of the device than what the video nodes offer may be required. In those cases, bridge drivers that implement [the media controller API](</kernel/userspace/userspace-api/media-mediactl/media-controller.md#rst-media-controller>) may opt for making the subdevice operations directly accessible from userspace.

Device nodes named `v4l-subdev`*X* can be created in `/dev` to access sub-devices directly. If a sub-device supports direct userspace configuration it must set the `V4L2_SUBDEV_FL_HAS_DEVNODE` flag before being registered.

After registering sub-devices, the `v4l2_device` driver can create device nodes for all registered sub-devices marked with `V4L2_SUBDEV_FL_HAS_DEVNODE` by calling `v4l2_device_register_subdev_nodes()`. Those device nodes will be automatically removed when sub-devices are unregistered.

The device node handles a subset of the V4L2 API.

`VIDIOC_QUERYCTRL`, `VIDIOC_QUERYMENU`, `VIDIOC_G_CTRL`, `VIDIOC_S_CTRL`, `VIDIOC_G_EXT_CTRLS`, `VIDIOC_S_EXT_CTRLS` and `VIDIOC_TRY_EXT_CTRLS`:

> The controls ioctls are identical to the ones defined in V4L2. They behave identically, with the only exception that they deal only with controls implemented in the sub-device. Depending on the driver, those controls can be also be accessed through one (or several) V4L2 device nodes.

`VIDIOC_DQEVENT`, `VIDIOC_SUBSCRIBE_EVENT` and `VIDIOC_UNSUBSCRIBE_EVENT`

> The events ioctls are identical to the ones defined in V4L2. They behave identically, with the only exception that they deal only with events generated by the sub-device. Depending on the driver, those events can also be reported by one (or several) V4L2 device nodes.
>
> Sub-device drivers that want to use events need to set the `V4L2_SUBDEV_FL_HAS_EVENTS` `v4l2_subdev`.flags before registering the sub-device. After registration events can be queued as usual on the `v4l2_subdev`.devnode device node.
>
> To properly support events, the `poll()` file operation is also implemented.

Private ioctls

> All ioctls not in the above list are passed directly to the sub-device driver through the core::ioctl operation.

<a id="rst-read-only-sub-device-userspace-api"></a>

## Read-only sub-device userspace API

Bridge drivers that control their connected subdevices through direct calls to the kernel API realized by `v4l2_subdev_ops` structure do not usually want userspace to be able to change the same parameters through the subdevice device node and thus do not usually register any.

It is sometimes useful to report to userspace the current subdevice configuration through a read-only API, that does not permit applications to change to the device parameters but allows interfacing to the subdevice device node to inspect them.

For instance, to implement cameras based on computational photography, userspace needs to know the detailed camera sensor configuration (in terms of skipping, binning, cropping and scaling) for each supported output resolution. To support such use cases, bridge drivers may expose the subdevice operations to userspace through a read-only API.

To create a read-only device node for all the subdevices registered with the `V4L2_SUBDEV_FL_HAS_DEVNODE` set, the `v4l2_device` driver should call `v4l2_device_register_ro_subdev_nodes()`.

Access to the following ioctls for userspace applications is restricted on sub-device device nodes registered with `v4l2_device_register_ro_subdev_nodes()`.

`VIDIOC_SUBDEV_S_FMT`, `VIDIOC_SUBDEV_S_CROP`, `VIDIOC_SUBDEV_S_SELECTION`:

> These ioctls are only allowed on a read-only subdevice device node for the [V4L2_SUBDEV_FORMAT_TRY](</kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#rst-v4l2-subdev-format-whence>) formats and selection rectangles.

`VIDIOC_SUBDEV_S_FRAME_INTERVAL`, `VIDIOC_SUBDEV_S_DV_TIMINGS`, `VIDIOC_SUBDEV_S_STD`:

> These ioctls are not allowed on a read-only subdevice node.

In case the ioctl is not allowed, or the format to modify is set to `V4L2_SUBDEV_FORMAT_ACTIVE`, the core returns a negative error code and the errno variable is set to `-EPERM`.

<a id="rst-i2c-sub-device-drivers"></a>

## I2C sub-device drivers

Since these drivers are so common, special helper functions are available to ease the use of these drivers (`v4l2-common.h`).

The recommended method of adding `v4l2_subdev` support to an I2C driver is to embed the `v4l2_subdev` struct into the state struct that is created for each I2C device instance. Very simple devices have no state struct and in that case you can just create a `v4l2_subdev` directly.

A typical state struct would look like this (where 'chipname' is replaced by the name of the chip):



```c
struct chipname_state {
        struct v4l2_subdev sd;
        ...  /* additional state fields */
};
```

Initialize the `v4l2_subdev` struct as follows:



```c
v4l2_i2c_subdev_init(&state->sd, client, subdev_ops);
```

This function will fill in all the fields of `v4l2_subdev` ensure that the `v4l2_subdev` and i2c_client both point to one another.

You should also add a helper inline function to go from a `v4l2_subdev` pointer to a chipname_state struct:



```c
static inline struct chipname_state *to_state(struct v4l2_subdev *sd)
{
        return container_of(sd, struct chipname_state, sd);
}
```

Use this to go from the `v4l2_subdev` struct to the `i2c_client` struct:



```c
struct i2c_client *client = v4l2_get_subdevdata(sd);
```

And this to go from an `i2c_client` to a `v4l2_subdev` struct:



```c
struct v4l2_subdev *sd = i2c_get_clientdata(client);
```

Make sure to call `v4l2_device_unregister_subdev()`(`sd <v4l2_subdev>`) when the `remove()` callback is called. This will unregister the sub-device from the bridge driver. It is safe to call this even if the sub-device was never registered.

You need to do this because when the bridge driver destroys the i2c adapter the `remove()` callbacks are called of the i2c devices on that adapter. After that the corresponding v4l2_subdev structures are invalid, so they have to be unregistered first. Calling `v4l2_device_unregister_subdev()`(`sd <v4l2_subdev>`) from the `remove()` callback ensures that this is always done correctly.

The bridge driver also has some helper functions it can use:



```c
struct v4l2_subdev *sd = v4l2_i2c_new_subdev(v4l2_dev, adapter,
                                "module_foo", "chipid", 0x36, NULL);
```

This loads the given module (can be `NULL` if no module needs to be loaded) and calls `i2c_new_client_device()` with the given `i2c_adapter` and chip/address arguments. If all goes well, then it registers the subdev with the v4l2_device.

You can also use the last argument of `v4l2_i2c_new_subdev()` to pass an array of possible I2C addresses that it should probe. These probe addresses are only used if the previous argument is 0. A non-zero argument means that you know the exact i2c address so in that case no probing will take place.

Both functions return `NULL` if something went wrong.

Note that the chipid you pass to `v4l2_i2c_new_subdev()` is usually the same as the module name. It allows you to specify a chip variant, e.g. "saa7114" or "saa7115". In general though the i2c driver autodetects this. The use of chipid is something that needs to be looked at more closely at a later date. It differs between i2c drivers and as such can be confusing. To see which chip variants are supported you can look in the i2c driver code for the i2c_device_id table. This lists all the possibilities.

There are one more helper function:

`v4l2_i2c_new_subdev_board()` uses an `i2c_board_info` struct which is passed to the i2c driver and replaces the irq, platform_data and addr arguments.

If the subdev supports the s_config core ops, then that op is called with the irq and platform_data arguments after the subdev was setup.

The `v4l2_i2c_new_subdev()` function will call `v4l2_i2c_new_subdev_board()`, internally filling a `i2c_board_info` structure using the `client_type` and the `addr` to fill it.

<a id="rst-centrally-managed-subdev-active-state"></a>

## Centrally managed subdev active state

Traditionally V4L2 subdev drivers maintained internal state for the active device configuration. This is often implemented as e.g. an array of struct v4l2_mbus_framefmt, one entry for each pad, and similarly for crop and compose rectangles.

In addition to the active configuration, each subdev file handle has a struct v4l2_subdev_state, managed by the V4L2 core, which contains the try configuration.

To simplify the subdev drivers the V4L2 subdev API now optionally supports a centrally managed active configuration represented by `v4l2_subdev_state`. One instance of state, which contains the active device configuration, is stored in the sub-device itself as part of the `v4l2_subdev` structure, while the core associates a try state to each open file handle, to store the try configuration related to that file handle.

Sub-device drivers can opt-in and use state to manage their active configuration by initializing the subdevice state with a call to v4l2_subdev_init_finalize() before registering the sub-device. They must also call v4l2_subdev_cleanup() to release all the allocated resources before unregistering the sub-device. The core automatically allocates and initializes a state for each open file handle to store the try configurations and frees it when closing the file handle.

V4L2 sub-device operations that use both the [ACTIVE and TRY formats](</kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#rst-v4l2-subdev-format-whence>) receive the correct state to operate on through the 'state' parameter. The state must be locked and unlocked by the caller by calling `v4l2_subdev_lock_state()` and `v4l2_subdev_unlock_state()`. The caller can do so by calling the subdev operation through the `v4l2_subdev_call_state_active()` macro.

Operations that do not receive a state parameter implicitly operate on the subdevice active state, which drivers can exclusively access by calling `v4l2_subdev_lock_and_get_active_state()`. The sub-device active state must equally be released by calling `v4l2_subdev_unlock_state()`.

Drivers must never manually access the state stored in the `v4l2_subdev` or in the file handle without going through the designated helpers.

While the V4L2 core passes the correct try or active state to the subdevice operations, many existing device drivers pass a NULL state when calling operations with `v4l2_subdev_call()`. This legacy construct causes issues with subdevice drivers that let the V4L2 core manage the active state, as they expect to receive the appropriate state as a parameter. To help the conversion of subdevice drivers to a managed active state without having to convert all callers at the same time, an additional wrapper layer has been added to v4l2_subdev_call(), which handles the NULL case by getting and locking the callee's active state with `v4l2_subdev_lock_and_get_active_state()`, and unlocking the state after the call.

The whole subdev state is in reality split into three parts: the v4l2_subdev_state, subdev controls and subdev driver's internal state. In the future these parts should be combined into a single state. For the time being we need a way to handle the locking for these parts. This can be accomplished by sharing a lock. The v4l2_ctrl_handler already supports this via its 'lock' pointer and the same model is used with states. The driver can do the following before calling v4l2_subdev_init_finalize():



```c
sd->ctrl_handler->lock = &priv->mutex;
sd->state_lock = &priv->mutex;
```

This shares the driver's private mutex between the controls and the states.

<a id="rst-streams-multiplexed-media-pads-and-internal-routing"></a>

## Streams, multiplexed media pads and internal routing

A subdevice driver can implement support for multiplexed streams by setting the V4L2_SUBDEV_FL_STREAMS subdev flag and implementing support for centrally managed subdev active state, routing and stream based configuration.

<a id="rst-v4l2-sub-device-functions-and-data-structures"></a>

## V4L2 sub-device functions and data structures


#### <a id="c-struct-v4l2_decode_vbi_line"></a>`struct v4l2_decode_vbi_line`

used to decode_vbi_line

**Definition**

```c
struct v4l2_decode_vbi_line {
    u32 is_second_field;
    u8 *p;
    u32 line;
    u32 type;
};
```

**Members**

- `is_second_field`: Set to 0 for the first (odd) field;
  set to 1 for the second (even) field.
- `p`: Pointer to the sliced VBI data from the decoder. On exit, points to
  the start of the payload.
- `line`: Line number of the sliced VBI data (1-23)
- `type`: VBI service type (V4L2_SLICED_*). 0 if no service found

#### <a id="c-enum-v4l2_subdev_io_pin_bits"></a>`enum v4l2_subdev_io_pin_bits`

Subdevice external IO pin configuration bits

**Constants**

- `V4L2_SUBDEV_IO_PIN_DISABLE`: disables a pin config. ENABLE assumed.
- `V4L2_SUBDEV_IO_PIN_OUTPUT`: set it if pin is an output.
- `V4L2_SUBDEV_IO_PIN_INPUT`: set it if pin is an input.
- `V4L2_SUBDEV_IO_PIN_SET_VALUE`: to set the output value via
  [`struct v4l2_subdev_io_pin_config`](#c-struct-v4l2_subdev_io_pin_config)->value.
- `V4L2_SUBDEV_IO_PIN_ACTIVE_LOW`: pin active is bit 0.
  Otherwise, ACTIVE HIGH is assumed.

#### <a id="c-struct-v4l2_subdev_io_pin_config"></a>`struct v4l2_subdev_io_pin_config`

Subdevice external IO pin configuration

**Definition**

```c
struct v4l2_subdev_io_pin_config {
    u32 flags;
    u8 pin;
    u8 function;
    u8 value;
    u8 strength;
};
```

**Members**

- `flags`: bitmask with flags for this pin's config, whose bits are defined by
  [`enum v4l2_subdev_io_pin_bits`](#c-enum-v4l2_subdev_io_pin_bits).
- `pin`: Chip external IO pin to configure
- `function`: Internal signal pad/function to route to IO pin
- `value`: Initial value for pin - e.g. GPIO output value
- `strength`: Pin drive strength

#### <a id="c-struct-v4l2_subdev_core_ops"></a>`struct v4l2_subdev_core_ops`

Define core ops callbacks for subdevs

**Definition**

```c
struct v4l2_subdev_core_ops {
        int (*log_status)(struct v4l2_subdev *sd);
        int (*s_io_pin_config)(struct v4l2_subdev *sd, size_t n, struct v4l2_subdev_io_pin_config *pincfg);
        int (*init)(struct v4l2_subdev *sd, u32 val);
        int (*load_fw)(struct v4l2_subdev *sd);
        int (*reset)(struct v4l2_subdev *sd, u32 val);
        int (*s_gpio)(struct v4l2_subdev *sd, u32 val);
        long (*command)(struct v4l2_subdev *sd, unsigned int cmd, void *arg);
        long (*ioctl)(struct v4l2_subdev *sd, unsigned int cmd, void *arg);
    #ifdef CONFIG_COMPAT;
        long (*compat_ioctl32)(struct v4l2_subdev *sd, unsigned int cmd, unsigned long arg);
    #endif;
    #ifdef CONFIG_VIDEO_ADV_DEBUG;
        int (*g_register)(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg);
        int (*s_register)(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg);
    #endif;
        int (*s_power)(struct v4l2_subdev *sd, int on);
        int (*interrupt_service_routine)(struct v4l2_subdev *sd, u32 status, bool *handled);
        int (*subscribe_event)(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub);
        int (*unsubscribe_event)(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub);
};
```

**Members**

- `log_status`: callback for `VIDIOC_LOG_STATUS()` ioctl handler code.
- `s_io_pin_config`: configure one or more chip I/O pins for chips that
  multiplex different internal signal pads out to IO pins.  This function
  takes a pointer to an array of 'n' pin configuration entries, one for
  each pin being configured.  This function could be called at times
  other than just subdevice initialization.
- `init`: initialize the sensor registers to some sort of reasonable default
  values. Do not use for new drivers and should be removed in existing
  drivers.
- `load_fw`: load firmware.
- `reset`: generic reset command. The argument selects which subsystems to
  reset. Passing 0 will always reset the whole chip. Do not use for new
  drivers without discussing this first on the linux-media mailinglist.
  There should be no reason normally to reset a device.
- `s_gpio`: set GPIO pins. Very simple right now, might need to be extended with
  a direction argument if needed.
- `command`: called by in-kernel drivers in order to call functions internal
  to subdev drivers driver that have a separate callback.
- `ioctl`: called at the end of `ioctl()` syscall handler at the V4L2 core.
  used to provide support for private ioctls used on the driver.
- `compat_ioctl32`: called when a 32 bits application uses a 64 bits Kernel,
  in order to fix data passed from/to userspace.
- `g_register`: callback for `VIDIOC_DBG_G_REGISTER()` ioctl handler code.
- `s_register`: callback for `VIDIOC_DBG_S_REGISTER()` ioctl handler code.
- `s_power`: puts subdevice in power saving mode (on == 0) or normal operation
  mode (on == 1). DEPRECATED. See
  Documentation/driver-api/media/camera-sensor.rst . pre_streamon and
  post_streamoff callbacks can be used for e.g. setting the bus to LP-11
  mode before s_stream is called.
- `interrupt_service_routine`: Called by the bridge chip's interrupt service
  handler, when an interrupt status has be raised due to this subdev,
  so that this subdev can handle the details.  It may schedule work to be
  performed later.  It must not sleep. **Called from an IRQ context**.
- `subscribe_event`: used by the drivers to request the control framework that
  for it to be warned when the value of a control changes.
- `unsubscribe_event`: remove event subscription from the control framework.

#### <a id="c-struct-v4l2_subdev_tuner_ops"></a>`struct v4l2_subdev_tuner_ops`

Callbacks used when v4l device was opened in radio mode.

**Definition**

```c
struct v4l2_subdev_tuner_ops {
    int (*standby)(struct v4l2_subdev *sd);
    int (*s_radio)(struct v4l2_subdev *sd);
    int (*s_frequency)(struct v4l2_subdev *sd, const struct v4l2_frequency *freq);
    int (*g_frequency)(struct v4l2_subdev *sd, struct v4l2_frequency *freq);
    int (*enum_freq_bands)(struct v4l2_subdev *sd, struct v4l2_frequency_band *band);
    int (*g_tuner)(struct v4l2_subdev *sd, struct v4l2_tuner *vt);
    int (*s_tuner)(struct v4l2_subdev *sd, const struct v4l2_tuner *vt);
    int (*g_modulator)(struct v4l2_subdev *sd, struct v4l2_modulator *vm);
    int (*s_modulator)(struct v4l2_subdev *sd, const struct v4l2_modulator *vm);
    int (*s_type_addr)(struct v4l2_subdev *sd, struct tuner_setup *type);
    int (*s_config)(struct v4l2_subdev *sd, const struct v4l2_priv_tun_config *config);
};
```

**Members**

- `standby`: puts the tuner in standby mode. It will be woken up
  automatically the next time it is used.
- `s_radio`: callback that switches the tuner to radio mode.
  drivers should explicitly call it when a tuner ops should
  operate on radio mode, before being able to handle it.
  Used on devices that have both AM/FM radio receiver and TV.
- `s_frequency`: callback for `VIDIOC_S_FREQUENCY()` ioctl handler code.
- `g_frequency`: callback for `VIDIOC_G_FREQUENCY()` ioctl handler code.
  freq->type must be filled in. Normally done by [`video_ioctl2()`](/kernel/hardware/driver-api/media/v4l2-common.md#c-video_ioctl2)
  or the bridge driver.
- `enum_freq_bands`: callback for `VIDIOC_ENUM_FREQ_BANDS()` ioctl handler code.
- `g_tuner`: callback for `VIDIOC_G_TUNER()` ioctl handler code.
- `s_tuner`: callback for `VIDIOC_S_TUNER()` ioctl handler code. **vt->type** must be
  filled in. Normally done by video_ioctl2 or the
  bridge driver.
- `g_modulator`: callback for `VIDIOC_G_MODULATOR()` ioctl handler code.
- `s_modulator`: callback for `VIDIOC_S_MODULATOR()` ioctl handler code.
- `s_type_addr`: sets tuner type and its I2C addr.
- `s_config`: sets tda9887 specific stuff, like port1, port2 and qss

**Description**

> [!NOTE]
> On devices that have both AM/FM and TV, it is up to the driver
> to explicitly call s_radio when the tuner should be switched to
> radio mode, before handling other [`struct v4l2_subdev_tuner_ops`](#c-struct-v4l2_subdev_tuner_ops)
> that would require it. An example of such usage is:
>
> ```text
> static void s_frequency(void *priv, const struct v4l2_frequency *f)
> {
>       ...
>       if (f.type == V4L2_TUNER_RADIO)
>               v4l2_device_call_all(v4l2_dev, 0, tuner, s_radio);
>       ...
>       v4l2_device_call_all(v4l2_dev, 0, tuner, s_frequency);
> }
> ```

#### <a id="c-struct-v4l2_subdev_audio_ops"></a>`struct v4l2_subdev_audio_ops`

Callbacks used for audio-related settings

**Definition**

```c
struct v4l2_subdev_audio_ops {
    int (*s_clock_freq)(struct v4l2_subdev *sd, u32 freq);
    int (*s_i2s_clock_freq)(struct v4l2_subdev *sd, u32 freq);
    int (*s_routing)(struct v4l2_subdev *sd, u32 input, u32 output, u32 config);
    int (*s_stream)(struct v4l2_subdev *sd, int enable);
};
```

**Members**

- `s_clock_freq`: set the frequency (in Hz) of the audio clock output.
  Used to slave an audio processor to the video decoder, ensuring that
  audio and video remain synchronized. Usual values for the frequency
  are 48000, 44100 or 32000 Hz. If the frequency is not supported, then
  -EINVAL is returned.
- `s_i2s_clock_freq`: sets I2S speed in bps. This is used to provide a standard
  way to select I2S clock used by driving digital audio streams at some
  board designs. Usual values for the frequency are 1024000 and 2048000.
  If the frequency is not supported, then `-EINVAL` is returned.
- `s_routing`: used to define the input and/or output pins of an audio chip,
  and any additional configuration data.
  Never attempt to use user-level input IDs (e.g. Composite, S-Video,
  Tuner) at this level. An i2c device shouldn't know about whether an
  input pin is connected to a Composite connector, become on another
  board or platform it might be connected to something else entirely.
  The calling driver is responsible for mapping a user-level input to
  the right pins on the i2c device.
- `s_stream`: used to notify the audio code that stream will start or has
  stopped.

#### <a id="c-struct-v4l2_mbus_frame_desc_entry_csi2"></a>`struct v4l2_mbus_frame_desc_entry_csi2`

**Definition**

```c
struct v4l2_mbus_frame_desc_entry_csi2 {
    u8 vc;
    u8 dt;
};
```

**Members**

- `vc`: CSI-2 virtual channel
- `dt`: CSI-2 data type ID

#### <a id="c-enum-v4l2_mbus_frame_desc_flags"></a>`enum v4l2_mbus_frame_desc_flags`

media bus frame description flags

**Constants**

- `V4L2_MBUS_FRAME_DESC_FL_LEN_MAX`: Indicates that [`struct v4l2_mbus_frame_desc_entry`](#c-struct-v4l2_mbus_frame_desc_entry)->length field
  specifies maximum data length.
- `V4L2_MBUS_FRAME_DESC_FL_BLOB`: Indicates that the format does not have line offsets, i.e.
  the receiver should use 1D DMA.

#### <a id="c-struct-v4l2_mbus_frame_desc_entry"></a>`struct v4l2_mbus_frame_desc_entry`

media bus frame description structure

**Definition**

```c
struct v4l2_mbus_frame_desc_entry {
    enum v4l2_mbus_frame_desc_flags flags;
    u32 stream;
    u32 pixelcode;
    u32 length;
    union {
        struct v4l2_mbus_frame_desc_entry_csi2 csi2;
    } bus;
};
```

**Members**

- `flags`: bitmask flags, as defined by [`enum v4l2_mbus_frame_desc_flags`](#c-enum-v4l2_mbus_frame_desc_flags).
- `stream`: stream in routing configuration
- `pixelcode`: media bus pixel code, valid if **flags**
  `FRAME_DESC_FL_BLOB` is not set.
- `length`: number of octets per frame, valid if **flags**
  `V4L2_MBUS_FRAME_DESC_FL_LEN_MAX` is set.
- `bus`: Bus-specific frame descriptor parameters
- `bus.csi2`: CSI-2-specific bus configuration

#### <a id="c-enum-v4l2_mbus_frame_desc_type"></a>`enum v4l2_mbus_frame_desc_type`

media bus frame description type

**Constants**

- `V4L2_MBUS_FRAME_DESC_TYPE_UNDEFINED`: Undefined frame desc type. Drivers should not use this, it is
  for backwards compatibility.
- `V4L2_MBUS_FRAME_DESC_TYPE_PARALLEL`: Parallel media bus.
- `V4L2_MBUS_FRAME_DESC_TYPE_CSI2`: CSI-2 media bus. Frame desc parameters must be set in
  [`struct v4l2_mbus_frame_desc_entry`](#c-struct-v4l2_mbus_frame_desc_entry)->csi2.

#### <a id="c-struct-v4l2_mbus_frame_desc"></a>`struct v4l2_mbus_frame_desc`

media bus data frame description

**Definition**

```c
struct v4l2_mbus_frame_desc {
    enum v4l2_mbus_frame_desc_type type;
    struct v4l2_mbus_frame_desc_entry entry[V4L2_FRAME_DESC_ENTRY_MAX];
    unsigned short num_entries;
};
```

**Members**

- `type`: type of the bus (enum v4l2_mbus_frame_desc_type)
- `entry`: frame descriptors array
- `num_entries`: number of entries in **entry** array

#### <a id="c-enum-v4l2_subdev_pre_streamon_flags"></a>`enum v4l2_subdev_pre_streamon_flags`

Flags for pre_streamon subdev core op

**Constants**

- `V4L2_SUBDEV_PRE_STREAMON_FL_MANUAL_LP`: Set the transmitter to either LP-11
  or LP-111 mode before call to `s_stream()`.

#### <a id="c-struct-v4l2_subdev_video_ops"></a>`struct v4l2_subdev_video_ops`

Callbacks used when v4l device was opened in video mode.

**Definition**

```c
struct v4l2_subdev_video_ops {
    int (*s_routing)(struct v4l2_subdev *sd, u32 input, u32 output, u32 config);
    int (*s_crystal_freq)(struct v4l2_subdev *sd, u32 freq, u32 flags);
    int (*g_std)(struct v4l2_subdev *sd, v4l2_std_id *norm);
    int (*s_std)(struct v4l2_subdev *sd, v4l2_std_id norm);
    int (*s_std_output)(struct v4l2_subdev *sd, v4l2_std_id std);
    int (*g_std_output)(struct v4l2_subdev *sd, v4l2_std_id *std);
    int (*querystd)(struct v4l2_subdev *sd, v4l2_std_id *std);
    int (*g_tvnorms)(struct v4l2_subdev *sd, v4l2_std_id *std);
    int (*g_tvnorms_output)(struct v4l2_subdev *sd, v4l2_std_id *std);
    int (*g_input_status)(struct v4l2_subdev *sd, u32 *status);
    int (*s_stream)(struct v4l2_subdev *sd, int enable);
    int (*s_rx_buffer)(struct v4l2_subdev *sd, void *buf, unsigned int *size);
    int (*pre_streamon)(struct v4l2_subdev *sd, u32 flags);
    int (*post_streamoff)(struct v4l2_subdev *sd);
};
```

**Members**

- `s_routing`: see s_routing in audio_ops, except this version is for video
  devices.
- `s_crystal_freq`: sets the frequency of the crystal used to generate the
  clocks in Hz. An extra flags field allows device specific configuration
  regarding clock frequency dividers, etc. If not used, then set flags
  to 0. If the frequency is not supported, then -EINVAL is returned.
- `g_std`: callback for `VIDIOC_G_STD()` ioctl handler code.
- `s_std`: callback for `VIDIOC_S_STD()` ioctl handler code.
- `s_std_output`: set v4l2_std_id for video OUTPUT devices. This is ignored by
  video input devices.
- `g_std_output`: get current standard for video OUTPUT devices. This is ignored
  by video input devices.
- `querystd`: callback for `VIDIOC_QUERYSTD()` ioctl handler code.
- `g_tvnorms`: get `v4l2_std_id` with all standards supported by the video
  CAPTURE device. This is ignored by video output devices.
- `g_tvnorms_output`: get v4l2_std_id with all standards supported by the video
  OUTPUT device. This is ignored by video capture devices.
- `g_input_status`: get input status. Same as the status field in the
  [`struct v4l2_input`](/kernel/userspace/userspace-api/media-v4l/vidioc-enuminput.md#c-v4l2_input)
- `s_stream`: start (enabled == 1) or stop (enabled == 0) streaming on the
  sub-device. Failure on stop will remove any resources acquired in
  streaming start, while the error code is still returned by the driver.
  The caller shall track the subdev state, and shall not start or stop an
  already started or stopped subdev. Also see call_s_stream wrapper in
  v4l2-subdev.c.
- `s_rx_buffer`: set a host allocated memory buffer for the subdev. The subdev
  can adjust **size** to a lower value and must not write more data to the
  buffer starting at **data** than the original value of **size**.
- `pre_streamon`: May be called before streaming is actually started, to help
  initialising the bus. Current usage is to set a CSI-2 transmitter to
  LP-11 or LP-111 mode before streaming. See [`enum v4l2_subdev_pre_streamon_flags`](#c-enum-v4l2_subdev_pre_streamon_flags).
- `post_streamoff`: Called after streaming is stopped, but if and only if
  pre_streamon was called earlier.

**Description**

This callback is DEPRECATED. New drivers should instead implement
[`v4l2_subdev_pad_ops.enable_streams`](#c-struct-v4l2_subdev_pad_ops) and
[`v4l2_subdev_pad_ops.disable_streams`](#c-struct-v4l2_subdev_pad_ops) operations, and use
v4l2_subdev_s_stream_helper for the [`v4l2_subdev_video_ops.s_stream`](#c-struct-v4l2_subdev_video_ops)
operation to support legacy users.

Drivers should also not call the .`s_stream()` subdev operation directly,
but use the [`v4l2_subdev_enable_streams()`](#c-v4l2_subdev_enable_streams) and
[`v4l2_subdev_disable_streams()`](#c-v4l2_subdev_disable_streams) helpers.

pre_streamon shall return error if it cannot perform the operation as
indicated by the flags argument. In particular, -EACCES indicates lack
of support for the operation. The caller shall call post_streamoff for
each successful call of pre_streamon.

#### <a id="c-struct-v4l2_subdev_vbi_ops"></a>`struct v4l2_subdev_vbi_ops`

Callbacks used when v4l device was opened in video mode via the vbi device node.

**Definition**

```c
struct v4l2_subdev_vbi_ops {
    int (*decode_vbi_line)(struct v4l2_subdev *sd, struct v4l2_decode_vbi_line *vbi_line);
    int (*s_vbi_data)(struct v4l2_subdev *sd, const struct v4l2_sliced_vbi_data *vbi_data);
    int (*g_vbi_data)(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_data *vbi_data);
    int (*g_sliced_vbi_cap)(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_cap *cap);
    int (*s_raw_fmt)(struct v4l2_subdev *sd, struct v4l2_vbi_format *fmt);
    int (*g_sliced_fmt)(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *fmt);
    int (*s_sliced_fmt)(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *fmt);
};
```

**Members**

- `decode_vbi_line`: video decoders that support sliced VBI need to implement
  this ioctl. Field p of the [`struct v4l2_decode_vbi_line`](#c-struct-v4l2_decode_vbi_line) is set to the
  start of the VBI data that was generated by the decoder. The driver
  then parses the sliced VBI data and sets the other fields in the
  struct accordingly. The pointer p is updated to point to the start of
  the payload which can be copied verbatim into the data field of the
  [`struct v4l2_sliced_vbi_data`](/kernel/userspace/userspace-api/media-v4l/dev-sliced-vbi.md#c-v4l2_sliced_vbi_data). If no valid VBI data was found, then the
  type field is set to 0 on return.
- `s_vbi_data`: used to generate VBI signals on a video signal.
  [`struct v4l2_sliced_vbi_data`](/kernel/userspace/userspace-api/media-v4l/dev-sliced-vbi.md#c-v4l2_sliced_vbi_data) is filled with the data packets that
  should be output. Note that if you set the line field to 0, then that
  VBI signal is disabled. If no valid VBI data was found, then the type
  field is set to 0 on return.
- `g_vbi_data`: used to obtain the sliced VBI packet from a readback register.
  Not all video decoders support this. If no data is available because
  the readback register contains invalid or erroneous data `-EIO` is
  returned. Note that you must fill in the 'id' member and the 'field'
  member (to determine whether CC data from the first or second field
  should be obtained).
- `g_sliced_vbi_cap`: callback for `VIDIOC_G_SLICED_VBI_CAP()` ioctl handler
  code.
- `s_raw_fmt`: setup the video encoder/decoder for raw VBI.
- `g_sliced_fmt`: retrieve the current sliced VBI settings.
- `s_sliced_fmt`: setup the sliced VBI settings.

#### <a id="c-struct-v4l2_subdev_sensor_ops"></a>`struct v4l2_subdev_sensor_ops`

v4l2-subdev sensor operations

**Definition**

```c
struct v4l2_subdev_sensor_ops {
    int (*g_skip_top_lines)(struct v4l2_subdev *sd, u32 *lines);
    int (*g_skip_frames)(struct v4l2_subdev *sd, u32 *frames);
};
```

**Members**

- `g_skip_top_lines`: number of lines at the top of the image to be skipped.
  This is needed for some sensors, which always corrupt
  several top lines of the output image, or which send their
  metadata in them.
- `g_skip_frames`: number of frames to skip at stream start. This is needed for
  buggy sensors that generate faulty frames when they are
  turned on.

#### <a id="c-enum-v4l2_subdev_ir_mode"></a>`enum v4l2_subdev_ir_mode`

describes the type of IR supported

**Constants**

- `V4L2_SUBDEV_IR_MODE_PULSE_WIDTH`: IR uses struct ir_raw_event records

#### <a id="c-struct-v4l2_subdev_ir_parameters"></a>`struct v4l2_subdev_ir_parameters`

Parameters for IR TX or TX

**Definition**

```c
struct v4l2_subdev_ir_parameters {
    unsigned int bytes_per_data_element;
    enum v4l2_subdev_ir_mode mode;
    bool enable;
    bool interrupt_enable;
    bool shutdown;
    bool modulation;
    u32 max_pulse_width;
    unsigned int carrier_freq;
    unsigned int duty_cycle;
    bool invert_level;
    bool invert_carrier_sense;
    u32 noise_filter_min_width;
    unsigned int carrier_range_lower;
    unsigned int carrier_range_upper;
    u32 resolution;
};
```

**Members**

- `bytes_per_data_element`: bytes per data element of data in read or
  write call.
- `mode`: IR mode as defined by [`enum v4l2_subdev_ir_mode`](#c-enum-v4l2_subdev_ir_mode).
- `enable`: device is active if true
- `interrupt_enable`: IR interrupts are enabled if true
- `shutdown`: if true: set hardware to low/no power, false: normal mode
- `modulation`: if true, it uses carrier, if false: baseband
- `max_pulse_width`: maximum pulse width in ns, valid only for baseband signal
- `carrier_freq`: carrier frequency in Hz, valid only for modulated signal
- `duty_cycle`: duty cycle percentage, valid only for modulated signal
- `invert_level`: invert signal level
- `invert_carrier_sense`: Send 0/space as a carrier burst. used only in TX.
- `noise_filter_min_width`: min time of a valid pulse, in ns. Used only for RX.
- `carrier_range_lower`: Lower carrier range, in Hz, valid only for modulated
  signal. Used only for RX.
- `carrier_range_upper`: Upper carrier range, in Hz, valid only for modulated
  signal. Used only for RX.
- `resolution`: The receive resolution, in ns . Used only for RX.

#### <a id="c-struct-v4l2_subdev_ir_ops"></a>`struct v4l2_subdev_ir_ops`

operations for IR subdevices

**Definition**

```c
struct v4l2_subdev_ir_ops {
    int (*rx_read)(struct v4l2_subdev *sd, u8 *buf, size_t count, ssize_t *num);
    int (*rx_g_parameters)(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *params);
    int (*rx_s_parameters)(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *params);
    int (*tx_write)(struct v4l2_subdev *sd, u8 *buf, size_t count, ssize_t *num);
    int (*tx_g_parameters)(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *params);
    int (*tx_s_parameters)(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *params);
};
```

**Members**

- `rx_read`: Reads received codes or pulse width data.
  The semantics are similar to a non-blocking `read()` call.
- `rx_g_parameters`: Get the current operating parameters and state of
  the IR receiver.
- `rx_s_parameters`: Set the current operating parameters and state of
  the IR receiver.  It is recommended to call
  \[rt\]x_g_parameters first to fill out the current state, and only change
  the fields that need to be changed.  Upon return, the actual device
  operating parameters and state will be returned.  Note that hardware
  limitations may prevent the actual settings from matching the requested
  settings - e.g. an actual carrier setting of 35,904 Hz when 36,000 Hz
  was requested.  An exception is when the shutdown parameter is true.
  The last used operational parameters will be returned, but the actual
  state of the hardware be different to minimize power consumption and
  processing when shutdown is true.
- `tx_write`: Writes codes or pulse width data for transmission.
  The semantics are similar to a non-blocking `write()` call.
- `tx_g_parameters`: Get the current operating parameters and state of
  the IR transmitter.
- `tx_s_parameters`: Set the current operating parameters and state of
  the IR transmitter.  It is recommended to call
  \[rt\]x_g_parameters first to fill out the current state, and only change
  the fields that need to be changed.  Upon return, the actual device
  operating parameters and state will be returned.  Note that hardware
  limitations may prevent the actual settings from matching the requested
  settings - e.g. an actual carrier setting of 35,904 Hz when 36,000 Hz
  was requested.  An exception is when the shutdown parameter is true.
  The last used operational parameters will be returned, but the actual
  state of the hardware be different to minimize power consumption and
  processing when shutdown is true.

#### <a id="c-struct-v4l2_subdev_pad_config"></a>`struct v4l2_subdev_pad_config`

Used for storing subdev pad information.

**Definition**

```c
struct v4l2_subdev_pad_config {
    struct v4l2_mbus_framefmt format;
    struct v4l2_rect crop;
    struct v4l2_rect compose;
    struct v4l2_fract interval;
};
```

**Members**

- `format`: [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt)
- `crop`: [`struct v4l2_rect`](/kernel/userspace/userspace-api/media-v4l/dev-overlay.md#c-v4l2_rect) to be used for crop
- `compose`: [`struct v4l2_rect`](/kernel/userspace/userspace-api/media-v4l/dev-overlay.md#c-v4l2_rect) to be used for compose
- `interval`: frame interval

#### <a id="c-struct-v4l2_subdev_stream_configs"></a>`struct v4l2_subdev_stream_configs`

A collection of stream configs.

**Definition**

```c
struct v4l2_subdev_stream_configs {
    u32 num_configs;
    struct v4l2_subdev_stream_config *configs;
};
```

**Members**

- `num_configs`: number of entries in **config**.
- `configs`: an array of [`struct v4l2_subdev_stream_configs`](#c-struct-v4l2_subdev_stream_configs).

#### <a id="c-struct-v4l2_subdev_krouting"></a>`struct v4l2_subdev_krouting`

subdev routing table

**Definition**

```c
struct v4l2_subdev_krouting {
    unsigned int len_routes;
    unsigned int num_routes;
    struct v4l2_subdev_route *routes;
};
```

**Members**

- `len_routes`: length of routes array, in routes
- `num_routes`: number of routes
- `routes`: [`struct v4l2_subdev_route`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-routing.md#c-v4l2_subdev_route)

**Description**

This structure contains the routing table for a subdev.

#### <a id="c-struct-v4l2_subdev_state"></a>`struct v4l2_subdev_state`

Used for storing subdev state information.

**Definition**

```c
struct v4l2_subdev_state {
    struct mutex _lock;
    struct mutex *lock;
    struct v4l2_subdev *sd;
    struct v4l2_subdev_pad_config *pads;
    struct v4l2_subdev_krouting routing;
    struct v4l2_subdev_stream_configs stream_configs;
};
```

**Members**

- `_lock`: default for 'lock'
- `lock`: mutex for the state. May be replaced by the user.
- `sd`: the sub-device which the state is related to
- `pads`: [`struct v4l2_subdev_pad_config`](#c-struct-v4l2_subdev_pad_config) array
- `routing`: routing table for the subdev
- `stream_configs`: stream configurations (only for V4L2_SUBDEV_FL_STREAMS)

**Description**

This structure only needs to be passed to the pad op if the 'which' field
of the main argument is set to `V4L2_SUBDEV_FORMAT_TRY`. For
`V4L2_SUBDEV_FORMAT_ACTIVE` it is safe to pass `NULL`.

#### <a id="c-struct-v4l2_subdev_pad_ops"></a>`struct v4l2_subdev_pad_ops`

v4l2-subdev pad level operations

**Definition**

```c
struct v4l2_subdev_pad_ops {
        int (*enum_mbus_code)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_mbus_code_enum *code);
        int (*enum_frame_size)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_size_enum *fse);
        int (*enum_frame_interval)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_interval_enum *fie);
        int (*get_fmt)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *format);
        int (*set_fmt)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *format);
        int (*get_selection)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_selection *sel);
        int (*set_selection)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_selection *sel);
        int (*get_frame_interval)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_interval *interval);
        int (*set_frame_interval)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_interval *interval);
        int (*get_edid)(struct v4l2_subdev *sd, struct v4l2_edid *edid);
        int (*set_edid)(struct v4l2_subdev *sd, struct v4l2_edid *edid);
        int (*s_dv_timings)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_dv_timings *timings);
        int (*g_dv_timings)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_dv_timings *timings);
        int (*query_dv_timings)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_dv_timings *timings);
        int (*dv_timings_cap)(struct v4l2_subdev *sd, struct v4l2_dv_timings_cap *cap);
        int (*enum_dv_timings)(struct v4l2_subdev *sd, struct v4l2_enum_dv_timings *timings);
    #ifdef CONFIG_MEDIA_CONTROLLER;
        int (*link_validate)(struct v4l2_subdev *sd, struct media_link *link, struct v4l2_subdev_format *source_fmt, struct v4l2_subdev_format *sink_fmt);
    #endif;
        int (*get_frame_desc)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_frame_desc *fd);
        int (*set_frame_desc)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_frame_desc *fd);
        int (*get_mbus_config)(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_config *config);
        int (*set_routing)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, enum v4l2_subdev_format_whence which, struct v4l2_subdev_krouting *route);
        int (*enable_streams)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, u32 pad, u64 streams_mask);
        int (*disable_streams)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, u32 pad, u64 streams_mask);
};
```

**Members**

- `enum_mbus_code`: callback for `VIDIOC_SUBDEV_ENUM_MBUS_CODE()` ioctl handler
  code.
- `enum_frame_size`: callback for `VIDIOC_SUBDEV_ENUM_FRAME_SIZE()` ioctl handler
  code.
- `enum_frame_interval`: callback for `VIDIOC_SUBDEV_ENUM_FRAME_INTERVAL()` ioctl
  handler code.
- `get_fmt`: callback for `VIDIOC_SUBDEV_G_FMT()` ioctl handler code.
- `set_fmt`: callback for `VIDIOC_SUBDEV_S_FMT()` ioctl handler code.
- `get_selection`: callback for `VIDIOC_SUBDEV_G_SELECTION()` ioctl handler code.
- `set_selection`: callback for `VIDIOC_SUBDEV_S_SELECTION()` ioctl handler code.
- `get_frame_interval`: callback for `VIDIOC_SUBDEV_G_FRAME_INTERVAL()`
  ioctl handler code.
- `set_frame_interval`: callback for `VIDIOC_SUBDEV_S_FRAME_INTERVAL()`
  ioctl handler code.
- `get_edid`: callback for `VIDIOC_SUBDEV_G_EDID()` ioctl handler code.
- `set_edid`: callback for `VIDIOC_SUBDEV_S_EDID()` ioctl handler code.
- `s_dv_timings`: Set custom dv timings in the sub device. This is used
  when sub device is capable of setting detailed timing information
  in the hardware to generate/detect the video signal.
- `g_dv_timings`: Get custom dv timings in the sub device.
- `query_dv_timings`: callback for `VIDIOC_QUERY_DV_TIMINGS()` ioctl handler code.
- `dv_timings_cap`: callback for `VIDIOC_SUBDEV_DV_TIMINGS_CAP()` ioctl handler
  code.
- `enum_dv_timings`: callback for `VIDIOC_SUBDEV_ENUM_DV_TIMINGS()` ioctl handler
  code.
- `link_validate`: used by the media controller code to check if the links
  that belongs to a pipeline can be used for stream.
- `get_frame_desc`: get the current low level media bus frame parameters.
- `set_frame_desc`: set the low level media bus frame parameters, **fd** array
  may be adjusted by the subdev driver to device capabilities.
- `get_mbus_config`: get the media bus configuration of a remote sub-device.
  The media bus configuration is usually retrieved from the
  firmware interface at sub-device probe time, immediately
  applied to the hardware and eventually adjusted by the
  driver. Remote sub-devices (usually video receivers) shall
  use this operation to query the transmitting end bus
  configuration in order to adjust their own one accordingly.
  Callers should make sure they get the most up-to-date as
  possible configuration from the remote end, likely calling
  this operation as close as possible to stream on time. The
  operation shall fail if the pad index it has been called on
  is not valid or in case of unrecoverable failures. The
  config argument has been memset to 0 just before calling
  the op.
- `set_routing`: Enable or disable data connection routes described in the
  subdevice routing table. Subdevs that implement this operation
  must set the V4L2_SUBDEV_FL_STREAMS flag.
- `enable_streams`: Enable the streams defined in streams_mask on the given
  source pad. Subdevs that implement this operation must use the active
  state management provided by the subdev core (enabled through a call to
  [`v4l2_subdev_init_finalize()`](#c-v4l2_subdev_init_finalize) at initialization time). Do not call
  directly, use [`v4l2_subdev_enable_streams()`](#c-v4l2_subdev_enable_streams) instead.
- `disable_streams`: Disable the streams defined in streams_mask on the given
  source pad. Subdevs that implement this operation must use the active
  state management provided by the subdev core (enabled through a call to
  [`v4l2_subdev_init_finalize()`](#c-v4l2_subdev_init_finalize) at initialization time). Do not call
  directly, use [`v4l2_subdev_disable_streams()`](#c-v4l2_subdev_disable_streams) instead.

**Description**

Drivers that support only a single stream without setting the
V4L2_SUBDEV_CAP_STREAMS sub-device capability flag can ignore the mask
argument.

Drivers that support only a single stream without setting the
V4L2_SUBDEV_CAP_STREAMS sub-device capability flag can ignore the mask
argument.

#### <a id="c-struct-v4l2_subdev_ops"></a>`struct v4l2_subdev_ops`

Subdev operations

**Definition**

```c
struct v4l2_subdev_ops {
    const struct v4l2_subdev_core_ops       *core;
    const struct v4l2_subdev_tuner_ops      *tuner;
    const struct v4l2_subdev_audio_ops      *audio;
    const struct v4l2_subdev_video_ops      *video;
    const struct v4l2_subdev_vbi_ops        *vbi;
    const struct v4l2_subdev_ir_ops         *ir;
    const struct v4l2_subdev_sensor_ops     *sensor;
    const struct v4l2_subdev_pad_ops        *pad;
};
```

**Members**

- `core`: pointer to [`struct v4l2_subdev_core_ops`](#c-struct-v4l2_subdev_core_ops). Can be `NULL`
- `tuner`: pointer to [`struct v4l2_subdev_tuner_ops`](#c-struct-v4l2_subdev_tuner_ops). Can be `NULL`
- `audio`: pointer to [`struct v4l2_subdev_audio_ops`](#c-struct-v4l2_subdev_audio_ops). Can be `NULL`
- `video`: pointer to [`struct v4l2_subdev_video_ops`](#c-struct-v4l2_subdev_video_ops). Can be `NULL`
- `vbi`: pointer to [`struct v4l2_subdev_vbi_ops`](#c-struct-v4l2_subdev_vbi_ops). Can be `NULL`
- `ir`: pointer to [`struct v4l2_subdev_ir_ops`](#c-struct-v4l2_subdev_ir_ops). Can be `NULL`
- `sensor`: pointer to [`struct v4l2_subdev_sensor_ops`](#c-struct-v4l2_subdev_sensor_ops). Can be `NULL`
- `pad`: pointer to [`struct v4l2_subdev_pad_ops`](#c-struct-v4l2_subdev_pad_ops). Can be `NULL`

#### <a id="c-struct-v4l2_subdev_internal_ops"></a>`struct v4l2_subdev_internal_ops`

V4L2 subdev internal ops

**Definition**

```c
struct v4l2_subdev_internal_ops {
    int (*init_state)(struct v4l2_subdev *sd, struct v4l2_subdev_state *state);
    int (*registered)(struct v4l2_subdev *sd);
    void (*unregistered)(struct v4l2_subdev *sd);
    int (*open)(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh);
    int (*close)(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh);
    void (*release)(struct v4l2_subdev *sd);
};
```

**Members**

- `init_state`: initialize the subdev state to default values
- `registered`: called when this subdev is registered. When called the v4l2_dev
  field is set to the correct v4l2_device.
- `unregistered`: called when this subdev is unregistered. When called the
  v4l2_dev field is still set to the correct v4l2_device.
- `open`: called when the subdev device node is opened by an application.
- `close`: called when the subdev device node is closed. Please note that
  it is possible for **close** to be called after **unregistered**!
- `release`: called when the last user of the subdev device is gone. This
  happens after the **unregistered** callback and when the last open
  filehandle to the v4l-subdevX device node was closed. If no device
  node was created for this sub-device, then the **release** callback
  is called right after the **unregistered** callback.
  The **release** callback is typically used to free the memory containing
  the v4l2_subdev structure. It is almost certainly required for any
  sub-device that sets the V4L2_SUBDEV_FL_HAS_DEVNODE flag.

**Description**

> [!NOTE]
> Never call this from drivers, only the v4l2 framework can call
> these ops.

#### <a id="c-struct-v4l2_subdev_platform_data"></a>`struct v4l2_subdev_platform_data`

regulators config struct

**Definition**

```c
struct v4l2_subdev_platform_data {
    struct regulator_bulk_data *regulators;
    int num_regulators;
    void *host_priv;
};
```

**Members**

- `regulators`: Optional regulators used to power on/off the subdevice
- `num_regulators`: Number of regululators
- `host_priv`: Per-subdevice data, specific for a certain video host device

#### <a id="c-struct-v4l2_subdev"></a>`struct v4l2_subdev`

describes a V4L2 sub-device

**Definition**

```c
struct v4l2_subdev {
    #if defined(CONFIG_MEDIA_CONTROLLER);
        struct media_entity entity;
    #endif;
        struct list_head list;
        struct module *owner;
        bool owner_v4l2_dev;
        u32 flags;
        struct v4l2_device *v4l2_dev;
        const struct v4l2_subdev_ops *ops;
        const struct v4l2_subdev_internal_ops *internal_ops;
        struct v4l2_ctrl_handler *ctrl_handler;
        char name[52];
        u32 grp_id;
        void *dev_priv;
        void *host_priv;
        struct video_device *devnode;
        struct device *dev;
        struct fwnode_handle *fwnode;
        struct list_head async_list;
        struct list_head async_subdev_endpoint_list;
        struct v4l2_async_notifier *subdev_notifier;
        struct list_head asc_list;
        struct v4l2_subdev_platform_data *pdata;
        struct mutex *state_lock;
        struct led_classdev *privacy_led;
        struct v4l2_subdev_state *active_state;
        u64 enabled_pads;
        bool s_stream_enabled;
};
```

**Members**

- `entity`: pointer to [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity)
- `list`: List of sub-devices
- `owner`: The owner is the same as the driver's [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) owner.
- `owner_v4l2_dev`: true if the `sd->owner` matches the owner of **v4l2_dev->dev**
  owner. Initialized by [`v4l2_device_register_subdev()`](/kernel/hardware/driver-api/media/v4l2-device.md#c-v4l2_device_register_subdev).
- `flags`: subdev flags. Can be:
  `V4L2_SUBDEV_FL_IS_I2C` - Set this flag if this subdev is a i2c device;
  `V4L2_SUBDEV_FL_IS_SPI` - Set this flag if this subdev is a spi device;
  `V4L2_SUBDEV_FL_HAS_DEVNODE` - Set this flag if this subdev needs a
  device node;
  `V4L2_SUBDEV_FL_HAS_EVENTS` -  Set this flag if this subdev generates
  events.
- `v4l2_dev`: pointer to struct [`v4l2_device`](/kernel/hardware/driver-api/media/v4l2-device.md#c-struct-v4l2_device)
- `ops`: pointer to struct [`v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops)
- `internal_ops`: pointer to struct [`v4l2_subdev_internal_ops`](#c-struct-v4l2_subdev_internal_ops).
  Never call these internal ops from within a driver!
- `ctrl_handler`: The control handler of this subdev. May be NULL.
- `name`: Name of the sub-device. Please notice that the name must be unique.
- `grp_id`: can be used to group similar subdevs. Value is driver-specific
- `dev_priv`: pointer to private data
- `host_priv`: pointer to private data used by the device where the subdev
  is attached.
- `devnode`: subdev device node
- `dev`: pointer to the physical device, if any
- `fwnode`: The fwnode_handle of the subdev, usually the same as
  either dev->of_node->fwnode or dev->fwnode (whichever is non-NULL).
- `async_list`: Links this subdev to a global subdev_list or
  **notifier->done_list** list.
- `async_subdev_endpoint_list`: List entry in async_subdev_endpoint_entry of
  [`struct v4l2_async_subdev_endpoint`](/kernel/hardware/driver-api/media/v4l2-async.md#c-struct-v4l2_async_subdev_endpoint).
- `subdev_notifier`: A sub-device notifier implicitly registered for the sub-
  device using [`v4l2_async_register_subdev_sensor()`](/kernel/hardware/driver-api/media/v4l2-async.md#c-v4l2_async_register_subdev_sensor).
- `asc_list`: Async connection list, of [`struct v4l2_async_connection`](/kernel/hardware/driver-api/media/v4l2-async.md#c-struct-v4l2_async_connection).subdev_entry.
- `pdata`: common part of subdevice platform data
- `state_lock`: A pointer to a lock used for all the subdev's states, set by the
  driver. This is optional. If NULL, each state instance will get
  a lock of its own.
- `privacy_led`: Optional pointer to a LED classdev for the privacy LED for sensors.
- `active_state`: Active state for the subdev (NULL for subdevs tracking the
  state internally). Initialized by calling
  [`v4l2_subdev_init_finalize()`](#c-v4l2_subdev_init_finalize).
- `enabled_pads`: Bitmask of enabled pads used by [`v4l2_subdev_enable_streams()`](#c-v4l2_subdev_enable_streams)
  and [`v4l2_subdev_disable_streams()`](#c-v4l2_subdev_disable_streams) helper functions for
  fallback cases.
- `s_stream_enabled`: Tracks whether streaming has been enabled with s_stream.
  This is only for `call_s_stream()` internal use.

**Description**

Each instance of a subdev driver should create this struct, either
stand-alone or embedded in a larger struct.

This structure should be initialized by [`v4l2_subdev_init()`](#c-v4l2_subdev_init) or one of
its variants: [`v4l2_spi_subdev_init()`](/kernel/hardware/driver-api/media/v4l2-common.md#c-v4l2_spi_subdev_init), [`v4l2_i2c_subdev_init()`](/kernel/hardware/driver-api/media/v4l2-common.md#c-v4l2_i2c_subdev_init).

#### <a id="c-media_entity_to_v4l2_subdev"></a>`media_entity_to_v4l2_subdev()`

```c
media_entity_to_v4l2_subdev(ent)
```

Returns a [`struct v4l2_subdev`](#c-struct-v4l2_subdev) from the [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity) embedded in it.

**Parameters**

- `ent`: pointer to [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity).

#### <a id="c-vdev_to_v4l2_subdev"></a>`vdev_to_v4l2_subdev()`

```c
vdev_to_v4l2_subdev(vdev)
```

Returns a [`struct v4l2_subdev`](#c-struct-v4l2_subdev) from the [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device) embedded on it.

**Parameters**

- `vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)

#### <a id="c-struct-v4l2_subdev_fh"></a>`struct v4l2_subdev_fh`

Used for storing subdev information per file handle

**Definition**

```c
struct v4l2_subdev_fh {
        struct v4l2_fh vfh;
        struct module *owner;
    #if defined(CONFIG_VIDEO_V4L2_SUBDEV_API);
        struct v4l2_subdev_state *state;
        u64 client_caps;
    #endif;
};
```

**Members**

- `vfh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)
- `owner`: module pointer to the owner of this file handle
- `state`: pointer to [`struct v4l2_subdev_state`](#c-struct-v4l2_subdev_state)
- `client_caps`: bitmask of `V4L2_SUBDEV_CLIENT_CAP_*`

#### <a id="c-to_v4l2_subdev_fh"></a>`to_v4l2_subdev_fh()`

```c
to_v4l2_subdev_fh(fh)
```

Returns a [`struct v4l2_subdev_fh`](#c-struct-v4l2_subdev_fh) from the [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh) embedded on it.

**Parameters**

- `fh`: pointer to [`struct v4l2_fh`](/kernel/hardware/driver-api/media/v4l2-fh.md#c-struct-v4l2_fh)

#### <a id="c-v4l2_set_subdevdata"></a>`v4l2_set_subdevdata()`

```c
void v4l2_set_subdevdata(struct v4l2_subdev *sd, void *p)
```

Sets V4L2 dev private device data

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `void *p`: pointer to the private device data to be stored.

#### <a id="c-v4l2_get_subdevdata"></a>`v4l2_get_subdevdata()`

```c
void * v4l2_get_subdevdata(const struct v4l2_subdev *sd)
```

Gets V4L2 dev private device data

**Parameters**

- `const struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)

**Description**

Returns the pointer to the private device data to be stored.

#### <a id="c-v4l2_set_subdev_hostdata"></a>`v4l2_set_subdev_hostdata()`

```c
void v4l2_set_subdev_hostdata(struct v4l2_subdev *sd, void *p)
```

Sets V4L2 dev private host data

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `void *p`: pointer to the private data to be stored.

#### <a id="c-v4l2_get_subdev_hostdata"></a>`v4l2_get_subdev_hostdata()`

```c
void * v4l2_get_subdev_hostdata(const struct v4l2_subdev *sd)
```

Gets V4L2 dev private data

**Parameters**

- `const struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)

**Description**

Returns the pointer to the private host data to be stored.

#### <a id="c-v4l2_subdev_get_fwnode_pad_1_to_1"></a>`v4l2_subdev_get_fwnode_pad_1_to_1()`

```c
int v4l2_subdev_get_fwnode_pad_1_to_1(struct media_entity *entity, struct fwnode_endpoint *endpoint)
```

Get pad number from a subdev fwnode endpoint, assuming 1:1 port:pad

**Parameters**

- `struct media_entity *entity`: Pointer to the subdev entity
- `struct fwnode_endpoint *endpoint`: Pointer to a parsed fwnode endpoint

**Description**

This function can be used as the .get_fwnode_pad operation for
subdevices that map port numbers and pad indexes 1:1. If the endpoint
is owned by the subdevice, the function returns the endpoint port
number.

Returns the endpoint port number on success or a negative error code.

#### <a id="c-v4l2_subdev_link_validate_default"></a>`v4l2_subdev_link_validate_default()`

```c
int v4l2_subdev_link_validate_default(struct v4l2_subdev *sd, struct media_link *link, struct v4l2_subdev_format *source_fmt, struct v4l2_subdev_format *sink_fmt)
```

validates a media link

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `struct media_link *link`: pointer to [`struct media_link`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_link)
- `struct v4l2_subdev_format *source_fmt`: pointer to [`struct v4l2_subdev_format`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#c-v4l2_subdev_format)
- `struct v4l2_subdev_format *sink_fmt`: pointer to [`struct v4l2_subdev_format`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#c-v4l2_subdev_format)

**Description**

This function ensures that width, height and the media bus pixel
code are equal on both source and sink of the link.

#### <a id="c-v4l2_subdev_link_validate"></a>`v4l2_subdev_link_validate()`

```c
int v4l2_subdev_link_validate(struct media_link *link)
```

validates a media link

**Parameters**

- `struct media_link *link`: pointer to [`struct media_link`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_link)

**Description**

This function calls the subdev's link_validate ops to validate
if a media link is valid for streaming. It also internally
calls [`v4l2_subdev_link_validate_default()`](#c-v4l2_subdev_link_validate_default) to ensure that
width, height and the media bus pixel code are equal on both
source and sink of the link.

The function can be used as a drop-in `media_entity_ops.link_validate`
implementation for v4l2_subdev instances. It supports all links between
subdevs, as well as links between subdevs and video devices, provided that
the video devices also implement their `media_entity_ops.link_validate`
operation.

#### <a id="c-v4l2_subdev_has_pad_interdep"></a>`v4l2_subdev_has_pad_interdep()`

```c
bool v4l2_subdev_has_pad_interdep(struct media_entity *entity, unsigned int pad0, unsigned int pad1)
```

MC has_pad_interdep implementation for subdevs

**Parameters**

- `struct media_entity *entity`: pointer to [`struct media_entity`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_entity)
- `unsigned int pad0`: pad number for the first pad
- `unsigned int pad1`: pad number for the second pad

**Description**

This function is an implementation of the
media_entity_operations.has_pad_interdep operation for subdevs that
implement the multiplexed streams API (as indicated by the
V4L2_SUBDEV_FL_STREAMS subdev flag).

It considers two pads interdependent if there is an active route between pad0
and pad1.

#### <a id="c-__v4l2_subdev_state_alloc"></a>`__v4l2_subdev_state_alloc()`

```c
struct v4l2_subdev_state * __v4l2_subdev_state_alloc(struct v4l2_subdev *sd, const char *lock_name, struct lock_class_key *key)
```

allocate v4l2_subdev_state

**Parameters**

- `struct v4l2_subdev *sd`: pointer to [`struct v4l2_subdev`](#c-struct-v4l2_subdev) for which the state is being allocated.
- `const char *lock_name`: name of the state lock
- `struct lock_class_key *key`: lock_class_key for the lock

**Description**

Must call [`__v4l2_subdev_state_free()`](#c-__v4l2_subdev_state_free) when state is no longer needed.

Not to be called directly by the drivers.

#### <a id="c-__v4l2_subdev_state_free"></a>`__v4l2_subdev_state_free()`

```c
void __v4l2_subdev_state_free(struct v4l2_subdev_state *state)
```

free a v4l2_subdev_state

**Parameters**

- `struct v4l2_subdev_state *state`: v4l2_subdev_state to be freed.

**Description**

Not to be called directly by the drivers.

#### <a id="c-v4l2_subdev_init_finalize"></a>`v4l2_subdev_init_finalize()`

```c
v4l2_subdev_init_finalize(sd)
```

Finalizes the initialization of the subdevice

**Parameters**

- `sd`: The subdev

**Description**

This function finalizes the initialization of the subdev, including
allocation of the active state for the subdev.

This function must be called by the subdev drivers that use the centralized
active state, after the subdev struct has been initialized and
[`media_entity_pads_init()`](/kernel/hardware/driver-api/media/mc-core.md#c-media_entity_pads_init) has been called, but before registering the
subdev.

The user must call [`v4l2_subdev_cleanup()`](#c-v4l2_subdev_cleanup) when the subdev is being removed.

#### <a id="c-v4l2_subdev_cleanup"></a>`v4l2_subdev_cleanup()`

```c
void v4l2_subdev_cleanup(struct v4l2_subdev *sd)
```

Releases the resources allocated by the subdevice

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

Clean up a V4L2 async sub-device. Must be called for a sub-device as part of
its release if resources have been associated with it using
[`v4l2_async_subdev_endpoint_add()`](/kernel/hardware/driver-api/media/v4l2-async.md#c-v4l2_async_subdev_endpoint_add) or [`v4l2_subdev_init_finalize()`](#c-v4l2_subdev_init_finalize).

#### <a id="c-v4l2_subdev_state_get_format"></a>`v4l2_subdev_state_get_format()`

```c
v4l2_subdev_state_get_format(state, pad, ...)
```

Get pointer to a stream format

**Parameters**

- `state`: subdevice state
- `pad`: pad id
- `...`: stream id (optional argument)

**Description**

This returns a pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) for the given pad +
stream in the subdev state.

For stream-unaware drivers the format for the corresponding pad is returned.
If the pad does not exist, NULL is returned.

#### <a id="c-v4l2_subdev_state_get_crop"></a>`v4l2_subdev_state_get_crop()`

```c
v4l2_subdev_state_get_crop(state, pad, ...)
```

Get pointer to a stream crop rectangle

**Parameters**

- `state`: subdevice state
- `pad`: pad id
- `...`: stream id (optional argument)

**Description**

This returns a pointer to crop rectangle for the given pad + stream in the
subdev state.

For stream-unaware drivers the crop rectangle for the corresponding pad is
returned. If the pad does not exist, NULL is returned.

#### <a id="c-v4l2_subdev_state_get_compose"></a>`v4l2_subdev_state_get_compose()`

```c
v4l2_subdev_state_get_compose(state, pad, ...)
```

Get pointer to a stream compose rectangle

**Parameters**

- `state`: subdevice state
- `pad`: pad id
- `...`: stream id (optional argument)

**Description**

This returns a pointer to compose rectangle for the given pad + stream in the
subdev state.

For stream-unaware drivers the compose rectangle for the corresponding pad is
returned. If the pad does not exist, NULL is returned.

#### <a id="c-v4l2_subdev_state_get_interval"></a>`v4l2_subdev_state_get_interval()`

```c
v4l2_subdev_state_get_interval(state, pad, ...)
```

Get pointer to a stream frame interval

**Parameters**

- `state`: subdevice state
- `pad`: pad id
- `...`: stream id (optional argument)

**Description**

This returns a pointer to the frame interval for the given pad + stream in
the subdev state.

For stream-unaware drivers the frame interval for the corresponding pad is
returned. If the pad does not exist, NULL is returned.

#### <a id="c-v4l2_subdev_get_fmt"></a>`v4l2_subdev_get_fmt()`

```c
int v4l2_subdev_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *format)
```

Fill format based on state

**Parameters**

- `struct v4l2_subdev *sd`: subdevice
- `struct v4l2_subdev_state *state`: subdevice state
- `struct v4l2_subdev_format *format`: pointer to [`struct v4l2_subdev_format`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-fmt.md#c-v4l2_subdev_format)

**Description**

Fill **format->format** field based on the information in the **format** struct.

This function can be used by the subdev drivers which support active state to
implement v4l2_subdev_pad_ops.get_fmt if the subdev driver does not need to
do anything special in their get_fmt op.

Returns 0 on success, error value otherwise.

#### <a id="c-v4l2_subdev_get_frame_interval"></a>`v4l2_subdev_get_frame_interval()`

```c
int v4l2_subdev_get_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_interval *fi)
```

Fill frame interval based on state

**Parameters**

- `struct v4l2_subdev *sd`: subdevice
- `struct v4l2_subdev_state *state`: subdevice state
- `struct v4l2_subdev_frame_interval *fi`: pointer to [`struct v4l2_subdev_frame_interval`](/kernel/userspace/userspace-api/media-v4l/vidioc-subdev-g-frame-interval.md#c-v4l2_subdev_frame_interval)

**Description**

Fill **fi->interval** field based on the information in the **fi** struct.

This function can be used by the subdev drivers which support active state to
implement v4l2_subdev_pad_ops.get_frame_interval if the subdev driver does
not need to do anything special in their get_frame_interval op.

Returns 0 on success, error value otherwise.

#### <a id="c-v4l2_subdev_set_routing"></a>`v4l2_subdev_set_routing()`

```c
int v4l2_subdev_set_routing(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, const struct v4l2_subdev_krouting *routing)
```

Set given routing to subdev state

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `struct v4l2_subdev_state *state`: The subdevice state
- `const struct v4l2_subdev_krouting *routing`: Routing that will be copied to subdev state

**Description**

This will release old routing table (if any) from the state, allocate
enough space for the given routing, and copy the routing.

This can be used from the subdev driver's set_routing op, after validating
the routing.

#### <a id="c-for_each_active_route"></a>`for_each_active_route()`

```c
for_each_active_route(routing, route)
```

iterate on all active routes of a routing table

**Parameters**

- `routing`: The routing table
- `route`: The route iterator

#### <a id="c-v4l2_subdev_set_routing_with_fmt"></a>`v4l2_subdev_set_routing_with_fmt()`

```c
int v4l2_subdev_set_routing_with_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, const struct v4l2_subdev_krouting *routing, const struct v4l2_mbus_framefmt *fmt)
```

Set given routing and format to subdev state

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `struct v4l2_subdev_state *state`: The subdevice state
- `const struct v4l2_subdev_krouting *routing`: Routing that will be copied to subdev state
- `const struct v4l2_mbus_framefmt *fmt`: Format used to initialize all the streams

**Description**

This is the same as v4l2_subdev_set_routing, but additionally initializes
all the streams using the given format.

#### <a id="c-v4l2_subdev_routing_find_opposite_end"></a>`v4l2_subdev_routing_find_opposite_end()`

```c
int v4l2_subdev_routing_find_opposite_end(const struct v4l2_subdev_krouting *routing, u32 pad, u32 stream, u32 *other_pad, u32 *other_stream)
```

Find the opposite stream

**Parameters**

- `const struct v4l2_subdev_krouting *routing`: routing used to find the opposite side
- `u32 pad`: pad id
- `u32 stream`: stream id
- `u32 *other_pad`: pointer used to return the opposite pad
- `u32 *other_stream`: pointer used to return the opposite stream

**Description**

This function uses the routing table to find the pad + stream which is
opposite the given pad + stream.

**other_pad** and/or **other_stream** can be NULL if the caller does not need the
value.

Returns 0 on success, or -EINVAL if no matching route is found.

#### <a id="c-v4l2_subdev_state_get_opposite_stream_format"></a>`v4l2_subdev_state_get_opposite_stream_format()`

```c
struct v4l2_mbus_framefmt * v4l2_subdev_state_get_opposite_stream_format(struct v4l2_subdev_state *state, u32 pad, u32 stream)
```

Get pointer to opposite stream format

**Parameters**

- `struct v4l2_subdev_state *state`: subdevice state
- `u32 pad`: pad id
- `u32 stream`: stream id

**Description**

This returns a pointer to [`struct v4l2_mbus_framefmt`](/kernel/userspace/userspace-api/media-v4l/subdev-formats.md#c-v4l2_mbus_framefmt) for the pad + stream
that is opposite the given pad + stream in the subdev state.

If the state does not contain the given pad + stream, NULL is returned.

#### <a id="c-v4l2_subdev_state_xlate_streams"></a>`v4l2_subdev_state_xlate_streams()`

```c
u64 v4l2_subdev_state_xlate_streams(const struct v4l2_subdev_state *state, u32 pad0, u32 pad1, u64 *streams)
```

Translate streams from one pad to another

**Parameters**

- `const struct v4l2_subdev_state *state`: Subdevice state
- `u32 pad0`: The first pad
- `u32 pad1`: The second pad
- `u64 *streams`: Streams bitmask on the first pad

**Description**

Streams on sink pads of a subdev are routed to source pads as expressed in
the subdev state routing table. Stream numbers don't necessarily match on
the sink and source side of a route. This function translates stream numbers
on **pad0**, expressed as a bitmask in **streams**, to the corresponding streams
on **pad1** using the routing table from the **state**. It returns the stream mask
on **pad1**, and updates **streams** with the streams that have been found in the
routing table.

**pad0** and **pad1** must be a sink and a source, in any order.

**Return**

The bitmask of streams of **pad1** that are routed to **streams** on **pad0**.

#### <a id="c-enum-v4l2_subdev_routing_restriction"></a>`enum v4l2_subdev_routing_restriction`

Subdevice internal routing restrictions

**Constants**

- `V4L2_SUBDEV_ROUTING_NO_1_TO_N`: an input stream shall not be routed to multiple output streams (stream
  duplication)
- `V4L2_SUBDEV_ROUTING_NO_N_TO_1`: multiple input streams shall not be routed to the same output stream
  (stream merging)
- `V4L2_SUBDEV_ROUTING_NO_SINK_STREAM_MIX`: all streams from a sink pad must be routed to a single source pad
- `V4L2_SUBDEV_ROUTING_NO_SOURCE_STREAM_MIX`: all streams on a source pad must originate from a single sink pad
- `V4L2_SUBDEV_ROUTING_NO_SINK_MULTIPLEXING`: sink pads shall not contain multiplexed streams
- `V4L2_SUBDEV_ROUTING_NO_SOURCE_MULTIPLEXING`: source pads shall not contain multiplexed streams
- `V4L2_SUBDEV_ROUTING_ONLY_1_TO_1`: only non-overlapping 1-to-1 stream routing is allowed (a combination of
  **V4L2_SUBDEV_ROUTING_NO_1_TO_N** and **V4L2_SUBDEV_ROUTING_NO_N_TO_1**)
- `V4L2_SUBDEV_ROUTING_NO_STREAM_MIX`: all streams from a sink pad must be routed to a single source pad, and
  that source pad shall not get routes from any other sink pad
  (a combination of **V4L2_SUBDEV_ROUTING_NO_SINK_STREAM_MIX** and
  **V4L2_SUBDEV_ROUTING_NO_SOURCE_STREAM_MIX**)
- `V4L2_SUBDEV_ROUTING_NO_MULTIPLEXING`: no multiplexed streams allowed on either source or sink sides.

#### <a id="c-v4l2_subdev_routing_validate"></a>`v4l2_subdev_routing_validate()`

```c
int v4l2_subdev_routing_validate(struct v4l2_subdev *sd, const struct v4l2_subdev_krouting *routing, enum v4l2_subdev_routing_restriction disallow)
```

Verify that routes comply with driver constraints

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `const struct v4l2_subdev_krouting *routing`: Routing to verify
- `enum v4l2_subdev_routing_restriction disallow`: Restrictions on routes

**Description**

This verifies that the given routing complies with the **disallow** constraints.

Returns 0 on success, error value otherwise.

#### <a id="c-v4l2_subdev_enable_streams"></a>`v4l2_subdev_enable_streams()`

```c
int v4l2_subdev_enable_streams(struct v4l2_subdev *sd, u32 pad, u64 streams_mask)
```

Enable streams on a pad

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `u32 pad`: The pad
- `u64 streams_mask`: Bitmask of streams to enable

**Description**

This function enables streams on a source **pad** of a subdevice. The pad is
identified by its index, while the streams are identified by the
**streams_mask** bitmask. This allows enabling multiple streams on a pad at
once.

Enabling a stream that is already enabled isn't allowed. If **streams_mask**
contains an already enabled stream, this function returns -EALREADY without
performing any operation.

Per-stream enable is only available for subdevs that implement the
.`enable_streams()` and .`disable_streams()` operations. For other subdevs, this
function implements a best-effort compatibility by calling the .`s_stream()`
operation, limited to subdevs that have a single source pad.

Drivers that are not stream-aware shall set **streams_mask** to BIT_ULL(0).

**Return**

* 0: Success
* -EALREADY: One of the streams in streams_mask is already enabled
* -EINVAL: The pad index is invalid, or doesn't correspond to a source pad
* -EOPNOTSUPP: Falling back to the legacy .`s_stream()` operation is
  impossible because the subdev has multiple source pads

#### <a id="c-v4l2_subdev_disable_streams"></a>`v4l2_subdev_disable_streams()`

```c
int v4l2_subdev_disable_streams(struct v4l2_subdev *sd, u32 pad, u64 streams_mask)
```

Disable streams on a pad

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `u32 pad`: The pad
- `u64 streams_mask`: Bitmask of streams to disable

**Description**

This function disables streams on a source **pad** of a subdevice. The pad is
identified by its index, while the streams are identified by the
**streams_mask** bitmask. This allows disabling multiple streams on a pad at
once.

Disabling a streams that is not enabled isn't allowed. If **streams_mask**
contains a disabled stream, this function returns -EALREADY without
performing any operation.

Per-stream disable is only available for subdevs that implement the
.`enable_streams()` and .`disable_streams()` operations. For other subdevs, this
function implements a best-effort compatibility by calling the .`s_stream()`
operation, limited to subdevs that have a single source pad.

Drivers that are not stream-aware shall set **streams_mask** to BIT_ULL(0).

**Return**

* 0: Success
* -EALREADY: One of the streams in streams_mask is not enabled
* -EINVAL: The pad index is invalid, or doesn't correspond to a source pad
* -EOPNOTSUPP: Falling back to the legacy .`s_stream()` operation is
  impossible because the subdev has multiple source pads

#### <a id="c-v4l2_subdev_s_stream_helper"></a>`v4l2_subdev_s_stream_helper()`

```c
int v4l2_subdev_s_stream_helper(struct v4l2_subdev *sd, int enable)
```

Helper to implement the subdev s_stream operation using enable_streams and disable_streams

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice
- `int enable`: Enable or disable streaming

**Description**

Subdevice drivers that implement the streams-aware
[`v4l2_subdev_pad_ops.enable_streams`](#c-struct-v4l2_subdev_pad_ops) and [`v4l2_subdev_pad_ops.disable_streams`](#c-struct-v4l2_subdev_pad_ops)
operations can use this helper to implement the legacy
[`v4l2_subdev_video_ops.s_stream`](#c-struct-v4l2_subdev_video_ops) operation.

This helper can only be used by subdevs that have a single source pad.

**Return**

0 on success, or a negative error code otherwise.

#### <a id="c-v4l2_subdev_lock_state"></a>`v4l2_subdev_lock_state()`

```c
void v4l2_subdev_lock_state(struct v4l2_subdev_state *state)
```

Locks the subdev state

**Parameters**

- `struct v4l2_subdev_state *state`: The subdevice state

**Description**

Locks the given subdev state.

The state must be unlocked with [`v4l2_subdev_unlock_state()`](#c-v4l2_subdev_unlock_state) after use.

#### <a id="c-v4l2_subdev_unlock_state"></a>`v4l2_subdev_unlock_state()`

```c
void v4l2_subdev_unlock_state(struct v4l2_subdev_state *state)
```

Unlocks the subdev state

**Parameters**

- `struct v4l2_subdev_state *state`: The subdevice state

**Description**

Unlocks the given subdev state.

#### <a id="c-v4l2_subdev_lock_states"></a>`v4l2_subdev_lock_states()`

```c
void v4l2_subdev_lock_states(struct v4l2_subdev_state *state1, struct v4l2_subdev_state *state2)
```

Lock two sub-device states

**Parameters**

- `struct v4l2_subdev_state *state1`: One subdevice state
- `struct v4l2_subdev_state *state2`: The other subdevice state

**Description**

Locks the state of two sub-devices.

The states must be unlocked with [`v4l2_subdev_unlock_states()`](#c-v4l2_subdev_unlock_states) after use.

This differs from calling [`v4l2_subdev_lock_state()`](#c-v4l2_subdev_lock_state) on both states so that if
the states share the same lock, the lock is acquired only once (so no
deadlock occurs). The caller is responsible for ensuring the locks will
always be acquired in the same order.

#### <a id="c-v4l2_subdev_unlock_states"></a>`v4l2_subdev_unlock_states()`

```c
void v4l2_subdev_unlock_states(struct v4l2_subdev_state *state1, struct v4l2_subdev_state *state2)
```

Unlock two sub-device states

**Parameters**

- `struct v4l2_subdev_state *state1`: One subdevice state
- `struct v4l2_subdev_state *state2`: The other subdevice state

**Description**

Unlocks the state of two sub-devices.

This differs from calling [`v4l2_subdev_unlock_state()`](#c-v4l2_subdev_unlock_state) on both states so that
if the states share the same lock, the lock is released only once.

#### <a id="c-v4l2_subdev_get_unlocked_active_state"></a>`v4l2_subdev_get_unlocked_active_state()`

```c
struct v4l2_subdev_state * v4l2_subdev_get_unlocked_active_state(struct v4l2_subdev *sd)
```

Checks that the active subdev state is unlocked and returns it

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

Returns the active state for the subdevice, or NULL if the subdev does not
support active state. If the state is not NULL, calls
`lockdep_assert_not_held()` to issue a warning if the state is locked.

This function is to be used e.g. when getting the active state for the sole
purpose of passing it forward, without accessing the state fields.

#### <a id="c-v4l2_subdev_get_locked_active_state"></a>`v4l2_subdev_get_locked_active_state()`

```c
struct v4l2_subdev_state * v4l2_subdev_get_locked_active_state(struct v4l2_subdev *sd)
```

Checks that the active subdev state is locked and returns it

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

Returns the active state for the subdevice, or NULL if the subdev does not
support active state. If the state is not NULL, calls `lockdep_assert_held()`
to issue a warning if the state is not locked.

This function is to be used when the caller knows that the active state is
already locked.

#### <a id="c-v4l2_subdev_lock_and_get_active_state"></a>`v4l2_subdev_lock_and_get_active_state()`

```c
struct v4l2_subdev_state * v4l2_subdev_lock_and_get_active_state(struct v4l2_subdev *sd)
```

Locks and returns the active subdev state for the subdevice

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

Returns the locked active state for the subdevice, or NULL if the subdev
does not support active state.

The state must be unlocked with [`v4l2_subdev_unlock_state()`](#c-v4l2_subdev_unlock_state) after use.

#### <a id="c-v4l2_subdev_init"></a>`v4l2_subdev_init()`

```c
void v4l2_subdev_init(struct v4l2_subdev *sd, const struct v4l2_subdev_ops *ops)
```

initializes the sub-device struct

**Parameters**

- `struct v4l2_subdev *sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev) to be initialized
- `const struct v4l2_subdev_ops *ops`: pointer to [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops).

#### <a id="c-v4l2_subdev_call"></a>`v4l2_subdev_call()`

```c
v4l2_subdev_call(sd, o, f, args...)
```

call an operation of a v4l2_subdev.

**Parameters**

- `sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `o`: name of the element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of callbacks functions.
- `f`: callback function to be called.
  The callback functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Example**

err = v4l2_subdev_call(sd, video, s_std, norm);

#### <a id="c-v4l2_subdev_call_state_active"></a>`v4l2_subdev_call_state_active()`

```c
v4l2_subdev_call_state_active(sd, o, f, args...)
```

call an operation of a v4l2_subdev which takes state as a parameter, passing the subdev its active state.

**Parameters**

- `sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `o`: name of the element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of callbacks functions.
- `f`: callback function to be called.
  The callback functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

This is similar to [`v4l2_subdev_call()`](#c-v4l2_subdev_call), except that this version can only be
used for ops that take a subdev state as a parameter. The macro will get the
active state, lock it before calling the op and unlock it after the call.

#### <a id="c-v4l2_subdev_call_state_try"></a>`v4l2_subdev_call_state_try()`

```c
v4l2_subdev_call_state_try(sd, o, f, args...)
```

call an operation of a v4l2_subdev which takes state as a parameter, passing the subdev a newly allocated try state.

**Parameters**

- `sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `o`: name of the element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops) that contains **f**.
  Each element there groups a set of callbacks functions.
- `f`: callback function to be called.
  The callback functions are defined in groups, according to
  each element at [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops).
- `args...`: arguments for **f**.

**Description**

This is similar to [`v4l2_subdev_call_state_active()`](#c-v4l2_subdev_call_state_active), except that as this
version allocates a new state, this is only usable for
V4L2_SUBDEV_FORMAT_TRY use cases.

**Note**

only legacy non-MC drivers may need this macro.

#### <a id="c-v4l2_subdev_has_op"></a>`v4l2_subdev_has_op()`

```c
v4l2_subdev_has_op(sd, o, f)
```

Checks if a subdev defines a certain operation.

**Parameters**

- `sd`: pointer to the [`struct v4l2_subdev`](#c-struct-v4l2_subdev)
- `o`: The group of callback functions in [`struct v4l2_subdev_ops`](#c-struct-v4l2_subdev_ops)
  which **f** is a part of.
- `f`: callback function to be checked for its existence.

#### <a id="c-v4l2_subdev_notify_event"></a>`v4l2_subdev_notify_event()`

```c
void v4l2_subdev_notify_event(struct v4l2_subdev *sd, const struct v4l2_event *ev)
```

Delivers event notification for subdevice

**Parameters**

- `struct v4l2_subdev *sd`: The subdev for which to deliver the event
- `const struct v4l2_event *ev`: The event to deliver

**Description**

Will deliver the specified event to all userspace event listeners which are
subscribed to the v42l subdev event queue as well as to the bridge driver
using the notify callback. The notification type for the notify callback
will be `V4L2_DEVICE_NOTIFY_EVENT`.

#### <a id="c-v4l2_subdev_is_streaming"></a>`v4l2_subdev_is_streaming()`

```c
bool v4l2_subdev_is_streaming(struct v4l2_subdev *sd)
```

Returns if the subdevice is streaming

**Parameters**

- `struct v4l2_subdev *sd`: The subdevice

**Description**

[`v4l2_subdev_is_streaming()`](#c-v4l2_subdev_is_streaming) tells if the subdevice is currently streaming.
"Streaming" here means whether .`s_stream()` or .`enable_streams()` has been
successfully called, and the streaming has not yet been disabled.

If the subdevice implements .`enable_streams()` this function must be called
while holding the active state lock.

---

# Tuner functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Tuner functions and data structures.

<a id="rst-tuner-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-tuner_mode"></a>`enum tuner_mode`

Mode of the tuner

**Constants**

- `T_RADIO`: Tuner core will work in radio mode
- `T_ANALOG_TV`: Tuner core will work in analog TV mode

**Description**

Older boards only had a single tuner device, but some devices have a
separate tuner for radio. In any case, the tuner-core needs to know if
the tuner chip(s) will be used in radio mode or analog TV mode, as, on
radio mode, frequencies are specified on a different range than on TV
mode. This enum is used by the tuner core in order to work with the
proper tuner range and eventually use a different tuner chip while in
radio mode.

#### <a id="c-struct-tuner_setup"></a>`struct tuner_setup`

setup the tuner chipsets

**Definition**

```c
struct tuner_setup {
    unsigned short  addr;
    unsigned int    type;
    unsigned int    mode_mask;
    void *config;
    int (*tuner_callback)(void *dev, int component, int cmd, int arg);
};
```

**Members**

- `addr`: I2C address used to control the tuner device/chipset
- `type`: Type of the tuner, as defined at the TUNER_* macros.
  Each different tuner model should have an unique
  identifier.
- `mode_mask`: Mask with the allowed tuner modes: V4L2_TUNER_RADIO,
  V4L2_TUNER_ANALOG_TV and/or V4L2_TUNER_DIGITAL_TV,
  describing if the tuner should be used to support
  Radio, analog TV and/or digital TV.
- `config`: Used to send tuner-specific configuration for complex
  tuners that require extra parameters to be set.
  Only a very few tuners require it and its usage on
  newer tuners should be avoided.
- `tuner_callback`: Some tuners require to call back the bridge driver,
  in order to do some tasks like rising a GPIO at the
  bridge chipset, in order to do things like resetting
  the device.

**Description**

Older boards only had a single tuner device. Nowadays multiple tuner
devices may be present on a single board. Using TUNER_SET_TYPE_ADDR
to pass the tuner_setup structure it is possible to setup each tuner
device in turn.

Since multiple devices may be present it is no longer sufficient to
send a command to a single i2c device. Instead you should broadcast
the command to all i2c devices.

By setting the mode_mask correctly you can select which commands are
accepted by a specific tuner device. For example, set mode_mask to
T_RADIO if the device is a radio-only tuner. That specific tuner will
only accept commands when the tuner is in radio mode and ignore them
when the tuner is set to TV mode.



#### <a id="c-enum-param_type"></a>`enum param_type`

type of the tuner pameters

**Constants**

- `TUNER_PARAM_TYPE_RADIO`: Tuner params are for FM and/or AM radio
- `TUNER_PARAM_TYPE_PAL`: Tuner params are for PAL color TV standard
- `TUNER_PARAM_TYPE_SECAM`: Tuner params are for SECAM color TV standard
- `TUNER_PARAM_TYPE_NTSC`: Tuner params are for NTSC color TV standard
- `TUNER_PARAM_TYPE_DIGITAL`: Tuner params are for digital TV

#### <a id="c-struct-tuner_range"></a>`struct tuner_range`

define the frequencies supported by the tuner

**Definition**

```c
struct tuner_range {
    unsigned short limit;
    unsigned char config;
    unsigned char cb;
};
```

**Members**

- `limit`: Max frequency supported by that range, in 62.5 kHz
  (TV) or 62.5 Hz (Radio), as defined by
  V4L2_TUNER_CAP_LOW.
- `config`: Value of the band switch byte (BB) to setup this mode.
- `cb`: Value of the CB byte to setup this mode.

**Description**

Please notice that digital tuners like xc3028/xc4000/xc5000 don't use
those ranges, as they're defined inside the driver. This is used by
analog tuners that are compatible with the "Philips way" to setup the
tuners. On those devices, the tuner set is done via 4 bytes:

\#) divider byte1 (DB1)
\#) divider byte 2 (DB2)
\#) Control byte (CB)
\#) band switch byte (BB)

Some tuners also have an additional optional Auxiliary byte (AB).

#### <a id="c-struct-tuner_params"></a>`struct tuner_params`

Parameters to be used to setup the tuner. Those are used by drivers/media/tuners/tuner-types.c in order to specify the tuner properties. Most of the parameters are for tuners based on tda9887 IF-PLL multi-standard analog TV/Radio demodulator, with is very common on legacy analog tuners.

**Definition**

```c
struct tuner_params {
    enum param_type type;
    unsigned int cb_first_if_lower_freq:1;
    unsigned int has_tda9887:1;
    unsigned int port1_fm_high_sensitivity:1;
    unsigned int port2_fm_high_sensitivity:1;
    unsigned int fm_gain_normal:1;
    unsigned int intercarrier_mode:1;
    unsigned int port1_active:1;
    unsigned int port2_active:1;
    unsigned int port1_invert_for_secam_lc:1;
    unsigned int port2_invert_for_secam_lc:1;
    unsigned int port1_set_for_fm_mono:1;
    unsigned int default_pll_gating_18:1;
    unsigned int radio_if:2;
    signed int default_top_low:5;
    signed int default_top_mid:5;
    signed int default_top_high:5;
    signed int default_top_secam_low:5;
    signed int default_top_secam_mid:5;
    signed int default_top_secam_high:5;
    u16 iffreq;
    unsigned int count;
    const struct tuner_range *ranges;
};
```

**Members**

- `type`: Type of the tuner parameters, as defined at
  enum param_type. If the tuner supports multiple
  standards, an array should be used, with one
  row per different standard.
- `cb_first_if_lower_freq`: Many Philips-based tuners have a comment in
  their datasheet like
  "For channel selection involving band
  switching, and to ensure smooth tuning to the
  desired channel without causing unnecessary
  charge pump action, it is recommended to
  consider the difference between wanted channel
  frequency and the current channel frequency.
  Unnecessary charge pump action will result
  in very low tuning voltage which may drive the
  oscillator to extreme conditions".
  Set cb_first_if_lower_freq to 1, if this check
  is required for this tuner. I tested this for
  PAL by first setting the TV frequency to
  203 MHz and then switching to 96.6 MHz FM
  radio. The result was static unless the
  control byte was sent first.
- `has_tda9887`: Set to 1 if this tuner uses a tda9887
- `port1_fm_high_sensitivity`: Many Philips tuners use tda9887 PORT1 to select
  the FM radio sensitivity. If this setting is 1,
  then set PORT1 to 1 to get proper FM reception.
- `port2_fm_high_sensitivity`: Some Philips tuners use tda9887 PORT2 to select
  the FM radio sensitivity. If this setting is 1,
  then set PORT2 to 1 to get proper FM reception.
- `fm_gain_normal`: Some Philips tuners use tda9887 cGainNormal to
  select the FM radio sensitivity. If this
  setting is 1, e register will use cGainNormal
  instead of cGainLow.
- `intercarrier_mode`: Most tuners with a tda9887 use QSS mode.
  Some (cheaper) tuners use Intercarrier mode.
  If this setting is 1, then the tuner needs to
  be set to intercarrier mode.
- `port1_active`: This setting sets the default value for PORT1.
  0 means inactive, 1 means active. Note: the
  actual bit value written to the tda9887 is
  inverted. So a 0 here means a 1 in the B6 bit.
- `port2_active`: This setting sets the default value for PORT2.
  0 means inactive, 1 means active. Note: the
  actual bit value written to the tda9887 is
  inverted. So a 0 here means a 1 in the B7 bit.
- `port1_invert_for_secam_lc`: Sometimes PORT1 is inverted when the SECAM-L'
  standard is selected. Set this bit to 1 if this
  is needed.
- `port2_invert_for_secam_lc`: Sometimes PORT2 is inverted when the SECAM-L'
  standard is selected. Set this bit to 1 if this
  is needed.
- `port1_set_for_fm_mono`: Some cards require PORT1 to be 1 for mono Radio
  FM and 0 for stereo.
- `default_pll_gating_18`: Select 18% (or according to datasheet 0%)
  L standard PLL gating, vs the driver default
  of 36%.
- `radio_if`: IF to use in radio mode.  Tuners with a
  separate radio IF filter seem to use 10.7,
  while those without use 33.3 for PAL/SECAM
  tuners and 41.3 for NTSC tuners.
  0 = 10.7, 1 = 33.3, 2 = 41.3
- `default_top_low`: Default tda9887 TOP value in dB for the low
  band. Default is 0. Range: -16:+15
- `default_top_mid`: Default tda9887 TOP value in dB for the mid
  band. Default is 0. Range: -16:+15
- `default_top_high`: Default tda9887 TOP value in dB for the high
  band. Default is 0. Range: -16:+15
- `default_top_secam_low`: Default tda9887 TOP value in dB for SECAM-L/L'
  for the low band. Default is 0. Several tuners
  require a different TOP value for the
  SECAM-L/L' standards. Range: -16:+15
- `default_top_secam_mid`: Default tda9887 TOP value in dB for SECAM-L/L'
  for the mid band. Default is 0. Several tuners
  require a different TOP value for the
  SECAM-L/L' standards. Range: -16:+15
- `default_top_secam_high`: Default tda9887 TOP value in dB for SECAM-L/L'
  for the high band. Default is 0. Several tuners
  require a different TOP value for the
  SECAM-L/L' standards. Range: -16:+15
- `iffreq`: Intermediate frequency (IF) used by the tuner
  on digital mode.
- `count`: Size of the ranges array.
- `ranges`: Array with the frequency ranges supported by
  the tuner.

#### <a id="c-struct-tunertype"></a>`struct tunertype`

describes the known tuners.

**Definition**

```c
struct tunertype {
    char *name;
    unsigned int count;
    const struct tuner_params *params;
    u16 min;
    u16 max;
    u32 stepsize;
    u8 *initdata;
    u8 *sleepdata;
};
```

**Members**

- `name`: string with the tuner's name.
- `count`: size of [`struct tuner_params`](#c-struct-tuner_params) array.
- `params`: pointer to [`struct tuner_params`](#c-struct-tuner_params) array.
- `min`: minimal tuner frequency, in 62.5 kHz step.
  should be multiplied to 16 to convert to MHz.
- `max`: minimal tuner frequency, in 62.5 kHz step.
  Should be multiplied to 16 to convert to MHz.
- `stepsize`: frequency step, in Hz.
- `initdata`: optional byte sequence to initialize the tuner.
- `sleepdata`: optional byte sequence to power down the tuner.

---

# Hauppauge TV EEPROM functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for Hauppauge TV EEPROM functions and data structures.

<a id="rst-hauppauge-tv-eeprom-functions-and-data-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-tveeprom_audio_processor"></a>`enum tveeprom_audio_processor`

Specifies the type of audio processor used on a Hauppauge device.

**Constants**

- `TVEEPROM_AUDPROC_NONE`: No audio processor present
- `TVEEPROM_AUDPROC_INTERNAL`: The audio processor is internal to the
  video processor
- `TVEEPROM_AUDPROC_MSP`: The audio processor is a MSPXXXX device
- `TVEEPROM_AUDPROC_OTHER`: The audio processor is another device

#### <a id="c-struct-tveeprom"></a>`struct tveeprom`

Contains the fields parsed from Hauppauge eeproms

**Definition**

```c
struct tveeprom {
    u32 has_radio;
    u32 has_ir;
    u32 has_MAC_address;
    u32 tuner_type;
    u32 tuner_formats;
    u32 tuner_hauppauge_model;
    u32 tuner2_type;
    u32 tuner2_formats;
    u32 tuner2_hauppauge_model;
    u32 audio_processor;
    u32 decoder_processor;
    u32 model;
    u32 revision;
    u32 serial_number;
    char rev_str[5];
    u8 MAC_address[ETH_ALEN];
};
```

**Members**

- `has_radio`: 1 if the device has radio; 0 otherwise.
- `has_ir`: If has_ir == 0, then it is unknown what the IR
  capabilities are. Otherwise:
  bit 0) 1 (= IR capabilities are known);
  bit 1) IR receiver present;
  bit 2) IR transmitter (blaster) present.
- `has_MAC_address`: 0: no MAC, 1: MAC present, 2: unknown.
- `tuner_type`: type of the tuner (TUNER_*, as defined at
  include/media/tuner.h).
- `tuner_formats`: Supported analog TV standards (V4L2_STD_*).
- `tuner_hauppauge_model`: Hauppauge's code for the device model number.
- `tuner2_type`: type of the second tuner (TUNER_*, as defined
  at include/media/tuner.h).
- `tuner2_formats`: Tuner 2 supported analog TV standards
  (V4L2_STD_*).
- `tuner2_hauppauge_model`: tuner 2 Hauppauge's code for the device model
  number.
- `audio_processor`: analog audio decoder, as defined by enum
  tveeprom_audio_processor.
- `decoder_processor`: Hauppauge's code for the decoder chipset.
  Unused by the drivers, as they probe the
  decoder based on the PCI or USB ID.
- `model`: Hauppauge's model number
- `revision`: Card revision number
- `serial_number`: Card's serial number
- `rev_str`: Card revision converted to number
- `MAC_address`: MAC address for the network interface

#### <a id="c-tveeprom_hauppauge_analog"></a>`tveeprom_hauppauge_analog()`

```c
void tveeprom_hauppauge_analog(struct tveeprom *tvee, unsigned char *eeprom_data)
```

Fill struct tveeprom using the contents of the eeprom previously filled at **eeprom_data** field.

**Parameters**

- `struct tveeprom *tvee`: Struct to where the eeprom parsed data will be filled;
- `unsigned char *eeprom_data`: Array with the contents of the eeprom_data. It should
  contain 256 bytes filled with the contents of the
  eeprom read from the Hauppauge device.

#### <a id="c-tveeprom_read"></a>`tveeprom_read()`

```c
int tveeprom_read(struct i2c_client *c, unsigned char *eedata, int len)
```

Reads the contents of the eeprom found at the Hauppauge devices.

**Parameters**

- `struct i2c_client *c`: I2C client struct
- `unsigned char *eedata`: Array where the eeprom content will be stored.
- `int len`: Size of **eedata** array. If the eeprom content will be latter
  be parsed by [`tveeprom_hauppauge_analog()`](#c-tveeprom_hauppauge_analog), len should be, at
  least, 256.

---

# V4L2 videobuf2 functions and data structures

_Peios Kernel / Hardware and drivers / Driver development / Media devices_

> Reference for V4L2 videobuf2 functions and data structures.

<a id="rst-v4l2-videobuf2-functions-and-data-structures"></a>
<a id="rst-vb2-framework"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-vb2_memory"></a>`enum vb2_memory`

type of memory model used to make the buffers visible on userspace.

**Constants**

- `VB2_MEMORY_UNKNOWN`: Buffer status is unknown or it is not used yet on
  userspace.
- `VB2_MEMORY_MMAP`: The buffers are allocated by the Kernel and it is
  memory mapped via `mmap()` ioctl. This model is
  also used when the user is using the buffers via
  `read()` or `write()` system calls.
- `VB2_MEMORY_USERPTR`: The buffers was allocated in userspace and it is
  memory mapped via `mmap()` ioctl.
- `VB2_MEMORY_DMABUF`: The buffers are passed to userspace via DMA buffer.

#### <a id="c-struct-vb2_mem_ops"></a>`struct vb2_mem_ops`

memory handling/memory allocator operations.

**Definition**

```c
struct vb2_mem_ops {
    void *(*alloc)(struct vb2_buffer *vb, struct device *dev, unsigned long size);
    void (*put)(void *buf_priv);
    struct dma_buf *(*get_dmabuf)(struct vb2_buffer *vb, void *buf_priv, unsigned long flags);
    void *(*get_userptr)(struct vb2_buffer *vb, struct device *dev, unsigned long vaddr, unsigned long size);
    void (*put_userptr)(void *buf_priv);
    void (*prepare)(void *buf_priv);
    void (*finish)(void *buf_priv);
    void *(*attach_dmabuf)(struct vb2_buffer *vb, struct device *dev, struct dma_buf *dbuf, unsigned long size);
    void (*detach_dmabuf)(void *buf_priv);
    int (*map_dmabuf)(void *buf_priv);
    void (*unmap_dmabuf)(void *buf_priv);
    void *(*vaddr)(struct vb2_buffer *vb, void *buf_priv);
    void *(*cookie)(struct vb2_buffer *vb, void *buf_priv);
    unsigned int    (*num_users)(void *buf_priv);
    int (*mmap)(void *buf_priv, struct vm_area_struct *vma);
};
```

**Members**

- `alloc`: allocate video memory and, optionally, allocator private data,
  return [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure or a pointer to allocator private,
  per-buffer data on success; the returned private structure
  will then be passed as **buf_priv** argument to other ops in this
  structure. The size argument to this function shall be
  *page aligned*.
- `put`: inform the allocator that the buffer will no longer be used;
  usually will result in the allocator freeing the buffer (if
  no other users of this buffer are present); the **buf_priv**
  argument is the allocator private per-buffer structure
  previously returned from the alloc callback.
- `get_dmabuf`: acquire userspace memory for a hardware operation; used for
  DMABUF memory types.
- `get_userptr`: acquire userspace memory for a hardware operation; used for
  USERPTR memory types; vaddr is the address passed to the
  videobuf2 layer when queuing a video buffer of USERPTR type;
  should return an allocator private per-buffer structure
  associated with the buffer on success, [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure;
  the returned private structure will then be passed as **buf_priv**
  argument to other ops in this structure.
- `put_userptr`: inform the allocator that a USERPTR buffer will no longer
  be used.
- `prepare`: called every time the buffer is passed from userspace to the
  driver, useful for cache synchronisation, optional.
- `finish`: called every time the buffer is passed back from the driver
  to the userspace, also optional.
- `attach_dmabuf`: attach a shared [`struct dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf) for a hardware operation;
  used for DMABUF memory types; dev is the alloc device
  dbuf is the shared dma_buf; returns [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure;
  allocator private per-buffer structure on success;
  this needs to be used for further accesses to the buffer.
- `detach_dmabuf`: inform the exporter of the buffer that the current DMABUF
  buffer is no longer used; the **buf_priv** argument is the
  allocator private per-buffer structure previously returned
  from the attach_dmabuf callback.
- `map_dmabuf`: request for access to the dmabuf from allocator; the allocator
  of dmabuf is informed that this driver is going to use the
  dmabuf.
- `unmap_dmabuf`: releases access control to the dmabuf - allocator is notified
  that this driver is done using the dmabuf for now.
- `vaddr`: return a kernel virtual address to a given memory buffer
  associated with the passed private structure or NULL if no
  such mapping exists.
- `cookie`: return allocator specific cookie for a given memory buffer
  associated with the passed private structure or NULL if not
  available.
- `num_users`: return the current number of users of a memory buffer;
  return 1 if the videobuf2 layer (or actually the driver using
  it) is the only user.
- `mmap`: setup a userspace mapping for a given memory buffer under
  the provided virtual memory region.

**Description**

Those operations are used by the videobuf2 core to implement the memory
handling/memory allocators for each type of supported streaming I/O method.

> [!NOTE]
> \#) Required ops for USERPTR types: get_userptr, put_userptr.
>
> \#) Required ops for MMAP types: alloc, put, num_users, mmap.
>
> \#) Required ops for read/write access types: alloc, put, num_users, vaddr.
>
> - #) Required ops for DMABUF types: attach_dmabuf, detach_dmabuf,
>
>   map_dmabuf, unmap_dmabuf.

#### <a id="c-struct-vb2_plane"></a>`struct vb2_plane`

plane information.

**Definition**

```c
struct vb2_plane {
    void *mem_priv;
    struct dma_buf          *dbuf;
    unsigned int            dbuf_mapped;
    bool dbuf_duplicated;
    unsigned int            bytesused;
    unsigned int            length;
    unsigned int            min_length;
    union {
        unsigned int    offset;
        unsigned long   userptr;
        int fd;
    } m;
    unsigned int            data_offset;
};
```

**Members**

- `mem_priv`: private data with this plane.
- `dbuf`: dma_buf - shared buffer object.
- `dbuf_mapped`: flag to show whether dbuf is mapped or not
- `dbuf_duplicated`: boolean to show whether dbuf is duplicated with a
  previous plane of the buffer.
- `bytesused`: number of bytes occupied by data in the plane (payload).
- `length`: size of this plane (NOT the payload) in bytes. The maximum
  valid size is MAX_UINT - PAGE_SIZE.
- `min_length`: minimum required size of this plane (NOT the payload) in bytes.
  **length** is always greater or equal to **min_length**, and like
  **length**, it is limited to MAX_UINT - PAGE_SIZE.
- `m`: Union with memtype-specific data.
- `m.offset`: when memory in the associated struct vb2_buffer is
  `VB2_MEMORY_MMAP`, equals the offset from the start of
  the device memory for this plane (or is a "cookie" that
  should be passed to `mmap()` called on the video node).
- `m.userptr`: when memory is `VB2_MEMORY_USERPTR`, a userspace pointer
  pointing to this plane.
- `m.fd`: when memory is `VB2_MEMORY_DMABUF`, a userspace file
  descriptor associated with this plane.
- `data_offset`: offset in the plane to the start of data; usually 0,
  unless there is a header in front of the data.

**Description**

Should contain enough information to be able to cover all the fields
of [`struct v4l2_plane`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_plane) at videodev2.h.

#### <a id="c-enum-vb2_io_modes"></a>`enum vb2_io_modes`

queue access methods.

**Constants**

- `VB2_MMAP`: driver supports MMAP with streaming API.
- `VB2_USERPTR`: driver supports USERPTR with streaming API.
- `VB2_READ`: driver supports `read()` style access.
- `VB2_WRITE`: driver supports `write()` style access.
- `VB2_DMABUF`: driver supports DMABUF with streaming API.

#### <a id="c-enum-vb2_buffer_state"></a>`enum vb2_buffer_state`

current video buffer state.

**Constants**

- `VB2_BUF_STATE_DEQUEUED`: buffer under userspace control.
- `VB2_BUF_STATE_IN_REQUEST`: buffer is queued in media request.
- `VB2_BUF_STATE_PREPARING`: buffer is being prepared in videobuf2.
- `VB2_BUF_STATE_QUEUED`: buffer queued in videobuf2, but not in driver.
- `VB2_BUF_STATE_ACTIVE`: buffer queued in driver and possibly used
  in a hardware operation.
- `VB2_BUF_STATE_DONE`: buffer returned from driver to videobuf2, but
  not yet dequeued to userspace.
- `VB2_BUF_STATE_ERROR`: same as above, but the operation on the buffer
  has ended with an error, which will be reported
  to the userspace when it is dequeued.

#### <a id="c-struct-vb2_buffer"></a>`struct vb2_buffer`

represents a video buffer.

**Definition**

```c
struct vb2_buffer {
    struct vb2_queue        *vb2_queue;
    unsigned int            index;
    unsigned int            type;
    unsigned int            memory;
    unsigned int            num_planes;
    u64 timestamp;
    struct media_request    *request;
    struct media_request_object     req_obj;
};
```

**Members**

- `vb2_queue`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with the queue to
  which this driver belongs.
- `index`: id number of the buffer.
- `type`: buffer type.
- `memory`: the method, in which the actual data is passed.
- `num_planes`: number of planes in the buffer
  on an internal driver queue.
- `timestamp`: frame timestamp in ns.
- `request`: the request this buffer is associated with.
- `req_obj`: used to bind this buffer to a request. This
  request object has a refcount.

#### <a id="c-struct-vb2_ops"></a>`struct vb2_ops`

driver-specific callbacks.

**Definition**

```c
struct vb2_ops {
    int (*queue_setup)(struct vb2_queue *q, unsigned int *num_buffers, unsigned int *num_planes, unsigned int sizes[], struct device *alloc_devs[]);
    int (*buf_out_validate)(struct vb2_buffer *vb);
    int (*buf_init)(struct vb2_buffer *vb);
    int (*buf_prepare)(struct vb2_buffer *vb);
    void (*buf_finish)(struct vb2_buffer *vb);
    void (*buf_cleanup)(struct vb2_buffer *vb);
    int (*prepare_streaming)(struct vb2_queue *q);
    int (*start_streaming)(struct vb2_queue *q, unsigned int count);
    void (*stop_streaming)(struct vb2_queue *q);
    void (*unprepare_streaming)(struct vb2_queue *q);
    void (*buf_queue)(struct vb2_buffer *vb);
    void (*buf_request_complete)(struct vb2_buffer *vb);
};
```

**Members**

- `queue_setup`: called from `VIDIOC_REQBUFS()` and `VIDIOC_CREATE_BUFS()`
  handlers before memory allocation. It can be called
  twice: if the original number of requested buffers
  could not be allocated, then it will be called a
  second time with the actually allocated number of
  buffers to verify if that is OK.
  The driver should return the required number of buffers
  in \*num_buffers, the required number of planes per
  buffer in \*num_planes, the size of each plane should be
  set in the sizes\\[\\] array and optional per-plane
  allocator specific device in the alloc_devs\\[\\] array.
  When called from `VIDIOC_REQBUFS()`, \*num_planes == 0,
  the driver has to use the currently configured format to
  determine the plane sizes and \*num_buffers is the total
  number of buffers that are being allocated. When called
  from `VIDIOC_CREATE_BUFS()`, \*num_planes != 0 and it
  describes the requested number of planes and sizes\\[\\]
  contains the requested plane sizes. In this case
  \*num_buffers are being allocated additionally to
  the buffers already allocated. If either \*num_planes
  or the requested sizes are invalid callback must return `-EINVAL`.
- `buf_out_validate`: called when the output buffer is prepared or queued
  to a request; drivers can use this to validate
  userspace-provided information; this is required only
  for OUTPUT queues.
- `buf_init`: called once after allocating a buffer (in MMAP case)
  or after acquiring a new USERPTR buffer; drivers may
  perform additional buffer-related initialization;
  initialization failure (return != 0) will prevent
  queue setup from completing successfully; optional.
- `buf_prepare`: called every time the buffer is queued from userspace
  and from the `VIDIOC_PREPARE_BUF()` ioctl; drivers may
  perform any initialization required before each
  hardware operation in this callback; drivers can
  access/modify the buffer here as it is still synced for
  the CPU; drivers that support `VIDIOC_CREATE_BUFS()` must
  also validate the buffer size; if an error is returned,
  the buffer will not be queued in driver; optional.
- `buf_finish`: called before every dequeue of the buffer back to
  userspace; the buffer is synced for the CPU, so drivers
  can access/modify the buffer contents; drivers may
  perform any operations required before userspace
  accesses the buffer; optional. The buffer state can be
  one of the following: `DONE` and `ERROR` occur while
  streaming is in progress, and the `PREPARED` state occurs
  when the queue has been canceled and all pending
  buffers are being returned to their default `DEQUEUED`
  state. Typically you only have to do something if the
  state is `VB2_BUF_STATE_DONE`, since in all other cases
  the buffer contents will be ignored anyway.
- `buf_cleanup`: called once before the buffer is freed; drivers may
  perform any additional cleanup; optional.
- `prepare_streaming`: called once to prepare for 'streaming' state; this is
  where validation can be done to verify everything is
  okay and streaming resources can be claimed. It is
  called when the VIDIOC_STREAMON ioctl is called. The
  actual streaming starts when **start_streaming** is called.
  Optional.
- `start_streaming`: called once to enter 'streaming' state; the driver may
  receive buffers with **buf_queue** callback
  before **start_streaming** is called; the driver gets the
  number of already queued buffers in count parameter;
  driver can return an error if hardware fails, in that
  case all buffers that have been already given by
  the **buf_queue** callback are to be returned by the driver
  by calling [`vb2_buffer_done()`](#c-vb2_buffer_done) with `VB2_BUF_STATE_QUEUED`.
  If you need a minimum number of buffers before you can
  start streaming, then set
  [`vb2_queue->min_queued_buffers`](#c-struct-vb2_queue). If that is non-zero
  then **start_streaming** won't be called until at least
  that many buffers have been queued up by userspace.
- `stop_streaming`: called when 'streaming' state must be disabled; driver
  should stop any DMA transactions or wait until they
  finish and give back all buffers it got from `buf_queue`
  callback by calling [`vb2_buffer_done()`](#c-vb2_buffer_done) with either
  `VB2_BUF_STATE_DONE` or `VB2_BUF_STATE_ERROR`; may use
  [`vb2_wait_for_all_buffers()`](#c-vb2_wait_for_all_buffers) function
- `unprepare_streaming`: called as counterpart to **prepare_streaming**; any claimed
  streaming resources can be released here. It is
  called when the VIDIOC_STREAMOFF ioctls is called or
  when the streaming filehandle is closed. Optional.
- `buf_queue`: passes buffer vb to the driver; driver may start
  hardware operation on this buffer; driver should give
  the buffer back by calling [`vb2_buffer_done()`](#c-vb2_buffer_done) function;
  it is always called after calling `VIDIOC_STREAMON()`
  ioctl; might be called before **start_streaming** callback
  if user pre-queued buffers before calling
  `VIDIOC_STREAMON()`.
- `buf_request_complete`: a buffer that was never queued to the driver but is
  associated with a queued request was canceled.
  The driver will have to mark associated objects in the
  request as completed; required if requests are
  supported.

**Description**

These operations are not called from interrupt context except where
mentioned specifically.

#### <a id="c-struct-vb2_buf_ops"></a>`struct vb2_buf_ops`

driver-specific callbacks.

**Definition**

```c
struct vb2_buf_ops {
    int (*verify_planes_array)(struct vb2_buffer *vb, const void *pb);
    void (*init_buffer)(struct vb2_buffer *vb);
    void (*fill_user_buffer)(struct vb2_buffer *vb, void *pb);
    int (*fill_vb2_buffer)(struct vb2_buffer *vb, struct vb2_plane *planes);
    void (*copy_timestamp)(struct vb2_buffer *vb, const void *pb);
};
```

**Members**

- `verify_planes_array`: Verify that a given user space structure contains
  enough planes for the buffer. This is called
  for each dequeued buffer.
- `init_buffer`: given a [`vb2_buffer`](#c-struct-vb2_buffer) initialize the extra data after
  struct vb2_buffer.
  For V4L2 this is a [`struct vb2_v4l2_buffer`](#c-struct-vb2_v4l2_buffer).
- `fill_user_buffer`: given a [`vb2_buffer`](#c-struct-vb2_buffer) fill in the userspace structure.
  For V4L2 this is a [`struct v4l2_buffer`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buffer).
- `fill_vb2_buffer`: given a userspace structure, fill in the [`vb2_buffer`](#c-struct-vb2_buffer).
  If the userspace structure is invalid, then this op
  will return an error.
- `copy_timestamp`: copy the timestamp from a userspace structure to
  the [`struct vb2_buffer`](#c-struct-vb2_buffer).

#### <a id="c-struct-vb2_queue"></a>`struct vb2_queue`

a videobuf2 queue.

**Definition**

```c
struct vb2_queue {
    unsigned int                    type;
    unsigned int                    io_modes;
    struct device                   *dev;
    unsigned long                   dma_attrs;
    unsigned int                    bidirectional:1;
    unsigned int                    fileio_read_once:1;
    unsigned int                    fileio_write_immediately:1;
    unsigned int                    allow_zero_bytesused:1;
    unsigned int               quirk_poll_must_check_waiting_for_buffers:1;
    unsigned int                    supports_requests:1;
    unsigned int                    requires_requests:1;
    unsigned int                    uses_qbuf:1;
    unsigned int                    uses_requests:1;
    unsigned int                    allow_cache_hints:1;
    unsigned int                    non_coherent_mem:1;
    struct mutex                    *lock;
    void *owner;
    const struct vb2_ops            *ops;
    const struct vb2_mem_ops        *mem_ops;
    const struct vb2_buf_ops        *buf_ops;
    void *drv_priv;
    u32 subsystem_flags;
    unsigned int                    buf_struct_size;
    u32 timestamp_flags;
    gfp_t gfp_flags;
    u32 min_queued_buffers;
    u32 min_reqbufs_allocation;
    struct device                   *alloc_devs[VB2_MAX_PLANES];
};
```

**Members**

- `type`: private buffer type whose content is defined by the vb2-core
  caller. For example, for V4L2, it should match
  the types defined on [`enum v4l2_buf_type`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buf_type).
- `io_modes`: supported io methods (see [`enum vb2_io_modes`](#c-enum-vb2_io_modes)).
- `dev`: device to use for the default allocation context if the driver
  doesn't fill in the **alloc_devs** array.
- `dma_attrs`: DMA attributes to use for the DMA.
- `bidirectional`: when this flag is set the DMA direction for the buffers of
  this queue will be overridden with `DMA_BIDIRECTIONAL` direction.
  This is useful in cases where the hardware (firmware) writes to
  a buffer which is mapped as read (`DMA_TO_DEVICE`), or reads from
  buffer which is mapped for write (`DMA_FROM_DEVICE`) in order
  to satisfy some internal hardware restrictions or adds a padding
  needed by the processing algorithm. In case the DMA mapping is
  not bidirectional but the hardware (firmware) trying to access
  the buffer (in the opposite direction) this could lead to an
  IOMMU protection faults.
- `fileio_read_once`: report EOF after reading the first buffer
- `fileio_write_immediately`: queue buffer after each `write()` call
- `allow_zero_bytesused`: allow bytesused == 0 to be passed to the driver
- `quirk_poll_must_check_waiting_for_buffers`: Return `EPOLLERR` at poll when QBUF
  has not been called. This is a vb1 idiom that has been adopted
  also by vb2.
- `supports_requests`: this queue supports the Request API.
- `requires_requests`: this queue requires the Request API. If this is set to 1,
  then supports_requests must be set to 1 as well.
- `uses_qbuf`: qbuf was used directly for this queue. Set to 1 the first
  time this is called. Set to 0 when the queue is canceled.
  If this is 1, then you cannot queue buffers from a request.
- `uses_requests`: requests are used for this queue. Set to 1 the first time
  a request is queued. Set to 0 when the queue is canceled.
  If this is 1, then you cannot queue buffers directly.
- `allow_cache_hints`: when set user-space can pass cache management hints in
  order to skip cache flush/invalidation on ->`prepare()` or/and
  ->`finish()`.
- `non_coherent_mem`: when set queue will attempt to allocate buffers using
  non-coherent memory.
- `lock`: pointer to a mutex that protects the [`struct vb2_queue`](#c-struct-vb2_queue). The
  driver must set this to a mutex to let the v4l2 core serialize
  the queuing ioctls. This lock is used when waiting for a new
  buffer to arrive: the lock is released, we wait for the new
  buffer, and then retaken.
- `owner`: The filehandle that 'owns' the buffers, i.e. the filehandle
  that called reqbufs, create_buffers or started fileio.
  This field is not used by the videobuf2 core API, but it allows
  drivers to easily associate an owner filehandle with the queue.
- `ops`: driver-specific callbacks
- `mem_ops`: memory allocator specific callbacks
- `buf_ops`: callbacks to deliver buffer information.
  between user-space and kernel-space.
- `drv_priv`: driver private data.
- `subsystem_flags`: Flags specific to the subsystem (V4L2/DVB/etc.). Not used
  by the vb2 core.
- `buf_struct_size`: size of the driver-specific buffer structure;
  "0" indicates the driver doesn't want to use a custom buffer
  structure type. In that case a subsystem-specific struct
  will be used (in the case of V4L2 that is
  `sizeof(struct vb2_v4l2_buffer)`). The first field of the
  driver-specific buffer structure must be the subsystem-specific
  struct (vb2_v4l2_buffer in the case of V4L2).
- `timestamp_flags`: Timestamp flags; `V4L2_BUF_FLAG_TIMESTAMP_*` and
  `V4L2_BUF_FLAG_TSTAMP_SRC_*`
- `gfp_flags`: additional gfp flags used when allocating the buffers.
  Typically this is 0, but it may be e.g. `GFP_DMA` or `__GFP_DMA32`
  to force the buffer allocation to a specific memory zone.
- `min_queued_buffers`: the minimum number of queued buffers needed before
  **start_streaming** can be called. Used when a DMA engine
  cannot be started unless at least this number of buffers
  have been queued into the driver.
  VIDIOC_REQBUFS will ensure at least **min_queued_buffers** + 1
  buffers will be allocated. Note that VIDIOC_CREATE_BUFS will not
  modify the requested buffer count.
- `min_reqbufs_allocation`: the minimum number of buffers to be allocated when
  calling VIDIOC_REQBUFS. Note that VIDIOC_CREATE_BUFS will *not*
  modify the requested buffer count and does not use this field.
  Drivers can set this if there has to be a certain number of
  buffers available for the hardware to work effectively.
  This allows calling VIDIOC_REQBUFS with a buffer count of 1 and
  it will be automatically adjusted to a workable buffer count.
  If set, then **min_reqbufs_allocation** must be larger than
  **min_queued_buffers** + 1.
  If this field is > 3, then it is highly recommended that the
  driver implements the V4L2_CID_MIN_BUFFERS_FOR_CAPTURE/OUTPUT
  control.
- `alloc_devs`: [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) memory type/allocator-specific per-plane device

#### <a id="c-vb2_queue_allows_cache_hints"></a>`vb2_queue_allows_cache_hints()`

```c
bool vb2_queue_allows_cache_hints(struct vb2_queue *q)
```

Return true if the queue allows cache and memory consistency hints.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue

#### <a id="c-vb2_plane_vaddr"></a>`vb2_plane_vaddr()`

```c
void * vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int plane_no)
```

Return a kernel virtual address of a given plane.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which the address is to be returned.

**Description**

This function returns a kernel virtual address of a given plane if
such a mapping exist, NULL otherwise.

#### <a id="c-vb2_plane_cookie"></a>`vb2_plane_cookie()`

```c
void * vb2_plane_cookie(struct vb2_buffer *vb, unsigned int plane_no)
```

Return allocator specific cookie for the given plane.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which the cookie is to be returned.

**Description**

This function returns an allocator specific cookie for a given plane if
available, NULL otherwise. The allocator should provide some simple static
inline function, which would convert this cookie to the allocator specific
type that can be used directly by the driver to access the buffer. This can
be for example physical address, pointer to scatter list or IOMMU mapping.

#### <a id="c-vb2_buffer_done"></a>`vb2_buffer_done()`

```c
void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
```

inform videobuf2 that an operation on a buffer is finished.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to be used.
- `enum vb2_buffer_state state`: state of the buffer, as defined by [`enum vb2_buffer_state`](#c-enum-vb2_buffer_state).
  Either `VB2_BUF_STATE_DONE` if the operation finished
  successfully, `VB2_BUF_STATE_ERROR` if the operation finished
  with an error or `VB2_BUF_STATE_QUEUED`.

**Description**

This function should be called by the driver after a hardware operation on
a buffer is finished and the buffer may be returned to userspace. The driver
cannot use this buffer anymore until it is queued back to it by videobuf
by the means of [`vb2_ops->buf_queue`](#c-struct-vb2_ops) callback. Only buffers previously queued
to the driver by [`vb2_ops->buf_queue`](#c-struct-vb2_ops) can be passed to this function.

While streaming a buffer can only be returned in state DONE or ERROR.
The [`vb2_ops->start_streaming`](#c-struct-vb2_ops) op can also return them in case the DMA engine
cannot be started for some reason. In that case the buffers should be
returned with state QUEUED to put them back into the queue.

#### <a id="c-vb2_discard_done"></a>`vb2_discard_done()`

```c
void vb2_discard_done(struct vb2_queue *q)
```

discard all buffers marked as DONE.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function is intended to be used with suspend/resume operations. It
discards all 'done' buffers as they would be too old to be requested after
resume.

Drivers must stop the hardware and synchronize with interrupt handlers and/or
delayed works before calling this function to make sure no buffer will be
touched by the driver and/or hardware.

#### <a id="c-vb2_wait_for_all_buffers"></a>`vb2_wait_for_all_buffers()`

```c
int vb2_wait_for_all_buffers(struct vb2_queue *q)
```

wait until all buffers are given back to vb2.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function will wait until all buffers that have been given to the driver
by [`vb2_ops->buf_queue`](#c-struct-vb2_ops) are given back to vb2 with [`vb2_buffer_done()`](#c-vb2_buffer_done).
It is intended to be called with all locks taken, for example from
[`vb2_ops->stop_streaming`](#c-struct-vb2_ops) callback.

#### <a id="c-vb2_core_querybuf"></a>`vb2_core_querybuf()`

```c
void vb2_core_querybuf(struct vb2_queue *q, struct vb2_buffer *vb, void *pb)
```

query video buffer information.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `void *pb`: buffer struct passed from userspace.

**Description**

Videobuf2 core helper to implement `VIDIOC_QUERYBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

The passed buffer should have been verified.

This function fills the relevant information for the userspace.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_reqbufs"></a>`vb2_core_reqbufs()`

```c
int vb2_core_reqbufs(struct vb2_queue *q, enum vb2_memory memory, unsigned int flags, unsigned int *count)
```

Initiate streaming.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum vb2_memory memory`: memory type, as defined by [`enum vb2_memory`](#c-enum-vb2_memory).
- `unsigned int flags`: auxiliary queue/buffer management flags. Currently, the only
  used flag is `V4L2_MEMORY_FLAG_NON_COHERENT`.
- `unsigned int *count`: requested buffer count.

**Description**

Videobuf2 core helper to implement `VIDIOC_REQBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

This function:

\#) verifies streaming parameters passed from the userspace;
\#) sets up the queue;
\#) negotiates number of buffers and planes per buffer with the driver
to be used during streaming;
\#) allocates internal buffer structures ([`struct vb2_buffer`](#c-struct-vb2_buffer)), according to
the agreed parameters;
\#) for MMAP memory type, allocates actual video memory, using the
memory handling/allocation routines provided during queue initialization.

If req->count is 0, all the memory will be freed instead.

If the queue has been allocated previously by a previous [`vb2_core_reqbufs()`](#c-vb2_core_reqbufs)
call and the queue is not busy, memory will be reallocated.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_create_bufs"></a>`vb2_core_create_bufs()`

```c
int vb2_core_create_bufs(struct vb2_queue *q, enum vb2_memory memory, unsigned int flags, unsigned int *count, unsigned int requested_planes, const unsigned int requested_sizes[], unsigned int *first_index)
```

Allocate buffers and any required auxiliary structs

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum vb2_memory memory`: memory type, as defined by [`enum vb2_memory`](#c-enum-vb2_memory).
- `unsigned int flags`: auxiliary queue/buffer management flags.
- `unsigned int *count`: requested buffer count.
- `unsigned int requested_planes`: number of planes requested.
- `const unsigned int requested_sizes[]`: array with the size of the planes.
- `unsigned int *first_index`: index of the first created buffer, all allocated buffers have
  indices in the range \[first_index..first_index+count-1\]

**Description**

Videobuf2 core helper to implement `VIDIOC_CREATE_BUFS()` operation. It is
called internally by VB2 by an API-specific handler, like
`videobuf2-v4l2.h`.

This function:

\#) verifies parameter sanity;
\#) calls the [`vb2_ops->queue_setup`](#c-struct-vb2_ops) queue operation;
\#) performs any necessary memory allocations.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_prepare_buf"></a>`vb2_core_prepare_buf()`

```c
int vb2_core_prepare_buf(struct vb2_queue *q, struct vb2_buffer *vb, void *pb)
```

Pass ownership of a buffer from userspace to the kernel.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `void *pb`: buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_prepare_buf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

**Description**

Videobuf2 core helper to implement `VIDIOC_PREPARE_BUF()` operation. It is
called internally by VB2 by an API-specific handler, like
`videobuf2-v4l2.h`.

The passed buffer should have been verified.

This function calls vb2_ops->buf_prepare callback in the driver
(if provided), in which driver-specific buffer initialization can
be performed.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_remove_bufs"></a>`vb2_core_remove_bufs()`

```c
int vb2_core_remove_bufs(struct vb2_queue *q, unsigned int start, unsigned int count)
```

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `unsigned int start`: first index of the range of buffers to remove.
- `unsigned int count`: number of buffers to remove.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_qbuf"></a>`vb2_core_qbuf()`

```c
int vb2_core_qbuf(struct vb2_queue *q, struct vb2_buffer *vb, void *pb, struct media_request *req)
```

Queue a buffer from userspace

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `void *pb`: buffer structure passed from userspace to
  v4l2_ioctl_ops->vidioc_qbuf handler in driver
- `struct media_request *req`: pointer to [`struct media_request`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_request), may be NULL.

**Description**

Videobuf2 core helper to implement `VIDIOC_QBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

This function:

- #) If **req** is non-NULL, then the buffer will be bound to this

  media request and it returns. The buffer will be prepared and
  queued to the driver (i.e. the next two steps) when the request
  itself is queued.
- #) if necessary, calls [`vb2_ops->buf_prepare`](#c-struct-vb2_ops) callback in the driver

  (if provided), in which driver-specific buffer initialization can
  be performed;
- #) if streaming is on, queues the buffer in driver by the means of

  [`vb2_ops->buf_queue`](#c-struct-vb2_ops) callback for processing.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_dqbuf"></a>`vb2_core_dqbuf()`

```c
int vb2_core_dqbuf(struct vb2_queue *q, unsigned int *pindex, void *pb, bool nonblocking)
```

Dequeue a buffer to the userspace

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue
- `unsigned int *pindex`: pointer to the buffer index. May be NULL
- `void *pb`: buffer structure passed from userspace to
  v4l2_ioctl_ops->vidioc_dqbuf handler in driver.
- `bool nonblocking`: if true, this call will not sleep waiting for a buffer if no
  buffers ready for dequeuing are present. Normally the driver
  would be passing (file->f_flags & O_NONBLOCK) here.

**Description**

Videobuf2 core helper to implement `VIDIOC_DQBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

This function:

- #) calls buf_finish callback in the driver (if provided), in which

  driver can perform any additional operations that may be required before
  returning the buffer to userspace, such as cache sync,
- #) the buffer struct members are filled with relevant information for

  the userspace.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_streamon"></a>`vb2_core_streamon()`

```c
int vb2_core_streamon(struct vb2_queue *q, unsigned int type)
```

Implements VB2 stream ON logic

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue
- `unsigned int type`: type of the queue to be started.
  For V4L2, this is defined by [`enum v4l2_buf_type`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buf_type) type.

**Description**

Videobuf2 core helper to implement `VIDIOC_STREAMON()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_streamoff"></a>`vb2_core_streamoff()`

```c
int vb2_core_streamoff(struct vb2_queue *q, unsigned int type)
```

Implements VB2 stream OFF logic

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue
- `unsigned int type`: type of the queue to be started.
  For V4L2, this is defined by [`enum v4l2_buf_type`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buf_type) type.

**Description**

Videobuf2 core helper to implement `VIDIOC_STREAMOFF()` operation. It is
called internally by VB2 by an API-specific handler, like
`videobuf2-v4l2.h`.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_expbuf"></a>`vb2_core_expbuf()`

```c
int vb2_core_expbuf(struct vb2_queue *q, int *fd, unsigned int type, struct vb2_buffer *vb, unsigned int plane, unsigned int flags)
```

Export a buffer as a file descriptor.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `int *fd`: pointer to the file descriptor associated with DMABUF
  (set by driver).
- `unsigned int type`: buffer type.
- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `unsigned int plane`: index of the plane to be exported, 0 for single plane queues
- `unsigned int flags`: file flags for newly created file, as defined at
  include/uapi/asm-generic/fcntl.h.
  Currently, the only used flag is `O_CLOEXEC`.
  is supported, refer to manual of open syscall for more details.

**Description**

Videobuf2 core helper to implement `VIDIOC_EXPBUF()` operation. It is called
internally by VB2 by an API-specific handler, like `videobuf2-v4l2.h`.

**Return**

returns zero on success; an error code otherwise.

#### <a id="c-vb2_core_queue_init"></a>`vb2_core_queue_init()`

```c
int vb2_core_queue_init(struct vb2_queue *q)
```

initialize a videobuf2 queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
  This structure should be allocated in driver

**Description**

The [`vb2_queue`](#c-struct-vb2_queue) structure should be allocated by the driver. The driver is
responsible of clearing it's content and setting initial values for some
required entries before calling this function.

> [!NOTE]
> The following fields at **q** should be set before calling this function:
> [`vb2_queue->ops`](#c-struct-vb2_queue), [`vb2_queue->mem_ops`](#c-struct-vb2_queue), [`vb2_queue->type`](#c-struct-vb2_queue).

#### <a id="c-vb2_core_queue_release"></a>`vb2_core_queue_release()`

```c
void vb2_core_queue_release(struct vb2_queue *q)
```

stop streaming, release the queue and free memory

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function stops streaming and performs necessary clean ups, including
freeing video buffer memory. The driver is responsible for freeing
the [`struct vb2_queue`](#c-struct-vb2_queue) itself.

#### <a id="c-vb2_queue_error"></a>`vb2_queue_error()`

```c
void vb2_queue_error(struct vb2_queue *q)
```

signal a fatal error on the queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

Flag that a fatal unrecoverable error has occurred and wake up all processes
waiting on the queue. Polling will now set `EPOLLERR` and queuing and dequeuing
buffers will return `-EIO`.

The error flag will be cleared when canceling the queue, either from
[`vb2_streamoff()`](#c-vb2_streamoff) or [`vb2_queue_release()`](#c-vb2_queue_release). Drivers should thus not call this
function before starting the stream, otherwise the error flag will remain set
until the queue is released when closing the device node.

#### <a id="c-vb2_mmap"></a>`vb2_mmap()`

```c
int vb2_mmap(struct vb2_queue *q, struct vm_area_struct *vma)
```

map video buffers into application address space.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vm_area_struct *vma`: pointer to `struct vm_area_struct` with the vma passed
  to the mmap file operation handler in the driver.

**Description**

Should be called from mmap file operation handler of a driver.
This function maps one plane of one of the available video buffers to
userspace. To map whole video memory allocated on reqbufs, this function
has to be called once per each plane per each buffer previously allocated.

When the userspace application calls mmap, it passes to it an offset returned
to it earlier by the means of [`v4l2_ioctl_ops->vidioc_querybuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler.
That offset acts as a "cookie", which is then used to identify the plane
to be mapped.

This function finds a plane with a matching offset and a mapping is performed
by the means of a provided memory operation.

The return values from this function are intended to be directly returned
from the mmap handler in driver.

#### <a id="c-vb2_get_unmapped_area"></a>`vb2_get_unmapped_area()`

```c
unsigned long vb2_get_unmapped_area(struct vb2_queue *q, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags)
```

map video buffers into application address space.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `unsigned long addr`: memory address.
- `unsigned long len`: buffer size.
- `unsigned long pgoff`: page offset.
- `unsigned long flags`: memory flags.

**Description**

This function is used in noMMU platforms to propose address mapping
for a given buffer. It's intended to be used as a handler for the
`file_operations->get_unmapped_area` operation.

This is called by the `mmap()` syscall routines will call this
to get a proposed address for the mapping, when `!CONFIG_MMU`.

#### <a id="c-vb2_core_poll"></a>`vb2_core_poll()`

```c
__poll_t vb2_core_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
```

implements poll `syscall()` logic.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct file *file`: [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) argument passed to the poll
  file operation handler.
- `poll_table *wait`: `poll_table` wait argument passed to the poll
  file operation handler.

**Description**

This function implements poll file operation handler for a driver.
For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
be informed that the file descriptor of a video device is available for
reading.
For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
will be reported as available for writing.

The return values from this function are intended to be directly returned
from poll handler in driver.

#### <a id="c-vb2_read"></a>`vb2_read()`

```c
size_t vb2_read(struct vb2_queue *q, char __user *data, size_t count, loff_t *ppos, int nonblock)
```

implements `read()` syscall logic.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `char __user *data`: pointed to target userspace buffer
- `size_t count`: number of bytes to read
- `loff_t *ppos`: file handle position tracking pointer
- `int nonblock`: mode selector (1 means blocking calls, 0 means nonblocking)

#### <a id="c-vb2_write"></a>`vb2_write()`

```c
size_t vb2_write(struct vb2_queue *q, const char __user *data, size_t count, loff_t *ppos, int nonblock)
```

implements `write()` syscall logic.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `const char __user *data`: pointed to target userspace buffer
- `size_t count`: number of bytes to write
- `loff_t *ppos`: file handle position tracking pointer
- `int nonblock`: mode selector (1 means blocking calls, 0 means nonblocking)

#### <a id="c-vb2_thread_fnc"></a>`vb2_thread_fnc()`

```c
typedef int vb2_thread_fnc(struct vb2_buffer *vb, void *priv)
```

callback function for use with vb2_thread.

**Parameters**

- `struct vb2_buffer *vb`: pointer to struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `void *priv`: pointer to a private data.

**Description**

This is called whenever a buffer is dequeued in the thread.

#### <a id="c-vb2_thread_start"></a>`vb2_thread_start()`

```c
int vb2_thread_start(struct vb2_queue *q, vb2_thread_fnc fnc, void *priv, const char *thread_name)
```

start a thread for the given queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `vb2_thread_fnc fnc`: [`vb2_thread_fnc`](#c-vb2_thread_fnc) callback function.
- `void *priv`: priv pointer passed to the callback function.
- `const char *thread_name`: the name of the thread. This will be prefixed with "vb2-".

**Description**

This starts a thread that will queue and dequeue until an error occurs
or [`vb2_thread_stop()`](#c-vb2_thread_stop) is called.

> [!IMPORTANT]
> This function should not be used for anything else but the videobuf2-dvb
> support. If you think you have another good use-case for this, then please
> contact the linux-media mailing list first.

#### <a id="c-vb2_thread_stop"></a>`vb2_thread_stop()`

```c
int vb2_thread_stop(struct vb2_queue *q)
```

stop the thread for the given queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_is_streaming"></a>`vb2_is_streaming()`

```c
bool vb2_is_streaming(struct vb2_queue *q)
```

return streaming status of the queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_fileio_is_active"></a>`vb2_fileio_is_active()`

```c
bool vb2_fileio_is_active(struct vb2_queue *q)
```

return true if fileio is active.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This returns true if `read()` or `write()` is used to stream the data
as opposed to stream I/O. This is almost never an important distinction,
except in rare cases. One such case is that using `read()` or `write()` to
stream a format using `V4L2_FIELD_ALTERNATE` is not allowed since there
is no way you can pass the field information of each buffer to/from
userspace. A driver that supports this field format should check for
this in the [`vb2_ops->queue_setup`](#c-struct-vb2_ops) op and reject it if this function returns
true.

#### <a id="c-vb2_get_num_buffers"></a>`vb2_get_num_buffers()`

```c
unsigned int vb2_get_num_buffers(struct vb2_queue *q)
```

get the number of buffer in a queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_is_busy"></a>`vb2_is_busy()`

```c
bool vb2_is_busy(struct vb2_queue *q)
```

return busy status of the queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function checks if queue has any buffers allocated.

#### <a id="c-vb2_get_drv_priv"></a>`vb2_get_drv_priv()`

```c
void * vb2_get_drv_priv(struct vb2_queue *q)
```

return driver private data associated with the queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_set_plane_payload"></a>`vb2_set_plane_payload()`

```c
void vb2_set_plane_payload(struct vb2_buffer *vb, unsigned int plane_no, unsigned long size)
```

set bytesused for the plane **plane_no**.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which payload should be set.
- `unsigned long size`: payload in bytes.

#### <a id="c-vb2_get_plane_payload"></a>`vb2_get_plane_payload()`

```c
unsigned long vb2_get_plane_payload(struct vb2_buffer *vb, unsigned int plane_no)
```

get bytesused for the plane plane_no

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which payload should be set.

#### <a id="c-vb2_plane_size"></a>`vb2_plane_size()`

```c
unsigned long vb2_plane_size(struct vb2_buffer *vb, unsigned int plane_no)
```

return plane size in bytes.

**Parameters**

- `struct vb2_buffer *vb`: pointer to [`struct vb2_buffer`](#c-struct-vb2_buffer) to which the plane in
  question belongs to.
- `unsigned int plane_no`: plane number for which size should be returned.

#### <a id="c-vb2_start_streaming_called"></a>`vb2_start_streaming_called()`

```c
bool vb2_start_streaming_called(struct vb2_queue *q)
```

return streaming status of driver.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_clear_last_buffer_dequeued"></a>`vb2_clear_last_buffer_dequeued()`

```c
void vb2_clear_last_buffer_dequeued(struct vb2_queue *q)
```

clear last buffer dequeued flag of queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

#### <a id="c-vb2_get_buffer"></a>`vb2_get_buffer()`

```c
struct vb2_buffer * vb2_get_buffer(struct vb2_queue *q, unsigned int index)
```

get a buffer from a queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `unsigned int index`: buffer index

**Description**

This function obtains a buffer from a queue, by its index.
Keep in mind that there is no refcounting involved in this
operation, so the buffer lifetime should be taken into
consideration.

#### <a id="c-vb2_buffer_in_use"></a>`vb2_buffer_in_use()`

```c
bool vb2_buffer_in_use(struct vb2_queue *q, struct vb2_buffer *vb)
```

return true if the buffer is in use and the queue cannot be freed (by the means of VIDIOC_REQBUFS(0)) call.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct vb2_buffer *vb`: buffer for which plane size should be returned.

#### <a id="c-vb2_verify_memory_type"></a>`vb2_verify_memory_type()`

```c
int vb2_verify_memory_type(struct vb2_queue *q, enum vb2_memory memory, unsigned int type)
```

Check whether the memory type and buffer type passed to a buffer operation are compatible with the queue.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum vb2_memory memory`: memory model, as defined by enum [`vb2_memory`](#c-enum-vb2_memory).
- `unsigned int type`: private buffer type whose content is defined by the vb2-core
  caller. For example, for V4L2, it should match
  the types defined on enum `v4l2_buf_type`.

#### <a id="c-vb2_request_object_is_buffer"></a>`vb2_request_object_is_buffer()`

```c
bool vb2_request_object_is_buffer(struct media_request_object *obj)
```

return true if the object is a buffer

**Parameters**

- `struct media_request_object *obj`: the request object.

#### <a id="c-vb2_request_buffer_cnt"></a>`vb2_request_buffer_cnt()`

```c
unsigned int vb2_request_buffer_cnt(struct media_request *req)
```

return the number of buffers in the request

**Parameters**

- `struct media_request *req`: the request.



#### <a id="c-struct-vb2_v4l2_buffer"></a>`struct vb2_v4l2_buffer`

video buffer information for v4l2.

**Definition**

```c
struct vb2_v4l2_buffer {
    struct vb2_buffer       vb2_buf;
    __u32 flags;
    __u32 field;
    struct v4l2_timecode    timecode;
    __u32 sequence;
    __s32 request_fd;
    bool is_held;
    struct vb2_plane        planes[VB2_MAX_PLANES];
};
```

**Members**

- `vb2_buf`: embedded struct [`vb2_buffer`](#c-struct-vb2_buffer).
- `flags`: buffer informational flags.
- `field`: field order of the image in the buffer, as defined by
  [`enum v4l2_field`](/kernel/userspace/userspace-api/media-v4l/field-order.md#c-v4l2_field).
- `timecode`: frame timecode.
- `sequence`: sequence count of this frame.
- `request_fd`: the request_fd associated with this buffer
- `is_held`: if true, then this capture buffer was held
- `planes`: plane information (userptr/fd, length, bytesused, data_offset).

**Description**

Should contain enough information to be able to cover all the fields
of [`struct v4l2_buffer`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buffer) at `videodev2.h`.

#### <a id="c-vb2_find_buffer"></a>`vb2_find_buffer()`

```c
struct vb2_buffer * vb2_find_buffer(struct vb2_queue *q, u64 timestamp)
```

Find a buffer with given timestamp

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `u64 timestamp`: the timestamp to find.

**Description**

Returns the buffer with the given **timestamp**, or NULL if not found.

#### <a id="c-vb2_reqbufs"></a>`vb2_reqbufs()`

```c
int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
```

Wrapper for [`vb2_core_reqbufs()`](#c-vb2_core_reqbufs) that also verifies the memory and type values.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct v4l2_requestbuffers *req`: [`struct v4l2_requestbuffers`](/kernel/userspace/userspace-api/media-v4l/vidioc-reqbufs.md#c-v4l2_requestbuffers) passed from userspace to
  [`v4l2_ioctl_ops->vidioc_reqbufs`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_create_bufs"></a>`vb2_create_bufs()`

```c
int vb2_create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
```

Wrapper for [`vb2_core_create_bufs()`](#c-vb2_core_create_bufs) that also verifies the memory and type values.

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct v4l2_create_buffers *create`: creation parameters, passed from userspace to
  [`v4l2_ioctl_ops->vidioc_create_bufs`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver

#### <a id="c-vb2_prepare_buf"></a>`vb2_prepare_buf()`

```c
int vb2_prepare_buf(struct vb2_queue *q, struct media_device *mdev, struct v4l2_buffer *b)
```

Pass ownership of a buffer from userspace to the kernel

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device), may be NULL.
- `struct v4l2_buffer *b`: buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_prepare_buf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver

**Description**

Should be called from [`v4l2_ioctl_ops->vidioc_prepare_buf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) ioctl handler
of a driver.

This function:

\#) verifies the passed buffer,
\#) calls [`vb2_ops->buf_prepare`](#c-struct-vb2_ops) callback in the driver (if provided),
in which driver-specific buffer initialization can be performed.
\#) if **b->request_fd** is non-zero and **mdev->ops->req_queue** is set,
then bind the prepared buffer to the request.

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_prepare_buf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_qbuf"></a>`vb2_qbuf()`

```c
int vb2_qbuf(struct vb2_queue *q, struct media_device *mdev, struct v4l2_buffer *b)
```

Queue a buffer from userspace

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct media_device *mdev`: pointer to [`struct media_device`](/kernel/hardware/driver-api/media/mc-core.md#c-struct-media_device), may be NULL.
- `struct v4l2_buffer *b`: buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_qbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver

**Description**

Should be called from [`v4l2_ioctl_ops->vidioc_qbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler of a driver.

This function:

\#) verifies the passed buffer;
\#) if **b->request_fd** is non-zero and **mdev->ops->req_queue** is set,
then bind the buffer to the request.
\#) if necessary, calls [`vb2_ops->buf_prepare`](#c-struct-vb2_ops) callback in the driver
(if provided), in which driver-specific buffer initialization can
be performed;
\#) if streaming is on, queues the buffer in driver by the means of
[`vb2_ops->buf_queue`](#c-struct-vb2_ops) callback for processing.

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_qbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_expbuf"></a>`vb2_expbuf()`

```c
int vb2_expbuf(struct vb2_queue *q, struct v4l2_exportbuffer *eb)
```

Export a buffer as a file descriptor

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct v4l2_exportbuffer *eb`: export buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_expbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver

**Description**

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_expbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_dqbuf"></a>`vb2_dqbuf()`

```c
int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
```

Dequeue a buffer to the userspace

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct v4l2_buffer *b`: buffer structure passed from userspace to
  [`v4l2_ioctl_ops->vidioc_dqbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver
- `bool nonblocking`: if true, this call will not sleep waiting for a buffer if no
  buffers ready for dequeuing are present. Normally the driver
  would be passing ([`file->f_flags`](/kernel/internals/filesystems/api-summary.md#c-struct-file) & `O_NONBLOCK`) here

**Description**

Should be called from [`v4l2_ioctl_ops->vidioc_dqbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) ioctl handler
of a driver.

This function:

\#) verifies the passed buffer;
\#) calls [`vb2_ops->buf_finish`](#c-struct-vb2_ops) callback in the driver (if provided), in which
driver can perform any additional operations that may be required before
returning the buffer to userspace, such as cache sync;
\#) the buffer struct members are filled with relevant information for
the userspace.

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_dqbuf`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in driver.

#### <a id="c-vb2_streamon"></a>`vb2_streamon()`

```c
int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
```

start streaming

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum v4l2_buf_type type`: type argument passed from userspace to vidioc_streamon handler,
  as defined by [`enum v4l2_buf_type`](/kernel/userspace/userspace-api/media-v4l/buffer.md#c-v4l2_buf_type).

**Description**

Should be called from [`v4l2_ioctl_ops->vidioc_streamon`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler of a driver.

This function:

1) verifies current state
2) passes any previously queued buffers to the driver and starts streaming

The return values from this function are intended to be directly returned
from [`v4l2_ioctl_ops->vidioc_streamon`](/kernel/hardware/driver-api/media/v4l2-common.md#c-struct-v4l2_ioctl_ops) handler in the driver.

#### <a id="c-vb2_streamoff"></a>`vb2_streamoff()`

```c
int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
```

stop streaming

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `enum v4l2_buf_type type`: type argument passed from userspace to vidioc_streamoff handler

**Description**

Should be called from vidioc_streamoff handler of a driver.

This function:

\#) verifies current state,
\#) stop streaming and dequeues any queued buffers, including those previously
passed to the driver (after waiting for the driver to finish).

This call can be used for pausing playback.
The return values from this function are intended to be directly returned
from vidioc_streamoff handler in the driver

#### <a id="c-vb2_queue_init"></a>`vb2_queue_init()`

```c
int vb2_queue_init(struct vb2_queue *q)
```

initialize a videobuf2 queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

The vb2_queue structure should be allocated by the driver. The driver is
responsible of clearing it's content and setting initial values for some
required entries before calling this function.
q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
to the struct vb2_queue description in include/media/videobuf2-core.h
for more information.

#### <a id="c-vb2_queue_init_name"></a>`vb2_queue_init_name()`

```c
int vb2_queue_init_name(struct vb2_queue *q, const char *name)
```

initialize a videobuf2 queue with a name

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `const char *name`: the queue name

**Description**

This function initializes the vb2_queue exactly like [`vb2_queue_init()`](#c-vb2_queue_init),
and additionally sets the queue name. The queue name is used for logging
purpose, and should uniquely identify the queue within the context of the
device it belongs to. This is useful to attribute kernel log messages to the
right queue for m2m devices or other devices that handle multiple queues.

#### <a id="c-vb2_queue_release"></a>`vb2_queue_release()`

```c
void vb2_queue_release(struct vb2_queue *q)
```

stop streaming, release the queue and free memory

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.

**Description**

This function stops streaming and performs necessary clean ups, including
freeing video buffer memory. The driver is responsible for freeing
the vb2_queue structure itself.

#### <a id="c-vb2_queue_change_type"></a>`vb2_queue_change_type()`

```c
int vb2_queue_change_type(struct vb2_queue *q, unsigned int type)
```

change the type of an inactive vb2_queue

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `unsigned int type`: the type to change to (V4L2_BUF_TYPE_VIDEO_*)

**Description**

This function changes the type of the vb2_queue. This is only possible
if the queue is not busy (i.e. no buffers have been allocated).

[`vb2_queue_change_type()`](#c-vb2_queue_change_type) can be used to support multiple buffer types using
the same queue. The driver can implement v4l2_ioctl_ops.vidioc_reqbufs and
v4l2_ioctl_ops.vidioc_create_bufs functions and call [`vb2_queue_change_type()`](#c-vb2_queue_change_type)
before calling `vb2_ioctl_reqbufs()` or `vb2_ioctl_create_bufs()`, and thus
"lock" the buffer type until the buffers have been released.

#### <a id="c-vb2_poll"></a>`vb2_poll()`

```c
__poll_t vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
```

implements poll userspace operation

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct file *file`: file argument passed to the poll file operation handler
- `poll_table *wait`: wait argument passed to the poll file operation handler

**Description**

This function implements poll file operation handler for a driver.
For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
be informed that the file descriptor of a video device is available for
reading.
For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
will be reported as available for writing.

If the driver uses struct v4l2_fh, then [`vb2_poll()`](#c-vb2_poll) will also check for any
pending events.

The return values from this function are intended to be directly returned
from poll handler in driver.

#### <a id="c-vb2_queue_is_busy"></a>`vb2_queue_is_busy()`

```c
bool vb2_queue_is_busy(struct vb2_queue *q, struct file *file)
```

check if the queue is busy

**Parameters**

- `struct vb2_queue *q`: pointer to [`struct vb2_queue`](#c-struct-vb2_queue) with videobuf2 queue.
- `struct file *file`: file through which the vb2 queue access is performed

**Description**

The queue is considered busy if it has an owner and the owner is not the
**file**.

Queue ownership is acquired and checked by some of the v4l2_ioctl_ops helpers
below. Drivers can also use this function directly when they need to
open-code ioctl handlers, for instance to add additional checks between the
queue ownership test and the call to the corresponding vb2 operation.

#### <a id="c-vb2_video_unregister_device"></a>`vb2_video_unregister_device()`

```c
void vb2_video_unregister_device(struct video_device *vdev)
```

unregister the video device and release queue

**Parameters**

- `struct video_device *vdev`: pointer to [`struct video_device`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-struct-video_device)

**Description**

If the driver uses `vb2_fop_release()`/`_vb2_fop_release()`, then it should use
[`vb2_video_unregister_device()`](#c-vb2_video_unregister_device) instead of [`video_unregister_device()`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-video_unregister_device).

This function will call [`video_unregister_device()`](/kernel/hardware/driver-api/media/v4l2-dev.md#c-video_unregister_device) and then release the
vb2_queue if streaming is in progress. This will stop streaming and
this will simplify the unbind sequence since after this call all subdevs
will have stopped streaming as well.



#### <a id="c-struct-vb2_vmarea_handler"></a>`struct vb2_vmarea_handler`

common vma refcount tracking handler.

**Definition**

```c
struct vb2_vmarea_handler {
    refcount_t *refcount;
    void (*put)(void *arg);
    void *arg;
};
```

**Members**

- `refcount`: pointer to `refcount_t` entry in the buffer.
- `put`: callback to function that decreases buffer refcount.
- `arg`: argument for **put** callback.

---

# Media driver-specific documentation

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Reference for Media driver-specific documentation.

<a id="rst-media-driver-specific-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

<a id="rst-video4linux-v4l-drivers"></a>

## Video4Linux (V4L) drivers

- [The bttv driver](</kernel/hardware/driver-api/media-drivers/bttv-devel.md>)
- [The cx2341x driver](</kernel/hardware/driver-api/media-drivers/cx2341x-devel.md>)
- [The cx88 driver](</kernel/hardware/driver-api/media-drivers/cx88-devel.md>)
- [The Samsung S5P/EXYNOS4 FIMC driver](</kernel/hardware/driver-api/media-drivers/fimc-devel.md>)
- [The pvrusb2 driver](</kernel/hardware/driver-api/media-drivers/pvrusb2.md>)
- [PXA-Camera Host Driver](</kernel/hardware/driver-api/media-drivers/pxa-camera.md>)
- [The Radiotrack radio driver](</kernel/hardware/driver-api/media-drivers/radiotrack.md>)
- [The Rockchip Image Signal Processor Driver (rkisp1)](</kernel/hardware/driver-api/media-drivers/rkisp1.md>)
- [The saa7134 driver](</kernel/hardware/driver-api/media-drivers/saa7134-devel.md>)
- [Cropping and Scaling algorithm, used in the sh_mobile_ceu_camera driver](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/media/drivers/sh_mobile_ceu_camera.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Tuner drivers](</kernel/hardware/driver-api/media-drivers/tuners.md>)
- [The Virtual Media Controller Driver (vimc)](</kernel/hardware/driver-api/media-drivers/vimc-devel.md>)
- [The Zoran driver](</kernel/hardware/driver-api/media-drivers/zoran.md>)
- [MIPI CCS camera sensor driver](</kernel/hardware/driver-api/media-drivers-ccs/ccs.md>)
- [Intel IPU6 Driver](</kernel/hardware/driver-api/media-drivers/ipu6.md>)

<a id="rst-digital-tv-drivers"></a>

## Digital TV drivers

- [Idea behind the dvb-usb-framework](</kernel/hardware/driver-api/media-drivers/dvb-usb.md>)
- [Frontend drivers](</kernel/hardware/driver-api/media-drivers/frontends.md>)
- [vidtv: Virtual Digital TV driver](</kernel/hardware/driver-api/media-drivers/vidtv.md>)
- [Contributors](</kernel/hardware/driver-api/media-drivers/contributors.md>)

---

# The bttv driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> There are a lot of different bt848/849/878/879 based boards available. Making video work often is not a big deal, because this is handled completely by the bt8xx chip, which is common on all boards. But sound is handled in slightly…

<a id="rst-the-bttv-driver"></a>

<a id="rst-bttv-and-sound-mini-howto"></a>

## bttv and sound mini howto

<!-- SPDX-License-Identifier: GPL-2.0 -->

There are a lot of different bt848/849/878/879 based boards available. Making video work often is not a big deal, because this is handled completely by the bt8xx chip, which is common on all boards.  But sound is handled in slightly different ways on each board.

To handle the grabber boards correctly, there is a array tvcards\[\] in bttv-cards.c, which holds the information required for each board. Sound will work only, if the correct entry is used (for video it often makes no difference).  The bttv driver prints a line to the kernel log, telling which card type is used.  Like this one:



```text
bttv0: model: BT848(Hauppauge old) [autodetected]
```

You should verify this is correct.  If it isn't, you have to pass the correct board type as insmod argument, `insmod bttv card=2` for example.  The file [Documentation/admin-guide/media/bttv-cardlist.rst](/kernel/administration/admin-guide/media/bttv-cardlist.md) has a list of valid arguments for card.

If your card isn't listed there, you might check the source code for new entries which are not listed yet.  If there isn't one for your card, you can check if one of the existing entries does work for you (just trial and error...).

Some boards have an extra processor for sound to do stereo decoding and other nice features.  The msp34xx chips are used by Hauppauge for example.  If your board has one, you might have to load a helper module like `msp3400` to make sound work.  If there isn't one for the chip used on your board:  Bad luck.  Start writing a new one.  Well, you might want to check the video4linux mailing list archive first...

Of course you need a correctly installed soundcard unless you have the speakers connected directly to the grabber board.  Hint: check the mixer settings too.  ALSA for example has everything muted by default.

<a id="rst-how-sound-works-in-detail"></a>

## How sound works in detail

Still doesn't work?  Looks like some driver hacking is required. Below is a do-it-yourself description for you.

The bt8xx chips have 32 general purpose pins, and registers to control these pins.  One register is the output enable register (`BT848_GPIO_OUT_EN`), it says which pins are actively driven by the bt848 chip.  Another one is the data register (`BT848_GPIO_DATA`), where you can get/set the status if these pins.  They can be used for input and output.

Most grabber board vendors use these pins to control an external chip which does the sound routing.  But every board is a little different. These pins are also used by some companies to drive remote control receiver chips.  Some boards use the i2c bus instead of the gpio pins to connect the mux chip.

As mentioned above, there is a array which holds the required information for each known board.  You basically have to create a new line for your board.  The important fields are these two:



```text
struct tvcard
{
      [ ... ]
      u32 gpiomask;
      u32 audiomux[6]; /* Tuner, Radio, external, internal, mute, stereo */
};
```

gpiomask specifies which pins are used to control the audio mux chip. The corresponding bits in the output enable register (`BT848_GPIO_OUT_EN`) will be set as these pins must be driven by the bt848 chip.

The `audiomux[]` array holds the data values for the different inputs (i.e. which pins must be high/low for tuner/mute/...).  This will be written to the data register (`BT848_GPIO_DATA`) to switch the audio mux.

What you have to do is figure out the correct values for gpiomask and the audiomux array.  If you have Windows and the drivers four your card installed, you might to check out if you can read these registers values used by the windows driver.  A tool to do this is available from [http://btwincap.sourceforge.net/download.html](<http://btwincap.sourceforge.net/download.html>).

You might also dig around in the `*.ini` files of the Windows applications. You can have a look at the board to see which of the gpio pins are connected at all and then start trial-and-error ...

Starting with release 0.7.41 bttv has a number of insmod options to make the gpio debugging easier:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> bttv_gpio=0/1
>
> </td>
> <td>
>
>
> enable/disable gpio debug messages
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> gpiomask=n
>
> </td>
> <td>
>
>
> set the gpiomask value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> audiomux=i,j,...
>
> </td>
> <td>
>
>
> set the values of the audiomux array
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> audioall=a
>
> </td>
> <td>
>
>
> set the values of the audiomux array (one value for all array elements, useful to check out which effect the particular value has).
>
> </td>
> </tr>
> </tbody>
> </table>

The messages printed with `bttv_gpio=1` look like this:



```text
bttv0: gpio: en=00000027, out=00000024 in=00ffffd8 [audio: off]

en  =   output _en_able register (BT848_GPIO_OUT_EN)
out =   _out_put bits of the data register (BT848_GPIO_DATA),
        i.e. BT848_GPIO_DATA & BT848_GPIO_OUT_EN
in  =   _in_put bits of the data register,
        i.e. BT848_GPIO_DATA & ~BT848_GPIO_OUT_EN
```

---

# Contributors

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Thanks go to the following people for patches and contributions:

<a id="rst-contributors"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> [!NOTE]
>
> This documentation is outdated. There are several other DVB contributors that aren't listed below.

Thanks go to the following people for patches and contributions:

- Michael Hunold &lt;[m.hunold@gmx.de](<mailto:m.hunold@gmx.de>)&gt;

  - for the initial saa7146 driver and its recent overhaul

- Christian Theiss

  - for his work on the initial Linux DVB driver

- Marcus Metzler &lt;[mocm@metzlerbros.de](<mailto:mocm@metzlerbros.de>)&gt; and Ralph Metzler &lt;[rjkm@metzlerbros.de](<mailto:rjkm@metzlerbros.de>)&gt;

  - for their continuing work on the DVB driver

- Michael Holzt &lt;[kju@debian.org](<mailto:kju@debian.org>)&gt;

  - for his contributions to the dvb-net driver

- Diego Picciani &lt;[d.picciani@novacomp.it](<mailto:d.picciani@novacomp.it>)&gt;

  - for CyberLogin for Linux which allows logging onto EON (in case you are wondering where CyberLogin is, EON changed its login procedure and CyberLogin is no longer used.)

- Martin Schaller &lt;[martin@smurf.franken.de](<mailto:martin@smurf.franken.de>)&gt;

  - for patching the cable card decoder driver

- Klaus Schmidinger &lt;[Klaus.Schmidinger@cadsoft.de](<mailto:Klaus.Schmidinger@cadsoft.de>)&gt;

  - for various fixes regarding tuning, OSD and CI stuff and his work on VDR

- Steve Brown &lt;[sbrown@cortland.com](<mailto:sbrown@cortland.com>)&gt;

  - for his AFC kernel thread

- Christoph Martin &lt;[martin@uni-mainz.de](<mailto:martin@uni-mainz.de>)&gt;

  - for his LIRC infrared handler

- Andreas Oberritter &lt;[obi@linuxtv.org](<mailto:obi@linuxtv.org>)&gt;, Dennis Noermann &lt;[dennis.noermann@noernet.de](<mailto:dennis.noermann@noernet.de>)&gt;, Felix Domke &lt;[tmbinc@elitedvb.net](<mailto:tmbinc@elitedvb.net>)&gt;, Florian Schirmer &lt;[jolt@tuxbox.org](<mailto:jolt@tuxbox.org>)&gt;, Ronny Strutz &lt;[3des@elitedvb.de](<mailto:3des@elitedvb.de>)&gt;, Wolfram Joost &lt;[dbox2@frokaschwei.de](<mailto:dbox2@frokaschwei.de>)&gt; and all the other dbox2 people

  - for many bugfixes in the generic DVB Core, frontend drivers and their work on the dbox2 port of the DVB driver

- Oliver Endriss &lt;[o.endriss@gmx.de](<mailto:o.endriss@gmx.de>)&gt;

  - for many bugfixes

- Andrew de Quincey &lt;[adq_dvb@lidskialf.net](<mailto:adq_dvb@lidskialf.net>)&gt;

  - for the tda1004x frontend driver, and various bugfixes

- Peter Schildmann &lt;[peter.schildmann@web.de](<mailto:peter.schildmann@web.de>)&gt;

  - for the driver for the Technisat SkyStar2 PCI DVB card

- Vadim Catana &lt;[skystar@moldova.cc](<mailto:skystar@moldova.cc>)&gt;, Roberto Ragusa &lt;[r.ragusa@libero.it](<mailto:r.ragusa@libero.it>)&gt; and Augusto Cardoso &lt;[augusto@carhil.net](<mailto:augusto@carhil.net>)&gt;

  - for all the work for the FlexCopII chipset by B2C2,Inc.

- Davor Emard &lt;[emard@softhome.net](<mailto:emard@softhome.net>)&gt;

  - for his work on the budget drivers, the demux code, the module unloading problems, ...

- Hans-Frieder Vogt &lt;[hfvogt@arcor.de](<mailto:hfvogt@arcor.de>)&gt;

  - for his work on calculating and checking the crc's for the TechnoTrend/Hauppauge DEC driver firmware

- Michael Dreher &lt;[michael@5dot1.de](<mailto:michael@5dot1.de>)&gt; and Andreas 'randy' Weinberger

  - for the support of the Fujitsu-Siemens Activy budget DVB-S

- Kenneth Aafløy &lt;[ke-aa@frisurf.no](<mailto:ke-aa@frisurf.no>)&gt;

  - for adding support for Typhoon DVB-S budget card

- Ernst Peinlich &lt;[e.peinlich@inode.at](<mailto:e.peinlich@inode.at>)&gt;

  - for tuning/DiSEqC support for the DEC 3000-s

- Peter Beutner &lt;[p.beutner@gmx.net](<mailto:p.beutner@gmx.net>)&gt;

  - for the IR code for the ttusb-dec driver

- Wilson Michaels &lt;[wilsonmichaels@earthlink.net](<mailto:wilsonmichaels@earthlink.net>)&gt;

  - for the lgdt330x frontend driver, and various bugfixes

- Michael Krufky &lt;[mkrufky@linuxtv.org](<mailto:mkrufky@linuxtv.org>)&gt;

  - for maintaining v4l/dvb inter-tree dependencies

- Taylor Jacob &lt;[rtjacob@earthlink.net](<mailto:rtjacob@earthlink.net>)&gt;

  - for the nxt2002 frontend driver

- Jean-Francois Thibert &lt;[jeanfrancois@sagetv.com](<mailto:jeanfrancois@sagetv.com>)&gt;

  - for the nxt2004 frontend driver

- Kirk Lapray &lt;[kirk.lapray@gmail.com](<mailto:kirk.lapray@gmail.com>)&gt;

  - for the or51211 and or51132 frontend drivers, and for merging the nxt2002 and nxt2004 modules into a single nxt200x frontend driver.

(If you think you should be in this list, but you are not, drop a line to the DVB mailing list)

---

# The cx2341x driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> This section describes the cx2341x memory map and documents some of the register space.

<a id="rst-the-cx2341x-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-memory-at-cx2341x-chips"></a>

## Memory at cx2341x chips

This section describes the cx2341x memory map and documents some of the register space.

> [!NOTE]
>
> the memory long words are little-endian ('intel format').

> [!WARNING]
>
> This information was figured out from searching through the memory and registers, this information may not be correct and is certainly not complete, and was not derived from anything more than searching through the memory space with commands like:
>
>
>
> ```none
> ivtvctl -O min=0x02000000,max=0x020000ff
> ```
>
> So take this as is, I'm always searching for more stuff, it's a large register space :-).

<a id="rst-memory-map"></a>

### Memory Map

The cx2341x exposes its entire 64M memory space to the PCI host via the PCI BAR0 (Base Address Register 0). The addresses here are offsets relative to the address held in BAR0.



```none
0x00000000-0x00ffffff Encoder memory space
0x00000000-0x0003ffff Encode.rom
???-???         MPEG buffer(s)
???-???         Raw video capture buffer(s)
???-???         Raw audio capture buffer(s)
???-???         Display buffers (6 or 9)

0x01000000-0x01ffffff Decoder memory space
0x01000000-0x0103ffff Decode.rom
???-???         MPEG buffers(s)
0x0114b000-0x0115afff Audio.rom (deprecated?)

0x02000000-0x0200ffff Register Space
```

<a id="rst-registers"></a>

### Registers

The registers occupy the 64k space starting at the 0x02000000 offset from BAR0. All of these registers are 32 bits wide.



```none
DMA Registers 0x000-0xff:

0x00 - Control:
        0=reset/cancel, 1=read, 2=write, 4=stop
0x04 - DMA status:
        1=read busy, 2=write busy, 4=read error, 8=write error, 16=link list error
0x08 - pci DMA pointer for read link list
0x0c - pci DMA pointer for write link list
0x10 - read/write DMA enable:
        1=read enable, 2=write enable
0x14 - always 0xffffffff, if set any lower instability occurs, 0x00 crashes
0x18 - ??
0x1c - always 0x20 or 32, smaller values slow down DMA transactions
0x20 - always value of 0x780a010a
0x24-0x3c - usually just random values???
0x40 - Interrupt status
0x44 - Write a bit here and shows up in Interrupt status 0x40
0x48 - Interrupt Mask
0x4C - always value of 0xfffdffff,
        if changed to 0xffffffff DMA write interrupts break.
0x50 - always 0xffffffff
0x54 - always 0xffffffff (0x4c, 0x50, 0x54 seem like interrupt masks, are
        3 processors on chip, Java ones, VPU, SPU, APU, maybe these are the
        interrupt masks???).
0x60-0x7C - random values
0x80 - first write linked list reg, for Encoder Memory addr
0x84 - first write linked list reg, for pci memory addr
0x88 - first write linked list reg, for length of buffer in memory addr
        (|0x80000000 or this for last link)
0x8c-0xdc - rest of write linked list reg, 8 sets of 3 total, DMA goes here
        from linked list addr in reg 0x0c, firmware must push through or
        something.
0xe0 - first (and only) read linked list reg, for pci memory addr
0xe4 - first (and only) read linked list reg, for Decoder memory addr
0xe8 - first (and only) read linked list reg, for length of buffer
0xec-0xff - Nothing seems to be in these registers, 0xec-f4 are 0x00000000.
```

Memory locations for Encoder Buffers 0x700-0x7ff:

These registers show offsets of memory locations pertaining to each buffer area used for encoding, have to shift them by &lt;&lt;1 first.

- 0x07F8: Encoder SDRAM refresh

- 0x07FC: Encoder SDRAM pre-charge

Memory locations for Decoder Buffers 0x800-0x8ff:

These registers show offsets of memory locations pertaining to each buffer area used for decoding, have to shift them by &lt;&lt;1 first.

- 0x08F8: Decoder SDRAM refresh

- 0x08FC: Decoder SDRAM pre-charge

Other memory locations:

- 0x2800: Video Display Module control

- 0x2D00: AO (audio output?) control

- 0x2D24: Bytes Flushed

- 0x7000: LSB I2C write clock bit (inverted)

- 0x7004: LSB I2C write data bit (inverted)

- 0x7008: LSB I2C read clock bit

- 0x700c: LSB I2C read data bit

- 0x9008: GPIO get input state

- 0x900c: GPIO set output state

- 0x9020: GPIO direction (Bit7 (GPIO 0..7) - 0:input, 1:output)

- 0x9050: SPU control

- 0x9054: Reset HW blocks

- 0x9058: VPU control

- 0xA018: Bit6: interrupt pending?

- 0xA064: APU command

<a id="rst-interrupt-status-register"></a>

### Interrupt Status Register

The definition of the bits in the interrupt status register 0x0040, and the interrupt mask 0x0048. If a bit is cleared in the mask, then we want our ISR to execute.

- bit 31 Encoder Start Capture

- bit 30 Encoder EOS

- bit 29 Encoder VBI capture

- bit 28 Encoder Video Input Module reset event

- bit 27 Encoder DMA complete

- bit 24 Decoder audio mode change detection event (through event notification)

- bit 22 Decoder data request

- bit 20 Decoder DMA complete

- bit 19 Decoder VBI re-insertion

- bit 18 Decoder DMA err (linked-list bad)

<a id="rst-missing-documentation"></a>

## Missing documentation

- Encoder API post(?)

- Decoder API post(?)

- Decoder VTRACE event

<a id="rst-the-cx2341x-firmware-upload"></a>

## The cx2341x firmware upload

This document describes how to upload the cx2341x firmware to the card.

<a id="rst-how-to-find"></a>

### How to find

See the web pages of the various projects that uses this chip for information on how to obtain the firmware.

The firmware stored in a Windows driver can be detected as follows:

- Each firmware image is 256k bytes.

- The 1st 32-bit word of the Encoder image is 0x0000da7

- The 1st 32-bit word of the Decoder image is 0x00003a7

- The 2nd 32-bit word of both images is 0xaa55bb66

<a id="rst-how-to-load"></a>

### How to load

- Issue the FWapi command to stop the encoder if it is running. Wait for the command to complete.

- Issue the FWapi command to stop the decoder if it is running. Wait for the command to complete.

- Issue the I2C command to the digitizer to stop emitting VSYNC events.

- Issue the FWapi command to halt the encoder's firmware.

- Sleep for 10ms.

- Issue the FWapi command to halt the decoder's firmware.

- Sleep for 10ms.

- Write 0x00000000 to register 0x2800 to stop the Video Display Module.

- Write 0x00000005 to register 0x2D00 to stop the AO (audio output?).

- Write 0x00000000 to register 0xA064 to ping? the APU.

- Write 0xFFFFFFFE to register 0x9058 to stop the VPU.

- Write 0xFFFFFFFF to register 0x9054 to reset the HW blocks.

- Write 0x00000001 to register 0x9050 to stop the SPU.

- Sleep for 10ms.

- Write 0x0000001A to register 0x07FC to init the Encoder SDRAM's pre-charge.

- Write 0x80000640 to register 0x07F8 to init the Encoder SDRAM's refresh to 1us.

- Write 0x0000001A to register 0x08FC to init the Decoder SDRAM's pre-charge.

- Write 0x80000640 to register 0x08F8 to init the Decoder SDRAM's refresh to 1us.

- Sleep for 512ms. (600ms is recommended)

- Transfer the encoder's firmware image to offset 0 in Encoder memory space.

- Transfer the decoder's firmware image to offset 0 in Decoder memory space.

- Use a read-modify-write operation to Clear bit 0 of register 0x9050 to re-enable the SPU.

- Sleep for 1 second.

- Use a read-modify-write operation to Clear bits 3 and 0 of register 0x9058 to re-enable the VPU.

- Sleep for 1 second.

- Issue status API commands to both firmware images to verify.

<a id="rst-how-to-call-the-firmware-api"></a>

## How to call the firmware API

The preferred calling convention is known as the firmware mailbox. The mailboxes are basically a fixed length array that serves as the call-stack.

Firmware mailboxes can be located by searching the encoder and decoder memory for a 16 byte signature. That signature will be located on a 256-byte boundary.

Signature:



```none
0x78, 0x56, 0x34, 0x12, 0x12, 0x78, 0x56, 0x34,
0x34, 0x12, 0x78, 0x56, 0x56, 0x34, 0x12, 0x78
```

The firmware implements 20 mailboxes of 20 32-bit words. The first 10 are reserved for API calls. The second 10 are used by the firmware for event notification.

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Index
>
> </th>
> <th>
>
>
> Name
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> Flags
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> Command
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> Return value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> Timeout
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4-19
>
> </td>
> <td>
>
>
> Parameter/Result
>
> </td>
> </tr>
> </tbody>
> </table>

The flags are defined in the following table. The direction is from the perspective of the firmware.

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Bit
>
> </th>
> <th>
>
>
> Direction
>
> </th>
> <th>
>
>
> Purpose
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> O
>
> </td>
> <td>
>
>
> Firmware has processed the command.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> I
>
> </td>
> <td>
>
>
> Driver has finished setting the parameters.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> I
>
> </td>
> <td>
>
>
> Driver is using this mailbox.
>
> </td>
> </tr>
> </tbody>
> </table>

The command is a 32-bit enumerator. The API specifics may be found in this chapter.

The return value is a 32-bit enumerator. Only two values are currently defined:

- 0=success

- -1=command undefined.

There are 16 parameters/results 32-bit fields. The driver populates these fields with values for all the parameters required by the call. The driver overwrites these fields with result values returned by the call.

The timeout value protects the card from a hung driver thread. If the driver doesn't handle the completed call within the timeout specified, the firmware will reset that mailbox.

To make an API call, the driver iterates over each mailbox looking for the first one available (bit 0 has been cleared). The driver sets that bit, fills in the command enumerator, the timeout value and any required parameters. The driver then sets the parameter ready bit (bit 1). The firmware scans the mailboxes for pending commands, processes them, sets the result code, populates the result value array with that call's return values and sets the call complete bit (bit 2). Once bit 2 is set, the driver should retrieve the results and clear all the flags. If the driver does not perform this task within the time set in the timeout register, the firmware will reset that mailbox.

Event notifications are sent from the firmware to the host. The host tells the firmware which events it is interested in via an API call. That call tells the firmware which notification mailbox to use. The firmware signals the host via an interrupt. Only the 16 Results fields are used, the Flags, Command, Return value and Timeout words are not used.

<a id="rst-osd-firmware-api-description"></a>

## OSD firmware API description

> [!NOTE]
>
> this API is part of the decoder firmware, so it's cx23415 only.

<a id="rst-cx2341x-osd-get-framebuffer"></a>

### CX2341X_OSD_GET_FRAMEBUFFER

Enum: 65/0x41

<a id="rst-description"></a>

#### Description

Return base and length of contiguous OSD memory.

<a id="rst-result-0"></a>

#### Result\[0\]

OSD base address

<a id="rst-result-1"></a>

#### Result\[1\]

OSD length

<a id="rst-cx2341x-osd-get-pixel-format"></a>

### CX2341X_OSD_GET_PIXEL_FORMAT

Enum: 66/0x42

<a id="rst-description-1"></a>

#### Description

Query OSD format

<a id="rst-result-0-1"></a>

#### Result\[0\]

0=8bit index 1=16bit RGB 5:6:5 2=16bit ARGB 1:5:5:5 3=16bit ARGB 1:4:4:4 4=32bit ARGB 8:8:8:8

<a id="rst-cx2341x-osd-set-pixel-format"></a>

### CX2341X_OSD_SET_PIXEL_FORMAT

Enum: 67/0x43

<a id="rst-description-2"></a>

#### Description

Assign pixel format

<a id="rst-param-0"></a>

#### Param\[0\]

- 0=8bit index

- 1=16bit RGB 5:6:5

- 2=16bit ARGB 1:5:5:5

- 3=16bit ARGB 1:4:4:4

- 4=32bit ARGB 8:8:8:8

<a id="rst-cx2341x-osd-get-state"></a>

### CX2341X_OSD_GET_STATE

Enum: 68/0x44

<a id="rst-description-3"></a>

#### Description

Query OSD state

<a id="rst-result-0-2"></a>

#### Result\[0\]

- Bit  0   0=off, 1=on

- Bits 1:2 alpha control

- Bits 3:5 pixel format

<a id="rst-cx2341x-osd-set-state"></a>

### CX2341X_OSD_SET_STATE

Enum: 69/0x45

<a id="rst-description-4"></a>

#### Description

OSD switch

<a id="rst-param-0-1"></a>

#### Param\[0\]

0=off, 1=on

<a id="rst-cx2341x-osd-get-osd-coords"></a>

### CX2341X_OSD_GET_OSD_COORDS

Enum: 70/0x46

<a id="rst-description-5"></a>

#### Description

Retrieve coordinates of OSD area blended with video

<a id="rst-result-0-3"></a>

#### Result\[0\]

OSD buffer address

<a id="rst-result-1-1"></a>

#### Result\[1\]

Stride in pixels

<a id="rst-result-2"></a>

#### Result\[2\]

Lines in OSD buffer

<a id="rst-result-3"></a>

#### Result\[3\]

Horizontal offset in buffer

<a id="rst-result-4"></a>

#### Result\[4\]

Vertical offset in buffer

<a id="rst-cx2341x-osd-set-osd-coords"></a>

### CX2341X_OSD_SET_OSD_COORDS

Enum: 71/0x47

<a id="rst-description-6"></a>

#### Description

Assign the coordinates of the OSD area to blend with video

<a id="rst-param-0-2"></a>

#### Param\[0\]

buffer address

<a id="rst-param-1"></a>

#### Param\[1\]

buffer stride in pixels

<a id="rst-param-2"></a>

#### Param\[2\]

lines in buffer

<a id="rst-param-3"></a>

#### Param\[3\]

horizontal offset

<a id="rst-param-4"></a>

#### Param\[4\]

vertical offset

<a id="rst-cx2341x-osd-get-screen-coords"></a>

### CX2341X_OSD_GET_SCREEN_COORDS

Enum: 72/0x48

<a id="rst-description-7"></a>

#### Description

Retrieve OSD screen area coordinates

<a id="rst-result-0-4"></a>

#### Result\[0\]

top left horizontal offset

<a id="rst-result-1-2"></a>

#### Result\[1\]

top left vertical offset

<a id="rst-result-2-1"></a>

#### Result\[2\]

bottom right horizontal offset

<a id="rst-result-3-1"></a>

#### Result\[3\]

bottom right vertical offset

<a id="rst-cx2341x-osd-set-screen-coords"></a>

### CX2341X_OSD_SET_SCREEN_COORDS

Enum: 73/0x49

<a id="rst-description-8"></a>

#### Description

Assign the coordinates of the screen area to blend with video

<a id="rst-param-0-3"></a>

#### Param\[0\]

top left horizontal offset

<a id="rst-param-1-1"></a>

#### Param\[1\]

top left vertical offset

<a id="rst-param-2-1"></a>

#### Param\[2\]

bottom left horizontal offset

<a id="rst-param-3-1"></a>

#### Param\[3\]

bottom left vertical offset

<a id="rst-cx2341x-osd-get-global-alpha"></a>

### CX2341X_OSD_GET_GLOBAL_ALPHA

Enum: 74/0x4A

<a id="rst-description-9"></a>

#### Description

Retrieve OSD global alpha

<a id="rst-result-0-5"></a>

#### Result\[0\]

global alpha: 0=off, 1=on

<a id="rst-result-1-3"></a>

#### Result\[1\]

bits 0:7 global alpha

<a id="rst-cx2341x-osd-set-global-alpha"></a>

### CX2341X_OSD_SET_GLOBAL_ALPHA

Enum: 75/0x4B

<a id="rst-description-10"></a>

#### Description

Update global alpha

<a id="rst-param-0-4"></a>

#### Param\[0\]

global alpha: 0=off, 1=on

<a id="rst-param-1-2"></a>

#### Param\[1\]

global alpha (8 bits)

<a id="rst-param-2-2"></a>

#### Param\[2\]

local alpha: 0=on, 1=off

<a id="rst-cx2341x-osd-set-blend-coords"></a>

### CX2341X_OSD_SET_BLEND_COORDS

Enum: 78/0x4C

<a id="rst-description-11"></a>

#### Description

Move start of blending area within display buffer

<a id="rst-param-0-5"></a>

#### Param\[0\]

horizontal offset in buffer

<a id="rst-param-1-3"></a>

#### Param\[1\]

vertical offset in buffer

<a id="rst-cx2341x-osd-get-flicker-state"></a>

### CX2341X_OSD_GET_FLICKER_STATE

Enum: 79/0x4F

<a id="rst-description-12"></a>

#### Description

Retrieve flicker reduction module state

<a id="rst-result-0-6"></a>

#### Result\[0\]

flicker state: 0=off, 1=on

<a id="rst-cx2341x-osd-set-flicker-state"></a>

### CX2341X_OSD_SET_FLICKER_STATE

Enum: 80/0x50

<a id="rst-description-13"></a>

#### Description

Set flicker reduction module state

<a id="rst-param-0-6"></a>

#### Param\[0\]

State: 0=off, 1=on

<a id="rst-cx2341x-osd-blt-copy"></a>

### CX2341X_OSD_BLT_COPY

Enum: 82/0x52

<a id="rst-description-14"></a>

#### Description

BLT copy

<a id="rst-param-0-7"></a>

#### Param\[0\]



```none
'0000'  zero
'0001' ~destination AND ~source
'0010' ~destination AND  source
'0011' ~destination
'0100'  destination AND ~source
'0101'                  ~source
'0110'  destination XOR  source
'0111' ~destination OR  ~source
'1000' ~destination AND ~source
'1001'  destination XNOR source
'1010'                   source
'1011' ~destination OR   source
'1100'  destination
'1101'  destination OR  ~source
'1110'  destination OR   source
'1111'  one
```

<a id="rst-param-1-4"></a>

#### Param\[1\]

Resulting alpha blending

- '01' source_alpha

- '10' destination_alpha

- '11' source_alpha\*destination_alpha+1 (zero if both source and destination alpha are zero)

<a id="rst-param-2-3"></a>

#### Param\[2\]



```none
'00' output_pixel = source_pixel

'01' if source_alpha=0:
         output_pixel = destination_pixel
     if 256 > source_alpha > 1:
         output_pixel = ((source_alpha + 1)*source_pixel +
                         (255 - source_alpha)*destination_pixel)/256

'10' if destination_alpha=0:
         output_pixel = source_pixel
      if 255 > destination_alpha > 0:
         output_pixel = ((255 - destination_alpha)*source_pixel +
                         (destination_alpha + 1)*destination_pixel)/256

'11' if source_alpha=0:
         source_temp = 0
     if source_alpha=255:
         source_temp = source_pixel*256
     if 255 > source_alpha > 0:
         source_temp = source_pixel*(source_alpha + 1)
     if destination_alpha=0:
         destination_temp = 0
     if destination_alpha=255:
         destination_temp = destination_pixel*256
     if 255 > destination_alpha > 0:
         destination_temp = destination_pixel*(destination_alpha + 1)
     output_pixel = (source_temp + destination_temp)/256
```

<a id="rst-param-3-2"></a>

#### Param\[3\]

width

<a id="rst-param-4-1"></a>

#### Param\[4\]

height

<a id="rst-param-5"></a>

#### Param\[5\]

destination pixel mask

<a id="rst-param-6"></a>

#### Param\[6\]

destination rectangle start address

<a id="rst-param-7"></a>

#### Param\[7\]

destination stride in dwords

<a id="rst-param-8"></a>

#### Param\[8\]

source stride in dwords

<a id="rst-param-9"></a>

#### Param\[9\]

source rectangle start address

<a id="rst-cx2341x-osd-blt-fill"></a>

### CX2341X_OSD_BLT_FILL

Enum: 83/0x53

<a id="rst-description-15"></a>

#### Description

BLT fill color

<a id="rst-param-0-8"></a>

#### Param\[0\]

Same as Param\[0\] on API 0x52

<a id="rst-param-1-5"></a>

#### Param\[1\]

Same as Param\[1\] on API 0x52

<a id="rst-param-2-4"></a>

#### Param\[2\]

Same as Param\[2\] on API 0x52

<a id="rst-param-3-3"></a>

#### Param\[3\]

width

<a id="rst-param-4-2"></a>

#### Param\[4\]

height

<a id="rst-param-5-1"></a>

#### Param\[5\]

destination pixel mask

<a id="rst-param-6-1"></a>

#### Param\[6\]

destination rectangle start address

<a id="rst-param-7-1"></a>

#### Param\[7\]

destination stride in dwords

<a id="rst-param-8-1"></a>

#### Param\[8\]

color fill value

<a id="rst-cx2341x-osd-blt-text"></a>

### CX2341X_OSD_BLT_TEXT

Enum: 84/0x54

<a id="rst-description-16"></a>

#### Description

BLT for 8 bit alpha text source

<a id="rst-param-0-9"></a>

#### Param\[0\]

Same as Param\[0\] on API 0x52

<a id="rst-param-1-6"></a>

#### Param\[1\]

Same as Param\[1\] on API 0x52

<a id="rst-param-2-5"></a>

#### Param\[2\]

Same as Param\[2\] on API 0x52

<a id="rst-param-3-4"></a>

#### Param\[3\]

width

<a id="rst-param-4-3"></a>

#### Param\[4\]

height

<a id="rst-param-5-2"></a>

#### Param\[5\]

destination pixel mask

<a id="rst-param-6-2"></a>

#### Param\[6\]

destination rectangle start address

<a id="rst-param-7-2"></a>

#### Param\[7\]

destination stride in dwords

<a id="rst-param-8-2"></a>

#### Param\[8\]

source stride in dwords

<a id="rst-param-9-1"></a>

#### Param\[9\]

source rectangle start address

<a id="rst-param-10"></a>

#### Param\[10\]

color fill value

<a id="rst-cx2341x-osd-set-framebuffer-window"></a>

### CX2341X_OSD_SET_FRAMEBUFFER_WINDOW

Enum: 86/0x56

<a id="rst-description-17"></a>

#### Description

Positions the main output window on the screen. The coordinates must be such that the entire window fits on the screen.

<a id="rst-param-0-10"></a>

#### Param\[0\]

window width

<a id="rst-param-1-7"></a>

#### Param\[1\]

window height

<a id="rst-param-2-6"></a>

#### Param\[2\]

top left window corner horizontal offset

<a id="rst-param-3-5"></a>

#### Param\[3\]

top left window corner vertical offset

<a id="rst-cx2341x-osd-set-chroma-key"></a>

### CX2341X_OSD_SET_CHROMA_KEY

Enum: 96/0x60

<a id="rst-description-18"></a>

#### Description

Chroma key switch and color

<a id="rst-param-0-11"></a>

#### Param\[0\]

state: 0=off, 1=on

<a id="rst-param-1-8"></a>

#### Param\[1\]

color

<a id="rst-cx2341x-osd-get-alpha-content-index"></a>

### CX2341X_OSD_GET_ALPHA_CONTENT_INDEX

Enum: 97/0x61

<a id="rst-description-19"></a>

#### Description

Retrieve alpha content index

<a id="rst-result-0-7"></a>

#### Result\[0\]

alpha content index, Range 0:15

<a id="rst-cx2341x-osd-set-alpha-content-index"></a>

### CX2341X_OSD_SET_ALPHA_CONTENT_INDEX

Enum: 98/0x62

<a id="rst-description-20"></a>

#### Description

Assign alpha content index

<a id="rst-param-0-12"></a>

#### Param\[0\]

alpha content index, range 0:15

<a id="rst-encoder-firmware-api-description"></a>

## Encoder firmware API description

<a id="rst-cx2341x-enc-ping-fw"></a>

### CX2341X_ENC_PING_FW

Enum: 128/0x80

<a id="rst-description-21"></a>

#### Description

Does nothing. Can be used to check if the firmware is responding.

<a id="rst-cx2341x-enc-start-capture"></a>

### CX2341X_ENC_START_CAPTURE

Enum: 129/0x81

<a id="rst-description-22"></a>

#### Description

Commences the capture of video, audio and/or VBI data. All encoding parameters must be initialized prior to this API call. Captures frames continuously or until a predefined number of frames have been captured.

<a id="rst-param-0-13"></a>

#### Param\[0\]

Capture stream type:

> - 0=MPEG
>
> - 1=Raw
>
> - 2=Raw passthrough
>
> - 3=VBI

<a id="rst-param-1-9"></a>

#### Param\[1\]

Bitmask:

> - Bit 0 when set, captures YUV
>
> - Bit 1 when set, captures PCM audio
>
> - Bit 2 when set, captures VBI (same as param\[0\]=3)
>
> - Bit 3 when set, the capture destination is the decoder (same as param\[0\]=2)
>
> - Bit 4 when set, the capture destination is the host

> [!NOTE]
>
> this parameter is only meaningful for RAW capture type.

<a id="rst-cx2341x-enc-stop-capture"></a>

### CX2341X_ENC_STOP_CAPTURE

Enum: 130/0x82

<a id="rst-description-23"></a>

#### Description

Ends a capture in progress

<a id="rst-param-0-14"></a>

#### Param\[0\]

- 0=stop at end of GOP (generates IRQ)

- 1=stop immediate (no IRQ)

<a id="rst-param-1-10"></a>

#### Param\[1\]

Stream type to stop, see param\[0\] of API 0x81

<a id="rst-param-2-7"></a>

#### Param\[2\]

Subtype, see param\[1\] of API 0x81

<a id="rst-cx2341x-enc-set-audio-id"></a>

### CX2341X_ENC_SET_AUDIO_ID

Enum: 137/0x89

<a id="rst-description-24"></a>

#### Description

Assigns the transport stream ID of the encoded audio stream

<a id="rst-param-0-15"></a>

#### Param\[0\]

Audio Stream ID

<a id="rst-cx2341x-enc-set-video-id"></a>

### CX2341X_ENC_SET_VIDEO_ID

Enum: 139/0x8B

<a id="rst-description-25"></a>

#### Description

Set video transport stream ID

<a id="rst-param-0-16"></a>

#### Param\[0\]

Video stream ID

<a id="rst-cx2341x-enc-set-pcr-id"></a>

### CX2341X_ENC_SET_PCR_ID

Enum: 141/0x8D

<a id="rst-description-26"></a>

#### Description

Assigns the transport stream ID for PCR packets

<a id="rst-param-0-17"></a>

#### Param\[0\]

PCR Stream ID

<a id="rst-cx2341x-enc-set-frame-rate"></a>

### CX2341X_ENC_SET_FRAME_RATE

Enum: 143/0x8F

<a id="rst-description-27"></a>

#### Description

Set video frames per second. Change occurs at start of new GOP.

<a id="rst-param-0-18"></a>

#### Param\[0\]

- 0=30fps

- 1=25fps

<a id="rst-cx2341x-enc-set-frame-size"></a>

### CX2341X_ENC_SET_FRAME_SIZE

Enum: 145/0x91

<a id="rst-description-28"></a>

#### Description

Select video stream encoding resolution.

<a id="rst-param-0-19"></a>

#### Param\[0\]

Height in lines. Default 480

<a id="rst-param-1-11"></a>

#### Param\[1\]

Width in pixels. Default 720

<a id="rst-cx2341x-enc-set-bit-rate"></a>

### CX2341X_ENC_SET_BIT_RATE

Enum: 149/0x95

<a id="rst-description-29"></a>

#### Description

Assign average video stream bitrate.

<a id="rst-param-0-20"></a>

#### Param\[0\]

0=variable bitrate, 1=constant bitrate

<a id="rst-param-1-12"></a>

#### Param\[1\]

bitrate in bits per second

<a id="rst-param-2-8"></a>

#### Param\[2\]

peak bitrate in bits per second, divided by 400

<a id="rst-param-3-6"></a>

#### Param\[3\]

Mux bitrate in bits per second, divided by 400. May be 0 (default).

<a id="rst-param-4-4"></a>

#### Param\[4\]

Rate Control VBR Padding

<a id="rst-param-5-3"></a>

#### Param\[5\]

VBV Buffer used by encoder

> [!NOTE]
>
> 1. Param\[3\] and Param\[4\] seem to be always 0
>
> 2. Param\[5\] doesn't seem to be used.

<a id="rst-cx2341x-enc-set-gop-properties"></a>

### CX2341X_ENC_SET_GOP_PROPERTIES

Enum: 151/0x97

<a id="rst-description-30"></a>

#### Description

Setup the GOP structure

<a id="rst-param-0-21"></a>

#### Param\[0\]

GOP size (maximum is 34)

<a id="rst-param-1-13"></a>

#### Param\[1\]

Number of B frames between the I and P frame, plus 1. For example: IBBPBBPBBPBB --&gt; GOP size: 12, number of B frames: 2+1 = 3

> [!NOTE]
>
> GOP size must be a multiple of (B-frames + 1).

<a id="rst-cx2341x-enc-set-aspect-ratio"></a>

### CX2341X_ENC_SET_ASPECT_RATIO

Enum: 153/0x99

<a id="rst-description-31"></a>

#### Description

Sets the encoding aspect ratio. Changes in the aspect ratio take effect at the start of the next GOP.

<a id="rst-param-0-22"></a>

#### Param\[0\]

- '0000' forbidden

- '0001' 1:1 square

- '0010' 4:3

- '0011' 16:9

- '0100' 2.21:1

- '0101' to '1111' reserved

<a id="rst-cx2341x-enc-set-dnr-filter-mode"></a>

### CX2341X_ENC_SET_DNR_FILTER_MODE

Enum: 155/0x9B

<a id="rst-description-32"></a>

#### Description

Assign Dynamic Noise Reduction operating mode

<a id="rst-param-0-23"></a>

#### Param\[0\]

Bit0: Spatial filter, set=auto, clear=manual Bit1: Temporal filter, set=auto, clear=manual

<a id="rst-param-1-14"></a>

#### Param\[1\]

Median filter:

- 0=Disabled

- 1=Horizontal

- 2=Vertical

- 3=Horiz/Vert

- 4=Diagonal

<a id="rst-cx2341x-enc-set-dnr-filter-props"></a>

### CX2341X_ENC_SET_DNR_FILTER_PROPS

Enum: 157/0x9D

<a id="rst-description-33"></a>

#### Description

These Dynamic Noise Reduction filter values are only meaningful when the respective filter is set to "manual" (See API 0x9B)

<a id="rst-param-0-24"></a>

#### Param\[0\]

Spatial filter: default 0, range 0:15

<a id="rst-param-1-15"></a>

#### Param\[1\]

Temporal filter: default 0, range 0:31

<a id="rst-cx2341x-enc-set-coring-levels"></a>

### CX2341X_ENC_SET_CORING_LEVELS

Enum: 159/0x9F

<a id="rst-description-34"></a>

#### Description

Assign Dynamic Noise Reduction median filter properties.

<a id="rst-param-0-25"></a>

#### Param\[0\]

Threshold above which the luminance median filter is enabled. Default: 0, range 0:255

<a id="rst-param-1-16"></a>

#### Param\[1\]

Threshold below which the luminance median filter is enabled. Default: 255, range 0:255

<a id="rst-param-2-9"></a>

#### Param\[2\]

Threshold above which the chrominance median filter is enabled. Default: 0, range 0:255

<a id="rst-param-3-7"></a>

#### Param\[3\]

Threshold below which the chrominance median filter is enabled. Default: 255, range 0:255

<a id="rst-cx2341x-enc-set-spatial-filter-type"></a>

### CX2341X_ENC_SET_SPATIAL_FILTER_TYPE

Enum: 161/0xA1

<a id="rst-description-35"></a>

#### Description

Assign spatial prefilter parameters

<a id="rst-param-0-26"></a>

#### Param\[0\]

Luminance filter

- 0=Off

- 1=1D Horizontal

- 2=1D Vertical

- 3=2D H/V Separable (default)

- 4=2D Symmetric non-separable

<a id="rst-param-1-17"></a>

#### Param\[1\]

Chrominance filter

- 0=Off

- 1=1D Horizontal (default)

<a id="rst-cx2341x-enc-set-vbi-line"></a>

### CX2341X_ENC_SET_VBI_LINE

Enum: 183/0xB7

<a id="rst-description-36"></a>

#### Description

Selects VBI line number.

<a id="rst-param-0-27"></a>

#### Param\[0\]

- Bits 0:4      line number

- Bit  31               0=top_field, 1=bottom_field

- Bits 0:31     all set specifies "all lines"

<a id="rst-param-1-18"></a>

#### Param\[1\]

VBI line information features: 0=disabled, 1=enabled

<a id="rst-param-2-10"></a>

#### Param\[2\]

Slicing: 0=None, 1=Closed Caption Almost certainly not implemented. Set to 0.

<a id="rst-param-3-8"></a>

#### Param\[3\]

Luminance samples in this line. Almost certainly not implemented. Set to 0.

<a id="rst-param-4-5"></a>

#### Param\[4\]

Chrominance samples in this line Almost certainly not implemented. Set to 0.

<a id="rst-cx2341x-enc-set-stream-type"></a>

### CX2341X_ENC_SET_STREAM_TYPE

Enum: 185/0xB9

<a id="rst-description-37"></a>

#### Description

Assign stream type

> [!NOTE]
>
> Transport stream is not working in recent firmwares. And in older firmwares the timestamps in the TS seem to be unreliable.

<a id="rst-param-0-28"></a>

#### Param\[0\]

- 0=Program stream

- 1=Transport stream

- 2=MPEG1 stream

- 3=PES A/V stream

- 5=PES Video stream

- 7=PES Audio stream

- 10=DVD stream

- 11=VCD stream

- 12=SVCD stream

- 13=DVD_S1 stream

- 14=DVD_S2 stream

<a id="rst-cx2341x-enc-set-output-port"></a>

### CX2341X_ENC_SET_OUTPUT_PORT

Enum: 187/0xBB

<a id="rst-description-38"></a>

#### Description

Assign stream output port. Normally 0 when the data is copied through the PCI bus (DMA), and 1 when the data is streamed to another chip (pvrusb and cx88-blackbird).

<a id="rst-param-0-29"></a>

#### Param\[0\]

- 0=Memory (default)

- 1=Streaming

- 2=Serial

<a id="rst-param-1-19"></a>

#### Param\[1\]

Unknown, but leaving this to 0 seems to work best. Indications are that this might have to do with USB support, although passing anything but 0 only breaks things.

<a id="rst-cx2341x-enc-set-audio-properties"></a>

### CX2341X_ENC_SET_AUDIO_PROPERTIES

Enum: 189/0xBD

<a id="rst-description-39"></a>

#### Description

Set audio stream properties, may be called while encoding is in progress.

> [!NOTE]
>
> All bitfields are consistent with ISO11172 documentation except bits 2:3 which ISO docs define as:
>
> - '11' Layer I
>
> - '10' Layer II
>
> - '01' Layer III
>
> - '00' Undefined
>
> This discrepancy may indicate a possible error in the documentation. Testing indicated that only Layer II is actually working, and that the minimum bitrate should be 192 kbps.

<a id="rst-param-0-30"></a>

#### Param\[0\]

Bitmask:



```none
 0:1  '00' 44.1Khz
      '01' 48Khz
      '10' 32Khz
      '11' reserved

 2:3  '01'=Layer I
      '10'=Layer II

 4:7  Bitrate:
           Index | Layer I     | Layer II
           ------+-------------+------------
          '0000' | free format | free format
          '0001' |  32 kbit/s  |  32 kbit/s
          '0010' |  64 kbit/s  |  48 kbit/s
          '0011' |  96 kbit/s  |  56 kbit/s
          '0100' | 128 kbit/s  |  64 kbit/s
          '0101' | 160 kbit/s  |  80 kbit/s
          '0110' | 192 kbit/s  |  96 kbit/s
          '0111' | 224 kbit/s  | 112 kbit/s
          '1000' | 256 kbit/s  | 128 kbit/s
          '1001' | 288 kbit/s  | 160 kbit/s
          '1010' | 320 kbit/s  | 192 kbit/s
          '1011' | 352 kbit/s  | 224 kbit/s
          '1100' | 384 kbit/s  | 256 kbit/s
          '1101' | 416 kbit/s  | 320 kbit/s
          '1110' | 448 kbit/s  | 384 kbit/s

      .. note::

              For Layer II, not all combinations of total bitrate
              and mode are allowed. See ISO11172-3 3-Annex B,
              Table 3-B.2

 8:9  '00'=Stereo
      '01'=JointStereo
      '10'=Dual
      '11'=Mono

      .. note::

              The cx23415 cannot decode Joint Stereo properly.

10:11 Mode Extension used in joint_stereo mode.
      In Layer I and II they indicate which subbands are in
      intensity_stereo. All other subbands are coded in stereo.
          '00' subbands 4-31 in intensity_stereo, bound==4
          '01' subbands 8-31 in intensity_stereo, bound==8
          '10' subbands 12-31 in intensity_stereo, bound==12
          '11' subbands 16-31 in intensity_stereo, bound==16

12:13 Emphasis:
          '00' None
          '01' 50/15uS
          '10' reserved
          '11' CCITT J.17

14    CRC:
          '0' off
          '1' on

15    Copyright:
          '0' off
          '1' on

16    Generation:
          '0' copy
          '1' original
```

<a id="rst-cx2341x-enc-halt-fw"></a>

### CX2341X_ENC_HALT_FW

Enum: 195/0xC3

<a id="rst-description-40"></a>

#### Description

The firmware is halted and no further API calls are serviced until the firmware is uploaded again.

<a id="rst-cx2341x-enc-get-version"></a>

### CX2341X_ENC_GET_VERSION

Enum: 196/0xC4

<a id="rst-description-41"></a>

#### Description

Returns the version of the encoder firmware.

<a id="rst-result-0-8"></a>

#### Result\[0\]

Version bitmask: - Bits  0:15 build - Bits 16:23 minor - Bits 24:31 major

<a id="rst-cx2341x-enc-set-gop-closure"></a>

### CX2341X_ENC_SET_GOP_CLOSURE

Enum: 197/0xC5

<a id="rst-description-42"></a>

#### Description

Assigns the GOP open/close property.

<a id="rst-param-0-31"></a>

#### Param\[0\]

- 0=Open

- 1=Closed

<a id="rst-cx2341x-enc-get-seq-end"></a>

### CX2341X_ENC_GET_SEQ_END

Enum: 198/0xC6

<a id="rst-description-43"></a>

#### Description

Obtains the sequence end code of the encoder's buffer. When a capture is started a number of interrupts are still generated, the last of which will have Result\[0\] set to 1 and Result\[1\] will contain the size of the buffer.

<a id="rst-result-0-9"></a>

#### Result\[0\]

State of the transfer (1 if last buffer)

<a id="rst-result-1-4"></a>

#### Result\[1\]

If Result\[0\] is 1, this contains the size of the last buffer, undefined otherwise.

<a id="rst-cx2341x-enc-set-pgm-index-info"></a>

### CX2341X_ENC_SET_PGM_INDEX_INFO

Enum: 199/0xC7

<a id="rst-description-44"></a>

#### Description

Sets the Program Index Information. The information is stored as follows:



```c
struct info {
        u32 length;             // Length of this frame
        u32 offset_low;         // Offset in the file of the
        u32 offset_high;        // start of this frame
        u32 mask1;              // Bits 0-2 are the type mask:
                                // 1=I, 2=P, 4=B
                                // 0=End of Program Index, other fields
                                //   are invalid.
        u32 pts;                // The PTS of the frame
        u32 mask2;              // Bit 0 is bit 32 of the pts.
};
u32 table_ptr;
struct info index[400];
```

The table_ptr is the encoder memory address in the table were *new* entries will be written.

> [!NOTE]
>
> This is a ringbuffer, so the table_ptr will wraparound.

<a id="rst-param-0-32"></a>

#### Param\[0\]

Picture Mask: - 0=No index capture - 1=I frames - 3=I,P frames - 7=I,P,B frames

(Seems to be ignored, it always indexes I, P and B frames)

<a id="rst-param-1-20"></a>

#### Param\[1\]

Elements requested (up to 400)

<a id="rst-result-0-10"></a>

#### Result\[0\]

Offset in the encoder memory of the start of the table.

<a id="rst-result-1-5"></a>

#### Result\[1\]

Number of allocated elements up to a maximum of Param\[1\]

<a id="rst-cx2341x-enc-set-vbi-config"></a>

### CX2341X_ENC_SET_VBI_CONFIG

Enum: 200/0xC8

<a id="rst-description-45"></a>

#### Description

Configure VBI settings

<a id="rst-param-0-33"></a>

#### Param\[0\]

Bitmap:



```none
0    Mode '0' Sliced, '1' Raw
1:3  Insertion:
         '000' insert in extension & user data
         '001' insert in private packets
         '010' separate stream and user data
         '111' separate stream and private data
8:15 Stream ID (normally 0xBD)
```

<a id="rst-param-1-21"></a>

#### Param\[1\]

Frames per interrupt (max 8). Only valid in raw mode.

<a id="rst-param-2-11"></a>

#### Param\[2\]

Total raw VBI frames. Only valid in raw mode.

<a id="rst-param-3-9"></a>

#### Param\[3\]

Start codes

<a id="rst-param-4-6"></a>

#### Param\[4\]

Stop codes

<a id="rst-param-5-4"></a>

#### Param\[5\]

Lines per frame

<a id="rst-param-6-3"></a>

#### Param\[6\]

Byte per line

<a id="rst-result-0-11"></a>

#### Result\[0\]

Observed frames per interrupt in raw mode only. Rage 1 to Param\[1\]

<a id="rst-result-1-6"></a>

#### Result\[1\]

Observed number of frames in raw mode. Range 1 to Param\[2\]

<a id="rst-result-2-2"></a>

#### Result\[2\]

Memory offset to start or raw VBI data

<a id="rst-cx2341x-enc-set-dma-block-size"></a>

### CX2341X_ENC_SET_DMA_BLOCK_SIZE

Enum: 201/0xC9

<a id="rst-description-46"></a>

#### Description

Set DMA transfer block size

<a id="rst-param-0-34"></a>

#### Param\[0\]

DMA transfer block size in bytes or frames. When unit is bytes, supported block sizes are 2^7, 2^8 and 2^9 bytes.

<a id="rst-param-1-22"></a>

#### Param\[1\]

Unit: 0=bytes, 1=frames

<a id="rst-cx2341x-enc-get-prev-dma-info-mb-10"></a>

### CX2341X_ENC_GET_PREV_DMA_INFO_MB_10

Enum: 202/0xCA

<a id="rst-description-47"></a>

#### Description

Returns information on the previous DMA transfer in conjunction with bit 27 of the interrupt mask. Uses mailbox 10.

<a id="rst-result-0-12"></a>

#### Result\[0\]

Type of stream

<a id="rst-result-1-7"></a>

#### Result\[1\]

Address Offset

<a id="rst-result-2-3"></a>

#### Result\[2\]

Maximum size of transfer

<a id="rst-cx2341x-enc-get-prev-dma-info-mb-9"></a>

### CX2341X_ENC_GET_PREV_DMA_INFO_MB_9

Enum: 203/0xCB

<a id="rst-description-48"></a>

#### Description

Returns information on the previous DMA transfer in conjunction with bit 27 or 18 of the interrupt mask. Uses mailbox 9.

<a id="rst-result-0-13"></a>

#### Result\[0\]

Status bits: - 0   read completed - 1   write completed - 2   DMA read error - 3   DMA write error - 4   Scatter-Gather array error

<a id="rst-result-1-8"></a>

#### Result\[1\]

DMA type

<a id="rst-result-2-4"></a>

#### Result\[2\]

Presentation Time Stamp bits 0..31

<a id="rst-result-3-2"></a>

#### Result\[3\]

Presentation Time Stamp bit 32

<a id="rst-cx2341x-enc-sched-dma-to-host"></a>

### CX2341X_ENC_SCHED_DMA_TO_HOST

Enum: 204/0xCC

<a id="rst-description-49"></a>

#### Description

Setup DMA to host operation

<a id="rst-param-0-35"></a>

#### Param\[0\]

Memory address of link list

<a id="rst-param-1-23"></a>

#### Param\[1\]

Length of link list (wtf: what units ???)

<a id="rst-param-2-12"></a>

#### Param\[2\]

DMA type (0=MPEG)

<a id="rst-cx2341x-enc-initialize-input"></a>

### CX2341X_ENC_INITIALIZE_INPUT

Enum: 205/0xCD

<a id="rst-description-50"></a>

#### Description

Initializes the video input

<a id="rst-cx2341x-enc-set-frame-drop-rate"></a>

### CX2341X_ENC_SET_FRAME_DROP_RATE

Enum: 208/0xD0

<a id="rst-description-51"></a>

#### Description

For each frame captured, skip specified number of frames.

<a id="rst-param-0-36"></a>

#### Param\[0\]

Number of frames to skip

<a id="rst-cx2341x-enc-pause-encoder"></a>

### CX2341X_ENC_PAUSE_ENCODER

Enum: 210/0xD2

<a id="rst-description-52"></a>

#### Description

During a pause condition, all frames are dropped instead of being encoded.

<a id="rst-param-0-37"></a>

#### Param\[0\]

- 0=Pause encoding

- 1=Continue encoding

<a id="rst-cx2341x-enc-refresh-input"></a>

### CX2341X_ENC_REFRESH_INPUT

Enum: 211/0xD3

<a id="rst-description-53"></a>

#### Description

Refreshes the video input

<a id="rst-cx2341x-enc-set-copyright"></a>

### CX2341X_ENC_SET_COPYRIGHT

Enum: 212/0xD4

<a id="rst-description-54"></a>

#### Description

Sets stream copyright property

<a id="rst-param-0-38"></a>

#### Param\[0\]

- 0=Stream is not copyrighted

- 1=Stream is copyrighted

<a id="rst-cx2341x-enc-set-event-notification"></a>

### CX2341X_ENC_SET_EVENT_NOTIFICATION

Enum: 213/0xD5

<a id="rst-description-55"></a>

#### Description

Setup firmware to notify the host about a particular event. Host must unmask the interrupt bit.

<a id="rst-param-0-39"></a>

#### Param\[0\]

Event (0=refresh encoder input)

<a id="rst-param-1-24"></a>

#### Param\[1\]

Notification 0=disabled 1=enabled

<a id="rst-param-2-13"></a>

#### Param\[2\]

Interrupt bit

<a id="rst-param-3-10"></a>

#### Param\[3\]

Mailbox slot, -1 if no mailbox required.

<a id="rst-cx2341x-enc-set-num-vsync-lines"></a>

### CX2341X_ENC_SET_NUM_VSYNC_LINES

Enum: 214/0xD6

<a id="rst-description-56"></a>

#### Description

Depending on the analog video decoder used, this assigns the number of lines for field 1 and 2.

<a id="rst-param-0-40"></a>

#### Param\[0\]

Field 1 number of lines: - 0x00EF for SAA7114 - 0x00F0 for SAA7115 - 0x0105 for Micronas

<a id="rst-param-1-25"></a>

#### Param\[1\]

Field 2 number of lines: - 0x00EF for SAA7114 - 0x00F0 for SAA7115 - 0x0106 for Micronas

<a id="rst-cx2341x-enc-set-placeholder"></a>

### CX2341X_ENC_SET_PLACEHOLDER

Enum: 215/0xD7

<a id="rst-description-57"></a>

#### Description

Provides a mechanism of inserting custom user data in the MPEG stream.

<a id="rst-param-0-41"></a>

#### Param\[0\]

- 0=extension &amp; user data

- 1=private packet with stream ID 0xBD

<a id="rst-param-1-26"></a>

#### Param\[1\]

Rate at which to insert data, in units of frames (for private packet) or GOPs (for ext. &amp; user data)

<a id="rst-param-2-14"></a>

#### Param\[2\]

Number of data DWORDs (below) to insert

<a id="rst-param-3-11"></a>

#### Param\[3\]

Custom data 0

<a id="rst-param-4-7"></a>

#### Param\[4\]

Custom data 1

<a id="rst-param-5-5"></a>

#### Param\[5\]

Custom data 2

<a id="rst-param-6-4"></a>

#### Param\[6\]

Custom data 3

<a id="rst-param-7-3"></a>

#### Param\[7\]

Custom data 4

<a id="rst-param-8-3"></a>

#### Param\[8\]

Custom data 5

<a id="rst-param-9-2"></a>

#### Param\[9\]

Custom data 6

<a id="rst-param-10-1"></a>

#### Param\[10\]

Custom data 7

<a id="rst-param-11"></a>

#### Param\[11\]

Custom data 8

<a id="rst-cx2341x-enc-mute-video"></a>

### CX2341X_ENC_MUTE_VIDEO

Enum: 217/0xD9

<a id="rst-description-58"></a>

#### Description

Video muting

<a id="rst-param-0-42"></a>

#### Param\[0\]

Bit usage:



```none
 0      '0'=video not muted
        '1'=video muted, creates frames with the YUV color defined below
 1:7    Unused
 8:15   V chrominance information
16:23   U chrominance information
24:31   Y luminance information
```

<a id="rst-cx2341x-enc-mute-audio"></a>

### CX2341X_ENC_MUTE_AUDIO

Enum: 218/0xDA

<a id="rst-description-59"></a>

#### Description

Audio muting

<a id="rst-param-0-43"></a>

#### Param\[0\]

- 0=audio not muted

- 1=audio muted (produces silent mpeg audio stream)

<a id="rst-cx2341x-enc-set-vert-crop-line"></a>

### CX2341X_ENC_SET_VERT_CROP_LINE

Enum: 219/0xDB

<a id="rst-description-60"></a>

#### Description

Something to do with 'Vertical Crop Line'

<a id="rst-param-0-44"></a>

#### Param\[0\]

If saa7114 and raw VBI capture and 60 Hz, then set to 10001. Else 0.

<a id="rst-cx2341x-enc-misc"></a>

### CX2341X_ENC_MISC

Enum: 220/0xDC

<a id="rst-description-61"></a>

#### Description

Miscellaneous actions. Not known for 100% what it does. It's really a sort of ioctl call. The first parameter is a command number, the second the value.

<a id="rst-param-0-45"></a>

#### Param\[0\]

Command number:



```none
 1=set initial SCR value when starting encoding (works).
 2=set quality mode (apparently some test setting).
 3=setup advanced VIM protection handling.
   Always 1 for the cx23416 and 0 for cx23415.
 4=generate DVD compatible PTS timestamps
 5=USB flush mode
 6=something to do with the quantization matrix
 7=set navigation pack insertion for DVD: adds 0xbf (private stream 2)
   packets to the MPEG. The size of these packets is 2048 bytes (including
   the header of 6 bytes: 0x000001bf + length). The payload is zeroed and
   it is up to the application to fill them in. These packets are apparently
   inserted every four frames.
 8=enable scene change detection (seems to be a failure)
 9=set history parameters of the video input module
10=set input field order of VIM
11=set quantization matrix
12=reset audio interface after channel change or input switch (has no argument).
   Needed for the cx2584x, not needed for the mspx4xx, but it doesn't seem to
   do any harm calling it regardless.
13=set audio volume delay
14=set audio delay
```

<a id="rst-param-1-27"></a>

#### Param\[1\]

Command value.

<a id="rst-decoder-firmware-api-description"></a>

## Decoder firmware API description

> [!NOTE]
>
> this API is part of the decoder firmware, so it's cx23415 only.

<a id="rst-cx2341x-dec-ping-fw"></a>

### CX2341X_DEC_PING_FW

Enum: 0/0x00

<a id="rst-description-62"></a>

#### Description

This API call does nothing. It may be used to check if the firmware is responding.

<a id="rst-cx2341x-dec-start-playback"></a>

### CX2341X_DEC_START_PLAYBACK

Enum: 1/0x01

<a id="rst-description-63"></a>

#### Description

Begin or resume playback.

<a id="rst-param-0-46"></a>

#### Param\[0\]

0 based frame number in GOP to begin playback from.

<a id="rst-param-1-28"></a>

#### Param\[1\]

Specifies the number of muted audio frames to play before normal audio resumes. (This is not implemented in the firmware, leave at 0)

<a id="rst-cx2341x-dec-stop-playback"></a>

### CX2341X_DEC_STOP_PLAYBACK

Enum: 2/0x02

<a id="rst-description-64"></a>

#### Description

Ends playback and clears all decoder buffers. If PTS is not zero, playback stops at specified PTS.

<a id="rst-param-0-47"></a>

#### Param\[0\]

Display 0=last frame, 1=black

> [!NOTE]
>
> this takes effect immediately, so if you want to wait for a PTS, then use '0', otherwise the screen goes to black at once. You can call this later (even if there is no playback) with a 1 value to set the screen to black.

<a id="rst-param-1-29"></a>

#### Param\[1\]

PTS low

<a id="rst-param-2-15"></a>

#### Param\[2\]

PTS high

<a id="rst-cx2341x-dec-set-playback-speed"></a>

### CX2341X_DEC_SET_PLAYBACK_SPEED

Enum: 3/0x03

<a id="rst-description-65"></a>

#### Description

Playback stream at speed other than normal. There are two modes of operation:

> - Smooth: host transfers entire stream and firmware drops unused frames.
>
> - Coarse: host drops frames based on indexing as required to achieve desired speed.

<a id="rst-param-0-48"></a>

#### Param\[0\]



```none
Bitmap:
    0:7  0 normal
         1 fast only "1.5 times"
         n nX fast, 1/nX slow
    30   Framedrop:
             '0' during 1.5 times play, every other B frame is dropped
             '1' during 1.5 times play, stream is unchanged (bitrate
                 must not exceed 8mbps)
    31   Speed:
             '0' slow
             '1' fast
```

> [!NOTE]
>
> n is limited to 2. Anything higher does not result in faster playback. Instead the host should start dropping frames.

<a id="rst-param-1-30"></a>

#### Param\[1\]

Direction: 0=forward, 1=reverse

> [!NOTE]
>
> to make reverse playback work you have to write full GOPs in reverse order.

<a id="rst-param-2-16"></a>

#### Param\[2\]



```none
Picture mask:
    1=I frames
    3=I, P frames
    7=I, P, B frames
```

<a id="rst-param-3-12"></a>

#### Param\[3\]

B frames per GOP (for reverse play only)

> [!NOTE]
>
> for reverse playback the Picture Mask should be set to I or I, P. Adding B frames to the mask will result in corrupt video. This field has to be set to the correct value in order to keep the timing correct.

<a id="rst-param-4-8"></a>

#### Param\[4\]

Mute audio: 0=disable, 1=enable

<a id="rst-param-5-6"></a>

#### Param\[5\]

Display 0=frame, 1=field

<a id="rst-param-6-5"></a>

#### Param\[6\]

Specifies the number of muted audio frames to play before normal audio resumes. (Not implemented in the firmware, leave at 0)

<a id="rst-cx2341x-dec-step-video"></a>

### CX2341X_DEC_STEP_VIDEO

Enum: 5/0x05

<a id="rst-description-66"></a>

#### Description

Each call to this API steps the playback to the next unit defined below in the current playback direction.

<a id="rst-param-0-49"></a>

#### Param\[0\]

0=frame, 1=top field, 2=bottom field

<a id="rst-cx2341x-dec-set-dma-block-size"></a>

### CX2341X_DEC_SET_DMA_BLOCK_SIZE

Enum: 8/0x08

<a id="rst-description-67"></a>

#### Description

Set DMA transfer block size. Counterpart to API 0xC9

<a id="rst-param-0-50"></a>

#### Param\[0\]

DMA transfer block size in bytes. A different size may be specified when issuing the DMA transfer command.

<a id="rst-cx2341x-dec-get-xfer-info"></a>

### CX2341X_DEC_GET_XFER_INFO

Enum: 9/0x09

<a id="rst-description-68"></a>

#### Description

This API call may be used to detect an end of stream condition.

<a id="rst-result-0-14"></a>

#### Result\[0\]

Stream type

<a id="rst-result-1-9"></a>

#### Result\[1\]

Address offset

<a id="rst-result-2-5"></a>

#### Result\[2\]

Maximum bytes to transfer

<a id="rst-result-3-3"></a>

#### Result\[3\]

Buffer fullness

<a id="rst-cx2341x-dec-get-dma-status"></a>

### CX2341X_DEC_GET_DMA_STATUS

Enum: 10/0x0A

<a id="rst-description-69"></a>

#### Description

Status of the last DMA transfer

<a id="rst-result-0-15"></a>

#### Result\[0\]

Bit 1 set means transfer complete Bit 2 set means DMA error Bit 3 set means linked list error

<a id="rst-result-1-10"></a>

#### Result\[1\]

DMA type: 0=MPEG, 1=OSD, 2=YUV

<a id="rst-cx2341x-dec-sched-dma-from-host"></a>

### CX2341X_DEC_SCHED_DMA_FROM_HOST

Enum: 11/0x0B

<a id="rst-description-70"></a>

#### Description

Setup DMA from host operation. Counterpart to API 0xCC

<a id="rst-param-0-51"></a>

#### Param\[0\]

Memory address of link list

<a id="rst-param-1-31"></a>

#### Param\[1\]

Total \# of bytes to transfer

<a id="rst-param-2-17"></a>

#### Param\[2\]

DMA type (0=MPEG, 1=OSD, 2=YUV)

<a id="rst-cx2341x-dec-pause-playback"></a>

### CX2341X_DEC_PAUSE_PLAYBACK

Enum: 13/0x0D

<a id="rst-description-71"></a>

#### Description

Freeze playback immediately. In this mode, when internal buffers are full, no more data will be accepted and data request IRQs will be masked.

<a id="rst-param-0-52"></a>

#### Param\[0\]

Display: 0=last frame, 1=black

<a id="rst-cx2341x-dec-halt-fw"></a>

### CX2341X_DEC_HALT_FW

Enum: 14/0x0E

<a id="rst-description-72"></a>

#### Description

The firmware is halted and no further API calls are serviced until the firmware is uploaded again.

<a id="rst-cx2341x-dec-set-standard"></a>

### CX2341X_DEC_SET_STANDARD

Enum: 16/0x10

<a id="rst-description-73"></a>

#### Description

Selects display standard

<a id="rst-param-0-53"></a>

#### Param\[0\]

0=NTSC, 1=PAL

<a id="rst-cx2341x-dec-get-version"></a>

### CX2341X_DEC_GET_VERSION

Enum: 17/0x11

<a id="rst-description-74"></a>

#### Description

Returns decoder firmware version information

<a id="rst-result-0-16"></a>

#### Result\[0\]

- **Version bitmask:**

  - Bits  0:15 build

  - Bits 16:23 minor

  - Bits 24:31 major

<a id="rst-cx2341x-dec-set-stream-input"></a>

### CX2341X_DEC_SET_STREAM_INPUT

Enum: 20/0x14

<a id="rst-description-75"></a>

#### Description

Select decoder stream input port

<a id="rst-param-0-54"></a>

#### Param\[0\]

0=memory (default), 1=streaming

<a id="rst-cx2341x-dec-get-timing-info"></a>

### CX2341X_DEC_GET_TIMING_INFO

Enum: 21/0x15

<a id="rst-description-76"></a>

#### Description

Returns timing information from start of playback

<a id="rst-result-0-17"></a>

#### Result\[0\]

Frame count by decode order

<a id="rst-result-1-11"></a>

#### Result\[1\]

Video PTS bits 0:31 by display order

<a id="rst-result-2-6"></a>

#### Result\[2\]

Video PTS bit 32 by display order

<a id="rst-result-3-4"></a>

#### Result\[3\]

SCR bits 0:31 by display order

<a id="rst-result-4-1"></a>

#### Result\[4\]

SCR bit 32 by display order

<a id="rst-cx2341x-dec-set-audio-mode"></a>

### CX2341X_DEC_SET_AUDIO_MODE

Enum: 22/0x16

<a id="rst-description-77"></a>

#### Description

Select audio mode

<a id="rst-param-0-55"></a>

#### Param\[0\]

- **Dual mono mode action**

  0=Stereo, 1=Left, 2=Right, 3=Mono, 4=Swap, -1=Unchanged

<a id="rst-param-1-32"></a>

#### Param\[1\]

- **Stereo mode action:**

  0=Stereo, 1=Left, 2=Right, 3=Mono, 4=Swap, -1=Unchanged

<a id="rst-cx2341x-dec-set-event-notification"></a>

### CX2341X_DEC_SET_EVENT_NOTIFICATION

Enum: 23/0x17

<a id="rst-description-78"></a>

#### Description

Setup firmware to notify the host about a particular event. Counterpart to API 0xD5

<a id="rst-param-0-56"></a>

#### Param\[0\]

- **Event:**

  - 0=Audio mode change between mono, (joint) stereo and dual channel.

  - 3=Decoder started

  - 4=Unknown: goes off 10-15 times per second while decoding.

  - 5=Some sync event: goes off once per frame.

<a id="rst-param-1-33"></a>

#### Param\[1\]

Notification 0=disabled, 1=enabled

<a id="rst-param-2-18"></a>

#### Param\[2\]

Interrupt bit

<a id="rst-param-3-13"></a>

#### Param\[3\]

Mailbox slot, -1 if no mailbox required.

<a id="rst-cx2341x-dec-set-display-buffers"></a>

### CX2341X_DEC_SET_DISPLAY_BUFFERS

Enum: 24/0x18

<a id="rst-description-79"></a>

#### Description

Number of display buffers. To decode all frames in reverse playback you must use nine buffers.

<a id="rst-param-0-57"></a>

#### Param\[0\]

0=six buffers, 1=nine buffers

<a id="rst-cx2341x-dec-extract-vbi"></a>

### CX2341X_DEC_EXTRACT_VBI

Enum: 25/0x19

<a id="rst-description-80"></a>

#### Description

Extracts VBI data

<a id="rst-param-0-58"></a>

#### Param\[0\]

0=extract from extension &amp; user data, 1=extract from private packets

<a id="rst-result-0-18"></a>

#### Result\[0\]

VBI table location

<a id="rst-result-1-12"></a>

#### Result\[1\]

VBI table size

<a id="rst-cx2341x-dec-set-decoder-source"></a>

### CX2341X_DEC_SET_DECODER_SOURCE

Enum: 26/0x1A

<a id="rst-description-81"></a>

#### Description

Selects decoder source. Ensure that the parameters passed to this API match the encoder settings.

<a id="rst-param-0-59"></a>

#### Param\[0\]

Mode: 0=MPEG from host, 1=YUV from encoder, 2=YUV from host

<a id="rst-param-1-34"></a>

#### Param\[1\]

YUV picture width

<a id="rst-param-2-19"></a>

#### Param\[2\]

YUV picture height

<a id="rst-param-3-14"></a>

#### Param\[3\]

Bitmap: see Param\[0\] of API 0xBD

<a id="rst-cx2341x-dec-set-prebuffering"></a>

### CX2341X_DEC_SET_PREBUFFERING

Enum: 30/0x1E

<a id="rst-description-82"></a>

#### Description

Decoder prebuffering, when enabled up to 128KB are buffered for streams &lt;8mpbs or 640KB for streams &gt;8mbps

<a id="rst-param-0-60"></a>

#### Param\[0\]

0=off, 1=on

<a id="rst-pvr350-video-decoder-registers-0x02002800-0x02002b00"></a>

## PVR350 Video decoder registers 0x02002800 -&gt; 0x02002B00

Author: Ian Armstrong &lt;[ian@iarmst.demon.co.uk](<mailto:ian@iarmst.demon.co.uk>)&gt;

Version: v0.4

Date: 12 March 2007

This list has been worked out through trial and error. There will be mistakes and omissions. Some registers have no obvious effect so it's hard to say what they do, while others interact with each other, or require a certain load sequence. Horizontal filter setup is one example, with six registers working in unison and requiring a certain load sequence to correctly configure. The indexed colour palette is much easier to set at just two registers, but again it requires a certain load sequence.

Some registers are fussy about what they are set to. Load in a bad value &amp; the decoder will fail. A firmware reload will often recover, but sometimes a reset is required. For registers containing size information, setting them to 0 is generally a bad idea. For other control registers i.e. 2878, you'll only find out what values are bad when it hangs.



```none
--------------------------------------------------------------------------------
2800
bit 0
        Decoder enable
        0 = disable
        1 = enable
--------------------------------------------------------------------------------
2804
bits 0:31
        Decoder horizontal Y alias register 1
---------------
2808
bits 0:31
        Decoder horizontal Y alias register 2
---------------
280C
bits 0:31
        Decoder horizontal Y alias register 3
---------------
2810
bits 0:31
        Decoder horizontal Y alias register 4
---------------
2814
bits 0:31
        Decoder horizontal Y alias register 5
---------------
2818
bits 0:31
        Decoder horizontal Y alias trigger

These six registers control the horizontal aliasing filter for the Y plane.
The first five registers must all be loaded before accessing the trigger
(2818), as this register actually clocks the data through for the first
five.

To correctly program set the filter, this whole procedure must be done 16
times. The actual register contents are copied from a lookup-table in the
firmware which contains 4 different filter settings.

--------------------------------------------------------------------------------
281C
bits 0:31
        Decoder horizontal UV alias register 1
---------------
2820
bits 0:31
        Decoder horizontal UV alias register 2
---------------
2824
bits 0:31
        Decoder horizontal UV alias register 3
---------------
2828
bits 0:31
        Decoder horizontal UV alias register 4
---------------
282C
bits 0:31
        Decoder horizontal UV alias register 5
---------------
2830
bits 0:31
        Decoder horizontal UV alias trigger

These six registers control the horizontal aliasing for the UV plane.
Operation is the same as the Y filter, with 2830 being the trigger
register.

--------------------------------------------------------------------------------
2834
bits 0:15
        Decoder Y source width in pixels

bits 16:31
        Decoder Y destination width in pixels
---------------
2838
bits 0:15
        Decoder UV source width in pixels

bits 16:31
        Decoder UV destination width in pixels

NOTE: For both registers, the resulting image must be fully visible on
screen. If the image exceeds the right edge both the source and destination
size must be adjusted to reflect the visible portion. For the source width,
you must take into account the scaling when calculating the new value.
--------------------------------------------------------------------------------

283C
bits 0:31
        Decoder Y horizontal scaling
                Normally = Reg 2854 >> 2
---------------
2840
bits 0:31
        Decoder ?? unknown - horizontal scaling
        Usually 0x00080514
---------------
2844
bits 0:31
        Decoder UV horizontal scaling
        Normally = Reg 2854 >> 2
---------------
2848
bits 0:31
        Decoder ?? unknown - horizontal scaling
        Usually 0x00100514
---------------
284C
bits 0:31
        Decoder ?? unknown - Y plane
        Usually 0x00200020
---------------
2850
bits 0:31
        Decoder ?? unknown - UV plane
        Usually 0x00200020
---------------
2854
bits 0:31
        Decoder 'master' value for horizontal scaling
---------------
2858
bits 0:31
        Decoder ?? unknown
        Usually 0
---------------
285C
bits 0:31
        Decoder ?? unknown
        Normally = Reg 2854 >> 1
---------------
2860
bits 0:31
        Decoder ?? unknown
        Usually 0
---------------
2864
bits 0:31
        Decoder ?? unknown
        Normally = Reg 2854 >> 1
---------------
2868
bits 0:31
        Decoder ?? unknown
        Usually 0

Most of these registers either control horizontal scaling, or appear linked
to it in some way. Register 2854 contains the 'master' value & the other
registers can be calculated from that one. You must also remember to
correctly set the divider in Reg 2874.

To enlarge:
        Reg 2854 = (source_width * 0x00200000) / destination_width
        Reg 2874 = No divide

To reduce from full size down to half size:
        Reg 2854 = (source_width/2 * 0x00200000) / destination width
        Reg 2874 = Divide by 2

To reduce from half size down to quarter size:
        Reg 2854 = (source_width/4 * 0x00200000) / destination width
        Reg 2874 = Divide by 4

The result is always rounded up.

--------------------------------------------------------------------------------
286C
bits 0:15
        Decoder horizontal Y buffer offset

bits 15:31
        Decoder horizontal UV buffer offset

Offset into the video image buffer. If the offset is gradually incremented,
the on screen image will move left & wrap around higher up on the right.

--------------------------------------------------------------------------------
2870
bits 0:15
        Decoder horizontal Y output offset

bits 16:31
        Decoder horizontal UV output offset

Offsets the actual video output. Controls output alignment of the Y & UV
planes. The higher the value, the greater the shift to the left. Use
reg 2890 to move the image right.

--------------------------------------------------------------------------------
2874
bits 0:1
        Decoder horizontal Y output size divider
        00 = No divide
        01 = Divide by 2
        10 = Divide by 3

bits 4:5
        Decoder horizontal UV output size divider
        00 = No divide
        01 = Divide by 2
        10 = Divide by 3

bit 8
        Decoder ?? unknown
        0 = Normal
        1 = Affects video output levels

bit 16
        Decoder ?? unknown
        0 = Normal
        1 = Disable horizontal filter

--------------------------------------------------------------------------------
2878
bit 0
        ?? unknown

bit 1
        osd on/off
        0 = osd off
        1 = osd on

bit 2
        Decoder + osd video timing
        0 = NTSC
        1 = PAL

bits 3:4
        ?? unknown

bit 5
        Decoder + osd
        Swaps upper & lower fields

--------------------------------------------------------------------------------
287C
bits 0:10
        Decoder & osd ?? unknown
        Moves entire screen horizontally. Starts at 0x005 with the screen
        shifted heavily to the right. Incrementing in steps of 0x004 will
        gradually shift the screen to the left.

bits 11:31
        ?? unknown

Normally contents are 0x00101111 (NTSC) or 0x1010111d (PAL)

--------------------------------------------------------------------------------
2880  --------    ?? unknown
2884  --------    ?? unknown
--------------------------------------------------------------------------------
2888
bit 0
        Decoder + osd ?? unknown
        0 = Normal
        1 = Misaligned fields (Correctable through 289C & 28A4)

bit 4
        ?? unknown

bit 8
        ?? unknown

Warning: Bad values will require a firmware reload to recover.
                Known to be bad are 0x000,0x011,0x100,0x111
--------------------------------------------------------------------------------
288C
bits 0:15
        osd ?? unknown
        Appears to affect the osd position stability. The higher the value the
        more unstable it becomes. Decoder output remains stable.

bits 16:31
        osd ?? unknown
        Same as bits 0:15

--------------------------------------------------------------------------------
2890
bits 0:11
        Decoder output horizontal offset.

Horizontal offset moves the video image right. A small left shift is
possible, but it's better to use reg 2870 for that due to its greater
range.

NOTE: Video corruption will occur if video window is shifted off the right
edge. To avoid this read the notes for 2834 & 2838.
--------------------------------------------------------------------------------
2894
bits 0:23
        Decoder output video surround colour.

Contains the colour (in yuv) used to fill the screen when the video is
running in a window.
--------------------------------------------------------------------------------
2898
bits 0:23
        Decoder video window colour
        Contains the colour (in yuv) used to fill the video window when the
        video is turned off.

bit 24
        Decoder video output
        0 = Video on
        1 = Video off

bit 28
        Decoder plane order
        0 = Y,UV
        1 = UV,Y

bit 29
        Decoder second plane byte order
        0 = Normal (UV)
        1 = Swapped (VU)

In normal usage, the first plane is Y & the second plane is UV. Though the
order of the planes can be swapped, only the byte order of the second plane
can be swapped. This isn't much use for the Y plane, but can be useful for
the UV plane.

--------------------------------------------------------------------------------
289C
bits 0:15
        Decoder vertical field offset 1

bits 16:31
        Decoder vertical field offset 2

Controls field output vertical alignment. The higher the number, the lower
the image on screen. Known starting values are 0x011E0017 (NTSC) &
0x01500017 (PAL)
--------------------------------------------------------------------------------
28A0
bits 0:15
        Decoder & osd width in pixels

bits 16:31
        Decoder & osd height in pixels

All output from the decoder & osd are disabled beyond this area. Decoder
output will simply go black outside of this region. If the osd tries to
exceed this area it will become corrupt.
--------------------------------------------------------------------------------
28A4
bits 0:11
        osd left shift.

Has a range of 0x770->0x7FF. With the exception of 0, any value outside of
this range corrupts the osd.
--------------------------------------------------------------------------------
28A8
bits 0:15
        osd vertical field offset 1

bits 16:31
        osd vertical field offset 2

Controls field output vertical alignment. The higher the number, the lower
the image on screen. Known starting values are 0x011E0017 (NTSC) &
0x01500017 (PAL)
--------------------------------------------------------------------------------
28AC  --------    ?? unknown
|
V
28BC  --------    ?? unknown
--------------------------------------------------------------------------------
28C0
bit 0
        Current output field
        0 = first field
        1 = second field

bits 16:31
        Current scanline
        The scanline counts from the top line of the first field
        through to the last line of the second field.
--------------------------------------------------------------------------------
28C4  --------    ?? unknown
|
V
28F8  --------    ?? unknown
--------------------------------------------------------------------------------
28FC
bit 0
        ?? unknown
        0 = Normal
        1 = Breaks decoder & osd output
--------------------------------------------------------------------------------
2900
bits 0:31
        Decoder vertical Y alias register 1
---------------
2904
bits 0:31
        Decoder vertical Y alias register 2
---------------
2908
bits 0:31
        Decoder vertical Y alias trigger

These three registers control the vertical aliasing filter for the Y plane.
Operation is similar to the horizontal Y filter (2804). The only real
difference is that there are only two registers to set before accessing
the trigger register (2908). As for the horizontal filter, the values are
taken from a lookup table in the firmware, and the procedure must be
repeated 16 times to fully program the filter.
--------------------------------------------------------------------------------
290C
bits 0:31
        Decoder vertical UV alias register 1
---------------
2910
bits 0:31
        Decoder vertical UV alias register 2
---------------
2914
bits 0:31
        Decoder vertical UV alias trigger

These three registers control the vertical aliasing filter for the UV
plane. Operation is the same as the Y filter, with 2914 being the trigger.
--------------------------------------------------------------------------------
2918
bits 0:15
        Decoder Y source height in pixels

bits 16:31
        Decoder Y destination height in pixels
---------------
291C
bits 0:15
        Decoder UV source height in pixels divided by 2

bits 16:31
        Decoder UV destination height in pixels

NOTE: For both registers, the resulting image must be fully visible on
screen. If the image exceeds the bottom edge both the source and
destination size must be adjusted to reflect the visible portion. For the
source height, you must take into account the scaling when calculating the
new value.
--------------------------------------------------------------------------------
2920
bits 0:31
        Decoder Y vertical scaling
        Normally = Reg 2930 >> 2
---------------
2924
bits 0:31
        Decoder Y vertical scaling
        Normally = Reg 2920 + 0x514
---------------
2928
bits 0:31
        Decoder UV vertical scaling
        When enlarging = Reg 2930 >> 2
        When reducing = Reg 2930 >> 3
---------------
292C
bits 0:31
        Decoder UV vertical scaling
        Normally = Reg 2928 + 0x514
---------------
2930
bits 0:31
        Decoder 'master' value for vertical scaling
---------------
2934
bits 0:31
        Decoder ?? unknown - Y vertical scaling
---------------
2938
bits 0:31
        Decoder Y vertical scaling
        Normally = Reg 2930
---------------
293C
bits 0:31
        Decoder ?? unknown - Y vertical scaling
---------------
2940
bits 0:31
        Decoder UV vertical scaling
        When enlarging = Reg 2930 >> 1
        When reducing = Reg 2930
---------------
2944
bits 0:31
        Decoder ?? unknown - UV vertical scaling
---------------
2948
bits 0:31
        Decoder UV vertical scaling
        Normally = Reg 2940
---------------
294C
bits 0:31
        Decoder ?? unknown - UV vertical scaling

Most of these registers either control vertical scaling, or appear linked
to it in some way. Register 2930 contains the 'master' value & all other
registers can be calculated from that one. You must also remember to
correctly set the divider in Reg 296C

To enlarge:
        Reg 2930 = (source_height * 0x00200000) / destination_height
        Reg 296C = No divide

To reduce from full size down to half size:
        Reg 2930 = (source_height/2 * 0x00200000) / destination height
        Reg 296C = Divide by 2

To reduce from half down to quarter.
        Reg 2930 = (source_height/4 * 0x00200000) / destination height
        Reg 296C = Divide by 4

--------------------------------------------------------------------------------
2950
bits 0:15
        Decoder Y line index into display buffer, first field

bits 16:31
        Decoder Y vertical line skip, first field
--------------------------------------------------------------------------------
2954
bits 0:15
        Decoder Y line index into display buffer, second field

bits 16:31
        Decoder Y vertical line skip, second field
--------------------------------------------------------------------------------
2958
bits 0:15
        Decoder UV line index into display buffer, first field

bits 16:31
        Decoder UV vertical line skip, first field
--------------------------------------------------------------------------------
295C
bits 0:15
        Decoder UV line index into display buffer, second field

bits 16:31
        Decoder UV vertical line skip, second field
--------------------------------------------------------------------------------
2960
bits 0:15
        Decoder destination height minus 1

bits 16:31
        Decoder destination height divided by 2
--------------------------------------------------------------------------------
2964
bits 0:15
        Decoder Y vertical offset, second field

bits 16:31
        Decoder Y vertical offset, first field

These two registers shift the Y plane up. The higher the number, the
greater the shift.
--------------------------------------------------------------------------------
2968
bits 0:15
        Decoder UV vertical offset, second field

bits 16:31
        Decoder UV vertical offset, first field

These two registers shift the UV plane up. The higher the number, the
greater the shift.
--------------------------------------------------------------------------------
296C
bits 0:1
        Decoder vertical Y output size divider
        00 = No divide
        01 = Divide by 2
        10 = Divide by 4

bits 8:9
        Decoder vertical UV output size divider
        00 = No divide
        01 = Divide by 2
        10 = Divide by 4
--------------------------------------------------------------------------------
2970
bit 0
        Decoder ?? unknown
        0 = Normal
        1 = Affect video output levels

bit 16
        Decoder ?? unknown
        0 = Normal
        1 = Disable vertical filter

--------------------------------------------------------------------------------
2974  --------   ?? unknown
|
V
29EF  --------   ?? unknown
--------------------------------------------------------------------------------
2A00
bits 0:2
        osd colour mode
        000 = 8 bit indexed
        001 = 16 bit (565)
        010 = 15 bit (555)
        011 = 12 bit (444)
        100 = 32 bit (8888)

bits 4:5
        osd display bpp
        01 = 8 bit
        10 = 16 bit
        11 = 32 bit

bit 8
        osd global alpha
        0 = Off
        1 = On

bit 9
        osd local alpha
        0 = Off
        1 = On

bit 10
        osd colour key
        0 = Off
        1 = On

bit 11
        osd ?? unknown
        Must be 1

bit 13
        osd colour space
        0 = ARGB
        1 = AYVU

bits 16:31
        osd ?? unknown
        Must be 0x001B (some kind of buffer pointer ?)

When the bits-per-pixel is set to 8, the colour mode is ignored and
assumed to be 8 bit indexed. For 16 & 32 bits-per-pixel the colour depth
is honoured, and when using a colour depth that requires fewer bytes than
allocated the extra bytes are used as padding. So for a 32 bpp with 8 bit
index colour, there are 3 padding bytes per pixel. It's also possible to
select 16bpp with a 32 bit colour mode. This results in the pixel width
being doubled, but the color key will not work as expected in this mode.

Colour key is as it suggests. You designate a colour which will become
completely transparent. When using 565, 555 or 444 colour modes, the
colour key is always 16 bits wide. The colour to key on is set in Reg 2A18.

Local alpha works differently depending on the colour mode. For 32bpp & 8
bit indexed, local alpha is a per-pixel 256 step transparency, with 0 being
transparent and 255 being solid. For the 16bpp modes 555 & 444, the unused
bit(s) act as a simple transparency switch, with 0 being solid & 1 being
fully transparent. There is no local alpha support for 16bit 565.

Global alpha is a 256 step transparency that applies to the entire osd,
with 0 being transparent & 255 being solid.

It's possible to combine colour key, local alpha & global alpha.
--------------------------------------------------------------------------------
2A04
bits 0:15
        osd x coord for left edge

bits 16:31
        osd y coord for top edge
---------------
2A08
bits 0:15
        osd x coord for right edge

bits 16:31
        osd y coord for bottom edge

For both registers, (0,0) = top left corner of the display area. These
registers do not control the osd size, only where it's positioned & how
much is visible. The visible osd area cannot exceed the right edge of the
display, otherwise the osd will become corrupt. See reg 2A10 for
setting osd width.
--------------------------------------------------------------------------------
2A0C
bits 0:31
        osd buffer index

An index into the osd buffer. Slowly incrementing this moves the osd left,
wrapping around onto the right edge
--------------------------------------------------------------------------------
2A10
bits 0:11
        osd buffer 32 bit word width

Contains the width of the osd measured in 32 bit words. This means that all
colour modes are restricted to a byte width which is divisible by 4.
--------------------------------------------------------------------------------
2A14
bits 0:15
        osd height in pixels

bits 16:32
        osd line index into buffer
        osd will start displaying from this line.
--------------------------------------------------------------------------------
2A18
bits 0:31
        osd colour key

Contains the colour value which will be transparent.
--------------------------------------------------------------------------------
2A1C
bits 0:7
        osd global alpha

Contains the global alpha value (equiv ivtvfbctl --alpha XX)
--------------------------------------------------------------------------------
2A20  --------    ?? unknown
|
V
2A2C  --------    ?? unknown
--------------------------------------------------------------------------------
2A30
bits 0:7
        osd colour to change in indexed palette
---------------
2A34
bits 0:31
        osd colour for indexed palette

To set the new palette, first load the index of the colour to change into
2A30, then load the new colour into 2A34. The full palette is 256 colours,
so the index range is 0x00-0xFF
--------------------------------------------------------------------------------
2A38  --------    ?? unknown
2A3C  --------    ?? unknown
--------------------------------------------------------------------------------
2A40
bits 0:31
        osd ?? unknown

Affects overall brightness, wrapping around to black
--------------------------------------------------------------------------------
2A44
bits 0:31
        osd ?? unknown

Green tint
--------------------------------------------------------------------------------
2A48
bits 0:31
        osd ?? unknown

Red tint
--------------------------------------------------------------------------------
2A4C
bits 0:31
        osd ?? unknown

Affects overall brightness, wrapping around to black
--------------------------------------------------------------------------------
2A50
bits 0:31
        osd ?? unknown

Colour shift
--------------------------------------------------------------------------------
2A54
bits 0:31
        osd ?? unknown

Colour shift
--------------------------------------------------------------------------------
2A58  --------    ?? unknown
|
V
2AFC  --------    ?? unknown
--------------------------------------------------------------------------------
2B00
bit 0
        osd filter control
        0 = filter off
        1 = filter on

bits 1:4
        osd ?? unknown

--------------------------------------------------------------------------------
```

<a id="rst-the-cx231xx-dma-engine"></a>

## The cx231xx DMA engine

This page describes the structures and procedures used by the cx2341x DMA engine.

<a id="rst-introduction"></a>

### Introduction

The cx2341x PCI interface is busmaster capable. This means it has a DMA engine to efficiently transfer large volumes of data between the card and main memory without requiring help from a CPU. Like most hardware, it must operate on contiguous physical memory. This is difficult to come by in large quantities on virtual memory machines.

Therefore, it also supports a technique called "scatter-gather". The card can transfer multiple buffers in one operation. Instead of allocating one large contiguous buffer, the driver can allocate several smaller buffers.

In practice, I've seen the average transfer to be roughly 80K, but transfers above 128K were not uncommon, particularly at startup. The 128K figure is important, because that is the largest block that the kernel can normally allocate. Even still, 128K blocks are hard to come by, so the driver writer is urged to choose a smaller block size and learn the scatter-gather technique.

Mailbox \#10 is reserved for DMA transfer information.

Note: the hardware expects little-endian data ('intel format').

<a id="rst-flow"></a>

### Flow

This section describes, in general, the order of events when handling DMA transfers. Detailed information follows this section.

- The card raises the Encoder interrupt.

- The driver reads the transfer type, offset and size from Mailbox \#10.

- The driver constructs the scatter-gather array from enough free dma buffers to cover the size.

- The driver schedules the DMA transfer via the ScheduleDMAtoHost API call.

- The card raises the DMA Complete interrupt.

- The driver checks the DMA status register for any errors.

- The driver post-processes the newly transferred buffers.

NOTE\! It is possible that the Encoder and DMA Complete interrupts get raised simultaneously. (End of the last, start of the next, etc.)

<a id="rst-mailbox-10"></a>

### Mailbox \#10

The Flags, Command, Return Value and Timeout fields are ignored.

- Name:       Mailbox \#10

- Results\[0\]: Type: 0: MPEG.

- Results\[1\]: Offset: The position relative to the card's memory space.

- Results\[2\]: Size: The exact number of bytes to transfer.

My speculation is that since the StartCapture API has a capture type of "RAW" available, that the type field will have other values that correspond to YUV and PCM data.

<a id="rst-scatter-gather-array"></a>

### Scatter-Gather Array

The scatter-gather array is a contiguously allocated block of memory that tells the card the source and destination of each data-block to transfer. Card "addresses" are derived from the offset supplied by Mailbox \#10. Host addresses are the physical memory location of the target DMA buffer.

Each S-G array element is a struct of three 32-bit words. The first word is the source address, the second is the destination address. Both take up the entire 32 bits. The lowest 18 bits of the third word is the transfer byte count. The high-bit of the third word is the "last" flag. The last-flag tells the card to raise the DMA_DONE interrupt. From hard personal experience, if you forget to set this bit, the card will still "work" but the stream will most likely get corrupted.

The transfer count must be a multiple of 256. Therefore, the driver will need to track how much data in the target buffer is valid and deal with it accordingly.

Array Element:

- 32-bit Source Address

- 32-bit Destination Address

- 14-bit reserved (high bit is the last flag)

- 18-bit byte count

<a id="rst-dma-transfer-status"></a>

### DMA Transfer Status

Register 0x0004 holds the DMA Transfer Status:

- bit 0:   read completed

- bit 1:   write completed

- bit 2:   DMA read error

- bit 3:   DMA write error

- bit 4:   Scatter-Gather array error

---

# The cx88 driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Author: Gerd Hoffmann

<a id="rst-the-cx88-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Author:  Gerd Hoffmann

<a id="rst-documentation-missing-at-the-cx88-datasheet"></a>

## Documentation missing at the cx88 datasheet

MO_OUTPUT_FORMAT (0x310164)



```none
Previous default from DScaler: 0x1c1f0008
Digit 8: 31-28
28: PREVREMOD = 1

Digit 7: 27-24 (0xc = 12 = b1100 )
27: COMBALT = 1
26: PAL_INV_PHASE
  (DScaler apparently set this to 1, resulted in sucky picture)

Digits 6,5: 23-16
25-16: COMB_RANGE = 0x1f [default] (9 bits -> max 512)

Digit 4: 15-12
15: DISIFX = 0
14: INVCBF = 0
13: DISADAPT = 0
12: NARROWADAPT = 0

Digit 3: 11-8
11: FORCE2H
10: FORCEREMD
9: NCHROMAEN
8: NREMODEN

Digit 2: 7-4
7-6: YCORE
5-4: CCORE

Digit 1: 3-0
3: RANGE = 1
2: HACTEXT
1: HSFMT
```

0x47 is the sync byte for MPEG-2 transport stream packets. Datasheet incorrectly states to use 47 decimal. 188 is the length. All DVB compliant frontends output packets with this start code.

<a id="rst-hauppauge-wintv-cx88-ir-information"></a>

## Hauppauge WinTV cx88 IR information

The controls for the mux are GPIO \[0,1\] for source, and GPIO 2 for muting.


<table>
<thead>
<tr>
<th>


GPIO0

</th>
<th>


GPIO1

</th>
<th>




</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


0

</td>
<td>


TV Audio

</td>
</tr>
<tr>
<td>


1

</td>
<td>


0

</td>
<td>


FM radio

</td>
</tr>
<tr>
<td>


0

</td>
<td>


1

</td>
<td>


Line-In

</td>
</tr>
<tr>
<td>


1

</td>
<td>


1

</td>
<td>


Mono tuner bypass or CD passthru (tuner specific)

</td>
</tr>
</tbody>
</table>

GPIO 16(I believe) is tied to the IR port (if present).

From the data sheet:

- Register 24'h20004  PCI Interrupt Status

> - bit \[18\]  IR_SMP_INT Set when 32 input samples have been collected over
>
> - gpio\[16\] pin into GP_SAMPLE register.

What's missing from the data sheet:

- Setup 4KHz sampling rate (roughly 2x oversampled; good enough for our RC5 compat remote)

- set register 0x35C050 to  0xa80a80

- enable sampling

- set register 0x35C054 to 0x5

- enable the IRQ bit 18 in the interrupt mask register (and provide for a handler)

GP_SAMPLE register is at 0x35C058

Bits are then right shifted into the GP_SAMPLE register at the specified rate; you get an interrupt when a full DWORD is received. You need to recover the actual RC5 bits out of the (oversampled) IR sensor bits. (Hint: look for the 0/1and 1/0 crossings of the RC5 bi-phase data)  An actual raw RC5 code will span 2-3 DWORDS, depending on the actual alignment.

I'm pretty sure when no IR signal is present the receiver is always in a marking state(1); but stray light, etc can cause intermittent noise values as well.  Remember, this is a free running sample of the IR receiver state over time, so don't assume any sample starts at any particular place.

<a id="rst-additional-info"></a>

### Additional info

This data sheet (google search) seems to have a lovely description of the RC5 basics: [http://www.atmel.com/dyn/resources/prod_documents/doc2817.pdf](<http://www.atmel.com/dyn/resources/prod_documents/doc2817.pdf>)

This document has more data: [http://www.nenya.be/beor/electronics/rc5.htm](<http://www.nenya.be/beor/electronics/rc5.htm>)

This document has a  how to decode a bi-phase data stream: [http://www.ee.washington.edu/circuit_archive/text/ir_decode.txt](<http://www.ee.washington.edu/circuit_archive/text/ir_decode.txt>)

This document has still more info: [http://www.xs4all.nl/\~sbp/knowledge/ir/rc5.htm](<http://www.xs4all.nl/~sbp/knowledge/ir/rc5.htm>)

---

# Idea behind the dvb-usb-framework

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> In March 2005 I got the new Twinhan USB2.0 DVB-T device. They provided specs and a firmware.

<a id="rst-idea-behind-the-dvb-usb-framework"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> [!NOTE]
>
> 1. This documentation is outdated. Please check at the DVB wiki at [https://linuxtv.org/wiki](<https://linuxtv.org/wiki>) for more updated info.
>
> 2. **deprecated:** Newer DVB USB drivers should use the dvb-usb-v2 framework.

In March 2005 I got the new Twinhan USB2.0 DVB-T device. They provided specs and a firmware.

Quite keen I wanted to put the driver (with some quirks of course) into dibusb. After reading some specs and doing some USB snooping, it realized, that the dibusb-driver would be a complete mess afterwards. So I decided to do it in a different way: With the help of a dvb-usb-framework.

The framework provides generic functions (mostly kernel API calls), such as:

- Transport Stream URB handling in conjunction with dvb-demux-feed-control (bulk and isoc are supported)

- registering the device for the DVB-API

- registering an I2C-adapter if applicable

- remote-control/input-device handling

- firmware requesting and loading (currently just for the Cypress USB controllers)

- other functions/methods which can be shared by several drivers (such as functions for bulk-control-commands)

- TODO: a I2C-chunker. It creates device-specific chunks of register-accesses depending on length of a register and the number of values that can be multi-written and multi-read.

The source code of the particular DVB USB devices does just the communication with the device via the bus. The connection between the DVB-API-functionality is done via callbacks, assigned in a static device-description (struct dvb_usb_device) each device-driver has to have.

For an example have a look in drivers/media/usb/dvb-usb/vp7045\*.

Objective is to migrate all the usb-devices (dibusb, cinergyT2, maybe the ttusb; flexcop-usb already benefits from the generic flexcop-device) to use the dvb-usb-lib.

TODO: dynamic enabling and disabling of the pid-filter in regard to number of feeds requested.

<a id="rst-supported-devices"></a>

## Supported devices

See the LinuxTV DVB Wiki at [https://linuxtv.org](<https://linuxtv.org>) for a complete list of cards/drivers/firmwares: [https://linuxtv.org/wiki/index.php/DVB_USB](<https://linuxtv.org/wiki/index.php/DVB_USB>)

0. History &amp; News:

> 2005-06-30
>
> - added support for WideView WT-220U (Thanks to Steve Chang)
>
> 2005-05-30
>
> - added basic isochronous support to the dvb-usb-framework
>
> - - **added support for Conexant Hybrid reference design and Nebula**
>
>     DigiTV USB
>
> 2005-04-17
>
> - all dibusb devices ported to make use of the dvb-usb-framework
>
> 2005-04-02
>
> - re-enabled and improved remote control code.
>
> 2005-03-31
>
> - ported the Yakumo/Hama/Typhoon DVB-T USB2.0 device to dvb-usb.
>
> 2005-03-30
>
> - first commit of the dvb-usb-module based on the dibusb-source. First device is a new driver for the TwinhanDTV Alpha / MagicBox II USB2.0-only DVB-T device.
>
> - (change from dvb-dibusb to dvb-usb)
>
> 2005-03-28
>
> - added support for the AVerMedia AverTV DVB-T USB2.0 device (Thanks to Glen Harris and Jiun-Kuei Jung, AVerMedia)
>
> 2005-03-14
>
> - added support for the Typhoon/Yakumo/HAMA DVB-T mobile USB2.0
>
> 2005-02-11
>
> - added support for the KWorld/ADSTech Instant DVB-T USB2.0. Thanks a lot to Joachim von Caron
>
> 2005-02-02 - added support for the Hauppauge Win-TV Nova-T USB2
>
> 2005-01-31 - distorted streaming is gone for USB1.1 devices
>
> 2005-01-13
>
> - moved the mirrored pid_filter_table back to dvb-dibusb first almost working version for HanfTek UMT-010 found out, that Yakumo/HAMA/Typhoon are predecessors of the HanfTek UMT-010
>
> 2005-01-10
>
> - refactoring completed, now everything is very delightful
>
> - tuner quirks for some weird devices (Artec T1 AN2235 device has sometimes a Panasonic Tuner assembled). Tunerprobing implemented. Thanks a lot to Gunnar Wittich.
>
> 2004-12-29
>
> - after several days of struggling around bug of no returning URBs fixed.
>
> 2004-12-26
>
> - refactored the dibusb-driver, split into separate files
>
> - i2c-probing enabled
>
> 2004-12-06
>
> - possibility for demod i2c-address probing
>
> - new usb IDs (Compro, Artec)
>
> 2004-11-23
>
> - merged changes from DiB3000MC_ver2.1
>
> - revised the debugging
>
> - possibility to deliver the complete TS for USB2.0
>
> 2004-11-21
>
> - first working version of the dib3000mc/p frontend driver.
>
> 2004-11-12
>
> - added additional remote control keys. Thanks to Uwe Hanke.
>
> 2004-11-07
>
> - added remote control support. Thanks to David Matthews.
>
> 2004-11-05
>
> - added support for a new devices (Grandtec/Avermedia/Artec)
>
> - merged my changes (for dib3000mb/dibusb) to the FE_REFACTORING, because it became HEAD
>
> - moved transfer control (pid filter, fifo control) from usb driver to frontend, it seems better settled there (added xfer_ops-struct)
>
> - created a common files for frontends (mc/p/mb)
>
> 2004-09-28
>
> - added support for a new device (Unknown, vendor ID is Hyper-Paltek)
>
> 2004-09-20
>
> - added support for a new device (Compro DVB-U2000), thanks to Amaury Demol for reporting
>
> - changed usb TS transfer method (several urbs, stopping transfer before setting a new pid)
>
> 2004-09-13
>
> - added support for a new device (Artec T1 USB TVBOX), thanks to Christian Motschke for reporting
>
> 2004-09-05
>
> - released the dibusb device and dib3000mb-frontend driver (old news for vp7041.c)
>
> 2004-07-15
>
> - found out, by accident, that the device has a TUA6010XS for PLL
>
> 2004-07-12
>
> - figured out, that the driver should also work with the CTS Portable (Chinese Television System)
>
> 2004-07-08
>
> - firmware-extraction-2.422-problem solved, driver is now working properly with firmware extracted from 2.422
>
> - \#if for 2.6.4 (dvb), compile issue
>
> - changed firmware handling, see vp7041.txt sec 1.1
>
> 2004-07-02
>
> - some tuner modifications, v0.1, cleanups, first public
>
> 2004-06-28
>
> - now using the dvb_dmx_swfilter_packets, everything runs fine now
>
> 2004-06-27
>
> - able to watch and switching channels (pre-alpha)
>
> - no section filtering yet
>
> 2004-06-06
>
> - first TS received, but kernel oops :/
>
> 2004-05-14
>
> - firmware loader is working
>
> 2004-05-11
>
> - start writing the driver

<a id="rst-how-to-use"></a>

## How to use?

<a id="rst-firmware"></a>

### Firmware

Most of the USB drivers need to download a firmware to the device before start working.

Have a look at the Wikipage for the DVB-USB-drivers to find out, which firmware you need for your device:

[https://linuxtv.org/wiki/index.php/DVB_USB](<https://linuxtv.org/wiki/index.php/DVB_USB>)

<a id="rst-compiling"></a>

### Compiling

Since the driver is in the linux kernel, activating the driver in your favorite config-environment should sufficient. I recommend to compile the driver as module. Hotplug does the rest.

If you use dvb-kernel enter the build-2.6 directory run 'make' and 'insmod.sh load' afterwards.

<a id="rst-loading-the-drivers"></a>

### Loading the drivers

Hotplug is able to load the driver, when it is needed (because you plugged in the device).

If you want to enable debug output, you have to load the driver manually and from within the dvb-kernel cvs repository.

first have a look, which debug level are available:



```none
# modinfo dvb-usb
# modinfo dvb-usb-vp7045

etc.
```



```none
modprobe dvb-usb debug=<level>
modprobe dvb-usb-vp7045 debug=<level>
etc.
```

should do the trick.

When the driver is loaded successfully, the firmware file was in the right place and the device is connected, the "Power"-LED should be turned on.

At this point you should be able to start a dvb-capable application. I'm use (t\|s)zap, mplayer and dvbscan to test the basics. VDR-xine provides the long-term test scenario.

<a id="rst-known-problems-and-bugs"></a>

## Known problems and bugs

- Don't remove the USB device while running an DVB application, your system will go crazy or die most likely.

<a id="rst-adding-support-for-devices"></a>

### Adding support for devices

TODO

<a id="rst-usb1-1-bandwidth-limitation"></a>

### USB1.1 Bandwidth limitation

A lot of the currently supported devices are USB1.1 and thus they have a maximum bandwidth of about 5-6 MBit/s when connected to a USB2.0 hub. This is not enough for receiving the complete transport stream of a DVB-T channel (which is about 16 MBit/s). Normally this is not a problem, if you only want to watch TV (this does not apply for HDTV), but watching a channel while recording another channel on the same frequency simply does not work very well. This applies to all USB1.1 DVB-T devices, not just the dvb-usb-devices)

The bug, where the TS is distorted by a heavy usage of the device is gone definitely. All dvb-usb-devices I was using (Twinhan, Kworld, DiBcom) are working like charm now with VDR. Sometimes I even was able to record a channel and watch another one.

<a id="rst-comments"></a>

### Comments

Patches, comments and suggestions are very very welcome.

<a id="rst-acknowledgements"></a>

## 3. Acknowledgements

> Amaury Demol ([Amaury.Demol@parrot.com](<mailto:Amaury.Demol@parrot.com>)) and Francois Kanounnikoff from DiBcom for providing specs, code and help, on which the dvb-dibusb, dib3000mb and dib3000mc are based.
>
> David Matthews for identifying a new device type (Artec T1 with AN2235) and for extending dibusb with remote control event handling. Thank you.
>
> Alex Woods for frequently answering question about usb and dvb stuff, a big thank you.
>
> Bernd Wagner for helping with huge bug reports and discussions.
>
> Gunnar Wittich and Joachim von Caron for their trust for providing root-shells on their machines to implement support for new devices.
>
> Allan Third and Michael Hutchinson for their help to write the Nebula digitv-driver.
>
> Glen Harris for bringing up, that there is a new dibusb-device and Jiun-Kuei Jung from AVerMedia who kindly provided a special firmware to get the device up and running in Linux.
>
> Jennifer Chen, Jeff and Jack from Twinhan for kindly supporting by writing the vp7045-driver.
>
> Steve Chang from WideView for providing information for new devices and firmware files.
>
> Michael Paxton for submitting remote control keymaps.
>
> Some guys on the linux-dvb mailing list for encouraging me.
>
> Peter Schildmann &gt;peter.schildmann-nospam-at-web.de&lt; for his user-level firmware loader, which saves a lot of time (when writing the vp7041 driver)
>
> Ulf Hermenau for helping me out with traditional chinese.
>
> André Smoktun and Christian Frömmel for supporting me with hardware and listening to my problems very patiently.

---

# The Samsung S5P/EXYNOS4 FIMC driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Copyright © 2012 - 2013 Samsung Electronics Co., Ltd.

<a id="rst-the-samsung-s5p-exynos4-fimc-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

Copyright © 2012 - 2013 Samsung Electronics Co., Ltd.

<a id="rst-files-partitioning"></a>

## Files partitioning

- media device driver

  drivers/media/platform/samsung/exynos4-is/media-dev.\[ch\]

- camera capture video device driver

  drivers/media/platform/samsung/exynos4-is/fimc-capture.c

- MIPI-CSI2 receiver subdev

  drivers/media/platform/samsung/exynos4-is/mipi-csis.\[ch\]

- video post-processor (mem-to-mem)

  drivers/media/platform/samsung/exynos4-is/fimc-core.c

- common files

  drivers/media/platform/samsung/exynos4-is/fimc-core.h drivers/media/platform/samsung/exynos4-is/fimc-reg.h drivers/media/platform/samsung/exynos4-is/regs-fimc.h

---

# Frontend drivers

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Reference for Frontend drivers.

<a id="rst-frontend-drivers"></a>

<a id="rst-frontend-attach-headers"></a>

## Frontend attach headers

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Keep it on alphabetic order -->


#### <a id="c-struct-a8293_platform_data"></a>`struct a8293_platform_data`

Platform data for the a8293 driver

**Definition**

```c
struct a8293_platform_data {
    struct dvb_frontend *dvb_frontend;
    int volt_slew_nanos_per_mv;
};
```

**Members**

- `dvb_frontend`: DVB frontend.
- `volt_slew_nanos_per_mv`: Slew rate when increasing LNB voltage,
  in nanoseconds per millivolt.



#### <a id="c-struct-af9013_platform_data"></a>`struct af9013_platform_data`

Platform data for the af9013 driver

**Definition**

```c
struct af9013_platform_data {
        u32 clk;
    #define AF9013_TUNER_MXL5003D      3;
    #define AF9013_TUNER_MXL5005D     13;
    #define AF9013_TUNER_MXL5005R     30;
    #define AF9013_TUNER_ENV77H11D5  129;
    #define AF9013_TUNER_MT2060      130;
    #define AF9013_TUNER_MC44S803    133;
    #define AF9013_TUNER_QT1010      134;
    #define AF9013_TUNER_UNKNOWN     140;
    #define AF9013_TUNER_MT2060_2    147;
    #define AF9013_TUNER_TDA18271    156;
    #define AF9013_TUNER_QT1010A     162;
    #define AF9013_TUNER_MXL5007T    177;
    #define AF9013_TUNER_TDA18218    179;
        u8 tuner;
        u32 if_frequency;
    #define AF9013_TS_MODE_USB       0;
    #define AF9013_TS_MODE_PARALLEL  1;
    #define AF9013_TS_MODE_SERIAL    2;
        u8 ts_mode;
        u8 ts_output_pin;
        bool spec_inv;
        u8 api_version[4];
    #define AF9013_GPIO_ON (1 << 0);
    #define AF9013_GPIO_EN (1 << 1);
    #define AF9013_GPIO_O  (1 << 2);
    #define AF9013_GPIO_I  (1 << 3);
    #define AF9013_GPIO_LO (AF9013_GPIO_ON|AF9013_GPIO_EN);
    #define AF9013_GPIO_HI (AF9013_GPIO_ON|AF9013_GPIO_EN|AF9013_GPIO_O);
    #define AF9013_GPIO_TUNER_ON  (AF9013_GPIO_ON|AF9013_GPIO_EN);
    #define AF9013_GPIO_TUNER_OFF (AF9013_GPIO_ON|AF9013_GPIO_EN|AF9013_GPIO_O);
        u8 gpio[4];
        struct dvb_frontend* (*get_dvb_frontend)(struct i2c_client *);
        struct i2c_adapter* (*get_i2c_adapter)(struct i2c_client *);
        int (*pid_filter_ctrl)(struct dvb_frontend *, int);
        int (*pid_filter)(struct dvb_frontend *, u8, u16, int);
};
```

**Members**

- `clk`: Clock frequency.
- `tuner`: Used tuner model.
- `if_frequency`: IF frequency.
- `ts_mode`: TS mode.
- `ts_output_pin`: TS output pin.
- `spec_inv`: Input spectrum inverted.
- `api_version`: Firmware API version.
- `gpio`: GPIOs.
- `get_dvb_frontend`: Get DVB frontend callback.
- `get_i2c_adapter`: Get I2C adapter.
- `pid_filter_ctrl`: Control PID filter.
- `pid_filter`: Set PID to PID filter.



#### <a id="c-struct-ascot2e_config"></a>`struct ascot2e_config`

the configuration of Ascot2E tuner driver

**Definition**

```c
struct ascot2e_config {
    u8 i2c_address;
    u8 xtal_freq_mhz;
    void *set_tuner_priv;
    int (*set_tuner_callback)(void *, int);
};
```

**Members**

- `i2c_address`: I2C address of the tuner
- `xtal_freq_mhz`: Oscillator frequency, MHz
- `set_tuner_priv`: Callback function private context
- `set_tuner_callback`: Callback function that notifies the parent driver
  which tuner is active now

#### <a id="c-ascot2e_attach"></a>`ascot2e_attach()`

```c
struct dvb_frontend * ascot2e_attach(struct dvb_frontend *fe, const struct ascot2e_config *config, struct i2c_adapter *i2c)
```

Attach an ascot2e tuner

**Parameters**

- `struct dvb_frontend *fe`: frontend to be attached
- `const struct ascot2e_config *config`: pointer to [`struct ascot2e_config`](#c-struct-ascot2e_config) with tuner configuration.
- `struct i2c_adapter *i2c`: i2c adapter to use.

**Return**

FE pointer on success, NULL on failure.



#### <a id="c-struct-cxd2820r_platform_data"></a>`struct cxd2820r_platform_data`

Platform data for the cxd2820r driver

**Definition**

```c
struct cxd2820r_platform_data {
    u8 ts_mode;
    bool ts_clk_inv;
    bool if_agc_polarity;
    bool spec_inv;
    int **gpio_chip_base;
    struct dvb_frontend* (*get_dvb_frontend)(struct i2c_client *);
};
```

**Members**

- `ts_mode`: TS mode.
- `ts_clk_inv`: TS clock inverted.
- `if_agc_polarity`: IF AGC polarity.
- `spec_inv`: Input spectrum inverted.
- `gpio_chip_base`: GPIO.
- `get_dvb_frontend`: Get DVB frontend.

#### <a id="c-struct-cxd2820r_config"></a>`struct cxd2820r_config`

configuration for cxd2020r demod

**Definition**

```c
struct cxd2820r_config {
    u8 i2c_address;
    u8 ts_mode;
    bool ts_clock_inv;
    bool if_agc_polarity;
    bool spec_inv;
};
```

**Members**

- `i2c_address`: Demodulator I2C address. Driver determines DVB-C slave I2C
  address automatically from master address.
  Default: none, must set. Values: 0x6c, 0x6d.
- `ts_mode`: TS output mode. Default: none, must set. Values: FIXME?
- `ts_clock_inv`: TS clock inverted. Default: 0. Values: 0, 1.
- `if_agc_polarity`: Default: 0. Values: 0, 1
- `spec_inv`: Spectrum inversion. Default: 0. Values: 0, 1.

#### <a id="c-cxd2820r_attach"></a>`cxd2820r_attach()`

```c
struct dvb_frontend * cxd2820r_attach(const struct cxd2820r_config *config, struct i2c_adapter *i2c, int *gpio_chip_base)
```

Attach a cxd2820r demod

**Parameters**

- `const struct cxd2820r_config *config`: pointer to [`struct cxd2820r_config`](#c-struct-cxd2820r_config) with demod configuration.
- `struct i2c_adapter *i2c`: i2c adapter to use.
- `int *gpio_chip_base`: if zero, disables GPIO setting. Otherwise, if
  CONFIG_GPIOLIB is set dynamically allocate
  gpio base; if is not set, use its value to
  setup the GPIO pins.

**Return**

FE pointer on success, NULL on failure.



#### <a id="c-struct-drxk_config"></a>`struct drxk_config`

Configure the initial parameters for DRX-K

**Definition**

```c
struct drxk_config {
    u8 adr;
    bool single_master;
    bool no_i2c_bridge;
    bool parallel_ts;
    bool dynamic_clk;
    bool enable_merr_cfg;
    bool antenna_dvbt;
    u16 antenna_gpio;
    u8 mpeg_out_clk_strength;
    int chunk_size;
    const char      *microcode_name;
    int qam_demod_parameter_count;
};
```

**Members**

- `adr`: I2C address of the DRX-K
- `single_master`: Device is on the single master mode
- `no_i2c_bridge`: Don't switch the I2C bridge to talk with tuner
- `parallel_ts`: True means that the device uses parallel TS,
  Serial otherwise.
- `dynamic_clk`: True means that the clock will be dynamically
  adjusted. Static clock otherwise.
- `enable_merr_cfg`: Enable SIO_PDR_PERR_CFG/SIO_PDR_MVAL_CFG.
- `antenna_dvbt`: GPIO bit for changing antenna to DVB-C. A value of 1
  means that 1=DVBC, 0 = DVBT. Zero means the opposite.
- `antenna_gpio`: GPIO bit used to control the antenna
- `mpeg_out_clk_strength`: DRXK Mpeg output clock drive strength.
- `chunk_size`: maximum size for I2C messages
- `microcode_name`: Name of the firmware file with the microcode
- `qam_demod_parameter_count`: The number of parameters used for the command
  to set the demodulator parameters. All
  firmwares are using the 2-parameter command.
  An exception is the `drxk_a3.mc` firmware,
  which uses the 4-parameter command.
  A value of 0 (default) or lower indicates that
  the correct number of parameters will be
  automatically detected.

**Description**

On the `*_gpio` vars, bit 0 is UIO-1, bit 1 is UIO-2 and bit 2 is
UIO-3.

#### <a id="c-drxk_attach"></a>`drxk_attach()`

```c
struct dvb_frontend * drxk_attach(const struct drxk_config *config, struct i2c_adapter *i2c)
```

Attach a drxk demod

**Parameters**

- `const struct drxk_config *config`: pointer to [`struct drxk_config`](#c-struct-drxk_config) with demod configuration.
- `struct i2c_adapter *i2c`: i2c adapter to use.

**Return**

FE pointer on success, NULL on failure.



#### <a id="c-dvb_pll_attach"></a>`dvb_pll_attach()`

```c
struct dvb_frontend * dvb_pll_attach(struct dvb_frontend *fe, int pll_addr, struct i2c_adapter *i2c, unsigned int pll_desc_id)
```

Attach a dvb-pll to the supplied frontend structure.

**Parameters**

- `struct dvb_frontend *fe`: Frontend to attach to.
- `int pll_addr`: i2c address of the PLL (if used).
- `struct i2c_adapter *i2c`: i2c adapter to use (set to NULL if not used).
- `unsigned int pll_desc_id`: dvb_pll_desc to use.

**Return**

Frontend pointer on success, NULL on failure



#### <a id="c-struct-helene_config"></a>`struct helene_config`

the configuration of 'Helene' tuner driver

**Definition**

```c
struct helene_config {
    u8 i2c_address;
    u8 xtal_freq_mhz;
    void *set_tuner_priv;
    int (*set_tuner_callback)(void *, int);
    enum helene_xtal xtal;
    struct dvb_frontend *fe;
};
```

**Members**

- `i2c_address`: I2C address of the tuner
- `xtal_freq_mhz`: Oscillator frequency, MHz
- `set_tuner_priv`: Callback function private context
- `set_tuner_callback`: Callback function that notifies the parent driver
  which tuner is active now
- `xtal`: Cristal frequency as described by `enum helene_xtal`
- `fe`: Frontend for which connects this tuner

#### <a id="c-helene_attach"></a>`helene_attach()`

```c
struct dvb_frontend * helene_attach(struct dvb_frontend *fe, const struct helene_config *config, struct i2c_adapter *i2c)
```

Attach a helene tuner (terrestrial and cable standards)

**Parameters**

- `struct dvb_frontend *fe`: frontend to be attached
- `const struct helene_config *config`: pointer to [`struct helene_config`](#c-struct-helene_config) with tuner configuration.
- `struct i2c_adapter *i2c`: i2c adapter to use.

**Return**

FE pointer on success, NULL on failure.

#### <a id="c-helene_attach_s"></a>`helene_attach_s()`

```c
struct dvb_frontend * helene_attach_s(struct dvb_frontend *fe, const struct helene_config *config, struct i2c_adapter *i2c)
```

Attach a helene tuner (satellite standards)

**Parameters**

- `struct dvb_frontend *fe`: frontend to be attached
- `const struct helene_config *config`: pointer to [`struct helene_config`](#c-struct-helene_config) with tuner configuration.
- `struct i2c_adapter *i2c`: i2c adapter to use.

**Return**

FE pointer on success, NULL on failure.



#### <a id="c-struct-horus3a_config"></a>`struct horus3a_config`

the configuration of Horus3A tuner driver

**Definition**

```c
struct horus3a_config {
    u8 i2c_address;
    u8 xtal_freq_mhz;
    void *set_tuner_priv;
    int (*set_tuner_callback)(void *, int);
};
```

**Members**

- `i2c_address`: I2C address of the tuner
- `xtal_freq_mhz`: Oscillator frequency, MHz
- `set_tuner_priv`: Callback function private context
- `set_tuner_callback`: Callback function that notifies the parent driver
  which tuner is active now

#### <a id="c-horus3a_attach"></a>`horus3a_attach()`

```c
struct dvb_frontend * horus3a_attach(struct dvb_frontend *fe, const struct horus3a_config *config, struct i2c_adapter *i2c)
```

Attach a horus3a tuner

**Parameters**

- `struct dvb_frontend *fe`: frontend to be attached
- `const struct horus3a_config *config`: pointer to [`struct helene_config`](#c-struct-helene_config) with tuner configuration.
- `struct i2c_adapter *i2c`: i2c adapter to use.

**Return**

FE pointer on success, NULL on failure.



#### <a id="c-struct-ix2505v_config"></a>`struct ix2505v_config`

ix2505 attachment configuration

**Definition**

```c
struct ix2505v_config {
    u8 tuner_address;
    u8 tuner_gain;
    u8 tuner_chargepump;
    int min_delay_ms;
    u8 tuner_write_only;
};
```

**Members**

- `tuner_address`: tuner address
- `tuner_gain`: Baseband AMP gain control 0/1=0dB(default) 2=-2bB 3=-4dB
- `tuner_chargepump`: Charge pump output +/- 0=120 1=260 2=555 3=1200(default)
- `min_delay_ms`: delay after tune
- `tuner_write_only`: disables reads

#### <a id="c-ix2505v_attach"></a>`ix2505v_attach()`

```c
struct dvb_frontend * ix2505v_attach(struct dvb_frontend *fe, const struct ix2505v_config *config, struct i2c_adapter *i2c)
```

Attach a ix2505v tuner to the supplied frontend structure.

**Parameters**

- `struct dvb_frontend *fe`: Frontend to attach to.
- `const struct ix2505v_config *config`: pointer to [`struct ix2505v_config`](#c-struct-ix2505v_config)
- `struct i2c_adapter *i2c`: pointer to `struct i2c_adapter`.

**Return**

FE pointer on success, NULL on failure.



#### <a id="c-enum-m88ds3103_ts_mode"></a>`enum m88ds3103_ts_mode`

TS connection mode

**Constants**

- `M88DS3103_TS_SERIAL`: TS output pin D0, normal
- `M88DS3103_TS_SERIAL_D7`: TS output pin D7
- `M88DS3103_TS_PARALLEL`: TS Parallel mode
- `M88DS3103_TS_CI`: TS CI Mode

#### <a id="c-enum-m88ds3103_clock_out"></a>`enum m88ds3103_clock_out`

**Constants**

- `M88DS3103_CLOCK_OUT_DISABLED`: Clock output is disabled
- `M88DS3103_CLOCK_OUT_ENABLED`: Clock output is enabled with crystal
  clock.
- `M88DS3103_CLOCK_OUT_ENABLED_DIV2`: Clock output is enabled with half
  crystal clock.

#### <a id="c-struct-m88ds3103_platform_data"></a>`struct m88ds3103_platform_data`

Platform data for the m88ds3103 driver

**Definition**

```c
struct m88ds3103_platform_data {
    u32 clk;
    u16 i2c_wr_max;
    enum m88ds3103_ts_mode ts_mode;
    u32 ts_clk;
    enum m88ds3103_clock_out clk_out;
    u8 ts_clk_pol:1;
    u8 spec_inv:1;
    u8 agc;
    u8 agc_inv:1;
    u8 envelope_mode:1;
    u8 lnb_hv_pol:1;
    u8 lnb_en_pol:1;
    struct dvb_frontend* (*get_dvb_frontend)(struct i2c_client *);
    struct i2c_adapter* (*get_i2c_adapter)(struct i2c_client *);
};
```

**Members**

- `clk`: Clock frequency.
- `i2c_wr_max`: Max bytes I2C adapter can write at once.
- `ts_mode`: TS mode.
- `ts_clk`: TS clock (KHz).
- `clk_out`: Clock output.
- `ts_clk_pol`: TS clk polarity. 1-active at falling edge; 0-active at rising
  edge.
- `spec_inv`: Input spectrum inversion.
- `agc`: AGC configuration.
- `agc_inv`: AGC polarity.
- `envelope_mode`: DiSEqC envelope mode.
- `lnb_hv_pol`: LNB H/V pin polarity. 0: pin high set to VOLTAGE_18, pin low to
  set VOLTAGE_13. 1: pin high set to VOLTAGE_13, pin low to set VOLTAGE_18.
- `lnb_en_pol`: LNB enable pin polarity. 0: pin high to disable, pin low to
  enable. 1: pin high to enable, pin low to disable.
- `get_dvb_frontend`: Get DVB frontend.
- `get_i2c_adapter`: Get I2C adapter.

#### <a id="c-struct-m88ds3103_config"></a>`struct m88ds3103_config`

m88ds3102 configuration

**Definition**

```c
struct m88ds3103_config {
    u8 i2c_addr;
    u32 clock;
    u16 i2c_wr_max;
    u8 ts_mode;
    u32 ts_clk;
    u8 ts_clk_pol:1;
    u8 spec_inv:1;
    u8 agc_inv:1;
    u8 clock_out;
    u8 envelope_mode:1;
    u8 agc;
    u8 lnb_hv_pol:1;
    u8 lnb_en_pol:1;
};
```

**Members**

- `i2c_addr`: I2C address. Default: none, must set. Example: 0x68, ...
- `clock`: Device's clock. Default: none, must set. Example: 27000000
- `i2c_wr_max`: Max bytes I2C provider is asked to write at once.
  Default: none, must set. Example: 33, 65, ...
- `ts_mode`: TS output mode, as defined by [`enum m88ds3103_ts_mode`](#c-enum-m88ds3103_ts_mode).
  Default: M88DS3103_TS_SERIAL.
- `ts_clk`: TS clk in KHz. Default: 0.
- `ts_clk_pol`: TS clk polarity.Default: 0.
  1-active at falling edge; 0-active at rising edge.
- `spec_inv`: Spectrum inversion. Default: 0.
- `agc_inv`: AGC polarity. Default: 0.
- `clock_out`: Clock output, as defined by [`enum m88ds3103_clock_out`](#c-enum-m88ds3103_clock_out).
  Default: M88DS3103_CLOCK_OUT_DISABLED.
- `envelope_mode`: DiSEqC envelope mode. Default: 0.
- `agc`: AGC configuration. Default: none, must set.
- `lnb_hv_pol`: LNB H/V pin polarity. Default: 0. Values:
  1: pin high set to VOLTAGE_13, pin low to set VOLTAGE_18;
  0: pin high set to VOLTAGE_18, pin low to set VOLTAGE_13.
- `lnb_en_pol`: LNB enable pin polarity. Default: 0. Values:
  1: pin high to enable, pin low to disable;
  0: pin high to disable, pin low to enable.

#### <a id="c-m88ds3103_attach"></a>`m88ds3103_attach()`

```c
struct dvb_frontend * m88ds3103_attach(const struct m88ds3103_config *config, struct i2c_adapter *i2c, struct i2c_adapter **tuner_i2c)
```

Attach a m88ds3103 demod

**Parameters**

- `const struct m88ds3103_config *config`: pointer to [`struct m88ds3103_config`](#c-struct-m88ds3103_config) with demod configuration.
- `struct i2c_adapter *i2c`: i2c adapter to use.
- `struct i2c_adapter **tuner_i2c`: on success, returns the I2C adapter associated with
  m88ds3103 tuner.

**Return**

FE pointer on success, NULL on failure.

**Note**

Do not add new [`m88ds3103_attach()`](#c-m88ds3103_attach) users! Use I2C bindings instead.



#### <a id="c-struct-mb86a20s_config"></a>`struct mb86a20s_config`

Define the per-device attributes of the frontend

**Definition**

```c
struct mb86a20s_config {
    u32 fclk;
    u8 demod_address;
    bool is_serial;
};
```

**Members**

- `fclk`: Clock frequency. If zero, assumes the default
  (32.57142 Mhz)
- `demod_address`: the demodulator's i2c address
- `is_serial`: if true, TS is serial. Otherwise, TS is parallel

#### <a id="c-mb86a20s_attach"></a>`mb86a20s_attach()`

```c
struct dvb_frontend * mb86a20s_attach(const struct mb86a20s_config *config, struct i2c_adapter *i2c)
```

Attach a mb86a20s demod

**Parameters**

- `const struct mb86a20s_config *config`: pointer to [`struct mb86a20s_config`](#c-struct-mb86a20s_config) with demod configuration.
- `struct i2c_adapter *i2c`: i2c adapter to use.

**Return**

FE pointer on success, NULL on failure.



#### <a id="c-struct-mn88472_config"></a>`struct mn88472_config`

Platform data for the mn88472 driver

**Definition**

```c
struct mn88472_config {
        unsigned int xtal;
    #define MN88472_TS_MODE_SERIAL      0;
    #define MN88472_TS_MODE_PARALLEL    1;
        int ts_mode;
    #define MN88472_TS_CLK_FIXED        0;
    #define MN88472_TS_CLK_VARIABLE     1;
        int ts_clock;
        u16 i2c_wr_max;
        struct dvb_frontend **fe;
        struct dvb_frontend* (*get_dvb_frontend)(struct i2c_client *);
};
```

**Members**

- `xtal`: Clock frequency.
- `ts_mode`: TS mode.
- `ts_clock`: TS clock config.
- `i2c_wr_max`: Max number of bytes driver writes to I2C at once.
- `fe`: pointer to a frontend pointer
- `get_dvb_frontend`: Get DVB frontend callback.



#### <a id="c-struct-rtl2830_platform_data"></a>`struct rtl2830_platform_data`

Platform data for the rtl2830 driver

**Definition**

```c
struct rtl2830_platform_data {
    u32 clk;
    bool spec_inv;
    u8 vtop;
    u8 krf;
    u8 agc_targ_val;
    struct dvb_frontend* (*get_dvb_frontend)(struct i2c_client *);
    struct i2c_adapter* (*get_i2c_adapter)(struct i2c_client *);
    int (*pid_filter)(struct dvb_frontend *, u8, u16, int);
    int (*pid_filter_ctrl)(struct dvb_frontend *, int);
};
```

**Members**

- `clk`: Clock frequency (4000000, 16000000, 25000000, 28800000).
- `spec_inv`: Spectrum inversion.
- `vtop`: AGC take-over point.
- `krf`: AGC ratio.
- `agc_targ_val`: AGC.
- `get_dvb_frontend`: Get DVB frontend.
- `get_i2c_adapter`: Get I2C adapter.
- `pid_filter`: Set PID to PID filter.
- `pid_filter_ctrl`: Control PID filter.



#### <a id="c-struct-rtl2832_platform_data"></a>`struct rtl2832_platform_data`

Platform data for the rtl2832 driver

**Definition**

```c
struct rtl2832_platform_data {
        u32 clk;
    #define RTL2832_TUNER_FC2580    0x21;
    #define RTL2832_TUNER_TUA9001   0x24;
    #define RTL2832_TUNER_FC0012    0x26;
    #define RTL2832_TUNER_E4000     0x27;
    #define RTL2832_TUNER_FC0013    0x29;
    #define RTL2832_TUNER_R820T     0x2a;
    #define RTL2832_TUNER_R828D     0x2b;
    #define RTL2832_TUNER_SI2157    0x2c;
        u8 tuner;
        struct dvb_frontend* (*get_dvb_frontend)(struct i2c_client *);
        struct i2c_adapter* (*get_i2c_adapter)(struct i2c_client *);
        int (*slave_ts_ctrl)(struct i2c_client *, bool);
        int (*pid_filter)(struct dvb_frontend *, u8, u16, int);
        int (*pid_filter_ctrl)(struct dvb_frontend *, int);
};
```

**Members**

- `clk`: Clock frequency (4000000, 16000000, 25000000, 28800000).
- `tuner`: Used tuner model.
- `get_dvb_frontend`: Get DVB frontend.
- `get_i2c_adapter`: Get I2C adapter.
- `slave_ts_ctrl`: Control slave TS interface.
- `pid_filter`: Set PID to PID filter.
- `pid_filter_ctrl`: Control PID filter.



#### <a id="c-struct-rtl2832_sdr_platform_data"></a>`struct rtl2832_sdr_platform_data`

Platform data for the rtl2832_sdr driver

**Definition**

```c
struct rtl2832_sdr_platform_data {
        u32 clk;
    #define RTL2832_SDR_TUNER_FC2580    0x21;
    #define RTL2832_SDR_TUNER_TUA9001   0x24;
    #define RTL2832_SDR_TUNER_FC0012    0x26;
    #define RTL2832_SDR_TUNER_E4000     0x27;
    #define RTL2832_SDR_TUNER_FC0013    0x29;
    #define RTL2832_SDR_TUNER_R820T     0x2a;
    #define RTL2832_SDR_TUNER_R828D     0x2b;
        u8 tuner;
        struct regmap *regmap;
        struct dvb_frontend *dvb_frontend;
        struct v4l2_subdev *v4l2_subdev;
        struct dvb_usb_device *dvb_usb_device;
};
```

**Members**

- `clk`: Clock frequency (4000000, 16000000, 25000000, 28800000).
- `tuner`: Used tuner model.
- `regmap`: pointer to `struct regmap`.
- `dvb_frontend`: rtl2832 DVB frontend.
- `v4l2_subdev`: Tuner v4l2 controls.
- `dvb_usb_device`: DVB USB interface for USB streaming.



#### <a id="c-stb6000_attach"></a>`stb6000_attach()`

```c
struct dvb_frontend * stb6000_attach(struct dvb_frontend *fe, int addr, struct i2c_adapter *i2c)
```

Attach a stb6000 tuner to the supplied frontend structure.

**Parameters**

- `struct dvb_frontend *fe`: Frontend to attach to.
- `int addr`: i2c address of the tuner.
- `struct i2c_adapter *i2c`: i2c adapter to use.

**Return**

FE pointer on success, NULL on failure.



#### <a id="c-struct-tda10071_platform_data"></a>`struct tda10071_platform_data`

Platform data for the tda10071 driver

**Definition**

```c
struct tda10071_platform_data {
        u32 clk;
        u16 i2c_wr_max;
    #define TDA10071_TS_SERIAL        0;
    #define TDA10071_TS_PARALLEL      1;
        u8 ts_mode;
        bool spec_inv;
        u8 pll_multiplier;
        u8 tuner_i2c_addr;
        struct dvb_frontend* (*get_dvb_frontend)(struct i2c_client *);
};
```

**Members**

- `clk`: Clock frequency.
- `i2c_wr_max`: Max bytes I2C adapter can write at once.
- `ts_mode`: TS mode.
- `spec_inv`: Input spectrum inversion.
- `pll_multiplier`: PLL multiplier.
- `tuner_i2c_addr`: CX24118A tuner I2C address (0x14, 0x54, ...).
- `get_dvb_frontend`: Get DVB frontend.



#### <a id="c-tda826x_attach"></a>`tda826x_attach()`

```c
struct dvb_frontend* tda826x_attach(struct dvb_frontend *fe, int addr, struct i2c_adapter *i2c, int has_loopthrough)
```

Attach a tda826x tuner to the supplied frontend structure.

**Parameters**

- `struct dvb_frontend *fe`: Frontend to attach to.
- `int addr`: i2c address of the tuner.
- `struct i2c_adapter *i2c`: i2c adapter to use.
- `int has_loopthrough`: Set to 1 if the card has a loopthrough RF connector.

**Return**

FE pointer on success, NULL on failure.



#### <a id="c-struct-zd1301_demod_platform_data"></a>`struct zd1301_demod_platform_data`

Platform data for the zd1301_demod driver

**Definition**

```c
struct zd1301_demod_platform_data {
    void *reg_priv;
    int (*reg_read)(void *, u16, u8 *);
    int (*reg_write)(void *, u16, u8);
};
```

**Members**

- `reg_priv`: First argument of reg_read and reg_write callbacks.
- `reg_read`: Register read callback.
- `reg_write`: Register write callback.

#### <a id="c-zd1301_demod_get_dvb_frontend"></a>`zd1301_demod_get_dvb_frontend()`

```c
struct dvb_frontend * zd1301_demod_get_dvb_frontend(struct platform_device *pdev)
```

Get pointer to DVB frontend

**Parameters**

- `struct platform_device *pdev`: Pointer to platform device

**Return**

Pointer to DVB frontend which given platform device owns.

#### <a id="c-zd1301_demod_get_i2c_adapter"></a>`zd1301_demod_get_i2c_adapter()`

```c
struct i2c_adapter * zd1301_demod_get_i2c_adapter(struct platform_device *pdev)
```

Get pointer to I2C adapter

**Parameters**

- `struct platform_device *pdev`: Pointer to platform device

**Return**

Pointer to I2C adapter which given platform device owns.



#### <a id="c-zl10036_attach"></a>`zl10036_attach()`

```c
struct dvb_frontend * zl10036_attach(struct dvb_frontend *fe, const struct zl10036_config *config, struct i2c_adapter *i2c)
```

Attach a zl10036 tuner to the supplied frontend structure.

**Parameters**

- `struct dvb_frontend *fe`: Frontend to attach to.
- `const struct zl10036_config *config`: zl10036_config structure.
- `struct i2c_adapter *i2c`: pointer to struct i2c_adapter.

**Return**

FE pointer on success, NULL on failure.

---

# Intel IPU6 Driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Author: Bingbu Cao <bingbu.cao@intel.com>

<a id="rst-intel-ipu6-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Author: Bingbu Cao &lt;[bingbu.cao@intel.com](<mailto:bingbu.cao@intel.com>)&gt;

<a id="rst-overview"></a>

## Overview

Intel IPU6 is the sixth generation of Intel Image Processing Unit used in some Intel Chipsets such as Tiger Lake, Jasper Lake, Alder Lake, Raptor Lake and Meteor Lake. IPU6 consists of two major systems: Input System (ISYS) and Processing System (PSYS). IPU6 are visible on the PCI bus as a single device, it can be found by `lspci`:

`0000:00:05.0 Multimedia controller: Intel Corporation Device xxxx (rev xx)`

IPU6 has a 16 MB BAR in PCI configuration Space for MMIO registers which is visible for driver.

<a id="rst-buttress"></a>

## Buttress

The IPU6 is connecting to the system fabric with Buttress which is enabling host driver to control the IPU6, it also allows IPU6 access the system memory to store and load frame pixel streams and any other metadata.

Buttress mainly manages several system functionalities: power management, interrupt handling, firmware authentication and global timer sync.

<a id="rst-isys-and-psys-power-flow"></a>

### ISYS and PSYS Power flow

IPU6 driver initialize the ISYS and PSYS power up or down request by setting the Buttress frequency control register for ISYS and PSYS (`IPU6_BUTTRESS_REG_IS_FREQ_CTL` and `IPU6_BUTTRESS_REG_PS_FREQ_CTL`) in function:





<a id="c-ipu6_buttress_power"></a>

```c
int ipu6_buttress_power(...)
```

Buttress forwards the request to Punit, after Punit execute the power up flow, Buttress indicates driver that ISYS or PSYS is powered up by updating the power status registers.

> [!NOTE]
>
> ISYS power up needs take place prior to PSYS power up, ISYS power down needs take place after PSYS power down due to hardware limitation.

<a id="rst-interrupt"></a>

### Interrupt

IPU6 interrupt can be generated as MSI or INTA, interrupt will be triggered when ISYS, PSYS, Buttress event or error happen, driver can get the interrupt cause by reading the interrupt status register `BUTTRESS_REG_ISR_STATUS`, driver clears the irq status and then calls specific ISYS or PSYS irq handler.





<a id="c-ipu6_buttress_isr"></a>

```c
irqreturn_t ipu6_buttress_isr(int irq, ...)
```

<a id="rst-security-and-firmware-authentication"></a>

### Security and firmware authentication

To address the IPU6 firmware security concerns, the IPU6 firmware needs to undergo an authentication process before it is allowed to executed on the IPU6 internal processors. The IPU6 driver will work with Converged Security Engine (CSE) to complete authentication process. The CSE is responsible of authenticating the IPU6 firmware. The authenticated firmware binary is copied into an isolated memory region. Firmware authentication process is implemented by CSE following an IPC handshake with the IPU6 driver. There are some Buttress registers used by the CSE and the IPU6 driver to communicate with each other via IPC.





<a id="c-ipu6_buttress_authenticate"></a>

```c
int ipu6_buttress_authenticate(...)
```

<a id="rst-global-timer-sync"></a>

### Global timer sync

The IPU6 driver initiates a Hammock Harbor synchronization flow each time it starts camera operation. The IPU6 will synchronizes an internal counter in the Buttress with a copy of the SoC time, this counter maintains the up-to-date time until camera operation is stopped. The IPU6 driver can use this time counter to calibrate the timestamp based on the timestamp in response event from firmware.





<a id="c-ipu6_buttress_start_tsc_sync"></a>

```c
int ipu6_buttress_start_tsc_sync(...)
```

<a id="rst-dma-and-mmu"></a>

## DMA and MMU

The IPU6 has its own scalar processor where the firmware run at and an internal 32-bit virtual address space. The IPU6 has MMU address translation hardware to allow that scalar processors to access the internal memory and external system memory through IPU6 virtual address. The address translation is based on two levels of page lookup tables stored in system memory which are maintained by the IPU6 driver. The IPU6 driver sets the level-1 page table base address to MMU register and allows MMU to perform page table lookups.

The IPU6 driver exports its own DMA operations. The IPU6 driver will update the page table entries for each DMA operation and invalidate the MMU TLB after each unmap and free.

<a id="rst-firmware-file-format"></a>

## Firmware file format

The IPU6 firmware is in Code Partition Directory (CPD) file format. The CPD firmware contains a CPD header, several CPD entries and components. The CPD component includes 3 entries - manifest, metadata and module data. Manifest and metadata are defined by CSE and used by CSE for authentication. Module data is specific to IPU6 which holds the binary data of firmware called package directory. The IPU6 driver (`ipu6-cpd.c` in particular) parses and validates the CPD firmware file and gets the package directory binary data of the IPU6 firmware, copies it to specific DMA buffer and sets its base address to Buttress `FW_SOURCE_BASE` register. Finally the CSE will do authentication for this firmware binary.

<a id="rst-syscom-interface"></a>

## Syscom interface

The IPU6 driver communicates with firmware via the Syscom ABI. Syscom is an inter-processor communication mechanism between the IPU scalar processors and the CPU. There are a number of resources shared between firmware and software. A system memory region where the message queues reside, firmware can access the memory region via the IPU MMU. The Syscom queues are FIFO fixed depth queues with a configurable number of tokens (messages). There are also common IPU6 MMIO registers where the queue read and write indices reside. Software and firmware function as producer and consumer of tokens in the queues and update the write and read indices separately when sending or receiving each message.

The IPU6 driver must prepare and configure the number of input and output queues, configure the count of tokens per queue and the size of per token before initiating and starting the communication with firmware. Firmware and software must use same configurations. The IPU6 Buttress has a number of firmware boot parameter registers which can be used to store the address of configuration and initialise the Syscom state, then driver can request firmware to start and run via setting the scalar processor control status register.

<a id="rst-input-system"></a>

## Input System

IPU6 input system consists of MIPI D-PHY and several CSI-2 receivers.  It can capture image pixel data from camera sensors or other MIPI CSI-2 output devices.

<a id="rst-d-phys-and-csi-2-ports-lane-mapping"></a>

### D-PHYs and CSI-2 ports lane mapping

The IPU6 integrates different D-PHY IPs on different SoCs, on Tiger Lake and Alder Lake, IPU6 integrates MCD10 D-PHY, IPU6SE on Jasper Lake integrates JSL D-PHY and IPU6EP on Meteor Lake integrates a Synopsys DWC D-PHY. There is an adaptional layer between D-PHY and CSI-2 receiver controller which includes port configuration, PHY wrapper or private test interfaces for D-PHY. There are 3 D-PHY drivers `ipu6-isys-mcd-phy.c`, `ipu6-isys-jsl-phy.c` and `ipu6-isys-dwc-phy.c` program the above 3 D-PHYs in IPU6.

Different IPU6 versions have different D-PHY lanes mappings, On Tiger Lake, there are 12 data lanes and 8 clock lanes, IPU6 support maximum 8 CSI-2 ports, see the PPI mmapping in `ipu6-isys-mcd-phy.c` for more information. On Jasper Lake and Alder Lake, D-PHY has 8 data lanes and 4 clock lanes, the IPU6 supports maximum 4 CSI-2 ports. For Meteor Lake, D-PHY has 12 data lanes and 6 clock lanes so IPU6 support maximum 6 CSI-2 ports.

> [!NOTE]
>
> Each pair of CSI-2 two ports is a single unit that can share the data lanes. For example, for CSI-2 port 0 and 1, CSI-2 port 0 support maximum 4 data lanes, CSI-2 port 1 support maximum 2 data lanes, CSI-2 port 0 with 2 data lanes can work together with CSI-2 port 1 with 2 data lanes. If trying to use CSI-2 port 0 with 4 lanes, CSI-2 port 1 will not be available as the 4 data lanes are shared by CSI-2 port 0 and 1. The same applies to CSI ports 2/3, 4/5 and 7/8.

<a id="rst-isys-firmware-abis"></a>

### ISYS firmware ABIs

The IPU6 firmware implements a series of ABIs for software access. In general, software firstly prepares the stream configuration `struct ipu6_fw_isys_stream_cfg_data_abi` and sends the configuration to firmware via sending `STREAM_OPEN` command. Stream configuration includes input pins and output pins, input pin `struct ipu6_fw_isys_input_pin_info_abi` defines the resolution and data type of input source, output pin `struct ipu6_fw_isys_output_pin_info_abi` defines the output resolution, stride and frame format, etc.

Once the driver gets the interrupt from firmware that indicates stream open successfully, the driver will send the `STREAM_START` and `STREAM_CAPTURE` command to request firmware to start capturing image frames. `STREAM_CAPTURE` command queues the buffers to firmware with `struct ipu6_fw_isys_frame_buff_set`, software then waits for the interrupt and response from firmware, `PIN_DATA_READY` means a buffer is ready on a specific output pin and then software can return the buffer to user.

> [!NOTE]
>
> See [Examples](</kernel/administration/admin-guide/media/ipu6-isys.md#rst-ipu6-isys-capture-examples>) about how to do capture by IPU6 ISYS driver.

---

# The pvrusb2 driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Author: Mike Isely <isely@pobox.com>

<a id="rst-the-pvrusb2-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Author: Mike Isely &lt;[isely@pobox.com](<mailto:isely@pobox.com>)&gt;

<a id="rst-background"></a>

## Background

This driver is intended for the "Hauppauge WinTV PVR USB 2.0", which is a USB 2.0 hosted TV Tuner.  This driver is a work in progress. Its history started with the reverse-engineering effort by Björn Danielsson &lt;[pvrusb2@dax.nu](<mailto:pvrusb2@dax.nu>)&gt; whose web page can be found here: [http://pvrusb2.dax.nu/](<http://pvrusb2.dax.nu/>)

From there Aurelien Alleaume &lt;[slts@free.fr](<mailto:slts@free.fr>)&gt; began an effort to create a video4linux compatible driver.  I began with Aurelien's last known snapshot and evolved the driver to the state it is in here.

More information on this driver can be found at: [https://www.isely.net/pvrusb2.html](<https://www.isely.net/pvrusb2.html>)

This driver has a strong separation of layers.  They are very roughly:

1. Low level wire-protocol implementation with the device.

2. I2C adaptor implementation and corresponding I2C client drivers implemented elsewhere in V4L.

3. High level hardware driver implementation which coordinates all activities that ensure correct operation of the device.

4. A "context" layer which manages instancing of driver, setup, tear-down, arbitration, and interaction with high level interfaces appropriately as devices are hotplugged in the system.

5. High level interfaces which glue the driver to various published Linux APIs (V4L, sysfs, maybe DVB in the future).

The most important shearing layer is between the top 2 layers.  A lot of work went into the driver to ensure that any kind of conceivable API can be laid on top of the core driver.  (Yes, the driver internally leverages V4L to do its work but that really has nothing to do with the API published by the driver to the outside world.)  The architecture allows for different APIs to simultaneously access the driver.  I have a strong sense of fairness about APIs and also feel that it is a good design principle to keep implementation and interface isolated from each other.  Thus while right now the V4L high level interface is the most complete, the sysfs high level interface will work equally well for similar functions, and there's no reason I see right now why it shouldn't be possible to produce a DVB high level interface that can sit right alongside V4L.

<a id="rst-building"></a>

## Building

To build these modules essentially amounts to just running "Make", but you need the kernel source tree nearby and you will likely also want to set a few controlling environment variables first in order to link things up with that source tree.  Please see the Makefile here for comments that explain how to do that.

<a id="rst-source-file-list-functional-overview"></a>

## Source file list / functional overview

(Note: The term "module" used below generally refers to loosely defined functional units within the pvrusb2 driver and bears no relation to the Linux kernel's concept of a loadable module.)

- **pvrusb2-audio.\[ch\] - This is glue logic that resides between this**

  driver and the msp3400.ko I2C client driver (which is found elsewhere in V4L).

- **pvrusb2-context.\[ch\] - This module implements the context for an**

  instance of the driver.  Everything else eventually ties back to or is otherwise instanced within the data structures implemented here.  Hotplugging is ultimately coordinated here.  All high level interfaces tie into the driver through this module.  This module helps arbitrate each interface's access to the actual driver core, and is designed to allow concurrent access through multiple instances of multiple interfaces (thus you can for example change the tuner's frequency through sysfs while simultaneously streaming video through V4L out to an instance of mplayer).

- **pvrusb2-debug.h - This header defines a printk() wrapper and a mask**

  of debugging bit definitions for the various kinds of debug messages that can be enabled within the driver.

- **pvrusb2-debugifc.\[ch\] - This module implements a crude command line**

  oriented debug interface into the driver.  Aside from being part of the process for implementing manual firmware extraction (see the pvrusb2 web site mentioned earlier), probably I'm the only one who has ever used this.  It is mainly a debugging aid.

- **pvrusb2-eeprom.\[ch\] - This is glue logic that resides between this**

  driver the tveeprom.ko module, which is itself implemented elsewhere in V4L.

- **pvrusb2-encoder.\[ch\] - This module implements all protocol needed to**

  interact with the Conexant mpeg2 encoder chip within the pvrusb2 device.  It is a crude echo of corresponding logic in ivtv, however the design goals (strict isolation) and physical layer (proxy through USB instead of PCI) are enough different that this implementation had to be completely different.

- **pvrusb2-hdw-internal.h - This header defines the core data structure**

  in the driver used to track ALL internal state related to control of the hardware.  Nobody outside of the core hardware-handling modules should have any business using this header.  All external access to the driver should be through one of the high level interfaces (e.g. V4L, sysfs, etc), and in fact even those high level interfaces are restricted to the API defined in pvrusb2-hdw.h and NOT this header.

- **pvrusb2-hdw.h - This header defines the full internal API for**

  controlling the hardware.  High level interfaces (e.g. V4L, sysfs) will work through here.

- **pvrusb2-hdw.c - This module implements all the various bits of logic**

  that handle overall control of a specific pvrusb2 device. (Policy, instantiation, and arbitration of pvrusb2 devices fall within the jurisdiction of pvrusb-context not here).

- **pvrusb2-i2c-chips-\*.c - These modules implement the glue logic to**

  tie together and configure various I2C modules as they attach to the I2C bus.  There are two versions of this file.  The "v4l2" version is intended to be used in-tree alongside V4L, where we implement just the logic that makes sense for a pure V4L environment.  The "all" version is intended for use outside of V4L, where we might encounter other possibly "challenging" modules from ivtv or older kernel snapshots (or even the support modules in the standalone snapshot).

- **pvrusb2-i2c-cmd-v4l1.\[ch\] - This module implements generic V4L1**

  compatible commands to the I2C modules.  It is here where state changes inside the pvrusb2 driver are translated into V4L1 commands that are in turn send to the various I2C modules.

- **pvrusb2-i2c-cmd-v4l2.\[ch\] - This module implements generic V4L2**

  compatible commands to the I2C modules.  It is here where state changes inside the pvrusb2 driver are translated into V4L2 commands that are in turn send to the various I2C modules.

- **pvrusb2-i2c-core.\[ch\] - This module provides an implementation of a**

  kernel-friendly I2C adaptor driver, through which other external I2C client drivers (e.g. msp3400, tuner, lirc) may connect and operate corresponding chips within the pvrusb2 device.  It is through here that other V4L modules can reach into this driver to operate specific pieces (and those modules are in turn driven by glue logic which is coordinated by pvrusb2-hdw, doled out by pvrusb2-context, and then ultimately made available to users through one of the high level interfaces).

- **pvrusb2-io.\[ch\] - This module implements a very low level ring of**

  transfer buffers, required in order to stream data from the device.  This module is *very* low level.  It only operates the buffers and makes no attempt to define any policy or mechanism for how such buffers might be used.

- **pvrusb2-ioread.\[ch\] - This module layers on top of pvrusb2-io.\[ch\]**

  to provide a streaming API usable by a read() system call style of I/O.  Right now this is the only layer on top of pvrusb2-io.\[ch\], however the underlying architecture here was intended to allow for other styles of I/O to be implemented with additional modules, like mmap()'ed buffers or something even more exotic.

- **pvrusb2-main.c - This is the top level of the driver.  Module level**

  and USB core entry points are here.  This is our "main".

- **pvrusb2-sysfs.\[ch\] - This is the high level interface which ties the**

  pvrusb2 driver into sysfs.  Through this interface you can do everything with the driver except actually stream data.

- **pvrusb2-tuner.\[ch\] - This is glue logic that resides between this**

  driver and the tuner.ko I2C client driver (which is found elsewhere in V4L).

- **pvrusb2-util.h - This header defines some common macros used**

  throughout the driver.  These macros are not really specific to the driver, but they had to go somewhere.

- **pvrusb2-v4l2.\[ch\] - This is the high level interface which ties the**

  pvrusb2 driver into video4linux.  It is through here that V4L applications can open and operate the driver in the usual V4L ways.  Note that **ALL** V4L functionality is published only through here and nowhere else.

- **pvrusb2-video-\*.\[ch\] - This is glue logic that resides between this**

  driver and the saa711x.ko I2C client driver (which is found elsewhere in V4L).  Note that saa711x.ko used to be known as saa7115.ko in ivtv.  There are two versions of this; one is selected depending on the particular saa711\[5x\].ko that is found.

- **pvrusb2.h - This header contains compile time tunable parameters**

  (and at the moment the driver has very little that needs to be tuned).

---

# PXA-Camera Host Driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Author: Robert Jarzmik <robert.jarzmik@free.fr>

<a id="rst-pxa-camera-host-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Author: Robert Jarzmik &lt;[robert.jarzmik@free.fr](<mailto:robert.jarzmik@free.fr>)&gt;

<a id="rst-constraints"></a>

## Constraints

- **a)** Image size for YUV422P format All YUV422P images are enforced to have width x height % 16 = 0. This is due to DMA constraints, which transfers only planes of 8 byte multiples.

<a id="rst-global-video-workflow"></a>

## Global video workflow

- **a)** QCI stopped Initially, the QCI interface is stopped. When a buffer is queued, start_streaming is called and the QCI starts.

- **b)** QCI started More buffers can be queued while the QCI is started without halting the capture.  The new buffers are "appended" at the tail of the DMA chain, and smoothly captured one frame after the other.

  Once a buffer is filled in the QCI interface, it is marked as "DONE" and removed from the active buffers list. It can be then requeud or dequeued by userland application.

  Once the last buffer is filled in, the QCI interface stops.

- **c)** Capture global finite state machine schema



```none
+----+                             +---+  +----+
| DQ |                             | Q |  | DQ |
|    v                             |   v  |    v
+-----------+                     +------------------------+
|   STOP    |                     | Wait for capture start |
+-----------+         Q           +------------------------+
+-> | QCI: stop | ------------------> | QCI: run               | <------------+
|   | DMA: stop |                     | DMA: stop              |              |
|   +-----------+             +-----> +------------------------+              |
|                            /                            |                   |
|                           /             +---+  +----+   |                   |
|capture list empty        /              | Q |  | DQ |   | QCI Irq EOF       |
|                         /               |   v  |    v   v                   |
|   +--------------------+             +----------------------+               |
|   | DMA hotlink missed |             |    Capture running   |               |
|   +--------------------+             +----------------------+               |
|   | QCI: run           |     +-----> | QCI: run             | <-+           |
|   | DMA: stop          |    /        | DMA: run             |   |           |
|   +--------------------+   /         +----------------------+   | Other     |
|     ^                     /DMA still            |               | channels  |
|     | capture list       /  running             | DMA Irq End   | not       |
|     | not empty         /                       |               | finished  |
|     |                  /                        v               | yet       |
|   +----------------------+           +----------------------+   |           |
|   |  Videobuf released   |           |  Channel completed   |   |           |
|   +----------------------+           +----------------------+   |           |
+-- | QCI: run             |           | QCI: run             | --+           |
| DMA: run             |           | DMA: run             |               |
+----------------------+           +----------------------+               |
        ^                      /           |                           |
        |          no overrun /            | overrun                   |
        |                    /             v                           |
+--------------------+         /   +----------------------+               |
|  Frame completed   |        /    |     Frame overran    |               |
+--------------------+ <-----+     +----------------------+ restart frame |
| QCI: run           |             | QCI: stop            | --------------+
| DMA: run           |             | DMA: stop            |
+--------------------+             +----------------------+

Legend: - each box is a FSM state
        - each arrow is the condition to transition to another state
        - an arrow with a comment is a mandatory transition (no condition)
        - arrow "Q" means : a buffer was enqueued
        - arrow "DQ" means : a buffer was dequeued
        - "QCI: stop" means the QCI interface is not enabled
        - "DMA: stop" means all 3 DMA channels are stopped
        - "DMA: run" means at least 1 DMA channel is still running
```

<a id="rst-dma-usage"></a>

## DMA usage

- **a)** - **DMA flow**

    - first buffer queued for capture Once a first buffer is queued for capture, the QCI is started, but data transfer is not started. On "End Of Frame" interrupt, the irq handler starts the DMA chain.

    - capture of one videobuffer The DMA chain starts transferring data into videobuffer RAM pages. When all pages are transferred, the DMA irq is raised on "ENDINTR" status

    - finishing one videobuffer The DMA irq handler marks the videobuffer as "done", and removes it from the active running queue Meanwhile, the next videobuffer (if there is one), is transferred by DMA

    - finishing the last videobuffer On the DMA irq of the last videobuffer, the QCI is stopped.

- **b)** DMA prepared buffer will have this structure



```none
+------------+-----+---------------+-----------------+
| desc-sg[0] | ... | desc-sg[last] | finisher/linker |
+------------+-----+---------------+-----------------+
```

This structure is pointed by dma-&gt;sg_cpu. The descriptors are used as follows:

- desc-sg\[i\]: i-th descriptor, transferring the i-th sg element to the video buffer scatter gather

- finisher: has ddadr=DADDR_STOP, dcmd=ENDIRQEN

- linker: has ddadr= desc-sg\[0\] of next video buffer, dcmd=0

For the next schema, let's assume d0=desc-sg\[0\] .. dN=desc-sg\[N\], "f" stands for finisher and "l" for linker. A typical running chain is :



```none
    Videobuffer 1         Videobuffer 2
+---------+----+---+  +----+----+----+---+
| d0 | .. | dN | l |  | d0 | .. | dN | f |
+---------+----+-|-+  ^----+----+----+---+
                 |    |
                 +----+
```

After the chaining is finished, the chain looks like :



```none
    Videobuffer 1         Videobuffer 2         Videobuffer 3
+---------+----+---+  +----+----+----+---+  +----+----+----+---+
| d0 | .. | dN | l |  | d0 | .. | dN | l |  | d0 | .. | dN | f |
+---------+----+-|-+  ^----+----+----+-|-+  ^----+----+----+---+
                 |    |                |    |
                 +----+                +----+
                                      new_link
```

- **c)** DMA hot chaining timeslice issue

As DMA chaining is done while DMA \_is\_ running, the linking may be done while the DMA jumps from one Videobuffer to another. On the schema, that would be a problem if the following sequence is encountered :

- DMA chain is Videobuffer1 + Videobuffer2

- pxa_videobuf_queue() is called to queue Videobuffer3

- DMA controller finishes Videobuffer2, and DMA stops



```none
 =>
    Videobuffer 1         Videobuffer 2
+---------+----+---+  +----+----+----+---+
| d0 | .. | dN | l |  | d0 | .. | dN | f |
+---------+----+-|-+  ^----+----+----+-^-+
                 |    |                |
                 +----+                +-- DMA DDADR loads DDADR_STOP
```

- pxa_dma_add_tail_buf() is called, the Videobuffer2 "finisher" is replaced by a "linker" to Videobuffer3 (creation of new_link)

- pxa_videobuf_queue() finishes

- the DMA irq handler is called, which terminates Videobuffer2

- Videobuffer3 capture is not scheduled on DMA chain (as it stopped \!\!\!)



```none
    Videobuffer 1         Videobuffer 2         Videobuffer 3
+---------+----+---+  +----+----+----+---+  +----+----+----+---+
| d0 | .. | dN | l |  | d0 | .. | dN | l |  | d0 | .. | dN | f |
+---------+----+-|-+  ^----+----+----+-|-+  ^----+----+----+---+
                 |    |                |    |
                 +----+                +----+
                                      new_link
                                     DMA DDADR still is DDADR_STOP
```

- pxa_camera_check_link_miss() is called This checks if the DMA is finished and a buffer is still on the pcdev-&gt;capture list. If that's the case, the capture will be restarted, and Videobuffer3 is scheduled on DMA chain.

- the DMA irq handler finishes

> [!NOTE]
>
> If DMA stops just after pxa_camera_check_link_miss() reads DDADR() value, we have the guarantee that the DMA irq handler will be called back when the DMA will finish the buffer, and pxa_camera_check_link_miss() will be called again, to reschedule Videobuffer3.

---

# The Radiotrack radio driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Author: Stephen M. Benoit <benoits@servicepro.com>

<a id="rst-the-radiotrack-radio-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Author: Stephen M. Benoit &lt;[benoits@servicepro.com](<mailto:benoits@servicepro.com>)&gt;

Date:  Dec 14, 1996

<a id="rst-acknowledgments"></a>

## ACKNOWLEDGMENTS

This document was made based on 'C' code for Linux from Gideon le Grange ([legrang@active.co.za](<mailto:legrang@active.co.za>) or [legrang@cs.sun.ac.za](<mailto:legrang@cs.sun.ac.za>)) in 1994, and elaborations from Frans Brinkman ([brinkman@esd.nl](<mailto:brinkman@esd.nl>)) in 1996.  The results reported here are from experiments that the author performed on his own setup, so your mileage may vary... I make no guarantees, claims or warranties to the suitability or validity of this information.  No other documentation on the AIMS Lab ([http://www.aimslab.com/](<http://www.aimslab.com/>)) RadioTrack card was made available to the author.  This document is offered in the hopes that it might help users who want to use the RadioTrack card in an environment other than MS Windows.

<a id="rst-why-this-document"></a>

## WHY THIS DOCUMENT?

I have a RadioTrack card from back when I ran an MS-Windows platform.  After converting to Linux, I found Gideon le Grange's command-line software for running the card, and found that it was good\!  Frans Brinkman made a comfortable X-windows interface, and added a scanning feature.  For hack value, I wanted to see if the tuner could be tuned beyond the usual FM radio broadcast band, so I could pick up the audio carriers from North American broadcast TV channels, situated just below and above the 87.0-109.0 MHz range. I did not get much success, but I learned about programming ioports under Linux and gained some insights about the hardware design used for the card.

So, without further delay, here are the details.

<a id="rst-physical-description"></a>

## PHYSICAL DESCRIPTION

The RadioTrack card is an ISA 8-bit FM radio card.  The radio frequency (RF) input is simply an antenna lead, and the output is a power audio signal available through a miniature phone plug.  Its RF frequencies of operation are more or less limited from 87.0 to 109.0 MHz (the commercial FM broadcast band).  Although the registers can be programmed to request frequencies beyond these limits, experiments did not give promising results.  The variable frequency oscillator (VFO) that demodulates the intermediate frequency (IF) signal probably has a small range of useful frequencies, and wraps around or gets clipped beyond the limits mentioned above.

<a id="rst-controlling-the-card-with-ioport"></a>

## CONTROLLING THE CARD WITH IOPORT

The RadioTrack (base) ioport is configurable for 0x30c or 0x20c.  Only one ioport seems to be involved.  The ioport decoding circuitry must be pretty simple, as individual ioport bits are directly matched to specific functions (or blocks) of the radio card.  This way, many functions can be changed in parallel with one write to the ioport.  The only feedback available through the ioports appears to be the "Stereo Detect" bit.

The bits of the ioport are arranged as follows:



```none
MSb                                                         LSb
+------+------+------+--------+--------+-------+---------+--------+
| VolA | VolB | ???? | Stereo | Radio  | TuneA | TuneB   | Tune   |
|  (+) |  (-) |      | Detect | Audio  | (bit) | (latch) | Update |
|      |      |      | Enable | Enable |       |         | Enable |
+------+------+------+--------+--------+-------+---------+--------+
```


<table>
<thead>
<tr>
<th>


VolA

</th>
<th>


VolB

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


0

</td>
<td>


audio mute

</td>
</tr>
<tr>
<td>


0

</td>
<td>


1

</td>
<td>


volume +    (some delay required)

</td>
</tr>
<tr>
<td>


1

</td>
<td>


0

</td>
<td>


volume -    (some delay required)

</td>
</tr>
<tr>
<td>


1

</td>
<td>


1

</td>
<td>


stay at present volume

</td>
</tr>
</tbody>
</table>


<table>
<thead>
<tr>
<th>


Stereo Detect Enable

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


No Detect

</td>
</tr>
<tr>
<td>


1

</td>
<td>


Detect

</td>
</tr>
</tbody>
</table>

Results available by reading ioport &gt;60 msec after last port write.

> 0xff ==&gt; no stereo detected,  0xfd ==&gt; stereo detected.


<table>
<thead>
<tr>
<th>


Radio to Audio (path) Enable

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


Disable path (silence)

</td>
</tr>
<tr>
<td>


1

</td>
<td>


Enable path  (audio produced)

</td>
</tr>
</tbody>
</table>


<table>
<thead>
<tr>
<th>


TuneA

</th>
<th>


TuneB

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


0

</td>
<td>


"zero" bit phase 1

</td>
</tr>
<tr>
<td>


0

</td>
<td>


1

</td>
<td>


"zero" bit phase 2

</td>
</tr>
<tr>
<td>


1

</td>
<td>


0

</td>
<td>


"one" bit phase 1

</td>
</tr>
<tr>
<td>


1

</td>
<td>


1

</td>
<td>


"one" bit phase 2

</td>
</tr>
</tbody>
</table>

24-bit code, where bits = (freq\*40) + 10486188. The Most Significant 11 bits must be 1010 xxxx 0x0 to be valid. The bits are shifted in LSb first.


<table>
<thead>
<tr>
<th>


Tune Update Enable

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


Tuner held constant

</td>
</tr>
<tr>
<td>


1

</td>
<td>


Tuner updating in progress

</td>
</tr>
</tbody>
</table>

<a id="rst-programming-examples"></a>

## PROGRAMMING EXAMPLES



```none
Default:        BASE <-- 0xc8  (current volume, no stereo detect,
                                radio enable, tuner adjust disable)

Card Off:       BASE <-- 0x00  (audio mute, no stereo detect,
                                radio disable, tuner adjust disable)

Card On:        BASE <-- 0x00  (see "Card Off", clears any unfinished business)
                BASE <-- 0xc8  (see "Default")

Volume Down:    BASE <-- 0x48  (volume down, no stereo detect,
                                radio enable, tuner adjust disable)
                wait 10 msec
                BASE <-- 0xc8  (see "Default")

Volume Up:      BASE <-- 0x88  (volume up, no stereo detect,
                                radio enable, tuner adjust disable)
                wait 10 msec
                BASE <-- 0xc8  (see "Default")

Check Stereo:   BASE <-- 0xd8  (current volume, stereo detect,
                                radio enable, tuner adjust disable)
                wait 100 msec
                x <-- BASE     (read ioport)
                BASE <-- 0xc8  (see "Default")

                x=0xff ==> "not stereo", x=0xfd ==> "stereo detected"

Set Frequency:  code = (freq*40) + 10486188
                foreach of the 24 bits in code,
                (from Least to Most Significant):
                to write a "zero" bit,
                BASE <-- 0x01  (audio mute, no stereo detect, radio
                                disable, "zero" bit phase 1, tuner adjust)
                BASE <-- 0x03  (audio mute, no stereo detect, radio
                                disable, "zero" bit phase 2, tuner adjust)
                to write a "one" bit,
                BASE <-- 0x05  (audio mute, no stereo detect, radio
                                disable, "one" bit phase 1, tuner adjust)
                BASE <-- 0x07  (audio mute, no stereo detect, radio
                                disable, "one" bit phase 2, tuner adjust)
```

---

# The Rockchip Image Signal Processor Driver (rkisp1)

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> The rkisp1 block underwent some changes between SoC implementations. The vendor designates them as:

<a id="rst-the-rockchip-image-signal-processor-driver-rkisp1"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-versions-and-their-differences"></a>

## Versions and their differences

The rkisp1 block underwent some changes between SoC implementations. The vendor designates them as:

- V10: used at least in rk3288 and rk3399

- V11: declared in the original vendor code, but not used

- V12: used at least in rk3326 and px30

- V13: used at least in rk1808

- V20: used in rk3568 and beyond

Right now the kernel supports rkisp1 implementations based on V10 and V12 variants. V11 does not seem to be actually used and V13 will need some more additions but isn't researched yet, especially as it seems to be limited to the rk1808 which hasn't reached much market spread.

V20 on the other hand will probably be used in future SoCs and has seen really big changes in the vendor kernel, so will need quite a bit of research.

<a id="rst-changes-from-v10-to-v12"></a>

## Changes from V10 to V12

- V12 supports a new CSI-host implementation but can still also use the same implementation from V10

- The module for lens shading correction got changed from 12bit to 13bit width

- The AWB and AEC modules got replaced to support finer grained data collection

<a id="rst-changes-from-v12-to-v13"></a>

## Changes from V12 to V13

The list for V13 is incomplete and needs further investigation.

- V13 does not support the old CSI-host implementation anymore

---

# The saa7134 driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Author Gerd Hoffmann

<a id="rst-the-saa7134-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Author Gerd Hoffmann

<a id="rst-card-variations"></a>

## Card Variations:

Cards can use either of these two crystals (xtal):

- 32.11 MHz -&gt; .audio_clock=0x187de7

- 24.576MHz -&gt; .audio_clock=0x200000 (xtal \* .audio_clock = 51539600)

Some details about 30/34/35:

- saa7130 - low-price chip, doesn't have mute, that is why all those cards should have .mute field defined in their tuner structure.

- saa7134 - usual chip

- saa7133/35 - saa7135 is probably a marketing decision, since all those chips identifies itself as 33 on pci.

<a id="rst-lifeview-gpios"></a>

## LifeView GPIOs

This section was authored by: Peter Missel &lt;[peter.missel@onlinehome.de](<mailto:peter.missel@onlinehome.de>)&gt;

- LifeView FlyTV Platinum FM (LR214WF)

  > - GP27    MDT2005 PB4 pin 10
  >
  > - GP26    MDT2005 PB3 pin 9
  >
  > - GP25    MDT2005 PB2 pin 8
  >
  > - GP23    MDT2005 PB1 pin 7
  >
  > - GP22    MDT2005 PB0 pin 6
  >
  > - GP21    MDT2005 PB5 pin 11
  >
  > - GP20    MDT2005 PB6 pin 12
  >
  > - GP19    MDT2005 PB7 pin 13
  >
  > - nc      MDT2005 PA3 pin 2
  >
  > - Remote  MDT2005 PA2 pin 1
  >
  > - GP18    MDT2005 PA1 pin 18
  >
  > - nc      MDT2005 PA0 pin 17 strap low
  >
  > - GP17    Strap "GP7"=High
  >
  > - GP16    Strap "GP6"=High
  >
  >   > - 0=Radio 1=TV
  >   >
  >   > - Drives SA630D ENCH1 and HEF4052 A1 pinsto do FM radio through SIF input
  >
  > - GP15    nc
  >
  > - GP14    nc
  >
  > - GP13    nc
  >
  > - GP12    Strap "GP5" = High
  >
  > - GP11    Strap "GP4" = High
  >
  > - GP10    Strap "GP3" = High
  >
  > - GP09    Strap "GP2" = Low
  >
  > - GP08    Strap "GP1" = Low
  >
  > - GP07.00 nc

<a id="rst-credits"></a>

## Credits

[andrew.stevens@philips.com](<mailto:andrew.stevens@philips.com>) + [werner.leeb@philips.com](<mailto:werner.leeb@philips.com>) for providing saa7134 hardware specs and sample board.

---

# Cropping and Scaling algorithm, used in the sh_mobile_ceu_camera driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Author: Guennadi Liakhovetski <g.liakhovetski@gmx.de>

<a id="rst-cropping-and-scaling-algorithm-used-in-the-sh-mobile-ceu-camera-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Author: Guennadi Liakhovetski &lt;[g.liakhovetski@gmx.de](<mailto:g.liakhovetski@gmx.de>)&gt;

<a id="rst-terminology"></a>

## Terminology

sensor scales: horizontal and vertical scales, configured by the sensor driver host scales: -"- host driver combined scales: sensor\_scale \* host\_scale

<a id="rst-generic-scaling-cropping-scheme"></a>

## Generic scaling / cropping scheme



```none
-1--
|
-2-- -\
|      --\
|         --\
+-5-- .      -- -3-- -\
|      `...            -\
|          `... -4-- .   - -7..
|                     `.
|                       `. .6--
|
|                        . .6'-
|                      .´
|           ... -4'- .´
|       ...´             - -7'.
+-5'- .´               -/
|            -- -3'- -/
|         --/
|      --/
-2'- -/
|
|
-1'-
```

In the above chart minuses and slashes represent "real" data amounts, points and accents represent "useful" data, basically, CEU scaled and cropped output, mapped back onto the client's source plane.

Such a configuration can be produced by user requests:

S\_CROP(left / top = (5) - (1), width / height = (5') - (5)) S\_FMT(width / height = (6') - (6))

Here:

(1) to (1') - whole max width or height (1) to (2)  - sensor cropped left or top (2) to (2') - sensor cropped width or height (3) to (3') - sensor scale (3) to (4)  - CEU cropped left or top (4) to (4') - CEU cropped width or height (5) to (5') - reverse sensor scale applied to CEU cropped width or height (2) to (5)  - reverse sensor scale applied to CEU cropped left or top (6) to (6') - CEU scale - user window

<a id="rst-s-fmt"></a>

## S\_FMT

Do not touch input rectangle - it is already optimal.

1. Calculate current sensor scales:

   > scale\_s = ((2') - (2)) / ((3') - (3))

2\. Calculate "effective" input crop (sensor subwindow) - CEU crop scaled back at current sensor scales onto input window - this is user S\_CROP:

> width\_u = (5') - (5) = ((4') - (4)) \* scale\_s

3\. Calculate new combined scales from "effective" input window to requested user window:

> scale\_comb = width\_u / ((6') - (6))

4\. Calculate sensor output window by applying combined scales to real input window:

> width\_s\_out = ((7') - (7)) = ((2') - (2)) / scale\_comb

5. Apply iterative sensor S\_FMT for sensor output window.

   > subdev-&gt;video\_ops-&gt;s\_fmt(.width = width\_s\_out)

6. Retrieve sensor output window (g\_fmt)

7. Calculate new sensor scales:

   > scale\_s\_new = ((3')\_new - (3)\_new) / ((2') - (2))

8\. Calculate new CEU crop - apply sensor scales to previously calculated "effective" crop:

> width\_ceu = (4')\_new - (4)\_new = width\_u / scale\_s\_new left\_ceu = (4)\_new - (3)\_new = ((5) - (2)) / scale\_s\_new

9. Use CEU cropping to crop to the new window:

   > ceu\_crop(.width = width\_ceu, .left = left\_ceu)

10. Use CEU scaling to scale to the requested user window:

    > scale\_ceu = width\_ceu / width

<a id="rst-s-crop"></a>

## S\_CROP

The [V4L2 crop API](</kernel/userspace/userspace-api/media-v4l/crop.md#rst-crop-scale>) says:

"...specification does not define an origin or units. However by convention drivers should horizontally count unscaled samples relative to 0H."

We choose to follow the advise and interpret cropping units as client input pixels.

Cropping is performed in the following 6 steps:

1. Request exactly user rectangle from the sensor.

2. If smaller - iterate until a larger one is obtained. Result: sensor cropped to 2 : 2', target crop 5 : 5', current output format 6' - 6.

3. In the previous step the sensor has tried to preserve its output frame as good as possible, but it could have changed. Retrieve it again.

4. Sensor scaled to 3 : 3'. Sensor's scale is (2' - 2) / (3' - 3). Calculate intermediate window: 4' - 4 = (5' - 5) \* (3' - 3) / (2' - 2)

5. Calculate and apply host scale = (6' - 6) / (4' - 4)

6. Calculate and apply host crop: 6 - 7 = (5 - 2) \* (6' - 6) / (5' - 5)

---

# Tuner drivers

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> There are some flavors of Tuner programming APIs. These differ mainly by the bandswitch byte.

<a id="rst-tuner-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-simple-tuner-programming"></a>

## Simple tuner Programming

There are some flavors of Tuner programming APIs. These differ mainly by the bandswitch byte.

- L= LG_API       (VHF_LO=0x01, VHF_HI=0x02, UHF=0x08, radio=0x04)

- P= PHILIPS_API  (VHF_LO=0xA0, VHF_HI=0x90, UHF=0x30, radio=0x04)

- T= TEMIC_API    (VHF_LO=0x02, VHF_HI=0x04, UHF=0x01)

- A= ALPS_API     (VHF_LO=0x14, VHF_HI=0x12, UHF=0x11)

- M= PHILIPS_MK3  (VHF_LO=0x01, VHF_HI=0x02, UHF=0x04, radio=0x19)

<a id="rst-tuner-manufacturers"></a>

## Tuner Manufacturers

- Samsung Tuner identification: (e.g. TCPM9091PD27)



```none
TCP [ABCJLMNQ] 90[89][125] [DP] [ACD] 27 [ABCD]
[ABCJLMNQ]:
  A= BG+DK
  B= BG
  C= I+DK
  J= NTSC-Japan
  L= Secam LL
  M= BG+I+DK
  N= NTSC
  Q= BG+I+DK+LL
[89]: ?
[125]:
  2: No FM
  5: With FM
[DP]:
  D= NTSC
  P= PAL
[ACD]:
  A= F-connector
  C= Phono connector
  D= Din Jack
[ABCD]:
  3-wire/I2C tuning, 2-band/3-band
```

These Tuners are PHILIPS_API compatible.

Philips Tuner identification: (e.g. FM1216MF)



```none
F[IRMQ]12[1345]6{MF|ME|MP}
F[IRMQ]:
 FI12x6: Tuner Series
 FR12x6: Tuner + Radio IF
 FM12x6: Tuner + FM
 FQ12x6: special
 FMR12x6: special
 TD15xx: Digital Tuner ATSC
12[1345]6:
 1216: PAL BG
 1236: NTSC
 1246: PAL I
 1256: Pal DK
{MF|ME|MP}
 MF: BG LL w/ Secam (Multi France)
 ME: BG DK I LL   (Multi Europe)
 MP: BG DK I      (Multi PAL)
 MR: BG DK M (?)
 MG: BG DKI M (?)
MK2 series PHILIPS_API, most tuners are compatible to this one !
MK3 series introduced in 2002 w/ PHILIPS_MK3_API
```

Temic Tuner identification: (.e.g 4006FH5)



```none
 4[01][0136][269]F[HYNR]5
  40x2: Tuner (5V/33V), TEMIC_API.
  40x6: Tuner 5V
  41xx: Tuner compact
  40x9: Tuner+FM compact
 [0136]
  xx0x: PAL BG
  xx1x: Pal DK, Secam LL
  xx3x: NTSC
  xx6x: PAL I
 F[HYNR]5
  FH5: Pal BG
  FY5: others
  FN5: multistandard
  FR5: w/ FM radio
 3X xxxx: order number with specific connector
Note: Only 40x2 series has TEMIC_API, all newer tuners have PHILIPS_API.
```

LG Innotek Tuner:

- TPI8NSR11 : NTSC J/M    (TPI8NSR01 w/FM)  (P,210/497)

- TPI8PSB11 : PAL B/G     (TPI8PSB01 w/FM)  (P,170/450)

- TAPC-I701 : PAL I       (TAPC-I001 w/FM)  (P,170/450)

- TPI8PSB12 : PAL D/K+B/G (TPI8PSB02 w/FM)  (P,170/450)

- TAPC-H701P: NTSC_JP     (TAPC-H001P w/FM) (L,170/450)

- TAPC-G701P: PAL B/G     (TAPC-G001P w/FM) (L,170/450)

- TAPC-W701P: PAL I       (TAPC-W001P w/FM) (L,170/450)

- TAPC-Q703P: PAL D/K     (TAPC-Q001P w/FM) (L,170/450)

- TAPC-Q704P: PAL D/K+I   (L,170/450)

- TAPC-G702P: PAL D/K+B/G (L,170/450)

- TADC-H002F: NTSC (L,175/410?; 2-B, C-W+11, W+12-69)

- TADC-M201D: PAL D/K+B/G+I (L,143/425)  (sound control at I2C address 0xc8)

- TADC-T003F: NTSC Taiwan  (L,175/410?; 2-B, C-W+11, W+12-69)

- **Suffix:**

  - P= Standard phono female socket

  - D= IEC female socket

  - F= F-connector

Other Tuners:

- TCL2002MB-1 : PAL BG + DK       =TUNER_LG_PAL_NEW_TAPC

- TCL2002MB-1F: PAL BG + DK w/FM  =PHILIPS_PAL

- TCL2002MI-2 : PAL I           = ??

ALPS Tuners:

- Most are LG_API compatible

- TSCH6 has ALPS_API (TSCH5 ?)

- TSBE1 has extra API 05,02,08 Control_byte=0xCB Source:<a id="rst-footnote-reference-1"></a>[1](#rst-f1)

<a id="rst-f1"></a>



**[1]** conexant100029b-PCI-Decoder-ApplicationNote.pdf

---

# vidtv: Virtual Digital TV driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Author: Daniel W. S. Almeida <dwlsalmeida@gmail.com>, June 2020.

<a id="rst-vidtv-virtual-digital-tv-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Author: Daniel W. S. Almeida &lt;[dwlsalmeida@gmail.com](<mailto:dwlsalmeida@gmail.com>)&gt;, June 2020.

<a id="rst-background"></a>

## Background

Vidtv is a virtual DVB driver that aims to serve as a reference for driver writers by serving as a template. It also validates the existing media DVB APIs, thus helping userspace application writers.

Currently, it consists of:

- A fake tuner driver, which will report a bad signal quality if the chosen frequency is too far away from a table of valid frequencies for a particular delivery system.

- A fake demod driver, which will constantly poll the fake signal quality returned by the tuner, simulating a device that can lose/reacquire a lock on the signal depending on the CNR levels.

- A fake bridge driver, which is the module responsible for modprobing the fake tuner and demod modules and implementing the demux logic. This module takes parameters at initialization that will dictate how the simulation behaves.

- Code responsible for encoding a valid MPEG Transport Stream, which is then passed to the bridge driver. This fake stream contains some hardcoded content. For now, we have a single, audio-only channel containing a single MPEG Elementary Stream, which in turn contains a SMPTE 302m encoded sine-wave. Note that this particular encoder was chosen because it is the easiest way to encode PCM audio data in a MPEG Transport Stream.

<a id="rst-building-vidtv"></a>

## Building vidtv

vidtv is a test driver and thus is **not** enabled by default when compiling the kernel.

In order to enable compilation of vidtv:

- Enable **DVB_TEST_DRIVERS**, then

- Enable **DVB_VIDTV**

When compiled as a module, expect the following .ko files:

- dvb_vidtv_tuner.ko

- dvb_vidtv_demod.ko

- dvb_vidtv_bridge.ko

<a id="rst-running-vidtv"></a>

## Running vidtv

When compiled as a module, run:



```text
modprobe vidtv
```

That's it\! The bridge driver will initialize the tuner and demod drivers as part of its own initialization.

By default, it will accept the following frequencies:

> - 474 MHz for DVB-T/T2/C;
>
> - 11,362 GHz for DVB-S/S2.

For satellite systems, the driver simulates an universal extended LNBf, with frequencies at Ku-Band, ranging from 10.7 GHz to 12.75 GHz.

You can optionally define some command-line arguments to vidtv.

<a id="rst-command-line-arguments-to-vidtv"></a>

## Command-line arguments to vidtv

Below is a list of all arguments that can be supplied to vidtv:

- **drop_tslock_prob_on_low_snr**

  Probability of losing the TS lock if the signal quality is bad. This probability be used by the fake demodulator driver to eventually return a status of 0 when the signal quality is not good.

- **recover_tslock_prob_on_good_snr:**

  Probability recovering the TS lock when the signal improves. This probability be used by the fake demodulator driver to eventually return a status of 0x1f when/if the signal quality improves.

- **mock_power_up_delay_msec**

  Simulate a power up delay.  Default: 0.

- **mock_tune_delay_msec**

  Simulate a tune delay.  Default 0.

- **vidtv_valid_dvb_t_freqs**

  Valid DVB-T frequencies to simulate, in Hz.

- **vidtv_valid_dvb_c_freqs**

  Valid DVB-C frequencies to simulate, in Hz.

- **vidtv_valid_dvb_s_freqs**

  Valid DVB-S/S2 frequencies to simulate at Ku-Band, in kHz.

- **max_frequency_shift_hz,**

  Maximum shift in HZ allowed when tuning in a channel.

- **si_period_msec**

  How often to send SI packets.  Default: 40ms.

- **pcr_period_msec**

  How often to send PCR packets.  Default: 40ms.

- **mux_rate_kbytes_sec**

  Attempt to maintain this bit rate by inserting TS null packets, if necessary.  Default: 4096.

- **pcr_pid,**

  PCR PID for all channels.  Default: 0x200.

- **mux_buf_sz_pkts,**

  Size for the mux buffer in multiples of 188 bytes.

<a id="rst-vidtv-internal-structure"></a>

## vidtv internal structure

The kernel modules are split in the following way:

- **vidtv_tuner.\[ch\]**

  Implements a fake tuner DVB driver.

- **vidtv_demod.\[ch\]**

  Implements a fake demodulator DVB driver.

- **vidtv_bridge.\[ch\]**

  Implements a bridge driver.

The MPEG related code is split in the following way:

- **vidtv_ts.\[ch\]**

  Code to work with MPEG TS packets, such as TS headers, adaptation fields, PCR packets and NULL packets.

- **vidtv_psi.\[ch\]**

  This is the PSI generator.  PSI packets contain general information about a MPEG Transport Stream.  A PSI generator is needed so userspace apps can retrieve information about the Transport Stream and eventually tune into a (dummy) channel.

  Because the generator is implemented in a separate file, it can be reused elsewhere in the media subsystem.

  Currently vidtv supports working with 5 PSI tables: PAT, PMT, SDT, NIT and EIT.

  The specification for PAT and PMT can be found in *ISO 13818-1: Systems*, while the specification for the SDT, NIT, EIT can be found in *ETSI EN 300 468: Specification for Service Information (SI) in DVB systems*.

  It isn't strictly necessary, but using a real TS file helps when debugging PSI tables. Vidtv currently tries to replicate the PSI structure found in this file: [TS1Globo.ts](<https://tsduck.io/streams/brazil-isdb-tb/TS1globo.ts>)<a id="rst-ts1globo-ts"></a>.

  A good way to visualize the structure of streams is by using [DVBInspector](<https://sourceforge.net/projects/dvbinspector/>)<a id="rst-dvbinspector"></a>.

- **vidtv_pes.\[ch\]**

  Implements the PES logic to convert encoder data into MPEG TS packets. These can then be fed into a TS multiplexer and eventually into userspace.

- **vidtv_encoder.h**

  An interface for vidtv encoders. New encoders can be added to this driver by implementing the calls in this file.

- **vidtv_s302m.\[ch\]**

  Implements a S302M encoder to make it possible to insert PCM audio data in the generated MPEG Transport Stream. The relevant specification is available online as *SMPTE 302M-2007: Television - Mapping of AES3 Data into MPEG-2 Transport Stream*.

  The resulting MPEG Elementary Stream is conveyed in a private stream with a S302M registration descriptor attached.

  This shall enable passing an audio signal into userspace so it can be decoded and played by media software. The corresponding decoder in ffmpeg is located in 'libavcodec/s302m.c' and is experimental.

- **vidtv_channel.\[ch\]**

  Implements a 'channel' abstraction.

  When vidtv boots, it will create some hardcoded channels:

  1. Their services will be concatenated to populate the SDT.

  2. Their programs will be concatenated to populate the PAT

  3. Their events will be concatenated to populate the EIT

  4. For each program in the PAT, a PMT section will be created

  5. The PMT section for a channel will be assigned its streams.

  6. Every stream will have its corresponding encoder polled in a loop to produce TS packets. These packets may be interleaved by the muxer and then delivered to the bridge.

- **vidtv_mux.\[ch\]**

  Implements a MPEG TS mux, loosely based on the ffmpeg implementation in "libavcodec/mpegtsenc.c"

  The muxer runs a loop which is responsible for:

  1. Keeping track of the amount of time elapsed since the last iteration.

  2. Polling encoders in order to fetch 'elapsed_time' worth of data.

  3. Inserting PSI and/or PCR packets, if needed.

  4. Padding the resulting stream with NULL packets if necessary in order to maintain the chosen bit rate.

  5. Delivering the resulting TS packets to the bridge driver so it can pass them to the demux.

<a id="rst-testing-vidtv-with-v4l-utils"></a>

## Testing vidtv with v4l-utils

Using the tools in v4l-utils is a great way to test and inspect the output of vidtv. It is hosted here: [v4l-utils Documentation](<https://linuxtv.org/wiki/index.php/V4l-utils>)<a id="rst-v4l-utils-documentation"></a>.

From its webpage:



```text
The v4l-utils are a series of packages for handling media devices.

It is hosted at http://git.linuxtv.org/v4l-utils.git, and packaged
on most distributions.

It provides a series of libraries and utilities to be used to
control several aspect of the media boards.
```

Start by installing v4l-utils and then modprobing vidtv:



```text
modprobe dvb_vidtv_bridge
```

If the driver is OK, it should load and its probing code will run. This will pull in the tuner and demod drivers.

<a id="rst-using-dvb-fe-tool"></a>

### Using dvb-fe-tool

The first step to check whether the demod loaded successfully is to run:



```text
$ dvb-fe-tool
Device Dummy demod for DVB-T/T2/C/S/S2 (/dev/dvb/adapter0/frontend0) capabilities:
    CAN_FEC_1_2
    CAN_FEC_2_3
    CAN_FEC_3_4
    CAN_FEC_4_5
    CAN_FEC_5_6
    CAN_FEC_6_7
    CAN_FEC_7_8
    CAN_FEC_8_9
    CAN_FEC_AUTO
    CAN_GUARD_INTERVAL_AUTO
    CAN_HIERARCHY_AUTO
    CAN_INVERSION_AUTO
    CAN_QAM_16
    CAN_QAM_32
    CAN_QAM_64
    CAN_QAM_128
    CAN_QAM_256
    CAN_QAM_AUTO
    CAN_QPSK
    CAN_TRANSMISSION_MODE_AUTO
DVB API Version 5.11, Current v5 delivery system: DVBC/ANNEX_A
Supported delivery systems:
    DVBT
    DVBT2
    [DVBC/ANNEX_A]
    DVBS
    DVBS2
Frequency range for the current standard:
From:            51.0 MHz
To:              2.15 GHz
Step:            62.5 kHz
Tolerance:       29.5 MHz
Symbol rate ranges for the current standard:
From:            1.00 MBauds
To:              45.0 MBauds
```

This should return what is currently set up at the demod struct, i.e.:



```text
static const struct dvb_frontend_ops vidtv_demod_ops = {
        .delsys = {
                SYS_DVBT,
                SYS_DVBT2,
                SYS_DVBC_ANNEX_A,
                SYS_DVBS,
                SYS_DVBS2,
        },

        .info = {
                .name                   = "Dummy demod for DVB-T/T2/C/S/S2",
                .frequency_min_hz       = 51 * MHz,
                .frequency_max_hz       = 2150 * MHz,
                .frequency_stepsize_hz  = 62500,
                .frequency_tolerance_hz = 29500 * kHz,
                .symbol_rate_min        = 1000000,
                .symbol_rate_max        = 45000000,

                .caps = FE_CAN_FEC_1_2 |
                        FE_CAN_FEC_2_3 |
                        FE_CAN_FEC_3_4 |
                        FE_CAN_FEC_4_5 |
                        FE_CAN_FEC_5_6 |
                        FE_CAN_FEC_6_7 |
                        FE_CAN_FEC_7_8 |
                        FE_CAN_FEC_8_9 |
                        FE_CAN_QAM_16 |
                        FE_CAN_QAM_64 |
                        FE_CAN_QAM_32 |
                        FE_CAN_QAM_128 |
                        FE_CAN_QAM_256 |
                        FE_CAN_QAM_AUTO |
                        FE_CAN_QPSK |
                        FE_CAN_FEC_AUTO |
                        FE_CAN_INVERSION_AUTO |
                        FE_CAN_TRANSMISSION_MODE_AUTO |
                        FE_CAN_GUARD_INTERVAL_AUTO |
                        FE_CAN_HIERARCHY_AUTO,
        }

        ....
```

For more information on dvb-fe-tools check its online documentation here: [dvb-fe-tool Documentation](<https://www.linuxtv.org/wiki/index.php/Dvb-fe-tool>)<a id="rst-dvb-fe-tool-documentation"></a>.

<a id="rst-using-dvb-scan"></a>

### Using dvb-scan

In order to tune into a channel and read the PSI tables, we can use dvb-scan.

For this, one should provide a configuration file known as a 'scan file', here's an example:



```text
[Channel]
FREQUENCY = 474000000
MODULATION = QAM/AUTO
SYMBOL_RATE = 6940000
INNER_FEC = AUTO
DELIVERY_SYSTEM = DVBC/ANNEX_A
```

> [!NOTE]
>
> The parameters depend on the video standard you're testing.

> [!NOTE]
>
> Vidtv is a fake driver and does not validate much of the information in the scan file. Just specifying 'FREQUENCY' and 'DELIVERY_SYSTEM' should be enough for DVB-T/DVB-T2. For DVB-S/DVB-C however, you should also provide 'SYMBOL_RATE'.

You can browse scan tables online here: [dvb-scan-tables](<https://git.linuxtv.org/dtv-scan-tables.git>)<a id="rst-dvb-scan-tables"></a>.

Assuming this channel is named 'channel.conf', you can then run:



```text
$ dvbv5-scan channel.conf
dvbv5-scan ~/vidtv.conf
ERROR    command BANDWIDTH_HZ (5) not found during retrieve
Cannot calc frequency shift. Either bandwidth/symbol-rate is unavailable (yet).
Scanning frequency #1 330000000
    (0x00) Signal= -68.00dBm
Scanning frequency #2 474000000
Lock   (0x1f) Signal= -34.45dBm C/N= 33.74dB UCB= 0
Service Beethoven, provider LinuxTV.org: digital television
```

For more information on dvb-scan, check its documentation online here: [dvb-scan Documentation](<https://www.linuxtv.org/wiki/index.php/Dvbscan>)<a id="rst-dvb-scan-documentation"></a>.

<a id="rst-using-dvb-zap"></a>

### Using dvb-zap

dvbv5-zap is a command line tool that can be used to record MPEG-TS to disk. The typical use is to tune into a channel and put it into record mode. The example below - which is taken from the documentation - illustrates that<a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1):



```text
$ dvbv5-zap -c dvb_channel.conf "beethoven" -o music.ts -P -t 10
using demux 'dvb0.demux0'
reading channels from file 'dvb_channel.conf'
tuning to 474000000 Hz
pass all PID's to TS
dvb_set_pesfilter 8192
dvb_dev_set_bufsize: buffer set to 6160384
Lock   (0x1f) Quality= Good Signal= -34.66dBm C/N= 33.41dB UCB= 0 postBER= 0 preBER= 1.05x10^-3 PER= 0
Lock   (0x1f) Quality= Good Signal= -34.57dBm C/N= 33.46dB UCB= 0 postBER= 0 preBER= 1.05x10^-3 PER= 0
Record to file 'music.ts' started
received 24587768 bytes (2401 Kbytes/sec)
Lock   (0x1f) Quality= Good Signal= -34.42dBm C/N= 33.89dB UCB= 0 postBER= 0 preBER= 2.44x10^-3 PER= 0
```

<a id="rst-footnote-1"></a>



**[1]** In this example, it records 10 seconds with all program ID's stored at the music.ts file.

The channel can be watched by playing the contents of the stream with some player that  recognizes the MPEG-TS format, such as `mplayer` or `vlc`.

By playing the contents of the stream one can visually inspect the workings of vidtv, e.g., to play a recorded TS file with:



```text
$ mplayer music.ts
```

or, alternatively, running this command on one terminal:



```text
$ dvbv5-zap -c dvb_channel.conf "beethoven" -P -r &
```

And, on a second terminal, playing the contents from DVR interface with:



```text
$ mplayer /dev/dvb/adapter0/dvr0
```

For more information on dvb-zap check its online documentation here: [dvb-zap Documentation](<https://www.linuxtv.org/wiki/index.php/Dvbv5-zap>)<a id="rst-dvb-zap-documentation"></a>. See also: [zap](<https://www.linuxtv.org/wiki/index.php/Zap>)<a id="rst-zap"></a>.

<a id="rst-what-can-still-be-improved-in-vidtv"></a>

## What can still be improved in vidtv

<a id="rst-add-debugfs-integration"></a>

### Add *debugfs* integration

Although frontend drivers provide DVBv5 statistics via the .read_status call, a nice addition would be to make additional statistics available to userspace via debugfs, which is a simple-to-use, RAM-based filesystem specifically designed for debug purposes.

The logic for this would be implemented on a separate file so as not to pollute the frontend driver.  These statistics are driver-specific and can be useful during tests.

The Siano driver is one example of a driver using debugfs to convey driver-specific statistics to userspace and it can be used as a reference.

This should be further enabled and disabled via a Kconfig option for convenience.

<a id="rst-add-a-way-to-test-video"></a>

### Add a way to test video

Currently, vidtv can only encode PCM audio. It would be great to implement a barebones version of MPEG-2 video encoding so we can also test video. The first place to look into is *ISO 13818-2: Information technology — Generic coding of moving pictures and associated audio information — Part 2: Video*, which covers the encoding of compressed video in MPEG Transport Streams.

This might optionally use the Video4Linux2 Test Pattern Generator, v4l2-tpg, which resides at:



```text
drivers/media/common/v4l2-tpg/
```

<a id="rst-add-white-noise-simulation"></a>

### Add white noise simulation

The vidtv tuner already has code to identify whether the chosen frequency is too far away from a table of valid frequencies. For now, this means that the demodulator can eventually lose the lock on the signal, since the tuner will report a bad signal quality.

A nice addition is to simulate some noise when the signal quality is bad by:

- Randomly dropping some TS packets. This will trigger a continuity error if the continuity counter is updated but the packet is not passed on to the demux.

- Updating the error statistics accordingly (e.g. BER, etc).

- Simulating some noise in the encoded data.

<a id="rst-functions-and-structs-used-within-vidtv"></a>

## Functions and structs used within vidtv


#### <a id="c-struct-vidtv_dvb"></a>`struct vidtv_dvb`

Vidtv bridge state

**Definition**

```c
struct vidtv_dvb {
        struct platform_device *pdev;
        struct dvb_frontend *fe[NUM_FE];
        struct dvb_adapter adapter;
        struct dvb_demux demux;
        struct dmxdev dmx_dev;
        struct dmx_frontend dmx_fe[NUM_FE];
        struct i2c_adapter i2c_adapter;
        struct i2c_client *i2c_client_demod[NUM_FE];
        struct i2c_client *i2c_client_tuner[NUM_FE];
        u32 nfeeds;
        struct mutex feed_lock;
        bool streaming;
        struct vidtv_mux *mux;
    #ifdef CONFIG_MEDIA_CONTROLLER_DVB;
        struct media_device mdev;
    #endif;
};
```

**Members**

- `pdev`: The platform device. Obtained when the bridge is probed.
- `fe`: The frontends. Obtained when probing the demodulator modules.
- `adapter`: Represents a DTV adapter. See 'dvb_register_adapter'.
- `demux`: The demux used by the [`dvb_dmx_swfilter_packets()`](/kernel/hardware/driver-api/media/dtv-demux.md#c-dvb_dmx_swfilter_packets) call.
- `dmx_dev`: Represents a demux device.
- `dmx_fe`: The frontends associated with the demux.
- `i2c_adapter`: The i2c_adapter associated with the bridge driver.
- `i2c_client_demod`: The i2c_clients associated with the demodulator modules.
- `i2c_client_tuner`: The i2c_clients associated with the tuner modules.
- `nfeeds`: The number of feeds active.
- `feed_lock`: Protects access to the start/stop stream logic/data.
- `streaming`: Whether we are streaming now.
- `mux`: The abstraction responsible for delivering MPEG TS packets to the bridge.
- `mdev`: The media_device struct for media controller support.



#### <a id="c-struct-vidtv_channel"></a>`struct vidtv_channel`

A 'channel' abstraction

**Definition**

```c
struct vidtv_channel {
    char *name;
    u16 transport_stream_id;
    struct vidtv_psi_table_sdt_service *service;
    u16 program_num;
    struct vidtv_psi_table_pat_program *program;
    struct vidtv_psi_table_pmt_stream *streams;
    struct vidtv_encoder *encoders;
    struct vidtv_psi_table_eit_event *events;
    struct vidtv_channel *next;
};
```

**Members**

- `name`: name of the channel
- `transport_stream_id`: a number to identify the TS, chosen at will.
- `service`: A _single_ service. Will be concatenated into the SDT.
- `program_num`: The link between PAT, PMT and SDT.
- `program`: A _single_ program with one or more streams associated with it.
  Will be concatenated into the PAT.
- `streams`: A stream loop used to populate the PMT section for 'program'
- `encoders`: A encoder loop. There must be one encoder for each stream.
- `events`: Optional event information. This will feed into the EIT.
- `next`: Optionally chain this channel.

**Description**

When vidtv boots, it will create some hardcoded channels.
Their services will be concatenated to populate the SDT.
Their programs will be concatenated to populate the PAT
For each program in the PAT, a PMT section will be created
The PMT section for a channel will be assigned its streams.
Every stream will have its corresponding encoder polled to produce TS packets
These packets may be interleaved by the mux and then delivered to the bridge

#### <a id="c-vidtv_channel_si_init"></a>`vidtv_channel_si_init()`

```c
int vidtv_channel_si_init(struct vidtv_mux *m)
```

Init the PSI tables from the channels in the mux

**Parameters**

- `struct vidtv_mux *m`: The mux containing the channels.

#### <a id="c-vidtv_channels_init"></a>`vidtv_channels_init()`

```c
int vidtv_channels_init(struct vidtv_mux *m)
```

Init hardcoded, fake 'channels'.

**Parameters**

- `struct vidtv_mux *m`: The mux to store the channels into.



#### <a id="c-struct-vidtv_demod_cnr_to_qual_s"></a>`struct vidtv_demod_cnr_to_qual_s`

Map CNR values to a given combination of modulation and fec_inner

**Definition**

```c
struct vidtv_demod_cnr_to_qual_s {
    u32 modulation;
    u32 fec;
    u32 cnr_ok;
    u32 cnr_good;
};
```

**Members**

- `modulation`: see enum fe_modulation
- `fec`: see enum fe_fec_rate
- `cnr_ok`: S/N threshold to consider the signal as OK. Below that, there's
  a chance of losing sync.
- `cnr_good`: S/N threshold to consider the signal strong.

**Description**

This struct matches values for 'good' and 'ok' CNRs given the combination
of modulation and fec_inner in use. We might simulate some noise if the
signal quality is not too good.

The values were taken from libdvbv5.

#### <a id="c-struct-vidtv_demod_config"></a>`struct vidtv_demod_config`

Configuration used to init the demod

**Definition**

```c
struct vidtv_demod_config {
    u8 drop_tslock_prob_on_low_snr;
    u8 recover_tslock_prob_on_good_snr;
};
```

**Members**

- `drop_tslock_prob_on_low_snr`: probability of losing the lock due to low snr
- `recover_tslock_prob_on_good_snr`: probability of recovering when the signal
  improves

**Description**

The configuration used to init the demodulator module, usually filled
by a bridge driver. For vidtv, this is filled by vidtv_bridge before the
demodulator module is probed.

#### <a id="c-struct-vidtv_demod_state"></a>`struct vidtv_demod_state`

The demodulator state

**Definition**

```c
struct vidtv_demod_state {
    struct dvb_frontend frontend;
    struct vidtv_demod_config config;
    enum fe_status status;
    u16 tuner_cnr;
};
```

**Members**

- `frontend`: The frontend structure allocated by the demod.
- `config`: The config used to init the demod.
- `status`: the demod status.
- `tuner_cnr`: current S/N ratio for the signal carrier



#### <a id="c-struct-vidtv_encoder"></a>`struct vidtv_encoder`

A generic encoder type.

**Definition**

```c
struct vidtv_encoder {
    enum vidtv_encoder_id id;
    char *name;
    u8 *encoder_buf;
    u32 encoder_buf_sz;
    u32 encoder_buf_offset;
    u64 sample_count;
    struct vidtv_access_unit *access_units;
    void *src_buf;
    u32 src_buf_sz;
    u32 src_buf_offset;
    bool is_video_encoder;
    void *ctx;
    __be16 stream_id;
    __be16 es_pid;
    void *(*encode)(struct vidtv_encoder *e);
    u32 (*clear)(struct vidtv_encoder *e);
    struct vidtv_encoder *sync;
    u32 sampling_rate_hz;
    void (*last_sample_cb)(u32 sample_no);
    void (*destroy)(struct vidtv_encoder *e);
    struct vidtv_encoder *next;
};
```

**Members**

- `id`: So we can cast to a concrete implementation when needed.
- `name`: Usually the same as the stream name.
- `encoder_buf`: The encoder internal buffer for the access units.
- `encoder_buf_sz`: The encoder buffer size, in bytes
- `encoder_buf_offset`: Our byte position in the encoder buffer.
- `sample_count`: How many samples we have encoded in total.
- `access_units`: encoder payload units, used for clock references
- `src_buf`: The source of raw data to be encoded, encoder might set a
  default if null.
- `src_buf_sz`: size of **src_buf**.
- `src_buf_offset`: Our position in the source buffer.
- `is_video_encoder`: Whether this a video encoder (as opposed to audio)
- `ctx`: Encoder-specific state.
- `stream_id`: Examples: Audio streams (0xc0-0xdf), Video streams
  (0xe0-0xef).
- `es_pid`: The TS PID to use for the elementary stream in this encoder.
- `encode`: Prepare enough AUs for the given amount of time.
- `clear`: Clear the encoder output.
- `sync`: Attempt to synchronize with this encoder.
- `sampling_rate_hz`: The sampling rate (or fps, if video) used.
- `last_sample_cb`: Called when the encoder runs out of data.This is
  so the source can read data in a
  piecemeal fashion instead of having to
  provide it all at once.
- `destroy`: Destroy this encoder, freeing allocated resources.
- `next`: Next in the chain



#### <a id="c-struct-vidtv_mux_timing"></a>`struct vidtv_mux_timing`

Timing related information

**Definition**

```c
struct vidtv_mux_timing {
    u64 start_jiffies;
    u64 current_jiffies;
    u64 past_jiffies;
    u64 clk;
    u64 pcr_period_usecs;
    u64 si_period_usecs;
};
```

**Members**

- `start_jiffies`: The value of 'jiffies' when we started the mux thread.
- `current_jiffies`: The value of 'jiffies' for the current iteration.
- `past_jiffies`: The value of 'jiffies' for the past iteration.
- `clk`: A 27Mhz clock from which we will drive the PCR. Updated proportionally
  on every iteration.
- `pcr_period_usecs`: How often we should send PCR packets.
- `si_period_usecs`: How often we should send PSI packets.

**Description**

This is used to decide when PCR or PSI packets should be sent. This will also
provide storage for the clock, which is used to compute the value for the PCR.

#### <a id="c-struct-vidtv_mux_si"></a>`struct vidtv_mux_si`

Store the PSI context.

**Definition**

```c
struct vidtv_mux_si {
    struct vidtv_psi_table_pat *pat;
    struct vidtv_psi_table_pmt **pmt_secs;
    struct vidtv_psi_table_sdt *sdt;
    struct vidtv_psi_table_nit *nit;
    struct vidtv_psi_table_eit *eit;
};
```

**Members**

- `pat`: The PAT in use by the muxer.
- `pmt_secs`: The PMT sections in use by the muxer. One for each program in the PAT.
- `sdt`: The SDT in use by the muxer.
- `nit`: The NIT in use by the muxer.
- `eit`: the EIT in use by the muxer.

**Description**

This is used to store the PAT, PMT sections and SDT in use by the muxer.

The muxer acquire these by looking into the hardcoded channels in
vidtv_channel and then periodically sends the TS packets for them>

#### <a id="c-struct-vidtv_mux_pid_ctx"></a>`struct vidtv_mux_pid_ctx`

Store the context for a given TS PID.

**Definition**

```c
struct vidtv_mux_pid_ctx {
    u16 pid;
    u8 cc;
    struct hlist_node h;
};
```

**Members**

- `pid`: The TS PID.
- `cc`: The continuity counter for this PID. It is incremented on every TS
  pack and it will wrap around at 0xf0. If the decoder notices a sudden jump in
  this counter this will trigger a discontinuity state.
- `h`: This is embedded in a hash table, mapping pid -> vidtv_mux_pid_ctx

#### <a id="c-struct-vidtv_mux"></a>`struct vidtv_mux`

A muxer abstraction loosely based in libavcodec/mpegtsenc.c

**Definition**

```c
struct vidtv_mux {
    struct dvb_frontend *fe;
    struct device *dev;
    struct vidtv_mux_timing timing;
    u32 mux_rate_kbytes_sec;
    unsigned long pid_ctx[1 << ((3) - 1)];
    void (*on_new_packets_available_cb)(void *priv, u8 *buf, u32 npackets);
    u8 *mux_buf;
    u32 mux_buf_sz;
    u32 mux_buf_offset;
    struct vidtv_channel  *channels;
    struct vidtv_mux_si si;
    u64 num_streamed_pcr;
    u64 num_streamed_si;
    struct work_struct mpeg_thread;
    bool streaming;
    u16 pcr_pid;
    u16 transport_stream_id;
    u16 network_id;
    char *network_name;
    void *priv;
};
```

**Members**

- `fe`: The frontend structure allocated by the muxer.
- `dev`: pointer to struct device.
- `timing`: Keeps track of timing related information.
- `mux_rate_kbytes_sec`: The bit rate for the TS, in kbytes.
- `pid_ctx`: A hash table to keep track of per-PID metadata.
- `on_new_packets_available_cb`: A callback to inform of new TS packets ready.
- `mux_buf`: A pointer to a buffer for this muxer. TS packets are stored there
  and then passed on to the bridge driver.
- `mux_buf_sz`: The size for 'mux_buf'.
- `mux_buf_offset`: The current offset into 'mux_buf'.
- `channels`: The channels associated with this muxer.
- `si`: Keeps track of the PSI context.
- `num_streamed_pcr`: Number of PCR packets streamed.
- `num_streamed_si`: The number of PSI packets streamed.
- `mpeg_thread`: Thread responsible for the muxer loop.
- `streaming`: whether 'mpeg_thread' is running.
- `pcr_pid`: The TS PID used for the PSI packets. All channels will share the
  same PCR.
- `transport_stream_id`: The transport stream ID
- `network_id`: The network ID
- `network_name`: The network name
- `priv`: Private data.

#### <a id="c-struct-vidtv_mux_init_args"></a>`struct vidtv_mux_init_args`

Arguments used to inix the muxer.

**Definition**

```c
struct vidtv_mux_init_args {
    u32 mux_rate_kbytes_sec;
    void (*on_new_packets_available_cb)(void *priv, u8 *buf, u32 npackets);
    u32 mux_buf_sz;
    u64 pcr_period_usecs;
    u64 si_period_usecs;
    u16 pcr_pid;
    u16 transport_stream_id;
    struct vidtv_channel *channels;
    u16 network_id;
    char *network_name;
    void *priv;
};
```

**Members**

- `mux_rate_kbytes_sec`: The bit rate for the TS, in kbytes.
- `on_new_packets_available_cb`: A callback to inform of new TS packets ready.
- `mux_buf_sz`: The size for 'mux_buf'.
- `pcr_period_usecs`: How often we should send PCR packets.
- `si_period_usecs`: How often we should send PSI packets.
- `pcr_pid`: The TS PID used for the PSI packets. All channels will share the
  same PCR.
- `transport_stream_id`: The transport stream ID
- `channels`: an optional list of channels to use
- `network_id`: The network ID
- `network_name`: The network name
- `priv`: Private data.



#### <a id="c-struct-pes_header_write_args"></a>`struct pes_header_write_args`

Arguments to write a PES header.

**Definition**

```c
struct pes_header_write_args {
    void *dest_buf;
    u32 dest_offset;
    u32 dest_buf_sz;
    u32 encoder_id;
    bool send_pts;
    u64 pts;
    bool send_dts;
    u64 dts;
    u16 stream_id;
    u32 n_pes_h_s_bytes;
    u32 access_unit_len;
};
```

**Members**

- `dest_buf`: The buffer to write into.
- `dest_offset`: where to start writing in the dest_buffer.
- `dest_buf_sz`: The size of the dest_buffer
- `encoder_id`: Encoder id (see vidtv_encoder.h)
- `send_pts`: Should we send PTS?
- `pts`: PTS value to send.
- `send_dts`: Should we send DTS?
- `dts`: DTS value to send.
- `stream_id`: The stream id to use. Ex: Audio streams (0xc0-0xdf), Video
  streams (0xe0-0xef).
- `n_pes_h_s_bytes`: Padding bytes. Might be used by an encoder if needed, gets
  discarded by the decoder.
- `access_unit_len`: The size of _one_ access unit (with any headers it might need)

#### <a id="c-struct-pes_ts_header_write_args"></a>`struct pes_ts_header_write_args`

Arguments to write a TS header.

**Definition**

```c
struct pes_ts_header_write_args {
    void *dest_buf;
    u32 dest_offset;
    u32 dest_buf_sz;
    u16 pid;
    u8 *continuity_counter;
    bool wrote_pes_header;
    u32 n_stuffing_bytes;
    u64 pcr;
};
```

**Members**

- `dest_buf`: The buffer to write into.
- `dest_offset`: where to start writing in the dest_buffer.
- `dest_buf_sz`: The size of the dest_buffer
- `pid`: The PID to use for the TS packets.
- `continuity_counter`: Incremented on every new TS packet.
- `wrote_pes_header`: Flag to indicate that the PES header was written
- `n_stuffing_bytes`: Padding bytes. Might be used by an encoder if needed, gets
  discarded by the decoder.
- `pcr`: counter driven by a 27Mhz clock.

#### <a id="c-struct-pes_write_args"></a>`struct pes_write_args`

Arguments for the packetizer.

**Definition**

```c
struct pes_write_args {
    void *dest_buf;
    void *from;
    u32 access_unit_len;
    u32 dest_offset;
    u32 dest_buf_sz;
    u16 pid;
    u32 encoder_id;
    u8 *continuity_counter;
    u16 stream_id;
    bool send_pts;
    u64 pts;
    bool send_dts;
    u64 dts;
    u32 n_pes_h_s_bytes;
    u64 pcr;
};
```

**Members**

- `dest_buf`: The buffer to write into.
- `from`: A pointer to the encoder buffer containing one access unit.
- `access_unit_len`: The size of _one_ access unit (with any headers it might need)
- `dest_offset`: where to start writing in the dest_buffer.
- `dest_buf_sz`: The size of the dest_buffer
- `pid`: The PID to use for the TS packets.
- `encoder_id`: Encoder id (see vidtv_encoder.h)
- `continuity_counter`: Incremented on every new TS packet.
- `stream_id`: The stream id to use. Ex: Audio streams (0xc0-0xdf), Video
  streams (0xe0-0xef).
- `send_pts`: Should we send PTS?
- `pts`: PTS value to send.
- `send_dts`: Should we send DTS?
- `dts`: DTS value to send.
- `n_pes_h_s_bytes`: Padding bytes. Might be used by an encoder if needed, gets
  discarded by the decoder.
- `pcr`: counter driven by a 27Mhz clock.

#### <a id="c-vidtv_pes_write_into"></a>`vidtv_pes_write_into()`

```c
u32 vidtv_pes_write_into(struct pes_write_args *args)
```

Write a PES packet as MPEG-TS packets into a buffer.

**Parameters**

- `struct pes_write_args *args`: The args to use when writing

**Description**

This function translate the ES data for one access unit
from an encoder into MPEG TS packets. It does so by first encapsulating it
with a PES header and then splitting it into TS packets.

The data is then written into the buffer pointed to by 'args.buf'

**Return**

The number of bytes written into the buffer. This is usually NOT
equal to the size of the access unit, since we need space for PES headers, TS headers
and padding bytes, if any.



#### <a id="c-struct-psi_write_args"></a>`struct psi_write_args`

Arguments for the PSI packetizer.

**Definition**

```c
struct psi_write_args {
    void *dest_buf;
    void *from;
    size_t len;
    u32 dest_offset;
    u16 pid;
    bool new_psi_section;
    u8 *continuity_counter;
    bool is_crc;
    u32 dest_buf_sz;
    u32 *crc;
};
```

**Members**

- `dest_buf`: The buffer to write into.
- `from`: PSI data to be copied.
- `len`: How much to write.
- `dest_offset`: where to start writing in the dest_buffer.
- `pid`: TS packet ID.
- `new_psi_section`: Set when starting a table section.
- `continuity_counter`: Incremented on every new packet.
- `is_crc`: Set when writing the CRC at the end.
- `dest_buf_sz`: The size of the dest_buffer
- `crc`: a pointer to store the crc for this chunk

#### <a id="c-struct-desc_write_args"></a>`struct desc_write_args`

Arguments in order to write a descriptor.

**Definition**

```c
struct desc_write_args {
    void *dest_buf;
    u32 dest_offset;
    struct vidtv_psi_desc *desc;
    u16 pid;
    u8 *continuity_counter;
    u32 dest_buf_sz;
    u32 *crc;
};
```

**Members**

- `dest_buf`: The buffer to write into.
- `dest_offset`: where to start writing in the dest_buffer.
- `desc`: A pointer to the descriptor
- `pid`: TS packet ID.
- `continuity_counter`: Incremented on every new packet.
- `dest_buf_sz`: The size of the dest_buffer
- `crc`: a pointer to store the crc for this chunk

#### <a id="c-struct-crc32_write_args"></a>`struct crc32_write_args`

Arguments in order to write the CRC at the end of the PSI tables.

**Definition**

```c
struct crc32_write_args {
    void *dest_buf;
    u32 dest_offset;
    __be32 crc;
    u16 pid;
    u8 *continuity_counter;
    u32 dest_buf_sz;
};
```

**Members**

- `dest_buf`: The buffer to write into.
- `dest_offset`: where to start writing in the dest_buffer.
- `crc`: the CRC value to write
- `pid`: TS packet ID.
- `continuity_counter`: Incremented on every new packet.
- `dest_buf_sz`: The size of the dest_buffer

#### <a id="c-struct-header_write_args"></a>`struct header_write_args`

Arguments in order to write the common table header

**Definition**

```c
struct header_write_args {
    void *dest_buf;
    u32 dest_offset;
    struct vidtv_psi_table_header *h;
    u16 pid;
    u8 *continuity_counter;
    u32 dest_buf_sz;
    u32 *crc;
};
```

**Members**

- `dest_buf`: The buffer to write into.
- `dest_offset`: where to start writing in the dest_buffer.
- `h`: a pointer to the header.
- `pid`: TS packet ID.
- `continuity_counter`: Incremented on every new packet.
- `dest_buf_sz`: The size of the dest_buffer
- `crc`: a pointer to store the crc for this chunk

#### <a id="c-vidtv_psi_sdt_service_assign"></a>`vidtv_psi_sdt_service_assign()`

```c
void vidtv_psi_sdt_service_assign(struct vidtv_psi_table_sdt *sdt, struct vidtv_psi_table_sdt_service *service)
```

Assigns the service loop to the SDT.

**Parameters**

- `struct vidtv_psi_table_sdt *sdt`: The SDT to assign to.
- `struct vidtv_psi_table_sdt_service *service`: The service loop (one or more services)

**Description**

This will free the previous service loop in the table.
This will assign ownership of the service loop to the table, i.e. the table
will free this service loop when a call to its destroy function is made.

#### <a id="c-vidtv_psi_desc_assign"></a>`vidtv_psi_desc_assign()`

```c
void vidtv_psi_desc_assign(struct vidtv_psi_desc **to, struct vidtv_psi_desc *desc)
```

Assigns a descriptor loop at some point

**Parameters**

- `struct vidtv_psi_desc **to`: Where to assign this descriptor loop to
- `struct vidtv_psi_desc *desc`: The descriptor loop that will be assigned.

**Description**

This will free the loop in 'to', if any.

#### <a id="c-vidtv_pmt_desc_assign"></a>`vidtv_pmt_desc_assign()`

```c
void vidtv_pmt_desc_assign(struct vidtv_psi_table_pmt *pmt, struct vidtv_psi_desc **to, struct vidtv_psi_desc *desc)
```

Assigns a descriptor loop at some point in a PMT section.

**Parameters**

- `struct vidtv_psi_table_pmt *pmt`: The PMT section that will contain the descriptor loop
- `struct vidtv_psi_desc **to`: Where in the PMT to assign this descriptor loop to
- `struct vidtv_psi_desc *desc`: The descriptor loop that will be assigned.

**Description**

This will free the loop in 'to', if any.
This will assign ownership of the loop to the table, i.e. the table
will free this loop when a call to its destroy function is made.

#### <a id="c-vidtv_sdt_desc_assign"></a>`vidtv_sdt_desc_assign()`

```c
void vidtv_sdt_desc_assign(struct vidtv_psi_table_sdt *sdt, struct vidtv_psi_desc **to, struct vidtv_psi_desc *desc)
```

Assigns a descriptor loop at some point in a SDT.

**Parameters**

- `struct vidtv_psi_table_sdt *sdt`: The SDT that will contain the descriptor loop
- `struct vidtv_psi_desc **to`: Where in the PMT to assign this descriptor loop to
- `struct vidtv_psi_desc *desc`: The descriptor loop that will be assigned.

**Description**

This will free the loop in 'to', if any.
This will assign ownership of the loop to the table, i.e. the table
will free this loop when a call to its destroy function is made.

#### <a id="c-vidtv_psi_pat_program_assign"></a>`vidtv_psi_pat_program_assign()`

```c
void vidtv_psi_pat_program_assign(struct vidtv_psi_table_pat *pat, struct vidtv_psi_table_pat_program *p)
```

Assigns the program loop to the PAT.

**Parameters**

- `struct vidtv_psi_table_pat *pat`: The PAT to assign to.
- `struct vidtv_psi_table_pat_program *p`: The program loop (one or more programs)

**Description**

This will free the previous program loop in the table.
This will assign ownership of the program loop to the table, i.e. the table
will free this program loop when a call to its destroy function is made.

#### <a id="c-vidtv_psi_pmt_stream_assign"></a>`vidtv_psi_pmt_stream_assign()`

```c
void vidtv_psi_pmt_stream_assign(struct vidtv_psi_table_pmt *pmt, struct vidtv_psi_table_pmt_stream *s)
```

Assigns the stream loop to the PAT.

**Parameters**

- `struct vidtv_psi_table_pmt *pmt`: The PMT to assign to.
- `struct vidtv_psi_table_pmt_stream *s`: The stream loop (one or more streams)

**Description**

This will free the previous stream loop in the table.
This will assign ownership of the stream loop to the table, i.e. the table
will free this stream loop when a call to its destroy function is made.

#### <a id="c-vidtv_psi_pmt_create_sec_for_each_pat_entry"></a>`vidtv_psi_pmt_create_sec_for_each_pat_entry()`

```c
struct vidtv_psi_table_pmt** vidtv_psi_pmt_create_sec_for_each_pat_entry(struct vidtv_psi_table_pat *pat, u16 pcr_pid)
```

Create a PMT section for each program found in the PAT

**Parameters**

- `struct vidtv_psi_table_pat *pat`: The PAT to look for programs.
- `u16 pcr_pid`: packet ID for the PCR to be used for the program described in this
  PMT section

#### <a id="c-vidtv_psi_pmt_get_pid"></a>`vidtv_psi_pmt_get_pid()`

```c
u16 vidtv_psi_pmt_get_pid(struct vidtv_psi_table_pmt *section, struct vidtv_psi_table_pat *pat)
```

Get the TS PID for a PMT section.

**Parameters**

- `struct vidtv_psi_table_pmt *section`: The PMT section whose PID we want to retrieve.
- `struct vidtv_psi_table_pat *pat`: The PAT table to look into.

**Return**

the TS PID for 'section'

#### <a id="c-vidtv_psi_pat_table_update_sec_len"></a>`vidtv_psi_pat_table_update_sec_len()`

```c
void vidtv_psi_pat_table_update_sec_len(struct vidtv_psi_table_pat *pat)
```

Recompute and update the PAT section length.

**Parameters**

- `struct vidtv_psi_table_pat *pat`: The PAT whose length is to be updated.

**Description**

This will traverse the table and accumulate the length of its components,
which is then used to replace the 'section_length' field.

If section_length > MAX_SECTION_LEN, the operation fails.

#### <a id="c-vidtv_psi_pmt_table_update_sec_len"></a>`vidtv_psi_pmt_table_update_sec_len()`

```c
void vidtv_psi_pmt_table_update_sec_len(struct vidtv_psi_table_pmt *pmt)
```

Recompute and update the PMT section length.

**Parameters**

- `struct vidtv_psi_table_pmt *pmt`: The PMT whose length is to be updated.

**Description**

This will traverse the table and accumulate the length of its components,
which is then used to replace the 'section_length' field.

If section_length > MAX_SECTION_LEN, the operation fails.

#### <a id="c-vidtv_psi_sdt_table_update_sec_len"></a>`vidtv_psi_sdt_table_update_sec_len()`

```c
void vidtv_psi_sdt_table_update_sec_len(struct vidtv_psi_table_sdt *sdt)
```

Recompute and update the SDT section length.

**Parameters**

- `struct vidtv_psi_table_sdt *sdt`: The SDT whose length is to be updated.

**Description**

This will traverse the table and accumulate the length of its components,
which is then used to replace the 'section_length' field.

If section_length > MAX_SECTION_LEN, the operation fails.

#### <a id="c-struct-vidtv_psi_pat_write_args"></a>`struct vidtv_psi_pat_write_args`

Arguments for writing a PAT table

**Definition**

```c
struct vidtv_psi_pat_write_args {
    char *buf;
    u32 offset;
    struct vidtv_psi_table_pat *pat;
    u32 buf_sz;
    u8 *continuity_counter;
};
```

**Members**

- `buf`: The destination buffer.
- `offset`: The offset into the destination buffer.
- `pat`: A pointer to the PAT.
- `buf_sz`: The size of the destination buffer.
- `continuity_counter`: A pointer to the CC. Incremented on every new packet.

#### <a id="c-vidtv_psi_pat_write_into"></a>`vidtv_psi_pat_write_into()`

```c
u32 vidtv_psi_pat_write_into(struct vidtv_psi_pat_write_args *args)
```

Write PAT as MPEG-TS packets into a buffer.

**Parameters**

- `struct vidtv_psi_pat_write_args *args`: An instance of struct vidtv_psi_pat_write_args

**Description**

This function writes the MPEG TS packets for a PAT table into a buffer.
Calling code will usually generate the PAT via a call to its init function
and thus is responsible for freeing it.

**Return**

The number of bytes written into the buffer. This is NOT
equal to the size of the PAT, since more space is needed for TS headers during TS
encapsulation.

#### <a id="c-struct-vidtv_psi_sdt_write_args"></a>`struct vidtv_psi_sdt_write_args`

Arguments for writing a SDT table

**Definition**

```c
struct vidtv_psi_sdt_write_args {
    char *buf;
    u32 offset;
    struct vidtv_psi_table_sdt *sdt;
    u32 buf_sz;
    u8 *continuity_counter;
};
```

**Members**

- `buf`: The destination buffer.
- `offset`: The offset into the destination buffer.
- `sdt`: A pointer to the SDT.
- `buf_sz`: The size of the destination buffer.
- `continuity_counter`: A pointer to the CC. Incremented on every new packet.

#### <a id="c-vidtv_psi_sdt_write_into"></a>`vidtv_psi_sdt_write_into()`

```c
u32 vidtv_psi_sdt_write_into(struct vidtv_psi_sdt_write_args *args)
```

Write SDT as MPEG-TS packets into a buffer.

**Parameters**

- `struct vidtv_psi_sdt_write_args *args`: an instance of struct vidtv_psi_sdt_write_args

**Description**

This function writes the MPEG TS packets for a SDT table into a buffer.
Calling code will usually generate the SDT via a call to its init function
and thus is responsible for freeing it.

**Return**

The number of bytes written into the buffer. This is NOT
equal to the size of the SDT, since more space is needed for TS headers during TS
encapsulation.

#### <a id="c-struct-vidtv_psi_pmt_write_args"></a>`struct vidtv_psi_pmt_write_args`

Arguments for writing a PMT section

**Definition**

```c
struct vidtv_psi_pmt_write_args {
    char *buf;
    u32 offset;
    struct vidtv_psi_table_pmt *pmt;
    u16 pid;
    u32 buf_sz;
    u8 *continuity_counter;
    u16 pcr_pid;
};
```

**Members**

- `buf`: The destination buffer.
- `offset`: The offset into the destination buffer.
- `pmt`: A pointer to the PMT.
- `pid`: Program ID
- `buf_sz`: The size of the destination buffer.
- `continuity_counter`: A pointer to the CC. Incremented on every new packet.
- `pcr_pid`: The TS PID used for the PSI packets. All channels will share the
  same PCR.

#### <a id="c-vidtv_psi_pmt_write_into"></a>`vidtv_psi_pmt_write_into()`

```c
u32 vidtv_psi_pmt_write_into(struct vidtv_psi_pmt_write_args *args)
```

Write PMT as MPEG-TS packets into a buffer.

**Parameters**

- `struct vidtv_psi_pmt_write_args *args`: an instance of struct vidtv_psi_pmt_write_args

**Description**

This function writes the MPEG TS packets for a PMT section into a buffer.
Calling code will usually generate the PMT section via a call to its init function
and thus is responsible for freeing it.

**Return**

The number of bytes written into the buffer. This is NOT
equal to the size of the PMT section, since more space is needed for TS headers
during TS encapsulation.

#### <a id="c-vidtv_psi_find_pmt_sec"></a>`vidtv_psi_find_pmt_sec()`

```c
struct vidtv_psi_table_pmt * vidtv_psi_find_pmt_sec(struct vidtv_psi_table_pmt **pmt_sections, u16 nsections, u16 program_num)
```

Finds the PMT section for 'program_num'

**Parameters**

- `struct vidtv_psi_table_pmt **pmt_sections`: The sections to look into.
- `u16 nsections`: The number of sections.
- `u16 program_num`: The 'program_num' from PAT pointing to a PMT section.

**Return**

A pointer to the PMT, if found, or NULL.

#### <a id="c-struct-vidtv_psi_table_transport"></a>`struct vidtv_psi_table_transport`

A entry in the TS loop for the NIT and/or other tables. See ETSI 300 468 section 5.2.1

**Definition**

```c
struct vidtv_psi_table_transport {
    __be16 transport_id;
    __be16 network_id;
    __be16 bitfield;
    struct vidtv_psi_desc *descriptor;
    struct vidtv_psi_table_transport *next;
};
```

**Members**

- `transport_id`: The TS ID being described
- `network_id`: The network_id that contains the TS ID
- `bitfield`: Contains the descriptor loop length
- `descriptor`: A descriptor loop
- `next`: Pointer to the next entry

#### <a id="c-struct-vidtv_psi_table_nit"></a>`struct vidtv_psi_table_nit`

A Network Information Table (NIT). See ETSI 300 468 section 5.2.1

**Definition**

```c
struct vidtv_psi_table_nit {
    struct vidtv_psi_table_header header;
    __be16 bitfield;
    struct vidtv_psi_desc *descriptor;
    __be16 bitfield2;
    struct vidtv_psi_table_transport *transport;
};
```

**Members**

- `header`: A PSI table header
- `bitfield`: Contains the network descriptor length
- `descriptor`: A descriptor loop describing the network
- `bitfield2`: Contains the transport stream loop length
- `transport`: The transport stream loop

#### <a id="c-struct-vidtv_psi_nit_write_args"></a>`struct vidtv_psi_nit_write_args`

Arguments for writing a NIT section

**Definition**

```c
struct vidtv_psi_nit_write_args {
    char *buf;
    u32 offset;
    struct vidtv_psi_table_nit *nit;
    u32 buf_sz;
    u8 *continuity_counter;
};
```

**Members**

- `buf`: The destination buffer.
- `offset`: The offset into the destination buffer.
- `nit`: A pointer to the NIT
- `buf_sz`: The size of the destination buffer.
- `continuity_counter`: A pointer to the CC. Incremented on every new packet.

#### <a id="c-vidtv_psi_nit_write_into"></a>`vidtv_psi_nit_write_into()`

```c
u32 vidtv_psi_nit_write_into(struct vidtv_psi_nit_write_args *args)
```

Write NIT as MPEG-TS packets into a buffer.

**Parameters**

- `struct vidtv_psi_nit_write_args *args`: an instance of struct vidtv_psi_nit_write_args

**Description**

This function writes the MPEG TS packets for a NIT table into a buffer.
Calling code will usually generate the NIT via a call to its init function
and thus is responsible for freeing it.

**Return**

The number of bytes written into the buffer. This is NOT
equal to the size of the NIT, since more space is needed for TS headers during TS
encapsulation.

#### <a id="c-struct-vidtv_psi_eit_write_args"></a>`struct vidtv_psi_eit_write_args`

Arguments for writing an EIT section

**Definition**

```c
struct vidtv_psi_eit_write_args {
    char *buf;
    u32 offset;
    struct vidtv_psi_table_eit *eit;
    u32 buf_sz;
    u8 *continuity_counter;
};
```

**Members**

- `buf`: The destination buffer.
- `offset`: The offset into the destination buffer.
- `eit`: A pointer to the EIT
- `buf_sz`: The size of the destination buffer.
- `continuity_counter`: A pointer to the CC. Incremented on every new packet.

#### <a id="c-vidtv_psi_eit_write_into"></a>`vidtv_psi_eit_write_into()`

```c
u32 vidtv_psi_eit_write_into(struct vidtv_psi_eit_write_args *args)
```

Write EIT as MPEG-TS packets into a buffer.

**Parameters**

- `struct vidtv_psi_eit_write_args *args`: an instance of struct vidtv_psi_nit_write_args

**Description**

This function writes the MPEG TS packets for a EIT table into a buffer.
Calling code will usually generate the EIT via a call to its init function
and thus is responsible for freeing it.

**Return**

The number of bytes written into the buffer. This is NOT
equal to the size of the EIT, since more space is needed for TS headers during TS
encapsulation.

#### <a id="c-vidtv_psi_eit_table_update_sec_len"></a>`vidtv_psi_eit_table_update_sec_len()`

```c
void vidtv_psi_eit_table_update_sec_len(struct vidtv_psi_table_eit *eit)
```

Recompute and update the EIT section length.

**Parameters**

- `struct vidtv_psi_table_eit *eit`: The EIT whose length is to be updated.

**Description**

This will traverse the table and accumulate the length of its components,
which is then used to replace the 'section_length' field.

If section_length > EIT_MAX_SECTION_LEN, the operation fails.

#### <a id="c-vidtv_psi_eit_event_assign"></a>`vidtv_psi_eit_event_assign()`

```c
void vidtv_psi_eit_event_assign(struct vidtv_psi_table_eit *eit, struct vidtv_psi_table_eit_event *e)
```

Assigns the event loop to the EIT.

**Parameters**

- `struct vidtv_psi_table_eit *eit`: The EIT to assign to.
- `struct vidtv_psi_table_eit_event *e`: The event loop

**Description**

This will free the previous event loop in the table.
This will assign ownership of the stream loop to the table, i.e. the table
will free this stream loop when a call to its destroy function is made.



#### <a id="c-struct-vidtv_s302m_ctx"></a>`struct vidtv_s302m_ctx`

s302m encoder context.

**Definition**

```c
struct vidtv_s302m_ctx {
    struct vidtv_encoder *enc;
    u32 frame_index;
    u32 au_count;
    int last_duration;
    unsigned int note_offset;
    enum musical_notes last_tone;
};
```

**Members**

- `enc`: A pointer to the containing encoder structure.
- `frame_index`: The current frame in a block
- `au_count`: The total number of access units encoded up to now
- `last_duration`: Duration of the tone currently being played
- `note_offset`: Position at the music tone array
- `last_tone`: Tone currently being played

#### <a id="c-struct-vidtv_s302m_encoder_init_args"></a>`struct vidtv_s302m_encoder_init_args`

Args for the s302m encoder.

**Definition**

```c
struct vidtv_s302m_encoder_init_args {
    char *name;
    void *src_buf;
    u32 src_buf_sz;
    u16 es_pid;
    struct vidtv_encoder *sync;
    void (*last_sample_cb)(u32 sample_no);
    struct vidtv_encoder *head;
};
```

**Members**

- `name`: A name to identify this particular instance
- `src_buf`: The source buffer, encoder will default to a sine wave if this is NULL.
- `src_buf_sz`: The size of the source buffer.
- `es_pid`: The MPEG Elementary Stream PID to use.
- `sync`: Attempt to synchronize audio with this video encoder, if not NULL.
- `last_sample_cb`: A callback called when the encoder runs out of data.
- `head`: Add to this chain



#### <a id="c-struct-pcr_write_args"></a>`struct pcr_write_args`

Arguments for the pcr_write_into function.

**Definition**

```c
struct pcr_write_args {
    void *dest_buf;
    u32 dest_offset;
    u16 pid;
    u32 buf_sz;
    u8 *continuity_counter;
    u64 pcr;
};
```

**Members**

- `dest_buf`: The buffer to write into.
- `dest_offset`: The byte offset into the buffer.
- `pid`: The TS PID for the PCR packets.
- `buf_sz`: The size of the buffer in bytes.
- `continuity_counter`: The TS continuity_counter.
- `pcr`: A sample from the system clock.

#### <a id="c-struct-null_packet_write_args"></a>`struct null_packet_write_args`

Arguments for the null_write_into function

**Definition**

```c
struct null_packet_write_args {
    void *dest_buf;
    u32 dest_offset;
    u32 buf_sz;
    u8 *continuity_counter;
};
```

**Members**

- `dest_buf`: The buffer to write into.
- `dest_offset`: The byte offset into the buffer.
- `buf_sz`: The size of the buffer in bytes.
- `continuity_counter`: The TS continuity_counter.

#### <a id="c-vidtv_ts_null_write_into"></a>`vidtv_ts_null_write_into()`

```c
u32 vidtv_ts_null_write_into(const struct null_packet_write_args *args)
```

Write a TS null packet into a buffer.

**Parameters**

- `const struct null_packet_write_args *args`: the arguments to use when writing.

**Description**

This function will write a null packet into a buffer. This is usually used to
pad TS streams.

**Return**

The number of bytes written into the buffer.

#### <a id="c-vidtv_ts_pcr_write_into"></a>`vidtv_ts_pcr_write_into()`

```c
u32 vidtv_ts_pcr_write_into(const struct pcr_write_args *args)
```

Write a PCR packet into a buffer.

**Parameters**

- `const struct pcr_write_args *args`: the arguments to use when writing.

**Description**

This function will write a PCR packet into a buffer. This is used to
synchronize the clocks between encoders and decoders.

**Return**

The number of bytes written into the buffer.



#### <a id="c-struct-vidtv_tuner_config"></a>`struct vidtv_tuner_config`

Configuration used to init the tuner.

**Definition**

```c
struct vidtv_tuner_config {
    struct dvb_frontend *fe;
    u32 mock_power_up_delay_msec;
    u32 mock_tune_delay_msec;
    u32 vidtv_valid_dvb_t_freqs[NUM_VALID_TUNER_FREQS];
    u32 vidtv_valid_dvb_c_freqs[NUM_VALID_TUNER_FREQS];
    u32 vidtv_valid_dvb_s_freqs[NUM_VALID_TUNER_FREQS];
    u8 max_frequency_shift_hz;
};
```

**Members**

- `fe`: A pointer to the dvb_frontend structure allocated by vidtv_demod.
- `mock_power_up_delay_msec`: Simulate a power-up delay.
- `mock_tune_delay_msec`: Simulate a tune delay.
- `vidtv_valid_dvb_t_freqs`: The valid DVB-T frequencies to simulate.
- `vidtv_valid_dvb_c_freqs`: The valid DVB-C frequencies to simulate.
- `vidtv_valid_dvb_s_freqs`: The valid DVB-S frequencies to simulate.
- `max_frequency_shift_hz`: The maximum frequency shift in HZ allowed when
  tuning in a channel

**Description**

The configuration used to init the tuner module, usually filled
by a bridge driver. For vidtv, this is filled by vidtv_bridge before the
tuner module is probed.



#### <a id="c-vidtv_memcpy"></a>`vidtv_memcpy()`

```c
u32 vidtv_memcpy(void *to, size_t to_offset, size_t to_size, const void *from, size_t len)
```

wrapper routine to be used by MPEG-TS generator, in order to avoid going past the output buffer.

**Parameters**

- `void *to`: Starting element to where a MPEG-TS packet will
  be copied.
- `size_t to_offset`: Starting position of the **to** buffer to be filled.
- `size_t to_size`: Size of the **to** buffer.
- `const void *from`: Starting element of the buffer to be copied.
- `size_t len`: Number of elements to be copy from **from** buffer
  into **to**+ **to_offset** buffer.

**Note**

Real digital TV demod drivers should not have memcpy
wrappers. We use it here because emulating MPEG-TS
generation at kernelspace requires some extra care.

**Return**

Returns the number of bytes written

#### <a id="c-vidtv_memset"></a>`vidtv_memset()`

```c
u32 vidtv_memset(void *to, size_t to_offset, size_t to_size, const int c, size_t len)
```

wrapper routine to be used by MPEG-TS generator, in order to avoid going past the output buffer.

**Parameters**

- `void *to`: Starting element to set
- `size_t to_offset`: Starting position of the **to** buffer to be filled.
- `size_t to_size`: Size of the **to** buffer.
- `const int c`: The value to set the memory to.
- `size_t len`: Number of elements to be copy from **from** buffer
  into **to**+ **to_offset** buffer.

**Note**

Real digital TV demod drivers should not have memset
wrappers. We use it here because emulating MPEG-TS
generation at kernelspace requires some extra care.

**Return**

Returns the number of bytes written



#### <a id="c-struct-vidtv_tuner_hardware_state"></a>`struct vidtv_tuner_hardware_state`

Simulate the tuner hardware status

**Definition**

```c
struct vidtv_tuner_hardware_state {
    bool asleep;
    u32 lock_status;
    u32 if_frequency;
    u32 tuned_frequency;
    u32 bandwidth;
};
```

**Members**

- `asleep`: whether the tuner is asleep, i.e whether `_sleep()` or `_suspend()` was
  called.
- `lock_status`: Whether the tuner has managed to lock on the requested
  frequency.
- `if_frequency`: The tuner's intermediate frequency. Hardcoded for the purposes
  of simulation.
- `tuned_frequency`: The actual tuned frequency.
- `bandwidth`: The actual bandwidth.

**Description**

This structure is meant to simulate the status of the tuner hardware, as if
we had a physical tuner hardware.

#### <a id="c-struct-vidtv_tuner_dev"></a>`struct vidtv_tuner_dev`

The tuner struct

**Definition**

```c
struct vidtv_tuner_dev {
    struct dvb_frontend *fe;
    struct vidtv_tuner_hardware_state hw_state;
    struct vidtv_tuner_config config;
};
```

**Members**

- `fe`: A pointer to the dvb_frontend structure allocated by vidtv_demod
- `hw_state`: A struct to simulate the tuner's hardware state as if we had a
  physical tuner hardware.
- `config`: The configuration used to start the tuner module, usually filled
  by a bridge driver. For vidtv, this is filled by vidtv_bridge before the
  tuner module is probed.

---

# The Virtual Media Controller Driver (vimc)

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> Reference for The Virtual Media Controller Driver (vimc).

<a id="rst-the-virtual-media-controller-driver-vimc"></a>

<a id="rst-source-code-documentation"></a>

## Source code documentation

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-vimc-streamer"></a>

## vimc-streamer


#### <a id="c-struct-vimc_stream"></a>`struct vimc_stream`

struct that represents a stream in the pipeline

**Definition**

```c
struct vimc_stream {
    struct media_pipeline pipe;
    struct vimc_ent_device *ved_pipeline[VIMC_STREAMER_PIPELINE_MAX_SIZE];
    unsigned int pipe_size;
    struct task_struct *kthread;
};
```

**Members**

- `pipe`: the media pipeline object associated with this stream
- `ved_pipeline`: array containing all the entities participating in the
  stream. The order is from a video device (usually a
  capture device) where stream_on was called, to the
  entity generating the first base image to be
  processed in the pipeline.
- `pipe_size`: size of **ved_pipeline**
- `kthread`: thread that generates the frames of the stream.

**Description**

When the user call stream_on in a video device, struct vimc_stream is
used to keep track of all entities and subdevices that generates and
process frames for the stream.



#### <a id="c-vimc_get_source_entity"></a>`vimc_get_source_entity()`

```c
struct media_entity * vimc_get_source_entity(struct media_entity *ent)
```

get the entity connected with the first sink pad

**Parameters**

- `struct media_entity *ent`: reference media_entity

**Description**

Helper function that returns the media entity containing the source pad
linked with the first sink pad from the given media entity pad list.

**Return**

The source pad or NULL, if it wasn't found.

#### <a id="c-vimc_streamer_pipeline_terminate"></a>`vimc_streamer_pipeline_terminate()`

```c
void vimc_streamer_pipeline_terminate(struct vimc_stream *stream)
```

Disable stream in all ved in stream

**Parameters**

- `struct vimc_stream *stream`: the pointer to the stream structure with the pipeline to be
  disabled.

**Description**

Calls s_stream to disable the stream in each entity of the pipeline

#### <a id="c-vimc_streamer_pipeline_init"></a>`vimc_streamer_pipeline_init()`

```c
int vimc_streamer_pipeline_init(struct vimc_stream *stream, struct vimc_ent_device *ved)
```

Initializes the stream structure

**Parameters**

- `struct vimc_stream *stream`: the pointer to the stream structure to be initialized
- `struct vimc_ent_device *ved`: the pointer to the vimc entity initializing the stream

**Description**

Initializes the stream structure. Walks through the entity graph to
construct the pipeline used later on the streamer thread.
Calls [`vimc_streamer_s_stream()`](#c-vimc_streamer_s_stream) to enable stream in all entities of
the pipeline.

**Return**

0 if success, error code otherwise.

#### <a id="c-vimc_streamer_thread"></a>`vimc_streamer_thread()`

```c
int vimc_streamer_thread(void *data)
```

Process frames through the pipeline

**Parameters**

- `void *data`: vimc_stream struct of the current stream

**Description**

From the source to the sink, gets a frame from each subdevice and send to
the next one of the pipeline at a fixed framerate.

**Return**

Always zero (created as `int` instead of `void` to comply with
kthread API).

#### <a id="c-vimc_streamer_s_stream"></a>`vimc_streamer_s_stream()`

```c
int vimc_streamer_s_stream(struct vimc_stream *stream, struct vimc_ent_device *ved, int enable)
```

Start/stop the streaming on the media pipeline

**Parameters**

- `struct vimc_stream *stream`: the pointer to the stream structure of the current stream
- `struct vimc_ent_device *ved`: pointer to the vimc entity of the entity of the stream
- `int enable`: flag to determine if stream should start/stop

**Description**

When starting, check if there is no `stream->kthread` allocated. This
should indicate that a stream is already running. Then, it initializes the
pipeline, creates and runs a kthread to consume buffers through the pipeline.
When stopping, analogously check if there is a stream running, stop the
thread and terminates the pipeline.

**Return**

0 if success, error code otherwise.

---

# The Zoran driver

_Peios Kernel / Hardware and drivers / Driver development / Media driver interfaces_

> unified zoran driver (zr360x7, zoran, buz, dc10(+), dc30(+), lml33)

<a id="rst-the-zoran-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

unified zoran driver (zr360x7, zoran, buz, dc10(+), dc30(+), lml33)

website: [http://mjpeg.sourceforge.net/driver-zoran/](<http://mjpeg.sourceforge.net/driver-zoran/>)

<a id="rst-frequently-asked-questions"></a>

## Frequently Asked Questions

<a id="rst-what-cards-are-supported"></a>

## What cards are supported

Iomega Buz, Linux Media Labs LML33/LML33R10, Pinnacle/Miro DC10/DC10+/DC30/DC30+ and related boards (available under various names).

<a id="rst-iomega-buz"></a>

### Iomega Buz

- Zoran zr36067 PCI controller

- Zoran zr36060 MJPEG codec

- Philips saa7111 TV decoder

- Philips saa7185 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit, videocodec, saa7111, saa7185, zr36060, zr36067

Inputs/outputs: Composite and S-video

Norms: PAL, SECAM (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)

Card number: 7

<a id="rst-avermedia-6-eyes-avs6eyes"></a>

### AverMedia 6 Eyes AVS6EYES

- Zoran zr36067 PCI controller

- Zoran zr36060 MJPEG codec

- Samsung ks0127 TV decoder

- Conexant bt866  TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit, videocodec, ks0127, bt866, zr36060, zr36067

- **Inputs/outputs:**

  Six physical inputs. 1-6 are composite, 1-2, 3-4, 5-6 doubles as S-video, 1-3 triples as component. One composite output.

Norms: PAL, SECAM (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)

Card number: 8

> [!NOTE]
>
> Not autodetected, card=8 is necessary.

<a id="rst-linux-media-labs-lml33"></a>

### Linux Media Labs LML33

- Zoran zr36067 PCI controller

- Zoran zr36060 MJPEG codec

- Brooktree bt819 TV decoder

- Brooktree bt856 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit, videocodec, bt819, bt856, zr36060, zr36067

Inputs/outputs: Composite and S-video

Norms: PAL (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)

Card number: 5

<a id="rst-linux-media-labs-lml33r10"></a>

### Linux Media Labs LML33R10

- Zoran zr36067 PCI controller

- Zoran zr36060 MJPEG codec

- Philips saa7114 TV decoder

- Analog Devices adv7170 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit, videocodec, saa7114, adv7170, zr36060, zr36067

Inputs/outputs: Composite and S-video

Norms: PAL (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)

Card number: 6

<a id="rst-pinnacle-miro-dc10-new"></a>

### Pinnacle/Miro DC10(new)

- Zoran zr36057 PCI controller

- Zoran zr36060 MJPEG codec

- Philips saa7110a TV decoder

- Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit, videocodec, saa7110, adv7175, zr36060, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 1

<a id="rst-pinnacle-miro-dc10"></a>

### Pinnacle/Miro DC10+

- Zoran zr36067 PCI controller

- Zoran zr36060 MJPEG codec

- Philips saa7110a TV decoder

- Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit, videocodec, saa7110, adv7175, zr36060, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 2

<a id="rst-pinnacle-miro-dc10-old"></a>

### Pinnacle/Miro DC10(old)

- Zoran zr36057 PCI controller

- Zoran zr36050 MJPEG codec

- Zoran zr36016 Video Front End or Fuji md0211 Video Front End (clone?)

- Micronas vpx3220a TV decoder

- mse3000 TV encoder or Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit, videocodec, vpx3220, mse3000/adv7175, zr36050, zr36016, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 0

<a id="rst-pinnacle-miro-dc30"></a>

### Pinnacle/Miro DC30

- Zoran zr36057 PCI controller

- Zoran zr36050 MJPEG codec

- Zoran zr36016 Video Front End

- Micronas vpx3225d/vpx3220a/vpx3216b TV decoder

- Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit, videocodec, vpx3220/vpx3224, adv7175, zr36050, zr36016, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 3

<a id="rst-pinnacle-miro-dc30-1"></a>

### Pinnacle/Miro DC30+

- Zoran zr36067 PCI controller

- Zoran zr36050 MJPEG codec

- Zoran zr36016 Video Front End

- Micronas vpx3225d/vpx3220a/vpx3216b TV decoder

- Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit, videocodec, vpx3220/vpx3224, adv7175, zr36050, zr36015, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 4

> [!NOTE]
>
> 1. No module for the mse3000 is available yet
>
> 2. No module for the vpx3224 is available yet

<a id="rst-what-the-tv-decoder-can-do-an-what-not"></a>

## 1.1 What the TV decoder can do an what not

The best know TV standards are NTSC/PAL/SECAM. but for decoding a frame that information is not enough. There are several formats of the TV standards. And not every TV decoder is able to handle every format. Also the every combination is supported by the driver. There are currently 11 different tv broadcast formats all aver the world.

The CCIR defines parameters needed for broadcasting the signal. The CCIR has defined different standards: A,B,D,E,F,G,D,H,I,K,K1,L,M,N,... The CCIR says not much about the colorsystem used \!\!\! And talking about a colorsystem says not to much about how it is broadcast.

The CCIR standards A,E,F are not used any more.

When you speak about NTSC, you usually mean the standard: CCIR - M using the NTSC colorsystem which is used in the USA, Japan, Mexico, Canada and a few others.

When you talk about PAL, you usually mean: CCIR - B/G using the PAL colorsystem which is used in many Countries.

When you talk about SECAM, you mean: CCIR - L using the SECAM Colorsystem which is used in France, and a few others.

There the other version of SECAM, CCIR - D/K is used in Bulgaria, China, Slovakai, Hungary, Korea (Rep.), Poland, Rumania and a others.

The CCIR - H uses the PAL colorsystem (sometimes SECAM) and is used in Egypt, Libya, Sri Lanka, Syrain Arab. Rep.

The CCIR - I uses the PAL colorsystem, and is used in Great Britain, Hong Kong, Ireland, Nigeria, South Africa.

The CCIR - N uses the PAL colorsystem and PAL frame size but the NTSC framerate, and is used in Argentina, Uruguay, an a few others

We do not talk about how the audio is broadcast \!

A rather good sites about the TV standards are: [http://www.sony.jp/support/](<http://www.sony.jp/support/>) [http://info.electronicwerkstatt.de/bereiche/fernsehtechnik/frequenzen_und_normen/Fernsehnormen/](<http://info.electronicwerkstatt.de/bereiche/fernsehtechnik/frequenzen_und_normen/Fernsehnormen/>) and [http://www.cabl.com/restaurant/channel.html](<http://www.cabl.com/restaurant/channel.html>)

Other weird things around: NTSC 4.43 is a modificated NTSC, which is mainly used in PAL VCR's that are able to play back NTSC. PAL 60 seems to be the same as NTSC 4.43 . The Datasheets also talk about NTSC 44, It seems as if it would be the same as NTSC 4.43. NTSC Combs seems to be a decoder mode where the decoder uses a comb filter to split coma and luma instead of a Delay line.

But I did not defiantly find out what NTSC Comb is.

<a id="rst-philips-saa7111-tv-decoder"></a>

### Philips saa7111 TV decoder

- was introduced in 1997, is used in the BUZ and

- can handle: PAL B/G/H/I, PAL N, PAL M, NTSC M, NTSC N, NTSC 4.43 and SECAM

<a id="rst-philips-saa7110a-tv-decoder"></a>

### Philips saa7110a TV decoder

- was introduced in 1995, is used in the Pinnacle/Miro DC10(new), DC10+ and

- can handle: PAL B/G, NTSC M and SECAM

<a id="rst-philips-saa7114-tv-decoder"></a>

### Philips saa7114 TV decoder

- was introduced in 2000, is used in the LML33R10 and

- can handle: PAL B/G/D/H/I/N, PAL N, PAL M, NTSC M, NTSC 4.43 and SECAM

<a id="rst-brooktree-bt819-tv-decoder"></a>

### Brooktree bt819 TV decoder

- was introduced in 1996, and is used in the LML33 and

- can handle: PAL B/D/G/H/I, NTSC M

<a id="rst-micronas-vpx3220a-tv-decoder"></a>

### Micronas vpx3220a TV decoder

- was introduced in 1996, is used in the DC30 and DC30+ and

- can handle: PAL B/G/H/I, PAL N, PAL M, NTSC M, NTSC 44, PAL 60, SECAM,NTSC Comb

<a id="rst-samsung-ks0127-tv-decoder"></a>

### Samsung ks0127 TV decoder

- is used in the AVS6EYES card and

- can handle: NTSC-M/N/44, PAL-M/N/B/G/H/I/D/K/L and SECAM

<a id="rst-what-the-tv-encoder-can-do-an-what-not"></a>

## What the TV encoder can do an what not

The TV encoder is doing the "same" as the decoder, but in the other direction. You feed them digital data and the generate a Composite or SVHS signal. For information about the colorsystems and TV norm take a look in the TV decoder section.

<a id="rst-philips-saa7185-tv-encoder"></a>

### Philips saa7185 TV Encoder

- was introduced in 1996, is used in the BUZ

- can generate: PAL B/G, NTSC M

<a id="rst-brooktree-bt856-tv-encoder"></a>

### Brooktree bt856 TV Encoder

- was introduced in 1994, is used in the LML33

- can generate: PAL B/D/G/H/I/N, PAL M, NTSC M, PAL-N (Argentina)

<a id="rst-analog-devices-adv7170-tv-encoder"></a>

### Analog Devices adv7170 TV Encoder

- was introduced in 2000, is used in the LML300R10

- can generate: PAL B/D/G/H/I/N, PAL M, NTSC M, PAL 60

<a id="rst-analog-devices-adv7175-tv-encoder"></a>

### Analog Devices adv7175 TV Encoder

- was introduced in 1996, is used in the DC10, DC10+, DC10 old, DC30, DC30+

- can generate: PAL B/D/G/H/I/N, PAL M, NTSC M

<a id="rst-itt-mse3000-tv-encoder"></a>

### ITT mse3000 TV encoder

- was introduced in 1991, is used in the DC10 old

- can generate: PAL , NTSC , SECAM

<a id="rst-conexant-bt866-tv-encoder"></a>

### Conexant bt866 TV encoder

- is used in AVS6EYES, and

- can generate: NTSC/PAL, PAL-M, PAL-N

The adv717x, should be able to produce PAL N. But you find nothing PAL N specific in the registers. Seem that you have to reuse a other standard to generate PAL N, maybe it would work if you use the PAL M settings.

<a id="rst-how-do-i-get-this-damn-thing-to-work"></a>

## How do I get this damn thing to work

Load zr36067.o. If it can't autodetect your card, use the card=X insmod option with X being the card number as given in the previous section. To have more than one card, use card=X1\[,X2\[,X3,\[X4\[..\]\]\]\]

To automate this, add the following to your /etc/modprobe.d/zoran.conf:

options zr36067 card=X1\[,X2\[,X3\[,X4\[..\]\]\]\] alias char-major-81-0 zr36067

One thing to keep in mind is that this doesn't load zr36067.o itself yet. It just automates loading. If you start using xawtv, the device won't load on some systems, since you're trying to load modules as a user, which is not allowed ("permission denied"). A quick workaround is to add 'Load "v4l"' to XF86Config-4 when you use X by default, or to run 'v4l-conf -c &lt;device&gt;' in one of your startup scripts (normally rc.local) if you don't use X. Both make sure that the modules are loaded on startup, under the root account.

<a id="rst-what-mainboard-should-i-use-or-why-doesn-t-my-card-work"></a>

## What mainboard should I use (or why doesn't my card work)

&lt;insert lousy disclaimer here&gt;. In short: good=SiS/Intel, bad=VIA.

Experience tells us that people with a Buz, on average, have more problems than users with a DC10+/LML33. Also, it tells us that people owning a VIA- based mainboard (ktXXX, MVP3) have more problems than users with a mainboard based on a different chipset. Here's some notes from Andrew Stevens:

Here's my experience of using LML33 and Buz on various motherboards:

- - **VIA MVP3**

    - Forget it. Pointless. Doesn't work.

- - **Intel 430FX (Pentium 200)**

    - LML33 perfect, Buz tolerable (3 or 4 frames dropped per movie)

- - **Intel 440BX (early stepping)**

    - LML33 tolerable. Buz starting to get annoying (6-10 frames/hour)

- - **Intel 440BX (late stepping)**

    - Buz tolerable, LML3 almost perfect (occasional single frame drops)

- - **SiS735**

    - LML33 perfect, Buz tolerable.

- - **VIA KT133(\*)**

    - LML33 starting to get annoying, Buz poor enough that I have up.

- Both 440BX boards were dual CPU versions.

Bernhard Praschinger later added:

- - **AMD 751**

    - Buz perfect-tolerable

- - **AMD 760**

    - Buz perfect-tolerable

In general, people on the user mailinglist won't give you much of a chance if you have a VIA-based motherboard. They may be cheap, but sometimes, you'd rather want to spend some more money on better boards. In general, VIA mainboard's IDE/PCI performance will also suck badly compared to others. You'll noticed the DC10+/DC30+ aren't mentioned anywhere in the overview. Basically, you can assume that if the Buz works, the LML33 will work too. If the LML33 works, the DC10+/DC30+ will work too. They're most tolerant to different mainboard chipsets from all of the supported cards.

If you experience timeouts during capture, buy a better mainboard or lower the quality/buffersize during capture (see 'Concerning buffer sizes, quality, output size etc.'). If it hangs, there's little we can do as of now. Check your IRQs and make sure the card has its own interrupts.

<a id="rst-programming-interface"></a>

## Programming interface

This driver conforms to video4linux2. Support for V4L1 and for the custom zoran ioctls has been removed in kernel 2.6.38.

For programming example, please, look at lavrec.c and lavplay.c code in the MJPEG-tools ([http://mjpeg.sf.net/](<http://mjpeg.sf.net/>)).

Additional notes for software developers:

> The driver returns maxwidth and maxheight parameters according to the current TV standard (norm). Therefore, the software which communicates with the driver and "asks" for these parameters should first set the correct norm. Well, it seems logically correct: TV standard is "more constant" for current country than geometry settings of a variety of TV capture cards which may work in ITU or square pixel format.

<a id="rst-applications"></a>

## Applications

Applications known to work with this driver:

TV viewing:

- xawtv

- kwintv

- probably any TV application that supports video4linux or video4linux2.

MJPEG capture/playback:

- mjpegtools/lavtools (or Linux Video Studio)

- gstreamer

- mplayer

General raw capture:

- xawtv

- gstreamer

- probably any application that supports video4linux or video4linux2

Video editing:

- Cinelerra

- MainActor

- mjpegtools (or Linux Video Studio)

<a id="rst-concerning-buffer-sizes-quality-output-size-etc"></a>

## Concerning buffer sizes, quality, output size etc.

The zr36060 can do 1:2 JPEG compression. This is really the theoretical maximum that the chipset can reach. The driver can, however, limit compression to a maximum (size) of 1:4. The reason for this is that some cards (e.g. Buz) can't handle 1:2 compression without stopping capture after only a few minutes. With 1:4, it'll mostly work. If you have a Buz, use 'low_bitrate=1' to go into 1:4 max. compression mode.

100% JPEG quality is thus 1:2 compression in practice. So for a full PAL frame (size 720x576). The JPEG fields are stored in YUY2 format, so the size of the fields are 720x288x16/2 bits/field (2 fields/frame) = 207360 bytes/field x 2 = 414720 bytes/frame (add some more bytes for headers and DHT (huffman)/DQT (quantization) tables, and you'll get to something like 512kB per frame for 1:2 compression. For 1:4 compression, you'd have frames of half this size.

Some additional explanation by Martin Samuelsson, which also explains the importance of buffer sizes: -- &gt; Hmm, I do not think it is really that way. With the current (downloaded &gt; at 18:00 Monday) driver I get that output sizes for 10 sec: &gt; -q 50 -b 128 : 24.283.332 Bytes &gt; -q 50 -b 256 : 48.442.368 &gt; -q 25 -b 128 : 24.655.992 &gt; -q 25 -b 256 : 25.859.820

I woke up, and can't go to sleep again. I'll kill some time explaining why this doesn't look strange to me.

Let's do some math using a width of 704 pixels. I'm not sure whether the Buz actually use that number or not, but that's not too important right now.

704x288 pixels, one field, is 202752 pixels. Divided by 64 pixels per block; 3168 blocks per field. Each pixel consist of two bytes; 128 bytes per block; 1024 bits per block. 100% in the new driver mean 1:2 compression; the maximum output becomes 512 bits per block. Actually 510, but 512 is simpler to use for calculations.

Let's say that we specify d1q50. We thus want 256 bits per block; times 3168 becomes 811008 bits; 101376 bytes per field. We're talking raw bits and bytes here, so we don't need to do any fancy corrections for bits-per-pixel or such things. 101376 bytes per field.

d1 video contains two fields per frame. Those sum up to 202752 bytes per frame, and one of those frames goes into each buffer.

But wait a second\! -b128 gives 128kB buffers\! It's not possible to cram 202752 bytes of JPEG data into 128kB\!

This is what the driver notice and automatically compensate for in your examples. Let's do some math using this information:

128kB is 131072 bytes. In this buffer, we want to store two fields, which leaves 65536 bytes for each field. Using 3168 blocks per field, we get 20.68686868... available bytes per block; 165 bits. We can't allow the request for 256 bits per block when there's only 165 bits available\! The -q50 option is silently overridden, and the -b128 option takes precedence, leaving us with the equivalence of -q32.

This gives us a data rate of 165 bits per block, which, times 3168, sums up to 65340 bytes per field, out of the allowed 65536. The current driver has another level of rate limiting; it won't accept -q values that fill more than 6/8 of the specified buffers. (I'm not sure why. "Playing it safe" seem to be a safe bet. Personally, I think I would have lowered requested-bits-per-block by one, or something like that.) We can't use 165 bits per block, but have to lower it again, to 6/8 of the available buffer space: We end up with 124 bits per block, the equivalence of -q24. With 128kB buffers, you can't use greater than -q24 at -d1. (And PAL, and 704 pixels width...)

The third example is limited to -q24 through the same process. The second example, using very similar calculations, is limited to -q48. The only example that actually grab at the specified -q value is the last one, which is clearly visible, looking at the file size. --

Conclusion: the quality of the resulting movie depends on buffer size, quality, whether or not you use 'low_bitrate=1' as insmod option for the zr36060.c module to do 1:4 instead of 1:2 compression, etc.

If you experience timeouts, lowering the quality/buffersize or using 'low_bitrate=1 as insmod option for zr36060.o might actually help, as is proven by the Buz.

<a id="rst-it-hangs-crashes-fails-whatevers-help"></a>

## It hangs/crashes/fails/whatevers\! Help\!

Make sure that the card has its own interrupts (see /proc/interrupts), check the output of dmesg at high verbosity (load zr36067.o with debug=2, load all other modules with debug=1). Check that your mainboard is favorable (see question 2) and if not, test the card in another computer. Also see the notes given in question 3 and try lowering quality/buffersize/capturesize if recording fails after a period of time.

If all this doesn't help, give a clear description of the problem including detailed hardware information (memory+brand, mainboard+chipset+brand, which MJPEG card, processor, other PCI cards that might be of interest), give the system PnP information (/proc/interrupts, /proc/dma, /proc/devices), and give the kernel version, driver version, glibc version, gcc version and any other information that might possibly be of interest. Also provide the dmesg output at high verbosity. See 'Contacting' on how to contact the developers.

<a id="rst-maintainers-contacting"></a>

## Maintainers/Contacting

Previous maintainers/developers of this driver are - Laurent Pinchart &lt;[laurent.pinchart@skynet.be](<mailto:laurent.pinchart@skynet.be>)&gt; - Ronald Bultje [rbultje@ronald.bitfreak.net](<mailto:rbultje@ronald.bitfreak.net>) - Serguei Miridonov &lt;[mirsev@cicese.mx](<mailto:mirsev@cicese.mx>)&gt; - Wolfgang Scherr &lt;[scherr@net4you.net](<mailto:scherr@net4you.net>)&gt; - Dave Perks &lt;[dperks@ibm.net](<mailto:dperks@ibm.net>)&gt; - Rainer Johanni &lt;[Rainer@Johanni.de](<mailto:Rainer@Johanni.de>)&gt;

<a id="rst-driver-s-license"></a>

## Driver's License

> This driver is distributed under the terms of the General Public License.
>
> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
>
> This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

See [http://www.gnu.org/](<http://www.gnu.org/>) for more information.

---

# MIPI CCS camera sensor driver

_Peios Kernel / Hardware and drivers / Driver development / media: drivers: ccs_

> The MIPI CCS camera sensor driver is a generic driver for MIPI CCS compliant camera sensors.

<!-- SPDX-License-Identifier: GPL-2.0-only OR BSD-3-Clause -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

<a id="rst-mipi-ccs-camera-sensor-driver"></a>
<a id="rst-media-ccs-driver"></a>

## MIPI CCS camera sensor driver

The MIPI CCS camera sensor driver is a generic driver for [MIPI CCS](<https://www.mipi.org/specifications/camera-command-set>)<a id="rst-mipi-ccs"></a> compliant camera sensors.

Also see [the CCS driver UAPI documentation](</kernel/userspace/userspace-api/media-drivers/ccs.md#rst-media-ccs-uapi>).

<a id="rst-ccs-static-data"></a>

### CCS static data

The MIPI CCS driver supports CCS static data for all compliant devices, including not just those compliant with CCS 1.1 but also CCS 1.0 and SMIA(++). For CCS the file names are formed as

> ccs/ccs-sensor-vvvv-mmmm-rrrr.fw (sensor) and ccs/ccs-module-vvvv-mmmm-rrrr.fw (module).

For SMIA++ compliant devices the corresponding file names are

> ccs/smiapp-sensor-vv-mmmm-rr.fw (sensor) and ccs/smiapp-module-vv-mmmm-rrrr.fw (module).

For SMIA (non-++) compliant devices the static data file name is

> ccs/smia-sensor-vv-mmmm-rr.fw (sensor).

vvvv or vv denotes MIPI and SMIA manufacturer IDs respectively, mmmm model ID and rrrr or rr revision number.

<a id="rst-ccs-tools"></a>

#### CCS tools

[CCS tools](<https://github.com/MIPI-Alliance/ccs-tools/>)<a id="rst-ccs-tools-1"></a> is a set of tools for working with CCS static data files. CCS tools includes a definition of the human-readable CCS static data YAML format and includes a program to convert it to a binary.

<a id="rst-register-definition-generator"></a>

### Register definition generator

The ccs-regs.asc file contains MIPI CCS register definitions that are used to produce C source code files for definitions that can be better used by programs written in C language. As there are many dependencies between the produced files, please do not modify them manually as it's error-prone and in vain, but instead change the script producing them.

<a id="rst-usage"></a>

#### Usage

Conventionally the script is called this way to update the CCS driver definitions:



```none
$ Documentation/driver-api/media/drivers/ccs/mk-ccs-regs -k \
        -e drivers/media/i2c/ccs/ccs-regs.h \
        -L drivers/media/i2c/ccs/ccs-limits.h \
        -l drivers/media/i2c/ccs/ccs-limits.c \
        -c Documentation/driver-api/media/drivers/ccs/ccs-regs.asc
```

<a id="rst-ccs-pll-calculator"></a>

## CCS PLL calculator

The CCS PLL calculator is used to compute the PLL configuration, given sensor's capabilities as well as board configuration and user specified configuration. As the configuration space that encompasses all these configurations is vast, the PLL calculator isn't entirely trivial. Yet it is relatively simple to use for a driver.

The PLL model implemented by the PLL calculator corresponds to MIPI CCS 1.1.


#### <a id="c-struct-ccs_pll_branch_fr"></a>`struct ccs_pll_branch_fr`

CCS PLL configuration (front)

**Definition**

```c
struct ccs_pll_branch_fr {
    u16 pre_pll_clk_div;
    u16 pll_multiplier;
    u32 pll_ip_clk_freq_hz;
    u32 pll_op_clk_freq_hz;
};
```

**Members**

- `pre_pll_clk_div`: Pre-PLL clock divisor
- `pll_multiplier`: PLL multiplier
- `pll_ip_clk_freq_hz`: PLL input clock frequency
- `pll_op_clk_freq_hz`: PLL output clock frequency

**Description**

A single branch front-end of the CCS PLL tree.

#### <a id="c-struct-ccs_pll_branch_bk"></a>`struct ccs_pll_branch_bk`

CCS PLL configuration (back)

**Definition**

```c
struct ccs_pll_branch_bk {
    u16 sys_clk_div;
    u16 pix_clk_div;
    u32 sys_clk_freq_hz;
    u32 pix_clk_freq_hz;
};
```

**Members**

- `sys_clk_div`: System clock divider
- `pix_clk_div`: Pixel clock divider
- `sys_clk_freq_hz`: System clock frequency
- `pix_clk_freq_hz`: Pixel clock frequency

**Description**

A single branch back-end of the CCS PLL tree.

#### <a id="c-struct-ccs_pll"></a>`struct ccs_pll`

Full CCS PLL configuration

**Definition**

```c
struct ccs_pll {
    u8 bus_type;
    u8 op_lanes;
    u8 vt_lanes;
    struct {
        u8 lanes;
    } csi2;
    u8 binning_horizontal;
    u8 binning_vertical;
    u8 scale_m;
    u8 scale_n;
    u8 bits_per_pixel;
    u8 op_bits_per_lane;
    u16 flags;
    u32 link_freq;
    u32 ext_clk_freq_hz;
    struct ccs_pll_branch_fr vt_fr;
    struct ccs_pll_branch_bk vt_bk;
    struct ccs_pll_branch_fr op_fr;
    struct ccs_pll_branch_bk op_bk;
    u32 pixel_rate_csi;
    u32 pixel_rate_pixel_array;
};
```

**Members**

- `bus_type`: Type of the data bus, CCS_PLL_BUS_TYPE_* (input)
- `op_lanes`: Number of operational lanes (input)
- `vt_lanes`: Number of video timing lanes (input)
- `csi2`: CSI-2 related parameters
- `csi2.lanes`: The number of the CSI-2 data lanes (input)
- `binning_horizontal`: Horizontal binning factor (input)
- `binning_vertical`: Vertical binning factor (input)
- `scale_m`: Downscaling factor, M component, \[16, max\] (input)
- `scale_n`: Downscaling factor, N component, typically 16 (input)
- `bits_per_pixel`: Bits per pixel on the output data bus (input)
- `op_bits_per_lane`: Number of bits per OP lane (input)
- `flags`: CCS_PLL_FLAG_* (input)
- `link_freq`: Chosen link frequency (input)
- `ext_clk_freq_hz`: External clock frequency, i.e. the sensor's input clock
  (input)
- `vt_fr`: Video timing front-end configuration (output)
- `vt_bk`: Video timing back-end configuration (output)
- `op_fr`: Operational timing front-end configuration (output)
- `op_bk`: Operational timing back-end configuration (output)
- `pixel_rate_csi`: Pixel rate on the output data bus (output)
- `pixel_rate_pixel_array`: Nominal pixel rate in the sensor's pixel array
  (output)

**Description**

All information required to calculate CCS PLL configuration.

#### <a id="c-struct-ccs_pll_branch_limits_fr"></a>`struct ccs_pll_branch_limits_fr`

CCS PLL front-end limits

**Definition**

```c
struct ccs_pll_branch_limits_fr {
    u16 min_pre_pll_clk_div;
    u16 max_pre_pll_clk_div;
    u32 min_pll_ip_clk_freq_hz;
    u32 max_pll_ip_clk_freq_hz;
    u16 min_pll_multiplier;
    u16 max_pll_multiplier;
    u32 min_pll_op_clk_freq_hz;
    u32 max_pll_op_clk_freq_hz;
};
```

**Members**

- `min_pre_pll_clk_div`: Minimum pre-PLL clock divider
- `max_pre_pll_clk_div`: Maximum pre-PLL clock divider
- `min_pll_ip_clk_freq_hz`: Minimum PLL input clock frequency
- `max_pll_ip_clk_freq_hz`: Maximum PLL input clock frequency
- `min_pll_multiplier`: Minimum PLL multiplier
- `max_pll_multiplier`: Maximum PLL multiplier
- `min_pll_op_clk_freq_hz`: Minimum PLL output clock frequency
- `max_pll_op_clk_freq_hz`: Maximum PLL output clock frequency

#### <a id="c-struct-ccs_pll_branch_limits_bk"></a>`struct ccs_pll_branch_limits_bk`

CCS PLL back-end limits

**Definition**

```c
struct ccs_pll_branch_limits_bk {
    u16 min_sys_clk_div;
    u16 max_sys_clk_div;
    u32 min_sys_clk_freq_hz;
    u32 max_sys_clk_freq_hz;
    u16 min_pix_clk_div;
    u16 max_pix_clk_div;
    u32 min_pix_clk_freq_hz;
    u32 max_pix_clk_freq_hz;
};
```

**Members**

- `min_sys_clk_div`: Minimum system clock divider
- `max_sys_clk_div`: Maximum system clock divider
- `min_sys_clk_freq_hz`: Minimum system clock frequency
- `max_sys_clk_freq_hz`: Maximum system clock frequency
- `min_pix_clk_div`: Minimum pixel clock divider
- `max_pix_clk_div`: Maximum pixel clock divider
- `min_pix_clk_freq_hz`: Minimum pixel clock frequency
- `max_pix_clk_freq_hz`: Maximum pixel clock frequency

#### <a id="c-struct-ccs_pll_limits"></a>`struct ccs_pll_limits`

CCS PLL limits

**Definition**

```c
struct ccs_pll_limits {
    u32 min_ext_clk_freq_hz;
    u32 max_ext_clk_freq_hz;
    struct ccs_pll_branch_limits_fr vt_fr;
    struct ccs_pll_branch_limits_bk vt_bk;
    struct ccs_pll_branch_limits_fr op_fr;
    struct ccs_pll_branch_limits_bk op_bk;
    u32 min_line_length_pck_bin;
    u32 min_line_length_pck;
};
```

**Members**

- `min_ext_clk_freq_hz`: Minimum external clock frequency
- `max_ext_clk_freq_hz`: Maximum external clock frequency
- `vt_fr`: Video timing front-end limits
- `vt_bk`: Video timing back-end limits
- `op_fr`: Operational timing front-end limits
- `op_bk`: Operational timing back-end limits
- `min_line_length_pck_bin`: Minimum line length in pixels, with binning
- `min_line_length_pck`: Minimum line length in pixels without binning

#### <a id="c-ccs_pll_calculate"></a>`ccs_pll_calculate()`

```c
int ccs_pll_calculate(struct device *dev, const struct ccs_pll_limits *limits, struct ccs_pll *pll)
```

Calculate CCS PLL configuration based on input parameters

**Parameters**

- `struct device *dev`: Device pointer, used for printing messages
- `const struct ccs_pll_limits *limits`: Limits specific to the sensor
- `struct ccs_pll *pll`: Given PLL configuration

**Description**

Calculate the CCS PLL configuration based on the limits as well as given
device specific, system specific or user configured input data.


**Copyright** © 2020 Intel Corporation

---

# MIPI CCS register definitions

_Peios Kernel / Hardware and drivers / Driver development / media: drivers: ccs_

> Register, field and enumeration definitions consumed by the CCS register generator.

Register, field and enumeration definitions consumed by the CCS register generator.


```text
# SPDX-License-Identifier: GPL-2.0-only OR BSD-3-Clause
# Copyright (C) 2019--2020 Intel Corporation

# register				rflags
# - f	field	LSB	MSB		rflags
# - e	enum	value			# after a field
# - e	enum	value	[LSB	MSB]
# - b	bool	bit
# - l	arg	name	min	max	elsize	[discontig...]
#
# rflags
#	8, 16, 32	register bits (default is 8)
#	v1.1		defined in version 1.1
#	f		formula
#	float_ireal	iReal or IEEE 754; 32 bits
#	ireal		unsigned iReal

# general status registers
module_model_id				0x0000	16
module_revision_number_major		0x0002	8
frame_count				0x0005	8
pixel_order				0x0006	8
- e	GRBG				0
- e	RGGB				1
- e	BGGR				2
- e	GBRG				3
MIPI_CCS_version			0x0007	8
- e	v1_0				0x10
- e	v1_1				0x11
- f	major				4	7
- f	minor				0	3
data_pedestal				0x0008	16
module_manufacturer_id			0x000e	16
module_revision_number_minor		0x0010	8
module_date_year			0x0012	8
module_date_month			0x0013	8
module_date_day				0x0014	8
module_date_phase			0x0015	8
- f					0	2
- e	ts				0
- e	es				1
- e	cs				2
- e	mp				3
sensor_model_id				0x0016	16
sensor_revision_number			0x0018	8
sensor_firmware_version			0x001a	8
serial_number				0x001c	32
sensor_manufacturer_id			0x0020	16
sensor_revision_number_16		0x0022	16

# frame format description registers
frame_format_model_type			0x0040	8
- e	2-byte				1
- e	4-byte				2
frame_format_model_subtype		0x0041	8
- f	rows				0	3
- f	columns				4	7
frame_format_descriptor(n)		0x0042	16	f
- l	n				0	14	2
- f	pixels				0	11
- f	pcode				12	15
- e	embedded			1
- e	dummy_pixel			2
- e	black_pixel			3
- e	dark_pixel			4
- e	visible_pixel			5
- e	manuf_specific_0		8
- e	manuf_specific_1		9
- e	manuf_specific_2		10
- e	manuf_specific_3		11
- e	manuf_specific_4		12
- e	manuf_specific_5		13
- e	manuf_specific_6		14
frame_format_descriptor_4(n)		0x0060	32	f
- l	n				0	7	4
- f	pixels				0	15
- f	pcode				28	31
- e	embedded			1
- e	dummy_pixel			2
- e	black_pixel			3
- e	dark_pixel			4
- e	visible_pixel			5
- e	manuf_specific_0		8
- e	manuf_specific_1		9
- e	manuf_specific_2		10
- e	manuf_specific_3		11
- e	manuf_specific_4		12
- e	manuf_specific_5		13
- e	manuf_specific_6		14

# analog gain description registers
analog_gain_capability			0x0080	16
- e	global				0
- e	alternate_global		2
analog_gain_code_min			0x0084	16
analog_gain_code_max			0x0086	16
analog_gain_code_step			0x0088	16
analog_gain_type			0x008a	16
analog_gain_m0				0x008c	16
analog_gain_c0				0x008e	16
analog_gain_m1				0x0090	16
analog_gain_c1				0x0092	16
analog_linear_gain_min			0x0094	16	v1.1
analog_linear_gain_max			0x0096	16	v1.1
analog_linear_gain_step_size		0x0098	16	v1.1
analog_exponential_gain_min		0x009a	16	v1.1
analog_exponential_gain_max		0x009c	16	v1.1
analog_exponential_gain_step_size	0x009e	16	v1.1

# data format description registers
data_format_model_type			0x00c0	8
- e	normal				1
- e	extended			2
data_format_model_subtype		0x00c1	8
- f	rows				0	3
- f	columns				4	7
data_format_descriptor(n)		0x00c2	16	f
- l	n				0	15	2
- f	compressed			0	7
- f	uncompressed			8	15

# general set-up registers
mode_select				0x0100	8
- e	software_standby		0
- e	streaming			1
image_orientation			0x0101	8
- b	horizontal_mirror		0
- b	vertical_flip			1
software_reset				0x0103	8
- e	off				0
- e	on				1
grouped_parameter_hold			0x0104	8
mask_corrupted_frames			0x0105	8
- e	allow				0
- e	mask				1
fast_standby_ctrl			0x0106	8
- e	complete_frames			0
- e	frame_truncation		1
CCI_address_ctrl			0x0107	8
2nd_CCI_if_ctrl				0x0108	8
- b	enable				0
- b	ack				1
2nd_CCI_address_ctrl			0x0109	8
CSI_channel_identifier			0x0110	8
CSI_signaling_mode			0x0111	8
- e	csi_2_dphy			2
- e	csi_2_cphy			3
CSI_data_format				0x0112	16
CSI_lane_mode				0x0114	8
DPCM_Frame_DT				0x011d	8
Bottom_embedded_data_DT			0x011e	8
Bottom_embedded_data_VC			0x011f	8

gain_mode				0x0120	8
- e	global				0
- e	alternate			1
ADC_bit_depth				0x0121	8
emb_data_ctrl				0x0122	v1.1
- b	raw8_packing_for_raw16		0
- b	raw10_packing_for_raw20		1
- b 	raw12_packing_for_raw24		2

GPIO_TRIG_mode				0x0130	8
extclk_frequency_mhz			0x0136	16	ireal
temp_sensor_ctrl			0x0138	8
- b	enable				0
temp_sensor_mode			0x0139	8
temp_sensor_output			0x013a	8

# integration time registers
fine_integration_time			0x0200	16
coarse_integration_time			0x0202	16

# analog gain registers
analog_gain_code_global			0x0204	16
analog_linear_gain_global		0x0206	16	v1.1
analog_exponential_gain_global		0x0208	16	v1.1

# digital gain registers
digital_gain_global			0x020e	16

# hdr control registers
Short_analog_gain_global		0x0216	16
Short_digital_gain_global		0x0218	16

HDR_mode				0x0220	8
- b	enabled				0
- b	separate_analog_gain		1
- b	upscaling			2
- b	reset_sync			3
- b	timing_mode			4
- b	exposure_ctrl_direct		5
- b	separate_digital_gain		6
HDR_resolution_reduction		0x0221	8
- f	row				0	3
- f	column				4	7
Exposure_ratio				0x0222	8
HDR_internal_bit_depth			0x0223	8
Direct_short_integration_time		0x0224	16
Short_analog_linear_gain_global		0x0226	16	v1.1
Short_analog_exponential_gain_global	0x0228	16	v1.1

# clock set-up registers
vt_pix_clk_div				0x0300	16
vt_sys_clk_div				0x0302	16
pre_pll_clk_div				0x0304	16
#vt_pre_pll_clk_div			0x0304	16
pll_multiplier				0x0306	16
#vt_pll_multiplier			0x0306	16
op_pix_clk_div				0x0308	16
op_sys_clk_div				0x030a	16
op_pre_pll_clk_div			0x030c	16
op_pll_multiplier			0x030e	16
pll_mode				0x0310	8
- f					0	0
- e	single				0
- e	dual				1
op_pix_clk_div_rev			0x0312	16	v1.1
op_sys_clk_div_rev			0x0314	16	v1.1

# frame timing registers
frame_length_lines			0x0340	16
line_length_pck				0x0342	16

# image size registers
x_addr_start				0x0344	16
y_addr_start				0x0346	16
x_addr_end				0x0348	16
y_addr_end				0x034a	16
x_output_size				0x034c	16
y_output_size				0x034e	16

# timing mode registers
Frame_length_ctrl			0x0350	8
- b	automatic			0
Timing_mode_ctrl			0x0352	8
- b	manual_readout			0
- b	delayed_exposure		1
Start_readout_rs			0x0353	8
- b	manual_readout_start		0
Frame_margin				0x0354	16

# sub-sampling registers
x_even_inc				0x0380	16
x_odd_inc				0x0382	16
y_even_inc				0x0384	16
y_odd_inc				0x0386	16

# monochrome readout registers
monochrome_en				0x0390		v1.1
- e	enabled				0

# image scaling registers
Scaling_mode				0x0400	16
- e	no_scaling			0
- e	horizontal			1
scale_m					0x0404	16
scale_n					0x0406	16
digital_crop_x_offset			0x0408	16
digital_crop_y_offset			0x040a	16
digital_crop_image_width		0x040c	16
digital_crop_image_height		0x040e	16

# image compression registers
compression_mode			0x0500	16
- e	none				0
- e	dpcm_pcm_simple			1

# test pattern registers
test_pattern_mode			0x0600	16
- e	none				0
- e	solid_color			1
- e	color_bars			2
- e	fade_to_grey			3
- e	pn9				4
- e	color_tile			5
test_data_red				0x0602	16
test_data_greenR			0x0604	16
test_data_blue				0x0606	16
test_data_greenB			0x0608	16
value_step_size_smooth			0x060a	8
value_step_size_quantised		0x060b	8

# phy configuration registers
tclk_post				0x0800	8
ths_prepare				0x0801	8
ths_zero_min				0x0802	8
ths_trail				0x0803	8
tclk_trail_min				0x0804	8
tclk_prepare				0x0805	8
tclk_zero				0x0806	8
tlpx					0x0807	8
phy_ctrl				0x0808	8
- e	auto				0
- e	UI				1
- e	manual				2
tclk_post_ex				0x080a	16
ths_prepare_ex				0x080c	16
ths_zero_min_ex				0x080e	16
ths_trail_ex				0x0810	16
tclk_trail_min_ex			0x0812	16
tclk_prepare_ex				0x0814	16
tclk_zero_ex				0x0816	16
tlpx_ex					0x0818	16

# link rate register
requested_link_rate			0x0820	32	u16.16

# equalization control registers
DPHY_equalization_mode			0x0824	8	v1.1
- b eq2					0
PHY_equalization_ctrl			0x0825	8	v1.1
- b enable				0

# d-phy preamble control registers
DPHY_preamble_ctrl			0x0826	8	v1.1
- b	enable				0
DPHY_preamble_length			0x0826	8	v1.1

# d-phy spread spectrum control registers
PHY_SSC_ctrl				0x0828	8	v1.1
- b	enable				0

# manual lp control register
manual_LP_ctrl				0x0829	8	v1.1
- b	enable				0

# additional phy configuration registers
twakeup					0x082a		v1.1
tinit					0x082b		v1.1
ths_exit				0x082c		v1.1
ths_exit_ex				0x082e	16	v1.1

# phy calibration configuration registers
PHY_periodic_calibration_ctrl		0x0830	8
- b	frame_blanking			0
PHY_periodic_calibration_interval	0x0831	8
PHY_init_calibration_ctrl		0x0832	8
- b	stream_start			0
DPHY_calibration_mode			0x0833	8	v1.1
- b	also_alternate			0
CPHY_calibration_mode			0x0834	8	v1.1
- e	format_1			0
- e	format_2			1
- e	format_3			2
t3_calpreamble_length			0x0835	8	v1.1
t3_calpreamble_length_per		0x0836	8	v1.1
t3_calaltseq_length			0x0837	8	v1.1
t3_calaltseq_length_per			0x0838	8	v1.1
FM2_init_seed				0x083a	16	v1.1
t3_caludefseq_length			0x083c	16	v1.1
t3_caludefseq_length_per		0x083e	16	v1.1

# c-phy manual control registers
TGR_Preamble_Length			0x0841	8
- b	preamable_prog_seq		7
- f	begin_preamble_length		0	5
TGR_Post_Length				0x0842	8
- f	post_length			0	4
TGR_Preamble_Prog_Sequence(n2)		0x0843
- l	n2				0	6	1
- f	symbol_n_1			3	5
- f	symbol_n			0	2
t3_prepare				0x084e	16
t3_lpx					0x0850	16

# alps control register
ALPS_ctrl				0x085a	8
- b	lvlp_dphy			0
- b	lvlp_cphy			1
- b	alp_cphy			2

# lrte control registers
TX_REG_CSI_EPD_EN_SSP_cphy		0x0860	16
TX_REG_CSI_EPD_OP_SLP_cphy		0x0862	16
TX_REG_CSI_EPD_EN_SSP_dphy		0x0864	16
TX_REG_CSI_EPD_OP_SLP_dphy		0x0866	16
TX_REG_CSI_EPD_MISC_OPTION_cphy		0x0868		v1.1
TX_REG_CSI_EPD_MISC_OPTION_dphy		0x0869		v1.1

# scrambling control registers
Scrambling_ctrl				0x0870
- b	enabled				0
- f					2	3
- e 	1_seed_cphy			0
- e	4_seed_cphy			3
lane_seed_value(seed, lane)		0x0872	16
- l	seed				0	3	0x10
- l	lane				0	7	0x2

# usl control registers
TX_USL_REV_ENTRY			0x08c0	16	v1.1
TX_USL_REV_Clock_Counter		0x08c2	16	v1.1
TX_USL_REV_LP_Counter			0x08c4	16	v1.1
TX_USL_REV_Frame_Counter		0x08c6	16	v1.1
TX_USL_REV_Chronological_Timer		0x08c8	16	v1.1
TX_USL_FWD_ENTRY			0x08ca	16	v1.1
TX_USL_GPIO				0x08cc	16	v1.1
TX_USL_Operation			0x08ce	16	v1.1
- b	reset				0
TX_USL_ALP_ctrl				0x08d0	16	v1.1
- b	clock_pause			0
TX_USL_APP_BTA_ACK_TIMEOUT		0x08d2	16	v1.1
TX_USL_SNS_BTA_ACK_TIMEOUT		0x08d2	16	v1.1
USL_Clock_Mode_d_ctrl			0x08d2		v1.1
- b	cont_clock_standby		0
- b	cont_clock_vblank		1
- b	cont_clock_hblank		2

# binning configuration registers
binning_mode				0x0900	8
binning_type				0x0901	8
binning_weighting			0x0902	8

# data transfer interface registers
data_transfer_if_1_ctrl			0x0a00	8
- b	enable				0
- b	write				1
- b	clear_error			2
data_transfer_if_1_status		0x0a01	8
- b	read_if_ready			0
- b	write_if_ready			1
- b	data_corrupted			2
- b	improper_if_usage		3
data_transfer_if_1_page_select		0x0a02	8
data_transfer_if_1_data(p)		0x0a04	8	f
- l	p				0	63	1

# image processing and sensor correction configuration registers
shading_correction_en			0x0b00	8
- b	enable				0
luminance_correction_level		0x0b01	8
green_imbalance_filter_en		0x0b02	8
- b	enable				0
mapped_defect_correct_en		0x0b05	8
- b	enable				0
single_defect_correct_en		0x0b06	8
- b	enable				0
dynamic_couplet_correct_en		0x0b08	8
- b	enable				0
combined_defect_correct_en		0x0b0a	8
- b	enable				0
module_specific_correction_en		0x0b0c	8
- b	enable				0
dynamic_triplet_defect_correct_en	0x0b13	8
- b	enable				0
NF_ctrl					0x0b15	8
- b	luma				0
- b	chroma				1
- b	combined			2

# optical black pixel readout registers
OB_readout_control			0x0b30	8
- b	enable				0
- b	interleaving			1
OB_virtual_channel			0x0b31	8
OB_DT					0x0b32	8
OB_data_format				0x0b33	8

# color temperature feedback registers
color_temperature			0x0b8c	16
absolute_gain_greenr			0x0b8e	16
absolute_gain_red			0x0b90	16
absolute_gain_blue			0x0b92	16
absolute_gain_greenb			0x0b94	16

# cfa conversion registers
CFA_conversion_ctrl			0x0ba0		v1.1
- b	bayer_conversion_enable		0

# flash strobe and sa strobe control registers
flash_strobe_adjustment			0x0c12	8
flash_strobe_start_point		0x0c14	16
tflash_strobe_delay_rs_ctrl		0x0c16	16
tflash_strobe_width_high_rs_ctrl	0x0c18	16
flash_mode_rs				0x0c1a	8
- b	continuous			0
- b	truncate			1
- b	async				3
flash_trigger_rs			0x0c1b	8
flash_status				0x0c1c	8
- b	retimed				0
sa_strobe_mode				0x0c1d	8
- b	continuous			0
- b	truncate			1
- b	async				3
- b	adjust_edge			4
sa_strobe_start_point			0x0c1e	16
tsa_strobe_delay_ctrl			0x0c20	16
tsa_strobe_width_ctrl			0x0c22	16
sa_strobe_trigger			0x0c24	8
sa_strobe_status			0x0c25	8
- b	retimed				0
tSA_strobe_re_delay_ctrl		0x0c30	16
tSA_strobe_fe_delay_ctrl		0x0c32	16

# pdaf control registers
PDAF_ctrl				0x0d00	16
- b 	enable				0
- b	processed			1
- b	interleaved			2
- b	visible_pdaf_correction		3
PDAF_VC					0x0d02	8
PDAF_DT					0x0d03	8
pd_x_addr_start				0x0d04	16
pd_y_addr_start				0x0d06	16
pd_x_addr_end				0x0d08	16
pd_y_addr_end				0x0d0a	16

# bracketing interface configuration registers
bracketing_LUT_ctrl			0x0e00	8
bracketing_LUT_mode			0x0e01	8
- b	continue_streaming		0
- b	loop_mode			1
bracketing_LUT_entry_ctrl		0x0e02	8
bracketing_LUT_frame(n)			0x0e10	v1.1	f
- l	n				0	0xef	1

# integration time and gain parameter limit registers
integration_time_capability		0x1000	16
- b	fine				0
coarse_integration_time_min		0x1004	16
coarse_integration_time_max_margin	0x1006	16
fine_integration_time_min		0x1008	16
fine_integration_time_max_margin	0x100a	16

# digital gain parameter limit registers
digital_gain_capability			0x1081
- e	none				0
- e	global				2
digital_gain_min			0x1084	16
digital_gain_max			0x1086	16
digital_gain_step_size			0x1088	16

# data pedestal capability registers
Pedestal_capability			0x10e0	8	v1.1

# adc capability registers
ADC_capability				0x10f0	8
- b	bit_depth_ctrl			0
ADC_bit_depth_capability		0x10f4	32	v1.1

# video timing parameter limit registers
min_ext_clk_freq_mhz			0x1100	32	float_ireal
max_ext_clk_freq_mhz			0x1104	32	float_ireal
min_pre_pll_clk_div			0x1108	16
# min_vt_pre_pll_clk_div			0x1108	16
max_pre_pll_clk_div			0x110a	16
# max_vt_pre_pll_clk_div			0x110a	16
min_pll_ip_clk_freq_mhz			0x110c	32	float_ireal
# min_vt_pll_ip_clk_freq_mhz		0x110c	32	float_ireal
max_pll_ip_clk_freq_mhz			0x1110	32	float_ireal
# max_vt_pll_ip_clk_freq_mhz		0x1110	32	float_ireal
min_pll_multiplier			0x1114	16
# min_vt_pll_multiplier			0x1114	16
max_pll_multiplier			0x1116	16
# max_vt_pll_multiplier			0x1116	16
min_pll_op_clk_freq_mhz			0x1118	32	float_ireal
max_pll_op_clk_freq_mhz			0x111c	32	float_ireal

# video timing set-up capability registers
min_vt_sys_clk_div			0x1120	16
max_vt_sys_clk_div			0x1122	16
min_vt_sys_clk_freq_mhz			0x1124	32	float_ireal
max_vt_sys_clk_freq_mhz			0x1128	32	float_ireal
min_vt_pix_clk_freq_mhz			0x112c	32	float_ireal
max_vt_pix_clk_freq_mhz			0x1130	32	float_ireal
min_vt_pix_clk_div			0x1134	16
max_vt_pix_clk_div			0x1136	16
clock_calculation			0x1138
- b	lane_speed			0
- b	link_decoupled			1
- b	dual_pll_op_sys_ddr		2
- b	dual_pll_op_pix_ddr		3
num_of_vt_lanes				0x1139
num_of_op_lanes				0x113a
op_bits_per_lane			0x113b	8	v1.1

# frame timing parameter limits
min_frame_length_lines			0x1140	16
max_frame_length_lines			0x1142	16
min_line_length_pck			0x1144	16
max_line_length_pck			0x1146	16
min_line_blanking_pck			0x1148	16
min_frame_blanking_lines		0x114a	16
min_line_length_pck_step_size		0x114c
timing_mode_capability			0x114d
- b	auto_frame_length		0
- b	rolling_shutter_manual_readout	2
- b	delayed_exposure_start		3
- b	manual_exposure_embedded_data	4
frame_margin_max_value			0x114e	16
frame_margin_min_value			0x1150
gain_delay_type				0x1151
- e	fixed				0
- e	variable			1

# output clock set-up capability registers
min_op_sys_clk_div			0x1160	16
max_op_sys_clk_div			0x1162	16
min_op_sys_clk_freq_mhz			0x1164	32	float_ireal
max_op_sys_clk_freq_mhz			0x1168	32	float_ireal
min_op_pix_clk_div			0x116c	16
max_op_pix_clk_div			0x116e	16
min_op_pix_clk_freq_mhz			0x1170	32	float_ireal
max_op_pix_clk_freq_mhz			0x1174	32	float_ireal

# image size parameter limit registers
x_addr_min				0x1180	16
y_addr_min				0x1182	16
x_addr_max				0x1184	16
y_addr_max				0x1186	16
min_x_output_size			0x1188	16
min_y_output_size			0x118a	16
max_x_output_size			0x118c	16
max_y_output_size			0x118e	16

x_addr_start_div_constant		0x1190		v1.1
y_addr_start_div_constant		0x1191		v1.1
x_addr_end_div_constant			0x1192		v1.1
y_addr_end_div_constant			0x1193		v1.1
x_size_div				0x1194		v1.1
y_size_div				0x1195		v1.1
x_output_div				0x1196		v1.1
y_output_div				0x1197		v1.1
non_flexible_resolution_support		0x1198		v1.1
- b	new_pix_addr			0
- b	new_output_res			1
- b	output_crop_no_pad		2
- b	output_size_lane_dep		3

min_op_pre_pll_clk_div			0x11a0	16
max_op_pre_pll_clk_div			0x11a2	16
min_op_pll_ip_clk_freq_mhz		0x11a4	32	float_ireal
max_op_pll_ip_clk_freq_mhz		0x11a8	32	float_ireal
min_op_pll_multiplier			0x11ac	16
max_op_pll_multiplier			0x11ae	16
min_op_pll_op_clk_freq_mhz		0x11b0	32	float_ireal
max_op_pll_op_clk_freq_mhz		0x11b4	32	float_ireal
clock_tree_pll_capability		0x11b8	8
- b	dual_pll			0
- b	single_pll			1
- b	ext_divider			2
- b	flexible_op_pix_clk_div		3
clock_capa_type_capability		0x11b9	v1.1
- b	ireal				0

# sub-sampling parameters limit registers
min_even_inc				0x11c0	16
min_odd_inc				0x11c2	16
max_even_inc				0x11c4	16
max_odd_inc				0x11c6	16
aux_subsamp_capability			0x11c8		v1.1
- b	factor_power_of_2		1
aux_subsamp_mono_capability		0x11c9		v1.1
- b	factor_power_of_2		1
monochrome_capability			0x11ca		v1.1
- e	inc_odd				0
- e	inc_even			1
pixel_readout_capability		0x11cb		v1.1
- e	bayer				0
- e	monochrome			1
- e	bayer_and_mono			2
min_even_inc_mono			0x11cc	16	v1.1
max_even_inc_mono			0x11ce	16	v1.1
min_odd_inc_mono			0x11d0	16	v1.1
max_odd_inc_mono			0x11d2	16	v1.1
min_even_inc_bc2			0x11d4	16	v1.1
max_even_inc_bc2			0x11d6	16	v1.1
min_odd_inc_bc2				0x11d8	16	v1.1
max_odd_inc_bc2				0x11da	16	v1.1
min_even_inc_mono_bc2			0x11dc	16	v1.1
max_even_inc_mono_bc2			0x11de	16	v1.1
min_odd_inc_mono_bc2			0x11f0	16	v1.1
max_odd_inc_mono_bc2			0x11f2	16	v1.1

# image scaling limit parameters
scaling_capability			0x1200	16
- e	none				0
- e	horizontal			1
- e	reserved			2
scaler_m_min				0x1204	16
scaler_m_max				0x1206	16
scaler_n_min				0x1208	16
scaler_n_max				0x120a	16
digital_crop_capability			0x120e
- e	none				0
- e	input_crop			1

# hdr limit registers
hdr_capability_1			0x1210
- b	2x2_binning			0
- b	combined_analog_gain		1
- b	separate_analog_gain		2
- b	upscaling			3
- b	reset_sync			4
- b	direct_short_exp_timing		5
- b	direct_short_exp_synthesis	6
min_hdr_bit_depth			0x1211
hdr_resolution_sub_types		0x1212
hdr_resolution_sub_type(n)		0x1213
- l	n				0	1	1
- f	row				0	3
- f	column				4	7
hdr_capability_2			0x121b
- b	combined_digital_gain		0
- b	separate_digital_gain		1
- b	timing_mode			3
- b	synthesis_mode			4
max_hdr_bit_depth			0x121c

# usl capability register
usl_support_capability			0x1230		v1.1
- b	clock_tree			0
- b	rev_clock_tree			1
- b	rev_clock_calc			2
usl_clock_mode_d_capability		0x1231		v1.1
- b	cont_clock_standby		0
- b	cont_clock_vblank		1
- b	cont_clock_hblank		2
- b	noncont_clock_standby		3
- b	noncont_clock_vblank		4
- b	noncont_clock_hblank		5
min_op_sys_clk_div_rev			0x1234		v1.1
max_op_sys_clk_div_rev			0x1236		v1.1
min_op_pix_clk_div_rev			0x1238		v1.1
max_op_pix_clk_div_rev			0x123a		v1.1
min_op_sys_clk_freq_rev_mhz		0x123c	32	v1.1	float_ireal
max_op_sys_clk_freq_rev_mhz		0x1240	32	v1.1	float_ireal
min_op_pix_clk_freq_rev_mhz		0x1244	32	v1.1	float_ireal
max_op_pix_clk_freq_rev_mhz		0x1248	32	v1.1	float_ireal
max_bitrate_rev_d_mode_mbps		0x124c	32	v1.1	ireal
max_symrate_rev_c_mode_msps		0x1250	32	v1.1	ireal

# image compression capability registers
compression_capability			0x1300
- b	dpcm_pcm_simple			0

# test mode capability registers
test_mode_capability			0x1310	16
- b	solid_color			0
- b	color_bars			1
- b	fade_to_grey			2
- b	pn9				3
- b	color_tile			5
pn9_data_format1			0x1312
pn9_data_format2			0x1313
pn9_data_format3			0x1314
pn9_data_format4			0x1315
pn9_misc_capability			0x1316
- f	num_pixels			0	2
- b	compression			3
test_pattern_capability			0x1317	v1.1
- b	no_repeat			1
pattern_size_div_m1			0x1318	v1.1

# fifo capability registers
fifo_support_capability			0x1502
- e	none				0
- e	derating			1
- e	derating_overrating		2

# csi-2 capability registers
phy_ctrl_capability			0x1600
- b	auto_phy_ctl			0
- b	ui_phy_ctl			1
- b	dphy_time_ui_reg_1_ctl		2
- b	dphy_time_ui_reg_2_ctl		3
- b	dphy_time_ctl			4
- b	dphy_ext_time_ui_reg_1_ctl	5
- b	dphy_ext_time_ui_reg_2_ctl	6
- b	dphy_ext_time_ctl		7
csi_dphy_lane_mode_capability		0x1601
- b	1_lane				0
- b	2_lane				1
- b	3_lane				2
- b	4_lane				3
- b	5_lane				4
- b	6_lane				5
- b	7_lane				6
- b	8_lane				7
csi_signaling_mode_capability		0x1602
- b	csi_dphy			2
- b	csi_cphy			3
fast_standby_capability			0x1603
- e	no_frame_truncation		0
- e	frame_truncation		1
csi_address_control_capability		0x1604
- b	cci_addr_change			0
- b	2nd_cci_addr			1
- b	sw_changeable_2nd_cci_addr	2
data_type_capability			0x1605
- b	dpcm_programmable		0
- b	bottom_embedded_dt_programmable	1
- b	bottom_embedded_vc_programmable	2
- b	ext_vc_range			3
csi_cphy_lane_mode_capability		0x1606
- b	1_lane				0
- b	2_lane				1
- b	3_lane				2
- b	4_lane				3
- b	5_lane				4
- b	6_lane				5
- b	7_lane				6
- b	8_lane				7
emb_data_capability			0x1607	v1.1
- b	two_bytes_per_raw16		0
- b	two_bytes_per_raw20		1
- b	two_bytes_per_raw24		2
- b	no_one_byte_per_raw16		3
- b	no_one_byte_per_raw20		4
- b	no_one_byte_per_raw24		5
max_per_lane_bitrate_lane_d_mode_mbps(n)	0x1608	32	ireal
- l	n				0	7	4	4,0x32
temp_sensor_capability			0x1618
- b	supported			0
- b	CCS_format			1
- b	reset_0x80			2
max_per_lane_bitrate_lane_c_mode_mbps(n)	0x161a	32	ireal
- l	n				0	7	4	4,0x30
dphy_equalization_capability		0x162b
- b	equalization_ctrl		0
- b	eq1				1
- b	eq2				2
cphy_equalization_capability		0x162c
- b	equalization_ctrl		0
dphy_preamble_capability		0x162d
- b	preamble_seq_ctrl		0
dphy_ssc_capability			0x162e
- b	supported			0
cphy_calibration_capability		0x162f
- b	manual				0
- b	manual_streaming		1
- b	format_1_ctrl			2
- b	format_2_ctrl			3
- b	format_3_ctrl			4
dphy_calibration_capability		0x1630
- b	manual				0
- b	manual_streaming		1
- b	alternate_seq			2
phy_ctrl_capability_2			0x1631
- b	tgr_length			0
- b	tgr_preamble_prog_seq		1
- b	extra_cphy_manual_timing	2
- b	clock_based_manual_cdphy	3
- b	clock_based_manual_dphy		4
- b	clock_based_manual_cphy		5
- b	manual_lp_dphy			6
- b	manual_lp_cphy			7
lrte_cphy_capability			0x1632
- b	pdq_short			0
- b	spacer_short			1
- b	pdq_long			2
- b	spacer_long			3
- b	spacer_no_pdq			4
lrte_dphy_capability			0x1633
- b	pdq_short_opt1			0
- b	spacer_short_opt1		1
- b	pdq_long_opt1			2
- b	spacer_long_opt1		3
- b	spacer_short_opt2		4
- b	spacer_long_opt2		5
- b	spacer_no_pdq_opt1		6
- b	spacer_variable_opt2		7
alps_capability_dphy			0x1634
- e	lvlp_not_supported		0	0x3
- e	lvlp_supported			1	0x3
- e 	controllable_lvlp		2	0x3
alps_capability_cphy			0x1635
- e	lvlp_not_supported		0	0x3
- e	lvlp_supported			1	0x3
- e 	controllable_lvlp		2	0x3
- e	alp_not_supported		0xc	0xc
- e	alp_supported			0xd	0xc
- e 	controllable_alp		0xe	0xc
scrambling_capability			0x1636
- b	scrambling_supported		0
- f	max_seeds_per_lane_c		1	2
- e	1				0
- e	4				3
- f	num_seed_regs			3	5
- e	0				0
- e	1				1
- e	4				4
- b	num_seed_per_lane		6
dphy_manual_constant			0x1637
cphy_manual_constant			0x1638
CSI2_interface_capability_misc		0x1639	v1.1
- b	eotp_short_pkt_opt2		0
PHY_ctrl_capability_3			0x165c	v1.1
- b	dphy_timing_not_multiple	0
- b	dphy_min_timing_value_1		1
- b	twakeup_supported		2
- b	tinit_supported			3
- b	ths_exit_supported		4
- b	cphy_timing_not_multiple	5
- b	cphy_min_timing_value_1		6
dphy_sf					0x165d	v1.1
cphy_sf					0x165e	v1.1
- f	twakeup				0	3
- f	tinit				4	7
dphy_limits_1				0x165f	v1.1
- f	ths_prepare			0	3
- f	ths_zero			4	7
dphy_limits_2				0x1660	v1.1
- f	ths_trail			0	3
- f	tclk_trail_min			4	7
dphy_limits_3				0x1661	v1.1
- f	tclk_prepare			0	3
- f	tclk_zero			4	7
dphy_limits_4				0x1662	v1.1
- f	tclk_post			0	3
- f	tlpx				4	7
dphy_limits_5				0x1663	v1.1
- f	ths_exit			0	3
- f	twakeup				4	7
dphy_limits_6				0x1664	v1.1
- f	tinit				0	3
cphy_limits_1				0x1665	v1.1
- f	t3_prepare_max			0	3
- f	t3_lpx_max			4	7
cphy_limits_2				0x1666	v1.1
- f	ths_exit_max			0	3
- f	twakeup_max			4	7
cphy_limits_3				0x1667	v1.1
- f	tinit_max			0	3

# binning capability registers
min_frame_length_lines_bin		0x1700	16
max_frame_length_lines_bin		0x1702	16
min_line_length_pck_bin			0x1704	16
max_line_length_pck_bin			0x1706	16
min_line_blanking_pck_bin		0x1708	16
fine_integration_time_min_bin		0x170a	16
fine_integration_time_max_margin_bin	0x170c	16
binning_capability			0x1710
- e	unsupported			0
- e	binning_then_subsampling	1
- e	subsampling_then_binning	2
binning_weighting_capability		0x1711
- b	averaged			0
- b	summed				1
- b	bayer_corrected			2
- b	module_specific_weight		3
binning_sub_types			0x1712
binning_sub_type(n)			0x1713
- l	n				0	63	1
- f	row				0	3
- f	column				4	7
binning_weighting_mono_capability	0x1771	v1.1
- b	averaged			0
- b	summed				1
- b	bayer_corrected			2
- b	module_specific_weight		3
binning_sub_types_mono			0x1772	v1.1
binning_sub_type_mono(n)		0x1773	v1.1	f
- l	n				0	63	1

# data transfer interface capability registers
data_transfer_if_capability		0x1800
- b	supported			0
- b	polling				2

# sensor correction capability registers
shading_correction_capability		0x1900
- b	color_shading			0
- b	luminance_correction		1
green_imbalance_capability		0x1901
- b	supported			0
module_specific_correction_capability	0x1903
defect_correction_capability		0x1904	16
- b	mapped_defect			0
- b	dynamic_couplet			2
- b	dynamic_single			5
- b	combined_dynamic		8
defect_correction_capability_2		0x1906	16
- b	dynamic_triplet			3
nf_capability				0x1908
- b	luma				0
- b	chroma				1
- b	combined			2

# optical black readout capability registers
ob_readout_capability			0x1980
- b	controllable_readout		0
- b	visible_pixel_readout		1
- b	different_vc_readout		2
- b	different_dt_readout		3
- b	prog_data_format		4

# color feedback capability registers
color_feedback_capability		0x1987
- b	kelvin				0
- b	awb_gain			1

# cfa pattern capability registers
CFA_pattern_capability			0x1990	v1.1
- e	bayer				0
- e	monochrome			1
- e	4x4_quad_bayer			2
- e	vendor_specific			3
CFA_pattern_conversion_capability	0x1991	v1.1
- b	bayer				0

# timer capability registers
flash_mode_capability			0x1a02
- b	single_strobe			0
sa_strobe_mode_capability		0x1a03
- b	fixed_width			0
- b	edge_ctrl			1

# soft reset capability registers
reset_max_delay				0x1a10	v1.1
reset_min_time				0x1a11	v1.1

# pdaf capability registers
pdaf_capability_1			0x1b80
- b	supported			0
- b	processed_bottom_embedded	1
- b	processed_interleaved		2
- b	raw_bottom_embedded		3
- b	raw_interleaved			4
- b	visible_pdaf_correction		5
- b	vc_interleaving			6
- b	dt_interleaving			7
pdaf_capability_2			0x1b81
- b	ROI				0
- b	after_digital_crop		1
- b	ctrl_retimed			2

# bracketing interface capability registers
bracketing_lut_capability_1		0x1c00
- b	coarse_integration		0
- b	global_analog_gain		1
- b	flash				4
- b	global_digital_gain		5
- b	alternate_global_analog_gain	6
bracketing_lut_capability_2		0x1c01
- b	single_bracketing_mode		0
- b	looped_bracketing_mode		1
bracketing_lut_size			0x1c02

```

---

# MIPI CCS register generator

_Peios Kernel / Hardware and drivers / Driver development / media: drivers: ccs_

> Source of the generator that reads CCS register definitions and emits register and limit tables.

Source of the generator that reads CCS register definitions and emits register and limit tables.


```perl
#!/usr/bin/perl -w
# SPDX-License-Identifier: GPL-2.0-only OR BSD-3-Clause
# Copyright (C) 2019--2020 Intel Corporation

use Getopt::Long qw(:config no_ignore_case);
use File::Basename;

my $ccsregs = "ccs-regs.asc";
my $header;
my $regarray;
my $limitc;
my $limith;
my $kernel;
my $help;

GetOptions("ccsregs|c=s" => \$ccsregs,
	   "header|e=s" => \$header,
	   "regarray|r=s" => \$regarray,
	   "limitc|l=s" => \$limitc,
	   "limith|L=s" => \$limith,
	   "kernel|k" => \$kernel,
	   "help|h" => \$help) or die "can't parse options";

$help = 1 if ! defined $header || ! defined $limitc || ! defined $limith;

if (defined $help) {
	print <<EOH
$0 - Create CCS register definitions for C

usage: $0 -c ccs-regs.asc -e header -r regarray -l limit-c -L limit-header [-k]

	-c ccs register file
	-e header file name
	-r register description array file name
	-l limit and capability array file name
	-L limit and capability header file name
	-k generate files for kernel space consumption
EOH
	  ;
	exit 0;
}

my $lh_hdr = ! defined $kernel
	? '#include "ccs-os.h"' . "\n"
	: "#include <linux/bits.h>\n#include <linux/types.h>\n";
my $uint32_t = ! defined $kernel ? 'uint32_t' : 'u32';
my $uint16_t = ! defined $kernel ? 'uint16_t' : 'u16';

open(my $R, "< $ccsregs") or die "can't open $ccsregs";

open(my $H, "> $header") or die "can't open $header";
my $A;
if (defined $regarray) {
	open($A, "> $regarray") or die "can't open $regarray";
}
open(my $LC, "> $limitc") or die "can't open $limitc";
open(my $LH, "> $limith") or die "can't open $limith";

my %this;

sub is_limit_reg($) {
	my $addr = hex $_[0];

	return 0 if $addr < 0x40; # weed out status registers
	return 0 if $addr >= 0x100 && $addr < 0xfff; # weed out configuration registers

	return 1;
}

my $uc_header = basename uc $header;
$uc_header =~ s/[^A-Z0-9]/_/g;

my $copyright = "/* Copyright (C) 2019--2020 Intel Corporation */\n";
my $license = "SPDX-License-Identifier: GPL-2.0-only OR BSD-3-Clause";
my $note = "/*\n * Generated by $0;\n * do not modify.\n */\n";

for my $fh ($A, $LC) {
	print $fh "// $license\n$copyright$note\n" if defined $fh;
}

for my $fh ($H, $LH) {
	print $fh "/* $license */\n$copyright$note\n";
}

print $H <<EOF
#ifndef __${uc_header}__
#define __${uc_header}__

EOF
  ;

print $H <<EOF
#include <linux/bits.h>

#include <media/v4l2-cci.h>

EOF
	if defined $kernel;

print $H "#define CCS_FL_BASE		" .
    (defined $kernel ? "CCI_REG_PRIVATE_SHIFT" : 16) . "\n";

my $flag = -1;
my $all_flags;

sub bit_def($) {
	my $bit = shift @_;

	if (defined $kernel) {
		return "BIT$bit" if $bit =~ /^\(.*\)$/;
		return "BIT($bit)";
	}
	return "(1U << $bit)";
}

sub flag_str($$) {
	my ($flag, $check) = @_;

	$$flag++;

	my $flag_str = !$$flag ? "CCS_FL_BASE" : "(CCS_FL_BASE + $$flag)";

	$flag_str = bit_def($flag_str);

	$$check .= " | " if defined $$check;

	$$check .= $flag_str;

	return $flag_str;
}

if (! defined $kernel) {
	print $H "#define CCS_FL_16BIT		" . flag_str(\$flag, \$all_flags) . "\n";
	print $H "#define CCS_FL_32BIT		" . flag_str(\$flag, \$all_flags) . "\n";
}

print $H "#define CCS_FL_FLOAT_IREAL	" . flag_str(\$flag, \$all_flags) . "\n";
print $H "#define CCS_FL_IREAL		" . flag_str(\$flag, \$all_flags) . "\n";
print $H "#define CCS_BUILD_BUG \\
	BUILD_BUG_ON(~CCI_REG_PRIVATE_MASK & ($all_flags))\n"
    if defined $kernel;

print $H <<EOF

#define CCS_R_ADDR(r)		((r) & 0xffff)

EOF
    if ! defined $kernel;

print $A <<EOF
#include <stdint.h>
#include <stdio.h>
#include "ccs-extra.h"
#include "ccs-regs.h"

EOF
	if defined $A;

my $uc_limith = basename uc $limith;
$uc_limith =~ s/[^A-Z0-9]/_/g;

print $LH <<EOF
#ifndef __${uc_limith}__
#define __${uc_limith}__

$lh_hdr
struct ccs_limit {
	$uint32_t reg;
	$uint16_t size;
	$uint16_t flags;
	const char *name;
};

EOF
  ;
print $LH "#define CCS_L_FL_SAME_REG	" . bit_def(0) . "\n\n";

print $LH <<EOF
extern const struct ccs_limit ccs_limits[];

EOF
  ;

print $LC <<EOF
#include "ccs-limits.h"
#include "ccs-regs.h"

const struct ccs_limit ccs_limits[] = {
EOF
  ;

my $limitcount = 0;
my $argdescs;
my $reglist = "const struct ccs_reg_desc ccs_reg_desc[] = {\n";

sub name_split($$) {
	my ($name, $addr) = @_;
	my $args;

	$name =~ /([^\(]+?)(\(.*)/;
	($name, $args) = ($1, $2);
	$args = [split /,\s*/, $args];
	foreach my $t (@$args) {
		$t =~ s/[\(\)]//g;
		$t =~ s/\//\\\//g;
	}

	return ($name, $addr, $args);
}

sub tabconv($) {
	$_ = shift;

	my @l = split "\n", $_;

	map {
		s/ {8,8}/\t/g;
		s/\t\K +//;
	} @l;

	return (join "\n", @l) . "\n";
}

sub elem_bits(@) {
	my @flags = @_;

	return 16 if grep /^16$/, @flags;
	return 32 if grep /^32$/, @flags;
	return 8;
}

sub arr_size($) {
	my $this = $_[0];
	my $size = $this->{elsize};
	my $h = $this->{argparams};

	foreach my $arg (@{$this->{args}}) {
		my $apref = $h->{$arg};

		$size *= $apref->{max} - $apref->{min} + 1;
	}

	return $size;
}

sub print_args($$$) {
	my ($this, $postfix, $is_same_reg) = @_;
	my ($args, $argparams, $name) =
	  ($this->{args}, $this->{argparams}, $this->{name});
	my $varname = "ccs_reg_arg_" . (lc $name) . $postfix;
	my @mins;
	my @sorted_args = @{$this->{sorted_args}};
	my $lim_arg;
	my $size = arr_size($this);

	$argdescs .= "static const struct ccs_reg_arg " . $varname . "[] = {\n";

	foreach my $sorted_arg (@sorted_args) {
		push @mins, $argparams->{$sorted_arg}->{min};
	}

	foreach my $sorted_arg (@sorted_args) {
		my $h = $argparams->{$sorted_arg};

		$argdescs .= "\t{ \"$sorted_arg\", $h->{min}, $h->{max}, $h->{elsize} },\n";

		$lim_arg .= defined $lim_arg ? ", $h->{min}" : "$h->{min}";
	}

	$argdescs .= "};\n\n";

	$reglist .= "\t{ CCS_R_" . (uc $name) . "(" . (join ",", (@mins)) .
	  "), $size, sizeof($varname) / sizeof(*$varname)," .
	    " \"" . (lc $name) . "\", $varname },\n";

	print $LC tabconv sprintf "\t{ CCS_R_" . (uc $name) . "($lim_arg), " .
	  $size . ", " . ($is_same_reg ? "CCS_L_FL_SAME_REG" : "0") .
	    ", \"$name" . (defined $this->{discontig} ? " $lim_arg" : "") . "\" },\n"
	      if is_limit_reg $this->{base_addr};
}

my $hdr_data;

while (<$R>) {
	chop;
	s/^\s*//;
	next if /^[#;]/ || /^$/;
	if (s/^-\s*//) {
		if (s/^b\s*//) {
			my ($bit, $addr) = split /\t+/;
			$bit = uc $bit;
			$hdr_data .= sprintf "#define %-62s %s", "CCS_" . (uc ${this{name}}) ."_$bit", bit_def($addr) . "\n";
		} elsif (s/^f\s*//) {
			s/[,\.-]/_/g;
			my @a = split /\s+/;
			my ($msb, $lsb, $this_field) = reverse @a;
		        @a = ( { "name" => "SHIFT", "addr" => $lsb, "fmt" => "%uU", },
			       { "name" => "MASK", "addr" => (1 << ($msb + 1)) - 1 - ((1 << $lsb) - 1), "fmt" => "0x%" . join(".", ($this{"elsize"} >> 2) x 2) . "x" } );
			$this{"field"} = $this_field;
			foreach my $ar (@a) {
				#print $ar->{fmt}."\n";
				$hdr_data .= sprintf "#define %-62s " . $ar->{"fmt"} . "\n", "CCS_" . (uc $this{"name"}) . (defined $this_field ? "_" . uc $this_field : "") . "_" . $ar->{"name"}, $ar->{"addr"} . "\n";
			}
		} elsif (s/^e\s*//) {
			s/[,\.-]/_/g;
			my ($enum, $addr) = split /\s+/;
			$enum = uc $enum;
			$hdr_data .= sprintf "#define %-62s %s", "CCS_" . (uc ${this{name}}) . (defined $this{"field"} ? "_" . uc $this{"field"} : "") ."_$enum", $addr . ($addr =~ /0x/i ? "" : "U") . "\n";
		} elsif (s/^l\s*//) {
			my ($arg, $min, $max, $elsize, @discontig) = split /\s+/;
			my $size;

			foreach my $num ($min, $max) {
				$num = hex $num if $num =~ /0x/i;
			}

			$hdr_data .= sprintf "#define %-62s %s", "CCS_LIM_" . (uc ${this{name}} . "_MIN_$arg"), $min . ($min =~ /0x/i ? "" : "U") . "\n";
			$hdr_data .= sprintf "#define %-62s %s", "CCS_LIM_" . (uc ${this{name}} . "_MAX_$arg"), $max . ($max =~ /0x/i ? "" : "U") . "\n";

			my $h = $this{argparams};

			$h->{$arg} = { "min" => $min,
				       "max" => $max,
				       "elsize" => $elsize =~ /^0x/ ? hex $elsize : $elsize,
				       "discontig" => \@discontig };

			$this{discontig} = $arg if @discontig;

			next if $#{$this{args}} + 1 != scalar keys %{$this{argparams}};

			my $reg_formula = "$this{addr}";
			my $lim_formula;

			chop $reg_formula;

			$reg_formula = "(" . $reg_formula if $this{flagstring} ne "";

			foreach my $arg (@{$this{args}}) {
				my $d = $h->{$arg}->{discontig};
				my $times = $h->{$arg}->{elsize} != 1 ?
				  " * " . $h->{$arg}->{elsize} : "";

				if (@$d) {
					my ($lim, $offset) = split /,/, $d->[0];

					$reg_formula .= " + (($arg) < $lim ? ($arg)$times : $offset + (($arg) - $lim)$times)";
				} else {
					$reg_formula .= " + ($arg)$times";
				}

				$lim_formula .= (defined $lim_formula ? " + " : "") . "($arg)$times";
			}

			$reg_formula .= ")";
			$lim_formula =~ s/^\(([a-z0-9]+)\)$/$1/i;

			print $H tabconv sprintf("#define %-62s %s", "CCS_R_" . (uc $this{name}) .
						 $this{arglist}, $reg_formula .
						 (($this{flagstring} eq "") ? "" :
						  " | " . $this{flagstring} . ")") . "\n");

			print $H tabconv $hdr_data;
			undef $hdr_data;

			# Sort arguments in descending order by size
			@{$this{sorted_args}} = sort {
				$h->{$a}->{elsize} <= $h->{$b}->{elsize}
			} @{$this{args}};

			if (defined $this{discontig}) {
				my $da = $this{argparams}->{$this{discontig}};
				my ($first_discontig) = split /,/, $da->{discontig}->[0];
				my $max = $da->{max};

				$da->{max} = $first_discontig - 1;
				print_args(\%this, "", 0);

				$da->{min} = $da->{max} + 1;
				$da->{max} = $max;
				print_args(\%this, $first_discontig, 1);
			} else {
				print_args(\%this, "", 0);
			}

			next unless is_limit_reg $this{base_addr};

			print $LH tabconv sprintf "#define %-63s%s\n",
			  "CCS_L_" . (uc $this{name}) . "_OFFSET(" .
			    (join ", ", @{$this{args}}) . ")", "($lim_formula)";
		}

		if (! @{$this{args}}) {
			print $H tabconv($hdr_data);
			undef $hdr_data;
		}

		next;
	}

	my ($name, $addr, @flags) = split /\t+/, $_;
	my $args = [];

	my $sp;

	($name, $addr, $args) = name_split($name, $addr) if /\(.*\)/;

	$name =~ s/[,\.-]/_/g;

	my $flagstring = "";
	my $bits = elem_bits(@flags);
	if (! defined $kernel) {
		$flagstring .= "| CCS_FL_16BIT " if $bits == 16;
		$flagstring .= "| CCS_FL_32BIT " if $bits == 32;
	}
	$flagstring .= "| CCS_FL_FLOAT_IREAL " if grep /^float_ireal$/, @flags;
	$flagstring .= "| CCS_FL_IREAL " if grep /^ireal$/, @flags;
	$flagstring =~ s/^\| //;
	$flagstring =~ s/ $//;
	$flagstring = "($flagstring)" if $flagstring =~ /\|/;
	my $base_addr = $addr;
	$addr = "CCI_REG$bits($addr)" if defined $kernel;

	if ($flagstring ne "" && !@$args) {
		$addr = "($addr | $flagstring)";
		$flagstring = "";
	}

	my $arglist = @$args ? "(" . (join ", ", @$args) . ")" : "";
	$hdr_data .= sprintf "#define %-62s %s\n", "CCS_R_" . (uc $name), $addr
	  if !@$args;

	$name =~ s/\(.*//;

	%this = ( name => $name,
		  addr => $addr,
		  flagstring => $flagstring,
		  base_addr => $base_addr,
		  argparams => {},
		  args => $args,
		  arglist => $arglist,
		  elsize => $bits / 8,
		);

	if (!@$args) {
		$reglist .= "\t{ CCS_R_" . (uc $name) . ", 1,  0, \"" . (lc $name) . "\", NULL },\n";
		print $H tabconv $hdr_data;
		undef $hdr_data;

		print $LC tabconv sprintf "\t{ CCS_R_" . (uc $name) . ", " .
		  $this{elsize} . ", 0, \"$name\" },\n"
		    if is_limit_reg $this{base_addr};
	}

	print $LH tabconv sprintf "#define %-63s%s\n",
	  "CCS_L_" . (uc $this{name}), $limitcount++
	    if is_limit_reg $this{base_addr};
}

if (defined $A) {
	print $A $argdescs, $reglist;

	print $A "\t{ 0 }\n";

	print $A "};\n";
}

print $H "\n#endif /* __${uc_header}__ */\n";

print $LH tabconv sprintf "#define %-63s%s\n", "CCS_L_LAST", $limitcount;

print $LH "\n#endif /* __${uc_limith}__ */\n";

print $LC "\t{ 0 } /* Guardian */\n";
print $LC "};\n";

close($R);
close($H);
close($A) if defined $A;
close($LC);
close($LH);

```

---

# SoundWire Documentation

_Peios Kernel / Hardware and drivers / Driver development / SoundWire_

> Reference for SoundWire Documentation.

<a id="rst-soundwire-documentation"></a>

- [SoundWire Subsystem Summary](</kernel/hardware/driver-api/soundwire/summary.md>)
- [Audio Stream in SoundWire](</kernel/hardware/driver-api/soundwire/stream.md>)
- [SoundWire Error Handling](</kernel/hardware/driver-api/soundwire/error-handling.md>)
- [SoundWire Locking](</kernel/hardware/driver-api/soundwire/locking.md>)
- [Bulk Register Access (BRA)](</kernel/hardware/driver-api/soundwire/bra.md>)
- [Cadence IP BRA support](</kernel/hardware/driver-api/soundwire/bra-cadence.md>)

---

# Bulk Register Access (BRA)

_Peios Kernel / Hardware and drivers / Driver development / SoundWire_

> Capitalized words used in this documentation are intentional and refer to concepts of the SoundWire 1.x specification.

<a id="rst-bulk-register-access-bra"></a>

<a id="rst-conventions"></a>

## Conventions

Capitalized words used in this documentation are intentional and refer to concepts of the SoundWire 1.x specification.

<a id="rst-introduction"></a>

## Introduction

The SoundWire 1.x specification provides a mechanism to speed-up command/control transfers by reclaiming parts of the audio bandwidth. The Bulk Register Access (BRA) protocol is a standard solution based on the Bulk Payload Transport (BPT) definitions.

The regular control channel uses Column 0 and can only send/retrieve one byte per frame with write/read commands. With a typical 48kHz frame rate, only 48kB/s can be transferred.

The optional Bulk Register Access capability can transmit up to 12 Mbits/s and reduce transfer times by several orders of magnitude, but has multiple design constraints:

> 1. Each frame can only support a read or a write transfer, with a 10-byte overhead per frame (header and footer response).
>
> 2. The read/writes SHALL be from/to contiguous register addresses in the same frame. A fragmented register space decreases the efficiency of the protocol by requiring multiple BRA transfers scheduled in different frames.
>
> 3. The targeted Peripheral device SHALL support the optional Data Port 0, and likewise the Manager SHALL expose audio-like Ports to insert BRA packets in the audio payload using the concepts of Sample Interval, HSTART, HSTOP, etc.
>
> 4. The BRA transport efficiency depends on the available bandwidth. If there are no on-going audio transfers, the entire frame minus Column 0 can be reclaimed for BRA. The frame shape also impacts efficiency: since Column0 cannot be used for BTP/BRA, the frame should rely on a large number of columns and minimize the number of rows. The bus clock should be as high as possible.
>
> 5. The number of bits transferred per frame SHALL be a multiple of 8 bits. Padding bits SHALL be inserted if necessary at the end of the data.
>
> 6. The regular read/write commands can be issued in parallel with BRA transfers. This is convenient to e.g. deal with alerts, jack detection or change the volume during firmware download, but accessing the same address with two independent protocols has to be avoided to avoid undefined behavior.
>
> 7. Some implementations may not be capable of handling the bandwidth of the BRA protocol, e.g. in the case of a slow I2C bus behind the SoundWire IP. In this case, the transfers may need to be spaced in time or flow-controlled.
>
> 8. Each BRA packet SHALL be marked as 'Active' when valid data is to be transmitted. This allows for software to allocate a BRA stream but not transmit/discard data while processing the results or preparing the next batch of data, or allowing the peripheral to deal with the previous transfer. In addition BRA transfer can be started early on without data being ready.
>
> 9. Up to 470 bytes may be transmitted per frame.
>
> 10. The address is represented with 32 bits and does not rely on the paging registers used for the regular command/control protocol in Column 0.

<a id="rst-error-checking"></a>

## Error checking

Firmware download is one of the key usages of the Bulk Register Access protocol. To make sure the binary data integrity is not compromised by transmission or programming errors, each BRA packet provides:

> 1. A CRC on the 7-byte header. This CRC helps the Peripheral Device check if it is addressed and set the start address and number of bytes. The Peripheral Device provides a response in Byte 7.
>
> 2. A CRC on the data block (header excluded). This CRC is transmitted as the last-but-one byte in the packet, prior to the footer response.

- **The header response can be one of:**

  - **(a)** Ack

  - **(b)** Nak

  - **(c)** Not Ready

- **The footer response can be one of:**

  1. Ack

  2. Nak  (CRC failure)

  3. Good (operation completed)

  4. Bad  (operation failed)

<a id="rst-example-frame"></a>

## Example frame

The example below is not to scale and makes simplifying assumptions for clarity. The different chunks in the BRA packets are not required to start on a new SoundWire Row, and the scale of data may vary.

>
>
> ```text
> +---+--------------------------------------------+
> +   |                                            |
> +   |             BRA HEADER                     |
> +   |                                            |
> +   +--------------------------------------------+
> + C |             HEADER CRC                     |
> + O +--------------------------------------------+
> + M |             HEADER RESPONSE                |
> + M +--------------------------------------------+
> + A |                                            |
> + N |                                            |
> + D |                 DATA                       |
> +   |                                            |
> +   |                                            |
> +   |                                            |
> +   +--------------------------------------------+
> +   |             DATA CRC                       |
> +   +--------------------------------------------+
> +   |             FOOTER RESPONSE                |
> +---+--------------------------------------------+
> ```

Assuming the frame uses N columns, the configuration shown above can be programmed by setting the DP0 registers as:

> - HSTART = 1
>
> - HSTOP = N - 1
>
> - Sampling Interval = N
>
> - WordLength = N - 1

<a id="rst-addressing-restrictions"></a>

## Addressing restrictions

The Device Number specified in the Header follows the SoundWire definitions, and broadcast and group addressing are permitted. For now the Linux implementation only allows for a single BPT transfer to a single device at a time. This might be revisited at a later point as an optimization to send the same firmware to multiple devices, but this would only be beneficial for single-link solutions.

In the case of multiple Peripheral devices attached to different Managers, the broadcast and group addressing is not supported by the SoundWire specification. Each device must be handled with separate BRA streams, possibly in parallel - the links are really independent.

<a id="rst-unsupported-features"></a>

## Unsupported features

The Bulk Register Access specification provides a number of capabilities that are not supported in known implementations, such as:

> 1. Transfers initiated by a Peripheral Device. The BRA Initiator is always the Manager Device.
>
> 2. Flow-control capabilities and retransmission based on the 'NotReady' header response require extra buffering in the SoundWire IP and are not implemented.

<a id="rst-bi-directional-handling"></a>

## Bi-directional handling

The BRA protocol can handle writes as well as reads, and in each packet the header and footer response are provided by the Peripheral Target device. On the Peripheral device, the BRA protocol is handled by a single DP0 data port, and at the low-level the bus ownership can will change for header/footer response as well as the data transmitted during a read.

On the host side, most implementations rely on a Port-like concept, with two FIFOs consuming/generating data transfers in parallel (Host-&gt;Peripheral and Peripheral-&gt;Host). The amount of data consumed/produced by these FIFOs is not symmetrical, as a result hardware typically inserts markers to help software and hardware interpret raw data

Each packet will typically have:

> 1. a 'Start of Packet' indicator.
>
> 2. an 'End of Packet' indicator.
>
> 3. a packet identifier to correlate the data requested and transmitted, and the error status for each frame

Hardware implementations can check errors at the frame level, and retry a transfer in case of errors. However, as for the flow-control case, this requires extra buffering and intelligence in the hardware. The Linux support assumes that the entire transfer is cancelled if a single error is detected in one of the responses.

<a id="rst-abstraction-required"></a>

### Abstraction required

There are no standard registers or mandatory implementation at the Manager level, so the low-level BPT/BRA details must be hidden in Manager-specific code. For example the Cadence IP format above is not known to the codec drivers.

Likewise, codec drivers should not have to know the frame size. The computation of CRC and handling of responses is handled in helpers and Manager-specific code.

The host BRA driver may also have restrictions on pages allocated for DMA, or other host-DSP communication protocols. The codec driver should not be aware of any of these restrictions, since it might be reused in combination with different implementations of Manager IPs.

<a id="rst-concurrency-between-bra-and-regular-read-write"></a>

### Concurrency between BRA and regular read/write

The existing 'nread/nwrite' API already relies on a notion of start address and number of bytes, so it would be possible to extend this API with a 'hint' requesting BPT/BRA be used.

However BRA transfers could be quite long, and the use of a single mutex for regular read/write and BRA is a show-stopper. Independent operation of the control/command and BRA transfers is a fundamental requirement, e.g. to change the volume level with the existing regmap interface while downloading firmware. The integration must however ensure that there are no concurrent access to the same address with the command/control protocol and the BRA protocol.

In addition, the 'sdw_msg' structure hard-codes support for 16-bit addresses and paging registers which are irrelevant for BPT/BRA support based on native 32-bit addresses. A separate API with 'sdw_bpt_msg' makes more sense.

One possible strategy to speed-up all initialization tasks would be to start a BRA transfer for firmware download, then deal with all the "regular" read/writes in parallel with the command channel, and last to wait for the BRA transfers to complete. This would allow for a degree of overlap instead of a purely sequential solution. As such, the BRA API must support async transfers and expose a separate wait function.

<a id="rst-peripheral-bus-interface"></a>

## Peripheral/bus interface

The bus interface for BPT/BRA is made of two functions:

> > - sdw_bpt_send_async(bpt_message)
> >
> >   This function sends the data using the Manager implementation-defined capabilities (typically DMA or IPC protocol).
> >
> >   Queueing is currently not supported, the caller needs to wait for completion of the requested transfer.
>
> - sdw_bpt_wait()
>
>   > This function waits for the entire message provided by the codec driver in the 'send_async' stage. Intermediate status for smaller chunks will not be provided back to the codec driver, only a return code will be provided.

<a id="rst-regmap-use"></a>

### Regmap use

Existing codec drivers rely on regmap to download firmware to Peripherals. regmap exposes an async interface similar to the send/wait API suggested above, so at a high-level it would seem natural to combine BRA and regmap. The regmap layer could check if BRA is available or not, and use a regular read-write command channel in the latter case.

The regmap integration will be handled in a second step.

<a id="rst-bra-stream-model"></a>

## BRA stream model

For regular audio transfers, the machine driver exposes a dailink connecting CPU DAI(s) and Codec DAI(s).

This model is not required BRA support:

> 1. The SoundWire DAIs are mainly wrappers for SoundWire Data Ports, with possibly some analog or audio conversion capabilities bolted behind the Data Port. In the context of BRA, the DP0 is the destination. DP0 registers are standard and can be programmed blindly without knowing what Peripheral is connected to each link. In addition, if there are multiple Peripherals on a link and some of them do not support DP0, the write commands to program DP0 registers will generate harmless COMMAND_IGNORED responses that will be wired-ORed with responses from Peripherals which support DP0. In other words, the DP0 programming can be done with broadcast commands, and the information on the Target device can be added only in the BRA Header.
>
> 2. At the CPU level, the DAI concept is not useful for BRA; the machine driver will not create a dailink relying on DP0. The only concept that is needed is the notion of port.
>
> 3. The stream concept relies on a set of master_rt and slave_rt concepts. All of these entities represent ports and not DAIs.
>
> 4. With the assumption that a single BRA stream is used per link, that stream can connect master ports as well as all peripheral DP0 ports.
>
> 5. BRA transfers only make sense in the context of one Manager/Link, so the BRA stream handling does not rely on the concept of multi-link aggregation allowed by regular DAI links.

<a id="rst-audio-dma-support"></a>

## Audio DMA support

Some DMAs, such as HDaudio, require an audio format field to be set. This format is in turn used to define acceptable bursts. BPT/BRA support is not fully compatible with these definitions in that the format and bandwidth may vary between read and write commands.

In addition, on Intel HDaudio Intel platforms the DMAs need to be programmed with a PCM format matching the bandwidth of the BPT/BRA transfer. The format is based on 192kHz 32-bit samples, and the number of channels varies to adjust the bandwidth. The notion of channel is completely notional since the data is not typical audio PCM. Programming such channels helps reserve enough bandwidth and adjust FIFO sizes to avoid xruns.

Alignment requirements are currently not enforced at the core level but at the platform-level, e.g. for Intel the data sizes must be equal to or larger than 16 bytes.

---

# Cadence IP BRA support

_Peios Kernel / Hardware and drivers / Driver development / SoundWire_

> The Cadence IP relies on PDI0 for TX and PDI1 for RX. The data needs to be formatted with the following conventions:

<a id="rst-cadence-ip-bra-support"></a>

<a id="rst-format-requirements"></a>

## Format requirements

The Cadence IP relies on PDI0 for TX and PDI1 for RX. The data needs to be formatted with the following conventions:

> 1. all Data is stored in bits 15..0 of the 32-bit PDI FIFOs.
>
> 2. the start of packet is BIT(31).
>
> 3. the end of packet is BIT(30).
>
> 4. A packet ID is stored in bits 19..16. This packet ID is determined by software and is typically a rolling counter.
>
> 5. Padding shall be inserted as needed so that the Header CRC, Header response, Footer CRC, Footer response are always in Byte0. Padding is inserted by software for writes, and on reads software shall discard the padding added by the hardware.

<a id="rst-example-format"></a>

## Example format

The following table represents the sequence provided to PDI0 for a write command followed by a read command.



```text
+---+---+--------+---------------+---------------+
+ 1 | 0 | ID = 0 |  WR HDR[1]    |  WR HDR[0]    |
+   |   |        |  WR HDR[3]    |  WR HDR[2]    |
+   |   |        |  WR HDR[5]    |  WR HDR[4]    |
+   |   |        |  pad          |  WR HDR CRC   |
+   |   |        |  WR Data[1]   |  WR Data[0]   |
+   |   |        |  WR Data[3]   |  WR Data[2]   |
+   |   |        |  WR Data[n-2] |  WR Data[n-3] |
+   |   |        |  pad          |  WR Data[n-1] |
+ 0 | 1 |        |  pad          |  WR Data CRC  |
+---+---+--------+---------------+---------------+
+ 1 | 0 | ID = 1 |  RD HDR[1]    |  RD HDR[0]    |
+   |   |        |  RD HDR[3]    |  RD HDR[2]    |
+   |   |        |  RD HDR[5]    |  RD HDR[4]    |
+ 0 | 1 |        |  pad          |  RD HDR CRC   |
+---+---+--------+---------------+---------------+
```

The table below represents the data received on PDI1 for the same write command followed by a read command.



```text
+---+---+--------+---------------+---------------+
+ 1 | 0 | ID = 0 |  pad          |  WR Hdr Rsp   |
+ 0 | 1 |        |  pad          |  WR Ftr Rsp   |
+---+---+--------+---------------+---------------+
+ 1 | 0 | ID = 0 |  pad          |  Rd Hdr Rsp   |
+   |   |        |  RD Data[1]   |  RD Data[0]   |
+   |   |        |  RD Data[3]   |  RD Data[2]   |
+   |   |        |  RD HDR[n-2]  |  RD Data[n-3] |
+   |   |        |  pad          |  RD Data[n-1] |
+   |   |        |  pad          |  RD Data CRC  |
+ 0 | 1 |        |  pad          |  RD Ftr Rsp   |
+---+---+--------+---------------+---------------+
```

---

# SoundWire Error Handling

_Peios Kernel / Hardware and drivers / Driver development / SoundWire_

> The SoundWire PHY was designed with care and errors on the bus are going to be very unlikely, and if they happen it should be limited to single bit errors. Examples of this design can be found in the synchronization mechanism (sync loss…

<a id="rst-soundwire-error-handling"></a>

The SoundWire PHY was designed with care and errors on the bus are going to be very unlikely, and if they happen it should be limited to single bit errors. Examples of this design can be found in the synchronization mechanism (sync loss after two errors) and short CRCs used for the Bulk Register Access.

The errors can be detected with multiple mechanisms:

1. Bus clash or parity errors: This mechanism relies on low-level detectors that are independent of the payload and usages, and they cover both control and audio data. The current implementation only logs such errors. Improvements could be invalidating an entire programming sequence and restarting from a known position. In the case of such errors outside of a control/command sequence, there is no concealment or recovery for audio data enabled by the SoundWire protocol, the location of the error will also impact its audibility (most-significant bits will be more impacted in PCM), and after a number of such errors are detected the bus might be reset. Note that bus clashes due to programming errors (two streams using the same bit slots) or electrical issues during the transmit/receive transition cannot be distinguished, although a recurring bus clash when audio is enabled is a indication of a bus allocation issue. The interrupt mechanism can also help identify Slaves which detected a Bus Clash or a Parity Error, but they may not be responsible for the errors so resetting them individually is not a viable recovery strategy.

2. Command status: Each command is associated with a status, which only covers transmission of the data between devices. The ACK status indicates that the command was received and will be executed by the end of the current frame. A NAK indicates that the command was in error and will not be applied. In case of a bad programming (command sent to non-existent Slave or to a non-implemented register) or electrical issue, no response signals the command was ignored. Some Master implementations allow for a command to be retransmitted several times.  If the retransmission fails, backtracking and restarting the entire programming sequence might be a solution. Alternatively some implementations might directly issue a bus reset and re-enumerate all devices.

3. Timeouts: In a number of cases such as ChannelPrepare or ClockStopPrepare, the bus driver is supposed to poll a register field until it transitions to a NotFinished value of zero. The MIPI SoundWire spec 1.1 does not define timeouts but the MIPI SoundWire DisCo document adds recommendation on timeouts. If such configurations do not complete, the driver will return a -ETIMEOUT. Such timeouts are symptoms of a faulty Slave device and are likely impossible to recover from.

Errors during global reconfiguration sequences are extremely difficult to handle:

1. BankSwitch: An error during the last command issuing a BankSwitch is difficult to backtrack from. Retransmitting the Bank Switch command may be possible in a single segment setup, but this can lead to synchronization problems when enabling multiple bus segments (a command with side effects such as frame reconfiguration would be handled at different times). A global hard-reset might be the best solution.

Note that SoundWire does not provide a mechanism to detect illegal values written in valid registers. In a number of cases the standard even mentions that the Slave might behave in implementation-defined ways. The bus implementation does not provide a recovery mechanism for such errors, Slave or Master driver implementers are responsible for writing valid values in valid registers and implement additional range checking if needed.

---

# SoundWire Locking

_Peios Kernel / Hardware and drivers / Driver development / SoundWire_

> This document explains locking mechanism of the SoundWire Bus. Bus uses following locks in order to avoid race conditions in Bus operations on shared resources.

<a id="rst-soundwire-locking"></a>

This document explains locking mechanism of the SoundWire Bus. Bus uses following locks in order to avoid race conditions in Bus operations on shared resources.

> - Bus lock
>
> - Message lock

<a id="rst-bus-lock"></a>

## Bus lock

SoundWire Bus lock is a mutex and is part of Bus data structure (sdw_bus) which is used for every Bus instance. This lock is used to serialize each of the following operations(s) within SoundWire Bus instance.

> - Addition and removal of Slave(s), changing Slave status.
>
> - Prepare, Enable, Disable and De-prepare stream operations.
>
> - Access of Stream data structure.

<a id="rst-message-lock"></a>

## Message lock

SoundWire message transfer lock. This mutex is part of Bus data structure (sdw_bus). This lock is used to serialize the message transfers (read/write) within a SoundWire Bus instance.

Below examples show how locks are acquired.

<a id="rst-example-1"></a>

### Example 1

Message transfer.

> 1. For every message transfer
>
>    - **a.** Acquire Message lock.
>
>    - **b.** Transfer message (Read/Write) to Slave1 or broadcast message on Bus in case of bank switch.
>
>    - **c.** Release Message lock
>
>
>
>    ```text
>    +----------+                    +---------+
>    |          |                    |         |
>    |   Bus    |                    | Master  |
>    |          |                    | Driver  |
>    |          |                    |         |
>    +----+-----+                    +----+----+
>         |                               |
>         |     bus->ops->xfer_msg()      |
>         <-------------------------------+   a. Acquire Message lock
>         |                               |   b. Transfer message
>         |                               |
>         +------------------------------->   c. Release Message lock
>         |    return success/error       |   d. Return success/error
>         |                               |
>         +                               +
>    ```

<a id="rst-example-2"></a>

### Example 2

Prepare operation.

> 1. Acquire lock for Bus instance associated with Master 1.
>
> 2. For every message transfer in Prepare operation
>
>    - **a.** Acquire Message lock.
>
>    - **b.** Transfer message (Read/Write) to Slave1 or broadcast message on Bus in case of bank switch.
>
>    - **c.** Release Message lock.
>
> 3. Release lock for Bus instance associated with Master 1
>
>
>
>    ```text
>    +----------+                    +---------+
>    |          |                    |         |
>    |   Bus    |                    | Master  |
>    |          |                    | Driver  |
>    |          |                    |         |
>    +----+-----+                    +----+----+
>         |                               |
>         |    sdw_prepare_stream()       |
>         <-------------------------------+   1. Acquire bus lock
>         |                               |   2. Perform stream prepare
>         |                               |
>         |                               |
>         |     bus->ops->xfer_msg()      |
>         <-------------------------------+   a. Acquire Message lock
>         |                               |   b. Transfer message
>         |                               |
>         +------------------------------->   c. Release Message lock
>         |    return success/error       |   d. Return success/error
>         |                               |
>         |                               |
>         |    return success/error       |   3. Release bus lock
>         +------------------------------->   4. Return success/error
>         |                               |
>         +                               +
>    ```

---

# Audio Stream in SoundWire

_Peios Kernel / Hardware and drivers / Driver development / SoundWire_

> An audio stream is a logical or virtual connection created between

<a id="rst-audio-stream-in-soundwire"></a>

An audio stream is a logical or virtual connection created between

> 1. System memory buffer(s) and Codec(s)
>
> 2. DSP memory buffer(s) and Codec(s)
>
> 3. FIFO(s) and Codec(s)
>
> 4. Codec(s) and Codec(s)

which is typically driven by a DMA(s) channel through the data link. An audio stream contains one or more channels of data. All channels within stream must have same sample rate and same sample size.

Assume a stream with two channels (Left &amp; Right) is opened using SoundWire interface. Below are some ways a stream can be represented in SoundWire.

Stream Sample in memory (System memory, DSP memory or FIFOs)



```text
-------------------------
| L | R | L | R | L | R |
-------------------------
```

Example 1: Stereo Stream with L and R channels is rendered from Master to Slave. Both Master and Slave is using single port.



```text
+---------------+                    Clock Signal  +---------------+
|    Master     +----------------------------------+     Slave     |
|   Interface   |                                  |   Interface   |
|               |                                  |       1       |
|               |                     Data Signal  |               |
|    L  +  R    +----------------------------------+    L  +  R    |
|     (Data)    |     Data Direction               |     (Data)    |
+---------------+  +----------------------->       +---------------+
```

Example 2: Stereo Stream with L and R channels is captured from Slave to Master. Both Master and Slave is using single port.



```text
+---------------+                    Clock Signal  +---------------+
|    Master     +----------------------------------+     Slave     |
|   Interface   |                                  |   Interface   |
|               |                                  |       1       |
|               |                     Data Signal  |               |
|    L  +  R    +----------------------------------+    L  +  R    |
|     (Data)    |     Data Direction               |     (Data)    |
+---------------+  <-----------------------+       +---------------+
```

Example 3: Stereo Stream with L and R channels is rendered by Master. Each of the L and R channel is received by two different Slaves. Master and both Slaves are using single port.



```text
+---------------+                    Clock Signal  +---------------+
|    Master     +---------+------------------------+     Slave     |
|   Interface   |         |                        |   Interface   |
|               |         |                        |       1       |
|               |         |           Data Signal  |               |
|    L  +  R    +---+------------------------------+       L       |
|     (Data)    |   |     |    Data Direction      |     (Data)    |
+---------------+   |     |   +------------->      +---------------+
                    |     |
                    |     |
                    |     |                        +---------------+
                    |     +----------------------> |     Slave     |
                    |                              |   Interface   |
                    |                              |       2       |
                    |                              |               |
                    +----------------------------> |       R       |
                                                   |     (Data)    |
                                                   +---------------+
```

Example 4: Stereo Stream with L and R channels is rendered by Master. Both of the L and R channels are received by two different Slaves. Master and both Slaves are using single port handling L+R. Each Slave device processes the L + R data locally, typically based on static configuration or dynamic orientation, and may drive one or more speakers.



```text
+---------------+                    Clock Signal  +---------------+
|    Master     +---------+------------------------+     Slave     |
|   Interface   |         |                        |   Interface   |
|               |         |                        |       1       |
|               |         |           Data Signal  |               |
|    L  +  R    +---+------------------------------+     L + R     |
|     (Data)    |   |     |    Data Direction      |     (Data)    |
+---------------+   |     |   +------------->      +---------------+
                    |     |
                    |     |
                    |     |                        +---------------+
                    |     +----------------------> |     Slave     |
                    |                              |   Interface   |
                    |                              |       2       |
                    |                              |               |
                    +----------------------------> |     L + R     |
                                                   |     (Data)    |
                                                   +---------------+
```

Example 5: Stereo Stream with L and R channel is rendered by two different Ports of the Master and is received by only single Port of the Slave interface.



```text
+--------------------+
|                    |
|     +--------------+                             +----------------+
|     |             ||                             |                |
|     |  Data Port  ||  L Channel                  |                |
|     |      1      |------------+                 |                |
|     |  L Channel  ||           |                 +-----+----+     |
|     |   (Data)    ||           |   L + R Channel ||    Data |     |
| Master  +----------+           | +---+---------> ||    Port |     |
| Interface          |           |                 ||     1   |     |
|     +--------------+           |                 ||         |     |
|     |             ||           |                 +----------+     |
|     |  Data Port  |------------+                 |                |
|     |      2      ||  R Channel                  |     Slave      |
|     |  R Channel  ||                             |   Interface    |
|     |   (Data)    ||                             |       1        |
|     +--------------+         Clock Signal        |     L  +  R    |
|                    +---------------------------> |      (Data)    |
+--------------------+                             |                |
                                                   +----------------+
```

Example 6: Stereo Stream with L and R channel is rendered by 2 Masters, each rendering one channel, and is received by two different Slaves, each receiving one channel. Both Masters and both Slaves are using single port.



```text
+---------------+                    Clock Signal  +---------------+
|    Master     +----------------------------------+     Slave     |
|   Interface   |                                  |   Interface   |
|       1       |                                  |       1       |
|               |                     Data Signal  |               |
|       L       +----------------------------------+       L       |
|     (Data)    |     Data Direction               |     (Data)    |
+---------------+  +----------------------->       +---------------+

+---------------+                    Clock Signal  +---------------+
|    Master     +----------------------------------+     Slave     |
|   Interface   |                                  |   Interface   |
|       2       |                                  |       2       |
|               |                     Data Signal  |               |
|       R       +----------------------------------+       R       |
|     (Data)    |     Data Direction               |     (Data)    |
+---------------+  +----------------------->       +---------------+
```

Example 7: Stereo Stream with L and R channel is rendered by 2 Masters, each rendering both channels. Each Slave receives L + R. This is the same application as Example 4 but with Slaves placed on separate links.



```text
+---------------+                    Clock Signal  +---------------+
|    Master     +----------------------------------+     Slave     |
|   Interface   |                                  |   Interface   |
|       1       |                                  |       1       |
|               |                     Data Signal  |               |
|     L + R     +----------------------------------+     L + R     |
|     (Data)    |     Data Direction               |     (Data)    |
+---------------+  +----------------------->       +---------------+

+---------------+                    Clock Signal  +---------------+
|    Master     +----------------------------------+     Slave     |
|   Interface   |                                  |   Interface   |
|       2       |                                  |       2       |
|               |                     Data Signal  |               |
|     L + R     +----------------------------------+     L + R     |
|     (Data)    |     Data Direction               |     (Data)    |
+---------------+  +----------------------->       +---------------+
```

Example 8: 4-channel Stream is rendered by 2 Masters, each rendering a 2 channels. Each Slave receives 2 channels.



```text
+---------------+                    Clock Signal  +---------------+
|    Master     +----------------------------------+     Slave     |
|   Interface   |                                  |   Interface   |
|       1       |                                  |       1       |
|               |                     Data Signal  |               |
|    L1 + R1    +----------------------------------+    L1 + R1    |
|     (Data)    |     Data Direction               |     (Data)    |
+---------------+  +----------------------->       +---------------+

+---------------+                    Clock Signal  +---------------+
|    Master     +----------------------------------+     Slave     |
|   Interface   |                                  |   Interface   |
|       2       |                                  |       2       |
|               |                     Data Signal  |               |
|     L2 + R2   +----------------------------------+    L2 + R2    |
|     (Data)    |     Data Direction               |     (Data)    |
+---------------+  +----------------------->       +---------------+
```

Note1: In multi-link cases like above, to lock, one would acquire a global lock and then go on locking bus instances. But, in this case the caller framework(ASoC DPCM) guarantees that stream operations on a card are always serialized. So, there is no race condition and hence no need for global lock.

Note2: A Slave device may be configured to receive all channels transmitted on a link for a given Stream (Example 4) or just a subset of the data (Example 3). The configuration of the Slave device is not handled by a SoundWire subsystem API, but instead by the snd_soc_dai_set_tdm_slot() API. The platform or machine driver will typically configure which of the slots are used. For Example 4, the same slots would be used by all Devices, while for Example 3 the Slave Device1 would use e.g. Slot 0 and Slave device2 slot 1.

Note3: Multiple Sink ports can extract the same information for the same bitSlots in the SoundWire frame, however multiple Source ports shall be configured with different bitSlot configurations. This is the same limitation as with I2S/PCM TDM usages.

<a id="rst-soundwire-stream-management-flow"></a>

## SoundWire Stream Management flow

<a id="rst-stream-definitions"></a>

### Stream definitions

> 1. Current stream: This is classified as the stream on which operation has to be performed like prepare, enable, disable, de-prepare etc.
>
> 2. Active stream: This is classified as the stream which is already active on Bus other than current stream. There can be multiple active streams on the Bus.

SoundWire Bus manages stream operations for each stream getting rendered/captured on the SoundWire Bus. This section explains Bus operations done for each of the stream allocated/released on Bus. Following are the stream states maintained by the Bus for each of the audio stream.

<a id="rst-soundwire-stream-states"></a>

### SoundWire stream states

Below shows the SoundWire stream states and state transition diagram.



```text
+-----------+     +------------+     +----------+     +----------+
| ALLOCATED +---->| CONFIGURED +---->| PREPARED +---->| ENABLED  |
|   STATE   |     |    STATE   |     |  STATE   |     |  STATE   |
+-----------+     +------------+     +---+--+---+     +----+-----+
                                         ^  ^              ^
                                         |  |              |
                                       __|  |___________   |
                                      |                 |  |
                                      v                 |  v
         +----------+           +-----+------+        +-+--+-----+
         | RELEASED |<----------+ DEPREPARED |<-------+ DISABLED |
         |  STATE   |           |   STATE    |        |  STATE   |
         +----------+           +------------+        +----------+
```

NOTE: State transitions between `SDW_STREAM_ENABLED` and `SDW_STREAM_DISABLED` are only relevant when then INFO_PAUSE flag is supported at the ALSA/ASoC level. Likewise the transition between `SDW_DISABLED_STATE` and `SDW_PREPARED_STATE` depends on the INFO_RESUME flag.

NOTE2: The framework implements basic state transition checks, but does not e.g. check if a transition from DISABLED to ENABLED is valid on a specific platform. Such tests need to be added at the ALSA/ASoC level.

<a id="rst-stream-state-operations"></a>

### Stream State Operations

Below section explains the operations done by the Bus on Master(s) and Slave(s) as part of stream state transitions.

<a id="rst-sdw-stream-allocated"></a>

#### SDW_STREAM_ALLOCATED

Allocation state for stream. This is the entry state of the stream. Operations performed before entering in this state:

> 1. A stream runtime is allocated for the stream. This stream runtime is used as a reference for all the operations performed on the stream.
>
> 2. The resources required for holding stream runtime information are allocated and initialized. This holds all stream related information such as stream type (PCM/PDM) and parameters, Master and Slave interface associated with the stream, stream state etc.

After all above operations are successful, stream state is set to `SDW_STREAM_ALLOCATED`.

Bus implements below API for allocate a stream which needs to be called once per stream. From ASoC DPCM framework, this stream state maybe linked to .startup() operation.



```c
int sdw_alloc_stream(char * stream_name, enum sdw_stream_type type);
```

The SoundWire core provides a sdw_startup_stream() helper function, typically called during a dailink .startup() callback, which performs stream allocation and sets the stream pointer for all DAIs connected to a stream.

<a id="rst-sdw-stream-configured"></a>

#### SDW_STREAM_CONFIGURED

Configuration state of stream. Operations performed before entering in this state:

> 1. The resources allocated for stream information in SDW_STREAM_ALLOCATED state are updated here. This includes stream parameters, Master(s) and Slave(s) runtime information associated with current stream.
>
> 2. All the Master(s) and Slave(s) associated with current stream provide the port information to Bus which includes port numbers allocated by Master(s) and Slave(s) for current stream and their channel mask.

After all above operations are successful, stream state is set to `SDW_STREAM_CONFIGURED`.

Bus implements below APIs for CONFIG state which needs to be called by the respective Master(s) and Slave(s) associated with stream. These APIs can only be invoked once by respective Master(s) and Slave(s). From ASoC DPCM framework, this stream state is linked to .hw_params() operation.



```c
int sdw_stream_add_master(struct sdw_bus * bus,
              struct sdw_stream_config * stream_config,
              const struct sdw_ports_config * ports_config,
              struct sdw_stream_runtime * stream);

int sdw_stream_add_slave(struct sdw_slave * slave,
              struct sdw_stream_config * stream_config,
              const struct sdw_ports_config * ports_config,
              struct sdw_stream_runtime * stream);
```

<a id="rst-sdw-stream-prepared"></a>

#### SDW_STREAM_PREPARED

Prepare state of stream. Operations performed before entering in this state:

> 0. Steps 1 and 2 are omitted in the case of a resume operation, where the bus bandwidth is known.
>
> 1. Bus parameters such as bandwidth, frame shape, clock frequency, are computed based on current stream as well as already active stream(s) on Bus. Re-computation is required to accommodate current stream on the Bus.
>
> 2. Transport and port parameters of all Master(s) and Slave(s) port(s) are computed for the current as well as already active stream based on frame shape and clock frequency computed in step 1.
>
> 3. Computed Bus and transport parameters are programmed in Master(s) and Slave(s) registers. The banked registers programming is done on the alternate bank (bank currently unused). Port(s) are enabled for the already active stream(s) on the alternate bank (bank currently unused). This is done in order to not disrupt already active stream(s).
>
> 4. Once all the values are programmed, Bus initiates switch to alternate bank where all new values programmed gets into effect.
>
> 5. Ports of Master(s) and Slave(s) for current stream are prepared by programming PrepareCtrl register.

After all above operations are successful, stream state is set to `SDW_STREAM_PREPARED`.

Bus implements below API for PREPARE state which needs to be called once per stream. From ASoC DPCM framework, this stream state is linked to .prepare() operation. Since the .trigger() operations may not follow the .prepare(), a direct transition from `SDW_STREAM_PREPARED` to `SDW_STREAM_DEPREPARED` is allowed.



```c
int sdw_prepare_stream(struct sdw_stream_runtime * stream);
```

<a id="rst-sdw-stream-enabled"></a>

#### SDW_STREAM_ENABLED

Enable state of stream. The data port(s) are enabled upon entering this state. Operations performed before entering in this state:

> 1. All the values computed in SDW_STREAM_PREPARED state are programmed in alternate bank (bank currently unused). It includes programming of already active stream(s) as well.
>
> 2. All the Master(s) and Slave(s) port(s) for the current stream are enabled on alternate bank (bank currently unused) by programming ChannelEn register.
>
> 3. Once all the values are programmed, Bus initiates switch to alternate bank where all new values programmed gets into effect and port(s) associated with current stream are enabled.

After all above operations are successful, stream state is set to `SDW_STREAM_ENABLED`.

Bus implements below API for ENABLE state which needs to be called once per stream. From ASoC DPCM framework, this stream state is linked to .trigger() start operation.



```c
int sdw_enable_stream(struct sdw_stream_runtime * stream);
```

<a id="rst-sdw-stream-disabled"></a>

#### SDW_STREAM_DISABLED

Disable state of stream. The data port(s) are disabled upon exiting this state. Operations performed before entering in this state:

> 1. All the Master(s) and Slave(s) port(s) for the current stream are disabled on alternate bank (bank currently unused) by programming ChannelEn register.
>
> 2. All the current configuration of Bus and active stream(s) are programmed into alternate bank (bank currently unused).
>
> 3. Once all the values are programmed, Bus initiates switch to alternate bank where all new values programmed gets into effect and port(s) associated with current stream are disabled.

After all above operations are successful, stream state is set to `SDW_STREAM_DISABLED`.

Bus implements below API for DISABLED state which needs to be called once per stream. From ASoC DPCM framework, this stream state is linked to .trigger() stop operation.

When the INFO_PAUSE flag is supported, a direct transition to `SDW_STREAM_ENABLED` is allowed.

For resume operations where ASoC will use the .prepare() callback, the stream can transition from `SDW_STREAM_DISABLED` to `SDW_STREAM_PREPARED`, with all required settings restored but without updating the bandwidth and bit allocation.



```c
int sdw_disable_stream(struct sdw_stream_runtime * stream);
```

<a id="rst-sdw-stream-deprepared"></a>

#### SDW_STREAM_DEPREPARED

De-prepare state of stream. Operations performed before entering in this state:

> 1. All the port(s) of Master(s) and Slave(s) for current stream are de-prepared by programming PrepareCtrl register.
>
> 2. The payload bandwidth of current stream is reduced from the total bandwidth requirement of bus and new parameters calculated and applied by performing bank switch etc.

After all above operations are successful, stream state is set to `SDW_STREAM_DEPREPARED`.

Bus implements below API for DEPREPARED state which needs to be called once per stream. ALSA/ASoC do not have a concept of 'deprepare', and the mapping from this stream state to ALSA/ASoC operation may be implementation specific.

When the INFO_PAUSE flag is supported, the stream state is linked to the .hw_free() operation - the stream is not deprepared on a TRIGGER_STOP.

Other implementations may transition to the `SDW_STREAM_DEPREPARED` state on TRIGGER_STOP, should they require a transition through the `SDW_STREAM_PREPARED` state.



```c
int sdw_deprepare_stream(struct sdw_stream_runtime * stream);
```

<a id="rst-sdw-stream-released"></a>

#### SDW_STREAM_RELEASED

Release state of stream. Operations performed before entering in this state:

> 1. Release port resources for all Master(s) and Slave(s) port(s) associated with current stream.
>
> 2. Release Master(s) and Slave(s) runtime resources associated with current stream.
>
> 3. Release stream runtime resources associated with current stream.

After all above operations are successful, stream state is set to `SDW_STREAM_RELEASED`.

Bus implements below APIs for RELEASE state which needs to be called by all the Master(s) and Slave(s) associated with stream. From ASoC DPCM framework, this stream state is linked to .hw_free() operation.



```c
int sdw_stream_remove_master(struct sdw_bus * bus,
              struct sdw_stream_runtime * stream);
int sdw_stream_remove_slave(struct sdw_slave * slave,
              struct sdw_stream_runtime * stream);
```

The .shutdown() ASoC DPCM operation calls below Bus API to release stream assigned as part of ALLOCATED state.

In .shutdown() the data structure maintaining stream state are freed up.



```c
void sdw_release_stream(struct sdw_stream_runtime * stream);
```

The SoundWire core provides a sdw_shutdown_stream() helper function, typically called during a dailink .shutdown() callback, which clears the stream pointer for all DAIS connected to a stream and releases the memory allocated for the stream.

<a id="rst-not-supported"></a>

## Not Supported

1. A single port with multiple channels supported cannot be used between two streams or across stream. For example a port with 4 channels cannot be used to handle 2 independent stereo streams even though it's possible in theory in SoundWire.

---

# SoundWire Subsystem Summary

_Peios Kernel / Hardware and drivers / Driver development / SoundWire_

> SoundWire is a new interface ratified in 2015 by the MIPI Alliance. SoundWire is used for transporting data typically related to audio functions. SoundWire interface is optimized to integrate audio devices in mobile or mobile inspired…

<a id="rst-soundwire-subsystem-summary"></a>

SoundWire is a new interface ratified in 2015 by the MIPI Alliance. SoundWire is used for transporting data typically related to audio functions. SoundWire interface is optimized to integrate audio devices in mobile or mobile inspired systems.

SoundWire is a 2-pin multi-drop interface with data and clock line. It facilitates development of low cost, efficient, high performance systems. Broad level key features of SoundWire interface include:

> 1. Transporting all of payload data channels, control information, and setup commands over a single two-pin interface.
>
> 2. Lower clock frequency, and hence lower power consumption, by use of DDR (Dual Data Rate) data transmission.
>
> 3. Clock scaling and optional multiple data lanes to give wide flexibility in data rate to match system requirements.
>
> 4. Device status monitoring, including interrupt-style alerts to the Master.

The SoundWire protocol supports up to eleven Slave interfaces. All the interfaces share the common Bus containing data and clock line. Each of the Slaves can support up to 14 Data Ports. 13 Data Ports are dedicated to audio transport. Data Port0 is dedicated to transport of Bulk control information, each of the audio Data Ports (1..14) can support up to 8 Channels in transmit or receiving mode (typically fixed direction but configurable direction is enabled by the specification).  Bandwidth restrictions to \~19.2..24.576Mbits/s don't however allow for 11\*13\*8 channels to be transmitted simultaneously.

Below figure shows an example of connectivity between a SoundWire Master and two Slave devices.



```text
+---------------+                                       +---------------+
|               |                       Clock Signal    |               |
|    Master     |-------+-------------------------------|    Slave      |
|   Interface   |       |               Data Signal     |  Interface 1  |
|               |-------|-------+-----------------------|               |
+---------------+       |       |                       +---------------+
                        |       |
                        |       |
                        |       |
                     +--+-------+--+
                     |             |
                     |   Slave     |
                     | Interface 2 |
                     |             |
                     +-------------+
```

<a id="rst-terminology"></a>

## Terminology

The MIPI SoundWire specification uses the term 'device' to refer to a Master or Slave interface, which of course can be confusing. In this summary and code we use the term interface only to refer to the hardware. We follow the Linux device model by mapping each Slave interface connected on the bus as a device managed by a specific driver. The Linux SoundWire subsystem provides a framework to implement a SoundWire Slave driver with an API allowing 3rd-party vendors to enable implementation-defined functionality while common setup/configuration tasks are handled by the bus.

Bus: Implements SoundWire Linux Bus which handles the SoundWire protocol. Programs all the MIPI-defined Slave registers. Represents a SoundWire Master. Multiple instances of Bus may be present in a system.

Slave: Registers as SoundWire Slave device (Linux Device). Multiple Slave devices can register to a Bus instance.

Slave driver: Driver controlling the Slave device. MIPI-specified registers are controlled directly by the Bus (and transmitted through the Master driver/interface). Any implementation-defined Slave register is controlled by Slave driver. In practice, it is expected that the Slave driver relies on regmap and does not request direct register access.

<a id="rst-programming-interfaces-soundwire-master-interface-driver"></a>

## Programming interfaces (SoundWire Master interface Driver)

SoundWire Bus supports programming interfaces for the SoundWire Master implementation and SoundWire Slave devices. All the code uses the "sdw" prefix commonly used by SoC designers and 3rd party vendors.

Each of the SoundWire Master interfaces needs to be registered to the Bus. Bus implements API to read standard Master MIPI properties and also provides callback in Master ops for Master driver to implement its own functions that provides capabilities information. DT support is not implemented at this time but should be trivial to add since capabilities are enabled with the `device_property_` API.

The Master interface along with the Master interface capabilities are registered based on board file, DT or ACPI.

Following is the Bus API to register the SoundWire Bus:



```c
int sdw_bus_master_add(struct sdw_bus *bus,
                        struct device *parent,
                        struct fwnode_handle)
{
        sdw_master_device_add(bus, parent, fwnode);

        mutex_init(&bus->lock);
        INIT_LIST_HEAD(&bus->slaves);

        /* Check ACPI for Slave devices */
        sdw_acpi_find_slaves(bus);

        /* Check DT for Slave devices */
        sdw_of_find_slaves(bus);

        return 0;
}
```

This will initialize sdw_bus object for Master device. "sdw_master_ops" and "sdw_master_port_ops" callback functions are provided to the Bus.

"sdw_master_ops" is used by Bus to control the Bus in the hardware specific way. It includes Bus control functions such as sending the SoundWire read/write messages on Bus, setting up clock frequency &amp; Stream Synchronization Point (SSP). The "sdw_master_ops" structure abstracts the hardware details of the Master from the Bus.

"sdw_master_port_ops" is used by Bus to setup the Port parameters of the Master interface Port. Master interface Port register map is not defined by MIPI specification, so Bus calls the "sdw_master_port_ops" callback function to do Port operations like "Port Prepare", "Port Transport params set", "Port enable and disable". The implementation of the Master driver can then perform hardware-specific configurations.

<a id="rst-programming-interfaces-soundwire-slave-driver"></a>

## Programming interfaces (SoundWire Slave Driver)

The MIPI specification requires each Slave interface to expose a unique 48-bit identifier, stored in 6 read-only dev_id registers. This dev_id identifier contains vendor and part information, as well as a field enabling to differentiate between identical components. An additional class field is currently unused. Slave driver is written for a specific vendor and part identifier, Bus enumerates the Slave device based on these two ids. Slave device and driver match is done based on these two ids . Probe of the Slave driver is called by Bus on successful match between device and driver id. A parent/child relationship is enforced between Master and Slave devices (the logical representation is aligned with the physical connectivity).

The information on Master/Slave dependencies is stored in platform data, board-file, ACPI or DT. The MIPI Software specification defines additional link_id parameters for controllers that have multiple Master interfaces. The dev_id registers are only unique in the scope of a link, and the link_id unique in the scope of a controller. Both dev_id and link_id are not necessarily unique at the system level but the parent/child information is used to avoid ambiguity.



```c
static const struct sdw_device_id slave_id[] = {
        SDW_SLAVE_ENTRY(0x025d, 0x700, 0),
        {},
};
MODULE_DEVICE_TABLE(sdw, slave_id);

static struct sdw_driver slave_sdw_driver = {
        .driver = {
                   .name = "slave_xxx",
                   .pm = &slave_runtime_pm,
                   },
        .probe = slave_sdw_probe,
        .remove = slave_sdw_remove,
        .ops = &slave_slave_ops,
        .id_table = slave_id,
};
```

For capabilities, Bus implements API to read standard Slave MIPI properties and also provides callback in Slave ops for Slave driver to implement own function that provides capabilities information. Bus needs to know a set of Slave capabilities to program Slave registers and to control the Bus reconfigurations.

<a id="rst-links"></a>

## Links

SoundWire MIPI specification 1.1 is available at: [https://members.mipi.org/wg/All-Members/document/70290](<https://members.mipi.org/wg/All-Members/document/70290>)

SoundWire MIPI DisCo (Discovery and Configuration) specification is available at: [https://www.mipi.org/specifications/mipi-disco-soundwire](<https://www.mipi.org/specifications/mipi-disco-soundwire>)

(publicly accessible with registration or directly accessible to MIPI members)

MIPI Alliance Manufacturer ID Page: mid.mipi.org

---

# ACPI Support

_Peios Kernel / Hardware and drivers / Driver development / ACPI_

> Reference for ACPI Support.

<a id="rst-acpi-support"></a>

- [Linuxized ACPICA - Introduction to ACPICA Release Automation](</kernel/hardware/driver-api/acpi/linuxized-acpica.md>)
- [ACPI Scan Handlers](</kernel/hardware/driver-api/acpi/scan-handlers.md>)
- [Why using ACPI drivers is not a good idea](</kernel/hardware/driver-api/acpi/acpi-drivers.md>)

---

# Why using ACPI drivers is not a good idea

_Peios Kernel / Hardware and drivers / Driver development / ACPI_

> Even though binding drivers directly to struct acpi_device objects, also referred to as "ACPI device nodes", allows basic functionality to be provided at least in some cases, there are problems with it, related to general consistency,…

<a id="rst-why-using-acpi-drivers-is-not-a-good-idea"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2026, Intel Corporation

**Author:** Rafael J. Wysocki &lt;[rafael.j.wysocki@intel.com](<mailto:rafael.j.wysocki@intel.com>)&gt;

Even though binding drivers directly to struct acpi_device objects, also referred to as "ACPI device nodes", allows basic functionality to be provided at least in some cases, there are problems with it, related to general consistency, sysfs layout, power management operation ordering, and code cleanliness.

First of all, ACPI device nodes represent firmware entities rather than hardware and in many cases they provide auxiliary information on devices enumerated independently (like PCI devices or CPUs).  It is therefore generally questionable to assign resources to them because the entities represented by them do not decode addresses in the memory or I/O address spaces and do not generate interrupts or similar (all of that is done by hardware).

Second, as a general rule, a struct acpi_device can only be a parent of another struct acpi_device.  If that is not the case, the location of the child device in the device hierarchy is at least confusing and it may not be straightforward to identify the piece of hardware providing functionality represented by it. However, binding a driver directly to an ACPI device node may cause that to happen if the given driver registers input devices or wakeup sources under it, for example.

Next, using system suspend and resume callbacks directly on ACPI device nodes is also questionable because it may cause ordering problems to appear.  Namely, ACPI device nodes are registered before enumerating hardware corresponding to them and they land on the PM list in front of the majority of other device objects.  Consequently, the execution ordering of their PM callbacks may be different from what is generally expected.  Also, in general, dependencies returned by \_DEP objects do not affect ACPI device nodes themselves, but the "physical" devices associated with them, which potentially is one more source of inconsistency related to treating ACPI device nodes as "real" device representation.

All of the above means that binding drivers to ACPI device nodes should generally be avoided and so struct acpi_driver objects should not be used.

Moreover, a device ID is necessary to bind a driver directly to an ACPI device node, but device IDs are not generally associated with all of them.  Some of them contain alternative information allowing the corresponding pieces of hardware to be identified, for example represeted by an \_ADR object return value, and device IDs are not used in those cases.  In consequence, confusingly enough, binding an ACPI driver to an ACPI device node may even be impossible.

When that happens, the piece of hardware corresponding to the given ACPI device node is represented by another device object, like a struct pci_dev, and the ACPI device node is the "ACPI companion" of that device, accessible through its fwnode pointer used by the ACPI_COMPANION() macro.  The ACPI companion holds additional information on the device configuration and possibly some "recipes" on device manipulation in the form of AML (ACPI Machine Language) bytecode provided by the platform firmware.  Thus the role of the ACPI device node is similar to the role of a struct device_node on a system where Device Tree is used for platform description.

For consistency, this approach has been extended to the cases in which ACPI device IDs are used.  Namely, in those cases, an additional device object is created to represent the piece of hardware corresponding to a given ACPI device node.  By default, it is a platform device, but it may also be a PNP device, a CPU device, or another type of device, depending on what the given piece of hardware actually is.  There are even cases in which multiple devices are "backed" or "accompanied" by one ACPI device node (e.g. ACPI device nodes corresponding to GPUs that may provide firmware interfaces for backlight brightness control in addition to GPU configuration information).

This means that it really should never be necessary to bind a driver directly to an ACPI device node because there is a "proper" device object representing the corresponding piece of hardware that can be bound to by a "proper" driver using the given ACPI device node as the device's ACPI companion.  Thus, in principle, there is no reason to use ACPI drivers and if they all were replaced with other driver types (for example, platform drivers), some code could be dropped and some complexity would go away.

---

# Linuxized ACPICA - Introduction to ACPICA Release Automation

_Peios Kernel / Hardware and drivers / Driver development / ACPI_

> This document describes the ACPICA project and the relationship between ACPICA and Linux. It also describes how ACPICA code in drivers/acpi/acpica, include/acpi and tools/power/acpi is automatically updated to follow the upstream.

<a id="rst-linuxized-acpica-introduction-to-acpica-release-automation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2013-2016, Intel Corporation

**Author:** Lv Zheng &lt;[lv.zheng@intel.com](<mailto:lv.zheng@intel.com>)&gt;

<a id="rst-abstract"></a>

## Abstract

This document describes the ACPICA project and the relationship between ACPICA and Linux.  It also describes how ACPICA code in drivers/acpi/acpica, include/acpi and tools/power/acpi is automatically updated to follow the upstream.

<a id="rst-acpica-project"></a>

## ACPICA Project

The ACPI Component Architecture (ACPICA) project provides an operating system (OS)-independent reference implementation of the Advanced Configuration and Power Interface Specification (ACPI).  It has been adapted by various host OSes.  By directly integrating ACPICA, Linux can also benefit from the application experiences of ACPICA from other host OSes.

The homepage of ACPICA project is: www.acpica.org, it is maintained and supported by Intel Corporation.

The following figure depicts the Linux ACPI subsystem where the ACPICA adaptation is included:



```text
+---------------------------------------------------------+
|                                                         |
|   +---------------------------------------------------+ |
|   | +------------------+                              | |
|   | | Table Management |                              | |
|   | +------------------+                              | |
|   | +----------------------+                          | |
|   | | Namespace Management |                          | |
|   | +----------------------+                          | |
|   | +------------------+       ACPICA Components      | |
|   | | Event Management |                              | |
|   | +------------------+                              | |
|   | +---------------------+                           | |
|   | | Resource Management |                           | |
|   | +---------------------+                           | |
|   | +---------------------+                           | |
|   | | Hardware Management |                           | |
|   | +---------------------+                           | |
| +---------------------------------------------------+ | |
| | |                            +------------------+ | | |
| | |                            | OS Service Layer | | | |
| | |                            +------------------+ | | |
| | +-------------------------------------------------|-+ |
| |   +--------------------+                          |   |
| |   | Device Enumeration |                          |   |
| |   +--------------------+                          |   |
| |   +------------------+                            |   |
| |   | Power Management |                            |   |
| |   +------------------+     Linux/ACPI Components  |   |
| |   +--------------------+                          |   |
| |   | Thermal Management |                          |   |
| |   +--------------------+                          |   |
| |   +--------------------------+                    |   |
| |   | Drivers for ACPI Devices |                    |   |
| |   +--------------------------+                    |   |
| |   +--------+                                      |   |
| |   | ...... |                                      |   |
| |   +--------+                                      |   |
| +---------------------------------------------------+   |
|                                                         |
+---------------------------------------------------------+

           Figure 1. Linux ACPI Software Components
```

> [!NOTE]
>
> - **A.** OS Service Layer - Provided by Linux to offer OS dependent implementation of the predefined ACPICA interfaces (acpi_os\_\*).
>
>
>
>   ```text
>   include/acpi/acpiosxf.h
>   drivers/acpi/osl.c
>   include/acpi/platform
>   include/asm/acenv.h
>   ```
>
> - **B.** ACPICA Functionality - Released from ACPICA code base to offer OS independent implementation of the ACPICA interfaces (acpi\_\*).
>
>
>
>   ```text
>   drivers/acpi/acpica
>   include/acpi/ac*.h
>   tools/power/acpi
>   ```
>
> - **C.** Linux/ACPI Functionality - Providing Linux specific ACPI functionality to the other Linux kernel subsystems and user space programs.
>
>
>
>   ```text
>   drivers/acpi
>   include/linux/acpi.h
>   include/linux/acpi*.h
>   include/acpi
>   tools/power/acpi
>   ```
>
> - **D.** Architecture Specific ACPICA/ACPI Functionalities - Provided by the ACPI subsystem to offer architecture specific implementation of the ACPI interfaces.  They are Linux specific components and are out of the scope of this document.
>
>
>
>   ```text
>   include/asm/acpi.h
>   include/asm/acpi*.h
>   arch/*/acpi
>   ```

<a id="rst-acpica-release"></a>

## ACPICA Release

The ACPICA project maintains its code base at the following repository URL: [https://github.com/acpica/acpica.git](<https://github.com/acpica/acpica.git>). As a rule, a release is made every month.

As the coding style adopted by the ACPICA project is not acceptable by Linux, there is a release process to convert the ACPICA git commits into Linux patches.  The patches generated by this process are referred to as "linuxized ACPICA patches".  The release process is carried out on a local copy the ACPICA git repository.  Each commit in the monthly release is converted into a linuxized ACPICA patch.  Together, they form the monthly ACPICA release patchset for the Linux ACPI community.  This process is illustrated in the following figure:



```text
+-----------------------------+
| acpica / master (-) commits |
+-----------------------------+
   /|\         |
    |         \|/
    |  /---------------------\    +----------------------+
    | < Linuxize repo Utility >-->| old linuxized acpica |--+
    |  \---------------------/    +----------------------+  |
    |                                                       |
 /---------\                                                |
< git reset >                                                \
 \---------/                                                  \
   /|\                                                        /+-+
    |                                                        /   |
+-----------------------------+                             |    |
| acpica / master (+) commits |                             |    |
+-----------------------------+                             |    |
               |                                            |    |
              \|/                                           |    |
     /-----------------------\    +----------------------+  |    |
    < Linuxize repo Utilities >-->| new linuxized acpica |--+    |
     \-----------------------/    +----------------------+       |
                                                                \|/
+--------------------------+                  /----------------------\
| Linuxized ACPICA Patches |<----------------< Linuxize patch Utility >
+--------------------------+                  \----------------------/
               |
              \|/
 /---------------------------\
< Linux ACPI Community Review >
 \---------------------------/
               |
              \|/
+-----------------------+    /------------------\    +----------------+
| linux-pm / linux-next |-->< Linux Merge Window >-->| linux / master |
+-----------------------+    \------------------/    +----------------+

            Figure 2. ACPICA -> Linux Upstream Process
```

> [!NOTE]
>
> > - **A.** Linuxize Utilities - Provided by the ACPICA repository, including a utility located in source/tools/acpisrc folder and a number of scripts located in generate/linux folder.
> >
> > - **B.** acpica / master - "master" branch of the git repository at &lt;[https://github.com/acpica/acpica.git](<https://github.com/acpica/acpica.git>)&gt;.
> >
> > - **C.** linux-pm / linux-next - "linux-next" branch of the git repository at &lt;[https://git.kernel.org/pub/scm/linux/kernel/git/rafael/linux-pm.git](<https://git.kernel.org/pub/scm/linux/kernel/git/rafael/linux-pm.git>)&gt;.
> >
> > - **D.** linux / master - "master" branch of the git repository at &lt;[https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git>)&gt;.
>
> Before the linuxized ACPICA patches are sent to the Linux ACPI community for review, there is a quality assurance build test process to reduce porting issues.  Currently this build process only takes care of the following kernel configuration options: CONFIG_ACPI/CONFIG_ACPI_DEBUG/CONFIG_ACPI_DEBUGGER

<a id="rst-acpica-divergences"></a>

## ACPICA Divergences

Ideally, all of the ACPICA commits should be converted into Linux patches automatically without manual modifications, the "linux / master" tree should contain the ACPICA code that exactly corresponds to the ACPICA code contained in "new linuxized acpica" tree and it should be possible to run the release process fully automatically.

As a matter of fact, however, there are source code differences between the ACPICA code in Linux and the upstream ACPICA code, referred to as "ACPICA Divergences".

- **The various sources of ACPICA divergences include:**

  1. Legacy divergences - Before the current ACPICA release process was established, there already had been divergences between Linux and ACPICA. Over the past several years those divergences have been greatly reduced, but there still are several ones and it takes time to figure out the underlying reasons for their existence.

  2. Manual modifications - Any manual modification (eg. coding style fixes) made directly in the Linux sources obviously hurts the ACPICA release automation.  Thus it is recommended to fix such issues in the ACPICA upstream source code and generate the linuxized fix using the ACPICA release utilities (please refer to Section 4 below for the details).

  3. Linux specific features - Sometimes it's impossible to use the current ACPICA APIs to implement features required by the Linux kernel, so Linux developers occasionally have to change ACPICA code directly. Those changes may not be acceptable by ACPICA upstream and in such cases they are left as committed ACPICA divergences unless the ACPICA side can implement new mechanisms as replacements for them.

  4. ACPICA release fixups - ACPICA only tests commits using a set of the user space simulation utilities, thus the linuxized ACPICA patches may break the Linux kernel, leaving us build/boot failures.  In order to avoid breaking Linux bisection, fixes are applied directly to the linuxized ACPICA patches during the release process.  When the release fixups are backported to the upstream ACPICA sources, they must follow the upstream ACPICA rules and so further modifications may appear. That may result in the appearance of new divergences.

  5. Fast tracking of ACPICA commits - Some ACPICA commits are regression fixes or stable-candidate material, so they are applied in advance with respect to the ACPICA release process.  If such commits are reverted or rebased on the ACPICA side in order to offer better solutions, new ACPICA divergences are generated.

<a id="rst-acpica-development"></a>

## ACPICA Development

This paragraph guides Linux developers to use the ACPICA upstream release utilities to obtain Linux patches corresponding to upstream ACPICA commits before they become available from the ACPICA release process.

> 1. Cherry-pick an ACPICA commit
>
> First you need to git clone the ACPICA repository and the ACPICA change you want to cherry pick must be committed into the local repository.
>
> Then the gen-patch.sh command can help to cherry-pick an ACPICA commit from the ACPICA local repository:
>
>
>
> ```text
> $ git clone https://github.com/acpica/acpica
> $ cd acpica
> $ generate/linux/gen-patch.sh -u [commit ID]
> ```
>
> Here the commit ID is the ACPICA local repository commit ID you want to cherry pick.  It can be omitted if the commit is "HEAD".
>
> 2. Cherry-pick recent ACPICA commits
>
> Sometimes you need to rebase your code on top of the most recent ACPICA changes that haven't been applied to Linux yet.
>
> You can generate the ACPICA release series yourself and rebase your code on top of the generated ACPICA release patches:
>
>
>
> ```text
> $ git clone https://github.com/acpica/acpica
> $ cd acpica
> $ generate/linux/make-patches.sh -u [commit ID]
> ```
>
> The commit ID should be the last ACPICA commit accepted by Linux.  Usually, it is the commit modifying ACPI_CA_VERSION.  It can be found by executing "git blame source/include/acpixf.h" and referencing the line that contains "ACPI_CA_VERSION".
>
> 3. Inspect the current divergences
>
> If you have local copies of both Linux and upstream ACPICA, you can generate a diff file indicating the state of the current divergences:
>
>
>
> ```text
> # git clone https://github.com/acpica/acpica
> # git clone https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
> # cd acpica
> # generate/linux/divergence.sh -s ../linux
> ```

---

# ACPI Scan Handlers

_Peios Kernel / Hardware and drivers / Driver development / ACPI_

> During system initialization and ACPI-based device hot-add, the ACPI namespace is scanned in search of device objects that generally represent various pieces of hardware. This causes a struct acpi_device object to be created and registered…

<a id="rst-acpi-scan-handlers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2012, Intel Corporation

**Author:** Rafael J. Wysocki &lt;[rafael.j.wysocki@intel.com](<mailto:rafael.j.wysocki@intel.com>)&gt;

During system initialization and ACPI-based device hot-add, the ACPI namespace is scanned in search of device objects that generally represent various pieces of hardware.  This causes a struct acpi_device object to be created and registered with the driver core for every device object in the ACPI namespace and the hierarchy of those struct acpi_device objects reflects the namespace layout (i.e. parent device objects in the namespace are represented by parent struct acpi_device objects and analogously for their children).  Those struct acpi_device objects are referred to as "device nodes" in what follows, but they should not be confused with struct device_node objects used by the Device Trees parsing code (although their role is analogous to the role of those objects).

During ACPI-based device hot-remove device nodes representing pieces of hardware being removed are unregistered and deleted.

The core ACPI namespace scanning code in drivers/acpi/scan.c carries out basic initialization of device nodes, such as retrieving common configuration information from the device objects represented by them and populating them with appropriate data, but some of them require additional handling after they have been registered.  For example, if the given device node represents a PCI host bridge, its registration should cause the PCI bus under that bridge to be enumerated and PCI devices on that bus to be registered with the driver core. Similarly, if the device node represents a PCI interrupt link, it is necessary to configure that link so that the kernel can use it.

Those additional configuration tasks usually depend on the type of the hardware component represented by the given device node which can be determined on the basis of the device node's hardware ID (HID).  They are performed by objects called ACPI scan handlers represented by the following structure:



```text
struct acpi_scan_handler {
        const struct acpi_device_id *ids;
        struct list_head list_node;
        int (*attach)(struct acpi_device *dev, const struct acpi_device_id *id);
        void (*detach)(struct acpi_device *dev);
};
```

where ids is the list of IDs of device nodes the given handler is supposed to take care of, list_node is the hook to the global list of ACPI scan handlers maintained by the ACPI core and the .attach() and .detach() callbacks are executed, respectively, after registration of new device nodes and before unregistration of device nodes the handler attached to previously.

The namespace scanning function, acpi_bus_scan(), first registers all of the device nodes in the given namespace scope with the driver core.  Then, it tries to match a scan handler against each of them using the ids arrays of the available scan handlers.  If a matching scan handler is found, its .attach() callback is executed for the given device node.  If that callback returns 1, that means that the handler has claimed the device node and is now responsible for carrying out any additional configuration tasks related to it.  It also will be responsible for preparing the device node for unregistration in that case. The device node's handler field is then populated with the address of the scan handler that has claimed it.

If the .attach() callback returns 0, it means that the device node is not interesting to the given scan handler and may be matched against the next scan handler in the list.  If it returns a (negative) error code, that means that the namespace scan should be terminated due to a serious error.  The error code returned should then reflect the type of the error.

The namespace trimming function, acpi_bus_trim(), first executes .detach() callbacks from the scan handlers of all device nodes in the given namespace scope (if they have scan handlers).  Next, it unregisters all of the device nodes in that scope.

ACPI scan handlers can be added to the list maintained by the ACPI core with the help of the acpi_scan_add_handler() function taking a pointer to the new scan handler as an argument.  The order in which scan handlers are added to the list is the order in which they are matched against device nodes during namespace scans.

All scan handles must be added to the list before acpi_bus_scan() is run for the first time and they cannot be removed from it.

---

# Confidential Computing

_Peios Kernel / Hardware and drivers / Driver development / Confidential computing_

> Reference for Confidential Computing.

<a id="rst-confidential-computing"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Measurement Registers](</kernel/hardware/driver-api/coco/measurement-registers.md>)

---

# Measurement Registers

_Peios Kernel / Hardware and drivers / Driver development / Confidential computing_

> Reference for Measurement Registers.

<a id="rst-measurement-registers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->


#### <a id="c-struct-tsm_measurement_register"></a>`struct tsm_measurement_register`

describes an architectural measurement register (MR)

**Definition**

```c
struct tsm_measurement_register {
    const char *mr_name;
    void *mr_value;
    u32 mr_size;
    u32 mr_flags;
    enum hash_algo mr_hash;
};
```

**Members**

- `mr_name`: name of the MR
- `mr_value`: buffer containing the current value of the MR
- `mr_size`: size of the MR - typically the digest size of **mr_hash**
- `mr_flags`: bitwise OR of one or more flags, detailed below
- `mr_hash`: optional hash identifier defined in include/uapi/linux/hash_info.h.

**Description**

A CC guest driver encloses an array of this structure in struct
tsm_measurements to detail the measurement facility supported by the
underlying CC hardware.

**mr_name** and **mr_value** must stay valid until this structure is no longer in
use.

**mr_flags** is the bitwise-OR of zero or more of the flags below.

* `TSM_MR_F_READABLE` - the sysfs attribute corresponding to this MR is readable.
* `TSM_MR_F_WRITABLE` - the sysfs attribute corresponding to this MR is writable.
  The semantics is typically to extend the MR but could vary depending on the
  architecture and the MR.
* `TSM_MR_F_LIVE` - this MR's value may differ from the last value written, so
  must be read back from the underlying CC hardware/firmware.
* `TSM_MR_F_RTMR` - bitwise-OR of `TSM_MR_F_LIVE` and `TSM_MR_F_WRITABLE`.
* `TSM_MR_F_NOHASH` - this MR does NOT have an associated hash algorithm.
  **mr_hash** will be ignored when this flag is set.

#### <a id="c-struct-tsm_measurements"></a>`struct tsm_measurements`

defines the CC architecture specific measurement facility and methods for updating measurement registers (MRs)

**Definition**

```c
struct tsm_measurements {
    const struct tsm_measurement_register *mrs;
    size_t nr_mrs;
    int (*refresh)(const struct tsm_measurements *tm);
    int (*write)(const struct tsm_measurements *tm, const struct tsm_measurement_register *mr, const u8 *data);
};
```

**Members**

- `mrs`: Array of MR definitions.
- `nr_mrs`: Number of elements in **mrs**.
- `refresh`: Callback function to load/sync all MRs from TVM hardware/firmware
  into the kernel cache.
- `write`: Callback function to write to the MR specified by the parameter **mr**.
  Typically, writing to an MR extends the input buffer to that MR.

**Description**

The **refresh** callback is invoked when an MR with `TSM_MR_F_LIVE` set is being
read and the cache is stale. It must reload all MRs with `TSM_MR_F_LIVE` set.
The function parameter **tm** is a pointer pointing back to this structure.

The **write** callback is invoked whenever an MR is being written. It takes two
additional parameters besides **tm**:

* **mr** - points to the MR (an element of **tm->mrs**) being written.
* **data** - contains the bytes to write and whose size is **mr->mr_size**.

Both **refresh** and **write** should return 0 on success and an appropriate error
code on failure.



#### <a id="c-tsm_mr_create_attribute_group"></a>`tsm_mr_create_attribute_group()`

```c
const struct attribute_group * tsm_mr_create_attribute_group(const struct tsm_measurements *tm)
```

creates an attribute group for measurement registers (MRs)

**Parameters**

- `const struct tsm_measurements *tm`: pointer to [`struct tsm_measurements`](#c-struct-tsm_measurements) containing the MR definitions.

**Description**

This function creates attributes corresponding to the MR definitions
provided by **tm->mrs**.

The created attributes will reference **tm** and its members. The caller must
not free **tm** until after [`tsm_mr_free_attribute_group()`](#c-tsm_mr_free_attribute_group) is called.

**Context**

Process context. May sleep due to memory allocation.

**Return**

* On success, the pointer to a an attribute group is returned; otherwise
* `-EINVAL` - Invalid MR definitions.
* `-ENOMEM` - Out of memory.

#### <a id="c-tsm_mr_free_attribute_group"></a>`tsm_mr_free_attribute_group()`

```c
void tsm_mr_free_attribute_group(const struct attribute_group *attr_grp)
```

frees the attribute group returned by [`tsm_mr_create_attribute_group()`](#c-tsm_mr_create_attribute_group)

**Parameters**

- `const struct attribute_group *attr_grp`: attribute group returned by [`tsm_mr_create_attribute_group()`](#c-tsm_mr_create_attribute_group)

**Context**

Process context.

---

# Linux Firmware API

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> Reference for Linux Firmware API.

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-linux-firmware-api"></a>

- [Introduction](</kernel/hardware/driver-api/firmware/introduction.md>)
- [Firmware API core features](</kernel/hardware/driver-api/firmware/core.md>)
- [Unified Extensible Firmware Interface (UEFI) Support](</kernel/hardware/driver-api/firmware-efi/index.md>)
- [request_firmware API](</kernel/hardware/driver-api/firmware/request-firmware.md>)
- [Firmware Upload API](</kernel/hardware/driver-api/firmware/fw-upload.md>)
- [Other Firmware Interfaces](</kernel/hardware/driver-api/firmware/other-interfaces.md>)

---

# Built-in firmware

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> Firmware can be built-in to the kernel, this means building the firmware into vmlinux directly, to enable avoiding having to look for firmware from the filesystem. Instead, firmware can be looked for inside the kernel directly. You can…

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-built-in-firmware"></a>

Firmware can be built-in to the kernel, this means building the firmware into vmlinux directly, to enable avoiding having to look for firmware from the filesystem. Instead, firmware can be looked for inside the kernel directly. You can enable built-in firmware using the kernel configuration options:

> - CONFIG_EXTRA_FIRMWARE
>
> - CONFIG_EXTRA_FIRMWARE_DIR

There are a few reasons why you might want to consider building your firmware into the kernel with CONFIG_EXTRA_FIRMWARE:

- Speed

- Firmware is needed for accessing the boot device, and the user doesn't want to stuff the firmware into the boot initramfs.

Even if you have these needs there are a few reasons why you may not be able to make use of built-in firmware:

- Legalese - firmware is non-GPL compatible

- Some firmware may be optional

- Firmware upgrades are possible, therefore a new firmware would implicate a complete kernel rebuild.

- Some firmware files may be really large in size. The remote-proc subsystem is an example subsystem which deals with these sorts of firmware

- The firmware may need to be scraped out from some device specific location dynamically, an example is calibration data for some WiFi chipsets. This calibration data can be unique per sold device.

---

# Firmware API core features

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> The firmware API has a rich set of core features available. This section documents these features.

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-firmware-api-core-features"></a>

The firmware API has a rich set of core features available. This section documents these features.

- [Firmware search paths](</kernel/hardware/driver-api/firmware/fw-search-path.md>)
- [Built-in firmware](</kernel/hardware/driver-api/firmware/built-in-fw.md>)
- [Firmware cache](</kernel/hardware/driver-api/firmware/firmware-cache.md>)
- [Direct filesystem lookup](</kernel/hardware/driver-api/firmware/direct-fs-lookup.md>)
- [Fallback mechanisms](</kernel/hardware/driver-api/firmware/fallback-mechanisms.md>)
- [Firmware lookup order](</kernel/hardware/driver-api/firmware/lookup-order.md>)
- [Firmware Guidelines](</kernel/hardware/driver-api/firmware/firmware-usage-guidelines.md>)

---

# Direct filesystem lookup

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> Direct filesystem lookup is the most common form of firmware lookup performed by the kernel. The kernel looks for the firmware directly on the root filesystem in the paths documented in the section 'Firmware search paths'. The filesystem…

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-direct-filesystem-lookup"></a>

Direct filesystem lookup is the most common form of firmware lookup performed by the kernel. The kernel looks for the firmware directly on the root filesystem in the paths documented in the section 'Firmware search paths'. The filesystem lookup is implemented in fw_get_filesystem_firmware(), it uses common core kernel file loader facility kernel_read_file_from_path(). The max path allowed is PATH_MAX -- currently this is 4096 characters.

It is recommended you keep /lib/firmware paths on your root filesystem, avoid having a separate partition for them in order to avoid possible races with lookups and avoid uses of the custom fallback mechanisms documented below.

<a id="rst-firmware-and-initramfs"></a>

## Firmware and initramfs

Drivers which are built-in to the kernel should have the firmware integrated also as part of the initramfs used to boot the kernel given that otherwise a race is possible with loading the driver and the real rootfs not yet being available. Stuffing the firmware into initramfs resolves this race issue, however note that using initrd does not suffice to address the same race.

There are circumstances that justify not wanting to include firmware into initramfs, such as dealing with large firmware files for the remote-proc subsystem. For such cases using a userspace fallback mechanism is currently the only viable solution as only userspace can know for sure when the real rootfs is ready and mounted.

---

# Fallback mechanisms

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> Optional upstream firmware-request fallback mechanisms, disabled in the configured Peios build.

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-fallback-mechanisms"></a>

The Peios base configuration disables `CONFIG_FW_LOADER_USER_HELPER`, so the sysfs firmware-request fallback described below is not enabled in the configured build. The separate device firmware-upload facility (`FW_UPLOAD`) can still be enabled.

The fallback is an optional upstream mechanism for failed filesystem lookups or firmware that cannot be installed on the root filesystem. Its configuration options are:

> - CONFIG_FW_LOADER_USER_HELPER: enables building the firmware fallback mechanism. If enabled but CONFIG_FW_LOADER_USER_HELPER_FALLBACK is disabled, only the custom fallback mechanism is available and for the request_firmware_nowait() call.
>
> - CONFIG_FW_LOADER_USER_HELPER_FALLBACK: force enables each request to enable the kobject uevent fallback mechanism on all firmware API calls except request_firmware_direct(). The call request_firmware_nowait() allows for one alternative fallback mechanism: if this kconfig option is enabled and your second argument to request_firmware_nowait(), uevent, is set to false you are informing the kernel that you have a custom fallback mechanism and it will manually load the firmware. Read below for more details.

Note that this means when having this configuration:

CONFIG_FW_LOADER_USER_HELPER=y CONFIG_FW_LOADER_USER_HELPER_FALLBACK=n

the kobject uevent fallback mechanism will never take effect even for request_firmware_nowait() when uevent is set to true.

<a id="rst-justifying-the-firmware-fallback-mechanism"></a>

## Justifying the firmware fallback mechanism

Direct filesystem lookups may fail for a variety of reasons. Known reasons for this are worth itemizing and documenting as it justifies the need for the fallback mechanism:

- Race against access with the root filesystem upon bootup.

- Races upon resume from suspend. This is resolved by the firmware cache, but the firmware cache is only supported if you use uevents, and its not supported for request_firmware_into_buf().

- Firmware is not accessible through typical means:

  > - It cannot be installed into the root filesystem
  >
  > - The firmware provides very unique device specific data tailored for the unit gathered with local information. An example is calibration data for WiFi chipsets for mobile devices. This calibration data is not common to all units, but tailored per unit.  Such information may be installed on a separate flash partition other than where the root filesystem is provided.

<a id="rst-types-of-fallback-mechanisms"></a>

## Types of fallback mechanisms

There are really two fallback mechanisms available using one shared sysfs interface as a loading facility:

- Kobject uevent fallback mechanism

- Custom fallback mechanism

First lets document the shared sysfs loading facility.

<a id="rst-firmware-sysfs-loading-facility"></a>

## Firmware sysfs loading facility

In order to help device drivers upload firmware using a fallback mechanism the firmware infrastructure creates a sysfs interface to enable userspace to load and indicate when firmware is ready. The sysfs directory is created via fw_create_instance(). This call creates a new struct device named after the firmware requested, and establishes it in the device hierarchy by associating the device used to make the request as the device's parent. The sysfs directory's file attributes are defined and controlled through the new device's class (firmware_class) and group (fw_dev_attr_groups). This is actually where the original firmware_class module name came from, given that originally the only firmware loading mechanism available was the mechanism we now use as a fallback mechanism, which registers a struct class firmware_class. Because the attributes exposed are part of the module name, the module name firmware_class cannot be renamed in the future, to ensure backward compatibility with old userspace.

To load firmware using the sysfs interface we expose a loading indicator, and a file upload firmware into:

> - /sys/$DEVPATH/loading
>
> - /sys/$DEVPATH/data

To upload firmware you will echo 1 onto the loading file to indicate you are loading firmware. You then write the firmware into the data file, and you notify the kernel the firmware is ready by echo'ing 0 onto the loading file.

The firmware device used to help load firmware using sysfs is only created if direct firmware loading fails and if the fallback mechanism is enabled for your firmware request, this is set up with `firmware_fallback_sysfs()`. It is important to re-iterate that no device is created if a direct filesystem lookup succeeded.

Using:



```text
echo 1 > /sys/$DEVPATH/loading
```

This discards any previous partial load and starts a fresh loading attempt. Writing `0` completes a load; writing `-1` aborts it. When loading firmware the firmware_class grows a buffer for the firmware in PAGE_SIZE increments to hold the image as it comes in.

firmware_data_read() and firmware_loading_show() are just provided for the test_firmware driver for testing, they are not called in normal use or expected to be used regularly by userspace.

<a id="rst-firmware-fallback-sysfs"></a>

### firmware_fallback_sysfs


#### <a id="c-firmware_fallback_sysfs"></a>`firmware_fallback_sysfs()`

```c
int firmware_fallback_sysfs(struct firmware *fw, const char *name, struct device *device, u32 opt_flags, int ret)
```

use the fallback mechanism to find firmware

**Parameters**

- `struct firmware *fw`: pointer to firmware image
- `const char *name`: name of firmware file to look for
- `struct device *device`: device for which firmware is being loaded
- `u32 opt_flags`: options to control firmware loading behaviour, as defined by
  `enum fw_opt`
- `int ret`: return value from direct lookup which triggered the fallback mechanism

**Description**

This function is called if direct lookup for the firmware failed, it enables
a fallback mechanism through userspace by exposing a sysfs loading
interface. Userspace is in charge of loading the firmware through the sysfs
loading interface. This sysfs fallback mechanism may be disabled completely
on a system by setting the proc sysctl value ignore_sysfs_fallback to true.
If this is false we check if the internal API caller set the
**FW_OPT_NOFALLBACK_SYSFS** flag, if so it would also disable the fallback
mechanism. A system may want to enforce the sysfs fallback mechanism at all
times, it can do this by setting ignore_sysfs_fallback to false and
force_sysfs_fallback to true.
Enabling force_sysfs_fallback is functionally equivalent to build a kernel
with CONFIG_FW_LOADER_USER_HELPER_FALLBACK.


<a id="rst-firmware-kobject-uevent-fallback-mechanism"></a>

## Firmware kobject uevent fallback mechanism

Since a device is created for the sysfs interface to help load firmware as a fallback mechanism userspace can be informed of the addition of the device by relying on kobject uevents. The addition of the device into the device hierarchy means the fallback mechanism for firmware loading has been initiated. For details of implementation refer to fw_load_sysfs_fallback(), in particular on the use of dev_set_uevent_suppress() and kobject_uevent().

The kernel's kobject uevent mechanism is implemented in lib/kobject_uevent.c, it issues uevents to userspace. As a supplement to kobject uevents Linux distributions could also enable CONFIG_UEVENT_HELPER_PATH, which makes use of core kernel's usermode helper (UMH) functionality to call out to a userspace helper for kobject uevents. In practice though no standard distribution has ever used the CONFIG_UEVENT_HELPER_PATH. If CONFIG_UEVENT_HELPER_PATH is enabled this binary would be called each time kobject_uevent_env() gets called in the kernel for each kobject uevent triggered.

Different implementations have been supported in userspace to take advantage of this fallback mechanism. When firmware loading was only possible using the sysfs mechanism the userspace component "hotplug" provided the functionality of monitoring for kobject events. Historically this was superseded be systemd's udev, however firmware loading support was removed from udev as of systemd commit be2ea723b1d0 ("udev: remove userspace firmware loading support") as of v217 on August, 2014. This means most Linux distributions today are not using or taking advantage of the firmware fallback mechanism provided by kobject uevents. This is specially exacerbated due to the fact that most distributions today disable CONFIG_FW_LOADER_USER_HELPER_FALLBACK.

Refer to do_firmware_uevent() for details of the kobject event variables setup. The variables currently passed to userspace with a "kobject add" event are:

- FIRMWARE=firmware name

- TIMEOUT=timeout value

- ASYNC=whether or not the API request was asynchronous

By default DEVPATH is set by the internal kernel kobject infrastructure. Below is an example simple kobject uevent script:



```text
# Both $DEVPATH and $FIRMWARE are already provided in the environment.
MY_FW_DIR=/lib/firmware/
echo 1 > /sys/$DEVPATH/loading
cat $MY_FW_DIR/$FIRMWARE > /sys/$DEVPATH/data
echo 0 > /sys/$DEVPATH/loading
```

<a id="rst-firmware-custom-fallback-mechanism"></a>

## Firmware custom fallback mechanism

Users of the request_firmware_nowait() call have yet another option available at their disposal: rely on the sysfs fallback mechanism but request that no kobject uevents be issued to userspace. The original logic behind this was that utilities other than udev might be required to lookup firmware in non-traditional paths -- paths outside of the listing documented in the section 'Direct filesystem lookup'. This option is not available to any of the other API calls as uevents are always forced for them.

Since uevents are only meaningful if the fallback mechanism is enabled in your kernel it would seem odd to enable uevents with kernels that do not have the fallback mechanism enabled in their kernels. Unfortunately we also rely on the uevent flag which can be disabled by request_firmware_nowait() to also setup the firmware cache for firmware requests. As documented above, the firmware cache is only set up if uevent is enabled for an API call. Although this can disable the firmware cache for request_firmware_nowait() calls, users of this API should not use it for the purposes of disabling the cache as that was not the original purpose of the flag. Not setting the uevent flag means you want to opt-in for the firmware fallback mechanism but you want to suppress kobject uevents, as you have a custom solution which will monitor for your device addition into the device hierarchy somehow and load firmware for you through a custom path.

<a id="rst-firmware-fallback-timeout"></a>

## Firmware fallback timeout

The firmware fallback mechanism has a timeout. If firmware is not loaded onto the sysfs interface by the timeout value an error is sent to the driver. By default the timeout is set to 60 seconds if uevents are desirable, otherwise MAX_JIFFY_OFFSET is used (max timeout possible). The logic behind using MAX_JIFFY_OFFSET for non-uevents is that a custom solution will have as much time as it needs to load firmware.

You can customize the firmware timeout by echo'ing your desired timeout into the following file:

- /sys/class/firmware/timeout

If you echo 0 into it means MAX_JIFFY_OFFSET will be used. The data type for the timeout is an int.

<a id="rst-efi-embedded-firmware-fallback-mechanism"></a>

## EFI embedded firmware fallback mechanism

On some devices the system's EFI code / ROM may contain an embedded copy of firmware for some of the system's integrated peripheral devices and the peripheral's Linux device-driver needs to access this firmware.

Device drivers which need such firmware can use the firmware_request_platform() function for this, note that this is a separate fallback mechanism from the other fallback mechanisms and this does not use the sysfs interface.

A device driver which needs this can describe the firmware it needs using an efi_embedded_fw_desc struct:


#### <a id="c-struct-efi_embedded_fw_desc"></a>`struct efi_embedded_fw_desc`

This struct is used by the EFI embedded-fw code to search for embedded firmwares.

**Definition**

```c
struct efi_embedded_fw_desc {
    const char *name;
    u8 prefix[EFI_EMBEDDED_FW_PREFIX_LEN];
    u32 length;
    u8 sha256[32];
};
```

**Members**

- `name`: Name to register the firmware with if found
- `prefix`: First 8 bytes of the firmware
- `length`: Length of the firmware in bytes including prefix
- `sha256`: SHA256 of the firmware


The EFI embedded-fw code works by scanning all EFI_BOOT_SERVICES_CODE memory segments for an eight byte sequence matching prefix; if the prefix is found it then does a sha256 over length bytes and if that matches makes a copy of length bytes and adds that to its list with found firmwares.

To avoid doing this somewhat expensive scan on all systems, dmi matching is used. Drivers are expected to export a dmi_system_id array, with each entries' driver_data pointing to an efi_embedded_fw_desc.

To register this array with the efi-embedded-fw code, a driver needs to:

1. Always be builtin to the kernel or store the dmi_system_id array in a separate object file which always gets builtin.

2. Add an extern declaration for the dmi_system_id array to include/linux/efi_embedded_fw.h.

3. Add the dmi_system_id array to the embedded_fw_table in drivers/firmware/efi/embedded-firmware.c wrapped in a \#ifdef testing that the driver is being builtin.

4. Add "select EFI_EMBEDDED_FIRMWARE if EFI_STUB" to its Kconfig entry.

The firmware_request_platform() function will always first try to load firmware with the specified name directly from the disk, so the EFI embedded-fw can always be overridden by placing a file under /lib/firmware.

Note that:

1. The code scanning for EFI embedded-firmware runs near the end of start_kernel(), just before calling rest_init(). For normal drivers and subsystems using subsys_initcall() to register themselves this does not matter. This means that code running earlier cannot use EFI embedded-firmware.

2. At the moment the EFI embedded-fw code assumes that firmwares always start at an offset which is a multiple of 8 bytes, if this is not true for your case send in a patch to fix this.

3. At the moment the EFI embedded-fw code only works on x86 because other archs free EFI_BOOT_SERVICES_CODE before the EFI embedded-fw code gets a chance to scan it.

4. The current brute-force scanning of EFI_BOOT_SERVICES_CODE is an ad-hoc brute-force solution. There has been discussion to use the UEFI Platform Initialization (PI) spec's Firmware Volume protocol. This has been rejected because the FV Protocol relies on *internal* interfaces of the PI spec, and: 1. The PI spec does not define peripheral firmware at all 2. The internal interfaces of the PI spec do not guarantee any backward compatibility. Any implementation details in FV may be subject to change, and may vary system to system. Supporting the FV Protocol would be difficult as it is purposely ambiguous.

<a id="rst-example-how-to-check-for-and-extract-embedded-firmware"></a>

### Example how to check for and extract embedded firmware

To check for, for example Silead touchscreen controller embedded firmware, do the following:

1. Boot the system with efi=debug on the kernel commandline

2. cp /sys/kernel/debug/efi/boot_services_code? to your home dir

3. Open the boot_services_code? files in a hex-editor, search for the magic prefix for Silead firmware: F0 00 00 00 02 00 00 00, this gives you the beginning address of the firmware inside the boot_services_code? file.

4. The firmware has a specific pattern, it starts with a 8 byte page-address, typically F0 00 00 00 02 00 00 00 for the first page followed by 32-bit word-address + 32-bit value pairs. With the word-address incrementing 4 bytes (1 word) for each pair until a page is complete. A complete page is followed by a new page-address, followed by more word + value pairs. This leads to a very distinct pattern. Scroll down until this pattern stops, this gives you the end of the firmware inside the boot_services_code? file.

5. "dd if=boot_services_code? of=firmware bs=1 skip=&lt;begin-addr&gt; count=&lt;len&gt;" will extract the firmware for you. Inspect the firmware file in a hexeditor to make sure you got the dd parameters correct.

6. Copy it to /lib/firmware under the expected name to test it.

7. If the extracted firmware works, you can use the found info to fill an efi_embedded_fw_desc struct to describe it, run "sha256sum firmware" to get the sha256sum to put in the sha256 field.

---

# Firmware Guidelines

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> Users switching to a newer kernel should not have to install newer firmware files to keep their hardware working. At the same time updated firmware files must not cause any regressions for users of older kernel releases.

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-firmware-guidelines"></a>

Users switching to a newer kernel should *not* have to install newer firmware files to keep their hardware working. At the same time updated firmware files must not cause any regressions for users of older kernel releases.

Drivers that use firmware from linux-firmware should follow the rules in this guide. (Where there is limited control of the firmware, i.e. company doesn't support Linux, firmwares sourced from misc places, then of course these rules will not apply strictly.)

- Firmware files shall be designed in a way that it allows checking for firmware ABI version changes. It is recommended that firmware files be versioned with at least a major/minor version. It is suggested that the firmware files in linux-firmware be named with some device specific name, and just the major version. The firmware version should be stored in the firmware header, or as an exception, as part of the firmware file name, in order to let the driver detact any non-ABI fixes/changes. The firmware files in linux-firmware should be overwritten with the newest compatible major version. Newer major version firmware shall remain compatible with all kernels that load that major number.

- If the kernel support for the hardware is normally inactive, or the hardware isn't available for public consumption, this can be ignored, until the first kernel release that enables that hardware. This means no major version bumps without the kernel retaining backwards compatibility for the older major versions.  Minor version bumps should not introduce new features that newer kernels depend on non-optionally.

- If a security fix needs lockstep firmware and kernel fixes in order to be successful, then all supported major versions in the linux-firmware repo that are required by currently supported stable/LTS kernels, should be updated with the security fix. The kernel patches should detect if the firmware is new enough to declare if the security issue is fixed.  All communications around security fixes should point at both the firmware and kernel fixes. If a security fix requires deprecating old major versions, then this should only be done as a last option, and be stated clearly in all communications.

- Firmware files that affect the User API (UAPI) shall not introduce changes that break existing userspace programs. Updates to such firmware must ensure backward compatibility with existing userspace applications. This includes maintaining consistent interfaces and behaviors that userspace programs rely on.

---

# Firmware cache

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> When Linux resumes from suspend some device drivers require firmware lookups to re-initialize devices. During resume there may be a period of time during which firmware lookups are not possible, during this short period of time firmware…

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-firmware-cache"></a>

When Linux resumes from suspend some device drivers require firmware lookups to re-initialize devices. During resume there may be a period of time during which firmware lookups are not possible, during this short period of time firmware requests will fail. Time is of essence though, and delaying drivers to wait for the root filesystem for firmware delays user experience with device functionality. In order to support these requirements the firmware infrastructure implements a firmware cache for device drivers for most API calls, automatically behind the scenes.

The firmware cache makes using certain firmware API calls safe during a device driver's suspend and resume callback.  Users of these API calls needn't cache the firmware by themselves for dealing with firmware loss during system resume.

The firmware cache works by requesting for firmware prior to suspend and caching it in memory. Upon resume device drivers using the firmware API will have access to the firmware immediately, without having to wait for the root filesystem to mount or dealing with possible race issues with lookups as the root filesystem mounts.

Some implementation details about the firmware cache setup:

- The firmware cache is setup by adding a devres entry for each device that uses all synchronous call except `request_firmware_into_buf()`.

- If an asynchronous call is used the firmware cache is only set up for a device if the second argument (uevent) to request_firmware_nowait() is true. When uevent is true it requests that a kobject uevent be sent to userspace for the firmware request through the sysfs fallback mechanism if the firmware file is not found.

- If the firmware cache is determined to be needed as per the above two criteria the firmware cache is setup by adding a devres entry for the device making the firmware request.

- The firmware devres entry is maintained throughout the lifetime of the device. This means that even if you release_firmware() the firmware cache will still be used on resume from suspend.

- The timeout for the fallback mechanism is temporarily reduced to 10 seconds as the firmware cache is set up during suspend, the timeout is set back to the old value you had configured after the cache is set up.

- Upon suspend any pending non-uevent firmware requests are killed to avoid stalling the kernel, this is done with kill_requests_without_uevent(). Kernel calls requiring the non-uevent therefore need to implement their own firmware cache mechanism but must not use the firmware API on suspend.

---

# Firmware search paths

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> The following search paths are used to look for firmware on your root filesystem.

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-firmware-search-paths"></a>

The following search paths are used to look for firmware on your root filesystem.

- fw_path_para - module parameter - default is empty so this is ignored

- /lib/firmware/updates/UTS_RELEASE/

- /lib/firmware/updates/

- /lib/firmware/UTS_RELEASE/

- /lib/firmware/

The module parameter ''path'' can be passed to the firmware_class module to activate the first optional custom fw_path_para. The custom path can only be up to 256 characters long. The kernel parameter passed would be:

- 'firmware_class.path=$CUSTOMIZED_PATH'

There is an alternative to customize the path at run time after bootup, you can use the file:

- /sys/module/firmware_class/parameters/path

You would echo into it your custom path and firmware requested will be searched for there first. Be aware that newline characters will be taken into account and may not produce the intended effects. For instance you might want to use:

echo -n /path/to/script &gt; /sys/module/firmware_class/parameters/path

to ensure that your script is being used.

---

# Firmware Upload API

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> A device driver that registers with the firmware loader will expose persistent sysfs nodes to enable users to initiate firmware updates for that device. It is the responsibility of the device driver and/or the device itself to perform any…

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-firmware-upload-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

A device driver that registers with the firmware loader will expose persistent sysfs nodes to enable users to initiate firmware updates for that device.  It is the responsibility of the device driver and/or the device itself to perform any validation on the data received. Firmware upload uses the same *loading* and *data* sysfs files described in the documentation for firmware fallback. It also adds additional sysfs files to provide status on the transfer of the firmware image to the device.

<a id="rst-register-for-firmware-upload"></a>

## Register for firmware upload

A device driver registers for firmware upload by calling firmware_upload_register(). Among the parameter list is a name to identify the device under /sys/class/firmware. A user may initiate a firmware upload by echoing a 1 to the *loading* sysfs file for the target device. Next, the user writes the firmware image to the *data* sysfs file. After writing the firmware data, the user echos 0 to the *loading* sysfs file to signal completion. Echoing 0 to *loading* also triggers the transfer of the firmware to the lower-lever device driver in the context of a kernel worker thread.

To use the firmware upload API, write a driver that implements a set of ops.  The probe function calls firmware_upload_register() and the remove function calls firmware_upload_unregister() such as:



```text
static const struct fw_upload_ops m10bmc_ops = {
        .prepare = m10bmc_sec_prepare,
        .write = m10bmc_sec_write,
        .poll_complete = m10bmc_sec_poll_complete,
        .cancel = m10bmc_sec_cancel,
        .cleanup = m10bmc_sec_cleanup,
};

static int m10bmc_sec_probe(struct platform_device *pdev)
{
        const char *fw_name, *truncate;
        struct m10bmc_sec *sec;
        struct fw_upload *fwl;
        unsigned int len;

        sec = devm_kzalloc(&pdev->dev, sizeof(*sec), GFP_KERNEL);
        if (!sec)
                return -ENOMEM;

        sec->dev = &pdev->dev;
        sec->m10bmc = dev_get_drvdata(pdev->dev.parent);
        dev_set_drvdata(&pdev->dev, sec);

        fw_name = dev_name(sec->dev);
        truncate = strstr(fw_name, ".auto");
        len = (truncate) ? truncate - fw_name : strlen(fw_name);
        sec->fw_name = kmemdup_nul(fw_name, len, GFP_KERNEL);

        fwl = firmware_upload_register(THIS_MODULE, sec->dev, sec->fw_name,
                                       &m10bmc_ops, sec);
        if (IS_ERR(fwl)) {
                dev_err(sec->dev, "Firmware Upload driver failed to start\n");
                kfree(sec->fw_name);
                return PTR_ERR(fwl);
        }

        sec->fwl = fwl;
        return 0;
}

static int m10bmc_sec_remove(struct platform_device *pdev)
{
        struct m10bmc_sec *sec = dev_get_drvdata(&pdev->dev);

        firmware_upload_unregister(sec->fwl);
        kfree(sec->fw_name);
        return 0;
}
```

<a id="rst-firmware-upload-register"></a>

### firmware_upload_register


#### <a id="c-firmware_upload_register"></a>`firmware_upload_register()`

```c
struct fw_upload * firmware_upload_register(struct module *module, struct device *parent, const char *name, const struct fw_upload_ops *ops, void *dd_handle)
```

register for the firmware upload sysfs API

**Parameters**

- `struct module *module`: kernel module of this device
- `struct device *parent`: parent device instantiating firmware upload
- `const char *name`: firmware name to be associated with this device
- `const struct fw_upload_ops *ops`: pointer to structure of firmware upload ops
- `void *dd_handle`: pointer to parent driver private data

**Description**

**name** must be unique among all users of firmware upload. The firmware
sysfs files for this device will be found at /sys/class/firmware/**name**.

**Return**

struct fw_upload pointer or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)


<a id="rst-firmware-upload-unregister"></a>

### firmware_upload_unregister


#### <a id="c-firmware_upload_unregister"></a>`firmware_upload_unregister()`

```c
void firmware_upload_unregister(struct fw_upload *fw_upload)
```

Unregister firmware upload interface

**Parameters**

- `struct fw_upload *fw_upload`: pointer to struct fw_upload


<a id="rst-firmware-upload-ops"></a>

### Firmware Upload Ops


#### <a id="c-struct-fw_upload_ops"></a>`struct fw_upload_ops`

device specific operations to support firmware upload

**Definition**

```c
struct fw_upload_ops {
    enum fw_upload_err (*prepare)(struct fw_upload *fw_upload, const u8 *data, u32 size);
    enum fw_upload_err (*write)(struct fw_upload *fw_upload, const u8 *data, u32 offset, u32 size, u32 *written);
    enum fw_upload_err (*poll_complete)(struct fw_upload *fw_upload);
    void (*cancel)(struct fw_upload *fw_upload);
    void (*cleanup)(struct fw_upload *fw_upload);
};
```

**Members**

- `prepare`: Required: Prepare secure update
- `write`: Required: The `write()` op receives the remaining
  size to be written and must return the actual
  size written or a negative error code. The `write()`
  op will be called repeatedly until all data is
  written.
- `poll_complete`: Required: Check for the completion of the
  HW authentication/programming process.
- `cancel`: Required: Request cancellation of update. This op
  is called from the context of a different kernel
  thread, so race conditions need to be considered.
- `cleanup`: Optional: Complements the `prepare()`
  function and is called at the completion
  of the update, on success or failure, if the
  prepare function succeeded.


<a id="rst-firmware-upload-progress-codes"></a>

### Firmware Upload Progress Codes

The following progress codes are used internally by the firmware loader. Corresponding strings are reported through the status sysfs node that is described below and are documented in the ABI documentation.


#### <a id="c-enum-fw_upload_prog"></a>`enum fw_upload_prog`

firmware upload progress codes

**Constants**

- `FW_UPLOAD_PROG_IDLE`: there is no firmware upload in progress
- `FW_UPLOAD_PROG_RECEIVING`: worker thread is receiving firmware data
- `FW_UPLOAD_PROG_PREPARING`: target device is preparing for firmware upload
- `FW_UPLOAD_PROG_TRANSFERRING`: data is being copied to the device
- `FW_UPLOAD_PROG_PROGRAMMING`: device is performing the firmware update
- `FW_UPLOAD_PROG_MAX`: Maximum progress code marker


<a id="rst-firmware-upload-error-codes"></a>

### Firmware Upload Error Codes

The following error codes may be returned by the driver ops in case of failure:


#### <a id="c-enum-fw_upload_err"></a>`enum fw_upload_err`

firmware upload error codes

**Constants**

- `FW_UPLOAD_ERR_NONE`: returned to indicate success
- `FW_UPLOAD_ERR_HW_ERROR`: error signalled by hardware, see kernel log
- `FW_UPLOAD_ERR_TIMEOUT`: SW timed out on handshake with HW/firmware
- `FW_UPLOAD_ERR_CANCELED`: upload was cancelled by the user
- `FW_UPLOAD_ERR_BUSY`: there is an upload operation already in progress
- `FW_UPLOAD_ERR_INVALID_SIZE`: invalid firmware image size
- `FW_UPLOAD_ERR_RW_ERROR`: read or write to HW failed, see kernel log
- `FW_UPLOAD_ERR_WEAROUT`: FLASH device is approaching wear-out, wait & retry
- `FW_UPLOAD_ERR_FW_INVALID`: invalid firmware file
- `FW_UPLOAD_ERR_MAX`: Maximum error code marker


<a id="rst-sysfs-attributes"></a>

## Sysfs Attributes

In addition to the *loading* and *data* sysfs files, there are additional sysfs files to monitor the status of the data transfer to the target device and to determine the final pass/fail status of the transfer. Depending on the device and the size of the firmware image, a firmware update could take milliseconds or minutes.

The additional sysfs files are:

- status - provides an indication of the progress of a firmware update

- error - provides error information for a failed firmware update

- remaining_size - tracks the data transfer portion of an update

- cancel - echo 1 to this file to cancel the update

---

# Introduction

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> The firmware API enables kernel code to request files required for functionality from userspace, the uses vary:

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-introduction"></a>

The firmware API enables kernel code to request files required for functionality from userspace, the uses vary:

- Microcode for CPU errata

- Device driver firmware, required to be loaded onto device microcontrollers

- Device driver information data (calibration data, EEPROM overrides), some of which can be completely optional.

<a id="rst-types-of-firmware-requests"></a>

## Types of firmware requests

There are two types of calls:

- Synchronous

- Asynchronous

Which one you use vary depending on your requirements, the rule of thumb however is you should strive to use the asynchronous APIs unless you also are already using asynchronous initialization mechanisms which will not stall or delay boot. Even if loading firmware does not take a lot of time processing firmware might, and this can still delay boot or initialization, as such mechanisms such as asynchronous probe can help supplement drivers.

---

# Firmware lookup order

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> Different functionality is available to enable firmware to be found. Below is chronological order of how firmware will be looked for once a driver issues a firmware API call.

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-firmware-lookup-order"></a>

Different functionality is available to enable firmware to be found. Below is chronological order of how firmware will be looked for once a driver issues a firmware API call.

- The ''Built-in firmware'' is checked first, if the firmware is present we return it immediately

- The ''Firmware cache'' is looked at next. If the firmware is found we return it immediately

- The ''Direct filesystem lookup'' is performed next, if found we return it immediately

- The ''Platform firmware fallback'' is performed next, but only when firmware_request_platform() is used, if found we return it immediately

- If no firmware has been found and the fallback mechanism was enabled the sysfs interface is created. After this either a kobject uevent is issued or the custom firmware loading is relied upon for firmware loading up to the timeout value.

---

# Other Firmware Interfaces

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> Some features of the Intel Stratix10 SoC require a level of privilege higher than the kernel is granted. Such secure features include FPGA programming. In terms of the ARMv8 architecture, the kernel runs at Exception Level 1 (EL1), access…

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-other-firmware-interfaces"></a>

<a id="rst-dmi-interfaces"></a>

## DMI Interfaces


#### <a id="c-dmi_check_system"></a>`dmi_check_system()`

```c
int dmi_check_system(const struct dmi_system_id *list)
```

check system DMI data

**Parameters**

- `const struct dmi_system_id *list`: array of dmi_system_id structures to match against
  All non-null elements of the list must match
  their slot's (field index's) data (i.e., each
  list string must be a substring of the specified
  DMI slot's string data) to be considered a
  successful match.

**Description**

Walk the blacklist table running matching functions until someone
returns non zero or we hit the end. Callback function is called for
each successful match. Returns the number of matches.

dmi_setup must be called before this function is called.

#### <a id="c-dmi_first_match"></a>`dmi_first_match()`

```c
const struct dmi_system_id * dmi_first_match(const struct dmi_system_id *list)
```

find dmi_system_id structure matching system DMI data

**Parameters**

- `const struct dmi_system_id *list`: array of dmi_system_id structures to match against
  All non-null elements of the list must match
  their slot's (field index's) data (i.e., each
  list string must be a substring of the specified
  DMI slot's string data) to be considered a
  successful match.

**Description**

Walk the blacklist table until the first match is found.  Return the
pointer to the matching entry or NULL if there's no match.

dmi_setup must be called before this function is called.

#### <a id="c-dmi_get_system_info"></a>`dmi_get_system_info()`

```c
const char * dmi_get_system_info(int field)
```

return DMI data value

**Parameters**

- `int field`: data index (see enum dmi_field)

**Description**

Returns one DMI data value, can be used to perform
complex DMI data checks.

#### <a id="c-dmi_name_in_vendors"></a>`dmi_name_in_vendors()`

```c
int dmi_name_in_vendors(const char *str)
```

Check if string is in the DMI system or board vendor name

**Parameters**

- `const char *str`: Case sensitive Name

#### <a id="c-dmi_find_device"></a>`dmi_find_device()`

```c
const struct dmi_device * dmi_find_device(int type, const char *name, const struct dmi_device *from)
```

find onboard device by type/name

**Parameters**

- `int type`: device type or `DMI_DEV_TYPE_ANY` to match all device types
- `const char *name`: device name string or `NULL` to match all
- `const struct dmi_device *from`: previous device found in search, or `NULL` for new search.

**Description**

Iterates through the list of known onboard devices. If a device is
found with a matching **type** and **name**, a pointer to its device
structure is returned.  Otherwise, `NULL` is returned.
A new search is initiated by passing `NULL` as the **from** argument.
If **from** is not `NULL`, searches continue from next device.

#### <a id="c-dmi_get_date"></a>`dmi_get_date()`

```c
bool dmi_get_date(int field, int *yearp, int *monthp, int *dayp)
```

parse a DMI date

**Parameters**

- `int field`: data index (see enum dmi_field)
- `int *yearp`: optional out parameter for the year
- `int *monthp`: optional out parameter for the month
- `int *dayp`: optional out parameter for the day

**Description**

The date field is assumed to be in the form resembling
\[mm\[/dd\]\]/yy\[yy\] and the result is stored in the out
parameters any or all of which can be omitted.

If the field doesn't exist, all out parameters are set to zero
and false is returned.  Otherwise, true is returned with any
invalid part of date set to zero.

On return, year, month and day are guaranteed to be in the
range of \[0,9999\], \[0,12\] and \[0,31\] respectively.

#### <a id="c-dmi_get_bios_year"></a>`dmi_get_bios_year()`

```c
int dmi_get_bios_year(void)
```

get a year out of DMI_BIOS_DATE field

**Parameters**

- `void`: no arguments

**Description**

Returns year on success, -ENXIO if DMI is not selected,
or a different negative error code if DMI field is not present
or not parseable.

#### <a id="c-dmi_walk"></a>`dmi_walk()`

```c
int dmi_walk(void (*decode)(const struct dmi_header *, void *), void *private_data)
```

Walk the DMI table and get called back for every record

**Parameters**

- `void (*decode)(const struct dmi_header *, void *)`: Callback function
- `void *private_data`: Private data to be passed to the callback function

**Description**

Returns 0 on success, -ENXIO if DMI is not selected or not present,
or a different negative error code if DMI walking fails.

#### <a id="c-dmi_match"></a>`dmi_match()`

```c
bool dmi_match(enum dmi_field f, const char *str)
```

compare a string to the dmi field (if exists)

**Parameters**

- `enum dmi_field f`: DMI field identifier
- `const char *str`: string to compare the DMI field to

**Description**

Returns true if the requested field equals to the str (including NULL).

#### <a id="c-dmi_memdev_type"></a>`dmi_memdev_type()`

```c
u8 dmi_memdev_type(u16 handle)
```

get the memory type

**Parameters**

- `u16 handle`: DMI structure handle

**Description**

Return the DMI memory type of the module in the slot associated with the
given DMI handle, or 0x0 if no such DMI handle exists.

#### <a id="c-dmi_memdev_handle"></a>`dmi_memdev_handle()`

```c
u16 dmi_memdev_handle(int slot)
```

get the DMI handle of a memory slot

**Parameters**

- `int slot`: slot number

**Description**

Return the DMI handle associated with a given memory slot, or `0xFFFF`
if there is no such slot.


<a id="rst-edd-interfaces"></a>

## EDD Interfaces


#### <a id="c-edd_show_raw_data"></a>`edd_show_raw_data()`

```c
ssize_t edd_show_raw_data(struct edd_device *edev, char *buf)
```

copies raw data to buffer for userspace to parse

**Parameters**

- `struct edd_device *edev`: target edd_device
- `char *buf`: output buffer

**Return**

number of bytes written, or -EINVAL on failure

#### <a id="c-edd_release"></a>`edd_release()`

```c
void edd_release(struct kobject * kobj)
```

free edd structure

**Parameters**

- `struct kobject * kobj`: kobject of edd structure

**Description**

This is called when the refcount of the edd structure
reaches 0. This should happen right after we unregister,
but just in case, we use the release callback anyway.

#### <a id="c-edd_dev_is_type"></a>`edd_dev_is_type()`

```c
int edd_dev_is_type(struct edd_device *edev, const char *type)
```

is this EDD device a 'type' device?

**Parameters**

- `struct edd_device *edev`: target edd_device
- `const char *type`: a host bus or interface identifier string per the EDD spec

**Description**

Returns 1 (TRUE) if it is a 'type' device, 0 otherwise.

#### <a id="c-edd_get_pci_dev"></a>`edd_get_pci_dev()`

```c
struct pci_dev * edd_get_pci_dev(struct edd_device *edev)
```

finds pci_dev that matches edev

**Parameters**

- `struct edd_device *edev`: edd_device

**Description**

Returns pci_dev if found, or NULL

#### <a id="c-edd_init"></a>`edd_init()`

```c
int edd_init(void)
```

creates sysfs tree of EDD data

**Parameters**

- `void`: no arguments


<a id="rst-generic-system-framebuffers-interface"></a>

## Generic System Framebuffers Interface


#### <a id="c-sysfb_disable"></a>`sysfb_disable()`

```c
void sysfb_disable(struct device *dev)
```

disable the Generic System Framebuffers support

**Parameters**

- `struct device *dev`: the device to check if non-NULL

**Description**

This disables the registration of system framebuffer devices that match the
generic drivers that make use of the system framebuffer set up by firmware.

It also unregisters a device if this was already registered by `sysfb_init()`.

**Context**

The function can sleep. A **disable_lock** mutex is acquired to serialize
against `sysfb_init()`, that registers a system framebuffer device.

#### <a id="c-sysfb_handles_screen_info"></a>`sysfb_handles_screen_info()`

```c
bool sysfb_handles_screen_info(void)
```

reports if sysfb handles the global screen_info

**Parameters**

- `void`: no arguments

**Description**

Callers can use [`sysfb_handles_screen_info()`](#c-sysfb_handles_screen_info) to determine whether the Generic
System Framebuffers (sysfb) can handle the global screen_info data structure
or not. Drivers might need this information to know if they have to setup the
system framebuffer, or if they have to delegate this action to sysfb instead.

**Return**

True if sysfb handles the global screen_info data structure.


<a id="rst-intel-stratix10-soc-service-layer"></a>

## Intel Stratix10 SoC Service Layer

Some features of the Intel Stratix10 SoC require a level of privilege higher than the kernel is granted. Such secure features include FPGA programming. In terms of the ARMv8 architecture, the kernel runs at Exception Level 1 (EL1), access to the features requires Exception Level 3 (EL3).

The Intel Stratix10 SoC service layer provides an in kernel API for drivers to request access to the secure features. The requests are queued and processed one by one. ARM’s SMCCC is used to pass the execution of the requests on to a secure monitor (EL3).


#### <a id="c-enum-stratix10_svc_command_code"></a>`enum stratix10_svc_command_code`

supported service commands

**Constants**

- `COMMAND_NOOP`: do 'dummy' request for integration/debug/trouble-shooting
- `COMMAND_RECONFIG`: ask for FPGA configuration preparation, return status
  is SVC_STATUS_OK
- `COMMAND_RECONFIG_DATA_SUBMIT`: submit buffer(s) of bit-stream data for the
  FPGA configuration, return status is SVC_STATUS_SUBMITTED or SVC_STATUS_ERROR
- `COMMAND_RECONFIG_DATA_CLAIM`: check the status of the configuration, return
  status is SVC_STATUS_COMPLETED, or SVC_STATUS_BUSY, or SVC_STATUS_ERROR
- `COMMAND_RECONFIG_STATUS`: check the status of the configuration, return
  status is SVC_STATUS_COMPLETED, or SVC_STATUS_BUSY, or SVC_STATUS_ERROR
- `COMMAND_RSU_STATUS`: request remote system update boot log, return status
  is log data or SVC_STATUS_RSU_ERROR
- `COMMAND_RSU_UPDATE`: set the offset of the bitstream to boot after reboot,
  return status is SVC_STATUS_OK or SVC_STATUS_ERROR
- `COMMAND_RSU_NOTIFY`: report the status of hard processor system
  software to firmware, return status is SVC_STATUS_OK or
  SVC_STATUS_ERROR
- `COMMAND_RSU_RETRY`: query firmware for the current image's retry counter,
  return status is SVC_STATUS_OK or SVC_STATUS_ERROR
- `COMMAND_RSU_MAX_RETRY`: query firmware for the max retry value,
  return status is SVC_STATUS_OK or SVC_STATUS_ERROR
- `COMMAND_RSU_DCMF_VERSION`: query firmware for the DCMF version, return status
  is SVC_STATUS_OK or SVC_STATUS_ERROR
- `COMMAND_RSU_DCMF_STATUS`: query firmware for the DCMF status
  return status is SVC_STATUS_OK or SVC_STATUS_ERROR
- `COMMAND_FIRMWARE_VERSION`: query running firmware version, return status
  is SVC_STATUS_OK or SVC_STATUS_ERROR
- `COMMAND_RSU_GET_SPT_TABLE`: query firmware for SPT table
  return status is SVC_STATUS_OK or SVC_STATUS_ERROR
- `COMMAND_FCS_REQUEST_SERVICE`: request validation of image from firmware,
  return status is SVC_STATUS_OK, SVC_STATUS_INVALID_PARAM
- `COMMAND_FCS_SEND_CERTIFICATE`: send a certificate, return status is
  SVC_STATUS_OK, SVC_STATUS_INVALID_PARAM, SVC_STATUS_ERROR
- `COMMAND_FCS_GET_PROVISION_DATA`: read the provisioning data, return status is
  SVC_STATUS_OK, SVC_STATUS_INVALID_PARAM, SVC_STATUS_ERROR
- `COMMAND_FCS_DATA_ENCRYPTION`: encrypt the data, return status is
  SVC_STATUS_OK, SVC_STATUS_INVALID_PARAM, SVC_STATUS_ERROR
- `COMMAND_FCS_DATA_DECRYPTION`: decrypt the data, return status is
  SVC_STATUS_OK, SVC_STATUS_INVALID_PARAM, SVC_STATUS_ERROR
- `COMMAND_FCS_RANDOM_NUMBER_GEN`: generate a random number, return status
  is SVC_STATUS_OK, SVC_STATUS_ERROR
- `COMMAND_POLL_SERVICE_STATUS`: poll if the service request is complete,
  return statis is SVC_STATUS_OK, SVC_STATUS_ERROR or SVC_STATUS_BUSY
- `COMMAND_MBOX_SEND_CMD`: send generic mailbox command, return status is
  SVC_STATUS_OK or SVC_STATUS_ERROR
- `COMMAND_SMC_SVC_VERSION`: Non-mailbox SMC SVC API Version,
  return status is SVC_STATUS_OK
- `COMMAND_HWMON_READTEMP`: query the temperature from the hardware monitor,
  return status is SVC_STATUS_OK or SVC_STATUS_ERROR
- `COMMAND_HWMON_READVOLT`: query the voltage from the hardware monitor,
  return status is SVC_STATUS_OK or SVC_STATUS_ERROR



#### <a id="c-struct-stratix10_svc_client_msg"></a>`struct stratix10_svc_client_msg`

message sent by client to service

**Definition**

```c
struct stratix10_svc_client_msg {
    void *payload;
    size_t payload_length;
    void *payload_output;
    size_t payload_length_output;
    enum stratix10_svc_command_code command;
    u64 arg[3];
};
```

**Members**

- `payload`: starting address of data need be processed
- `payload_length`: to be processed data size in bytes
- `payload_output`: starting address of processed data
- `payload_length_output`: processed data size in bytes
- `command`: service command
- `arg`: args to be passed via registers and not physically mapped buffers



#### <a id="c-struct-stratix10_svc_command_config_type"></a>`struct stratix10_svc_command_config_type`

config type

**Definition**

```c
struct stratix10_svc_command_config_type {
    u32 flags;
};
```

**Members**

- `flags`: flag bit for the type of FPGA configuration



#### <a id="c-struct-stratix10_svc_cb_data"></a>`struct stratix10_svc_cb_data`

callback data structure from service layer

**Definition**

```c
struct stratix10_svc_cb_data {
    u32 status;
    void *kaddr1;
    void *kaddr2;
    void *kaddr3;
};
```

**Members**

- `status`: the status of sent command
- `kaddr1`: address of 1st completed data block
- `kaddr2`: address of 2nd completed data block
- `kaddr3`: address of 3rd completed data block



#### <a id="c-struct-stratix10_svc_client"></a>`struct stratix10_svc_client`

service client structure

**Definition**

```c
struct stratix10_svc_client {
    struct device *dev;
    void (*receive_cb)(struct stratix10_svc_client *client, struct stratix10_svc_cb_data *cb_data);
    void *priv;
};
```

**Members**

- `dev`: the client device
- `receive_cb`: callback to provide service client the received data
- `priv`: client private data



#### <a id="c-stratix10_svc_request_channel_byname"></a>`stratix10_svc_request_channel_byname()`

```c
struct stratix10_svc_chan * stratix10_svc_request_channel_byname(struct stratix10_svc_client *client, const char *name)
```

request a service channel

**Parameters**

- `struct stratix10_svc_client *client`: pointer to service client
- `const char *name`: service client name

**Description**

This function is used by service client to request a service channel.

**Return**

a pointer to channel assigned to the client on success,
or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

#### <a id="c-stratix10_svc_add_async_client"></a>`stratix10_svc_add_async_client()`

```c
int stratix10_svc_add_async_client(struct stratix10_svc_chan *chan, bool use_unique_clientid)
```

Add an asynchronous client to the Stratix10 service channel.

**Parameters**

- `struct stratix10_svc_chan *chan`: Pointer to the Stratix10 service channel structure.
- `bool use_unique_clientid`: Boolean flag indicating whether to use a
  unique client ID.

**Description**

This function adds an asynchronous client to the specified
Stratix10 service channel. If the `use_unique_clientid` flag is
set to true, a unique client ID is allocated for the asynchronous
channel. Otherwise, a common asynchronous channel is used.

**Return**

0 on success, or a negative error code on failure:
-EINVAL if the channel is NULL or the async controller is
not initialized.
-EALREADY if the async channel is already allocated.
-ENOMEM if memory allocation fails.
Other negative values if ID allocation fails.

#### <a id="c-stratix10_svc_remove_async_client"></a>`stratix10_svc_remove_async_client()`

```c
int stratix10_svc_remove_async_client(struct stratix10_svc_chan *chan)
```

Remove an asynchronous client from the Stratix10 service channel.

**Parameters**

- `struct stratix10_svc_chan *chan`: Pointer to the Stratix10 service channel structure.

**Description**

This function removes an asynchronous client associated with the
given service channel. It checks if the channel and the
asynchronous channel are valid, and then proceeds to decrement
the reference count for the common asynchronous channel if
applicable. If the reference count reaches zero, it destroys the
job ID pool and deallocates the asynchronous client ID. For
non-common asynchronous channels, it directly destroys the job ID
pool, deallocates the asynchronous client ID, and frees the
memory allocated for the asynchronous channel.

**Return**

0 on success, -EINVAL if the channel or asynchronous
channel is invalid.

#### <a id="c-stratix10_svc_async_send"></a>`stratix10_svc_async_send()`

```c
int stratix10_svc_async_send(struct stratix10_svc_chan *chan, void *msg, void **handler, async_callback_t cb, void *cb_arg)
```

Send an asynchronous message to the Stratix10 service

**Parameters**

- `struct stratix10_svc_chan *chan`: Pointer to the service channel structure
- `void *msg`: Pointer to the message to be sent
- `void **handler`: Pointer to the handler for the asynchronous message
  used by caller for later reference.
- `async_callback_t cb`: Callback function to be called upon completion
- `void *cb_arg`: Argument to be passed to the callback function

**Description**

This function sends an asynchronous message to the SDM mailbox in
EL3 secure firmware. It performs various checks and setups,
including allocating a job ID, setting up the transaction ID and
packaging it to El3 firmware. The function handles different
commands by setting up the appropriate arguments for the SMC call.
If the SMC call is successful, the handler is set up and the
function returns 0. If the SMC call fails, appropriate error
handling is performed along with cleanup of resources.

**Return**

0 on success, -EINVAL for invalid argument, -ENOMEM if
memory is not available, -EAGAIN if EL3 firmware is busy, -EBADF
if the message is rejected by EL3 firmware and -EIO on other
errors from EL3 firmware.

#### <a id="c-stratix10_svc_async_poll"></a>`stratix10_svc_async_poll()`

```c
int stratix10_svc_async_poll(struct stratix10_svc_chan *chan, void *tx_handle, struct stratix10_svc_cb_data *data)
```

Polls the status of an asynchronous transaction.

**Parameters**

- `struct stratix10_svc_chan *chan`: Pointer to the service channel structure.
- `void *tx_handle`: Handle to the transaction being polled.
- `struct stratix10_svc_cb_data *data`: Pointer to the callback data structure.

**Description**

This function polls the status of an asynchronous transaction
identified by the given transaction handle. It ensures that the
necessary structures are initialized and valid before proceeding
with the poll operation. The function sets up the necessary
arguments for the SMC call, invokes the call, and prepares the
response data if the call is successful. If the call fails, the
function returns the error mapped to the SVC status error.

**Return**

0 on success, -EINVAL if any input parameter is invalid,
-EAGAIN if the transaction is still in progress,
-EPERM if the command is invalid, or other negative
error codes on failure.

#### <a id="c-stratix10_svc_async_done"></a>`stratix10_svc_async_done()`

```c
int stratix10_svc_async_done(struct stratix10_svc_chan *chan, void *tx_handle)
```

Completes an asynchronous transaction.

**Parameters**

- `struct stratix10_svc_chan *chan`: Pointer to the service channel structure.
- `void *tx_handle`: Handle to the transaction being completed.

**Description**

This function completes an asynchronous transaction identified by
the given transaction handle. It ensures that the necessary
structures are initialized and valid before proceeding with the
completion operation. The function deallocates the transaction ID,
frees the memory allocated for the handler, and removes the handler
from the transaction list.

**Return**

0 on success, -EINVAL if any input parameter is invalid,
or other negative error codes on failure.

#### <a id="c-stratix10_svc_free_channel"></a>`stratix10_svc_free_channel()`

```c
void stratix10_svc_free_channel(struct stratix10_svc_chan *chan)
```

free service channel

**Parameters**

- `struct stratix10_svc_chan *chan`: service channel to be freed

**Description**

This function is used by service client to free a service channel.

#### <a id="c-stratix10_svc_send"></a>`stratix10_svc_send()`

```c
int stratix10_svc_send(struct stratix10_svc_chan *chan, void *msg)
```

send a message data to the remote

**Parameters**

- `struct stratix10_svc_chan *chan`: service channel assigned to the client
- `void *msg`: message data to be sent, in the format of
  "struct stratix10_svc_client_msg"

**Description**

This function is used by service client to add a message to the service
layer driver's queue for being sent to the secure world.

**Return**

0 for success, -ENOMEM or -ENOBUFS on error.

#### <a id="c-stratix10_svc_done"></a>`stratix10_svc_done()`

```c
void stratix10_svc_done(struct stratix10_svc_chan *chan)
```

complete service request transactions

**Parameters**

- `struct stratix10_svc_chan *chan`: service channel assigned to the client

**Description**

This function should be called when client has finished its request
or there is an error in the request process. It allows the service layer
to stop the running thread to have maximize savings in kernel resources.

#### <a id="c-stratix10_svc_allocate_memory"></a>`stratix10_svc_allocate_memory()`

```c
void * stratix10_svc_allocate_memory(struct stratix10_svc_chan *chan, size_t size)
```

allocate memory

**Parameters**

- `struct stratix10_svc_chan *chan`: service channel assigned to the client
- `size_t size`: memory size requested by a specific service client

**Description**

Service layer allocates the requested number of bytes buffer from the
memory pool, service client uses this function to get allocated buffers.

**Return**

address of allocated memory on success, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on error.

#### <a id="c-stratix10_svc_free_memory"></a>`stratix10_svc_free_memory()`

```c
void stratix10_svc_free_memory(struct stratix10_svc_chan *chan, void *kaddr)
```

free allocated memory

**Parameters**

- `struct stratix10_svc_chan *chan`: service channel assigned to the client
- `void *kaddr`: memory to be freed

**Description**

This function is used by service client to free allocated buffers.

---

# request_firmware API

_Peios Kernel / Hardware and drivers / Driver development / Firmware loading_

> You would typically load firmware and then load it into your device somehow. The typical firmware work flow is reflected below:

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-request-firmware-api"></a>

You would typically load firmware and then load it into your device somehow. The typical firmware work flow is reflected below:



```text
if(request_firmware(&fw_entry, $FIRMWARE, device) == 0)
       copy_fw_to_device(fw_entry->data, fw_entry->size);
release_firmware(fw_entry);
```

<a id="rst-synchronous-firmware-requests"></a>

## Synchronous firmware requests

Synchronous firmware requests will wait until the firmware is found or until an error is returned.

<a id="rst-request-firmware"></a>

### request_firmware


#### <a id="c-request_firmware"></a>`request_firmware()`

```c
int request_firmware(const struct firmware **firmware_p, const char *name, struct device *device)
```

send firmware request and wait for it

**Parameters**

- `const struct firmware **firmware_p`: pointer to firmware image
- `const char *name`: name of firmware file
- `struct device *device`: device for which firmware is being loaded

**Description**

**firmware_p** will be used to return a firmware image by the name
of **name** for device **device**.

Should be called from user context where sleeping is allowed.

**name** will be used as $FIRMWARE in the uevent environment and
should be distinctive enough not to be confused with any other
firmware image for this or any other device.
It must not contain any ".." path components - "foo/bar..bin" is
allowed, but "foo/../bar.bin" is not.

Caller must hold the reference count of **device**.

The function can be called safely inside device's suspend and
resume callback.


<a id="rst-firmware-request-nowarn"></a>

### firmware_request_nowarn


#### <a id="c-firmware_request_nowarn"></a>`firmware_request_nowarn()`

```c
int firmware_request_nowarn(const struct firmware **firmware, const char *name, struct device *device)
```

request for an optional fw module

**Parameters**

- `const struct firmware **firmware`: pointer to firmware image
- `const char *name`: name of firmware file
- `struct device *device`: device for which firmware is being loaded

**Description**

This function is similar in behaviour to [`request_firmware()`](#c-request_firmware), except it
doesn't produce warning messages when the file is not found. The sysfs
fallback mechanism is enabled if direct filesystem lookup fails. However,
failures to find the firmware file with it are still suppressed. It is
therefore up to the driver to check for the return value of this call and to
decide when to inform the users of errors.


<a id="rst-firmware-request-platform"></a>

### firmware_request_platform


#### <a id="c-firmware_request_platform"></a>`firmware_request_platform()`

```c
int firmware_request_platform(const struct firmware **firmware, const char *name, struct device *device)
```

request firmware with platform-fw fallback

**Parameters**

- `const struct firmware **firmware`: pointer to firmware image
- `const char *name`: name of firmware file
- `struct device *device`: device for which firmware is being loaded

**Description**

This function is similar in behaviour to request_firmware, except that if
direct filesystem lookup fails, it will fallback to looking for a copy of the
requested firmware embedded in the platform's main (e.g. UEFI) firmware.


<a id="rst-request-firmware-direct"></a>

### request_firmware_direct


#### <a id="c-request_firmware_direct"></a>`request_firmware_direct()`

```c
int request_firmware_direct(const struct firmware **firmware_p, const char *name, struct device *device)
```

load firmware directly without usermode helper

**Parameters**

- `const struct firmware **firmware_p`: pointer to firmware image
- `const char *name`: name of firmware file
- `struct device *device`: device for which firmware is being loaded

**Description**

This function works pretty much like [`request_firmware()`](#c-request_firmware), but this doesn't
fall back to usermode helper even if the firmware couldn't be loaded
directly from fs.  Hence it's useful for loading optional firmwares, which
aren't always present, without extra long timeouts of udev.


<a id="rst-request-firmware-into-buf"></a>

### request_firmware_into_buf


#### <a id="c-request_firmware_into_buf"></a>`request_firmware_into_buf()`

```c
int request_firmware_into_buf(const struct firmware **firmware_p, const char *name, struct device *device, void *buf, size_t size)
```

load firmware into a previously allocated buffer

**Parameters**

- `const struct firmware **firmware_p`: pointer to firmware image
- `const char *name`: name of firmware file
- `struct device *device`: device for which firmware is being loaded and DMA region allocated
- `void *buf`: address of buffer to load firmware into
- `size_t size`: size of buffer

**Description**

This function works pretty much like [`request_firmware()`](#c-request_firmware), but it doesn't
allocate a buffer to hold the firmware data. Instead, the firmware
is loaded directly into the buffer pointed to by **buf** and the **firmware_p**
data member is pointed at **buf**.

This function doesn't cache firmware either.


<a id="rst-asynchronous-firmware-requests"></a>

## Asynchronous firmware requests

Asynchronous firmware requests allow driver code to not have to wait until the firmware or an error is returned. Function callbacks are provided so that when the firmware or an error is found the driver is informed through the callback. request_firmware_nowait() cannot be called in atomic contexts.

<a id="rst-request-firmware-nowait"></a>

### request_firmware_nowait


#### <a id="c-request_firmware_nowait"></a>`request_firmware_nowait()`

```c
int request_firmware_nowait(struct module *module, bool uevent, const char *name, struct device *device, gfp_t gfp, void *context, void (*cont)(const struct firmware *fw, void *context))
```

asynchronous version of request_firmware

**Parameters**

- `struct module *module`: module requesting the firmware
- `bool uevent`: sends uevent to copy the firmware image if this flag
  is non-zero else the firmware copy must be done manually.
- `const char *name`: name of firmware file
- `struct device *device`: device for which firmware is being loaded
- `gfp_t gfp`: allocation flags
- `void *context`: will be passed over to **cont**, and
  **fw** may be `NULL` if firmware request fails.
- `void (*cont)(const struct firmware *fw, void *context)`: function will be called asynchronously when the firmware
  request is over.

**Description**

Caller must hold the reference count of **device**.

- Asynchronous variant of [`request_firmware()`](#c-request_firmware) for user contexts:
  - sleep for as small periods as possible since it may
    increase kernel boot time of built-in device drivers
    requesting firmware in their ->`probe()` methods, if
    **gfp** is GFP_KERNEL.

  - can't sleep at all if **gfp** is GFP_ATOMIC.


<a id="rst-special-optimizations-on-reboot"></a>

## Special optimizations on reboot

Some devices have an optimization in place to enable the firmware to be retained during system reboot. When such optimizations are used the driver author must ensure the firmware is still available on resume from suspend, this can be done with firmware_request_cache() instead of requesting for the firmware to be loaded.

<a id="rst-firmware-request-cache"></a>

### firmware_request_cache()


#### <a id="c-firmware_request_cache"></a>`firmware_request_cache()`

```c
int firmware_request_cache(struct device *device, const char *name)
```

cache firmware for suspend so resume can use it

**Parameters**

- `struct device *device`: device for which firmware should be cached for
- `const char *name`: name of firmware file

**Description**

There are some devices with an optimization that enables the device to not
require loading firmware on system reboot. This optimization may still
require the firmware present on resume from suspend. This routine can be
used to ensure the firmware is present on resume from suspend in these
situations. This helper is not compatible with drivers which use
[`request_firmware_into_buf()`](#c-request_firmware_into_buf) or [`request_firmware_nowait()`](#c-request_firmware_nowait) with no uevent set.


<a id="rst-request-firmware-api-expected-driver-use"></a>

## request firmware API expected driver use

Once an API call returns you process the firmware and then release the firmware. For example if you used request_firmware() and it returns, the driver has the firmware image accessible in fw_entry-&gt;\{data,size\}. If something went wrong request_firmware() returns non-zero and fw_entry is set to NULL. Once your driver is done with processing the firmware it can call release_firmware(fw_entry) to release the firmware image and any related resource.

---

# Unified Extensible Firmware Interface (UEFI) Support

_Peios Kernel / Hardware and drivers / Driver development / firmware: efi_

> Reference for Unified Extensible Firmware Interface (UEFI) Support.

> **Peios:** File-based firmware loading has an additional Peios signature check. The development profile defaults to logging (`kacs_fwsig=log`); `kacs_fwsig=enforce` requires PeiosTcb trust for that path. This does not cover the separate `FW_UPLOAD` interface. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-unified-extensible-firmware-interface-uefi-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-uefi-stub-library-functions"></a>

## UEFI stub library functions


#### <a id="c-efi_get_memory_map"></a>`efi_get_memory_map()`

```c
efi_status_t efi_get_memory_map(struct efi_boot_memmap **map, bool install_cfg_tbl)
```

get memory map

**Parameters**

- `struct efi_boot_memmap **map`: pointer to memory map pointer to which to assign the
  newly allocated memory map
- `bool install_cfg_tbl`: whether or not to install the boot memory map as a
  configuration table

**Description**

Retrieve the UEFI memory map. The allocated memory leaves room for
up to EFI_MMAP_NR_SLACK_SLOTS additional memory map entries.

**Return**

status code

#### <a id="c-efi_allocate_pages"></a>`efi_allocate_pages()`

```c
efi_status_t efi_allocate_pages(unsigned long size, unsigned long *addr, unsigned long max)
```

Allocate memory pages

**Parameters**

- `unsigned long size`: minimum number of bytes to allocate
- `unsigned long *addr`: On return the address of the first allocated page. The first
  allocated page has alignment EFI_ALLOC_ALIGN which is an
  architecture dependent multiple of the page size.
- `unsigned long max`: the address that the last allocated memory page shall not
  exceed

**Description**

Allocate pages as EFI_LOADER_DATA. The allocated pages are aligned according
to EFI_ALLOC_ALIGN. The last allocated page will not exceed the address
given by **max**.

**Return**

status code

#### <a id="c-efi_free"></a>`efi_free()`

```c
void efi_free(unsigned long size, unsigned long addr)
```

free memory pages

**Parameters**

- `unsigned long size`: size of the memory area to free in bytes
- `unsigned long addr`: start of the memory area to free (must be EFI_PAGE_SIZE
  aligned)

**Description**

**size** is rounded up to a multiple of EFI_ALLOC_ALIGN which is an
architecture specific multiple of EFI_PAGE_SIZE. So this function should
only be used to return pages allocated with [`efi_allocate_pages()`](#c-efi_allocate_pages) or
`efi_low_alloc_above()`.


<a id="rst-uefi-common-platform-error-record-cper-functions"></a>

## UEFI Common Platform Error Record (CPER) functions


#### <a id="c-cper_print_bits"></a>`cper_print_bits()`

```c
void cper_print_bits(const char *pfx, unsigned int bits, const char * const strs[], unsigned int strs_size)
```

print strings for set bits

**Parameters**

- `const char *pfx`: prefix for each line, including log level and prefix string
- `unsigned int bits`: bit mask
- `const char * const strs[]`: string array, indexed by bit position
- `unsigned int strs_size`: size of the string array: **strs**

**Description**

For each set bit in **bits**, print the corresponding string in **strs**.
If the output length is longer than 80, multiple line will be
printed, with **pfx** is printed at the beginning of each line.

#### <a id="c-cper_bits_to_str"></a>`cper_bits_to_str()`

```c
int cper_bits_to_str(char *buf, int buf_size, unsigned long bits, const char * const strs[], unsigned int strs_size)
```

return a string for set bits

**Parameters**

- `char *buf`: buffer to store the output string
- `int buf_size`: size of the output string buffer
- `unsigned long bits`: bit mask
- `const char * const strs[]`: string array, indexed by bit position
- `unsigned int strs_size`: size of the string array: **strs**

**Description**

Add to **buf** the bitmask in hexadecimal. Then, for each set bit in **bits**,
add the corresponding string describing the bit in **strs** to **buf**.

A typical example is:

```text
const char * const bits[] = {
        "bit 3 name",
        "bit 4 name",
        "bit 5 name",
};
char str[120];
unsigned int bitmask = BIT(3) | BIT(5);
#define MASK GENMASK(5,3)

cper_bits_to_str(str, sizeof(str), FIELD_GET(MASK, bitmask),
                 bits, ARRAY_SIZE(bits));
```

The above code fills the string `str` with `bit 3 name|bit 5 name`.

**Return**

number of bytes stored or an error code if lower than zero.

---

# The Linux Hardware Timestamping Engine (HTE)

_Peios Kernel / Hardware and drivers / Driver development / Hardware timestamps_

> Reference for The Linux Hardware Timestamping Engine (HTE).

<a id="rst-the-linux-hardware-timestamping-engine-hte"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-the-hte-subsystem"></a>

## The HTE Subsystem

- [The Linux Hardware Timestamping Engine (HTE)](</kernel/hardware/driver-api/hte/hte.md>)

<a id="rst-hte-tegra-provider"></a>

## HTE Tegra Provider

- [HTE Kernel provider driver](</kernel/hardware/driver-api/hte/tegra-hte.md>)

---

# The Linux Hardware Timestamping Engine (HTE)

_Peios Kernel / Hardware and drivers / Driver development / Hardware timestamps_

> Certain devices have built in hardware timestamping engines which can monitor sets of system signals, lines, buses etc... in realtime for state change; upon detecting the change they can automatically store the timestamp at the moment of…

<a id="rst-the-linux-hardware-timestamping-engine-hte"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

**Author:** Dipen Patel

<a id="rst-introduction"></a>

## Introduction

Certain devices have built in hardware timestamping engines which can monitor sets of system signals, lines, buses etc... in realtime for state change; upon detecting the change they can automatically store the timestamp at the moment of occurrence. Such functionality may help achieve better accuracy in obtaining timestamps than using software counterparts i.e. ktime and friends.

This document describes the API that can be used by hardware timestamping engine provider and consumer drivers that want to use the hardware timestamping engine (HTE) framework. Both consumers and providers must include `#include <linux/hte.h>`.

<a id="rst-the-hte-framework-apis-for-the-providers"></a>

## The HTE framework APIs for the providers


#### <a id="c-hte_push_ts_ns"></a>`hte_push_ts_ns()`

```c
int hte_push_ts_ns(const struct hte_chip *chip, u32 xlated_id, struct hte_ts_data *data)
```

Push timestamp data in nanoseconds.

**Parameters**

- `const struct hte_chip *chip`: The HTE chip, used during the registration.
- `u32 xlated_id`: entity id understood by both subsystem and provider, this is
  obtained from xlate callback during request API.
- `struct hte_ts_data *data`: timestamp data.

**Description**

It is used by the provider to push timestamp data.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-devm_hte_register_chip"></a>`devm_hte_register_chip()`

```c
int devm_hte_register_chip(struct hte_chip *chip)
```

Resource managed API to register HTE chip.

**Parameters**

- `struct hte_chip *chip`: the HTE chip to add to subsystem.

**Description**

It is used by the provider to register itself with the HTE subsystem.
The unregistration is done automatically when the provider exits.

**Return**

0 on success or a negative error code on failure.


<a id="rst-the-hte-framework-apis-for-the-consumers"></a>

## The HTE framework APIs for the consumers


#### <a id="c-hte_ts_put"></a>`hte_ts_put()`

```c
int hte_ts_put(struct hte_ts_desc *desc)
```

Release and disable timestamp for the given desc.

**Parameters**

- `struct hte_ts_desc *desc`: timestamp descriptor.

**Context**

`debugfs_remove_recursive()` function call may use sleeping locks,
not suitable from atomic context.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-hte_disable_ts"></a>`hte_disable_ts()`

```c
int hte_disable_ts(struct hte_ts_desc *desc)
```

Disable timestamp on given descriptor.

**Parameters**

- `struct hte_ts_desc *desc`: ts descriptor, this is the same as returned by the request API.

**Description**

The API does not release any resources associated with desc.

**Context**

Holds mutex lock, not suitable from atomic context.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-hte_enable_ts"></a>`hte_enable_ts()`

```c
int hte_enable_ts(struct hte_ts_desc *desc)
```

Enable timestamp on given descriptor.

**Parameters**

- `struct hte_ts_desc *desc`: ts descriptor, this is the same as returned by the request API.

**Context**

Holds mutex lock, not suitable from atomic context.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-of_hte_req_count"></a>`of_hte_req_count()`

```c
int of_hte_req_count(struct device *dev)
```

Return the number of entities to timestamp.

**Parameters**

- `struct device *dev`: The HTE consumer.

**Description**

The function returns the total count of the requested entities to timestamp
by parsing device tree.

**Return**

Positive number on success, -ENOENT if no entries,
-EINVAL for other errors.

#### <a id="c-hte_ts_get"></a>`hte_ts_get()`

```c
int hte_ts_get(struct device *dev, struct hte_ts_desc *desc, int index)
```

The function to initialize and obtain HTE desc.

**Parameters**

- `struct device *dev`: HTE consumer/client device, used in case of parsing device tree node.
- `struct hte_ts_desc *desc`: Pre-allocated timestamp descriptor.
- `int index`: The index will be used as an index to parse line_id from the
  device tree node if node is present.

**Description**

The function initializes the consumer provided HTE descriptor. If consumer
has device tree node, index is used to parse the line id and other details.
The function needs to be called before using any request APIs.

**Context**

Holds mutex lock.

**Return**

Returns 0 on success or negative error code on failure.

#### <a id="c-hte_request_ts_ns"></a>`hte_request_ts_ns()`

```c
int hte_request_ts_ns(struct hte_ts_desc *desc, hte_ts_cb_t cb, hte_ts_sec_cb_t tcb, void *data)
```

The API to request and enable hardware timestamp in nanoseconds.

**Parameters**

- `struct hte_ts_desc *desc`: Pre-allocated and initialized timestamp descriptor.
- `hte_ts_cb_t cb`: Callback to push the timestamp data to consumer.
- `hte_ts_sec_cb_t tcb`: Optional callback. If its provided, subsystem initializes
  workqueue. It is called when cb returns HTE_RUN_SECOND_CB.
- `void *data`: Client data, used during cb and tcb callbacks.

**Description**

The entity is provider specific for example, GPIO lines, signals, buses
etc...The API allocates necessary resources and enables the timestamp.

**Context**

Holds mutex lock.

**Return**

Returns 0 on success or negative error code on failure.

#### <a id="c-devm_hte_request_ts_ns"></a>`devm_hte_request_ts_ns()`

```c
int devm_hte_request_ts_ns(struct device *dev, struct hte_ts_desc *desc, hte_ts_cb_t cb, hte_ts_sec_cb_t tcb, void *data)
```

Resource managed API to request and enable hardware timestamp in nanoseconds.

**Parameters**

- `struct device *dev`: HTE consumer/client device.
- `struct hte_ts_desc *desc`: Pre-allocated and initialized timestamp descriptor.
- `hte_ts_cb_t cb`: Callback to push the timestamp data to consumer.
- `hte_ts_sec_cb_t tcb`: Optional callback. If its provided, subsystem initializes
  workqueue. It is called when cb returns HTE_RUN_SECOND_CB.
- `void *data`: Client data, used during cb and tcb callbacks.

**Description**

The entity is provider specific for example, GPIO lines, signals, buses
etc...The API allocates necessary resources and enables the timestamp. It
deallocates and disables automatically when the consumer exits.

**Context**

Holds mutex lock.

**Return**

Returns 0 on success or negative error code on failure.

#### <a id="c-hte_init_line_attr"></a>`hte_init_line_attr()`

```c
int hte_init_line_attr(struct hte_ts_desc *desc, u32 line_id, unsigned long edge_flags, const char *name, void *data)
```

Initialize line attributes.

**Parameters**

- `struct hte_ts_desc *desc`: Pre-allocated timestamp descriptor.
- `u32 line_id`: line id.
- `unsigned long edge_flags`: edge flags related to line_id.
- `const char *name`: name of the line.
- `void *data`: line data related to line_id.

**Description**

Zeroes out line attributes and initializes with provided arguments.
The function needs to be called before calling any consumer facing
functions.

**Context**

Any.

**Return**

0 on success or negative error code for the failure.

#### <a id="c-hte_get_clk_src_info"></a>`hte_get_clk_src_info()`

```c
int hte_get_clk_src_info(const struct hte_ts_desc *desc, struct hte_clk_info *ci)
```

Get the clock source information for a ts descriptor.

**Parameters**

- `const struct hte_ts_desc *desc`: ts descriptor, same as returned from request API.
- `struct hte_clk_info *ci`: The API fills this structure with the clock information data.

**Context**

Any context.

**Return**

0 on success else negative error code on failure.


<a id="rst-the-hte-framework-public-structures"></a>

## The HTE framework public structures


#### <a id="c-enum-hte_edge"></a>`enum hte_edge`

HTE line edge flags.

**Constants**

- `HTE_EDGE_NO_SETUP`: No edge setup. In this case consumer will setup edges,
  for example during request irq call.
- `HTE_RISING_EDGE_TS`: Rising edge.
- `HTE_FALLING_EDGE_TS`: Falling edge.

#### <a id="c-enum-hte_return"></a>`enum hte_return`

HTE subsystem return values used during callback.

**Constants**

- `HTE_CB_HANDLED`: The consumer handled the data.
- `HTE_RUN_SECOND_CB`: The consumer needs further processing, in that case
  HTE subsystem calls secondary callback provided by the consumer where it
  is allowed to sleep.

#### <a id="c-struct-hte_ts_data"></a>`struct hte_ts_data`

HTE timestamp data.

**Definition**

```c
struct hte_ts_data {
    u64 tsc;
    u64 seq;
    int raw_level;
};
```

**Members**

- `tsc`: Timestamp value.
- `seq`: Sequence counter of the timestamps.
- `raw_level`: Level of the line at the timestamp if provider supports it,
  -1 otherwise.

#### <a id="c-struct-hte_clk_info"></a>`struct hte_clk_info`

Clock source info that HTE provider uses to timestamp.

**Definition**

```c
struct hte_clk_info {
    u64 hz;
    clockid_t type;
};
```

**Members**

- `hz`: Supported clock rate in HZ, for example 1KHz clock = 1000.
- `type`: Supported clock type.

#### <a id="c-hte_ts_cb_t"></a>`hte_ts_cb_t()`

```c
typedef enum hte_return hte_ts_cb_t(struct hte_ts_data *ts, void *data)
```

HTE timestamp data processing primary callback.

**Parameters**

- `struct hte_ts_data *ts`: HW timestamp data.
- `void *data`: Client supplied data.

**Description**

The callback is used to push timestamp data to the client and it is
not allowed to sleep.

#### <a id="c-hte_ts_sec_cb_t"></a>`hte_ts_sec_cb_t()`

```c
typedef enum hte_return hte_ts_sec_cb_t(void *data)
```

HTE timestamp data processing secondary callback.

**Parameters**

- `void *data`: Client supplied data.

**Description**

This is used when the client needs further processing where it is
allowed to sleep.

#### <a id="c-struct-hte_line_attr"></a>`struct hte_line_attr`

Line attributes.

**Definition**

```c
struct hte_line_attr {
    u32 line_id;
    void *line_data;
    unsigned long edge_flags;
    const char *name;
};
```

**Members**

- `line_id`: The logical ID understood by the consumers and providers.
- `line_data`: Line data related to line_id.
- `edge_flags`: Edge setup flags.
- `name`: Descriptive name of the entity that is being monitored for the
  hardware timestamping. If null, HTE core will construct the name.

#### <a id="c-struct-hte_ts_desc"></a>`struct hte_ts_desc`

HTE timestamp descriptor.

**Definition**

```c
struct hte_ts_desc {
    struct hte_line_attr attr;
    void *hte_data;
};
```

**Members**

- `attr`: The line attributes.
- `hte_data`: Subsystem's private data, set by HTE subsystem.

**Description**

This structure is a communication token between consumers to subsystem
and subsystem to providers.

#### <a id="c-struct-hte_ops"></a>`struct hte_ops`

HTE operations set by providers.

**Definition**

```c
struct hte_ops {
    int (*request)(struct hte_chip *chip, struct hte_ts_desc *desc, u32 xlated_id);
    int (*release)(struct hte_chip *chip, struct hte_ts_desc *desc, u32 xlated_id);
    int (*enable)(struct hte_chip *chip, u32 xlated_id);
    int (*disable)(struct hte_chip *chip, u32 xlated_id);
    int (*get_clk_src_info)(struct hte_chip *chip, struct hte_clk_info *ci);
};
```

**Members**

- `request`: Hook for requesting a HTE timestamp. Returns 0 on success,
  non-zero for failures.
- `release`: Hook for releasing a HTE timestamp. Returns 0 on success,
  non-zero for failures.
- `enable`: Hook to enable the specified timestamp. Returns 0 on success,
  non-zero for failures.
- `disable`: Hook to disable specified timestamp. Returns 0 on success,
  non-zero for failures.
- `get_clk_src_info`: Hook to get the clock information the provider uses
  to timestamp. Returns 0 for success and negative error code for failure. On
  success HTE subsystem fills up provided struct hte_clk_info.

**Description**

xlated_id parameter is used to communicate between HTE subsystem and the
providers and is translated by the provider.

#### <a id="c-struct-hte_chip"></a>`struct hte_chip`

Abstract HTE chip.

**Definition**

```c
struct hte_chip {
    const char *name;
    struct device *dev;
    const struct hte_ops *ops;
    u32 nlines;
    int (*xlate_of)(struct hte_chip *gc, const struct of_phandle_args *args, struct hte_ts_desc *desc, u32 *xlated_id);
    int (*xlate_plat)(struct hte_chip *gc, struct hte_ts_desc *desc, u32 *xlated_id);
    bool (*match_from_linedata)(const struct hte_chip *chip, const struct hte_ts_desc *hdesc);
    u8 of_hte_n_cells;
    struct hte_device *gdev;
    void *data;
};
```

**Members**

- `name`: functional name of the HTE IP block.
- `dev`: device providing the HTE.
- `ops`: callbacks for this HTE.
- `nlines`: number of lines/signals supported by this chip.
- `xlate_of`: Callback which translates consumer supplied logical ids to
  physical ids, return 0 for the success and negative for the failures.
  It stores (between 0 to **nlines**) in xlated_id parameter for the success.
- `xlate_plat`: Same as above but for the consumers with no DT node.
- `match_from_linedata`: Match HTE device using the line_data.
- `of_hte_n_cells`: Number of cells used to form the HTE specifier.
- `gdev`: HTE subsystem abstract device, internal to the HTE subsystem.
- `data`: chip specific private data.


<a id="rst-more-on-the-hte-timestamp-data"></a>

## More on the HTE timestamp data

The `struct hte_ts_data` is used to pass timestamp details between the consumers and the providers. It expresses timestamp data in nanoseconds in u64. An example of the typical timestamp data life cycle, for the GPIO line is as follows:



```text
- Monitors GPIO line change.
- Detects the state change on GPIO line.
- Converts timestamps in nanoseconds.
- Stores GPIO raw level in raw_level variable if the provider has that
hardware capability.
- Pushes this hte_ts_data object to HTE subsystem.
- HTE subsystem increments seq counter and invokes consumer provided callback.
Based on callback return value, the HTE core invokes secondary callback in
the thread context.
```

<a id="rst-hte-subsystem-debugfs-attributes"></a>

## HTE subsystem debugfs attributes

HTE subsystem creates debugfs attributes at `/sys/kernel/debug/hte/`. It also creates line/signal-related debugfs attributes at `/sys/kernel/debug/hte/<provider>/<label or line id>/`. Note that these attributes are read-only.

- **`ts_requested`**

  The total number of entities requested from the given provider, where entity is specified by the provider and could represent lines, GPIO, chip signals, buses etc... The attribute will be available at `/sys/kernel/debug/hte/<provider>/`.

- **`total_ts`**

  The total number of entities supported by the provider. The attribute will be available at `/sys/kernel/debug/hte/<provider>/`.

- **`dropped_timestamps`**

  The dropped timestamps for a given line. The attribute will be available at `/sys/kernel/debug/hte/<provider>/<label or line id>/`.

---

# HTE Kernel provider driver

_Peios Kernel / Hardware and drivers / Driver development / Hardware timestamps_

> The Nvidia tegra HTE provider also known as GTE (Generic Timestamping Engine) driver implements two GTE instances: 1) GPIO GTE and 2) LIC (Legacy Interrupt Controller) IRQ GTE. Both GTE instances get the timestamp from the system counter…

<a id="rst-hte-kernel-provider-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<a id="rst-description"></a>

## Description

The Nvidia tegra HTE provider also known as GTE (Generic Timestamping Engine) driver implements two GTE instances: 1) GPIO GTE and 2) LIC (Legacy Interrupt Controller) IRQ GTE. Both GTE instances get the timestamp from the system counter TSC which has 31.25MHz clock rate, and the driver converts clock tick rate to nanoseconds before storing it as timestamp value.

<a id="rst-gpio-gte"></a>

## GPIO GTE

This GTE instance timestamps GPIO in real time. For that to happen GPIO needs to be configured as input. Only the always on (AON) GPIO controller instance supports timestamping GPIOs in real time as it is tightly coupled with the GPIO GTE. To support this, GPIOLIB adds two optional APIs as mentioned below. The GPIO GTE code supports both kernel and userspace consumers. The kernel space consumers can directly talk to HTE subsystem while userspace consumers timestamp requests go through GPIOLIB CDEV framework to HTE subsystem. The hte devicetree binding described at `Documentation/devicetree/bindings/timestamp` provides an example of how a consumer can request an GPIO line.

See gpiod_enable_hw_timestamp_ns() and gpiod_disable_hw_timestamp_ns().

For userspace consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE flag must be specified during IOCTL calls. Refer to `tools/gpio/gpio-event-mon.c`, which returns the timestamp in nanoseconds.

<a id="rst-lic-legacy-interrupt-controller-irq-gte"></a>

## LIC (Legacy Interrupt Controller) IRQ GTE

This GTE instance timestamps LIC IRQ lines in real time. The hte devicetree binding described at `Documentation/devicetree/bindings/timestamp` provides an example of how a consumer can request an IRQ line. Since it is a one-to-one mapping with IRQ GTE provider, consumers can simply specify the IRQ number that they are interested in. There is no userspace consumer support for this GTE instance in the HTE framework.

The provider source code of both IRQ and GPIO GTE instances is located at `drivers/hte/hte-tegra194.c`. The test driver `drivers/hte/hte-tegra194-test.c` demonstrates HTE API usage for both IRQ and GPIO GTE.

---

# PLDM Firmware Flash Update Library

_Peios Kernel / Hardware and drivers / Driver development / PLDM firmware updates_

> pldmfw implements functionality for updating the flash on a device using the PLDM for Firmware Update standard <https://www.dmtf.org/documents/pmci/pldm-firmware-update-specification-100>.

<a id="rst-pldm-firmware-flash-update-library"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

`pldmfw` implements functionality for updating the flash on a device using the PLDM for Firmware Update standard &lt;[https://www.dmtf.org/documents/pmci/pldm-firmware-update-specification-100](<https://www.dmtf.org/documents/pmci/pldm-firmware-update-specification-100>)&gt;.

- [PLDM Firmware file format overview](</kernel/hardware/driver-api/pldmfw/file-format.md>)
- [Driver-specific callbacks](</kernel/hardware/driver-api/pldmfw/driver-ops.md>)

<a id="rst-overview-of-the-pldmfw-library"></a>

## Overview of the `pldmfw` library

The `pldmfw` library is intended to be used by device drivers for implementing device flash update based on firmware files following the PLDM firmware file format.

It is implemented using an ops table that allows device drivers to provide the underlying device specific functionality.

`pldmfw` implements logic to parse the packed binary format of the PLDM firmware file into data structures, and then uses the provided function operations to determine if the firmware file is a match for the device. If so, it sends the record and component data to the firmware using the device specific implementations provided by device drivers. Once the device firmware indicates that the update may be performed, the firmware data is sent to the device for programming.

<a id="rst-parsing-the-pldm-file"></a>

## Parsing the PLDM file

The PLDM file format uses packed binary data, with most multi-byte fields stored in the Little Endian format. Several pieces of data are variable length, including version strings and the number of records and components. Due to this, it is not straight forward to index the record, record descriptors, or components.

To avoid proliferating access to the packed binary data, the `pldmfw` library parses and extracts this data into simpler structures for ease of access.

In order to safely process the firmware file, care is taken to avoid unaligned access of multi-byte fields, and to properly convert from Little Endian to CPU host format. Additionally the records, descriptors, and components are stored in linked lists.

<a id="rst-performing-a-flash-update"></a>

## Performing a flash update

To perform a flash update, the `pldmfw` module performs the following steps

1. Parse the firmware file for record and component information

2. Scan through the records and determine if the device matches any record in the file. The first matched record will be used.

3. If the matching record provides package data, send this package data to the device.

4. For each component that the record indicates, send the component data to the device. For each component, the firmware may respond with an indication of whether the update is suitable or not. If any component is not suitable, the update is canceled.

5. For each component, send the binary data to the device firmware for updating.

6. After all components are programmed, perform any final device-specific actions to finalize the update.

---

# Driver-specific callbacks

_Peios Kernel / Hardware and drivers / Driver development / PLDM firmware updates_

> The pldmfw module relies on the device driver for implementing device specific behavior using the following operations.

<a id="rst-driver-specific-callbacks"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

The `pldmfw` module relies on the device driver for implementing device specific behavior using the following operations.

<a id="rst-match-record"></a>

## `.match_record`

The `.match_record` operation is used to determine whether a given PLDM record matches the device being updated. This requires comparing the record descriptors in the record with information from the device. Many record descriptors are defined by the PLDM standard, but it is also allowed for devices to implement their own descriptors.

The `.match_record` operation should return true if a given record matches the device.

<a id="rst-send-package-data"></a>

## `.send_package_data`

The `.send_package_data` operation is used to send the device-specific package data in a record to the device firmware. If the matching record provides package data, `pldmfw` will call the `.send_package_data` function with a pointer to the package data and with the package data length. The device driver should send this data to firmware.

<a id="rst-send-component-table"></a>

## `.send_component_table`

The `.send_component_table` operation is used to forward component information to the device. It is called once for each applicable component, that is, for each component indicated by the matching record. The device driver should send the component information to the device firmware, and wait for a response. The provided transfer flag indicates whether this is the first, last, or a middle component, and is expected to be forwarded to firmware as part of the component table information. The driver should an error in the case when the firmware indicates that the component cannot be updated, or return zero if the component can be updated.

<a id="rst-flash-component"></a>

## `.flash_component`

The `.flash_component` operation is used to inform the device driver to flash a given component. The driver must perform any steps necessary to send the component data to the device.

<a id="rst-finalize-update"></a>

## `.finalize_update`

The `.finalize_update` operation is used by the `pldmfw` library in order to allow the device driver to perform any remaining device specific logic needed to finish the update.

---

# PLDM Firmware file format overview

_Peios Kernel / Hardware and drivers / Driver development / PLDM firmware updates_

> A PLDM firmware package is a binary file which contains a header that describes the contents of the firmware package. This includes an initial package header, one or more firmware records, and one or more components describing the actual…

<a id="rst-pldm-firmware-file-format-overview"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

A PLDM firmware package is a binary file which contains a header that describes the contents of the firmware package. This includes an initial package header, one or more firmware records, and one or more components describing the actual flash contents to program.

This diagram provides an overview of the file format:



```text
  overall file layout
+----------------------+
|                      |
|  Package Header      |
|                      |
+----------------------+
|                      |
|  Device Records      |
|                      |
+----------------------+
|                      |
|  Component Info      |
|                      |
+----------------------+
|                      |
|  Package Header CRC  |
|                      |
+----------------------+
|                      |
|  Component Image 1   |
|                      |
+----------------------+
|                      |
|  Component Image 2   |
|                      |
+----------------------+
|                      |
|         ...          |
|                      |
+----------------------+
|                      |
|  Component Image N   |
|                      |
+----------------------+
```

<a id="rst-package-header"></a>

## Package Header

The package header begins with the UUID of the PLDM file format, and contains information about the version of the format that the file uses. It also includes the total header size, a release date, the size of the component bitmap, and an overall package version.

The following diagram provides an overview of the package header:



```text
       header layout
+-------------------------+
| PLDM UUID               |
+-------------------------+
| Format Revision         |
+-------------------------+
| Header Size             |
+-------------------------+
| Release Date            |
+-------------------------+
| Component Bitmap Length |
+-------------------------+
| Package Version Info    |
+-------------------------+
```

<a id="rst-device-records"></a>

## Device Records

The device firmware records area starts with a count indicating the total number of records in the file, followed by each record. A single device record describes what device matches this record. All valid PLDM firmware files must contain at least one record, but optionally may contain more than one record if they support multiple devices.

Each record will identify the device it supports via TLVs that describe the device, such as the PCI device and vendor information. It will also indicate which set of components that are used by this device. It is possible that only subset of provided components will be used by a given record. A record may also optionally contain device-specific package data that will be used by the device firmware during the update process.

The following diagram provides an overview of the device record area:



```text
   area layout
+---------------+
|               |
|  Record Count |
|               |
+---------------+
|               |
|  Record 1     |
|               |
+---------------+
|               |
|  Record 2     |
|               |
+---------------+
|               |
|      ...      |
|               |
+---------------+
|               |
|  Record N     |
|               |
+---------------+

     record layout
+-----------------------+
| Record Length         |
+-----------------------+
| Descriptor Count      |
+-----------------------+
| Option Flags          |
+-----------------------+
| Version Settings      |
+-----------------------+
| Package Data Length   |
+-----------------------+
| Applicable Components |
+-----------------------+
| Version String        |
+-----------------------+
| Descriptor TLVs       |
+-----------------------+
| Package Data          |
+-----------------------+
```

<a id="rst-component-info"></a>

## Component Info

The component information area begins with a count of the number of components. Following this count is a description for each component. The component information points to the location in the file where the component data is stored, and includes version data used to identify the version of the component.

The following diagram provides an overview of the component area:



```text
   area layout
+-----------------+
|                 |
| Component Count |
|                 |
+-----------------+
|                 |
| Component 1     |
|                 |
+-----------------+
|                 |
| Component 2     |
|                 |
+-----------------+
|                 |
|     ...         |
|                 |
+-----------------+
|                 |
| Component N     |
|                 |
+-----------------+

     component layout
+------------------------+
| Classification         |
+------------------------+
| Component Identifier   |
+------------------------+
| Comparison Stamp       |
+------------------------+
| Component Options      |
+------------------------+
| Activation Method      |
+------------------------+
| Location Offset        |
+------------------------+
| Component Size         |
+------------------------+
| Component Version Info |
+------------------------+
| Package Data           |
+------------------------+
```

<a id="rst-package-header-crc"></a>

## Package Header CRC

Following the component information is a short 4-byte CRC calculated over the contents of all of the header information.

<a id="rst-component-images"></a>

## Component Images

The component images follow the package header information in the PLDM firmware file. Each of these is simply a binary chunk with its start and size defined by the matching component structure in the component info area.

---

# CPU and Device Power Management

_Peios Kernel / Hardware and drivers / Driver development / Power management_

> Reference for CPU and Device Power Management.

<a id="rst-cpu-and-device-power-management"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [CPU Idle Time Management](</kernel/hardware/driver-api/pm/cpuidle.md>)
- [Device Power Management Basics](</kernel/hardware/driver-api/pm/devices.md>)
- [Suspend/Hibernation Notifiers](</kernel/hardware/driver-api/pm/notifiers.md>)
- [Device Power Management Data Types](</kernel/hardware/driver-api/pm/types.md>)

---

# CPU Idle Time Management

_Peios Kernel / Hardware and drivers / Driver development / Power management_

> Every time one of the logical CPUs in the system (the entities that appear to fetch and execute instructions: hardware threads, if present, or processor cores) is idle after an interrupt or equivalent wakeup event, which means that there…

<a id="rst-cpu-idle-time-management"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2019 Intel Corporation

**Author:** Rafael J. Wysocki &lt;[rafael.j.wysocki@intel.com](<mailto:rafael.j.wysocki@intel.com>)&gt;

<a id="rst-cpu-idle-time-management-subsystem"></a>

## CPU Idle Time Management Subsystem

Every time one of the logical CPUs in the system (the entities that appear to fetch and execute instructions: hardware threads, if present, or processor cores) is idle after an interrupt or equivalent wakeup event, which means that there are no tasks to run on it except for the special "idle" task associated with it, there is an opportunity to save energy for the processor that it belongs to.  That can be done by making the idle logical CPU stop fetching instructions from memory and putting some of the processor's functional units depended on by it into an idle state in which they will draw less power.

However, there may be multiple different idle states that can be used in such a situation in principle, so it may be necessary to find the most suitable one (from the kernel perspective) and ask the processor to use (or "enter") that particular idle state.  That is the role of the CPU idle time management subsystem in the kernel, called `CPUIdle`.

The design of `CPUIdle` is modular and based on the code duplication avoidance principle, so the generic code that in principle need not depend on the hardware or platform design details in it is separate from the code that interacts with the hardware.  It generally is divided into three categories of functional units: *governors* responsible for selecting idle states to ask the processor to enter, *drivers* that pass the governors' decisions on to the hardware and the *core* providing a common framework for them.

<a id="rst-cpu-idle-time-governors"></a>

## CPU Idle Time Governors

A CPU idle time (`CPUIdle`) governor is a bundle of policy code invoked when one of the logical CPUs in the system turns out to be idle.  Its role is to select an idle state to ask the processor to enter in order to save some energy.

`CPUIdle` governors are generic and each of them can be used on any hardware platform that the Linux kernel can run on.  For this reason, data structures operated on by them cannot depend on any hardware architecture or platform design details as well.

The governor itself is represented by a struct cpuidle_governor object containing four callback pointers, `enable`, `disable`, `select`, `reflect`, a `rating` field described below, and a name (string) used for identifying it.

For the governor to be available at all, that object needs to be registered with the `CPUIdle` core by calling `cpuidle_register_governor()` with a pointer to it passed as the argument.  If successful, that causes the core to add the governor to the global list of available governors and, if it is the only one in the list (that is, the list was empty before) or the value of its `rating` field is greater than the value of that field for the governor currently in use, or the name of the new governor was passed to the kernel as the value of the `cpuidle.governor=` command line parameter, the new governor will be used from that point on (there can be only one `CPUIdle` governor in use at a time).  Also, user space can choose the `CPUIdle` governor to use at run time via `sysfs`.

Once registered, `CPUIdle` governors cannot be unregistered, so it is not practical to put them into loadable kernel modules.

The interface between `CPUIdle` governors and the core consists of four callbacks:

- **`enable`**



  ```text
  int (*enable) (struct cpuidle_driver *drv, struct cpuidle_device *dev);
  ```

  The role of this callback is to prepare the governor for handling the (logical) CPU represented by the struct cpuidle_device object   pointed to by the `dev` argument.  The struct cpuidle_driver object pointed to by the `drv` argument represents the `CPUIdle` driver to be used with that CPU (among other things, it should contain the list of struct cpuidle_state objects representing idle states that the processor holding the given CPU can be asked to enter).

  It may fail, in which case it is expected to return a negative error code, and that causes the kernel to run the architecture-specific default code for idle CPUs on the CPU in question instead of `CPUIdle` until the `->enable()` governor callback is invoked for that CPU again.

- **`disable`**



  ```text
  void (*disable) (struct cpuidle_driver *drv, struct cpuidle_device *dev);
  ```

  Called to make the governor stop handling the (logical) CPU represented by the struct cpuidle_device object pointed to by the `dev` argument.

  It is expected to reverse any changes made by the `->enable()` callback when it was last invoked for the target CPU, free all memory allocated by that callback and so on.

- **`select`**



  ```text
  int (*select) (struct cpuidle_driver *drv, struct cpuidle_device *dev,
                 bool *stop_tick);
  ```

  Called to select an idle state for the processor holding the (logical) CPU represented by the struct cpuidle_device object pointed to by the `dev` argument.

  The list of idle states to take into consideration is represented by the `states` array of struct cpuidle_state objects held by the struct cpuidle_driver object pointed to by the `drv` argument (which represents the `CPUIdle` driver to be used with the CPU at hand).  The value returned by this callback is interpreted as an index into that array (unless it is a negative error code).

  The `stop_tick` argument is used to indicate whether or not to stop the scheduler tick before asking the processor to enter the selected idle state.  When the `bool` variable pointed to by it (which is set to `true` before invoking this callback) is cleared to `false`, the processor will be asked to enter the selected idle state without stopping the scheduler tick on the given CPU (if the tick has been stopped on that CPU already, however, it will not be restarted before asking the processor to enter the idle state).

  This callback is mandatory (i.e. the `select` callback pointer in struct cpuidle_governor must not be `NULL` for the registration of the governor to succeed).

- **`reflect`**



  ```text
  void (*reflect) (struct cpuidle_device *dev, int index);
  ```

  Called to allow the governor to evaluate the accuracy of the idle state selection made by the `->select()` callback (when it was invoked last time) and possibly use the result of that to improve the accuracy of idle state selections in the future.

In addition, `CPUIdle` governors are required to take power management quality of service (PM QoS) constraints on the processor wakeup latency into account when selecting idle states.  In order to obtain the current effective PM QoS wakeup latency constraint for a given CPU, a `CPUIdle` governor is expected to pass the number of the CPU to `cpuidle_governor_latency_req()`.  Then, the governor's `->select()` callback must not return the index of an indle state whose `exit_latency` value is greater than the number returned by that function.

<a id="rst-cpu-idle-time-management-drivers"></a>

## CPU Idle Time Management Drivers

CPU idle time management (`CPUIdle`) drivers provide an interface between the other parts of `CPUIdle` and the hardware.

First of all, a `CPUIdle` driver has to populate the `states` array of struct cpuidle_state objects included in the struct cpuidle_driver object representing it.  Going forward this array will represent the list of available idle states that the processor hardware can be asked to enter shared by all of the logical CPUs handled by the given driver.

The entries in the `states` array are expected to be sorted by the value of the `target_residency` field in struct cpuidle_state in the ascending order (that is, index 0 should correspond to the idle state with the minimum value of `target_residency`).  \[Since the `target_residency` value is expected to reflect the "depth" of the idle state represented by the struct cpuidle_state object holding it, this sorting order should be the same as the ascending sorting order by the idle state "depth".\]

Three fields in struct cpuidle_state are used by the existing `CPUIdle` governors for computations related to idle state selection:

- **`target_residency`**

  Minimum time to spend in this idle state including the time needed to enter it (which may be substantial) to save more energy than could be saved by staying in a shallower idle state for the same amount of time, in microseconds.

- **`exit_latency`**

  Maximum time it will take a CPU asking the processor to enter this idle state to start executing the first instruction after a wakeup from it, in microseconds.

- **`flags`**

  Flags representing idle state properties.  Currently, governors only use the `CPUIDLE_FLAG_POLLING` flag which is set if the given object does not represent a real idle state, but an interface to a software "loop" that can be used in order to avoid asking the processor to enter any idle state at all.  \[There are other flags used by the `CPUIdle` core in special situations.\]

The `enter` callback pointer in struct cpuidle_state, which must not be `NULL`, points to the routine to execute in order to ask the processor to enter this particular idle state:



```text
void (*enter) (struct cpuidle_device *dev, struct cpuidle_driver *drv,
               int index);
```

The first two arguments of it point to the struct cpuidle_device object representing the logical CPU running this callback and the struct cpuidle_driver object representing the driver itself, respectively, and the last one is an index of the struct cpuidle_state entry in the driver's `states` array representing the idle state to ask the processor to enter.

The analogous `->enter_s2idle()` callback in struct cpuidle_state is used only for implementing the suspend-to-idle system-wide power management feature. The difference between in and `->enter()` is that it must not re-enable interrupts at any point (even temporarily) or attempt to change the states of clock event devices, which the `->enter()` callback may do sometimes.

Once the `states` array has been populated, the number of valid entries in it has to be stored in the `state_count` field of the struct cpuidle_driver object representing the driver.  Moreover, if any entries in the `states` array represent "coupled" idle states (that is, idle states that can only be asked for if multiple related logical CPUs are idle), the `safe_state_index` field in struct cpuidle_driver needs to be the index of an idle state that is not "coupled" (that is, one that can be asked for if only one logical CPU is idle).

In addition to that, if the given `CPUIdle` driver is only going to handle a subset of logical CPUs in the system, the `cpumask` field in its struct cpuidle_driver object must point to the set (mask) of CPUs that will be handled by it.

A `CPUIdle` driver can only be used after it has been registered.  If there are no "coupled" idle state entries in the driver's `states` array, that can be accomplished by passing the driver's struct cpuidle_driver object to `cpuidle_register_driver()`.  Otherwise, `cpuidle_register()` should be used for this purpose.

However, it also is necessary to register struct cpuidle_device objects for all of the logical CPUs to be handled by the given `CPUIdle` driver with the help of `cpuidle_register_device()` after the driver has been registered and `cpuidle_register_driver()`, unlike `cpuidle_register()`, does not do that automatically.  For this reason, the drivers that use `cpuidle_register_driver()` to register themselves must also take care of registering the struct cpuidle_device objects as needed, so it is generally recommended to use `cpuidle_register()` for `CPUIdle` driver registration in all cases.

The registration of a struct cpuidle_device object causes the `CPUIdle` `sysfs` interface to be created and the governor's `->enable()` callback to be invoked for the logical CPU represented by it, so it must take place after registering the driver that will handle the CPU in question.

`CPUIdle` drivers and struct cpuidle_device objects can be unregistered when they are not necessary any more which allows some resources associated with them to be released.  Due to dependencies between them, all of the struct cpuidle_device objects representing CPUs handled by the given `CPUIdle` driver must be unregistered, with the help of `cpuidle_unregister_device()`, before calling `cpuidle_unregister_driver()` to unregister the driver.  Alternatively, `cpuidle_unregister()` can be called to unregister a `CPUIdle` driver along with all of the struct cpuidle_device objects representing CPUs handled by it.

`CPUIdle` drivers can respond to runtime system configuration changes that lead to modifications of the list of available processor idle states (which can happen, for example, when the system's power source is switched from AC to battery or the other way around).  Upon a notification of such a change, a `CPUIdle` driver is expected to call `cpuidle_pause_and_lock()` to turn `CPUIdle` off temporarily and then `cpuidle_disable_device()` for all of the struct cpuidle_device objects representing CPUs affected by that change.  Next, it can update its `states` array in accordance with the new configuration of the system, call `cpuidle_enable_device()` for all of the relevant struct cpuidle_device objects and invoke `cpuidle_resume_and_unlock()` to allow `CPUIdle` to be used again.

---

# Device Power Management Basics

_Peios Kernel / Hardware and drivers / Driver development / Power management_

> Most of the code in Linux is device drivers, so most of the Linux power management (PM) code is also driver-specific. Most drivers will do very little; others, especially for platforms with small batteries (like cell phones), will do a lot.

<a id="rst-device-power-management-basics"></a>
<a id="rst-driverapi-pm-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2010-2011 Rafael J. Wysocki &lt;[rjw@sisk.pl](<mailto:rjw@sisk.pl>)&gt;, Novell Inc.

**Copyright:** © 2010 Alan Stern &lt;[stern@rowland.harvard.edu](<mailto:stern@rowland.harvard.edu>)&gt;

**Copyright:** © 2016 Intel Corporation

**Author:** Rafael J. Wysocki &lt;[rafael.j.wysocki@intel.com](<mailto:rafael.j.wysocki@intel.com>)&gt;

Most of the code in Linux is device drivers, so most of the Linux power management (PM) code is also driver-specific.  Most drivers will do very little; others, especially for platforms with small batteries (like cell phones), will do a lot.

This writeup gives an overview of how drivers interact with system-wide power management goals, emphasizing the models and interfaces that are shared by everything that hooks up to the driver model core.  Read it as background for the domain-specific work you'd do with any specific driver.

<a id="rst-two-models-for-device-power-management"></a>

## Two Models for Device Power Management

Drivers will use one or both of these models to put devices into low-power states:

> System Sleep model:
>
> > Drivers can enter low-power states as part of entering system-wide low-power states like "suspend" (also known as "suspend-to-RAM"), or (mostly for systems with disks) "hibernation" (also known as "suspend-to-disk").
> >
> > This is something that device, bus, and class drivers collaborate on by implementing various role-specific suspend and resume methods to cleanly power down hardware and software subsystems, then reactivate them without loss of data.
> >
> > Some drivers can manage hardware wakeup events, which make the system leave the low-power state.  This feature may be enabled or disabled using the relevant `/sys/devices/.../power/wakeup` file (for Ethernet drivers the ioctl interface used by ethtool may also be used for this purpose); enabling it may cost some power usage, but let the whole system enter low-power states more often.
>
> Runtime Power Management model:
>
> > Devices may also be put into low-power states while the system is running, independently of other power management activity in principle. However, devices are not generally independent of each other (for example, a parent device cannot be suspended unless all of its child devices have been suspended).  Moreover, depending on the bus type the device is on, it may be necessary to carry out some bus-specific operations on the device for this purpose.  Devices put into low power states at run time may require special handling during system-wide power transitions (suspend or hibernation).
> >
> > For these reasons not only the device driver itself, but also the appropriate subsystem (bus type, device type or device class) driver and the PM core are involved in runtime power management.  As in the system sleep power management case, they need to collaborate by implementing various role-specific suspend and resume methods, so that the hardware is cleanly powered down and reactivated without data or service loss.

There's not a lot to be said about those low-power states except that they are very system-specific, and often device-specific.  Also, that if enough devices have been put into low-power states (at runtime), the effect may be very similar to entering some system-wide low-power state (system sleep) ... and that synergies exist, so that several drivers using runtime PM might put the system into a state where even deeper power saving options are available.

Most suspended devices will have quiesced all I/O: no more DMA or IRQs (except for wakeup events), no more data read or written, and requests from upstream drivers are no longer accepted.  A given bus or platform may have different requirements though.

Examples of hardware wakeup events include an alarm from a real time clock, network wake-on-LAN packets, keyboard or mouse activity, and media insertion or removal (for PCMCIA, MMC/SD, USB, and so on).

<a id="rst-interfaces-for-entering-system-sleep-states"></a>

## Interfaces for Entering System Sleep States

There are programming interfaces provided for subsystems (bus type, device type, device class) and device drivers to allow them to participate in the power management of devices they are concerned with.  These interfaces cover both system sleep and runtime power management.

<a id="rst-device-power-management-operations"></a>

### Device Power Management Operations

Device power management operations, at the subsystem level as well as at the device driver level, are implemented by defining and populating objects of type struct dev_pm_ops defined in `include/linux/pm.h`.  The roles of the methods included in it will be explained in what follows.  For now, it should be sufficient to remember that the last three methods are specific to runtime power management while the remaining ones are used during system-wide power transitions.

There also is a deprecated "old" or "legacy" interface for power management operations available at least for some subsystems.  This approach does not use struct dev_pm_ops objects and it is suitable only for implementing system sleep power management methods in a limited way.  Therefore it is not described in this document, so please refer directly to the source code for more information about it.

<a id="rst-subsystem-level-methods"></a>

### Subsystem-Level Methods

The core methods to suspend and resume devices reside in struct dev_pm_ops pointed to by the `ops` member of struct dev_pm_domain, or by the `pm` member of struct bus_type, struct device_type and struct class.  They are mostly of interest to the people writing infrastructure for platforms and buses, like PCI or USB, or device type and device class drivers.  They also are relevant to the writers of device drivers whose subsystems (PM domains, device types, device classes and bus types) don't provide all power management methods.

Bus drivers implement these methods as appropriate for the hardware and the drivers using it; PCI works differently from USB, and so on.  Not many people write subsystem-level drivers; most driver code is a "device driver" that builds on top of bus-specific framework code.

For more information on these driver calls, see the description later; they are called in phases for every device, respecting the parent-child sequencing in the driver model tree.

<a id="rst-sys-devices-power-wakeup-files"></a>

### `/sys/devices/.../power/wakeup` files

All device objects in the driver model contain fields that control the handling of system wakeup events (hardware signals that can force the system out of a sleep state).  These fields are initialized by bus or device driver code using `device_set_wakeup_capable()` and `device_set_wakeup_enable()`, defined in `include/linux/pm_wakeup.h`.

The `power.can_wakeup` flag just records whether the device (and its driver) can physically support wakeup events.  The `device_set_wakeup_capable()` routine affects this flag.  The `power.wakeup` field is a pointer to an object of type struct wakeup_source used for controlling whether or not the device should use its system wakeup mechanism and for notifying the PM core of system wakeup events signaled by the device.  This object is only present for wakeup-capable devices (i.e. devices whose `can_wakeup` flags are set) and is created (or removed) by `device_set_wakeup_capable()`.

Whether or not a device is capable of issuing wakeup events is a hardware matter, and the kernel is responsible for keeping track of it.  By contrast, whether or not a wakeup-capable device should issue wakeup events is a policy decision, and it is managed by user space through a sysfs attribute: the `power/wakeup` file.  User space can write the "enabled" or "disabled" strings to it to indicate whether or not, respectively, the device is supposed to signal system wakeup.  This file is only present if the `power.wakeup` object exists for the given device and is created (or removed) along with that object, by `device_set_wakeup_capable()`. Reads from the file will return the corresponding string.

The initial value in the `power/wakeup` file is "disabled" for the majority of devices; the major exceptions are power buttons, keyboards, and Ethernet adapters whose WoL (wake-on-LAN) feature has been set up with ethtool. It should also default to "enabled" for devices that don't generate wakeup requests on their own but merely forward wakeup requests from one bus to another (like PCI Express ports).

The `device_may_wakeup()` routine returns true only if the `power.wakeup` object exists and the corresponding `power/wakeup` file contains the "enabled" string.  This information is used by subsystems, like the PCI bus type code, to see whether or not to enable the devices' wakeup mechanisms.  If device wakeup mechanisms are enabled or disabled directly by drivers, they also should use `device_may_wakeup()` to decide what to do during a system sleep transition.  Device drivers, however, are not expected to call `device_set_wakeup_enable()` directly in any case.

It ought to be noted that system wakeup is conceptually different from "remote wakeup" used by runtime power management, although it may be supported by the same physical mechanism.  Remote wakeup is a feature allowing devices in low-power states to trigger specific interrupts to signal conditions in which they should be put into the full-power state.  Those interrupts may or may not be used to signal system wakeup events, depending on the hardware design.  On some systems it is impossible to trigger them from system sleep states.  In any case, remote wakeup should always be enabled for runtime power management for all devices and drivers that support it.

<a id="rst-sys-devices-power-control-files"></a>

### `/sys/devices/.../power/control` files

Each device in the driver model has a flag to control whether it is subject to runtime power management.  This flag, `runtime_auto`, is initialized by the bus type (or generally subsystem) code using `pm_runtime_allow()` or `pm_runtime_forbid()`; the default is to allow runtime power management.

The setting can be adjusted by user space by writing either "on" or "auto" to the device's `power/control` sysfs file.  Writing "auto" calls `pm_runtime_allow()`, setting the flag and allowing the device to be runtime power-managed by its driver.  Writing "on" calls `pm_runtime_forbid()`, clearing the flag, returning the device to full power if it was in a low-power state, and preventing the device from being runtime power-managed.  User space can check the current value of the `runtime_auto` flag by reading that file.

The device's `runtime_auto` flag has no effect on the handling of system-wide power transitions.  In particular, the device can (and in the majority of cases should and will) be put into a low-power state during a system-wide transition to a sleep state even though its `runtime_auto` flag is clear.

For more information about the runtime power management framework, refer to [Documentation/power/runtime_pm.rst](/kernel/internals/power/runtime-pm.md).

<a id="rst-calling-drivers-to-enter-and-leave-system-sleep-states"></a>

## Calling Drivers to Enter and Leave System Sleep States

When the system goes into a sleep state, each device's driver is asked to suspend the device by putting it into a state compatible with the target system state.  That's usually some version of "off", but the details are system-specific.  Also, wakeup-enabled devices will usually stay partly functional in order to wake the system.

When the system leaves that low-power state, the device's driver is asked to resume it by returning it to full power.  The suspend and resume operations always go together, and both are multi-phase operations.

For simple drivers, suspend might quiesce the device using class code and then turn its hardware as "off" as possible during suspend_noirq.  The matching resume calls would then completely reinitialize the hardware before reactivating its class I/O queues.

More power-aware drivers might prepare the devices for triggering system wakeup events.

<a id="rst-call-sequence-guarantees"></a>

### Call Sequence Guarantees

To ensure that bridges and similar links needing to talk to a device are available when the device is suspended or resumed, the device hierarchy is walked in a bottom-up order to suspend devices.  A top-down order is used to resume those devices.

The ordering of the device hierarchy is defined by the order in which devices get registered:  a child can never be registered, probed or resumed before its parent; and can't be removed or suspended after that parent.

The policy is that the device hierarchy should match hardware bus topology. \[Or at least the control bus, for devices which use multiple buses.\] In particular, this means that a device registration may fail if the parent of the device is suspending (i.e. has been chosen by the PM core as the next device to suspend) or has already suspended, as well as after all of the other devices have been suspended.  Device drivers must be prepared to cope with such situations.

<a id="rst-system-power-management-phases"></a>

### System Power Management Phases

Suspending or resuming the system is done in several phases.  Different phases are used for suspend-to-idle, shallow (standby), and deep ("suspend-to-RAM") sleep states and the hibernation state ("suspend-to-disk").  Each phase involves executing callbacks for every device before the next phase begins.  Not all buses or classes support all these callbacks and not all drivers use all the callbacks.  The various phases always run after tasks have been frozen and before they are unfrozen.  Furthermore, the `*_noirq` phases run at a time when IRQ handlers have been disabled (except for those marked with the IRQF_NO_SUSPEND flag).

All phases use PM domain, bus, type, class or driver callbacks (that is, methods defined in `dev->pm_domain->ops`, `dev->bus->pm`, `dev->type->pm`, `dev->class->pm` or `dev->driver->pm`).  These callbacks are regarded by the PM core as mutually exclusive.  Moreover, PM domain callbacks always take precedence over all of the other callbacks and, for example, type callbacks take precedence over bus, class and driver callbacks.  To be precise, the following rules are used to determine which callback to execute in the given phase:

> 1. If `dev->pm_domain` is present, the PM core will choose the callback provided by `dev->pm_domain->ops` for execution.
>
> 2. Otherwise, if both `dev->type` and `dev->type->pm` are present, the callback provided by `dev->type->pm` will be chosen for execution.
>
> 3. Otherwise, if both `dev->class` and `dev->class->pm` are present, the callback provided by `dev->class->pm` will be chosen for execution.
>
> 4. Otherwise, if both `dev->bus` and `dev->bus->pm` are present, the callback provided by `dev->bus->pm` will be chosen for execution.

This allows PM domains and device types to override callbacks provided by bus types or device classes if necessary.

The PM domain, type, class and bus callbacks may in turn invoke device- or driver-specific methods stored in `dev->driver->pm`, but they don't have to do that.

If the subsystem callback chosen for execution is not present, the PM core will execute the corresponding method from the `dev->driver->pm` set instead if there is one.

<a id="rst-entering-system-suspend"></a>

### Entering System Suspend

When the system goes into the freeze, standby or memory sleep state, the phases are: `prepare`, `suspend`, `suspend_late`, `suspend_noirq`.

> 1. The `prepare` phase is meant to prevent races by preventing new devices from being registered; the PM core would never know that all the children of a device had been suspended if new children could be registered at will.  \[By contrast, from the PM core's perspective, devices may be unregistered at any time.\]  Unlike the other suspend-related phases, during the `prepare` phase the device hierarchy is traversed top-down.
>
>    After the `->prepare` callback method returns, no new children may be registered below the device.  The method may also prepare the device or driver in some way for the upcoming system power transition, but it should not put the device into a low-power state.  Moreover, if the device supports runtime power management, the `->prepare` callback method must not update its state in case it is necessary to resume it from runtime suspend later on.
>
>    For devices supporting runtime power management, the return value of the prepare callback can be used to indicate to the PM core that it may safely leave the device in runtime suspend (if runtime-suspended already), provided that all of the device's descendants are also left in runtime suspend.  Namely, if the prepare callback returns a positive number and that happens for all of the descendants of the device too, and all of them (including the device itself) are runtime-suspended, the PM core will skip the `suspend`, `suspend_late` and `suspend_noirq` phases as well as all of the corresponding phases of the subsequent device resume for all of these devices.  In that case, the `->complete` callback will be the next one invoked after the `->prepare` callback and is entirely responsible for putting the device into a consistent state as appropriate.
>
>    Note that this direct-complete procedure applies even if the device is disabled for runtime PM; only the runtime-PM status matters.  It follows that if a device has system-sleep callbacks but does not support runtime PM, then its prepare callback must never return a positive value.  This is because all such devices are initially set to runtime-suspended with runtime PM disabled.
>
>    This feature also can be controlled by device drivers by using the `DPM_FLAG_NO_DIRECT_COMPLETE` and `DPM_FLAG_SMART_PREPARE` driver power management flags.  \[Typically, they are set at the time the driver is probed against the device in question by passing them to the `dev_pm_set_driver_flags()` helper function.\]  If the first of these flags is set, the PM core will not apply the direct-complete procedure described above to the given device and, consequently, to any of its ancestors.  The second flag, when set, informs the middle layer code (bus types, device types, PM domains, classes) that it should take the return value of the `->prepare` callback provided by the driver into account and it may only return a positive value from its own `->prepare` callback if the driver's one also has returned a positive value.
>
> 2. The `->suspend` methods should quiesce the device to stop it from performing I/O.  They also may save the device registers and put it into the appropriate low-power state, depending on the bus type the device is on, and they may enable wakeup events.
>
>    However, for devices supporting runtime power management, the `->suspend` methods provided by subsystems (bus types and PM domains in particular) must follow an additional rule regarding what can be done to the devices before their drivers' `->suspend` methods are called. Namely, they may resume the devices from runtime suspend by calling `pm_runtime_resume()` for them, if that is necessary, but they must not update the state of the devices in any other way at that time (in case the drivers need to resume the devices from runtime suspend in their `->suspend` methods).  In fact, the PM core prevents subsystems or drivers from putting devices into runtime suspend at these times by calling `pm_runtime_get_noresume()` before issuing the `->prepare` callback (and calling `pm_runtime_put()` after issuing the `->complete` callback).
>
> 3. For a number of devices it is convenient to split suspend into the "quiesce device" and "save device state" phases, in which cases `suspend_late` is meant to do the latter.  It is always executed after runtime power management has been disabled for the device in question.
>
> 4. The `suspend_noirq` phase occurs after IRQ handlers have been disabled, which means that the driver's interrupt handler will not be called while the callback method is running.  The `->suspend_noirq` methods should save the values of the device's registers that weren't saved previously and finally put the device into the appropriate low-power state.
>
>    The majority of subsystems and device drivers need not implement this callback.  However, bus types allowing devices to share interrupt vectors, like PCI, generally need it; otherwise a driver might encounter an error during the suspend phase by fielding a shared interrupt generated by some other device after its own device had been set to low power.

At the end of these phases, drivers should have stopped all I/O transactions (DMA, IRQs), saved enough state that they can re-initialize or restore previous state (as needed by the hardware), and placed the device into a low-power state. On many platforms they will gate off one or more clock sources; sometimes they will also switch off power supplies or reduce voltages.  \[Drivers supporting runtime PM may already have performed some or all of these steps.\]

If `device_may_wakeup()` returns `true`, the device should be prepared for generating hardware wakeup signals to trigger a system wakeup event when the system is in the sleep state.  For example, `enable_irq_wake()` might identify GPIO signals hooked up to a switch or other external hardware, and `pci_enable_wake()` does something similar for the PCI PME signal.

If any of these callbacks returns an error, the system won't enter the desired low-power state.  Instead, the PM core will unwind its actions by resuming all the devices that were suspended.

<a id="rst-leaving-system-suspend"></a>

### Leaving System Suspend

When resuming from freeze, standby or memory sleep, the phases are: `resume_noirq`, `resume_early`, `resume`, `complete`.

> 1. The `->resume_noirq` callback methods should perform any actions needed before the driver's interrupt handlers are invoked.  This generally means undoing the actions of the `suspend_noirq` phase.  If the bus type permits devices to share interrupt vectors, like PCI, the method should bring the device and its driver into a state in which the driver can recognize if the device is the source of incoming interrupts, if any, and handle them correctly.
>
>    For example, the PCI bus type's `->pm.resume_noirq()` puts the device into the full-power state (D0 in the PCI terminology) and restores the standard configuration registers of the device.  Then it calls the device driver's `->pm.resume_noirq()` method to perform device-specific actions.
>
> 2. The `->resume_early` methods should prepare devices for the execution of the resume methods.  This generally involves undoing the actions of the preceding `suspend_late` phase.
>
> 3. The `->resume` methods should bring the device back to its operating state, so that it can perform normal I/O.  This generally involves undoing the actions of the `suspend` phase.
>
> 4. The `complete` phase should undo the actions of the `prepare` phase. For this reason, unlike the other resume-related phases, during the `complete` phase the device hierarchy is traversed bottom-up.
>
>    Note, however, that new children may be registered below the device as soon as the `->resume` callbacks occur; it's not necessary to wait until the `complete` phase runs.
>
>    Moreover, if the preceding `->prepare` callback returned a positive number, the device may have been left in runtime suspend throughout the whole system suspend and resume (its `->suspend`, `->suspend_late`, `->suspend_noirq`, `->resume_noirq`, `->resume_early`, and `->resume` callbacks may have been skipped).  In that case, the `->complete` callback is entirely responsible for putting the device into a consistent state after system suspend if necessary.  \[For example, it may need to queue up a runtime resume request for the device for this purpose.\]  To check if that is the case, the `->complete` callback can consult the device's `power.direct_complete` flag.  If that flag is set when the `->complete` callback is being run then the direct-complete mechanism was used, and special actions may be required to make the device work correctly afterward.

At the end of these phases, drivers should be as functional as they were before suspending: I/O can be performed using DMA and IRQs, and the relevant clocks are gated on.

However, the details here may again be platform-specific.  For example, some systems support multiple "run" states, and the mode in effect at the end of resume might not be the one which preceded suspension. That means availability of certain clocks or power supplies changed, which could easily affect how a driver works.

Drivers need to be able to handle hardware which has been reset since all of the suspend methods were called, for example by complete reinitialization. This may be the hardest part, and the one most protected by NDA'd documents and chip errata.  It's simplest if the hardware state hasn't changed since the suspend was carried out, but that can only be guaranteed if the target system sleep entered was suspend-to-idle.  For the other system sleep states that may not be the case (and usually isn't for ACPI-defined system sleep states, like S3).

Drivers must also be prepared to notice that the device has been removed while the system was powered down, whenever that's physically possible. PCMCIA, MMC, USB, Firewire, SCSI, and even IDE are common examples of buses where common Linux platforms will see such removal.  Details of how drivers will notice and handle such removals are currently bus-specific, and often involve a separate thread.

These callbacks may return an error value, but the PM core will ignore such errors since there's nothing it can do about them other than printing them in the system log.

<a id="rst-entering-hibernation"></a>

### Entering Hibernation

Hibernating the system is more complicated than putting it into sleep states, because it involves creating and saving a system image.  Therefore there are more phases for hibernation, with a different set of callbacks.  These phases always run after tasks have been frozen and enough memory has been freed.

The general procedure for hibernation is to quiesce all devices ("freeze"), create an image of the system memory while everything is stable, reactivate all devices ("thaw"), write the image to permanent storage, and finally shut down the system ("power off").  The phases used to accomplish this are: `prepare`, `freeze`, `freeze_late`, `freeze_noirq`, `thaw_noirq`, `thaw_early`, `thaw`, `complete`, `prepare`, `poweroff`, `poweroff_late`, `poweroff_noirq`.

> 1. The `prepare` phase is discussed in the "Entering System Suspend" section above.
>
> 2. The `->freeze` methods should quiesce the device so that it doesn't generate IRQs or DMA, and they may need to save the values of device registers.  However the device does not have to be put in a low-power state, and to save time it's best not to do so.  Also, the device should not be prepared to generate wakeup events.
>
> 3. The `freeze_late` phase is analogous to the `suspend_late` phase described earlier, except that the device should not be put into a low-power state and should not be allowed to generate wakeup events.
>
> 4. The `freeze_noirq` phase is analogous to the `suspend_noirq` phase discussed earlier, except again that the device should not be put into a low-power state and should not be allowed to generate wakeup events.

At this point the system image is created.  All devices should be inactive and the contents of memory should remain undisturbed while this happens, so that the image forms an atomic snapshot of the system state.

> 5. The `thaw_noirq` phase is analogous to the `resume_noirq` phase discussed earlier.  The main difference is that its methods can assume the device is in the same state as at the end of the `freeze_noirq` phase.
>
> 6. The `thaw_early` phase is analogous to the `resume_early` phase described above.  Its methods should undo the actions of the preceding `freeze_late`, if necessary.
>
> 7. The `thaw` phase is analogous to the `resume` phase discussed earlier.  Its methods should bring the device back to an operating state, so that it can be used for saving the image if necessary.
>
> 8. The `complete` phase is discussed in the "Leaving System Suspend" section above.

At this point the system image is saved, and the devices then need to be prepared for the upcoming system shutdown.  This is much like suspending them before putting the system into the suspend-to-idle, shallow or deep sleep state, and the phases are similar.

> 9. The `prepare` phase is discussed above.
>
> 10. The `poweroff` phase is analogous to the `suspend` phase.
>
> 11. The `poweroff_late` phase is analogous to the `suspend_late` phase.
>
> 12. The `poweroff_noirq` phase is analogous to the `suspend_noirq` phase.

The `->poweroff`, `->poweroff_late` and `->poweroff_noirq` callbacks should do essentially the same things as the `->suspend`, `->suspend_late` and `->suspend_noirq` callbacks, respectively.  A notable difference is that they need not store the device register values, because the registers should already have been stored during the `freeze`, `freeze_late` or `freeze_noirq` phases.  Also, on many machines the firmware will power-down the entire system, so it is not necessary for the callback to put the device in a low-power state.

<a id="rst-leaving-hibernation"></a>

### Leaving Hibernation

Resuming from hibernation is, again, more complicated than resuming from a sleep state in which the contents of main memory are preserved, because it requires a system image to be loaded into memory and the pre-hibernation memory contents to be restored before control can be passed back to the image kernel.

Although in principle the image might be loaded into memory and the pre-hibernation memory contents restored by the boot loader, in practice this can't be done because boot loaders aren't smart enough and there is no established protocol for passing the necessary information.  So instead, the boot loader loads a fresh instance of the kernel, called "the restore kernel", into memory and passes control to it in the usual way.  Then the restore kernel reads the system image, restores the pre-hibernation memory contents, and passes control to the image kernel.  Thus two different kernel instances are involved in resuming from hibernation.  In fact, the restore kernel may be completely different from the image kernel: a different configuration and even a different version.  This has important consequences for device drivers and their subsystems.

To be able to load the system image into memory, the restore kernel needs to include at least a subset of device drivers allowing it to access the storage medium containing the image, although it doesn't need to include all of the drivers present in the image kernel.  After the image has been loaded, the devices managed by the boot kernel need to be prepared for passing control back to the image kernel.  This is very similar to the initial steps involved in creating a system image, and it is accomplished in the same way, using `prepare`, `freeze`, and `freeze_noirq` phases.  However, the devices affected by these phases are only those having drivers in the restore kernel; other devices will still be in whatever state the boot loader left them.

Should the restoration of the pre-hibernation memory contents fail, the restore kernel would go through the "thawing" procedure described above, using the `thaw_noirq`, `thaw_early`, `thaw`, and `complete` phases, and then continue running normally.  This happens only rarely.  Most often the pre-hibernation memory contents are restored successfully and control is passed to the image kernel, which then becomes responsible for bringing the system back to the working state.

To achieve this, the image kernel must restore the devices' pre-hibernation functionality.  The operation is much like waking up from a sleep state (with the memory contents preserved), although it involves different phases: `restore_noirq`, `restore_early`, `restore`, `complete`.

> 1. The `restore_noirq` phase is analogous to the `resume_noirq` phase.
>
> 2. The `restore_early` phase is analogous to the `resume_early` phase.
>
> 3. The `restore` phase is analogous to the `resume` phase.
>
> 4. The `complete` phase is discussed above.

The main difference from `resume[_early|_noirq]` is that `restore[_early|_noirq]` must assume the device has been accessed and reconfigured by the boot loader or the restore kernel.  Consequently, the state of the device may be different from the state remembered from the `freeze`, `freeze_late` and `freeze_noirq` phases.  The device may even need to be reset and completely re-initialized.  In many cases this difference doesn't matter, so the `->resume[_early|_noirq]` and `->restore[_early|_norq]` method pointers can be set to the same routines.  Nevertheless, different callback pointers are used in case there is a situation where it actually does matter.

<a id="rst-power-management-notifiers"></a>

## Power Management Notifiers

There are some operations that cannot be carried out by the power management callbacks discussed above, because the callbacks occur too late or too early. To handle these cases, subsystems and device drivers may register power management notifiers that are called before tasks are frozen and after they have been thawed.  Generally speaking, the PM notifiers are suitable for performing actions that either require user space to be available, or at least won't interfere with user space.

For details refer to [Documentation/driver-api/pm/notifiers.rst](/kernel/hardware/driver-api/pm/notifiers.md).

<a id="rst-device-low-power-suspend-states"></a>

## Device Low-Power (suspend) States

Device low-power states aren't standard.  One device might only handle "on" and "off", while another might support a dozen different versions of "on" (how many engines are active?), plus a state that gets back to "on" faster than from a full "off".

Some buses define rules about what different suspend states mean.  PCI gives one example: after the suspend sequence completes, a non-legacy PCI device may not perform DMA or issue IRQs, and any wakeup events it issues would be issued through the PME\# bus signal.  Plus, there are several PCI-standard device states, some of which are optional.

In contrast, integrated system-on-chip processors often use IRQs as the wakeup event sources (so drivers would call `enable_irq_wake()`) and might be able to treat DMA completion as a wakeup event (sometimes DMA can stay active too, it'd only be the CPU and some peripherals that sleep).

Some details here may be platform-specific.  Systems may have devices that can be fully active in certain sleep states, such as an LCD display that's refreshed using DMA while most of the system is sleeping lightly ... and its frame buffer might even be updated by a DSP or other non-Linux CPU while the Linux control processor stays idle.

Moreover, the specific actions taken may depend on the target system state. One target system state might allow a given device to be very operational; another might require a hard shut down with re-initialization on resume. And two different target systems might use the same device in different ways; the aforementioned LCD might be active in one product's "standby", but a different product using the same SOC might work differently.

<a id="rst-device-power-management-domains"></a>

## Device Power Management Domains

Sometimes devices share reference clocks or other power resources.  In those cases it generally is not possible to put devices into low-power states individually.  Instead, a set of devices sharing a power resource can be put into a low-power state together at the same time by turning off the shared power resource.  Of course, they also need to be put into the full-power state together, by turning the shared power resource on.  A set of devices with this property is often referred to as a power domain. A power domain may also be nested inside another power domain. The nested domain is referred to as the sub-domain of the parent domain.

Support for power domains is provided through the `pm_domain` field of struct device.  This field is a pointer to an object of type struct dev_pm_domain, defined in `include/linux/pm.h`, providing a set of power management callbacks analogous to the subsystem-level and device driver callbacks that are executed for the given device during all power transitions, instead of the respective subsystem-level callbacks.  Specifically, if a device's `pm_domain` pointer is not NULL, the `->suspend()` callback from the object pointed to by it will be executed instead of its subsystem's (e.g. bus type's) `->suspend()` callback and analogously for all of the remaining callbacks.  In other words, power management domain callbacks, if defined for the given device, always take precedence over the callbacks provided by the device's subsystem (e.g. bus type).

The support for device power management domains is only relevant to platforms needing to use the same device driver power management callbacks in many different power domain configurations and wanting to avoid incorporating the support for power domains into subsystem-level callbacks, for example by modifying the platform bus type.  Other platforms need not implement it or take it into account in any way.

Devices may be defined as IRQ-safe which indicates to the PM core that their runtime PM callbacks may be invoked with disabled interrupts (see [Documentation/power/runtime_pm.rst](/kernel/internals/power/runtime-pm.md) for more information).  If an IRQ-safe device belongs to a PM domain, the runtime PM of the domain will be disallowed, unless the domain itself is defined as IRQ-safe. However, it makes sense to define a PM domain as IRQ-safe only if all the devices in it are IRQ-safe. Moreover, if an IRQ-safe domain has a parent domain, the runtime PM of the parent is only allowed if the parent itself is IRQ-safe too with the additional restriction that all child domains of an IRQ-safe parent must also be IRQ-safe.

<a id="rst-runtime-power-management"></a>

## Runtime Power Management

Many devices are able to dynamically power down while the system is still running. This feature is useful for devices that are not being used, and can offer significant power savings on a running system.  These devices often support a range of runtime power states, which might use names such as "off", "sleep", "idle", "active", and so on.  Those states will in some cases (like PCI) be partially constrained by the bus the device uses, and will usually include hardware states that are also used in system sleep states.

A system-wide power transition can be started while some devices are in low power states due to runtime power management.  The system sleep PM callbacks should recognize such situations and react to them appropriately, but the necessary actions are subsystem-specific.

In some cases the decision may be made at the subsystem level while in other cases the device driver may be left to decide.  In some cases it may be desirable to leave a suspended device in that state during a system-wide power transition, but in other cases the device must be put back into the full-power state temporarily, for example so that its system wakeup capability can be disabled.  This all depends on the hardware and the design of the subsystem and device driver in question.

If it is necessary to resume a device from runtime suspend during a system-wide transition into a sleep state, that can be done by calling `pm_runtime_resume()` from the `->suspend` callback (or the `->freeze` or `->poweroff` callback for transitions related to hibernation) of either the device's driver or its subsystem (for example, a bus type or a PM domain). However, subsystems must not otherwise change the runtime status of devices from their `->prepare` and `->suspend` callbacks (or equivalent) *before* invoking device drivers' `->suspend` callbacks (or equivalent).

<a id="rst-the-dpm-flag-smart-suspend-driver-flag"></a>
<a id="rst-smart-suspend-flag"></a>

### The `DPM_FLAG_SMART_SUSPEND` Driver Flag

Some bus types and PM domains have a policy to resume all devices from runtime suspend upfront in their `->suspend` callbacks, but that may not be really necessary if the device's driver can cope with runtime-suspended devices. The driver can indicate this by setting `DPM_FLAG_SMART_SUSPEND` in `power.driver_flags` at probe time, with the assistance of the `dev_pm_set_driver_flags()` helper routine.

Setting that flag causes the PM core and middle-layer code (bus types, PM domains etc.) to skip the `->suspend_late` and `->suspend_noirq` callbacks provided by the driver if the device remains in runtime suspend throughout those phases of the system-wide suspend (and similarly for the "freeze" and "poweroff" parts of system hibernation). \[Otherwise the same driver callback might be executed twice in a row for the same device, which would not be valid in general.\]  If the middle-layer system-wide PM callbacks are present for the device then they are responsible for skipping these driver callbacks; if not then the PM core skips them.  The subsystem callback routines can determine whether they need to skip the driver callbacks by testing the return value from the `dev_pm_skip_suspend()` helper function.

In addition, with `DPM_FLAG_SMART_SUSPEND` set, the driver's `->thaw_noirq` and `->thaw_early` callbacks are skipped in hibernation if the device remained in runtime suspend throughout the preceding "freeze" transition.  Again, if the middle-layer callbacks are present for the device, they are responsible for doing this, otherwise the PM core takes care of it.

<a id="rst-the-dpm-flag-may-skip-resume-driver-flag"></a>

### The `DPM_FLAG_MAY_SKIP_RESUME` Driver Flag

During system-wide resume from a sleep state it's easiest to put devices into the full-power state, as explained in [Documentation/power/runtime_pm.rst](/kernel/internals/power/runtime-pm.md). \[Refer to that document for more information regarding this particular issue as well as for information on the device runtime power management framework in general.\]  However, it often is desirable to leave devices in suspend after system transitions to the working state, especially if those devices had been in runtime suspend before the preceding system-wide suspend (or analogous) transition.

To that end, device drivers can use the `DPM_FLAG_MAY_SKIP_RESUME` flag to indicate to the PM core and middle-layer code that they allow their "noirq" and "early" resume callbacks to be skipped if the device can be left in suspend after system-wide PM transitions to the working state.  Whether or not that is the case generally depends on the state of the device before the given system suspend-resume cycle and on the type of the system transition under way. In particular, the "thaw" and "restore" transitions related to hibernation are not affected by `DPM_FLAG_MAY_SKIP_RESUME` at all.  \[All callbacks are issued during the "restore" transition regardless of the flag settings, and whether or not any driver callbacks are skipped during the "thaw" transition depends whether or not the `DPM_FLAG_SMART_SUSPEND` flag is set (see [above](<#rst-smart-suspend-flag>)<a id="rst-above"></a>). In addition, a device is not allowed to remain in runtime suspend if any of its children will be returned to full power.\]

The `DPM_FLAG_MAY_SKIP_RESUME` flag is taken into account in combination with the `power.may_skip_resume` status bit set by the PM core during the "suspend" phase of suspend-type transitions.  If the driver or the middle layer has a reason to prevent the driver's "noirq" and "early" resume callbacks from being skipped during the subsequent system resume transition, it should clear `power.may_skip_resume` in its `->suspend`, `->suspend_late` or `->suspend_noirq` callback.  \[Note that the drivers setting `DPM_FLAG_SMART_SUSPEND` need to clear `power.may_skip_resume` in their `->suspend` callback in case the other two are skipped.\]

Setting the `power.may_skip_resume` status bit along with the `DPM_FLAG_MAY_SKIP_RESUME` flag is necessary, but generally not sufficient, for the driver's "noirq" and "early" resume callbacks to be skipped.  Whether or not they should be skipped can be determined by evaluating the `dev_pm_skip_resume()` helper function.

If that function returns `true`, the driver's "noirq" and "early" resume callbacks should be skipped and the device's runtime PM status will be set to "suspended" by the PM core.  Otherwise, if the device was runtime-suspended during the preceding system-wide suspend transition and its `DPM_FLAG_SMART_SUSPEND` is set, its runtime PM status will be set to "active" by the PM core.  \[Hence, the drivers that do not set `DPM_FLAG_SMART_SUSPEND` should not expect the runtime PM status of their devices to be changed from "suspended" to "active" by the PM core during system-wide resume-type transitions.\]

If the `DPM_FLAG_MAY_SKIP_RESUME` flag is not set for a device, but `DPM_FLAG_SMART_SUSPEND` is set and the driver's "late" and "noirq" suspend callbacks are skipped, its system-wide "noirq" and "early" resume callbacks, if present, are invoked as usual and the device's runtime PM status is set to "active" by the PM core before enabling runtime PM for it.  In that case, the driver must be prepared to cope with the invocation of its system-wide resume callbacks back-to-back with its `->runtime_suspend` one (without the intervening `->runtime_resume` and system-wide suspend callbacks) and the final state of the device must reflect the "active" runtime PM status in that case.  \[Note that this is not a problem at all if the driver's `->suspend_late` callback pointer points to the same function as its `->runtime_suspend` one and its `->resume_early` callback pointer points to the same function as the `->runtime_resume` one, while none of the other system-wide suspend-resume callbacks of the driver are present, for example.\]

Likewise, if `DPM_FLAG_MAY_SKIP_RESUME` is set for a device, its driver's system-wide "noirq" and "early" resume callbacks may be skipped while its "late" and "noirq" suspend callbacks may have been executed (in principle, regardless of whether or not `DPM_FLAG_SMART_SUSPEND` is set).  In that case, the driver needs to be able to cope with the invocation of its `->runtime_resume` callback back-to-back with its "late" and "noirq" suspend ones.  \[For instance, that is not a concern if the driver sets both `DPM_FLAG_SMART_SUSPEND` and `DPM_FLAG_MAY_SKIP_RESUME` and uses the same pair of suspend/resume callback functions for runtime PM and system-wide suspend/resume.\]

---

# Suspend/Hibernation Notifiers

_Peios Kernel / Hardware and drivers / Driver development / Power management_

> There are some operations that subsystems or drivers may want to carry out before hibernation/suspend or after restore/resume, but they require the system to be fully functional, so the drivers' and subsystems' ->suspend() and ->resume()…

<a id="rst-suspend-hibernation-notifiers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2016 Intel Corporation

**Author:** Rafael J. Wysocki &lt;[rafael.j.wysocki@intel.com](<mailto:rafael.j.wysocki@intel.com>)&gt;

There are some operations that subsystems or drivers may want to carry out before hibernation/suspend or after restore/resume, but they require the system to be fully functional, so the drivers' and subsystems' `->suspend()` and `->resume()` or even `->prepare()` and `->complete()` callbacks are not suitable for this purpose.

For example, device drivers may want to upload firmware to their devices after resume/restore, but they cannot do it by calling `request_firmware()` from their `->resume()` or `->complete()` callback routines (user land processes are frozen at these points).  The solution may be to load the firmware into memory before processes are frozen and upload it from there in the `->resume()` routine.  A suspend/hibernation notifier may be used for that.

Subsystems or drivers having such needs can register suspend notifiers that will be called upon the following events by the PM core:

- **`PM_HIBERNATION_PREPARE`**

  The system is going to hibernate, tasks will be frozen immediately. This is different from `PM_SUSPEND_PREPARE` below, because in this case additional work is done between the notifiers and the invocation of PM callbacks for the "freeze" transition.

- **`PM_POST_HIBERNATION`**

  The system memory state has been restored from a hibernation image or an error occurred during hibernation.  Device restore callbacks have been executed and tasks have been thawed.

- **`PM_RESTORE_PREPARE`**

  The system is going to restore a hibernation image.  If all goes well, the restored image kernel will issue a `PM_POST_HIBERNATION` notification.

- **`PM_POST_RESTORE`**

  An error occurred during restore from hibernation.  Device restore callbacks have been executed and tasks have been thawed.

- **`PM_SUSPEND_PREPARE`**

  The system is preparing for suspend.

- **`PM_POST_SUSPEND`**

  The system has just resumed or an error occurred during suspend.  Device resume callbacks have been executed and tasks have been thawed.

It is generally assumed that whatever the notifiers do for `PM_HIBERNATION_PREPARE`, should be undone for `PM_POST_HIBERNATION`. Analogously, operations carried out for `PM_SUSPEND_PREPARE` should be reversed for `PM_POST_SUSPEND`.

Moreover, if one of the notifiers fails for the `PM_HIBERNATION_PREPARE` or `PM_SUSPEND_PREPARE` event, the notifiers that have already succeeded for that event will be called for `PM_POST_HIBERNATION` or `PM_POST_SUSPEND`, respectively.

The hibernation and suspend notifiers are called with `pm_mutex` held. They are defined in the usual way, but their last argument is meaningless (it is always NULL).

To register and/or unregister a suspend notifier use `register_pm_notifier()` and `unregister_pm_notifier()`, respectively (both defined in `include/linux/suspend.h`).  If you don't need to unregister the notifier, you can also use the `pm_notifier()` macro defined in `include/linux/suspend.h`.

---

# Device Power Management Data Types

_Peios Kernel / Hardware and drivers / Driver development / Power management_

> Reference for Device Power Management Data Types.

<a id="rst-device-power-management-data-types"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-struct-dev_pm_ops"></a>`struct dev_pm_ops`

device PM callbacks.

**Definition**

```c
struct dev_pm_ops {
    int (*prepare)(struct device *dev);
    void (*complete)(struct device *dev);
    int (*suspend)(struct device *dev);
    int (*resume)(struct device *dev);
    int (*freeze)(struct device *dev);
    int (*thaw)(struct device *dev);
    int (*poweroff)(struct device *dev);
    int (*restore)(struct device *dev);
    int (*suspend_late)(struct device *dev);
    int (*resume_early)(struct device *dev);
    int (*freeze_late)(struct device *dev);
    int (*thaw_early)(struct device *dev);
    int (*poweroff_late)(struct device *dev);
    int (*restore_early)(struct device *dev);
    int (*suspend_noirq)(struct device *dev);
    int (*resume_noirq)(struct device *dev);
    int (*freeze_noirq)(struct device *dev);
    int (*thaw_noirq)(struct device *dev);
    int (*poweroff_noirq)(struct device *dev);
    int (*restore_noirq)(struct device *dev);
    int (*runtime_suspend)(struct device *dev);
    int (*runtime_resume)(struct device *dev);
    int (*runtime_idle)(struct device *dev);
};
```

**Members**

- `prepare`: The principal role of this callback is to prevent new children of
  the device from being registered after it has returned (the driver's
  subsystem and generally the rest of the kernel is supposed to prevent
  new calls to the probe method from being made too once **prepare()** has
  succeeded).  If **prepare()** detects a situation it cannot handle (e.g.
  registration of a child already in progress), it may return -EAGAIN, so
  that the PM core can execute it once again (e.g. after a new child has
  been registered) to recover from the race condition.
  This method is executed for all kinds of suspend transitions and is
  followed by one of the suspend callbacks: **suspend()**, **freeze()**, or
  **poweroff()**.  If the transition is a suspend to memory or standby (that
  is, not related to hibernation), the return value of **prepare()** may be
  used to indicate to the PM core to leave the device in runtime suspend
  if applicable.  Namely, if **prepare()** returns a positive number, the PM
  core will understand that as a declaration that the device appears to be
  runtime-suspended and it may be left in that state during the entire
  transition and during the subsequent resume if all of its descendants
  are left in runtime suspend too.  If that happens, **complete()** will be
  executed directly after **prepare()** and it must ensure the proper
  functioning of the device after the system resume.
  The PM core executes subsystem-level **prepare()** for all devices before
  starting to invoke suspend callbacks for any of them, so generally
  devices may be assumed to be functional or to respond to runtime resume
  requests while **prepare()** is being executed.  However, device drivers
  may NOT assume anything about the availability of user space at that
  time and it is NOT valid to request firmware from within **prepare()**
  (it's too late to do that).  It also is NOT valid to allocate
  substantial amounts of memory from **prepare()** in the GFP_KERNEL mode.
  \[To work around these limitations, drivers may register suspend and
  hibernation notifiers to be executed before the freezing of tasks.\]
- `complete`: Undo the changes made by **prepare()**.  This method is executed for
  all kinds of resume transitions, following one of the resume callbacks:
  **resume()**, **thaw()**, **restore()**.  Also called if the state transition
  fails before the driver's suspend callback: **suspend()**, **freeze()** or
  **poweroff()**, can be executed (e.g. if the suspend callback fails for one
  of the other devices that the PM core has unsuccessfully attempted to
  suspend earlier).
  The PM core executes subsystem-level **complete()** after it has executed
  the appropriate resume callbacks for all devices.  If the corresponding
  **prepare()** at the beginning of the suspend transition returned a
  positive number and the device was left in runtime suspend (without
  executing any suspend and resume callbacks for it), **complete()** will be
  the only callback executed for the device during resume.  In that case,
  **complete()** must be prepared to do whatever is necessary to ensure the
  proper functioning of the device after the system resume.  To this end,
  **complete()** can check the power.direct_complete flag of the device to
  learn whether (unset) or not (set) the previous suspend and resume
  callbacks have been executed for it.
- `suspend`: Executed before putting the system into a sleep state in which the
  contents of main memory are preserved.  The exact action to perform
  depends on the device's subsystem (PM domain, device type, class or bus
  type), but generally the device must be quiescent after subsystem-level
  **suspend()** has returned, so that it doesn't do any I/O or DMA.
  Subsystem-level **suspend()** is executed for all devices after invoking
  subsystem-level **prepare()** for all of them.
- `resume`: Executed after waking the system up from a sleep state in which the
  contents of main memory were preserved.  The exact action to perform
  depends on the device's subsystem, but generally the driver is expected
  to start working again, responding to hardware events and software
  requests (the device itself may be left in a low-power state, waiting
  for a runtime resume to occur).  The state of the device at the time its
  driver's **resume()** callback is run depends on the platform and subsystem
  the device belongs to.  On most platforms, there are no restrictions on
  availability of resources like clocks during **resume()**.
  Subsystem-level **resume()** is executed for all devices after invoking
  subsystem-level **resume_noirq()** for all of them.
- `freeze`: Hibernation-specific, executed before creating a hibernation image.
  Analogous to **suspend()**, but it should not enable the device to signal
  wakeup events or change its power state.  The majority of subsystems
  (with the notable exception of the PCI bus type) expect the driver-level
  **freeze()** to save the device settings in memory to be used by **restore()**
  during the subsequent resume from hibernation.
  Subsystem-level **freeze()** is executed for all devices after invoking
  subsystem-level **prepare()** for all of them.
- `thaw`: Hibernation-specific, executed after creating a hibernation image OR
  if the creation of an image has failed.  Also executed after a failing
  attempt to restore the contents of main memory from such an image.
  Undo the changes made by the preceding **freeze()**, so the device can be
  operated in the same way as immediately before the call to **freeze()**.
  Subsystem-level **thaw()** is executed for all devices after invoking
  subsystem-level **thaw_noirq()** for all of them.  It also may be executed
  directly after **freeze()** in case of a transition error.
- `poweroff`: Hibernation-specific, executed after saving a hibernation image.
  Analogous to **suspend()**, but it need not save the device's settings in
  memory.
  Subsystem-level **poweroff()** is executed for all devices after invoking
  subsystem-level **prepare()** for all of them.
- `restore`: Hibernation-specific, executed after restoring the contents of main
  memory from a hibernation image, analogous to **resume()**.
- `suspend_late`: Continue operations started by **suspend()**.  For a number of
  devices **suspend_late()** may point to the same callback routine as the
  runtime suspend callback.
- `resume_early`: Prepare to execute **resume()**.  For a number of devices
  **resume_early()** may point to the same callback routine as the runtime
  resume callback.
- `freeze_late`: Continue operations started by **freeze()**.  Analogous to
  **suspend_late()**, but it should not enable the device to signal wakeup
  events or change its power state.
- `thaw_early`: Prepare to execute **thaw()**.  Undo the changes made by the
  preceding **freeze_late()**.
- `poweroff_late`: Continue operations started by **poweroff()**.  Analogous to
  **suspend_late()**, but it need not save the device's settings in memory.
- `restore_early`: Prepare to execute **restore()**, analogous to **resume_early()**.
- `suspend_noirq`: Complete the actions started by **suspend()**.  Carry out any
  additional operations required for suspending the device that might be
  racing with its driver's interrupt handler, which is guaranteed not to
  run while **suspend_noirq()** is being executed.
  It generally is expected that the device will be in a low-power state
  (appropriate for the target system sleep state) after subsystem-level
  **suspend_noirq()** has returned successfully.  If the device can generate
  system wakeup signals and is enabled to wake up the system, it should be
  configured to do so at that time.  However, depending on the platform
  and device's subsystem, **suspend()** or **suspend_late()** may be allowed to
  put the device into the low-power state and configure it to generate
  wakeup signals, in which case it generally is not necessary to define
  **suspend_noirq()**.
- `resume_noirq`: Prepare for the execution of **resume()** by carrying out any
  operations required for resuming the device that might be racing with
  its driver's interrupt handler, which is guaranteed not to run while
  **resume_noirq()** is being executed.
- `freeze_noirq`: Complete the actions started by **freeze()**.  Carry out any
  additional operations required for freezing the device that might be
  racing with its driver's interrupt handler, which is guaranteed not to
  run while **freeze_noirq()** is being executed.
  The power state of the device should not be changed by either **freeze()**,
  or **freeze_late()**, or **freeze_noirq()** and it should not be configured to
  signal system wakeup by any of these callbacks.
- `thaw_noirq`: Prepare for the execution of **thaw()** by carrying out any
  operations required for thawing the device that might be racing with its
  driver's interrupt handler, which is guaranteed not to run while
  **thaw_noirq()** is being executed.
- `poweroff_noirq`: Complete the actions started by **poweroff()**.  Analogous to
  **suspend_noirq()**, but it need not save the device's settings in memory.
- `restore_noirq`: Prepare for the execution of **restore()** by carrying out any
  operations required for thawing the device that might be racing with its
  driver's interrupt handler, which is guaranteed not to run while
  **restore_noirq()** is being executed.  Analogous to **resume_noirq()**.
- `runtime_suspend`: Prepare the device for a condition in which it won't be
  able to communicate with the CPU(s) and RAM due to power management.
  This need not mean that the device should be put into a low-power state.
  For example, if the device is behind a link which is about to be turned
  off, the device may remain at full power.  If the device does go to low
  power and is capable of generating runtime wakeup events, remote wakeup
  (i.e., a hardware mechanism allowing the device to request a change of
  its power state via an interrupt) should be enabled for it.
- `runtime_resume`: Put the device into the fully active state in response to a
  wakeup event generated by hardware or at the request of software.  If
  necessary, put the device into the full-power state and restore its
  registers, so that it is fully operational.
- `runtime_idle`: Device appears to be inactive and it might be put into a
  low-power state if all of the necessary conditions are satisfied.
  Check these conditions, and return 0 if it's appropriate to let the PM
  core queue a suspend request for the device.

**Description**

Several device power state transitions are externally visible, affecting
the state of pending I/O queues and (for drivers that touch hardware)
interrupts, wakeups, DMA, and other hardware state.  There may also be
internal transitions to various low-power modes which are transparent
to the rest of the driver stack (such as a driver that's ON gating off
clocks which are not in active use).

The externally visible transitions are handled with the help of callbacks
included in this structure in such a way that, typically, two levels of
callbacks are involved.  First, the PM core executes callbacks provided by PM
domains, device types, classes and bus types.  They are the subsystem-level
callbacks expected to execute callbacks provided by device drivers, although
they may choose not to do that.  If the driver callbacks are executed, they
have to collaborate with the subsystem-level callbacks to achieve the goals
appropriate for the given system transition, given transition phase and the
subsystem the device belongs to.

All of the above callbacks, except for **complete()**, return error codes.
However, the error codes returned by **resume()**, **thaw()**, **restore()**,
**resume_noirq()**, **thaw_noirq()**, and **restore_noirq()**, do not cause the PM
core to abort the resume transition during which they are returned.  The
error codes returned in those cases are only printed to the system logs for
debugging purposes.  Still, it is recommended that drivers only return error
codes from their resume methods in case of an unrecoverable failure (i.e.
when the device being handled refuses to resume and becomes unusable) to
allow the PM core to be modified in the future, so that it can avoid
attempting to handle devices that failed to resume and their children.

It is allowed to unregister devices while the above callbacks are being
executed.  However, a callback routine MUST NOT try to unregister the device
it was called for, although it may unregister children of that device (for
example, if it detects that a child was unplugged while the system was
asleep).

There also are callbacks related to runtime power management of devices.
Again, as a rule these callbacks are executed by the PM core for subsystems
(PM domains, device types, classes and bus types) and the subsystem-level
callbacks are expected to invoke the driver callbacks.  Moreover, the exact
actions to be performed by a device driver's callbacks generally depend on
the platform and subsystem the device belongs to.

Refer to Documentation/power/runtime_pm.rst for more information about the
role of the **runtime_suspend()**, **runtime_resume()** and **runtime_idle()**
callbacks in device runtime power management.

#### <a id="c-struct-dev_pm_domain"></a>`struct dev_pm_domain`

power management domain representation.

**Definition**

```c
struct dev_pm_domain {
    struct dev_pm_ops       ops;
    int (*start)(struct device *dev);
    void (*detach)(struct device *dev, bool power_off);
    int (*activate)(struct device *dev);
    void (*sync)(struct device *dev);
    void (*dismiss)(struct device *dev);
    int (*set_performance_state)(struct device *dev, unsigned int state);
};
```

**Members**

- `ops`: Power management operations associated with this domain.
- `start`: Called when a user needs to start the device via the domain.
- `detach`: Called when removing a device from the domain.
- `activate`: Called before executing probe routines for bus types and drivers.
- `sync`: Called after successful driver probe.
- `dismiss`: Called after unsuccessful driver probe and after driver removal.
- `set_performance_state`: Called to request a new performance state.

**Description**

Power domains provide callbacks that are executed during system suspend,
hibernation, system resume and during runtime PM transitions instead of
subsystem-level and driver-level callbacks.

---

# Surface System Aggregator Module (SSAM)

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> Reference for Surface System Aggregator Module (SSAM).

<a id="rst-surface-system-aggregator-module-ssam"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

- [Overview](</kernel/hardware/driver-api/surface-aggregator/overview.md>)
- [Writing Client Drivers](</kernel/hardware/driver-api/surface-aggregator/client.md>)
- [Client Driver Documentation](</kernel/hardware/driver-api/surface-aggregator-clients/index.md>)
- [Surface Serial Hub Protocol](</kernel/hardware/driver-api/surface-aggregator/ssh.md>)
- [Core Driver Internals](</kernel/hardware/driver-api/surface-aggregator/internal.md>)

---

# Client Driver API Documentation

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> Serial Hub Communication

<a id="rst-client-driver-api-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<a id="rst-contents"></a>



<a id="rst-serial-hub-communication"></a>

## Serial Hub Communication


#### <a id="c-enum-ssh_frame_type"></a>`enum ssh_frame_type`

Frame types for SSH frames.

**Constants**

- `SSH_FRAME_TYPE_DATA_SEQ`: Indicates a data frame, followed by a payload with the length specified
  in the `struct ssh_frame.len` field. This frame is sequenced, meaning
  that an ACK is required.
- `SSH_FRAME_TYPE_DATA_NSQ`: Same as `SSH_FRAME_TYPE_DATA_SEQ`, but unsequenced, meaning that the
  message does not have to be ACKed.
- `SSH_FRAME_TYPE_ACK`: Indicates an ACK message.
- `SSH_FRAME_TYPE_NAK`: Indicates an error response for previously sent frame. In general, this
  means that the frame and/or payload is malformed, e.g. a CRC is wrong.
  For command-type payloads, this can also mean that the command is
  invalid.

#### <a id="c-struct-ssh_frame"></a>`struct ssh_frame`

SSH communication frame.

**Definition**

```c
struct ssh_frame {
    u8 type;
    __le16 len;
    u8 seq;
};
```

**Members**

- `type`: The type of the frame. See [`enum ssh_frame_type`](#c-enum-ssh_frame_type).
- `len`: The length of the frame payload directly following the CRC for this
  frame. Does not include the final CRC for that payload.
- `seq`: The sequence number for this message/exchange.

#### <a id="c-enum-ssh_payload_type"></a>`enum ssh_payload_type`

Type indicator for the SSH payload.

**Constants**

- `SSH_PLD_TYPE_CMD`: The payload is a command structure with optional command
  payload.

#### <a id="c-struct-ssh_command"></a>`struct ssh_command`

Payload of a command-type frame.

**Definition**

```c
struct ssh_command {
    u8 type;
    u8 tc;
    u8 tid;
    u8 sid;
    u8 iid;
    __le16 rqid;
    u8 cid;
};
```

**Members**

- `type`: The type of the payload. See [`enum ssh_payload_type`](#c-enum-ssh_payload_type). Should be
  SSH_PLD_TYPE_CMD for this struct.
- `tc`: Command target category.
- `tid`: Target ID. Indicates the target of the message.
- `sid`: Source ID. Indicates the source of the message.
- `iid`: Instance ID.
- `rqid`: Request ID. Used to match requests with responses and differentiate
  between responses and events.
- `cid`: Command ID.

#### <a id="c-SSH_MESSAGE_LENGTH"></a>`SSH_MESSAGE_LENGTH()`

```c
SSH_MESSAGE_LENGTH(payload_size)
```

Compute length of SSH message.

**Parameters**

- `payload_size`: Length of the payload inside the SSH frame.

**Return**

Returns the length of a SSH message with payload of specified size.

#### <a id="c-SSH_COMMAND_MESSAGE_LENGTH"></a>`SSH_COMMAND_MESSAGE_LENGTH()`

```c
SSH_COMMAND_MESSAGE_LENGTH(payload_size)
```

Compute length of SSH command message.

**Parameters**

- `payload_size`: Length of the command payload.

**Return**

Returns the length of a SSH command message with command payload of
specified size.

#### <a id="c-SSH_MSGOFFSET_FRAME"></a>`SSH_MSGOFFSET_FRAME()`

```c
SSH_MSGOFFSET_FRAME(field)
```

Compute offset in SSH message to specified field in frame.

**Parameters**

- `field`: The field for which the offset should be computed.

**Return**

Returns the offset of the specified [`struct ssh_frame`](#c-struct-ssh_frame) field in the
raw SSH message data as. Takes SYN bytes (u16) preceding the frame into
account.

#### <a id="c-SSH_MSGOFFSET_COMMAND"></a>`SSH_MSGOFFSET_COMMAND()`

```c
SSH_MSGOFFSET_COMMAND(field)
```

Compute offset in SSH message to specified field in command.

**Parameters**

- `field`: The field for which the offset should be computed.

**Return**

Returns the offset of the specified [`struct ssh_command`](#c-struct-ssh_command) field in
the raw SSH message data. Takes SYN bytes (u16) preceding the frame and the
frame CRC (u16) between frame and command into account.

#### <a id="c-ssh_crc"></a>`ssh_crc()`

```c
u16 ssh_crc(const u8 *buf, size_t len)
```

Compute CRC for SSH messages.

**Parameters**

- `const u8 *buf`: The pointer pointing to the data for which the CRC should be computed.
- `size_t len`: The length of the data for which the CRC should be computed.

**Return**

Returns the CRC computed on the provided data, as used for SSH
messages.

#### <a id="c-ssh_rqid_next_valid"></a>`ssh_rqid_next_valid()`

```c
u16 ssh_rqid_next_valid(u16 rqid)
```

Return the next valid request ID.

**Parameters**

- `u16 rqid`: The current request ID.

**Return**

Returns the next valid request ID, following the current request ID
provided to this function. This function skips any request IDs reserved for
events.

#### <a id="c-ssh_rqid_to_event"></a>`ssh_rqid_to_event()`

```c
u16 ssh_rqid_to_event(u16 rqid)
```

Convert request ID to its corresponding event ID.

**Parameters**

- `u16 rqid`: The request ID to convert.

#### <a id="c-ssh_rqid_is_event"></a>`ssh_rqid_is_event()`

```c
bool ssh_rqid_is_event(u16 rqid)
```

Check if given request ID is a valid event ID.

**Parameters**

- `u16 rqid`: The request ID to check.

#### <a id="c-ssh_tc_to_rqid"></a>`ssh_tc_to_rqid()`

```c
u16 ssh_tc_to_rqid(u8 tc)
```

Convert target category to its corresponding request ID.

**Parameters**

- `u8 tc`: The target category to convert.

#### <a id="c-ssh_tid_to_index"></a>`ssh_tid_to_index()`

```c
u8 ssh_tid_to_index(u8 tid)
```

Convert target ID to its corresponding target index.

**Parameters**

- `u8 tid`: The target ID to convert.

#### <a id="c-ssh_tid_is_valid"></a>`ssh_tid_is_valid()`

```c
bool ssh_tid_is_valid(u8 tid)
```

Check if target ID is valid/supported.

**Parameters**

- `u8 tid`: The target ID to check.

#### <a id="c-struct-ssam_span"></a>`struct ssam_span`

Reference to a buffer region.

**Definition**

```c
struct ssam_span {
    u8 *ptr;
    size_t len;
};
```

**Members**

- `ptr`: Pointer to the buffer region.
- `len`: Length of the buffer region.

**Description**

A reference to a (non-owned) buffer segment, consisting of pointer and
length. Use of this struct indicates non-owned data, i.e. data of which the
life-time is managed (i.e. it is allocated/freed) via another pointer.

#### <a id="c-enum-ssam_ssh_tid"></a>`enum ssam_ssh_tid`

Target/source IDs for Serial Hub messages.

**Constants**

- `SSAM_SSH_TID_HOST`: We as the kernel Serial Hub driver.
- `SSAM_SSH_TID_SAM`: The Surface Aggregator EC.
- `SSAM_SSH_TID_KIP`: Keyboard and perihperal controller.
- `SSAM_SSH_TID_DEBUG`: Debug connector.
- `SSAM_SSH_TID_SURFLINK`: SurfLink connector.

#### <a id="c-enum-ssh_packet_base_priority"></a>`enum ssh_packet_base_priority`

Base priorities for [`struct ssh_packet`](#c-struct-ssh_packet).

**Constants**

- `SSH_PACKET_PRIORITY_FLUSH`: Base priority for flush packets.
- `SSH_PACKET_PRIORITY_DATA`: Base priority for normal data packets.
- `SSH_PACKET_PRIORITY_NAK`: Base priority for NAK packets.
- `SSH_PACKET_PRIORITY_ACK`: Base priority for ACK packets.

#### <a id="c-SSH_PACKET_PRIORITY"></a>`SSH_PACKET_PRIORITY()`

```c
SSH_PACKET_PRIORITY(base, try)
```

Compute packet priority from base priority and number of tries.

**Parameters**

- `base`: The base priority as suffix of [`enum ssh_packet_base_priority`](#c-enum-ssh_packet_base_priority), e.g.
  `FLUSH`, `DATA`, `ACK`, or `NAK`.
- `try`: The number of tries (must be less than 16).

**Description**

Compute the combined packet priority. The combined priority is dominated by
the base priority, whereas the number of (re-)tries decides the precedence
of packets with the same base priority, giving higher priority to packets
that already have more tries.

**Return**

Returns the computed priority as value fitting inside a `u8`. A
higher number means a higher priority.

#### <a id="c-ssh_packet_priority_get_try"></a>`ssh_packet_priority_get_try()`

```c
u8 ssh_packet_priority_get_try(u8 priority)
```

Get number of tries from packet priority.

**Parameters**

- `u8 priority`: The packet priority.

**Return**

Returns the number of tries encoded in the specified packet
priority.

#### <a id="c-ssh_packet_priority_get_base"></a>`ssh_packet_priority_get_base()`

```c
u8 ssh_packet_priority_get_base(u8 priority)
```

Get base priority from packet priority.

**Parameters**

- `u8 priority`: The packet priority.

**Return**

Returns the base priority encoded in the given packet priority.

#### <a id="c-struct-ssh_packet_ops"></a>`struct ssh_packet_ops`

Callback operations for a SSH packet.

**Definition**

```c
struct ssh_packet_ops {
    void (*release)(struct ssh_packet *p);
    void (*complete)(struct ssh_packet *p, int status);
};
```

**Members**

- `release`: Function called when the packet reference count reaches zero.
  This callback must be relied upon to ensure that the packet has
  left the transport system(s).
- `complete`: Function called when the packet is completed, either with
  success or failure. In case of failure, the reason for the
  failure is indicated by the value of the provided status code
  argument. This value will be zero in case of success. Note that
  a call to this callback does not guarantee that the packet is
  not in use by the transport system any more.

#### <a id="c-struct-ssh_packet"></a>`struct ssh_packet`

SSH transport packet.

**Definition**

```c
struct ssh_packet {
    struct ssh_ptl *ptl;
    struct kref refcnt;
    u8 priority;
    struct {
        size_t len;
        u8 *ptr;
    } data;
    unsigned long state;
    ktime_t timestamp;
    struct list_head queue_node;
    struct list_head pending_node;
    const struct ssh_packet_ops *ops;
};
```

**Members**

- `ptl`: Pointer to the packet transport layer. May be `NULL` if the packet
  (or enclosing request) has not been submitted yet.
- `refcnt`: Reference count of the packet.
- `priority`: Priority of the packet. Must be computed via
  [`SSH_PACKET_PRIORITY()`](#c-SSH_PACKET_PRIORITY). Must only be accessed while holding the
  queue lock after first submission.
- `data`: Raw message data.
- `data.len`: Length of the raw message data.
- `data.ptr`: Pointer to the raw message data buffer.
- `state`: State and type flags describing current packet state (dynamic)
  and type (static). See `enum ssh_packet_flags` for possible
  options.
- `timestamp`: Timestamp specifying when the latest transmission of a
  currently pending packet has been started. May be `KTIME_MAX`
  before or in-between transmission attempts. Used for the packet
  timeout implementation. Must only be accessed while holding the
  pending lock after first submission.
- `queue_node`: The list node for the packet queue.
- `pending_node`: The list node for the set of pending packets.
- `ops`: Packet operations.

#### <a id="c-ssh_packet_set_data"></a>`ssh_packet_set_data()`

```c
void ssh_packet_set_data(struct ssh_packet *p, u8 *ptr, size_t len)
```

Set raw message data of packet.

**Parameters**

- `struct ssh_packet *p`: The packet for which the message data should be set.
- `u8 *ptr`: Pointer to the memory holding the message data.
- `size_t len`: Length of the message data.

**Description**

Sets the raw message data buffer of the packet to the provided memory. The
memory is not copied. Instead, the caller is responsible for management
(i.e. allocation and deallocation) of the memory. The caller must ensure
that the provided memory is valid and contains a valid SSH message,
starting from the time of submission of the packet until the `release`
callback has been called. During this time, the memory may not be altered
in any way.

#### <a id="c-struct-ssh_request_ops"></a>`struct ssh_request_ops`

Callback operations for a SSH request.

**Definition**

```c
struct ssh_request_ops {
    void (*release)(struct ssh_request *rqst);
    void (*complete)(struct ssh_request *rqst, const struct ssh_command *cmd, const struct ssam_span *data, int status);
};
```

**Members**

- `release`: Function called when the request's reference count reaches zero.
  This callback must be relied upon to ensure that the request has
  left the transport systems (both, packet an request systems).
- `complete`: Function called when the request is completed, either with
  success or failure. The command data for the request response
  is provided via the [`struct ssh_command`](#c-struct-ssh_command) parameter (`cmd`),
  the command payload of the request response via the `struct ssh_span` parameter (`data`).

**Description**

If the request does not have any response or has not been
completed with success, both `cmd` and `data` parameters will
be NULL. If the request response does not have any command
payload, the `data` span will be an empty (zero-length) span.

In case of failure, the reason for the failure is indicated by
the value of the provided status code argument (`status`). This
value will be zero in case of success and a regular errno
otherwise.

Note that a call to this callback does not guarantee that the
request is not in use by the transport systems any more.

#### <a id="c-struct-ssh_request"></a>`struct ssh_request`

SSH transport request.

**Definition**

```c
struct ssh_request {
    struct ssh_packet packet;
    struct list_head node;
    unsigned long state;
    ktime_t timestamp;
    const struct ssh_request_ops *ops;
};
```

**Members**

- `packet`: The underlying SSH transport packet.
- `node`: List node for the request queue and pending set.
- `state`: State and type flags describing current request state (dynamic)
  and type (static). See `enum ssh_request_flags` for possible
  options.
- `timestamp`: Timestamp specifying when we start waiting on the response of
  the request. This is set once the underlying packet has been
  completed and may be `KTIME_MAX` before that, or when the request
  does not expect a response. Used for the request timeout
  implementation.
- `ops`: Request Operations.

#### <a id="c-to_ssh_request"></a>`to_ssh_request()`

```c
struct ssh_request * to_ssh_request(struct ssh_packet *p)
```

Cast a SSH packet to its enclosing SSH request.

**Parameters**

- `struct ssh_packet *p`: The packet to cast.

**Description**

Casts the given [`struct ssh_packet`](#c-struct-ssh_packet) to its enclosing [`struct ssh_request`](#c-struct-ssh_request).
The caller is responsible for making sure that the packet is actually
wrapped in a [`struct ssh_request`](#c-struct-ssh_request).

**Return**

Returns the [`struct ssh_request`](#c-struct-ssh_request) wrapping the provided packet.

#### <a id="c-ssh_request_get"></a>`ssh_request_get()`

```c
struct ssh_request * ssh_request_get(struct ssh_request *r)
```

Increment reference count of request.

**Parameters**

- `struct ssh_request *r`: The request to increment the reference count of.

**Description**

Increments the reference count of the given request by incrementing the
reference count of the underlying [`struct ssh_packet`](#c-struct-ssh_packet), enclosed in it.

See also [`ssh_request_put()`](#c-ssh_request_put), [`ssh_packet_get()`](#c-ssh_packet_get).

**Return**

Returns the request provided as input.

#### <a id="c-ssh_request_put"></a>`ssh_request_put()`

```c
void ssh_request_put(struct ssh_request *r)
```

Decrement reference count of request.

**Parameters**

- `struct ssh_request *r`: The request to decrement the reference count of.

**Description**

Decrements the reference count of the given request by decrementing the
reference count of the underlying [`struct ssh_packet`](#c-struct-ssh_packet), enclosed in it. If
the reference count reaches zero, the `release` callback specified in the
request's [`struct ssh_request_ops`](#c-struct-ssh_request_ops), i.e. `r->ops->release`, will be
called.

See also [`ssh_request_get()`](#c-ssh_request_get), [`ssh_packet_put()`](#c-ssh_packet_put).

#### <a id="c-ssh_request_set_data"></a>`ssh_request_set_data()`

```c
void ssh_request_set_data(struct ssh_request *r, u8 *ptr, size_t len)
```

Set raw message data of request.

**Parameters**

- `struct ssh_request *r`: The request for which the message data should be set.
- `u8 *ptr`: Pointer to the memory holding the message data.
- `size_t len`: Length of the message data.

**Description**

Sets the raw message data buffer of the underlying packet to the specified
buffer. Does not copy the actual message data, just sets the buffer pointer
and length. Refer to [`ssh_packet_set_data()`](#c-ssh_packet_set_data) for more details.



#### <a id="c-ssh_packet_get"></a>`ssh_packet_get()`

```c
struct ssh_packet * ssh_packet_get(struct ssh_packet *packet)
```

Increment reference count of packet.

**Parameters**

- `struct ssh_packet *packet`: The packet to increment the reference count of.

**Description**

Increments the reference count of the given packet. See [`ssh_packet_put()`](#c-ssh_packet_put)
for the counter-part of this function.

**Return**

Returns the packet provided as input.

#### <a id="c-ssh_packet_put"></a>`ssh_packet_put()`

```c
void ssh_packet_put(struct ssh_packet *packet)
```

Decrement reference count of packet.

**Parameters**

- `struct ssh_packet *packet`: The packet to decrement the reference count of.

**Description**

If the reference count reaches zero, the `release` callback specified in
the packet's [`struct ssh_packet_ops`](#c-struct-ssh_packet_ops), i.e. `packet->ops->release`, will be
called.

See [`ssh_packet_get()`](#c-ssh_packet_get) for the counter-part of this function.


<a id="rst-controller-and-core-interface"></a>

## Controller and Core Interface


#### <a id="c-enum-ssam_event_flags"></a>`enum ssam_event_flags`

Flags for enabling/disabling SAM events

**Constants**

- `SSAM_EVENT_SEQUENCED`: The event will be sent via a sequenced data frame.

#### <a id="c-struct-ssam_event"></a>`struct ssam_event`

SAM event sent from the EC to the host.

**Definition**

```c
struct ssam_event {
    u8 target_category;
    u8 target_id;
    u8 command_id;
    u8 instance_id;
    u16 length;
    u8 data[] ;
};
```

**Members**

- `target_category`: Target category of the event source. See `enum ssam_ssh_tc`.
- `target_id`: Target ID of the event source.
- `command_id`: Command ID of the event.
- `instance_id`: Instance ID of the event source.
- `length`: Length of the event payload in bytes.
- `data`: Event payload data.

#### <a id="c-enum-ssam_request_flags"></a>`enum ssam_request_flags`

Flags for SAM requests.

**Constants**

- `SSAM_REQUEST_HAS_RESPONSE`: Specifies that the request expects a response. If not set, the request
  will be directly completed after its underlying packet has been
  transmitted. If set, the request transport system waits for a response
  of the request.
- `SSAM_REQUEST_UNSEQUENCED`: Specifies that the request should be transmitted via an unsequenced
  packet. If set, the request must not have a response, meaning that this
  flag and the `SSAM_REQUEST_HAS_RESPONSE` flag are mutually exclusive.

#### <a id="c-struct-ssam_request"></a>`struct ssam_request`

SAM request description.

**Definition**

```c
struct ssam_request {
    u8 target_category;
    u8 target_id;
    u8 command_id;
    u8 instance_id;
    u16 flags;
    u16 length;
    const u8 *payload;
};
```

**Members**

- `target_category`: Category of the request's target. See `enum ssam_ssh_tc`.
- `target_id`: ID of the request's target.
- `command_id`: Command ID of the request.
- `instance_id`: Instance ID of the request's target.
- `flags`: Flags for the request. See [`enum ssam_request_flags`](#c-enum-ssam_request_flags).
- `length`: Length of the request payload in bytes.
- `payload`: Request payload data.

**Description**

This struct fully describes a SAM request with payload. It is intended to
help set up the actual transport struct, e.g. [`struct ssam_request_sync`](#c-struct-ssam_request_sync),
and specifically its raw message data via [`ssam_request_write_data()`](#c-ssam_request_write_data).

#### <a id="c-struct-ssam_response"></a>`struct ssam_response`

Response buffer for SAM request.

**Definition**

```c
struct ssam_response {
    size_t capacity;
    size_t length;
    u8 *pointer;
};
```

**Members**

- `capacity`: Capacity of the buffer, in bytes.
- `length`: Length of the actual data stored in the memory pointed to by
  **pointer**, in bytes. Set by the transport system.
- `pointer`: Pointer to the buffer's memory, storing the response payload data.

#### <a id="c-struct-ssam_request_sync"></a>`struct ssam_request_sync`

Synchronous SAM request struct.

**Definition**

```c
struct ssam_request_sync {
    struct ssh_request base;
    struct completion comp;
    struct ssam_response *resp;
    int status;
};
```

**Members**

- `base`: Underlying SSH request.
- `comp`: Completion used to signal full completion of the request. After the
  request has been submitted, this struct may only be modified or
  deallocated after the completion has been signaled.
  request has been submitted,
- `resp`: Buffer to store the response.
- `status`: Status of the request, set after the base request has been
  completed or has failed.

#### <a id="c-ssam_request_sync_set_data"></a>`ssam_request_sync_set_data()`

```c
void ssam_request_sync_set_data(struct ssam_request_sync *rqst, u8 *ptr, size_t len)
```

Set message data of a synchronous request.

**Parameters**

- `struct ssam_request_sync *rqst`: The request.
- `u8 *ptr`: Pointer to the request message data.
- `size_t len`: Length of the request message data.

**Description**

Set the request message data of a synchronous request. The provided buffer
needs to live until the request has been completed.

#### <a id="c-ssam_request_sync_set_resp"></a>`ssam_request_sync_set_resp()`

```c
void ssam_request_sync_set_resp(struct ssam_request_sync *rqst, struct ssam_response *resp)
```

Set response buffer of a synchronous request.

**Parameters**

- `struct ssam_request_sync *rqst`: The request.
- `struct ssam_response *resp`: The response buffer.

**Description**

Sets the response buffer of a synchronous request. This buffer will store
the response of the request after it has been completed. May be `NULL` if no
response is expected.

#### <a id="c-ssam_request_sync_wait"></a>`ssam_request_sync_wait()`

```c
int ssam_request_sync_wait(struct ssam_request_sync *rqst)
```

Wait for completion of a synchronous request.

**Parameters**

- `struct ssam_request_sync *rqst`: The request to wait for.

**Description**

Wait for completion and release of a synchronous request. After this
function terminates, the request is guaranteed to have left the transport
system. After successful submission of a request, this function must be
called before accessing the response of the request, freeing the request,
or freeing any of the buffers associated with the request.

This function must not be called if the request has not been submitted yet
and may lead to a deadlock/infinite wait if a subsequent request submission
fails in that case, due to the completion never triggering.

**Return**

Returns the status of the given request, which is set on completion
of the packet. This value is zero on success and negative on failure.

#### <a id="c-ssam_request_do_sync_onstack"></a>`ssam_request_do_sync_onstack()`

```c
ssam_request_do_sync_onstack(ctrl, rqst, rsp, payload_len)
```

Execute a synchronous request on the stack.

**Parameters**

- `ctrl`: The controller via which the request is submitted.
- `rqst`: The request specification.
- `rsp`: The response buffer.
- `payload_len`: The (maximum) request payload length.

**Description**

Allocates a synchronous request with specified payload length on the stack,
fully initializes it via the provided request specification, submits it,
and finally waits for its completion before returning its status. This
helper macro essentially allocates the request message buffer on the stack
and then calls [`ssam_request_do_sync_with_buffer()`](#c-ssam_request_do_sync_with_buffer).

**Note**

The **payload_len** parameter specifies the maximum payload length, used
for buffer allocation. The actual payload length may be smaller.

**Return**

Returns the status of the request or any failure during setup, i.e.
zero on success and a negative value on failure.

#### <a id="c-__ssam_retry"></a>`__ssam_retry()`

```c
__ssam_retry(request, n, args...)
```

Retry request in case of I/O errors or timeouts.

**Parameters**

- `request`: The request function to execute. Must return an integer.
- `n`: Number of tries.
- `args...`: Arguments for the request function.

**Description**

Executes the given request function, i.e. calls **request**. In case the
request returns `-EREMOTEIO` (indicates I/O error) or `-ETIMEDOUT` (request
or underlying packet timed out), **request** will be re-executed again, up to
**n** times in total.

**Return**

Returns the return value of the last execution of **request**.

#### <a id="c-ssam_retry"></a>`ssam_retry()`

```c
ssam_retry(request, args...)
```

Retry request in case of I/O errors or timeouts up to three times in total.

**Parameters**

- `request`: The request function to execute. Must return an integer.
- `args...`: Arguments for the request function.

**Description**

Executes the given request function, i.e. calls **request**. In case the
request returns `-EREMOTEIO` (indicates I/O error) or -`ETIMEDOUT` (request
or underlying packet timed out), **request** will be re-executed again, up to
three times in total.

See [`__ssam_retry()`](#c-__ssam_retry) for a more generic macro for this purpose.

**Return**

Returns the return value of the last execution of **request**.

#### <a id="c-struct-ssam_request_spec"></a>`struct ssam_request_spec`

Blue-print specification of SAM request.

**Definition**

```c
struct ssam_request_spec {
    u8 target_category;
    u8 target_id;
    u8 command_id;
    u8 instance_id;
    u8 flags;
};
```

**Members**

- `target_category`: Category of the request's target. See `enum ssam_ssh_tc`.
- `target_id`: ID of the request's target.
- `command_id`: Command ID of the request.
- `instance_id`: Instance ID of the request's target.
- `flags`: Flags for the request. See [`enum ssam_request_flags`](#c-enum-ssam_request_flags).

**Description**

Blue-print specification for a SAM request. This struct describes the
unique static parameters of a request (i.e. type) without specifying any of
its instance-specific data (e.g. payload). It is intended to be used as base
for defining simple request functions via the
`SSAM_DEFINE_SYNC_REQUEST_x()` family of macros.

#### <a id="c-struct-ssam_request_spec_md"></a>`struct ssam_request_spec_md`

Blue-print specification for multi-device SAM request.

**Definition**

```c
struct ssam_request_spec_md {
    u8 target_category;
    u8 command_id;
    u8 flags;
};
```

**Members**

- `target_category`: Category of the request's target. See `enum ssam_ssh_tc`.
- `command_id`: Command ID of the request.
- `flags`: Flags for the request. See [`enum ssam_request_flags`](#c-enum-ssam_request_flags).

**Description**

Blue-print specification for a multi-device SAM request, i.e. a request
that is applicable to multiple device instances, described by their
individual target and instance IDs. This struct describes the unique static
parameters of a request (i.e. type) without specifying any of its
instance-specific data (e.g. payload) and without specifying any of its
device specific IDs (i.e. target and instance ID). It is intended to be
used as base for defining simple multi-device request functions via the
`SSAM_DEFINE_SYNC_REQUEST_MD_x()` and `SSAM_DEFINE_SYNC_REQUEST_CL_x()`
families of macros.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_N"></a>`SSAM_DEFINE_SYNC_REQUEST_N()`

```c
SSAM_DEFINE_SYNC_REQUEST_N(name, spec...)
```

Define synchronous SAM request function with neither argument nor return value.

**Parameters**

- `name`: Name of the generated function.
- `spec...`: Specification ([`struct ssam_request_spec`](#c-struct-ssam_request_spec)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request having neither argument nor return value. The
generated function takes care of setting up the request struct and buffer
allocation, as well as execution of the request itself, returning once the
request has been fully completed. The required transport buffer will be
allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl)`, returning the status of the request, which is
zero on success and negative on failure. The `ctrl` parameter is the
controller via which the request is being sent.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_W"></a>`SSAM_DEFINE_SYNC_REQUEST_W()`

```c
SSAM_DEFINE_SYNC_REQUEST_W(name, atype, spec...)
```

Define synchronous SAM request function with argument.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `spec...`: Specification ([`struct ssam_request_spec`](#c-struct-ssam_request_spec)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking an argument of type **atype** and having no
return value. The generated function takes care of setting up the request
struct, buffer allocation, as well as execution of the request itself,
returning once the request has been fully completed. The required transport
buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, const atype *arg)`, returning the status of the
request, which is zero on success and negative on failure. The `ctrl`
parameter is the controller via which the request is sent. The request
argument is specified via the `arg` pointer.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_R"></a>`SSAM_DEFINE_SYNC_REQUEST_R()`

```c
SSAM_DEFINE_SYNC_REQUEST_R(name, rtype, spec...)
```

Define synchronous SAM request function with return value.

**Parameters**

- `name`: Name of the generated function.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec`](#c-struct-ssam_request_spec)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking no argument but having a return value of
type **rtype**. The generated function takes care of setting up the request
and response structs, buffer allocation, as well as execution of the
request itself, returning once the request has been fully completed. The
required transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, rtype *ret)`, returning the status of the request,
which is zero on success and negative on failure. The `ctrl` parameter is
the controller via which the request is sent. The request's return value is
written to the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_WR"></a>`SSAM_DEFINE_SYNC_REQUEST_WR()`

```c
SSAM_DEFINE_SYNC_REQUEST_WR(name, atype, rtype, spec...)
```

Define synchronous SAM request function with both argument and return value.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec`](#c-struct-ssam_request_spec)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by **spec**,
with the request taking an argument of type **atype** and having a return value
of type **rtype**. The generated function takes care of setting up the request
and response structs, buffer allocation, as well as execution of the request
itself, returning once the request has been fully completed. The required
transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, const atype *arg, rtype *ret)`, returning the status
of the request, which is zero on success and negative on failure. The
`ctrl` parameter is the controller via which the request is sent. The
request argument is specified via the `arg` pointer. The request's return
value is written to the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_MD_N"></a>`SSAM_DEFINE_SYNC_REQUEST_MD_N()`

```c
SSAM_DEFINE_SYNC_REQUEST_MD_N(name, spec...)
```

Define synchronous multi-device SAM request function with neither argument nor return value.

**Parameters**

- `name`: Name of the generated function.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request having neither argument nor return value. Device
specifying parameters are not hard-coded, but instead must be provided to
the function. The generated function takes care of setting up the request
struct, buffer allocation, as well as execution of the request itself,
returning once the request has been fully completed. The required transport
buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, u8 tid, u8 iid)`, returning the status of the
request, which is zero on success and negative on failure. The `ctrl`
parameter is the controller via which the request is sent, `tid` the
target ID for the request, and `iid` the instance ID.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_MD_W"></a>`SSAM_DEFINE_SYNC_REQUEST_MD_W()`

```c
SSAM_DEFINE_SYNC_REQUEST_MD_W(name, atype, spec...)
```

Define synchronous multi-device SAM request function with argument.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking an argument of type **atype** and having no
return value. Device specifying parameters are not hard-coded, but instead
must be provided to the function. The generated function takes care of
setting up the request struct, buffer allocation, as well as execution of
the request itself, returning once the request has been fully completed.
The required transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, u8 tid, u8 iid, const atype *arg)`, returning the
status of the request, which is zero on success and negative on failure.
The `ctrl` parameter is the controller via which the request is sent,
`tid` the target ID for the request, and `iid` the instance ID. The
request argument is specified via the `arg` pointer.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_MD_R"></a>`SSAM_DEFINE_SYNC_REQUEST_MD_R()`

```c
SSAM_DEFINE_SYNC_REQUEST_MD_R(name, rtype, spec...)
```

Define synchronous multi-device SAM request function with return value.

**Parameters**

- `name`: Name of the generated function.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking no argument but having a return value of
type **rtype**. Device specifying parameters are not hard-coded, but instead
must be provided to the function. The generated function takes care of
setting up the request and response structs, buffer allocation, as well as
execution of the request itself, returning once the request has been fully
completed. The required transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, u8 tid, u8 iid, rtype *ret)`, returning the status
of the request, which is zero on success and negative on failure. The
`ctrl` parameter is the controller via which the request is sent, `tid`
the target ID for the request, and `iid` the instance ID. The request's
return value is written to the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_MD_WR"></a>`SSAM_DEFINE_SYNC_REQUEST_MD_WR()`

```c
SSAM_DEFINE_SYNC_REQUEST_MD_WR(name, atype, rtype, spec...)
```

Define synchronous multi-device SAM request function with both argument and return value.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by **spec**,
with the request taking an argument of type **atype** and having a return value
of type **rtype**. Device specifying parameters are not hard-coded, but instead
must be provided to the function. The generated function takes care of
setting up the request and response structs, buffer allocation, as well as
execution of the request itself, returning once the request has been fully
completed. The required transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, u8 tid, u8 iid, const atype *arg, rtype *ret)`,
returning the status of the request, which is zero on success and negative
on failure. The `ctrl` parameter is the controller via which the request
is sent, `tid` the target ID for the request, and `iid` the instance ID.
The request argument is specified via the `arg` pointer. The request's
return value is written to the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-enum-ssam_notif_flags"></a>`enum ssam_notif_flags`

Flags used in return values from SSAM notifier callback functions.

**Constants**

- `SSAM_NOTIF_HANDLED`: Indicates that the notification has been handled. This flag should be
  set by the handler if the handler can act/has acted upon the event
  provided to it. This flag should not be set if the handler is not a
  primary handler intended for the provided event.
- `SSAM_NOTIF_STOP`: Indicates that the notifier traversal should stop. If this flag is
  returned from a notifier callback, notifier chain traversal will
  immediately stop and any remaining notifiers will not be called. This
  flag is automatically set when [`ssam_notifier_from_errno()`](#c-ssam_notifier_from_errno) is called
  with a negative error value.

**Description**

If this flag has not been set by any handler after the notifier chain
has been traversed, a warning will be emitted, stating that the event
has not been handled.

#### <a id="c-struct-ssam_notifier_block"></a>`struct ssam_notifier_block`

Base notifier block for SSAM event notifications.

**Definition**

```c
struct ssam_notifier_block {
    struct list_head node;
    ssam_notifier_fn_t fn;
    int priority;
};
```

**Members**

- `node`: The node for the list of notifiers.
- `fn`: The callback function of this notifier. This function takes the
  respective notifier block and event as input and should return
  a notifier value, which can either be obtained from the flags
  provided in [`enum ssam_notif_flags`](#c-enum-ssam_notif_flags), converted from a standard
  error value via [`ssam_notifier_from_errno()`](#c-ssam_notifier_from_errno), or a combination of
  both (e.g. `ssam_notifier_from_errno(e) | SSAM_NOTIF_HANDLED`).
- `priority`: Priority value determining the order in which notifier callbacks
  will be called. A higher value means higher priority, i.e. the
  associated callback will be executed earlier than other (lower
  priority) callbacks.

#### <a id="c-ssam_notifier_from_errno"></a>`ssam_notifier_from_errno()`

```c
u32 ssam_notifier_from_errno(int err)
```

Convert standard error value to notifier return code.

**Parameters**

- `int err`: The error code to convert, must be negative (in case of failure) or
  zero (in case of success).

**Return**

Returns the notifier return value obtained by converting the
specified **err** value. In case **err** is negative, the `SSAM_NOTIF_STOP` flag
will be set, causing notifier call chain traversal to abort.

#### <a id="c-ssam_notifier_to_errno"></a>`ssam_notifier_to_errno()`

```c
int ssam_notifier_to_errno(u32 ret)
```

Convert notifier return code to standard error value.

**Parameters**

- `u32 ret`: The notifier return value to convert.

**Return**

Returns the negative error value encoded in **ret** or zero if **ret**
indicates success.

#### <a id="c-struct-ssam_event_registry"></a>`struct ssam_event_registry`

Registry specification used for enabling events.

**Definition**

```c
struct ssam_event_registry {
    u8 target_category;
    u8 target_id;
    u8 cid_enable;
    u8 cid_disable;
};
```

**Members**

- `target_category`: Target category for the event registry requests.
- `target_id`: Target ID for the event registry requests.
- `cid_enable`: Command ID for the event-enable request.
- `cid_disable`: Command ID for the event-disable request.

**Description**

This struct describes a SAM event registry via the minimal collection of
SAM IDs specifying the requests to use for enabling and disabling an event.
The individual event to be enabled/disabled itself is specified via [`struct ssam_event_id`](#c-struct-ssam_event_id).

#### <a id="c-struct-ssam_event_id"></a>`struct ssam_event_id`

Unique event ID used for enabling events.

**Definition**

```c
struct ssam_event_id {
    u8 target_category;
    u8 instance;
};
```

**Members**

- `target_category`: Target category of the event source.
- `instance`: Instance ID of the event source.

**Description**

This struct specifies the event to be enabled/disabled via an externally
provided registry. It does not specify the registry to be used itself, this
is done via [`struct ssam_event_registry`](#c-struct-ssam_event_registry).

#### <a id="c-enum-ssam_event_mask"></a>`enum ssam_event_mask`

Flags specifying how events are matched to notifiers.

**Constants**

- `SSAM_EVENT_MASK_TARGET`: In addition to filtering by target category, only execute the notifier
  callback for events with a target ID matching to the one of the
  registry used for enabling/disabling the event.
- `SSAM_EVENT_MASK_INSTANCE`: In addition to filtering by target category, only execute the notifier
  callback for events with an instance ID matching to the instance ID
  used when enabling the event.
- `SSAM_EVENT_MASK_NONE`: Run the callback for any event with matching target category. Do not
  do any additional filtering.
- `SSAM_EVENT_MASK_STRICT`: Do all the filtering above.

#### <a id="c-SSAM_EVENT_REGISTRY"></a>`SSAM_EVENT_REGISTRY()`

```c
SSAM_EVENT_REGISTRY(tc, tid, cid_en, cid_dis)
```

Define a new event registry.

**Parameters**

- `tc`: Target category for the event registry requests.
- `tid`: Target ID for the event registry requests.
- `cid_en`: Command ID for the event-enable request.
- `cid_dis`: Command ID for the event-disable request.

**Return**

Returns the [`struct ssam_event_registry`](#c-struct-ssam_event_registry) specified by the given
parameters.

#### <a id="c-enum-ssam_event_notifier_flags"></a>`enum ssam_event_notifier_flags`

Flags for event notifiers.

**Constants**

- `SSAM_EVENT_NOTIFIER_OBSERVER`: The corresponding notifier acts as observer. Registering a notifier
  with this flag set will not attempt to enable any event. Equally,
  unregistering will not attempt to disable any event. Note that a
  notifier with this flag may not even correspond to a certain event at
  all, only to a specific event target category. Event matching will not
  be influenced by this flag.

#### <a id="c-struct-ssam_event_notifier"></a>`struct ssam_event_notifier`

Notifier block for SSAM events.

**Definition**

```c
struct ssam_event_notifier {
    struct ssam_notifier_block base;
    struct {
        struct ssam_event_registry reg;
        struct ssam_event_id id;
        enum ssam_event_mask mask;
        u8 flags;
    } event;
    unsigned long flags;
};
```

**Members**

- `base`: The base notifier block with callback function and priority.
- `event`: The event for which this block will receive notifications.
- `event.reg`: Registry via which the event will be enabled/disabled.
- `event.id`: ID specifying the event.
- `event.mask`: Flags determining how events are matched to the notifier.
- `event.flags`: Flags used for enabling the event.
- `flags`: Notifier flags (see [`enum ssam_event_notifier_flags`](#c-enum-ssam_event_notifier_flags)).

#### <a id="c-ssam_notifier_unregister"></a>`ssam_notifier_unregister()`

```c
int ssam_notifier_unregister(struct ssam_controller *ctrl, struct ssam_event_notifier *n)
```

Unregister an event notifier.

**Parameters**

- `struct ssam_controller *ctrl`: The controller the notifier has been registered on.
- `struct ssam_event_notifier *n`: The event notifier to unregister.

**Description**

Unregister an event notifier. Decrement the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the usage counter
reaches zero, the event will be disabled.

**Return**

Returns zero on success, `-ENOENT` if the given notifier block has
not been registered on the controller. If the given notifier block was the
last one associated with its specific event, returns the status of the
event-disable EC-command.



#### <a id="c-ssam_controller_device"></a>`ssam_controller_device()`

```c
struct device * ssam_controller_device(struct ssam_controller *c)
```

Get the [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) associated with this controller.

**Parameters**

- `struct ssam_controller *c`: The controller for which to get the device.

**Return**

Returns the [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) associated with this controller,
providing its lower-level transport.

#### <a id="c-ssam_controller_get"></a>`ssam_controller_get()`

```c
struct ssam_controller * ssam_controller_get(struct ssam_controller *c)
```

Increment reference count of controller.

**Parameters**

- `struct ssam_controller *c`: The controller.

**Return**

Returns the controller provided as input.

#### <a id="c-ssam_controller_put"></a>`ssam_controller_put()`

```c
void ssam_controller_put(struct ssam_controller *c)
```

Decrement reference count of controller.

**Parameters**

- `struct ssam_controller *c`: The controller.

#### <a id="c-ssam_controller_statelock"></a>`ssam_controller_statelock()`

```c
void ssam_controller_statelock(struct ssam_controller *c)
```

Lock the controller against state transitions.

**Parameters**

- `struct ssam_controller *c`: The controller to lock.

**Description**

Lock the controller against state transitions. Holding this lock guarantees
that the controller will not transition between states, i.e. if the
controller is in state "started", when this lock has been acquired, it will
remain in this state at least until the lock has been released.

Multiple clients may concurrently hold this lock. In other words: The
`statelock` functions represent the read-lock part of a r/w-semaphore.
Actions causing state transitions of the controller must be executed while
holding the write-part of this r/w-semaphore (see [`ssam_controller_lock()`](/kernel/hardware/driver-api/surface-aggregator/internal-api.md#c-ssam_controller_lock)
and `ssam_controller_unlock()` for that).

See [`ssam_controller_stateunlock()`](#c-ssam_controller_stateunlock) for the corresponding unlock function.

#### <a id="c-ssam_controller_stateunlock"></a>`ssam_controller_stateunlock()`

```c
void ssam_controller_stateunlock(struct ssam_controller *c)
```

Unlock controller state transitions.

**Parameters**

- `struct ssam_controller *c`: The controller to unlock.

**Description**

See [`ssam_controller_statelock()`](#c-ssam_controller_statelock) for the corresponding lock function.

#### <a id="c-ssam_request_write_data"></a>`ssam_request_write_data()`

```c
ssize_t ssam_request_write_data(struct ssam_span *buf, struct ssam_controller *ctrl, const struct ssam_request *spec)
```

Construct and write SAM request message to buffer.

**Parameters**

- `struct ssam_span *buf`: The buffer to write the data to.
- `struct ssam_controller *ctrl`: The controller via which the request will be sent.
- `const struct ssam_request *spec`: The request data and specification.

**Description**

Constructs a SAM/SSH request message and writes it to the provided buffer.
The request and transport counters, specifically RQID and SEQ, will be set
in this call. These counters are obtained from the controller. It is thus
only valid to send the resulting message via the controller specified here.

For calculation of the required buffer size, refer to the
[`SSH_COMMAND_MESSAGE_LENGTH()`](#c-SSH_COMMAND_MESSAGE_LENGTH) macro.

**Return**

Returns the number of bytes used in the buffer on success. Returns
`-EINVAL` if the payload length provided in the request specification is too
large (larger than `SSH_COMMAND_MAX_PAYLOAD_SIZE`) or if the provided buffer
is too small.

#### <a id="c-ssam_request_sync_alloc"></a>`ssam_request_sync_alloc()`

```c
int ssam_request_sync_alloc(size_t payload_len, gfp_t flags, struct ssam_request_sync **rqst, struct ssam_span *buffer)
```

Allocate a synchronous request.

**Parameters**

- `size_t payload_len`: The length of the request payload.
- `gfp_t flags`: Flags used for allocation.
- `struct ssam_request_sync **rqst`: Where to store the pointer to the allocated request.
- `struct ssam_span *buffer`: Where to store the buffer descriptor for the message buffer of
  the request.

**Description**

Allocates a synchronous request with corresponding message buffer. The
request still needs to be initialized [`ssam_request_sync_init()`](#c-ssam_request_sync_init) before
it can be submitted, and the message buffer data must still be set to the
returned buffer via [`ssam_request_sync_set_data()`](#c-ssam_request_sync_set_data) after it has been filled,
if need be with adjusted message length.

After use, the request and its corresponding message buffer should be freed
via [`ssam_request_sync_free()`](#c-ssam_request_sync_free). The buffer must not be freed separately.

**Return**

Returns zero on success, `-ENOMEM` if the request could not be
allocated.

#### <a id="c-ssam_request_sync_free"></a>`ssam_request_sync_free()`

```c
void ssam_request_sync_free(struct ssam_request_sync *rqst)
```

Free a synchronous request.

**Parameters**

- `struct ssam_request_sync *rqst`: The request to be freed.

**Description**

Free a synchronous request and its corresponding buffer allocated with
[`ssam_request_sync_alloc()`](#c-ssam_request_sync_alloc). Do not use for requests allocated on the stack
or via any other function.

Warning: The caller must ensure that the request is not in use any more.
I.e. the caller must ensure that it has the only reference to the request
and the request is not currently pending. This means that the caller has
either never submitted the request, request submission has failed, or the
caller has waited until the submitted request has been completed via
[`ssam_request_sync_wait()`](#c-ssam_request_sync_wait).

#### <a id="c-ssam_request_sync_init"></a>`ssam_request_sync_init()`

```c
int ssam_request_sync_init(struct ssam_request_sync *rqst, enum ssam_request_flags flags)
```

Initialize a synchronous request struct.

**Parameters**

- `struct ssam_request_sync *rqst`: The request to initialize.
- `enum ssam_request_flags flags`: The request flags.

**Description**

Initializes the given request struct. Does not initialize the request
message data. This has to be done explicitly after this call via
[`ssam_request_sync_set_data()`](#c-ssam_request_sync_set_data) and the actual message data has to be written
via [`ssam_request_write_data()`](#c-ssam_request_write_data).

**Return**

Returns zero on success or `-EINVAL` if the given flags are invalid.

#### <a id="c-ssam_request_sync_submit"></a>`ssam_request_sync_submit()`

```c
int ssam_request_sync_submit(struct ssam_controller *ctrl, struct ssam_request_sync *rqst)
```

Submit a synchronous request.

**Parameters**

- `struct ssam_controller *ctrl`: The controller with which to submit the request.
- `struct ssam_request_sync *rqst`: The request to submit.

**Description**

Submit a synchronous request. The request has to be initialized and
properly set up, including response buffer (may be `NULL` if no response is
expected) and command message data. This function does not wait for the
request to be completed.

If this function succeeds, [`ssam_request_sync_wait()`](#c-ssam_request_sync_wait) must be used to ensure
that the request has been completed before the response data can be
accessed and/or the request can be freed. On failure, the request may
immediately be freed.

This function may only be used if the controller is active, i.e. has been
initialized and not suspended.

#### <a id="c-ssam_request_do_sync"></a>`ssam_request_do_sync()`

```c
int ssam_request_do_sync(struct ssam_controller *ctrl, const struct ssam_request *spec, struct ssam_response *rsp)
```

Execute a synchronous request.

**Parameters**

- `struct ssam_controller *ctrl`: The controller via which the request will be submitted.
- `const struct ssam_request *spec`: The request specification and payload.
- `struct ssam_response *rsp`: The response buffer.

**Description**

Allocates a synchronous request with its message data buffer on the heap
via [`ssam_request_sync_alloc()`](#c-ssam_request_sync_alloc), fully initializes it via the provided
request specification, submits it, and finally waits for its completion
before freeing it and returning its status.

**Return**

Returns the status of the request or any failure during setup.

#### <a id="c-ssam_request_do_sync_with_buffer"></a>`ssam_request_do_sync_with_buffer()`

```c
int ssam_request_do_sync_with_buffer(struct ssam_controller *ctrl, const struct ssam_request *spec, struct ssam_response *rsp, struct ssam_span *buf)
```

Execute a synchronous request with the provided buffer as back-end for the message buffer.

**Parameters**

- `struct ssam_controller *ctrl`: The controller via which the request will be submitted.
- `const struct ssam_request *spec`: The request specification and payload.
- `struct ssam_response *rsp`: The response buffer.
- `struct ssam_span *buf`: The buffer for the request message data.

**Description**

Allocates a synchronous request struct on the stack, fully initializes it
using the provided buffer as message data buffer, submits it, and then
waits for its completion before returning its status. The
[`SSH_COMMAND_MESSAGE_LENGTH()`](#c-SSH_COMMAND_MESSAGE_LENGTH) macro can be used to compute the required
message buffer size.

This function does essentially the same as [`ssam_request_do_sync()`](#c-ssam_request_do_sync), but
instead of dynamically allocating the request and message data buffer, it
uses the provided message data buffer and stores the (small) request struct
on the heap.

**Return**

Returns the status of the request or any failure during setup.

#### <a id="c-ssam_notifier_register"></a>`ssam_notifier_register()`

```c
int ssam_notifier_register(struct ssam_controller *ctrl, struct ssam_event_notifier *n)
```

Register an event notifier.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to register the notifier on.
- `struct ssam_event_notifier *n`: The event notifier to register.

**Description**

Register an event notifier. Increment the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the event is not
marked as an observer and is currently not enabled, it will be enabled
during this call. If the notifier is marked as an observer, no attempt will
be made at enabling any event and no reference count will be modified.

Notifiers marked as observers do not need to be associated with one specific
event, i.e. as long as no event matching is performed, only the event target
category needs to be set.

**Return**

Returns zero on success, `-ENOSPC` if there have already been
`INT_MAX` notifiers for the event ID/type associated with the notifier block
registered, `-ENOMEM` if the corresponding event entry could not be
allocated. If this is the first time that a notifier block is registered
for the specific associated event, returns the status of the event-enable
EC-command.

#### <a id="c-__ssam_notifier_unregister"></a>`__ssam_notifier_unregister()`

```c
int __ssam_notifier_unregister(struct ssam_controller *ctrl, struct ssam_event_notifier *n, bool disable)
```

Unregister an event notifier.

**Parameters**

- `struct ssam_controller *ctrl`: The controller the notifier has been registered on.
- `struct ssam_event_notifier *n`: The event notifier to unregister.
- `bool disable`: Whether to disable the corresponding event on the EC.

**Description**

Unregister an event notifier. Decrement the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the usage counter
reaches zero and `disable` equals `true`, the event will be disabled.

Useful for hot-removable devices, where communication may fail once the
device has been physically removed. In that case, specifying `disable` as
`false` avoids communication with the EC.

**Return**

Returns zero on success, `-ENOENT` if the given notifier block has
not been registered on the controller. If the given notifier block was the
last one associated with its specific event, returns the status of the
event-disable EC-command.

#### <a id="c-ssam_controller_event_enable"></a>`ssam_controller_event_enable()`

```c
int ssam_controller_event_enable(struct ssam_controller *ctrl, struct ssam_event_registry reg, struct ssam_event_id id, u8 flags)
```

Enable the specified event.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to enable the event for.
- `struct ssam_event_registry reg`: The event registry to use for enabling the event.
- `struct ssam_event_id id`: The event ID specifying the event to be enabled.
- `u8 flags`: The SAM event flags used for enabling the event.

**Description**

Increment the event reference count of the specified event. If the event has
not been enabled previously, it will be enabled by this call.

**Note**

In general, [`ssam_notifier_register()`](#c-ssam_notifier_register) with a non-observer notifier
should be preferred for enabling/disabling events, as this will guarantee
proper ordering and event forwarding in case of errors during event
enabling/disabling.

**Return**

Returns zero on success, `-ENOSPC` if the reference count for the
specified event has reached its maximum, `-ENOMEM` if the corresponding event
entry could not be allocated. If this is the first time that this event has
been enabled (i.e. the reference count was incremented from zero to one by
this call), returns the status of the event-enable EC-command.

#### <a id="c-ssam_controller_event_disable"></a>`ssam_controller_event_disable()`

```c
int ssam_controller_event_disable(struct ssam_controller *ctrl, struct ssam_event_registry reg, struct ssam_event_id id, u8 flags)
```

Disable the specified event.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to disable the event for.
- `struct ssam_event_registry reg`: The event registry to use for disabling the event.
- `struct ssam_event_id id`: The event ID specifying the event to be disabled.
- `u8 flags`: The flags used when enabling the event.

**Description**

Decrement the reference count of the specified event. If the reference count
reaches zero, the event will be disabled.

**Note**

In general, [`ssam_notifier_register()`](#c-ssam_notifier_register)/[`ssam_notifier_unregister()`](#c-ssam_notifier_unregister) with a
non-observer notifier should be preferred for enabling/disabling events, as
this will guarantee proper ordering and event forwarding in case of errors
during event enabling/disabling.

**Return**

Returns zero on success, `-ENOENT` if the given event has not been
enabled on the controller. If the reference count of the event reaches zero
during this call, returns the status of the event-disable EC-command.



#### <a id="c-ssam_get_controller"></a>`ssam_get_controller()`

```c
struct ssam_controller * ssam_get_controller(void)
```

Get reference to SSAM controller.

**Parameters**

- `void`: no arguments

**Description**

Returns a reference to the SSAM controller of the system or `NULL` if there
is none, it hasn't been set up yet, or it has already been unregistered.
This function automatically increments the reference count of the
controller, thus the calling party must ensure that [`ssam_controller_put()`](#c-ssam_controller_put)
is called when it doesn't need the controller any more.

#### <a id="c-ssam_client_link"></a>`ssam_client_link()`

```c
int ssam_client_link(struct ssam_controller *c, struct device *client)
```

Link an arbitrary client device to the controller.

**Parameters**

- `struct ssam_controller *c`: The controller to link to.
- `struct device *client`: The client device.

**Description**

Link an arbitrary client device to the controller by creating a device link
between it as consumer and the controller device as provider. This function
can be used for non-SSAM devices (or SSAM devices not registered as child
under the controller) to guarantee that the controller is valid for as long
as the driver of the client device is bound, and that proper suspend and
resume ordering is guaranteed.

The device link does not have to be destructed manually. It is removed
automatically once the driver of the client device unbinds.

**Return**

Returns zero on success, `-ENODEV` if the controller is not ready or
going to be removed soon, or `-ENOMEM` if the device link could not be
created for other reasons.

#### <a id="c-ssam_client_bind"></a>`ssam_client_bind()`

```c
struct ssam_controller * ssam_client_bind(struct device *client)
```

Bind an arbitrary client device to the controller.

**Parameters**

- `struct device *client`: The client device.

**Description**

Link an arbitrary client device to the controller by creating a device link
between it as consumer and the main controller device as provider. This
function can be used for non-SSAM devices to guarantee that the controller
returned by this function is valid for as long as the driver of the client
device is bound, and that proper suspend and resume ordering is guaranteed.

This function does essentially the same as [`ssam_client_link()`](#c-ssam_client_link), except that
it first fetches the main controller reference, then creates the link, and
finally returns this reference. Note that this function does not increment
the reference counter of the controller, as, due to the link, the
controller lifetime is assured as long as the driver of the client device
is bound.

It is not valid to use the controller reference obtained by this method
outside of the driver bound to the client device at the time of calling
this function, without first incrementing the reference count of the
controller via [`ssam_controller_get()`](#c-ssam_controller_get). Even after doing this, care must be
taken that requests are only submitted and notifiers are only
(un-)registered when the controller is active and not suspended. In other
words: The device link only lives as long as the client driver is bound and
any guarantees enforced by this link (e.g. active controller state) can
only be relied upon as long as this link exists and may need to be enforced
in other ways afterwards.

The created device link does not have to be destructed manually. It is
removed automatically once the driver of the client device unbinds.

**Return**

Returns the controller on success, an error pointer with `-ENODEV`
if the controller is not present, not ready or going to be removed soon, or
`-ENOMEM` if the device link could not be created for other reasons.


<a id="rst-client-bus-and-client-device-api"></a>

## Client Bus and Client Device API


#### <a id="c-enum-ssam_device_domain"></a>`enum ssam_device_domain`

SAM device domain.

**Constants**

- `SSAM_DOMAIN_VIRTUAL`: Virtual device.
- `SSAM_DOMAIN_SERIALHUB`: Physical device connected via Surface Serial Hub.

#### <a id="c-enum-ssam_virtual_tc"></a>`enum ssam_virtual_tc`

Target categories for the virtual SAM domain.

**Constants**

- `SSAM_VIRTUAL_TC_HUB`: Device hub category.

#### <a id="c-struct-ssam_device_uid"></a>`struct ssam_device_uid`

Unique identifier for SSAM device.

**Definition**

```c
struct ssam_device_uid {
    u8 domain;
    u8 category;
    u8 target;
    u8 instance;
    u8 function;
};
```

**Members**

- `domain`: Domain of the device.
- `category`: Target category of the device.
- `target`: Target ID of the device.
- `instance`: Instance ID of the device.
- `function`: Sub-function of the device. This field can be used to split a
  single SAM device into multiple virtual subdevices to separate
  different functionality of that device and allow one driver per
  such functionality.

#### <a id="c-SSAM_DEVICE"></a>`SSAM_DEVICE()`

```c
SSAM_DEVICE(d, cat, tid, iid, fun)
```

Initialize a `struct ssam_device_id` with the given parameters.

**Parameters**

- `d`: Domain of the device.
- `cat`: Target category of the device.
- `tid`: Target ID of the device.
- `iid`: Instance ID of the device.
- `fun`: Sub-function of the device.

**Description**

Initializes a `struct ssam_device_id` with the given parameters. See [`struct ssam_device_uid`](#c-struct-ssam_device_uid) for details regarding the parameters. The special values
`SSAM_SSH_TID_ANY`, `SSAM_SSH_IID_ANY`, and `SSAM_SSH_FUN_ANY` can be used to specify that
matching should ignore target ID, instance ID, and/or sub-function,
respectively. This macro initializes the `match_flags` field based on the
given parameters.

**Note**

The parameters **d** and **cat** must be valid `u8` values, the parameters
**tid**, **iid**, and **fun** must be either valid `u8` values or `SSAM_SSH_TID_ANY`,
`SSAM_SSH_IID_ANY`, or `SSAM_SSH_FUN_ANY`, respectively. Other non-`u8` values are not
allowed.

#### <a id="c-SSAM_VDEV"></a>`SSAM_VDEV()`

```c
SSAM_VDEV(cat, tid, iid, fun)
```

Initialize a `struct ssam_device_id` as virtual device with the given parameters.

**Parameters**

- `cat`: Target category of the device.
- `tid`: Target ID of the device.
- `iid`: Instance ID of the device.
- `fun`: Sub-function of the device.

**Description**

Initializes a `struct ssam_device_id` with the given parameters in the
virtual domain. See [`struct ssam_device_uid`](#c-struct-ssam_device_uid) for details regarding the
parameters. The special values `SSAM_SSH_TID_ANY`, `SSAM_SSH_IID_ANY`, and
`SSAM_SSH_FUN_ANY` can be used to specify that matching should ignore target ID,
instance ID, and/or sub-function, respectively. This macro initializes the
`match_flags` field based on the given parameters.

**Note**

The parameter **cat** must be a valid `u8` value, the parameters **tid**,
**iid**, and **fun** must be either valid `u8` values or `SSAM_SSH_TID_ANY`,
`SSAM_SSH_IID_ANY`, or `SSAM_SSH_FUN_ANY`, respectively. Other non-`u8` values are not
allowed.

#### <a id="c-SSAM_SDEV"></a>`SSAM_SDEV()`

```c
SSAM_SDEV(cat, tid, iid, fun)
```

Initialize a `struct ssam_device_id` as physical SSH device with the given parameters.

**Parameters**

- `cat`: Target category of the device.
- `tid`: Target ID of the device.
- `iid`: Instance ID of the device.
- `fun`: Sub-function of the device.

**Description**

Initializes a `struct ssam_device_id` with the given parameters in the SSH
domain. See [`struct ssam_device_uid`](#c-struct-ssam_device_uid) for details regarding the parameters.
The special values `SSAM_SSH_TID_ANY`, `SSAM_SSH_IID_ANY`, and
`SSAM_SSH_FUN_ANY` can be used to specify that matching should ignore target
ID, instance ID, and/or sub-function, respectively. This macro initializes
the `match_flags` field based on the given parameters.

**Note**

The parameter **cat** must be a valid `u8` value, the parameters **tid**,
**iid**, and **fun** must be either valid `u8` values or `SSAM_SSH_TID_ANY`,
`SSAM_SSH_IID_ANY`, or `SSAM_SSH_FUN_ANY`, respectively. Other non-`u8` values
are not allowed.

#### <a id="c-struct-ssam_device"></a>`struct ssam_device`

SSAM client device.

**Definition**

```c
struct ssam_device {
    struct device dev;
    struct ssam_controller *ctrl;
    struct ssam_device_uid uid;
    unsigned long flags;
};
```

**Members**

- `dev`: Driver model representation of the device.
- `ctrl`: SSAM controller managing this device.
- `uid`: UID identifying the device.
- `flags`: Device state flags, see `enum ssam_device_flags`.

#### <a id="c-struct-ssam_device_driver"></a>`struct ssam_device_driver`

SSAM client device driver.

**Definition**

```c
struct ssam_device_driver {
    struct device_driver driver;
    const struct ssam_device_id *match_table;
    int (*probe)(struct ssam_device *sdev);
    void (*remove)(struct ssam_device *sdev);
};
```

**Members**

- `driver`: Base driver model structure.
- `match_table`: Match table specifying which devices the driver should bind to.
- `probe`: Called when the driver is being bound to a device.
- `remove`: Called when the driver is being unbound from the device.

#### <a id="c-is_ssam_device"></a>`is_ssam_device()`

```c
bool is_ssam_device(struct device *d)
```

Check if the given device is a SSAM client device.

**Parameters**

- `struct device *d`: The device to test the type of.

**Return**

Returns `true` if the specified device is of type [`struct ssam_device`](#c-struct-ssam_device), i.e. the device type points to `ssam_device_type`, and `false`
otherwise.

#### <a id="c-to_ssam_device"></a>`to_ssam_device()`

```c
to_ssam_device(d)
```

Casts the given device to a SSAM client device.

**Parameters**

- `d`: The device to cast.

**Description**

Casts the given [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) to a [`struct ssam_device`](#c-struct-ssam_device). The caller has to
ensure that the given device is actually enclosed in a [`struct ssam_device`](#c-struct-ssam_device),
e.g. by calling [`is_ssam_device()`](#c-is_ssam_device).

**Return**

Returns a pointer to the [`struct ssam_device`](#c-struct-ssam_device) wrapping the given
device **d**.

#### <a id="c-to_ssam_device_driver"></a>`to_ssam_device_driver()`

```c
to_ssam_device_driver(d)
```

Casts the given device driver to a SSAM client device driver.

**Parameters**

- `d`: The driver to cast.

**Description**

Casts the given [`struct device_driver`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device_driver) to a [`struct ssam_device_driver`](#c-struct-ssam_device_driver). The
caller has to ensure that the given driver is actually enclosed in a
[`struct ssam_device_driver`](#c-struct-ssam_device_driver).

**Return**

Returns the pointer to the [`struct ssam_device_driver`](#c-struct-ssam_device_driver) wrapping the
given device driver **d**.

#### <a id="c-ssam_device_mark_hot_removed"></a>`ssam_device_mark_hot_removed()`

```c
void ssam_device_mark_hot_removed(struct ssam_device *sdev)
```

Mark the given device as hot-removed.

**Parameters**

- `struct ssam_device *sdev`: The device to mark as hot-removed.

**Description**

Mark the device as having been hot-removed. This signals drivers using the
device that communication with the device should be avoided and may lead to
timeouts.

#### <a id="c-ssam_device_is_hot_removed"></a>`ssam_device_is_hot_removed()`

```c
bool ssam_device_is_hot_removed(struct ssam_device *sdev)
```

Check if the given device has been hot-removed.

**Parameters**

- `struct ssam_device *sdev`: The device to check.

**Description**

Checks if the given device has been marked as hot-removed. See
[`ssam_device_mark_hot_removed()`](#c-ssam_device_mark_hot_removed) for more details.

**Return**

Returns `true` if the device has been marked as hot-removed.

#### <a id="c-ssam_device_get"></a>`ssam_device_get()`

```c
struct ssam_device * ssam_device_get(struct ssam_device *sdev)
```

Increment reference count of SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to increment the reference count of.

**Description**

Increments the reference count of the given SSAM client device by
incrementing the reference count of the enclosed [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) via
[`get_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-get_device).

See [`ssam_device_put()`](#c-ssam_device_put) for the counter-part of this function.

**Return**

Returns the device provided as input.

#### <a id="c-ssam_device_put"></a>`ssam_device_put()`

```c
void ssam_device_put(struct ssam_device *sdev)
```

Decrement reference count of SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to decrement the reference count of.

**Description**

Decrements the reference count of the given SSAM client device by
decrementing the reference count of the enclosed [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) via
[`put_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-put_device).

See [`ssam_device_get()`](#c-ssam_device_get) for the counter-part of this function.

#### <a id="c-ssam_device_get_drvdata"></a>`ssam_device_get_drvdata()`

```c
void * ssam_device_get_drvdata(struct ssam_device *sdev)
```

Get driver-data of SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to get the driver-data from.

**Return**

Returns the driver-data of the given device, previously set via
[`ssam_device_set_drvdata()`](#c-ssam_device_set_drvdata).

#### <a id="c-ssam_device_set_drvdata"></a>`ssam_device_set_drvdata()`

```c
void ssam_device_set_drvdata(struct ssam_device *sdev, void *data)
```

Set driver-data of SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to set the driver-data of.
- `void *data`: The data to set the device's driver-data pointer to.

#### <a id="c-ssam_device_driver_register"></a>`ssam_device_driver_register()`

```c
ssam_device_driver_register(drv)
```

Register a SSAM client device driver.

**Parameters**

- `drv`: The driver to register.

#### <a id="c-module_ssam_device_driver"></a>`module_ssam_device_driver()`

```c
module_ssam_device_driver(drv)
```

Helper macro for SSAM device driver registration.

**Parameters**

- `drv`: The driver managed by this module.

**Description**

Helper macro to register a SSAM device driver via [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and
[`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit). This macro may only be used once per module and replaces the
aforementioned definitions.

#### <a id="c-ssam_register_clients"></a>`ssam_register_clients()`

```c
int ssam_register_clients(struct device *dev, struct ssam_controller *ctrl)
```

Register all client devices defined under the given parent device.

**Parameters**

- `struct device *dev`: The parent device under which clients should be registered.
- `struct ssam_controller *ctrl`: The controller with which client should be registered.

**Description**

Register all clients that have via firmware nodes been defined as children
of the given (parent) device. The respective child firmware nodes will be
associated with the correspondingly created child devices.

The given controller will be used to instantiate the new devices. See
[`ssam_device_add()`](#c-ssam_device_add) for details.

**Return**

Returns zero on success, nonzero on failure.

#### <a id="c-ssam_device_register_clients"></a>`ssam_device_register_clients()`

```c
int ssam_device_register_clients(struct ssam_device *sdev)
```

Register all client devices defined under the given SSAM parent device.

**Parameters**

- `struct ssam_device *sdev`: The parent device under which clients should be registered.

**Description**

Register all clients that have via firmware nodes been defined as children
of the given (parent) device. The respective child firmware nodes will be
associated with the correspondingly created child devices.

The controller used by the parent device will be used to instantiate the new
devices. See [`ssam_device_add()`](#c-ssam_device_add) for details.

**Return**

Returns zero on success, nonzero on failure.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_CL_N"></a>`SSAM_DEFINE_SYNC_REQUEST_CL_N()`

```c
SSAM_DEFINE_SYNC_REQUEST_CL_N(name, spec...)
```

Define synchronous client-device SAM request function with neither argument nor return value.

**Parameters**

- `name`: Name of the generated function.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request having neither argument nor return value. Device
specifying parameters are not hard-coded, but instead are provided via the
client device, specifically its UID, supplied when calling this function.
The generated function takes care of setting up the request struct, buffer
allocation, as well as execution of the request itself, returning once the
request has been fully completed. The required transport buffer will be
allocated on the stack.

The generated function is defined as `static int name(struct ssam_device *sdev)`, returning the status of the request, which is zero on success and
negative on failure. The `sdev` parameter specifies both the target
device of the request and by association the controller via which the
request is sent.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_CL_W"></a>`SSAM_DEFINE_SYNC_REQUEST_CL_W()`

```c
SSAM_DEFINE_SYNC_REQUEST_CL_W(name, atype, spec...)
```

Define synchronous client-device SAM request function with argument.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking an argument of type **atype** and having no
return value. Device specifying parameters are not hard-coded, but instead
are provided via the client device, specifically its UID, supplied when
calling this function. The generated function takes care of setting up the
request struct, buffer allocation, as well as execution of the request
itself, returning once the request has been fully completed. The required
transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_device *sdev, const atype *arg)`, returning the status of the request, which is
zero on success and negative on failure. The `sdev` parameter specifies
both the target device of the request and by association the controller via
which the request is sent. The request's argument is specified via the
`arg` pointer.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_CL_R"></a>`SSAM_DEFINE_SYNC_REQUEST_CL_R()`

```c
SSAM_DEFINE_SYNC_REQUEST_CL_R(name, rtype, spec...)
```

Define synchronous client-device SAM request function with return value.

**Parameters**

- `name`: Name of the generated function.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking no argument but having a return value of
type **rtype**. Device specifying parameters are not hard-coded, but instead
are provided via the client device, specifically its UID, supplied when
calling this function. The generated function takes care of setting up the
request struct, buffer allocation, as well as execution of the request
itself, returning once the request has been fully completed. The required
transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_device *sdev, rtype *ret)`, returning the status of the request, which is zero on
success and negative on failure. The `sdev` parameter specifies both the
target device of the request and by association the controller via which
the request is sent. The request's return value is written to the memory
pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_CL_WR"></a>`SSAM_DEFINE_SYNC_REQUEST_CL_WR()`

```c
SSAM_DEFINE_SYNC_REQUEST_CL_WR(name, atype, rtype, spec...)
```

Define synchronous client-device SAM request function with argument and return value.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by **spec**,
with the request taking an argument of type **atype** and having a return value
of type **rtype**. Device specifying parameters are not hard-coded, but instead
are provided via the client device, specifically its UID, supplied when
calling this function. The generated function takes care of setting up the
request struct, buffer allocation, as well as execution of the request
itself, returning once the request has been fully completed. The required
transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_device *sdev, const atype *arg, rtype *ret)`, returning the status of the request,
which is zero on success and negative on failure. The `sdev` parameter
specifies both the target device of the request and by association the
controller via which the request is sent. The request's argument is
specified via the `arg` pointer. The request's return value is written to
the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-ssam_device_notifier_register"></a>`ssam_device_notifier_register()`

```c
int ssam_device_notifier_register(struct ssam_device *sdev, struct ssam_event_notifier *n)
```

Register an event notifier for the specified client device.

**Parameters**

- `struct ssam_device *sdev`: The device the notifier should be registered on.
- `struct ssam_event_notifier *n`: The event notifier to register.

**Description**

Register an event notifier. Increment the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the event is not
marked as an observer and is currently not enabled, it will be enabled
during this call. If the notifier is marked as an observer, no attempt will
be made at enabling any event and no reference count will be modified.

Notifiers marked as observers do not need to be associated with one specific
event, i.e. as long as no event matching is performed, only the event target
category needs to be set.

**Return**

Returns zero on success, `-ENOSPC` if there have already been
`INT_MAX` notifiers for the event ID/type associated with the notifier block
registered, `-ENOMEM` if the corresponding event entry could not be
allocated, `-ENODEV` if the device is marked as hot-removed. If this is the
first time that a notifier block is registered for the specific associated
event, returns the status of the event-enable EC-command.

#### <a id="c-ssam_device_notifier_unregister"></a>`ssam_device_notifier_unregister()`

```c
int ssam_device_notifier_unregister(struct ssam_device *sdev, struct ssam_event_notifier *n)
```

Unregister an event notifier for the specified client device.

**Parameters**

- `struct ssam_device *sdev`: The device the notifier has been registered on.
- `struct ssam_event_notifier *n`: The event notifier to unregister.

**Description**

Unregister an event notifier. Decrement the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the usage counter
reaches zero, the event will be disabled.

In case the device has been marked as hot-removed, the event will not be
disabled on the EC, as in those cases any attempt at doing so may time out.

**Return**

Returns zero on success, `-ENOENT` if the given notifier block has
not been registered on the controller. If the given notifier block was the
last one associated with its specific event, returns the status of the
event-disable EC-command.



#### <a id="c-ssam_device_alloc"></a>`ssam_device_alloc()`

```c
struct ssam_device * ssam_device_alloc(struct ssam_controller *ctrl, struct ssam_device_uid uid)
```

Allocate and initialize a SSAM client device.

**Parameters**

- `struct ssam_controller *ctrl`: The controller under which the device should be added.
- `struct ssam_device_uid uid`: The UID of the device to be added.

**Description**

Allocates and initializes a new client device. The parent of the device
will be set to the controller device and the name will be set based on the
UID. Note that the device still has to be added via [`ssam_device_add()`](#c-ssam_device_add).
Refer to that function for more details.

**Return**

Returns the newly allocated and initialized SSAM client device, or
`NULL` if it could not be allocated.

#### <a id="c-ssam_device_add"></a>`ssam_device_add()`

```c
int ssam_device_add(struct ssam_device *sdev)
```

Add a SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The SSAM client device to be added.

**Description**

Added client devices must be guaranteed to always have a valid and active
controller. Thus, this function will fail with `-ENODEV` if the controller
of the device has not been initialized yet, has been suspended, or has been
shut down.

The caller of this function should ensure that the corresponding call to
[`ssam_device_remove()`](#c-ssam_device_remove) is issued before the controller is shut down. If the
added device is a direct child of the controller device (default), it will
be automatically removed when the controller is shut down.

By default, the controller device will become the parent of the newly
created client device. The parent may be changed before ssam_device_add is
called, but care must be taken that a) the correct suspend/resume ordering
is guaranteed and b) the client device does not outlive the controller,
i.e. that the device is removed before the controller is being shut down.
In case these guarantees have to be manually enforced, please refer to the
[`ssam_client_link()`](#c-ssam_client_link) and [`ssam_client_bind()`](#c-ssam_client_bind) functions, which are intended to
set up device-links for this purpose.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssam_device_remove"></a>`ssam_device_remove()`

```c
void ssam_device_remove(struct ssam_device *sdev)
```

Remove a SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to remove.

**Description**

Removes and unregisters the provided SSAM client device.

#### <a id="c-ssam_device_id_match"></a>`ssam_device_id_match()`

```c
const struct ssam_device_id * ssam_device_id_match(const struct ssam_device_id *table, const struct ssam_device_uid uid)
```

Find the matching ID table entry for the given UID.

**Parameters**

- `const struct ssam_device_id *table`: The table to search in.
- `const struct ssam_device_uid uid`: The UID to matched against the individual table entries.

**Description**

Find the first match for the provided device UID in the provided ID table
and return it. Returns `NULL` if no match could be found.

#### <a id="c-ssam_device_get_match"></a>`ssam_device_get_match()`

```c
const struct ssam_device_id * ssam_device_get_match(const struct ssam_device *dev)
```

Find and return the ID matching the device in the ID table of the bound driver.

**Parameters**

- `const struct ssam_device *dev`: The device for which to get the matching ID table entry.

**Description**

Find the fist match for the UID of the device in the ID table of the
currently bound driver and return it. Returns `NULL` if the device does not
have a driver bound to it, the driver does not have match_table (i.e. it is
`NULL`), or there is no match in the driver's match_table.

This function essentially calls [`ssam_device_id_match()`](#c-ssam_device_id_match) with the ID table of
the bound device driver and the UID of the device.

**Return**

Returns the first match for the UID of the device in the device
driver's match table, or `NULL` if no such match could be found.

#### <a id="c-ssam_device_get_match_data"></a>`ssam_device_get_match_data()`

```c
const void * ssam_device_get_match_data(const struct ssam_device *dev)
```

Find the ID matching the device in the ID table of the bound driver and return its `driver_data` member.

**Parameters**

- `const struct ssam_device *dev`: The device for which to get the match data.

**Description**

Find the fist match for the UID of the device in the ID table of the
corresponding driver and return its driver_data. Returns `NULL` if the
device does not have a driver bound to it, the driver does not have
match_table (i.e. it is `NULL`), there is no match in the driver's
match_table, or the match does not have any driver_data.

This function essentially calls [`ssam_device_get_match()`](#c-ssam_device_get_match) and, if any match
could be found, returns its `struct ssam_device_id.driver_data` member.

**Return**

Returns the driver data associated with the first match for the UID
of the device in the device driver's match table, or `NULL` if no such match
could be found.

#### <a id="c-__ssam_device_driver_register"></a>`__ssam_device_driver_register()`

```c
int __ssam_device_driver_register(struct ssam_device_driver *sdrv, struct module *owner)
```

Register a SSAM client device driver.

**Parameters**

- `struct ssam_device_driver *sdrv`: The driver to register.
- `struct module *owner`: The module owning the provided driver.

**Description**

Please refer to the [`ssam_device_driver_register()`](#c-ssam_device_driver_register) macro for the normal way
to register a driver from inside its owning module.

#### <a id="c-ssam_device_driver_unregister"></a>`ssam_device_driver_unregister()`

```c
void ssam_device_driver_unregister(struct ssam_device_driver *sdrv)
```

Unregister a SSAM device driver.

**Parameters**

- `struct ssam_device_driver *sdrv`: The driver to unregister.

#### <a id="c-__ssam_register_clients"></a>`__ssam_register_clients()`

```c
int __ssam_register_clients(struct device *parent, struct ssam_controller *ctrl, struct fwnode_handle *node)
```

Register client devices defined under the given firmware node as children of the given device.

**Parameters**

- `struct device *parent`: The parent device under which clients should be registered.
- `struct ssam_controller *ctrl`: The controller with which client should be registered.
- `struct fwnode_handle *node`: The firmware node holding definitions of the devices to be added.

**Description**

Register all clients that have been defined as children of the given root
firmware node as children of the given parent device. The respective child
firmware nodes will be associated with the correspondingly created child
devices.

The given controller will be used to instantiate the new devices. See
[`ssam_device_add()`](#c-ssam_device_add) for details.

Note that, generally, the use of either [`ssam_device_register_clients()`](#c-ssam_device_register_clients) or
[`ssam_register_clients()`](#c-ssam_register_clients) should be preferred as they directly use the
firmware node and/or controller associated with the given device. This
function is only intended for use when different device specifications (e.g.
ACPI and firmware nodes) need to be combined (as is done in the platform hub
of the device registry).

**Return**

Returns zero on success, nonzero on failure.

#### <a id="c-ssam_remove_clients"></a>`ssam_remove_clients()`

```c
void ssam_remove_clients(struct device *dev)
```

Remove SSAM client devices registered as direct children under the given parent device.

**Parameters**

- `struct device *dev`: The (parent) device to remove all direct clients for.

**Description**

Remove all SSAM client devices registered as direct children under the given
device. Note that this only accounts for direct children of the device.
Refer to [`ssam_device_add()`](#c-ssam_device_add)/[`ssam_device_remove()`](#c-ssam_device_remove) for more details.

---

# Writing Client Drivers

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> For the API documentation, refer to:

<a id="rst-writing-client-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

For the API documentation, refer to:

- [Client Driver API Documentation](</kernel/hardware/driver-api/surface-aggregator/client-api.md>)

<a id="rst-overview"></a>

## Overview

Client drivers can be set up in two main ways, depending on how the corresponding device is made available to the system. We specifically differentiate between devices that are presented to the system via one of the conventional ways, e.g. as platform devices via ACPI, and devices that are non-discoverable and instead need to be explicitly provided by some other mechanism, as discussed further below.

<a id="rst-non-ssam-client-drivers"></a>

## Non-SSAM Client Drivers

All communication with the SAM EC is handled via the `struct ssam_controller <ssam_controller>` representing that EC to the kernel. Drivers targeting a non-SSAM device (and thus not being a `struct ssam_device_driver <ssam_device_driver>`) need to explicitly establish a connection/relation to that controller. This can be done via the `ssam_client_bind()` function. Said function returns a reference to the SSAM controller, but, more importantly, also establishes a device link between client device and controller (this can also be done separate via `ssam_client_link()`). It is important to do this, as it, first, guarantees that the returned controller is valid for use in the client driver for as long as this driver is bound to its device, i.e. that the driver gets unbound before the controller ever becomes invalid, and, second, as it ensures correct suspend/resume ordering. This setup should be done in the driver's probe function, and may be used to defer probing in case the SSAM subsystem is not ready yet, for example:



```c
static int client_driver_probe(struct platform_device *pdev)
{
        struct ssam_controller *ctrl;

        ctrl = ssam_client_bind(&pdev->dev);
        if (IS_ERR(ctrl))
                return PTR_ERR(ctrl) == -ENODEV ? -EPROBE_DEFER : PTR_ERR(ctrl);

        // ...

        return 0;
}
```

The controller may be separately obtained via `ssam_get_controller()` and its lifetime be guaranteed via `ssam_controller_get()` and `ssam_controller_put()`. Note that none of these functions, however, guarantee that the controller will not be shut down or suspended. These functions essentially only operate on the reference, i.e. only guarantee a bare minimum of accessibility without any guarantees at all on practical operability.

<a id="rst-adding-ssam-devices"></a>

## Adding SSAM Devices

If a device does not already exist/is not already provided via conventional means, it should be provided as `struct ssam_device <ssam_device>` via the SSAM client device hub. New devices can be added to this hub by entering their UID into the corresponding registry. SSAM devices can also be manually allocated via `ssam_device_alloc()`, subsequently to which they have to be added via `ssam_device_add()` and eventually removed via `ssam_device_remove()`. By default, the parent of the device is set to the controller device provided for allocation, however this may be changed before the device is added. Note that, when changing the parent device, care must be taken to ensure that the controller lifetime and suspend/resume ordering guarantees, in the default setup provided through the parent-child relation, are preserved. If necessary, by use of `ssam_client_link()` as is done for non-SSAM client drivers and described in more detail above.

A client device must always be removed by the party which added the respective device before the controller shuts down. Such removal can be guaranteed by linking the driver providing the SSAM device to the controller via `ssam_client_link()`, causing it to unbind before the controller driver unbinds. Client devices registered with the controller as parent are automatically removed when the controller shuts down, but this should not be relied upon, especially as this does not extend to client devices with a different parent.

<a id="rst-ssam-client-drivers"></a>

## SSAM Client Drivers

SSAM client device drivers are, in essence, no different than other device driver types. They are represented via `struct ssam_device_driver <ssam_device_driver>` and bind to a `struct ssam_device <ssam_device>` via its UID (`struct ssam_device.uid <ssam_device>`) member and the match table (`struct ssam_device_driver.match_table <ssam_device_driver>`), which should be set when declaring the driver struct instance. Refer to the `SSAM_DEVICE()` macro documentation for more details on how to define members of the driver's match table.

The UID for SSAM client devices consists of a `domain`, a `category`, a `target`, an `instance`, and a `function`. The `domain` is used differentiate between physical SAM devices (`SSAM_DOMAIN_SERIALHUB <ssam_device_domain>`), i.e. devices that can be accessed via the Surface Serial Hub, and virtual ones (`SSAM_DOMAIN_VIRTUAL <ssam_device_domain>`), such as client-device hubs, that have no real representation on the SAM EC and are solely used on the kernel/driver-side. For physical devices, `category` represents the target category, `target` the target ID, and `instance` the instance ID used to access the physical SAM device. In addition, `function` references a specific device functionality, but has no meaning to the SAM EC. The (default) name of a client device is generated based on its UID.

A driver instance can be registered via `ssam_device_driver_register()` and unregistered via `ssam_device_driver_unregister()`. For convenience, the `module_ssam_device_driver()` macro may be used to define module init- and exit-functions registering the driver.

The controller associated with a SSAM client device can be found in its `struct ssam_device.ctrl <ssam_device>` member. This reference is guaranteed to be valid for at least as long as the client driver is bound, but should also be valid for as long as the client device exists. Note, however, that access outside of the bound client driver must ensure that the controller device is not suspended while making any requests or (un-)registering event notifiers (and thus should generally be avoided). This is guaranteed when the controller is accessed from inside the bound client driver.

<a id="rst-making-synchronous-requests"></a>

## Making Synchronous Requests

Synchronous requests are (currently) the main form of host-initiated communication with the EC. There are a couple of ways to define and execute such requests, however, most of them boil down to something similar as shown in the example below. This example defines a write-read request, meaning that the caller provides an argument to the SAM EC and receives a response. The caller needs to know the (maximum) length of the response payload and provide a buffer for it.

Care must be taken to ensure that any command payload data passed to the SAM EC is provided in little-endian format and, similarly, any response payload data received from it is converted from little-endian to host endianness.



```c
int perform_request(struct ssam_controller *ctrl, u32 arg, u32 *ret)
{
        struct ssam_request rqst;
        struct ssam_response resp;
        int status;

        /* Convert request argument to little-endian. */
        __le32 arg_le = cpu_to_le32(arg);
        __le32 ret_le = cpu_to_le32(0);

        /*
         * Initialize request specification. Replace this with your values.
         * The rqst.payload field may be NULL if rqst.length is zero,
         * indicating that the request does not have any argument.
         *
         * Note: The request parameters used here are not valid, i.e.
         *       they do not correspond to an actual SAM/EC request.
         */
        rqst.target_category = SSAM_SSH_TC_SAM;
        rqst.target_id = SSAM_SSH_TID_SAM;
        rqst.command_id = 0x02;
        rqst.instance_id = 0x03;
        rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
        rqst.length = sizeof(arg_le);
        rqst.payload = (u8 *)&arg_le;

        /* Initialize request response. */
        resp.capacity = sizeof(ret_le);
        resp.length = 0;
        resp.pointer = (u8 *)&ret_le;

        /*
         * Perform actual request. The response pointer may be null in case
         * the request does not have any response. This must be consistent
         * with the SSAM_REQUEST_HAS_RESPONSE flag set in the specification
         * above.
         */
        status = ssam_request_do_sync(ctrl, &rqst, &resp);

        /*
         * Alternatively use
         *
         *   ssam_request_do_sync_onstack(ctrl, &rqst, &resp, sizeof(arg_le));
         *
         * to perform the request, allocating the message buffer directly
         * on the stack as opposed to allocation via kzalloc().
         */

        /*
         * Convert request response back to native format. Note that in the
         * error case, this value is not touched by the SSAM core, i.e.
         * 'ret_le' will be zero as specified in its initialization.
         */
        *ret = le32_to_cpu(ret_le);

        return status;
}
```

Note that `ssam_request_do_sync()` in its essence is a wrapper over lower-level request primitives, which may also be used to perform requests. Refer to its implementation and documentation for more details.

An arguably more user-friendly way of defining such functions is by using one of the generator macros, for example via:



```c
SSAM_DEFINE_SYNC_REQUEST_W(__ssam_tmp_perf_mode_set, __le32, {
        .target_category = SSAM_SSH_TC_TMP,
        .target_id       = SSAM_SSH_TID_SAM,
        .command_id      = 0x03,
        .instance_id     = 0x00,
});
```

This example defines a function



```c
static int __ssam_tmp_perf_mode_set(struct ssam_controller *ctrl, const __le32 *arg);
```

executing the specified request, with the controller passed in when calling said function. In this example, the argument is provided via the `arg` pointer. Note that the generated function allocates the message buffer on the stack. Thus, if the argument provided via the request is large, these kinds of macros should be avoided. Also note that, in contrast to the previous non-macro example, this function does not do any endianness conversion, which has to be handled by the caller. Apart from those differences the function generated by the macro is similar to the one provided in the non-macro example above.

The full list of such function-generating macros is

- `SSAM_DEFINE_SYNC_REQUEST_N()` for requests without return value and without argument.

- `SSAM_DEFINE_SYNC_REQUEST_R()` for requests with return value but no argument.

- `SSAM_DEFINE_SYNC_REQUEST_W()` for requests without return value but with argument.

Refer to their respective documentation for more details. For each one of these macros, a special variant is provided, which targets request types applicable to multiple instances of the same device type:

- `SSAM_DEFINE_SYNC_REQUEST_MD_N()`

- `SSAM_DEFINE_SYNC_REQUEST_MD_R()`

- `SSAM_DEFINE_SYNC_REQUEST_MD_W()`

The difference of those macros to the previously mentioned versions is, that the device target and instance IDs are not fixed for the generated function, but instead have to be provided by the caller of said function.

Additionally, variants for direct use with client devices, i.e. `struct ssam_device <ssam_device>`, are also provided. These can, for example, be used as follows:



```c
SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_sta, __le32, {
        .target_category = SSAM_SSH_TC_BAT,
        .command_id      = 0x01,
});
```

This invocation of the macro defines a function



```c
static int ssam_bat_get_sta(struct ssam_device *sdev, __le32 *ret);
```

executing the specified request, using the device IDs and controller given in the client device. The full list of such macros for client devices is:

- `SSAM_DEFINE_SYNC_REQUEST_CL_N()`

- `SSAM_DEFINE_SYNC_REQUEST_CL_R()`

- `SSAM_DEFINE_SYNC_REQUEST_CL_W()`

<a id="rst-handling-events"></a>

## Handling Events

To receive events from the SAM EC, an event notifier must be registered for the desired event via `ssam_notifier_register()`. The notifier must be unregistered via `ssam_notifier_unregister()` once it is not required any more. For `struct ssam_device <ssam_device>` type clients, the `ssam_device_notifier_register()` and `ssam_device_notifier_unregister()` wrappers should be preferred as they properly handle hot-removal of client devices.

Event notifiers are registered by providing (at minimum) a callback to call in case an event has been received, the registry specifying how the event should be enabled, an event ID specifying for which target category and, optionally and depending on the registry used, for which instance ID events should be enabled, and finally, flags describing how the EC will send these events. If the specific registry does not enable events by instance ID, the instance ID must be set to zero. Additionally, a priority for the respective notifier may be specified, which determines its order in relation to any other notifier registered for the same target category.

By default, event notifiers will receive all events for the specific target category, regardless of the instance ID specified when registering the notifier. The core may be instructed to only call a notifier if the target ID or instance ID (or both) of the event match the ones implied by the notifier IDs (in case of target ID, the target ID of the registry), by providing an event mask (see `enum ssam_event_mask <ssam_event_mask>`).

In general, the target ID of the registry is also the target ID of the enabled event (with the notable exception being keyboard input events on the Surface Laptop 1 and 2, which are enabled via a registry with target ID 1, but provide events with target ID 2).

A full example for registering an event notifier and handling received events is provided below:



```c
u32 notifier_callback(struct ssam_event_notifier *nf,
                      const struct ssam_event *event)
{
        int status = ...

        /* Handle the event here ... */

        /* Convert return value and indicate that we handled the event. */
        return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
}

int setup_notifier(struct ssam_device *sdev,
                   struct ssam_event_notifier *nf)
{
        /* Set priority wrt. other handlers of same target category. */
        nf->base.priority = 1;

        /* Set event/notifier callback. */
        nf->base.fn = notifier_callback;

        /* Specify event registry, i.e. how events get enabled/disabled. */
        nf->event.reg = SSAM_EVENT_REGISTRY_KIP;

        /* Specify which event to enable/disable */
        nf->event.id.target_category = sdev->uid.category;
        nf->event.id.instance = sdev->uid.instance;

        /*
         * Specify for which events the notifier callback gets executed.
         * This essentially tells the core if it can skip notifiers that
         * don't have target or instance IDs matching those of the event.
         */
        nf->event.mask = SSAM_EVENT_MASK_STRICT;

        /* Specify event flags. */
        nf->event.flags = SSAM_EVENT_SEQUENCED;

        return ssam_notifier_register(sdev->ctrl, nf);
}
```

Multiple event notifiers can be registered for the same event. The event handler core takes care of enabling and disabling events when notifiers are registered and unregistered, by keeping track of how many notifiers for a specific event (combination of registry, event target category, and event instance ID) are currently registered. This means that a specific event will be enabled when the first notifier for it is being registered and disabled when the last notifier for it is being unregistered. Note that the event flags are therefore only used on the first registered notifier, however, one should take care that notifiers for a specific event are always registered with the same flag and it is considered a bug to do otherwise.

---

# Internal API Documentation

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> Packet Transport Layer

<a id="rst-internal-api-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<a id="rst-contents"></a>



<a id="rst-packet-transport-layer"></a>

## Packet Transport Layer


#### <a id="c-struct-sshp_buf"></a>`struct sshp_buf`

Parser buffer for SSH messages.

**Definition**

```c
struct sshp_buf {
    u8 *ptr;
    size_t len;
    size_t cap;
};
```

**Members**

- `ptr`: Pointer to the beginning of the buffer.
- `len`: Number of bytes used in the buffer.
- `cap`: Maximum capacity of the buffer.

#### <a id="c-sshp_buf_init"></a>`sshp_buf_init()`

```c
void sshp_buf_init(struct sshp_buf *buf, u8 *ptr, size_t cap)
```

Initialize a SSH parser buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to initialize.
- `u8 *ptr`: The memory backing the buffer.
- `size_t cap`: The length of the memory backing the buffer, i.e. its capacity.

**Description**

Initializes the buffer with the given memory as backing and set its used
length to zero.

#### <a id="c-sshp_buf_alloc"></a>`sshp_buf_alloc()`

```c
int sshp_buf_alloc(struct sshp_buf *buf, size_t cap, gfp_t flags)
```

Allocate and initialize a SSH parser buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to initialize/allocate to.
- `size_t cap`: The desired capacity of the buffer.
- `gfp_t flags`: The flags used for allocating the memory.

**Description**

Allocates **cap** bytes and initializes the provided buffer struct with the
allocated memory.

**Return**

Returns zero on success and `-ENOMEM` if allocation failed.

#### <a id="c-sshp_buf_free"></a>`sshp_buf_free()`

```c
void sshp_buf_free(struct sshp_buf *buf)
```

Free a SSH parser buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to free.

**Description**

Frees a SSH parser buffer by freeing the memory backing it and then
resetting its pointer to `NULL` and length and capacity to zero. Intended to
free a buffer previously allocated with [`sshp_buf_alloc()`](#c-sshp_buf_alloc).

#### <a id="c-sshp_buf_drop"></a>`sshp_buf_drop()`

```c
void sshp_buf_drop(struct sshp_buf *buf, size_t n)
```

Drop data from the beginning of the buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to drop data from.
- `size_t n`: The number of bytes to drop.

**Description**

Drops the first **n** bytes from the buffer. Re-aligns any remaining data to
the beginning of the buffer.

#### <a id="c-sshp_buf_read_from_fifo"></a>`sshp_buf_read_from_fifo()`

```c
size_t sshp_buf_read_from_fifo(struct sshp_buf *buf, struct kfifo *fifo)
```

Transfer data from a fifo to the buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to write the data into.
- `struct kfifo *fifo`: The fifo to read the data from.

**Description**

Transfers the data contained in the fifo to the buffer, removing it from
the fifo. This function will try to transfer as much data as possible,
limited either by the remaining space in the buffer or by the number of
bytes available in the fifo.

**Return**

Returns the number of bytes transferred.

#### <a id="c-sshp_buf_span_from"></a>`sshp_buf_span_from()`

```c
void sshp_buf_span_from(struct sshp_buf *buf, size_t offset, struct ssam_span *span)
```

Initialize a span from the given buffer and offset.

**Parameters**

- `struct sshp_buf *buf`: The buffer to create the span from.
- `size_t offset`: The offset in the buffer at which the span should start.
- `struct ssam_span *span`: The span to initialize (output).

**Description**

Initializes the provided span to point to the memory at the given offset in
the buffer, with the length of the span being capped by the number of bytes
used in the buffer after the offset (i.e. bytes remaining after the
offset).

Warning: This function does not validate that **offset** is less than or equal
to the number of bytes used in the buffer or the buffer capacity. This must
be guaranteed by the caller.



#### <a id="c-sshp_validate_crc"></a>`sshp_validate_crc()`

```c
bool sshp_validate_crc(const struct ssam_span *src, const u8 *crc)
```

Validate a CRC in raw message data.

**Parameters**

- `const struct ssam_span *src`: The span of data over which the CRC should be computed.
- `const u8 *crc`: The pointer to the expected u16 CRC value.

**Description**

Computes the CRC of the provided data span (**src**), compares it to the CRC
stored at the given address (**crc**), and returns the result of this
comparison, i.e. `true` if equal. This function is intended to run on raw
input/message data.

**Return**

Returns `true` if the computed CRC matches the stored CRC, `false`
otherwise.

#### <a id="c-sshp_starts_with_syn"></a>`sshp_starts_with_syn()`

```c
bool sshp_starts_with_syn(const struct ssam_span *src)
```

Check if the given data starts with SSH SYN bytes.

**Parameters**

- `const struct ssam_span *src`: The data span to check the start of.

#### <a id="c-sshp_find_syn"></a>`sshp_find_syn()`

```c
bool sshp_find_syn(const struct ssam_span *src, struct ssam_span *rem)
```

Find SSH SYN bytes in the given data span.

**Parameters**

- `const struct ssam_span *src`: The data span to search in.
- `struct ssam_span *rem`: The span (output) indicating the remaining data, starting with SSH
  SYN bytes, if found.

**Description**

Search for SSH SYN bytes in the given source span. If found, set the **rem**
span to the remaining data, starting with the first SYN bytes and capped by
the source span length, and return `true`. This function does not copy any
data, but rather only sets pointers to the respective start addresses and
length values.

If no SSH SYN bytes could be found, set the **rem** span to the zero-length
span at the end of the source span and return `false`.

If partial SSH SYN bytes could be found at the end of the source span, set
the **rem** span to cover these partial SYN bytes, capped by the end of the
source span, and return `false`. This function should then be re-run once
more data is available.

**Return**

Returns `true` if a complete SSH SYN sequence could be found,
`false` otherwise.

#### <a id="c-sshp_parse_frame"></a>`sshp_parse_frame()`

```c
int sshp_parse_frame(const struct device *dev, const struct ssam_span *source, struct ssh_frame **frame, struct ssam_span *payload, size_t maxlen)
```

Parse SSH frame.

**Parameters**

- `const struct device *dev`: The device used for logging.
- `const struct ssam_span *source`: The source to parse from.
- `struct ssh_frame **frame`: The parsed frame (output).
- `struct ssam_span *payload`: The parsed payload (output).
- `size_t maxlen`: The maximum supported message length.

**Description**

Parses and validates a SSH frame, including its payload, from the given
source. Sets the provided **frame** pointer to the start of the frame and
writes the limits of the frame payload to the provided **payload** span
pointer.

This function does not copy any data, but rather only validates the message
data and sets pointers (and length values) to indicate the respective parts.

If no complete SSH frame could be found, the frame pointer will be set to
the `NULL` pointer and the payload span will be set to the null span (start
pointer `NULL`, size zero).

**Return**

Returns zero on success or if the frame is incomplete, `-ENOMSG` if
the start of the message is invalid, `-EBADMSG` if any (frame-header or
payload) CRC is invalid, or `-EMSGSIZE` if the SSH message is bigger than
the maximum message length specified in the **maxlen** parameter.

#### <a id="c-sshp_parse_command"></a>`sshp_parse_command()`

```c
int sshp_parse_command(const struct device *dev, const struct ssam_span *source, struct ssh_command **command, struct ssam_span *command_data)
```

Parse SSH command frame payload.

**Parameters**

- `const struct device *dev`: The device used for logging.
- `const struct ssam_span *source`: The source to parse from.
- `struct ssh_command **command`: The parsed command (output).
- `struct ssam_span *command_data`: The parsed command data/payload (output).

**Description**

Parses and validates a SSH command frame payload. Sets the **command** pointer
to the command header and the **command_data** span to the command data (i.e.
payload of the command). This will result in a zero-length span if the
command does not have any associated data/payload. This function does not
check the frame-payload-type field, which should be checked by the caller
before calling this function.

The **source** parameter should be the complete frame payload, e.g. returned
by the [`sshp_parse_frame()`](#c-sshp_parse_frame) command.

This function does not copy any data, but rather only validates the frame
payload data and sets pointers (and length values) to indicate the
respective parts.

**Return**

Returns zero on success or `-ENOMSG` if **source** does not represent a
valid command-type frame payload, i.e. is too short.



#### <a id="c-struct-msgbuf"></a>`struct msgbuf`

Buffer struct to construct SSH messages.

**Definition**

```c
struct msgbuf {
    u8 *begin;
    u8 *end;
    u8 *ptr;
};
```

**Members**

- `begin`: Pointer to the beginning of the allocated buffer space.
- `end`: Pointer to the end (one past last element) of the allocated buffer
  space.
- `ptr`: Pointer to the first free element in the buffer.

#### <a id="c-msgb_init"></a>`msgb_init()`

```c
void msgb_init(struct msgbuf *msgb, u8 *ptr, size_t cap)
```

Initialize the given message buffer struct.

**Parameters**

- `struct msgbuf *msgb`: The buffer struct to initialize
- `u8 *ptr`: Pointer to the underlying memory by which the buffer will be backed.
- `size_t cap`: Size of the underlying memory.

**Description**

Initialize the given message buffer struct using the provided memory as
backing.

#### <a id="c-msgb_bytes_used"></a>`msgb_bytes_used()`

```c
size_t msgb_bytes_used(const struct msgbuf *msgb)
```

Return the current number of bytes used in the buffer.

**Parameters**

- `const struct msgbuf *msgb`: The message buffer.

#### <a id="c-msgb_push_u16"></a>`msgb_push_u16()`

```c
void msgb_push_u16(struct msgbuf *msgb, u16 value)
```

Push a u16 value to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.
- `u16 value`: The value to push to the buffer.

#### <a id="c-msgb_push_syn"></a>`msgb_push_syn()`

```c
void msgb_push_syn(struct msgbuf *msgb)
```

Push SSH SYN bytes to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.

#### <a id="c-msgb_push_buf"></a>`msgb_push_buf()`

```c
void msgb_push_buf(struct msgbuf *msgb, const u8 *buf, size_t len)
```

Push raw data to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.
- `const u8 *buf`: The data to push to the buffer.
- `size_t len`: The length of the data to push to the buffer.

#### <a id="c-msgb_push_crc"></a>`msgb_push_crc()`

```c
void msgb_push_crc(struct msgbuf *msgb, const u8 *buf, size_t len)
```

Compute CRC and push it to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.
- `const u8 *buf`: The data for which the CRC should be computed.
- `size_t len`: The length of the data for which the CRC should be computed.

#### <a id="c-msgb_push_frame"></a>`msgb_push_frame()`

```c
void msgb_push_frame(struct msgbuf *msgb, u8 ty, u16 len, u8 seq)
```

Push a SSH message frame header to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer
- `u8 ty`: The type of the frame.
- `u16 len`: The length of the payload of the frame.
- `u8 seq`: The sequence ID of the frame/packet.

#### <a id="c-msgb_push_ack"></a>`msgb_push_ack()`

```c
void msgb_push_ack(struct msgbuf *msgb, u8 seq)
```

Push a SSH ACK frame to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer
- `u8 seq`: The sequence ID of the frame/packet to be ACKed.

#### <a id="c-msgb_push_nak"></a>`msgb_push_nak()`

```c
void msgb_push_nak(struct msgbuf *msgb)
```

Push a SSH NAK frame to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer

#### <a id="c-msgb_push_cmd"></a>`msgb_push_cmd()`

```c
void msgb_push_cmd(struct msgbuf *msgb, u8 seq, u16 rqid, const struct ssam_request *rqst)
```

Push a SSH command frame with payload to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.
- `u8 seq`: The sequence ID (SEQ) of the frame/packet.
- `u16 rqid`: The request ID (RQID) of the request contained in the frame.
- `const struct ssam_request *rqst`: The request to wrap in the frame.



#### <a id="c-enum-ssh_ptl_state_flags"></a>`enum ssh_ptl_state_flags`

State-flags for [`struct ssh_ptl`](#c-struct-ssh_ptl).

**Constants**

- `SSH_PTL_SF_SHUTDOWN_BIT`: Indicates that the packet transport layer has been shut down or is
  being shut down and should not accept any new packets/data.

#### <a id="c-struct-ssh_ptl_ops"></a>`struct ssh_ptl_ops`

Callback operations for packet transport layer.

**Definition**

```c
struct ssh_ptl_ops {
    void (*data_received)(struct ssh_ptl *p, const struct ssam_span *data);
};
```

**Members**

- `data_received`: Function called when a data-packet has been received. Both,
  the packet layer on which the packet has been received and
  the packet's payload data are provided to this function.

#### <a id="c-struct-ssh_ptl"></a>`struct ssh_ptl`

SSH packet transport layer.

**Definition**

```c
struct ssh_ptl {
    struct serdev_device *serdev;
    unsigned long state;
    struct {
        spinlock_t lock;
        struct list_head head;
    } queue;
    struct {
        spinlock_t lock;
        struct list_head head;
        atomic_t count;
    } pending;
    struct {
        atomic_t running;
        struct task_struct *thread;
        struct completion thread_cplt_tx;
        struct completion thread_cplt_pkt;
        struct wait_queue_head packet_wq;
    } tx;
    struct {
        struct task_struct *thread;
        struct wait_queue_head wq;
        struct kfifo fifo;
        struct sshp_buf buf;
        struct {
            u16 seqs[8];
            u16 offset;
        } blocked;
    } rx;
    struct {
        spinlock_t lock;
        ktime_t timeout;
        ktime_t expires;
        struct delayed_work reaper;
    } rtx_timeout;
    struct ssh_ptl_ops ops;
};
```

**Members**

- `serdev`: Serial device providing the underlying data transport.
- `state`: State(-flags) of the transport layer.
- `queue`: Packet submission queue.
- `queue.lock`: Lock for modifying the packet submission queue.
- `queue.head`: List-head of the packet submission queue.
- `pending`: Set/list of pending packets.
- `pending.lock`: Lock for modifying the pending set.
- `pending.head`: List-head of the pending set/list.
- `pending.count`: Number of currently pending packets.
- `tx`: Transmitter subsystem.
- `tx.running`: Flag indicating (desired) transmitter thread state.
- `tx.thread`: Transmitter thread.
- `tx.thread_cplt_tx`: Completion for transmitter thread waiting on transfer.
- `tx.thread_cplt_pkt`: Completion for transmitter thread waiting on packets.
- `tx.packet_wq`: Waitqueue-head for packet transmit completion.
- `rx`: Receiver subsystem.
- `rx.thread`: Receiver thread.
- `rx.wq`: Waitqueue-head for receiver thread.
- `rx.fifo`: Buffer for receiving data/pushing data to receiver thread.
- `rx.buf`: Buffer for evaluating data on receiver thread.
- `rx.blocked`: List of recent/blocked sequence IDs to detect retransmission.
- `rx.blocked.seqs`: Array of blocked sequence IDs.
- `rx.blocked.offset`: Offset indicating where a new ID should be inserted.
- `rtx_timeout`: Retransmission timeout subsystem.
- `rtx_timeout.lock`: Lock for modifying the retransmission timeout reaper.
- `rtx_timeout.timeout`: Timeout interval for retransmission.
- `rtx_timeout.expires`: Time specifying when the reaper work is next scheduled.
- `rtx_timeout.reaper`: Work performing timeout checks and subsequent actions.
- `ops`: Packet layer operations.

#### <a id="c-ssh_ptl_get_device"></a>`ssh_ptl_get_device()`

```c
struct device * ssh_ptl_get_device(struct ssh_ptl *ptl)
```

Get device associated with packet transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns the device on which the given packet transport layer builds
upon.

#### <a id="c-ssh_ptl_tx_wakeup_transfer"></a>`ssh_ptl_tx_wakeup_transfer()`

```c
void ssh_ptl_tx_wakeup_transfer(struct ssh_ptl *ptl)
```

Wake up packet transmitter thread for transfer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Description**

Wakes up the packet transmitter thread, notifying it that the underlying
transport has more space for data to be transmitted. If the packet
transport layer has been shut down, calls to this function will be ignored.



#### <a id="c-ssh_ptl_should_drop_ack_packet"></a>`ssh_ptl_should_drop_ack_packet()`

```c
bool ssh_ptl_should_drop_ack_packet(void)
```

Error injection hook to drop ACK packets.

**Parameters**

- `void`: no arguments

**Description**

Useful to test detection and handling of automated re-transmits by the EC.
Specifically of packets that the EC considers not-ACKed but the driver
already considers ACKed (due to dropped ACK). In this case, the EC
re-transmits the packet-to-be-ACKed and the driver should detect it as
duplicate/already handled. Note that the driver should still send an ACK
for the re-transmitted packet.

#### <a id="c-ssh_ptl_should_drop_nak_packet"></a>`ssh_ptl_should_drop_nak_packet()`

```c
bool ssh_ptl_should_drop_nak_packet(void)
```

Error injection hook to drop NAK packets.

**Parameters**

- `void`: no arguments

**Description**

Useful to test/force automated (timeout-based) re-transmit by the EC.
Specifically, packets that have not reached the driver completely/with valid
checksums. Only useful in combination with receival of (injected) bad data.

#### <a id="c-ssh_ptl_should_drop_dsq_packet"></a>`ssh_ptl_should_drop_dsq_packet()`

```c
bool ssh_ptl_should_drop_dsq_packet(void)
```

Error injection hook to drop sequenced data packet.

**Parameters**

- `void`: no arguments

**Description**

Useful to test re-transmit timeout of the driver. If the data packet has not
been ACKed after a certain time, the driver should re-transmit the packet up
to limited number of times defined in SSH_PTL_MAX_PACKET_TRIES.

#### <a id="c-ssh_ptl_should_fail_write"></a>`ssh_ptl_should_fail_write()`

```c
int ssh_ptl_should_fail_write(void)
```

Error injection hook to make `serdev_device_write()` fail.

**Parameters**

- `void`: no arguments

**Description**

Hook to simulate errors in serdev_device_write when transmitting packets.

#### <a id="c-ssh_ptl_should_corrupt_tx_data"></a>`ssh_ptl_should_corrupt_tx_data()`

```c
bool ssh_ptl_should_corrupt_tx_data(void)
```

Error injection hook to simulate invalid data being sent to the EC.

**Parameters**

- `void`: no arguments

**Description**

Hook to simulate corrupt/invalid data being sent from host (driver) to EC.
Causes the packet data to be actively corrupted by overwriting it with
pre-defined values, such that it becomes invalid, causing the EC to respond
with a NAK packet. Useful to test handling of NAK packets received by the
driver.

#### <a id="c-ssh_ptl_should_corrupt_rx_syn"></a>`ssh_ptl_should_corrupt_rx_syn()`

```c
bool ssh_ptl_should_corrupt_rx_syn(void)
```

Error injection hook to simulate invalid data being sent by the EC.

**Parameters**

- `void`: no arguments

**Description**

Hook to simulate invalid SYN bytes, i.e. an invalid start of messages and
test handling thereof in the driver.

#### <a id="c-ssh_ptl_should_corrupt_rx_data"></a>`ssh_ptl_should_corrupt_rx_data()`

```c
bool ssh_ptl_should_corrupt_rx_data(void)
```

Error injection hook to simulate invalid data being sent by the EC.

**Parameters**

- `void`: no arguments

**Description**

Hook to simulate invalid data/checksum of the message frame and test handling
thereof in the driver.

#### <a id="c-ssh_packet_init"></a>`ssh_packet_init()`

```c
void ssh_packet_init(struct ssh_packet *packet, unsigned long type, u8 priority, const struct ssh_packet_ops *ops)
```

Initialize SSH packet.

**Parameters**

- `struct ssh_packet *packet`: The packet to initialize.
- `unsigned long type`: Type-flags of the packet.
- `u8 priority`: Priority of the packet. See [`SSH_PACKET_PRIORITY()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-SSH_PACKET_PRIORITY) for details.
- `const struct ssh_packet_ops *ops`: Packet operations.

**Description**

Initializes the given SSH packet. Sets the transmission buffer pointer to
`NULL` and the transmission buffer length to zero. For data-type packets,
this buffer has to be set separately via [`ssh_packet_set_data()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssh_packet_set_data) before
submission, and must contain a valid SSH message, i.e. frame with optional
payload of any type.

#### <a id="c-ssh_ctrl_packet_cache_init"></a>`ssh_ctrl_packet_cache_init()`

```c
int ssh_ctrl_packet_cache_init(void)
```

Initialize the control packet cache.

**Parameters**

- `void`: no arguments

#### <a id="c-ssh_ctrl_packet_cache_destroy"></a>`ssh_ctrl_packet_cache_destroy()`

```c
void ssh_ctrl_packet_cache_destroy(void)
```

Deinitialize the control packet cache.

**Parameters**

- `void`: no arguments

#### <a id="c-ssh_ctrl_packet_alloc"></a>`ssh_ctrl_packet_alloc()`

```c
int ssh_ctrl_packet_alloc(struct ssh_packet **packet, struct ssam_span *buffer, gfp_t flags)
```

Allocate packet from control packet cache.

**Parameters**

- `struct ssh_packet **packet`: Where the pointer to the newly allocated packet should be stored.
- `struct ssam_span *buffer`: The buffer corresponding to this packet.
- `gfp_t flags`: Flags used for allocation.

**Description**

Allocates a packet and corresponding transport buffer from the control
packet cache. Sets the packet's buffer reference to the allocated buffer.
The packet must be freed via [`ssh_ctrl_packet_free()`](#c-ssh_ctrl_packet_free), which will also free
the corresponding buffer. The corresponding buffer must not be freed
separately. Intended to be used with `ssh_ptl_ctrl_packet_ops` as packet
operations.

**Return**

Returns zero on success, `-ENOMEM` if the allocation failed.

#### <a id="c-ssh_ctrl_packet_free"></a>`ssh_ctrl_packet_free()`

```c
void ssh_ctrl_packet_free(struct ssh_packet *p)
```

Free packet allocated from control packet cache.

**Parameters**

- `struct ssh_packet *p`: The packet to free.

#### <a id="c-ssh_ptl_tx_wakeup_packet"></a>`ssh_ptl_tx_wakeup_packet()`

```c
void ssh_ptl_tx_wakeup_packet(struct ssh_ptl *ptl)
```

Wake up packet transmitter thread for new packet.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Description**

Wakes up the packet transmitter thread, notifying it that a new packet has
arrived and is ready for transfer. If the packet transport layer has been
shut down, calls to this function will be ignored.

#### <a id="c-ssh_ptl_tx_start"></a>`ssh_ptl_tx_start()`

```c
int ssh_ptl_tx_start(struct ssh_ptl *ptl)
```

Start packet transmitter thread.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_ptl_tx_stop"></a>`ssh_ptl_tx_stop()`

```c
int ssh_ptl_tx_stop(struct ssh_ptl *ptl)
```

Stop packet transmitter thread.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_ptl_submit"></a>`ssh_ptl_submit()`

```c
int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *p)
```

Submit a packet to the transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer to submit the packet to.
- `struct ssh_packet *p`: The packet to submit.

**Description**

Submits a new packet to the transport layer, queuing it to be sent. This
function should not be used for re-submission.

**Return**

Returns zero on success, `-EINVAL` if a packet field is invalid or
the packet has been canceled prior to submission, `-EALREADY` if the packet
has already been submitted, or `-ESHUTDOWN` if the packet transport layer
has been shut down.

#### <a id="c-ssh_ptl_cancel"></a>`ssh_ptl_cancel()`

```c
void ssh_ptl_cancel(struct ssh_packet *p)
```

Cancel a packet.

**Parameters**

- `struct ssh_packet *p`: The packet to cancel.

**Description**

Cancels a packet. There are no guarantees on when completion and release
callbacks will be called. This may occur during execution of this function
or may occur at any point later.

Note that it is not guaranteed that the packet will actually be canceled if
the packet is concurrently completed by another process. The only guarantee
of this function is that the packet will be completed (with success,
failure, or cancellation) and released from the transport layer in a
reasonable time-frame.

May be called before the packet has been submitted, in which case any later
packet submission fails.

#### <a id="c-ssh_ptl_rx_start"></a>`ssh_ptl_rx_start()`

```c
int ssh_ptl_rx_start(struct ssh_ptl *ptl)
```

Start packet transport layer receiver thread.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_ptl_rx_stop"></a>`ssh_ptl_rx_stop()`

```c
int ssh_ptl_rx_stop(struct ssh_ptl *ptl)
```

Stop packet transport layer receiver thread.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_ptl_rx_rcvbuf"></a>`ssh_ptl_rx_rcvbuf()`

```c
ssize_t ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n)
```

Push data from lower-layer transport to the packet layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.
- `const u8 *buf`: Pointer to the data to push to the layer.
- `size_t n`: Size of the data to push to the layer, in bytes.

**Description**

Pushes data from a lower-layer transport to the receiver fifo buffer of the
packet layer and notifies the receiver thread. Calls to this function are
ignored once the packet layer has been shut down.

**Return**

Returns the number of bytes transferred (positive or zero) on
success. Returns `-ESHUTDOWN` if the packet layer has been shut down.

#### <a id="c-ssh_ptl_shutdown"></a>`ssh_ptl_shutdown()`

```c
void ssh_ptl_shutdown(struct ssh_ptl *ptl)
```

Shut down the packet transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Description**

Shuts down the packet transport layer, removing and canceling all queued
and pending packets. Packets canceled by this operation will be completed
with `-ESHUTDOWN` as status. Receiver and transmitter threads will be
stopped.

As a result of this function, the transport layer will be marked as shut
down. Submission of packets after the transport layer has been shut down
will fail with `-ESHUTDOWN`.

#### <a id="c-ssh_ptl_init"></a>`ssh_ptl_init()`

```c
int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev, struct ssh_ptl_ops *ops)
```

Initialize packet transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer to initialize.
- `struct serdev_device *serdev`: The underlying serial device, i.e. the lower-level transport.
- `struct ssh_ptl_ops *ops`: Packet layer operations.

**Description**

Initializes the given packet transport layer. Transmitter and receiver
threads must be started separately via [`ssh_ptl_tx_start()`](#c-ssh_ptl_tx_start) and
[`ssh_ptl_rx_start()`](#c-ssh_ptl_rx_start), after the packet-layer has been initialized and the
lower-level transport layer has been set up.

**Return**

Returns zero on success and a nonzero error code on failure.

#### <a id="c-ssh_ptl_destroy"></a>`ssh_ptl_destroy()`

```c
void ssh_ptl_destroy(struct ssh_ptl *ptl)
```

Deinitialize packet transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer to deinitialize.

**Description**

Deinitializes the given packet transport layer and frees resources
associated with it. If receiver and/or transmitter threads have been
started, the layer must first be shut down via [`ssh_ptl_shutdown()`](#c-ssh_ptl_shutdown) before
this function can be called.


<a id="rst-request-transport-layer"></a>

## Request Transport Layer


#### <a id="c-enum-ssh_rtl_state_flags"></a>`enum ssh_rtl_state_flags`

State-flags for [`struct ssh_rtl`](#c-struct-ssh_rtl).

**Constants**

- `SSH_RTL_SF_SHUTDOWN_BIT`: Indicates that the request transport layer has been shut down or is
  being shut down and should not accept any new requests.

#### <a id="c-struct-ssh_rtl_ops"></a>`struct ssh_rtl_ops`

Callback operations for request transport layer.

**Definition**

```c
struct ssh_rtl_ops {
    void (*handle_event)(struct ssh_rtl *rtl, const struct ssh_command *cmd, const struct ssam_span *data);
};
```

**Members**

- `handle_event`: Function called when a SSH event has been received. The
  specified function takes the request layer, received command
  struct, and corresponding payload as arguments. If the event
  has no payload, the payload span is empty (not `NULL`).

#### <a id="c-struct-ssh_rtl"></a>`struct ssh_rtl`

SSH request transport layer.

**Definition**

```c
struct ssh_rtl {
    struct ssh_ptl ptl;
    unsigned long state;
    struct {
        spinlock_t lock;
        struct list_head head;
    } queue;
    struct {
        spinlock_t lock;
        struct list_head head;
        atomic_t count;
    } pending;
    struct {
        struct work_struct work;
    } tx;
    struct {
        spinlock_t lock;
        ktime_t timeout;
        ktime_t expires;
        struct delayed_work reaper;
    } rtx_timeout;
    struct ssh_rtl_ops ops;
};
```

**Members**

- `ptl`: Underlying packet transport layer.
- `state`: State(-flags) of the transport layer.
- `queue`: Request submission queue.
- `queue.lock`: Lock for modifying the request submission queue.
- `queue.head`: List-head of the request submission queue.
- `pending`: Set/list of pending requests.
- `pending.lock`: Lock for modifying the request set.
- `pending.head`: List-head of the pending set/list.
- `pending.count`: Number of currently pending requests.
- `tx`: Transmitter subsystem.
- `tx.work`: Transmitter work item.
- `rtx_timeout`: Retransmission timeout subsystem.
- `rtx_timeout.lock`: Lock for modifying the retransmission timeout reaper.
- `rtx_timeout.timeout`: Timeout interval for retransmission.
- `rtx_timeout.expires`: Time specifying when the reaper work is next scheduled.
- `rtx_timeout.reaper`: Work performing timeout checks and subsequent actions.
- `ops`: Request layer operations.

#### <a id="c-ssh_rtl_get_device"></a>`ssh_rtl_get_device()`

```c
struct device * ssh_rtl_get_device(struct ssh_rtl *rtl)
```

Get device associated with request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer.

**Return**

Returns the device on which the given request transport layer
builds upon.

#### <a id="c-ssh_request_rtl"></a>`ssh_request_rtl()`

```c
struct ssh_rtl * ssh_request_rtl(struct ssh_request *rqst)
```

Get request transport layer associated with request.

**Parameters**

- `struct ssh_request *rqst`: The request to get the request transport layer reference for.

**Return**

Returns the [`struct ssh_rtl`](#c-struct-ssh_rtl) associated with the given SSH request.



#### <a id="c-ssh_rtl_should_drop_response"></a>`ssh_rtl_should_drop_response()`

```c
bool ssh_rtl_should_drop_response(void)
```

Error injection hook to drop request responses.

**Parameters**

- `void`: no arguments

**Description**

Useful to cause request transmission timeouts in the driver by dropping the
response to a request.

#### <a id="c-ssh_rtl_submit"></a>`ssh_rtl_submit()`

```c
int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst)
```

Submit a request to the transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer.
- `struct ssh_request *rqst`: The request to submit.

**Description**

Submits a request to the transport layer. A single request may not be
submitted multiple times without reinitializing it.

**Return**

Returns zero on success, `-EINVAL` if the request type is invalid or
the request has been canceled prior to submission, `-EALREADY` if the
request has already been submitted, or `-ESHUTDOWN` in case the request
transport layer has been shut down.

#### <a id="c-ssh_rtl_cancel"></a>`ssh_rtl_cancel()`

```c
bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending)
```

Cancel request.

**Parameters**

- `struct ssh_request *rqst`: The request to cancel.
- `bool pending`: Whether to also cancel pending requests.

**Description**

Cancels the given request. If **pending** is `false`, this will not cancel
pending requests, i.e. requests that have already been submitted to the
packet layer but not been completed yet. If **pending** is `true`, this will
cancel the given request regardless of the state it is in.

If the request has been canceled by calling this function, both completion
and release callbacks of the request will be executed in a reasonable
time-frame. This may happen during execution of this function, however,
there is no guarantee for this. For example, a request currently
transmitting will be canceled/completed only after transmission has
completed, and the respective callbacks will be executed on the transmitter
thread, which may happen during, but also some time after execution of the
cancel function.

**Return**

Returns `true` if the given request has been canceled or completed,
either by this function or prior to calling this function, `false`
otherwise. If **pending** is `true`, this function will always return `true`.

#### <a id="c-ssh_request_init"></a>`ssh_request_init()`

```c
int ssh_request_init(struct ssh_request *rqst, enum ssam_request_flags flags, const struct ssh_request_ops *ops)
```

Initialize SSH request.

**Parameters**

- `struct ssh_request *rqst`: The request to initialize.
- `enum ssam_request_flags flags`: Request flags, determining the type of the request.
- `const struct ssh_request_ops *ops`: Request operations.

**Description**

Initializes the given SSH request and underlying packet. Sets the message
buffer pointer to `NULL` and the message buffer length to zero. This buffer
has to be set separately via [`ssh_request_set_data()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssh_request_set_data) before submission and
must contain a valid SSH request message.

**Return**

Returns zero on success or `-EINVAL` if the given flags are invalid.

#### <a id="c-ssh_rtl_init"></a>`ssh_rtl_init()`

```c
int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev, const struct ssh_rtl_ops *ops)
```

Initialize request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer to initialize.
- `struct serdev_device *serdev`: The underlying serial device, i.e. the lower-level transport.
- `const struct ssh_rtl_ops *ops`: Request transport layer operations.

**Description**

Initializes the given request transport layer and associated packet
transport layer. Transmitter and receiver threads must be started
separately via [`ssh_rtl_start()`](#c-ssh_rtl_start), after the request-layer has been
initialized and the lower-level serial device layer has been set up.

**Return**

Returns zero on success and a nonzero error code on failure.

#### <a id="c-ssh_rtl_destroy"></a>`ssh_rtl_destroy()`

```c
void ssh_rtl_destroy(struct ssh_rtl *rtl)
```

Deinitialize request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer to deinitialize.

**Description**

Deinitializes the given request transport layer and frees resources
associated with it. If receiver and/or transmitter threads have been
started, the layer must first be shut down via [`ssh_rtl_shutdown()`](#c-ssh_rtl_shutdown) before
this function can be called.

#### <a id="c-ssh_rtl_start"></a>`ssh_rtl_start()`

```c
int ssh_rtl_start(struct ssh_rtl *rtl)
```

Start request transmitter and receiver.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_rtl_flush"></a>`ssh_rtl_flush()`

```c
int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout)
```

Flush the request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: request transport layer
- `unsigned long timeout`: timeout for the flush operation in jiffies

**Description**

Queue a special flush request and wait for its completion. This request
will be completed after all other currently queued and pending requests
have been completed. Instead of a normal data packet, this request submits
a special flush packet, meaning that upon completion, also the underlying
packet transport layer has been flushed.

Flushing the request layer guarantees that all previously submitted
requests have been fully completed before this call returns. Additionally,
flushing blocks execution of all later submitted requests until the flush
has been completed.

If the caller ensures that no new requests are submitted after a call to
this function, the request transport layer is guaranteed to have no
remaining requests when this call returns. The same guarantee does not hold
for the packet layer, on which control packets may still be queued after
this call.

**Return**

Returns zero on success, `-ETIMEDOUT` if the flush timed out and has
been canceled as a result of the timeout, or `-ESHUTDOWN` if the packet
and/or request transport layer has been shut down before this call. May
also return `-EINTR` if the underlying packet transmission has been
interrupted.

#### <a id="c-ssh_rtl_shutdown"></a>`ssh_rtl_shutdown()`

```c
void ssh_rtl_shutdown(struct ssh_rtl *rtl)
```

Shut down request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer.

**Description**

Shuts down the request transport layer, removing and canceling all queued
and pending requests. Requests canceled by this operation will be completed
with `-ESHUTDOWN` as status. Receiver and transmitter threads will be
stopped, the lower-level packet layer will be shutdown.

As a result of this function, the transport layer will be marked as shut
down. Submission of requests after the transport layer has been shut down
will fail with `-ESHUTDOWN`.


<a id="rst-controller"></a>

## Controller


#### <a id="c-struct-ssh_seq_counter"></a>`struct ssh_seq_counter`

Safe counter for SSH sequence IDs.

**Definition**

```c
struct ssh_seq_counter {
    u8 value;
};
```

**Members**

- `value`: The current counter value.

#### <a id="c-struct-ssh_rqid_counter"></a>`struct ssh_rqid_counter`

Safe counter for SSH request IDs.

**Definition**

```c
struct ssh_rqid_counter {
    u16 value;
};
```

**Members**

- `value`: The current counter value.

#### <a id="c-struct-ssam_nf_head"></a>`struct ssam_nf_head`

Notifier head for SSAM events.

**Definition**

```c
struct ssam_nf_head {
    struct srcu_struct srcu;
    struct list_head head;
};
```

**Members**

- `srcu`: The SRCU struct for synchronization.
- `head`: List-head for notifier blocks registered under this head.

#### <a id="c-struct-ssam_nf"></a>`struct ssam_nf`

Notifier callback- and activation-registry for SSAM events.

**Definition**

```c
struct ssam_nf {
    struct mutex lock;
    struct rb_root refcount;
    struct ssam_nf_head head[SSH_NUM_EVENTS];
};
```

**Members**

- `lock`: Lock guarding (de-)registration of notifier blocks. Note: This
  lock does not need to be held for notifier calls, only
  registration and deregistration.
- `refcount`: The root of the RB-tree used for reference-counting enabled
  events/notifications.
- `head`: The list of notifier heads for event/notification callbacks.

#### <a id="c-struct-ssam_event_item"></a>`struct ssam_event_item`

Struct for event queuing and completion.

**Definition**

```c
struct ssam_event_item {
    struct list_head node;
    u16 rqid;
    struct {
        void (*free)(struct ssam_event_item *event);
    } ops;
    struct ssam_event event;
};
```

**Members**

- `node`: The node in the queue.
- `rqid`: The request ID of the event.
- `ops`: Instance specific functions.
- `ops.free`: Callback for freeing this event item.
- `event`: Actual event data.

#### <a id="c-struct-ssam_event_queue"></a>`struct ssam_event_queue`

Queue for completing received events.

**Definition**

```c
struct ssam_event_queue {
    struct ssam_cplt *cplt;
    spinlock_t lock;
    struct list_head head;
    struct work_struct work;
};
```

**Members**

- `cplt`: Reference to the completion system on which this queue is active.
- `lock`: The lock for any operation on the queue.
- `head`: The list-head of the queue.
- `work`: The `struct work_struct` performing completion work for this queue.

#### <a id="c-struct-ssam_event_target"></a>`struct ssam_event_target`

Set of queues for a single SSH target ID.

**Definition**

```c
struct ssam_event_target {
    struct ssam_event_queue queue[SSH_NUM_EVENTS];
};
```

**Members**

- `queue`: The array of queues, one queue per event ID.

#### <a id="c-struct-ssam_cplt"></a>`struct ssam_cplt`

SSAM event/async request completion system.

**Definition**

```c
struct ssam_cplt {
    struct device *dev;
    struct workqueue_struct *wq;
    struct {
        struct ssam_event_target target[SSH_NUM_TARGETS];
        struct ssam_nf notif;
    } event;
};
```

**Members**

- `dev`: The device with which this system is associated. Only used
  for logging.
- `wq`: The `struct workqueue_struct` on which all completion work
  items are queued.
- `event`: Event completion management.
- `event.target`: Array of [`struct ssam_event_target`](#c-struct-ssam_event_target), one for each target.
- `event.notif`: Notifier callbacks and event activation reference counting.

#### <a id="c-enum-ssam_controller_state"></a>`enum ssam_controller_state`

State values for [`struct ssam_controller`](#c-struct-ssam_controller).

**Constants**

- `SSAM_CONTROLLER_UNINITIALIZED`: The controller has not been initialized yet or has been deinitialized.
- `SSAM_CONTROLLER_INITIALIZED`: The controller is initialized, but has not been started yet.
- `SSAM_CONTROLLER_STARTED`: The controller has been started and is ready to use.
- `SSAM_CONTROLLER_STOPPED`: The controller has been stopped.
- `SSAM_CONTROLLER_SUSPENDED`: The controller has been suspended.

#### <a id="c-struct-ssam_controller_caps"></a>`struct ssam_controller_caps`

Controller device capabilities.

**Definition**

```c
struct ssam_controller_caps {
    u32 ssh_power_profile;
    u32 ssh_buffer_size;
    u32 screen_on_sleep_idle_timeout;
    u32 screen_off_sleep_idle_timeout;
    u32 d3_closes_handle:1;
};
```

**Members**

- `ssh_power_profile`: SSH power profile.
- `ssh_buffer_size`: SSH driver UART buffer size.
- `screen_on_sleep_idle_timeout`: SAM UART screen-on sleep idle timeout.
- `screen_off_sleep_idle_timeout`: SAM UART screen-off sleep idle timeout.
- `d3_closes_handle`: SAM closes UART handle in D3.

**Description**

Controller and SSH device capabilities found in ACPI.

#### <a id="c-struct-ssam_controller"></a>`struct ssam_controller`

SSAM controller device.

**Definition**

```c
struct ssam_controller {
    struct kref kref;
    struct rw_semaphore lock;
    enum ssam_controller_state state;
    struct ssh_rtl rtl;
    struct ssam_cplt cplt;
    struct {
        struct ssh_seq_counter seq;
        struct ssh_rqid_counter rqid;
    } counter;
    struct {
        int num;
        bool wakeup_enabled;
    } irq;
    struct ssam_controller_caps caps;
};
```

**Members**

- `kref`: Reference count of the controller.
- `lock`: Main lock for the controller, used to guard state changes.
- `state`: Controller state.
- `rtl`: Request transport layer for SSH I/O.
- `cplt`: Completion system for SSH/SSAM events and asynchronous requests.
- `counter`: Safe SSH message ID counters.
- `counter.seq`: Sequence ID counter.
- `counter.rqid`: Request ID counter.
- `irq`: Wakeup IRQ resources.
- `irq.num`: The wakeup IRQ number.
- `irq.wakeup_enabled`: Whether wakeup by IRQ is enabled during suspend.
- `caps`: The controller device capabilities.

#### <a id="c-ssam_controller_receive_buf"></a>`ssam_controller_receive_buf()`

```c
ssize_t ssam_controller_receive_buf(struct ssam_controller *ctrl, const u8 *buf, size_t n)
```

Provide input-data to the controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.
- `const u8 *buf`: The input buffer.
- `size_t n`: The number of bytes in the input buffer.

**Description**

Provide input data to be evaluated by the controller, which has been
received via the lower-level transport.

**Return**

Returns the number of bytes consumed, or, if the packet transport
layer of the controller has been shut down, `-ESHUTDOWN`.

#### <a id="c-ssam_controller_write_wakeup"></a>`ssam_controller_write_wakeup()`

```c
void ssam_controller_write_wakeup(struct ssam_controller *ctrl)
```

Notify the controller that the underlying device has space available for data to be written.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.



#### <a id="c-ssh_seq_reset"></a>`ssh_seq_reset()`

```c
void ssh_seq_reset(struct ssh_seq_counter *c)
```

Reset/initialize sequence ID counter.

**Parameters**

- `struct ssh_seq_counter *c`: The counter to reset.

#### <a id="c-ssh_seq_next"></a>`ssh_seq_next()`

```c
u8 ssh_seq_next(struct ssh_seq_counter *c)
```

Get next sequence ID.

**Parameters**

- `struct ssh_seq_counter *c`: The counter providing the sequence IDs.

**Return**

Returns the next sequence ID of the counter.

#### <a id="c-ssh_rqid_reset"></a>`ssh_rqid_reset()`

```c
void ssh_rqid_reset(struct ssh_rqid_counter *c)
```

Reset/initialize request ID counter.

**Parameters**

- `struct ssh_rqid_counter *c`: The counter to reset.

#### <a id="c-ssh_rqid_next"></a>`ssh_rqid_next()`

```c
u16 ssh_rqid_next(struct ssh_rqid_counter *c)
```

Get next request ID.

**Parameters**

- `struct ssh_rqid_counter *c`: The counter providing the request IDs.

**Return**

Returns the next request ID of the counter, skipping any reserved
request IDs.

#### <a id="c-ssam_event_matches_notifier"></a>`ssam_event_matches_notifier()`

```c
bool ssam_event_matches_notifier(const struct ssam_event_notifier *n, const struct ssam_event *event)
```

Test if an event matches a notifier.

**Parameters**

- `const struct ssam_event_notifier *n`: The event notifier to test against.
- `const struct ssam_event *event`: The event to test.

**Return**

Returns `true` if the given event matches the given notifier
according to the rules set in the notifier's event mask, `false` otherwise.

#### <a id="c-ssam_nfblk_call_chain"></a>`ssam_nfblk_call_chain()`

```c
int ssam_nfblk_call_chain(struct ssam_nf_head *nh, struct ssam_event *event)
```

Call event notifier callbacks of the given chain.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head for which the notifier callbacks should be called.
- `struct ssam_event *event`: The event data provided to the callbacks.

**Description**

Call all registered notifier callbacks in order of their priority until
either no notifier is left or a notifier returns a value with the
`SSAM_NOTIF_STOP` bit set. Note that this bit is automatically set via
[`ssam_notifier_from_errno()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssam_notifier_from_errno) on any non-zero error value.

**Return**

Returns the notifier status value, which contains the notifier
status bits (`SSAM_NOTIF_HANDLED` and `SSAM_NOTIF_STOP`) as well as a
potential error value returned from the last executed notifier callback.
Use [`ssam_notifier_to_errno()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssam_notifier_to_errno) to convert this value to the original error
value.

#### <a id="c-ssam_nfblk_insert"></a>`ssam_nfblk_insert()`

```c
int ssam_nfblk_insert(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
```

Insert a new notifier block into the given notifier list.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head into which the block should be inserted.
- `struct ssam_notifier_block *nb`: The notifier block to add.

**Note**

This function must be synchronized by the caller with respect to other
insert, find, and/or remove calls by holding `struct ssam_nf.lock`.

**Return**

Returns zero on success, `-EEXIST` if the notifier block has already
been registered.

#### <a id="c-ssam_nfblk_find"></a>`ssam_nfblk_find()`

```c
bool ssam_nfblk_find(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
```

Check if a notifier block is registered on the given notifier head. list.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head on which to search.
- `struct ssam_notifier_block *nb`: The notifier block to search for.

**Note**

This function must be synchronized by the caller with respect to other
insert, find, and/or remove calls by holding `struct ssam_nf.lock`.

**Return**

Returns true if the given notifier block is registered on the given
notifier head, false otherwise.

#### <a id="c-ssam_nfblk_remove"></a>`ssam_nfblk_remove()`

```c
void ssam_nfblk_remove(struct ssam_notifier_block *nb)
```

Remove a notifier block from its notifier list.

**Parameters**

- `struct ssam_notifier_block *nb`: The notifier block to be removed.

**Note**

This function must be synchronized by the caller with respect to
other insert, find, and/or remove calls by holding `struct ssam_nf.lock`.
Furthermore, the caller _must_ ensure SRCU synchronization by calling
[`synchronize_srcu()`](/kernel/internals/core-api/kernel-api.md#c-synchronize_srcu) with `nh->srcu` after leaving the critical section, to
ensure that the removed notifier block is not in use any more.

#### <a id="c-ssam_nf_head_init"></a>`ssam_nf_head_init()`

```c
int ssam_nf_head_init(struct ssam_nf_head *nh)
```

Initialize the given notifier head.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head to initialize.

#### <a id="c-ssam_nf_head_destroy"></a>`ssam_nf_head_destroy()`

```c
void ssam_nf_head_destroy(struct ssam_nf_head *nh)
```

Deinitialize the given notifier head.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head to deinitialize.

#### <a id="c-struct-ssam_nf_refcount_key"></a>`struct ssam_nf_refcount_key`

Key used for event activation reference counting.

**Definition**

```c
struct ssam_nf_refcount_key {
    struct ssam_event_registry reg;
    struct ssam_event_id id;
};
```

**Members**

- `reg`: The registry via which the event is enabled/disabled.
- `id`: The ID uniquely describing the event.

#### <a id="c-struct-ssam_nf_refcount_entry"></a>`struct ssam_nf_refcount_entry`

RB-tree entry for reference counting event activations.

**Definition**

```c
struct ssam_nf_refcount_entry {
    struct rb_node node;
    struct ssam_nf_refcount_key key;
    int refcount;
    u8 flags;
};
```

**Members**

- `node`: The node of this entry in the rb-tree.
- `key`: The key of the event.
- `refcount`: The reference-count of the event.
- `flags`: The flags used when enabling the event.

#### <a id="c-ssam_nf_refcount_inc"></a>`ssam_nf_refcount_inc()`

```c
struct ssam_nf_refcount_entry * ssam_nf_refcount_inc(struct ssam_nf *nf, struct ssam_event_registry reg, struct ssam_event_id id)
```

Increment reference-/activation-count of the given event.

**Parameters**

- `struct ssam_nf *nf`: The notifier system reference.
- `struct ssam_event_registry reg`: The registry used to enable/disable the event.
- `struct ssam_event_id id`: The event ID.

**Description**

Increments the reference-/activation-count associated with the specified
event type/ID, allocating a new entry for this event ID if necessary. A
newly allocated entry will have a refcount of one.

**Note**

`nf->lock` must be held when calling this function.

**Return**

Returns the refcount entry on success. Returns an error pointer
with `-ENOSPC` if there have already been `INT_MAX` events of the specified
ID and type registered, or `-ENOMEM` if the entry could not be allocated.

#### <a id="c-ssam_nf_refcount_dec"></a>`ssam_nf_refcount_dec()`

```c
struct ssam_nf_refcount_entry * ssam_nf_refcount_dec(struct ssam_nf *nf, struct ssam_event_registry reg, struct ssam_event_id id)
```

Decrement reference-/activation-count of the given event.

**Parameters**

- `struct ssam_nf *nf`: The notifier system reference.
- `struct ssam_event_registry reg`: The registry used to enable/disable the event.
- `struct ssam_event_id id`: The event ID.

**Description**

Decrements the reference-/activation-count of the specified event,
returning its entry. If the returned entry has a refcount of zero, the
caller is responsible for freeing it using [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

**Note**

`nf->lock` must be held when calling this function.

**Return**

Returns the refcount entry on success or `NULL` if the entry has not
been found.

#### <a id="c-ssam_nf_refcount_dec_free"></a>`ssam_nf_refcount_dec_free()`

```c
void ssam_nf_refcount_dec_free(struct ssam_nf *nf, struct ssam_event_registry reg, struct ssam_event_id id)
```

Decrement reference-/activation-count of the given event and free its entry if the reference count reaches zero.

**Parameters**

- `struct ssam_nf *nf`: The notifier system reference.
- `struct ssam_event_registry reg`: The registry used to enable/disable the event.
- `struct ssam_event_id id`: The event ID.

**Description**

Decrements the reference-/activation-count of the specified event, freeing
its entry if it reaches zero.

**Note**

`nf->lock` must be held when calling this function.

#### <a id="c-ssam_nf_refcount_empty"></a>`ssam_nf_refcount_empty()`

```c
bool ssam_nf_refcount_empty(struct ssam_nf *nf)
```

Test if the notification system has any enabled/active events.

**Parameters**

- `struct ssam_nf *nf`: The notification system.

#### <a id="c-ssam_nf_call"></a>`ssam_nf_call()`

```c
void ssam_nf_call(struct ssam_nf *nf, struct device *dev, u16 rqid, struct ssam_event *event)
```

Call notification callbacks for the provided event.

**Parameters**

- `struct ssam_nf *nf`: The notifier system
- `struct device *dev`: The associated device, only used for logging.
- `u16 rqid`: The request ID of the event.
- `struct ssam_event *event`: The event provided to the callbacks.

**Description**

Execute registered callbacks in order of their priority until either no
callback is left or a callback returns a value with the `SSAM_NOTIF_STOP`
bit set. Note that this bit is set automatically when converting non-zero
error values via [`ssam_notifier_from_errno()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssam_notifier_from_errno) to notifier values.

Also note that any callback that could handle an event should return a value
with bit `SSAM_NOTIF_HANDLED` set, indicating that the event does not go
unhandled/ignored. In case no registered callback could handle an event,
this function will emit a warning.

In case a callback failed, this function will emit an error message.

#### <a id="c-ssam_nf_init"></a>`ssam_nf_init()`

```c
int ssam_nf_init(struct ssam_nf *nf)
```

Initialize the notifier system.

**Parameters**

- `struct ssam_nf *nf`: The notifier system to initialize.

#### <a id="c-ssam_nf_destroy"></a>`ssam_nf_destroy()`

```c
void ssam_nf_destroy(struct ssam_nf *nf)
```

Deinitialize the notifier system.

**Parameters**

- `struct ssam_nf *nf`: The notifier system to deinitialize.

#### <a id="c-ssam_event_item_cache_init"></a>`ssam_event_item_cache_init()`

```c
int ssam_event_item_cache_init(void)
```

Initialize the event item cache.

**Parameters**

- `void`: no arguments

#### <a id="c-ssam_event_item_cache_destroy"></a>`ssam_event_item_cache_destroy()`

```c
void ssam_event_item_cache_destroy(void)
```

Deinitialize the event item cache.

**Parameters**

- `void`: no arguments

#### <a id="c-ssam_event_item_free"></a>`ssam_event_item_free()`

```c
void ssam_event_item_free(struct ssam_event_item *item)
```

Free the provided event item.

**Parameters**

- `struct ssam_event_item *item`: The event item to free.

#### <a id="c-ssam_event_item_alloc"></a>`ssam_event_item_alloc()`

```c
struct ssam_event_item * ssam_event_item_alloc(size_t len, gfp_t flags)
```

Allocate an event item with the given payload size.

**Parameters**

- `size_t len`: The event payload length.
- `gfp_t flags`: The flags used for allocation.

**Description**

Allocate an event item with the given payload size, preferring allocation
from the event item cache if the payload is small enough (i.e. smaller than
`SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN`). Sets the item operations and payload
length values. The item free callback (`ops.free`) should not be
overwritten after this call.

**Return**

Returns the newly allocated event item.

#### <a id="c-ssam_event_queue_push"></a>`ssam_event_queue_push()`

```c
void ssam_event_queue_push(struct ssam_event_queue *q, struct ssam_event_item *item)
```

Push an event item to the event queue.

**Parameters**

- `struct ssam_event_queue *q`: The event queue.
- `struct ssam_event_item *item`: The item to add.

#### <a id="c-ssam_event_queue_pop"></a>`ssam_event_queue_pop()`

```c
struct ssam_event_item * ssam_event_queue_pop(struct ssam_event_queue *q)
```

Pop the next event item from the event queue.

**Parameters**

- `struct ssam_event_queue *q`: The event queue.

**Description**

Returns and removes the next event item from the queue. Returns `NULL` If
there is no event item left.

#### <a id="c-ssam_event_queue_is_empty"></a>`ssam_event_queue_is_empty()`

```c
bool ssam_event_queue_is_empty(struct ssam_event_queue *q)
```

Check if the event queue is empty.

**Parameters**

- `struct ssam_event_queue *q`: The event queue.

#### <a id="c-ssam_cplt_get_event_queue"></a>`ssam_cplt_get_event_queue()`

```c
struct ssam_event_queue * ssam_cplt_get_event_queue(struct ssam_cplt *cplt, u8 tid, u16 rqid)
```

Get the event queue for the given parameters.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system on which to look for the queue.
- `u8 tid`: The target ID of the queue.
- `u16 rqid`: The request ID representing the event ID for which to get the queue.

**Return**

Returns the event queue corresponding to the event type described
by the given parameters. If the request ID does not represent an event,
this function returns `NULL`. If the target ID is not supported, this
function will fall back to the default target ID (`tid = 1`).

#### <a id="c-ssam_cplt_submit"></a>`ssam_cplt_submit()`

```c
bool ssam_cplt_submit(struct ssam_cplt *cplt, struct work_struct *work)
```

Submit a work item to the completion system workqueue.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system.
- `struct work_struct *work`: The work item to submit.

#### <a id="c-ssam_cplt_submit_event"></a>`ssam_cplt_submit_event()`

```c
int ssam_cplt_submit_event(struct ssam_cplt *cplt, struct ssam_event_item *item)
```

Submit an event to the completion system.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system.
- `struct ssam_event_item *item`: The event item to submit.

**Description**

Submits the event to the completion system by queuing it on the event item
queue and queuing the respective event queue work item on the completion
workqueue, which will eventually complete the event.

**Return**

Returns zero on success, `-EINVAL` if there is no event queue that
can handle the given event item.

#### <a id="c-ssam_cplt_flush"></a>`ssam_cplt_flush()`

```c
void ssam_cplt_flush(struct ssam_cplt *cplt)
```

Flush the completion system.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system.

**Description**

Flush the completion system by waiting until all currently submitted work
items have been completed.

**Note**

This function does not guarantee that all events will have been
handled once this call terminates. In case of a larger number of
to-be-completed events, the event queue work function may re-schedule its
work item, which this flush operation will ignore.

This operation is only intended to, during normal operation prior to
shutdown, try to complete most events and requests to get them out of the
system while the system is still fully operational. It does not aim to
provide any guarantee that all of them have been handled.

#### <a id="c-ssam_event_queue_init"></a>`ssam_event_queue_init()`

```c
void ssam_event_queue_init(struct ssam_cplt *cplt, struct ssam_event_queue *evq)
```

Initialize an event queue.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system on which the queue resides.
- `struct ssam_event_queue *evq`: The event queue to initialize.

#### <a id="c-ssam_cplt_init"></a>`ssam_cplt_init()`

```c
int ssam_cplt_init(struct ssam_cplt *cplt, struct device *dev)
```

Initialize completion system.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system to initialize.
- `struct device *dev`: The device used for logging.

#### <a id="c-ssam_cplt_destroy"></a>`ssam_cplt_destroy()`

```c
void ssam_cplt_destroy(struct ssam_cplt *cplt)
```

Deinitialize the completion system.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system to deinitialize.

**Description**

Deinitialize the given completion system and ensure that all pending, i.e.
yet-to-be-completed, event items and requests have been handled.

#### <a id="c-ssam_controller_lock"></a>`ssam_controller_lock()`

```c
void ssam_controller_lock(struct ssam_controller *c)
```

Acquire the main controller lock.

**Parameters**

- `struct ssam_controller *c`: The controller to lock.

**Description**

This lock must be held for any state transitions, including transition to
suspend/resumed states and during shutdown. See [`ssam_controller_statelock()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssam_controller_statelock)
for more details on controller locking.

See `ssam_controller_unlock()` for the corresponding unlock function.

#### <a id="c-ssam_controller_caps_load_from_acpi"></a>`ssam_controller_caps_load_from_acpi()`

```c
int ssam_controller_caps_load_from_acpi(acpi_handle handle, struct ssam_controller_caps *caps)
```

Load controller capabilities from ACPI _DSM.

**Parameters**

- `acpi_handle handle`: The handle of the ACPI controller/SSH device.
- `struct ssam_controller_caps *caps`: Where to store the capabilities in.

**Description**

Initializes the given controller capabilities with default values, then
checks and, if the respective _DSM functions are available, loads the
actual capabilities from the _DSM.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssam_controller_caps_load_from_of"></a>`ssam_controller_caps_load_from_of()`

```c
int ssam_controller_caps_load_from_of(struct device *dev, struct ssam_controller_caps *caps)
```

Load controller capabilities from OF/DT.

**Parameters**

- `struct device *dev`: A pointer to the controller device
- `struct ssam_controller_caps *caps`: Where to store the capabilities in.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssam_controller_caps_load"></a>`ssam_controller_caps_load()`

```c
int ssam_controller_caps_load(struct device *dev, struct ssam_controller_caps *caps)
```

Load controller capabilities

**Parameters**

- `struct device *dev`: A pointer to the controller device
- `struct ssam_controller_caps *caps`: Where to store the capabilities in.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssam_controller_init"></a>`ssam_controller_init()`

```c
int ssam_controller_init(struct ssam_controller *ctrl, struct serdev_device *serdev)
```

Initialize SSAM controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to initialize.
- `struct serdev_device *serdev`: The serial device representing the underlying data transport.

**Description**

Initializes the given controller. Does neither start receiver nor
transmitter threads. After this call, the controller has to be hooked up to
the serdev core separately via `struct serdev_device_ops`, relaying calls to
[`ssam_controller_receive_buf()`](#c-ssam_controller_receive_buf) and [`ssam_controller_write_wakeup()`](#c-ssam_controller_write_wakeup). Once the
controller has been hooked up, transmitter and receiver threads may be
started via [`ssam_controller_start()`](#c-ssam_controller_start). These setup steps need to be completed
before controller can be used for requests.

#### <a id="c-ssam_controller_start"></a>`ssam_controller_start()`

```c
int ssam_controller_start(struct ssam_controller *ctrl)
```

Start the receiver and transmitter threads of the controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Note**

When this function is called, the controller should be properly
hooked up to the serdev core via `struct serdev_device_ops`. Please refer
to [`ssam_controller_init()`](#c-ssam_controller_init) for more details on controller initialization.

This function must be called with the main controller lock held (i.e. by
calling [`ssam_controller_lock()`](#c-ssam_controller_lock)).

#### <a id="c-ssam_controller_shutdown"></a>`ssam_controller_shutdown()`

```c
void ssam_controller_shutdown(struct ssam_controller *ctrl)
```

Shut down the controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Description**

Shuts down the controller by flushing all pending requests and stopping the
transmitter and receiver threads. All requests submitted after this call
will fail with `-ESHUTDOWN`. While it is discouraged to do so, this function
is safe to use in parallel with ongoing request submission.

In the course of this shutdown procedure, all currently registered
notifiers will be unregistered. It is, however, strongly recommended to not
rely on this behavior, and instead the party registering the notifier
should unregister it before the controller gets shut down, e.g. via the
SSAM bus which guarantees client devices to be removed before a shutdown.

Note that events may still be pending after this call, but, due to the
notifiers being unregistered, these events will be dropped when the
controller is subsequently destroyed via [`ssam_controller_destroy()`](#c-ssam_controller_destroy).

This function must be called with the main controller lock held (i.e. by
calling [`ssam_controller_lock()`](#c-ssam_controller_lock)).

#### <a id="c-ssam_controller_destroy"></a>`ssam_controller_destroy()`

```c
void ssam_controller_destroy(struct ssam_controller *ctrl)
```

Destroy the controller and free its resources.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Description**

Ensures that all resources associated with the controller get freed. This
function should only be called after the controller has been stopped via
[`ssam_controller_shutdown()`](#c-ssam_controller_shutdown). In general, this function should not be called
directly. The only valid place to call this function directly is during
initialization, before the controller has been fully initialized and passed
to other processes. This function is called automatically when the
reference count of the controller reaches zero.

This function must be called with the main controller lock held (i.e. by
calling [`ssam_controller_lock()`](#c-ssam_controller_lock)).

#### <a id="c-ssam_controller_suspend"></a>`ssam_controller_suspend()`

```c
int ssam_controller_suspend(struct ssam_controller *ctrl)
```

Suspend the controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to suspend.

**Description**

Marks the controller as suspended. Note that display-off and D0-exit
notifications have to be sent manually before transitioning the controller
into the suspended state via this function.

See [`ssam_controller_resume()`](#c-ssam_controller_resume) for the corresponding resume function.

**Return**

Returns `-EINVAL` if the controller is currently not in the
"started" state.

#### <a id="c-ssam_controller_resume"></a>`ssam_controller_resume()`

```c
int ssam_controller_resume(struct ssam_controller *ctrl)
```

Resume the controller from suspend.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to resume.

**Description**

Resume the controller from the suspended state it was put into via
[`ssam_controller_suspend()`](#c-ssam_controller_suspend). This function does not issue display-on and
D0-entry notifications. If required, those have to be sent manually after
this call.

**Return**

Returns `-EINVAL` if the controller is currently not suspended.

#### <a id="c-struct-ssh_notification_params"></a>`struct ssh_notification_params`

Command payload to enable/disable SSH notifications.

**Definition**

```c
struct ssh_notification_params {
    u8 target_category;
    u8 flags;
    __le16 request_id;
    u8 instance_id;
};
```

**Members**

- `target_category`: The target category for which notifications should be
  enabled/disabled.
- `flags`: Flags determining how notifications are being sent.
- `request_id`: The request ID that is used to send these notifications.
- `instance_id`: The specific instance in the given target category for
  which notifications should be enabled.

#### <a id="c-ssam_ssh_event_enable"></a>`ssam_ssh_event_enable()`

```c
int ssam_ssh_event_enable(struct ssam_controller *ctrl, struct ssam_event_registry reg, struct ssam_event_id id, u8 flags)
```

Enable SSH event.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which to enable the event.
- `struct ssam_event_registry reg`: The event registry describing what request to use for enabling and
  disabling the event.
- `struct ssam_event_id id`: The event identifier.
- `u8 flags`: The event flags.

**Description**

Enables the specified event on the EC. This function does not manage
reference counting of enabled events and is basically only a wrapper for
the raw EC request. If the specified event is already enabled, the EC will
ignore this request.

**Return**

Returns the status of the executed SAM request (zero on success and
negative on direct failure) or `-EPROTO` if the request response indicates a
failure.

#### <a id="c-ssam_ssh_event_disable"></a>`ssam_ssh_event_disable()`

```c
int ssam_ssh_event_disable(struct ssam_controller *ctrl, struct ssam_event_registry reg, struct ssam_event_id id, u8 flags)
```

Disable SSH event.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which to disable the event.
- `struct ssam_event_registry reg`: The event registry describing what request to use for enabling and
  disabling the event (must be same as used when enabling the event).
- `struct ssam_event_id id`: The event identifier.
- `u8 flags`: The event flags (likely ignored for disabling of events).

**Description**

Disables the specified event on the EC. This function does not manage
reference counting of enabled events and is basically only a wrapper for
the raw EC request. If the specified event is already disabled, the EC will
ignore this request.

**Return**

Returns the status of the executed SAM request (zero on success and
negative on direct failure) or `-EPROTO` if the request response indicates a
failure.

#### <a id="c-ssam_get_firmware_version"></a>`ssam_get_firmware_version()`

```c
int ssam_get_firmware_version(struct ssam_controller *ctrl, u32 *version)
```

Get the SAM/EC firmware version.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.
- `u32 *version`: Where to store the version number.

**Return**

Returns zero on success or the status of the executed SAM request
if that request failed.

#### <a id="c-ssam_ctrl_notif_display_off"></a>`ssam_ctrl_notif_display_off()`

```c
int ssam_ctrl_notif_display_off(struct ssam_controller *ctrl)
```

Notify EC that the display has been turned off.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Description**

Notify the EC that the display has been turned off and the driver may enter
a lower-power state. This will prevent events from being sent directly.
Rather, the EC signals an event by pulling the wakeup GPIO high for as long
as there are pending events. The events then need to be manually released,
one by one, via the GPIO callback request. All pending events accumulated
during this state can also be released by issuing the display-on
notification, e.g. via [`ssam_ctrl_notif_display_on()`](#c-ssam_ctrl_notif_display_on), which will also reset
the GPIO.

On some devices, specifically ones with an integrated keyboard, the keyboard
backlight will be turned off by this call.

This function will only send the display-off notification command if
display notifications are supported by the EC. Currently all known devices
support these notifications.

Use [`ssam_ctrl_notif_display_on()`](#c-ssam_ctrl_notif_display_on) to reverse the effects of this function.

**Return**

Returns zero on success or if no request has been executed, the
status of the executed SAM request if that request failed, or `-EPROTO` if
an unexpected response has been received.

#### <a id="c-ssam_ctrl_notif_display_on"></a>`ssam_ctrl_notif_display_on()`

```c
int ssam_ctrl_notif_display_on(struct ssam_controller *ctrl)
```

Notify EC that the display has been turned on.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Description**

Notify the EC that the display has been turned back on and the driver has
exited its lower-power state. This notification is the counterpart to the
display-off notification sent via [`ssam_ctrl_notif_display_off()`](#c-ssam_ctrl_notif_display_off) and will
reverse its effects, including resetting events to their default behavior.

This function will only send the display-on notification command if display
notifications are supported by the EC. Currently all known devices support
these notifications.

See [`ssam_ctrl_notif_display_off()`](#c-ssam_ctrl_notif_display_off) for more details.

**Return**

Returns zero on success or if no request has been executed, the
status of the executed SAM request if that request failed, or `-EPROTO` if
an unexpected response has been received.

#### <a id="c-ssam_ctrl_notif_d0_exit"></a>`ssam_ctrl_notif_d0_exit()`

```c
int ssam_ctrl_notif_d0_exit(struct ssam_controller *ctrl)
```

Notify EC that the driver/device exits the D0 power state.

**Parameters**

- `struct ssam_controller *ctrl`: The controller

**Description**

Notifies the EC that the driver prepares to exit the D0 power state in
favor of a lower-power state. Exact effects of this function related to the
EC are currently unknown.

This function will only send the D0-exit notification command if D0-state
notifications are supported by the EC. Only newer Surface generations
support these notifications.

Use [`ssam_ctrl_notif_d0_entry()`](#c-ssam_ctrl_notif_d0_entry) to reverse the effects of this function.

**Return**

Returns zero on success or if no request has been executed, the
status of the executed SAM request if that request failed, or `-EPROTO` if
an unexpected response has been received.

#### <a id="c-ssam_ctrl_notif_d0_entry"></a>`ssam_ctrl_notif_d0_entry()`

```c
int ssam_ctrl_notif_d0_entry(struct ssam_controller *ctrl)
```

Notify EC that the driver/device enters the D0 power state.

**Parameters**

- `struct ssam_controller *ctrl`: The controller

**Description**

Notifies the EC that the driver has exited a lower-power state and entered
the D0 power state. Exact effects of this function related to the EC are
currently unknown.

This function will only send the D0-entry notification command if D0-state
notifications are supported by the EC. Only newer Surface generations
support these notifications.

See [`ssam_ctrl_notif_d0_exit()`](#c-ssam_ctrl_notif_d0_exit) for more details.

**Return**

Returns zero on success or if no request has been executed, the
status of the executed SAM request if that request failed, or `-EPROTO` if
an unexpected response has been received.

#### <a id="c-ssam_nf_refcount_enable"></a>`ssam_nf_refcount_enable()`

```c
int ssam_nf_refcount_enable(struct ssam_controller *ctrl, struct ssam_nf_refcount_entry *entry, u8 flags)
```

Enable event for reference count entry if it has not already been enabled.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to enable the event on.
- `struct ssam_nf_refcount_entry *entry`: The reference count entry for the event to be enabled.
- `u8 flags`: The flags used for enabling the event on the EC.

**Description**

Enable the event associated with the given reference count entry if the
reference count equals one, i.e. the event has not previously been enabled.
If the event has already been enabled (i.e. reference count not equal to
one), check that the flags used for enabling match and warn about this if
they do not.

This does not modify the reference count itself, which is done with
[`ssam_nf_refcount_inc()`](#c-ssam_nf_refcount_inc) / [`ssam_nf_refcount_dec()`](#c-ssam_nf_refcount_dec).

**Note**

`nf->lock` must be held when calling this function.

**Return**

Returns zero on success. If the event is enabled by this call,
returns the status of the event-enable EC command.

#### <a id="c-ssam_nf_refcount_disable_free"></a>`ssam_nf_refcount_disable_free()`

```c
int ssam_nf_refcount_disable_free(struct ssam_controller *ctrl, struct ssam_nf_refcount_entry *entry, u8 flags, bool ec)
```

Disable event for reference count entry if it is no longer in use and free the corresponding entry.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to disable the event on.
- `struct ssam_nf_refcount_entry *entry`: The reference count entry for the event to be disabled.
- `u8 flags`: The flags used for enabling the event on the EC.
- `bool ec`: Flag specifying if the event should actually be disabled on the EC.

**Description**

If `ec` equals `true` and the reference count equals zero (i.e. the
event is no longer requested by any client), the specified event will be
disabled on the EC via the corresponding request.

If `ec` equals `false`, no request will be sent to the EC and the event
can be considered in a detached state (i.e. no longer used but still
enabled). Disabling an event via this method may be required for
hot-removable devices, where event disable requests may time out after the
device has been physically removed.

In both cases, if the reference count equals zero, the corresponding
reference count entry will be freed. The reference count entry must not be
used any more after a call to this function.

Also checks if the flags used for disabling the event match the flags used
for enabling the event and warns if they do not (regardless of reference
count).

This does not modify the reference count itself, which is done with
[`ssam_nf_refcount_inc()`](#c-ssam_nf_refcount_inc) / [`ssam_nf_refcount_dec()`](#c-ssam_nf_refcount_dec).

**Note**

`nf->lock` must be held when calling this function.

**Return**

Returns zero on success. If the event is disabled by this call,
returns the status of the event-enable EC command.

#### <a id="c-ssam_notifier_disable_registered"></a>`ssam_notifier_disable_registered()`

```c
int ssam_notifier_disable_registered(struct ssam_controller *ctrl)
```

Disable events for all registered notifiers.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which to disable the notifiers/events.

**Description**

Disables events for all currently registered notifiers. In case of an error
(EC command failing), all previously disabled events will be restored and
the error code returned.

This function is intended to disable all events prior to hibernation entry.
See [`ssam_notifier_restore_registered()`](#c-ssam_notifier_restore_registered) to restore/re-enable all events
disabled with this function.

Note that this function will not disable events for notifiers registered
after calling this function. It should thus be made sure that no new
notifiers are going to be added after this call and before the corresponding
call to [`ssam_notifier_restore_registered()`](#c-ssam_notifier_restore_registered).

**Return**

Returns zero on success. In case of failure returns the error code
returned by the failed EC command to disable an event.

#### <a id="c-ssam_notifier_restore_registered"></a>`ssam_notifier_restore_registered()`

```c
void ssam_notifier_restore_registered(struct ssam_controller *ctrl)
```

Restore/re-enable events for all registered notifiers.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which to restore the notifiers/events.

**Description**

Restores/re-enables all events for which notifiers have been registered on
the given controller. In case of a failure, the error is logged and the
function continues to try and enable the remaining events.

This function is intended to restore/re-enable all registered events after
hibernation. See [`ssam_notifier_disable_registered()`](#c-ssam_notifier_disable_registered) for the counter part
disabling the events and more details.

#### <a id="c-ssam_notifier_is_empty"></a>`ssam_notifier_is_empty()`

```c
bool ssam_notifier_is_empty(struct ssam_controller *ctrl)
```

Check if there are any registered notifiers.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to check on.

**Return**

Returns `true` if there are currently no notifiers registered on the
controller, `false` otherwise.

#### <a id="c-ssam_notifier_unregister_all"></a>`ssam_notifier_unregister_all()`

```c
void ssam_notifier_unregister_all(struct ssam_controller *ctrl)
```

Unregister all currently registered notifiers.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to unregister the notifiers on.

**Description**

Unregisters all currently registered notifiers. This function is used to
ensure that all notifiers will be unregistered and associated
entries/resources freed when the controller is being shut down.

#### <a id="c-ssam_irq_setup"></a>`ssam_irq_setup()`

```c
int ssam_irq_setup(struct ssam_controller *ctrl)
```

Set up SAM EC wakeup-GPIO interrupt.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which the IRQ should be set up.

**Description**

Set up an IRQ for the wakeup-GPIO pin of the SAM EC. This IRQ can be used
to wake the device from a low power state.

Note that this IRQ can only be triggered while the EC is in the display-off
state. In this state, events are not sent to the host in the usual way.
Instead the wakeup-GPIO gets pulled to "high" as long as there are pending
events and these events need to be released one-by-one via the GPIO
callback request, either until there are no events left and the GPIO is
reset, or all at once by transitioning the EC out of the display-off state,
which will also clear the GPIO.

Not all events, however, should trigger a full system wakeup. Instead the
driver should, if necessary, inspect and forward each event to the
corresponding subsystem, which in turn should decide if the system needs to
be woken up. This logic has not been implemented yet, thus wakeup by this
IRQ should be disabled by default to avoid spurious wake-ups, caused, for
example, by the remaining battery percentage changing. Refer to comments in
this function and comments in the corresponding IRQ handler for more
details on how this should be implemented.

See also [`ssam_ctrl_notif_display_off()`](#c-ssam_ctrl_notif_display_off) and [`ssam_ctrl_notif_display_off()`](#c-ssam_ctrl_notif_display_off)
for functions to transition the EC into and out of the display-off state as
well as more details on it.

The IRQ is disabled by default and has to be enabled before it can wake up
the device from suspend via [`ssam_irq_arm_for_wakeup()`](#c-ssam_irq_arm_for_wakeup). On teardown, the IRQ
should be freed via [`ssam_irq_free()`](#c-ssam_irq_free).

#### <a id="c-ssam_irq_free"></a>`ssam_irq_free()`

```c
void ssam_irq_free(struct ssam_controller *ctrl)
```

Free SAM EC wakeup-GPIO interrupt.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which the IRQ should be freed.

**Description**

Free the wakeup-GPIO IRQ previously set-up via [`ssam_irq_setup()`](#c-ssam_irq_setup).

#### <a id="c-ssam_irq_arm_for_wakeup"></a>`ssam_irq_arm_for_wakeup()`

```c
int ssam_irq_arm_for_wakeup(struct ssam_controller *ctrl)
```

Arm the EC IRQ for wakeup, if enabled.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which the IRQ should be armed.

**Description**

Sets up the IRQ so that it can be used to wake the device. Specifically,
this function enables the irq and then, if the device is allowed to wake up
the system, calls `enable_irq_wake()`. See [`ssam_irq_disarm_wakeup()`](#c-ssam_irq_disarm_wakeup) for the
corresponding function to disable the IRQ.

This function is intended to arm the IRQ before entering S2idle suspend.

**Note**

calls to [`ssam_irq_arm_for_wakeup()`](#c-ssam_irq_arm_for_wakeup) and [`ssam_irq_disarm_wakeup()`](#c-ssam_irq_disarm_wakeup) must
be balanced.

#### <a id="c-ssam_irq_disarm_wakeup"></a>`ssam_irq_disarm_wakeup()`

```c
void ssam_irq_disarm_wakeup(struct ssam_controller *ctrl)
```

Disarm the wakeup IRQ.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which the IRQ should be disarmed.

**Description**

Disarm the IRQ previously set up for wake via [`ssam_irq_arm_for_wakeup()`](#c-ssam_irq_arm_for_wakeup).

This function is intended to disarm the IRQ after exiting S2idle suspend.

**Note**

calls to [`ssam_irq_arm_for_wakeup()`](#c-ssam_irq_arm_for_wakeup) and [`ssam_irq_disarm_wakeup()`](#c-ssam_irq_disarm_wakeup) must
be balanced.


<a id="rst-client-device-bus"></a>

## Client Device Bus


#### <a id="c-ssam_device_id_compatible"></a>`ssam_device_id_compatible()`

```c
bool ssam_device_id_compatible(const struct ssam_device_id *id, struct ssam_device_uid uid)
```

Check if a device ID matches a UID.

**Parameters**

- `const struct ssam_device_id *id`: The device ID as potential match.
- `struct ssam_device_uid uid`: The device UID matching against.

**Description**

Check if the given ID is a match for the given UID, i.e. if a device with
the provided UID is compatible to the given ID following the match rules
described in its `ssam_device_id.match_flags` member.

**Return**

Returns `true` if the given UID is compatible to the match rule
described by the given ID, `false` otherwise.

#### <a id="c-ssam_device_id_is_null"></a>`ssam_device_id_is_null()`

```c
bool ssam_device_id_is_null(const struct ssam_device_id *id)
```

Check if a device ID is null.

**Parameters**

- `const struct ssam_device_id *id`: The device ID to check.

**Description**

Check if a given device ID is null, i.e. all zeros. Used to check for the
end of `MODULE_DEVICE_TABLE(ssam, ...)` or similar lists.

**Return**

Returns `true` if the given ID represents a null ID, `false`
otherwise.

#### <a id="c-ssam_bus_register"></a>`ssam_bus_register()`

```c
int ssam_bus_register(void)
```

Register and set-up the SSAM client device bus.

**Parameters**

- `void`: no arguments

#### <a id="c-ssam_bus_unregister"></a>`ssam_bus_unregister()`

```c
void ssam_bus_unregister(void)
```

Unregister the SSAM client device bus.

**Parameters**

- `void`: no arguments


<a id="rst-core"></a>

## Core


#### <a id="c-ssam_try_set_controller"></a>`ssam_try_set_controller()`

```c
int ssam_try_set_controller(struct ssam_controller *ctrl)
```

Try to set the main controller reference.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to which the reference should point.

**Description**

Set the main controller reference to the given pointer if the reference
hasn't been set already.

**Return**

Returns zero on success or `-EEXIST` if the reference has already
been set.

#### <a id="c-ssam_clear_controller"></a>`ssam_clear_controller()`

```c
void ssam_clear_controller(void)
```

Remove/clear the main controller reference.

**Parameters**

- `void`: no arguments

**Description**

Clears the main controller reference, i.e. sets it to `NULL`. This function
should be called before the controller is shut down.


<a id="rst-trace-helpers"></a>

## Trace Helpers


#### <a id="c-ssam_trace_ptr_uid"></a>`ssam_trace_ptr_uid()`

```c
void ssam_trace_ptr_uid(const void *ptr, char *uid_str)
```

Convert the pointer to a non-pointer UID string.

**Parameters**

- `const void *ptr`: The pointer to convert.
- `char *uid_str`: A buffer of length SSAM_PTR_UID_LEN where the UID will be stored.

**Description**

Converts the given pointer into a UID string that is safe to be shared
with userspace and logs, i.e. doesn't give away the real memory location.

#### <a id="c-ssam_trace_get_packet_seq"></a>`ssam_trace_get_packet_seq()`

```c
u16 ssam_trace_get_packet_seq(const struct ssh_packet *p)
```

Read the packet's sequence ID.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's sequence ID (SEQ) field if present, or
`SSAM_SEQ_NOT_APPLICABLE` if not (e.g. flush packet).

#### <a id="c-ssam_trace_get_request_id"></a>`ssam_trace_get_request_id()`

```c
u32 ssam_trace_get_request_id(const struct ssh_packet *p)
```

Read the packet's request ID.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's request ID (RQID) field if the packet
represents a request with command data, or `SSAM_RQID_NOT_APPLICABLE` if not
(e.g. flush request, control packet).

#### <a id="c-ssam_trace_get_request_tid"></a>`ssam_trace_get_request_tid()`

```c
u32 ssam_trace_get_request_tid(const struct ssh_packet *p)
```

Read the packet's request target ID.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's request target ID (TID) field if the packet
represents a request with command data, or `SSAM_SSH_TID_NOT_APPLICABLE`
if not (e.g. flush request, control packet).

#### <a id="c-ssam_trace_get_request_sid"></a>`ssam_trace_get_request_sid()`

```c
u32 ssam_trace_get_request_sid(const struct ssh_packet *p)
```

Read the packet's request source ID.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's request source ID (SID) field if the packet
represents a request with command data, or `SSAM_SSH_TID_NOT_APPLICABLE`
if not (e.g. flush request, control packet).

#### <a id="c-ssam_trace_get_request_tc"></a>`ssam_trace_get_request_tc()`

```c
u32 ssam_trace_get_request_tc(const struct ssh_packet *p)
```

Read the packet's request target category.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's request target category (TC) field if the
packet represents a request with command data, or `SSAM_SSH_TC_NOT_APPLICABLE`
if not (e.g. flush request, control packet).

---

# Core Driver Internals

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> Architectural overview of the Surface System Aggregator Module (SSAM) core and Surface Serial Hub (SSH) driver. For the API documentation, refer to:

<a id="rst-core-driver-internals"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Architectural overview of the Surface System Aggregator Module (SSAM) core and Surface Serial Hub (SSH) driver. For the API documentation, refer to:

- [Internal API Documentation](</kernel/hardware/driver-api/surface-aggregator/internal-api.md>)

<a id="rst-overview"></a>

## Overview

The SSAM core implementation is structured in layers, somewhat following the SSH protocol structure:

Lower-level packet transport is implemented in the *packet transport layer (PTL)*, directly building on top of the serial device (serdev) infrastructure of the kernel. As the name indicates, this layer deals with the packet transport logic and handles things like packet validation, packet acknowledgment (ACKing), packet (retransmission) timeouts, and relaying packet payloads to higher-level layers.

Above this sits the *request transport layer (RTL)*. This layer is centered around command-type packet payloads, i.e. requests (sent from host to EC), responses of the EC to those requests, and events (sent from EC to host). It, specifically, distinguishes events from request responses, matches responses to their corresponding requests, and implements request timeouts.

The *controller* layer is building on top of this and essentially decides how request responses and, especially, events are dealt with. It provides an event notifier system, handles event activation/deactivation, provides a workqueue for event and asynchronous request completion, and also manages the message counters required for building command messages (`SEQ`, `RQID`). This layer basically provides a fundamental interface to the SAM EC for use in other kernel drivers.

While the controller layer already provides an interface for other kernel drivers, the client *bus* extends this interface to provide support for native SSAM devices, i.e. devices that are not defined in ACPI and not implemented as platform devices, via `struct ssam_device <ssam_device>` and `struct ssam_device_driver <ssam_device_driver>` simplify management of client devices and client drivers.

Refer to [Documentation/driver-api/surface_aggregator/client.rst](/kernel/hardware/driver-api/surface-aggregator/client.md) for documentation regarding the client device/driver API and interface options for other kernel drivers. It is recommended to familiarize oneself with that chapter and the [Documentation/driver-api/surface_aggregator/ssh.rst](/kernel/hardware/driver-api/surface-aggregator/ssh.md) before continuing with the architectural overview below.

<a id="rst-packet-transport-layer"></a>

## Packet Transport Layer

The packet transport layer is represented via `struct ssh_ptl <ssh_ptl>` and is structured around the following key concepts:

<a id="rst-packets"></a>

### Packets

Packets are the fundamental transmission unit of the SSH protocol. They are managed by the packet transport layer, which is essentially the lowest layer of the driver and is built upon by other components of the SSAM core. Packets to be transmitted by the SSAM core are represented via `struct ssh_packet <ssh_packet>` (in contrast, packets received by the core do not have any specific structure and are managed entirely via the raw `struct ssh_frame <ssh_frame>`).

This structure contains the required fields to manage the packet inside the transport layer, as well as a reference to the buffer containing the data to be transmitted (i.e. the message wrapped in `struct ssh_frame <ssh_frame>`). Most notably, it contains an internal reference count, which is used for managing its lifetime (accessible via `ssh_packet_get()` and `ssh_packet_put()`). When this counter reaches zero, the `release()` callback provided to the packet via its `struct ssh_packet_ops <ssh_packet_ops>` reference is executed, which may then deallocate the packet or its enclosing structure (e.g. `struct ssh_request <ssh_request>`).

In addition to the `release` callback, the `struct ssh_packet_ops <ssh_packet_ops>` reference also provides a `complete()` callback, which is run once the packet has been completed and provides the status of this completion, i.e. zero on success or a negative errno value in case of an error. Once the packet has been submitted to the packet transport layer, the `complete()` callback is always guaranteed to be executed before the `release()` callback, i.e. the packet will always be completed, either successfully, with an error, or due to cancellation, before it will be released.

The state of a packet is managed via its `state` flags (`enum ssh_packet_flags <ssh_packet_flags>`), which also contains the packet type. In particular, the following bits are noteworthy:

- `SSH_PACKET_SF_LOCKED_BIT`: This bit is set when completion, either through error or success, is imminent. It indicates that no further references of the packet should be taken and any existing references should be dropped as soon as possible. The process setting this bit is responsible for removing any references to this packet from the packet queue and pending set.

- `SSH_PACKET_SF_COMPLETED_BIT`: This bit is set by the process running the `complete()` callback and is used to ensure that this callback only runs once.

- `SSH_PACKET_SF_QUEUED_BIT`: This bit is set when the packet is queued on the packet queue and cleared when it is dequeued.

- `SSH_PACKET_SF_PENDING_BIT`: This bit is set when the packet is added to the pending set and cleared when it is removed from it.

<a id="rst-packet-queue"></a>

### Packet Queue

The packet queue is the first of the two fundamental collections in the packet transport layer. It is a priority queue, with priority of the respective packets based on the packet type (major) and number of tries (minor). See `SSH_PACKET_PRIORITY()` for more details on the priority value.

All packets to be transmitted by the transport layer must be submitted to this queue via `ssh_ptl_submit()`. Note that this includes control packets sent by the transport layer itself. Internally, data packets can be re-submitted to this queue due to timeouts or NAK packets sent by the EC.

<a id="rst-pending-set"></a>

### Pending Set

The pending set is the second of the two fundamental collections in the packet transport layer. It stores references to packets that have already been transmitted, but wait for acknowledgment (e.g. the corresponding ACK packet) by the EC.

Note that a packet may both be pending and queued if it has been re-submitted due to a packet acknowledgment timeout or NAK. On such a re-submission, packets are not removed from the pending set.

<a id="rst-transmitter-thread"></a>

### Transmitter Thread

The transmitter thread is responsible for most of the actual work regarding packet transmission. In each iteration, it (waits for and) checks if the next packet on the queue (if any) can be transmitted and, if so, removes it from the queue and increments its counter for the number of transmission attempts, i.e. tries. If the packet is sequenced, i.e. requires an ACK by the EC, the packet is added to the pending set. Next, the packet's data is submitted to the serdev subsystem. In case of an error or timeout during this submission, the packet is completed by the transmitter thread with the status value of the callback set accordingly. In case the packet is unsequenced, i.e. does not require an ACK by the EC, the packet is completed with success on the transmitter thread.

Transmission of sequenced packets is limited by the number of concurrently pending packets, i.e. a limit on how many packets may be waiting for an ACK from the EC in parallel. This limit is currently set to one (see [Documentation/driver-api/surface_aggregator/ssh.rst](/kernel/hardware/driver-api/surface-aggregator/ssh.md) for the reasoning behind this). Control packets (i.e. ACK and NAK) can always be transmitted.

<a id="rst-receiver-thread"></a>

### Receiver Thread

Any data received from the EC is put into a FIFO buffer for further processing. This processing happens on the receiver thread. The receiver thread parses and validates the received message into its `struct ssh_frame <ssh_frame>` and corresponding payload. It prepares and submits the necessary ACK (and on validation error or invalid data NAK) packets for the received messages.

This thread also handles further processing, such as matching ACK messages to the corresponding pending packet (via sequence ID) and completing it, as well as initiating re-submission of all currently pending packets on receival of a NAK message (re-submission in case of a NAK is similar to re-submission due to timeout, see below for more details on that). Note that the successful completion of a sequenced packet will always run on the receiver thread (whereas any failure-indicating completion will run on the process where the failure occurred).

Any payload data is forwarded via a callback to the next upper layer, i.e. the request transport layer.

<a id="rst-timeout-reaper"></a>

### Timeout Reaper

The packet acknowledgment timeout is a per-packet timeout for sequenced packets, started when the respective packet begins (re-)transmission (i.e. this timeout is armed once per transmission attempt on the transmitter thread). It is used to trigger re-submission or, when the number of tries has been exceeded, cancellation of the packet in question.

This timeout is handled via a dedicated reaper task, which is essentially a work item (re-)scheduled to run when the next packet is set to time out. The work item then checks the set of pending packets for any packets that have exceeded the timeout and, if there are any remaining packets, re-schedules itself to the next appropriate point in time.

If a timeout has been detected by the reaper, the packet will either be re-submitted if it still has some remaining tries left, or completed with `-ETIMEDOUT` as status if not. Note that re-submission, in this case and triggered by receival of a NAK, means that the packet is added to the queue with a now incremented number of tries, yielding a higher priority. The timeout for the packet will be disabled until the next transmission attempt and the packet remains on the pending set.

Note that due to transmission and packet acknowledgment timeouts, the packet transport layer is always guaranteed to make progress, if only through timing out packets, and will never fully block.

<a id="rst-concurrency-and-locking"></a>

### Concurrency and Locking

There are two main locks in the packet transport layer: One guarding access to the packet queue and one guarding access to the pending set. These collections may only be accessed and modified under the respective lock. If access to both collections is needed, the pending lock must be acquired before the queue lock to avoid deadlocks.

In addition to guarding the collections, after initial packet submission certain packet fields may only be accessed under one of the locks. Specifically, the packet priority must only be accessed while holding the queue lock and the packet timestamp must only be accessed while holding the pending lock.

Other parts of the packet transport layer are guarded independently. State flags are managed by atomic bit operations and, if necessary, memory barriers. Modifications to the timeout reaper work item and expiration date are guarded by their own lock.

The reference of the packet to the packet transport layer (`ptl`) is somewhat special. It is either set when the upper layer request is submitted or, if there is none, when the packet is first submitted. After it is set, it will not change its value. Functions that may run concurrently with submission, i.e. cancellation, can not rely on the `ptl` reference to be set. Access to it in these functions is guarded by `READ_ONCE()`, whereas setting `ptl` is equally guarded with `WRITE_ONCE()` for symmetry.

Some packet fields may be read outside of the respective locks guarding them, specifically priority and state for tracing. In those cases, proper access is ensured by employing `WRITE_ONCE()` and `READ_ONCE()`. Such read-only access is only allowed when stale values are not critical.

With respect to the interface for higher layers, packet submission (`ssh_ptl_submit()`), packet cancellation (`ssh_ptl_cancel()`), data receival (`ssh_ptl_rx_rcvbuf()`), and layer shutdown (`ssh_ptl_shutdown()`) may always be executed concurrently with respect to each other. Note that packet submission may not run concurrently with itself for the same packet. Equally, shutdown and data receival may also not run concurrently with themselves (but may run concurrently with each other).

<a id="rst-request-transport-layer"></a>

## Request Transport Layer

The request transport layer is represented via `struct ssh_rtl <ssh_rtl>` and builds on top of the packet transport layer. It deals with requests, i.e. SSH packets sent by the host containing a `struct ssh_command <ssh_command>` as frame payload. This layer separates responses to requests from events, which are also sent by the EC via a `struct ssh_command <ssh_command>` payload. While responses are handled in this layer, events are relayed to the next upper layer, i.e. the controller layer, via the corresponding callback. The request transport layer is structured around the following key concepts:

<a id="rst-request"></a>

### Request

Requests are packets with a command-type payload, sent from host to EC to query data from or trigger an action on it (or both simultaneously). They are represented by `struct ssh_request <ssh_request>`, wrapping the underlying `struct ssh_packet <ssh_packet>` storing its message data (i.e. SSH frame with command payload). Note that all top-level representations, e.g. `struct ssam_request_sync <ssam_request_sync>` are built upon this struct.

As `struct ssh_request <ssh_request>` extends `struct ssh_packet <ssh_packet>`, its lifetime is also managed by the reference counter inside the packet struct (which can be accessed via `ssh_request_get()` and `ssh_request_put()`). Once the counter reaches zero, the `release()` callback of the `struct ssh_request_ops <ssh_request_ops>` reference of the request is called.

Requests can have an optional response that is equally sent via a SSH message with command-type payload (from EC to host). The party constructing the request must know if a response is expected and mark this in the request flags provided to `ssh_request_init()`, so that the request transport layer can wait for this response.

Similar to `struct ssh_packet <ssh_packet>`, `struct ssh_request <ssh_request>` also has a `complete()` callback provided via its request ops reference and is guaranteed to be completed before it is released once it has been submitted to the request transport layer via `ssh_rtl_submit()`. For a request without a response, successful completion will occur once the underlying packet has been successfully transmitted by the packet transport layer (i.e. from within the packet completion callback). For a request with response, successful completion will occur once the response has been received and matched to the request via its request ID (which happens on the packet layer's data-received callback running on the receiver thread). If the request is completed with an error, the status value will be set to the corresponding (negative) errno value.

The state of a request is again managed via its `state` flags (`enum ssh_request_flags <ssh_request_flags>`), which also encode the request type. In particular, the following bits are noteworthy:

- `SSH_REQUEST_SF_LOCKED_BIT`: This bit is set when completion, either through error or success, is imminent. It indicates that no further references of the request should be taken and any existing references should be dropped as soon as possible. The process setting this bit is responsible for removing any references to this request from the request queue and pending set.

- `SSH_REQUEST_SF_COMPLETED_BIT`: This bit is set by the process running the `complete()` callback and is used to ensure that this callback only runs once.

- `SSH_REQUEST_SF_QUEUED_BIT`: This bit is set when the request is queued on the request queue and cleared when it is dequeued.

- `SSH_REQUEST_SF_PENDING_BIT`: This bit is set when the request is added to the pending set and cleared when it is removed from it.

<a id="rst-request-queue"></a>

### Request Queue

The request queue is the first of the two fundamental collections in the request transport layer. In contrast to the packet queue of the packet transport layer, it is not a priority queue and the simple first come first serve principle applies.

All requests to be transmitted by the request transport layer must be submitted to this queue via `ssh_rtl_submit()`. Once submitted, requests may not be re-submitted, and will not be re-submitted automatically on timeout. Instead, the request is completed with a timeout error. If desired, the caller can create and submit a new request for another try, but it must not submit the same request again.

<a id="rst-pending-set-1"></a>

### Pending Set

The pending set is the second of the two fundamental collections in the request transport layer. This collection stores references to all pending requests, i.e. requests awaiting a response from the EC (similar to what the pending set of the packet transport layer does for packets).

<a id="rst-transmitter-task"></a>

### Transmitter Task

The transmitter task is scheduled when a new request is available for transmission. It checks if the next request on the request queue can be transmitted and, if so, submits its underlying packet to the packet transport layer. This check ensures that only a limited number of requests can be pending, i.e. waiting for a response, at the same time. If the request requires a response, the request is added to the pending set before its packet is submitted.

<a id="rst-packet-completion-callback"></a>

### Packet Completion Callback

The packet completion callback is executed once the underlying packet of a request has been completed. In case of an error completion, the corresponding request is completed with the error value provided in this callback.

On successful packet completion, further processing depends on the request. If the request expects a response, it is marked as transmitted and the request timeout is started. If the request does not expect a response, it is completed with success.

<a id="rst-data-received-callback"></a>

### Data-Received Callback

The data received callback notifies the request transport layer of data being received by the underlying packet transport layer via a data-type frame. In general, this is expected to be a command-type payload.

If the request ID of the command is one of the request IDs reserved for events (one to `SSH_NUM_EVENTS`, inclusively), it is forwarded to the event callback registered in the request transport layer. If the request ID indicates a response to a request, the respective request is looked up in the pending set and, if found and marked as transmitted, completed with success.

<a id="rst-timeout-reaper-1"></a>

### Timeout Reaper

The request-response-timeout is a per-request timeout for requests expecting a response. It is used to ensure that a request does not wait indefinitely on a response from the EC and is started after the underlying packet has been successfully completed.

This timeout is, similar to the packet acknowledgment timeout on the packet transport layer, handled via a dedicated reaper task. This task is essentially a work-item (re-)scheduled to run when the next request is set to time out. The work item then scans the set of pending requests for any requests that have timed out and completes them with `-ETIMEDOUT` as status. Requests will not be re-submitted automatically. Instead, the issuer of the request must construct and submit a new request, if so desired.

Note that this timeout, in combination with packet transmission and acknowledgment timeouts, guarantees that the request layer will always make progress, even if only through timing out packets, and never fully block.

<a id="rst-concurrency-and-locking-1"></a>

### Concurrency and Locking

Similar to the packet transport layer, there are two main locks in the request transport layer: One guarding access to the request queue and one guarding access to the pending set. These collections may only be accessed and modified under the respective lock.

Other parts of the request transport layer are guarded independently. State flags are (again) managed by atomic bit operations and, if necessary, memory barriers. Modifications to the timeout reaper work item and expiration date are guarded by their own lock.

Some request fields may be read outside of the respective locks guarding them, specifically the state for tracing. In those cases, proper access is ensured by employing `WRITE_ONCE()` and `READ_ONCE()`. Such read-only access is only allowed when stale values are not critical.

With respect to the interface for higher layers, request submission (`ssh_rtl_submit()`), request cancellation (`ssh_rtl_cancel()`), and layer shutdown (`ssh_rtl_shutdown()`) may always be executed concurrently with respect to each other. Note that request submission may not run concurrently with itself for the same request (and also may only be called once per request). Equally, shutdown may also not run concurrently with itself.

<a id="rst-controller-layer"></a>

## Controller Layer

The controller layer extends on the request transport layer to provide an easy-to-use interface for client drivers. It is represented by `struct ssam_controller <ssam_controller>` and the SSH driver. While the lower level transport layers take care of transmitting and handling packets and requests, the controller layer takes on more of a management role. Specifically, it handles device initialization, power management, and event handling, including event delivery and registration via the (event) completion system (`struct ssam_cplt <ssam_cplt>`).

<a id="rst-event-registration"></a>

### Event Registration

In general, an event (or rather a class of events) has to be explicitly requested by the host before the EC will send it (HID input events seem to be the exception). This is done via an event-enable request (similarly, events should be disabled via an event-disable request once no longer desired).

The specific request used to enable (or disable) an event is given via an event registry, i.e. the governing authority of this event (so to speak), represented by `struct ssam_event_registry <ssam_event_registry>`. As parameters to this request, the target category and, depending on the event registry, instance ID of the event to be enabled must be provided. This (optional) instance ID must be zero if the registry does not use it. Together, target category and instance ID form the event ID, represented by `struct ssam_event_id <ssam_event_id>`. In short, both, event registry and event ID, are required to uniquely identify a respective class of events.

Note that a further *request ID* parameter must be provided for the enable-event request. This parameter does not influence the class of events being enabled, but instead is set as the request ID (RQID) on each event of this class sent by the EC. It is used to identify events (as a limited number of request IDs is reserved for use in events only, specifically one to `SSH_NUM_EVENTS` inclusively) and also map events to their specific class. Currently, the controller always sets this parameter to the target category specified in `struct ssam_event_id <ssam_event_id>`.

As multiple client drivers may rely on the same (or overlapping) classes of events and enable/disable calls are strictly binary (i.e. on/off), the controller has to manage access to these events. It does so via reference counting, storing the counter inside an RB-tree based mapping with event registry and ID as key (there is no known list of valid event registry and event ID combinations). See `struct ssam_nf <ssam_nf>`, `ssam_nf_refcount_inc()`, and `ssam_nf_refcount_dec()` for details.

This management is done together with notifier registration (described in the next section) via the top-level `ssam_notifier_register()` and `ssam_notifier_unregister()` functions.

<a id="rst-event-delivery"></a>

### Event Delivery

To receive events, a client driver has to register an event notifier via `ssam_notifier_register()`. This increments the reference counter for that specific class of events (as detailed in the previous section), enables the class on the EC (if it has not been enabled already), and installs the provided notifier callback.

Notifier callbacks are stored in lists, with one (RCU) list per target category (provided via the event ID; NB: there is a fixed known number of target categories). There is no known association from the combination of event registry and event ID to the command data (target ID, target category, command ID, and instance ID) that can be provided by an event class, apart from target category and instance ID given via the event ID.

Note that due to the way notifiers are (or rather have to be) stored, client drivers may receive events that they have not requested and need to account for them. Specifically, they will, by default, receive all events from the same target category. To simplify dealing with this, filtering of events by target ID (provided via the event registry) and instance ID (provided via the event ID) can be requested when registering a notifier. This filtering is applied when iterating over the notifiers at the time they are executed.

All notifier callbacks are executed on a dedicated workqueue, the so-called completion workqueue. After an event has been received via the callback installed in the request layer (running on the receiver thread of the packet transport layer), it will be put on its respective event queue (`struct ssam_event_queue <ssam_event_queue>`). From this event queue the completion work item of that queue (running on the completion workqueue) will pick up the event and execute the notifier callback. This is done to avoid blocking on the receiver thread.

There is one event queue per combination of target ID and target category. This is done to ensure that notifier callbacks are executed in sequence for events of the same target ID and target category. Callbacks can be executed in parallel for events with a different combination of target ID and target category.

<a id="rst-concurrency-and-locking-2"></a>

### Concurrency and Locking

Most of the concurrency related safety guarantees of the controller are provided by the lower-level request transport layer. In addition to this, event (un-)registration is guarded by its own lock.

Access to the controller state is guarded by the state lock. This lock is a read/write semaphore. The reader part can be used to ensure that the state does not change while functions depending on the state to stay the same (e.g. `ssam_notifier_register()`, `ssam_notifier_unregister()`, `ssam_request_sync_submit()`, and derivatives) are executed and this guarantee is not already provided otherwise (e.g. through `ssam_client_bind()` or `ssam_client_link()`). The writer part guards any transitions that will change the state, i.e. initialization, destruction, suspension, and resumption.

The controller state may be accessed (read-only) outside the state lock for smoke-testing against invalid API usage (e.g. in `ssam_request_sync_submit()`). Note that such checks are not supposed to (and will not) protect against all invalid usages, but rather aim to help catch them. In those cases, proper variable access is ensured by employing `WRITE_ONCE()` and `READ_ONCE()`.

Assuming any preconditions on the state not changing have been satisfied, all non-initialization and non-shutdown functions may run concurrently with each other. This includes `ssam_notifier_register()`, `ssam_notifier_unregister()`, `ssam_request_sync_submit()`, as well as all functions building on top of those.

---

# Overview

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> The Surface/System Aggregator Module (SAM, SSAM) is an (arguably the) embedded controller (EC) on Microsoft Surface devices. It has been originally introduced on 4th generation devices (Surface Pro 4, Surface Book 1), but its…

<a id="rst-overview"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

The Surface/System Aggregator Module (SAM, SSAM) is an (arguably *the*) embedded controller (EC) on Microsoft Surface devices. It has been originally introduced on 4th generation devices (Surface Pro 4, Surface Book 1), but its responsibilities and feature-set have since been expanded significantly with the following generations.

<a id="rst-features-and-integration"></a>

## Features and Integration

Not much is currently known about SAM on 4th generation devices (Surface Pro 4, Surface Book 1), due to the use of a different communication interface between host and EC (as detailed below). On 5th (Surface Pro 2017, Surface Book 2, Surface Laptop 1) and later generation devices, SAM is responsible for providing battery information (both current status and static values, such as maximum capacity etc.), as well as an assortment of temperature sensors (e.g. skin temperature) and cooling/performance-mode setting to the host. On the Surface Book 2, specifically, it additionally provides an interface for properly handling clipboard detachment (i.e. separating the display part from the keyboard part of the device), on the Surface Laptop 1 and 2 it is required for keyboard HID input. This HID subsystem has been restructured for 7th generation devices and on those, specifically Surface Laptop 3 and Surface Book 3, is responsible for all major HID input (i.e. keyboard and touchpad).

While features have not changed much on a coarse level since the 5th generation, internal interfaces have undergone some rather large changes. On 5th and 6th generation devices, both battery and temperature information is exposed to ACPI via a shim driver (referred to as Surface ACPI Notify, or SAN), translating ACPI generic serial bus write-/read-accesses to SAM requests. On 7th generation devices, this additional layer is gone and these devices require a driver hooking directly into the SAM interface. Equally, on newer generations, less devices are declared in ACPI, making them a bit harder to discover and requiring us to hard-code a sort of device registry. Due to this, a SSAM bus and subsystem with client devices (`struct ssam_device <ssam_device>`) has been implemented.

<a id="rst-communication"></a>

## Communication

The type of communication interface between host and EC depends on the generation of the Surface device. On 4th generation devices, host and EC communicate via HID, specifically using a HID-over-I2C device, whereas on 5th and later generations, communication takes place via a USART serial device. In accordance to the drivers found on other operating systems, we refer to the serial device and its driver as Surface Serial Hub (SSH). When needed, we differentiate between both types of SAM by referring to them as SAM-over-SSH and SAM-over-HID.

Currently, this subsystem only supports SAM-over-SSH. The SSH communication interface is described in more detail below. The HID interface has not been reverse engineered yet and it is, at the moment, unclear how many (and which) concepts of the SSH interface detailed below can be transferred to it.

<a id="rst-surface-serial-hub"></a>

### Surface Serial Hub

As already elaborated above, the Surface Serial Hub (SSH) is the communication interface for SAM on 5th- and all later-generation Surface devices. On the highest level, communication can be separated into two main types: Requests, messages sent from host to EC that may trigger a direct response from the EC (explicitly associated with the request), and events (sometimes also referred to as notifications), sent from EC to host without being a direct response to a previous request. We may also refer to requests without response as commands. In general, events need to be enabled via one of multiple dedicated requests before they are sent by the EC.

See [Documentation/driver-api/surface_aggregator/ssh.rst](/kernel/hardware/driver-api/surface-aggregator/ssh.md) for a more technical protocol documentation and [Documentation/driver-api/surface_aggregator/internal.rst](/kernel/hardware/driver-api/surface-aggregator/internal.md) for an overview of the internal driver architecture.

---

# Surface Serial Hub Protocol

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> The Surface Serial Hub (SSH) is the central communication interface for the embedded Surface Aggregator Module controller (SAM or EC), found on newer Surface generations. We will refer to this protocol and interface as SAM-over-SSH, as…

<a id="rst-surface-serial-hub-protocol"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

The Surface Serial Hub (SSH) is the central communication interface for the embedded Surface Aggregator Module controller (SAM or EC), found on newer Surface generations. We will refer to this protocol and interface as SAM-over-SSH, as opposed to SAM-over-HID for the older generations.

On Surface devices with SAM-over-SSH, SAM is connected to the host via UART and defined in ACPI as device with ID `MSHW0084`. On these devices, significant functionality is provided via SAM, including access to battery and power information and events, thermal read-outs and events, and many more. For Surface Laptops, keyboard input is handled via HID directed through SAM, on the Surface Laptop 3 and Surface Book 3 this also includes touchpad input.

Note that the standard disclaimer for this subsystem also applies to this document: All of this has been reverse-engineered and may thus be erroneous and/or incomplete.

All CRCs used in the following are two-byte `crc_itu_t(0xffff, ...)`. All multi-byte values are little-endian, there is no implicit padding between values.

<a id="rst-ssh-packet-protocol-definitions"></a>

## SSH Packet Protocol: Definitions

The fundamental communication unit of the SSH protocol is a frame (`struct ssh_frame <ssh_frame>`). A frame consists of the following fields, packed together and in order:


<table>
<caption>SSH Frame</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Type

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`TYPE`

</td>
<td>


`u8 <u8>`

</td>
<td>


Type identifier of the frame.

</td>
</tr>
<tr>
<td>


`LEN`

</td>
<td>


`u16 <u16>`

</td>
<td>


Length of the payload associated with the frame.

</td>
</tr>
<tr>
<td>


`SEQ`

</td>
<td>


`u8 <u8>`

</td>
<td>


Sequence ID (see explanation below).

</td>
</tr>
</tbody>
</table>

Each frame structure is followed by a CRC over this structure. The CRC over the frame structure (`TYPE`, `LEN`, and `SEQ` fields) is placed directly after the frame structure and before the payload. The payload is followed by its own CRC (over all payload bytes). If the payload is not present (i.e. the frame has `LEN=0`), the CRC of the payload is still present and will evaluate to `0xffff`. The `LEN` field does not include any of the CRCs, it equals the number of bytes between the CRC of the frame and the CRC of the payload.

Additionally, the following fixed two-byte sequences are used:


<table>
<caption>SSH Byte Sequences</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`SYN`

</td>
<td>


`[0xAA, 0x55]`

</td>
<td>


Synchronization bytes.

</td>
</tr>
</tbody>
</table>

A message consists of `SYN`, followed by the frame (`TYPE`, `LEN`, `SEQ` and CRC) and, if specified in the frame (i.e. `LEN > 0`), payload bytes, followed finally, regardless if the payload is present, the payload CRC. The messages corresponding to an exchange are, in part, identified by having the same sequence ID (`SEQ`), stored inside the frame (more on this in the next section). The sequence ID is a wrapping counter.

A frame can have the following types (`enum ssh_frame_type <ssh_frame_type>`):


<table>
<caption>SSH Frame Types</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


Value

</th>
<th>


Short Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`NAK`

</td>
<td>


`0x04`

</td>
<td>


Sent on error in previously received message.

</td>
</tr>
<tr>
<td>


`ACK`

</td>
<td>


`0x40`

</td>
<td>


Sent to acknowledge receival of `DATA` frame.

</td>
</tr>
<tr>
<td>


`DATA_SEQ`

</td>
<td>


`0x80`

</td>
<td>


Sent to transfer data. Sequenced.

</td>
</tr>
<tr>
<td>


`DATA_NSQ`

</td>
<td>


`0x00`

</td>
<td>


Same as `DATA_SEQ`, but does not need to be ACKed.

</td>
</tr>
</tbody>
</table>

Both `NAK`- and `ACK`-type frames are used to control flow of messages and thus do not carry a payload. `DATA_SEQ`- and `DATA_NSQ`-type frames on the other hand must carry a payload. The flow sequence and interaction of different frame types will be described in more depth in the next section.

<a id="rst-ssh-packet-protocol-flow-sequence"></a>

## SSH Packet Protocol: Flow Sequence

Each exchange begins with `SYN`, followed by a `DATA_SEQ`- or `DATA_NSQ`-type frame, followed by its CRC, payload, and payload CRC. In case of a `DATA_NSQ`-type frame, the exchange is then finished. In case of a `DATA_SEQ`-type frame, the receiving party has to acknowledge receival of the frame by responding with a message containing an `ACK`-type frame with the same sequence ID of the `DATA` frame. In other words, the sequence ID of the `ACK` frame specifies the `DATA` frame to be acknowledged. In case of an error, e.g. an invalid CRC, the receiving party responds with a message containing an `NAK`-type frame. As the sequence ID of the previous data frame, for which an error is indicated via the `NAK` frame, cannot be relied upon, the sequence ID of the `NAK` frame should not be used and is set to zero. After receival of an `NAK` frame, the sending party should re-send all outstanding (non-ACKed) messages.

Sequence IDs are not synchronized between the two parties, meaning that they are managed independently for each party. Identifying the messages corresponding to a single exchange thus relies on the sequence ID as well as the type of the message, and the context. Specifically, the sequence ID is used to associate an `ACK` with its `DATA_SEQ`-type frame, but not `DATA_SEQ`- or `DATA_NSQ`-type frames with other `DATA`- type frames.

An example exchange might look like this:



```text
tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
rx: ------------------------------------- SYN FRAME(A) CRC(F) CRC(P) --
```

where both frames have the same sequence ID (`SEQ`). Here, `FRAME(D)` indicates a `DATA_SEQ`-type frame, `FRAME(A)` an `ACK`-type frame, `CRC(F)` the CRC over the previous frame, `CRC(P)` the CRC over the previous payload. In case of an error, the exchange would look like this:



```text
tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
rx: ------------------------------------- SYN FRAME(N) CRC(F) CRC(P) --
```

upon which the sender should re-send the message. `FRAME(N)` indicates an `NAK`-type frame. Note that the sequence ID of the `NAK`-type frame is fixed to zero. For `DATA_NSQ`-type frames, both exchanges are the same:



```text
tx: -- SYN FRAME(DATA_NSQ) CRC(F) PAYLOAD CRC(P) ----------------------
rx: -------------------------------------------------------------------
```

Here, an error can be detected, but not corrected or indicated to the sending party. These exchanges are symmetric, i.e. switching `rx` and `tx` results again in a valid exchange. Currently, no longer exchanges are known.

<a id="rst-commands-requests-responses-and-events"></a>

## Commands: Requests, Responses, and Events

Commands are sent as payload inside a data frame. Currently, this is the only known payload type of `DATA` frames, with a payload-type value of `0x80` (`SSH_PLD_TYPE_CMD <ssh_payload_type>`).

The command-type payload (`struct ssh_command <ssh_command>`) consists of an eight-byte command structure, followed by optional and variable length command data. The length of this optional data is derived from the frame payload length given in the corresponding frame, i.e. it is `frame.len - sizeof(struct ssh_command)`. The command struct contains the following fields, packed together and in order:


<table>
<caption>SSH Command</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Type

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`TYPE`

</td>
<td>


`u8 <u8>`

</td>
<td>


Type of the payload. For commands always `0x80`.

</td>
</tr>
<tr>
<td>


`TC`

</td>
<td>


`u8 <u8>`

</td>
<td>


Target category.

</td>
</tr>
<tr>
<td>


`TID`

</td>
<td>


`u8 <u8>`

</td>
<td>


Target ID for commands/messages.

</td>
</tr>
<tr>
<td>


`SID`

</td>
<td>


`u8 <u8>`

</td>
<td>


Source ID for commands/messages.

</td>
</tr>
<tr>
<td>


`IID`

</td>
<td>


`u8 <u8>`

</td>
<td>


Instance ID.

</td>
</tr>
<tr>
<td>


`RQID`

</td>
<td>


`u16 <u16>`

</td>
<td>


Request ID.

</td>
</tr>
<tr>
<td>


`CID`

</td>
<td>


`u8 <u8>`

</td>
<td>


Command ID.

</td>
</tr>
</tbody>
</table>

The command struct and data, in general, does not contain any failure detection mechanism (e.g. CRCs), this is solely done on the frame level.

Command-type payloads are used by the host to send commands and requests to the EC as well as by the EC to send responses and events back to the host. We differentiate between requests (sent by the host), responses (sent by the EC in response to a request), and events (sent by the EC without a preceding request).

Commands and events are uniquely identified by their target category (`TC`) and command ID (`CID`). The target category specifies a general category for the command (e.g. system in general, vs. battery and AC, vs. temperature, and so on), while the command ID specifies the command inside that category. Only the combination of `TC` + `CID` is unique. Additionally, commands have an instance ID (`IID`), which is used to differentiate between different sub-devices. For example `TC=3` `CID=1` is a request to get the temperature on a thermal sensor, where `IID` specifies the respective sensor. If the instance ID is not used, it should be set to zero. If instance IDs are used, they, in general, start with a value of one, whereas zero may be used for instance independent queries, if applicable. A response to a request should have the same target category, command ID, and instance ID as the corresponding request.

Responses are matched to their corresponding request via the request ID (`RQID`) field. This is a 16 bit wrapping counter similar to the sequence ID on the frames. Note that the sequence ID of the frames for a request-response pair does not match. Only the request ID has to match. Frame-protocol wise these are two separate exchanges, and may even be separated, e.g. by an event being sent after the request but before the response. Not all commands produce a response, and this is not detectable by `TC` + `CID`. It is the responsibility of the issuing party to wait for a response (or signal this to the communication framework, as is done in SAN/ACPI via the `SNC` flag).

Events are identified by unique and reserved request IDs. These IDs should not be used by the host when sending a new request. They are used on the host to, first, detect events and, second, match them with a registered event handler. Request IDs for events are chosen by the host and directed to the EC when setting up and enabling an event source (via the enable-event-source request). The EC then uses the specified request ID for events sent from the respective source. Note that an event should still be identified by its target category, command ID, and, if applicable, instance ID, as a single event source can send multiple different event types. In general, however, a single target category should map to a single reserved event request ID.

Furthermore, requests, responses, and events have an associated target ID (`TID`) and source ID (`SID`). These two fields indicate where a message originates from (`SID`) and what the intended target of the message is (`TID`). Note that a response to a specific request therefore has the source and target IDs swapped when compared to the original request (i.e. the request target is the response source and the request source is the response target). See (`enum ssh_request_id <ssh_request_id>`) for possible values of both.

Note that, even though requests and events should be uniquely identifiable by target category and command ID alone, the EC may require specific target ID and instance ID values to accept a command. A command that is accepted for `TID=1`, for example, may not be accepted for `TID=2` and vice versa. While this may not always hold in reality, you can think of different target/source IDs indicating different physical ECs with potentially different feature sets.

<a id="rst-limitations-and-observations"></a>

## Limitations and Observations

The protocol can, in theory, handle up to `U8_MAX` frames in parallel, with up to `U16_MAX` pending requests (neglecting request IDs reserved for events). In practice, however, this is more limited. From our testing (although via a python and thus a user-space program), it seems that the EC can handle up to four requests (mostly) reliably in parallel at a certain time. With five or more requests in parallel, consistent discarding of commands (ACKed frame but no command response) has been observed. For five simultaneous commands, this reproducibly resulted in one command being dropped and four commands being handled.

However, it has also been noted that, even with three requests in parallel, occasional frame drops happen. Apart from this, with a limit of three pending requests, no dropped commands (i.e. command being dropped but frame carrying command being ACKed) have been observed. In any case, frames (and possibly also commands) should be re-sent by the host if a certain timeout is exceeded. This is done by the EC for frames with a timeout of one second, up to two re-tries (i.e. three transmissions in total). The limit of re-tries also applies to received NAKs, and, in a worst case scenario, can lead to entire messages being dropped.

While this also seems to work fine for pending data frames as long as no transmission failures occur, implementation and handling of these seems to depend on the assumption that there is only one non-acknowledged data frame. In particular, the detection of repeated frames relies on the last sequence number. This means that, if a frame that has been successfully received by the EC is sent again, e.g. due to the host not receiving an `ACK`, the EC will only detect this if it has the sequence ID of the last frame received by the EC. As an example: Sending two frames with `SEQ=0` and `SEQ=1` followed by a repetition of `SEQ=0` will not detect the second `SEQ=0` frame as such, and thus execute the command in this frame each time it has been received, i.e. twice in this example. Sending `SEQ=0`, `SEQ=1` and then repeating `SEQ=1` will detect the second `SEQ=1` as repetition of the first one and ignore it, thus executing the contained command only once.

In conclusion, this suggests a limit of at most one pending un-ACKed frame (per party, effectively leading to synchronous communication regarding frames) and at most three pending commands. The limit to synchronous frame transfers seems to be consistent with behavior observed on Windows.

---

# Client Driver Documentation

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator: clients_

> This is the documentation for client drivers themselves. Refer to Documentation/driver-api/surface_aggregator/client.rst for documentation on how to write client drivers.

<a id="rst-client-driver-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

This is the documentation for client drivers themselves. Refer to [Documentation/driver-api/surface_aggregator/client.rst](/kernel/hardware/driver-api/surface-aggregator/client.md) for documentation on how to write client drivers.

- [User-Space EC Interface (cdev)](</kernel/hardware/driver-api/surface-aggregator-clients/cdev.md>)
- [User-Space DTX (Clipboard Detachment System) Interface](</kernel/hardware/driver-api/surface-aggregator-clients/dtx.md>)
- [Surface ACPI Notify](</kernel/hardware/driver-api/surface-aggregator-clients/san.md>)

---

# User-Space EC Interface (cdev)

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator: clients_

> The surface_aggregator_cdev module provides a misc-device for the SSAM controller to allow for a (more or less) direct connection from user-space to the SAM EC. It is intended to be used for development and debugging, and therefore should…

<a id="rst-user-space-ec-interface-cdev"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

The `surface_aggregator_cdev` module provides a misc-device for the SSAM controller to allow for a (more or less) direct connection from user-space to the SAM EC. It is intended to be used for development and debugging, and therefore should not be used or relied upon in any other way. Note that this module is not loaded automatically, but instead must be loaded manually.

The provided interface is accessible through the `/dev/surface/aggregator` device-file. All functionality of this interface is provided via IOCTLs. These IOCTLs and their respective input/output parameter structs are defined in `include/uapi/linux/surface_aggregator/cdev.h`.

A small python library and scripts for accessing this interface can be found at [https://github.com/linux-surface/surface-aggregator-module/tree/master/scripts/ssam](<https://github.com/linux-surface/surface-aggregator-module/tree/master/scripts/ssam>).

<a id="rst-contents"></a>



<a id="rst-receiving-events"></a>

## Receiving Events

Events can be received by reading from the device-file. The are represented by the `struct ssam_cdev_event <ssam_cdev_event>` datatype.

Before events are available to be read, however, the desired notifiers must be registered via the `SSAM_CDEV_NOTIF_REGISTER` IOCTL. Notifiers are, in essence, callbacks, called when the EC sends an event. They are, in this interface, associated with a specific target category and device-file-instance. They forward any event of this category to the buffer of the corresponding instance, from which it can then be read.

Notifiers themselves do not enable events on the EC. Thus, it may additionally be necessary to enable events via the `SSAM_CDEV_EVENT_ENABLE` IOCTL. While notifiers work per-client (i.e. per-device-file-instance), events are enabled globally, for the EC and all of its clients (regardless of userspace or non-userspace). The `SSAM_CDEV_EVENT_ENABLE` and `SSAM_CDEV_EVENT_DISABLE` IOCTLs take care of reference counting the events, such that an event is enabled as long as there is a client that has requested it.

Note that enabled events are not automatically disabled once the client instance is closed. Therefore any client process (or group of processes) should balance their event enable calls with the corresponding event disable calls. It is, however, perfectly valid to enable and disable events on different client instances. For example, it is valid to set up notifiers and read events on client instance `A`, enable those events on instance `B` (note that these will also be received by A since events are enabled/disabled globally), and after no more events are desired, disable the previously enabled events via instance `C`.

<a id="rst-controller-ioctls"></a>

## Controller IOCTLs

The following IOCTLs are provided:


<table>
<caption>Controller IOCTLs</caption>
<thead>
<tr>
<th>


Type

</th>
<th>


Number

</th>
<th>


Direction

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`0xA5`

</td>
<td>


`1`

</td>
<td>


`WR`

</td>
<td>


`REQUEST`

</td>
<td>


Perform synchronous SAM request.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`2`

</td>
<td>


`W`

</td>
<td>


`NOTIF_REGISTER`

</td>
<td>


Register event notifier.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`3`

</td>
<td>


`W`

</td>
<td>


`NOTIF_UNREGISTER`

</td>
<td>


Unregister event notifier.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`4`

</td>
<td>


`W`

</td>
<td>


`EVENT_ENABLE`

</td>
<td>


Enable event source.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`5`

</td>
<td>


`W`

</td>
<td>


`EVENT_DISABLE`

</td>
<td>


Disable event source.

</td>
</tr>
</tbody>
</table>

<a id="rst-ssam-cdev-request"></a>

### `SSAM_CDEV_REQUEST`

Defined as `_IOWR(0xA5, 1, struct ssam_cdev_request)`.

Executes a synchronous SAM request. The request specification is passed in as argument of type `struct ssam_cdev_request <ssam_cdev_request>`, which is then written to/modified by the IOCTL to return status and result of the request.

Request payload data must be allocated separately and is passed in via the `payload.data` and `payload.length` members. If a response is required, the response buffer must be allocated by the caller and passed in via the `response.data` member. The `response.length` member must be set to the capacity of this buffer, or if no response is required, zero. Upon completion of the request, the call will write the response to the response buffer (if its capacity allows it) and overwrite the length field with the actual size of the response, in bytes.

Additionally, if the request has a response, this must be indicated via the request flags, as is done with in-kernel requests. Request flags can be set via the `flags` member and the values correspond to the values found in `enum ssam_cdev_request_flags <ssam_cdev_request_flags>`.

Finally, the status of the request itself is returned in the `status` member (a negative errno value indicating failure). Note that failure indication of the IOCTL is separated from failure indication of the request: The IOCTL returns a negative status code if anything failed during setup of the request (`-EFAULT`) or if the provided argument or any of its fields are invalid (`-EINVAL`). In this case, the status value of the request argument may be set, providing more detail on what went wrong (e.g. `-ENOMEM` for out-of-memory), but this value may also be zero. The IOCTL will return with a zero status code in case the request has been set up, submitted, and completed (i.e. handed back to user-space) successfully from inside the IOCTL, but the request `status` member may still be negative in case the actual execution of the request failed after it has been submitted.

A full definition of the argument struct is provided below.

<a id="rst-ssam-cdev-notif-register"></a>

### `SSAM_CDEV_NOTIF_REGISTER`

Defined as `_IOW(0xA5, 2, struct ssam_cdev_notifier_desc)`.

Register a notifier for the event target category specified in the given notifier description with the specified priority. Notifiers registration is required to receive events, but does not enable events themselves. After a notifier for a specific target category has been registered, all events of that category will be forwarded to the userspace client and can then be read from the device file instance. Note that events may have to be enabled, e.g. via the `SSAM_CDEV_EVENT_ENABLE` IOCTL, before the EC will send them.

Only one notifier can be registered per target category and client instance. If a notifier has already been registered, this IOCTL will fail with `-EEXIST`.

Notifiers will automatically be removed when the device file instance is closed.

<a id="rst-ssam-cdev-notif-unregister"></a>

### `SSAM_CDEV_NOTIF_UNREGISTER`

Defined as `_IOW(0xA5, 3, struct ssam_cdev_notifier_desc)`.

Unregisters the notifier associated with the specified target category. The priority field will be ignored by this IOCTL. If no notifier has been registered for this client instance and the given category, this IOCTL will fail with `-ENOENT`.

<a id="rst-ssam-cdev-event-enable"></a>

### `SSAM_CDEV_EVENT_ENABLE`

Defined as `_IOW(0xA5, 4, struct ssam_cdev_event_desc)`.

Enable the event associated with the given event descriptor.

Note that this call will not register a notifier itself, it will only enable events on the controller. If you want to receive events by reading from the device file, you will need to register the corresponding notifier(s) on that instance.

Events are not automatically disabled when the device file is closed. This must be done manually, via a call to the `SSAM_CDEV_EVENT_DISABLE` IOCTL.

<a id="rst-ssam-cdev-event-disable"></a>

### `SSAM_CDEV_EVENT_DISABLE`

Defined as `_IOW(0xA5, 5, struct ssam_cdev_event_desc)`.

Disable the event associated with the given event descriptor.

Note that this will not unregister any notifiers. Events may still be received and forwarded to user-space after this call. The only safe way of stopping events from being received is unregistering all previously registered notifiers.

<a id="rst-structures-and-enums"></a>

## Structures and Enums


#### <a id="c-enum-ssam_cdev_request_flags"></a>`enum ssam_cdev_request_flags`

Request flags for SSAM cdev request IOCTL.

**Constants**

- `SSAM_CDEV_REQUEST_HAS_RESPONSE`: Specifies that the request expects a response. If not set, the request
  will be directly completed after its underlying packet has been
  transmitted. If set, the request transport system waits for a response
  of the request.
- `SSAM_CDEV_REQUEST_UNSEQUENCED`: Specifies that the request should be transmitted via an unsequenced
  packet. If set, the request must not have a response, meaning that this
  flag and the `SSAM_CDEV_REQUEST_HAS_RESPONSE` flag are mutually
  exclusive.

#### <a id="c-struct-ssam_cdev_request"></a>`struct ssam_cdev_request`

Controller request IOCTL argument.

**Definition**

```c
struct ssam_cdev_request {
    __u8 target_category;
    __u8 target_id;
    __u8 command_id;
    __u8 instance_id;
    __u16 flags;
    __s16 status;
    struct {
        __u64 data;
        __u16 length;
        __u8 __pad[6];
    } payload;
    struct {
        __u64 data;
        __u16 length;
        __u8 __pad[6];
    } response;
};
```

**Members**

- `target_category`: Target category of the SAM request.
- `target_id`: Target ID of the SAM request.
- `command_id`: Command ID of the SAM request.
- `instance_id`: Instance ID of the SAM request.
- `flags`: Request flags (see [`enum ssam_cdev_request_flags`](#c-enum-ssam_cdev_request_flags)).
- `status`: Request status (output).
- `payload`: Request payload (input data).
- `payload.data`: Pointer to request payload data.
- `payload.length`: Length of request payload data (in bytes).
- `response`: Request response (output data).
- `response.data`: Pointer to response buffer.
- `response.length`: On input: Capacity of response buffer (in bytes).
  On output: Length of request response (number of bytes
  in the buffer that are actually used).

#### <a id="c-struct-ssam_cdev_notifier_desc"></a>`struct ssam_cdev_notifier_desc`

Notifier descriptor.

**Definition**

```c
struct ssam_cdev_notifier_desc {
    __s32 priority;
    __u8 target_category;
};
```

**Members**

- `priority`: Priority value determining the order in which notifier
  callbacks will be called. A higher value means higher
  priority, i.e. the associated callback will be executed
  earlier than other (lower priority) callbacks.
- `target_category`: The event target category for which this notifier should
  receive events.

**Description**

Specifies the notifier that should be registered or unregistered,
specifically with which priority and for which target category of events.

#### <a id="c-struct-ssam_cdev_event_desc"></a>`struct ssam_cdev_event_desc`

Event descriptor.

**Definition**

```c
struct ssam_cdev_event_desc {
    struct {
        __u8 target_category;
        __u8 target_id;
        __u8 cid_enable;
        __u8 cid_disable;
    } reg;
    struct {
        __u8 target_category;
        __u8 instance;
    } id;
    __u8 flags;
};
```

**Members**

- `reg`: Registry via which the event will be enabled/disabled.
- `reg.target_category`: Target category for the event registry requests.
- `reg.target_id`: Target ID for the event registry requests.
- `reg.cid_enable`: Command ID for the event-enable request.
- `reg.cid_disable`: Command ID for the event-disable request.
- `id`: ID specifying the event.
- `id.target_category`: Target category of the event source.
- `id.instance`: Instance ID of the event source.
- `flags`: Flags used for enabling the event.

**Description**

Specifies which event should be enabled/disabled and how to do that.

#### <a id="c-struct-ssam_cdev_event"></a>`struct ssam_cdev_event`

SSAM event sent by the EC.

**Definition**

```c
struct ssam_cdev_event {
    __u8 target_category;
    __u8 target_id;
    __u8 command_id;
    __u8 instance_id;
    __u16 length;
    __u8 data[];
};
```

**Members**

- `target_category`: Target category of the event source. See `enum ssam_ssh_tc`.
- `target_id`: Target ID of the event source.
- `command_id`: Command ID of the event.
- `instance_id`: Instance ID of the event source.
- `length`: Length of the event payload in bytes.
- `data`: Event payload data.

---

# User-Space DTX (Clipboard Detachment System) Interface

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator: clients_

> The surface_dtx driver is responsible for proper clipboard detachment and re-attachment handling. To this end, it provides the /dev/surface/dtx device file, through which it can interface with a user-space daemon. This daemon is then…

<a id="rst-user-space-dtx-clipboard-detachment-system-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

The `surface_dtx` driver is responsible for proper clipboard detachment and re-attachment handling. To this end, it provides the `/dev/surface/dtx` device file, through which it can interface with a user-space daemon. This daemon is then ultimately responsible for determining and taking necessary actions, such as unmounting devices attached to the base, unloading/reloading the graphics-driver, user-notifications, etc.

There are two basic communication principles used in this driver: Commands (in other parts of the documentation also referred to as requests) and events. Commands are sent to the EC and may have a different implications in different contexts. Events are sent by the EC upon some internal state change. Commands are always driver-initiated, whereas events are always initiated by the EC.

<a id="rst-contents"></a>



<a id="rst-nomenclature"></a>

## Nomenclature

- **Clipboard:** The detachable upper part of the Surface Book, housing the screen and CPU.

- **Base:** The lower part of the Surface Book from which the clipboard can be detached, optionally (model dependent) housing the discrete GPU (dGPU).

- **Latch:** The mechanism keeping the clipboard attached to the base in normal operation and allowing it to be detached when requested.

- **Silently ignored commands:** The command is accepted by the EC as a valid command and acknowledged (following the standard communication protocol), but the EC does not act upon it, i.e. ignores it.e upper part of the

<a id="rst-detachment-process"></a>

## Detachment Process

Warning: This part of the documentation is based on reverse engineering and testing and thus may contain errors or be incomplete.

<a id="rst-latch-states"></a>

### Latch States

The latch mechanism has two major states: *open* and *closed*. In the *closed* state (default), the clipboard is secured to the base, whereas in the *open* state, the clipboard can be removed by a user.

The latch can additionally be locked and, correspondingly, unlocked, which can influence the detachment procedure. Specifically, this locking mechanism is intended to prevent the dGPU, positioned in the base of the device, from being hot-unplugged while in use. More details can be found in the documentation for the detachment procedure below. By default, the latch is unlocked.

<a id="rst-detachment-procedure"></a>

### Detachment Procedure

Note that the detachment process is governed fully by the EC. The `surface_dtx` driver only relays events from the EC to user-space and commands from user-space to the EC, i.e. it does not influence this process.

The detachment process is started with the user pressing the *detach* button on the base of the device or executing the `SDTX_IOCTL_LATCH_REQUEST` IOCTL. Following that:

1. The EC turns on the indicator led on the detach-button, sends a *detach-request* event (`SDTX_EVENT_REQUEST`), and awaits further instructions/commands. In case the latch is unlocked, the led will flash green. If the latch has been locked, the led will be solid red

2. The event is, via the `surface_dtx` driver, relayed to user-space, where an appropriate user-space daemon can handle it and send instructions back to the EC via IOCTLs provided by this driver.

3. The EC waits for instructions from user-space and acts according to them. If the EC does not receive any instructions in a given period, it will time out and continue as follows:

   - If the latch is unlocked, the EC will open the latch and the clipboard can be detached from the base. This is the exact behavior as without this driver or any user-space daemon. See the `SDTX_IOCTL_LATCH_CONFIRM` description below for more details on the follow-up behavior of the EC.

   - If the latch is locked, the EC will *not* open the latch, meaning the clipboard cannot be detached from the base. Furthermore, the EC sends an cancel event (`SDTX_EVENT_CANCEL`) detailing this with the cancel reason `SDTX_DETACH_TIMEDOUT` (see [Events](<#rst-events-1>) for details).

Valid responses by a user-space daemon to a detachment request event are:

- Execute `SDTX_IOCTL_LATCH_REQUEST`. This will immediately abort the detachment process. Furthermore, the EC will send a detach-request event, similar to the user pressing the detach-button to cancel said process (see below).

- Execute `SDTX_IOCTL_LATCH_CONFIRM`. This will cause the EC to open the latch, after which the user can separate clipboard and base.

  As this changes the latch state, a *latch-status* event (`SDTX_EVENT_LATCH_STATUS`) will be sent once the latch has been opened successfully. If the EC fails to open the latch, e.g. due to hardware error or low battery, a latch-cancel event (`SDTX_EVENT_CANCEL`) will be sent with the cancel reason indicating the specific failure.

  If the latch is currently locked, the latch will automatically be unlocked before it is opened.

- Execute `SDTX_IOCTL_LATCH_HEARTBEAT`. This will reset the internal timeout. No other actions will be performed, i.e. the detachment process will neither be completed nor canceled, and the EC will still be waiting for further responses.

- Execute `SDTX_IOCTL_LATCH_CANCEL`. This will abort the detachment process, similar to `SDTX_IOCTL_LATCH_REQUEST`, described above, or the button press, described below. A *generic request* event (`SDTX_EVENT_REQUEST`) is send in response to this. In contrast to those, however, this command does not trigger a new detachment process if none is currently in progress.

- Do nothing. The detachment process eventually times out as described in point 3.

See [IOCTLs](<#rst-ioctls-1>) for more details on these responses.

It is important to note that, if the user presses the detach button at any point when a detachment operation is in progress (i.e. after the EC has sent the initial *detach-request* event (`SDTX_EVENT_REQUEST`) and before it received the corresponding response concluding the process), the detachment process is canceled on the EC-level and an identical event is being sent. Thus a *detach-request* event, by itself, does not signal the start of the detachment process.

The detachment process may further be canceled by the EC due to hardware failures or a low clipboard battery. This is done via a cancel event (`SDTX_EVENT_CANCEL`) with the corresponding cancel reason.

<a id="rst-user-space-interface-documentation"></a>

## User-Space Interface Documentation

<a id="rst-error-codes-and-status-values"></a>

### Error Codes and Status Values

Error and status codes are divided into different categories, which can be used to determine if the status code is an error, and, if it is, the severity and type of that error. The current categories are:


<table>
<caption>Overview of Status/Error Categories.</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


Value

</th>
<th>


Short Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`STATUS`

</td>
<td>


`0x0000`

</td>
<td>


Non-error status codes.

</td>
</tr>
<tr>
<td>


`RUNTIME_ERROR`

</td>
<td>


`0x1000`

</td>
<td>


Non-critical runtime errors.

</td>
</tr>
<tr>
<td>


`HARDWARE_ERROR`

</td>
<td>


`0x2000`

</td>
<td>


Critical hardware failures.

</td>
</tr>
<tr>
<td>


`UNKNOWN`

</td>
<td>


`0xF000`

</td>
<td>


Unknown error codes.

</td>
</tr>
</tbody>
</table>

Other categories are reserved for future use. The `SDTX_CATEGORY()` macro can be used to determine the category of any status value. The `SDTX_SUCCESS()` macro can be used to check if the status value is a success value (`SDTX_CATEGORY_STATUS`) or if it indicates a failure.

Unknown status or error codes sent by the EC are assigned to the `UNKNOWN` category by the driver and may be implemented via their own code in the future.

Currently used error codes are:


<table>
<caption>Overview of Error Codes.</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


Category

</th>
<th>


Value

</th>
<th>


Short Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`SDTX_DETACH_NOT_FEASIBLE`

</td>
<td>


`RUNTIME`

</td>
<td>


`0x1001`

</td>
<td>


Detachment not feasible due to low clipboard battery.

</td>
</tr>
<tr>
<td>


`SDTX_DETACH_TIMEDOUT`

</td>
<td>


`RUNTIME`

</td>
<td>


`0x1002`

</td>
<td>


Detachment process timed out while the latch was locked.

</td>
</tr>
<tr>
<td>


`SDTX_ERR_FAILED_TO_OPEN`

</td>
<td>


`HARDWARE`

</td>
<td>


`0x2001`

</td>
<td>


Failed to open latch.

</td>
</tr>
<tr>
<td>


`SDTX_ERR_FAILED_TO_REMAIN_OPEN`

</td>
<td>


`HARDWARE`

</td>
<td>


`0x2002`

</td>
<td>


Failed to keep latch open.

</td>
</tr>
<tr>
<td>


`SDTX_ERR_FAILED_TO_CLOSE`

</td>
<td>


`HARDWARE`

</td>
<td>


`0x2003`

</td>
<td>


Failed to close latch.

</td>
</tr>
</tbody>
</table>

Other error codes are reserved for future use. Non-error status codes may overlap and are generally only unique within their use-case:


<table>
<caption>Latch Status Codes.</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


Category

</th>
<th>


Value

</th>
<th>


Short Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`SDTX_LATCH_CLOSED`

</td>
<td>


`STATUS`

</td>
<td>


`0x0000`

</td>
<td>


Latch is closed/has been closed.

</td>
</tr>
<tr>
<td>


`SDTX_LATCH_OPENED`

</td>
<td>


`STATUS`

</td>
<td>


`0x0001`

</td>
<td>


Latch is open/has been opened.

</td>
</tr>
</tbody>
</table>


<table>
<caption>Base State Codes.</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


Category

</th>
<th>


Value

</th>
<th>


Short Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`SDTX_BASE_DETACHED`

</td>
<td>


`STATUS`

</td>
<td>


`0x0000`

</td>
<td>


Base has been detached/is not present.

</td>
</tr>
<tr>
<td>


`SDTX_BASE_ATTACHED`

</td>
<td>


`STATUS`

</td>
<td>


`0x0001`

</td>
<td>


Base has been attached/is present.

</td>
</tr>
</tbody>
</table>

Again, other codes are reserved for future use.

<a id="rst-events-1"></a>
<a id="rst-events"></a>

### Events

Events can be received by reading from the device file. They are disabled by default and have to be enabled by executing `SDTX_IOCTL_EVENTS_ENABLE` first. All events follow the layout prescribed by `struct sdtx_event <sdtx_event>`. Specific event types can be identified by their event code, described in `enum sdtx_event_code <sdtx_event_code>`. Note that other event codes are reserved for future use, thus an event parser must be able to handle any unknown/unsupported event types gracefully, by relying on the payload length given in the event header.

Currently provided event types are:


<table>
<caption>Overview of DTX events.</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


Code

</th>
<th>


Payload

</th>
<th>


Short Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`SDTX_EVENT_REQUEST`

</td>
<td>


`1`

</td>
<td>


`0` bytes

</td>
<td>


Detachment process initiated/aborted.

</td>
</tr>
<tr>
<td>


`SDTX_EVENT_CANCEL`

</td>
<td>


`2`

</td>
<td>


`2` bytes

</td>
<td>


EC canceled detachment process.

</td>
</tr>
<tr>
<td>


`SDTX_EVENT_BASE_CONNECTION`

</td>
<td>


`3`

</td>
<td>


`4` bytes

</td>
<td>


Base connection state changed.

</td>
</tr>
<tr>
<td>


`SDTX_EVENT_LATCH_STATUS`

</td>
<td>


`4`

</td>
<td>


`2` bytes

</td>
<td>


Latch status changed.

</td>
</tr>
<tr>
<td>


`SDTX_EVENT_DEVICE_MODE`

</td>
<td>


`5`

</td>
<td>


`2` bytes

</td>
<td>


Device mode changed.

</td>
</tr>
</tbody>
</table>

Individual events in more detail:

<a id="rst-sdtx-event-request"></a>

#### `SDTX_EVENT_REQUEST`

Sent when a detachment process is started or, if in progress, aborted by the user, either via a detach button press or a detach request (`SDTX_IOCTL_LATCH_REQUEST`) being sent from user-space.

Does not have any payload.

<a id="rst-sdtx-event-cancel"></a>

#### `SDTX_EVENT_CANCEL`

Sent when a detachment process is canceled by the EC due to unfulfilled preconditions (e.g. clipboard battery too low to detach) or hardware failure. The reason for cancellation is given in the event payload detailed below and can be one of

- `SDTX_DETACH_TIMEDOUT`: Detachment timed out while the latch was locked. The latch has neither been opened nor unlocked.

- `SDTX_DETACH_NOT_FEASIBLE`: Detachment not feasible due to low clipboard battery.

- `SDTX_ERR_FAILED_TO_OPEN`: Could not open the latch (hardware failure).

- `SDTX_ERR_FAILED_TO_REMAIN_OPEN`: Could not keep the latch open (hardware failure).

- `SDTX_ERR_FAILED_TO_CLOSE`: Could not close the latch (hardware failure).

Other error codes in this context are reserved for future use.

These codes can be classified via the `SDTX_CATEGORY()` macro to discern between critical hardware errors (`SDTX_CATEGORY_HARDWARE_ERROR`) or runtime errors (`SDTX_CATEGORY_RUNTIME_ERROR`), the latter of which may happen during normal operation if certain preconditions for detachment are not given.


<table>
<caption>Detachment Cancel Event Payload</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Type

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`reason`

</td>
<td>


`__u16 <__u16>`

</td>
<td>


Reason for cancellation.

</td>
</tr>
</tbody>
</table>

<a id="rst-sdtx-event-base-connection"></a>

#### `SDTX_EVENT_BASE_CONNECTION`

Sent when the base connection state has changed, i.e. when the base has been attached, detached, or detachment has become infeasible due to low clipboard battery. The new state and, if a base is connected, ID of the base is provided as payload of type `struct sdtx_base_info <sdtx_base_info>` with its layout presented below:


<table>
<caption>Base-Connection-Change Event Payload</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Type

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`state`

</td>
<td>


`__u16 <__u16>`

</td>
<td>


Base connection state.

</td>
</tr>
<tr>
<td>


`base_id`

</td>
<td>


`__u16 <__u16>`

</td>
<td>


Type of base connected (zero if none).

</td>
</tr>
</tbody>
</table>

Possible values for `state` are:

- `SDTX_BASE_DETACHED`,

- `SDTX_BASE_ATTACHED`, and

- `SDTX_DETACH_NOT_FEASIBLE`.

Other values are reserved for future use.

<a id="rst-sdtx-event-latch-status"></a>

#### `SDTX_EVENT_LATCH_STATUS`

Sent when the latch status has changed, i.e. when the latch has been opened, closed, or an error occurred. The current status is provided as payload:


<table>
<caption>Latch-Status-Change Event Payload</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Type

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`status`

</td>
<td>


`__u16 <__u16>`

</td>
<td>


Latch status.

</td>
</tr>
</tbody>
</table>

Possible values for `status` are:

- `SDTX_LATCH_CLOSED`,

- `SDTX_LATCH_OPENED`,

- `SDTX_ERR_FAILED_TO_OPEN`,

- `SDTX_ERR_FAILED_TO_REMAIN_OPEN`, and

- `SDTX_ERR_FAILED_TO_CLOSE`.

Other values are reserved for future use.

<a id="rst-sdtx-event-device-mode"></a>

#### `SDTX_EVENT_DEVICE_MODE`

Sent when the device mode has changed. The new device mode is provided as payload:


<table>
<caption>Device-Mode-Change Event Payload</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Type

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`mode`

</td>
<td>


`__u16 <__u16>`

</td>
<td>


Device operation mode.

</td>
</tr>
</tbody>
</table>

Possible values for `mode` are:

- `SDTX_DEVICE_MODE_TABLET`,

- `SDTX_DEVICE_MODE_LAPTOP`, and

- `SDTX_DEVICE_MODE_STUDIO`.

Other values are reserved for future use.

<a id="rst-ioctls-1"></a>
<a id="rst-ioctls"></a>

### IOCTLs

The following IOCTLs are provided:


<table>
<caption>Overview of DTX IOCTLs</caption>
<thead>
<tr>
<th>


Type

</th>
<th>


Number

</th>
<th>


Direction

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`0xA5`

</td>
<td>


`0x21`

</td>
<td>


`-`

</td>
<td>


`EVENTS_ENABLE`

</td>
<td>


Enable events for the current file descriptor.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x22`

</td>
<td>


`-`

</td>
<td>


`EVENTS_DISABLE`

</td>
<td>


Disable events for the current file descriptor.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x23`

</td>
<td>


`-`

</td>
<td>


`LATCH_LOCK`

</td>
<td>


Lock the latch.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x24`

</td>
<td>


`-`

</td>
<td>


`LATCH_UNLOCK`

</td>
<td>


Unlock the latch.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x25`

</td>
<td>


`-`

</td>
<td>


`LATCH_REQUEST`

</td>
<td>


Request clipboard detachment.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x26`

</td>
<td>


`-`

</td>
<td>


`LATCH_CONFIRM`

</td>
<td>


Confirm clipboard detachment request.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x27`

</td>
<td>


`-`

</td>
<td>


`LATCH_HEARTBEAT`

</td>
<td>


Send heartbeat signal to EC.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x28`

</td>
<td>


`-`

</td>
<td>


`LATCH_CANCEL`

</td>
<td>


Cancel detachment process.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x29`

</td>
<td>


`R`

</td>
<td>


`GET_BASE_INFO`

</td>
<td>


Get current base/connection information.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x2A`

</td>
<td>


`R`

</td>
<td>


`GET_DEVICE_MODE`

</td>
<td>


Get current device operation mode.

</td>
</tr>
<tr>
<td>


`0xA5`

</td>
<td>


`0x2B`

</td>
<td>


`R`

</td>
<td>


`GET_LATCH_STATUS`

</td>
<td>


Get current device latch status.

</td>
</tr>
</tbody>
</table>

<a id="rst-sdtx-ioctl-events-enable"></a>

#### `SDTX_IOCTL_EVENTS_ENABLE`

Defined as `_IO(0xA5, 0x22)`.

Enable events for the current file descriptor. Events can be obtained by reading from the device, if enabled. Events are disabled by default.

<a id="rst-sdtx-ioctl-events-disable"></a>

#### `SDTX_IOCTL_EVENTS_DISABLE`

Defined as `_IO(0xA5, 0x22)`.

Disable events for the current file descriptor. Events can be obtained by reading from the device, if enabled. Events are disabled by default.

<a id="rst-sdtx-ioctl-latch-lock"></a>

#### `SDTX_IOCTL_LATCH_LOCK`

Defined as `_IO(0xA5, 0x23)`.

Locks the latch, causing the detachment procedure to abort without opening the latch on timeout. The latch is unlocked by default. This command will be silently ignored if the latch is already locked.

<a id="rst-sdtx-ioctl-latch-unlock"></a>

#### `SDTX_IOCTL_LATCH_UNLOCK`

Defined as `_IO(0xA5, 0x24)`.

Unlocks the latch, causing the detachment procedure to open the latch on timeout. The latch is unlocked by default. This command will not open the latch when sent during an ongoing detachment process. It will be silently ignored if the latch is already unlocked.

<a id="rst-sdtx-ioctl-latch-request"></a>

#### `SDTX_IOCTL_LATCH_REQUEST`

Defined as `_IO(0xA5, 0x25)`.

Generic latch request. Behavior depends on the context: If no detachment-process is active, detachment is requested. Otherwise the currently active detachment-process will be aborted.

If a detachment process is canceled by this operation, a generic detachment request event (`SDTX_EVENT_REQUEST`) will be sent.

This essentially behaves the same as a detachment button press.

<a id="rst-sdtx-ioctl-latch-confirm"></a>

#### `SDTX_IOCTL_LATCH_CONFIRM`

Defined as `_IO(0xA5, 0x26)`.

Acknowledges and confirms a latch request. If sent during an ongoing detachment process, this command causes the latch to be opened immediately. The latch will also be opened if it has been locked. In this case, the latch lock is reset to the unlocked state.

This command will be silently ignored if there is currently no detachment procedure in progress.

<a id="rst-sdtx-ioctl-latch-heartbeat"></a>

#### `SDTX_IOCTL_LATCH_HEARTBEAT`

Defined as `_IO(0xA5, 0x27)`.

Sends a heartbeat, essentially resetting the detachment timeout. This command can be used to keep the detachment process alive while work required for the detachment to succeed is still in progress.

This command will be silently ignored if there is currently no detachment procedure in progress.

<a id="rst-sdtx-ioctl-latch-cancel"></a>

#### `SDTX_IOCTL_LATCH_CANCEL`

Defined as `_IO(0xA5, 0x28)`.

Cancels detachment in progress (if any). If a detachment process is canceled by this operation, a generic detachment request event (`SDTX_EVENT_REQUEST`) will be sent.

This command will be silently ignored if there is currently no detachment procedure in progress.

<a id="rst-sdtx-ioctl-get-base-info"></a>

#### `SDTX_IOCTL_GET_BASE_INFO`

Defined as `_IOR(0xA5, 0x29, struct sdtx_base_info)`.

Get the current base connection state (i.e. attached/detached) and the type of the base connected to the clipboard. This is command essentially provides a way to query the information provided by the base connection change event (`SDTX_EVENT_BASE_CONNECTION`).

Possible values for `struct sdtx_base_info.state` are:

- `SDTX_BASE_DETACHED`,

- `SDTX_BASE_ATTACHED`, and

- `SDTX_DETACH_NOT_FEASIBLE`.

Other values are reserved for future use.

<a id="rst-sdtx-ioctl-get-device-mode"></a>

#### `SDTX_IOCTL_GET_DEVICE_MODE`

Defined as `_IOR(0xA5, 0x2A, __u16)`.

Returns the device operation mode, indicating if and how the base is attached to the clipboard. This is command essentially provides a way to query the information provided by the device mode change event (`SDTX_EVENT_DEVICE_MODE`).

Returned values are:

- `SDTX_DEVICE_MODE_LAPTOP`

- `SDTX_DEVICE_MODE_TABLET`

- `SDTX_DEVICE_MODE_STUDIO`

See `struct sdtx_device_mode <sdtx_device_mode>` for details. Other values are reserved for future use.

<a id="rst-sdtx-ioctl-get-latch-status"></a>

#### `SDTX_IOCTL_GET_LATCH_STATUS`

Defined as `_IOR(0xA5, 0x2B, __u16)`.

Get the current latch status or (presumably) the last error encountered when trying to open/close the latch. This is command essentially provides a way to query the information provided by the latch status change event (`SDTX_EVENT_LATCH_STATUS`).

Returned values are:

- `SDTX_LATCH_CLOSED`,

- `SDTX_LATCH_OPENED`,

- `SDTX_ERR_FAILED_TO_OPEN`,

- `SDTX_ERR_FAILED_TO_REMAIN_OPEN`, and

- `SDTX_ERR_FAILED_TO_CLOSE`.

Other values are reserved for future use.

<a id="rst-a-note-on-base-ids"></a>

### A Note on Base IDs

Base types/IDs provided via `SDTX_EVENT_BASE_CONNECTION` or `SDTX_IOCTL_GET_BASE_INFO` are directly forwarded from the EC in the lower byte of the combined `__u16 <__u16>` value, with the driver storing the EC type from which this ID comes in the high byte (without this, base IDs over different types of ECs may be overlapping).

The `SDTX_DEVICE_TYPE()` macro can be used to determine the EC device type. This can be one of

- `SDTX_DEVICE_TYPE_HID`, for Surface Aggregator Module over HID, and

- `SDTX_DEVICE_TYPE_SSH`, for Surface Aggregator Module over Surface Serial Hub.

Note that currently only the `SSH` type EC is supported, however `HID` type is reserved for future use.

<a id="rst-structures-and-enums"></a>

### Structures and Enums


#### <a id="c-enum-sdtx_device_mode"></a>`enum sdtx_device_mode`

Mode describing how (and if) the clipboard is attached to the base of the device.

**Constants**

- `SDTX_DEVICE_MODE_TABLET`: The clipboard is detached from the base and the
  device operates as tablet.
- `SDTX_DEVICE_MODE_LAPTOP`: The clipboard is attached normally to the base
  and the device operates as laptop.
- `SDTX_DEVICE_MODE_STUDIO`: The clipboard is attached to the base in reverse.
  The device operates as tablet with keyboard and
  touchpad deactivated, however, the base battery
  and, if present in the specific device model, dGPU
  are available to the system.

#### <a id="c-struct-sdtx_event"></a>`struct sdtx_event`

Event provided by reading from the DTX device file.

**Definition**

```c
struct sdtx_event {
    __u16 length;
    __u16 code;
    __u8 data[];
};
```

**Members**

- `length`: Length of the event payload, in bytes.
- `code`: Event code, detailing what type of event this is.
- `data`: Payload of the event, containing **length** bytes.

**Description**

See [`enum sdtx_event_code`](#c-enum-sdtx_event_code) for currently valid event codes.

#### <a id="c-enum-sdtx_event_code"></a>`enum sdtx_event_code`

Code describing the type of an event.

**Constants**

- `SDTX_EVENT_REQUEST`: Detachment request event type.
- `SDTX_EVENT_CANCEL`: Cancel detachment process event type.
- `SDTX_EVENT_BASE_CONNECTION`: Base/clipboard connection change event type.
- `SDTX_EVENT_LATCH_STATUS`: Latch status change event type.
- `SDTX_EVENT_DEVICE_MODE`: Device mode change event type.

**Description**

Used in [`struct sdtx_event`](#c-struct-sdtx_event) to describe the type of the event. Further event
codes are reserved for future use. Any event parser should be able to
gracefully handle unknown events, i.e. by simply skipping them.

Consult the DTX user-space interface documentation for details regarding
the individual event types.

#### <a id="c-struct-sdtx_base_info"></a>`struct sdtx_base_info`

Describes if and what type of base is connected.

**Definition**

```c
struct sdtx_base_info {
    __u16 state;
    __u16 base_id;
};
```

**Members**

- `state`: The state of the connection. Valid values are `SDTX_BASE_DETACHED`,
  `SDTX_BASE_ATTACHED`, and `SDTX_DETACH_NOT_FEASIBLE` (in case a base
  is attached but low clipboard battery prevents detachment). Other
  values are currently reserved.
- `base_id`: The type of base connected. Zero if no base is connected.


<a id="rst-api-users"></a>

## API Users

A user-space daemon utilizing this API can be found at [https://github.com/linux-surface/surface-dtx-daemon](<https://github.com/linux-surface/surface-dtx-daemon>).

---

# Surface ACPI Notify

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator: clients_

> The Surface ACPI Notify (SAN) device provides the bridge between ACPI and SAM controller. Specifically, ACPI code can execute requests and handle battery and thermal events via this interface. In addition to this, events relating to the…

<a id="rst-surface-acpi-notify"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

The Surface ACPI Notify (SAN) device provides the bridge between ACPI and SAM controller. Specifically, ACPI code can execute requests and handle battery and thermal events via this interface. In addition to this, events relating to the discrete GPU (dGPU) of the Surface Book 2 can be sent from ACPI code (note: the Surface Book 3 uses a different method for this). The only currently known event sent via this interface is a dGPU power-on notification. While this driver handles the former part internally, it only relays the dGPU events to any other driver interested via its public API and does not handle them.

The public interface of this driver is split into two parts: Client registration and notifier-block registration.

A client to the SAN interface can be linked as consumer to the SAN device via `san_client_link()`. This can be used to ensure that the a client receiving dGPU events does not miss any events due to the SAN interface not being set up as this forces the client driver to unbind once the SAN driver is unbound.

Notifier-blocks can be registered by any device for as long as the module is loaded, regardless of being linked as client or not. Registration is done with `san_dgpu_notifier_register()`. If the notifier is not needed any more, it should be unregistered via `san_dgpu_notifier_unregister()`.

Consult the API documentation below for more details.

<a id="rst-api-documentation"></a>

## API Documentation


#### <a id="c-struct-san_dgpu_event"></a>`struct san_dgpu_event`

Discrete GPU ACPI event.

**Definition**

```c
struct san_dgpu_event {
    u8 category;
    u8 target;
    u8 command;
    u8 instance;
    u16 length;
    u8 *payload;
};
```

**Members**

- `category`: Category of the event.
- `target`: Target ID of the event source.
- `command`: Command ID of the event.
- `instance`: Instance ID of the event source.
- `length`: Length of the event's payload data (in bytes).
- `payload`: Pointer to the event's payload data.



#### <a id="c-san_client_link"></a>`san_client_link()`

```c
int san_client_link(struct device *client)
```

Link client as consumer to SAN device.

**Parameters**

- `struct device *client`: The client to link.

**Description**

Sets up a device link between the provided client device as consumer and
the SAN device as provider. This function can be used to ensure that the
SAN interface has been set up and will be set up for as long as the driver
of the client device is bound. This guarantees that, during that time, all
dGPU events will be received by any registered notifier.

The link will be automatically removed once the client device's driver is
unbound.

**Return**

Returns zero on success, `-ENXIO` if the SAN interface has not been
set up yet, and `-ENOMEM` if device link creation failed.

#### <a id="c-san_dgpu_notifier_register"></a>`san_dgpu_notifier_register()`

```c
int san_dgpu_notifier_register(struct notifier_block *nb)
```

Register a SAN dGPU notifier.

**Parameters**

- `struct notifier_block *nb`: The notifier-block to register.

**Description**

Registers a SAN dGPU notifier, receiving any new SAN dGPU events sent from
ACPI. The registered notifier will be called with [`struct san_dgpu_event`](#c-struct-san_dgpu_event)
as notifier data and the command ID of that event as notifier action.

#### <a id="c-san_dgpu_notifier_unregister"></a>`san_dgpu_notifier_unregister()`

```c
int san_dgpu_notifier_unregister(struct notifier_block *nb)
```

Unregister a SAN dGPU notifier.

**Parameters**

- `struct notifier_block *nb`: The notifier-block to unregister.

---

# Thermal

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> Reference for Thermal.

<a id="rst-thermal"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [CPU cooling APIs How To](</kernel/hardware/driver-api/thermal/cpu-cooling-api.md>)
- [CPU Idle Cooling](</kernel/hardware/driver-api/thermal/cpu-idle-cooling.md>)
- [Generic Thermal Sysfs driver How To](</kernel/hardware/driver-api/thermal/sysfs-api.md>)
- [Power allocator governor tunables](</kernel/hardware/driver-api/thermal/power-allocator.md>)
- [Kernel driver exynos_tmu](</kernel/hardware/driver-api/thermal/exynos-thermal.md>)
- [Exynos Emulation Mode](</kernel/hardware/driver-api/thermal/exynos-thermal-emulation.md>)
- [Kernel driver nouveau](</kernel/hardware/driver-api/thermal/nouveau-thermal.md>)
- [Kernel driver: x86_pkg_temp_thermal](</kernel/hardware/driver-api/thermal/x86-pkg-temperature-thermal.md>)
- [Intel(R) Dynamic Platform and Thermal Framework Sysfs Interface](</kernel/hardware/driver-api/thermal/intel-dptf.md>)

---

# CPU cooling APIs How To

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> Written by Amit Daniel Kachhap <amit.kachhap@linaro.org>

<a id="rst-cpu-cooling-apis-how-to"></a>

Written by Amit Daniel Kachhap &lt;[amit.kachhap@linaro.org](<mailto:amit.kachhap@linaro.org>)&gt;

Updated: 6 Jan 2015

Copyright (c)  2012 Samsung Electronics Co., Ltd([http://www.samsung.com](<http://www.samsung.com>))

<a id="rst-introduction"></a>

## 0. Introduction

The generic cpu cooling(freq clipping) provides registration/unregistration APIs to the caller. The binding of the cooling devices to the trip point is left for the user. The registration APIs returns the cooling device pointer.

<a id="rst-cpu-cooling-apis"></a>

## 1. cpu cooling APIs

<a id="rst-cpufreq-registration-unregistration-apis"></a>

### 1.1 cpufreq registration/unregistration APIs

> >
> >
> > ```text
> > struct thermal_cooling_device
> > *cpufreq_cooling_register(struct cpumask *clip_cpus)
> > ```
> >
> > This interface function registers the cpufreq cooling device with the name "thermal-cpufreq-%x". This api can support multiple instances of cpufreq cooling devices.
>
> - **clip_cpus:**
>
>   > cpumask of cpus where the frequency constraints will happen.
>
>
>
>   ```text
>   struct thermal_cooling_device
>   *of_cpufreq_cooling_register(struct cpufreq_policy *policy)
>   ```
>
>   This interface function registers the cpufreq cooling device with the name "thermal-cpufreq-%x" linking it with a device tree node, in order to bind it via the thermal DT code. This api can support multiple instances of cpufreq cooling devices.
>
>   - **policy:**
>
>     CPUFreq policy.
>
>
>
>   ```text
>   void cpufreq_cooling_unregister(struct thermal_cooling_device *cdev)
>   ```
>
>   This interface function unregisters the "thermal-cpufreq-%x" cooling device.
>
>   cdev: Cooling device pointer which has to be unregistered.

<a id="rst-power-models"></a>

## 2. Power models

The power API registration functions provide a simple power model for CPUs.  The current power is calculated as dynamic power (static power isn't supported currently).  This power model requires that the operating-points of the CPUs are registered using the kernel's opp library and the `cpufreq_frequency_table` is assigned to the `struct device` of the cpu.  If you are using CONFIG_CPUFREQ_DT then the `cpufreq_frequency_table` should already be assigned to the cpu device.

The dynamic power consumption of a processor depends on many factors. For a given processor implementation the primary factors are:

- The time the processor spends running, consuming dynamic power, as compared to the time in idle states where dynamic consumption is negligible.  Herein we refer to this as 'utilisation'.

- The voltage and frequency levels as a result of DVFS.  The DVFS level is a dominant factor governing power consumption.

- In running time the 'execution' behaviour (instruction types, memory access patterns and so forth) causes, in most cases, a second order variation.  In pathological cases this variation can be significant, but typically it is of a much lesser impact than the factors above.

A high level dynamic power consumption model may then be represented as:



```text
Pdyn = f(run) * Voltage^2 * Frequency * Utilisation
```

f(run) here represents the described execution behaviour and its result has a units of Watts/Hz/Volt^2 (this often expressed in mW/MHz/uVolt^2)

The detailed behaviour for f(run) could be modelled on-line.  However, in practice, such an on-line model has dependencies on a number of implementation specific processor support and characterisation factors.  Therefore, in initial implementation that contribution is represented as a constant coefficient.  This is a simplification consistent with the relative contribution to overall power variation.

In this simplified representation our model becomes:



```text
Pdyn = Capacitance * Voltage^2 * Frequency * Utilisation
```

Where `capacitance` is a constant that represents an indicative running time dynamic power coefficient in fundamental units of mW/MHz/uVolt^2.  Typical values for mobile CPUs might lie in range from 100 to 500.  For reference, the approximate values for the SoC in ARM's Juno Development Platform are 530 for the Cortex-A57 cluster and 140 for the Cortex-A53 cluster.

---

# CPU Idle Cooling

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> Under certain circumstances a SoC can reach a critical temperature limit and is unable to stabilize the temperature around a temperature control. When the SoC has to stabilize the temperature, the kernel can act on a cooling device to…

<a id="rst-cpu-idle-cooling"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-situation"></a>

## Situation:

Under certain circumstances a SoC can reach a critical temperature limit and is unable to stabilize the temperature around a temperature control. When the SoC has to stabilize the temperature, the kernel can act on a cooling device to mitigate the dissipated power. When the critical temperature is reached, a decision must be taken to reduce the temperature, that, in turn impacts performance.

Another situation is when the silicon temperature continues to increase even after the dynamic leakage is reduced to its minimum by clock gating the component. This runaway phenomenon can continue due to the static leakage. The only solution is to power down the component, thus dropping the dynamic and static leakage that will allow the component to cool down.

Last but not least, the system can ask for a specific power budget but because of the OPP density, we can only choose an OPP with a power budget lower than the requested one and under-utilize the CPU, thus losing performance. In other words, one OPP under-utilizes the CPU with a power less than the requested power budget and the next OPP exceeds the power budget. An intermediate OPP could have been used if it were present.

<a id="rst-solutions"></a>

## Solutions:

If we can remove the static and the dynamic leakage for a specific duration in a controlled period, the SoC temperature will decrease. Acting on the idle state duration or the idle cycle injection period, we can mitigate the temperature by modulating the power budget.

The Operating Performance Point (OPP) density has a great influence on the control precision of cpufreq, however different vendors have a plethora of OPP density, and some have large power gap between OPPs, that will result in loss of performance during thermal control and loss of power in other scenarios.

At a specific OPP, we can assume that injecting idle cycle on all CPUs belong to the same cluster, with a duration greater than the cluster idle state target residency, we lead to dropping the static and the dynamic leakage for this period (modulo the energy needed to enter this state). So the sustainable power with idle cycles has a linear relation with the OPP’s sustainable power and can be computed with a coefficient similar to:



```text
Power(IdleCycle) = Coef x Power(OPP)
```

<a id="rst-idle-injection"></a>

## Idle Injection:

The base concept of the idle injection is to force the CPU to go to an idle state for a specified time each control cycle, it provides another way to control CPU power and heat in addition to cpufreq. Ideally, if all CPUs belonging to the same cluster, inject their idle cycles synchronously, the cluster can reach its power down state with a minimum power consumption and reduce the static leakage to almost zero.  However, these idle cycles injection will add extra latencies as the CPUs will have to wakeup from a deep sleep state.

We use a fixed duration of idle injection that gives an acceptable performance penalty and a fixed latency. Mitigation can be increased or decreased by modulating the duty cycle of the idle injection.



```text
^
|
|
|-------                         -------
|_______|_______________________|_______|___________

<------>
  idle  <---------------------->
               running

 <----------------------------->
         duty cycle 25%
```

The implementation of the cooling device bases the number of states on the duty cycle percentage. When no mitigation is happening the cooling device state is zero, meaning the duty cycle is 0%.

When the mitigation begins, depending on the governor's policy, a starting state is selected. With a fixed idle duration and the duty cycle (aka the cooling device state), the running duration can be computed.

The governor will change the cooling device state thus the duty cycle and this variation will modulate the cooling effect.



```text
^
|
|
|-------                 -------
|_______|_______________|_______|___________

<------>
  idle  <-------------->
           running

 <--------------------->
     duty cycle 33%


^
|
|
|-------         -------
|_______|_______|_______|___________

<------>
  idle  <------>
         running

 <------------->
  duty cycle 50%
```

The idle injection duration value must comply with the constraints:

- It is less than or equal to the latency we tolerate when the mitigation begins. It is platform dependent and will depend on the user experience, reactivity vs performance trade off we want. This value should be specified.

- It is greater than the idle state’s target residency we want to go for thermal mitigation, otherwise we end up consuming more energy.

<a id="rst-power-considerations"></a>

## Power considerations

When we reach the thermal trip point, we have to sustain a specified power for a specific temperature but at this time we consume:



```text
Power = Capacitance x Voltage^2 x Frequency x Utilisation
```

... which is more than the sustainable power (or there is something wrong in the system setup). The ‘Capacitance’ and ‘Utilisation’ are a fixed value, ‘Voltage’ and the ‘Frequency’ are fixed artificially because we don’t want to change the OPP. We can group the ‘Capacitance’ and the ‘Utilisation’ into a single term which is the ‘Dynamic Power Coefficient (Cdyn)’ Simplifying the above, we have:



```text
Pdyn = Cdyn x Voltage^2 x Frequency
```

The power allocator governor will ask us somehow to reduce our power in order to target the sustainable power defined in the device tree. So with the idle injection mechanism, we want an average power (Ptarget) resulting in an amount of time running at full power on a specific OPP and idle another amount of time. That could be put in a equation:



```text
P(opp)target = ((Trunning x (P(opp)running) + (Tidle x P(opp)idle)) /
                       (Trunning + Tidle)

 ...

Tidle = Trunning x ((P(opp)running / P(opp)target) - 1)
```

At this point if we know the running period for the CPU, that gives us the idle injection we need. Alternatively if we have the idle injection duration, we can compute the running duration with:



```text
Trunning = Tidle / ((P(opp)running / P(opp)target) - 1)
```

Practically, if the running power is less than the targeted power, we end up with a negative time value, so obviously the equation usage is bound to a power reduction, hence a higher OPP is needed to have the running power greater than the targeted power.

However, in this demonstration we ignore three aspects:

> - The static leakage is not defined here, we can introduce it in the equation but assuming it will be zero most of the time as it is difficult to get the values from the SoC vendors
>
> - The idle state wake up latency (or entry + exit latency) is not taken into account, it must be added in the equation in order to rigorously compute the idle injection
>
> - The injected idle duration must be greater than the idle state target residency, otherwise we end up consuming more energy and potentially invert the mitigation effect

So the final equation is:



```text
Trunning = (Tidle - Twakeup ) x
               (((P(opp)dyn + P(opp)static ) - P(opp)target) / P(opp)target )
```

---

# Kernel driver exynos_tmu

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> Supported chips:

<a id="rst-kernel-driver-exynos-tmu"></a>

Supported chips:

- ARM Samsung Exynos4, Exynos5 series of SoC

  Datasheet: Not publicly available

Authors: Donggeun Kim &lt;[dg77.kim@samsung.com](<mailto:dg77.kim@samsung.com>)&gt; Authors: Amit Daniel &lt;[amit.daniel@samsung.com](<mailto:amit.daniel@samsung.com>)&gt;

<a id="rst-tmu-controller-description"></a>

## TMU controller Description:

This driver allows to read temperature inside Samsung Exynos4/5 series of SoC.

The chip only exposes the measured 8-bit temperature code value through a register. Temperature can be taken from the temperature code. There are three equations converting from temperature to temperature code.

- **The three equations are:**

  1. Two point trimming:



     ```text
     Tc = (T - 25) * (TI2 - TI1) / (85 - 25) + TI1
     ```

  2. One point trimming:



     ```text
     Tc = T + TI1 - 25
     ```

  3. No trimming:



     ```text
     Tc = T + 50
     ```

  - **Tc:**

    Temperature code, T: Temperature,

  - **TI1:**

    Trimming info for 25 degree Celsius (stored at TRIMINFO register) Temperature code measured at 25 degree Celsius which is unchanged

  - **TI2:**

    Trimming info for 85 degree Celsius (stored at TRIMINFO register) Temperature code measured at 85 degree Celsius which is unchanged

TMU(Thermal Management Unit) in Exynos4/5 generates interrupt when temperature exceeds pre-defined levels. The maximum number of configurable threshold is five. The threshold levels are defined as follows:



```text
Level_0: current temperature > trigger_level_0 + threshold
Level_1: current temperature > trigger_level_1 + threshold
Level_2: current temperature > trigger_level_2 + threshold
Level_3: current temperature > trigger_level_3 + threshold
```

The threshold and each trigger_level are set through the corresponding registers.

When an interrupt occurs, this driver notify kernel thermal framework with the function exynos_report_trigger. Although an interrupt condition for level_0 can be set, it can be used to synchronize the cooling action.

<a id="rst-tmu-driver-description"></a>

## TMU driver description:

The exynos thermal driver is structured as:



```text
                                      Kernel Core thermal framework
                              (thermal_core.c, step_wise.c, cpufreq_cooling.c)
                                                              ^
                                                              |
                                                              |
TMU configuration data -----> TMU Driver  <----> Exynos Core thermal wrapper
(exynos_tmu_data.c)         (exynos_tmu.c)       (exynos_thermal_common.c)
(exynos_tmu_data.h)         (exynos_tmu.h)       (exynos_thermal_common.h)
```

- **a)** - **TMU configuration data:**

    This consist of TMU register offsets/bitfields described through structure exynos_tmu_registers. Also several other platform data (struct exynos_tmu_platform_data) members are used to configure the TMU.

- **b)** - **TMU driver:**

    This component initialises the TMU controller and sets different thresholds. It invokes core thermal implementation with the call exynos_report_trigger.

- **c)** - **Exynos Core thermal wrapper:**

    This provides 3 wrapper function to use the Kernel core thermal framework. They are exynos_unregister_thermal, exynos_register_thermal and exynos_report_trigger.

---

# Exynos Emulation Mode

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> Copyright (C) 2012 Samsung Electronics

<a id="rst-exynos-emulation-mode"></a>

Copyright (C) 2012 Samsung Electronics

Written by Jonghwa Lee &lt;[jonghwa3.lee@samsung.com](<mailto:jonghwa3.lee@samsung.com>)&gt;

<a id="rst-description"></a>

## Description

Exynos 4x12 (4212, 4412) and 5 series provide emulation mode for thermal management unit. Thermal emulation mode supports software debug for TMU's operation. User can set temperature manually with software code and TMU will read current temperature from user value not from sensor's value.

Enabling CONFIG_THERMAL_EMULATION option will make this support available. When it's enabled, sysfs node will be created as /sys/devices/virtual/thermal/thermal_zone'zone id'/emul_temp.

The sysfs node, 'emul_node', will contain value 0 for the initial state. When you input any temperature you want to update to sysfs node, it automatically enable emulation mode and current temperature will be changed into it.

(Exynos also supports user changeable delay time which would be used to delay of changing temperature. However, this node only uses same delay of real sensing time, 938us.)

Exynos emulation mode requires that value changes and enabling are performed synchronously. This means that when you want to update any value, such as the delay or the next temperature, you must enable emulation mode at the same time (or keep the mode enabled). If you do not, the value will fail to update and the last successful value will continue to be used. For this reason, this node only allows users to change the temperature. Providing a single interface makes it simpler to use.

Disabling emulation mode only requires writing value 0 to sysfs node.



```text
TEMP  120 |
          |
      100 |
          |
       80 |
          |                            +-----------
       60 |                            |          |
          |              +-------------|          |
       40 |              |             |          |
          |              |             |          |
       20 |              |             |          +----------
          |              |             |          |          |
        0 |______________|_____________|__________|__________|_________
                 A             A          A                  A     TIME
                 |<----->|     |<----->|  |<----->|          |
                 | 938us |     |       |  |       |          |
emulation   : 0  50      |     70      |  20      |          0
current temp:   sensor   50            70         20        sensor
```

---

# Intel(R) Dynamic Platform and Thermal Framework Sysfs Interface

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> Intel(R) Dynamic Platform and Thermal Framework (DPTF) is a platform level hardware/software solution for power and thermal management.

<a id="rst-intel-r-dynamic-platform-and-thermal-framework-sysfs-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Copyright:** © 2022 Intel Corporation

**Author:** Srinivas Pandruvada &lt;[srinivas.pandruvada@linux.intel.com](<mailto:srinivas.pandruvada@linux.intel.com>)&gt;

<a id="rst-introduction"></a>

## Introduction

Intel(R) Dynamic Platform and Thermal Framework (DPTF) is a platform level hardware/software solution for power and thermal management.

As a container for multiple power/thermal technologies, DPTF provides a coordinated approach for different policies to effect the hardware state of a system.

Since it is a platform level framework, this has several components. Some parts of the technology is implemented in the firmware and uses ACPI and PCI devices to expose various features for monitoring and control. Linux has a set of kernel drivers exposing hardware interface to user space. This allows user space thermal solutions like "Linux Thermal Daemon" to read platform specific thermal and power tables to deliver adequate performance while keeping the system under thermal limits.

<a id="rst-dptf-acpi-drivers-interface"></a>

## DPTF ACPI Drivers interface

`/sys/bus/platform/devices/<N>/uuids`, where &lt;N&gt; =INT3400\|INTC1040\|INTC1041\|INTC10A0

- **`available_uuids` (RO)**

  A set of UUIDs strings presenting available policies which should be notified to the firmware when the user space can support those policies.

  UUID strings:

  "42A441D6-AE6A-462b-A84B-4A8CE79027D3" : Passive 1

  "3A95C389-E4B8-4629-A526-C52C88626BAE" : Active

  "97C68AE7-15FA-499c-B8C9-5DA81D606E0A" : Critical

  "63BE270F-1C11-48FD-A6F7-3AF253FF3E2D" : Adaptive performance

  "5349962F-71E6-431D-9AE8-0A635B710AEE" : Emergency call

  "9E04115A-AE87-4D1C-9500-0F3E340BFE75" : Passive 2

  "F5A35014-C209-46A4-993A-EB56DE7530A1" : Power Boss

  "6ED722A7-9240-48A5-B479-31EEF723D7CF" : Virtual Sensor

  "16CAF1B7-DD38-40ED-B1C1-1B8A1913D531" : Cooling mode

  "BE84BABF-C4D4-403D-B495-3128FD44dAC1" : HDC

- **`current_uuid` (RW)**

  User space can write strings from available UUIDs, one at a time.

`/sys/bus/platform/devices/<N>/`, where &lt;N&gt; =INT3400\|INTC1040\|INTC1041\|INTC10A0

- **`imok` (WO)**

  User space daemon write 1 to respond to firmware event for sending keep alive notification. User space receives THERMAL_EVENT_KEEP_ALIVE kobject uevent notification when firmware calls for user space to respond with imok ACPI method.

- **`odvp*` (RO)**

  Firmware thermal status variable values. Thermal tables calls for different processing based on these variable values.

- **`data_vault` (RO)**

  Binary thermal table. Refer to [https:/github.com/intel/thermal_daemon](<https:/github.com/intel/thermal_daemon>) for decoding thermal table.

- **`production_mode` (RO)**

  When different from zero, manufacturer locked thermal configuration from further changes.

<a id="rst-acpi-thermal-relationship-table-interface"></a>

## ACPI Thermal Relationship table interface

`/dev/acpi_thermal_rel`

> This device provides IOCTL interface to read standard ACPI thermal relationship tables via ACPI methods \_TRT and \_ART. These IOCTLs are defined in drivers/thermal/intel/int340x_thermal/acpi_thermal_rel.h
>
> IOCTLs:
>
> ACPI_THERMAL_GET_TRT_LEN: Get length of TRT table
>
> ACPI_THERMAL_GET_ART_LEN: Get length of ART table
>
> ACPI_THERMAL_GET_TRT_COUNT: Number of records in TRT table
>
> ACPI_THERMAL_GET_ART_COUNT: Number of records in ART table
>
> ACPI_THERMAL_GET_TRT: Read binary TRT table, length to read is provided via argument to ioctl().
>
> ACPI_THERMAL_GET_ART: Read binary ART table, length to read is provided via argument to ioctl().

<a id="rst-dptf-acpi-sensor-drivers"></a>

## DPTF ACPI Sensor drivers

DPTF Sensor drivers are presented as standard thermal sysfs thermal_zone.

<a id="rst-dptf-acpi-cooling-drivers"></a>

## DPTF ACPI Cooling drivers

DPTF cooling drivers are presented as standard thermal sysfs cooling_device.

<a id="rst-dptf-processor-thermal-pci-driver-interface"></a>

## DPTF Processor thermal PCI Driver interface

`/sys/bus/pci/devices/0000:00:04.0/power_limits/`

Refer to [Documentation/power/powercap/powercap.rst](/kernel/internals/power/powercap/powercap.md) for powercap ABI.

- **`power_limit_0_max_uw` (RO)**

  Maximum powercap sysfs constraint_0_power_limit_uw for Intel RAPL

- **`power_limit_0_step_uw` (RO)**

  Power limit increment/decrements for Intel RAPL constraint 0 power limit

- **`power_limit_0_min_uw` (RO)**

  Minimum powercap sysfs constraint_0_power_limit_uw for Intel RAPL

- **`power_limit_0_tmin_us` (RO)**

  Minimum powercap sysfs constraint_0_time_window_us for Intel RAPL

- **`power_limit_0_tmax_us` (RO)**

  Maximum powercap sysfs constraint_0_time_window_us for Intel RAPL

- **`power_limit_1_max_uw` (RO)**

  Maximum powercap sysfs constraint_1_power_limit_uw for Intel RAPL

- **`power_limit_1_step_uw` (RO)**

  Power limit increment/decrements for Intel RAPL constraint 1 power limit

- **`power_limit_1_min_uw` (RO)**

  Minimum powercap sysfs constraint_1_power_limit_uw for Intel RAPL

- **`power_limit_1_tmin_us` (RO)**

  Minimum powercap sysfs constraint_1_time_window_us for Intel RAPL

- **`power_limit_1_tmax_us` (RO)**

  Maximum powercap sysfs constraint_1_time_window_us for Intel RAPL

- **`power_floor_status` (RO)**

  When set to 1, the power floor of the system in the current configuration has been reached.  It needs to be reconfigured to allow power to be reduced any further.

- **`power_floor_enable` (RW)**

  When set to 1, enable reading and notification of the power floor status. Notifications are triggered for the power_floor_status attribute value changes.

`/sys/bus/pci/devices/0000:00:04.0/`

- **`tcc_offset_degree_celsius` (RW)**

  TCC offset from the critical temperature where hardware will throttle CPU.

`/sys/bus/pci/devices/0000:00:04.0/workload_request`

- **`workload_available_types` (RO)**

  Available workload types. User space can specify one of the workload type it is currently executing via workload_type. For example: idle, bursty, sustained etc.

- **`workload_type` (RW)**

  User space can specify any one of the available workload type using this interface.

`/sys/bus/pci/devices/0000:00:04.0/ptc_0_control` `/sys/bus/pci/devices/0000:00:04.0/ptc_1_control` `/sys/bus/pci/devices/0000:00:04.0/ptc_2_control`

All these controls needs admin privilege to update.

- **`enable` (RW)**

  1 for enable, 0 for disable. Shows the current enable status of platform temperature control feature. User space can enable/disable hardware controls.

- **`temperature_target` (RW)**

  Update a new temperature target in milli degree celsius for hardware to use for the temperature control.

- **`thermal_tolerance` (RW)**

  This attribute ranges from 0 to 7, where 0 represents the most aggressive control to avoid any temperature overshoots, and 7 represents a more graceful approach, favoring performance even at the expense of temperature overshoots. Note: This level may not scale linearly. For example, a value of 3 does not necessarily imply a 50% improvement in performance compared to a value of 0.

Given that this is platform temperature control, it is expected that a single user-level manager owns and manages the controls. If multiple user-level software applications attempt to write different targets, it can lead to unexpected behavior.

<a id="rst-dptf-processor-thermal-rfim-interface"></a>

## DPTF Processor thermal RFIM interface

RFIM interface allows adjustment of FIVR (Fully Integrated Voltage Regulator), DDR (Double Data Rate) and DLVR (Digital Linear Voltage Regulator) frequencies to avoid RF interference with WiFi and 5G.

Switching voltage regulators (VR) generate radiated EMI or RFI at the fundamental frequency and its harmonics. Some harmonics may interfere with very sensitive wireless receivers such as Wi-Fi and cellular that are integrated into host systems like notebook PCs.  One of mitigation methods is requesting SOC integrated VR (IVR) switching frequency to a small % and shift away the switching noise harmonic interference from radio channels.  OEM or ODMs can use the driver to control SOC IVR operation within the range where it does not impact IVR performance.

Some products use DLVR instead of FIVR as switching voltage regulator. In this case attributes of DLVR must be adjusted instead of FIVR.

While shifting the frequencies additional clock noise can be introduced, which is compensated by adjusting Spread spectrum percent. This helps to reduce the clock noise to meet regulatory compliance. This spreading % increases bandwidth of signal transmission and hence reduces the effects of interference, noise and signal fading.

DRAM devices of DDR IO interface and their power plane can generate EMI at the data rates. Similar to IVR control mechanism, Intel offers a mechanism by which DDR data rates can be changed if several conditions are met: there is strong RFI interference because of DDR; CPU power management has no other restriction in changing DDR data rates; PC ODMs enable this feature (real time DDR RFI Mitigation referred to as DDR-RFIM) for Wi-Fi from BIOS.

FIVR attributes

`/sys/bus/pci/devices/0000:00:04.0/fivr/`

- **`vco_ref_code_lo` (RW)**

  The VCO reference code is an 11-bit field and controls the FIVR switching frequency. This is the 3-bit LSB field.

- **`vco_ref_code_hi` (RW)**

  The VCO reference code is an 11-bit field and controls the FIVR switching frequency. This is the 8-bit MSB field.

- **`spread_spectrum_pct` (RW)**

  Set the FIVR spread spectrum clocking percentage

- **`spread_spectrum_clk_enable` (RW)**

  Enable/disable of the FIVR spread spectrum clocking feature

- **`rfi_vco_ref_code` (RW)**

  This field is a read only status register which reflects the current FIVR switching frequency

- **`fivr_fffc_rev` (RW)**

  This field indicated the revision of the FIVR HW.

DVFS attributes

`/sys/bus/pci/devices/0000:00:04.0/dvfs/`

- **`rfi_restriction_run_busy` (RW)**

  Request the restriction of specific DDR data rate and set this value 1. Self reset to 0 after operation.

- **`rfi_restriction_err_code` (RW)**

  0 :Request is accepted, 1:Feature disabled, 2: the request restricts more points than it is allowed

- **`rfi_restriction_data_rate_Delta` (RW)**

  Restricted DDR data rate for RFI protection: Lower Limit

- **`rfi_restriction_data_rate_Base` (RW)**

  Restricted DDR data rate for RFI protection: Upper Limit

- **`ddr_data_rate_point_0` (RO)**

  DDR data rate selection 1st point

- **`ddr_data_rate_point_1` (RO)**

  DDR data rate selection 2nd point

- **`ddr_data_rate_point_2` (RO)**

  DDR data rate selection 3rd point

- **`ddr_data_rate_point_3` (RO)**

  DDR data rate selection 4th point

- **`rfi_disable (RW)`**

  Disable DDR rate change feature

DLVR attributes

`/sys/bus/pci/devices/0000:00:04.0/dlvr/`

- **`dlvr_hardware_rev` (RO)**

  DLVR hardware revision.

- **`dlvr_freq_mhz` (RO)**

  Current DLVR PLL frequency in MHz.

- **`dlvr_freq_select` (RW)**

  Sets DLVR PLL clock frequency. Once set, and enabled via dlvr_rfim_enable, the dlvr_freq_mhz will show the current DLVR PLL frequency.

- **`dlvr_pll_busy` (RO)**

  PLL can't accept frequency change when set.

- **`dlvr_rfim_enable` (RW)**

  0: Disable RF frequency hopping, 1: Enable RF frequency hopping.

- **`dlvr_spread_spectrum_pct` (RW)**

  Sets DLVR spread spectrum percent value.

- **`dlvr_control_mode` (RW)**

  Specifies how frequencies are spread using spread spectrum. 0: Down spread, 1: Spread in the Center.

- **`dlvr_control_lock` (RW)**

  1: future writes are ignored.

<a id="rst-dptf-power-supply-and-battery-interface"></a>

## DPTF Power supply and Battery Interface

Refer to Documentation/ABI/testing/sysfs-platform-dptf

<a id="rst-dptf-fan-control"></a>

## DPTF Fan Control

Refer to [Documentation/admin-guide/acpi/fan_performance_states.rst](/kernel/administration/admin-guide/acpi/fan-performance-states.md)

<a id="rst-workload-type-hints"></a>

## Workload Type Hints

The firmware in Meteor Lake processor generation is capable of identifying workload type and passing hints regarding it to the OS. A special sysfs interface is provided to allow user space to obtain workload type hints from the firmware and control the rate at which they are provided.

User space can poll attribute "workload_type_index" for the current hint or can receive a notification whenever the value of this attribute is updated.

file:`/sys/bus/pci/devices/0000:00:04.0/workload_hint/` Segment 0, bus 0, device 4, function 0 is reserved for the processor thermal device on all Intel client processors. So, the above path doesn't change based on the processor generation.

- **`workload_hint_enable` (RW)**

  Enable firmware to send workload type hints to user space.

- **`workload_slow_hint_enable` (RW)**

  Enable firmware to send slow workload type hints to user space.

- **`notification_delay_ms` (RW)**

  Minimum delay in milliseconds before firmware will notify OS. This is for the rate control of notifications. This delay is between changing the workload type prediction in the firmware and notifying the OS about the change. The default delay is 1024 ms. The delay of 0 is invalid. The delay is rounded up to the nearest power of 2 to simplify firmware programming of the delay value. The read of notification_delay_ms attribute shows the effective value used.

- **`workload_type_index` (RO)**

  Predicted workload type index. User space can get notification of change via existing sysfs attribute change notification mechanism.

  The supported index values and their meaning for the Meteor Lake processor generation are as follows:

  - **0 -  Idle: System performs no tasks, power and idle residency are**

    consistently low for long periods of time.

  - **1 – Battery Life: Power is relatively low, but the processor may**

    still be actively performing a task, such as video playback for a long period of time.

  - **2 – Sustained: Power level that is relatively high for a long period**

    of time, with very few to no periods of idleness, which will eventually exhaust RAPL Power Limit 1 and 2.

  - **3 – Bursty: Consumes a relatively constant average amount of power, but**

    periods of relative idleness are interrupted by bursts of activity. The bursts are relatively short and the periods of relative idleness between them typically prevent RAPL Power Limit 1 from being exhausted.

  4 – Unknown: Can't classify.

  On processors starting from Panther Lake additional hints are provided. The hardware analyzes workload residencies over an extended period to determine whether the workload classification tends toward idle/battery life states or sustained/performance states. Based on this long-term analysis, it classifies:

  Power Classification: If the workload exhibits more idle or battery life residencies, it is classified as "power".

  Performance Classification: If the workload exhibits more sustained or performance residencies, it is classified as "performance".

  This approach enables applications to ignore short-term workload fluctuations and instead respond to longer-term power vs. performance trends.

  Residency thresholds for this classification are CPU generation-specific. Classification is reported via bit 4 of the workload_type_index:

  Bit 4 = 1: Power classification

  Bit 4 = 0: Performance classification

---

# Kernel driver nouveau

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> Supported chips:

<a id="rst-kernel-driver-nouveau"></a>

Supported chips:

- NV43+

Authors: Martin Peres (mupuf) &lt;[martin.peres@free.fr](<mailto:martin.peres@free.fr>)&gt;

<a id="rst-description"></a>

## Description

This driver allows to read the GPU core temperature, drive the GPU fan and set temperature alarms.

Currently, due to the absence of in-kernel API to access HWMON drivers, Nouveau cannot access any of the i2c external monitoring chips it may find. If you have one of those, temperature and/or fan management through Nouveau's HWMON interface is likely not to work. This document may then not cover your situation entirely.

<a id="rst-temperature-management"></a>

## Temperature management

Temperature is exposed under as a read-only HWMON attribute temp1_input.

In order to protect the GPU from overheating, Nouveau supports 4 configurable temperature thresholds:

> - - **Fan_boost:**
>
>     Fan speed is set to 100% when reaching this temperature;
>
> - - **Downclock:**
>
>     The GPU will be downclocked to reduce its power dissipation;
>
> - - **Critical:**
>
>     The GPU is put on hold to further lower power dissipation;
>
> - - **Shutdown:**
>
>     Shut the computer down to protect your GPU.

- **WARNING:**

  Some of these thresholds may not be used by Nouveau depending on your chipset.

The default value for these thresholds comes from the GPU's vbios. These thresholds can be configured thanks to the following HWMON attributes:

> - Fan_boost: temp1_auto_point1_temp and temp1_auto_point1_temp_hyst;
>
> - Downclock: temp1_max and temp1_max_hyst;
>
> - Critical: temp1_crit and temp1_crit_hyst;
>
> - Shutdown: temp1_emergency and temp1_emergency_hyst.

NOTE: Remember that the values are stored as milli degrees Celsius. Don't forget to multiply\!

<a id="rst-fan-management"></a>

## Fan management

Not all cards have a drivable fan. If you do, then the following HWMON attributes should be available:

> - - **pwm1_enable:**
>
>     Current fan management mode (NONE, MANUAL or AUTO);
>
> - - **pwm1:**
>
>     Current PWM value (power percentage);
>
> - - **pwm1_min:**
>
>     The minimum PWM speed allowed;
>
> - - **pwm1_max:**
>
>     The maximum PWM speed allowed (bypassed when hitting Fan_boost);

You may also have the following attribute:

> - - **fan1_input:**
>
>     Speed in RPM of your fan.

Your fan can be driven in different modes:

> - 0: The fan is left untouched;
>
> - 1: The fan can be driven in manual (use pwm1 to change the speed);
>
> - 2; The fan is driven automatically depending on the temperature.

- **NOTE:**

  Be sure to use the manual mode if you want to drive the fan speed manually

- **NOTE2:**

  When operating in manual mode outside the vbios-defined \[PWM_min, PWM_max\] range, the reported fan speed (RPM) may not be accurate depending on your hardware.

<a id="rst-bug-reports"></a>

## Bug reports

Thermal management on Nouveau is new and may not work on all cards. If you have inquiries, please ping mupuf on IRC (\#nouveau, OFTC).

Bug reports should be filled on Freedesktop's bug tracker. Please follow [https://nouveau.freedesktop.org/wiki/Bugs](<https://nouveau.freedesktop.org/wiki/Bugs>)

---

# Power allocator governor tunables

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> The governor works optimally with the following two passive trip points:

<a id="rst-power-allocator-governor-tunables"></a>

<a id="rst-trip-points"></a>

## Trip points

The governor works optimally with the following two passive trip points:

1. "switch on" trip point: temperature above which the governor control loop starts operating.  This is the first passive trip point of the thermal zone.

2. "desired temperature" trip point: it should be higher than the "switch on" trip point.  This the target temperature the governor is controlling for.  This is the last passive trip point of the thermal zone.

<a id="rst-pid-controller"></a>

## PID Controller

The power allocator governor implements a Proportional-Integral-Derivative controller (PID controller) with temperature as the control input and power as the controlled output:

> P_max = k_p \* e + k_i \* err_integral + k_d \* diff_err + sustainable_power

- **where**

  - e = desired_temperature - current_temperature

  - err_integral is the sum of previous errors

  - diff_err = e - previous_error

It is similar to the one depicted below:



```text
                                    k_d
                                     |
current_temp                         |
     |                               v
     |              +----------+   +---+
     |       +----->| diff_err |-->| X |------+
     |       |      +----------+   +---+      |
     |       |                                |      tdp        actor
     |       |                      k_i       |       |  get_requested_power()
     |       |                       |        |       |        |     |
     |       |                       |        |       |        |     | ...
     v       |                       v        v       v        v     v
   +---+     |      +-------+      +---+    +---+   +---+   +----------+
   | S |-----+----->| sum e |----->| X |--->| S |-->| S |-->|power     |
   +---+     |      +-------+      +---+    +---+   +---+   |allocation|
     ^       |                                ^             +----------+
     |       |                                |                |     |
     |       |        +---+                   |                |     |
     |       +------->| X |-------------------+                v     v
     |                +---+                               granted performance
desired_temperature     ^
                        |
                        |
                    k_po/k_pu
```

<a id="rst-sustainable-power"></a>

## Sustainable power

An estimate of the sustainable dissipatable power (in mW) should be provided while registering the thermal zone.  This estimates the sustained power that can be dissipated at the desired control temperature.  This is the maximum sustained power for allocation at the desired maximum temperature.  The actual sustained power can vary for a number of reasons.  The closed loop controller will take care of variations such as environmental conditions, and some factors related to the speed-grade of the silicon.  `sustainable_power` is therefore simply an estimate, and may be tuned to affect the aggressiveness of the thermal ramp. For reference, the sustainable power of a 4" phone is typically 2000mW, while on a 10" tablet is around 4500mW (may vary depending on screen size). It is possible to have the power value expressed in an abstract scale. The sustained power should be aligned to the scale used by the related cooling devices.

If you are using device tree, do add it as a property of the thermal-zone.  For example:



```text
thermal-zones {
        soc_thermal {
                polling-delay = <1000>;
                polling-delay-passive = <100>;
                sustainable-power = <2500>;
                ...
```

Instead, if the thermal zone is registered from the platform code, pass a `thermal_zone_params` that has a `sustainable_power`.  If no `thermal_zone_params` were being passed, then something like below will suffice:



```text
static const struct thermal_zone_params tz_params = {
        .sustainable_power = 3500,
};
```

and then pass `tz_params` as the 5th parameter to `thermal_zone_device_register()`

<a id="rst-k-po-and-k-pu"></a>

## k_po and k_pu

The implementation of the PID controller in the power allocator thermal governor allows the configuration of two proportional term constants: `k_po` and `k_pu`.  `k_po` is the proportional term constant during temperature overshoot periods (current temperature is above "desired temperature" trip point).  Conversely, `k_pu` is the proportional term constant during temperature undershoot periods (current temperature below "desired temperature" trip point).

These controls are intended as the primary mechanism for configuring the permitted thermal "ramp" of the system.  For instance, a lower `k_pu` value will provide a slower ramp, at the cost of capping available capacity at a low temperature.  On the other hand, a high value of `k_pu` will result in the governor granting very high power while temperature is low, and may lead to temperature overshooting.

The default value for `k_pu` is:



```text
2 * sustainable_power / (desired_temperature - switch_on_temp)
```

This means that at `switch_on_temp` the output of the controller's proportional term will be 2 \* `sustainable_power`.  The default value for `k_po` is:



```text
sustainable_power / (desired_temperature - switch_on_temp)
```

Focusing on the proportional and feed forward values of the PID controller equation we have:



```text
P_max = k_p * e + sustainable_power
```

The proportional term is proportional to the difference between the desired temperature and the current one.  When the current temperature is the desired one, then the proportional component is zero and `P_max` = `sustainable_power`.  That is, the system should operate in thermal equilibrium under constant load.  `sustainable_power` is only an estimate, which is the reason for closed-loop control such as this.

Expanding `k_pu` we get:



```text
P_max = 2 * sustainable_power * (T_set - T) / (T_set - T_on) +
    sustainable_power
```

where:

> - T_set is the desired temperature
>
> - T is the current temperature
>
> - T_on is the switch on temperature

When the current temperature is the switch_on temperature, the above formula becomes:



```text
P_max = 2 * sustainable_power * (T_set - T_on) / (T_set - T_on) +
    sustainable_power = 2 * sustainable_power + sustainable_power =
    3 * sustainable_power
```

Therefore, the proportional term alone linearly decreases power from 3 \* `sustainable_power` to `sustainable_power` as the temperature rises from the switch on temperature to the desired temperature.

<a id="rst-k-i-and-integral-cutoff"></a>

## k_i and integral_cutoff

`k_i` configures the PID loop's integral term constant.  This term allows the PID controller to compensate for long term drift and for the quantized nature of the output control: cooling devices can't set the exact power that the governor requests.  When the temperature error is below `integral_cutoff`, errors are accumulated in the integral term.  This term is then multiplied by `k_i` and the result added to the output of the controller.  Typically `k_i` is set low (1 or 2) and `integral_cutoff` is 0.

<a id="rst-k-d"></a>

## k_d

`k_d` configures the PID loop's derivative term constant.  It's recommended to leave it as the default: 0.

<a id="rst-cooling-device-power-api"></a>

### Cooling device power API

Cooling devices controlled by this governor must supply the additional "power" API in their `cooling_device_ops`.  It consists on three ops:

1. 

   ```text
   int get_requested_power(struct thermal_cooling_device *cdev,
                           struct thermal_zone_device *tz, u32 *power);
   ```

- **@cdev:**

  The `struct thermal_cooling_device` pointer

- **@tz:**

  thermal zone in which we are currently operating

- **@power:**

  pointer in which to store the calculated power

`get_requested_power()` calculates the power requested by the device in milliwatts and stores it in @power .  It should return 0 on success, -E\* on failure.  This is currently used by the power allocator governor to calculate how much power to give to each cooling device.

2. 

   ```text
   int state2power(struct thermal_cooling_device *cdev, struct
                   thermal_zone_device *tz, unsigned long state,
                   u32 *power);
   ```

- **@cdev:**

  The `struct thermal_cooling_device` pointer

- **@tz:**

  thermal zone in which we are currently operating

- **@state:**

  A cooling device state

- **@power:**

  pointer in which to store the equivalent power

Convert cooling device state @state into power consumption in milliwatts and store it in @power.  It should return 0 on success, -E\* on failure.  This is currently used by thermal core to calculate the maximum power that an actor can consume.

3. 

   ```text
   int power2state(struct thermal_cooling_device *cdev, u32 power,
                   unsigned long *state);
   ```

- **@cdev:**

  The `struct thermal_cooling_device` pointer

- **@power:**

  power in milliwatts

- **@state:**

  pointer in which to store the resulting state

Calculate a cooling device state that would make the device consume at most @power mW and store it in @state.  It should return 0 on success, -E\* on failure.  This is currently used by the thermal core to convert a given power set by the power allocator governor to a state that the cooling device can set.  It is a function because this conversion may depend on external factors that may change so this function should the best conversion given "current circumstances".

<a id="rst-cooling-device-weights"></a>

## Cooling device weights

Weights are a mechanism to bias the allocation among cooling devices.  They express the relative power efficiency of different cooling devices.  Higher weight can be used to express higher power efficiency.  Weighting is relative such that if each cooling device has a weight of one they are considered equal.  This is particularly useful in heterogeneous systems where two cooling devices may perform the same kind of compute, but with different efficiency.  For example, a system with two different types of processors.

If the thermal zone is registered using `thermal_zone_device_register()` (i.e., platform code), then weights are passed as part of the thermal zone's `thermal_bind_parameters`. If the platform is registered using device tree, then they are passed as the `contribution` property of each map in the `cooling-maps` node.

<a id="rst-limitations-of-the-power-allocator-governor"></a>

### Limitations of the power allocator governor

The power allocator governor's PID controller works best if there is a periodic tick.  If you have a driver that calls `thermal_zone_device_update()` (or anything that ends up calling the governor's `throttle()` function) repetitively, the governor response won't be very good.  Note that this is not particular to this governor, step-wise will also misbehave if you call its throttle() faster than the normal thermal framework tick (due to interrupts for example) as it will overreact.

<a id="rst-energy-model-requirements"></a>

### Energy Model requirements

Another important thing is the consistent scale of the power values provided by the cooling devices. All of the cooling devices in a single thermal zone should have power values reported either in milli-Watts or scaled to the same 'abstract scale'.

---

# Generic Thermal Sysfs driver How To

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> Written by Sujith Thomas <sujith.thomas@intel.com>, Zhang Rui <rui.zhang@intel.com>

<a id="rst-generic-thermal-sysfs-driver-how-to"></a>

Written by Sujith Thomas &lt;[sujith.thomas@intel.com](<mailto:sujith.thomas@intel.com>)&gt;, Zhang Rui &lt;[rui.zhang@intel.com](<mailto:rui.zhang@intel.com>)&gt;

Copyright (c)  2008 Intel Corporation

<a id="rst-introduction"></a>

## 0. Introduction

The generic thermal sysfs provides a set of interfaces for thermal zone devices (sensors) and thermal cooling devices (fan, processor...) to register with the thermal management solution and to be a part of it.

This how-to focuses on enabling new thermal zone and cooling devices to participate in thermal management. This solution is platform independent and any type of thermal zone devices and cooling devices should be able to make use of the infrastructure.

The main task of the thermal sysfs driver is to expose thermal zone attributes as well as cooling device attributes to the user space. An intelligent thermal management application can make decisions based on inputs from thermal zone attributes (the current temperature and trip point temperature) and throttle appropriate devices.

- `[0-*]`       denotes any positive number starting from 0

- `[1-*]`       denotes any positive number starting from 1

<a id="rst-thermal-sysfs-driver-interface-functions"></a>

## 1. thermal sysfs driver interface functions

<a id="rst-thermal-zone-device-interface"></a>

### 1.1 thermal zone device interface

>
>
> ```text
> struct thermal_zone_device *
> thermal_zone_device_register_with_trips(const char *type,
>                                 const struct thermal_trip *trips,
>                                 int num_trips, void *devdata,
>                                 const struct thermal_zone_device_ops *ops,
>                                 const struct thermal_zone_params *tzp,
>                                 unsigned int passive_delay,
>                                 unsigned int polling_delay)
> ```
>
> This interface function adds a new thermal zone device (sensor) to the /sys/class/thermal folder as `thermal_zone[0-*]`. It tries to bind all the thermal cooling devices registered to it at the same time.
>
> - **type:**
>
>   the thermal zone type.
>
> - **trips:**
>
>   the table of trip points for this thermal zone.
>
> - **devdata:**
>
>   device private data
>
> - **ops:**
>
>   thermal zone device call-backs.
>
>   - **.should_bind:**
>
>     check whether or not a given cooling device should be bound to a given trip point in this thermal zone.
>
>   - **.get_temp:**
>
>     get the current temperature of the thermal zone.
>
>   - **.set_trips:**
>
>     set the trip points window. Whenever the current temperature is updated, the trip points immediately below and above the current temperature are found.
>
>   - **.change_mode:**
>
>     change the mode (enabled/disabled) of the thermal zone.
>
>   - **.set_trip_temp:**
>
>     set the temperature of a given trip point.
>
>   - **.get_crit_temp:**
>
>     get the critical temperature for this thermal zone.
>
>   - **.set_emul_temp:**
>
>     set the emulation temperature which helps in debugging different threshold temperature points.
>
>   - **.get_trend:**
>
>     get the trend of most recent zone temperature changes.
>
>   - **.hot:**
>
>     hot trip point crossing handler.
>
>   - **.critical:**
>
>     critical trip point crossing handler.
>
> - **tzp:**
>
>   thermal zone platform parameters.
>
> - **passive_delay:**
>
>   number of milliseconds to wait between polls when performing passive cooling.
>
> - **polling_delay:**
>
>   number of milliseconds to wait between polls when checking whether trip points have been crossed (0 for interrupt driven systems).
>
>
>
> ```text
> void thermal_zone_device_unregister(struct thermal_zone_device *tz)
> ```
>
> This interface function removes the thermal zone device. It deletes the corresponding entry from /sys/class/thermal folder and unbinds all the thermal cooling devices it uses.
>
> >
> >
> > ```text
> > struct thermal_zone_device
> > *thermal_zone_of_sensor_register(struct device *dev, int sensor_id,
> >                      void *data,
> >                      const struct thermal_zone_of_device_ops *ops)
> > ```
> >
> > This interface adds a new sensor to a DT thermal zone. This function will search the list of thermal zones described in device tree and look for the zone that refer to the sensor device pointed by dev-&gt;of_node as temperature providers. For the zone pointing to the sensor node, the sensor will be added to the DT thermal zone device.
> >
> > The parameters for this interface are:
> >
> > - **dev:**
> >
> >   Device node of sensor containing valid node pointer in dev-&gt;of_node.
> >
> > - **sensor_id:**
> >
> >   a sensor identifier, in case the sensor IP has more than one sensors
> >
> > - **data:**
> >
> >   a private pointer (owned by the caller) that will be passed back, when a temperature reading is needed.
> >
> > - **ops:**
> >
> >   `struct thermal_zone_of_device_ops *`.
> >
> >
> >   <table>
> >   <tbody>
> >   <tr>
> >   <td>
> >
> >
> >   get_temp
> >
> >   </td>
> >   <td>
> >
> >
> >   a pointer to a function that reads the sensor temperature. This is mandatory callback provided by sensor driver.
> >
> >   </td>
> >   </tr>
> >   <tr>
> >   <td>
> >
> >
> >   set_trips
> >
> >   </td>
> >   <td>
> >
> >
> >   a pointer to a function that sets a temperature window. When this window is left the driver must inform the thermal core via thermal_zone_device_update.
> >
> >   </td>
> >   </tr>
> >   <tr>
> >   <td>
> >
> >
> >   get_trend
> >
> >   </td>
> >   <td>
> >
> >
> >   a pointer to a function that reads the sensor temperature trend.
> >
> >   </td>
> >   </tr>
> >   <tr>
> >   <td>
> >
> >
> >   set_emul_temp
> >
> >   </td>
> >   <td>
> >
> >
> >   a pointer to a function that sets sensor emulated temperature.
> >
> >   </td>
> >   </tr>
> >   </tbody>
> >   </table>
> >
> > The thermal zone temperature is provided by the get_temp() function pointer of thermal_zone_of_device_ops. When called, it will have the private pointer @data back.
> >
> > It returns error pointer if fails otherwise valid thermal zone device handle. Caller should check the return handle with IS_ERR() for finding whether success or not.
> >
> >
> >
> > ```text
> > void thermal_zone_of_sensor_unregister(struct device *dev,
> >                                        struct thermal_zone_device *tzd)
> > ```
> >
> > This interface unregisters a sensor from a DT thermal zone which was successfully added by interface thermal_zone_of_sensor_register(). This function removes the sensor callbacks and private data from the thermal zone device registered with thermal_zone_of_sensor_register() interface. It will also silent the zone by remove the .get_temp() and get_trend() thermal zone device callbacks.
> >
> >
> >
> > ```text
> > struct thermal_zone_device
> > *devm_thermal_zone_of_sensor_register(struct device *dev,
> >                       int sensor_id,
> >                       void *data,
> >                       const struct thermal_zone_of_device_ops *ops)
> > ```
> >
> > This interface is resource managed version of thermal_zone_of_sensor_register().
> >
> > All details of thermal_zone_of_sensor_register() described in section 1.1.3 is applicable here.
> >
> > The benefit of using this interface to register sensor is that it is not require to explicitly call thermal_zone_of_sensor_unregister() in error path or during driver unbinding as this is done by driver resource manager.
> >
> >
> >
> > ```text
> > void devm_thermal_zone_of_sensor_unregister(struct device *dev,
> >                                 struct thermal_zone_device *tzd)
> > ```
> >
> > This interface is resource managed version of thermal_zone_of_sensor_unregister(). All details of thermal_zone_of_sensor_unregister() described in section 1.1.4 is applicable here. Normally this function will not need to be called and the resource management code will ensure that the resource is freed.
> >
> >
> >
> > ```text
> > int thermal_zone_get_slope(struct thermal_zone_device *tz)
> > ```
> >
> > This interface is used to read the slope attribute value for the thermal zone device, which might be useful for platform drivers for temperature calculations.
> >
> >
> >
> > ```text
> > int thermal_zone_get_offset(struct thermal_zone_device *tz)
> > ```
> >
> > This interface is used to read the offset attribute value for the thermal zone device, which might be useful for platform drivers for temperature calculations.

<a id="rst-thermal-cooling-device-interface"></a>

### 1.2 thermal cooling device interface

>
>
> ```text
> struct thermal_cooling_device
> *thermal_cooling_device_register(char *name,
>                 void *devdata, struct thermal_cooling_device_ops *)
> ```
>
> This interface function adds a new thermal cooling device (fan/processor/...) to /sys/class/thermal/ folder as `cooling_device[0-*]`. It tries to bind itself to all the thermal zone devices registered at the same time.
>
> - **name:**
>
>   the cooling device name.
>
> - **devdata:**
>
>   device private data.
>
> - **ops:**
>
>   thermal cooling devices call-backs.
>
>   - **.get_max_state:**
>
>     get the Maximum throttle state of the cooling device.
>
>   - **.get_cur_state:**
>
>     get the Currently requested throttle state of the cooling device.
>
>   - **.set_cur_state:**
>
>     set the Current throttle state of the cooling device.
>
>
>
> ```text
> void thermal_cooling_device_unregister(struct thermal_cooling_device *cdev)
> ```
>
> This interface function removes the thermal cooling device. It deletes the corresponding entry from /sys/class/thermal folder and unbinds itself from all the thermal zone devices using it.

<a id="rst-thermal-zone-parameters"></a>

### 1.4 Thermal Zone Parameters

>
>
> ```text
> struct thermal_zone_params
> ```
>
> This structure defines the platform level parameters for a thermal zone. This data, for each thermal zone should come from the platform layer. This is an optional feature where some platforms can choose not to provide this data.
>
> - **.governor_name:**
>
>   Name of the thermal governor used for this zone
>
> - **.no_hwmon:**
>
>   a boolean to indicate if the thermal to hwmon sysfs interface is required. when no_hwmon == false, a hwmon sysfs interface will be created. when no_hwmon == true, nothing will be done. In case the thermal_zone_params is NULL, the hwmon interface will be created (for backward compatibility).

<a id="rst-sysfs-attributes-structure"></a>

## 2. sysfs attributes structure


<table>
<tbody>
<tr>
<td>


RO

</td>
<td>


read only value

</td>
</tr>
<tr>
<td>


WO

</td>
<td>


write only value

</td>
</tr>
<tr>
<td>


RW

</td>
<td>


read/write value

</td>
</tr>
</tbody>
</table>

Thermal sysfs attributes will be represented under /sys/class/thermal. Hwmon sysfs I/F extension is also available under /sys/class/hwmon if hwmon is compiled in or built as a module.

Thermal zone device sys I/F, created once it's registered:



```text
/sys/class/thermal/thermal_zone[0-*]:
  |---type:                   Type of the thermal zone
  |---temp:                   Current temperature
  |---mode:                   Working mode of the thermal zone
  |---policy:                 Thermal governor used for this zone
  |---available_policies:     Available thermal governors for this zone
  |---trip_point_[0-*]_temp:  Trip point temperature
  |---trip_point_[0-*]_type:  Trip point type
  |---trip_point_[0-*]_hyst:  Hysteresis value for this trip point
  |---emul_temp:              Emulated temperature set node
  |---sustainable_power:      Sustainable dissipatable power
  |---k_po:                   Proportional term during temperature overshoot
  |---k_pu:                   Proportional term during temperature undershoot
  |---k_i:                    PID's integral term in the power allocator gov
  |---k_d:                    PID's derivative term in the power allocator
  |---integral_cutoff:        Offset above which errors are accumulated
  |---slope:                  Slope constant applied as linear extrapolation
  |---offset:                 Offset constant applied as linear extrapolation
```

Thermal cooling device sys I/F, created once it's registered:



```text
/sys/class/thermal/cooling_device[0-*]:
  |---type:                   Type of the cooling device(processor/fan/...)
  |---max_state:              Maximum cooling state of the cooling device
  |---cur_state:              Current cooling state of the cooling device
  |---stats:                  Directory containing cooling device's statistics
  |---stats/reset:            Writing any value resets the statistics
  |---stats/time_in_state_ms: Time (msec) spent in various cooling states
  |---stats/total_trans:      Total number of times cooling state is changed
  |---stats/trans_table:      Cooling state transition table
```

Then next two dynamic attributes are created/removed in pairs. They represent the relationship between a thermal zone and its associated cooling device.



```text
/sys/class/thermal/thermal_zone[0-*]:
  |---cdev[0-*]:              [0-*]th cooling device in current thermal zone
  |---cdev[0-*]_trip_point:   Trip point that cdev[0-*] is associated with
  |---cdev[0-*]_weight:       Influence of the cooling device in
                              this thermal zone
```

Besides the thermal zone device sysfs I/F and cooling device sysfs I/F, the generic thermal driver also creates a hwmon sysfs I/F for each \_type\_ of thermal zone device. E.g. the generic thermal driver registers one hwmon class device and build the associated hwmon sysfs I/F for all the registered ACPI thermal zones.

Please read Documentation/ABI/testing/sysfs-class-thermal for thermal zone and cooling device attribute details.



```text
/sys/class/hwmon/hwmon[0-*]:
  |---name:                   The type of the thermal zone devices
  |---temp[1-*]_input:        The current temperature of thermal zone [1-*]
  |---temp[1-*]_critical:     The critical trip point of thermal zone [1-*]
```

Please read [Documentation/hwmon/sysfs-interface.rst](/kernel/hardware/hwmon/sysfs-interface.md) for additional information.

<a id="rst-a-simple-implementation"></a>

## 3. A simple implementation

ACPI thermal zone may support multiple trip points like critical, hot, passive, active. If an ACPI thermal zone supports critical, passive, active\[0\] and active\[1\] at the same time, it may register itself as a thermal_zone_device (thermal_zone1) with 4 trip points in all. It has one processor and one fan, which are both registered as thermal_cooling_device. Both are considered to have the same effectiveness in cooling the thermal zone.

If the processor is listed in \_PSL method, and the fan is listed in \_AL0 method, the sys I/F structure will be built like this:



```text
/sys/class/thermal:
 |thermal_zone1:
   |---type:                   acpitz
   |---temp:                   37000
   |---mode:                   enabled
   |---policy:                 step_wise
   |---available_policies:     step_wise fair_share
   |---trip_point_0_temp:      100000
   |---trip_point_0_type:      critical
   |---trip_point_1_temp:      80000
   |---trip_point_1_type:      passive
   |---trip_point_2_temp:      70000
   |---trip_point_2_type:      active0
   |---trip_point_3_temp:      60000
   |---trip_point_3_type:      active1
   |---cdev0:                  --->/sys/class/thermal/cooling_device0
   |---cdev0_trip_point:       1       /* cdev0 can be used for passive */
   |---cdev0_weight:           1024
   |---cdev1:                  --->/sys/class/thermal/cooling_device3
   |---cdev1_trip_point:       2       /* cdev1 can be used for active[0]*/
   |---cdev1_weight:           1024

 |cooling_device0:
   |---type:                   Processor
   |---max_state:              8
   |---cur_state:              0

 |cooling_device3:
   |---type:                   Fan
   |---max_state:              2
   |---cur_state:              0

/sys/class/hwmon:
 |hwmon0:
   |---name:                   acpitz
   |---temp1_input:            37000
   |---temp1_crit:             100000
```

<a id="rst-export-symbol-apis"></a>

## 4. Export Symbol APIs

<a id="rst-get-tz-trend"></a>

### 4.1. get_tz_trend

This function returns the trend of a thermal zone, i.e the rate of change of temperature of the thermal zone. Ideally, the thermal sensor drivers are supposed to implement the callback. If they don't, the thermal framework calculated the trend by comparing the previous and the current temperature values.

<a id="rst-thermal-cdev-update"></a>

### 4.2. thermal_cdev_update

This function serves as an arbitrator to set the state of a cooling device. It sets the cooling device to the deepest cooling state if possible.

<a id="rst-critical-events"></a>

## 5. Critical Events

On an event of critical trip temperature crossing, the thermal framework will trigger a hardware protection power-off (shutdown) or reboot, depending on configuration.

At first, the kernel will attempt an orderly power-off or reboot, but accepts a delay after which it proceeds to do a forced power-off or reboot, respectively. If this fails, `emergency_restart()` is invoked as last resort.

The delay should be carefully profiled so as to give adequate time for orderly power-off or reboot.

If the delay is set to 0, the emergency action will not be supported. So a carefully profiled non-zero positive value is a must for the emergency action to be triggered.

---

# Kernel driver: x86_pkg_temp_thermal

_Peios Kernel / Hardware and drivers / Driver development / Thermal management_

> Supported chips:

<a id="rst-kernel-driver-x86-pkg-temp-thermal"></a>

Supported chips:

- x86: with package level thermal management

(Verify using: CPUID.06H:EAX\[bit 6\] =1)

Authors: Srinivas Pandruvada &lt;[srinivas.pandruvada@linux.intel.com](<mailto:srinivas.pandruvada@linux.intel.com>)&gt;

<a id="rst-reference"></a>

## Reference

Intel® 64 and IA-32 Architectures Software Developer’s Manual (Jan, 2013): Chapter 14.6: PACKAGE LEVEL THERMAL MANAGEMENT

<a id="rst-description"></a>

## Description

This driver register CPU digital temperature package level sensor as a thermal zone with maximum two user mode configurable trip points. Number of trip points depends on the capability of the package. Once the trip point is violated, user mode can receive notification via thermal notification mechanism and can take any action to control temperature.

<a id="rst-threshold-management"></a>

## Threshold management

Each package will register as a thermal zone under /sys/class/thermal.

Example:



```text
/sys/class/thermal/thermal_zone1
```

This contains two trip points:

- trip_point_0_temp

- trip_point_1_temp

User can set any temperature between 0 to TJ-Max temperature. Temperature units are in milli-degree Celsius. Refer to "[Documentation/driver-api/thermal/sysfs-api.rst](/kernel/hardware/driver-api/thermal/sysfs-api.md)" for thermal sys-fs details.

Any value other than 0 in these trip points, can trigger thermal notifications. Setting 0, stops sending thermal notifications.

Thermal notifications: To get kobject-uevent notifications, set the thermal zone policy to "user_space".

For example:



```text
echo -n "user_space" > policy
```

---

# Firmware hotplug script example

_Peios Kernel / Hardware and drivers / Driver development / firmware_class_

> Original firmware-loading example using the DEVPATH and FIRMWARE environment variables and the sysfs loading interface.

Original firmware-loading example using the DEVPATH and FIRMWARE environment variables and the sysfs loading interface.


```bash
#!/bin/sh

# Simple hotplug script sample:
# 
# Both $DEVPATH and $FIRMWARE are already provided in the environment.

HOTPLUG_FW_DIR=/usr/lib/hotplug/firmware/

if [ "$SUBSYSTEM" == "firmware" -a "$ACTION" == "add" ]; then
  if [ -f $HOTPLUG_FW_DIR/$FIRMWARE ]; then
    echo 1 > /sys/$DEVPATH/loading
    cat $HOTPLUG_FW_DIR/$FIRMWARE > /sys/$DEVPATH/data
    echo 0 > /sys/$DEVPATH/loading
  else
    echo -1 > /sys/$DEVPATH/loading
  fi
fi

```

---

# Linux 802.11 Driver Developer's Guide

_Peios Kernel / Hardware and drivers / Driver development / Wireless LAN (802.11)_

> Reference for Linux 802.11 Driver Developer's Guide.

<a id="rst-linux-802-11-driver-developer-s-guide"></a>

- [Introduction](</kernel/hardware/driver-api/80211/introduction.md>)
- [cfg80211 subsystem](</kernel/hardware/driver-api/80211/cfg80211.md>)
- [mac80211 subsystem (basics)](</kernel/hardware/driver-api/80211/mac80211.md>)
- [mac80211 subsystem (advanced)](</kernel/hardware/driver-api/80211/mac80211-advanced.md>)

---

# cfg80211 subsystem

_Peios Kernel / Hardware and drivers / Driver development / Wireless LAN (802.11)_

> Reference for cfg80211 subsystem.

<a id="rst-cfg80211-subsystem"></a>


cfg80211 is the configuration API for 802.11 devices in Linux. It bridges
userspace and drivers, and offers some utility functionality associated
with 802.11. cfg80211 must, directly or indirectly via mac80211, be used
by all modern wireless drivers in Linux, so that they offer a consistent
API through nl80211. For backward compatibility, cfg80211 also offers
wireless extensions to userspace, but hides them from drivers completely.

Additionally, cfg80211 contains code to help enforce regulatory spectrum
use restrictions.


<a id="rst-device-registration"></a>

## Device registration


In order for a driver to use cfg80211, it must register the hardware device
with cfg80211. This happens through a number of hardware capability structs
described below.

The fundamental structure for each device is the 'wiphy', of which each
instance describes a physical wireless device connected to the system. Each
such wiphy can have zero, one, or many virtual interfaces associated with
it, which need to be identified as such by pointing the network interface's
**ieee80211_ptr** pointer to a [`struct wireless_dev`](#c-struct-wireless_dev) which further describes
the wireless part of the interface. Normally this struct is embedded in the
network interface's private data area. Drivers can optionally allow creating
or destroying virtual interfaces on the fly, but without at least one or the
ability to create some the wireless device isn't useful.

Each wiphy structure contains device capability information, and also has
a pointer to the various operations the driver offers. The definitions and
structures here describe these capabilities in detail.



#### <a id="c-enum-ieee80211_channel_flags"></a>`enum ieee80211_channel_flags`

channel flags

**Constants**

- `IEEE80211_CHAN_DISABLED`: This channel is disabled.
- `IEEE80211_CHAN_NO_IR`: do not initiate radiation, this includes
  sending probe requests or beaconing.
- `IEEE80211_CHAN_PSD`: Power spectral density (in dBm) is set for this
  channel.
- `IEEE80211_CHAN_RADAR`: Radar detection is required on this channel.
- `IEEE80211_CHAN_NO_HT40PLUS`: extension channel above this channel
  is not permitted.
- `IEEE80211_CHAN_NO_HT40MINUS`: extension channel below this channel
  is not permitted.
- `IEEE80211_CHAN_NO_OFDM`: OFDM is not allowed on this channel.
- `IEEE80211_CHAN_NO_80MHZ`: If the driver supports 80 MHz on the band,
  this flag indicates that an 80 MHz channel cannot use this
  channel as the control or any of the secondary channels.
  This may be due to the driver or due to regulatory bandwidth
  restrictions.
- `IEEE80211_CHAN_NO_160MHZ`: If the driver supports 160 MHz on the band,
  this flag indicates that an 160 MHz channel cannot use this
  channel as the control or any of the secondary channels.
  This may be due to the driver or due to regulatory bandwidth
  restrictions.
- `IEEE80211_CHAN_INDOOR_ONLY`: see `NL80211_FREQUENCY_ATTR_INDOOR_ONLY`
- `IEEE80211_CHAN_IR_CONCURRENT`: see `NL80211_FREQUENCY_ATTR_IR_CONCURRENT`
- `IEEE80211_CHAN_NO_20MHZ`: 20 MHz bandwidth is not permitted
  on this channel.
- `IEEE80211_CHAN_NO_10MHZ`: 10 MHz bandwidth is not permitted
  on this channel.
- `IEEE80211_CHAN_NO_HE`: HE operation is not permitted on this channel.
- `IEEE80211_CHAN_NO_UHR`: UHR operation is not permitted on this channel.
- `IEEE80211_CHAN_NO_320MHZ`: If the driver supports 320 MHz on the band,
  this flag indicates that a 320 MHz channel cannot use this
  channel as the control or any of the secondary channels.
  This may be due to the driver or due to regulatory bandwidth
  restrictions.
- `IEEE80211_CHAN_NO_EHT`: EHT operation is not permitted on this channel.
- `IEEE80211_CHAN_DFS_CONCURRENT`: See `NL80211_RRF_DFS_CONCURRENT`
- `IEEE80211_CHAN_NO_6GHZ_VLP_CLIENT`: Client connection with VLP AP
  not permitted using this channel
- `IEEE80211_CHAN_NO_6GHZ_AFC_CLIENT`: Client connection with AFC AP
  not permitted using this channel
- `IEEE80211_CHAN_CAN_MONITOR`: This channel can be used for monitor
  mode even in the presence of other (regulatory) restrictions,
  even if it is otherwise disabled.
- `IEEE80211_CHAN_ALLOW_6GHZ_VLP_AP`: Allow using this channel for AP operation
  with very low power (VLP), even if otherwise set to NO_IR.
- `IEEE80211_CHAN_ALLOW_20MHZ_ACTIVITY`: Allow activity on a 20 MHz channel,
  even if otherwise set to NO_IR.
- `IEEE80211_CHAN_S1G_NO_PRIMARY`: Prevents the channel for use as an S1G
  primary channel. Does not prevent the wider operating channel
  described by the chandef from being used. In order for a 2MHz primary
  to be used, both 1MHz subchannels shall not contain this flag.
- `IEEE80211_CHAN_NO_4MHZ`: 4 MHz bandwidth is not permitted on this channel.
- `IEEE80211_CHAN_NO_8MHZ`: 8 MHz bandwidth is not permitted on this channel.
- `IEEE80211_CHAN_NO_16MHZ`: 16 MHz bandwidth is not permitted on this channel.

**Description**

Channel flags set by the regulatory control code.

#### <a id="c-struct-ieee80211_channel"></a>`struct ieee80211_channel`

channel definition

**Definition**

```c
struct ieee80211_channel {
    enum nl80211_band band;
    u32 center_freq;
    u16 freq_offset;
    u16 hw_value;
    u32 flags;
    int max_antenna_gain;
    int max_power;
    int max_reg_power;
    bool beacon_found;
    u32 orig_flags;
    int orig_mag, orig_mpwr;
    enum nl80211_dfs_state dfs_state;
    unsigned long dfs_state_entered;
    unsigned int dfs_cac_ms;
    s8 psd;
};
```

**Members**

- `band`: band this channel belongs to.
- `center_freq`: center frequency in MHz
- `freq_offset`: offset from **center_freq**, in KHz
- `hw_value`: hardware-specific value for the channel
- `flags`: channel flags from [`enum ieee80211_channel_flags`](#c-enum-ieee80211_channel_flags).
- `max_antenna_gain`: maximum antenna gain in dBi
- `max_power`: maximum transmission power (in dBm)
- `max_reg_power`: maximum regulatory transmission power (in dBm)
- `beacon_found`: helper to regulatory code to indicate when a beacon
  has been found on this channel. Use `regulatory_hint_found_beacon()`
  to enable this, this is useful only on 5 GHz band.
- `orig_flags`: channel flags at registration time, used by regulatory
  code to support devices with additional restrictions
- `orig_mag`: internal use
- `orig_mpwr`: internal use
- `dfs_state`: current state of this channel. Only relevant if radar is required
  on this channel.
- `dfs_state_entered`: timestamp (jiffies) when the dfs state was entered.
- `dfs_cac_ms`: DFS CAC time in milliseconds, this is valid for DFS channels.
- `psd`: power spectral density (in dBm)

**Description**

This structure describes a single channel for use
with cfg80211.

#### <a id="c-enum-ieee80211_rate_flags"></a>`enum ieee80211_rate_flags`

rate flags

**Constants**

- `IEEE80211_RATE_SHORT_PREAMBLE`: Hardware can send with short
  preamble on this bitrate; only relevant in 2.4GHz band and
  with CCK rates.
- `IEEE80211_RATE_MANDATORY_A`: This bitrate is a mandatory rate
  when used with 802.11a (on the 5 GHz band); filled by the
  core code when registering the wiphy.
- `IEEE80211_RATE_MANDATORY_B`: This bitrate is a mandatory rate
  when used with 802.11b (on the 2.4 GHz band); filled by the
  core code when registering the wiphy.
- `IEEE80211_RATE_MANDATORY_G`: This bitrate is a mandatory rate
  when used with 802.11g (on the 2.4 GHz band); filled by the
  core code when registering the wiphy.
- `IEEE80211_RATE_ERP_G`: This is an ERP rate in 802.11g mode.
- `IEEE80211_RATE_SUPPORTS_5MHZ`: Rate can be used in 5 MHz mode
- `IEEE80211_RATE_SUPPORTS_10MHZ`: Rate can be used in 10 MHz mode

**Description**

Hardware/specification flags for rates. These are structured
in a way that allows using the same bitrate structure for
different bands/PHY modes.

#### <a id="c-struct-ieee80211_rate"></a>`struct ieee80211_rate`

bitrate definition

**Definition**

```c
struct ieee80211_rate {
    u32 flags;
    u16 bitrate;
    u16 hw_value, hw_value_short;
};
```

**Members**

- `flags`: rate-specific flags from [`enum ieee80211_rate_flags`](#c-enum-ieee80211_rate_flags)
- `bitrate`: bitrate in units of 100 Kbps
- `hw_value`: driver/hardware value for this rate
- `hw_value_short`: driver/hardware value for this rate when
  short preamble is used

**Description**

This structure describes a bitrate that an 802.11 PHY can
operate with. The two values **hw_value** and **hw_value_short**
are only for driver use when pointers to this structure are
passed around.

#### <a id="c-struct-ieee80211_sta_ht_cap"></a>`struct ieee80211_sta_ht_cap`

STA's HT capabilities

**Definition**

```c
struct ieee80211_sta_ht_cap {
    u16 cap;
    bool ht_supported;
    u8 ampdu_factor;
    u8 ampdu_density;
    struct ieee80211_mcs_info mcs;
};
```

**Members**

- `cap`: HT capabilities map as described in 802.11n spec
- `ht_supported`: is HT supported by the STA
- `ampdu_factor`: Maximum A-MPDU length factor
- `ampdu_density`: Minimum A-MPDU spacing
- `mcs`: Supported MCS rates

**Description**

This structure describes most essential parameters needed
to describe 802.11n HT capabilities for an STA.

#### <a id="c-struct-ieee80211_supported_band"></a>`struct ieee80211_supported_band`

frequency band definition

**Definition**

```c
struct ieee80211_supported_band {
    struct ieee80211_channel *channels;
    struct ieee80211_rate *bitrates;
    enum nl80211_band band;
    int n_channels;
    int n_bitrates;
    struct ieee80211_sta_ht_cap ht_cap;
    struct ieee80211_sta_vht_cap vht_cap;
    struct ieee80211_sta_s1g_cap s1g_cap;
    struct ieee80211_edmg edmg_cap;
    u16 n_iftype_data;
    const struct ieee80211_sband_iftype_data __iftd *iftype_data;
};
```

**Members**

- `channels`: Array of channels the hardware can operate with
  in this band.
- `bitrates`: Array of bitrates the hardware can operate with
  in this band. Must be sorted to give a valid "supported
  rates" IE, i.e. CCK rates first, then OFDM.
- `band`: the band this structure represents
- `n_channels`: Number of channels in **channels**
- `n_bitrates`: Number of bitrates in **bitrates**
- `ht_cap`: HT capabilities in this band
- `vht_cap`: VHT capabilities in this band
- `s1g_cap`: S1G capabilities in this band (S1G band only, of course)
- `edmg_cap`: EDMG capabilities in this band
- `n_iftype_data`: number of iftype data entries
- `iftype_data`: interface type data entries.  Note that the bits in
  **types_mask** inside this structure cannot overlap (i.e. only
  one occurrence of each type is allowed across all instances of
  iftype_data).

**Description**

This structure describes a frequency band a wiphy
is able to operate in.

#### <a id="c-wiphy_read_of_freq_limits"></a>`wiphy_read_of_freq_limits()`

```c
void wiphy_read_of_freq_limits(struct wiphy *wiphy)
```

read frequency limits from device tree

**Parameters**

- `struct wiphy *wiphy`: the wireless device to get extra limits for

**Description**

Some devices may have extra limitations specified in DT. This may be useful
for chipsets that normally support more bands but are limited due to board
design (e.g. by antennas or external power amplifier).

This function reads info from DT and uses it to *modify* channels (disable
unavailable ones). It's usually a *bad* idea to use it in drivers with
shared channel data as DT limitations are device specific. You should make
sure to call it only if channels in wiphy are copied and can be modified
without affecting other devices.

As this function access device node it has to be called after set_wiphy_dev.
It also modifies channels so they have to be set first.
If using this helper, call it before [`wiphy_register()`](#c-wiphy_register).

#### <a id="c-enum-cfg80211_signal_type"></a>`enum cfg80211_signal_type`

signal type

**Constants**

- `CFG80211_SIGNAL_TYPE_NONE`: no signal strength information available
- `CFG80211_SIGNAL_TYPE_MBM`: signal strength in mBm (100*dBm)
- `CFG80211_SIGNAL_TYPE_UNSPEC`: signal strength, increasing from 0 through 100

#### <a id="c-enum-wiphy_params_flags"></a>`enum wiphy_params_flags`

set_wiphy_params bitfield values

**Constants**

- `WIPHY_PARAM_RETRY_SHORT`: wiphy->retry_short has changed
- `WIPHY_PARAM_RETRY_LONG`: wiphy->retry_long has changed
- `WIPHY_PARAM_FRAG_THRESHOLD`: wiphy->frag_threshold has changed
- `WIPHY_PARAM_RTS_THRESHOLD`: wiphy->rts_threshold has changed
- `WIPHY_PARAM_COVERAGE_CLASS`: coverage class changed
- `WIPHY_PARAM_DYN_ACK`: dynack has been enabled
- `WIPHY_PARAM_TXQ_LIMIT`: TXQ packet limit has been changed
- `WIPHY_PARAM_TXQ_MEMORY_LIMIT`: TXQ memory limit has been changed
- `WIPHY_PARAM_TXQ_QUANTUM`: TXQ scheduler quantum

#### <a id="c-enum-wiphy_flags"></a>`enum wiphy_flags`

wiphy capability flags

**Constants**

- `WIPHY_FLAG_SUPPORTS_EXT_KEK_KCK`: The device supports bigger kek and kck keys
- `WIPHY_FLAG_SUPPORTS_MLO`: This is a temporary flag gating the MLO APIs,
  in order to not have them reachable in normal drivers, until we have
  complete feature/interface combinations/etc. advertisement. No driver
  should set this flag for now.
- `WIPHY_FLAG_SPLIT_SCAN_6GHZ`: if set to true, the scan request will be split
  into two, first for legacy bands and second for 6 GHz.
- `WIPHY_FLAG_NETNS_OK`: if not set, do not allow changing the netns of this
  wiphy at all
- `WIPHY_FLAG_PS_ON_BY_DEFAULT`: if set to true, powersave will be enabled
  by default -- this flag will be set depending on the kernel's default
  on [`wiphy_new()`](#c-wiphy_new), but can be changed by the driver if it has a good
  reason to override the default
- `WIPHY_FLAG_4ADDR_AP`: supports 4addr mode even on AP (with a single station
  on a VLAN interface). This flag also serves an extra purpose of
  supporting 4ADDR AP mode on devices which do not support AP/VLAN iftype.
- `WIPHY_FLAG_4ADDR_STATION`: supports 4addr mode even as a station
- `WIPHY_FLAG_CONTROL_PORT_PROTOCOL`: This device supports setting the
  control port protocol ethertype. The device also honours the
  control_port_no_encrypt flag.
- `WIPHY_FLAG_IBSS_RSN`: The device supports IBSS RSN.
- `WIPHY_FLAG_DISABLE_WEXT`: disable wireless extensions for this device
- `WIPHY_FLAG_MESH_AUTH`: The device supports mesh authentication by routing
  auth frames to userspace. See **NL80211_MESH_SETUP_USERSPACE_AUTH**.
- `WIPHY_FLAG_SUPPORTS_EXT_KCK_32`: The device supports 32-byte KCK keys.
- `WIPHY_FLAG_SUPPORTS_NSTR_NONPRIMARY`: support connection to non-primary link
  of an NSTR mobile AP MLD.
- `WIPHY_FLAG_SUPPORTS_FW_ROAM`: The device supports roaming feature in the
  firmware.
- `WIPHY_FLAG_AP_UAPSD`: The device supports uapsd on AP.
- `WIPHY_FLAG_SUPPORTS_TDLS`: The device supports TDLS (802.11z) operation.
- `WIPHY_FLAG_TDLS_EXTERNAL_SETUP`: The device does not handle TDLS (802.11z)
  link setup/discovery operations internally. Setup, discovery and
  teardown packets should be sent through the **NL80211_CMD_TDLS_MGMT**
  command. When this flag is not set, **NL80211_CMD_TDLS_OPER** should be
  used for asking the driver/firmware to perform a TDLS operation.
- `WIPHY_FLAG_HAVE_AP_SME`: device integrates AP SME
- `WIPHY_FLAG_REPORTS_OBSS`: the device will report beacons from other BSSes
  when there are virtual interfaces in AP mode by calling
  `cfg80211_report_obss_beacon()`.
- `WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD`: When operating as an AP, the device
  responds to probe-requests in hardware.
- `WIPHY_FLAG_OFFCHAN_TX`: Device supports direct off-channel TX.
- `WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL`: Device supports remain-on-channel call.
- `WIPHY_FLAG_SUPPORTS_5_10_MHZ`: Device supports 5 MHz and 10 MHz channels.
- `WIPHY_FLAG_HAS_CHANNEL_SWITCH`: Device supports channel switch in
  beaconing mode (AP, IBSS, Mesh, ...).
- `WIPHY_FLAG_NOTIFY_REGDOM_BY_DRIVER`: The device could handle reg notify for
  NL80211_REGDOM_SET_BY_DRIVER.
- `WIPHY_FLAG_CHANNEL_CHANGE_ON_BEACON`: `reg_call_notifier()` is called if driver
  set this flag to update channels on beacon hints.

#### <a id="c-struct-ieee80211_iface_limit"></a>`struct ieee80211_iface_limit`

limit on certain interface types

**Definition**

```c
struct ieee80211_iface_limit {
    u16 max;
    u16 types;
};
```

**Members**

- `max`: maximum number of interfaces of these types
- `types`: interface types (bits)

#### <a id="c-struct-ieee80211_iface_combination"></a>`struct ieee80211_iface_combination`

possible interface combination

**Definition**

```c
struct ieee80211_iface_combination {
    const struct ieee80211_iface_limit *limits;
    u32 num_different_channels;
    u16 max_interfaces;
    u8 n_limits;
    bool beacon_int_infra_match;
    u8 radar_detect_widths;
    u8 radar_detect_regions;
    u32 beacon_int_min_gcd;
};
```

**Members**

- `limits`: limits for the given interface types
- `num_different_channels`: can use up to this many different channels
- `max_interfaces`: maximum number of interfaces in total allowed in this group
- `n_limits`: number of limitations
- `beacon_int_infra_match`: In this combination, the beacon intervals between infrastructure
  and AP types must match. This is required only in special cases.
- `radar_detect_widths`: bitmap of channel widths supported for radar detection
- `radar_detect_regions`: bitmap of regions supported for radar detection
- `beacon_int_min_gcd`: This interface combination supports different beacon intervals.

  - = 0

    all beacon intervals for different interface must be same.
  - > 0

    any beacon interval for the interface part of this combination AND
    GCD of all beacon intervals from beaconing interfaces of this
    combination must be greater or equal to this value.

**Description**

With this structure the driver can describe which interface
combinations it supports concurrently. When set in a struct wiphy_radio,
the combinations refer to combinations of interfaces currently active on
that radio.

**Examples**

1. Allow #STA \<= 1, #AP \<= 1, matching BI, channels = 1, 2 total:

```c
struct ieee80211_iface_limit limits1[] = {
        { .max = 1, .types = BIT(NL80211_IFTYPE_STATION), },
        { .max = 1, .types = BIT(NL80211_IFTYPE_AP), },
};
struct ieee80211_iface_combination combination1 = {
        .limits = limits1,
        .n_limits = ARRAY_SIZE(limits1),
        .max_interfaces = 2,
        .beacon_int_infra_match = true,
};
```

2. Allow #{AP, P2P-GO} \<= 8, channels = 1, 8 total:

```c
struct ieee80211_iface_limit limits2[] = {
        { .max = 8, .types = BIT(NL80211_IFTYPE_AP) |
                             BIT(NL80211_IFTYPE_P2P_GO), },
};
struct ieee80211_iface_combination combination2 = {
        .limits = limits2,
        .n_limits = ARRAY_SIZE(limits2),
        .max_interfaces = 8,
        .num_different_channels = 1,
};
```

3. Allow #STA \<= 1, #{P2P-client,P2P-GO} \<= 3 on two channels, 4 total.

   This allows for an infrastructure connection and three P2P connections.

```c
struct ieee80211_iface_limit limits3[] = {
        { .max = 1, .types = BIT(NL80211_IFTYPE_STATION), },
        { .max = 3, .types = BIT(NL80211_IFTYPE_P2P_GO) |
                             BIT(NL80211_IFTYPE_P2P_CLIENT), },
};
struct ieee80211_iface_combination combination3 = {
        .limits = limits3,
        .n_limits = ARRAY_SIZE(limits3),
        .max_interfaces = 4,
        .num_different_channels = 2,
};
```

#### <a id="c-struct-wiphy"></a>`struct wiphy`

wireless hardware description

**Definition**

```c
struct wiphy {
        struct mutex mtx;
        u8 perm_addr[ETH_ALEN];
        u8 addr_mask[ETH_ALEN];
        struct mac_address *addresses;
        const struct ieee80211_txrx_stypes *mgmt_stypes;
        const struct ieee80211_iface_combination *iface_combinations;
        int n_iface_combinations;
        u16 software_iftypes;
        u16 n_addresses;
        u16 interface_modes;
        u16 max_acl_mac_addrs;
        u32 flags, regulatory_flags, features;
        u8 ext_features[DIV_ROUND_UP(NUM_NL80211_EXT_FEATURES, 8)];
        u32 ap_sme_capa;
        enum cfg80211_signal_type signal_type;
        int bss_priv_size;
        u8 max_scan_ssids;
        u8 max_sched_scan_reqs;
        u8 max_sched_scan_ssids;
        u8 max_match_sets;
        u16 max_scan_ie_len;
        u16 max_sched_scan_ie_len;
        u32 max_sched_scan_plans;
        u32 max_sched_scan_plan_interval;
        u32 max_sched_scan_plan_iterations;
        int n_cipher_suites;
        const u32 *cipher_suites;
        int n_akm_suites;
        const u32 *akm_suites;
        const struct wiphy_iftype_akm_suites *iftype_akm_suites;
        unsigned int num_iftype_akm_suites;
        u8 retry_short;
        u8 retry_long;
        u32 frag_threshold;
        u32 rts_threshold;
        u8 coverage_class;
        char fw_version[ETHTOOL_FWVERS_LEN];
        u32 hw_version;
    #ifdef CONFIG_PM;
        const struct wiphy_wowlan_support *wowlan;
        struct cfg80211_wowlan *wowlan_config;
    #endif;
        u16 max_remain_on_channel_duration;
        u8 max_num_pmkids;
        u32 available_antennas_tx;
        u32 available_antennas_rx;
        u32 probe_resp_offload;
        const u8 *extended_capabilities, *extended_capabilities_mask;
        u8 extended_capabilities_len;
        const struct wiphy_iftype_ext_capab *iftype_ext_capab;
        unsigned int num_iftype_ext_capab;
        const void *privid;
        struct ieee80211_supported_band *bands[NUM_NL80211_BANDS];
        void (*reg_notifier)(struct wiphy *wiphy, struct regulatory_request *request);
        struct wiphy_radio_cfg *radio_cfg;
        const struct ieee80211_regdomain  *regd;
        struct device dev;
        bool registered;
        struct dentry *debugfsdir;
        const struct ieee80211_ht_cap *ht_capa_mod_mask;
        const struct ieee80211_vht_cap *vht_capa_mod_mask;
        struct list_head wdev_list;
        possible_net_t _net;
    #ifdef CONFIG_CFG80211_WEXT;
        const struct iw_handler_def *wext;
    #endif;
        const struct wiphy_coalesce_support *coalesce;
        const struct wiphy_vendor_command *vendor_commands;
        const struct nl80211_vendor_cmd_info *vendor_events;
        int n_vendor_commands, n_vendor_events;
        u16 max_ap_assoc_sta;
        u8 max_num_csa_counters;
        u32 bss_param_support;
        u32 bss_select_support;
        u8 nan_supported_bands;
        struct wiphy_nan_capa nan_capa;
        u32 txq_limit;
        u32 txq_memory_limit;
        u32 txq_quantum;
        unsigned long tx_queue_len;
        u8 support_mbssid:1, support_only_he_mbssid:1;
        const struct cfg80211_pmsr_capabilities *pmsr_capa;
        struct {
            u64 peer, vif;
            u8 max_retry;
        } tid_config_support;
        u8 max_data_retry_count;
        const struct cfg80211_sar_capa *sar_capa;
        struct rfkill *rfkill;
        u8 mbssid_max_interfaces;
        u8 ema_max_profile_periodicity;
        u16 max_num_akm_suites;
        u16 hw_timestamp_max_peers;
        int n_radio;
        const struct wiphy_radio *radio;
        char priv[] ;
};
```

**Members**

- `mtx`: mutex for the data (structures) of this device
- `perm_addr`: permanent MAC address of this device
- `addr_mask`: If the device supports multiple MAC addresses by masking,
  set this to a mask with variable bits set to 1, e.g. if the last
  four bits are variable then set it to 00-00-00-00-00-0f. The actual
  variable bits shall be determined by the interfaces added, with
  interfaces not matching the mask being rejected to be brought up.
- `addresses`: If the device has more than one address, set this pointer
  to a list of addresses (6 bytes each). The first one will be used
  by default for perm_addr. In this case, the mask should be set to
  all-zeroes. In this case it is assumed that the device can handle
  the same number of arbitrary MAC addresses.
- `mgmt_stypes`: bitmasks of frame subtypes that can be subscribed to or
  transmitted through nl80211, points to an array indexed by interface
  type
- `iface_combinations`: Valid interface combinations array, should not
  list single interface types.
- `n_iface_combinations`: number of entries in **iface_combinations** array.
- `software_iftypes`: bitmask of software interface types, these are not
  subject to any restrictions since they are purely managed in SW.
- `n_addresses`: number of addresses in **addresses**.
- `interface_modes`: bitmask of interfaces types valid for this wiphy,
  must be set by driver
- `max_acl_mac_addrs`: Maximum number of MAC addresses that the device
  supports for ACL.
- `flags`: wiphy flags, see [`enum wiphy_flags`](#c-enum-wiphy_flags)
- `regulatory_flags`: wiphy regulatory flags, see
  `enum ieee80211_regulatory_flags`
- `features`: features advertised to nl80211, see `enum nl80211_feature_flags`.
- `ext_features`: extended features advertised to nl80211, see
  `enum nl80211_ext_feature_index`.
- `ap_sme_capa`: AP SME capabilities, flags from `enum nl80211_ap_sme_features`.
- `signal_type`: signal type reported in [`struct cfg80211_bss`](#c-struct-cfg80211_bss).
- `bss_priv_size`: each BSS struct has private data allocated with it,
  this variable determines its size
- `max_scan_ssids`: maximum number of SSIDs the device can scan for in
  any given scan
- `max_sched_scan_reqs`: maximum number of scheduled scan requests that
  the device can run concurrently.
- `max_sched_scan_ssids`: maximum number of SSIDs the device can scan
  for in any given scheduled scan
- `max_match_sets`: maximum number of match sets the device can handle
  when performing a scheduled scan, 0 if filtering is not
  supported.
- `max_scan_ie_len`: maximum length of user-controlled IEs device can
  add to probe request frames transmitted during a scan, must not
  include fixed IEs like supported rates
- `max_sched_scan_ie_len`: same as max_scan_ie_len, but for scheduled
  scans
- `max_sched_scan_plans`: maximum number of scan plans (scan interval and number
  of iterations) for scheduled scan supported by the device.
- `max_sched_scan_plan_interval`: maximum interval (in seconds) for a
  single scan plan supported by the device.
- `max_sched_scan_plan_iterations`: maximum number of iterations for a single
  scan plan supported by the device.
- `n_cipher_suites`: number of supported cipher suites
- `cipher_suites`: supported cipher suites
- `n_akm_suites`: number of supported AKM suites
- `akm_suites`: supported AKM suites. These are the default AKMs supported if
  the supported AKMs not advertized for a specific interface type in
  iftype_akm_suites.
- `iftype_akm_suites`: array of supported akm suites info per interface type.
  Note that the bits in **iftypes_mask** inside this structure cannot
  overlap (i.e. only one occurrence of each type is allowed across all
  instances of iftype_akm_suites).
- `num_iftype_akm_suites`: number of interface types for which supported akm
  suites are specified separately.
- `retry_short`: Retry limit for short frames (dot11ShortRetryLimit)
- `retry_long`: Retry limit for long frames (dot11LongRetryLimit)
- `frag_threshold`: Fragmentation threshold (dot11FragmentationThreshold);
  -1 = fragmentation disabled, only odd values >= 256 used
- `rts_threshold`: RTS threshold (dot11RTSThreshold); -1 = RTS/CTS disabled
- `coverage_class`: current coverage class
- `fw_version`: firmware version for ethtool reporting
- `hw_version`: hardware version for ethtool reporting
- `wowlan`: WoWLAN support information
- `wowlan_config`: current WoWLAN configuration; this should usually not be
  used since access to it is necessarily racy, use the parameter passed
  to the `suspend()` operation instead.
- `max_remain_on_channel_duration`: Maximum time a remain-on-channel operation
  may request, if implemented.
- `max_num_pmkids`: maximum number of PMKIDs supported by device
- `available_antennas_tx`: bitmap of antennas which are available to be
  configured as TX antennas. Antenna configuration commands will be
  rejected unless this or **available_antennas_rx** is set.
- `available_antennas_rx`: bitmap of antennas which are available to be
  configured as RX antennas. Antenna configuration commands will be
  rejected unless this or **available_antennas_tx** is set.
- `probe_resp_offload`: Bitmap of supported protocols for probe response offloading.
  See `enum nl80211_probe_resp_offload_support_attr`. Only valid
  when the wiphy flag **WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD** is set.
- `extended_capabilities`: extended capabilities supported by the driver,
  additional capabilities might be supported by userspace; these are
  the 802.11 extended capabilities ("Extended Capabilities element")
  and are in the same format as in the information element. See
  802.11-2012 8.4.2.29 for the defined fields. These are the default
  extended capabilities to be used if the capabilities are not specified
  for a specific interface type in iftype_ext_capab.
- `extended_capabilities_mask`: mask of the valid values
- `extended_capabilities_len`: length of the extended capabilities
- `iftype_ext_capab`: array of extended capabilities per interface type
- `num_iftype_ext_capab`: number of interface types for which extended
  capabilities are specified separately.
- `privid`: a pointer that drivers can use to identify if an arbitrary
  wiphy is theirs, e.g. in global notifiers
- `bands`: information about bands/channels supported by this device
- `reg_notifier`: the driver's regulatory notification callback,
  note that if your driver uses [`wiphy_apply_custom_regulatory()`](#c-wiphy_apply_custom_regulatory)
  the reg_notifier's request can be passed as NULL
- `radio_cfg`: configuration of radios belonging to a muli-radio wiphy. This
  struct contains a list of all radio specific attributes and should be
  used only for multi-radio wiphy.
- `regd`: the driver's regulatory domain, if one was requested via
  the [`regulatory_hint()`](#c-regulatory_hint) API. This can be used by the driver
  on the `reg_notifier()` if it chooses to ignore future
  regulatory domain changes caused by other drivers.
- `dev`: (virtual) struct device for this wiphy. The item in
  /sys/class/ieee80211/ points to this. You need use [`set_wiphy_dev()`](#c-set_wiphy_dev)
  (see below).
- `registered`: protects ->resume and ->suspend sysfs callbacks against
  unregister hardware
- `debugfsdir`: debugfs directory used for this wiphy (ieee80211/\<wiphyname>).
  It will be renamed automatically on wiphy renames
- `ht_capa_mod_mask`: Specify what ht_cap values can be over-ridden.
  If null, then none can be over-ridden.
- `vht_capa_mod_mask`: Specify what VHT capabilities can be over-ridden.
  If null, then none can be over-ridden.
- `wdev_list`: the list of associated (virtual) interfaces; this list must
  not be modified by the driver, but can be read with RTNL/RCU protection.
- `_net`: the network namespace this wiphy currently lives in
- `wext`: wireless extension handlers
- `coalesce`: packet coalescing support information
- `vendor_commands`: array of vendor commands supported by the hardware
- `vendor_events`: array of vendor events supported by the hardware
- `n_vendor_commands`: number of vendor commands
- `n_vendor_events`: number of vendor events
- `max_ap_assoc_sta`: maximum number of associated stations supported in AP mode
  (including P2P GO) or 0 to indicate no such limit is advertised. The
  driver is allowed to advertise a theoretical limit that it can reach in
  some cases, but may not always reach.
- `max_num_csa_counters`: Number of supported csa_counters in beacons
  and probe responses.  This value should be set if the driver
  wishes to limit the number of csa counters. Default (0) means
  infinite.
- `bss_param_support`: bitmask indicating which bss_parameters as defined in
  [`struct bss_parameters`](#c-struct-bss_parameters) the driver can actually handle in the
  .`change_bss()` callback. The bit positions are defined in `enum wiphy_bss_param_flags`.
- `bss_select_support`: bitmask indicating the BSS selection criteria supported
  by the driver in the .`connect()` callback. The bit position maps to the
  attribute indices defined in `enum nl80211_bss_select_attr`.
- `nan_supported_bands`: bands supported by the device in NAN mode, a
  bitmap of `enum nl80211_band` values.  For instance, for
  NL80211_BAND_2GHZ, bit 0 would be set
  (i.e. BIT(NL80211_BAND_2GHZ)).
- `nan_capa`: NAN capabilities
- `txq_limit`: configuration of internal TX queue frame limit
- `txq_memory_limit`: configuration internal TX queue memory limit
- `txq_quantum`: configuration of internal TX queue scheduler quantum
- `tx_queue_len`: allow setting transmit queue len for drivers not using
  wake_tx_queue
- `support_mbssid`: can HW support association with nontransmitted AP
- `support_only_he_mbssid`: don't parse MBSSID elements if it is not
  HE AP, in order to avoid compatibility issues.
  **support_mbssid** must be set for this to have any effect.
- `pmsr_capa`: peer measurement capabilities
- `tid_config_support`: describes the per-TID config support that the
  device has
- `tid_config_support.peer`: bitmap of attributes (configurations)
  supported by the driver for each peer
- `tid_config_support.vif`: bitmap of attributes (configurations)
  supported by the driver for each vif
- `tid_config_support.max_retry`: maximum supported retry count for
  long/short retry configuration
- `max_data_retry_count`: maximum supported per TID retry count for
  configuration through the `NL80211_TID_CONFIG_ATTR_RETRY_SHORT` and
  `NL80211_TID_CONFIG_ATTR_RETRY_LONG` attributes
- `sar_capa`: SAR control capabilities
- `rfkill`: a pointer to the rfkill structure
- `mbssid_max_interfaces`: maximum number of interfaces supported by the driver
  in a multiple BSSID set. This field must be set to a non-zero value
  by the driver to advertise MBSSID support.
- `ema_max_profile_periodicity`: maximum profile periodicity supported by
  the driver. Setting this field to a non-zero value indicates that the
  driver supports enhanced multi-BSSID advertisements (EMA AP).
- `max_num_akm_suites`: maximum number of AKM suites allowed for
  configuration through `NL80211_CMD_CONNECT`, `NL80211_CMD_ASSOCIATE` and
  `NL80211_CMD_START_AP`. Set to NL80211_MAX_NR_AKM_SUITES if not set by
  driver. If set by driver minimum allowed value is
  NL80211_MAX_NR_AKM_SUITES in order to avoid compatibility issues with
  legacy userspace and maximum allowed value is
  CFG80211_MAX_NUM_AKM_SUITES.
- `hw_timestamp_max_peers`: maximum number of peers that the driver supports
  enabling HW timestamping for concurrently. Setting this field to a
  non-zero value indicates that the driver supports HW timestamping.
  A value of `CFG80211_HW_TIMESTAMP_ALL_PEERS` indicates the driver
  supports enabling HW timestamping for all peers (i.e. no need to
  specify a mac address).
- `n_radio`: number of radios
- `radio`: radios belonging to this wiphy
- `priv`: driver private data (sized according to [`wiphy_new()`](#c-wiphy_new) parameter)

#### <a id="c-wiphy_priv"></a>`wiphy_priv()`

```c
void * wiphy_priv(struct wiphy *wiphy)
```

return priv from wiphy

**Parameters**

- `struct wiphy *wiphy`: the wiphy whose priv pointer to return

**Return**

The priv of **wiphy**.

#### <a id="c-priv_to_wiphy"></a>`priv_to_wiphy()`

```c
struct wiphy * priv_to_wiphy(void *priv)
```

return the wiphy containing the priv

**Parameters**

- `void *priv`: a pointer previously returned by wiphy_priv

**Return**

The wiphy of **priv**.

#### <a id="c-set_wiphy_dev"></a>`set_wiphy_dev()`

```c
void set_wiphy_dev(struct wiphy *wiphy, struct device *dev)
```

set device pointer for wiphy

**Parameters**

- `struct wiphy *wiphy`: The wiphy whose device to bind
- `struct device *dev`: The device to parent it to

#### <a id="c-wiphy_dev"></a>`wiphy_dev()`

```c
struct device * wiphy_dev(struct wiphy *wiphy)
```

get wiphy dev pointer

**Parameters**

- `struct wiphy *wiphy`: The wiphy whose device struct to look up

**Return**

The dev of **wiphy**.

#### <a id="c-wiphy_name"></a>`wiphy_name()`

```c
const char * wiphy_name(const struct wiphy *wiphy)
```

get wiphy name

**Parameters**

- `const struct wiphy *wiphy`: The wiphy whose name to return

**Return**

The name of **wiphy**.

#### <a id="c-wiphy_new"></a>`wiphy_new()`

```c
struct wiphy * wiphy_new(const struct cfg80211_ops *ops, int sizeof_priv)
```

create a new wiphy for use with cfg80211

**Parameters**

- `const struct cfg80211_ops *ops`: The configuration operations for this device
- `int sizeof_priv`: The size of the private area to allocate

**Description**

Create a new wiphy and associate the given operations with it.
**sizeof_priv** bytes are allocated for private use.

**Return**

A pointer to the new wiphy. This pointer must be
assigned to each netdev's ieee80211_ptr for proper operation.

#### <a id="c-wiphy_register"></a>`wiphy_register()`

```c
int wiphy_register(struct wiphy *wiphy)
```

register a wiphy with cfg80211

**Parameters**

- `struct wiphy *wiphy`: The wiphy to register.

**Return**

A non-negative wiphy index or a negative error code.

#### <a id="c-wiphy_unregister"></a>`wiphy_unregister()`

```c
void wiphy_unregister(struct wiphy *wiphy)
```

deregister a wiphy from cfg80211

**Parameters**

- `struct wiphy *wiphy`: The wiphy to unregister.

**Description**

After this call, no more requests can be made with this priv
pointer, but the call may sleep to wait for an outstanding
request that is being handled.

#### <a id="c-wiphy_free"></a>`wiphy_free()`

```c
void wiphy_free(struct wiphy *wiphy)
```

free wiphy

**Parameters**

- `struct wiphy *wiphy`: The wiphy to free

#### <a id="c-struct-wireless_dev"></a>`struct wireless_dev`

wireless device state

**Definition**

```c
struct wireless_dev {
        struct wiphy *wiphy;
        enum nl80211_iftype iftype;
        struct list_head list;
        struct net_device *netdev;
        u32 identifier;
        struct list_head mgmt_registrations;
        u8 mgmt_registrations_need_update:1;
        bool use_4addr, is_running, registered, registering;
        u8 address[ETH_ALEN] ;
        struct cfg80211_conn *conn;
        struct cfg80211_cached_keys *connect_keys;
        enum ieee80211_bss_type conn_bss_type;
        u32 conn_owner_nlportid;
        struct work_struct disconnect_wk;
        u8 disconnect_bssid[ETH_ALEN];
        struct list_head event_list;
        spinlock_t event_lock;
        u8 connected:1;
        bool ps;
        int ps_timeout;
        u32 ap_unexpected_nlportid;
        u32 owner_nlportid;
        bool nl_owner_dead;
    #ifdef CONFIG_CFG80211_WEXT;
        struct {
            struct cfg80211_ibss_params ibss;
            struct cfg80211_connect_params connect;
            struct cfg80211_cached_keys *keys;
            const u8 *ie;
            size_t ie_len;
            u8 bssid[ETH_ALEN];
            u8 prev_bssid[ETH_ALEN];
            u8 ssid[IEEE80211_MAX_SSID_LEN];
            s8 default_key, default_mgmt_key;
            bool prev_bssid_valid;
        } wext;
    #endif;
        struct wiphy_work cqm_rssi_work;
        struct cfg80211_cqm_config  *cqm_config;
        struct list_head pmsr_list;
        spinlock_t pmsr_lock;
        struct work_struct pmsr_free_wk;
        unsigned long unprot_beacon_reported;
        union {
            struct {
                u8 connected_addr[ETH_ALEN] ;
                u8 ssid[IEEE80211_MAX_SSID_LEN];
                u8 ssid_len;
            } client;
            struct {
                int beacon_interval;
                struct cfg80211_chan_def preset_chandef;
                struct cfg80211_chan_def chandef;
                u8 id[IEEE80211_MAX_MESH_ID_LEN];
                u8 id_len, id_up_len;
            } mesh;
            struct {
                struct cfg80211_chan_def preset_chandef;
                u8 ssid[IEEE80211_MAX_SSID_LEN];
                u8 ssid_len;
            } ap;
            struct {
                struct cfg80211_internal_bss *current_bss;
                struct cfg80211_chan_def chandef;
                int beacon_interval;
                u8 ssid[IEEE80211_MAX_SSID_LEN];
                u8 ssid_len;
            } ibss;
            struct {
                struct cfg80211_chan_def chandef;
            } ocb;
            struct {
                u8 cluster_id[ETH_ALEN] ;
            } nan;
        } u;
        struct {
            u8 addr[ETH_ALEN] ;
            union {
                struct {
                    unsigned int beacon_interval;
                    struct cfg80211_chan_def chandef;
                } ap;
                struct {
                    struct cfg80211_internal_bss *current_bss;
                } client;
            };
            bool cac_started;
            unsigned long cac_start_time;
            unsigned int cac_time_ms;
        } links[IEEE80211_MLD_MAX_NUM_LINKS];
        u16 valid_links;
        u32 radio_mask;
};
```

**Members**

- `wiphy`: pointer to hardware description
- `iftype`: interface type
- `list`: (private) Used to collect the interfaces
- `netdev`: (private) Used to reference back to the netdev, may be `NULL`
- `identifier`: (private) Identifier used in nl80211 to identify this
  wireless device if it has no netdev
- `mgmt_registrations`: list of registrations for management frames
- `mgmt_registrations_need_update`: mgmt registrations were updated,
  need to propagate the update to the driver
- `use_4addr`: indicates 4addr mode is used on this interface, must be
  set by driver (if supported) on add_interface BEFORE registering the
  netdev and may otherwise be used by driver read-only, will be update
  by cfg80211 on change_interface
- `is_running`: true if this is a non-netdev device that has been started, e.g.
  the P2P Device.
- `registered`: is this wdev already registered with cfg80211
- `registering`: indicates we're doing registration under wiphy lock
  for the notifier
- `address`: The address for this device, valid only if **netdev** is `NULL`
- `conn`: (private) cfg80211 software SME connection state machine data
- `connect_keys`: (private) keys to set after connection is established
- `conn_bss_type`: connecting/connected BSS type
- `conn_owner_nlportid`: (private) connection owner socket port ID
- `disconnect_wk`: (private) auto-disconnect work
- `disconnect_bssid`: (private) the BSSID to use for auto-disconnect
- `event_list`: (private) list for internal event processing
- `event_lock`: (private) lock for event list
- `connected`: indicates if connected or not (STA mode)
- `ps`: powersave mode is enabled
- `ps_timeout`: dynamic powersave timeout
- `ap_unexpected_nlportid`: (private) netlink port ID of application
  registered for unexpected class 3 frames (AP mode)
- `owner_nlportid`: (private) owner socket port ID
- `nl_owner_dead`: (private) owner socket went away
- `wext`: (private) Used by the internal wireless extensions compat code
- `wext.ibss`: (private) IBSS data part of wext handling
- `wext.connect`: (private) connection handling data
- `wext.keys`: (private) (WEP) key data
- `wext.ie`: (private) extra elements for association
- `wext.ie_len`: (private) length of extra elements
- `wext.bssid`: (private) selected network BSSID
- `wext.prev_bssid`: (private) previous BSSID for reassociation
- `wext.ssid`: (private) selected network SSID
- `wext.default_key`: (private) selected default key index
- `wext.default_mgmt_key`: (private) selected default management key index
- `wext.prev_bssid_valid`: (private) previous BSSID validity
- `cqm_rssi_work`: (private) CQM RSSI reporting work
- `cqm_config`: (private) nl80211 RSSI monitor state
- `pmsr_list`: (private) peer measurement requests
- `pmsr_lock`: (private) peer measurements requests/results lock
- `pmsr_free_wk`: (private) peer measurements cleanup work
- `unprot_beacon_reported`: (private) timestamp of last
  unprotected beacon report
- `u`: union containing data specific to **iftype**
- `links`: array of `IEEE80211_MLD_MAX_NUM_LINKS` elements containing **addr**
  **ap** and **client** for each link
- `{unnamed_union}`: anonymous
- `links.cac_started`: true if DFS channel availability check has been
  started
- `links.cac_start_time`: timestamp (jiffies) when the dfs state was
  entered.
- `links.cac_time_ms`: CAC time in ms
- `valid_links`: bitmap describing what elements of **links** are valid
- `radio_mask`: Bitmask of radios that this interface is allowed to operate on.

**Description**

For netdevs, this structure must be allocated by the driver
that uses the ieee80211_ptr field in struct net_device (this
is intentional so it can be allocated along with the netdev.)
It need not be registered then as netdev registration will
be intercepted by cfg80211 to see the new wireless device,
however, drivers must lock the wiphy before registering or
unregistering netdevs if they pre-create any netdevs (in ops
called from cfg80211, the wiphy is already locked.)

For non-netdev uses, it must also be allocated by the driver
in response to the cfg80211 callbacks that require it, as
there's no netdev registration in that case it may not be
allocated outside of callback operations that return it.

#### <a id="c-wdev_priv"></a>`wdev_priv()`

```c
void * wdev_priv(struct wireless_dev *wdev)
```

return wiphy priv from wireless_dev

**Parameters**

- `struct wireless_dev *wdev`: The wireless device whose wiphy's priv pointer to return

**Return**

The wiphy priv of **wdev**.

#### <a id="c-cfg80211_check_combinations"></a>`cfg80211_check_combinations()`

```c
int cfg80211_check_combinations(struct wiphy *wiphy, struct iface_combination_params *params)
```

check interface combinations

**Parameters**

- `struct wiphy *wiphy`: the wiphy
- `struct iface_combination_params *params`: the interface combinations parameter

**Description**

This function can be called by the driver to check whether a
combination of interfaces and their types are allowed according to
the interface combinations.

**Return**

0 if combinations are allowed. Non-zero on error.


<a id="rst-actions-and-configuration"></a>

## Actions and configuration


Each wireless device and each virtual interface offer a set of configuration
operations and other actions that are invoked by userspace. Each of these
actions is described in the operations structure, and the parameters these
operations use are described separately.

Additionally, some operations are asynchronous and expect to get status
information via some functions that drivers need to call.

Scanning and BSS list handling with its associated functionality is described
in a separate chapter.



#### <a id="c-struct-vif_params"></a>`struct vif_params`

describes virtual interface parameters

**Definition**

```c
struct vif_params {
    u32 flags;
    int use_4addr;
    u8 macaddr[ETH_ALEN];
    const u8 *vht_mumimo_groups;
    const u8 *vht_mumimo_follow_addr;
};
```

**Members**

- `flags`: monitor interface flags, unchanged if 0, otherwise
  `MONITOR_FLAG_CHANGED` will be set
- `use_4addr`: use 4-address frames
- `macaddr`: address to use for this virtual interface.
  If this parameter is set to zero address the driver may
  determine the address as needed.
  This feature is only fully supported by drivers that enable the
  `NL80211_FEATURE_MAC_ON_CREATE` flag.  Others may support creating
  * only p2p devices with specified MAC.
- `vht_mumimo_groups`: MU-MIMO groupID, used for monitoring MU-MIMO packets
  belonging to that MU-MIMO groupID; `NULL` if not changed
- `vht_mumimo_follow_addr`: MU-MIMO follow address, used for monitoring
  MU-MIMO packets going to the specified station; `NULL` if not changed

#### <a id="c-struct-key_params"></a>`struct key_params`

key information

**Definition**

```c
struct key_params {
    const u8 *key;
    const u8 *seq;
    int key_len;
    int seq_len;
    u16 vlan_id;
    u32 cipher;
    enum nl80211_key_mode mode;
};
```

**Members**

- `key`: key material
- `seq`: sequence counter (IV/PN), must be in little endian,
  length given by **seq_len**.
- `key_len`: length of key material
- `seq_len`: length of **seq**.
- `vlan_id`: vlan_id for VLAN group key (if nonzero)
- `cipher`: cipher suite selector
- `mode`: key install mode (RX_TX, NO_TX or SET_TX)

**Description**

Information about a key

#### <a id="c-enum-survey_info_flags"></a>`enum survey_info_flags`

survey information flags

**Constants**

- `SURVEY_INFO_NOISE_DBM`: noise (in dBm) was filled in
- `SURVEY_INFO_IN_USE`: channel is currently being used
- `SURVEY_INFO_TIME`: active time (in ms) was filled in
- `SURVEY_INFO_TIME_BUSY`: busy time was filled in
- `SURVEY_INFO_TIME_EXT_BUSY`: extension channel busy time was filled in
- `SURVEY_INFO_TIME_RX`: receive time was filled in
- `SURVEY_INFO_TIME_TX`: transmit time was filled in
- `SURVEY_INFO_TIME_SCAN`: scan time was filled in
- `SURVEY_INFO_TIME_BSS_RX`: local BSS receive time was filled in

**Description**

Used by the driver to indicate which info in [`struct survey_info`](#c-struct-survey_info)
it has filled in during the `get_survey()`.

#### <a id="c-struct-survey_info"></a>`struct survey_info`

channel survey response

**Definition**

```c
struct survey_info {
    struct ieee80211_channel *channel;
    u64 time;
    u64 time_busy;
    u64 time_ext_busy;
    u64 time_rx;
    u64 time_tx;
    u64 time_scan;
    u64 time_bss_rx;
    u32 filled;
    s8 noise;
};
```

**Members**

- `channel`: the channel this survey record reports, may be `NULL` for a single
  record to report global statistics
- `time`: amount of time in ms the radio was turn on (on the channel)
- `time_busy`: amount of time the primary channel was sensed busy
- `time_ext_busy`: amount of time the extension channel was sensed busy
- `time_rx`: amount of time the radio spent receiving data
- `time_tx`: amount of time the radio spent transmitting data
- `time_scan`: amount of time the radio spent for scanning
- `time_bss_rx`: amount of time the radio spent receiving data on a local BSS
- `filled`: bitflag of flags from [`enum survey_info_flags`](#c-enum-survey_info_flags)
- `noise`: channel noise in dBm. This and all following fields are
  optional

**Description**

Used by `dump_survey()` to report back per-channel survey information.

This structure can later be expanded with things like
channel duty cycle etc.

#### <a id="c-struct-cfg80211_crypto_settings"></a>`struct cfg80211_crypto_settings`

Crypto settings

**Definition**

```c
struct cfg80211_crypto_settings {
    u32 wpa_versions;
    u32 cipher_group;
    int n_ciphers_pairwise;
    u32 ciphers_pairwise[NL80211_MAX_NR_CIPHER_SUITES];
    int n_akm_suites;
    u32 akm_suites[CFG80211_MAX_NUM_AKM_SUITES];
    bool control_port;
    __be16 control_port_ethertype;
    bool control_port_no_encrypt;
    bool control_port_over_nl80211;
    bool control_port_no_preauth;
    const u8 *psk;
    const u8 *sae_pwd;
    u8 sae_pwd_len;
    enum nl80211_sae_pwe_mechanism sae_pwe;
};
```

**Members**

- `wpa_versions`: indicates which, if any, WPA versions are enabled
  (from enum nl80211_wpa_versions)
- `cipher_group`: group key cipher suite (or 0 if unset)
- `n_ciphers_pairwise`: number of AP supported unicast ciphers
- `ciphers_pairwise`: unicast key cipher suites
- `n_akm_suites`: number of AKM suites
- `akm_suites`: AKM suites
- `control_port`: Whether user space controls IEEE 802.1X port, i.e.,
  sets/clears `NL80211_STA_FLAG_AUTHORIZED`. If true, the driver is
  required to assume that the port is unauthorized until authorized by
  user space. Otherwise, port is marked authorized by default.
- `control_port_ethertype`: the control port protocol that should be
  allowed through even on unauthorized ports
- `control_port_no_encrypt`: TRUE to prevent encryption of control port
  protocol frames.
- `control_port_over_nl80211`: TRUE if userspace expects to exchange control
  port frames over NL80211 instead of the network interface.
- `control_port_no_preauth`: disables pre-auth rx over the nl80211 control
  port for mac80211
- `psk`: PSK (for devices supporting 4-way-handshake offload)
- `sae_pwd`: password for SAE authentication (for devices supporting SAE
  offload)
- `sae_pwd_len`: length of SAE password (for devices supporting SAE offload)
- `sae_pwe`: The mechanisms allowed for SAE PWE derivation:

**Description**

- NL80211_SAE_PWE_UNSPECIFIED:
  Not-specified, used to indicate userspace did not specify any
  preference. The driver should follow its internal policy in
  such a scenario.

- NL80211_SAE_PWE_HUNT_AND_PECK:
  Allow hunting-and-pecking loop only

- NL80211_SAE_PWE_HASH_TO_ELEMENT:
  Allow hash-to-element only

- NL80211_SAE_PWE_BOTH:
  Allow either hunting-and-pecking loop or hash-to-element

#### <a id="c-struct-cfg80211_beacon_data"></a>`struct cfg80211_beacon_data`

beacon data

**Definition**

```c
struct cfg80211_beacon_data {
    unsigned int link_id;
    const u8 *head, *tail;
    const u8 *beacon_ies;
    const u8 *proberesp_ies;
    const u8 *assocresp_ies;
    const u8 *probe_resp;
    const u8 *lci;
    const u8 *civicloc;
    struct cfg80211_mbssid_elems *mbssid_ies;
    struct cfg80211_rnr_elems *rnr_ies;
    s8 ftm_responder;
    size_t head_len, tail_len;
    size_t beacon_ies_len;
    size_t proberesp_ies_len;
    size_t assocresp_ies_len;
    size_t probe_resp_len;
    size_t lci_len;
    size_t civicloc_len;
    struct cfg80211_he_bss_color he_bss_color;
    bool he_bss_color_valid;
};
```

**Members**

- `link_id`: the link ID for the AP MLD link sending this beacon
- `head`: head portion of beacon (before TIM IE)
  or `NULL` if not changed
- `tail`: tail portion of beacon (after TIM IE)
  or `NULL` if not changed
- `beacon_ies`: extra information element(s) to add into Beacon frames or `NULL`
- `proberesp_ies`: extra information element(s) to add into Probe Response
  frames or `NULL`
- `assocresp_ies`: extra information element(s) to add into (Re)Association
  Response frames or `NULL`
- `probe_resp`: probe response template (AP mode only)
- `lci`: Measurement Report element content, starting with Measurement Token
  (measurement type 8)
- `civicloc`: Measurement Report element content, starting with Measurement
  Token (measurement type 11)
- `mbssid_ies`: multiple BSSID elements
- `rnr_ies`: reduced neighbor report elements
- `ftm_responder`: enable FTM responder functionality; -1 for no change
  (which also implies no change in LCI/civic location data)
- `head_len`: length of **head**
- `tail_len`: length of **tail**
- `beacon_ies_len`: length of beacon_ies in octets
- `proberesp_ies_len`: length of proberesp_ies in octets
- `assocresp_ies_len`: length of assocresp_ies in octets
- `probe_resp_len`: length of probe response template (**probe_resp**)
- `lci_len`: LCI data length
- `civicloc_len`: Civic location data length
- `he_bss_color`: BSS Color settings
- `he_bss_color_valid`: indicates whether bss color
  attribute is present in beacon data or not.

#### <a id="c-struct-cfg80211_ap_settings"></a>`struct cfg80211_ap_settings`

AP configuration

**Definition**

```c
struct cfg80211_ap_settings {
    struct cfg80211_chan_def chandef;
    struct cfg80211_beacon_data beacon;
    int beacon_interval, dtim_period;
    const u8 *ssid;
    size_t ssid_len;
    enum nl80211_hidden_ssid hidden_ssid;
    struct cfg80211_crypto_settings crypto;
    bool privacy;
    enum nl80211_auth_type auth_type;
    int inactivity_timeout;
    u8 p2p_ctwindow;
    bool p2p_opp_ps;
    const struct cfg80211_acl_data *acl;
    bool pbss;
    struct cfg80211_bitrate_mask beacon_rate;
    const struct ieee80211_ht_cap *ht_cap;
    const struct ieee80211_vht_cap *vht_cap;
    const struct ieee80211_he_cap_elem *he_cap;
    const struct ieee80211_he_operation *he_oper;
    const struct ieee80211_eht_cap_elem *eht_cap;
    const struct ieee80211_eht_operation *eht_oper;
    const struct ieee80211_uhr_operation *uhr_oper;
    bool ht_required, vht_required, he_required, sae_h2e_required;
    bool twt_responder;
    u32 flags;
    struct ieee80211_he_obss_pd he_obss_pd;
    struct cfg80211_fils_discovery fils_discovery;
    struct cfg80211_unsol_bcast_probe_resp unsol_bcast_probe_resp;
    struct cfg80211_mbssid_config mbssid_config;
    u8 s1g_long_beacon_period;
    struct cfg80211_s1g_short_beacon s1g_short_beacon;
};
```

**Members**

- `chandef`: defines the channel to use
- `beacon`: beacon data
- `beacon_interval`: beacon interval
- `dtim_period`: DTIM period
- `ssid`: SSID to be used in the BSS (note: may be `NULL` if not provided from
  user space)
- `ssid_len`: length of **ssid**
- `hidden_ssid`: whether to hide the SSID in Beacon/Probe Response frames
- `crypto`: crypto settings
- `privacy`: the BSS uses privacy
- `auth_type`: Authentication type (algorithm)
- `inactivity_timeout`: time in seconds to determine station's inactivity.
- `p2p_ctwindow`: P2P CT Window
- `p2p_opp_ps`: P2P opportunistic PS
- `acl`: ACL configuration used by the drivers which has support for
  MAC address based access control
- `pbss`: If set, start as a PCP instead of AP. Relevant for DMG
  networks.
- `beacon_rate`: bitrate to be used for beacons
- `ht_cap`: HT capabilities (or `NULL` if HT isn't enabled)
- `vht_cap`: VHT capabilities (or `NULL` if VHT isn't enabled)
- `he_cap`: HE capabilities (or `NULL` if HE isn't enabled)
- `he_oper`: HE operation IE (or `NULL` if HE isn't enabled)
- `eht_cap`: EHT capabilities (or `NULL` if EHT isn't enabled)
- `eht_oper`: EHT operation IE (or `NULL` if EHT isn't enabled)
- `uhr_oper`: UHR operation (or `NULL` if UHR isn't enabled)
- `ht_required`: stations must support HT
- `vht_required`: stations must support VHT
- `he_required`: stations must support HE
- `sae_h2e_required`: stations must support direct H2E technique in SAE
- `twt_responder`: Enable Target Wait Time
- `flags`: flags, as defined in `enum nl80211_ap_settings_flags`
- `he_obss_pd`: OBSS Packet Detection settings
- `fils_discovery`: FILS discovery transmission parameters
- `unsol_bcast_probe_resp`: Unsolicited broadcast probe response parameters
- `mbssid_config`: AP settings for multiple bssid
- `s1g_long_beacon_period`: S1G long beacon period
- `s1g_short_beacon`: S1G short beacon data

**Description**

Used to configure an AP interface.

#### <a id="c-struct-station_parameters"></a>`struct station_parameters`

station parameters

**Definition**

```c
struct station_parameters {
    struct net_device *vlan;
    u32 sta_flags_mask, sta_flags_set;
    u32 sta_modify_mask;
    int listen_interval;
    u16 aid;
    u16 vlan_id;
    u16 peer_aid;
    u8 plink_action;
    u8 plink_state;
    u8 uapsd_queues;
    u8 max_sp;
    enum nl80211_mesh_power_mode local_pm;
    u16 capability;
    const u8 *ext_capab;
    u8 ext_capab_len;
    const u8 *supported_channels;
    u8 supported_channels_len;
    const u8 *supported_oper_classes;
    u8 supported_oper_classes_len;
    int support_p2p_ps;
    u16 airtime_weight;
    bool eml_cap_present;
    u16 eml_cap;
    struct link_station_parameters link_sta_params;
    bool epp_peer;
};
```

**Members**

- `vlan`: vlan interface station should belong to
- `sta_flags_mask`: station flags that changed
  (bitmask of BIT(`NL80211_STA_FLAG_`...))
- `sta_flags_set`: station flags values
  (bitmask of BIT(`NL80211_STA_FLAG_`...))
- `sta_modify_mask`: bitmap indicating which parameters changed
  (for those that don't have a natural "no change" value),
  see `enum station_parameters_apply_mask`
- `listen_interval`: listen interval or -1 for no change
- `aid`: AID or zero for no change
- `vlan_id`: VLAN ID for station (if nonzero)
- `peer_aid`: mesh peer AID or zero for no change
- `plink_action`: plink action to take
- `plink_state`: set the peer link state for a station
- `uapsd_queues`: bitmap of queues configured for uapsd. same format
  as the AC bitmap in the QoS info field
- `max_sp`: max Service Period. same format as the MAX_SP in the
  QoS info field (but already shifted down)
- `local_pm`: local link-specific mesh power save mode (no change when set
  to unknown)
- `capability`: station capability
- `ext_capab`: extended capabilities of the station
- `ext_capab_len`: number of extended capabilities
- `supported_channels`: supported channels in IEEE 802.11 format
- `supported_channels_len`: number of supported channels
- `supported_oper_classes`: supported oper classes in IEEE 802.11 format
- `supported_oper_classes_len`: number of supported operating classes
- `support_p2p_ps`: information if station supports P2P PS mechanism
- `airtime_weight`: airtime scheduler weight for this station
- `eml_cap_present`: Specifies if EML capabilities field (**eml_cap**) is
  present/updated
- `eml_cap`: EML capabilities of this station
- `link_sta_params`: link related params.
- `epp_peer`: EPP peer indication

**Description**

Used to change and create a new station.

#### <a id="c-enum-rate_info_flags"></a>`enum rate_info_flags`

bitrate info flags

**Constants**

- `RATE_INFO_FLAGS_MCS`: mcs field filled with HT MCS
- `RATE_INFO_FLAGS_VHT_MCS`: mcs field filled with VHT MCS
- `RATE_INFO_FLAGS_SHORT_GI`: 400ns guard interval
- `RATE_INFO_FLAGS_DMG`: 60GHz MCS
- `RATE_INFO_FLAGS_HE_MCS`: HE MCS information
- `RATE_INFO_FLAGS_EDMG`: 60GHz MCS in EDMG mode
- `RATE_INFO_FLAGS_EXTENDED_SC_DMG`: 60GHz extended SC MCS
- `RATE_INFO_FLAGS_EHT_MCS`: EHT MCS information
- `RATE_INFO_FLAGS_S1G_MCS`: MCS field filled with S1G MCS
- `RATE_INFO_FLAGS_UHR_MCS`: UHR MCS information
- `RATE_INFO_FLAGS_UHR_ELR_MCS`: UHR ELR MCS was used
  (set together with **RATE_INFO_FLAGS_UHR_MCS**)
- `RATE_INFO_FLAGS_UHR_IM`: UHR Interference Mitigation
  was used

**Description**

Used by the driver to indicate the specific rate transmission
type for 802.11n transmissions.

#### <a id="c-struct-rate_info"></a>`struct rate_info`

bitrate information

**Definition**

```c
struct rate_info {
    u16 flags;
    u16 legacy;
    u8 mcs;
    u8 nss;
    u8 bw;
    u8 he_gi;
    u8 he_dcm;
    u8 he_ru_alloc;
    u8 n_bonded_ch;
    u8 eht_gi;
    u8 eht_ru_alloc;
};
```

**Members**

- `flags`: bitflag of flags from [`enum rate_info_flags`](#c-enum-rate_info_flags)
- `legacy`: bitrate in 100kbit/s for 802.11abg
- `mcs`: mcs index if struct describes an HT/VHT/HE/EHT/S1G/UHR rate
- `nss`: number of streams (VHT & HE only)
- `bw`: bandwidth (from `enum rate_info_bw`)
- `he_gi`: HE guard interval (from `enum nl80211_he_gi`)
- `he_dcm`: HE DCM value
- `he_ru_alloc`: HE RU allocation (from `enum nl80211_he_ru_alloc`,
  only valid if bw is `RATE_INFO_BW_HE_RU`)
- `n_bonded_ch`: In case of EDMG the number of bonded channels (1-4)
- `eht_gi`: EHT guard interval (from `enum nl80211_eht_gi`)
- `eht_ru_alloc`: EHT RU allocation (from `enum nl80211_eht_ru_alloc`,
  only valid if bw is `RATE_INFO_BW_EHT_RU`)

**Description**

Information about a receiving or transmitting bitrate

#### <a id="c-struct-station_info"></a>`struct station_info`

station information

**Definition**

```c
struct station_info {
    u64 filled;
    u32 connected_time;
    u32 inactive_time;
    u64 assoc_at;
    u64 rx_bytes;
    u64 tx_bytes;
    s8 signal;
    s8 signal_avg;
    u8 chains;
    s8 chain_signal[IEEE80211_MAX_CHAINS];
    s8 chain_signal_avg[IEEE80211_MAX_CHAINS];
    struct rate_info txrate;
    struct rate_info rxrate;
    u32 rx_packets;
    u32 tx_packets;
    u32 tx_retries;
    u32 tx_failed;
    u32 rx_dropped_misc;
    struct sta_bss_parameters bss_param;
    struct nl80211_sta_flag_update sta_flags;
    int generation;
    u32 beacon_loss_count;
    const u8 *assoc_req_ies;
    size_t assoc_req_ies_len;
    s64 t_offset;
    u16 llid;
    u16 plid;
    u8 plink_state;
    u8 connected_to_gate;
    u8 connected_to_as;
    u32 airtime_link_metric;
    enum nl80211_mesh_power_mode local_pm;
    enum nl80211_mesh_power_mode peer_pm;
    enum nl80211_mesh_power_mode nonpeer_pm;
    u32 expected_throughput;
    u16 airtime_weight;
    s8 ack_signal;
    s8 avg_ack_signal;
    struct cfg80211_tid_stats *pertid;
    u64 tx_duration;
    u64 rx_duration;
    u64 rx_beacon;
    u8 rx_beacon_signal_avg;
    u32 rx_mpdu_count;
    u32 fcs_err_count;
    bool mlo_params_valid;
    u8 assoc_link_id;
    u8 mld_addr[ETH_ALEN] ;
    const u8 *assoc_resp_ies;
    size_t assoc_resp_ies_len;
    u16 valid_links;
    struct link_station_info *links[IEEE80211_MLD_MAX_NUM_LINKS];
};
```

**Members**

- `filled`: bitflag of flags using the bits of `enum nl80211_sta_info` to
  indicate the relevant values in this struct for them
- `connected_time`: time(in secs) since a station is last connected
- `inactive_time`: time since last station activity (tx/rx) in milliseconds
- `assoc_at`: bootime (ns) of the last association
- `rx_bytes`: bytes (size of MPDUs) received from this station
- `tx_bytes`: bytes (size of MPDUs) transmitted to this station
- `signal`: The signal strength, type depends on the wiphy's signal_type.
  For CFG80211_SIGNAL_TYPE_MBM, value is expressed in _dBm_.
- `signal_avg`: Average signal strength, type depends on the wiphy's signal_type.
  For CFG80211_SIGNAL_TYPE_MBM, value is expressed in _dBm_.
- `chains`: bitmask for filled values in **chain_signal**, **chain_signal_avg**
- `chain_signal`: per-chain signal strength of last received packet in dBm
- `chain_signal_avg`: per-chain signal strength average in dBm
- `txrate`: current unicast bitrate from this station
- `rxrate`: current unicast bitrate to this station
- `rx_packets`: packets (MSDUs & MMPDUs) received from this station
- `tx_packets`: packets (MSDUs & MMPDUs) transmitted to this station
- `tx_retries`: cumulative retry counts (MPDUs)
- `tx_failed`: number of failed transmissions (MPDUs) (retries exceeded, no ACK)
- `rx_dropped_misc`: Dropped for un-specified reason.
- `bss_param`: current BSS parameters
- `sta_flags`: station flags mask & values
- `generation`: generation number for nl80211 dumps.
  This number should increase every time the list of stations
  changes, i.e. when a station is added or removed, so that
  userspace can tell whether it got a consistent snapshot.
- `beacon_loss_count`: Number of times beacon loss event has triggered.
- `assoc_req_ies`: IEs from (Re)Association Request.
  This is used only when in AP mode with drivers that do not use
  user space MLME/SME implementation. The information is provided for
  the [`cfg80211_new_sta()`](#c-cfg80211_new_sta) calls to notify user space of the IEs.
- `assoc_req_ies_len`: Length of assoc_req_ies buffer in octets.
- `t_offset`: Time offset of the station relative to this host.
- `llid`: mesh local link id
- `plid`: mesh peer link id
- `plink_state`: mesh peer link state
- `connected_to_gate`: true if mesh STA has a path to mesh gate
- `connected_to_as`: true if mesh STA has a path to authentication server
- `airtime_link_metric`: mesh airtime link metric.
- `local_pm`: local mesh STA power save mode
- `peer_pm`: peer mesh STA power save mode
- `nonpeer_pm`: non-peer mesh STA power save mode
- `expected_throughput`: expected throughput in kbps (including 802.11 headers)
  towards this station.
- `airtime_weight`: current airtime scheduling weight
- `ack_signal`: signal strength (in dBm) of the last ACK frame.
- `avg_ack_signal`: average rssi value of ack packet for the no of msdu's has
  been sent.
- `pertid`: per-TID statistics, see `struct cfg80211_tid_stats`, using the last
  (IEEE80211_NUM_TIDS) index for MSDUs not encapsulated in QoS-MPDUs.
  Note that this doesn't use the **filled** bit, but is used if non-NULL.
- `tx_duration`: aggregate PPDU duration(usecs) for all the frames to a peer
- `rx_duration`: aggregate PPDU duration(usecs) for all the frames from a peer
- `rx_beacon`: number of beacons received from this peer
- `rx_beacon_signal_avg`: signal strength average (in dBm) for beacons received
  from this peer
- `rx_mpdu_count`: number of MPDUs received from this station
- `fcs_err_count`: number of packets (MPDUs) received from this station with
  an FCS error. This counter should be incremented only when TA of the
  received packet with an FCS error matches the peer MAC address.
- `mlo_params_valid`: Indicates **assoc_link_id** and **mld_addr** fields are filled
  by driver. Drivers use this only in [`cfg80211_new_sta()`](#c-cfg80211_new_sta) calls when AP
  MLD's MLME/SME is offload to driver. Drivers won't fill this
  information in `cfg80211_del_sta_sinfo()`, `get_station()` and
  `dump_station()` callbacks.
- `assoc_link_id`: Indicates MLO link ID of the AP, with which the station
  completed (re)association. This information filled for both MLO
  and non-MLO STA connections when the AP affiliated with an MLD.
- `mld_addr`: For MLO STA connection, filled with MLD address of the station.
  For non-MLO STA connection, filled with all zeros.
- `assoc_resp_ies`: IEs from (Re)Association Response.
  This is used only when in AP mode with drivers that do not use user
  space MLME/SME implementation. The information is provided only for the
  [`cfg80211_new_sta()`](#c-cfg80211_new_sta) calls to notify user space of the IEs. Drivers won't
  fill this information in `cfg80211_del_sta_sinfo()`, `get_station()` and
  `dump_station()` callbacks. User space needs this information to determine
  the accepted and rejected affiliated links of the connected station.
- `assoc_resp_ies_len`: Length of **assoc_resp_ies** buffer in octets.
- `valid_links`: bitmap of valid links, or 0 for non-MLO. Drivers fill this
  information in [`cfg80211_new_sta()`](#c-cfg80211_new_sta), `cfg80211_del_sta_sinfo()`,
  `get_station()` and `dump_station()` callbacks.
- `links`: reference to Link sta entries for MLO STA, all link specific
  information is accessed through links\[link_id\].

**Description**

Station information filled by driver for `get_station()` and dump_station.

#### <a id="c-enum-monitor_flags"></a>`enum monitor_flags`

monitor flags

**Constants**

- `MONITOR_FLAG_CHANGED`: set if the flags were changed
- `MONITOR_FLAG_FCSFAIL`: pass frames with bad FCS
- `MONITOR_FLAG_PLCPFAIL`: pass frames with bad PLCP
- `MONITOR_FLAG_CONTROL`: pass control frames
- `MONITOR_FLAG_OTHER_BSS`: disable BSSID filtering
- `MONITOR_FLAG_COOK_FRAMES`: deprecated, will unconditionally be refused
- `MONITOR_FLAG_ACTIVE`: active monitor, ACKs frames on its MAC address
- `MONITOR_FLAG_SKIP_TX`: do not pass locally transmitted frames

**Description**

Monitor interface configuration flags. Note that these must be the bits
according to the nl80211 flags.

#### <a id="c-enum-mpath_info_flags"></a>`enum mpath_info_flags`

mesh path information flags

**Constants**

- `MPATH_INFO_FRAME_QLEN`:

  **frame_qlen** filled
- `MPATH_INFO_SN`:

  **sn** filled
- `MPATH_INFO_METRIC`:

  **metric** filled
- `MPATH_INFO_EXPTIME`:

  **exptime** filled
- `MPATH_INFO_DISCOVERY_TIMEOUT`:

  **discovery_timeout** filled
- `MPATH_INFO_DISCOVERY_RETRIES`:

  **discovery_retries** filled
- `MPATH_INFO_FLAGS`:

  **flags** filled
- `MPATH_INFO_HOP_COUNT`:

  **hop_count** filled
- `MPATH_INFO_PATH_CHANGE`:

  **path_change_count** filled

**Description**

Used by the driver to indicate which info in [`struct mpath_info`](#c-struct-mpath_info) it has filled
in during `get_station()` or `dump_station()`.

#### <a id="c-struct-mpath_info"></a>`struct mpath_info`

mesh path information

**Definition**

```c
struct mpath_info {
    u32 filled;
    u32 frame_qlen;
    u32 sn;
    u32 metric;
    u32 exptime;
    u32 discovery_timeout;
    u8 discovery_retries;
    u8 flags;
    u8 hop_count;
    u32 path_change_count;
    int generation;
};
```

**Members**

- `filled`: bitfield of flags from [`enum mpath_info_flags`](#c-enum-mpath_info_flags)
- `frame_qlen`: number of queued frames for this destination
- `sn`: target sequence number
- `metric`: metric (cost) of this mesh path
- `exptime`: expiration time for the mesh path from now, in msecs
- `discovery_timeout`: total mesh path discovery timeout, in msecs
- `discovery_retries`: mesh path discovery retries
- `flags`: mesh path flags from `enum mesh_path_flags`
- `hop_count`: hops to destination
- `path_change_count`: total number of path changes to destination
- `generation`: generation number for nl80211 dumps.
  This number should increase every time the list of mesh paths
  changes, i.e. when a station is added or removed, so that
  userspace can tell whether it got a consistent snapshot.

**Description**

Mesh path information filled by driver for `get_mpath()` and `dump_mpath()`.

#### <a id="c-struct-bss_parameters"></a>`struct bss_parameters`

BSS parameters

**Definition**

```c
struct bss_parameters {
    int link_id;
    int use_cts_prot;
    int use_short_preamble;
    int use_short_slot_time;
    const u8 *basic_rates;
    u8 basic_rates_len;
    int ap_isolate;
    int ht_opmode;
    s8 p2p_ctwindow, p2p_opp_ps;
};
```

**Members**

- `link_id`: link_id or -1 for non-MLD
- `use_cts_prot`: Whether to use CTS protection
  (0 = no, 1 = yes, -1 = do not change)
- `use_short_preamble`: Whether the use of short preambles is allowed
  (0 = no, 1 = yes, -1 = do not change)
- `use_short_slot_time`: Whether the use of short slot time is allowed
  (0 = no, 1 = yes, -1 = do not change)
- `basic_rates`: basic rates in IEEE 802.11 format
  (or NULL for no change)
- `basic_rates_len`: number of basic rates
- `ap_isolate`: do not forward packets between connected stations
  (0 = no, 1 = yes, -1 = do not change)
- `ht_opmode`: HT Operation mode
  (u16 = opmode, -1 = do not change)
- `p2p_ctwindow`: P2P CT Window (-1 = no change)
- `p2p_opp_ps`: P2P opportunistic PS (-1 = no change)

**Description**

Used to change BSS parameters (mainly for AP mode).

#### <a id="c-struct-ieee80211_txq_params"></a>`struct ieee80211_txq_params`

TX queue parameters

**Definition**

```c
struct ieee80211_txq_params {
    enum nl80211_ac ac;
    u16 txop;
    u16 cwmin;
    u16 cwmax;
    u8 aifs;
    int link_id;
};
```

**Members**

- `ac`: AC identifier
- `txop`: Maximum burst time in units of 32 usecs, 0 meaning disabled
- `cwmin`: Minimum contention window \[a value of the form 2^n-1 in the range
  1..32767\]
- `cwmax`: Maximum contention window \[a value of the form 2^n-1 in the range
  1..32767\]
- `aifs`: Arbitration interframe space \[0..255\]
- `link_id`: link_id or -1 for non-MLD

#### <a id="c-struct-cfg80211_auth_request"></a>`struct cfg80211_auth_request`

Authentication request data

**Definition**

```c
struct cfg80211_auth_request {
    struct cfg80211_bss *bss;
    const u8 *ie;
    size_t ie_len;
    const u8 *supported_selectors;
    u8 supported_selectors_len;
    enum nl80211_auth_type auth_type;
    const u8 *key;
    u8 key_len;
    s8 key_idx;
    const u8 *auth_data;
    size_t auth_data_len;
    s8 link_id;
    const u8 *ap_mld_addr;
};
```

**Members**

- `bss`: The BSS to authenticate with, the callee must obtain a reference
  to it if it needs to keep it.
- `ie`: Extra IEs to add to Authentication frame or `NULL`
- `ie_len`: Length of ie buffer in octets
- `supported_selectors`: List of selectors that should be assumed to be
  supported by the station.
  SAE_H2E must be assumed supported if set to `NULL`.
- `supported_selectors_len`: Length of supported_selectors in octets.
- `auth_type`: Authentication type (algorithm)
- `key`: WEP key for shared key authentication
- `key_len`: length of WEP key for shared key authentication
- `key_idx`: index of WEP key for shared key authentication
- `auth_data`: Fields and elements in Authentication frames. This contains
  the authentication frame body (non-IE and IE data), excluding the
  Authentication algorithm number, i.e., starting at the Authentication
  transaction sequence number field.
- `auth_data_len`: Length of auth_data buffer in octets
- `link_id`: if >= 0, indicates authentication should be done as an MLD,
  the interface address is included as the MLD address and the
  necessary link (with the given link_id) will be created (and
  given an MLD address) by the driver
- `ap_mld_addr`: AP MLD address in case of authentication request with
  an AP MLD, valid iff **link_id** >= 0

**Description**

This structure provides information needed to complete IEEE 802.11
authentication.

#### <a id="c-struct-cfg80211_assoc_request"></a>`struct cfg80211_assoc_request`

(Re)Association request data

**Definition**

```c
struct cfg80211_assoc_request {
    struct cfg80211_bss *bss;
    const u8 *ie, *prev_bssid;
    size_t ie_len;
    struct cfg80211_crypto_settings crypto;
    bool use_mfp;
    u32 flags;
    const u8 *supported_selectors;
    u8 supported_selectors_len;
    struct ieee80211_ht_cap ht_capa;
    struct ieee80211_ht_cap ht_capa_mask;
    struct ieee80211_vht_cap vht_capa, vht_capa_mask;
    const u8 *fils_kek;
    size_t fils_kek_len;
    const u8 *fils_nonces;
    struct ieee80211_s1g_cap s1g_capa, s1g_capa_mask;
    struct cfg80211_assoc_link links[IEEE80211_MLD_MAX_NUM_LINKS];
    const u8 *ap_mld_addr;
    s8 link_id;
    u16 ext_mld_capa_ops;
};
```

**Members**

- `bss`: The BSS to associate with. If the call is successful the driver is
  given a reference that it must give back to `cfg80211_send_rx_assoc()`
  or to `cfg80211_assoc_timeout()`. To ensure proper refcounting, new
  association requests while already associating must be rejected.
  This also applies to the **links.bss** parameter, which is used instead
  of this one (it is `NULL`) for MLO associations.
- `ie`: Extra IEs to add to (Re)Association Request frame or `NULL`
- `prev_bssid`: previous BSSID, if not `NULL` use reassociate frame. This is used
  to indicate a request to reassociate within the ESS instead of a request
  do the initial association with the ESS. When included, this is set to
  the BSSID of the current association, i.e., to the value that is
  included in the Current AP address field of the Reassociation Request
  frame.
- `ie_len`: Length of ie buffer in octets
- `crypto`: crypto settings
- `use_mfp`: Use management frame protection (IEEE 802.11w) in this association
- `flags`: See `enum cfg80211_assoc_req_flags`
- `supported_selectors`: supported BSS selectors in IEEE 802.11 format
  (or `NULL` for no change).
  If `NULL`, then support for SAE_H2E should be assumed.
- `supported_selectors_len`: number of supported BSS selectors
- `ht_capa`: HT Capabilities over-rides.  Values set in ht_capa_mask
  will be used in ht_capa.  Un-supported values will be ignored.
- `ht_capa_mask`: The bits of ht_capa which are to be used.
- `vht_capa`: VHT capability override
- `vht_capa_mask`: VHT capability mask indicating which fields to use
- `fils_kek`: FILS KEK for protecting (Re)Association Request/Response frame or
  `NULL` if FILS is not used.
- `fils_kek_len`: Length of fils_kek in octets
- `fils_nonces`: FILS nonces (part of AAD) for protecting (Re)Association
  Request/Response frame or `NULL` if FILS is not used. This field starts
  with 16 octets of STA Nonce followed by 16 octets of AP Nonce.
- `s1g_capa`: S1G capability override
- `s1g_capa_mask`: S1G capability override mask
- `links`: per-link information for MLO connections
- `ap_mld_addr`: AP MLD address in case of MLO association request,
  valid iff **link_id** >= 0
- `link_id`: \>= 0 for MLO connections, where links are given, and indicates
  the link on which the association request should be sent
- `ext_mld_capa_ops`: extended MLD capabilities and operations set by
  userspace for the association

**Description**

This structure provides information needed to complete IEEE 802.11
(re)association.

#### <a id="c-struct-cfg80211_deauth_request"></a>`struct cfg80211_deauth_request`

Deauthentication request data

**Definition**

```c
struct cfg80211_deauth_request {
    const u8 *bssid;
    const u8 *ie;
    size_t ie_len;
    u16 reason_code;
    bool local_state_change;
};
```

**Members**

- `bssid`: the BSSID or AP MLD address to deauthenticate from
- `ie`: Extra IEs to add to Deauthentication frame or `NULL`
- `ie_len`: Length of ie buffer in octets
- `reason_code`: The reason code for the deauthentication
- `local_state_change`: if set, change local state only and
  do not set a deauth frame

**Description**

This structure provides information needed to complete IEEE 802.11
deauthentication.

#### <a id="c-struct-cfg80211_disassoc_request"></a>`struct cfg80211_disassoc_request`

Disassociation request data

**Definition**

```c
struct cfg80211_disassoc_request {
    const u8 *ap_addr;
    const u8 *ie;
    size_t ie_len;
    u16 reason_code;
    bool local_state_change;
};
```

**Members**

- `ap_addr`: the BSSID or AP MLD address to disassociate from
- `ie`: Extra IEs to add to Disassociation frame or `NULL`
- `ie_len`: Length of ie buffer in octets
- `reason_code`: The reason code for the disassociation
- `local_state_change`: This is a request for a local state only, i.e., no
  Disassociation frame is to be transmitted.

**Description**

This structure provides information needed to complete IEEE 802.11
disassociation.

#### <a id="c-struct-cfg80211_ibss_params"></a>`struct cfg80211_ibss_params`

IBSS parameters

**Definition**

```c
struct cfg80211_ibss_params {
    const u8 *ssid;
    const u8 *bssid;
    struct cfg80211_chan_def chandef;
    const u8 *ie;
    u8 ssid_len, ie_len;
    u16 beacon_interval;
    u32 basic_rates;
    bool channel_fixed;
    bool privacy;
    bool control_port;
    bool control_port_over_nl80211;
    bool userspace_handles_dfs;
    int mcast_rate[NUM_NL80211_BANDS];
    struct ieee80211_ht_cap ht_capa;
    struct ieee80211_ht_cap ht_capa_mask;
    struct key_params *wep_keys;
    int wep_tx_key;
};
```

**Members**

- `ssid`: The SSID, will always be non-null.
- `bssid`: Fixed BSSID requested, maybe be `NULL`, if set do not
  search for IBSSs with a different BSSID.
- `chandef`: defines the channel to use if no other IBSS to join can be found
- `ie`: information element(s) to include in the beacon
- `ssid_len`: The length of the SSID, will always be non-zero.
- `ie_len`: length of that
- `beacon_interval`: beacon interval to use
- `basic_rates`: bitmap of basic rates to use when creating the IBSS
- `channel_fixed`: The channel should be fixed -- do not search for
  IBSSs to join on other channels.
- `privacy`: this is a protected network, keys will be configured
  after joining
- `control_port`: whether user space controls IEEE 802.1X port, i.e.,
  sets/clears `NL80211_STA_FLAG_AUTHORIZED`. If true, the driver is
  required to assume that the port is unauthorized until authorized by
  user space. Otherwise, port is marked authorized by default.
- `control_port_over_nl80211`: TRUE if userspace expects to exchange control
  port frames over NL80211 instead of the network interface.
- `userspace_handles_dfs`: whether user space controls DFS operation, i.e.
  changes the channel when a radar is detected. This is required
  to operate on DFS channels.
- `mcast_rate`: per-band multicast rate index + 1 (0: disabled)
- `ht_capa`: HT Capabilities over-rides.  Values set in ht_capa_mask
  will be used in ht_capa.  Un-supported values will be ignored.
- `ht_capa_mask`: The bits of ht_capa which are to be used.
- `wep_keys`: static WEP keys, if not NULL points to an array of
  CFG80211_MAX_WEP_KEYS WEP keys
- `wep_tx_key`: key index (0..3) of the default TX static WEP key

**Description**

This structure defines the IBSS parameters for the `join_ibss()`
method.

#### <a id="c-struct-cfg80211_connect_params"></a>`struct cfg80211_connect_params`

Connection parameters

**Definition**

```c
struct cfg80211_connect_params {
    struct ieee80211_channel *channel;
    struct ieee80211_channel *channel_hint;
    const u8 *bssid;
    const u8 *bssid_hint;
    const u8 *ssid;
    size_t ssid_len;
    enum nl80211_auth_type auth_type;
    const u8 *ie;
    size_t ie_len;
    bool privacy;
    enum nl80211_mfp mfp;
    struct cfg80211_crypto_settings crypto;
    const u8 *key;
    u8 key_len, key_idx;
    u32 flags;
    int bg_scan_period;
    struct ieee80211_ht_cap ht_capa;
    struct ieee80211_ht_cap ht_capa_mask;
    struct ieee80211_vht_cap vht_capa;
    struct ieee80211_vht_cap vht_capa_mask;
    bool pbss;
    struct cfg80211_bss_selection bss_select;
    const u8 *prev_bssid;
    const u8 *fils_erp_username;
    size_t fils_erp_username_len;
    const u8 *fils_erp_realm;
    size_t fils_erp_realm_len;
    u16 fils_erp_next_seq_num;
    const u8 *fils_erp_rrk;
    size_t fils_erp_rrk_len;
    bool want_1x;
    struct ieee80211_edmg edmg;
};
```

**Members**

- `channel`: The channel to use or `NULL` if not specified (auto-select based
  on scan results)
- `channel_hint`: The channel of the recommended BSS for initial connection or
  `NULL` if not specified
- `bssid`: The AP BSSID or `NULL` if not specified (auto-select based on scan
  results)
- `bssid_hint`: The recommended AP BSSID for initial connection to the BSS or
  `NULL` if not specified. Unlike the **bssid** parameter, the driver is
  allowed to ignore this **bssid_hint** if it has knowledge of a better BSS
  to use.
- `ssid`: SSID
- `ssid_len`: Length of ssid in octets
- `auth_type`: Authentication type (algorithm)
- `ie`: IEs for association request
- `ie_len`: Length of assoc_ie in octets
- `privacy`: indicates whether privacy-enabled APs should be used
- `mfp`: indicate whether management frame protection is used
- `crypto`: crypto settings
- `key`: WEP key for shared key authentication
- `key_len`: length of WEP key for shared key authentication
- `key_idx`: index of WEP key for shared key authentication
- `flags`: See `enum cfg80211_assoc_req_flags`
- `bg_scan_period`: Background scan period in seconds
  or -1 to indicate that default value is to be used.
- `ht_capa`: HT Capabilities over-rides.  Values set in ht_capa_mask
  will be used in ht_capa.  Un-supported values will be ignored.
- `ht_capa_mask`: The bits of ht_capa which are to be used.
- `vht_capa`: VHT Capability overrides
- `vht_capa_mask`: The bits of vht_capa which are to be used.
- `pbss`: if set, connect to a PCP instead of AP. Valid for DMG
  networks.
- `bss_select`: criteria to be used for BSS selection.
- `prev_bssid`: previous BSSID, if not `NULL` use reassociate frame. This is used
  to indicate a request to reassociate within the ESS instead of a request
  do the initial association with the ESS. When included, this is set to
  the BSSID of the current association, i.e., to the value that is
  included in the Current AP address field of the Reassociation Request
  frame.
- `fils_erp_username`: EAP re-authentication protocol (ERP) username part of the
  NAI or `NULL` if not specified. This is used to construct FILS wrapped
  data IE.
- `fils_erp_username_len`: Length of **fils_erp_username** in octets.
- `fils_erp_realm`: EAP re-authentication protocol (ERP) realm part of NAI or
  `NULL` if not specified. This specifies the domain name of ER server and
  is used to construct FILS wrapped data IE.
- `fils_erp_realm_len`: Length of **fils_erp_realm** in octets.
- `fils_erp_next_seq_num`: The next sequence number to use in the FILS ERP
  messages. This is also used to construct FILS wrapped data IE.
- `fils_erp_rrk`: ERP re-authentication Root Key (rRK) used to derive additional
  keys in FILS or `NULL` if not specified.
- `fils_erp_rrk_len`: Length of **fils_erp_rrk** in octets.
- `want_1x`: indicates user-space supports and wants to use 802.1X driver
  offload of 4-way handshake.
- `edmg`: define the EDMG channels.
  This may specify multiple channels and bonding options for the driver
  to choose from, based on BSS configuration.

**Description**

This structure provides information needed to complete IEEE 802.11
authentication and association.

#### <a id="c-struct-cfg80211_pmksa"></a>`struct cfg80211_pmksa`

PMK Security Association

**Definition**

```c
struct cfg80211_pmksa {
    const u8 *bssid;
    const u8 *pmkid;
    const u8 *pmk;
    size_t pmk_len;
    const u8 *ssid;
    size_t ssid_len;
    const u8 *cache_id;
    u32 pmk_lifetime;
    u8 pmk_reauth_threshold;
};
```

**Members**

- `bssid`: The AP's BSSID (may be `NULL`).
- `pmkid`: The identifier to refer a PMKSA.
- `pmk`: The PMK for the PMKSA identified by **pmkid**. This is used for key
  derivation by a FILS STA. Otherwise, `NULL`.
- `pmk_len`: Length of the **pmk**. The length of **pmk** can differ depending on
  the hash algorithm used to generate this.
- `ssid`: SSID to specify the ESS within which a PMKSA is valid when using FILS
  cache identifier (may be `NULL`).
- `ssid_len`: Length of the **ssid** in octets.
- `cache_id`: 2-octet cache identifier advertized by a FILS AP identifying the
  scope of PMKSA. This is valid only if **ssid_len** is non-zero (may be
  `NULL`).
- `pmk_lifetime`: Maximum lifetime for PMKSA in seconds
  (dot11RSNAConfigPMKLifetime) or 0 if not specified.
  The configured PMKSA must not be used for PMKSA caching after
  expiration and any keys derived from this PMK become invalid on
  expiration, i.e., the current association must be dropped if the PMK
  used for it expires.
- `pmk_reauth_threshold`: Threshold time for reauthentication (percentage of
  PMK lifetime, dot11RSNAConfigPMKReauthThreshold) or 0 if not specified.
  Drivers are expected to trigger a full authentication instead of using
  this PMKSA for caching when reassociating to a new BSS after this
  threshold to generate a new PMK before the current one expires.

**Description**

This structure is passed to the set/`del_pmksa()` method for PMKSA
caching.

#### <a id="c-struct-cfg80211_ops"></a>`struct cfg80211_ops`

backend description for wireless configuration

**Definition**

```c
struct cfg80211_ops {
        int (*suspend)(struct wiphy *wiphy, struct cfg80211_wowlan *wow);
        int (*resume)(struct wiphy *wiphy);
        void (*set_wakeup)(struct wiphy *wiphy, bool enabled);
        struct wireless_dev * (*add_virtual_intf)(struct wiphy *wiphy, const char *name, unsigned char name_assign_type, enum nl80211_iftype type, struct vif_params *params);
        int (*del_virtual_intf)(struct wiphy *wiphy, struct wireless_dev *wdev);
        int (*change_virtual_intf)(struct wiphy *wiphy, struct net_device *dev, enum nl80211_iftype type, struct vif_params *params);
        int (*add_intf_link)(struct wiphy *wiphy, struct wireless_dev *wdev, unsigned int link_id);
        void (*del_intf_link)(struct wiphy *wiphy, struct wireless_dev *wdev, unsigned int link_id);
        int (*add_key)(struct wiphy *wiphy, struct net_device *netdev, int link_id, u8 key_index, bool pairwise, const u8 *mac_addr, struct key_params *params);
        int (*get_key)(struct wiphy *wiphy, struct net_device *netdev, int link_id, u8 key_index, bool pairwise, const u8 *mac_addr, void *cookie, void (*callback)(void *cookie, struct key_params*));
        int (*del_key)(struct wiphy *wiphy, struct net_device *netdev, int link_id, u8 key_index, bool pairwise, const u8 *mac_addr);
        int (*set_default_key)(struct wiphy *wiphy, struct net_device *netdev, int link_id, u8 key_index, bool unicast, bool multicast);
        int (*set_default_mgmt_key)(struct wiphy *wiphy, struct net_device *netdev, int link_id, u8 key_index);
        int (*set_default_beacon_key)(struct wiphy *wiphy, struct net_device *netdev, int link_id, u8 key_index);
        int (*start_ap)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_ap_settings *settings);
        int (*change_beacon)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_ap_update *info);
        int (*stop_ap)(struct wiphy *wiphy, struct net_device *dev, unsigned int link_id);
        int (*add_station)(struct wiphy *wiphy, struct net_device *dev, const u8 *mac, struct station_parameters *params);
        int (*del_station)(struct wiphy *wiphy, struct net_device *dev, struct station_del_parameters *params);
        int (*change_station)(struct wiphy *wiphy, struct net_device *dev, const u8 *mac, struct station_parameters *params);
        int (*get_station)(struct wiphy *wiphy, struct net_device *dev, const u8 *mac, struct station_info *sinfo);
        int (*dump_station)(struct wiphy *wiphy, struct net_device *dev, int idx, u8 *mac, struct station_info *sinfo);
        int (*add_mpath)(struct wiphy *wiphy, struct net_device *dev, const u8 *dst, const u8 *next_hop);
        int (*del_mpath)(struct wiphy *wiphy, struct net_device *dev, const u8 *dst);
        int (*change_mpath)(struct wiphy *wiphy, struct net_device *dev, const u8 *dst, const u8 *next_hop);
        int (*get_mpath)(struct wiphy *wiphy, struct net_device *dev, u8 *dst, u8 *next_hop, struct mpath_info *pinfo);
        int (*dump_mpath)(struct wiphy *wiphy, struct net_device *dev, int idx, u8 *dst, u8 *next_hop, struct mpath_info *pinfo);
        int (*get_mpp)(struct wiphy *wiphy, struct net_device *dev, u8 *dst, u8 *mpp, struct mpath_info *pinfo);
        int (*dump_mpp)(struct wiphy *wiphy, struct net_device *dev, int idx, u8 *dst, u8 *mpp, struct mpath_info *pinfo);
        int (*get_mesh_config)(struct wiphy *wiphy, struct net_device *dev, struct mesh_config *conf);
        int (*update_mesh_config)(struct wiphy *wiphy, struct net_device *dev, u32 mask, const struct mesh_config *nconf);
        int (*join_mesh)(struct wiphy *wiphy, struct net_device *dev, const struct mesh_config *conf, const struct mesh_setup *setup);
        int (*leave_mesh)(struct wiphy *wiphy, struct net_device *dev);
        int (*join_ocb)(struct wiphy *wiphy, struct net_device *dev, struct ocb_setup *setup);
        int (*leave_ocb)(struct wiphy *wiphy, struct net_device *dev);
        int (*change_bss)(struct wiphy *wiphy, struct net_device *dev, struct bss_parameters *params);
        void (*inform_bss)(struct wiphy *wiphy, struct cfg80211_bss *bss, const struct cfg80211_bss_ies *ies, void *data);
        int (*set_txq_params)(struct wiphy *wiphy, struct net_device *dev, struct ieee80211_txq_params *params);
        int (*libertas_set_mesh_channel)(struct wiphy *wiphy, struct net_device *dev, struct ieee80211_channel *chan);
        int (*set_monitor_channel)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_chan_def *chandef);
        int (*scan)(struct wiphy *wiphy, struct cfg80211_scan_request *request);
        void (*abort_scan)(struct wiphy *wiphy, struct wireless_dev *wdev);
        int (*auth)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_auth_request *req);
        int (*assoc)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_assoc_request *req);
        int (*deauth)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_deauth_request *req);
        int (*disassoc)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_disassoc_request *req);
        int (*connect)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_connect_params *sme);
        int (*update_connect_params)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_connect_params *sme, u32 changed);
        int (*disconnect)(struct wiphy *wiphy, struct net_device *dev, u16 reason_code);
        int (*join_ibss)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_ibss_params *params);
        int (*leave_ibss)(struct wiphy *wiphy, struct net_device *dev);
        int (*set_mcast_rate)(struct wiphy *wiphy, struct net_device *dev, int rate[NUM_NL80211_BANDS]);
        int (*set_wiphy_params)(struct wiphy *wiphy, int radio_idx, u32 changed);
        int (*set_tx_power)(struct wiphy *wiphy, struct wireless_dev *wdev, int radio_idx, enum nl80211_tx_power_setting type, int mbm);
        int (*get_tx_power)(struct wiphy *wiphy, struct wireless_dev *wdev, int radio_idx, unsigned int link_id, int *dbm);
        void (*rfkill_poll)(struct wiphy *wiphy);
    #ifdef CONFIG_NL80211_TESTMODE;
        int (*testmode_cmd)(struct wiphy *wiphy, struct wireless_dev *wdev, void *data, int len);
        int (*testmode_dump)(struct wiphy *wiphy, struct sk_buff *skb, struct netlink_callback *cb, void *data, int len);
    #endif;
        int (*set_bitrate_mask)(struct wiphy *wiphy, struct net_device *dev, unsigned int link_id, const u8 *peer, const struct cfg80211_bitrate_mask *mask);
        int (*dump_survey)(struct wiphy *wiphy, struct net_device *netdev, int idx, struct survey_info *info);
        int (*set_pmksa)(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_pmksa *pmksa);
        int (*del_pmksa)(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_pmksa *pmksa);
        int (*flush_pmksa)(struct wiphy *wiphy, struct net_device *netdev);
        int (*remain_on_channel)(struct wiphy *wiphy, struct wireless_dev *wdev, struct ieee80211_channel *chan, unsigned int duration, u64 *cookie);
        int (*cancel_remain_on_channel)(struct wiphy *wiphy, struct wireless_dev *wdev, u64 cookie);
        int (*mgmt_tx)(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_mgmt_tx_params *params, u64 *cookie);
        int (*mgmt_tx_cancel_wait)(struct wiphy *wiphy, struct wireless_dev *wdev, u64 cookie);
        int (*set_power_mgmt)(struct wiphy *wiphy, struct net_device *dev, bool enabled, int timeout);
        int (*set_cqm_rssi_config)(struct wiphy *wiphy, struct net_device *dev, s32 rssi_thold, u32 rssi_hyst);
        int (*set_cqm_rssi_range_config)(struct wiphy *wiphy, struct net_device *dev, s32 rssi_low, s32 rssi_high);
        int (*set_cqm_txe_config)(struct wiphy *wiphy, struct net_device *dev, u32 rate, u32 pkts, u32 intvl);
        void (*update_mgmt_frame_registrations)(struct wiphy *wiphy, struct wireless_dev *wdev, struct mgmt_frame_regs *upd);
        int (*set_antenna)(struct wiphy *wiphy, int radio_idx, u32 tx_ant, u32 rx_ant);
        int (*get_antenna)(struct wiphy *wiphy, int radio_idx, u32 *tx_ant, u32 *rx_ant);
        int (*sched_scan_start)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_sched_scan_request *request);
        int (*sched_scan_stop)(struct wiphy *wiphy, struct net_device *dev, u64 reqid);
        int (*set_rekey_data)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_gtk_rekey_data *data);
        int (*tdls_mgmt)(struct wiphy *wiphy, struct net_device *dev, const u8 *peer, int link_id, u8 action_code, u8 dialog_token, u16 status_code, u32 peer_capability, bool initiator, const u8 *buf, size_t len);
        int (*tdls_oper)(struct wiphy *wiphy, struct net_device *dev, const u8 *peer, enum nl80211_tdls_operation oper);
        int (*probe_client)(struct wiphy *wiphy, struct net_device *dev, const u8 *peer, u64 *cookie);
        int (*set_noack_map)(struct wiphy *wiphy, struct net_device *dev, u16 noack_map);
        int (*get_channel)(struct wiphy *wiphy, struct wireless_dev *wdev, unsigned int link_id, struct cfg80211_chan_def *chandef);
        int (*start_p2p_device)(struct wiphy *wiphy, struct wireless_dev *wdev);
        void (*stop_p2p_device)(struct wiphy *wiphy, struct wireless_dev *wdev);
        int (*set_mac_acl)(struct wiphy *wiphy, struct net_device *dev, const struct cfg80211_acl_data *params);
        int (*start_radar_detection)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_chan_def *chandef, u32 cac_time_ms, int link_id);
        void (*end_cac)(struct wiphy *wiphy, struct net_device *dev, unsigned int link_id);
        int (*update_ft_ies)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_update_ft_ies_params *ftie);
        int (*crit_proto_start)(struct wiphy *wiphy, struct wireless_dev *wdev, enum nl80211_crit_proto_id protocol, u16 duration);
        void (*crit_proto_stop)(struct wiphy *wiphy, struct wireless_dev *wdev);
        int (*set_coalesce)(struct wiphy *wiphy, struct cfg80211_coalesce *coalesce);
        int (*channel_switch)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_csa_settings *params);
        int (*set_qos_map)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_qos_map *qos_map);
        int (*set_ap_chanwidth)(struct wiphy *wiphy, struct net_device *dev, unsigned int link_id, struct cfg80211_chan_def *chandef);
        int (*add_tx_ts)(struct wiphy *wiphy, struct net_device *dev, u8 tsid, const u8 *peer, u8 user_prio, u16 admitted_time);
        int (*del_tx_ts)(struct wiphy *wiphy, struct net_device *dev, u8 tsid, const u8 *peer);
        int (*tdls_channel_switch)(struct wiphy *wiphy, struct net_device *dev, const u8 *addr, u8 oper_class, struct cfg80211_chan_def *chandef);
        void (*tdls_cancel_channel_switch)(struct wiphy *wiphy, struct net_device *dev, const u8 *addr);
        int (*start_nan)(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_nan_conf *conf);
        void (*stop_nan)(struct wiphy *wiphy, struct wireless_dev *wdev);
        int (*add_nan_func)(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_nan_func *nan_func);
        void (*del_nan_func)(struct wiphy *wiphy, struct wireless_dev *wdev, u64 cookie);
        int (*nan_change_conf)(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_nan_conf *conf, u32 changes);
        int (*set_multicast_to_unicast)(struct wiphy *wiphy, struct net_device *dev, const bool enabled);
        int (*get_txq_stats)(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_txq_stats *txqstats);
        int (*set_pmk)(struct wiphy *wiphy, struct net_device *dev, const struct cfg80211_pmk_conf *conf);
        int (*del_pmk)(struct wiphy *wiphy, struct net_device *dev, const u8 *aa);
        int (*external_auth)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_external_auth_params *params);
        int (*tx_control_port)(struct wiphy *wiphy, struct net_device *dev, const u8 *buf, size_t len, const u8 *dest, const __be16 proto, const bool noencrypt, int link_id, u64 *cookie);
        int (*get_ftm_responder_stats)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_ftm_responder_stats *ftm_stats);
        int (*start_pmsr)(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_pmsr_request *request);
        void (*abort_pmsr)(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_pmsr_request *request);
        int (*update_owe_info)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_update_owe_info *owe_info);
        int (*probe_mesh_link)(struct wiphy *wiphy, struct net_device *dev, const u8 *buf, size_t len);
        int (*set_tid_config)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_tid_config *tid_conf);
        int (*reset_tid_config)(struct wiphy *wiphy, struct net_device *dev, const u8 *peer, u8 tids);
        int (*set_sar_specs)(struct wiphy *wiphy, struct cfg80211_sar_specs *sar);
        int (*color_change)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_color_change_settings *params);
        int (*set_fils_aad)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_fils_aad *fils_aad);
        int (*set_radar_background)(struct wiphy *wiphy, struct cfg80211_chan_def *chandef);
        int (*add_link_station)(struct wiphy *wiphy, struct net_device *dev, struct link_station_parameters *params);
        int (*mod_link_station)(struct wiphy *wiphy, struct net_device *dev, struct link_station_parameters *params);
        int (*del_link_station)(struct wiphy *wiphy, struct net_device *dev, struct link_station_del_parameters *params);
        int (*set_hw_timestamp)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_set_hw_timestamp *hwts);
        int (*set_ttlm)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_ttlm_params *params);
        u32 (*get_radio_mask)(struct wiphy *wiphy, struct net_device *dev);
        int (*assoc_ml_reconf)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_ml_reconf_req *req);
        int (*set_epcs)(struct wiphy *wiphy, struct net_device *dev, bool val);
};
```

**Members**

- `suspend`: wiphy device needs to be suspended. The variable **wow** will
  be `NULL` or contain the enabled Wake-on-Wireless triggers that are
  configured for the device.
- `resume`: wiphy device needs to be resumed
- `set_wakeup`: Called when WoWLAN is enabled/disabled, use this callback
  to call `device_set_wakeup_enable()` to enable/disable wakeup from
  the device.
- `add_virtual_intf`: create a new virtual interface with the given name,
  must set the struct wireless_dev's iftype. Beware: You must create
  the new netdev in the wiphy's network namespace! Returns the struct
  wireless_dev, or an ERR_PTR. For P2P device wdevs, the driver must
  also set the address member in the wdev.
  This additionally holds the RTNL to be able to do netdev changes.
- `del_virtual_intf`: remove the virtual interface
  This additionally holds the RTNL to be able to do netdev changes.
- `change_virtual_intf`: change type/configuration of virtual interface,
  keep the struct wireless_dev's iftype updated.
  This additionally holds the RTNL to be able to do netdev changes.
- `add_intf_link`: Add a new MLO link to the given interface. Note that
  the wdev->link\[\] data structure has been updated, so the new link
  address is available.
- `del_intf_link`: Remove an MLO link from the given interface.
- `add_key`: add a key with the given parameters. **mac_addr** will be `NULL`
  when adding a group key. **link_id** will be -1 for non-MLO connection.
  For MLO connection, **link_id** will be >= 0 for group key and -1 for
  pairwise key, **mac_addr** will be peer's MLD address for MLO pairwise key.
- `get_key`: get information about the key with the given parameters.
  **mac_addr** will be `NULL` when requesting information for a group
  key. All pointers given to the **callback** function need not be valid
  after it returns. This function should return an error if it is
  not possible to retrieve the key, -ENOENT if it doesn't exist.
  **link_id** will be -1 for non-MLO connection. For MLO connection,
  **link_id** will be >= 0 for group key and -1 for pairwise key, **mac_addr**
  will be peer's MLD address for MLO pairwise key.
- `del_key`: remove a key given the **mac_addr** (`NULL` for a group key)
  and **key_index**, return -ENOENT if the key doesn't exist. **link_id** will
  be -1 for non-MLO connection. For MLO connection, **link_id** will be >= 0
  for group key and -1 for pairwise key, **mac_addr** will be peer's MLD
  address for MLO pairwise key.
- `set_default_key`: set the default key on an interface. **link_id** will be >= 0
  for MLO connection and -1 for non-MLO connection.
- `set_default_mgmt_key`: set the default management frame key on an interface.
  **link_id** will be >= 0 for MLO connection and -1 for non-MLO connection.
- `set_default_beacon_key`: set the default Beacon frame key on an interface.
  **link_id** will be >= 0 for MLO connection and -1 for non-MLO connection.
- `start_ap`: Start acting in AP mode defined by the parameters.
- `change_beacon`: Change the beacon parameters for an access point mode
  interface. This should reject the call when AP mode wasn't started.
- `stop_ap`: Stop being an AP, including stopping beaconing.
- `add_station`: Add a new station.
- `del_station`: Remove a station
- `change_station`: Modify a given station. Note that flags changes are not much
  validated in cfg80211, in particular the auth/assoc/authorized flags
  might come to the driver in invalid combinations -- make sure to check
  them, also against the existing state! Drivers must call
  `cfg80211_check_station_change()` to validate the information.
- `get_station`: get station information for the station identified by **mac**
- `dump_station`: dump station callback -- resume dump at index **idx**
- `add_mpath`: add a fixed mesh path
- `del_mpath`: delete a given mesh path
- `change_mpath`: change a given mesh path
- `get_mpath`: get a mesh path for the given parameters
- `dump_mpath`: dump mesh path callback -- resume dump at index **idx**
- `get_mpp`: get a mesh proxy path for the given parameters
- `dump_mpp`: dump mesh proxy path callback -- resume dump at index **idx**
- `get_mesh_config`: Get the current mesh configuration
- `update_mesh_config`: Update mesh parameters on a running mesh.
  The mask is a bitfield which tells us which parameters to
  set, and which to leave alone.
- `join_mesh`: join the mesh network with the specified parameters
  (invoked with the wireless_dev mutex held)
- `leave_mesh`: leave the current mesh network
  (invoked with the wireless_dev mutex held)
- `join_ocb`: join the OCB network with the specified parameters
  (invoked with the wireless_dev mutex held)
- `leave_ocb`: leave the current OCB network
  (invoked with the wireless_dev mutex held)
- `change_bss`: Modify parameters for a given BSS.
- `inform_bss`: Called by cfg80211 while being informed about new BSS data
  for every BSS found within the reported data or frame. This is called
  from within the cfg8011 inform_bss handlers while holding the bss_lock.
  The data parameter is passed through from drv_data inside
  struct cfg80211_inform_bss.
  The new IE data for the BSS is explicitly passed.
- `set_txq_params`: Set TX queue parameters
- `libertas_set_mesh_channel`: Only for backward compatibility for libertas,
  as it doesn't implement join_mesh and needs to set the channel to
  join the mesh instead.
- `set_monitor_channel`: Set the monitor mode channel for the device. If other
  interfaces are active this callback should reject the configuration.
  If no interfaces are active or the device is down, the channel should
  be stored for when a monitor interface becomes active.
- `scan`: Request to do a scan. If returning zero, the scan request is given
  the driver, and will be valid until passed to [`cfg80211_scan_done()`](#c-cfg80211_scan_done).
  For scan results, call `cfg80211_inform_bss()`; you can call this outside
  the scan/scan_done bracket too.
- `abort_scan`: Tell the driver to abort an ongoing scan. The driver shall
  indicate the status of the scan through [`cfg80211_scan_done()`](#c-cfg80211_scan_done).
- `auth`: Request to authenticate with the specified peer
  (invoked with the wireless_dev mutex held)
- `assoc`: Request to (re)associate with the specified peer
  (invoked with the wireless_dev mutex held)
- `deauth`: Request to deauthenticate from the specified peer
  (invoked with the wireless_dev mutex held)
- `disassoc`: Request to disassociate from the specified peer
  (invoked with the wireless_dev mutex held)
- `connect`: Connect to the ESS with the specified parameters. When connected,
  call [`cfg80211_connect_result()`](#c-cfg80211_connect_result)/[`cfg80211_connect_bss()`](#c-cfg80211_connect_bss) with status code
  `WLAN_STATUS_SUCCESS`. If the connection fails for some reason, call
  [`cfg80211_connect_result()`](#c-cfg80211_connect_result)/[`cfg80211_connect_bss()`](#c-cfg80211_connect_bss) with the status code
  from the AP or [`cfg80211_connect_timeout()`](#c-cfg80211_connect_timeout) if no frame with status code
  was received.
  The driver is allowed to roam to other BSSes within the ESS when the
  other BSS matches the connect parameters. When such roaming is initiated
  by the driver, the driver is expected to verify that the target matches
  the configured security parameters and to use Reassociation Request
  frame instead of Association Request frame.
  The connect function can also be used to request the driver to perform a
  specific roam when connected to an ESS. In that case, the prev_bssid
  parameter is set to the BSSID of the currently associated BSS as an
  indication of requesting reassociation.
  In both the driver-initiated and new `connect()` call initiated roaming
  cases, the result of roaming is indicated with a call to
  [`cfg80211_roamed()`](#c-cfg80211_roamed). (invoked with the wireless_dev mutex held)
- `update_connect_params`: Update the connect parameters while connected to a
  BSS. The updated parameters can be used by driver/firmware for
  subsequent BSS selection (roaming) decisions and to form the
  Authentication/(Re)Association Request frames. This call does not
  request an immediate disassociation or reassociation with the current
  BSS, i.e., this impacts only subsequent (re)associations. The bits in
  changed are defined in `enum cfg80211_connect_params_changed`.
  (invoked with the wireless_dev mutex held)
- `disconnect`: Disconnect from the BSS/ESS or stop connection attempts if
  connection is in progress. Once done, call [`cfg80211_disconnected()`](#c-cfg80211_disconnected) in
  case connection was already established (invoked with the
  wireless_dev mutex held), otherwise call [`cfg80211_connect_timeout()`](#c-cfg80211_connect_timeout).
- `join_ibss`: Join the specified IBSS (or create if necessary). Once done, call
  [`cfg80211_ibss_joined()`](#c-cfg80211_ibss_joined), also call that function when changing BSSID due
  to a merge.
  (invoked with the wireless_dev mutex held)
- `leave_ibss`: Leave the IBSS.
  (invoked with the wireless_dev mutex held)
- `set_mcast_rate`: Set the specified multicast rate (only if vif is in ADHOC or
  MESH mode)
- `set_wiphy_params`: Notify that wiphy parameters have changed;
  **changed** bitfield (see [`enum wiphy_params_flags`](#c-enum-wiphy_params_flags)) describes which values
  have changed. The actual parameter values are available in
  struct wiphy. If returning an error, no value should be changed.
- `set_tx_power`: set the transmit power according to the parameters,
  the power passed is in mBm, to get dBm use `MBM_TO_DBM()`. The
  wdev may be `NULL` if power was set for the wiphy, and will
  always be `NULL` unless the driver supports per-vif TX power
  (as advertised by the nl80211 feature flag.)
- `get_tx_power`: store the current TX power into the dbm variable;
  return 0 if successful
- `rfkill_poll`: polls the hw rfkill line, use cfg80211 reporting
  functions to adjust rfkill hw state
- `testmode_cmd`: run a test mode command; **wdev** may be `NULL`
- `testmode_dump`: Implement a test mode dump. The cb->args\[2\] and up may be
  used by the function, but 0 and 1 must not be touched. Additionally,
  return error codes other than -ENOBUFS and -ENOENT will terminate the
  dump and return to userspace with an error, so be careful. If any data
  was passed in from userspace then the data/len arguments will be present
  and point to the data contained in `NL80211_ATTR_TESTDATA`.
- `set_bitrate_mask`: set the bitrate mask configuration
- `dump_survey`: get site survey information.
- `set_pmksa`: Cache a PMKID for a BSSID. This is mostly useful for fullmac
  devices running firmwares capable of generating the (re) association
  RSN IE. It allows for faster roaming between WPA2 BSSIDs.
- `del_pmksa`: Delete a cached PMKID.
- `flush_pmksa`: Flush all cached PMKIDs.
- `remain_on_channel`: Request the driver to remain awake on the specified
  channel for the specified duration to complete an off-channel
  operation (e.g., public action frame exchange). When the driver is
  ready on the requested channel, it must indicate this with an event
  notification by calling [`cfg80211_ready_on_channel()`](#c-cfg80211_ready_on_channel).
- `cancel_remain_on_channel`: Cancel an on-going remain-on-channel operation.
  This allows the operation to be terminated prior to timeout based on
  the duration value.
- `mgmt_tx`: Transmit a management frame.
- `mgmt_tx_cancel_wait`: Cancel the wait time from transmitting a management
  frame on another channel
- `set_power_mgmt`: Configure WLAN power management. A timeout value of -1
  allows the driver to adjust the dynamic ps timeout value.
- `set_cqm_rssi_config`: Configure connection quality monitor RSSI threshold.
  After configuration, the driver should (soon) send an event indicating
  the current level is above/below the configured threshold; this may
  need some care when the configuration is changed (without first being
  disabled.)
- `set_cqm_rssi_range_config`: Configure two RSSI thresholds in the
  connection quality monitor.  An event is to be sent only when the
  signal level is found to be outside the two values.  The driver should
  set `NL80211_EXT_FEATURE_CQM_RSSI_LIST` if this method is implemented.
  If it is provided then there's no point providing **set_cqm_rssi_config**.
- `set_cqm_txe_config`: Configure connection quality monitor TX error
  thresholds.
- `update_mgmt_frame_registrations`: Notify the driver that management frame
  registrations were updated. The callback is allowed to sleep.
- `set_antenna`: Set antenna configuration (tx_ant, rx_ant) on the device.
  Parameters are bitmaps of allowed antennas to use for TX/RX. Drivers may
  reject TX/RX mask combinations they cannot support by returning -EINVAL
  (also see nl80211.h **NL80211_ATTR_WIPHY_ANTENNA_TX**).
- `get_antenna`: Get current antenna configuration from device (tx_ant, rx_ant).
- `sched_scan_start`: Tell the driver to start a scheduled scan.
- `sched_scan_stop`: Tell the driver to stop an ongoing scheduled scan with
  given request id. This call must stop the scheduled scan and be ready
  for starting a new one before it returns, i.e. **sched_scan_start** may be
  called immediately after that again and should not fail in that case.
  The driver should not call `cfg80211_sched_scan_stopped()` for a requested
  stop (when this method returns 0).
- `set_rekey_data`: give the data necessary for GTK rekeying to the driver
- `tdls_mgmt`: Transmit a TDLS management frame.
- `tdls_oper`: Perform a high-level TDLS operation (e.g. TDLS link setup).
- `probe_client`: probe an associated client, must return a cookie that it
  later passes to `cfg80211_probe_status()`.
- `set_noack_map`: Set the NoAck Map for the TIDs.
- `get_channel`: Get the current operating channel for the virtual interface.
  For monitor interfaces, it should return `NULL` unless there's a single
  current monitoring channel.
- `start_p2p_device`: Start the given P2P device.
- `stop_p2p_device`: Stop the given P2P device.
- `set_mac_acl`: Sets MAC address control list in AP and P2P GO mode.
  Parameters include ACL policy, an array of MAC address of stations
  and the number of MAC addresses. If there is already a list in driver
  this new list replaces the existing one. Driver has to clear its ACL
  when number of MAC addresses entries is passed as 0. Drivers which
  advertise the support for MAC based ACL have to implement this callback.
- `start_radar_detection`: Start radar detection in the driver.
- `end_cac`: End running CAC, probably because a related CAC
  was finished on another phy.
- `update_ft_ies`: Provide updated Fast BSS Transition information to the
  driver. If the SME is in the driver/firmware, this information can be
  used in building Authentication and Reassociation Request frames.
- `crit_proto_start`: Indicates a critical protocol needs more link reliability
  for a given duration (milliseconds). The protocol is provided so the
  driver can take the most appropriate actions.
- `crit_proto_stop`: Indicates critical protocol no longer needs increased link
  reliability. This operation can not fail.
- `set_coalesce`: Set coalesce parameters.
- `channel_switch`: initiate channel-switch procedure (with CSA). Driver is
  responsible for veryfing if the switch is possible. Since this is
  inherently tricky driver may decide to disconnect an interface later
  with `cfg80211_stop_iface()`. This doesn't mean driver can accept
  everything. It should do it's best to verify requests and reject them
  as soon as possible.
- `set_qos_map`: Set QoS mapping information to the driver
- `set_ap_chanwidth`: Set the AP (including P2P GO) mode channel width for the
  given interface This is used e.g. for dynamic HT 20/40 MHz channel width
  changes during the lifetime of the BSS.
- `add_tx_ts`: validate (if admitted_time is 0) or add a TX TS to the device
  with the given parameters; action frame exchange has been handled by
  userspace so this just has to modify the TX path to take the TS into
  account.
  If the admitted time is 0 just validate the parameters to make sure
  the session can be created at all; it is valid to just always return
  success for that but that may result in inefficient behaviour (handshake
  with the peer followed by immediate teardown when the addition is later
  rejected)
- `del_tx_ts`: remove an existing TX TS
- `tdls_channel_switch`: Start channel-switching with a TDLS peer. The driver
  is responsible for continually initiating channel-switching operations
  and returning to the base channel for communication with the AP.
- `tdls_cancel_channel_switch`: Stop channel-switching with a TDLS peer. Both
  peers must be on the base channel when the call completes.
- `start_nan`: Start the NAN interface.
- `stop_nan`: Stop the NAN interface.
- `add_nan_func`: Add a NAN function. Returns negative value on failure.
  On success **nan_func** ownership is transferred to the driver and
  it may access it outside of the scope of this function. The driver
  should free the **nan_func** when no longer needed by calling
  `cfg80211_free_nan_func()`.
  On success the driver should assign an instance_id in the
  provided **nan_func**.
- `del_nan_func`: Delete a NAN function.
- `nan_change_conf`: changes NAN configuration. The changed parameters must
  be specified in **changes** (using `enum cfg80211_nan_conf_changes`);
  All other parameters must be ignored.
- `set_multicast_to_unicast`: configure multicast to unicast conversion for BSS
- `get_txq_stats`: Get TXQ stats for interface or phy. If wdev is `NULL`, this
  function should return phy stats, and interface stats otherwise.
- `set_pmk`: configure the PMK to be used for offloaded 802.1X 4-Way handshake.
  If not deleted through **del_pmk** the PMK remains valid until disconnect
  upon which the driver should clear it.
  (invoked with the wireless_dev mutex held)
- `del_pmk`: delete the previously configured PMK for the given authenticator.
  (invoked with the wireless_dev mutex held)
- `external_auth`: indicates result of offloaded authentication processing from
  user space
- `tx_control_port`: TX a control port frame (EAPoL).  The noencrypt parameter
  tells the driver that the frame should not be encrypted.
- `get_ftm_responder_stats`: Retrieve FTM responder statistics, if available.
  Statistics should be cumulative, currently no way to reset is provided.
- `start_pmsr`: start peer measurement (e.g. FTM)
- `abort_pmsr`: abort peer measurement
- `update_owe_info`: Provide updated OWE info to driver. Driver implementing SME
  but offloading OWE processing to the user space will get the updated
  DH IE through this interface.
- `probe_mesh_link`: Probe direct Mesh peer's link quality by sending data frame
  and overrule HWMP path selection algorithm.
- `set_tid_config`: TID specific configuration, this can be peer or BSS specific
  This callback may sleep.
- `reset_tid_config`: Reset TID specific configuration for the peer, for the
  given TIDs. This callback may sleep.
- `set_sar_specs`: Update the SAR (TX power) settings.
- `color_change`: Initiate a color change.
- `set_fils_aad`: Set FILS AAD data to the AP driver so that the driver can use
  those to decrypt (Re)Association Request and encrypt (Re)Association
  Response frame.
- `set_radar_background`: Configure dedicated offchannel chain available for
  radar/CAC detection on some hw. This chain can't be used to transmit
  or receive frames and it is bounded to a running wdev.
  Background radar/CAC detection allows to avoid the CAC downtime
  switching to a different channel during CAC detection on the selected
  radar channel.
  The caller is expected to set chandef pointer to NULL in order to
  disable background CAC/radar detection.
- `add_link_station`: Add a link to a station.
- `mod_link_station`: Modify a link of a station.
- `del_link_station`: Remove a link of a station.
- `set_hw_timestamp`: Enable/disable HW timestamping of TM/FTM frames.
- `set_ttlm`: set the TID to link mapping.
- `get_radio_mask`: get bitmask of radios in use.
  (invoked with the wiphy mutex held)
- `assoc_ml_reconf`: Request a non-AP MLO connection to perform ML
  reconfiguration, i.e., add and/or remove links to/from the
  association using ML reconfiguration action frames. Successfully added
  links will be added to the set of valid links. Successfully removed
  links will be removed from the set of valid links. The driver must
  indicate removed links by calling `cfg80211_links_removed()` and added
  links by calling `cfg80211_mlo_reconf_add_done()`. When calling
  `cfg80211_mlo_reconf_add_done()` the bss pointer must be given for each
  link for which MLO reconfiguration 'add' operation was requested.
- `set_epcs`: Enable/Disable EPCS for station mode.

**Description**

This struct is registered by fullmac card drivers and/or wireless stacks
in order to handle configuration requests on their interfaces.

All callbacks except where otherwise noted should return 0
on success or a negative error code.

All operations are invoked with the wiphy mutex held. The RTNL may be
held in addition (due to wireless extensions) but this cannot be relied
upon except in cases where documented below. Note that due to ordering,
the RTNL also cannot be acquired in any handlers.

#### <a id="c-cfg80211_rx_mlme_mgmt"></a>`cfg80211_rx_mlme_mgmt()`

```c
void cfg80211_rx_mlme_mgmt(struct net_device *dev, const u8 *buf, size_t len)
```

notification of processed MLME management frame

**Parameters**

- `struct net_device *dev`: network device
- `const u8 *buf`: authentication frame (header + body)
- `size_t len`: length of the frame data

**Description**

This function is called whenever an authentication, disassociation or
deauthentication frame has been received and processed in station mode.
After being asked to authenticate via cfg80211_ops::`auth()` the driver must
call either this function or [`cfg80211_auth_timeout()`](#c-cfg80211_auth_timeout).
After being asked to associate via cfg80211_ops::`assoc()` the driver must
call either this function or [`cfg80211_auth_timeout()`](#c-cfg80211_auth_timeout).
While connected, the driver must calls this for received and processed
disassociation and deauthentication frames. If the frame couldn't be used
because it was unprotected, the driver must call the function
`cfg80211_rx_unprot_mlme_mgmt()` instead.

This function may sleep. The caller must hold the corresponding wdev's mutex.

#### <a id="c-cfg80211_auth_timeout"></a>`cfg80211_auth_timeout()`

```c
void cfg80211_auth_timeout(struct net_device *dev, const u8 *addr)
```

notification of timed out authentication

**Parameters**

- `struct net_device *dev`: network device
- `const u8 *addr`: The MAC address of the device with which the authentication timed out

**Description**

This function may sleep. The caller must hold the corresponding wdev's
mutex.

#### <a id="c-cfg80211_rx_assoc_resp"></a>`cfg80211_rx_assoc_resp()`

```c
void cfg80211_rx_assoc_resp(struct net_device *dev, const struct cfg80211_rx_assoc_resp_data *data)
```

notification of processed association response

**Parameters**

- `struct net_device *dev`: network device
- `const struct cfg80211_rx_assoc_resp_data *data`: association response data, `struct cfg80211_rx_assoc_resp_data`

**Description**

After being asked to associate via cfg80211_ops::`assoc()` the driver must
call either this function or [`cfg80211_auth_timeout()`](#c-cfg80211_auth_timeout).

This function may sleep. The caller must hold the corresponding wdev's mutex.

#### <a id="c-cfg80211_tx_mlme_mgmt"></a>`cfg80211_tx_mlme_mgmt()`

```c
void cfg80211_tx_mlme_mgmt(struct net_device *dev, const u8 *buf, size_t len, bool reconnect)
```

notification of transmitted deauth/disassoc frame

**Parameters**

- `struct net_device *dev`: network device
- `const u8 *buf`: 802.11 frame (header + body)
- `size_t len`: length of the frame data
- `bool reconnect`: immediate reconnect is desired (include the nl80211 attribute)

**Description**

This function is called whenever deauthentication has been processed in
station mode. This includes both received deauthentication frames and
locally generated ones. This function may sleep. The caller must hold the
corresponding wdev's mutex.

#### <a id="c-cfg80211_michael_mic_failure"></a>`cfg80211_michael_mic_failure()`

```c
void cfg80211_michael_mic_failure(struct net_device *dev, const u8 *addr, enum nl80211_key_type key_type, int key_id, const u8 *tsc, gfp_t gfp)
```

notification of Michael MIC failure (TKIP)

**Parameters**

- `struct net_device *dev`: network device
- `const u8 *addr`: The source MAC address of the frame
- `enum nl80211_key_type key_type`: The key type that the received frame used
- `int key_id`: Key identifier (0..3). Can be -1 if missing.
- `const u8 *tsc`: The TSC value of the frame that generated the MIC failure (6 octets)
- `gfp_t gfp`: allocation flags

**Description**

This function is called whenever the local MAC detects a MIC failure in a
received frame. This matches with MLME-MICHAELMICFAILURE.`indication()`
primitive.

#### <a id="c-cfg80211_ibss_joined"></a>`cfg80211_ibss_joined()`

```c
void cfg80211_ibss_joined(struct net_device *dev, const u8 *bssid, struct ieee80211_channel *channel, gfp_t gfp)
```

notify cfg80211 that device joined an IBSS

**Parameters**

- `struct net_device *dev`: network device
- `const u8 *bssid`: the BSSID of the IBSS joined
- `struct ieee80211_channel *channel`: the channel of the IBSS joined
- `gfp_t gfp`: allocation flags

**Description**

This function notifies cfg80211 that the device joined an IBSS or
switched to a different BSSID. Before this function can be called,
either a beacon has to have been received from the IBSS, or one of
the cfg80211_inform_bss{,_frame} functions must have been called
with the locally generated beacon -- this guarantees that there is
always a scan result for this IBSS. cfg80211 will handle the rest.

#### <a id="c-struct-cfg80211_connect_resp_params"></a>`struct cfg80211_connect_resp_params`

Connection response params

**Definition**

```c
struct cfg80211_connect_resp_params {
    int status;
    const u8 *req_ie;
    size_t req_ie_len;
    const u8 *resp_ie;
    size_t resp_ie_len;
    struct cfg80211_fils_resp_params fils;
    enum nl80211_timeout_reason timeout_reason;
    const u8 *ap_mld_addr;
    u16 valid_links;
    struct {
        const u8 *addr;
        const u8 *bssid;
        struct cfg80211_bss *bss;
        u16 status;
    } links[IEEE80211_MLD_MAX_NUM_LINKS];
};
```

**Members**

- `status`: Status code, `WLAN_STATUS_SUCCESS` for successful connection, use
  `WLAN_STATUS_UNSPECIFIED_FAILURE` if your device cannot give you
  the real status code for failures. If this call is used to report a
  failure due to a timeout (e.g., not receiving an Authentication frame
  from the AP) instead of an explicit rejection by the AP, -1 is used to
  indicate that this is a failure, but without a status code.
  **timeout_reason** is used to report the reason for the timeout in that
  case.
- `req_ie`: Association request IEs (may be `NULL`)
- `req_ie_len`: Association request IEs length
- `resp_ie`: Association response IEs (may be `NULL`)
- `resp_ie_len`: Association response IEs length
- `fils`: FILS connection response parameters.
- `timeout_reason`: Reason for connection timeout. This is used when the
  connection fails due to a timeout instead of an explicit rejection from
  the AP. `NL80211_TIMEOUT_UNSPECIFIED` is used when the timeout reason is
  not known. This value is used only if **status** \< 0 to indicate that the
  failure is due to a timeout and not due to explicit rejection by the AP.
  This value is ignored in other cases (**status** >= 0).
- `ap_mld_addr`: For MLO connection, MLD address of the AP. Otherwise `NULL`.
- `valid_links`: For MLO connection, BIT mask of the valid link ids. Otherwise
  zero.
- `links`: For MLO connection, contains link info for the valid links indicated
  using **valid_links**. For non-MLO connection, links\[0\] contains the
  connected AP info.
- `links.addr`: For MLO connection, MAC address of the STA link. Otherwise
  `NULL`.
- `links.bssid`: For MLO connection, MAC address of the AP link. For non-MLO
  connection, links\[0\].bssid points to the BSSID of the AP (may be `NULL`).
- `links.bss`: For MLO connection, entry of bss to which STA link is connected.
  For non-MLO connection, links\[0\].bss points to entry of bss to which STA
  is connected. It can be obtained through `cfg80211_get_bss()` (may be
  `NULL`). It is recommended to store the bss from the connect_request and
  hold a reference to it and return through this param to avoid a warning
  if the bss is expired during the connection, esp. for those drivers
  implementing connect op. Only one parameter among **bssid** and **bss** needs
  to be specified.
- `links.status`: per-link status code, to report a status code that's not
  `WLAN_STATUS_SUCCESS` for a given link, it must also be in the
  **valid_links** bitmap and may have a BSS pointer (which is then released)

#### <a id="c-cfg80211_connect_done"></a>`cfg80211_connect_done()`

```c
void cfg80211_connect_done(struct net_device *dev, struct cfg80211_connect_resp_params *params, gfp_t gfp)
```

notify cfg80211 of connection result

**Parameters**

- `struct net_device *dev`: network device
- `struct cfg80211_connect_resp_params *params`: connection response parameters
- `gfp_t gfp`: allocation flags

**Description**

It should be called by the underlying driver once execution of the connection
request from `connect()` has been completed. This is similar to
[`cfg80211_connect_bss()`](#c-cfg80211_connect_bss), but takes a structure pointer for connection response
parameters. Only one of the functions among [`cfg80211_connect_bss()`](#c-cfg80211_connect_bss),
[`cfg80211_connect_result()`](#c-cfg80211_connect_result), [`cfg80211_connect_timeout()`](#c-cfg80211_connect_timeout),
and [`cfg80211_connect_done()`](#c-cfg80211_connect_done) should be called.

#### <a id="c-cfg80211_connect_bss"></a>`cfg80211_connect_bss()`

```c
void cfg80211_connect_bss(struct net_device *dev, const u8 *bssid, struct cfg80211_bss *bss, const u8 *req_ie, size_t req_ie_len, const u8 *resp_ie, size_t resp_ie_len, int status, gfp_t gfp, enum nl80211_timeout_reason timeout_reason)
```

notify cfg80211 of connection result

**Parameters**

- `struct net_device *dev`: network device
- `const u8 *bssid`: the BSSID of the AP
- `struct cfg80211_bss *bss`: Entry of bss to which STA got connected to, can be obtained through
  `cfg80211_get_bss()` (may be `NULL`). But it is recommended to store the
  bss from the connect_request and hold a reference to it and return
  through this param to avoid a warning if the bss is expired during the
  connection, esp. for those drivers implementing connect op.
  Only one parameter among **bssid** and **bss** needs to be specified.
- `const u8 *req_ie`: association request IEs (maybe be `NULL`)
- `size_t req_ie_len`: association request IEs length
- `const u8 *resp_ie`: association response IEs (may be `NULL`)
- `size_t resp_ie_len`: assoc response IEs length
- `int status`: status code, `WLAN_STATUS_SUCCESS` for successful connection, use
  `WLAN_STATUS_UNSPECIFIED_FAILURE` if your device cannot give you
  the real status code for failures. If this call is used to report a
  failure due to a timeout (e.g., not receiving an Authentication frame
  from the AP) instead of an explicit rejection by the AP, -1 is used to
  indicate that this is a failure, but without a status code.
  **timeout_reason** is used to report the reason for the timeout in that
  case.
- `gfp_t gfp`: allocation flags
- `enum nl80211_timeout_reason timeout_reason`: reason for connection timeout. This is used when the
  connection fails due to a timeout instead of an explicit rejection from
  the AP. `NL80211_TIMEOUT_UNSPECIFIED` is used when the timeout reason is
  not known. This value is used only if **status** \< 0 to indicate that the
  failure is due to a timeout and not due to explicit rejection by the AP.
  This value is ignored in other cases (**status** >= 0).

**Description**

It should be called by the underlying driver once execution of the connection
request from `connect()` has been completed. This is similar to
[`cfg80211_connect_result()`](#c-cfg80211_connect_result), but with the option of identifying the exact bss
entry for the connection. Only one of the functions among
[`cfg80211_connect_bss()`](#c-cfg80211_connect_bss), [`cfg80211_connect_result()`](#c-cfg80211_connect_result),
[`cfg80211_connect_timeout()`](#c-cfg80211_connect_timeout), and [`cfg80211_connect_done()`](#c-cfg80211_connect_done) should be called.

#### <a id="c-cfg80211_connect_result"></a>`cfg80211_connect_result()`

```c
void cfg80211_connect_result(struct net_device *dev, const u8 *bssid, const u8 *req_ie, size_t req_ie_len, const u8 *resp_ie, size_t resp_ie_len, u16 status, gfp_t gfp)
```

notify cfg80211 of connection result

**Parameters**

- `struct net_device *dev`: network device
- `const u8 *bssid`: the BSSID of the AP
- `const u8 *req_ie`: association request IEs (maybe be `NULL`)
- `size_t req_ie_len`: association request IEs length
- `const u8 *resp_ie`: association response IEs (may be `NULL`)
- `size_t resp_ie_len`: assoc response IEs length
- `u16 status`: status code, `WLAN_STATUS_SUCCESS` for successful connection, use
  `WLAN_STATUS_UNSPECIFIED_FAILURE` if your device cannot give you
  the real status code for failures.
- `gfp_t gfp`: allocation flags

**Description**

It should be called by the underlying driver once execution of the connection
request from `connect()` has been completed. This is similar to
[`cfg80211_connect_bss()`](#c-cfg80211_connect_bss) which allows the exact bss entry to be specified. Only
one of the functions among [`cfg80211_connect_bss()`](#c-cfg80211_connect_bss), [`cfg80211_connect_result()`](#c-cfg80211_connect_result),
[`cfg80211_connect_timeout()`](#c-cfg80211_connect_timeout), and [`cfg80211_connect_done()`](#c-cfg80211_connect_done) should be called.

#### <a id="c-cfg80211_connect_timeout"></a>`cfg80211_connect_timeout()`

```c
void cfg80211_connect_timeout(struct net_device *dev, const u8 *bssid, const u8 *req_ie, size_t req_ie_len, gfp_t gfp, enum nl80211_timeout_reason timeout_reason)
```

notify cfg80211 of connection timeout

**Parameters**

- `struct net_device *dev`: network device
- `const u8 *bssid`: the BSSID of the AP
- `const u8 *req_ie`: association request IEs (maybe be `NULL`)
- `size_t req_ie_len`: association request IEs length
- `gfp_t gfp`: allocation flags
- `enum nl80211_timeout_reason timeout_reason`: reason for connection timeout.

**Description**

It should be called by the underlying driver whenever `connect()` has failed
in a sequence where no explicit authentication/association rejection was
received from the AP. This could happen, e.g., due to not being able to send
out the Authentication or Association Request frame or timing out while
waiting for the response. Only one of the functions among
[`cfg80211_connect_bss()`](#c-cfg80211_connect_bss), [`cfg80211_connect_result()`](#c-cfg80211_connect_result),
[`cfg80211_connect_timeout()`](#c-cfg80211_connect_timeout), and [`cfg80211_connect_done()`](#c-cfg80211_connect_done) should be called.

#### <a id="c-cfg80211_roamed"></a>`cfg80211_roamed()`

```c
void cfg80211_roamed(struct net_device *dev, struct cfg80211_roam_info *info, gfp_t gfp)
```

notify cfg80211 of roaming

**Parameters**

- `struct net_device *dev`: network device
- `struct cfg80211_roam_info *info`: information about the new BSS. struct `cfg80211_roam_info`.
- `gfp_t gfp`: allocation flags

**Description**

This function may be called with the driver passing either the BSSID of the
new AP or passing the bss entry to avoid a race in timeout of the bss entry.
It should be called by the underlying driver whenever it roamed from one AP
to another while connected. Drivers which have roaming implemented in
firmware should pass the bss entry to avoid a race in bss entry timeout where
the bss entry of the new AP is seen in the driver, but gets timed out by the
time it is accessed in `__cfg80211_roamed()` due to delay in scheduling
rdev->event_work. In case of any failures, the reference is released
either in [`cfg80211_roamed()`](#c-cfg80211_roamed) or in `__cfg80211_romed()`, Otherwise, it will be
released while disconnecting from the current bss.

#### <a id="c-cfg80211_disconnected"></a>`cfg80211_disconnected()`

```c
void cfg80211_disconnected(struct net_device *dev, u16 reason, const u8 *ie, size_t ie_len, bool locally_generated, gfp_t gfp)
```

notify cfg80211 that connection was dropped

**Parameters**

- `struct net_device *dev`: network device
- `u16 reason`: reason code for the disconnection, set it to 0 if unknown
- `const u8 *ie`: information elements of the deauth/disassoc frame (may be `NULL`)
- `size_t ie_len`: length of IEs
- `bool locally_generated`: disconnection was requested locally
- `gfp_t gfp`: allocation flags

**Description**

After it calls this function, the driver should enter an idle state
and not try to connect to any AP any more.

#### <a id="c-cfg80211_ready_on_channel"></a>`cfg80211_ready_on_channel()`

```c
void cfg80211_ready_on_channel(struct wireless_dev *wdev, u64 cookie, struct ieee80211_channel *chan, unsigned int duration, gfp_t gfp)
```

notification of remain_on_channel start

**Parameters**

- `struct wireless_dev *wdev`: wireless device
- `u64 cookie`: the request cookie
- `struct ieee80211_channel *chan`: The current channel (from remain_on_channel request)
- `unsigned int duration`: Duration in milliseconds that the driver intents to remain on the
  channel
- `gfp_t gfp`: allocation flags

#### <a id="c-cfg80211_remain_on_channel_expired"></a>`cfg80211_remain_on_channel_expired()`

```c
void cfg80211_remain_on_channel_expired(struct wireless_dev *wdev, u64 cookie, struct ieee80211_channel *chan, gfp_t gfp)
```

remain_on_channel duration expired

**Parameters**

- `struct wireless_dev *wdev`: wireless device
- `u64 cookie`: the request cookie
- `struct ieee80211_channel *chan`: The current channel (from remain_on_channel request)
- `gfp_t gfp`: allocation flags

#### <a id="c-cfg80211_new_sta"></a>`cfg80211_new_sta()`

```c
void cfg80211_new_sta(struct net_device *dev, const u8 *mac_addr, struct station_info *sinfo, gfp_t gfp)
```

notify userspace about station

**Parameters**

- `struct net_device *dev`: the netdev
- `const u8 *mac_addr`: the station's address
- `struct station_info *sinfo`: the station information
- `gfp_t gfp`: allocation flags

#### <a id="c-cfg80211_rx_mgmt"></a>`cfg80211_rx_mgmt()`

```c
bool cfg80211_rx_mgmt(struct wireless_dev *wdev, int freq, int sig_dbm, const u8 *buf, size_t len, u32 flags)
```

notification of received, unprocessed management frame

**Parameters**

- `struct wireless_dev *wdev`: wireless device receiving the frame
- `int freq`: Frequency on which the frame was received in MHz
- `int sig_dbm`: signal strength in dBm, or 0 if unknown
- `const u8 *buf`: Management frame (header + body)
- `size_t len`: length of the frame data
- `u32 flags`: flags, as defined in enum nl80211_rxmgmt_flags

**Description**

This function is called whenever an Action frame is received for a station
mode interface, but is not processed in kernel.

**Return**

`true` if a user space application has registered for this frame.
For action frames, that makes it responsible for rejecting unrecognized
action frames; `false` otherwise, in which case for action frames the
driver is responsible for rejecting the frame.

#### <a id="c-cfg80211_mgmt_tx_status"></a>`cfg80211_mgmt_tx_status()`

```c
void cfg80211_mgmt_tx_status(struct wireless_dev *wdev, u64 cookie, const u8 *buf, size_t len, bool ack, gfp_t gfp)
```

notification of TX status for management frame

**Parameters**

- `struct wireless_dev *wdev`: wireless device receiving the frame
- `u64 cookie`: Cookie returned by cfg80211_ops::`mgmt_tx()`
- `const u8 *buf`: Management frame (header + body)
- `size_t len`: length of the frame data
- `bool ack`: Whether frame was acknowledged
- `gfp_t gfp`: context flags

**Description**

This function is called whenever a management frame was requested to be
transmitted with cfg80211_ops::`mgmt_tx()` to report the TX status of the
transmission attempt.

#### <a id="c-cfg80211_cqm_rssi_notify"></a>`cfg80211_cqm_rssi_notify()`

```c
void cfg80211_cqm_rssi_notify(struct net_device *dev, enum nl80211_cqm_rssi_threshold_event rssi_event, s32 rssi_level, gfp_t gfp)
```

connection quality monitoring rssi event

**Parameters**

- `struct net_device *dev`: network device
- `enum nl80211_cqm_rssi_threshold_event rssi_event`: the triggered RSSI event
- `s32 rssi_level`: new RSSI level value or 0 if not available
- `gfp_t gfp`: context flags

**Description**

This function is called when a configured connection quality monitoring
rssi threshold reached event occurs.

#### <a id="c-cfg80211_cqm_pktloss_notify"></a>`cfg80211_cqm_pktloss_notify()`

```c
void cfg80211_cqm_pktloss_notify(struct net_device *dev, const u8 *peer, u32 num_packets, gfp_t gfp)
```

notify userspace about packetloss to peer

**Parameters**

- `struct net_device *dev`: network device
- `const u8 *peer`: peer's MAC address
- `u32 num_packets`: how many packets were lost -- should be a fixed threshold
  but probably no less than maybe 50, or maybe a throughput dependent
  threshold (to account for temporary interference)
- `gfp_t gfp`: context flags


<a id="rst-scanning-and-bss-list-handling"></a>

## Scanning and BSS list handling


The scanning process itself is fairly simple, but cfg80211 offers quite
a bit of helper functionality. To start a scan, the scan operation will
be invoked with a scan definition. This scan definition contains the
channels to scan, and the SSIDs to send probe requests for (including the
wildcard, if desired). A passive scan is indicated by having no SSIDs to
probe. Additionally, a scan request may contain extra information elements
that should be added to the probe request. The IEs are guaranteed to be
well-formed, and will not exceed the maximum length the driver advertised
in the wiphy structure.

When scanning finds a BSS, cfg80211 needs to be notified of that, because
it is responsible for maintaining the BSS list; the driver should not
maintain a list itself. For this notification, various functions exist.

Since drivers do not maintain a BSS list, there are also a number of
functions to search for a BSS and obtain information about it from the
BSS structure cfg80211 maintains. The BSS list is also made available
to userspace.



#### <a id="c-struct-cfg80211_ssid"></a>`struct cfg80211_ssid`

SSID description

**Definition**

```c
struct cfg80211_ssid {
    u8 ssid[IEEE80211_MAX_SSID_LEN];
    u8 ssid_len;
};
```

**Members**

- `ssid`: the SSID
- `ssid_len`: length of the ssid

#### <a id="c-struct-cfg80211_scan_request"></a>`struct cfg80211_scan_request`

scan request description

**Definition**

```c
struct cfg80211_scan_request {
    struct cfg80211_ssid *ssids;
    int n_ssids;
    u32 n_channels;
    const u8 *ie;
    size_t ie_len;
    u16 duration;
    bool duration_mandatory;
    u32 flags;
    u32 rates[NUM_NL80211_BANDS];
    struct wireless_dev *wdev;
    u8 mac_addr[ETH_ALEN] ;
    u8 mac_addr_mask[ETH_ALEN] ;
    u8 bssid[ETH_ALEN] ;
    struct wiphy *wiphy;
    unsigned long scan_start;
    bool no_cck;
    bool scan_6ghz;
    bool first_part;
    u32 n_6ghz_params;
    struct cfg80211_scan_6ghz_params *scan_6ghz_params;
    s8 tsf_report_link_id;
    struct ieee80211_channel *channels[];
};
```

**Members**

- `ssids`: SSIDs to scan for (active scan only)
- `n_ssids`: number of SSIDs
- `n_channels`: total number of channels to scan
- `ie`: optional information element(s) to add into Probe Request or `NULL`
- `ie_len`: length of ie in octets
- `duration`: how long to listen on each channel, in TUs. If
  `duration_mandatory` is not set, this is the maximum dwell time and
  the actual dwell time may be shorter.
- `duration_mandatory`: if set, the scan duration must be as specified by the
  `duration` field.
- `flags`: control flags from `enum nl80211_scan_flags`
- `rates`: bitmap of rates to advertise for each band
- `wdev`: the wireless device to scan for
- `mac_addr`: MAC address used with randomisation
- `mac_addr_mask`: MAC address mask used with randomisation, bits that
  are 0 in the mask should be randomised, bits that are 1 should
  be taken from the **mac_addr**
- `bssid`: BSSID to scan for (most commonly, the wildcard BSSID)
- `wiphy`: the wiphy this was for
- `scan_start`: time (in jiffies) when the scan started
- `no_cck`: used to send probe requests at non CCK rate in 2GHz band
- `scan_6ghz`: relevant for split scan request only,
  true if this is a 6 GHz scan request
- `first_part`: `true` if this is the first part of a split scan request or a
  scan that was not split. May be `true` for a **scan_6ghz** scan if no other
  channels were requested
- `n_6ghz_params`: number of 6 GHz params
- `scan_6ghz_params`: 6 GHz params
- `tsf_report_link_id`: for MLO, indicates the link ID of the BSS that should be
  used for TSF reporting. Can be set to -1 to indicate no preference.
- `channels`: channels to scan on.

#### <a id="c-struct-cfg80211_inform_bss"></a>`struct cfg80211_inform_bss`

BSS inform data

**Definition**

```c
struct cfg80211_inform_bss {
    struct ieee80211_channel *chan;
    s32 signal;
    u64 boottime_ns;
    u64 parent_tsf;
    u8 parent_bssid[ETH_ALEN] ;
    u8 chains;
    s8 chain_signal[IEEE80211_MAX_CHAINS];
    u8 restrict_use:1, use_for:7;
    u8 cannot_use_reasons;
    void *drv_data;
};
```

**Members**

- `chan`: channel the frame was received on
- `signal`: signal strength value, according to the wiphy's
  signal type
- `boottime_ns`: timestamp (CLOCK_BOOTTIME) when the information was
  received; should match the time when the frame was actually
  received by the device (not just by the host, in case it was
  buffered on the device) and be accurate to about 10ms.
  If the frame isn't buffered, just passing the return value of
  `ktime_get_boottime_ns()` is likely appropriate.
- `parent_tsf`: the time at the start of reception of the first octet of the
  timestamp field of the frame. The time is the TSF of the BSS specified
  by `parent_bssid`.
- `parent_bssid`: the BSS according to which `parent_tsf` is set. This is set to
  the BSS that requested the scan in which the beacon/probe was received.
- `chains`: bitmask for filled values in **chain_signal**.
- `chain_signal`: per-chain signal strength of last received BSS in dBm.
- `restrict_use`: restrict usage, if not set, assume **use_for** is
  `NL80211_BSS_USE_FOR_NORMAL`.
- `use_for`: bitmap of possible usage for this BSS, see
  `enum nl80211_bss_use_for`
- `cannot_use_reasons`: the reasons (bitmap) for not being able to connect,
  if **restrict_use** is set and **use_for** is zero (empty); may be 0 for
  unspecified reasons; see `enum nl80211_bss_cannot_use_reasons`
- `drv_data`: Data to be passed through to **inform_bss**

#### <a id="c-struct-cfg80211_bss"></a>`struct cfg80211_bss`

BSS description

**Definition**

```c
struct cfg80211_bss {
    struct ieee80211_channel *channel;
    const struct cfg80211_bss_ies  *ies;
    const struct cfg80211_bss_ies  *beacon_ies;
    const struct cfg80211_bss_ies  *proberesp_ies;
    struct cfg80211_bss *hidden_beacon_bss;
    struct cfg80211_bss *transmitted_bss;
    struct list_head nontrans_list;
    s32 signal;
    u64 ts_boottime;
    u16 beacon_interval;
    u16 capability;
    u8 bssid[ETH_ALEN];
    u8 chains;
    s8 chain_signal[IEEE80211_MAX_CHAINS];
    u8 proberesp_ecsa_stuck:1;
    u8 bssid_index;
    u8 max_bssid_indicator;
    u8 use_for;
    u8 cannot_use_reasons;
    u8 priv[] ;
};
```

**Members**

- `channel`: channel this BSS is on
- `ies`: the information elements (Note that there is no guarantee that these
  are well-formed!); this is a pointer to either the beacon_ies or
  proberesp_ies depending on whether Probe Response frame has been
  received. It is always non-`NULL`.
- `beacon_ies`: the information elements from the last Beacon frame
  (implementation note: if **hidden_beacon_bss** is set this struct doesn't
  own the beacon_ies, but they're just pointers to the ones from the
  **hidden_beacon_bss** struct)
- `proberesp_ies`: the information elements from the last Probe Response frame
- `hidden_beacon_bss`: in case this BSS struct represents a probe response from
  a BSS that hides the SSID in its beacon, this points to the BSS struct
  that holds the beacon data. **beacon_ies** is still valid, of course, and
  points to the same data as hidden_beacon_bss->beacon_ies in that case.
- `transmitted_bss`: pointer to the transmitted BSS, if this is a
  non-transmitted one (multi-BSSID support)
- `nontrans_list`: list of non-transmitted BSS, if this is a transmitted one
  (multi-BSSID support)
- `signal`: signal strength value (type depends on the wiphy's signal_type)
- `ts_boottime`: timestamp of the last BSS update in nanoseconds since boot
- `beacon_interval`: the beacon interval as from the frame
- `capability`: the capability field in host byte order
- `bssid`: BSSID of the BSS
- `chains`: bitmask for filled values in **chain_signal**.
- `chain_signal`: per-chain signal strength of last received BSS in dBm.
- `proberesp_ecsa_stuck`: ECSA element is stuck in the Probe Response frame,
  cannot rely on it having valid data
- `bssid_index`: index in the multiple BSS set
- `max_bssid_indicator`: max number of members in the BSS set
- `use_for`: bitmap of possible usage for this BSS, see
  `enum nl80211_bss_use_for`
- `cannot_use_reasons`: the reasons (bitmap) for not being able to connect,
  if **restrict_use** is set and **use_for** is zero (empty); may be 0 for
  unspecified reasons; see `enum nl80211_bss_cannot_use_reasons`
- `priv`: private area for driver use, has at least wiphy->bss_priv_size bytes

**Description**

This structure describes a BSS (which may also be a mesh network)
for use in scan results and similar.

#### <a id="c-ieee80211_bss_get_ie"></a>`ieee80211_bss_get_ie()`

```c
const u8 * ieee80211_bss_get_ie(struct cfg80211_bss *bss, u8 id)
```

find IE with given ID

**Parameters**

- `struct cfg80211_bss *bss`: the bss to search
- `u8 id`: the element ID

**Description**

Note that the return value is an RCU-protected pointer, so
[`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock) must be held when calling this function.

**Return**

`NULL` if not found.

#### <a id="c-cfg80211_find_ie"></a>`cfg80211_find_ie()`

```c
const u8 * cfg80211_find_ie(u8 eid, const u8 *ies, int len)
```

find information element in data

**Parameters**

- `u8 eid`: element ID
- `const u8 *ies`: data consisting of IEs
- `int len`: length of data

**Return**

`NULL` if the element ID could not be found or if
the element is invalid (claims to be longer than the given
data), or a pointer to the first byte of the requested
element, that is the byte containing the element ID.

**Note**

There are no checks on the element length other than
having to fit into the given data.

#### <a id="c-cfg80211_scan_done"></a>`cfg80211_scan_done()`

```c
void cfg80211_scan_done(struct cfg80211_scan_request *request, struct cfg80211_scan_info *info)
```

notify that scan finished

**Parameters**

- `struct cfg80211_scan_request *request`: the corresponding scan request
- `struct cfg80211_scan_info *info`: information about the completed scan

#### <a id="c-cfg80211_inform_bss_frame_data"></a>`cfg80211_inform_bss_frame_data()`

```c
struct cfg80211_bss * cfg80211_inform_bss_frame_data(struct wiphy *wiphy, struct cfg80211_inform_bss *data, struct ieee80211_mgmt *mgmt, size_t len, gfp_t gfp)
```

inform cfg80211 of a received BSS frame

**Parameters**

- `struct wiphy *wiphy`: the wiphy reporting the BSS
- `struct cfg80211_inform_bss *data`: the BSS metadata
- `struct ieee80211_mgmt *mgmt`: the management frame (probe response or beacon)
- `size_t len`: length of the management frame
- `gfp_t gfp`: context flags

**Description**

This informs cfg80211 that BSS information was found and
the BSS should be updated/added.

**Return**

A referenced struct, must be released with `cfg80211_put_bss()`!
Or `NULL` on error.

#### <a id="c-cfg80211_inform_bss_data"></a>`cfg80211_inform_bss_data()`

```c
struct cfg80211_bss * cfg80211_inform_bss_data(struct wiphy *wiphy, struct cfg80211_inform_bss *data, enum cfg80211_bss_frame_type ftype, const u8 *bssid, u64 tsf, u16 capability, u16 beacon_interval, const u8 *ie, size_t ielen, gfp_t gfp)
```

inform cfg80211 of a new BSS

**Parameters**

- `struct wiphy *wiphy`: the wiphy reporting the BSS
- `struct cfg80211_inform_bss *data`: the BSS metadata
- `enum cfg80211_bss_frame_type ftype`: frame type (if known)
- `const u8 *bssid`: the BSSID of the BSS
- `u64 tsf`: the TSF sent by the peer in the beacon/probe response (or 0)
- `u16 capability`: the capability field sent by the peer
- `u16 beacon_interval`: the beacon interval announced by the peer
- `const u8 *ie`: additional IEs sent by the peer
- `size_t ielen`: length of the additional IEs
- `gfp_t gfp`: context flags

**Description**

This informs cfg80211 that BSS information was found and
the BSS should be updated/added.

**Return**

A referenced struct, must be released with `cfg80211_put_bss()`!
Or `NULL` on error.

#### <a id="c-cfg80211_unlink_bss"></a>`cfg80211_unlink_bss()`

```c
void cfg80211_unlink_bss(struct wiphy *wiphy, struct cfg80211_bss *bss)
```

unlink BSS from internal data structures

**Parameters**

- `struct wiphy *wiphy`: the wiphy
- `struct cfg80211_bss *bss`: the bss to remove

**Description**

This function removes the given BSS from the internal data structures
thereby making it no longer show up in scan results etc. Use this
function when you detect a BSS is gone. Normally BSSes will also time
out, so it is not necessary to use this function at all.


<a id="rst-utility-functions"></a>

## Utility functions


cfg80211 offers a number of utility functions that can be useful.



#### <a id="c-ieee80211_channel_to_frequency"></a>`ieee80211_channel_to_frequency()`

```c
int ieee80211_channel_to_frequency(int chan, enum nl80211_band band)
```

convert channel number to frequency

**Parameters**

- `int chan`: channel number
- `enum nl80211_band band`: band, necessary due to channel number overlap

**Return**

The corresponding frequency (in MHz), or 0 if the conversion failed.

#### <a id="c-ieee80211_frequency_to_channel"></a>`ieee80211_frequency_to_channel()`

```c
int ieee80211_frequency_to_channel(int freq)
```

convert frequency to channel number

**Parameters**

- `int freq`: center frequency in MHz

**Return**

The corresponding channel, or 0 if the conversion failed.

#### <a id="c-ieee80211_get_channel"></a>`ieee80211_get_channel()`

```c
struct ieee80211_channel * ieee80211_get_channel(struct wiphy *wiphy, int freq)
```

get channel struct from wiphy for specified frequency

**Parameters**

- `struct wiphy *wiphy`: the struct wiphy to get the channel for
- `int freq`: the center frequency (in MHz) of the channel

**Return**

The channel struct from **wiphy** at **freq**.

#### <a id="c-ieee80211_get_response_rate"></a>`ieee80211_get_response_rate()`

```c
const struct ieee80211_rate * ieee80211_get_response_rate(struct ieee80211_supported_band *sband, u32 basic_rates, int bitrate)
```

get basic rate for a given rate

**Parameters**

- `struct ieee80211_supported_band *sband`: the band to look for rates in
- `u32 basic_rates`: bitmap of basic rates
- `int bitrate`: the bitrate for which to find the basic rate

**Return**

The basic rate corresponding to a given bitrate, that
is the next lower bitrate contained in the basic rate map,
which is, for this function, given as a bitmap of indices of
rates in the band's bitrate table.

#### <a id="c-struct-ieee80211_radiotap_iterator"></a>`struct ieee80211_radiotap_iterator`

tracks walk thru present radiotap args

**Definition**

```c
struct ieee80211_radiotap_iterator {
    struct ieee80211_radiotap_header *_rtheader;
    const struct ieee80211_radiotap_vendor_namespaces *_vns;
    const struct ieee80211_radiotap_namespace *current_namespace;
    unsigned char *_arg, *_next_ns_data;
    __le32 *_next_bitmap;
    unsigned char *this_arg;
    int this_arg_index;
    int this_arg_size;
    int is_radiotap_ns;
    int _max_length;
    int _arg_index;
    uint32_t _bitmap_shifter;
    int _reset_on_ext;
};
```

**Members**

- `_rtheader`: pointer to the radiotap header we are walking through
- `_vns`: vendor namespace definitions
- `current_namespace`: pointer to the current namespace definition
  (or internally `NULL` if the current namespace is unknown)
- `_arg`: next argument pointer
- `_next_ns_data`: beginning of the next namespace's data
- `_next_bitmap`: internal pointer to next present u32
- `this_arg`: pointer to current radiotap arg; it is valid after each
  call to `ieee80211_radiotap_iterator_next()` but also after
  `ieee80211_radiotap_iterator_init()` where it will point to
  the beginning of the actual data portion
- `this_arg_index`: index of current arg, valid after each successful call
  to `ieee80211_radiotap_iterator_next()`
- `this_arg_size`: length of the current arg, for convenience
- `is_radiotap_ns`: indicates whether the current namespace is the default
  radiotap namespace or not
- `_max_length`: length of radiotap header in cpu byte ordering
- `_arg_index`: next argument index
- `_bitmap_shifter`: internal shifter for curr u32 bitmap, b0 set == arg present
- `_reset_on_ext`: internal; reset the arg index to 0 when going to the
  next bitmap word

**Description**

Describes the radiotap parser state. Fields prefixed with an underscore
must not be used by users of the parser, only by the parser internally.

#### <a id="c-ieee80211_get_hdrlen_from_skb"></a>`ieee80211_get_hdrlen_from_skb()`

```c
unsigned int ieee80211_get_hdrlen_from_skb(const struct sk_buff *skb)
```

get header length from data

**Parameters**

- `const struct sk_buff *skb`: the frame

**Description**

Given an skb with a raw 802.11 header at the data pointer this function
returns the 802.11 header length.

**Return**

The 802.11 header length in bytes (not including encryption
headers). Or 0 if the data in the sk_buff is too short to contain a valid
802.11 header.

#### <a id="c-ieee80211_hdrlen"></a>`ieee80211_hdrlen()`

```c
unsigned int ieee80211_hdrlen(__le16 fc)
```

get header length in bytes from frame control

**Parameters**

- `__le16 fc`: frame control field in little-endian format

**Return**

The header length in bytes.


<a id="rst-data-path-helpers"></a>

## Data path helpers


In addition to generic utilities, cfg80211 also offers
functions that help implement the data path for devices
that do not do the 802.11/802.3 conversion on the device.



#### <a id="c-ieee80211_data_to_8023"></a>`ieee80211_data_to_8023()`

```c
int ieee80211_data_to_8023(struct sk_buff *skb, const u8 *addr, enum nl80211_iftype iftype)
```

convert an 802.11 data frame to 802.3

**Parameters**

- `struct sk_buff *skb`: the 802.11 data frame
- `const u8 *addr`: the device MAC address
- `enum nl80211_iftype iftype`: the virtual interface type

**Return**

0 on success. Non-zero on error.

#### <a id="c-ieee80211_amsdu_to_8023s"></a>`ieee80211_amsdu_to_8023s()`

```c
void ieee80211_amsdu_to_8023s(struct sk_buff *skb, struct sk_buff_head *list, const u8 *addr, enum nl80211_iftype iftype, const unsigned int extra_headroom, const u8 *check_da, const u8 *check_sa, u8 mesh_control)
```

decode an IEEE 802.11n A-MSDU frame

**Parameters**

- `struct sk_buff *skb`: The input A-MSDU frame without any headers.
- `struct sk_buff_head *list`: The output list of 802.3 frames. It must be allocated and
  initialized by the caller.
- `const u8 *addr`: The device MAC address.
- `enum nl80211_iftype iftype`: The device interface type.
- `const unsigned int extra_headroom`: The hardware extra headroom for SKBs in the **list**.
- `const u8 *check_da`: DA to check in the inner ethernet header, or NULL
- `const u8 *check_sa`: SA to check in the inner ethernet header, or NULL
- `u8 mesh_control`: see mesh_hdr in ieee80211_is_valid_amsdu

**Description**

Decode an IEEE 802.11 A-MSDU and convert it to a list of 802.3 frames.
The **list** will be empty if the decode fails. The **skb** must be fully
header-less before being passed in here; it is freed in this function.

#### <a id="c-cfg80211_classify8021d"></a>`cfg80211_classify8021d()`

```c
unsigned int cfg80211_classify8021d(struct sk_buff *skb, struct cfg80211_qos_map *qos_map)
```

determine the 802.1p/1d tag for a data frame

**Parameters**

- `struct sk_buff *skb`: the data frame
- `struct cfg80211_qos_map *qos_map`: Interworking QoS mapping or `NULL` if not in use

**Return**

The 802.1p/1d tag.


<a id="rst-regulatory-enforcement-infrastructure"></a>

## Regulatory enforcement infrastructure


TODO



#### <a id="c-regulatory_hint"></a>`regulatory_hint()`

```c
int regulatory_hint(struct wiphy *wiphy, const char *alpha2)
```

driver hint to the wireless core a regulatory domain

**Parameters**

- `struct wiphy *wiphy`: the wireless device giving the hint (used only for reporting
  conflicts)
- `const char *alpha2`: the ISO/IEC 3166 alpha2 the driver claims its regulatory domain
  should be in. If **rd** is set this should be NULL. Note that if you
  set this to NULL you should still set rd->alpha2 to some accepted
  alpha2.

**Description**

Wireless drivers can use this function to hint to the wireless core
what it believes should be the current regulatory domain by
giving it an ISO/IEC 3166 alpha2 country code it knows its regulatory
domain should be in or by providing a completely build regulatory domain.
If the driver provides an ISO/IEC 3166 alpha2 userspace will be queried
for a regulatory domain structure for the respective country.

The wiphy must have been registered to cfg80211 prior to this call.
For cfg80211 drivers this means you must first use [`wiphy_register()`](#c-wiphy_register),
for mac80211 drivers you must first use [`ieee80211_register_hw()`](/kernel/hardware/driver-api/80211/mac80211.md#c-ieee80211_register_hw).

Drivers should check the return value, its possible you can get
an -ENOMEM.

**Return**

0 on success. -ENOMEM.

#### <a id="c-wiphy_apply_custom_regulatory"></a>`wiphy_apply_custom_regulatory()`

```c
void wiphy_apply_custom_regulatory(struct wiphy *wiphy, const struct ieee80211_regdomain *regd)
```

apply a custom driver regulatory domain

**Parameters**

- `struct wiphy *wiphy`: the wireless device we want to process the regulatory domain on
- `const struct ieee80211_regdomain *regd`: the custom regulatory domain to use for this wiphy

**Description**

Drivers can sometimes have custom regulatory domains which do not apply
to a specific country. Drivers can use this to apply such custom regulatory
domains. This routine must be called prior to wiphy registration. The
custom regulatory domain will be trusted completely and as such previous
default channel settings will be disregarded. If no rule is found for a
channel on the regulatory domain the channel will be disabled.
Drivers using this for a wiphy should also set the wiphy flag
REGULATORY_CUSTOM_REG or cfg80211 will set it for the wiphy
that called this helper.

#### <a id="c-freq_reg_info"></a>`freq_reg_info()`

```c
const struct ieee80211_reg_rule * freq_reg_info(struct wiphy *wiphy, u32 center_freq)
```

get regulatory information for the given frequency

**Parameters**

- `struct wiphy *wiphy`: the wiphy for which we want to process this rule for
- `u32 center_freq`: Frequency in KHz for which we want regulatory information for

**Description**

Use this function to get the regulatory rule for a specific frequency on
a given wireless device. If the device has a specific regulatory domain
it wants to follow we respect that unless a country IE has been received
and processed already.

**Return**

A valid pointer, or, when an error occurs, for example if no rule
can be found, the return value is encoded using [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR). Use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) to
check and [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) to obtain the numeric return value. The numeric return
value will be -ERANGE if we determine the given center_freq does not even
have a regulatory rule for a frequency range in the center_freq's band.
See `freq_in_rule_band()` for our current definition of a band -- this is
purely subjective and right now it's 802.11 specific.


<a id="rst-rfkill-integration"></a>

## RFkill integration


RFkill integration in cfg80211 is almost invisible to drivers,
as cfg80211 automatically registers an rfkill instance for each
wireless device it knows about. Soft kill is also translated
into disconnecting and turning all interfaces off. Drivers are
expected to turn off the device when all interfaces are down.

However, devices may have a hard RFkill line, in which case they
also need to interact with the rfkill subsystem, via cfg80211.
They can do this with a few helper functions documented here.



#### <a id="c-wiphy_rfkill_start_polling"></a>`wiphy_rfkill_start_polling()`

```c
void wiphy_rfkill_start_polling(struct wiphy *wiphy)
```

start polling rfkill

**Parameters**

- `struct wiphy *wiphy`: the wiphy

#### <a id="c-wiphy_rfkill_stop_polling"></a>`wiphy_rfkill_stop_polling()`

```c
void wiphy_rfkill_stop_polling(struct wiphy *wiphy)
```

stop polling rfkill

**Parameters**

- `struct wiphy *wiphy`: the wiphy


<a id="rst-test-mode"></a>

## Test mode


Test mode is a set of utility functions to allow drivers to
interact with driver-specific tools to aid, for instance,
factory programming.

This chapter describes how drivers interact with it. For more
information see the nl80211 book's chapter on it.



#### <a id="c-cfg80211_testmode_alloc_reply_skb"></a>`cfg80211_testmode_alloc_reply_skb()`

```c
struct sk_buff * cfg80211_testmode_alloc_reply_skb(struct wiphy *wiphy, int approxlen)
```

allocate testmode reply

**Parameters**

- `struct wiphy *wiphy`: the wiphy
- `int approxlen`: an upper bound of the length of the data that will
  be put into the skb

**Description**

This function allocates and pre-fills an skb for a reply to
the testmode command. Since it is intended for a reply, calling
it outside of the **testmode_cmd** operation is invalid.

The returned skb is pre-filled with the wiphy index and set up in
a way that any data that is put into the skb (with [`skb_put()`](/kernel/internals/networking/kapi.md#c-skb_put),
`nla_put()` or similar) will end up being within the
`NL80211_ATTR_TESTDATA` attribute, so all that needs to be done
with the skb is adding data for the corresponding userspace tool
which can then read that data out of the testdata attribute. You
must not modify the skb in any other way.

When done, call [`cfg80211_testmode_reply()`](#c-cfg80211_testmode_reply) with the skb and return
its error code as the result of the **testmode_cmd** operation.

**Return**

An allocated and pre-filled skb. `NULL` if any errors happen.

#### <a id="c-cfg80211_testmode_reply"></a>`cfg80211_testmode_reply()`

```c
int cfg80211_testmode_reply(struct sk_buff *skb)
```

send the reply skb

**Parameters**

- `struct sk_buff *skb`: The skb, must have been allocated with
  [`cfg80211_testmode_alloc_reply_skb()`](#c-cfg80211_testmode_alloc_reply_skb)

**Description**

Since calling this function will usually be the last thing
before returning from the **testmode_cmd** you should return
the error code.  Note that this function consumes the skb
regardless of the return value.

**Return**

An error code or 0 on success.

#### <a id="c-cfg80211_testmode_alloc_event_skb"></a>`cfg80211_testmode_alloc_event_skb()`

```c
struct sk_buff * cfg80211_testmode_alloc_event_skb(struct wiphy *wiphy, int approxlen, gfp_t gfp)
```

allocate testmode event

**Parameters**

- `struct wiphy *wiphy`: the wiphy
- `int approxlen`: an upper bound of the length of the data that will
  be put into the skb
- `gfp_t gfp`: allocation flags

**Description**

This function allocates and pre-fills an skb for an event on the
testmode multicast group.

The returned skb is set up in the same way as with
[`cfg80211_testmode_alloc_reply_skb()`](#c-cfg80211_testmode_alloc_reply_skb) but prepared for an event. As
there, you should simply add data to it that will then end up in the
`NL80211_ATTR_TESTDATA` attribute. Again, you must not modify the skb
in any other way.

When done filling the skb, call [`cfg80211_testmode_event()`](#c-cfg80211_testmode_event) with the
skb to send the event.

**Return**

An allocated and pre-filled skb. `NULL` if any errors happen.

#### <a id="c-cfg80211_testmode_event"></a>`cfg80211_testmode_event()`

```c
void cfg80211_testmode_event(struct sk_buff *skb, gfp_t gfp)
```

send the event

**Parameters**

- `struct sk_buff *skb`: The skb, must have been allocated with
  [`cfg80211_testmode_alloc_event_skb()`](#c-cfg80211_testmode_alloc_event_skb)
- `gfp_t gfp`: allocation flags

**Description**

This function sends the given **skb**, which must have been allocated
by [`cfg80211_testmode_alloc_event_skb()`](#c-cfg80211_testmode_alloc_event_skb), as an event. It always
consumes it.

---

# Introduction

_Peios Kernel / Hardware and drivers / Driver development / Wireless LAN (802.11)_

> Explaining wireless 802.11 networking in the Linux kernel

<a id="rst-introduction"></a>

Explaining wireless 802.11 networking in the Linux kernel

Copyright 2007-2009 Johannes Berg

These books attempt to give a description of the various subsystems that play a role in 802.11 wireless networking in Linux. Since these books are for kernel developers they attempts to document the structures and functions used in the kernel as well as giving a higher-level overview.

The reader is expected to be familiar with the 802.11 standard as published by the IEEE in 802.11-2007 (or possibly later versions). References to this standard will be given as "802.11-2007 8.1.5".

---

# mac80211 subsystem (advanced)

_Peios Kernel / Hardware and drivers / Driver development / Wireless LAN (802.11)_

> Information contained within this part of the book is of interest only for advanced interaction of mac80211 with drivers to exploit more hardware capabilities and improve performance.

<a id="rst-mac80211-subsystem-advanced"></a>

Information contained within this part of the book is of interest only for advanced interaction of mac80211 with drivers to exploit more hardware capabilities and improve performance.

<a id="rst-led-support"></a>

## LED support

Mac80211 supports various ways of blinking LEDs. Wherever possible, device LEDs should be exposed as LED class devices and hooked up to the appropriate trigger, which will then be triggered appropriately by mac80211.


#### <a id="c-struct-ieee80211_tpt_blink"></a>`struct ieee80211_tpt_blink`

throughput blink description

**Definition**

```c
struct ieee80211_tpt_blink {
    int throughput;
    int blink_time;
};
```

**Members**

- `throughput`: throughput in Kbit/sec
- `blink_time`: blink time in milliseconds
  (full cycle, ie. one off + one on period)

#### <a id="c-enum-ieee80211_tpt_led_trigger_flags"></a>`enum ieee80211_tpt_led_trigger_flags`

throughput trigger flags

**Constants**

- `IEEE80211_TPT_LEDTRIG_FL_RADIO`: enable blinking with radio
- `IEEE80211_TPT_LEDTRIG_FL_WORK`: enable blinking when working
- `IEEE80211_TPT_LEDTRIG_FL_CONNECTED`: enable blinking when at least one
  interface is connected in some way, including being an AP

#### <a id="c-ieee80211_get_tx_led_name"></a>`ieee80211_get_tx_led_name()`

```c
const char * ieee80211_get_tx_led_name(struct ieee80211_hw *hw)
```

get name of TX LED

**Parameters**

- `struct ieee80211_hw *hw`: the hardware to get the LED trigger name for

**Description**

mac80211 creates a transmit LED trigger for each wireless hardware
that can be used to drive LEDs if your driver registers a LED device.
This function returns the name (or `NULL` if not configured for LEDs)
of the trigger so you can automatically link the LED device.

**Return**

The name of the LED trigger. `NULL` if not configured for LEDs.

#### <a id="c-ieee80211_get_rx_led_name"></a>`ieee80211_get_rx_led_name()`

```c
const char * ieee80211_get_rx_led_name(struct ieee80211_hw *hw)
```

get name of RX LED

**Parameters**

- `struct ieee80211_hw *hw`: the hardware to get the LED trigger name for

**Description**

mac80211 creates a receive LED trigger for each wireless hardware
that can be used to drive LEDs if your driver registers a LED device.
This function returns the name (or `NULL` if not configured for LEDs)
of the trigger so you can automatically link the LED device.

**Return**

The name of the LED trigger. `NULL` if not configured for LEDs.

#### <a id="c-ieee80211_get_assoc_led_name"></a>`ieee80211_get_assoc_led_name()`

```c
const char * ieee80211_get_assoc_led_name(struct ieee80211_hw *hw)
```

get name of association LED

**Parameters**

- `struct ieee80211_hw *hw`: the hardware to get the LED trigger name for

**Description**

mac80211 creates a association LED trigger for each wireless hardware
that can be used to drive LEDs if your driver registers a LED device.
This function returns the name (or `NULL` if not configured for LEDs)
of the trigger so you can automatically link the LED device.

**Return**

The name of the LED trigger. `NULL` if not configured for LEDs.

#### <a id="c-ieee80211_get_radio_led_name"></a>`ieee80211_get_radio_led_name()`

```c
const char * ieee80211_get_radio_led_name(struct ieee80211_hw *hw)
```

get name of radio LED

**Parameters**

- `struct ieee80211_hw *hw`: the hardware to get the LED trigger name for

**Description**

mac80211 creates a radio change LED trigger for each wireless hardware
that can be used to drive LEDs if your driver registers a LED device.
This function returns the name (or `NULL` if not configured for LEDs)
of the trigger so you can automatically link the LED device.

**Return**

The name of the LED trigger. `NULL` if not configured for LEDs.

#### <a id="c-ieee80211_create_tpt_led_trigger"></a>`ieee80211_create_tpt_led_trigger()`

```c
const char * ieee80211_create_tpt_led_trigger(struct ieee80211_hw *hw, unsigned int flags, const struct ieee80211_tpt_blink *blink_table, unsigned int blink_table_len)
```

create throughput LED trigger

**Parameters**

- `struct ieee80211_hw *hw`: the hardware to create the trigger for
- `unsigned int flags`: trigger flags, see [`enum ieee80211_tpt_led_trigger_flags`](#c-enum-ieee80211_tpt_led_trigger_flags)
- `const struct ieee80211_tpt_blink *blink_table`: the blink table -- needs to be ordered by throughput
- `unsigned int blink_table_len`: size of the blink table

**Return**

`NULL` (in case of error, or if no LED triggers are
configured) or the name of the new trigger.

**Note**

This function must be called before [`ieee80211_register_hw()`](/kernel/hardware/driver-api/80211/mac80211.md#c-ieee80211_register_hw).


<a id="rst-hardware-crypto-acceleration"></a>

## Hardware crypto acceleration


mac80211 is capable of taking advantage of many hardware
acceleration designs for encryption and decryption operations.

The `set_key()` callback in the [`struct ieee80211_ops`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_ops) for a given
device is called to enable hardware acceleration of encryption and
decryption. The callback takes a **sta** parameter that will be NULL
for default keys or keys used for transmission only, or point to
the station information for the peer for individual keys.
Multiple transmission keys with the same key index may be used when
VLANs are configured for an access point.

When transmitting, the TX control data will use the **hw_key_idx**
selected by the driver by modifying the [`struct ieee80211_key_conf`](#c-struct-ieee80211_key_conf)
pointed to by the **key** parameter to the `set_key()` function.

The `set_key()` call for the `SET_KEY` command should return 0 if
the key is now in use, -`EOPNOTSUPP` or -`ENOSPC` if it couldn't be
added; if you return 0 then hw_key_idx must be assigned to the
hardware key index. You are free to use the full u8 range.

Note that in the case that the **IEEE80211_HW_SW_CRYPTO_CONTROL** flag is
set, mac80211 will not automatically fall back to software crypto if
enabling hardware crypto failed. The `set_key()` call may also return the
value 1 to permit this specific key/algorithm to be done in software.

When the cmd is `DISABLE_KEY` then it must succeed.

Note that it is permissible to not decrypt a frame even if a key
for it has been uploaded to hardware. The stack will not make any
decision based on whether a key has been uploaded or not but rather
based on the receive flags.

The [`struct ieee80211_key_conf`](#c-struct-ieee80211_key_conf) structure pointed to by the **key**
parameter is guaranteed to be valid until another call to `set_key()`
removes it, but it can only be used as a cookie to differentiate
keys.

In TKIP some HW need to be provided a phase 1 key, for RX decryption
acceleration (i.e. iwlwifi). Those drivers should provide update_tkip_key
handler.
The `update_tkip_key()` call updates the driver with the new phase 1 key.
This happens every time the iv16 wraps around (every 65536 packets). The
`set_key()` call will happen only once for each key (unless the AP did
rekeying); it will not include a valid phase 1 key. The valid phase 1 key is
provided by update_tkip_key only. The trigger that makes mac80211 call this
handler is software decryption with wrap around of iv16.

The `set_default_unicast_key()` call updates the default WEP key index
configured to the hardware for WEP encryption type. This is required
for devices that support offload of data packets (e.g. ARP responses).

Mac80211 drivers should set the **NL80211_EXT_FEATURE_CAN_REPLACE_PTK0** flag
when they are able to replace in-use PTK keys according to the following
requirements:
1) They do not hand over frames decrypted with the old key to mac80211



#### <a id="c-enum-ieee80211_key_flags"></a>`enum ieee80211_key_flags`

key flags

**Constants**

- `IEEE80211_KEY_FLAG_GENERATE_IV_MGMT`: This flag should be set by the
  driver for a CCMP/GCMP key to indicate that is requires IV generation
  only for management frames (MFP).
- `IEEE80211_KEY_FLAG_GENERATE_IV`: This flag should be set by the
  driver to indicate that it requires IV generation for this
  particular key. Setting this flag does not necessarily mean that SKBs
  will have sufficient tailroom for ICV or MIC.
- `IEEE80211_KEY_FLAG_GENERATE_MMIC`: This flag should be set by
  the driver for a TKIP key if it requires Michael MIC
  generation in software.
- `IEEE80211_KEY_FLAG_PAIRWISE`: Set by mac80211, this flag indicates
  that the key is pairwise rather then a shared key.
- `IEEE80211_KEY_FLAG_SW_MGMT_TX`: This flag should be set by the driver for a
  CCMP/GCMP key if it requires CCMP/GCMP encryption of management frames
  (MFP) to be done in software.
- `IEEE80211_KEY_FLAG_PUT_IV_SPACE`: This flag should be set by the driver
  if space should be prepared for the IV, but the IV
  itself should not be generated. Do not set together with
  **IEEE80211_KEY_FLAG_GENERATE_IV** on the same key. Setting this flag does
  not necessarily mean that SKBs will have sufficient tailroom for ICV or
  MIC.
- `IEEE80211_KEY_FLAG_RX_MGMT`: This key will be used to decrypt received
  management frames. The flag can help drivers that have a hardware
  crypto implementation that doesn't deal with management frames
  properly by allowing them to not upload the keys to hardware and
  fall back to software crypto. Note that this flag deals only with
  RX, if your crypto engine can't deal with TX you can also set the
  `IEEE80211_KEY_FLAG_SW_MGMT_TX` flag to encrypt such frames in SW.
- `IEEE80211_KEY_FLAG_RESERVE_TAILROOM`: This flag should be set by the
  driver for a key to indicate that sufficient tailroom must always
  be reserved for ICV or MIC, even when HW encryption is enabled.
- `IEEE80211_KEY_FLAG_PUT_MIC_SPACE`: This flag should be set by the driver for
  a TKIP key if it only requires MIC space. Do not set together with
  **IEEE80211_KEY_FLAG_GENERATE_MMIC** on the same key.
- `IEEE80211_KEY_FLAG_NO_AUTO_TX`: Key needs explicit Tx activation.
- `IEEE80211_KEY_FLAG_GENERATE_MMIE`: This flag should be set by the driver
  for a AES_CMAC or a AES_GMAC key to indicate that it requires sequence
  number generation only
- `IEEE80211_KEY_FLAG_SPP_AMSDU`: SPP A-MSDUs can be used with this key
  (set by mac80211 from the sta->spp_amsdu flag)

**Description**

These flags are used for communication about keys between the driver
and mac80211, with the **flags** parameter of [`struct ieee80211_key_conf`](#c-struct-ieee80211_key_conf).

#### <a id="c-struct-ieee80211_key_conf"></a>`struct ieee80211_key_conf`

key information

**Definition**

```c
struct ieee80211_key_conf {
    atomic64_t tx_pn;
    u32 cipher;
    u8 icv_len;
    u8 iv_len;
    u8 hw_key_idx;
    s8 keyidx;
    u16 flags;
    s8 link_id;
    u8 keylen;
    u8 key[];
};
```

**Members**

- `tx_pn`: PN used for TX keys, may be used by the driver as well if it
  needs to do software PN assignment by itself (e.g. due to TSO)
- `cipher`: The key's cipher suite selector.
- `icv_len`: The ICV length for this key type
- `iv_len`: The IV length for this key type
- `hw_key_idx`: To be set by the driver, this is the key index the driver
  wants to be given when a frame is transmitted and needs to be
  encrypted in hardware.
- `keyidx`: the key index (0-7)
- `flags`: key flags, see [`enum ieee80211_key_flags`](#c-enum-ieee80211_key_flags).
- `link_id`: the link ID, 0 for non-MLO, or -1 for pairwise keys
- `keylen`: key material length
- `key`: key material. For ALG_TKIP the key is encoded as a 256-bit (32 byte)
  data block:
  - Temporal Encryption Key (128 bits)
  - Temporal Authenticator Tx MIC Key (64 bits)
  - Temporal Authenticator Rx MIC Key (64 bits)

**Description**

This key information is given by mac80211 to the driver by
the `set_key()` callback in [`struct ieee80211_ops`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_ops).

#### <a id="c-enum-set_key_cmd"></a>`enum set_key_cmd`

key command

**Constants**

- `SET_KEY`: a key is set
- `DISABLE_KEY`: a key must be disabled

**Description**

Used with the `set_key()` callback in [`struct ieee80211_ops`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_ops), this
indicates whether a key is being removed or added.

#### <a id="c-ieee80211_get_tkip_p1k_iv"></a>`ieee80211_get_tkip_p1k_iv()`

```c
void ieee80211_get_tkip_p1k_iv(struct ieee80211_key_conf *keyconf, u32 iv32, u16 *p1k)
```

get a TKIP phase 1 key for IV32

**Parameters**

- `struct ieee80211_key_conf *keyconf`: the parameter passed with the set key
- `u32 iv32`: IV32 to get the P1K for
- `u16 *p1k`: a buffer to which the key will be written, as 5 u16 values

**Description**

This function returns the TKIP phase 1 key for the given IV32.

#### <a id="c-ieee80211_get_tkip_p1k"></a>`ieee80211_get_tkip_p1k()`

```c
void ieee80211_get_tkip_p1k(struct ieee80211_key_conf *keyconf, struct sk_buff *skb, u16 *p1k)
```

get a TKIP phase 1 key

**Parameters**

- `struct ieee80211_key_conf *keyconf`: the parameter passed with the set key
- `struct sk_buff *skb`: the packet to take the IV32 value from that will be encrypted
  with this P1K
- `u16 *p1k`: a buffer to which the key will be written, as 5 u16 values

**Description**

This function returns the TKIP phase 1 key for the IV32 taken
from the given packet.

#### <a id="c-ieee80211_get_tkip_p2k"></a>`ieee80211_get_tkip_p2k()`

```c
void ieee80211_get_tkip_p2k(struct ieee80211_key_conf *keyconf, struct sk_buff *skb, u8 *p2k)
```

get a TKIP phase 2 key

**Parameters**

- `struct ieee80211_key_conf *keyconf`: the parameter passed with the set key
- `struct sk_buff *skb`: the packet to take the IV32/IV16 values from that will be
  encrypted with this key
- `u8 *p2k`: a buffer to which the key will be written, 16 bytes

**Description**

This function computes the TKIP RC4 key for the IV values
in the packet.


<a id="rst-powersave-support"></a>

## Powersave support


mac80211 has support for various powersave implementations.

First, it can support hardware that handles all powersaving by itself;
such hardware should simply set the `IEEE80211_HW_SUPPORTS_PS` hardware
flag. In that case, it will be told about the desired powersave mode
with the `IEEE80211_CONF_PS` flag depending on the association status.
The hardware must take care of sending nullfunc frames when necessary,
i.e. when entering and leaving powersave mode. The hardware is required
to look at the AID in beacons and signal to the AP that it woke up when
it finds traffic directed to it.

`IEEE80211_CONF_PS` flag enabled means that the powersave mode defined in
IEEE 802.11-2007 section 11.2 is enabled. This is not to be confused
with hardware wakeup and sleep states. Driver is responsible for waking
up the hardware before issuing commands to the hardware and putting it
back to sleep at appropriate times.

When PS is enabled, hardware needs to wakeup for beacons and receive the
buffered multicast/broadcast frames after the beacon. Also it must be
possible to send frames and receive the acknowledment frame.

Other hardware designs cannot send nullfunc frames by themselves and also
need software support for parsing the TIM bitmap. This is also supported
by mac80211 by combining the `IEEE80211_HW_SUPPORTS_PS` and
`IEEE80211_HW_PS_NULLFUNC_STACK` flags. The hardware is of course still
required to pass up beacons. The hardware is still required to handle
waking up for multicast traffic; if it cannot the driver must handle that
as best as it can; mac80211 is too slow to do that.

Dynamic powersave is an extension to normal powersave in which the
hardware stays awake for a user-specified period of time after sending a
frame so that reply frames need not be buffered and therefore delayed to
the next wakeup. It's a compromise of getting good enough latency when
there's data traffic and still saving significantly power in idle
periods.

Dynamic powersave is simply supported by mac80211 enabling and disabling
PS based on traffic. Driver needs to only set `IEEE80211_HW_SUPPORTS_PS`
flag and mac80211 will handle everything automatically. Additionally,
hardware having support for the dynamic PS feature may set the
`IEEE80211_HW_SUPPORTS_DYNAMIC_PS` flag to indicate that it can support
dynamic PS mode itself. The driver needs to look at the
**dynamic_ps_timeout** hardware configuration value and use it that value
whenever `IEEE80211_CONF_PS` is set. In this case mac80211 will disable
dynamic PS feature in stack and will just keep `IEEE80211_CONF_PS`
enabled whenever user has enabled powersave.

Driver informs U-APSD client support by enabling
`IEEE80211_VIF_SUPPORTS_UAPSD` flag. The mode is configured through the
uapsd parameter in `conf_tx()` operation. Hardware needs to send the QoS
Nullfunc frames and stay awake until the service period has ended. To
utilize U-APSD, dynamic powersave is disabled for voip AC and all frames
from that AC are transmitted with powersave enabled.

Note: U-APSD client mode is not yet supported with
`IEEE80211_HW_PS_NULLFUNC_STACK`.


<a id="rst-beacon-filter-support"></a>

## Beacon filter support


Some hardware have beacon filter support to reduce host cpu wakeups
which will reduce system power consumption. It usually works so that
the firmware creates a checksum of the beacon but omits all constantly
changing elements (TSF, TIM etc). Whenever the checksum changes the
beacon is forwarded to the host, otherwise it will be just dropped. That
way the host will only receive beacons where some relevant information
(for example ERP protection or WMM settings) have changed.

Beacon filter support is advertised with the `IEEE80211_VIF_BEACON_FILTER`
interface capability. The driver needs to enable beacon filter support
whenever power save is enabled, that is `IEEE80211_CONF_PS` is set. When
power save is enabled, the stack will not check for beacon loss and the
driver needs to notify about loss of beacons with [`ieee80211_beacon_loss()`](#c-ieee80211_beacon_loss).

The time (or number of beacons missed) until the firmware notifies the
driver of a beacon loss event (which in turn causes the driver to call
[`ieee80211_beacon_loss()`](#c-ieee80211_beacon_loss)) should be configurable and will be controlled
by mac80211 and the roaming algorithm in the future.

Since there may be constantly changing information elements that nothing
in the software stack cares about, we will, in the future, have mac80211
tell the driver which information elements are interesting in the sense
that we want to see changes in them. This will include

- a list of information element IDs
- a list of OUIs for the vendor information element

Ideally, the hardware would filter out any beacons without changes in the
requested elements, but if it cannot support that it may, at the expense
of some efficiency, filter out only a subset. For example, if the device
doesn't support checking for OUIs it should pass up all changes in all
vendor information elements.

Note that change, for the sake of simplification, also includes information
elements appearing or disappearing from the beacon.

Some hardware supports an "ignore list" instead. Just make sure nothing
that was requested is on the ignore list, and include commonly changing
information element IDs in the ignore list, for example 11 (BSS load) and
the various vendor-assigned IEs with unknown contents (128, 129, 133-136,
149, 150, 155, 156, 173, 176, 178, 179, 219); for forward compatibility
it could also include some currently unused IDs.

In addition to these capabilities, hardware should support notifying the
host of changes in the beacon RSSI. This is relevant to implement roaming
when no traffic is flowing (when traffic is flowing we see the RSSI of
the received data packets). This can consist of notifying the host when
the RSSI changes significantly or when it drops below or rises above
configurable thresholds. In the future these thresholds will also be
configured by mac80211 (which gets them from userspace) to implement
them as the roaming algorithm requires.

If the hardware cannot implement this, the driver should ask it to
periodically pass beacon frames to the host so that software can do the
signal strength threshold checking.



#### <a id="c-ieee80211_beacon_loss"></a>`ieee80211_beacon_loss()`

```c
void ieee80211_beacon_loss(struct ieee80211_vif *vif)
```

inform hardware does not receive beacons

**Parameters**

- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_vif) pointer from the add_interface callback.

**Description**

When beacon filtering is enabled with `IEEE80211_VIF_BEACON_FILTER` and
`IEEE80211_CONF_PS` is set, the driver needs to inform whenever the
hardware is not receiving beacons with this function.


<a id="rst-multiple-queues-and-qos-support"></a>

## Multiple queues and QoS support

TBD


#### <a id="c-struct-ieee80211_tx_queue_params"></a>`struct ieee80211_tx_queue_params`

transmit queue configuration

**Definition**

```c
struct ieee80211_tx_queue_params {
    u16 txop;
    u16 cw_min;
    u16 cw_max;
    u8 aifs;
    bool acm;
    bool uapsd;
    bool mu_edca;
    struct ieee80211_he_mu_edca_param_ac_rec mu_edca_param_rec;
};
```

**Members**

- `txop`: maximum burst time in units of 32 usecs, 0 meaning disabled
- `cw_min`: minimum contention window \[a value of the form
  2^n-1 in the range 1..32767\]
- `cw_max`: maximum contention window \[like **cw_min**\]
- `aifs`: arbitration interframe space \[0..255\]
- `acm`: is mandatory admission control required for the access category
- `uapsd`: is U-APSD mode enabled for the queue
- `mu_edca`: is the MU EDCA configured
- `mu_edca_param_rec`: MU EDCA Parameter Record for HE

**Description**

The information provided in this structure is required for QoS
transmit queue configuration. Cf. IEEE 802.11 7.3.2.29.


<a id="rst-access-point-mode-support"></a>

## Access point mode support

TBD

Some parts of the if_conf should be discussed here instead

Insert notes about VLAN interfaces with hw crypto here or in the hw crypto chapter.

<a id="rst-support-for-powersaving-clients"></a>

### support for powersaving clients


In order to implement AP and P2P GO modes, mac80211 has support for
client powersaving, both "legacy" PS (PS-Poll/null data) and uAPSD.
There currently is no support for sAPSD.

There is one assumption that mac80211 makes, namely that a client
will not poll with PS-Poll and trigger with uAPSD at the same time.
Both are supported, and both can be used by the same client, but
they can't be used concurrently by the same client. This simplifies
the driver code.

The first thing to keep in mind is that there is a flag for complete
driver implementation: `IEEE80211_HW_AP_LINK_PS`. If this flag is set,
mac80211 expects the driver to handle most of the state machine for
powersaving clients and will ignore the PM bit in incoming frames.
Drivers then use [`ieee80211_sta_ps_transition()`](#c-ieee80211_sta_ps_transition) to inform mac80211 of
stations' powersave transitions. In this mode, mac80211 also doesn't
handle PS-Poll/uAPSD.

In the mode without `IEEE80211_HW_AP_LINK_PS`, mac80211 will check the
PM bit in incoming frames for client powersave transitions. When a
station goes to sleep, we will stop transmitting to it. There is,
however, a race condition: a station might go to sleep while there is
data buffered on hardware queues. If the device has support for this
it will reject frames, and the driver should give the frames back to
mac80211 with the `IEEE80211_TX_STAT_TX_FILTERED` flag set which will
cause mac80211 to retry the frame when the station wakes up. The
driver is also notified of powersave transitions by calling its
**sta_notify** callback.

When the station is asleep, it has three choices: it can wake up,
it can PS-Poll, or it can possibly start a uAPSD service period.
Waking up is implemented by simply transmitting all buffered (and
filtered) frames to the station. This is the easiest case. When
the station sends a PS-Poll or a uAPSD trigger frame, mac80211
will inform the driver of this with the **allow_buffered_frames**
callback; this callback is optional. mac80211 will then transmit
the frames as usual and set the `IEEE80211_TX_CTL_NO_PS_BUFFER`
on each frame. The last frame in the service period (or the only
response to a PS-Poll) also has `IEEE80211_TX_STATUS_EOSP` set to
indicate that it ends the service period; as this frame must have
TX status report it also sets `IEEE80211_TX_CTL_REQ_TX_STATUS`.
When TX status is reported for this frame, the service period is
marked has having ended and a new one can be started by the peer.

Additionally, non-bufferable MMPDUs can also be transmitted by
mac80211 with the `IEEE80211_TX_CTL_NO_PS_BUFFER` set in them.

Another race condition can happen on some devices like iwlwifi
when there are frames queued for the station and it wakes up
or polls; the frames that are already queued could end up being
transmitted first instead, causing reordering and/or wrong
processing of the EOSP. The cause is that allowing frames to be
transmitted to a certain station is out-of-band communication to
the device. To allow this problem to be solved, the driver can
call [`ieee80211_sta_block_awake()`](#c-ieee80211_sta_block_awake) if frames are buffered when it
is notified that the station went to sleep. When all these frames
have been filtered (see above), it must call the function again
to indicate that the station is no longer blocked.

If the driver buffers frames in the driver for aggregation in any
way, it must use the [`ieee80211_sta_set_buffered()`](#c-ieee80211_sta_set_buffered) call when it is
notified of the station going to sleep to inform mac80211 of any
TIDs that have frames buffered. Note that when a station wakes up
this information is reset (hence the requirement to call it when
informed of the station going to sleep). Then, when a service
period starts for any reason, **release_buffered_frames** is called
with the number of frames to be released and which TIDs they are
to come from. In this case, the driver is responsible for setting
the EOSP (for uAPSD) and MORE_DATA bits in the released frames.
To help the **more_data** parameter is passed to tell the driver if
there is more data on other TIDs -- the TIDs to release frames
from are ignored since mac80211 doesn't know how many frames the
buffers for those TIDs contain.

If the driver also implement GO mode, where absence periods may
shorten service periods (or abort PS-Poll responses), it must
filter those response frames except in the case of frames that
are buffered in the driver -- those must remain buffered to avoid
reordering. Because it is possible that no frames are released
in this case, the driver must call [`ieee80211_sta_eosp()`](#c-ieee80211_sta_eosp)
to indicate to mac80211 that the service period ended anyway.

Finally, if frames from multiple TIDs are released from mac80211
but the driver might reorder them, it must clear & set the flags
appropriately (only the last frame may have `IEEE80211_TX_STATUS_EOSP`)
and also take care of the EOSP and MORE_DATA bits in the frame.
The driver may also use [`ieee80211_sta_eosp()`](#c-ieee80211_sta_eosp) in this case.

Note that if the driver ever buffers frames other than QoS-data
frames, it must take care to never send a non-QoS-data frame as
the last frame in a service period, adding a QoS-nulldata frame
after a non-QoS-data frame if needed.



#### <a id="c-enum-ieee80211_frame_release_type"></a>`enum ieee80211_frame_release_type`

frame release reason

**Constants**

- `IEEE80211_FRAME_RELEASE_PSPOLL`: frame released for PS-Poll
- `IEEE80211_FRAME_RELEASE_UAPSD`: frame(s) released due to
  frame received on trigger-enabled AC

#### <a id="c-ieee80211_sta_ps_transition"></a>`ieee80211_sta_ps_transition()`

```c
int ieee80211_sta_ps_transition(struct ieee80211_sta *sta, bool start)
```

PS transition for connected sta

**Parameters**

- `struct ieee80211_sta *sta`: currently connected sta
- `bool start`: start or stop PS

**Description**

When operating in AP mode with the `IEEE80211_HW_AP_LINK_PS`
flag set, use this function to inform mac80211 about a connected station
entering/leaving PS mode.

This function may not be called in IRQ context or with softirqs enabled.

Calls to this function for a single hardware must be synchronized against
each other.

**Return**

0 on success. -EINVAL when the requested PS mode is already set.

#### <a id="c-ieee80211_sta_ps_transition_ni"></a>`ieee80211_sta_ps_transition_ni()`

```c
int ieee80211_sta_ps_transition_ni(struct ieee80211_sta *sta, bool start)
```

PS transition for connected sta (in process context)

**Parameters**

- `struct ieee80211_sta *sta`: currently connected sta
- `bool start`: start or stop PS

**Description**

Like [`ieee80211_sta_ps_transition()`](#c-ieee80211_sta_ps_transition) but can be called in process context
(internally disables bottom halves). Concurrent call restriction still
applies.

**Return**

Like [`ieee80211_sta_ps_transition()`](#c-ieee80211_sta_ps_transition).

#### <a id="c-ieee80211_sta_set_buffered"></a>`ieee80211_sta_set_buffered()`

```c
void ieee80211_sta_set_buffered(struct ieee80211_sta *sta, u8 tid, bool buffered)
```

inform mac80211 about driver-buffered frames

**Parameters**

- `struct ieee80211_sta *sta`: [`struct ieee80211_sta`](#c-struct-ieee80211_sta) pointer for the sleeping station
- `u8 tid`: the TID that has buffered frames
- `bool buffered`: indicates whether or not frames are buffered for this TID

**Description**

If a driver buffers frames for a powersave station instead of passing
them back to mac80211 for retransmission, the station may still need
to be told that there are buffered frames via the TIM bit.

This function informs mac80211 whether or not there are frames that are
buffered in the driver for a given TID; mac80211 can then use this data
to set the TIM bit (NOTE: This may call back into the driver's set_tim
call! Beware of the locking!)

If all frames are released to the station (due to PS-poll or uAPSD)
then the driver needs to inform mac80211 that there no longer are
frames buffered. However, when the station wakes up mac80211 assumes
that all buffered frames will be transmitted and clears this data,
drivers need to make sure they inform mac80211 about all buffered
frames on the sleep transition (`sta_notify()` with `STA_NOTIFY_SLEEP`).

Note that technically mac80211 only needs to know this per AC, not per
TID, but since driver buffering will inevitably happen per TID (since
it is related to aggregation) it is easier to make mac80211 map the
TID to the AC as required instead of keeping track in all drivers that
use this API.

#### <a id="c-ieee80211_beacon_get"></a>`ieee80211_beacon_get()`

```c
struct sk_buff * ieee80211_beacon_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, unsigned int link_id)
```

beacon generation function

**Parameters**

- `struct ieee80211_hw *hw`: pointer obtained from [`ieee80211_alloc_hw()`](/kernel/hardware/driver-api/80211/mac80211.md#c-ieee80211_alloc_hw).
- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_vif) pointer from the add_interface callback.
- `unsigned int link_id`: the link id to which the beacon belongs (or 0 for an AP STA
  that is not associated with AP MLD).

**Description**

See `ieee80211_beacon_get_tim()`.

**Return**

See `ieee80211_beacon_get_tim()`.

#### <a id="c-ieee80211_get_buffered_bc"></a>`ieee80211_get_buffered_bc()`

```c
struct sk_buff * ieee80211_get_buffered_bc(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
```

accessing buffered broadcast and multicast frames

**Parameters**

- `struct ieee80211_hw *hw`: pointer as obtained from [`ieee80211_alloc_hw()`](/kernel/hardware/driver-api/80211/mac80211.md#c-ieee80211_alloc_hw).
- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_vif) pointer from the add_interface callback.

**Description**

Function for accessing buffered broadcast and multicast frames. If
hardware/firmware does not implement buffering of broadcast/multicast
frames when power saving is used, 802.11 code buffers them in the host
memory. The low-level driver uses this function to fetch next buffered
frame. In most cases, this is used when generating beacon frame.

**Return**

A pointer to the next buffered skb or NULL if no more buffered
frames are available.

**Note**

buffered frames are returned only after DTIM beacon frame was
generated with [`ieee80211_beacon_get()`](#c-ieee80211_beacon_get) and the low-level driver must thus
call [`ieee80211_beacon_get()`](#c-ieee80211_beacon_get) first. [`ieee80211_get_buffered_bc()`](#c-ieee80211_get_buffered_bc) returns
NULL if the previous generated beacon was not DTIM, so the low-level driver
does not need to check for DTIM beacons separately and should be able to
use common code for all beacons.

#### <a id="c-ieee80211_sta_block_awake"></a>`ieee80211_sta_block_awake()`

```c
void ieee80211_sta_block_awake(struct ieee80211_hw *hw, struct ieee80211_sta *pubsta, bool block)
```

block station from waking up

**Parameters**

- `struct ieee80211_hw *hw`: the hardware
- `struct ieee80211_sta *pubsta`: the station
- `bool block`: whether to block or unblock

**Description**

Some devices require that all frames that are on the queues
for a specific station that went to sleep are flushed before
a poll response or frames after the station woke up can be
delivered to that it. Note that such frames must be rejected
by the driver as filtered, with the appropriate status flag.

This function allows implementing this mode in a race-free
manner.

To do this, a driver must keep track of the number of frames
still enqueued for a specific station. If this number is not
zero when the station goes to sleep, the driver must call
this function to force mac80211 to consider the station to
be asleep regardless of the station's actual state. Once the
number of outstanding frames reaches zero, the driver must
call this function again to unblock the station. That will
cause mac80211 to be able to send ps-poll responses, and if
the station queried in the meantime then frames will also
be sent out as a result of this. Additionally, the driver
will be notified that the station woke up some time after
it is unblocked, regardless of whether the station actually
woke up while blocked or not.

#### <a id="c-ieee80211_sta_eosp"></a>`ieee80211_sta_eosp()`

```c
void ieee80211_sta_eosp(struct ieee80211_sta *pubsta)
```

notify mac80211 about end of SP

**Parameters**

- `struct ieee80211_sta *pubsta`: the station

**Description**

When a device transmits frames in a way that it can't tell
mac80211 in the TX status about the EOSP, it must clear the
`IEEE80211_TX_STATUS_EOSP` bit and call this function instead.
This applies for PS-Poll as well as uAPSD.

Note that just like with `_tx_status()` and `_rx()` drivers must
not mix calls to irqsafe/non-irqsafe versions, this function
must not be mixed with those either. Use the all irqsafe, or
all non-irqsafe, don't mix!

- NB: the _irqsafe version of this function doesn't exist, no

  driver needs it right now. Don't call this function if
  you'd need the _irqsafe version, look at the git history
  and restore the _irqsafe version!


<a id="rst-supporting-multiple-virtual-interfaces"></a>

## Supporting multiple virtual interfaces

TBD

Note: WDS with identical MAC address should almost always be OK

Insert notes about having multiple virtual interfaces with different MAC addresses here, note which configurations are supported by mac80211, add notes about supporting hw crypto with it.


#### <a id="c-ieee80211_iterate_active_interfaces"></a>`ieee80211_iterate_active_interfaces()`

```c
void ieee80211_iterate_active_interfaces(struct ieee80211_hw *hw, u32 iter_flags, void (*iterator)(void *data, u8 *mac, struct ieee80211_vif *vif), void *data)
```

iterate active interfaces

**Parameters**

- `struct ieee80211_hw *hw`: the hardware struct of which the interfaces should be iterated over
- `u32 iter_flags`: iteration flags, see `enum ieee80211_interface_iteration_flags`
- `void (*iterator)(void *data, u8 *mac, struct ieee80211_vif *vif)`: the iterator function to call
- `void *data`: first argument of the iterator function

**Description**

This function iterates over the interfaces associated with a given
hardware that are currently active and calls the callback for them.
This function allows the iterator function to sleep, when the iterator
function is atomic **ieee80211_iterate_active_interfaces_atomic** can
be used.
Does not iterate over a new interface during `add_interface()`.

#### <a id="c-ieee80211_iterate_active_interfaces_atomic"></a>`ieee80211_iterate_active_interfaces_atomic()`

```c
void ieee80211_iterate_active_interfaces_atomic(struct ieee80211_hw *hw, u32 iter_flags, void (*iterator)(void *data, u8 *mac, struct ieee80211_vif *vif), void *data)
```

iterate active interfaces

**Parameters**

- `struct ieee80211_hw *hw`: the hardware struct of which the interfaces should be iterated over
- `u32 iter_flags`: iteration flags, see `enum ieee80211_interface_iteration_flags`
- `void (*iterator)(void *data, u8 *mac, struct ieee80211_vif *vif)`: the iterator function to call, cannot sleep
- `void *data`: first argument of the iterator function

**Description**

This function iterates over the interfaces associated with a given
hardware that are currently active and calls the callback for them.
This function requires the iterator callback function to be atomic,
if that is not desired, use **ieee80211_iterate_active_interfaces** instead.
Does not iterate over a new interface during `add_interface()`.


<a id="rst-station-handling"></a>

## Station handling

TODO


#### <a id="c-struct-ieee80211_sta"></a>`struct ieee80211_sta`

station table entry

**Definition**

```c
struct ieee80211_sta {
    u8 addr[ETH_ALEN] ;
    u16 aid;
    u16 max_rx_aggregation_subframes;
    bool wme;
    u8 uapsd_queues;
    u8 max_sp;
    struct ieee80211_sta_rates  *rates;
    bool tdls;
    bool tdls_initiator;
    bool mfp;
    bool mlo;
    bool spp_amsdu;
    u8 max_amsdu_subframes;
    u16 eml_cap;
    struct ieee80211_sta_aggregates *cur;
    bool support_p2p_ps;
    struct ieee80211_txq *txq[IEEE80211_NUM_TIDS + 1];
    u16 valid_links;
    bool epp_peer;
    struct ieee80211_link_sta deflink;
    struct ieee80211_link_sta  *link[IEEE80211_MLD_MAX_NUM_LINKS];
    u8 drv_priv[] ;
};
```

**Members**

- `addr`: MAC address
- `aid`: AID we assigned to the station if we're an AP
- `max_rx_aggregation_subframes`: maximal amount of frames in a single AMPDU
  that this station is allowed to transmit to us.
  Can be modified by driver.
- `wme`: indicates whether the STA supports QoS/WME (if local devices does,
  otherwise always false)
- `uapsd_queues`: bitmap of queues configured for uapsd. Only valid
  if wme is supported. The bits order is like in
  IEEE80211_WMM_IE_STA_QOSINFO_AC_*.
- `max_sp`: max Service Period. Only valid if wme is supported.
- `rates`: rate control selection table
- `tdls`: indicates whether the STA is a TDLS peer
- `tdls_initiator`: indicates the STA is an initiator of the TDLS link. Only
  valid if the STA is a TDLS peer in the first place.
- `mfp`: indicates whether the STA uses management frame protection or not.
- `mlo`: indicates whether the STA is MLO station.
- `spp_amsdu`: indicates whether the STA uses SPP A-MSDU or not.
- `max_amsdu_subframes`: indicates the maximal number of MSDUs in a single
  A-MSDU. Taken from the Extended Capabilities element. 0 means
  unlimited.
- `eml_cap`: EML capabilities of this MLO station
- `cur`: currently valid data as aggregated from the active links
  For non MLO STA it will point to the deflink data. For MLO STA
  `ieee80211_sta_recalc_aggregates()` must be called to update it.
- `support_p2p_ps`: indicates whether the STA supports P2P PS mechanism or not.
- `txq`: per-TID data TX queues; note that the last entry (`IEEE80211_NUM_TIDS`)
  is used for non-data frames
- `valid_links`: bitmap of valid links, or 0 for non-MLO
- `epp_peer`: indicates that the peer is an EPP peer.
- `deflink`: This holds the default link STA information, for non MLO STA all link
  specific STA information is accessed through **deflink** or through
  link\[0\] which points to address of **deflink**. For MLO Link STA
  the first added link STA will point to deflink.
- `link`: reference to Link Sta entries. For Non MLO STA, except 1st link,
  i.e link\[0\] all links would be assigned to NULL by default and
  would access link information via **deflink** or link\[0\]. For MLO
  STA, first link STA being added will point its link pointer to
  **deflink** address and remaining would be allocated and the address
  would be assigned to link\[link_id\] where link_id is the id assigned
  by the AP.
- `drv_priv`: data area for driver use, will always be aligned to
  sizeof(void \*), size is determined in hw information.

**Description**

A station table entry represents a station we are possibly
communicating with. Since stations are RCU-managed in
mac80211, any ieee80211_sta pointer you get access to must
either be protected by [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock) explicitly or implicitly,
or you must take good care to not use such a pointer after a
call to your sta_remove callback that removed it.
This also represents the MLD STA in case of MLO association
and holds pointers to various link STA's

#### <a id="c-enum-sta_notify_cmd"></a>`enum sta_notify_cmd`

sta notify command

**Constants**

- `STA_NOTIFY_SLEEP`: a station is now sleeping
- `STA_NOTIFY_AWAKE`: a sleeping station woke up

**Description**

Used with the `sta_notify()` callback in [`struct ieee80211_ops`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_ops), this
indicates if an associated station made a power state transition.

#### <a id="c-ieee80211_find_sta"></a>`ieee80211_find_sta()`

```c
struct ieee80211_sta * ieee80211_find_sta(struct ieee80211_vif *vif, const u8 *addr)
```

find a station

**Parameters**

- `struct ieee80211_vif *vif`: virtual interface to look for station on
- `const u8 *addr`: station's address

**Return**

The station, if found. `NULL` otherwise.

**Note**

This function must be called under RCU lock and the
resulting pointer is only valid under RCU lock as well.

#### <a id="c-ieee80211_find_sta_by_ifaddr"></a>`ieee80211_find_sta_by_ifaddr()`

```c
struct ieee80211_sta * ieee80211_find_sta_by_ifaddr(struct ieee80211_hw *hw, const u8 *addr, const u8 *localaddr)
```

find a station on hardware

**Parameters**

- `struct ieee80211_hw *hw`: pointer as obtained from [`ieee80211_alloc_hw()`](/kernel/hardware/driver-api/80211/mac80211.md#c-ieee80211_alloc_hw)
- `const u8 *addr`: remote station's address
- `const u8 *localaddr`: local address (vif->sdata->vif.addr). Use NULL for 'any'.

**Return**

The station, if found. `NULL` otherwise.

**Note**

This function must be called under RCU lock and the
resulting pointer is only valid under RCU lock as well.

**NOTE**

- You may pass NULL for localaddr, but then you will just get

  the first STA that matches the remote address 'addr'.
  We can have multiple STA associated with multiple
  logical stations (e.g. consider a station connecting to another
  BSSID on the same AP hardware without disconnecting first).
  In this case, the result of this method with localaddr NULL
  is not reliable.

DO NOT USE THIS FUNCTION with localaddr NULL if at all possible.


<a id="rst-hardware-scan-offload"></a>

## Hardware scan offload

TBD


#### <a id="c-ieee80211_scan_completed"></a>`ieee80211_scan_completed()`

```c
void ieee80211_scan_completed(struct ieee80211_hw *hw, struct cfg80211_scan_info *info)
```

completed hardware scan

**Parameters**

- `struct ieee80211_hw *hw`: the hardware that finished the scan
- `struct cfg80211_scan_info *info`: information about the completed scan

**Description**

When hardware scan offload is used (i.e. the `hw_scan()` callback is
assigned) this function needs to be called by the driver to notify
mac80211 that the scan finished. This function can be called from
any context, including hardirq context.


<a id="rst-aggregation"></a>

## Aggregation

<a id="rst-tx-a-mpdu-aggregation"></a>

### TX A-MPDU aggregation


Aggregation on the TX side requires setting the hardware flag
`IEEE80211_HW_AMPDU_AGGREGATION`. The driver will then be handed
packets with a flag indicating A-MPDU aggregation. The driver
or device is responsible for actually aggregating the frames,
as well as deciding how many and which to aggregate.

When TX aggregation is started by some subsystem (usually the rate
control algorithm would be appropriate) by calling the
[`ieee80211_start_tx_ba_session()`](#c-ieee80211_start_tx_ba_session) function, the driver will be
notified via its **ampdu_action** function, with the
`IEEE80211_AMPDU_TX_START` action.

In response to that, the driver is later required to call the
[`ieee80211_start_tx_ba_cb_irqsafe()`](#c-ieee80211_start_tx_ba_cb_irqsafe) function, which will really
start the aggregation session after the peer has also responded.
If the peer responds negatively, the session will be stopped
again right away. Note that it is possible for the aggregation
session to be stopped before the driver has indicated that it
is done setting it up, in which case it must not indicate the
setup completion.

Also note that, since we also need to wait for a response from
the peer, the driver is notified of the completion of the
handshake by the `IEEE80211_AMPDU_TX_OPERATIONAL` action to the
**ampdu_action** callback.

Similarly, when the aggregation session is stopped by the peer
or something calling [`ieee80211_stop_tx_ba_session()`](#c-ieee80211_stop_tx_ba_session), the driver's
**ampdu_action** function will be called with the action
`IEEE80211_AMPDU_TX_STOP`. In this case, the call must not fail,
and the driver must later call [`ieee80211_stop_tx_ba_cb_irqsafe()`](#c-ieee80211_stop_tx_ba_cb_irqsafe).
Note that the sta can get destroyed before the BA tear down is
complete.


<!-- WARNING: DOCPROC directive not supported: !Cnet/mac80211/agg-tx.c -->

<a id="rst-rx-a-mpdu-aggregation"></a>

### RX A-MPDU aggregation


Aggregation on the RX side requires only implementing the
**ampdu_action** callback that is invoked to start/stop any
block-ack sessions for RX aggregation.

When RX aggregation is started by the peer, the driver is
notified via **ampdu_action** function, with the
`IEEE80211_AMPDU_RX_START` action, and may reject the request
in which case a negative response is sent to the peer, if it
accepts it a positive response is sent.

While the session is active, the device/driver are required
to de-aggregate frames and pass them up one by one to mac80211,
which will handle the reorder buffer.

When the aggregation session is stopped again by the peer or
ourselves, the driver's **ampdu_action** function will be called
with the action `IEEE80211_AMPDU_RX_STOP`. In this case, the
call must not fail.


<!-- WARNING: DOCPROC directive not supported: !Cnet/mac80211/agg-rx.c -->


#### <a id="c-enum-ieee80211_ampdu_mlme_action"></a>`enum ieee80211_ampdu_mlme_action`

A-MPDU actions

**Constants**

- `IEEE80211_AMPDU_RX_START`: start RX aggregation
- `IEEE80211_AMPDU_RX_STOP`: stop RX aggregation
- `IEEE80211_AMPDU_TX_START`: start TX aggregation, the driver must either
  call [`ieee80211_start_tx_ba_cb_irqsafe()`](#c-ieee80211_start_tx_ba_cb_irqsafe) or
  call [`ieee80211_start_tx_ba_cb_irqsafe()`](#c-ieee80211_start_tx_ba_cb_irqsafe) with status
  `IEEE80211_AMPDU_TX_START_DELAY_ADDBA` to delay addba after
  ieee80211_start_tx_ba_cb_irqsafe is called, or just return the special
  status `IEEE80211_AMPDU_TX_START_IMMEDIATE`.
- `IEEE80211_AMPDU_TX_STOP_CONT`: stop TX aggregation but continue transmitting
  queued packets, now unaggregated. After all packets are transmitted the
  driver has to call [`ieee80211_stop_tx_ba_cb_irqsafe()`](#c-ieee80211_stop_tx_ba_cb_irqsafe).
- `IEEE80211_AMPDU_TX_STOP_FLUSH`: stop TX aggregation and flush all packets,
  called when the station is removed. There's no need or reason to call
  [`ieee80211_stop_tx_ba_cb_irqsafe()`](#c-ieee80211_stop_tx_ba_cb_irqsafe) in this case as mac80211 assumes the
  session is gone and removes the station.
- `IEEE80211_AMPDU_TX_STOP_FLUSH_CONT`: called when TX aggregation is stopped
  but the driver hasn't called [`ieee80211_stop_tx_ba_cb_irqsafe()`](#c-ieee80211_stop_tx_ba_cb_irqsafe) yet and
  now the connection is dropped and the station will be removed. Drivers
  should clean up and drop remaining packets when this is called.
- `IEEE80211_AMPDU_TX_OPERATIONAL`: TX aggregation has become operational

**Description**

These flags are used with the `ampdu_action()` callback in
[`struct ieee80211_ops`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_ops) to indicate which action is needed.

Note that drivers MUST be able to deal with a TX aggregation
session being stopped even before they OK'ed starting it by
calling ieee80211_start_tx_ba_cb_irqsafe, because the peer
might receive the addBA frame and send a delBA right away!


<a id="rst-spatial-multiplexing-powersave-smps"></a>

## Spatial Multiplexing Powersave (SMPS)


SMPS (Spatial multiplexing power save) is a mechanism to conserve
power in an 802.11n implementation. For details on the mechanism
and rationale, please refer to 802.11 (as amended by 802.11n-2009)
"11.2.3 SM power save".

The mac80211 implementation is capable of sending action frames
to update the AP about the station's SMPS mode, and will instruct
the driver to enter the specific mode. It will also announce the
requested SMPS mode during the association handshake. Hardware
support for this feature is required, and can be indicated by
hardware flags.

The default mode will be "automatic", which nl80211/cfg80211
defines to be dynamic SMPS in (regular) powersave, and SMPS
turned off otherwise.

To support this feature, the driver must set the appropriate
hardware support flags, and handle the SMPS flag to the `config()`
operation. It will then with this mechanism be instructed to
enter the requested SMPS mode while associated to an HT AP.



#### <a id="c-enum-ieee80211_smps_mode"></a>`enum ieee80211_smps_mode`

spatial multiplexing power save mode

**Constants**

- `IEEE80211_SMPS_AUTOMATIC`: automatic
- `IEEE80211_SMPS_OFF`: off
- `IEEE80211_SMPS_STATIC`: static
- `IEEE80211_SMPS_DYNAMIC`: dynamic
- `IEEE80211_SMPS_NUM_MODES`: internal, don't use

#### <a id="c-ieee80211_request_smps"></a>`ieee80211_request_smps()`

```c
void ieee80211_request_smps(struct ieee80211_vif *vif, unsigned int link_id, enum ieee80211_smps_mode smps_mode)
```

request SM PS transition

**Parameters**

- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_vif) pointer from the add_interface callback.
- `unsigned int link_id`: link ID for MLO, or 0
- `enum ieee80211_smps_mode smps_mode`: new SM PS mode

**Description**

This allows the driver to request an SM PS transition in managed
mode. This is useful when the driver has more information than
the stack about possible interference, for example by bluetooth.


TBD

This part of the book describes the rate control algorithm interface and how it relates to mac80211 and drivers.

<a id="rst-rate-control-api"></a>

## Rate Control API

TBD


#### <a id="c-enum-ieee80211_rate_control_changed"></a>`enum ieee80211_rate_control_changed`

flags to indicate what changed

**Constants**

- `IEEE80211_RC_BW_CHANGED`: The bandwidth that can be used to transmit
  to this station changed. The actual bandwidth is in the station
  information -- for HT20/40 the IEEE80211_HT_CAP_SUP_WIDTH_20_40
  flag changes, for HT and VHT the bandwidth field changes.
- `IEEE80211_RC_SMPS_CHANGED`: The SMPS state of the station changed.
- `IEEE80211_RC_SUPP_RATES_CHANGED`: The supported rate set of this peer
  changed (in IBSS mode) due to discovering more information about
  the peer.
- `IEEE80211_RC_NSS_CHANGED`: N_SS (number of spatial streams) was changed
  by the peer

#### <a id="c-ieee80211_start_tx_ba_session"></a>`ieee80211_start_tx_ba_session()`

```c
int ieee80211_start_tx_ba_session(struct ieee80211_sta *sta, u16 tid, u16 timeout)
```

Start a tx Block Ack session.

**Parameters**

- `struct ieee80211_sta *sta`: the station for which to start a BA session
- `u16 tid`: the TID to BA on.
- `u16 timeout`: session timeout value (in TUs)

**Return**

success if addBA request was sent, failure otherwise

**Description**

Although mac80211/low level driver/user space application can estimate
the need to start aggregation on a certain RA/TID, the session level
will be managed by the mac80211.

#### <a id="c-ieee80211_start_tx_ba_cb_irqsafe"></a>`ieee80211_start_tx_ba_cb_irqsafe()`

```c
void ieee80211_start_tx_ba_cb_irqsafe(struct ieee80211_vif *vif, const u8 *ra, u16 tid)
```

low level driver ready to aggregate.

**Parameters**

- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_vif) pointer from the add_interface callback
- `const u8 *ra`: receiver address of the BA session recipient.
- `u16 tid`: the TID to BA on.

**Description**

This function must be called by low level driver once it has
finished with preparations for the BA session. It can be called
from any context.

#### <a id="c-ieee80211_stop_tx_ba_session"></a>`ieee80211_stop_tx_ba_session()`

```c
int ieee80211_stop_tx_ba_session(struct ieee80211_sta *sta, u16 tid)
```

Stop a Block Ack session.

**Parameters**

- `struct ieee80211_sta *sta`: the station whose BA session to stop
- `u16 tid`: the TID to stop BA.

**Return**

negative error if the TID is invalid, or no aggregation active

**Description**

Although mac80211/low level driver/user space application can estimate
the need to stop aggregation on a certain RA/TID, the session level
will be managed by the mac80211.

#### <a id="c-ieee80211_stop_tx_ba_cb_irqsafe"></a>`ieee80211_stop_tx_ba_cb_irqsafe()`

```c
void ieee80211_stop_tx_ba_cb_irqsafe(struct ieee80211_vif *vif, const u8 *ra, u16 tid)
```

low level driver ready to stop aggregate.

**Parameters**

- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](/kernel/hardware/driver-api/80211/mac80211.md#c-struct-ieee80211_vif) pointer from the add_interface callback
- `const u8 *ra`: receiver address of the BA session recipient.
- `u16 tid`: the desired TID to BA on.

**Description**

This function must be called by low level driver once it has
finished with preparations for the BA session tear down. It
can be called from any context.

#### <a id="c-struct-ieee80211_tx_rate_control"></a>`struct ieee80211_tx_rate_control`

rate control information for/from RC algo

**Definition**

```c
struct ieee80211_tx_rate_control {
    struct ieee80211_hw *hw;
    struct ieee80211_supported_band *sband;
    struct ieee80211_bss_conf *bss_conf;
    struct sk_buff *skb;
    struct ieee80211_tx_rate reported_rate;
    bool rts, short_preamble;
    u32 rate_idx_mask;
    u8 *rate_idx_mcs_mask;
    bool bss;
};
```

**Members**

- `hw`: The hardware the algorithm is invoked for.
- `sband`: The band this frame is being transmitted on.
- `bss_conf`: the current BSS configuration
- `skb`: the skb that will be transmitted, the control information in it needs
  to be filled in
- `reported_rate`: The rate control algorithm can fill this in to indicate
  which rate should be reported to userspace as the current rate and
  used for rate calculations in the mesh network.
- `rts`: whether RTS will be used for this frame because it is longer than the
  RTS threshold
- `short_preamble`: whether mac80211 will request short-preamble transmission
  if the selected rate supports it
- `rate_idx_mask`: user-requested (legacy) rate mask
- `rate_idx_mcs_mask`: user-requested MCS rate mask (NULL if not in use)
- `bss`: whether this frame is sent out in AP or IBSS mode


TBD

This part of the book describes mac80211 internals.

<a id="rst-key-handling"></a>

## Key handling

<a id="rst-key-handling-basics"></a>

### Key handling basics


Key handling in mac80211 is done based on per-interface (sub_if_data)
keys and per-station keys. Since each station belongs to an interface,
each station key also belongs to that interface.

Hardware acceleration is done on a best-effort basis for algorithms
that are implemented in software,  for each key the hardware is asked
to enable that key for offloading but if it cannot do that the key is
simply kept for software encryption (unless it is for an algorithm
that isn't implemented in software).
There is currently no way of knowing whether a key is handled in SW
or HW except by looking into debugfs.

All key management is internally protected by a mutex. Within all
other parts of mac80211, key references are, just as STA structure
references, protected by RCU. Note, however, that some things are
unprotected, namely the key->sta dereferences within the hardware
acceleration functions. This means that `sta_info_destroy()` must
remove the key which waits for an RCU grace period.


<a id="rst-more-tbd"></a>

### MORE TBD

TBD

<a id="rst-receive-processing"></a>

## Receive processing

TBD

<a id="rst-transmit-processing"></a>

## Transmit processing

TBD

<a id="rst-station-info-handling"></a>

## Station info handling

<a id="rst-programming-information"></a>

### Programming information


#### <a id="c-enum-ieee80211_sta_info_flags"></a>`enum ieee80211_sta_info_flags`

Stations flags

**Constants**

- `WLAN_STA_AUTH`: Station is authenticated.
- `WLAN_STA_ASSOC`: Station is associated.
- `WLAN_STA_PS_STA`: Station is in power-save mode
- `WLAN_STA_AUTHORIZED`: Station is authorized to send/receive traffic.
  This bit is always checked so needs to be enabled for all stations
  when virtual port control is not in use.
- `WLAN_STA_SHORT_PREAMBLE`: Station is capable of receiving short-preamble
  frames.
- `WLAN_STA_WDS`: Station is one of our WDS peers.
- `WLAN_STA_CLEAR_PS_FILT`: Clear PS filter in hardware (using the
  IEEE80211_TX_CTL_CLEAR_PS_FILT control flag) when the next
  frame to this station is transmitted.
- `WLAN_STA_MFP`: Management frame protection is used with this STA.
- `WLAN_STA_BLOCK_BA`: Used to deny ADDBA requests (both TX and RX)
  during suspend/resume and station removal.
- `WLAN_STA_PS_DRIVER`: driver requires keeping this station in
  power-save mode logically to flush frames that might still
  be in the queues
- `WLAN_STA_PSPOLL`: Station sent PS-poll while driver was keeping
  station in power-save mode, reply when the driver unblocks.
- `WLAN_STA_TDLS_PEER`: Station is a TDLS peer.
- `WLAN_STA_TDLS_PEER_AUTH`: This TDLS peer is authorized to send direct
  packets. This means the link is enabled.
- `WLAN_STA_TDLS_INITIATOR`: We are the initiator of the TDLS link with this
  station.
- `WLAN_STA_TDLS_CHAN_SWITCH`: This TDLS peer supports TDLS channel-switching
- `WLAN_STA_TDLS_OFF_CHANNEL`: The local STA is currently off-channel with this
  TDLS peer
- `WLAN_STA_TDLS_WIDER_BW`: This TDLS peer supports working on a wider bw on
  the BSS base channel.
- `WLAN_STA_UAPSD`: Station requested unscheduled SP while driver was
  keeping station in power-save mode, reply when the driver
  unblocks the station.
- `WLAN_STA_SP`: Station is in a service period, so don't try to
  reply to other uAPSD trigger frames or PS-Poll.
- `WLAN_STA_4ADDR_EVENT`: 4-addr event was already sent for this frame.
- `WLAN_STA_INSERTED`: This station is inserted into the hash table.
- `WLAN_STA_RATE_CONTROL`: rate control was initialized for this station.
- `WLAN_STA_TOFFSET_KNOWN`: toffset calculated for this station is valid.
- `WLAN_STA_MPSP_OWNER`: local STA is owner of a mesh Peer Service Period.
- `WLAN_STA_MPSP_RECIPIENT`: local STA is recipient of a MPSP.
- `WLAN_STA_PS_DELIVER`: station woke up, but we're still blocking TX
  until pending frames are delivered
- `WLAN_STA_USES_ENCRYPTION`: This station was configured for encryption,
  so drop all packets without a key later.
- `WLAN_STA_DECAP_OFFLOAD`: This station uses rx decap offload
- `NUM_WLAN_STA_FLAGS`: number of defined flags

**Description**

These flags are used with [`struct sta_info`](#c-struct-sta_info)'s **flags** member, but
only indirectly with `set_sta_flag()` and friends.

#### <a id="c-struct-sta_info"></a>`struct sta_info`

STA information

**Definition**

```c
struct sta_info {
        struct list_head list, free_list;
        struct rcu_head rcu_head;
        struct rhlist_head hash_node;
        u8 addr[ETH_ALEN];
        struct ieee80211_local *local;
        struct ieee80211_sub_if_data *sdata;
        struct ieee80211_key  *ptk[NUM_DEFAULT_KEYS];
        u8 ptk_idx;
        struct rate_control_ref *rate_ctrl;
        void *rate_ctrl_priv;
        spinlock_t rate_ctrl_lock;
        spinlock_t lock;
        struct ieee80211_fast_tx  *fast_tx;
        struct ieee80211_fast_rx  *fast_rx;
    #ifdef CONFIG_MAC80211_MESH;
        struct mesh_sta *mesh;
    #endif;
        struct work_struct drv_deliver_wk;
        u16 listen_interval;
        bool dead;
        bool removed;
        bool uploaded;
        enum ieee80211_sta_state sta_state;
        unsigned long _flags;
        spinlock_t ps_lock;
        struct sk_buff_head ps_tx_buf[IEEE80211_NUM_ACS];
        struct sk_buff_head tx_filtered[IEEE80211_NUM_ACS];
        unsigned long driver_buffered_tids;
        unsigned long txq_buffered_tids;
        u64 assoc_at;
        long last_connected;
        __le16 last_seq_ctrl[IEEE80211_NUM_TIDS + 1];
        u16 tid_seq[IEEE80211_QOS_CTL_TID_MASK + 1];
        struct airtime_info airtime[IEEE80211_NUM_ACS];
        u16 airtime_weight;
        struct sta_ampdu_mlme ampdu_mlme;
    #ifdef CONFIG_MAC80211_DEBUGFS;
        struct dentry *debugfs_dir;
    #endif;
        u8 reserved_tid;
        s8 amsdu_mesh_control;
        struct cfg80211_chan_def tdls_chandef;
        struct ieee80211_fragment_cache frags;
        struct ieee80211_sta_aggregates cur;
        struct link_sta_info deflink;
        struct link_sta_info  *link[IEEE80211_MLD_MAX_NUM_LINKS];
        struct ieee80211_sta_removed_link_stats rem_link_stats;
        struct ieee80211_sta sta;
};
```

**Members**

- `list`: global linked list entry
- `free_list`: list entry for keeping track of stations to free
- `rcu_head`: RCU head used for freeing this station struct
- `hash_node`: hash node for rhashtable
- `addr`: station's MAC address - duplicated from public part to
  let the hash table work with just a single cacheline
- `local`: pointer to the global information
- `sdata`: virtual interface this station belongs to
- `ptk`: peer keys negotiated with this station, if any
- `ptk_idx`: last installed peer key index
- `rate_ctrl`: rate control algorithm reference
- `rate_ctrl_priv`: rate control private per-STA pointer
- `rate_ctrl_lock`: spinlock used to protect rate control data
  (data inside the algorithm, so serializes calls there)
- `lock`: used for locking all fields that require locking, see comments
  in the header file.
- `fast_tx`: TX fastpath information
- `fast_rx`: RX fastpath information
- `mesh`: mesh STA information
- `drv_deliver_wk`: used for delivering frames after driver PS unblocking
- `listen_interval`: listen interval of this station, when we're acting as AP
- `dead`: set to true when sta is unlinked
- `removed`: set to true when sta is being removed from sta_list
- `uploaded`: set to true when sta is uploaded to the driver
- `sta_state`: duplicates information about station state (for debug)
- `_flags`: STA flags, see [`enum ieee80211_sta_info_flags`](#c-enum-ieee80211_sta_info_flags), do not use directly
- `ps_lock`: used for powersave (when mac80211 is the AP) related locking
- `ps_tx_buf`: buffers (per AC) of frames to transmit to this station
  when it leaves power saving state or polls
- `tx_filtered`: buffers (per AC) of frames we already tried to
  transmit but were filtered by hardware due to STA having
  entered power saving state, these are also delivered to
  the station when it leaves powersave or polls for frames
- `driver_buffered_tids`: bitmap of TIDs the driver has data buffered on
- `txq_buffered_tids`: bitmap of TIDs that mac80211 has txq data buffered on
- `assoc_at`: clock boottime (in ns) of last association
- `last_connected`: time (in seconds) when a station got connected
- `last_seq_ctrl`: last received seq/frag number from this STA (per TID
  plus one for non-QoS frames)
- `tid_seq`: per-TID sequence numbers for sending to this STA
- `airtime`: per-AC struct airtime_info describing airtime statistics for this
  station
- `airtime_weight`: station weight for airtime fairness calculation purposes
- `ampdu_mlme`: A-MPDU state machine state
- `debugfs_dir`: debug filesystem directory dentry
- `reserved_tid`: reserved TID (if any, otherwise IEEE80211_TID_UNRESERVED)
- `amsdu_mesh_control`: track the mesh A-MSDU format used by the peer:
- `tdls_chandef`: a TDLS peer can have a wider chandef that is compatible to
  the BSS one.
- `frags`: fragment cache
- `cur`: storage for aggregation data
  [`struct ieee80211_sta`](#c-struct-ieee80211_sta) points either here or to deflink.agg.
- `deflink`: This is the default link STA information, for non MLO STA all link
  specific STA information is accessed through **deflink** or through
  link\[0\] which points to address of **deflink**. For MLO Link STA
  the first added link STA will point to deflink.
- `link`: reference to Link Sta entries. For Non MLO STA, except 1st link,
  i.e link\[0\] all links would be assigned to NULL by default and
  would access link information via **deflink** or link\[0\]. For MLO
  STA, first link STA being added will point its link pointer to
  **deflink** address and remaining would be allocated and the address
  would be assigned to link\[link_id\] where link_id is the id assigned
  by the AP.
- `rem_link_stats`: accumulated removed link stats
- `sta`: station information we share with the driver

**Description**

This structure collects information about a station that
mac80211 is communicating with.

* -1: not yet known
* 0: non-mesh A-MSDU length field
* 1: big-endian mesh A-MSDU length field
* 2: little-endian mesh A-MSDU length field


<a id="rst-sta-information-lifetime-rules"></a>

### STA information lifetime rules


STA info structures ([`struct sta_info`](#c-struct-sta_info)) are managed in a hash table
for faster lookup and a list for iteration. They are managed using
RCU, i.e. access to the list and hash table is protected by RCU.

Upon allocating a STA info structure with `sta_info_alloc()`, the caller
owns that structure. It must then insert it into the hash table using
either `sta_info_insert()` or `sta_info_insert_rcu()`; only in the latter
case (which acquires an rcu read section but must not be called from
within one) will the pointer still be valid after the call. Note that
the caller may not do much with the STA info before inserting it; in
particular, it may not start any mesh peer link management or add
encryption keys.

When the insertion fails (`sta_info_insert()`) returns non-zero), the
structure will have been freed by `sta_info_insert()`!

Station entries are added by mac80211 when you establish a link with a
peer. This means different things for the different type of interfaces
we support. For a regular station this mean we add the AP sta when we
receive an association response from the AP. For IBSS this occurs when
get to know about a peer on the same IBSS. For WDS we add the sta for
the peer immediately upon device open. When using AP mode we add stations
for each respective station upon request from userspace through nl80211.

In order to remove a STA info structure, various sta_info_destroy_*()
calls are available.

There is no concept of ownership on a STA entry; each structure is
owned by the global hash table/list until it is removed. All users of
the structure need to be RCU protected so that the structure won't be
freed before they are done using it.


<a id="rst-aggregation-functions"></a>

## Aggregation Functions


#### <a id="c-struct-tid_ampdu_tx"></a>`struct tid_ampdu_tx`

TID aggregation information (Tx).

**Definition**

```c
struct tid_ampdu_tx {
    struct rcu_head rcu_head;
    struct timer_list session_timer;
    struct timer_list addba_resp_timer;
    struct sk_buff_head pending;
    struct sta_info *sta;
    unsigned long state;
    unsigned long last_tx;
    u16 timeout;
    u8 dialog_token;
    u8 stop_initiator;
    bool tx_stop;
    u16 buf_size;
    u16 ssn;
    u16 failed_bar_ssn;
    bool bar_pending;
    bool amsdu;
    u8 tid;
};
```

**Members**

- `rcu_head`: rcu head for freeing structure
- `session_timer`: check if we keep Tx-ing on the TID (by timeout value)
- `addba_resp_timer`: timer for peer's response to addba request
- `pending`: pending frames queue -- use sta's spinlock to protect
- `sta`: station we are attached to
- `state`: session state (see above)
- `last_tx`: jiffies of last tx activity
- `timeout`: session timeout value to be filled in ADDBA requests
- `dialog_token`: dialog token for aggregation session
- `stop_initiator`: initiator of a session stop
- `tx_stop`: TX DelBA frame when stopping
- `buf_size`: reorder buffer size at receiver
- `ssn`: starting sequence number of the session
- `failed_bar_ssn`: ssn of the last failed BAR tx attempt
- `bar_pending`: BAR needs to be re-sent
- `amsdu`: support A-MSDU within A-MDPU
- `tid`: TID number

**Description**

This structure's lifetime is managed by RCU, assignments to
the array holding it must hold the aggregation mutex.

The TX path can access it under RCU lock-free if, and
only if, the state has the flag `HT_AGG_STATE_OPERATIONAL`
set. Otherwise, the TX path must also acquire the spinlock
and re-check the state, see comments in the tx code
touching it.

#### <a id="c-struct-tid_ampdu_rx"></a>`struct tid_ampdu_rx`

TID aggregation information (Rx).

**Definition**

```c
struct tid_ampdu_rx {
    struct rcu_head rcu_head;
    spinlock_t reorder_lock;
    u64 reorder_buf_filtered;
    struct sk_buff_head *reorder_buf;
    unsigned long *reorder_time;
    struct sta_info *sta;
    struct timer_list session_timer;
    struct timer_list reorder_timer;
    unsigned long last_rx;
    u16 head_seq_num;
    u16 stored_mpdu_num;
    u16 ssn;
    u16 buf_size;
    u16 timeout;
    u8 tid;
    u8 auto_seq:1, removed:1, started:1;
};
```

**Members**

- `rcu_head`: RCU head used for freeing this struct
- `reorder_lock`: serializes access to reorder buffer, see below.
- `reorder_buf_filtered`: bitmap indicating where there are filtered frames in
  the reorder buffer that should be ignored when releasing frames
- `reorder_buf`: buffer to reorder incoming aggregated MPDUs. An MPDU may be an
  A-MSDU with individually reported subframes.
- `reorder_time`: jiffies when skb was added
- `sta`: station we are attached to
- `session_timer`: check if peer keeps Tx-ing on the TID (by timeout value)
- `reorder_timer`: releases expired frames from the reorder buffer.
- `last_rx`: jiffies of last rx activity
- `head_seq_num`: head sequence number in reordering buffer.
- `stored_mpdu_num`: number of MPDUs in reordering buffer
- `ssn`: Starting Sequence Number expected to be aggregated.
- `buf_size`: buffer size for incoming A-MPDUs
- `timeout`: reset timer value (in TUs).
- `tid`: TID number
- `auto_seq`: used for offloaded BA sessions to automatically pick head_seq_and
  and ssn.
- `removed`: this session is removed (but might have been found due to RCU)
- `started`: this session has started (head ssn or higher was received)

**Description**

This structure's lifetime is managed by RCU, assignments to
the array holding it must hold the aggregation mutex.

The **reorder_lock** is used to protect the members of this
struct, except for **timeout**, **buf_size** and **dialog_token**,
which are constant across the lifetime of the struct (the
dialog token being used only for debugging).

#### <a id="c-struct-sta_ampdu_mlme"></a>`struct sta_ampdu_mlme`

STA aggregation information.

**Definition**

```c
struct sta_ampdu_mlme {
    struct tid_ampdu_rx  *tid_rx[IEEE80211_NUM_TIDS];
    u8 tid_rx_token[IEEE80211_NUM_TIDS];
    unsigned long tid_rx_timer_expired[BITS_TO_LONGS(IEEE80211_NUM_TIDS)];
    unsigned long tid_rx_stop_requested[BITS_TO_LONGS(IEEE80211_NUM_TIDS)];
    unsigned long tid_rx_manage_offl[BITS_TO_LONGS(2 * IEEE80211_NUM_TIDS)];
    unsigned long agg_session_valid[BITS_TO_LONGS(IEEE80211_NUM_TIDS)];
    unsigned long unexpected_agg[BITS_TO_LONGS(IEEE80211_NUM_TIDS)];
    struct wiphy_work work;
    struct tid_ampdu_tx  *tid_tx[IEEE80211_NUM_TIDS];
    struct tid_ampdu_tx *tid_start_tx[IEEE80211_NUM_TIDS];
    unsigned long last_addba_req_time[IEEE80211_NUM_TIDS];
    u8 addba_req_num[IEEE80211_NUM_TIDS];
    u8 dialog_token_allocator;
};
```

**Members**

- `tid_rx`: aggregation info for Rx per TID -- RCU protected
- `tid_rx_token`: dialog tokens for valid aggregation sessions
- `tid_rx_timer_expired`: bitmap indicating on which TIDs the
  RX timer expired until the work for it runs
- `tid_rx_stop_requested`: bitmap indicating which BA sessions per TID the
  driver requested to close until the work for it runs
- `tid_rx_manage_offl`: bitmap indicating which BA sessions were requested
  to be treated as started/stopped due to offloading
- `agg_session_valid`: bitmap indicating which TID has a rx BA session open on
- `unexpected_agg`: bitmap indicating which TID already sent a delBA due to
  unexpected aggregation related frames outside a session
- `work`: work struct for starting/stopping aggregation
- `tid_tx`: aggregation info for Tx per TID
- `tid_start_tx`: sessions where start was requested, not just protected
  by wiphy mutex but also sta->lock
- `last_addba_req_time`: timestamp of the last addBA request.
- `addba_req_num`: number of times addBA request has been sent.
- `dialog_token_allocator`: dialog token enumerator for each new session;


<a id="rst-synchronisation-functions"></a>

## Synchronisation Functions

TBD

Locking, lots of RCU

---

# mac80211 subsystem (basics)

_Peios Kernel / Hardware and drivers / Driver development / Wireless LAN (802.11)_

> You should read and understand the information contained within this part of the book while implementing a mac80211 driver. In some chapters, advanced usage is noted, those may be skipped if this isn't needed.

<a id="rst-mac80211-subsystem-basics"></a>

You should read and understand the information contained within this part of the book while implementing a mac80211 driver. In some chapters, advanced usage is noted, those may be skipped if this isn't needed.

This part of the book only covers station and monitor mode functionality, additional information required to implement the other modes is covered in the second part of the book.

<a id="rst-basic-hardware-handling"></a>

## Basic hardware handling

TBD

This chapter shall contain information on getting a hw struct allocated and registered with mac80211.

Since it is required to allocate rates/modes before registering a hw struct, this chapter shall also contain information on setting up the rate/mode structs.

Additionally, some discussion about the callbacks and the general programming model should be in here, including the definition of ieee80211_ops which will be referred to a lot.

Finally, a discussion of hardware capabilities should be done with references to other parts of the book.


#### <a id="c-enum-ieee80211_hw_flags"></a>`enum ieee80211_hw_flags`

hardware flags

**Constants**

- `IEEE80211_HW_HAS_RATE_CONTROL`: The hardware or firmware includes rate control, and cannot be
  controlled by the stack. As such, no rate control algorithm
  should be instantiated, and the TX rate reported to userspace
  will be taken from the TX status instead of the rate control
  algorithm.
  Note that this requires that the driver implement a number of
  callbacks so it has the correct information, it needs to have
  the **set_rts_threshold** callback and must look at the BSS config
  **use_cts_prot** for G/N protection, **use_short_slot** for slot
  timing in 2.4 GHz and **use_short_preamble** for preambles for
  CCK frames.
- `IEEE80211_HW_RX_INCLUDES_FCS`: Indicates that received frames passed to the stack include
  the FCS at the end.
- `IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING`: Some wireless LAN chipsets buffer broadcast/multicast frames
  for power saving stations in the hardware/firmware and others
  rely on the host system for such buffering. This option is used
  to configure the IEEE 802.11 upper layer to buffer broadcast and
  multicast frames when there are power saving stations so that
  the driver can fetch them with [`ieee80211_get_buffered_bc()`](/kernel/hardware/driver-api/80211/mac80211-advanced.md#c-ieee80211_get_buffered_bc).
- `IEEE80211_HW_SIGNAL_UNSPEC`: Hardware can provide signal values but we don't know its units. We
  expect values between 0 and **max_signal**.
  If possible please provide dB or dBm instead.
- `IEEE80211_HW_SIGNAL_DBM`: Hardware gives signal values in dBm, decibel difference from
  one milliwatt. This is the preferred method since it is standardized
  between different devices. **max_signal** does not need to be set.
- `IEEE80211_HW_NEED_DTIM_BEFORE_ASSOC`: This device needs to get data from beacon before association (i.e.
  dtim_period).
- `IEEE80211_HW_SPECTRUM_MGMT`: Hardware supports spectrum management defined in 802.11h
  Measurement, Channel Switch, Quieting, TPC
- `IEEE80211_HW_AMPDU_AGGREGATION`: Hardware supports 11n A-MPDU aggregation.
- `IEEE80211_HW_SUPPORTS_PS`: Hardware has power save support (i.e. can go to sleep).
- `IEEE80211_HW_PS_NULLFUNC_STACK`: Hardware requires nullfunc frame handling in stack, implies
  stack support for dynamic PS.
- `IEEE80211_HW_SUPPORTS_DYNAMIC_PS`: Hardware has support for dynamic PS.
- `IEEE80211_HW_MFP_CAPABLE`: Hardware supports management frame protection (MFP, IEEE 802.11w).
- `IEEE80211_HW_WANT_MONITOR_VIF`: The driver would like to be informed of
  a virtual monitor interface when monitor interfaces are the only
  active interfaces.
- `IEEE80211_HW_NO_VIRTUAL_MONITOR`: The driver would like to be informed
  of any monitor interface, as well as their configured channel.
  This is useful for supporting multiple monitor interfaces on different
  channels.
- `IEEE80211_HW_NO_AUTO_VIF`: The driver would like for no wlanX to
  be created.  It is expected user-space will create vifs as
  desired (and thus have them named as desired).
- `IEEE80211_HW_SW_CRYPTO_CONTROL`: The driver wants to control which of the
  crypto algorithms can be done in software - so don't automatically
  try to fall back to it if hardware crypto fails, but do so only if
  the driver returns 1. This also forces the driver to advertise its
  supported cipher suites.
- `IEEE80211_HW_SUPPORT_FAST_XMIT`: The driver/hardware supports fast-xmit,
  this currently requires only the ability to calculate the duration
  for frames.
- `IEEE80211_HW_REPORTS_TX_ACK_STATUS`: Hardware can provide ack status reports of Tx frames to
  the stack.
- `IEEE80211_HW_CONNECTION_MONITOR`: The hardware performs its own connection monitoring, including
  periodic keep-alives to the AP and probing the AP on beacon loss.
- `IEEE80211_HW_QUEUE_CONTROL`: The driver wants to control per-interface
  queue mapping in order to use different queues (not just one per AC)
  for different virtual interfaces. See the doc section on HW queue
  control for more details.
- `IEEE80211_HW_SUPPORTS_PER_STA_GTK`: The device's crypto engine supports
  per-station GTKs as used by IBSS RSN or during fast transition. If
  the device doesn't support per-station GTKs, but can be asked not
  to decrypt group addressed frames, then IBSS RSN support is still
  possible but software crypto will be used. Advertise the wiphy flag
  only in that case.
- `IEEE80211_HW_AP_LINK_PS`: When operating in AP mode the device
  autonomously manages the PS status of connected stations. When
  this flag is set mac80211 will not trigger PS mode for connected
  stations based on the PM bit of incoming frames.
  Use `ieee80211_start_ps()`/`ieee8021_end_ps()` to manually configure
  the PS mode of connected stations.
- `IEEE80211_HW_TX_AMPDU_SETUP_IN_HW`: The device handles TX A-MPDU session
  setup strictly in HW. mac80211 should not attempt to do this in
  software.
- `IEEE80211_HW_SUPPORTS_RC_TABLE`: The driver supports using a rate
  selection table provided by the rate control algorithm.
- `IEEE80211_HW_P2P_DEV_ADDR_FOR_INTF`: Use the P2P Device address for any
  P2P Interface. This will be honoured even if more than one interface
  is supported.
- `IEEE80211_HW_TIMING_BEACON_ONLY`: Use sync timing from beacon frames
  only, to allow getting TBTT of a DTIM beacon.
- `IEEE80211_HW_SUPPORTS_HT_CCK_RATES`: Hardware supports mixing HT/CCK rates
  and can cope with CCK rates in an aggregation session (e.g. by not
  using aggregation for such frames.)
- `IEEE80211_HW_CHANCTX_STA_CSA`: Support 802.11h based channel-switch (CSA)
  for a single active channel while using channel contexts. When support
  is not enabled the default action is to disconnect when getting the
  CSA frame.
- `IEEE80211_HW_SUPPORTS_CLONED_SKBS`: The driver will never modify the payload
  or tailroom of TX skbs without copying them first.
- `IEEE80211_HW_SINGLE_SCAN_ON_ALL_BANDS`: The HW supports scanning on all bands
  in one command, mac80211 doesn't have to run separate scans per band.
- `IEEE80211_HW_TDLS_WIDER_BW`: The device/driver supports wider bandwidth
  than then BSS bandwidth for a TDLS link on the base channel.
- `IEEE80211_HW_SUPPORTS_AMSDU_IN_AMPDU`: The driver supports receiving A-MSDUs
  within A-MPDU.
- `IEEE80211_HW_BEACON_TX_STATUS`: The device/driver provides TX status
  for sent beacons.
- `IEEE80211_HW_NEEDS_UNIQUE_STA_ADDR`: Hardware (or driver) requires that each
  station has a unique address, i.e. each station entry can be identified
  by just its MAC address; this prevents, for example, the same station
  from connecting to two virtual AP interfaces at the same time.
- `IEEE80211_HW_SUPPORTS_REORDERING_BUFFER`: Hardware (or driver) manages the
  reordering buffer internally, guaranteeing mac80211 receives frames in
  order and does not need to manage its own reorder buffer or BA session
  timeout.
- `IEEE80211_HW_USES_RSS`: The device uses RSS and thus requires parallel RX,
  which implies using per-CPU station statistics.
- `IEEE80211_HW_TX_AMSDU`: Hardware (or driver) supports software aggregated
  A-MSDU frames. Requires software tx queueing and fast-xmit support.
  When not using minstrel/minstrel_ht rate control, the driver must
  limit the maximum A-MSDU size based on the current tx rate by setting
  max_rc_amsdu_len in struct ieee80211_sta.
- `IEEE80211_HW_TX_FRAG_LIST`: Hardware (or driver) supports sending frag_list
  skbs, needed for zero-copy software A-MSDU.
- `IEEE80211_HW_REPORTS_LOW_ACK`: The driver (or firmware) reports low ack event
  by `ieee80211_report_low_ack()` based on its own algorithm. For such
  drivers, mac80211 packet loss mechanism will not be triggered and driver
  is completely depending on firmware event for station kickout.
- `IEEE80211_HW_SUPPORTS_TX_FRAG`: Hardware does fragmentation by itself.
  The stack will not do fragmentation.
  The callback for **set_frag_threshold** should be set as well.
- `IEEE80211_HW_SUPPORTS_TDLS_BUFFER_STA`: Hardware supports buffer STA on
  TDLS links.
- `IEEE80211_HW_DOESNT_SUPPORT_QOS_NDP`: The driver (or firmware) doesn't
  support QoS NDP for AP probing - that's most likely a driver bug.
- `IEEE80211_HW_BUFF_MMPDU_TXQ`: use the TXQ for bufferable MMPDUs, this of
  course requires the driver to use TXQs to start with.
- `IEEE80211_HW_SUPPORTS_VHT_EXT_NSS_BW`: (Hardware) rate control supports VHT
  extended NSS BW (dot11VHTExtendedNSSBWCapable). This flag will be set if
  the selected rate control algorithm sets `RATE_CTRL_CAPA_VHT_EXT_NSS_BW`
  but if the rate control is built-in then it must be set by the driver.
  See also the documentation for that flag.
- `IEEE80211_HW_STA_MMPDU_TXQ`: use the extra non-TID per-station TXQ for all
  MMPDUs on station interfaces. This of course requires the driver to use
  TXQs to start with.
- `IEEE80211_HW_TX_STATUS_NO_AMPDU_LEN`: Driver does not report accurate A-MPDU
  length in tx status information
- `IEEE80211_HW_SUPPORTS_MULTI_BSSID`: Hardware supports multi BSSID
- `IEEE80211_HW_SUPPORTS_ONLY_HE_MULTI_BSSID`: Hardware supports multi BSSID
  only for HE APs. Applies if **IEEE80211_HW_SUPPORTS_MULTI_BSSID** is set.
- `IEEE80211_HW_AMPDU_KEYBORDER_SUPPORT`: The card and driver is only
  aggregating MPDUs with the same keyid, allowing mac80211 to keep Tx
  A-MPDU sessions active while rekeying with Extended Key ID.
- `IEEE80211_HW_SUPPORTS_TX_ENCAP_OFFLOAD`: Hardware supports tx encapsulation
  offload
- `IEEE80211_HW_SUPPORTS_RX_DECAP_OFFLOAD`: Hardware supports rx decapsulation
  offload
- `IEEE80211_HW_SUPPORTS_CONC_MON_RX_DECAP`: Hardware supports concurrent rx
  decapsulation offload and passing raw 802.11 frames for monitor iface.
  If this is supported, the driver must pass both 802.3 frames for real
  usage and 802.11 frames with `RX_FLAG_ONLY_MONITOR` set for monitor to
  the stack.
- `IEEE80211_HW_DETECTS_COLOR_COLLISION`: HW/driver has support for BSS color
  collision detection and doesn't need it in software.
- `IEEE80211_HW_MLO_MCAST_MULTI_LINK_TX`: Hardware/driver handles transmitting
  multicast frames on all links, mac80211 should not do that.
- `IEEE80211_HW_DISALLOW_PUNCTURING`: HW requires disabling puncturing in EHT
  and connecting with a lower bandwidth instead
- `IEEE80211_HW_HANDLES_QUIET_CSA`: HW/driver handles quieting for CSA, so
  no need to stop queues. This really should be set by a driver that
  implements MLO, so operation can continue on other links when one
  link is switching.
- `IEEE80211_HW_STRICT`: strictly enforce certain things mandated by the spec
  but otherwise ignored/worked around for interoperability. This is a
  HW flag so drivers can opt in according to their own control, e.g. in
  testing.
- `NUM_IEEE80211_HW_FLAGS`: number of hardware flags, used for sizing arrays

**Description**

These flags are used to indicate hardware capabilities to
the stack. Generally, flags here should have their meaning
done in a way that the simplest hardware doesn't need setting
any particular flags. There are some exceptions to this rule,
however, so you are advised to review these flags carefully.

#### <a id="c-struct-ieee80211_hw"></a>`struct ieee80211_hw`

hardware information and state

**Definition**

```c
struct ieee80211_hw {
    struct ieee80211_conf conf;
    struct wiphy *wiphy;
    const char *rate_control_algorithm;
    void *priv;
    unsigned long flags[BITS_TO_LONGS(NUM_IEEE80211_HW_FLAGS)];
    unsigned int extra_tx_headroom;
    unsigned int extra_beacon_tailroom;
    int vif_data_size;
    int sta_data_size;
    int chanctx_data_size;
    int txq_data_size;
    u16 queues;
    u16 max_listen_interval;
    s8 max_signal;
    u8 max_rates;
    u8 max_report_rates;
    u8 max_rate_tries;
    u16 max_rx_aggregation_subframes;
    u16 max_tx_aggregation_subframes;
    u8 max_tx_fragments;
    u8 offchannel_tx_hw_queue;
    u8 radiotap_mcs_details;
    u16 radiotap_vht_details;
    struct {
        int units_pos;
        s16 accuracy;
    } radiotap_timestamp;
    netdev_features_t netdev_features;
    u8 uapsd_queues;
    u8 uapsd_max_sp_len;
    u8 max_nan_de_entries;
    u8 tx_sk_pacing_shift;
    u8 weight_multiplier;
    u32 max_mtu;
    const s8 *tx_power_levels;
    u8 max_txpwr_levels_idx;
};
```

**Members**

- `conf`: [`struct ieee80211_conf`](#c-struct-ieee80211_conf), device configuration, don't use.
- `wiphy`: This points to the [`struct wiphy`](/kernel/hardware/driver-api/80211/cfg80211.md#c-struct-wiphy) allocated for this
  802.11 PHY. You must fill in the **perm_addr** and **dev**
  members of this structure using [`SET_IEEE80211_DEV()`](#c-SET_IEEE80211_DEV)
  and [`SET_IEEE80211_PERM_ADDR()`](#c-SET_IEEE80211_PERM_ADDR). Additionally, all supported
  bands (with channels, bitrates) are registered here.
- `rate_control_algorithm`: rate control algorithm for this hardware.
  If unset (NULL), the default algorithm will be used. Must be
  set before calling [`ieee80211_register_hw()`](#c-ieee80211_register_hw).
- `priv`: pointer to private area that was allocated for driver use
  along with this structure.
- `flags`: hardware flags, see [`enum ieee80211_hw_flags`](#c-enum-ieee80211_hw_flags).
- `extra_tx_headroom`: headroom to reserve in each transmit skb
  for use by the driver (e.g. for transmit headers.)
- `extra_beacon_tailroom`: tailroom to reserve in each beacon tx skb.
  Can be used by drivers to add extra IEs.
- `vif_data_size`: size (in bytes) of the drv_priv data area
  within [`struct ieee80211_vif`](#c-struct-ieee80211_vif).
- `sta_data_size`: size (in bytes) of the drv_priv data area
  within [`struct ieee80211_sta`](/kernel/hardware/driver-api/80211/mac80211-advanced.md#c-struct-ieee80211_sta).
- `chanctx_data_size`: size (in bytes) of the drv_priv data area
  within `struct ieee80211_chanctx_conf`.
- `txq_data_size`: size (in bytes) of the drv_priv data area
  within **struct** ieee80211_txq.
- `queues`: number of available hardware transmit queues for
  data packets. WMM/QoS requires at least four, these
  queues need to have configurable access parameters.
- `max_listen_interval`: max listen interval in units of beacon interval
  that HW supports
- `max_signal`: Maximum value for signal (rssi) in RX information, used
  only when **IEEE80211_HW_SIGNAL_UNSPEC** or **IEEE80211_HW_SIGNAL_DB**
- `max_rates`: maximum number of alternate rate retry stages the hw
  can handle.
- `max_report_rates`: maximum number of alternate rate retry stages
  the hw can report back.
- `max_rate_tries`: maximum number of tries for each stage
- `max_rx_aggregation_subframes`: maximum buffer size (number of
  sub-frames) to be used for A-MPDU block ack receiver
  aggregation.
  This is only relevant if the device has restrictions on the
  number of subframes, if it relies on mac80211 to do reordering
  it shouldn't be set.
- `max_tx_aggregation_subframes`: maximum number of subframes in an
  aggregate an HT/HE device will transmit. In HT AddBA we'll
  advertise a constant value of 64 as some older APs crash if
  the window size is smaller (an example is LinkSys WRT120N
  with FW v1.0.07 build 002 Jun 18 2012).
  For AddBA to HE capable peers this value will be used.
- `max_tx_fragments`: maximum number of tx buffers per (A)-MSDU, sum
  of 1 + skb_shinfo(skb)->nr_frags for each skb in the frag_list.
- `offchannel_tx_hw_queue`: HW queue ID to use for offchannel TX
  (if `IEEE80211_HW_QUEUE_CONTROL` is set)
- `radiotap_mcs_details`: lists which MCS information can the HW
  reports, by default it is set to _MCS, _GI and _BW but doesn't
  include _FMT. Use `IEEE80211_RADIOTAP_MCS_HAVE_`\* values, only
  adding _BW is supported today.
- `radiotap_vht_details`: lists which VHT MCS information the HW reports,
  the default is _GI | _BANDWIDTH.
  Use the `IEEE80211_RADIOTAP_VHT_KNOWN_`\* values.
- `radiotap_timestamp`: Information for the radiotap timestamp field; if the
  **units_pos** member is set to a non-negative value then the timestamp
  field will be added and populated from the [`struct ieee80211_rx_status`](#c-struct-ieee80211_rx_status)
  device_timestamp.
- `radiotap_timestamp.units_pos`: Must be set to a combination of a
  IEEE80211_RADIOTAP_TIMESTAMP_UNIT_* and a
  IEEE80211_RADIOTAP_TIMESTAMP_SPOS_* value.
- `radiotap_timestamp.accuracy`: If non-negative, fills the accuracy in the
  radiotap field and the accuracy known flag will be set.
- `netdev_features`: netdev features to be set in each netdev created
  from this HW. Note that not all features are usable with mac80211,
  other features will be rejected during HW registration.
- `uapsd_queues`: This bitmap is included in (re)association frame to indicate
  for each access category if it is uAPSD trigger-enabled and delivery-
  enabled. Use IEEE80211_WMM_IE_STA_QOSINFO_AC_* to set this bitmap.
  Each bit corresponds to different AC. Value '1' in specific bit means
  that corresponding AC is both trigger- and delivery-enabled. '0' means
  neither enabled.
- `uapsd_max_sp_len`: maximum number of total buffered frames the WMM AP may
  deliver to a WMM STA during any Service Period triggered by the WMM STA.
  Use IEEE80211_WMM_IE_STA_QOSINFO_SP_* for correct values.
- `max_nan_de_entries`: maximum number of NAN DE functions supported by the
  device.
- `tx_sk_pacing_shift`: Pacing shift to set on TCP sockets when frames from
  them are encountered. The default should typically not be changed,
  unless the driver has good reasons for needing more buffers.
- `weight_multiplier`: Driver specific airtime weight multiplier used while
  refilling deficit of each TXQ.
- `max_mtu`: the max mtu could be set.
- `tx_power_levels`: a list of power levels supported by the wifi hardware.
  The power levels can be specified either as integer or fractions.
  The power level at idx 0 shall be the maximum positive power level.
- `max_txpwr_levels_idx`: the maximum valid idx of 'tx_power_levels' list.

**Description**

This structure contains the configuration and hardware
information for an 802.11 PHY.

#### <a id="c-SET_IEEE80211_DEV"></a>`SET_IEEE80211_DEV()`

```c
void SET_IEEE80211_DEV(struct ieee80211_hw *hw, struct device *dev)
```

set device for 802.11 hardware

**Parameters**

- `struct ieee80211_hw *hw`: the [`struct ieee80211_hw`](#c-struct-ieee80211_hw) to set the device for
- `struct device *dev`: the [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) of this 802.11 device

#### <a id="c-SET_IEEE80211_PERM_ADDR"></a>`SET_IEEE80211_PERM_ADDR()`

```c
void SET_IEEE80211_PERM_ADDR(struct ieee80211_hw *hw, const u8 *addr)
```

set the permanent MAC address for 802.11 hardware

**Parameters**

- `struct ieee80211_hw *hw`: the [`struct ieee80211_hw`](#c-struct-ieee80211_hw) to set the MAC address for
- `const u8 *addr`: the address to set

#### <a id="c-struct-ieee80211_ops"></a>`struct ieee80211_ops`

callbacks from mac80211 to the driver

**Definition**

```c
struct ieee80211_ops {
        void (*tx)(struct ieee80211_hw *hw, struct ieee80211_tx_control *control, struct sk_buff *skb);
        int (*start)(struct ieee80211_hw *hw);
        void (*stop)(struct ieee80211_hw *hw, bool suspend);
    #ifdef CONFIG_PM;
        int (*suspend)(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan);
        int (*resume)(struct ieee80211_hw *hw);
        void (*set_wakeup)(struct ieee80211_hw *hw, bool enabled);
    #endif;
        int (*add_interface)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        int (*change_interface)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum nl80211_iftype new_type, bool p2p);
        void (*remove_interface)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        int (*config)(struct ieee80211_hw *hw, int radio_idx, u32 changed);
        void (*bss_info_changed)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *info, u64 changed);
        void (*vif_cfg_changed)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u64 changed);
        void (*link_info_changed)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *info, u64 changed);
        int (*start_ap)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *link_conf);
        void (*stop_ap)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *link_conf);
        u64 (*prepare_multicast)(struct ieee80211_hw *hw, struct netdev_hw_addr_list *mc_list);
        void (*configure_filter)(struct ieee80211_hw *hw, unsigned int changed_flags, unsigned int *total_flags, u64 multicast);
        void (*config_iface_filter)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, unsigned int filter_flags, unsigned int changed_flags);
        int (*set_tim)(struct ieee80211_hw *hw, struct ieee80211_sta *sta, bool set);
        int (*set_key)(struct ieee80211_hw *hw, enum set_key_cmd cmd, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key);
        void (*update_tkip_key)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_key_conf *conf, struct ieee80211_sta *sta, u32 iv32, u16 *phase1key);
        void (*set_rekey_data)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_gtk_rekey_data *data);
        void (*set_default_unicast_key)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, int idx);
        int (*hw_scan)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_scan_request *req);
        void (*cancel_hw_scan)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        int (*sched_scan_start)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_sched_scan_request *req, struct ieee80211_scan_ies *ies);
        int (*sched_scan_stop)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        void (*sw_scan_start)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const u8 *mac_addr);
        void (*sw_scan_complete)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        int (*get_stats)(struct ieee80211_hw *hw, struct ieee80211_low_level_stats *stats);
        void (*get_key_seq)(struct ieee80211_hw *hw, struct ieee80211_key_conf *key, struct ieee80211_key_seq *seq);
        int (*set_frag_threshold)(struct ieee80211_hw *hw, int radio_idx, u32 value);
        int (*set_rts_threshold)(struct ieee80211_hw *hw, int radio_idx, u32 value);
        int (*sta_add)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta);
        int (*sta_remove)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta);
    #ifdef CONFIG_MAC80211_DEBUGFS;
        void (*vif_add_debugfs)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        void (*link_add_debugfs)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *link_conf, struct dentry *dir);
        void (*sta_add_debugfs)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct dentry *dir);
        void (*link_sta_add_debugfs)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_link_sta *link_sta, struct dentry *dir);
    #endif;
        void (*sta_notify)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum sta_notify_cmd, struct ieee80211_sta *sta);
        int (*sta_set_txpwr)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta);
        int (*sta_state)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, enum ieee80211_sta_state old_state, enum ieee80211_sta_state new_state);
        void (*sta_pre_rcu_remove)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta);
        void (*link_sta_rc_update)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_link_sta *link_sta, u32 changed);
        void (*sta_rate_tbl_update)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta);
        void (*sta_statistics)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct station_info *sinfo);
        int (*conf_tx)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, unsigned int link_id, u16 ac, const struct ieee80211_tx_queue_params *params);
        u64 (*get_tsf)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        void (*set_tsf)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u64 tsf);
        void (*offset_tsf)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, s64 offset);
        void (*reset_tsf)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        int (*tx_last_beacon)(struct ieee80211_hw *hw);
        void (*link_sta_statistics)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_link_sta *link_sta, struct link_station_info *link_sinfo);
        int (*ampdu_action)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_ampdu_params *params);
        int (*get_survey)(struct ieee80211_hw *hw, int idx, struct survey_info *survey);
        void (*rfkill_poll)(struct ieee80211_hw *hw);
        void (*set_coverage_class)(struct ieee80211_hw *hw, int radio_idx, s16 coverage_class);
    #ifdef CONFIG_NL80211_TESTMODE;
        int (*testmode_cmd)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, void *data, int len);
        int (*testmode_dump)(struct ieee80211_hw *hw, struct sk_buff *skb, struct netlink_callback *cb, void *data, int len);
    #endif;
        void (*flush)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u32 queues, bool drop);
        void (*flush_sta)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta);
        void (*channel_switch)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_channel_switch *ch_switch);
        int (*set_antenna)(struct ieee80211_hw *hw, int radio_idx, u32 tx_ant, u32 rx_ant);
        int (*get_antenna)(struct ieee80211_hw *hw, int radio_idx, u32 *tx_ant, u32 *rx_ant);
        int (*remain_on_channel)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_channel *chan, int duration, enum ieee80211_roc_type type);
        int (*cancel_remain_on_channel)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        int (*set_ringparam)(struct ieee80211_hw *hw, u32 tx, u32 rx);
        void (*get_ringparam)(struct ieee80211_hw *hw, u32 *tx, u32 *tx_max, u32 *rx, u32 *rx_max);
        bool (*tx_frames_pending)(struct ieee80211_hw *hw);
        int (*set_bitrate_mask)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const struct cfg80211_bitrate_mask *mask);
        void (*event_callback)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const struct ieee80211_event *event);
        void (*allow_buffered_frames)(struct ieee80211_hw *hw, struct ieee80211_sta *sta, u16 tids, int num_frames, enum ieee80211_frame_release_type reason, bool more_data);
        void (*release_buffered_frames)(struct ieee80211_hw *hw, struct ieee80211_sta *sta, u16 tids, int num_frames, enum ieee80211_frame_release_type reason, bool more_data);
        int (*get_et_sset_count)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, int sset);
        void (*get_et_stats)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ethtool_stats *stats, u64 *data);
        void (*get_et_strings)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u32 sset, u8 *data);
        void (*mgd_prepare_tx)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_prep_tx_info *info);
        void (*mgd_complete_tx)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_prep_tx_info *info);
        void (*mgd_protect_tdls_discover)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, unsigned int link_id);
        int (*add_chanctx)(struct ieee80211_hw *hw, struct ieee80211_chanctx_conf *ctx);
        void (*remove_chanctx)(struct ieee80211_hw *hw, struct ieee80211_chanctx_conf *ctx);
        void (*change_chanctx)(struct ieee80211_hw *hw, struct ieee80211_chanctx_conf *ctx, u32 changed);
        int (*assign_vif_chanctx)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *link_conf, struct ieee80211_chanctx_conf *ctx);
        void (*unassign_vif_chanctx)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *link_conf, struct ieee80211_chanctx_conf *ctx);
        int (*switch_vif_chanctx)(struct ieee80211_hw *hw, struct ieee80211_vif_chanctx_switch *vifs, int n_vifs, enum ieee80211_chanctx_switch_mode mode);
        void (*reconfig_complete)(struct ieee80211_hw *hw, enum ieee80211_reconfig_type reconfig_type);
    #if IS_ENABLED(CONFIG_IPV6);
        void (*ipv6_addr_change)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct inet6_dev *idev);
    #endif;
        void (*channel_switch_beacon)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_chan_def *chandef);
        int (*pre_channel_switch)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_channel_switch *ch_switch);
        int (*post_channel_switch)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *link_conf);
        void (*abort_channel_switch)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *link_conf);
        void (*channel_switch_rx_beacon)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_channel_switch *ch_switch);
        int (*join_ibss)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        void (*leave_ibss)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        u32 (*get_expected_throughput)(struct ieee80211_hw *hw, struct ieee80211_sta *sta);
        int (*get_txpower)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, unsigned int link_id, int *dbm);
        int (*tdls_channel_switch)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, u8 oper_class, struct cfg80211_chan_def *chandef, struct sk_buff *tmpl_skb, u32 ch_sw_tm_ie);
        void (*tdls_cancel_channel_switch)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta);
        void (*tdls_recv_channel_switch)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_tdls_ch_sw_params *params);
        void (*wake_tx_queue)(struct ieee80211_hw *hw, struct ieee80211_txq *txq);
        void (*sync_rx_queues)(struct ieee80211_hw *hw);
        int (*start_nan)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_nan_conf *conf);
        int (*stop_nan)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        int (*nan_change_conf)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_nan_conf *conf, u32 changes);
        int (*add_nan_func)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const struct cfg80211_nan_func *nan_func);
        void (*del_nan_func)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u8 instance_id);
        bool (*can_aggregate_in_amsdu)(struct ieee80211_hw *hw, struct sk_buff *head, struct sk_buff *skb);
        int (*get_ftm_responder_stats)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_ftm_responder_stats *ftm_stats);
        int (*start_pmsr)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_pmsr_request *request);
        void (*abort_pmsr)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_pmsr_request *request);
        int (*set_tid_config)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct cfg80211_tid_config *tid_conf);
        int (*reset_tid_config)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, u8 tids);
        void (*update_vif_offload)(struct ieee80211_hw *hw, struct ieee80211_vif *vif);
        void (*sta_set_4addr)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, bool enabled);
        int (*set_sar_specs)(struct ieee80211_hw *hw, const struct cfg80211_sar_specs *sar);
        void (*sta_set_decap_offload)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, bool enabled);
        void (*add_twt_setup)(struct ieee80211_hw *hw, struct ieee80211_sta *sta, struct ieee80211_twt_setup *twt);
        void (*twt_teardown_request)(struct ieee80211_hw *hw, struct ieee80211_sta *sta, u8 flowid);
        int (*set_radar_background)(struct ieee80211_hw *hw, struct cfg80211_chan_def *chandef);
        int (*net_fill_forward_path)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct net_device_path_ctx *ctx, struct net_device_path *path);
        bool (*can_activate_links)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u16 active_links);
        int (*change_vif_links)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u16 old_links, u16 new_links, struct ieee80211_bss_conf *old[IEEE80211_MLD_MAX_NUM_LINKS]);
        int (*change_sta_links)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, u16 old_links, u16 new_links);
        int (*set_hw_timestamp)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_set_hw_timestamp *hwts);
        int (*net_setup_tc)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct net_device *dev, enum tc_setup_type type, void *type_data);
        enum ieee80211_neg_ttlm_res (*can_neg_ttlm)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_neg_ttlm *ttlm);
        void (*prep_add_interface)(struct ieee80211_hw *hw, enum nl80211_iftype type);
        int (*set_eml_op_mode)(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_eml_params *eml_params);
};
```

**Members**

- `tx`: Handler that 802.11 module calls for each transmitted frame.
  skb contains the buffer starting from the IEEE 802.11 header.
  The low-level driver should send the frame out based on
  configuration in the TX control data. This handler should,
  preferably, never fail and stop queues appropriately.
  Must be atomic.
- `start`: Called before the first netdevice attached to the hardware
  is enabled. This should turn on the hardware and must turn on
  frame reception (for possibly enabled monitor interfaces.)
  Returns negative error codes, these may be seen in userspace,
  or zero.
  When the device is started it should not have a MAC address
  to avoid acknowledging frames before a non-monitor device
  is added.
  Must be implemented and can sleep.
- `stop`: Called after last netdevice attached to the hardware
  is disabled. This should turn off the hardware (at least
  it must turn off frame reception.)
  May be called right after add_interface if that rejects
  an interface. If you added any work onto the mac80211 workqueue
  you should ensure to cancel it on this callback.
  Must be implemented and can sleep.
- `suspend`: Suspend the device; mac80211 itself will quiesce before and
  stop transmitting and doing any other configuration, and then
  ask the device to suspend. This is only invoked when WoWLAN is
  configured, otherwise the device is deconfigured completely and
  reconfigured at resume time.
  The driver may also impose special conditions under which it
  wants to use the "normal" suspend (deconfigure), say if it only
  supports WoWLAN when the device is associated. In this case, it
  must return 1 from this function.
- `resume`: If WoWLAN was configured, this indicates that mac80211 is
  now resuming its operation, after this the device must be fully
  functional again. If this returns an error, the only way out is
  to also unregister the device. If it returns 1, then mac80211
  will also go through the regular complete restart on resume.
- `set_wakeup`: Enable or disable wakeup when WoWLAN configuration is
  modified. The reason is that `device_set_wakeup_enable()` is
  supposed to be called when the configuration changes, not only
  in `suspend()`.
- `add_interface`: Called when a netdevice attached to the hardware is
  enabled. Because it is not called for monitor mode devices, **start**
  and **stop** must be implemented.
  The driver should perform any initialization it needs before
  the device can be enabled. The initial configuration for the
  interface is given in the conf parameter.
  The callback may refuse to add an interface by returning a
  negative error code (which will be seen in userspace.)
  Must be implemented and can sleep.
- `change_interface`: Called when a netdevice changes type. This callback
  is optional, but only if it is supported can interface types be
  switched while the interface is UP. The callback may sleep.
  Note that while an interface is being switched, it will not be
  found by the interface iteration callbacks.
- `remove_interface`: Notifies a driver that an interface is going down.
  The **stop** callback is called after this if it is the last interface
  and no monitor interfaces are present.
  When all interfaces are removed, the MAC address in the hardware
  must be cleared so the device no longer acknowledges packets,
  the mac_addr member of the conf structure is, however, set to the
  MAC address of the device going away.
  Hence, this callback must be implemented. It can sleep.
- `config`: Handler for configuration requests. IEEE 802.11 code calls this
  function to change hardware configuration, e.g., channel.
  This function should never fail but returns a negative error code
  if it does. The callback can sleep.
- `bss_info_changed`: Handler for configuration requests related to BSS
  parameters that may vary during BSS's lifespan, and may affect low
  level driver (e.g. assoc/disassoc status, erp parameters).
  This function should not be used if no BSS has been set, unless
  for association indication. The **changed** parameter indicates which
  of the bss parameters has changed when a call is made. The callback
  can sleep.
- `vif_cfg_changed`: Handler for configuration requests related to interface
  (MLD) parameters from `struct ieee80211_vif_cfg` that vary during the
  lifetime of the interface (e.g. assoc status, IP addresses, etc.)
  The **changed** parameter indicates which value changed.
  The callback can sleep.
- `link_info_changed`: Handler for configuration requests related to link
  parameters from `struct ieee80211_bss_conf` that are related to an
  individual link. e.g. legacy/HT/VHT/... rate information.
  The **changed** parameter indicates which value changed, and the **link_id**
  parameter indicates the link ID. Note that the **link_id** will be 0 for
  non-MLO connections.
  The callback can sleep.
- `start_ap`: Start operation on the AP interface, this is called after all the
  information in bss_conf is set and beacon can be retrieved. A channel
  context is bound before this is called. Note that if the driver uses
  software scan or ROC, this (and **stop_ap**) isn't called when the AP is
  just "paused" for scanning/ROC, which is indicated by the beacon being
  disabled/enabled via **bss_info_changed**.
- `stop_ap`: Stop operation on the AP interface.
- `prepare_multicast`: Prepare for multicast filter configuration.
  This callback is optional, and its return value is passed
  to `configure_filter()`. This callback must be atomic.
- `configure_filter`: Configure the device's RX filter.
  See the section "Frame filtering" for more information.
  This callback must be implemented and can sleep.
- `config_iface_filter`: Configure the interface's RX filter.
  This callback is optional and is used to configure which frames
  should be passed to mac80211. The filter_flags is the combination
  of FIF_* flags. The changed_flags is a bit mask that indicates
  which flags are changed.
  This callback can sleep.
- `set_tim`: Set TIM bit. mac80211 calls this function when a TIM bit
  must be set or cleared for a given STA. Must be atomic.
- `set_key`: See the section "Hardware crypto acceleration"
  This callback is only called between add_interface and
  remove_interface calls, i.e. while the given virtual interface
  is enabled.
  Returns a negative error code if the key can't be added.
  The callback can sleep.
- `update_tkip_key`: See the section "Hardware crypto acceleration"
  This callback will be called in the context of Rx. Called for drivers
  which set IEEE80211_KEY_FLAG_TKIP_REQ_RX_P1_KEY.
  The callback must be atomic.
- `set_rekey_data`: If the device supports GTK rekeying, for example while the
  host is suspended, it can assign this callback to retrieve the data
  necessary to do GTK rekeying, this is the KEK, KCK and replay counter.
  After rekeying was done it should (for example during resume) notify
  userspace of the new replay counter using `ieee80211_gtk_rekey_notify()`.
- `set_default_unicast_key`: Set the default (unicast) key index, useful for
  WEP when the device sends data packets autonomously, e.g. for ARP
  offloading. The index can be 0-3, or -1 for unsetting it.
- `hw_scan`: Ask the hardware to service the scan request, no need to start
  the scan state machine in stack. The scan must honour the channel
  configuration done by the regulatory agent in the wiphy's
  registered bands. The hardware (or the driver) needs to make sure
  that power save is disabled.
  The **req** ie/ie_len members are rewritten by mac80211 to contain the
  entire IEs after the SSID, so that drivers need not look at these
  at all but just send them after the SSID -- mac80211 includes the
  (extended) supported rates and HT information (where applicable).
  When the scan finishes, [`ieee80211_scan_completed()`](/kernel/hardware/driver-api/80211/mac80211-advanced.md#c-ieee80211_scan_completed) must be called;
  note that it also must be called when the scan cannot finish due to
  any error unless this callback returned a negative error code.
  This callback is also allowed to return the special return value 1,
  this indicates that hardware scan isn't desirable right now and a
  software scan should be done instead. A driver wishing to use this
  capability must ensure its (hardware) scan capabilities aren't
  advertised as more capable than mac80211's software scan is.
  The callback can sleep.
- `cancel_hw_scan`: Ask the low-level tp cancel the active hw scan.
  The driver should ask the hardware to cancel the scan (if possible),
  but the scan will be completed only after the driver will call
  [`ieee80211_scan_completed()`](/kernel/hardware/driver-api/80211/mac80211-advanced.md#c-ieee80211_scan_completed).
  This callback is needed for wowlan, to prevent enqueueing a new
  scan_work after the low-level driver was already suspended.
  The callback can sleep.
- `sched_scan_start`: Ask the hardware to start scanning repeatedly at
  specific intervals.  The driver must call the
  `ieee80211_sched_scan_results()` function whenever it finds results.
  This process will continue until sched_scan_stop is called.
- `sched_scan_stop`: Tell the hardware to stop an ongoing scheduled scan.
  In this case, `ieee80211_sched_scan_stopped()` must not be called.
- `sw_scan_start`: Notifier function that is called just before a software scan
  is started. Can be NULL, if the driver doesn't need this notification.
  The mac_addr parameter allows supporting NL80211_SCAN_FLAG_RANDOM_ADDR,
  the driver may set the NL80211_FEATURE_SCAN_RANDOM_MAC_ADDR flag if it
  can use this parameter. The callback can sleep.
- `sw_scan_complete`: Notifier function that is called just after a
  software scan finished. Can be NULL, if the driver doesn't need
  this notification.
  The callback can sleep.
- `get_stats`: Return low-level statistics.
  Returns zero if statistics are available.
  The callback can sleep.
- `get_key_seq`: If your device implements encryption in hardware and does
  IV/PN assignment then this callback should be provided to read the
  IV/PN for the given key from hardware.
  The callback must be atomic.
- `set_frag_threshold`: Configuration of fragmentation threshold. Assign this
  if the device does fragmentation by itself. Note that to prevent the
  stack from doing fragmentation IEEE80211_HW_SUPPORTS_TX_FRAG
  should be set as well.
  The callback can sleep.
- `set_rts_threshold`: Configuration of RTS threshold (if device needs it)
  The callback can sleep.
- `sta_add`: Notifies low level driver about addition of an associated station,
  AP, IBSS/WDS/mesh peer etc. This callback can sleep.
- `sta_remove`: Notifies low level driver about removal of an associated
  station, AP, IBSS/WDS/mesh peer etc. Note that after the callback
  returns it isn't safe to use the pointer, not even RCU protected;
  no RCU grace period is guaranteed between returning here and freeing
  the station. See **sta_pre_rcu_remove** if needed.
  This callback can sleep.
- `vif_add_debugfs`: Drivers can use this callback to add a debugfs vif
  directory with its files. This callback should be within a
  CONFIG_MAC80211_DEBUGFS conditional. This callback can sleep.
- `link_add_debugfs`: Drivers can use this callback to add debugfs files
  when a link is added to a mac80211 vif. This callback should be within
  a CONFIG_MAC80211_DEBUGFS conditional. This callback can sleep.
  For non-MLO the callback will be called once for the default bss_conf
  with the vif's directory rather than a separate subdirectory.
- `sta_add_debugfs`: Drivers can use this callback to add debugfs files
  when a station is added to mac80211's station list. This callback
  should be within a CONFIG_MAC80211_DEBUGFS conditional. This
  callback can sleep.
- `link_sta_add_debugfs`: Drivers can use this callback to add debugfs files
  when a link is added to a mac80211 station. This callback
  should be within a CONFIG_MAC80211_DEBUGFS conditional. This
  callback can sleep.
  For non-MLO the callback will be called once for the deflink with the
  station's directory rather than a separate subdirectory.
- `sta_notify`: Notifies low level driver about power state transition of an
  associated station, AP,  IBSS/WDS/mesh peer etc. For a VIF operating
  in AP mode, this callback will not be called when the flag
  `IEEE80211_HW_AP_LINK_PS` is set. Must be atomic.
- `sta_set_txpwr`: Configure the station tx power. This callback set the tx
  power for the station.
  This callback can sleep.
- `sta_state`: Notifies low level driver about state transition of a
  station (which can be the AP, a client, IBSS/WDS/mesh peer etc.)
  This callback is mutually exclusive with **sta_add**/**sta_remove**.
  It must not fail for down transitions but may fail for transitions
  up the list of states. Also note that after the callback returns it
  isn't safe to use the pointer, not even RCU protected - no RCU grace
  period is guaranteed between returning here and freeing the station.
  See **sta_pre_rcu_remove** if needed.
  The callback can sleep.
- `sta_pre_rcu_remove`: Notify driver about station removal before RCU
  synchronisation. This is useful if a driver needs to have station
  pointers protected using RCU, it can then use this call to clear
  the pointers instead of waiting for an RCU grace period to elapse
  in **sta_state**.
  The callback can sleep.
- `link_sta_rc_update`: Notifies the driver of changes to the bitrates that can
  be used to transmit to the station. The changes are advertised with bits
  from [`enum ieee80211_rate_control_changed`](/kernel/hardware/driver-api/80211/mac80211-advanced.md#c-enum-ieee80211_rate_control_changed) and the values are reflected
  in the station data. This callback should only be used when the driver
  uses hardware rate control (`IEEE80211_HW_HAS_RATE_CONTROL`) since
  otherwise the rate control algorithm is notified directly.
  Must be atomic.
- `sta_rate_tbl_update`: Notifies the driver that the rate table changed. This
  is only used if the configured rate control algorithm actually uses
  the new rate table API, and is therefore optional. Must be atomic.
- `sta_statistics`: Get statistics for this station. For example with beacon
  filtering, the statistics kept by mac80211 might not be accurate, so
  let the driver pre-fill the statistics. The driver can fill most of
  the values (indicating which by setting the filled bitmap), but not
  all of them make sense - see the source for which ones are possible.
  Statistics that the driver doesn't fill will be filled by mac80211.
  The callback can sleep.
- `conf_tx`: Configure TX queue parameters (EDCF (aifs, cw_min, cw_max),
  bursting) for a hardware TX queue.
  Returns a negative error code on failure.
  The callback can sleep.
- `get_tsf`: Get the current TSF timer value from firmware/hardware. Currently,
  this is only used for IBSS mode BSSID merging and debugging. Is not a
  required function.
  The callback can sleep.
- `set_tsf`: Set the TSF timer to the specified value in the firmware/hardware.
  Currently, this is only used for IBSS mode debugging. Is not a
  required function.
  The callback can sleep.
- `offset_tsf`: Offset the TSF timer by the specified value in the
  firmware/hardware.  Preferred to set_tsf as it avoids delay between
  calling `set_tsf()` and hardware getting programmed, which will show up
  as TSF delay. Is not a required function.
  The callback can sleep.
- `reset_tsf`: Reset the TSF timer and allow firmware/hardware to synchronize
  with other STAs in the IBSS. This is only used in IBSS mode. This
  function is optional if the firmware/hardware takes full care of
  TSF synchronization.
  The callback can sleep.
- `tx_last_beacon`: Determine whether the last IBSS beacon was sent by us.
  This is needed only for IBSS mode and the result of this function is
  used to determine whether to reply to Probe Requests.
  Returns non-zero if this device sent the last beacon.
  The callback can sleep.
- `link_sta_statistics`: Get link statistics for this station. For example with
  beacon filtering, the statistics kept by mac80211 might not be
  accurate, so let the driver pre-fill the statistics. The driver can
  fill most of the values (indicating which by setting the filled
  bitmap), but not all of them make sense - see the source for which
  ones are possible.
  Statistics that the driver doesn't fill will be filled by mac80211.
  The callback can sleep.
- `ampdu_action`: Perform a certain A-MPDU action.
  The RA/TID combination determines the destination and TID we want
  the ampdu action to be performed for. The action is defined through
  ieee80211_ampdu_mlme_action.
  When the action is set to `IEEE80211_AMPDU_TX_OPERATIONAL` the driver
  may neither send aggregates containing more subframes than **buf_size**
  nor send aggregates in a way that lost frames would exceed the
  buffer size. If just limiting the aggregate size, this would be
  possible with a buf_size of 8:

  - `TX: 1.....7`
  - `RX:  2....7` (lost frame #1)
  - `TX:        8..1...`

  which is invalid since #1 was now re-transmitted well past the
  buffer size of 8. Correct ways to retransmit #1 would be:

  - `TX:        1   or`
  - `TX:        18  or`
  - `TX:        81`

  Even `189` would be wrong since 1 could be lost again.

  Returns a negative error code on failure. The driver may return
  `IEEE80211_AMPDU_TX_START_IMMEDIATE` for `IEEE80211_AMPDU_TX_START`
  if the session can start immediately.

  The callback can sleep.
- `get_survey`: Return per-channel survey information
- `rfkill_poll`: Poll rfkill hardware state. If you need this, you also
  need to set wiphy->rfkill_poll to `true` before registration,
  and need to call `wiphy_rfkill_set_hw_state()` in the callback.
  The callback can sleep.
- `set_coverage_class`: Set slot time for given coverage class as specified
  in IEEE 802.11-2007 section 17.3.8.6 and modify ACK timeout
  accordingly; coverage class equals to -1 to enable ACK timeout
  estimation algorithm (dynack). To disable dynack set valid value for
  coverage class. This callback is not required and may sleep.
- `testmode_cmd`: Implement a cfg80211 test mode command. The passed **vif** may
  be `NULL`. The callback can sleep.
- `testmode_dump`: Implement a cfg80211 test mode dump. The callback can sleep.
- `flush`: Flush all pending frames from the hardware queue, making sure
  that the hardware queues are empty. The **queues** parameter is a bitmap
  of queues to flush, which is useful if different virtual interfaces
  use different hardware queues; it may also indicate all queues.
  If the parameter **drop** is set to `true`, pending frames may be dropped.
  Note that vif can be NULL.
  The callback can sleep.
- `flush_sta`: Flush or drop all pending frames from the hardware queue(s) for
  the given station, as it's about to be removed.
  The callback can sleep.
- `channel_switch`: Drivers that need (or want) to offload the channel
  switch operation for CSAs received from the AP may implement this
  callback. They must then call `ieee80211_chswitch_done()` to indicate
  completion of the channel switch.
- `set_antenna`: Set antenna configuration (tx_ant, rx_ant) on the device.
  Parameters are bitmaps of allowed antennas to use for TX/RX. Drivers may
  reject TX/RX mask combinations they cannot support by returning -EINVAL
  (also see nl80211.h **NL80211_ATTR_WIPHY_ANTENNA_TX**).
- `get_antenna`: Get current antenna configuration from device (tx_ant, rx_ant).
- `remain_on_channel`: Starts an off-channel period on the given channel, must
  call back to `ieee80211_ready_on_channel()` when on that channel. Note
  that normal channel traffic is not stopped as this is intended for hw
  offload. Frames to transmit on the off-channel channel are transmitted
  normally except for the `IEEE80211_TX_CTL_TX_OFFCHAN` flag. When the
  duration (which will always be non-zero) expires, the driver must call
  `ieee80211_remain_on_channel_expired()`.
  Note that this callback may be called while the device is in IDLE and
  must be accepted in this case.
  This callback may sleep.
- `cancel_remain_on_channel`: Requests that an ongoing off-channel period is
  aborted before it expires. This callback may sleep.
- `set_ringparam`: Set tx and rx ring sizes.
- `get_ringparam`: Get tx and rx ring current and maximum sizes.
- `tx_frames_pending`: Check if there is any pending frame in the hardware
  queues before entering power save.
- `set_bitrate_mask`: Set a mask of rates to be used for rate control selection
  when transmitting a frame. Currently only legacy rates are handled.
  The callback can sleep.
- `event_callback`: Notify driver about any event in mac80211. See
  `enum ieee80211_event_type` for the different types.
  The callback must be atomic.
- `allow_buffered_frames`: Prepare device to allow the given number of frames
  to go out to the given station. The frames will be sent by mac80211
  via the usual TX path after this call. The TX information for frames
  released will also have the `IEEE80211_TX_CTL_NO_PS_BUFFER` flag set
  and the last one will also have `IEEE80211_TX_STATUS_EOSP` set. In case
  frames from multiple TIDs are released and the driver might reorder
  them between the TIDs, it must set the `IEEE80211_TX_STATUS_EOSP` flag
  on the last frame and clear it on all others and also handle the EOSP
  bit in the QoS header correctly. Alternatively, it can also call the
  [`ieee80211_sta_eosp()`](/kernel/hardware/driver-api/80211/mac80211-advanced.md#c-ieee80211_sta_eosp) function.
  The **tids** parameter is a bitmap and tells the driver which TIDs the
  frames will be on; it will at most have two bits set.
  This callback must be atomic.
- `release_buffered_frames`: Release buffered frames according to the given
  parameters. In the case where the driver buffers some frames for
  sleeping stations mac80211 will use this callback to tell the driver
  to release some frames, either for PS-poll or uAPSD.
  Note that if the **more_data** parameter is `false` the driver must check
  if there are more frames on the given TIDs, and if there are more than
  the frames being released then it must still set the more-data bit in
  the frame. If the **more_data** parameter is `true`, then of course the
  more-data bit must always be set.
  The **tids** parameter tells the driver which TIDs to release frames
  from, for PS-poll it will always have only a single bit set.
  In the case this is used for a PS-poll initiated release, the
  **num_frames** parameter will always be 1 so code can be shared. In
  this case the driver must also set `IEEE80211_TX_STATUS_EOSP` flag
  on the TX status (and must report TX status) so that the PS-poll
  period is properly ended. This is used to avoid sending multiple
  responses for a retried PS-poll frame.
  In the case this is used for uAPSD, the **num_frames** parameter may be
  bigger than one, but the driver may send fewer frames (it must send
  at least one, however). In this case it is also responsible for
  setting the EOSP flag in the QoS header of the frames. Also, when the
  service period ends, the driver must set `IEEE80211_TX_STATUS_EOSP`
  on the last frame in the SP. Alternatively, it may call the function
  [`ieee80211_sta_eosp()`](/kernel/hardware/driver-api/80211/mac80211-advanced.md#c-ieee80211_sta_eosp) to inform mac80211 of the end of the SP.
  This callback must be atomic.
- `get_et_sset_count`: Ethtool API to get string-set count.
  Note that the wiphy mutex is not held for this callback since it's
  expected to return a static value.
- `get_et_stats`: Ethtool API to get a set of u64 stats.
- `get_et_strings`: Ethtool API to get a set of strings to describe stats
  and perhaps other supported types of ethtool data-sets.
  Note that the wiphy mutex is not held for this callback since it's
  expected to return a static value.
- `mgd_prepare_tx`: Prepare for transmitting a management frame for association
  before associated. In multi-channel scenarios, a virtual interface is
  bound to a channel before it is associated, but as it isn't associated
  yet it need not necessarily be given airtime, in particular since any
  transmission to a P2P GO needs to be synchronized against the GO's
  powersave state. mac80211 will call this function before transmitting a
  management frame prior to transmitting that frame to allow the driver
  to give it channel time for the transmission, to get a response and be
  able to synchronize with the GO.
  The callback will be called before each transmission and upon return
  mac80211 will transmit the frame right away.
  Additional information is passed in the `struct ieee80211_prep_tx_info`
  data. If duration there is greater than zero, mac80211 hints to the
  driver the duration for which the operation is requested.
  The callback is optional and can (should!) sleep.
- `mgd_complete_tx`: Notify the driver that the response frame for a previously
  transmitted frame announced with **mgd_prepare_tx** was received, the data
  is filled similarly to **mgd_prepare_tx** though the duration is not used.
  Note that this isn't always called for each `mgd_prepare_tx()` call, for
  example for SAE the 'confirm' messages can be on the air in any order.
- `mgd_protect_tdls_discover`: Protect a TDLS discovery session. After sending
  a TDLS discovery-request, we expect a reply to arrive on the AP's
  channel. We must stay on the channel (no PSM, scan, etc.), since a TDLS
  setup-response is a direct packet not buffered by the AP.
  mac80211 will call this function just before the transmission of a TDLS
  discovery-request. The recommended period of protection is at least
  2 * (DTIM period).
  The callback is optional and can sleep.
- `add_chanctx`: Notifies device driver about new channel context creation.
  This callback may sleep.
- `remove_chanctx`: Notifies device driver about channel context destruction.
  This callback may sleep.
- `change_chanctx`: Notifies device driver about channel context changes that
  may happen when combining different virtual interfaces on the same
  channel context with different settings
  This callback may sleep.
- `assign_vif_chanctx`: Notifies device driver about channel context being bound
  to vif. Possible use is for hw queue remapping.
  This callback may sleep.
- `unassign_vif_chanctx`: Notifies device driver about channel context being
  unbound from vif.
  This callback may sleep.
- `switch_vif_chanctx`: switch a number of vifs from one chanctx to
  another, as specified in the list of
  **ieee80211_vif_chanctx_switch** passed to the driver, according
  to the mode defined in `ieee80211_chanctx_switch_mode`.
  This callback may sleep.
- `reconfig_complete`: Called after a call to `ieee80211_restart_hw()` and
  during resume, when the reconfiguration has completed.
  This can help the driver implement the reconfiguration step (and
  indicate mac80211 is ready to receive frames).
  This callback may sleep.
- `ipv6_addr_change`: IPv6 address assignment on the given interface changed.
  Currently, this is only called for managed or P2P client interfaces.
  This callback is optional; it must not sleep.
- `channel_switch_beacon`: Starts a channel switch to a new channel.
  Beacons are modified to include CSA or ECSA IEs before calling this
  function. The corresponding count fields in these IEs must be
  decremented, and when they reach 1 the driver must call
  `ieee80211_csa_finish()`. Drivers which use [`ieee80211_beacon_get()`](/kernel/hardware/driver-api/80211/mac80211-advanced.md#c-ieee80211_beacon_get)
  get the csa counter decremented by mac80211, but must check if it is
  1 using `ieee80211_beacon_counter_is_complete()` after the beacon has been
  transmitted and then call `ieee80211_csa_finish()`.
  If the CSA count starts as zero or 1, this function will not be called,
  since there won't be any time to beacon before the switch anyway.
- `pre_channel_switch`: This is an optional callback that is called
  before a channel switch procedure is started (ie. when a STA
  gets a CSA or a userspace initiated channel-switch), allowing
  the driver to prepare for the channel switch.
- `post_channel_switch`: This is an optional callback that is called
  after a channel switch procedure is completed, allowing the
  driver to go back to a normal configuration.
- `abort_channel_switch`: This is an optional callback that is called
  when channel switch procedure was aborted, allowing the
  driver to go back to a normal configuration.
- `channel_switch_rx_beacon`: This is an optional callback that is called
  when channel switch procedure is in progress and additional beacon with
  CSA IE was received, allowing driver to track changes in count.
- `join_ibss`: Join an IBSS (on an IBSS interface); this is called after all
  information in bss_conf is set up and the beacon can be retrieved. A
  channel context is bound before this is called.
- `leave_ibss`: Leave the IBSS again.
- `get_expected_throughput`: extract the expected throughput towards the
  specified station. The returned value is expressed in Kbps. It returns 0
  if the RC algorithm does not have proper data to provide.
- `get_txpower`: get current maximum tx power (in dBm) based on configuration
  and hardware limits.
- `tdls_channel_switch`: Start channel-switching with a TDLS peer. The driver
  is responsible for continually initiating channel-switching operations
  and returning to the base channel for communication with the AP. The
  driver receives a channel-switch request template and the location of
  the switch-timing IE within the template as part of the invocation.
  The template is valid only within the call, and the driver can
  optionally copy the skb for further re-use.
- `tdls_cancel_channel_switch`: Stop channel-switching with a TDLS peer. Both
  peers must be on the base channel when the call completes.
- `tdls_recv_channel_switch`: a TDLS channel-switch related frame (request or
  response) has been received from a remote peer. The driver gets
  parameters parsed from the incoming frame and may use them to continue
  an ongoing channel-switch operation. In addition, a channel-switch
  response template is provided, together with the location of the
  switch-timing IE within the template. The skb can only be used within
  the function call.
- `wake_tx_queue`: Called when new packets have been added to the queue.
- `sync_rx_queues`: Process all pending frames in RSS queues. This is a
  synchronization which is needed in case driver has in its RSS queues
  pending frames that were received prior to the control path action
  currently taken (e.g. disassociation) but are not processed yet.
- `start_nan`: join an existing NAN cluster, or create a new one.
- `stop_nan`: leave the NAN cluster.
- `nan_change_conf`: change NAN configuration. The data in cfg80211_nan_conf
  contains full new configuration and changes specify which parameters
  are changed with respect to the last NAN config.
  The driver gets both full configuration and the changed parameters since
  some devices may need the full configuration while others need only the
  changed parameters.
- `add_nan_func`: Add a NAN function. Returns 0 on success. The data in
  cfg80211_nan_func must not be referenced outside the scope of
  this call.
- `del_nan_func`: Remove a NAN function. The driver must call
  `ieee80211_nan_func_terminated()` with
  NL80211_NAN_FUNC_TERM_REASON_USER_REQUEST reason code upon removal.
- `can_aggregate_in_amsdu`: Called in order to determine if HW supports
  aggregating two specific frames in the same A-MSDU. The relation
  between the skbs should be symmetric and transitive. Note that while
  skb is always a real frame, head may or may not be an A-MSDU.
- `get_ftm_responder_stats`: Retrieve FTM responder statistics, if available.
  Statistics should be cumulative, currently no way to reset is provided.
- `start_pmsr`: start peer measurement (e.g. FTM) (this call can sleep)
- `abort_pmsr`: abort peer measurement (this call can sleep)
- `set_tid_config`: Apply TID specific configurations. This callback may sleep.
- `reset_tid_config`: Reset TID specific configuration for the peer.
  This callback may sleep.
- `update_vif_offload`: Update virtual interface offload flags
  This callback may sleep.
- `sta_set_4addr`: Called to notify the driver when a station starts/stops using
  4-address mode
- `set_sar_specs`: Update the SAR (TX power) settings.
- `sta_set_decap_offload`: Called to notify the driver when a station is allowed
  to use rx decapsulation offload
- `add_twt_setup`: Update hw with TWT agreement parameters received from the peer.
  This callback allows the hw to check if requested parameters
  are supported and if there is enough room for a new agreement.
  The hw is expected to set agreement result in the req_type field of
  twt structure.
- `twt_teardown_request`: Update the hw with TWT teardown request received
  from the peer.
- `set_radar_background`: Configure dedicated offchannel chain available for
  radar/CAC detection on some hw. This chain can't be used to transmit
  or receive frames and it is bounded to a running wdev.
  Background radar/CAC detection allows to avoid the CAC downtime
  switching to a different channel during CAC detection on the selected
  radar channel.
  The caller is expected to set chandef pointer to NULL in order to
  disable background CAC/radar detection.
- `net_fill_forward_path`: Called from .ndo_fill_forward_path in order to
  resolve a path for hardware flow offloading
- `can_activate_links`: Checks if a specific active_links bitmap is
  supported by the driver.
- `change_vif_links`: Change the valid links on an interface, note that while
  removing the old link information is still valid (link_conf pointer),
  but may immediately disappear after the function returns. The old or
  new links bitmaps may be 0 if going from/to a non-MLO situation.
  The **old** array contains pointers to the old bss_conf structures
  that were already removed, in case they're needed.
  Note that removal of link should always succeed, so the return value
  will be ignored in a removal only case.
  This callback can sleep.
- `change_sta_links`: Change the valid links of a station, similar to
  **change_vif_links**. This callback can sleep.
  Note that a sta can also be inserted or removed with valid links,
  i.e. passed to **sta_add**/**sta_state** with sta->valid_links not zero.
  In fact, cannot change from having valid_links and not having them.
- `set_hw_timestamp`: Enable/disable HW timestamping of TM/FTM frames. This is
  not restored at HW reset by mac80211 so drivers need to take care of
  that.
- `net_setup_tc`: Called from .ndo_setup_tc in order to prepare hardware
  flow offloading for flows originating from the vif.
  Note that the driver must not assume that the vif driver_data is valid
  at this point, since the callback can be called during netdev teardown.
- `can_neg_ttlm`: for managed interface, requests the driver to determine
  if the requested TID-To-Link mapping can be accepted or not.
  If it's not accepted the driver may suggest a preferred mapping and
  modify **ttlm** parameter with the suggested TID-to-Link mapping.
- `prep_add_interface`: prepare for interface addition. This can be used by
  drivers to prepare for the addition of a new interface, e.g., allocate
  the needed resources etc. This callback doesn't guarantee that an
  interface with the specified type would be added, and thus drivers that
  implement this callback need to handle such cases. The type is the full
  `enum nl80211_iftype`.
- `set_eml_op_mode`: Configure eMLSR/eMLMR operation mode in the underlay
  driver according to the parameter received in the EML Operating mode
  notification frame.

**Description**

This structure contains various callbacks that the driver may
handle or, in some cases, must handle, for example to configure
the hardware to a new channel or to transmit a frame.

**Note**

- this callback is called if **vif_cfg_changed** or **link_info_changed**

  are not implemented.

#### <a id="c-ieee80211_alloc_hw"></a>`ieee80211_alloc_hw()`

```c
struct ieee80211_hw * ieee80211_alloc_hw(size_t priv_data_len, const struct ieee80211_ops *ops)
```

Allocate a new hardware device

**Parameters**

- `size_t priv_data_len`: length of private data
- `const struct ieee80211_ops *ops`: callbacks for this device

**Description**

This must be called once for each hardware device. The returned pointer
must be used to refer to this device when calling other functions.
mac80211 allocates a private data area for the driver pointed to by
**priv** in [`struct ieee80211_hw`](#c-struct-ieee80211_hw), the size of this area is given as
**priv_data_len**.

**Return**

A pointer to the new hardware device, or `NULL` on error.

#### <a id="c-ieee80211_register_hw"></a>`ieee80211_register_hw()`

```c
int ieee80211_register_hw(struct ieee80211_hw *hw)
```

Register hardware device

**Parameters**

- `struct ieee80211_hw *hw`: the device to register as returned by [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw)

**Description**

You must call this function before any other functions in
mac80211. Note that before a hardware can be registered, you
need to fill the contained wiphy's information.

**Return**

0 on success. An error code otherwise.

#### <a id="c-ieee80211_unregister_hw"></a>`ieee80211_unregister_hw()`

```c
void ieee80211_unregister_hw(struct ieee80211_hw *hw)
```

Unregister a hardware device

**Parameters**

- `struct ieee80211_hw *hw`: the hardware to unregister

**Description**

This function instructs mac80211 to free allocated resources
and unregister netdevices from the networking subsystem.

#### <a id="c-ieee80211_free_hw"></a>`ieee80211_free_hw()`

```c
void ieee80211_free_hw(struct ieee80211_hw *hw)
```

free hardware descriptor

**Parameters**

- `struct ieee80211_hw *hw`: the hardware to free

**Description**

This function frees everything that was allocated, including the
private data for the driver. You must call [`ieee80211_unregister_hw()`](#c-ieee80211_unregister_hw)
before calling this function.


<a id="rst-phy-configuration"></a>

## PHY configuration

TBD

This chapter should describe PHY handling including start/stop callbacks and the various structures used.


#### <a id="c-enum-ieee80211_conf_flags"></a>`enum ieee80211_conf_flags`

configuration flags

**Constants**

- `IEEE80211_CONF_MONITOR`: there's a monitor interface present -- use this
  to determine for example whether to calculate timestamps for packets
  or not, do not use instead of filter flags!
- `IEEE80211_CONF_PS`: Enable 802.11 power save mode (managed mode only).
  This is the power save mode defined by IEEE 802.11-2007 section 11.2,
  meaning that the hardware still wakes up for beacons, is able to
  transmit frames and receive the possible acknowledgment frames.
  Not to be confused with hardware specific wakeup/sleep states,
  driver is responsible for that. See the section "Powersave support"
  for more.
- `IEEE80211_CONF_IDLE`: The device is running, but idle; if the flag is set
  the driver should be prepared to handle configuration requests but
  may turn the device off as much as possible. Typically, this flag will
  be set when an interface is set UP but not associated or scanning, but
  it can also be unset in that case when monitor interfaces are active.
- `IEEE80211_CONF_OFFCHANNEL`: The device is currently not on its main
  operating channel.

**Description**

Flags to define PHY configuration options

#### <a id="c-struct-ieee80211_conf"></a>`struct ieee80211_conf`

configuration of the device

**Definition**

```c
struct ieee80211_conf {
    u32 flags;
    int power_level, dynamic_ps_timeout;
    u16 listen_interval;
    u8 ps_dtim_period;
    u8 long_frame_max_tx_count, short_frame_max_tx_count;
    struct cfg80211_chan_def chandef;
    bool radar_enabled;
    enum ieee80211_smps_mode smps_mode;
};
```

**Members**

- `flags`: configuration flags defined above
- `power_level`: requested transmit power (in dBm), backward compatibility
  value only that is set to the minimum of all interfaces
- `dynamic_ps_timeout`: The dynamic powersave timeout (in ms), see the
  powersave documentation below. This variable is valid only when
  the CONF_PS flag is set.
- `listen_interval`: listen interval in units of beacon interval
- `ps_dtim_period`: The DTIM period of the AP we're connected to, for use
  in power saving. Power saving will not be enabled until a beacon
  has been received and the DTIM period is known.
- `long_frame_max_tx_count`: Maximum number of transmissions for a "long" frame
  (a frame not RTS protected), called "dot11LongRetryLimit" in 802.11,
  but actually means the number of transmissions not the number of retries
- `short_frame_max_tx_count`: Maximum number of transmissions for a "short"
  frame, called "dot11ShortRetryLimit" in 802.11, but actually means the
  number of transmissions not the number of retries
- `chandef`: the channel definition to tune to
- `radar_enabled`: whether radar detection is enabled
- `smps_mode`: spatial multiplexing powersave mode; note that
  `IEEE80211_SMPS_STATIC` is used when the device is not
  configured for an HT channel.
  Note that this is only valid if channel contexts are not used,
  otherwise each channel context has the number of chains listed.

**Description**

This struct indicates how the driver shall configure the hardware.


<a id="rst-virtual-interfaces"></a>

## Virtual interfaces

TBD

This chapter should describe virtual interface basics that are relevant to the driver (VLANs, MGMT etc are not.) It should explain the use of the add_iface/remove_iface callbacks as well as the interface configuration callbacks.

Things related to AP mode should be discussed there.

Things related to supporting multiple interfaces should be in the appropriate chapter, a BIG FAT note should be here about this though and the recommendation to allow only a single interface in STA mode at first\!


#### <a id="c-struct-ieee80211_vif"></a>`struct ieee80211_vif`

per-interface data

**Definition**

```c
struct ieee80211_vif {
        enum nl80211_iftype type;
        struct ieee80211_vif_cfg cfg;
        struct ieee80211_bss_conf bss_conf;
        struct ieee80211_bss_conf  *link_conf[IEEE80211_MLD_MAX_NUM_LINKS];
        u16 valid_links, active_links, dormant_links, suspended_links;
        struct ieee80211_neg_ttlm neg_ttlm;
        u8 addr[ETH_ALEN] ;
        bool addr_valid;
        bool p2p;
        u8 cab_queue;
        u8 hw_queue[IEEE80211_NUM_ACS];
        struct ieee80211_txq *txq;
        netdev_features_t netdev_features;
        u32 driver_flags;
        u32 offload_flags;
    #ifdef CONFIG_MAC80211_DEBUGFS;
        struct dentry *debugfs_dir;
    #endif;
        bool probe_req_reg;
        bool rx_mcast_action_reg;
        u8 drv_priv[] ;
};
```

**Members**

- `type`: type of this virtual interface
- `cfg`: vif configuration, see `struct ieee80211_vif_cfg`
- `bss_conf`: BSS configuration for this interface, either our own
  or the BSS we're associated to
- `link_conf`: in case of MLD, the per-link BSS configuration,
  indexed by link ID
- `valid_links`: bitmap of valid links, or 0 for non-MLO.
- `active_links`: The bitmap of active links, or 0 for non-MLO.
  The driver shouldn't change this directly, but use the
  API calls meant for that purpose.
- `dormant_links`: subset of the valid links that are disabled/suspended
  due to advertised or negotiated TTLM respectively.
  0 for non-MLO.
- `suspended_links`: subset of dormant_links representing links that are
  suspended due to negotiated TTLM, and could be activated in the
  future by tearing down the TTLM negotiation.
  0 for non-MLO.
- `neg_ttlm`: negotiated TID to link mapping info.
  see `struct ieee80211_neg_ttlm`.
- `addr`: address of this interface
- `addr_valid`: indicates if the address is actively used. Set to false for
  passive monitor interfaces, true in all other cases.
- `p2p`: indicates whether this AP or STA interface is a p2p
  interface, i.e. a GO or p2p-sta respectively
- `cab_queue`: content-after-beacon (DTIM beacon really) queue, AP mode only
- `hw_queue`: hardware queue for each AC
- `txq`: the multicast data TX queue
- `netdev_features`: tx netdev features supported by the hardware for this
  vif. mac80211 initializes this to hw->netdev_features, and the driver
  can mask out specific tx features. mac80211 will handle software fixup
  for masked offloads (GSO, CSUM)
- `driver_flags`: flags/capabilities the driver has for this interface,
  these need to be set (or cleared) when the interface is added
  or, if supported by the driver, the interface type is changed
  at runtime, mac80211 will never touch this field
- `offload_flags`: 802.3 -> 802.11 enapsulation offload flags, see
  `enum ieee80211_offload_flags`.
- `debugfs_dir`: debugfs dentry, can be used by drivers to create own per
  interface debug files. Note that it will be NULL for the virtual
  monitor interface (if that is requested.)
- `probe_req_reg`: probe requests should be reported to mac80211 for this
  interface.
- `rx_mcast_action_reg`: multicast Action frames should be reported to mac80211
  for this interface.
- `drv_priv`: data area for driver use, will always be aligned to
  sizeof(void \*).

**Description**

Data in this structure is continually present for driver
use during the life of a virtual interface.


<a id="rst-receive-and-transmit-processing"></a>

## Receive and transmit processing

<a id="rst-what-should-be-here"></a>

### what should be here

TBD

This should describe the receive and transmit paths in mac80211/the drivers as well as transmit status handling.

<a id="rst-frame-format"></a>

### Frame format


As a general rule, when frames are passed between mac80211 and the driver,
they start with the IEEE 802.11 header and include the same octets that are
sent over the air except for the FCS which should be calculated by the
hardware.

There are, however, various exceptions to this rule for advanced features:

The first exception is for hardware encryption and decryption offload
where the IV/ICV may or may not be generated in hardware.

Secondly, when the hardware handles fragmentation, the frame handed to
the driver from mac80211 is the MSDU, not the MPDU.


<a id="rst-packet-alignment"></a>

### Packet alignment


Drivers always need to pass packets that are aligned to two-byte boundaries
to the stack.

Additionally, they should, if possible, align the payload data in a way that
guarantees that the contained IP header is aligned to a four-byte
boundary. In the case of regular frames, this simply means aligning the
payload to a four-byte boundary (because either the IP header is directly
contained, or IV/RFC1042 headers that have a length divisible by four are
in front of it).  If the payload data is not properly aligned and the
architecture doesn't support efficient unaligned operations, mac80211
will align the data.

With A-MSDU frames, however, the payload data address must yield two modulo
four because there are 14-byte 802.3 headers within the A-MSDU frames that
push the IP header further back to a multiple of four again. Thankfully, the
specs were sane enough this time around to require padding each A-MSDU
subframe to a length that is a multiple of four.

Padding like Atheros hardware adds which is between the 802.11 header and
the payload is not supported; the driver is required to move the 802.11
header to be directly in front of the payload in that case.


<a id="rst-calling-into-mac80211-from-interrupts"></a>

### Calling into mac80211 from interrupts


Only [`ieee80211_tx_status_irqsafe()`](#c-ieee80211_tx_status_irqsafe) and [`ieee80211_rx_irqsafe()`](#c-ieee80211_rx_irqsafe) can be
called in hardware interrupt context. The low-level driver must not call any
other functions in hardware interrupt context. If there is a need for such
call, the low-level driver should first ACK the interrupt and perform the
IEEE 802.11 code call after this, e.g. from a scheduled workqueue or even
tasklet function.

- NOTE: If the driver opts to use the `_irqsafe()` functions, it may not also

  use the non-IRQ-safe functions!


<a id="rst-functions-definitions"></a>

### functions/definitions


#### <a id="c-enum-mac80211_tx_info_flags"></a>`enum mac80211_tx_info_flags`

flags to describe transmission information/status

**Constants**

- `IEEE80211_TX_CTL_REQ_TX_STATUS`: require TX status callback for this frame.
- `IEEE80211_TX_CTL_ASSIGN_SEQ`: The driver has to assign a sequence
  number to this frame, taking care of not overwriting the fragment
  number and increasing the sequence number only when the
  IEEE80211_TX_CTL_FIRST_FRAGMENT flag is set. mac80211 will properly
  assign sequence numbers to QoS-data frames but cannot do so correctly
  for non-QoS-data and management frames because beacons need them from
  that counter as well and mac80211 cannot guarantee proper sequencing.
  If this flag is set, the driver should instruct the hardware to
  assign a sequence number to the frame or assign one itself. Cf. IEEE
  802.11-2007 7.1.3.4.1 paragraph 3. This flag will always be set for
  beacons and always be clear for frames without a sequence number field.
- `IEEE80211_TX_CTL_NO_ACK`: tell the low level not to wait for an ack
- `IEEE80211_TX_CTL_CLEAR_PS_FILT`: clear powersave filter for destination
  station
- `IEEE80211_TX_CTL_FIRST_FRAGMENT`: this is a first fragment of the frame
- `IEEE80211_TX_CTL_SEND_AFTER_DTIM`: send this frame after DTIM beacon
- `IEEE80211_TX_CTL_AMPDU`: this frame should be sent as part of an A-MPDU
- `IEEE80211_TX_CTL_INJECTED`: Frame was injected, internal to mac80211.
- `IEEE80211_TX_STAT_TX_FILTERED`: The frame was not transmitted
  because the destination STA was in powersave mode. Note that to
  avoid race conditions, the filter must be set by the hardware or
  firmware upon receiving a frame that indicates that the station
  went to sleep (must be done on device to filter frames already on
  the queue) and may only be unset after mac80211 gives the OK for
  that by setting the IEEE80211_TX_CTL_CLEAR_PS_FILT (see above),
  since only then is it guaranteed that no more frames are in the
  hardware queue.
- `IEEE80211_TX_STAT_ACK`: Frame was acknowledged
- `IEEE80211_TX_STAT_AMPDU`: The frame was aggregated, so status
  is for the whole aggregation.
- `IEEE80211_TX_STAT_AMPDU_NO_BACK`: no block ack was returned,
  so consider using block ack request (BAR).
- `IEEE80211_TX_CTL_RATE_CTRL_PROBE`: internal to mac80211, can be
  set by rate control algorithms to indicate probe rate, will
  be cleared for fragmented frames (except on the last fragment)
- `IEEE80211_TX_INTFL_OFFCHAN_TX_OK`: Internal to mac80211. Used to indicate
  that a frame can be transmitted while the queues are stopped for
  off-channel operation.
- `IEEE80211_TX_CTL_HW_80211_ENCAP`: This frame uses hardware encapsulation
  (header conversion)
- `IEEE80211_TX_INTFL_RETRIED`: completely internal to mac80211,
  used to indicate that a frame was already retried due to PS
- `IEEE80211_TX_INTFL_DONT_ENCRYPT`: completely internal to mac80211,
  used to indicate frame should not be encrypted
- `IEEE80211_TX_CTL_NO_PS_BUFFER`: This frame is a response to a poll
  frame (PS-Poll or uAPSD) or a non-bufferable MMPDU and must
  be sent although the station is in powersave mode.
- `IEEE80211_TX_CTL_MORE_FRAMES`: More frames will be passed to the
  transmit function after the current frame, this can be used
  by drivers to kick the DMA queue only if unset or when the
  queue gets full.
- `IEEE80211_TX_INTFL_RETRANSMISSION`: This frame is being retransmitted
  after TX status because the destination was asleep, it must not
  be modified again (no seqno assignment, crypto, etc.)
- `IEEE80211_TX_INTFL_MLME_CONN_TX`: This frame was transmitted by the MLME
  code for connection establishment, this indicates that its status
  should kick the MLME state machine.
- `IEEE80211_TX_INTFL_NL80211_FRAME_TX`: Frame was requested through nl80211
  MLME command (internal to mac80211 to figure out whether to send TX
  status to user space)
- `IEEE80211_TX_CTL_LDPC`: tells the driver to use LDPC for this frame
- `IEEE80211_TX_CTL_STBC`: Enables Space-Time Block Coding (STBC) for this
  frame and selects the maximum number of streams that it can use.
- `IEEE80211_TX_CTL_TX_OFFCHAN`: Marks this packet to be transmitted on
  the off-channel channel when a remain-on-channel offload is done
  in hardware -- normal packets still flow and are expected to be
  handled properly by the device.
- `IEEE80211_TX_INTFL_TKIP_MIC_FAILURE`: Marks this packet to be used for TKIP
  testing. It will be sent out with incorrect Michael MIC key to allow
  TKIP countermeasures to be tested.
- `IEEE80211_TX_CTL_NO_CCK_RATE`: This frame will be sent at non CCK rate.
  This flag is actually used for management frame especially for P2P
  frames not being sent at CCK rate in 2GHz band.
- `IEEE80211_TX_STATUS_EOSP`: This packet marks the end of service period,
  when its status is reported the service period ends. For frames in
  an SP that mac80211 transmits, it is already set; for driver frames
  the driver may set this flag. It is also used to do the same for
  PS-Poll responses.
- `IEEE80211_TX_CTL_USE_MINRATE`: This frame will be sent at lowest rate.
  This flag is used to send nullfunc frame at minimum rate when
  the nullfunc is used for connection monitoring purpose.
- `IEEE80211_TX_CTL_DONTFRAG`: Don't fragment this packet even if it
  would be fragmented by size (this is optional, only used for
  monitor injection).
- `IEEE80211_TX_STAT_NOACK_TRANSMITTED`: A frame that was marked with
  IEEE80211_TX_CTL_NO_ACK has been successfully transmitted without
  any errors (like issues specific to the driver/HW).
  This flag must not be set for frames that don't request no-ack
  behaviour with IEEE80211_TX_CTL_NO_ACK.

**Description**

These flags are used with the **flags** member of [`ieee80211_tx_info`](#c-struct-ieee80211_tx_info).

**Note**

- If you have to add new flags to the enumeration, then don't

  forget to update `IEEE80211_TX_TEMPORARY_FLAGS` when necessary.

#### <a id="c-enum-mac80211_tx_control_flags"></a>`enum mac80211_tx_control_flags`

flags to describe transmit control

**Constants**

- `IEEE80211_TX_CTRL_PORT_CTRL_PROTO`: this frame is a port control
  protocol frame (e.g. EAP)
- `IEEE80211_TX_CTRL_PS_RESPONSE`: This frame is a response to a poll
  frame (PS-Poll or uAPSD).
- `IEEE80211_TX_CTRL_RATE_INJECT`: This frame is injected with rate information
- `IEEE80211_TX_CTRL_AMSDU`: This frame is an A-MSDU frame
- `IEEE80211_TX_CTRL_FAST_XMIT`: This frame is going through the fast_xmit path
- `IEEE80211_TX_CTRL_SKIP_MPATH_LOOKUP`: This frame skips mesh path lookup
- `IEEE80211_TX_INTCFL_NEED_TXPROCESSING`: completely internal to mac80211,
  used to indicate that a pending frame requires TX processing before
  it can be sent out.
- `IEEE80211_TX_CTRL_NO_SEQNO`: Do not overwrite the sequence number that
  has already been assigned to this frame.
- `IEEE80211_TX_CTRL_DONT_REORDER`: This frame should not be reordered
  relative to other frames that have this flag set, independent
  of their QoS TID or other priority field values.
- `IEEE80211_TX_CTRL_MCAST_MLO_FIRST_TX`: first MLO TX, used mostly internally
  for sequence number assignment
- `IEEE80211_TX_CTRL_DONT_USE_RATE_MASK`: Don't use rate mask for this frame
  which is transmitted due to scanning or offchannel TX, not in normal
  operation on the interface.
- `IEEE80211_TX_CTRL_MLO_LINK`: If not **IEEE80211_LINK_UNSPECIFIED**, this
  frame should be transmitted on the specific link. This really is
  only relevant for frames that do not have data present, and is
  also not used for 802.3 format frames. Note that even if the frame
  is on a specific link, address translation might still apply if
  it's intended for an MLD.

**Description**

These flags are used in tx_info->control.flags.

#### <a id="c-enum-mac80211_rate_control_flags"></a>`enum mac80211_rate_control_flags`

per-rate flags set by the Rate Control algorithm.

**Constants**

- `IEEE80211_TX_RC_USE_RTS_CTS`: Use RTS/CTS exchange for this rate.
- `IEEE80211_TX_RC_USE_CTS_PROTECT`: CTS-to-self protection is required.
  This is set if the current BSS requires ERP protection.
- `IEEE80211_TX_RC_USE_SHORT_PREAMBLE`: Use short preamble.
- `IEEE80211_TX_RC_MCS`: HT rate.
- `IEEE80211_TX_RC_GREEN_FIELD`: Indicates whether this rate should be used in
  Greenfield mode.
- `IEEE80211_TX_RC_40_MHZ_WIDTH`: Indicates if the Channel Width should be 40 MHz.
- `IEEE80211_TX_RC_DUP_DATA`: The frame should be transmitted on both of the
  adjacent 20 MHz channels, if the current channel type is
  NL80211_CHAN_HT40MINUS or NL80211_CHAN_HT40PLUS.
- `IEEE80211_TX_RC_SHORT_GI`: Short Guard interval should be used for this rate.
- `IEEE80211_TX_RC_VHT_MCS`: VHT MCS rate, in this case the idx field is split
  into a higher 4 bits (Nss) and lower 4 bits (MCS number)
- `IEEE80211_TX_RC_80_MHZ_WIDTH`: Indicates 80 MHz transmission
- `IEEE80211_TX_RC_160_MHZ_WIDTH`: Indicates 160 MHz transmission
  (80+80 isn't supported yet)

**Description**

These flags are set by the Rate control algorithm for each rate during tx,
in the **flags** member of struct ieee80211_tx_rate.

#### <a id="c-struct-ieee80211_tx_rate"></a>`struct ieee80211_tx_rate`

rate selection/status

**Definition**

```c
struct ieee80211_tx_rate {
    s8 idx;
    u16 count:5, flags:11;
};
```

**Members**

- `idx`: rate index to attempt to send with
- `count`: number of tries in this rate before going to the next rate
- `flags`: rate control flags ([`enum mac80211_rate_control_flags`](#c-enum-mac80211_rate_control_flags))

**Description**

A value of -1 for **idx** indicates an invalid rate and, if used
in an array of retry rates, that no more rates should be tried.

When used for transmit status reporting, the driver should
always report the rate along with the flags it used.

[`struct ieee80211_tx_info`](#c-struct-ieee80211_tx_info) contains an array of these structs
in the control information, and it will be filled by the rate
control algorithm according to what should be sent. For example,
if this array contains, in the format { \<idx>, \<count> } the
information:

```text
{ 3, 2 }, { 2, 2 }, { 1, 4 }, { -1, 0 }, { -1, 0 }
```

then this means that the frame should be transmitted
up to twice at rate 3, up to twice at rate 2, and up to four
times at rate 1 if it doesn't get acknowledged. Say it gets
acknowledged by the peer after the fifth attempt, the status
information should then contain:

```text
{ 3, 2 }, { 2, 2 }, { 1, 1 }, { -1, 0 } ...
```

since it was transmitted twice at rate 3, twice at rate 2
and once at rate 1 after which we received an acknowledgement.

#### <a id="c-struct-ieee80211_tx_info"></a>`struct ieee80211_tx_info`

skb transmit information

**Definition**

```c
struct ieee80211_tx_info {
    u32 flags;
    u32 band:3, status_data_idr:1, status_data:13, hw_queue:4, tx_time_est:10;
    union {
        struct {
            union {
                struct {
                    struct ieee80211_tx_rate rates[ IEEE80211_TX_MAX_RATES];
                    s8 rts_cts_rate_idx;
                    u8 use_rts:1;
                    u8 use_cts_prot:1;
                    u8 short_preamble:1;
                    u8 skip_table:1;
                    u8 antennas:2;
                };
                unsigned long jiffies;
            };
            struct ieee80211_vif *vif;
            struct ieee80211_key_conf *hw_key;
            u32 flags;
            codel_time_t enqueue_time;
        } control;
        struct {
            u64 cookie;
        } ack;
        struct {
            struct ieee80211_tx_rate rates[IEEE80211_TX_MAX_RATES];
            s32 ack_signal;
            u8 ampdu_ack_len;
            u8 ampdu_len;
            u8 antenna;
            u8 pad;
            u16 tx_time;
            u8 flags;
            u8 pad2;
            void *status_driver_data[16 / sizeof(void *)];
        } status;
        struct {
            struct ieee80211_tx_rate driver_rates[ IEEE80211_TX_MAX_RATES];
            u8 pad[4];
            void *rate_driver_data[ IEEE80211_TX_INFO_RATE_DRIVER_DATA_SIZE / sizeof(void *)];
        };
        void *driver_data[ IEEE80211_TX_INFO_DRIVER_DATA_SIZE / sizeof(void *)];
    };
};
```

**Members**

- `flags`: transmit info flags, defined above
- `band`: the band to transmit on (use e.g. for checking for races),
  not valid if the interface is an MLD since we won't know which
  link the frame will be transmitted on
- `status_data_idr`: indicates status data is IDR allocated ID for ack frame
- `status_data`: internal data for TX status handling, assigned privately,
  see also `enum ieee80211_status_data` for the internal documentation
- `hw_queue`: HW queue to put the frame on, `skb_get_queue_mapping()` gives the AC
- `tx_time_est`: TX time estimate in units of 4us, used internally
- `{unnamed_union}`: anonymous
- `control`: union part for control data
- `{unnamed_union}`: anonymous
- `{unnamed_struct}`: anonymous
- `control.rates`: TX rates array to try
- `control.rts_cts_rate_idx`: rate for RTS or CTS
- `control.use_rts`: use RTS
- `control.use_cts_prot`: use RTS/CTS
- `control.short_preamble`: use short preamble (CCK only)
- `control.skip_table`: skip externally configured rate table
- `control.jiffies`: timestamp for expiry on powersave clients
- `control.vif`: virtual interface (may be NULL)
- `control.hw_key`: key to encrypt with (may be NULL)
- `control.flags`: control flags, see [`enum mac80211_tx_control_flags`](#c-enum-mac80211_tx_control_flags)
- `control.enqueue_time`: enqueue time (for iTXQs)
- `ack`: union part for pure ACK data
- `ack.cookie`: cookie for the ACK
- `status`: union part for status data
- `status.rates`: attempted rates
- `status.ack_signal`: ACK signal
- `status.ampdu_ack_len`: AMPDU ack length
- `status.ampdu_len`: AMPDU length
- `status.antenna`: (legacy, kept only for iwlegacy)
- `status.tx_time`: airtime consumed for transmission; note this is only
  used for WMM AC, not for airtime fairness
- `status.flags`: status flags, see `enum mac80211_tx_status_flags`
- `status.status_driver_data`: driver use area
- `{unnamed_struct}`: anonymous
- `driver_rates`: alias to **control.rates** to reserve space
- `pad`: padding
- `rate_driver_data`: driver use area if driver needs **control.rates**
- `driver_data`: array of driver_data pointers

**Description**

- This structure is placed in skb->cb for three uses:
  (1) mac80211 TX control - mac80211 tells the driver what to do
  (2) driver internal use (if applicable)
  (3) TX status information - driver tells mac80211 what happened

#### <a id="c-ieee80211_tx_info_clear_status"></a>`ieee80211_tx_info_clear_status()`

```c
void ieee80211_tx_info_clear_status(struct ieee80211_tx_info *info)
```

clear TX status

**Parameters**

- `struct ieee80211_tx_info *info`: The [`struct ieee80211_tx_info`](#c-struct-ieee80211_tx_info) to be cleared.

**Description**

When the driver passes an skb back to mac80211, it must report
a number of things in TX status. This function clears everything
in the TX status but the rate control information (it does clear
the count since you need to fill that in anyway).

**NOTE**

- While the rates array is kept intact, this will wipe all of the

  driver_data fields in info, so it's up to the driver to restore
  any fields it needs after calling this helper.

#### <a id="c-enum-mac80211_rx_flags"></a>`enum mac80211_rx_flags`

receive flags

**Constants**

- `RX_FLAG_MMIC_ERROR`: Michael MIC error was reported on this frame.
  Use together with `RX_FLAG_MMIC_STRIPPED`.
- `RX_FLAG_DECRYPTED`: This frame was decrypted in hardware.
- `RX_FLAG_ONLY_MONITOR`: Report frame only to monitor interfaces without
  processing it in any regular way.
  This is useful if drivers offload some frames but still want to report
  them for sniffing purposes.
- `RX_FLAG_MMIC_STRIPPED`: the Michael MIC is stripped off this frame,
  verification has been done by the hardware.
- `RX_FLAG_IV_STRIPPED`: The IV and ICV are stripped from this frame.
  If this flag is set, the stack cannot do any replay detection
  hence the driver or hardware will have to do that.
- `RX_FLAG_FAILED_FCS_CRC`: Set this flag if the FCS check failed on
  the frame.
- `RX_FLAG_FAILED_PLCP_CRC`: Set this flag if the PCLP check failed on
  the frame.
- `RX_FLAG_MACTIME_IS_RTAP_TS64`: The timestamp passed in the RX status **mactime**
  is only for use in the radiotap timestamp header, not otherwise a valid
  **mactime** value. Note this is a separate flag so that we continue to see
  `RX_FLAG_MACTIME` as unset. Also note that in this case the timestamp is
  reported to be 64 bits wide, not just 32.
- `RX_FLAG_NO_SIGNAL_VAL`: The signal strength value is not present.
  Valid only for data frames (mainly A-MPDU)
- `RX_FLAG_AMPDU_DETAILS`: A-MPDU details are known, in particular the reference
  number (**ampdu_reference**) must be populated and be a distinct number for
  each A-MPDU
- `RX_FLAG_PN_VALIDATED`: Currently only valid for CCMP/GCMP frames, this
  flag indicates that the PN was verified for replay protection.
  Note that this flag is also currently only supported when a frame
  is also decrypted (ie. **RX_FLAG_DECRYPTED** must be set)
- `RX_FLAG_DUP_VALIDATED`: The driver should set this flag if it did
  de-duplication by itself.
- `RX_FLAG_AMPDU_LAST_KNOWN`: last subframe is known, should be set on all
  subframes of a single A-MPDU
- `RX_FLAG_AMPDU_IS_LAST`: this subframe is the last subframe of the A-MPDU
- `RX_FLAG_AMPDU_DELIM_CRC_ERROR`: A delimiter CRC error has been detected
  on this subframe
- `RX_FLAG_MACTIME`: The timestamp passed in the RX status (**mactime**
  field) is valid if this field is non-zero, and the position
  where the timestamp was sampled depends on the value.
- `RX_FLAG_MACTIME_PLCP_START`: The timestamp passed in the RX status (**mactime**
  field) is valid and contains the time the SYNC preamble was received.
- `RX_FLAG_MACTIME_START`: The timestamp passed in the RX status (**mactime**
  field) is valid and contains the time the first symbol of the MPDU
  was received. This is useful in monitor mode and for proper IBSS
  merging.
- `RX_FLAG_MACTIME_END`: The timestamp passed in the RX status (**mactime**
  field) is valid and contains the time the last symbol of the MPDU
  (including FCS) was received.
- `RX_FLAG_SKIP_MONITOR`: Process and report frame to all interfaces except
  monitor interfaces.
  This is useful if drivers offload some frames but still want to report
  them for sniffing purposes.
- `RX_FLAG_AMSDU_MORE`: Some drivers may prefer to report separate A-MSDU
  subframes instead of a one huge frame for performance reasons.
  All, but the last MSDU from an A-MSDU should have this flag set. E.g.
  if an A-MSDU has 3 frames, the first 2 must have the flag set, while
  the 3rd (last) one must not have this flag set. The flag is used to
  deal with retransmission/duplication recovery properly since A-MSDU
  subframes share the same sequence number. Reported subframes can be
  either regular MSDU or singly A-MSDUs. Subframes must not be
  interleaved with other frames.
- `RX_FLAG_RADIOTAP_TLV_AT_END`: This frame contains radiotap TLVs in the
  skb->data (before the 802.11 header).
  If used, the SKB's mac_header pointer must be set to point
  to the 802.11 header after the TLVs, and any padding added after TLV
  data to align to 4 must be cleared by the driver putting the TLVs
  in the skb.
- `RX_FLAG_MIC_STRIPPED`: The mic was stripped of this packet. Decryption was
  done by the hardware
- `RX_FLAG_ALLOW_SAME_PN`: Allow the same PN as same packet before.
  This is used for AMSDU subframes which can have the same PN as
  the first subframe.
- `RX_FLAG_ICV_STRIPPED`: The ICV is stripped from this frame. CRC checking must
  be done in the hardware.
- `RX_FLAG_AMPDU_EOF_BIT`: Value of the EOF bit in the A-MPDU delimiter for this
  frame
- `RX_FLAG_AMPDU_EOF_BIT_KNOWN`: The EOF value is known
- `RX_FLAG_RADIOTAP_HE`: HE radiotap data is present
  (`struct ieee80211_radiotap_he`, mac80211 will fill in
- `RX_FLAG_RADIOTAP_HE_MU`: HE MU radiotap data is present
  (`struct ieee80211_radiotap_he_mu`)
- `RX_FLAG_RADIOTAP_LSIG`: L-SIG radiotap data is present
- `RX_FLAG_NO_PSDU`: use the frame only for radiotap reporting, with
  the "0-length PSDU" field included there.  The value for it is
  in [`struct ieee80211_rx_status`](#c-struct-ieee80211_rx_status).  Note that if this value isn't
  known the frame shouldn't be reported.
- `RX_FLAG_8023`: the frame has an 802.3 header (decap offload performed by
  hardware or driver)
- `RX_FLAG_RADIOTAP_VHT`: VHT radiotap data is present

**Description**

These flags are used with the **flag** member of [`struct ieee80211_rx_status`](#c-struct-ieee80211_rx_status).

- DATA3_DATA_MCS
- DATA3_DATA_DCM
- DATA3_CODING
- DATA5_GI
- DATA5_DATA_BW_RU_ALLOC
- DATA6_NSTS
- DATA3_STBC

  from the RX info data, so leave those zeroed when building this data)

#### <a id="c-enum-mac80211_rx_encoding_flags"></a>`enum mac80211_rx_encoding_flags`

MCS & bandwidth flags

**Constants**

- `RX_ENC_FLAG_SHORTPRE`: Short preamble was used for this frame
- `RX_ENC_FLAG_SHORT_GI`: Short guard interval was used
- `RX_ENC_FLAG_HT_GF`: This frame was received in a HT-greenfield transmission,
  if the driver fills this value it should add
  `IEEE80211_RADIOTAP_MCS_HAVE_FMT`
  to **hw.radiotap_mcs_details** to advertise that fact.
- `RX_ENC_FLAG_STBC_MASK`: STBC 2 bit bitmask. 1 - Nss=1, 2 - Nss=2, 3 - Nss=3
- `RX_ENC_FLAG_LDPC`: LDPC was used
- `RX_ENC_FLAG_BF`: packet was beamformed

#### <a id="c-struct-ieee80211_rx_status"></a>`struct ieee80211_rx_status`

receive status

**Definition**

```c
struct ieee80211_rx_status {
    u64 mactime;
    union {
        u64 boottime_ns;
        ktime_t ack_tx_hwtstamp;
    };
    u32 device_timestamp;
    u32 ampdu_reference;
    u32 flag;
    u16 freq: 13, freq_offset: 1;
    u8 enc_flags;
    u8 encoding:3, bw:4;
    union {
        struct {
            u8 he_ru:3;
            u8 he_gi:2;
            u8 he_dcm:1;
        };
        struct {
            u8 ru:4;
            u8 gi:2;
        } eht;
        struct {
            u8 ru:4;
            u8 gi:2;
            u8 elr:1;
            u8 im:1;
        } uhr;
    };
    u8 rate_idx;
    u8 nss;
    u8 rx_flags;
    u8 band;
    u8 antenna;
    s8 signal;
    u8 chains;
    s8 chain_signal[IEEE80211_MAX_CHAINS];
    u8 zero_length_psdu_type;
    u8 link_valid:1, link_id:4;
};
```

**Members**

- `mactime`: value in microseconds of the 64-bit Time Synchronization Function
  (TSF) timer when the first data symbol (MPDU) arrived at the hardware.
- `{unnamed_union}`: anonymous
- `boottime_ns`: CLOCK_BOOTTIME timestamp the frame was received at, this is
  needed only for beacons and probe responses that update the scan cache.
- `ack_tx_hwtstamp`: Hardware timestamp for the ack TX in nanoseconds. Only
  needed for Timing measurement and Fine timing measurement action frames.
  Only reported by devices that have timestamping enabled.
- `device_timestamp`: arbitrary timestamp for the device, mac80211 doesn't use
  it but can store it and pass it back to the driver for synchronisation
- `ampdu_reference`: A-MPDU reference number, must be a different value for
  each A-MPDU but the same for each subframe within one A-MPDU
- `flag`: `RX_FLAG_`\*
- `freq`: frequency the radio was tuned to when receiving this frame, in MHz
  This field must be set for management frames, but isn't strictly needed
  for data (other) frames - for those it only affects radiotap reporting.
- `freq_offset`:

  **freq** has a positive offset of 500Khz.
- `enc_flags`: uses bits from [`enum mac80211_rx_encoding_flags`](#c-enum-mac80211_rx_encoding_flags)
- `encoding`: `enum mac80211_rx_encoding`
- `bw`: `enum rate_info_bw`
- `{unnamed_union}`: anonymous
- `{unnamed_struct}`: anonymous
- `he_ru`: HE RU, from `enum nl80211_he_ru_alloc`
- `he_gi`: HE GI, from `enum nl80211_he_gi`
- `he_dcm`: HE DCM value
- `eht`: EHT specific rate information
- `eht.ru`: EHT RU, from `enum nl80211_eht_ru_alloc`
- `eht.gi`: EHT GI, from `enum nl80211_eht_gi`
- `uhr`: UHR specific rate information
- `uhr.ru`: UHR RU, from `enum nl80211_eht_ru_alloc`
- `uhr.gi`: UHR GI, from `enum nl80211_eht_gi`
- `uhr.elr`: UHR ELR MCS was used
- `uhr.im`: UHR interference mitigation was used
- `rate_idx`: index of data rate into band's supported rates or MCS index if
  HT or VHT is used (`RX_FLAG_HT`/`RX_FLAG_VHT`)
- `nss`: number of streams (VHT, HE, EHT and UHR only)
- `rx_flags`: internal RX flags for mac80211
- `band`: the active band when this frame was received
- `antenna`: antenna used
- `signal`: signal strength when receiving this frame, either in dBm, in dB or
  unspecified depending on the hardware capabilities flags
  **IEEE80211_HW_SIGNAL_***
- `chains`: bitmask of receive chains for which separate signal strength
  values were filled.
- `chain_signal`: per-chain signal strength, in dBm (unlike **signal**, doesn't
  support dB or unspecified units)
- `zero_length_psdu_type`: radiotap type of the 0-length PSDU
- `link_valid`: if the link which is identified by **link_id** is valid. This flag
  is set only when connection is MLO.
- `link_id`: id of the link used to receive the packet. This is used along with
  **link_valid**.

**Description**

The low-level driver should provide this information (the subset
supported by hardware) to the 802.11 code with each received
frame, in the skb's control buffer (cb).

#### <a id="c-ieee80211_rx"></a>`ieee80211_rx()`

```c
void ieee80211_rx(struct ieee80211_hw *hw, struct sk_buff *skb)
```

receive frame

**Parameters**

- `struct ieee80211_hw *hw`: the hardware this frame came in on
- `struct sk_buff *skb`: the buffer to receive, owned by mac80211 after this call

**Description**

Use this function to hand received frames to mac80211. The receive
buffer in **skb** must start with an IEEE 802.11 header. In case of a
paged **skb** is used, the driver is recommended to put the ieee80211
header of the frame on the linear part of the **skb** to avoid memory
allocation and/or memcpy by the stack.

This function may not be called in IRQ context. Calls to this function
for a single hardware must be synchronized against each other. Calls to
this function, [`ieee80211_rx_ni()`](#c-ieee80211_rx_ni) and [`ieee80211_rx_irqsafe()`](#c-ieee80211_rx_irqsafe) may not be
mixed for a single hardware. Must not run concurrently with
[`ieee80211_tx_status_skb()`](#c-ieee80211_tx_status_skb) or [`ieee80211_tx_status_ni()`](#c-ieee80211_tx_status_ni).

In process context use instead [`ieee80211_rx_ni()`](#c-ieee80211_rx_ni).

#### <a id="c-ieee80211_rx_irqsafe"></a>`ieee80211_rx_irqsafe()`

```c
void ieee80211_rx_irqsafe(struct ieee80211_hw *hw, struct sk_buff *skb)
```

receive frame

**Parameters**

- `struct ieee80211_hw *hw`: the hardware this frame came in on
- `struct sk_buff *skb`: the buffer to receive, owned by mac80211 after this call

**Description**

Like [`ieee80211_rx()`](#c-ieee80211_rx) but can be called in IRQ context
(internally defers to a tasklet.)

Calls to this function, [`ieee80211_rx()`](#c-ieee80211_rx) or [`ieee80211_rx_ni()`](#c-ieee80211_rx_ni) may not
be mixed for a single hardware.Must not run concurrently with
[`ieee80211_tx_status_skb()`](#c-ieee80211_tx_status_skb) or [`ieee80211_tx_status_ni()`](#c-ieee80211_tx_status_ni).

#### <a id="c-ieee80211_rx_ni"></a>`ieee80211_rx_ni()`

```c
void ieee80211_rx_ni(struct ieee80211_hw *hw, struct sk_buff *skb)
```

receive frame (in process context)

**Parameters**

- `struct ieee80211_hw *hw`: the hardware this frame came in on
- `struct sk_buff *skb`: the buffer to receive, owned by mac80211 after this call

**Description**

Like [`ieee80211_rx()`](#c-ieee80211_rx) but can be called in process context
(internally disables bottom halves).

Calls to this function, [`ieee80211_rx()`](#c-ieee80211_rx) and [`ieee80211_rx_irqsafe()`](#c-ieee80211_rx_irqsafe) may
not be mixed for a single hardware. Must not run concurrently with
[`ieee80211_tx_status_skb()`](#c-ieee80211_tx_status_skb) or [`ieee80211_tx_status_ni()`](#c-ieee80211_tx_status_ni).

#### <a id="c-ieee80211_tx_status_skb"></a>`ieee80211_tx_status_skb()`

```c
void ieee80211_tx_status_skb(struct ieee80211_hw *hw, struct sk_buff *skb)
```

transmit status callback

**Parameters**

- `struct ieee80211_hw *hw`: the hardware the frame was transmitted by
- `struct sk_buff *skb`: the frame that was transmitted, owned by mac80211 after this call

**Description**

Call this function for all transmitted frames after they have been
transmitted. It is permissible to not call this function for
multicast frames but this can affect statistics.

This function may not be called in IRQ context. Calls to this function
for a single hardware must be synchronized against each other. Calls
to this function, [`ieee80211_tx_status_ni()`](#c-ieee80211_tx_status_ni) and [`ieee80211_tx_status_irqsafe()`](#c-ieee80211_tx_status_irqsafe)
may not be mixed for a single hardware. Must not run concurrently with
[`ieee80211_rx()`](#c-ieee80211_rx) or [`ieee80211_rx_ni()`](#c-ieee80211_rx_ni).

#### <a id="c-ieee80211_tx_status_ni"></a>`ieee80211_tx_status_ni()`

```c
void ieee80211_tx_status_ni(struct ieee80211_hw *hw, struct sk_buff *skb)
```

transmit status callback (in process context)

**Parameters**

- `struct ieee80211_hw *hw`: the hardware the frame was transmitted by
- `struct sk_buff *skb`: the frame that was transmitted, owned by mac80211 after this call

**Description**

Like [`ieee80211_tx_status_skb()`](#c-ieee80211_tx_status_skb) but can be called in process context.

Calls to this function, [`ieee80211_tx_status_skb()`](#c-ieee80211_tx_status_skb) and
[`ieee80211_tx_status_irqsafe()`](#c-ieee80211_tx_status_irqsafe) may not be mixed
for a single hardware.

#### <a id="c-ieee80211_tx_status_irqsafe"></a>`ieee80211_tx_status_irqsafe()`

```c
void ieee80211_tx_status_irqsafe(struct ieee80211_hw *hw, struct sk_buff *skb)
```

IRQ-safe transmit status callback

**Parameters**

- `struct ieee80211_hw *hw`: the hardware the frame was transmitted by
- `struct sk_buff *skb`: the frame that was transmitted, owned by mac80211 after this call

**Description**

Like [`ieee80211_tx_status_skb()`](#c-ieee80211_tx_status_skb) but can be called in IRQ context
(internally defers to a tasklet.)

Calls to this function, [`ieee80211_tx_status_skb()`](#c-ieee80211_tx_status_skb) and
[`ieee80211_tx_status_ni()`](#c-ieee80211_tx_status_ni) may not be mixed for a single hardware.

#### <a id="c-ieee80211_rts_get"></a>`ieee80211_rts_get()`

```c
void ieee80211_rts_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const void *frame, size_t frame_len, const struct ieee80211_tx_info *frame_txctl, struct ieee80211_rts *rts)
```

RTS frame generation function

**Parameters**

- `struct ieee80211_hw *hw`: pointer obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).
- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](#c-struct-ieee80211_vif) pointer from the add_interface callback.
- `const void *frame`: pointer to the frame that is going to be protected by the RTS.
- `size_t frame_len`: the frame length (in octets).
- `const struct ieee80211_tx_info *frame_txctl`: [`struct ieee80211_tx_info`](#c-struct-ieee80211_tx_info) of the frame.
- `struct ieee80211_rts *rts`: The buffer where to store the RTS frame.

**Description**

If the RTS frames are generated by the host system (i.e., not in
hardware/firmware), the low-level driver uses this function to receive
the next RTS frame from the 802.11 code. The low-level is responsible
for calling this function before and RTS frame is needed.

#### <a id="c-ieee80211_rts_duration"></a>`ieee80211_rts_duration()`

```c
__le16 ieee80211_rts_duration(struct ieee80211_hw *hw, struct ieee80211_vif *vif, size_t frame_len, const struct ieee80211_tx_info *frame_txctl)
```

Get the duration field for an RTS frame

**Parameters**

- `struct ieee80211_hw *hw`: pointer obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).
- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](#c-struct-ieee80211_vif) pointer from the add_interface callback.
- `size_t frame_len`: the length of the frame that is going to be protected by the RTS.
- `const struct ieee80211_tx_info *frame_txctl`: [`struct ieee80211_tx_info`](#c-struct-ieee80211_tx_info) of the frame.

**Description**

If the RTS is generated in firmware, but the host system must provide
the duration field, the low-level driver uses this function to receive
the duration field value in little-endian byteorder.

**Return**

The duration.

#### <a id="c-ieee80211_ctstoself_get"></a>`ieee80211_ctstoself_get()`

```c
void ieee80211_ctstoself_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const void *frame, size_t frame_len, const struct ieee80211_tx_info *frame_txctl, struct ieee80211_cts *cts)
```

CTS-to-self frame generation function

**Parameters**

- `struct ieee80211_hw *hw`: pointer obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).
- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](#c-struct-ieee80211_vif) pointer from the add_interface callback.
- `const void *frame`: pointer to the frame that is going to be protected by the CTS-to-self.
- `size_t frame_len`: the frame length (in octets).
- `const struct ieee80211_tx_info *frame_txctl`: [`struct ieee80211_tx_info`](#c-struct-ieee80211_tx_info) of the frame.
- `struct ieee80211_cts *cts`: The buffer where to store the CTS-to-self frame.

**Description**

If the CTS-to-self frames are generated by the host system (i.e., not in
hardware/firmware), the low-level driver uses this function to receive
the next CTS-to-self frame from the 802.11 code. The low-level is responsible
for calling this function before and CTS-to-self frame is needed.

#### <a id="c-ieee80211_ctstoself_duration"></a>`ieee80211_ctstoself_duration()`

```c
__le16 ieee80211_ctstoself_duration(struct ieee80211_hw *hw, struct ieee80211_vif *vif, size_t frame_len, const struct ieee80211_tx_info *frame_txctl)
```

Get the duration field for a CTS-to-self frame

**Parameters**

- `struct ieee80211_hw *hw`: pointer obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).
- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](#c-struct-ieee80211_vif) pointer from the add_interface callback.
- `size_t frame_len`: the length of the frame that is going to be protected by the CTS-to-self.
- `const struct ieee80211_tx_info *frame_txctl`: [`struct ieee80211_tx_info`](#c-struct-ieee80211_tx_info) of the frame.

**Description**

If the CTS-to-self is generated in firmware, but the host system must provide
the duration field, the low-level driver uses this function to receive
the duration field value in little-endian byteorder.

**Return**

The duration.

#### <a id="c-ieee80211_generic_frame_duration"></a>`ieee80211_generic_frame_duration()`

```c
__le16 ieee80211_generic_frame_duration(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum nl80211_band band, size_t frame_len, struct ieee80211_rate *rate)
```

Calculate the duration field for a frame

**Parameters**

- `struct ieee80211_hw *hw`: pointer obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).
- `struct ieee80211_vif *vif`: [`struct ieee80211_vif`](#c-struct-ieee80211_vif) pointer from the add_interface callback.
- `enum nl80211_band band`: the band to calculate the frame duration on
- `size_t frame_len`: the length of the frame.
- `struct ieee80211_rate *rate`: the rate at which the frame is going to be transmitted.

**Description**

Calculate the duration field of some generic frame, given its
length and transmission rate (in 100kbps).

**Return**

The duration.

#### <a id="c-ieee80211_wake_queue"></a>`ieee80211_wake_queue()`

```c
void ieee80211_wake_queue(struct ieee80211_hw *hw, int queue)
```

wake specific queue

**Parameters**

- `struct ieee80211_hw *hw`: pointer as obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).
- `int queue`: queue number (counted from zero).

**Description**

Drivers must use this function instead of netif_wake_queue.

#### <a id="c-ieee80211_stop_queue"></a>`ieee80211_stop_queue()`

```c
void ieee80211_stop_queue(struct ieee80211_hw *hw, int queue)
```

stop specific queue

**Parameters**

- `struct ieee80211_hw *hw`: pointer as obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).
- `int queue`: queue number (counted from zero).

**Description**

Drivers must use this function instead of netif_stop_queue.

#### <a id="c-ieee80211_queue_stopped"></a>`ieee80211_queue_stopped()`

```c
int ieee80211_queue_stopped(struct ieee80211_hw *hw, int queue)
```

test status of the queue

**Parameters**

- `struct ieee80211_hw *hw`: pointer as obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).
- `int queue`: queue number (counted from zero).

**Description**

Drivers must use this function instead of netif_queue_stopped.

**Return**

`true` if the queue is stopped. `false` otherwise.

#### <a id="c-ieee80211_stop_queues"></a>`ieee80211_stop_queues()`

```c
void ieee80211_stop_queues(struct ieee80211_hw *hw)
```

stop all queues

**Parameters**

- `struct ieee80211_hw *hw`: pointer as obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).

**Description**

Drivers must use this function instead of netif_tx_stop_all_queues.

#### <a id="c-ieee80211_wake_queues"></a>`ieee80211_wake_queues()`

```c
void ieee80211_wake_queues(struct ieee80211_hw *hw)
```

wake all queues

**Parameters**

- `struct ieee80211_hw *hw`: pointer as obtained from [`ieee80211_alloc_hw()`](#c-ieee80211_alloc_hw).

**Description**

Drivers must use this function instead of netif_tx_wake_all_queues.


<a id="rst-frame-filtering"></a>

## Frame filtering


mac80211 requires to see many management frames for proper
operation, and users may want to see many more frames when
in monitor mode. However, for best CPU usage and power consumption,
having as few frames as possible percolate through the stack is
desirable. Hence, the hardware should filter as much as possible.

To achieve this, mac80211 uses filter flags (see below) to tell
the driver's `configure_filter()` function which frames should be
passed to mac80211 and which should be filtered out.

Before `configure_filter()` is invoked, the `prepare_multicast()`
callback is invoked with the parameters **mc_count** and **mc_list**
for the combined multicast address list of all virtual interfaces.
It's use is optional, and it returns a u64 that is passed to
`configure_filter()`. Additionally, `configure_filter()` has the
arguments **changed_flags** telling which flags were changed and
**total_flags** with the new flag states.

If your device has no multicast address filters your driver will
need to check both the `FIF_ALLMULTI` flag and the **mc_count**
parameter to see whether multicast frames should be accepted
or dropped.

All unsupported flags in **total_flags** must be cleared.
Hardware does not support a flag if it is incapable of _passing_
the frame to the stack. Otherwise the driver must ignore
the flag, but not clear it.
You must _only_ clear the flag (announce no support for the
flag to mac80211) if you are not able to pass the packet type
to the stack (so the hardware always filters it).
So for example, you should clear **FIF_CONTROL**, if your hardware
always filters control frames. If your hardware always passes
control frames to the kernel and is incapable of filtering them,
you do _not_ clear the **FIF_CONTROL** flag.
This rule applies to all other FIF flags as well.



#### <a id="c-enum-ieee80211_filter_flags"></a>`enum ieee80211_filter_flags`

hardware filter flags

**Constants**

- `FIF_ALLMULTI`: pass all multicast frames, this is used if requested
  by the user or if the hardware is not capable of filtering by
  multicast address.
- `FIF_FCSFAIL`: pass frames with failed FCS (but you need to set the
  `RX_FLAG_FAILED_FCS_CRC` for them)
- `FIF_PLCPFAIL`: pass frames with failed PLCP CRC (but you need to set
  the `RX_FLAG_FAILED_PLCP_CRC` for them
- `FIF_BCN_PRBRESP_PROMISC`: This flag is set during scanning to indicate
  to the hardware that it should not filter beacons or probe responses
  by BSSID. Filtering them can greatly reduce the amount of processing
  mac80211 needs to do and the amount of CPU wakeups, so you should
  honour this flag if possible.
- `FIF_CONTROL`: pass control frames (except for PS Poll) addressed to this
  station
- `FIF_OTHER_BSS`: pass frames destined to other BSSes
- `FIF_PSPOLL`: pass PS Poll frames
- `FIF_PROBE_REQ`: pass probe request frames
- `FIF_MCAST_ACTION`: pass multicast Action frames

**Description**

These flags determine what the filter in hardware should be
programmed to let through and what should not be passed to the
stack. It is always safe to pass more frames than requested,
but this has negative impact on power consumption.


<a id="rst-the-mac80211-workqueue"></a>

## The mac80211 workqueue


mac80211 provides its own workqueue for drivers and internal mac80211 use.
The workqueue is a single threaded workqueue and can only be accessed by
helpers for sanity checking. Drivers must ensure all work added onto the
mac80211 workqueue should be cancelled on the driver `stop()` callback.

mac80211 will flush the workqueue upon interface removal and during
suspend.

All work performed on the mac80211 workqueue must not acquire the RTNL lock.



#### <a id="c-ieee80211_queue_work"></a>`ieee80211_queue_work()`

```c
void ieee80211_queue_work(struct ieee80211_hw *hw, struct work_struct *work)
```

add work onto the mac80211 workqueue

**Parameters**

- `struct ieee80211_hw *hw`: the hardware struct for the interface we are adding work for
- `struct work_struct *work`: the work we want to add onto the mac80211 workqueue

**Description**

Drivers and mac80211 use this to add work onto the mac80211 workqueue.
This helper ensures drivers are not queueing work when they should not be.

#### <a id="c-ieee80211_queue_delayed_work"></a>`ieee80211_queue_delayed_work()`

```c
void ieee80211_queue_delayed_work(struct ieee80211_hw *hw, struct delayed_work *dwork, unsigned long delay)
```

add work onto the mac80211 workqueue

**Parameters**

- `struct ieee80211_hw *hw`: the hardware struct for the interface we are adding work for
- `struct delayed_work *dwork`: delayable work to queue onto the mac80211 workqueue
- `unsigned long delay`: number of jiffies to wait before queueing

**Description**

Drivers and mac80211 use this to queue delayed work onto the mac80211
workqueue.

---

# Crypto Drivers

_Peios Kernel / Hardware and drivers / Driver development / Cryptographic devices_

> Documentation for crypto drivers that may need more involved setup and configuration.

<a id="rst-crypto-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Documentation for crypto drivers that may need more involved setup and configuration.

- [IAA (Intel Analytics Accelerator)](</kernel/hardware/driver-api/crypto-iaa/index.md>)

---

# IAA (Intel Analytics Accelerator)

_Peios Kernel / Hardware and drivers / Driver development / crypto: iaa_

> IAA provides hardware compression and decompression via the crypto API.

<a id="rst-iaa-intel-analytics-accelerator"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

IAA provides hardware compression and decompression via the crypto API.

- [IAA Compression Accelerator Crypto Driver](</kernel/hardware/driver-api/crypto-iaa/iaa-crypto.md>)

---

# IAA Compression Accelerator Crypto Driver

_Peios Kernel / Hardware and drivers / Driver development / crypto: iaa_

> Tom Zanussi <tom.zanussi@linux.intel.com>

<a id="rst-iaa-compression-accelerator-crypto-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Tom Zanussi &lt;[tom.zanussi@linux.intel.com](<mailto:tom.zanussi@linux.intel.com>)&gt;

The IAA crypto driver supports compression/decompression compatible with the DEFLATE compression standard described in RFC 1951, which is the compression/decompression algorithm exported by this module.

The IAA hardware spec can be found here:

> [https://cdrdv2.intel.com/v1/dl/getContent/721858](<https://cdrdv2.intel.com/v1/dl/getContent/721858>)

The iaa_crypto driver is designed to work as a layer underneath higher-level compression devices such as zswap.

Users can select IAA compress/decompress acceleration by specifying one of the supported IAA compression algorithms in whatever facility allows compression algorithms to be selected.

For example, a zswap device can select the IAA 'fixed' mode represented by selecting the 'deflate-iaa' crypto compression algorithm:



```text
# echo deflate-iaa > /sys/module/zswap/parameters/compressor
```

This will tell zswap to use the IAA 'fixed' compression mode for all compresses and decompresses.

Currently, there is only one compression modes available, 'fixed' mode.

The 'fixed' compression mode implements the compression scheme specified by RFC 1951 and is given the crypto algorithm name 'deflate-iaa'.  (Because the IAA hardware has a 4k history-window limitation, only buffers &lt;= 4k, or that have been compressed using a &lt;= 4k history window, are technically compliant with the deflate spec, which allows for a window of up to 32k.  Because of this limitation, the IAA fixed mode deflate algorithm is given its own algorithm name rather than simply 'deflate').

<a id="rst-config-options-and-other-setup"></a>

## Config options and other setup

The IAA crypto driver is available via menuconfig using the following path:



```text
Cryptographic API -> Hardware crypto devices -> Support for Intel(R) IAA Compression Accelerator
```

In the configuration file the option called CONFIG_CRYPTO_DEV_IAA_CRYPTO.

The IAA crypto driver also supports statistics, which are available via menuconfig using the following path:



```text
Cryptographic API -> Hardware crypto devices -> Support for Intel(R) IAA Compression -> Enable Intel(R) IAA Compression Accelerator Statistics
```

In the configuration file the option called CONFIG_CRYPTO_DEV_IAA_CRYPTO_STATS.

The following config options should also be enabled:



```text
CONFIG_IRQ_REMAP=y
CONFIG_INTEL_IOMMU=y
CONFIG_INTEL_IOMMU_SVM=y
CONFIG_PCI_ATS=y
CONFIG_PCI_PRI=y
CONFIG_PCI_PASID=y
CONFIG_INTEL_IDXD=m
CONFIG_INTEL_IDXD_SVM=y
```

IAA is one of the first Intel accelerator IPs that can work in conjunction with the Intel IOMMU.  There are multiple modes that exist for testing. Based on IOMMU configuration, there are 3 modes:



```text
- Scalable
- Legacy
- No IOMMU
```

<a id="rst-scalable-mode"></a>

### Scalable mode

Scalable mode supports Shared Virtual Memory (SVM or SVA). It is entered when using the kernel boot commandline:



```text
intel_iommu=on,sm_on
```

with VT-d turned on in BIOS.

With scalable mode, both shared and dedicated workqueues are available for use.

For scalable mode, the following BIOS settings should be enabled:



```text
Socket Configuration > IIO Configuration > Intel VT for Directed I/O (VT-d) > Intel VT for Directed I/O

Socket Configuration > IIO Configuration > PCIe ENQCMD > ENQCMDS
```

<a id="rst-legacy-mode"></a>

### Legacy mode

Legacy mode is entered when using the kernel boot commandline:



```text
intel_iommu=off
```

or VT-d is not turned on in BIOS.

If you have booted into Linux and not sure if VT-d is on, do a "dmesg \| grep -i dmar". If you don't see a number of DMAR devices enumerated, most likely VT-d is not on.

With legacy mode, only dedicated workqueues are available for use.

<a id="rst-no-iommu-mode"></a>

### No IOMMU mode

No IOMMU mode is entered when using the kernel boot commandline:



```text
iommu=off.
```

With no IOMMU mode, only dedicated workqueues are available for use.

<a id="rst-usage"></a>

## Usage

<a id="rst-accel-config"></a>

### accel-config

When loaded, the iaa_crypto driver automatically creates a default configuration and enables it, and assigns default driver attributes. If a different configuration or set of driver attributes is required, the user must first disable the IAA devices and workqueues, reset the configuration, and then re-register the deflate-iaa algorithm with the crypto subsystem by removing and reinserting the iaa_crypto module.

The [IAA disable script](<#rst-iaa-disable-script>) in the 'Use Cases' section below can be used to disable the default configuration.

See [IAA Default Configuration](<#rst-iaa-default-config>) below for details of the default configuration.

More likely than not, however, and because of the complexity and configurability of the accelerator devices, the user will want to configure the device and manually enable the desired devices and workqueues.

The userspace tool to help doing that is called accel-config.  Using accel-config to configure device or loading a previously saved config is highly recommended.  The device can be controlled via sysfs directly but comes with the warning that you should do this ONLY if you know exactly what you are doing.  The following sections will not cover the sysfs interface but assumes you will be using accel-config.

The [IAA sysfs config interface](<#rst-iaa-sysfs-config>) section in the appendix below can be consulted for the sysfs interface details if interested.

The accel-config tool along with instructions for building it can be found here:

> [https://github.com/intel/idxd-config/\#readme](<https://github.com/intel/idxd-config/#readme>)

<a id="rst-typical-usage"></a>

### Typical usage

In order for the iaa_crypto module to actually do any compression/decompression work on behalf of a facility, one or more IAA workqueues need to be bound to the iaa_crypto driver.

For instance, here's an example of configuring an IAA workqueue and binding it to the iaa_crypto driver (note that device names are specified as 'iax' rather than 'iaa' - this is because upstream still has the old 'iax' device naming in place)



```text
# configure wq1.0

accel-config config-wq --group-id=0 --mode=dedicated --type=kernel --priority=10 --name="iaa_crypto" --driver-name="crypto" iax1/wq1.0

accel-config config-engine iax1/engine1.0 --group-id=0

# enable IAA device iax1

accel-config enable-device iax1

# enable wq1.0 on IAX device iax1

accel-config enable-wq iax1/wq1.0
```

Whenever a new workqueue is bound to or unbound from the iaa_crypto driver, the available workqueues are 'rebalanced' such that work submitted from a particular CPU is given to the most appropriate workqueue available.  Current best practice is to configure and bind at least one workqueue for each IAA device, but as long as there is at least one workqueue configured and bound to any IAA device in the system, the iaa_crypto driver will work, albeit most likely not as efficiently.

The IAA crypto algorigthms is operational and compression and decompression operations are fully enabled following the successful binding of the first IAA workqueue to the iaa_crypto driver.

Similarly, the IAA crypto algorithm is not operational and compression and decompression operations are disabled following the unbinding of the last IAA worqueue to the iaa_crypto driver.

As a result, the IAA crypto algorithms and thus the IAA hardware are only available when one or more workques are bound to the iaa_crypto driver.

When there are no IAA workqueues bound to the driver, the IAA crypto algorithms can be unregistered by removing the module.

<a id="rst-driver-attributes"></a>

### Driver attributes

There are a couple user-configurable driver attributes that can be used to configure various modes of operation.  They're listed below, along with their default values.  To set any of these attributes, echo the appropriate values to the attribute file located under /sys/bus/dsa/drivers/crypto/

The attribute settings at the time the IAA algorithms are registered are captured in each algorithm's crypto_ctx and used for all compresses and decompresses when using that algorithm.

The available attributes are:

> - verify_compress
>
>   Toggle compression verification.  If set, each compress will be internally decompressed and the contents verified, returning error codes if unsuccessful.  This can be toggled with 0/1:
>
>
>
>   ```text
>   echo 0 > /sys/bus/dsa/drivers/crypto/verify_compress
>   ```
>
>   The default setting is '1' - verify all compresses.
>
> - sync_mode
>
>   Select mode to be used to wait for completion of each compresses and decompress operation.
>
>   The crypto async interface support implemented by iaa_crypto provides an implementation that satisfies the interface but does so in a synchronous manner - it fills and submits the IDXD descriptor and then loops around waiting for it to complete before returning.  This isn't a problem at the moment, since all existing callers (e.g. zswap) wrap any asynchronous callees in a synchronous wrapper anyway.
>
>   The iaa_crypto driver does however provide true asynchronous support for callers that can make use of it.  In this mode, it fills and submits the IDXD descriptor, then returns immediately with -EINPROGRESS.  The caller can then either poll for completion itself, which requires specific code in the caller which currently nothing in the upstream kernel implements, or go to sleep and wait for an interrupt signaling completion.  This latter mode is supported by current users in the kernel such as zswap via synchronous wrappers.  Although it is supported this mode is significantly slower than the synchronous mode that does the polling in the iaa_crypto driver previously mentioned.
>
>   This mode can be enabled by writing 'async_irq' to the sync_mode iaa_crypto driver attribute:
>
>
>
>   ```text
>   echo async_irq > /sys/bus/dsa/drivers/crypto/sync_mode
>   ```
>
>   Async mode without interrupts (caller must poll) can be enabled by writing 'async' to it (please see Caveat):
>
>
>
>   ```text
>   echo async > /sys/bus/dsa/drivers/crypto/sync_mode
>   ```
>
>   The mode that does the polling in the iaa_crypto driver can be enabled by writing 'sync' to it:
>
>
>
>   ```text
>   echo sync > /sys/bus/dsa/drivers/crypto/sync_mode
>   ```
>
>   The default mode is 'sync'.
>
>   Caveat: since the only mechanism that iaa_crypto currently implements for async polling without interrupts is via the 'sync' mode as described earlier, writing 'async' to '/sys/bus/dsa/drivers/crypto/sync_mode' will internally enable the 'sync' mode. This is to ensure correct iaa_crypto behavior until true async polling without interrupts is enabled in iaa_crypto.

<a id="rst-iaa-default-configuration"></a>
<a id="rst-iaa-default-config"></a>

### IAA Default Configuration

When the iaa_crypto driver is loaded, each IAA device has a single work queue configured for it, with the following attributes:



```text
mode              "dedicated"
threshold         0
size              Total WQ Size from WQCAP
priority          10
type              IDXD_WQT_KERNEL
group             0
name              "iaa_crypto"
driver_name       "crypto"
```

The devices and workqueues are also enabled and therefore the driver is ready to be used without any additional configuration.

The default driver attributes in effect when the driver is loaded are:



```text
sync_mode         "sync"
verify_compress   1
```

In order to change either the device/work queue or driver attributes, the enabled devices and workqueues must first be disabled.  In order to have the new configuration applied to the deflate-iaa crypto algorithm, it needs to be re-registered by removing and reinserting the iaa_crypto module.  The [IAA disable script](<#rst-iaa-disable-script>) in the 'Use Cases' section below can be used to disable the default configuration.

<a id="rst-statistics"></a>

## Statistics

If the optional debugfs statistics support is enabled, the IAA crypto driver will generate statistics which can be accessed in debugfs at:



```text
# ls -al /sys/kernel/debug/iaa-crypto/
total 0
drwxr-xr-x  2 root root 0 Mar  3 07:55 .
drwx------ 53 root root 0 Mar  3 07:55 ..
-rw-r--r--  1 root root 0 Mar  3 07:55 global_stats
-rw-r--r--  1 root root 0 Mar  3 07:55 stats_reset
-rw-r--r--  1 root root 0 Mar  3 07:55 wq_stats
```

The global_stats file shows a set of global statistics collected since the driver has been loaded or reset:



```text
# cat global_stats
global stats:
  total_comp_calls: 4300
  total_decomp_calls: 4164
  total_sw_decomp_calls: 0
  total_comp_bytes_out: 5993989
  total_decomp_bytes_in: 5993989
  total_completion_einval_errors: 0
  total_completion_timeout_errors: 0
  total_completion_comp_buf_overflow_errors: 136
```

The wq_stats file shows per-wq stats, a set for each iaa device and wq in addition to some global stats:



```text
# cat wq_stats
iaa device:
  id: 1
  n_wqs: 1
  comp_calls: 0
  comp_bytes: 0
  decomp_calls: 0
  decomp_bytes: 0
  wqs:
    name: iaa_crypto
    comp_calls: 0
    comp_bytes: 0
    decomp_calls: 0
    decomp_bytes: 0

iaa device:
  id: 3
  n_wqs: 1
  comp_calls: 0
  comp_bytes: 0
  decomp_calls: 0
  decomp_bytes: 0
  wqs:
    name: iaa_crypto
    comp_calls: 0
    comp_bytes: 0
    decomp_calls: 0
    decomp_bytes: 0

iaa device:
  id: 5
  n_wqs: 1
  comp_calls: 1360
  comp_bytes: 1999776
  decomp_calls: 0
  decomp_bytes: 0
  wqs:
    name: iaa_crypto
    comp_calls: 1360
    comp_bytes: 1999776
    decomp_calls: 0
    decomp_bytes: 0

iaa device:
  id: 7
  n_wqs: 1
  comp_calls: 2940
  comp_bytes: 3994213
  decomp_calls: 4164
  decomp_bytes: 5993989
  wqs:
    name: iaa_crypto
    comp_calls: 2940
    comp_bytes: 3994213
    decomp_calls: 4164
    decomp_bytes: 5993989
  ...
```

Writing to 'stats_reset' resets all the stats, including the per-device and per-wq stats:



```text
# echo 1 > stats_reset
# cat wq_stats
  global stats:
  total_comp_calls: 0
  total_decomp_calls: 0
  total_comp_bytes_out: 0
  total_decomp_bytes_in: 0
  total_completion_einval_errors: 0
  total_completion_timeout_errors: 0
  total_completion_comp_buf_overflow_errors: 0
  ...
```

<a id="rst-use-cases"></a>

## Use cases

<a id="rst-simple-zswap-test"></a>

### Simple zswap test

For this example, the kernel should be configured according to the dedicated mode options described above, and zswap should be enabled as well:



```text
CONFIG_ZSWAP=y
```

This is a simple test that uses iaa_compress as the compressor for a swap (zswap) device.  It sets up the zswap device and then uses the memory_memadvise program listed below to forcibly swap out and in a specified number of pages, demonstrating both compress and decompress.

The zswap test expects the work queues for each IAA device on the system to be configured properly as a kernel workqueue with a workqueue driver_name of "crypto".

The first step is to make sure the iaa_crypto module is loaded:



```text
modprobe iaa_crypto
```

If the IAA devices and workqueues haven't previously been disabled and reconfigured, then the default configuration should be in place and no further IAA configuration is necessary.  See [IAA Default Configuration](<#rst-iaa-default-config>) below for details of the default configuration.

If the default configuration is in place, you should see the iaa devices and wq0s enabled:



```text
# cat /sys/bus/dsa/devices/iax1/state
enabled
# cat /sys/bus/dsa/devices/iax1/wq1.0/state
enabled
```

To demonstrate that the following steps work as expected, these commands can be used to enable debug output:



```text
# echo -n 'module iaa_crypto +p' > /sys/kernel/debug/dynamic_debug/control
# echo -n 'module idxd +p' > /sys/kernel/debug/dynamic_debug/control
```

Use the following commands to enable zswap:



```text
# echo 0 > /sys/module/zswap/parameters/enabled
# echo 50 > /sys/module/zswap/parameters/max_pool_percent
# echo deflate-iaa > /sys/module/zswap/parameters/compressor
# echo 1 > /sys/module/zswap/parameters/enabled
# echo 100 > /proc/sys/vm/swappiness
# echo never > /sys/kernel/mm/transparent_hugepage/enabled
# echo 1 > /proc/sys/vm/overcommit_memory
```

Now you can now run the zswap workload you want to measure. For example, using the memory_memadvise code below, the following command will swap in and out 100 pages:



```text
./memory_madvise 100

Allocating 100 pages to swap in/out
Swapping out 100 pages
Swapping in 100 pages
Swapped out and in 100 pages
```

You should see something like the following in the dmesg output:



```text
[  404.202972] idxd 0000:e7:02.0: iaa_comp_acompress: dma_map_sg, src_addr 223925c000, nr_sgs 1, req->src 00000000ee7cb5e6, req->slen 4096, sg_dma_len(sg) 4096
[  404.202973] idxd 0000:e7:02.0: iaa_comp_acompress: dma_map_sg, dst_addr 21dadf8000, nr_sgs 1, req->dst 000000008d6acea8, req->dlen 4096, sg_dma_len(sg) 8192
[  404.202975] idxd 0000:e7:02.0: iaa_compress: desc->src1_addr 223925c000, desc->src1_size 4096, desc->dst_addr 21dadf8000, desc->max_dst_size 4096, desc->src2_addr 2203543000, desc->src2_size 1568
[  404.202981] idxd 0000:e7:02.0: iaa_compress_verify: (verify) desc->src1_addr 21dadf8000, desc->src1_size 228, desc->dst_addr 223925c000, desc->max_dst_size 4096, desc->src2_addr 0, desc->src2_size 0
...
```

Now that basic functionality has been demonstrated, the defaults can be erased and replaced with a different configuration.  To do that, first disable zswap:



```text
# echo lzo > /sys/module/zswap/parameters/compressor
# swapoff -a
# echo 0 > /sys/module/zswap/parameters/accept_threshold_percent
# echo 0 > /sys/module/zswap/parameters/max_pool_percent
# echo 0 > /sys/module/zswap/parameters/enabled
# echo 0 > /sys/module/zswap/parameters/enabled
```

Then run the [IAA disable script](<#rst-iaa-disable-script>) in the 'Use Cases' section below to disable the default configuration.

Finally turn swap back on:



```text
# swapon -a
```

Following all that the IAA device(s) can now be re-configured and enabled as desired for further testing.  Below is one example.

The zswap test expects the work queues for each IAA device on the system to be configured properly as a kernel workqueue with a workqueue driver_name of "crypto".

The below script automatically does that:



```text
#!/bin/bash

echo "IAA devices:"
lspci -d:0cfe
echo "# IAA devices:"
lspci -d:0cfe | wc -l

#
# count iaa instances
#
iaa_dev_id="0cfe"
num_iaa=$(lspci -d:${iaa_dev_id} | wc -l)
echo "Found ${num_iaa} IAA instances"

#
# disable iaa wqs and devices
#
echo "Disable IAA"

for ((i = 1; i < ${num_iaa} * 2; i += 2)); do
    echo disable wq iax${i}/wq${i}.0
    accel-config disable-wq iax${i}/wq${i}.0
    echo disable iaa iax${i}
    accel-config disable-device iax${i}
done

echo "End Disable IAA"

echo "Reload iaa_crypto module"

rmmod iaa_crypto
modprobe iaa_crypto

echo "End Reload iaa_crypto module"

#
# configure iaa wqs and devices
#
echo "Configure IAA"
for ((i = 1; i < ${num_iaa} * 2; i += 2)); do
    accel-config config-wq --group-id=0 --mode=dedicated --wq-size=128 --priority=10 --type=kernel --name="iaa_crypto" --driver-name="crypto" iax${i}/wq${i}.0
    accel-config config-engine iax${i}/engine${i}.0 --group-id=0
done

echo "End Configure IAA"

#
# enable iaa wqs and devices
#
echo "Enable IAA"

for ((i = 1; i < ${num_iaa} * 2; i += 2)); do
    echo enable iaa iax${i}
    accel-config enable-device iax${i}
    echo enable wq iax${i}/wq${i}.0
    accel-config enable-wq iax${i}/wq${i}.0
done

echo "End Enable IAA"
```

When the workqueues are bound to the iaa_crypto driver, you should see something similar to the following in dmesg output if you've enabled debug output (echo -n 'module iaa_crypto +p' &gt; /sys/kernel/debug/dynamic_debug/control):



```text
[   60.752344] idxd 0000:f6:02.0: add_iaa_wq: added wq 000000004068d14d to iaa 00000000c9585ba2, n_wq 1
[   60.752346] iaa_crypto: rebalance_wq_table: nr_nodes=2, nr_cpus 160, nr_iaa 8, cpus_per_iaa 20
[   60.752347] iaa_crypto: rebalance_wq_table: iaa=0
[   60.752349] idxd 0000:6a:02.0: request_iaa_wq: getting wq from iaa_device 0000000042d7bc52 (0)
[   60.752350] idxd 0000:6a:02.0: request_iaa_wq: returning unused wq 00000000c8bb4452 (0) from iaa device 0000000042d7bc52 (0)
[   60.752352] iaa_crypto: rebalance_wq_table: assigned wq for cpu=0, node=0 = wq 00000000c8bb4452
[   60.752354] iaa_crypto: rebalance_wq_table: iaa=0
[   60.752355] idxd 0000:6a:02.0: request_iaa_wq: getting wq from iaa_device 0000000042d7bc52 (0)
[   60.752356] idxd 0000:6a:02.0: request_iaa_wq: returning unused wq 00000000c8bb4452 (0) from iaa device 0000000042d7bc52 (0)
[   60.752358] iaa_crypto: rebalance_wq_table: assigned wq for cpu=1, node=0 = wq 00000000c8bb4452
[   60.752359] iaa_crypto: rebalance_wq_table: iaa=0
[   60.752360] idxd 0000:6a:02.0: request_iaa_wq: getting wq from iaa_device 0000000042d7bc52 (0)
[   60.752361] idxd 0000:6a:02.0: request_iaa_wq: returning unused wq 00000000c8bb4452 (0) from iaa device 0000000042d7bc52 (0)
[   60.752362] iaa_crypto: rebalance_wq_table: assigned wq for cpu=2, node=0 = wq 00000000c8bb4452
[   60.752364] iaa_crypto: rebalance_wq_table: iaa=0
.
.
.
```

Once the workqueues and devices have been enabled, the IAA crypto algorithms are enabled and available.  When the IAA crypto algorithms have been successfully enabled, you should see the following dmesg output:



```text
[   64.893759] iaa_crypto: iaa_crypto_enable: iaa_crypto now ENABLED
```

Now run the following zswap-specific setup commands to have zswap use the 'fixed' compression mode:



```text
echo 0 > /sys/module/zswap/parameters/enabled
echo 50 > /sys/module/zswap/parameters/max_pool_percent
echo deflate-iaa > /sys/module/zswap/parameters/compressor
echo 1 > /sys/module/zswap/parameters/enabled

echo 100 > /proc/sys/vm/swappiness
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo 1 > /proc/sys/vm/overcommit_memory
```

Finally, you can now run the zswap workload you want to measure. For example, using the code below, the following command will swap in and out 100 pages:



```text
./memory_madvise 100

Allocating 100 pages to swap in/out
Swapping out 100 pages
Swapping in 100 pages
Swapped out and in 100 pages
```

You should see something like the following in the dmesg output if you've enabled debug output (echo -n 'module iaa_crypto +p' &gt; /sys/kernel/debug/dynamic_debug/control):



```text
[  404.202972] idxd 0000:e7:02.0: iaa_comp_acompress: dma_map_sg, src_addr 223925c000, nr_sgs 1, req->src 00000000ee7cb5e6, req->slen 4096, sg_dma_len(sg) 4096
[  404.202973] idxd 0000:e7:02.0: iaa_comp_acompress: dma_map_sg, dst_addr 21dadf8000, nr_sgs 1, req->dst 000000008d6acea8, req->dlen 4096, sg_dma_len(sg) 8192
[  404.202975] idxd 0000:e7:02.0: iaa_compress: desc->src1_addr 223925c000, desc->src1_size 4096, desc->dst_addr 21dadf8000, desc->max_dst_size 4096, desc->src2_addr 2203543000, desc->src2_size 1568
[  404.202981] idxd 0000:e7:02.0: iaa_compress_verify: (verify) desc->src1_addr 21dadf8000, desc->src1_size 228, desc->dst_addr 223925c000, desc->max_dst_size 4096, desc->src2_addr 0, desc->src2_size 0
[  409.203227] idxd 0000:e7:02.0: iaa_comp_adecompress: dma_map_sg, src_addr 21ddd8b100, nr_sgs 1, req->src 0000000084adab64, req->slen 228, sg_dma_len(sg) 228
[  409.203235] idxd 0000:e7:02.0: iaa_comp_adecompress: dma_map_sg, dst_addr 21ee3dc000, nr_sgs 1, req->dst 000000004e2990d0, req->dlen 4096, sg_dma_len(sg) 4096
[  409.203239] idxd 0000:e7:02.0: iaa_decompress: desc->src1_addr 21ddd8b100, desc->src1_size 228, desc->dst_addr 21ee3dc000, desc->max_dst_size 4096, desc->src2_addr 0, desc->src2_size 0
[  409.203254] idxd 0000:e7:02.0: iaa_comp_adecompress: dma_map_sg, src_addr 21ddd8b100, nr_sgs 1, req->src 0000000084adab64, req->slen 228, sg_dma_len(sg) 228
[  409.203256] idxd 0000:e7:02.0: iaa_comp_adecompress: dma_map_sg, dst_addr 21f1551000, nr_sgs 1, req->dst 000000004e2990d0, req->dlen 4096, sg_dma_len(sg) 4096
[  409.203257] idxd 0000:e7:02.0: iaa_decompress: desc->src1_addr 21ddd8b100, desc->src1_size 228, desc->dst_addr 21f1551000, desc->max_dst_size 4096, desc->src2_addr 0, desc->src2_size 0
```

In order to unregister the IAA crypto algorithms, and register new ones using different parameters, any users of the current algorithm should be stopped and the IAA workqueues and devices disabled.

In the case of zswap, remove the IAA crypto algorithm as the compressor and turn off swap (to remove all references to iaa_crypto):



```text
echo lzo > /sys/module/zswap/parameters/compressor
swapoff -a

echo 0 > /sys/module/zswap/parameters/accept_threshold_percent
echo 0 > /sys/module/zswap/parameters/max_pool_percent
echo 0 > /sys/module/zswap/parameters/enabled
```

Once zswap is disabled and no longer using iaa_crypto, the IAA wqs and devices can be disabled.

<a id="rst-iaa-disable-script-1"></a>
<a id="rst-iaa-disable-script"></a>

### IAA disable script

The below script automatically does that:



```text
#!/bin/bash

echo "IAA devices:"
lspci -d:0cfe
echo "# IAA devices:"
lspci -d:0cfe | wc -l

#
# count iaa instances
#
iaa_dev_id="0cfe"
num_iaa=$(lspci -d:${iaa_dev_id} | wc -l)
echo "Found ${num_iaa} IAA instances"

#
# disable iaa wqs and devices
#
echo "Disable IAA"

for ((i = 1; i < ${num_iaa} * 2; i += 2)); do
    echo disable wq iax${i}/wq${i}.0
    accel-config disable-wq iax${i}/wq${i}.0
    echo disable iaa iax${i}
    accel-config disable-device iax${i}
done

echo "End Disable IAA"
```

Finally, at this point the iaa_crypto module can be removed, which will unregister the current IAA crypto algorithms:



```text
rmmod iaa_crypto
```

memory_madvise.c (gcc -o memory_memadvise memory_madvise.c):



```text
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <linux/mman.h>

#ifndef MADV_PAGEOUT
#define MADV_PAGEOUT    21      /* force pages out immediately */
#endif

#define PG_SZ           4096

int main(int argc, char **argv)
{
      int i, nr_pages = 1;
      int64_t *dump_ptr;
      char *addr, *a;
      int loop = 1;

      if (argc > 1)
              nr_pages = atoi(argv[1]);

      printf("Allocating %d pages to swap in/out\n", nr_pages);

      /* allocate pages */
      addr = mmap(NULL, nr_pages * PG_SZ, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
      *addr = 1;

      /* initialize data in page to all '*' chars */
      memset(addr, '*', nr_pages * PG_SZ);

       printf("Swapping out %d pages\n", nr_pages);

      /* Tell kernel to swap it out */
      madvise(addr, nr_pages * PG_SZ, MADV_PAGEOUT);

      while (loop > 0) {
              /* Wait for swap out to finish */
              sleep(5);

              a = addr;

              printf("Swapping in %d pages\n", nr_pages);

              /* Access the page ... this will swap it back in again */
              for (i = 0; i < nr_pages; i++) {
                      if (a[0] != '*') {
                              printf("Bad data from decompress!!!!!\n");

                              dump_ptr = (int64_t *)a;
                               for (int j = 0; j < 100; j++) {
                                      printf("  page %d data: %#llx\n", i, *dump_ptr);
                                      dump_ptr++;
                              }
                      }

                      a += PG_SZ;
              }

              loop --;
      }

     printf("Swapped out and in %d pages\n", nr_pages);
```

<a id="rst-appendix"></a>

## Appendix

<a id="rst-iaa-sysfs-config-interface"></a>
<a id="rst-iaa-sysfs-config"></a>

### IAA sysfs config interface

Below is a description of the IAA sysfs interface, which as mentioned in the main document, should only be used if you know exactly what you are doing.  Even then, there's no compelling reason to use it directly since accel-config can do everything the sysfs interface can and in fact accel-config is based on it under the covers.

The 'IAA config path' is /sys/bus/dsa/devices and contains subdirectories representing each IAA device, workqueue, engine, and group.  Note that in the sysfs interface, the IAA devices are actually named using iax e.g. iax1, iax3, etc. (Note that IAA devices are the odd-numbered devices; the even-numbered devices are DSA devices and can be ignored for IAA).

The 'IAA device bind path' is /sys/bus/dsa/drivers/idxd/bind and is the file that is written to enable an IAA device.

The 'IAA workqueue bind path' is /sys/bus/dsa/drivers/crypto/bind and is the file that is written to enable an IAA workqueue.

Similarly /sys/bus/dsa/drivers/idxd/unbind and /sys/bus/dsa/drivers/crypto/unbind are used to disable IAA devices and workqueues.

The basic sequence of commands needed to set up the IAA devices and workqueues is:

- **For each device::**

  1. Disable any workqueues enabled on the device.  For example to disable workques 0 and 1 on IAA device 3:



     ```text
     # echo wq3.0 > /sys/bus/dsa/drivers/crypto/unbind
     # echo wq3.1 > /sys/bus/dsa/drivers/crypto/unbind
     ```

  2. Disable the device. For example to disable IAA device 3:



     ```text
     # echo iax3 > /sys/bus/dsa/drivers/idxd/unbind
     ```

  3. configure the desired workqueues.  For example, to configure workqueue 3 on IAA device 3:



     ```text
     # echo dedicated > /sys/bus/dsa/devices/iax3/wq3.3/mode
     # echo 128 > /sys/bus/dsa/devices/iax3/wq3.3/size
     # echo 0 > /sys/bus/dsa/devices/iax3/wq3.3/group_id
     # echo 10 > /sys/bus/dsa/devices/iax3/wq3.3/priority
     # echo "kernel" > /sys/bus/dsa/devices/iax3/wq3.3/type
     # echo "iaa_crypto" > /sys/bus/dsa/devices/iax3/wq3.3/name
     # echo "crypto" > /sys/bus/dsa/devices/iax3/wq3.3/driver_name
     ```

  4. Enable the device. For example to enable IAA device 3:



     ```text
     # echo iax3 > /sys/bus/dsa/drivers/idxd/bind
     ```

  5. Enable the desired workqueues on the device.  For example to enable workques 0 and 1 on IAA device 3:



     ```text
     # echo wq3.0 > /sys/bus/dsa/drivers/crypto/bind
     # echo wq3.1 > /sys/bus/dsa/drivers/crypto/bind
     ```

---

# FPGA Subsystem

_Peios Kernel / Hardware and drivers / Driver development / FPGAs_

> Reference for FPGA Subsystem.

<a id="rst-fpga-subsystem"></a>

**Author:** Alan Tull

- [Introduction](</kernel/hardware/driver-api/fpga/intro.md>)
- [FPGA Manager](</kernel/hardware/driver-api/fpga/fpga-mgr.md>)
- [FPGA Bridge](</kernel/hardware/driver-api/fpga/fpga-bridge.md>)
- [FPGA Region](</kernel/hardware/driver-api/fpga/fpga-region.md>)
- [In-kernel API for FPGA Programming](</kernel/hardware/driver-api/fpga/fpga-programming.md>)

---

# FPGA Bridge

_Peios Kernel / Hardware and drivers / Driver development / FPGAs_

> struct fpga_bridge - The FPGA Bridge structure

<a id="rst-fpga-bridge"></a>

<a id="rst-api-to-implement-a-new-fpga-bridge"></a>

## API to implement a new FPGA bridge

- struct fpga_bridge - The FPGA Bridge structure

- struct fpga_bridge_ops - Low level Bridge driver ops

- \__fpga_bridge_register() - Create and register a bridge

- fpga_bridge_unregister() - Unregister a bridge

The helper macro `fpga_bridge_register()` automatically sets the module that registers the FPGA bridge as the owner.


#### <a id="c-struct-fpga_bridge"></a>`struct fpga_bridge`

FPGA bridge structure

**Definition**

```c
struct fpga_bridge {
    const char *name;
    struct device dev;
    struct mutex mutex;
    const struct fpga_bridge_ops *br_ops;
    struct module *br_ops_owner;
    struct fpga_image_info *info;
    struct list_head node;
    void *priv;
};
```

**Members**

- `name`: name of low level FPGA bridge
- `dev`: FPGA bridge device
- `mutex`: enforces exclusive reference to bridge
- `br_ops`: pointer to struct of FPGA bridge ops
- `br_ops_owner`: module containing the br_ops
- `info`: fpga image specific information
- `node`: FPGA bridge list node
- `priv`: low level driver private date



#### <a id="c-struct-fpga_bridge_ops"></a>`struct fpga_bridge_ops`

ops for low level FPGA bridge drivers

**Definition**

```c
struct fpga_bridge_ops {
    int (*enable_show)(struct fpga_bridge *bridge);
    int (*enable_set)(struct fpga_bridge *bridge, bool enable);
    void (*fpga_bridge_remove)(struct fpga_bridge *bridge);
    const struct attribute_group **groups;
};
```

**Members**

- `enable_show`: returns the FPGA bridge's status
- `enable_set`: set an FPGA bridge as enabled or disabled
- `fpga_bridge_remove`: set FPGA into a specific state during driver remove
- `groups`: optional attribute groups.



#### <a id="c-__fpga_bridge_register"></a>`__fpga_bridge_register()`

```c
struct fpga_bridge * __fpga_bridge_register(struct device *parent, const char *name, const struct fpga_bridge_ops *br_ops, void *priv, struct module *owner)
```

create and register an FPGA Bridge device

**Parameters**

- `struct device *parent`: FPGA bridge device from pdev
- `const char *name`: FPGA bridge name
- `const struct fpga_bridge_ops *br_ops`: pointer to structure of fpga bridge ops
- `void *priv`: FPGA bridge private data
- `struct module *owner`: owner module containing the br_ops

**Return**

struct fpga_bridge pointer or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)



#### <a id="c-fpga_bridge_unregister"></a>`fpga_bridge_unregister()`

```c
void fpga_bridge_unregister(struct fpga_bridge *bridge)
```

unregister an FPGA bridge

**Parameters**

- `struct fpga_bridge *bridge`: FPGA bridge struct

**Description**

This function is intended for use in an FPGA bridge driver's remove function.

---

# FPGA Manager

_Peios Kernel / Hardware and drivers / Driver development / FPGAs_

> The FPGA manager core exports a set of functions for programming an FPGA with an image. The API is manufacturer agnostic. All manufacturer specifics are hidden away in a low level driver which registers a set of ops with the core. The FPGA…

<a id="rst-fpga-manager"></a>

<a id="rst-overview"></a>

## Overview

The FPGA manager core exports a set of functions for programming an FPGA with an image.  The API is manufacturer agnostic.  All manufacturer specifics are hidden away in a low level driver which registers a set of ops with the core. The FPGA image data itself is very manufacturer specific, but for our purposes it's just binary data.  The FPGA manager core won't parse it.

The FPGA image to be programmed can be in a scatter gather list, a single contiguous buffer, or a firmware file.  Because allocating contiguous kernel memory for the buffer should be avoided, users are encouraged to use a scatter gather list instead if possible.

The particulars for programming the image are presented in a structure (struct fpga_image_info).  This struct contains parameters such as pointers to the FPGA image as well as image-specific particulars such as whether the image was built for full or partial reconfiguration.

<a id="rst-how-to-support-a-new-fpga-device"></a>

## How to support a new FPGA device

To add another FPGA manager, write a driver that implements a set of ops.  The probe function calls `fpga_mgr_register()` or `fpga_mgr_register_full()`, such as:



```text
static const struct fpga_manager_ops socfpga_fpga_ops = {
        .write_init = socfpga_fpga_ops_configure_init,
        .write = socfpga_fpga_ops_configure_write,
        .write_complete = socfpga_fpga_ops_configure_complete,
        .state = socfpga_fpga_ops_state,
};

static int socfpga_fpga_probe(struct platform_device *pdev)
{
        struct device *dev = &pdev->dev;
        struct socfpga_fpga_priv *priv;
        struct fpga_manager *mgr;
        int ret;

        priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
        if (!priv)
                return -ENOMEM;

        /*
         * do ioremaps, get interrupts, etc. and save
         * them in priv
         */

        mgr = fpga_mgr_register(dev, "Altera SOCFPGA FPGA Manager",
                                &socfpga_fpga_ops, priv);
        if (IS_ERR(mgr))
                return PTR_ERR(mgr);

        platform_set_drvdata(pdev, mgr);

        return 0;
}

static int socfpga_fpga_remove(struct platform_device *pdev)
{
        struct fpga_manager *mgr = platform_get_drvdata(pdev);

        fpga_mgr_unregister(mgr);

        return 0;
}
```

Alternatively, the probe function could call one of the resource managed register functions, `devm_fpga_mgr_register()` or `devm_fpga_mgr_register_full()`.  When these functions are used, the parameter syntax is the same, but the call to `fpga_mgr_unregister()` should be removed. In the above example, the `socfpga_fpga_remove()` function would not be required.

The ops will implement whatever device specific register writes are needed to do the programming sequence for this particular FPGA.  These ops return 0 for success or negative error codes otherwise.

- **The programming sequence is::**

  1. .parse_header (optional, may be called once or multiple times)

  2. .write_init

  3. .write or .write_sg (may be called once or multiple times)

  4. .write_complete

The .parse_header function will set header_size and data_size to struct fpga_image_info. Before parse_header call, header_size is initialized with initial_header_size. If flag skip_header of fpga_manager_ops is true, .write function will get image buffer starting at header_size offset from the beginning. If data_size is set, .write function will get data_size bytes of the image buffer, otherwise .write will get data up to the end of image buffer. This will not affect .write_sg, .write_sg will still get whole image in sg_table form. If FPGA image is already mapped as a single contiguous buffer, whole buffer will be passed into .parse_header. If image is in scatter-gather form, core code will buffer up at least .initial_header_size before the first call of .parse_header, if it is not enough, .parse_header should set desired size into info-&gt;header_size and return -EAGAIN, then it will be called again with greater part of image buffer on the input.

The .write_init function will prepare the FPGA to receive the image data. The buffer passed into .write_init will be at least info-&gt;header_size bytes long; if the whole bitstream is not immediately available then the core code will buffer up at least this much before starting.

The .write function writes a buffer to the FPGA. The buffer may be contain the whole FPGA image or may be a smaller chunk of an FPGA image.  In the latter case, this function is called multiple times for successive chunks. This interface is suitable for drivers which use PIO.

The .write_sg version behaves the same as .write except the input is a sg_table scatter list. This interface is suitable for drivers which use DMA.

The .write_complete function is called after all the image has been written to put the FPGA into operating mode.

The ops include a .state function which will determine the state the FPGA is in and return a code of type enum fpga_mgr_states.  It doesn't result in a change in state.

<a id="rst-api-for-implementing-a-new-fpga-manager-driver"></a>

## API for implementing a new FPGA Manager driver

- `fpga_mgr_states` -  Values for `fpga_manager->state`.

- struct fpga_manager -  the FPGA manager struct

- struct fpga_manager_ops -  Low level FPGA manager driver ops

- struct fpga_manager_info -  Parameter structure for fpga_mgr_register_full()

- \__fpga_mgr_register_full() -  Create and register an FPGA manager using the fpga_mgr_info structure to provide the full flexibility of options

- \__fpga_mgr_register() -  Create and register an FPGA manager using standard arguments

- \__devm_fpga_mgr_register_full() -  Resource managed version of \__fpga_mgr_register_full()

- \__devm_fpga_mgr_register() -  Resource managed version of \__fpga_mgr_register()

- fpga_mgr_unregister() -  Unregister an FPGA manager

Helper macros `fpga_mgr_register_full()`, `fpga_mgr_register()`, `devm_fpga_mgr_register_full()`, and `devm_fpga_mgr_register()` are available to ease the registration.


#### <a id="c-enum-fpga_mgr_states"></a>`enum fpga_mgr_states`

fpga framework states

**Constants**

- `FPGA_MGR_STATE_UNKNOWN`: can't determine state
- `FPGA_MGR_STATE_POWER_OFF`: FPGA power is off
- `FPGA_MGR_STATE_POWER_UP`: FPGA reports power is up
- `FPGA_MGR_STATE_RESET`: FPGA in reset state
- `FPGA_MGR_STATE_FIRMWARE_REQ`: firmware request in progress
- `FPGA_MGR_STATE_FIRMWARE_REQ_ERR`: firmware request failed
- `FPGA_MGR_STATE_PARSE_HEADER`: parse FPGA image header
- `FPGA_MGR_STATE_PARSE_HEADER_ERR`: Error during PARSE_HEADER stage
- `FPGA_MGR_STATE_WRITE_INIT`: preparing FPGA for programming
- `FPGA_MGR_STATE_WRITE_INIT_ERR`: Error during WRITE_INIT stage
- `FPGA_MGR_STATE_WRITE`: writing image to FPGA
- `FPGA_MGR_STATE_WRITE_ERR`: Error while writing FPGA
- `FPGA_MGR_STATE_WRITE_COMPLETE`: Doing post programming steps
- `FPGA_MGR_STATE_WRITE_COMPLETE_ERR`: Error during WRITE_COMPLETE
- `FPGA_MGR_STATE_OPERATING`: FPGA is programmed and operating



#### <a id="c-struct-fpga_manager"></a>`struct fpga_manager`

fpga manager structure

**Definition**

```c
struct fpga_manager {
    const char *name;
    struct device dev;
    struct mutex ref_mutex;
    enum fpga_mgr_states state;
    struct fpga_compat_id *compat_id;
    const struct fpga_manager_ops *mops;
    struct module *mops_owner;
    void *priv;
};
```

**Members**

- `name`: name of low level fpga manager
- `dev`: fpga manager device
- `ref_mutex`: only allows one reference to fpga manager
- `state`: state of fpga manager
- `compat_id`: FPGA manager id for compatibility check.
- `mops`: pointer to struct of fpga manager ops
- `mops_owner`: module containing the mops
- `priv`: low level driver private date



#### <a id="c-struct-fpga_manager_ops"></a>`struct fpga_manager_ops`

ops for low level fpga manager drivers

**Definition**

```c
struct fpga_manager_ops {
    size_t initial_header_size;
    bool skip_header;
    enum fpga_mgr_states (*state)(struct fpga_manager *mgr);
    u64 (*status)(struct fpga_manager *mgr);
    int (*parse_header)(struct fpga_manager *mgr, struct fpga_image_info *info, const char *buf, size_t count);
    int (*write_init)(struct fpga_manager *mgr, struct fpga_image_info *info, const char *buf, size_t count);
    int (*write)(struct fpga_manager *mgr, const char *buf, size_t count);
    int (*write_sg)(struct fpga_manager *mgr, struct sg_table *sgt);
    int (*write_complete)(struct fpga_manager *mgr, struct fpga_image_info *info);
    void (*fpga_remove)(struct fpga_manager *mgr);
    const struct attribute_group **groups;
};
```

**Members**

- `initial_header_size`: minimum number of bytes that should be passed into
  parse_header and write_init.
- `skip_header`: bool flag to tell fpga-mgr core whether it should skip
  info->header_size part at the beginning of the image when invoking
  write callback.
- `state`: returns an enum value of the FPGA's state
- `status`: returns status of the FPGA, including reconfiguration error code
- `parse_header`: parse FPGA image header to set info->header_size and
  info->data_size. In case the input buffer is not large enough, set
  required size to info->header_size and return -EAGAIN.
- `write_init`: prepare the FPGA to receive configuration data
- `write`: write count bytes of configuration data to the FPGA
- `write_sg`: write the scatter list of configuration data to the FPGA
- `write_complete`: set FPGA to operating state after writing is done
- `fpga_remove`: optional: Set FPGA into a specific state during driver remove
- `groups`: optional attribute groups.

**Description**

fpga_manager_ops are the low level functions implemented by a specific
fpga manager driver.  The optional ones are tested for NULL before being
called, so leaving them out is fine.



#### <a id="c-struct-fpga_manager_info"></a>`struct fpga_manager_info`

collection of parameters for an FPGA Manager

**Definition**

```c
struct fpga_manager_info {
    const char *name;
    struct fpga_compat_id *compat_id;
    const struct fpga_manager_ops *mops;
    void *priv;
};
```

**Members**

- `name`: fpga manager name
- `compat_id`: FPGA manager id for compatibility check.
- `mops`: pointer to structure of fpga manager ops
- `priv`: fpga manager private data

**Description**

fpga_manager_info contains parameters for the register_full function.
These are separated into an info structure because they some are optional
others could be added to in the future. The info structure facilitates
maintaining a stable API.



#### <a id="c-__fpga_mgr_register_full"></a>`__fpga_mgr_register_full()`

```c
struct fpga_manager * __fpga_mgr_register_full(struct device *parent, const struct fpga_manager_info *info, struct module *owner)
```

create and register an FPGA Manager device

**Parameters**

- `struct device *parent`: fpga manager device from pdev
- `const struct fpga_manager_info *info`: parameters for fpga manager
- `struct module *owner`: owner module containing the ops

**Description**

The caller of this function is responsible for calling [`fpga_mgr_unregister()`](#c-fpga_mgr_unregister).
Using `devm_fpga_mgr_register_full()` instead is recommended.

**Return**

pointer to struct fpga_manager pointer or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)



#### <a id="c-__fpga_mgr_register"></a>`__fpga_mgr_register()`

```c
struct fpga_manager * __fpga_mgr_register(struct device *parent, const char *name, const struct fpga_manager_ops *mops, void *priv, struct module *owner)
```

create and register an FPGA Manager device

**Parameters**

- `struct device *parent`: fpga manager device from pdev
- `const char *name`: fpga manager name
- `const struct fpga_manager_ops *mops`: pointer to structure of fpga manager ops
- `void *priv`: fpga manager private data
- `struct module *owner`: owner module containing the ops

**Description**

The caller of this function is responsible for calling [`fpga_mgr_unregister()`](#c-fpga_mgr_unregister).
Using `devm_fpga_mgr_register()` instead is recommended. This simple
version of the register function should be sufficient for most users. The
`fpga_mgr_register_full()` function is available for users that need to pass
additional, optional parameters.

**Return**

pointer to struct fpga_manager pointer or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)



#### <a id="c-__devm_fpga_mgr_register_full"></a>`__devm_fpga_mgr_register_full()`

```c
struct fpga_manager * __devm_fpga_mgr_register_full(struct device *parent, const struct fpga_manager_info *info, struct module *owner)
```

resource managed variant of `fpga_mgr_register()`

**Parameters**

- `struct device *parent`: fpga manager device from pdev
- `const struct fpga_manager_info *info`: parameters for fpga manager
- `struct module *owner`: owner module containing the ops

**Return**

fpga manager pointer on success, negative error code otherwise.

**Description**

This is the devres variant of `fpga_mgr_register_full()` for which the unregister
function will be called automatically when the managing device is detached.



#### <a id="c-__devm_fpga_mgr_register"></a>`__devm_fpga_mgr_register()`

```c
struct fpga_manager * __devm_fpga_mgr_register(struct device *parent, const char *name, const struct fpga_manager_ops *mops, void *priv, struct module *owner)
```

resource managed variant of `fpga_mgr_register()`

**Parameters**

- `struct device *parent`: fpga manager device from pdev
- `const char *name`: fpga manager name
- `const struct fpga_manager_ops *mops`: pointer to structure of fpga manager ops
- `void *priv`: fpga manager private data
- `struct module *owner`: owner module containing the ops

**Return**

fpga manager pointer on success, negative error code otherwise.

**Description**

This is the devres variant of `fpga_mgr_register()` for which the
unregister function will be called automatically when the managing
device is detached.



#### <a id="c-fpga_mgr_unregister"></a>`fpga_mgr_unregister()`

```c
void fpga_mgr_unregister(struct fpga_manager *mgr)
```

unregister an FPGA manager

**Parameters**

- `struct fpga_manager *mgr`: fpga manager struct

**Description**

This function is intended for use in an FPGA manager driver's remove function.

---

# In-kernel API for FPGA Programming

_Peios Kernel / Hardware and drivers / Driver development / FPGAs_

> The in-kernel API for FPGA programming is a combination of APIs from FPGA manager, bridge, and regions. The actual function used to trigger FPGA programming is fpga_region_program_fpga().

<a id="rst-in-kernel-api-for-fpga-programming"></a>

<a id="rst-overview"></a>

## Overview

The in-kernel API for FPGA programming is a combination of APIs from FPGA manager, bridge, and regions.  The actual function used to trigger FPGA programming is fpga_region_program_fpga().

fpga_region_program_fpga() uses functionality supplied by the FPGA manager and bridges.  It will:

> - lock the region's mutex
>
> - lock the mutex of the region's FPGA manager
>
> - build a list of FPGA bridges if a method has been specified to do so
>
> - disable the bridges
>
> - program the FPGA using info passed in `fpga_region->info`.
>
> - re-enable the bridges
>
> - release the locks

The struct fpga_image_info specifies what FPGA image to program.  It is allocated/freed by fpga_image_info_alloc() and freed with fpga_image_info_free()

<a id="rst-how-to-program-an-fpga-using-a-region"></a>

## How to program an FPGA using a region

When the FPGA region driver probed, it was given a pointer to an FPGA manager driver so it knows which manager to use.  The region also either has a list of bridges to control during programming or it has a pointer to a function that will generate that list.  Here's some sample code of what to do next:



```text
#include <linux/fpga/fpga-mgr.h>
#include <linux/fpga/fpga-region.h>

struct fpga_image_info *info;
int ret;

/*
 * First, alloc the struct with information about the FPGA image to
 * program.
 */
info = fpga_image_info_alloc(dev);
if (!info)
        return -ENOMEM;

/* Set flags as needed, such as: */
info->flags = FPGA_MGR_PARTIAL_RECONFIG;

/*
 * Indicate where the FPGA image is. This is pseudo-code; you're
 * going to use one of these three.
 */
if (image is in a scatter gather table) {

        info->sgt = [your scatter gather table]

} else if (image is in a buffer) {

        info->buf = [your image buffer]
        info->count = [image buffer size]

} else if (image is in a firmware file) {

        info->firmware_name = devm_kstrdup(dev, firmware_name,
                                           GFP_KERNEL);

}

/* Add info to region and do the programming */
region->info = info;
ret = fpga_region_program_fpga(region);

/* Deallocate the image info if you're done with it */
region->info = NULL;
fpga_image_info_free(info);

if (ret)
        return ret;

/* Now enumerate whatever hardware has appeared in the FPGA. */
```

<a id="rst-api-for-programming-an-fpga"></a>

## API for programming an FPGA

- fpga_region_program_fpga() -  Program an FPGA

- fpga_image_info() -  Specifies what FPGA image to program

- fpga_image_info_alloc() -  Allocate an FPGA image info struct

- fpga_image_info_free() -  Free an FPGA image info struct


#### <a id="c-fpga_region_program_fpga"></a>`fpga_region_program_fpga()`

```c
int fpga_region_program_fpga(struct fpga_region *region)
```

program FPGA

**Parameters**

- `struct fpga_region *region`: FPGA region

**Description**

Program an FPGA using fpga image info (region->info).
If the region has a get_bridges function, the exclusive reference for the
bridges will be held if programming succeeds.  This is intended to prevent
reprogramming the region until the caller considers it safe to do so.
The caller will need to call [`fpga_bridges_put()`](/kernel/hardware/driver-api/fpga/fpga-region.md#c-fpga_bridges_put) before attempting to
reprogram the region.

**Return**

0 for success or negative error code.


FPGA Manager flags


Flags used in the [`fpga_image_info->flags`](#c-struct-fpga_image_info) field

`FPGA_MGR_PARTIAL_RECONFIG`: do partial reconfiguration if supported

`FPGA_MGR_EXTERNAL_CONFIG`: FPGA has been configured prior to Linux booting

`FPGA_MGR_ENCRYPTED_BITSTREAM`: indicates bitstream is encrypted

`FPGA_MGR_BITSTREAM_LSB_FIRST`: SPI bitstream bit order is LSB first

`FPGA_MGR_COMPRESSED_BITSTREAM`: FPGA bitstream is compressed



#### <a id="c-struct-fpga_image_info"></a>`struct fpga_image_info`

information specific to an FPGA image

**Definition**

```c
struct fpga_image_info {
        u32 flags;
        u32 enable_timeout_us;
        u32 disable_timeout_us;
        u32 config_complete_timeout_us;
        char *firmware_name;
        struct sg_table *sgt;
        const char *buf;
        size_t count;
        size_t header_size;
        size_t data_size;
        int region_id;
        struct device *dev;
    #ifdef CONFIG_OF;
        struct device_node *overlay;
    #endif;
};
```

**Members**

- `flags`: boolean flags as defined above
- `enable_timeout_us`: maximum time to enable traffic through bridge (uSec)
- `disable_timeout_us`: maximum time to disable traffic through bridge (uSec)
- `config_complete_timeout_us`: maximum time for FPGA to switch to operating
  status in the write_complete op.
- `firmware_name`: name of FPGA image firmware file
- `sgt`: scatter/gather table containing FPGA image
- `buf`: contiguous buffer containing FPGA image
- `count`: size of buf
- `header_size`: size of image header.
- `data_size`: size of image data to be sent to the device. If not specified,
  whole image will be used. Header may be skipped in either case.
- `region_id`: id of target region
- `dev`: device that owns this
- `overlay`: Device Tree overlay



#### <a id="c-fpga_image_info_alloc"></a>`fpga_image_info_alloc()`

```c
struct fpga_image_info * fpga_image_info_alloc(struct device *dev)
```

Allocate an FPGA image info struct

**Parameters**

- `struct device *dev`: owning device

**Return**

struct fpga_image_info or NULL



#### <a id="c-fpga_image_info_free"></a>`fpga_image_info_free()`

```c
void fpga_image_info_free(struct fpga_image_info *info)
```

Free an FPGA image info struct

**Parameters**

- `struct fpga_image_info *info`: FPGA image info struct to free

---

# FPGA Region

_Peios Kernel / Hardware and drivers / Driver development / FPGAs_

> This document is meant to be a brief overview of the FPGA region API usage. A more conceptual look at regions can be found in the Device Tree binding document 1.

<a id="rst-fpga-region"></a>

<a id="rst-overview"></a>

## Overview

This document is meant to be a brief overview of the FPGA region API usage.  A more conceptual look at regions can be found in the Device Tree binding document <a id="rst-footnote-reference-1"></a>[1](#rst-f1).

For the purposes of this API document, let's just say that a region associates an FPGA Manager and a bridge (or bridges) with a reprogrammable region of an FPGA or the whole FPGA.  The API provides a way to register a region and to program a region.

Currently the only layer above fpga-region.c in the kernel is the Device Tree support (of-fpga-region.c) described in <a id="rst-footnote-reference-2"></a>[1](#rst-f1).  The DT support layer uses regions to program the FPGA and then DT to handle enumeration.  The common region code is intended to be used by other schemes that have other ways of accomplishing enumeration after programming.

An fpga-region can be set up to know the following things:

> - which FPGA manager to use to do the programming
>
> - which bridges to disable before programming and enable afterwards.

Additional info needed to program the FPGA image is passed in the struct fpga_image_info including:

> - pointers to the image as either a scatter-gather buffer, a contiguous buffer, or the name of firmware file
>
> - flags indicating specifics such as whether the image is for partial reconfiguration.

<a id="rst-how-to-add-a-new-fpga-region"></a>

## How to add a new FPGA region

An example of usage can be seen in the probe function of <a id="rst-footnote-reference-3"></a>[2](#rst-f2).

<a id="rst-f1"></a>



**[1]** ../devicetree/bindings/fpga/fpga-region.txt

<a id="rst-f2"></a>



**[2]** ../../drivers/fpga/of-fpga-region.c

<a id="rst-api-to-add-a-new-fpga-region"></a>

## API to add a new FPGA region

- struct fpga_region - The FPGA region struct

- struct fpga_region_info - Parameter structure for \__fpga_region_register_full()

- \__fpga_region_register_full() -  Create and register an FPGA region using the fpga_region_info structure to provide the full flexibility of options

- \__fpga_region_register() -  Create and register an FPGA region using standard arguments

- fpga_region_unregister() -  Unregister an FPGA region

Helper macros `fpga_region_register()` and `fpga_region_register_full()` automatically set the module that registers the FPGA region as the owner.

The FPGA region's probe function will need to get a reference to the FPGA Manager it will be using to do the programming.  This usually would happen during the region's probe function.

- fpga_mgr_get() - Get a reference to an FPGA manager, raise ref count

- of_fpga_mgr_get() -  Get a reference to an FPGA manager, raise ref count, given a device node.

- fpga_mgr_put() - Put an FPGA manager

The FPGA region will need to specify which bridges to control while programming the FPGA.  The region driver can build a list of bridges during probe time (`fpga_region->bridge_list`) or it can have a function that creates the list of bridges to program just before programming (`fpga_region->get_bridges`).  The FPGA bridge framework supplies the following APIs to handle building or tearing down that list.

- fpga_bridge_get_to_list() - Get a ref of an FPGA bridge, add it to a list

- of_fpga_bridge_get_to_list() - Get a ref of an FPGA bridge, add it to a list, given a device node

- fpga_bridges_put() - Given a list of bridges, put them


#### <a id="c-struct-fpga_region"></a>`struct fpga_region`

FPGA Region structure

**Definition**

```c
struct fpga_region {
    struct device dev;
    struct mutex mutex;
    struct list_head bridge_list;
    struct fpga_manager *mgr;
    struct fpga_image_info *info;
    struct fpga_compat_id *compat_id;
    struct module *ops_owner;
    void *priv;
    int (*get_bridges)(struct fpga_region *region);
};
```

**Members**

- `dev`: FPGA Region device
- `mutex`: enforces exclusive reference to region
- `bridge_list`: list of FPGA bridges specified in region
- `mgr`: FPGA manager
- `info`: FPGA image info
- `compat_id`: FPGA region id for compatibility check.
- `ops_owner`: module containing the get_bridges function
- `priv`: private data
- `get_bridges`: optional function to get bridges to a list



#### <a id="c-struct-fpga_region_info"></a>`struct fpga_region_info`

collection of parameters an FPGA Region

**Definition**

```c
struct fpga_region_info {
    struct fpga_manager *mgr;
    struct fpga_compat_id *compat_id;
    void *priv;
    int (*get_bridges)(struct fpga_region *region);
};
```

**Members**

- `mgr`: fpga region manager
- `compat_id`: FPGA region id for compatibility check.
- `priv`: fpga region private data
- `get_bridges`: optional function to get bridges to a list

**Description**

fpga_region_info contains parameters for the register_full function.
These are separated into an info structure because they some are optional
others could be added to in the future. The info structure facilitates
maintaining a stable API.



#### <a id="c-__fpga_region_register_full"></a>`__fpga_region_register_full()`

```c
struct fpga_region * __fpga_region_register_full(struct device *parent, const struct fpga_region_info *info, struct module *owner)
```

create and register an FPGA Region device

**Parameters**

- `struct device *parent`: device parent
- `const struct fpga_region_info *info`: parameters for FPGA Region
- `struct module *owner`: module containing the get_bridges function

**Return**

struct fpga_region or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)



#### <a id="c-__fpga_region_register"></a>`__fpga_region_register()`

```c
struct fpga_region * __fpga_region_register(struct device *parent, struct fpga_manager *mgr, int (*get_bridges)(struct fpga_region *), struct module *owner)
```

create and register an FPGA Region device

**Parameters**

- `struct device *parent`: device parent
- `struct fpga_manager *mgr`: manager that programs this region
- `int (*get_bridges)(struct fpga_region *)`: optional function to get bridges to a list
- `struct module *owner`: module containing the get_bridges function

**Description**

This simple version of the register function should be sufficient for most users.
The `fpga_region_register_full()` function is available for users that need to
pass additional, optional parameters.

**Return**

struct fpga_region or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)



#### <a id="c-fpga_region_unregister"></a>`fpga_region_unregister()`

```c
void fpga_region_unregister(struct fpga_region *region)
```

unregister an FPGA region

**Parameters**

- `struct fpga_region *region`: FPGA region

**Description**

This function is intended for use in an FPGA region driver's remove function.



#### <a id="c-fpga_mgr_get"></a>`fpga_mgr_get()`

```c
struct fpga_manager * fpga_mgr_get(struct device *dev)
```

Given a device, get a reference to an fpga mgr.

**Parameters**

- `struct device *dev`: parent device that fpga mgr was registered with

**Return**

fpga manager struct or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing error code.



#### <a id="c-of_fpga_mgr_get"></a>`of_fpga_mgr_get()`

```c
struct fpga_manager * of_fpga_mgr_get(struct device_node *node)
```

Given a device node, get a reference to an fpga mgr.

**Parameters**

- `struct device_node *node`: device node

**Return**

fpga manager struct or [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) condition containing error code.



#### <a id="c-fpga_mgr_put"></a>`fpga_mgr_put()`

```c
void fpga_mgr_put(struct fpga_manager *mgr)
```

release a reference to an fpga manager

**Parameters**

- `struct fpga_manager *mgr`: fpga manager structure



#### <a id="c-fpga_bridge_get_to_list"></a>`fpga_bridge_get_to_list()`

```c
int fpga_bridge_get_to_list(struct device *dev, struct fpga_image_info *info, struct list_head *bridge_list)
```

given device, get a bridge, add it to a list

**Parameters**

- `struct device *dev`: FPGA bridge device
- `struct fpga_image_info *info`: fpga image specific information
- `struct list_head *bridge_list`: list of FPGA bridges

**Description**

Get an exclusive reference to the bridge and it to the list.

**Return**

0 for success, error code from `fpga_bridge_get()` otherwise.



#### <a id="c-of_fpga_bridge_get_to_list"></a>`of_fpga_bridge_get_to_list()`

```c
int of_fpga_bridge_get_to_list(struct device_node *np, struct fpga_image_info *info, struct list_head *bridge_list)
```

get a bridge, add it to a list

**Parameters**

- `struct device_node *np`: node pointer of an FPGA bridge
- `struct fpga_image_info *info`: fpga image specific information
- `struct list_head *bridge_list`: list of FPGA bridges

**Description**

Get an exclusive reference to the bridge and it to the list.

**Return**

0 for success, error code from `of_fpga_bridge_get()` otherwise.



#### <a id="c-fpga_bridges_put"></a>`fpga_bridges_put()`

```c
void fpga_bridges_put(struct list_head *bridge_list)
```

put bridges

**Parameters**

- `struct list_head *bridge_list`: list of FPGA bridges

**Description**

For each bridge in the list, put the bridge and remove it from the list.
If list is empty, do nothing.

---

# Introduction

_Peios Kernel / Hardware and drivers / Driver development / FPGAs_

> The FPGA subsystem supports reprogramming FPGAs dynamically under Linux. Some of the core intentions of the FPGA subsystems are:

<a id="rst-introduction"></a>

The FPGA subsystem supports reprogramming FPGAs dynamically under Linux.  Some of the core intentions of the FPGA subsystems are:

- The FPGA subsystem is vendor agnostic.

- The FPGA subsystem separates upper layers (userspace interfaces and enumeration) from lower layers that know how to program a specific FPGA.

- Code should not be shared between upper and lower layers.  This should go without saying.  If that seems necessary, there's probably framework functionality that can be added that will benefit other users.  Write the linux-fpga mailing list and maintainers and seek out a solution that expands the framework for broad reuse.

- Generally, when adding code, think of the future.  Plan for reuse.

The framework in the kernel is divided into:

<a id="rst-fpga-manager"></a>

## FPGA Manager

If you are adding a new FPGA or a new method of programming an FPGA, this is the subsystem for you.  Low level FPGA manager drivers contain the knowledge of how to program a specific device.  This subsystem includes the framework in fpga-mgr.c and the low level drivers that are registered with it.

<a id="rst-fpga-bridge"></a>

## FPGA Bridge

FPGA Bridges prevent spurious signals from going out of an FPGA or a region of an FPGA during programming.  They are disabled before programming begins and re-enabled afterwards.  An FPGA bridge may be actual hard hardware that gates a bus to a CPU or a soft ("freeze") bridge in FPGA fabric that surrounds a partial reconfiguration region of an FPGA.  This subsystem includes fpga-bridge.c and the low level drivers that are registered with it.

<a id="rst-fpga-region"></a>

## FPGA Region

If you are adding a new interface to the FPGA framework, add it on top of an FPGA region.

The FPGA Region framework (fpga-region.c) associates managers and bridges as reconfigurable regions.  A region may refer to the whole FPGA in full reconfiguration or to a partial reconfiguration region.

The Device Tree FPGA Region support (of-fpga-region.c) handles reprogramming FPGAs when device tree overlays are applied.

---

# General Purpose Input/Output (GPIO)

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> Contents:

<a id="rst-general-purpose-input-output-gpio"></a>

Contents:

- [Introduction](</kernel/hardware/driver-api/gpio/intro.md>)
- [Using GPIO Lines in Linux](</kernel/hardware/driver-api/gpio/using-gpio.md>)
- [GPIO Driver Interface](</kernel/hardware/driver-api/gpio/driver.md>)
- [GPIO Descriptor Consumer Interface](</kernel/hardware/driver-api/gpio/consumer.md>)
- [GPIO Mappings](</kernel/hardware/driver-api/gpio/board.md>)
- [Supporting Legacy Boards](</kernel/hardware/driver-api/gpio/legacy-boards.md>)
- [Subsystem drivers using GPIO](</kernel/hardware/driver-api/gpio/drivers-on-gpio.md>)
- [A driver for a selfmade cheap BT8xx based PCI GPIO-card (bt8xxgpio)](</kernel/hardware/driver-api/gpio/bt8xxgpio.md>)
- [PCA953x I²C GPIO expander compatibility list](</kernel/hardware/driver-api/gpio/pca953x.md>)

<a id="rst-core"></a>

## Core


#### <a id="c-struct-gpio_irq_chip"></a>`struct gpio_irq_chip`

GPIO interrupt controller

**Definition**

```c
struct gpio_irq_chip {
        struct irq_chip *chip;
        struct irq_domain *domain;
    #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY;
        struct fwnode_handle *fwnode;
        struct irq_domain *parent_domain;
        int (*child_to_parent_hwirq)(struct gpio_chip *gc, unsigned int child_hwirq, unsigned int child_type, unsigned int *parent_hwirq, unsigned int *parent_type);
        int (*populate_parent_alloc_arg)(struct gpio_chip *gc, union gpio_irq_fwspec *fwspec, unsigned int parent_hwirq, unsigned int parent_type);
        unsigned int (*child_offset_to_irq)(struct gpio_chip *gc, unsigned int pin);
        struct irq_domain_ops child_irq_domain_ops;
    #endif;
        irq_flow_handler_t handler;
        unsigned int default_type;
        struct lock_class_key *lock_key;
        struct lock_class_key *request_key;
        irq_flow_handler_t parent_handler;
        union {
            void *parent_handler_data;
            void **parent_handler_data_array;
        };
        unsigned int num_parents;
        unsigned int *parents;
        unsigned int *map;
        bool threaded;
        bool per_parent_data;
        bool initialized;
        bool domain_is_allocated_externally;
        int (*init_hw)(struct gpio_chip *gc);
        void (*init_valid_mask)(struct gpio_chip *gc, unsigned long *valid_mask, unsigned int ngpios);
        unsigned long *valid_mask;
        unsigned int first;
        void (*irq_enable)(struct irq_data *data);
        void (*irq_disable)(struct irq_data *data);
        void (*irq_unmask)(struct irq_data *data);
        void (*irq_mask)(struct irq_data *data);
};
```

**Members**

- `chip`: GPIO IRQ chip implementation, provided by GPIO driver.
- `domain`: Interrupt translation domain; responsible for mapping between GPIO
  hwirq number and Linux IRQ number.
- `fwnode`: Firmware node corresponding to this gpiochip/irqchip, necessary
  for hierarchical irqdomain support.
- `parent_domain`: If non-NULL, will be set as the parent of this GPIO interrupt
  controller's IRQ domain to establish a hierarchical interrupt
  domain. The presence of this will activate the hierarchical
  interrupt support.
- `child_to_parent_hwirq`: This callback translates a child hardware IRQ offset to a parent
  hardware IRQ offset on a hierarchical interrupt chip. The child
  hardware IRQs correspond to the GPIO index 0..ngpio-1 (see the
  ngpio field of struct gpio_chip) and the corresponding parent
  hardware IRQ and type (such as IRQ_TYPE_*) shall be returned by
  the driver. The driver can calculate this from an offset or using
  a lookup table or whatever method is best for this chip. Return
  0 on successful translation in the driver.

  If some ranges of hardware IRQs do not have a corresponding parent
  HWIRQ, return -EINVAL, but also make sure to fill in **valid_mask** and
  **need_valid_mask** to make these GPIO lines unavailable for
  translation.
- `populate_parent_alloc_arg`: This optional callback allocates and populates the specific struct
  for the parent's IRQ domain. If this is not specified, then
  `gpiochip_populate_parent_fwspec_twocell` will be used. A four-cell
  variant named `gpiochip_populate_parent_fwspec_fourcell` is also
  available.
- `child_offset_to_irq`: This optional callback is used to translate the child's GPIO line
  offset on the GPIO chip to an IRQ number for the GPIO `to_irq()`
  callback. If this is not specified, then a default callback will be
  provided that returns the line offset.
- `child_irq_domain_ops`: The IRQ domain operations that will be used for this GPIO IRQ
  chip. If no operations are provided, then default callbacks will
  be populated to setup the IRQ hierarchy. Some drivers need to
  supply their own translate function.
- `handler`: The IRQ handler to use (often a predefined IRQ core function) for
  GPIO IRQs, provided by GPIO driver.
- `default_type`: Default IRQ triggering type applied during GPIO driver
  initialization, provided by GPIO driver.
- `lock_key`: Per GPIO IRQ chip lockdep class for IRQ lock.
- `request_key`: Per GPIO IRQ chip lockdep class for IRQ request.
- `parent_handler`: The interrupt handler for the GPIO chip's parent interrupts, may be
  NULL if the parent interrupts are nested rather than cascaded.
- `{unnamed_union}`: anonymous
- `parent_handler_data`: If **per_parent_data** is false, **parent_handler_data** is a
  single pointer used as the data associated with every
  parent interrupt.
- `parent_handler_data_array`: If **per_parent_data** is true, **parent_handler_data_array** is
  an array of **num_parents** pointers, and is used to associate
  different data for each parent. This cannot be NULL if
  **per_parent_data** is true.
- `num_parents`: The number of interrupt parents of a GPIO chip.
- `parents`: A list of interrupt parents of a GPIO chip. This is owned by the
  driver, so the core will only reference this list, not modify it.
- `map`: A list of interrupt parents for each line of a GPIO chip.
- `threaded`: True if set the interrupt handling uses nested threads.
- `per_parent_data`: True if parent_handler_data_array describes a **num_parents**
  sized array to be used as parent data.
- `initialized`: Flag to track GPIO chip irq member's initialization.
  This flag will make sure GPIO chip irq members are not used
  before they are initialized.
- `domain_is_allocated_externally`: True it the irq_domain was allocated outside of gpiolib, in which
  case gpiolib won't free the irq_domain itself.
- `init_hw`: optional routine to initialize hardware before
  an IRQ chip will be added. This is quite useful when
  a particular driver wants to clear IRQ related registers
  in order to avoid undesired events.
- `init_valid_mask`: optional routine to initialize **valid_mask**, to be
  used if not all GPIO lines are valid interrupts. Sometimes some
  lines just cannot fire interrupts, and this routine, when defined,
  is passed a bitmap in "valid_mask" and it will have ngpios
  bits from 0..(ngpios-1) set to "1" as in valid. The callback can
  then directly set some bits to "0" if they cannot be used for
  interrupts.
- `valid_mask`: If not `NULL`, holds bitmask of GPIOs which are valid to be included
  in IRQ domain of the chip.
- `first`: Required for static IRQ allocation. If set,
  [`irq_domain_create_simple()`](/kernel/internals/core-api/irq/irq-domain.md#c-irq_domain_create_simple) will allocate and map all IRQs
  during initialization.
- `irq_enable`: Store old irq_chip irq_enable callback
- `irq_disable`: Store old irq_chip irq_disable callback
- `irq_unmask`: Store old irq_chip irq_unmask callback
- `irq_mask`: Store old irq_chip irq_mask callback

#### <a id="c-struct-gpio_chip"></a>`struct gpio_chip`

abstract a GPIO controller

**Definition**

```c
struct gpio_chip {
        const char              *label;
        struct gpio_device      *gpiodev;
        struct device           *parent;
        struct fwnode_handle    *fwnode;
        struct module           *owner;
        int (*request)(struct gpio_chip *gc, unsigned int offset);
        void (*free)(struct gpio_chip *gc, unsigned int offset);
        int (*get_direction)(struct gpio_chip *gc, unsigned int offset);
        int (*direction_input)(struct gpio_chip *gc, unsigned int offset);
        int (*direction_output)(struct gpio_chip *gc, unsigned int offset, int value);
        int (*get)(struct gpio_chip *gc, unsigned int offset);
        int (*get_multiple)(struct gpio_chip *gc, unsigned long *mask, unsigned long *bits);
        int (*set)(struct gpio_chip *gc, unsigned int offset, int value);
        int (*set_multiple)(struct gpio_chip *gc, unsigned long *mask, unsigned long *bits);
        int (*set_config)(struct gpio_chip *gc, unsigned int offset, unsigned long config);
        int (*to_irq)(struct gpio_chip *gc, unsigned int offset);
        void (*dbg_show)(struct seq_file *s, struct gpio_chip *gc);
        int (*init_valid_mask)(struct gpio_chip *gc, unsigned long *valid_mask, unsigned int ngpios);
        int (*add_pin_ranges)(struct gpio_chip *gc);
        int (*en_hw_timestamp)(struct gpio_chip *gc, u32 offset, unsigned long flags);
        int (*dis_hw_timestamp)(struct gpio_chip *gc, u32 offset, unsigned long flags);
        int base;
        u16 ngpio;
        u16 offset;
        const char              *const *names;
        bool can_sleep;
    #ifdef CONFIG_GPIOLIB_IRQCHIP;
        struct gpio_irq_chip irq;
    #endif;
    #if defined(CONFIG_OF_GPIO);
        unsigned int of_gpio_n_cells;
        bool (*of_node_instance_match)(struct gpio_chip *gc, unsigned int i);
        int (*of_xlate)(struct gpio_chip *gc, const struct of_phandle_args *gpiospec, u32 *flags);
    #endif;
};
```

**Members**

- `label`: a functional name for the GPIO device, such as a part
  number or the name of the SoC IP-block implementing it.
- `gpiodev`: the internal state holder, opaque struct
- `parent`: optional parent device providing the GPIOs
- `fwnode`: optional fwnode providing this controller's properties
- `owner`: helps prevent removal of modules exporting active GPIOs
- `request`: optional hook for chip-specific activation, such as
  enabling module power and clock; may sleep; must return 0 on success
  or negative error number on failure
- `free`: optional hook for chip-specific deactivation, such as
  disabling module power and clock; may sleep
- `get_direction`: returns direction for signal "offset", 0=out, 1=in,
  (same as GPIO_LINE_DIRECTION_OUT / GPIO_LINE_DIRECTION_IN),
  or negative error. It is recommended to always implement this
  function, even on input-only or output-only gpio chips.
- `direction_input`: configures signal "offset" as input, returns 0 on success
  or a negative error number. This can be omitted on input-only or
  output-only gpio chips.
- `direction_output`: configures signal "offset" as output, returns 0 on
  success or a negative error number. This can be omitted on input-only
  or output-only gpio chips.
- `get`: returns value for signal "offset", 0=low, 1=high, or negative error
- `get_multiple`: reads values for multiple signals defined by "mask" and
  stores them in "bits", returns 0 on success or negative error
- `set`: assigns output value for signal "offset", returns 0 on success or
  negative error value
- `set_multiple`: assigns output values for multiple signals defined by
  "mask", returns 0 on success or negative error value
- `set_config`: optional hook for all kinds of settings. Uses the same
  packed config format as generic pinconf. Must return 0 on success and
  a negative error number on failure.
- `to_irq`: optional hook supporting non-static [`gpiod_to_irq()`](#c-gpiod_to_irq) mappings;
  implementation may not sleep
- `dbg_show`: optional routine to show contents in debugfs; default code
  will be used when this is omitted, but custom code can show extra
  state (such as pullup/pulldown configuration).
- `init_valid_mask`: optional routine to initialize **valid_mask**, to be used if
  not all GPIOs are valid.
- `add_pin_ranges`: optional routine to initialize pin ranges, to be used when
  requires special mapping of the pins that provides GPIO functionality.
  It is called after adding GPIO chip and before adding IRQ chip.
- `en_hw_timestamp`: Dependent on GPIO chip, an optional routine to
  enable hardware timestamp.
- `dis_hw_timestamp`: Dependent on GPIO chip, an optional routine to
  disable hardware timestamp.
- `base`: identifies the first GPIO number handled by this chip;
  or, if negative during registration, requests dynamic ID allocation.
  DEPRECATION: providing anything non-negative and nailing the base
  offset of GPIO chips is deprecated. Please pass -1 as base to
  let gpiolib select the chip base in all possible cases. We want to
  get rid of the static GPIO number space in the long run.
- `ngpio`: the number of GPIOs handled by this controller; the last GPIO
  handled is (base + ngpio - 1).
- `offset`: when multiple gpio chips belong to the same device this
  can be used as offset within the device so friendly names can
  be properly assigned.
- `names`: if set, must be an array of strings to use as alternative
  names for the GPIOs in this chip. Any entry in the array
  may be NULL if there is no alias for the GPIO, however the
  array must be **ngpio** entries long.
- `can_sleep`: flag must be set iff `get()`/`set()` methods sleep, as they
  must while accessing GPIO expander chips over I2C or SPI. This
  implies that if the chip supports IRQs, these IRQs need to be threaded
  as the chip access may sleep when e.g. reading out the IRQ status
  registers.
- `irq`: Integrates interrupt chip functionality with the GPIO chip. Can be
  used to handle IRQs for most practical cases.
- `of_gpio_n_cells`: Number of cells used to form the GPIO specifier. The standard is 2
  cells:

  gpios = \<`gpio` offset flags>;

  some complex GPIO controllers instantiate more than one chip per
  device tree node and have 3 cells:

  gpios = \<`gpio` instance offset flags>;

  Legacy GPIO controllers may even have 1 cell:

  gpios = \<`gpio` offset>;
- `of_node_instance_match`: Determine if a chip is the right instance. Must be implemented by
  any driver using more than one gpio_chip per device tree node.
  Returns true if gc is the instance indicated by i (which is the
  first cell in the phandles for GPIO lines and gpio-ranges).
- `of_xlate`: Callback to translate a device tree GPIO specifier into a chip-
  relative GPIO number and flags.

**Description**

A gpio_chip can help platforms abstract various sources of GPIOs so
they can all be accessed through a common programming interface.
Example sources would be SOC controllers, FPGAs, multifunction
chips, dedicated GPIO expanders, and so on.

Each chip controls a number of signals, identified in method calls
by "offset" values in the range 0..(**ngpio** - 1).  When those signals
are referenced through calls like gpio_get_value(gpio), the offset
is calculated by subtracting **base** from the gpio number.

#### <a id="c-for_each_hwgpio_in_range"></a>`for_each_hwgpio_in_range()`

```c
for_each_hwgpio_in_range(_chip, _i, _base, _size, _label)
```

Iterates over all GPIOs in a given range

**Parameters**

- `_chip`: Chip to iterate over.
- `_i`: Loop counter.
- `_base`: First GPIO in the ranger.
- `_size`: Amount of GPIOs to check starting from **base**.
- `_label`: Place to store the address of the label if the GPIO is requested.
  Set to NULL for unused GPIOs.

#### <a id="c-for_each_hwgpio"></a>`for_each_hwgpio()`

```c
for_each_hwgpio(_chip, _i, _label)
```

Iterates over all GPIOs for given chip.

**Parameters**

- `_chip`: Chip to iterate over.
- `_i`: Loop counter.
- `_label`: Place to store the address of the label if the GPIO is requested.
  Set to NULL for unused GPIOs.

#### <a id="c-for_each_requested_gpio_in_range"></a>`for_each_requested_gpio_in_range()`

```c
for_each_requested_gpio_in_range(_chip, _i, _base, _size, _label)
```

iterates over requested GPIOs in a given range

**Parameters**

- `_chip`: the chip to query
- `_i`: loop variable
- `_base`: first GPIO in the range
- `_size`: amount of GPIOs to check starting from **base**
- `_label`: label of current GPIO

#### <a id="c-gpiochip_add_data"></a>`gpiochip_add_data()`

```c
gpiochip_add_data(gc, data)
```

register a gpio_chip

**Parameters**

- `gc`: the chip to register, with gc->base initialized
- `data`: driver-private data associated with this chip

**Context**

potentially before irqs will work

**Description**

When [`gpiochip_add_data()`](#c-gpiochip_add_data) is called very early during boot, so that GPIOs
can be freely used, the gc->parent device must be registered before
the gpio framework's `arch_initcall()`.  Otherwise sysfs initialization
for GPIOs will fail rudely.

[`gpiochip_add_data()`](#c-gpiochip_add_data) must only be called after gpiolib initialization,
i.e. after `core_initcall()`.

If gc->base is negative, this requests dynamic assignment of
a range of valid GPIOs.

**Return**

A negative errno if the chip can't be registered, such as because the
gc->base is invalid or already associated with a different chip.
Otherwise it returns zero as a success code.

#### <a id="c-struct-gpio_pin_range"></a>`struct gpio_pin_range`

pin range controlled by a gpio chip

**Definition**

```c
struct gpio_pin_range {
    struct list_head node;
    struct pinctrl_dev *pctldev;
    struct pinctrl_gpio_range range;
};
```

**Members**

- `node`: list for maintaining set of pin ranges, used internally
- `pctldev`: pinctrl device which handles corresponding pins
- `range`: actual range of pins controlled by a gpio controller



#### <a id="c-gpio_to_desc"></a>`gpio_to_desc()`

```c
struct gpio_desc * gpio_to_desc(unsigned gpio)
```

Convert a GPIO number to its descriptor

**Parameters**

- `unsigned gpio`: global GPIO number

**Return**

The GPIO descriptor associated with the given GPIO, or `NULL` if no GPIO
with the given number exists in the system.

#### <a id="c-gpio_device_get_desc"></a>`gpio_device_get_desc()`

```c
struct gpio_desc * gpio_device_get_desc(struct gpio_device *gdev, unsigned int hwnum)
```

get the GPIO descriptor corresponding to the given hardware number for this GPIO device

**Parameters**

- `struct gpio_device *gdev`: GPIO device to get the descriptor from
- `unsigned int hwnum`: hardware number of the GPIO for this chip

**Return**

A pointer to the GPIO descriptor or `EINVAL` if no GPIO exists in the given
chip for the specified hardware number or `ENODEV` if the underlying chip
already vanished.

**Description**

The reference count of struct gpio_device is *NOT* increased like when the
GPIO is being requested for exclusive usage. It's up to the caller to make
sure the GPIO device will stay alive together with the descriptor returned
by this function.

#### <a id="c-desc_to_gpio"></a>`desc_to_gpio()`

```c
int desc_to_gpio(const struct gpio_desc *desc)
```

convert a GPIO descriptor to the integer namespace

**Parameters**

- `const struct gpio_desc *desc`: GPIO descriptor

**Description**

This should disappear in the future but is needed since we still
use GPIO numbers for error messages and sysfs nodes.

**Return**

The global GPIO number for the GPIO specified by its descriptor.

#### <a id="c-gpiod_hwgpio"></a>`gpiod_hwgpio()`

```c
int gpiod_hwgpio(const struct gpio_desc *desc)
```

Return the GPIO number of the passed descriptor relative to its chip.

**Parameters**

- `const struct gpio_desc *desc`: GPIO descriptor

**Return**

Hardware offset of the GPIO represented by the descriptor.

#### <a id="c-gpiod_to_chip"></a>`gpiod_to_chip()`

```c
struct gpio_chip * gpiod_to_chip(const struct gpio_desc *desc)
```

Return the GPIO chip to which a GPIO descriptor belongs

**Parameters**

- `const struct gpio_desc *desc`: descriptor to return the chip of

**Description**

*DEPRECATED*
This function is unsafe and should not be used. Using the chip address
without taking the SRCU read lock may result in dereferencing a dangling
pointer.

**Return**

Address of the GPIO chip backing this device.

#### <a id="c-gpiod_to_gpio_device"></a>`gpiod_to_gpio_device()`

```c
struct gpio_device * gpiod_to_gpio_device(struct gpio_desc *desc)
```

Return the GPIO device to which this descriptor belongs.

**Parameters**

- `struct gpio_desc *desc`: Descriptor for which to return the GPIO device.

**Description**

This *DOES NOT* increase the reference count of the GPIO device as it's
expected that the descriptor is requested and the users already holds a
reference to the device.

**Return**

Address of the GPIO device owning this descriptor.

#### <a id="c-gpio_device_get_base"></a>`gpio_device_get_base()`

```c
int gpio_device_get_base(struct gpio_device *gdev)
```

Get the base GPIO number allocated by this device

**Parameters**

- `struct gpio_device *gdev`: GPIO device

**Return**

First GPIO number in the global GPIO numberspace for this device.

#### <a id="c-gpio_device_get_label"></a>`gpio_device_get_label()`

```c
const char * gpio_device_get_label(struct gpio_device *gdev)
```

Get the label of this GPIO device

**Parameters**

- `struct gpio_device *gdev`: GPIO device

**Return**

Pointer to the string containing the GPIO device label. The string's
lifetime is tied to that of the underlying GPIO device.

#### <a id="c-gpio_device_get_chip"></a>`gpio_device_get_chip()`

```c
struct gpio_chip * gpio_device_get_chip(struct gpio_device *gdev)
```

Get the gpio_chip implementation of this GPIO device

**Parameters**

- `struct gpio_device *gdev`: GPIO device

**Return**

Address of the GPIO chip backing this device.

**Description**

*DEPRECATED*
Until we can get rid of all non-driver users of struct gpio_chip, we must
provide a way of retrieving the pointer to it from struct gpio_device. This
is *NOT* safe as the GPIO API is considered to be hot-unpluggable and the
chip can dissapear at any moment (unlike reference-counted struct
gpio_device).

Use at your own risk.

#### <a id="c-gpiod_is_equal"></a>`gpiod_is_equal()`

```c
bool gpiod_is_equal(const struct gpio_desc *desc, const struct gpio_desc *other)
```

Check if two GPIO descriptors refer to the same pin.

**Parameters**

- `const struct gpio_desc *desc`: Descriptor to compare.
- `const struct gpio_desc *other`: The second descriptor to compare against.

**Return**

True if the descriptors refer to the same physical pin. False otherwise.

#### <a id="c-gpiod_get_direction"></a>`gpiod_get_direction()`

```c
int gpiod_get_direction(struct gpio_desc *desc)
```

return the current direction of a GPIO

**Parameters**

- `struct gpio_desc *desc`: GPIO to get the direction of

**Return**

0 for output, 1 for input, or an error code in case of error.

**Description**

This function may sleep if [`gpiod_cansleep()`](#c-gpiod_cansleep) is true.

#### <a id="c-gpiochip_query_valid_mask"></a>`gpiochip_query_valid_mask()`

```c
const unsigned long * gpiochip_query_valid_mask(const struct gpio_chip *gc)
```

return the GPIO validity information

**Parameters**

- `const struct gpio_chip *gc`: gpio chip which validity information is queried

**Return**

bitmap representing valid GPIOs or NULL if all GPIOs are valid

**Description**

Some GPIO chips may support configurations where some of the pins aren't
available. These chips can have valid_mask set to represent the valid
GPIOs. This function can be used to retrieve this information.

#### <a id="c-gpiochip_get_data"></a>`gpiochip_get_data()`

```c
void * gpiochip_get_data(struct gpio_chip *gc)
```

get per-subdriver data for the chip

**Parameters**

- `struct gpio_chip *gc`: GPIO chip

**Return**

The per-subdriver data for the chip.

#### <a id="c-gpiochip_remove"></a>`gpiochip_remove()`

```c
void gpiochip_remove(struct gpio_chip *gc)
```

unregister a gpio_chip

**Parameters**

- `struct gpio_chip *gc`: the chip to unregister

**Description**

A gpio_chip with any GPIOs still requested may not be removed.

#### <a id="c-gpio_device_find"></a>`gpio_device_find()`

```c
struct gpio_device * gpio_device_find(const void *data, int (*match)(struct gpio_chip *gc, const void *data))
```

find a specific GPIO device

**Parameters**

- `const void *data`: data to pass to match function
- `int (*match)(struct gpio_chip *gc, const void *data)`: Callback function to check gpio_chip

**Return**

New reference to struct gpio_device.

**Description**

Similar to [`bus_find_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-bus_find_device). It returns a reference to a gpio_device as
determined by a user supplied **match** callback. The callback should return
0 if the device doesn't match and non-zero if it does. If the callback
returns non-zero, this function will return to the caller and not iterate
over any more gpio_devices.

The callback takes the GPIO chip structure as argument. During the execution
of the callback function the chip is protected from being freed. TODO: This
actually has yet to be implemented.

If the function returns non-NULL, the returned reference must be freed by
the caller using [`gpio_device_put()`](#c-gpio_device_put).

#### <a id="c-gpio_device_find_by_label"></a>`gpio_device_find_by_label()`

```c
struct gpio_device * gpio_device_find_by_label(const char *label)
```

wrapper around [`gpio_device_find()`](#c-gpio_device_find) finding the GPIO device by its backing chip's label

**Parameters**

- `const char *label`: Label to lookup

**Return**

Reference to the GPIO device or NULL. Reference must be released with
[`gpio_device_put()`](#c-gpio_device_put).

#### <a id="c-gpio_device_find_by_fwnode"></a>`gpio_device_find_by_fwnode()`

```c
struct gpio_device * gpio_device_find_by_fwnode(const struct fwnode_handle *fwnode)
```

wrapper around [`gpio_device_find()`](#c-gpio_device_find) finding the GPIO device by its fwnode

**Parameters**

- `const struct fwnode_handle *fwnode`: Firmware node to lookup

**Return**

Reference to the GPIO device or NULL. Reference must be released with
[`gpio_device_put()`](#c-gpio_device_put).

#### <a id="c-gpio_device_get"></a>`gpio_device_get()`

```c
struct gpio_device * gpio_device_get(struct gpio_device *gdev)
```

Increase the reference count of this GPIO device

**Parameters**

- `struct gpio_device *gdev`: GPIO device to increase the refcount for

**Return**

Pointer to **gdev**.

#### <a id="c-gpio_device_put"></a>`gpio_device_put()`

```c
void gpio_device_put(struct gpio_device *gdev)
```

Decrease the reference count of this GPIO device and possibly free all resources associated with it.

**Parameters**

- `struct gpio_device *gdev`: GPIO device to decrease the reference count for

#### <a id="c-gpio_device_to_device"></a>`gpio_device_to_device()`

```c
struct device * gpio_device_to_device(struct gpio_device *gdev)
```

Retrieve the address of the underlying struct device.

**Parameters**

- `struct gpio_device *gdev`: GPIO device for which to return the address.

**Description**

This does not increase the reference count of the GPIO device nor the
underlying struct device.

**Return**

Address of struct device backing this GPIO device.

#### <a id="c-gpiochip_irqchip_add_domain"></a>`gpiochip_irqchip_add_domain()`

```c
int gpiochip_irqchip_add_domain(struct gpio_chip *gc, struct irq_domain *domain)
```

adds an irqdomain to a gpiochip

**Parameters**

- `struct gpio_chip *gc`: the gpiochip to add the irqchip to
- `struct irq_domain *domain`: the irqdomain to add to the gpiochip

**Description**

This function adds an IRQ domain to the gpiochip.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiochip_generic_request"></a>`gpiochip_generic_request()`

```c
int gpiochip_generic_request(struct gpio_chip *gc, unsigned int offset)
```

request the gpio function for a pin

**Parameters**

- `struct gpio_chip *gc`: the gpiochip owning the GPIO
- `unsigned int offset`: the offset of the GPIO to request for GPIO function

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiochip_generic_free"></a>`gpiochip_generic_free()`

```c
void gpiochip_generic_free(struct gpio_chip *gc, unsigned int offset)
```

free the gpio function from a pin

**Parameters**

- `struct gpio_chip *gc`: the gpiochip to request the gpio function for
- `unsigned int offset`: the offset of the GPIO to free from GPIO function

#### <a id="c-gpiochip_generic_config"></a>`gpiochip_generic_config()`

```c
int gpiochip_generic_config(struct gpio_chip *gc, unsigned int offset, unsigned long config)
```

apply configuration for a pin

**Parameters**

- `struct gpio_chip *gc`: the gpiochip owning the GPIO
- `unsigned int offset`: the offset of the GPIO to apply the configuration
- `unsigned long config`: the configuration to be applied

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiochip_add_pingroup_range"></a>`gpiochip_add_pingroup_range()`

```c
int gpiochip_add_pingroup_range(struct gpio_chip *gc, struct pinctrl_dev *pctldev, unsigned int gpio_offset, const char *pin_group)
```

add a range for GPIO \<-> pin mapping

**Parameters**

- `struct gpio_chip *gc`: the gpiochip to add the range for
- `struct pinctrl_dev *pctldev`: the pin controller to map to
- `unsigned int gpio_offset`: the start offset in the current gpio_chip number space
- `const char *pin_group`: name of the pin group inside the pin controller

**Description**

Calling this function directly from a DeviceTree-supported
pinctrl driver is DEPRECATED. Please see Section 2.1 of
Documentation/devicetree/bindings/gpio/gpio.txt on how to
bind pinctrl and gpio drivers via the "gpio-ranges" property.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiochip_add_pin_range_with_pins"></a>`gpiochip_add_pin_range_with_pins()`

```c
int gpiochip_add_pin_range_with_pins(struct gpio_chip *gc, const char *pinctl_name, unsigned int gpio_offset, unsigned int pin_offset, unsigned int const *pins, unsigned int npins)
```

add a range for GPIO \<-> pin mapping

**Parameters**

- `struct gpio_chip *gc`: the gpiochip to add the range for
- `const char *pinctl_name`: the [`dev_name()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-dev_name) of the pin controller to map to
- `unsigned int gpio_offset`: the start offset in the current gpio_chip number space
- `unsigned int pin_offset`: the start offset in the pin controller number space
- `unsigned int const *pins`: the list of non consecutive pins to accumulate in this range (if not
  NULL, pin_offset is ignored by pinctrl core)
- `unsigned int npins`: the number of pins from the offset of each pin space (GPIO and
  pin controller) to accumulate in this range

**Description**

Calling this function directly from a DeviceTree-supported
pinctrl driver is DEPRECATED. Please see Section 2.1 of
Documentation/devicetree/bindings/gpio/gpio.txt on how to
bind pinctrl and gpio drivers via the "gpio-ranges" property.

**Return**

0 on success, or a negative errno on failure.

#### <a id="c-gpiochip_remove_pin_ranges"></a>`gpiochip_remove_pin_ranges()`

```c
void gpiochip_remove_pin_ranges(struct gpio_chip *gc)
```

remove all the GPIO \<-> pin mappings

**Parameters**

- `struct gpio_chip *gc`: the chip to remove all the mappings for

#### <a id="c-gpiochip_dup_line_label"></a>`gpiochip_dup_line_label()`

```c
char * gpiochip_dup_line_label(struct gpio_chip *gc, unsigned int offset)
```

Get a copy of the consumer label.

**Parameters**

- `struct gpio_chip *gc`: GPIO chip controlling this line.
- `unsigned int offset`: Hardware offset of the line.

**Return**

Pointer to a copy of the consumer label if the line is requested or NULL
if it's not. If a valid pointer was returned, it must be freed using
[`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree). In case of a memory allocation error, the function returns `ENOMEM`.

**Description**

Must not be called from atomic context.

#### <a id="c-gpiochip_request_own_desc"></a>`gpiochip_request_own_desc()`

```c
struct gpio_desc * gpiochip_request_own_desc(struct gpio_chip *gc, unsigned int hwnum, const char *label, enum gpio_lookup_flags lflags, enum gpiod_flags dflags)
```

Allow GPIO chip to request its own descriptor

**Parameters**

- `struct gpio_chip *gc`: GPIO chip
- `unsigned int hwnum`: hardware number of the GPIO for which to request the descriptor
- `const char *label`: label for the GPIO
- `enum gpio_lookup_flags lflags`: lookup flags for this GPIO or 0 if default, this can be used to
  specify things like line inversion semantics with the machine flags
  such as GPIO_OUT_LOW
- `enum gpiod_flags dflags`: descriptor request flags for this GPIO or 0 if default, this
  can be used to specify consumer semantics such as open drain

**Description**

Function allows GPIO chip drivers to request and use their own GPIO
descriptors via gpiolib API. Difference to `gpiod_request()` is that this
function will not increase reference count of the GPIO chip module. This
allows the GPIO chip module to be unloaded as needed (we assume that the
GPIO chip driver handles freeing the GPIOs it has requested).

**Return**

A pointer to the GPIO descriptor, or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-encoded negative error
code on failure.

#### <a id="c-gpiochip_free_own_desc"></a>`gpiochip_free_own_desc()`

```c
void gpiochip_free_own_desc(struct gpio_desc *desc)
```

Free GPIO requested by the chip driver

**Parameters**

- `struct gpio_desc *desc`: GPIO descriptor to free

**Description**

Function frees the given GPIO requested previously with
[`gpiochip_request_own_desc()`](#c-gpiochip_request_own_desc).

#### <a id="c-gpiod_direction_input"></a>`gpiod_direction_input()`

```c
int gpiod_direction_input(struct gpio_desc *desc)
```

set the GPIO direction to input

**Parameters**

- `struct gpio_desc *desc`: GPIO to set to input

**Description**

Set the direction of the passed GPIO to input, such as [`gpiod_get_value()`](#c-gpiod_get_value) can
be called safely on it.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_direction_output_raw"></a>`gpiod_direction_output_raw()`

```c
int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
```

set the GPIO direction to output

**Parameters**

- `struct gpio_desc *desc`: GPIO to set to output
- `int value`: initial output value of the GPIO

**Description**

Set the direction of the passed GPIO to output, such as [`gpiod_set_value()`](#c-gpiod_set_value) can
be called safely on it. The initial value of the output must be specified
as raw value on the physical line without regard for the ACTIVE_LOW status.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_direction_output"></a>`gpiod_direction_output()`

```c
int gpiod_direction_output(struct gpio_desc *desc, int value)
```

set the GPIO direction to output

**Parameters**

- `struct gpio_desc *desc`: GPIO to set to output
- `int value`: initial output value of the GPIO

**Description**

Set the direction of the passed GPIO to output, such as [`gpiod_set_value()`](#c-gpiod_set_value) can
be called safely on it. The initial value of the output must be specified
as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
account.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_enable_hw_timestamp_ns"></a>`gpiod_enable_hw_timestamp_ns()`

```c
int gpiod_enable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)
```

Enable hardware timestamp in nanoseconds.

**Parameters**

- `struct gpio_desc *desc`: GPIO to enable.
- `unsigned long flags`: Flags related to GPIO edge.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_disable_hw_timestamp_ns"></a>`gpiod_disable_hw_timestamp_ns()`

```c
int gpiod_disable_hw_timestamp_ns(struct gpio_desc *desc, unsigned long flags)
```

Disable hardware timestamp.

**Parameters**

- `struct gpio_desc *desc`: GPIO to disable.
- `unsigned long flags`: Flags related to GPIO edge, same value as used during enable call.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_set_config"></a>`gpiod_set_config()`

```c
int gpiod_set_config(struct gpio_desc *desc, unsigned long config)
```

sets **config** for a GPIO

**Parameters**

- `struct gpio_desc *desc`: descriptor of the GPIO for which to set the configuration
- `unsigned long config`: Same packed config format as generic pinconf

**Return**

0 on success, `-ENOTSUPP` if the controller doesn't support setting the
configuration.

#### <a id="c-gpiod_set_debounce"></a>`gpiod_set_debounce()`

```c
int gpiod_set_debounce(struct gpio_desc *desc, unsigned int debounce)
```

sets **debounce** time for a GPIO

**Parameters**

- `struct gpio_desc *desc`: descriptor of the GPIO for which to set debounce time
- `unsigned int debounce`: debounce time in microseconds

**Return**

0 on success, `-ENOTSUPP` if the controller doesn't support setting the
debounce time.

#### <a id="c-gpiod_is_active_low"></a>`gpiod_is_active_low()`

```c
int gpiod_is_active_low(const struct gpio_desc *desc)
```

test whether a GPIO is active-low or not

**Parameters**

- `const struct gpio_desc *desc`: the gpio descriptor to test

**Return**

1 if the GPIO is active-low, 0 otherwise.

#### <a id="c-gpiod_toggle_active_low"></a>`gpiod_toggle_active_low()`

```c
void gpiod_toggle_active_low(struct gpio_desc *desc)
```

toggle whether a GPIO is active-low or not

**Parameters**

- `struct gpio_desc *desc`: the gpio descriptor to change

#### <a id="c-gpiod_get_raw_value"></a>`gpiod_get_raw_value()`

```c
int gpiod_get_raw_value(const struct gpio_desc *desc)
```

return a gpio's raw value

**Parameters**

- `const struct gpio_desc *desc`: gpio whose value will be returned

**Return**

The GPIO's raw value, i.e. the value of the physical line disregarding
its ACTIVE_LOW status, or negative errno on failure.

**Description**

This function can be called from contexts where we cannot sleep, and will
complain if the GPIO chip functions potentially sleep.

#### <a id="c-gpiod_get_value"></a>`gpiod_get_value()`

```c
int gpiod_get_value(const struct gpio_desc *desc)
```

return a gpio's value

**Parameters**

- `const struct gpio_desc *desc`: gpio whose value will be returned

**Return**

The GPIO's logical value, i.e. taking the ACTIVE_LOW status into
account, or negative errno on failure.

**Description**

This function can be called from contexts where we cannot sleep, and will
complain if the GPIO chip functions potentially sleep.

#### <a id="c-gpiod_get_raw_array_value"></a>`gpiod_get_raw_array_value()`

```c
int gpiod_get_raw_array_value(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)
```

read raw values from an array of GPIOs

**Parameters**

- `unsigned int array_size`: number of elements in the descriptor array / value bitmap
- `struct gpio_desc **desc_array`: array of GPIO descriptors whose values will be read
- `struct gpio_array *array_info`: information on applicability of fast bitmap processing path
- `unsigned long *value_bitmap`: bitmap to store the read values

**Description**

Read the raw values of the GPIOs, i.e. the values of the physical lines
without regard for their ACTIVE_LOW status.

This function can be called from contexts where we cannot sleep,
and it will complain if the GPIO chip functions potentially sleep.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_get_array_value"></a>`gpiod_get_array_value()`

```c
int gpiod_get_array_value(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)
```

read values from an array of GPIOs

**Parameters**

- `unsigned int array_size`: number of elements in the descriptor array / value bitmap
- `struct gpio_desc **desc_array`: array of GPIO descriptors whose values will be read
- `struct gpio_array *array_info`: information on applicability of fast bitmap processing path
- `unsigned long *value_bitmap`: bitmap to store the read values

**Description**

Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
into account.

This function can be called from contexts where we cannot sleep,
and it will complain if the GPIO chip functions potentially sleep.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_set_raw_value"></a>`gpiod_set_raw_value()`

```c
int gpiod_set_raw_value(struct gpio_desc *desc, int value)
```

assign a gpio's raw value

**Parameters**

- `struct gpio_desc *desc`: gpio whose value will be assigned
- `int value`: value to assign

**Description**

Set the raw value of the GPIO, i.e. the value of its physical line without
regard for its ACTIVE_LOW status.

This function can be called from contexts where we cannot sleep, and will
complain if the GPIO chip functions potentially sleep.

**Return**

0 on success, negative error number on failure.

#### <a id="c-gpiod_set_value"></a>`gpiod_set_value()`

```c
int gpiod_set_value(struct gpio_desc *desc, int value)
```

assign a gpio's value

**Parameters**

- `struct gpio_desc *desc`: gpio whose value will be assigned
- `int value`: value to assign

**Description**

Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
OPEN_DRAIN and OPEN_SOURCE flags into account.

This function can be called from contexts where we cannot sleep, and will
complain if the GPIO chip functions potentially sleep.

**Return**

0 on success, negative error number on failure.

#### <a id="c-gpiod_set_raw_array_value"></a>`gpiod_set_raw_array_value()`

```c
int gpiod_set_raw_array_value(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)
```

assign values to an array of GPIOs

**Parameters**

- `unsigned int array_size`: number of elements in the descriptor array / value bitmap
- `struct gpio_desc **desc_array`: array of GPIO descriptors whose values will be assigned
- `struct gpio_array *array_info`: information on applicability of fast bitmap processing path
- `unsigned long *value_bitmap`: bitmap of values to assign

**Description**

Set the raw values of the GPIOs, i.e. the values of the physical lines
without regard for their ACTIVE_LOW status.

This function can be called from contexts where we cannot sleep, and will
complain if the GPIO chip functions potentially sleep.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_set_array_value"></a>`gpiod_set_array_value()`

```c
int gpiod_set_array_value(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)
```

assign values to an array of GPIOs

**Parameters**

- `unsigned int array_size`: number of elements in the descriptor array / value bitmap
- `struct gpio_desc **desc_array`: array of GPIO descriptors whose values will be assigned
- `struct gpio_array *array_info`: information on applicability of fast bitmap processing path
- `unsigned long *value_bitmap`: bitmap of values to assign

**Description**

Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
into account.

This function can be called from contexts where we cannot sleep, and will
complain if the GPIO chip functions potentially sleep.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_cansleep"></a>`gpiod_cansleep()`

```c
int gpiod_cansleep(const struct gpio_desc *desc)
```

report whether gpio value access may sleep

**Parameters**

- `const struct gpio_desc *desc`: gpio to check

**Return**

0 for non-sleepable, 1 for sleepable, or an error code in case of error.

#### <a id="c-gpiod_set_consumer_name"></a>`gpiod_set_consumer_name()`

```c
int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
```

set the consumer name for the descriptor

**Parameters**

- `struct gpio_desc *desc`: gpio to set the consumer name on
- `const char *name`: the new consumer name

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_is_shared"></a>`gpiod_is_shared()`

```c
bool gpiod_is_shared(const struct gpio_desc *desc)
```

check if this GPIO can be shared by multiple consumers

**Parameters**

- `const struct gpio_desc *desc`: GPIO to inspect

**Return**

True if this GPIO can be shared by multiple consumers at once. False if it's
a regular, exclusive GPIO.

**Note**

This function returning true does not mean that this GPIO is currently being
shared. It means the GPIO core has registered the fact that the firmware
configuration indicates that it can be shared by multiple consumers and is
in charge of arbitrating the access.

#### <a id="c-gpiod_to_irq"></a>`gpiod_to_irq()`

```c
int gpiod_to_irq(const struct gpio_desc *desc)
```

return the IRQ corresponding to a GPIO

**Parameters**

- `const struct gpio_desc *desc`: gpio whose IRQ will be returned (already requested)

**Return**

The IRQ corresponding to the passed GPIO, or an error code in case of error.

#### <a id="c-gpiochip_lock_as_irq"></a>`gpiochip_lock_as_irq()`

```c
int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)
```

lock a GPIO to be used as IRQ

**Parameters**

- `struct gpio_chip *gc`: the chip the GPIO to lock belongs to
- `unsigned int offset`: the offset of the GPIO to lock as IRQ

**Description**

This is used directly by GPIO drivers that want to lock down
a certain GPIO line to be used for IRQs.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiochip_unlock_as_irq"></a>`gpiochip_unlock_as_irq()`

```c
void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)
```

unlock a GPIO used as IRQ

**Parameters**

- `struct gpio_chip *gc`: the chip the GPIO to lock belongs to
- `unsigned int offset`: the offset of the GPIO to lock as IRQ

**Description**

This is used directly by GPIO drivers that want to indicate
that a certain GPIO is no longer used exclusively for IRQ.

#### <a id="c-gpiod_get_raw_value_cansleep"></a>`gpiod_get_raw_value_cansleep()`

```c
int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
```

return a gpio's raw value

**Parameters**

- `const struct gpio_desc *desc`: gpio whose value will be returned

**Return**

The GPIO's raw value, i.e. the value of the physical line disregarding
its ACTIVE_LOW status, or negative errno on failure.

**Description**

This function is to be called from contexts that can sleep.

#### <a id="c-gpiod_get_value_cansleep"></a>`gpiod_get_value_cansleep()`

```c
int gpiod_get_value_cansleep(const struct gpio_desc *desc)
```

return a gpio's value

**Parameters**

- `const struct gpio_desc *desc`: gpio whose value will be returned

**Return**

The GPIO's logical value, i.e. taking the ACTIVE_LOW status into
account, or negative errno on failure.

**Description**

This function is to be called from contexts that can sleep.

#### <a id="c-gpiod_get_raw_array_value_cansleep"></a>`gpiod_get_raw_array_value_cansleep()`

```c
int gpiod_get_raw_array_value_cansleep(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)
```

read raw values from an array of GPIOs

**Parameters**

- `unsigned int array_size`: number of elements in the descriptor array / value bitmap
- `struct gpio_desc **desc_array`: array of GPIO descriptors whose values will be read
- `struct gpio_array *array_info`: information on applicability of fast bitmap processing path
- `unsigned long *value_bitmap`: bitmap to store the read values

**Description**

Read the raw values of the GPIOs, i.e. the values of the physical lines
without regard for their ACTIVE_LOW status.

This function is to be called from contexts that can sleep.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_get_array_value_cansleep"></a>`gpiod_get_array_value_cansleep()`

```c
int gpiod_get_array_value_cansleep(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)
```

read values from an array of GPIOs

**Parameters**

- `unsigned int array_size`: number of elements in the descriptor array / value bitmap
- `struct gpio_desc **desc_array`: array of GPIO descriptors whose values will be read
- `struct gpio_array *array_info`: information on applicability of fast bitmap processing path
- `unsigned long *value_bitmap`: bitmap to store the read values

**Description**

Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
into account.

This function is to be called from contexts that can sleep.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_set_raw_value_cansleep"></a>`gpiod_set_raw_value_cansleep()`

```c
int gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
```

assign a gpio's raw value

**Parameters**

- `struct gpio_desc *desc`: gpio whose value will be assigned
- `int value`: value to assign

**Description**

Set the raw value of the GPIO, i.e. the value of its physical line without
regard for its ACTIVE_LOW status.

This function is to be called from contexts that can sleep.

**Return**

0 on success, negative error number on failure.

#### <a id="c-gpiod_set_value_cansleep"></a>`gpiod_set_value_cansleep()`

```c
int gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
```

assign a gpio's value

**Parameters**

- `struct gpio_desc *desc`: gpio whose value will be assigned
- `int value`: value to assign

**Description**

Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
account

This function is to be called from contexts that can sleep.

**Return**

0 on success, negative error number on failure.

#### <a id="c-gpiod_set_raw_array_value_cansleep"></a>`gpiod_set_raw_array_value_cansleep()`

```c
int gpiod_set_raw_array_value_cansleep(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)
```

assign values to an array of GPIOs

**Parameters**

- `unsigned int array_size`: number of elements in the descriptor array / value bitmap
- `struct gpio_desc **desc_array`: array of GPIO descriptors whose values will be assigned
- `struct gpio_array *array_info`: information on applicability of fast bitmap processing path
- `unsigned long *value_bitmap`: bitmap of values to assign

**Description**

Set the raw values of the GPIOs, i.e. the values of the physical lines
without regard for their ACTIVE_LOW status.

This function is to be called from contexts that can sleep.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_set_array_value_cansleep"></a>`gpiod_set_array_value_cansleep()`

```c
int gpiod_set_array_value_cansleep(unsigned int array_size, struct gpio_desc **desc_array, struct gpio_array *array_info, unsigned long *value_bitmap)
```

assign values to an array of GPIOs

**Parameters**

- `unsigned int array_size`: number of elements in the descriptor array / value bitmap
- `struct gpio_desc **desc_array`: array of GPIO descriptors whose values will be assigned
- `struct gpio_array *array_info`: information on applicability of fast bitmap processing path
- `unsigned long *value_bitmap`: bitmap of values to assign

**Description**

Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
into account.

This function is to be called from contexts that can sleep.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_add_lookup_table"></a>`gpiod_add_lookup_table()`

```c
void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
```

register GPIO device consumers

**Parameters**

- `struct gpiod_lookup_table *table`: table of consumers to register

#### <a id="c-gpiod_remove_lookup_table"></a>`gpiod_remove_lookup_table()`

```c
void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
```

unregister GPIO device consumers

**Parameters**

- `struct gpiod_lookup_table *table`: table of consumers to unregister

#### <a id="c-gpiod_add_hogs"></a>`gpiod_add_hogs()`

```c
void gpiod_add_hogs(struct gpiod_hog *hogs)
```

register a set of GPIO hogs from machine code

**Parameters**

- `struct gpiod_hog *hogs`: table of gpio hog entries with a zeroed sentinel at the end

#### <a id="c-fwnode_gpiod_get_index"></a>`fwnode_gpiod_get_index()`

```c
struct gpio_desc * fwnode_gpiod_get_index(struct fwnode_handle *fwnode, const char *con_id, int index, enum gpiod_flags flags, const char *label)
```

obtain a GPIO from firmware node

**Parameters**

- `struct fwnode_handle *fwnode`: handle of the firmware node
- `const char *con_id`: function within the GPIO consumer
- `int index`: index of the GPIO to obtain for the consumer
- `enum gpiod_flags flags`: GPIO initialization flags
- `const char *label`: label to attach to the requested GPIO

**Description**

This function can be used for drivers that get their configuration
from opaque firmware.

The function properly finds the corresponding GPIO using whatever is the
underlying firmware interface and then makes sure that the GPIO
descriptor is requested before it is returned to the caller.

In case of error an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) is returned.

**Return**

On successful request the GPIO pin is configured in accordance with
provided **flags**.

#### <a id="c-gpiod_count"></a>`gpiod_count()`

```c
int gpiod_count(struct device *dev, const char *con_id)
```

return the number of GPIOs associated with a device / function

**Parameters**

- `struct device *dev`: GPIO consumer, can be NULL for system-global GPIOs
- `const char *con_id`: function within the GPIO consumer

**Return**

The number of GPIOs associated with a device / function or -ENOENT if no
GPIO has been assigned to the requested function.

#### <a id="c-gpiod_get"></a>`gpiod_get()`

```c
struct gpio_desc * gpiod_get(struct device *dev, const char *con_id, enum gpiod_flags flags)
```

obtain a GPIO for a given GPIO function

**Parameters**

- `struct device *dev`: GPIO consumer, can be NULL for system-global GPIOs
- `const char *con_id`: function within the GPIO consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Return**

The GPIO descriptor corresponding to the function **con_id** of device
dev, -ENOENT if no GPIO has been assigned to the requested function, or
another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire the GPIO.

#### <a id="c-gpiod_get_optional"></a>`gpiod_get_optional()`

```c
struct gpio_desc * gpiod_get_optional(struct device *dev, const char *con_id, enum gpiod_flags flags)
```

obtain an optional GPIO for a given GPIO function

**Parameters**

- `struct device *dev`: GPIO consumer, can be NULL for system-global GPIOs
- `const char *con_id`: function within the GPIO consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

This is equivalent to [`gpiod_get()`](#c-gpiod_get), except that when no GPIO was assigned to
the requested function it will return NULL. This is convenient for drivers
that need to handle optional GPIOs.

**Return**

The GPIO descriptor corresponding to the function **con_id** of device
dev, NULL if no GPIO has been assigned to the requested function, or
another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire the GPIO.

#### <a id="c-gpiod_get_index"></a>`gpiod_get_index()`

```c
struct gpio_desc * gpiod_get_index(struct device *dev, const char *con_id, unsigned int idx, enum gpiod_flags flags)
```

obtain a GPIO from a multi-index GPIO function

**Parameters**

- `struct device *dev`: GPIO consumer, can be NULL for system-global GPIOs
- `const char *con_id`: function within the GPIO consumer
- `unsigned int idx`: index of the GPIO to obtain in the consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

This variant of [`gpiod_get()`](#c-gpiod_get) allows to access GPIOs other than the first
defined one for functions that define several GPIOs.

**Return**

A valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
requested function and/or index, or another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error
occurred while trying to acquire the GPIO.

#### <a id="c-gpiod_get_index_optional"></a>`gpiod_get_index_optional()`

```c
struct gpio_desc * gpiod_get_index_optional(struct device *dev, const char *con_id, unsigned int index, enum gpiod_flags flags)
```

obtain an optional GPIO from a multi-index GPIO function

**Parameters**

- `struct device *dev`: GPIO consumer, can be NULL for system-global GPIOs
- `const char *con_id`: function within the GPIO consumer
- `unsigned int index`: index of the GPIO to obtain in the consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

This is equivalent to [`gpiod_get_index()`](#c-gpiod_get_index), except that when no GPIO with the
specified index was assigned to the requested function it will return NULL.
This is convenient for drivers that need to handle optional GPIOs.

**Return**

A valid GPIO descriptor, NULL if no GPIO has been assigned to the
requested function and/or index, or another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error
occurred while trying to acquire the GPIO.

#### <a id="c-gpiod_get_array"></a>`gpiod_get_array()`

```c
struct gpio_descs * gpiod_get_array(struct device *dev, const char *con_id, enum gpiod_flags flags)
```

obtain multiple GPIOs from a multi-index GPIO function

**Parameters**

- `struct device *dev`: GPIO consumer, can be NULL for system-global GPIOs
- `const char *con_id`: function within the GPIO consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

This function acquires all the GPIOs defined under a given function.

**Return**

The GPIO descriptors corresponding to the function **con_id** of device
dev, -ENOENT if no GPIO has been assigned to the requested function,
or another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire
the GPIOs.

#### <a id="c-gpiod_get_array_optional"></a>`gpiod_get_array_optional()`

```c
struct gpio_descs * gpiod_get_array_optional(struct device *dev, const char *con_id, enum gpiod_flags flags)
```

obtain multiple GPIOs from a multi-index GPIO function

**Parameters**

- `struct device *dev`: GPIO consumer, can be NULL for system-global GPIOs
- `const char *con_id`: function within the GPIO consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

This is equivalent to [`gpiod_get_array()`](#c-gpiod_get_array), except that when no GPIO was
assigned to the requested function it will return NULL.

**Return**

The GPIO descriptors corresponding to the function **con_id** of device
dev, NULL if no GPIO has been assigned to the requested function,
or another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire
the GPIOs.

#### <a id="c-gpiod_put"></a>`gpiod_put()`

```c
void gpiod_put(struct gpio_desc *desc)
```

dispose of a GPIO descriptor

**Parameters**

- `struct gpio_desc *desc`: GPIO descriptor to dispose of

**Description**

No descriptor can be used after [`gpiod_put()`](#c-gpiod_put) has been called on it.

#### <a id="c-gpiod_put_array"></a>`gpiod_put_array()`

```c
void gpiod_put_array(struct gpio_descs *descs)
```

dispose of multiple GPIO descriptors

**Parameters**

- `struct gpio_descs *descs`: struct gpio_descs containing an array of descriptors


<a id="rst-acpi-support"></a>

## ACPI support


#### <a id="c-acpi_gpio_get_io_resource"></a>`acpi_gpio_get_io_resource()`

```c
bool acpi_gpio_get_io_resource(struct acpi_resource *ares, struct acpi_resource_gpio **agpio)
```

Fetch details of an ACPI resource if it is a GPIO I/O resource or return False if not.

**Parameters**

- `struct acpi_resource *ares`: Pointer to the ACPI resource to fetch
- `struct acpi_resource_gpio **agpio`: Pointer to a `struct acpi_resource_gpio` to store the output pointer

**Return**

`true` if GpioIo resource is found, `false` otherwise.

#### <a id="c-acpi_gpiochip_request_interrupts"></a>`acpi_gpiochip_request_interrupts()`

```c
void acpi_gpiochip_request_interrupts(struct gpio_chip *chip)
```

Register isr for gpio chip ACPI events

**Parameters**

- `struct gpio_chip *chip`: GPIO chip

**Description**

ACPI5 platforms can use GPIO signaled ACPI events. These GPIO interrupts are
handled by ACPI event methods which need to be called from the GPIO
chip's interrupt handler. [`acpi_gpiochip_request_interrupts()`](#c-acpi_gpiochip_request_interrupts) finds out which
GPIO pins have ACPI event methods and assigns interrupt handlers that calls
the ACPI event methods for those pins.

#### <a id="c-acpi_gpiochip_free_interrupts"></a>`acpi_gpiochip_free_interrupts()`

```c
void acpi_gpiochip_free_interrupts(struct gpio_chip *chip)
```

Free GPIO ACPI event interrupts.

**Parameters**

- `struct gpio_chip *chip`: GPIO chip

**Description**

Free interrupts associated with GPIO ACPI event method for the given
GPIO chip.

#### <a id="c-acpi_dev_gpio_irq_wake_get_by"></a>`acpi_dev_gpio_irq_wake_get_by()`

```c
int acpi_dev_gpio_irq_wake_get_by(struct acpi_device *adev, const char *con_id, int index, bool *wake_capable)
```

Find GpioInt and translate it to Linux IRQ number

**Parameters**

- `struct acpi_device *adev`: pointer to a ACPI device to get IRQ from
- `const char *con_id`: optional name of GpioInt resource
- `int index`: index of GpioInt resource (starting from `0`)
- `bool *wake_capable`: Set to true if the IRQ is wake capable

**Description**

If the device has one or more GpioInt resources, this function can be
used to translate from the GPIO offset in the resource to the Linux IRQ
number.

The function is idempotent, though each time it runs it will configure GPIO
pin direction according to the flags in GpioInt resource.

The function takes optional **con_id** parameter. If the resource has
a **con_id** in a property, then only those will be taken into account.

The GPIO is considered wake capable if the GpioInt resource specifies
SharedAndWake or ExclusiveAndWake.

**Return**

Linux IRQ number (> 0) on success, negative errno on failure.


<a id="rst-device-tree-support"></a>

## Device tree support


#### <a id="c-of_get_named_gpio"></a>`of_get_named_gpio()`

```c
int of_get_named_gpio(const struct device_node *np, const char *propname, int index)
```

Get a GPIO number to use with GPIO API

**Parameters**

- `const struct device_node *np`: device node to get GPIO from
- `const char *propname`: Name of property containing gpio specifier(s)
- `int index`: index of the GPIO

**Description**

**DEPRECATED** This function is deprecated and must not be used in new code.

**Return**

GPIO number to use with Linux generic GPIO API, or one of the errno
value on the error condition.


<a id="rst-device-managed-api"></a>

## Device-managed API


#### <a id="c-devm_gpiod_get"></a>`devm_gpiod_get()`

```c
struct gpio_desc * devm_gpiod_get(struct device *dev, const char *con_id, enum gpiod_flags flags)
```

Resource-managed [`gpiod_get()`](#c-gpiod_get)

**Parameters**

- `struct device *dev`: GPIO consumer
- `const char *con_id`: function within the GPIO consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

Managed [`gpiod_get()`](#c-gpiod_get). GPIO descriptors returned from this function are
automatically disposed on driver detach. See [`gpiod_get()`](#c-gpiod_get) for detailed
information about behavior and return values.

**Return**

The GPIO descriptor corresponding to the function **con_id** of device
dev, `-ENOENT` if no GPIO has been assigned to the requested function, or
another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire the GPIO.

#### <a id="c-devm_gpiod_get_optional"></a>`devm_gpiod_get_optional()`

```c
struct gpio_desc * devm_gpiod_get_optional(struct device *dev, const char *con_id, enum gpiod_flags flags)
```

Resource-managed [`gpiod_get_optional()`](#c-gpiod_get_optional)

**Parameters**

- `struct device *dev`: GPIO consumer
- `const char *con_id`: function within the GPIO consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

Managed [`gpiod_get_optional()`](#c-gpiod_get_optional). GPIO descriptors returned from this function
are automatically disposed on driver detach. See [`gpiod_get_optional()`](#c-gpiod_get_optional) for
detailed information about behavior and return values.

**Return**

The GPIO descriptor corresponding to the function **con_id** of device
dev, NULL if no GPIO has been assigned to the requested function, or
another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire the GPIO.

#### <a id="c-devm_gpiod_get_index"></a>`devm_gpiod_get_index()`

```c
struct gpio_desc * devm_gpiod_get_index(struct device *dev, const char *con_id, unsigned int idx, enum gpiod_flags flags)
```

Resource-managed [`gpiod_get_index()`](#c-gpiod_get_index)

**Parameters**

- `struct device *dev`: GPIO consumer
- `const char *con_id`: function within the GPIO consumer
- `unsigned int idx`: index of the GPIO to obtain in the consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

Managed [`gpiod_get_index()`](#c-gpiod_get_index). GPIO descriptors returned from this function are
automatically disposed on driver detach. See [`gpiod_get_index()`](#c-gpiod_get_index) for detailed
information about behavior and return values.

**Return**

The GPIO descriptor corresponding to the function **con_id** of device
dev, `-ENOENT` if no GPIO has been assigned to the requested function, or
another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire the GPIO.

#### <a id="c-devm_fwnode_gpiod_get_index"></a>`devm_fwnode_gpiod_get_index()`

```c
struct gpio_desc * devm_fwnode_gpiod_get_index(struct device *dev, struct fwnode_handle *fwnode, const char *con_id, int index, enum gpiod_flags flags, const char *label)
```

get a GPIO descriptor from a given node

**Parameters**

- `struct device *dev`: GPIO consumer
- `struct fwnode_handle *fwnode`: firmware node containing GPIO reference
- `const char *con_id`: function within the GPIO consumer
- `int index`: index of the GPIO to obtain in the consumer
- `enum gpiod_flags flags`: GPIO initialization flags
- `const char *label`: label to attach to the requested GPIO

**Description**

GPIO descriptors returned from this function are automatically disposed on
driver detach.

**Return**

The GPIO descriptor corresponding to the function **con_id** of device
dev, `-ENOENT` if no GPIO has been assigned to the requested function, or
another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire the GPIO.

#### <a id="c-devm_gpiod_get_index_optional"></a>`devm_gpiod_get_index_optional()`

```c
struct gpio_desc * devm_gpiod_get_index_optional(struct device *dev, const char *con_id, unsigned int index, enum gpiod_flags flags)
```

Resource-managed [`gpiod_get_index_optional()`](#c-gpiod_get_index_optional)

**Parameters**

- `struct device *dev`: GPIO consumer
- `const char *con_id`: function within the GPIO consumer
- `unsigned int index`: index of the GPIO to obtain in the consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

Managed [`gpiod_get_index_optional()`](#c-gpiod_get_index_optional). GPIO descriptors returned from this
function are automatically disposed on driver detach. See
[`gpiod_get_index_optional()`](#c-gpiod_get_index_optional) for detailed information about behavior and
return values.

**Return**

The GPIO descriptor corresponding to the function **con_id** of device
dev, `NULL` if no GPIO has been assigned to the requested function, or
another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire the GPIO.

#### <a id="c-devm_gpiod_get_array"></a>`devm_gpiod_get_array()`

```c
struct gpio_descs * devm_gpiod_get_array(struct device *dev, const char *con_id, enum gpiod_flags flags)
```

Resource-managed [`gpiod_get_array()`](#c-gpiod_get_array)

**Parameters**

- `struct device *dev`: GPIO consumer
- `const char *con_id`: function within the GPIO consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

Managed [`gpiod_get_array()`](#c-gpiod_get_array). GPIO descriptors returned from this function are
automatically disposed on driver detach. See [`gpiod_get_array()`](#c-gpiod_get_array) for detailed
information about behavior and return values.

**Return**

The GPIO descriptors corresponding to the function **con_id** of device
dev, `-ENOENT` if no GPIO has been assigned to the requested function,
or another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire
the GPIOs.

#### <a id="c-devm_gpiod_get_array_optional"></a>`devm_gpiod_get_array_optional()`

```c
struct gpio_descs * devm_gpiod_get_array_optional(struct device *dev, const char *con_id, enum gpiod_flags flags)
```

Resource-managed [`gpiod_get_array_optional()`](#c-gpiod_get_array_optional)

**Parameters**

- `struct device *dev`: GPIO consumer
- `const char *con_id`: function within the GPIO consumer
- `enum gpiod_flags flags`: optional GPIO initialization flags

**Description**

Managed [`gpiod_get_array_optional()`](#c-gpiod_get_array_optional). GPIO descriptors returned from this
function are automatically disposed on driver detach.
See [`gpiod_get_array_optional()`](#c-gpiod_get_array_optional) for detailed information about behavior and
return values.

**Return**

The GPIO descriptors corresponding to the function **con_id** of device
dev, `NULL` if no GPIO has been assigned to the requested function,
or another [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) code if an error occurred while trying to acquire
the GPIOs.

#### <a id="c-devm_gpiod_put"></a>`devm_gpiod_put()`

```c
void devm_gpiod_put(struct device *dev, struct gpio_desc *desc)
```

Resource-managed [`gpiod_put()`](#c-gpiod_put)

**Parameters**

- `struct device *dev`: GPIO consumer
- `struct gpio_desc *desc`: GPIO descriptor to dispose of

**Description**

Dispose of a GPIO descriptor obtained with [`devm_gpiod_get()`](#c-devm_gpiod_get) or
[`devm_gpiod_get_index()`](#c-devm_gpiod_get_index). Normally this function will not be called as the GPIO
will be disposed of by the resource management code.

#### <a id="c-devm_gpiod_unhinge"></a>`devm_gpiod_unhinge()`

```c
void devm_gpiod_unhinge(struct device *dev, struct gpio_desc *desc)
```

Remove resource management from a gpio descriptor

**Parameters**

- `struct device *dev`: GPIO consumer
- `struct gpio_desc *desc`: GPIO descriptor to remove resource management from

**Description**

*DEPRECATED*
This function should not be used. It's been provided as a workaround for
resource ownership issues in the regulator framework and should be replaced
with a better solution.

Remove resource management from a GPIO descriptor. This is needed when
you want to hand over lifecycle management of a descriptor to another
mechanism.

#### <a id="c-devm_gpiod_put_array"></a>`devm_gpiod_put_array()`

```c
void devm_gpiod_put_array(struct device *dev, struct gpio_descs *descs)
```

Resource-managed [`gpiod_put_array()`](#c-gpiod_put_array)

**Parameters**

- `struct device *dev`: GPIO consumer
- `struct gpio_descs *descs`: GPIO descriptor array to dispose of

**Description**

Dispose of an array of GPIO descriptors obtained with [`devm_gpiod_get_array()`](#c-devm_gpiod_get_array).
Normally this function will not be called as the GPIOs will be disposed of
by the resource management code.

#### <a id="c-devm_gpiochip_add_data_with_key"></a>`devm_gpiochip_add_data_with_key()`

```c
int devm_gpiochip_add_data_with_key(struct device *dev, struct gpio_chip *gc, void *data, struct lock_class_key *lock_key, struct lock_class_key *request_key)
```

Resource managed `gpiochip_add_data_with_key()`

**Parameters**

- `struct device *dev`: pointer to the device that gpio_chip belongs to.
- `struct gpio_chip *gc`: the GPIO chip to register
- `void *data`: driver-private data associated with this chip
- `struct lock_class_key *lock_key`: lockdep class for IRQ lock
- `struct lock_class_key *request_key`: lockdep class for IRQ request

**Context**

potentially before irqs will work

**Description**

The gpio chip automatically be released when the device is unbound.

**Return**

A negative errno if the chip can't be registered, such as because the
gc->base is invalid or already associated with a different chip.
Otherwise it returns zero as a success code.


<a id="rst-sysfs-helpers"></a>

## sysfs helpers


#### <a id="c-gpiod_export"></a>`gpiod_export()`

```c
int gpiod_export(struct gpio_desc *desc, bool direction_may_change)
```

export a GPIO through sysfs

**Parameters**

- `struct gpio_desc *desc`: GPIO to make available, already requested
- `bool direction_may_change`: true if userspace may change GPIO direction

**Context**

arch_initcall or later

**Description**

When drivers want to make a GPIO accessible to userspace after they
have requested it -- perhaps while debugging, or as part of their
public interface -- they may use this routine.  If the GPIO can
change direction (some can't) and the caller allows it, userspace
will see "direction" sysfs attribute which may be used to change
the gpio's direction.  A "value" attribute will always be provided.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_export_link"></a>`gpiod_export_link()`

```c
int gpiod_export_link(struct device *dev, const char *name, struct gpio_desc *desc)
```

create a sysfs link to an exported GPIO node

**Parameters**

- `struct device *dev`: device under which to create symlink
- `const char *name`: name of the symlink
- `struct gpio_desc *desc`: GPIO to create symlink to, already exported

**Description**

Set up a symlink from /sys/.../dev/name to /sys/class/gpio/gpioN
node. Caller is responsible for unlinking.

**Return**

0 on success, or negative errno on failure.

#### <a id="c-gpiod_unexport"></a>`gpiod_unexport()`

```c
void gpiod_unexport(struct gpio_desc *desc)
```

reverse effect of [`gpiod_export()`](#c-gpiod_export)

**Parameters**

- `struct gpio_desc *desc`: GPIO to make unavailable

**Description**

This is implicit on `gpiod_free()`.

---

# GPIO Mappings

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> This document explains how GPIOs can be assigned to given devices and functions.

<a id="rst-gpio-mappings"></a>

This document explains how GPIOs can be assigned to given devices and functions.

All platforms can enable the GPIO library, but if the platform strictly requires GPIO functionality to be present, it needs to select GPIOLIB from its Kconfig. Then, how GPIOs are mapped depends on what the platform uses to describe its hardware layout. Currently, mappings can be defined through device tree, ACPI, and platform data.

<a id="rst-device-tree"></a>

## Device Tree

GPIOs can easily be mapped to devices and functions in the device tree. The exact way to do it depends on the GPIO controller providing the GPIOs, see the device tree bindings for your controller.

GPIOs mappings are defined in the consumer device's node, in a property named &lt;function&gt;-gpios, where &lt;function&gt; is the function the driver will request through gpiod_get(). For example:



```text
foo_device {
        compatible = "acme,foo";
        ...
        led-gpios = <&gpio 15 GPIO_ACTIVE_HIGH>, /* red */
                    <&gpio 16 GPIO_ACTIVE_HIGH>, /* green */
                    <&gpio 17 GPIO_ACTIVE_HIGH>; /* blue */

        power-gpios = <&gpio 1 GPIO_ACTIVE_LOW>;
};
```

Properties named &lt;function&gt;-gpio are also considered valid and old bindings use it but are only supported for compatibility reasons and should not be used for newer bindings since it has been deprecated.

This property will make GPIOs 15, 16 and 17 available to the driver under the "led" function, and GPIO 1 as the "power" GPIO:



```text
struct gpio_desc *red, *green, *blue, *power;

red = gpiod_get_index(dev, "led", 0, GPIOD_OUT_HIGH);
green = gpiod_get_index(dev, "led", 1, GPIOD_OUT_HIGH);
blue = gpiod_get_index(dev, "led", 2, GPIOD_OUT_HIGH);

power = gpiod_get(dev, "power", GPIOD_OUT_HIGH);
```

The led GPIOs will be active high, while the power GPIO will be active low (i.e. gpiod_is_active_low(power) will be true).

The second parameter of the gpiod_get() functions, the con_id string, has to be the &lt;function&gt;-prefix of the GPIO suffixes ("gpios" or "gpio", automatically looked up by the gpiod functions internally) used in the device tree. With above "led-gpios" example, use the prefix without the "-" as con_id parameter: "led".

Internally, the GPIO subsystem prefixes the GPIO suffix ("gpios" or "gpio") with the string passed in con_id to get the resulting string (`snprintf(... "%s-%s", con_id, gpio_suffixes[]`).

<a id="rst-acpi"></a>

## ACPI

ACPI also supports function names for GPIOs in a similar fashion to DT. The above DT example can be converted to an equivalent ACPI description with the help of \_DSD (Device Specific Data), introduced in ACPI 5.1:



```text
Device (FOO) {
        Name (_CRS, ResourceTemplate () {
                GpioIo (Exclusive, PullUp, 0, 0, IoRestrictionOutputOnly,
                        "\\_SB.GPI0", 0, ResourceConsumer) { 15 } // red
                GpioIo (Exclusive, PullUp, 0, 0, IoRestrictionOutputOnly,
                        "\\_SB.GPI0", 0, ResourceConsumer) { 16 } // green
                GpioIo (Exclusive, PullUp, 0, 0, IoRestrictionOutputOnly,
                        "\\_SB.GPI0", 0, ResourceConsumer) { 17 } // blue
                GpioIo (Exclusive, PullNone, 0, 0, IoRestrictionOutputOnly,
                        "\\_SB.GPI0", 0, ResourceConsumer) { 1 } // power
        })

        Name (_DSD, Package () {
                ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"),
                Package () {
                        Package () {
                                "led-gpios",
                                Package () {
                                        ^FOO, 0, 0, 1,
                                        ^FOO, 1, 0, 1,
                                        ^FOO, 2, 0, 1,
                                }
                        },
                        Package () { "power-gpios", Package () { ^FOO, 3, 0, 0 } },
                }
        })
}
```

For more information about the ACPI GPIO bindings see [Documentation/firmware-guide/acpi/gpio-properties.rst](/kernel/hardware/firmware-guide/acpi/gpio-properties.md).

<a id="rst-software-nodes"></a>

## Software Nodes

Software nodes allow board-specific code to construct an in-memory, device-tree-like structure using struct software_node and struct property_entry. This structure can then be associated with a platform device, allowing drivers to use the standard device properties API to query configuration, just as they would on an ACPI or device tree system.

Software-node-backed GPIOs are described using the `PROPERTY_ENTRY_GPIO()` macro, which ties a software node representing the GPIO controller with consumer device. It allows consumers to use regular gpiolib APIs, such as gpiod_get(), gpiod_get_optional().

The software node representing a GPIO controller need not be attached to the GPIO controller device. The only requirement is that the node must be registered and its name must match the GPIO controller's label.

For example, here is how to describe a single GPIO-connected LED. This is an alternative to using platform_data on legacy systems.



```c
#include <linux/property.h>
#include <linux/gpio/machine.h>
#include <linux/gpio/property.h>

/*
 * 1. Define a node for the GPIO controller. Its .name must match the
 *    controller's label.
 */
static const struct software_node gpio_controller_node = {
        .name = "gpio-foo",
};

/* 2. Define the properties for the LED device. */
static const struct property_entry led_device_props[] = {
        PROPERTY_ENTRY_STRING("label", "myboard:green:status"),
        PROPERTY_ENTRY_STRING("linux,default-trigger", "heartbeat"),
        PROPERTY_ENTRY_GPIO("gpios", &gpio_controller_node, 42, GPIO_ACTIVE_HIGH),
        { }
};

/* 3. Define the software node for the LED device. */
static const struct software_node led_device_swnode = {
        .name = "status-led",
        .properties = led_device_props,
};

/*
 * 4. Register the software nodes and the platform device.
 */
const struct software_node *swnodes[] = {
        &gpio_controller_node,
        &led_device_swnode,
        NULL
};
software_node_register_node_group(swnodes);

// Then register a platform_device for "leds-gpio" and associate
// it with &led_device_swnode via .fwnode.
```

For a complete guide on converting board files to use software nodes, see [Documentation/driver-api/gpio/legacy-boards.rst](/kernel/hardware/driver-api/gpio/legacy-boards.md).

<a id="rst-platform-data"></a>

## Platform Data

Finally, GPIOs can be bound to devices and functions using platform data. Board files that desire to do so need to include the following header:



```text
#include <linux/gpio/machine.h>
```

GPIOs are mapped by the means of tables of lookups, containing instances of the gpiod_lookup structure. Two macros are defined to help declaring such mappings:



```text
GPIO_LOOKUP(key, chip_hwnum, con_id, flags)
GPIO_LOOKUP_IDX(key, chip_hwnum, con_id, idx, flags)
```

where

> - key is either the label of the gpiod_chip instance providing the GPIO, or the GPIO line name
>
> - chip_hwnum is the hardware number of the GPIO within the chip, or U16_MAX to indicate that key is a GPIO line name
>
> - - **con_id is the name of the GPIO function from the device point of view. It**
>
>     can be NULL, in which case it will match any function.
>
> - idx is the index of the GPIO within the function.
>
> - - **flags is defined to specify the following properties:**
>
>     - GPIO_ACTIVE_HIGH      - GPIO line is active high
>
>     - GPIO_ACTIVE_LOW       - GPIO line is active low
>
>     - GPIO_OPEN_DRAIN       - GPIO line is set up as open drain
>
>     - GPIO_OPEN_SOURCE      - GPIO line is set up as open source
>
>     - - **GPIO_PERSISTENT       - GPIO line is persistent during**
>
>         suspend/resume and maintains its value
>
>     - - **GPIO_TRANSITORY       - GPIO line is transitory and may loose its**
>
>         electrical state during suspend/resume

In the future, these flags might be extended to support more properties.

- **Note that:**

  1. GPIO line names are not guaranteed to be globally unique, so the first match found will be used.

  2. GPIO_LOOKUP() is just a shortcut to GPIO_LOOKUP_IDX() where idx = 0.

A lookup table can then be defined as follows, with an empty entry defining its end. The 'dev_id' field of the table is the identifier of the device that will make use of these GPIOs. It can be NULL, in which case it will be matched for calls to gpiod_get() with a NULL device.



```c
struct gpiod_lookup_table gpios_table = {
        .dev_id = "foo.0",
        .table = {
                GPIO_LOOKUP_IDX("gpio.0", 15, "led", 0, GPIO_ACTIVE_HIGH),
                GPIO_LOOKUP_IDX("gpio.0", 16, "led", 1, GPIO_ACTIVE_HIGH),
                GPIO_LOOKUP_IDX("gpio.0", 17, "led", 2, GPIO_ACTIVE_HIGH),
                GPIO_LOOKUP("gpio.0", 1, "power", GPIO_ACTIVE_LOW),
                { },
        },
};
```

And the table can be added by the board code as follows:



```text
gpiod_add_lookup_table(&gpios_table);
```

The driver controlling "foo.0" will then be able to obtain its GPIOs as follows:



```text
struct gpio_desc *red, *green, *blue, *power;

red = gpiod_get_index(dev, "led", 0, GPIOD_OUT_HIGH);
green = gpiod_get_index(dev, "led", 1, GPIOD_OUT_HIGH);
blue = gpiod_get_index(dev, "led", 2, GPIOD_OUT_HIGH);

power = gpiod_get(dev, "power", GPIOD_OUT_HIGH);
```

Since the "led" GPIOs are mapped as active-high, this example will switch their signals to 1, i.e. enabling the LEDs. And for the "power" GPIO, which is mapped as active-low, its actual signal will be 0 after this code. Contrary to the legacy integer GPIO interface, the active-low property is handled during mapping and is thus transparent to GPIO consumers.

A set of functions such as gpiod_set_value() is available to work with the new descriptor-oriented interface.

Boards using platform data can also hog GPIO lines by defining GPIO hog tables.



```c
struct gpiod_hog gpio_hog_table[] = {
        GPIO_HOG("gpio.0", 10, "foo", GPIO_ACTIVE_LOW, GPIOD_OUT_HIGH),
        { }
};
```

And the table can be added to the board code as follows:



```text
gpiod_add_hogs(gpio_hog_table);
```

The line will be hogged as soon as the gpiochip is created or - in case the chip was created earlier - when the hog table is registered.

<a id="rst-arrays-of-pins"></a>

## Arrays of pins

In addition to requesting pins belonging to a function one by one, a device may also request an array of pins assigned to the function.  The way those pins are mapped to the device determines if the array qualifies for fast bitmap processing.  If yes, a bitmap is passed over get/set array functions directly between a caller and a respective .get/set_multiple() callback of a GPIO chip.

In order to qualify for fast bitmap processing, the array must meet the following requirements:

- pin hardware number of array member 0 must also be 0,

- pin hardware numbers of consecutive array members which belong to the same chip as member 0 does must also match their array indexes.

Otherwise fast bitmap processing path is not used in order to avoid consecutive pins which belong to the same chip but are not in hardware order being processed separately.

If the array applies for fast bitmap processing path, pins which belong to different chips than member 0 does, as well as those with indexes different from their hardware pin numbers, are excluded from the fast path, both input and output.  Moreover, open drain and open source pins are excluded from fast bitmap output processing.

---

# A driver for a selfmade cheap BT8xx based PCI GPIO-card (bt8xxgpio)

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> For advanced documentation, see https://bues.ch/cms/unmaintained/btgpio.html

<a id="rst-a-driver-for-a-selfmade-cheap-bt8xx-based-pci-gpio-card-bt8xxgpio"></a>

For advanced documentation, see [https://bues.ch/cms/unmaintained/btgpio.html](<https://bues.ch/cms/unmaintained/btgpio.html>)

A generic digital 24-port PCI GPIO card can be built out of an ordinary Brooktree bt848, bt849, bt878 or bt879 based analog TV tuner card. The Brooktree chip is used in old analog Hauppauge WinTV PCI cards. You can easily find them used for low prices on the net.

The bt8xx chip does have 24 digital GPIO ports. These ports are accessible via 24 pins on the SMD chip package.

<a id="rst-how-to-physically-access-the-gpio-pins"></a>

## How to physically access the GPIO pins

The are several ways to access these pins. One might unsolder the whole chip and put it on a custom PCI board, or one might only unsolder each individual GPIO pin and solder that to some tiny wire. As the chip package really is tiny there are some advanced soldering skills needed in any case.

The physical pinouts are drawn in the following ASCII art. The GPIO pins are marked with G00-G23:



```text
                                  G G G G G G G G G G G G     G G G G G G
                                  0 0 0 0 0 0 0 0 0 0 1 1     1 1 1 1 1 1
                                  0 1 2 3 4 5 6 7 8 9 0 1     2 3 4 5 6 7
  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
  ---------------------------------------------------------------------------
--|                               ^                                     ^   |--
--|                               pin 86                           pin 67   |--
--|                                                                         |--
--|                                                               pin 61 >  |-- G18
--|                                                                         |-- G19
--|                                                                         |-- G20
--|                                                                         |-- G21
--|                                                                         |-- G22
--|                                                               pin 56 >  |-- G23
--|                                                                         |--
--|                           Brooktree 878/879                             |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|                                                                         |--
--|   O                                                                     |--
--|                                                                         |--
  ---------------------------------------------------------------------------
  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
  ^
  This is pin 1
```

---

# GPIO Descriptor Consumer Interface

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> This document describes the consumer interface of the GPIO framework.

<a id="rst-gpio-descriptor-consumer-interface"></a>

This document describes the consumer interface of the GPIO framework.

<a id="rst-guidelines-for-gpios-consumers"></a>

## Guidelines for GPIOs consumers

Drivers that can't work without standard GPIO calls should have Kconfig entries that depend on GPIOLIB or select GPIOLIB. The functions that allow a driver to obtain and use GPIOs are available by including the following file:



```text
#include <linux/gpio/consumer.h>
```

There are static inline stubs for all functions in the header file in the case where GPIOLIB is disabled. When these stubs are called they will emit warnings. These stubs are used for two use cases:

- Simple compile coverage with e.g. COMPILE_TEST - it does not matter that the current platform does not enable or select GPIOLIB because we are not going to execute the system anyway.

- Truly optional GPIOLIB support - where the driver does not really make use of the GPIOs on certain compile-time configurations for certain systems, but will use it under other compile-time configurations. In this case the consumer must make sure not to call into these functions, or the user will be met with console warnings that may be perceived as intimidating. Combining truly optional GPIOLIB usage with calls to `[devm_]gpiod_get_optional()` is a *bad idea*, and will result in weird error messages. Use the ordinary getter functions with optional GPIOLIB: some open coding of error handling should be expected when you do this.

All the functions that work with the descriptor-based GPIO interface are prefixed with `gpiod_`. The `gpio_` prefix is used for the legacy interface. No other function in the kernel should use these prefixes. The use of the legacy functions is strongly discouraged, new code should use &lt;linux/gpio/consumer.h&gt; and descriptors exclusively.

<a id="rst-obtaining-and-disposing-gpios"></a>

## Obtaining and Disposing GPIOs

With the descriptor-based interface, GPIOs are identified with an opaque, non-forgeable handler that must be obtained through a call to one of the gpiod_get() functions. Like many other kernel subsystems, gpiod_get() takes the device that will use the GPIO and the function the requested GPIO is supposed to fulfill:



```text
struct gpio_desc *gpiod_get(struct device *dev, const char *con_id,
                            enum gpiod_flags flags)
```

If a function is implemented by using several GPIOs together (e.g. a simple LED device that displays digits), an additional index argument can be specified:



```text
struct gpio_desc *gpiod_get_index(struct device *dev,
                                  const char *con_id, unsigned int idx,
                                  enum gpiod_flags flags)
```

For a more detailed description of the con_id parameter in the DeviceTree case see [Documentation/driver-api/gpio/board.rst](/kernel/hardware/driver-api/gpio/board.md)

The flags parameter is used to optionally specify a direction and initial value for the GPIO. Values can be:

- GPIOD_ASIS or 0 to not initialize the GPIO at all. The direction must be set later with one of the dedicated functions.

- GPIOD_IN to initialize the GPIO as input.

- GPIOD_OUT_LOW to initialize the GPIO as output with a value of 0.

- GPIOD_OUT_HIGH to initialize the GPIO as output with a value of 1.

- GPIOD_OUT_LOW_OPEN_DRAIN same as GPIOD_OUT_LOW but also enforce the line to be electrically used with open drain.

- GPIOD_OUT_HIGH_OPEN_DRAIN same as GPIOD_OUT_HIGH but also enforce the line to be electrically used with open drain.

Note that the initial value is *logical* and the physical line level depends on whether the line is configured active high or active low (see [The active low and open drain semantics](<#rst-active-low-semantics>)).

The two last flags are used for use cases where open drain is mandatory, such as I2C: if the line is not already configured as open drain in the mappings (see [board.rst](/kernel/hardware/driver-api/gpio/board.md)), then open drain will be enforced anyway and a warning will be printed that the board configuration needs to be updated to match the use case.

Both functions return either a valid GPIO descriptor, or an error code checkable with IS_ERR() (they will never return a NULL pointer). -ENOENT will be returned if and only if no GPIO has been assigned to the device/function/index triplet, other error codes are used for cases where a GPIO has been assigned but an error occurred while trying to acquire it. This is useful to discriminate between mere errors and an absence of GPIO for optional GPIO parameters. For the common pattern where a GPIO is optional, the gpiod_get_optional() and gpiod_get_index_optional() functions can be used. These functions return NULL instead of -ENOENT if no GPIO has been assigned to the requested function:



```text
struct gpio_desc *gpiod_get_optional(struct device *dev,
                                     const char *con_id,
                                     enum gpiod_flags flags)

struct gpio_desc *gpiod_get_index_optional(struct device *dev,
                                           const char *con_id,
                                           unsigned int index,
                                           enum gpiod_flags flags)
```

Note that gpio_get\*\_optional() functions (and their managed variants), unlike the rest of gpiolib API, also return NULL when gpiolib support is disabled. This is helpful to driver authors, since they do not need to special case -ENOSYS return codes.  System integrators should however be careful to enable gpiolib on systems that need it.

For a function using multiple GPIOs all of those can be obtained with one call:



```text
struct gpio_descs *gpiod_get_array(struct device *dev,
                                   const char *con_id,
                                   enum gpiod_flags flags)
```

This function returns a struct gpio_descs which contains an array of descriptors.  It also contains a pointer to a gpiolib private structure which, if passed back to get/set array functions, may speed up I/O processing:



```text
struct gpio_descs {
        struct gpio_array *info;
        unsigned int ndescs;
        struct gpio_desc *desc[];
}
```

The following function returns NULL instead of -ENOENT if no GPIOs have been assigned to the requested function:



```text
struct gpio_descs *gpiod_get_array_optional(struct device *dev,
                                            const char *con_id,
                                            enum gpiod_flags flags)
```

Device-managed variants of these functions are also defined:



```text
struct gpio_desc *devm_gpiod_get(struct device *dev, const char *con_id,
                                 enum gpiod_flags flags)

struct gpio_desc *devm_gpiod_get_index(struct device *dev,
                                       const char *con_id,
                                       unsigned int idx,
                                       enum gpiod_flags flags)

struct gpio_desc *devm_gpiod_get_optional(struct device *dev,
                                          const char *con_id,
                                          enum gpiod_flags flags)

struct gpio_desc *devm_gpiod_get_index_optional(struct device *dev,
                                                const char *con_id,
                                                unsigned int index,
                                                enum gpiod_flags flags)

struct gpio_descs *devm_gpiod_get_array(struct device *dev,
                                        const char *con_id,
                                        enum gpiod_flags flags)

struct gpio_descs *devm_gpiod_get_array_optional(struct device *dev,
                                                 const char *con_id,
                                                 enum gpiod_flags flags)
```

A GPIO descriptor can be disposed of using the gpiod_put() function:



```text
void gpiod_put(struct gpio_desc *desc)
```

For an array of GPIOs this function can be used:



```text
void gpiod_put_array(struct gpio_descs *descs)
```

It is strictly forbidden to use a descriptor after calling these functions. It is also not allowed to individually release descriptors (using gpiod_put()) from an array acquired with gpiod_get_array().

The device-managed variants are, unsurprisingly:



```text
void devm_gpiod_put(struct device *dev, struct gpio_desc *desc)

void devm_gpiod_put_array(struct device *dev, struct gpio_descs *descs)
```

<a id="rst-using-gpios"></a>

## Using GPIOs

<a id="rst-setting-direction"></a>

### Setting Direction

The first thing a driver must do with a GPIO is setting its direction. If no direction-setting flags have been given to gpiod_get\*(), this is done by invoking one of the gpiod_direction\_\*() functions:



```text
int gpiod_direction_input(struct gpio_desc *desc)
int gpiod_direction_output(struct gpio_desc *desc, int value)
```

The return value is zero for success, else a negative errno. It should be checked, since the get/set calls don't return errors and since misconfiguration is possible. You should normally issue these calls from a task context. However, for spinlock-safe GPIOs it is OK to use them before tasking is enabled, as part of early board setup.

For output GPIOs, the value provided becomes the initial output value. This helps avoid signal glitching during system startup.

A driver can also query the current direction of a GPIO:



```text
int gpiod_get_direction(const struct gpio_desc *desc)
```

This function returns 0 for output, 1 for input, or an error code in case of error.

Be aware that there is no default direction for GPIOs. Therefore, **using a GPIO without setting its direction first is illegal and will result in undefined behavior\!**

<a id="rst-spinlock-safe-gpio-access"></a>

### Spinlock-Safe GPIO Access

Most GPIO controllers can be accessed with memory read/write instructions. Those don't need to sleep, and can safely be done from inside hard (non-threaded) IRQ handlers and similar contexts.

Use the following calls to access GPIOs from an atomic context:



```text
int gpiod_get_value(const struct gpio_desc *desc);
void gpiod_set_value(struct gpio_desc *desc, int value);
```

The values are boolean, zero for inactive, nonzero for active. When reading the value of an output pin, the value returned should be what's seen on the pin. That won't always match the specified output value, because of issues including open-drain signaling and output latencies.

The get/set calls do not return errors because "invalid GPIO" should have been reported earlier from gpiod_direction\_\*(). However, note that not all platforms can read the value of output pins; those that can't should always return zero. Also, using these calls for GPIOs that can't safely be accessed without sleeping (see below) is an error.

<a id="rst-gpio-access-that-may-sleep"></a>

### GPIO Access That May Sleep

Some GPIO controllers must be accessed using message based buses like I2C or SPI. Commands to read or write those GPIO values require waiting to get to the head of a queue to transmit a command and get its response. This requires sleeping, which can't be done from inside IRQ handlers.

Platforms that support this type of GPIO distinguish them from other GPIOs by returning nonzero from this call:



```text
int gpiod_cansleep(const struct gpio_desc *desc)
```

To access such GPIOs, a different set of accessors is defined:



```text
int gpiod_get_value_cansleep(const struct gpio_desc *desc)
void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
```

Accessing such GPIOs requires a context which may sleep, for example a threaded IRQ handler, and those accessors must be used instead of spinlock-safe accessors without the cansleep() name suffix.

Other than the fact that these accessors might sleep, and will work on GPIOs that can't be accessed from hardIRQ handlers, these calls act the same as the spinlock-safe calls.

<a id="rst-the-active-low-and-open-drain-semantics"></a>
<a id="rst-active-low-semantics"></a>

### The active low and open drain semantics

As a consumer should not have to care about the physical line level, all of the gpiod_set_value_xxx() or gpiod_set_array_value_xxx() functions operate with the *logical* value. With this they take the active low property into account. This means that they check whether the GPIO is configured to be active low, and if so, they manipulate the passed value before the physical line level is driven.

The same is applicable for open drain or open source output lines: those do not actively drive their output high (open drain) or low (open source), they just switch their output to a high impedance value. The consumer should not need to care. (For details read about open drain in [driver.rst](/kernel/hardware/driver-api/gpio/driver.md).)

With this, all the gpiod_set\_(array)\_value_xxx() functions interpret the parameter "value" as "active" ("1") or "inactive" ("0"). The physical line level will be driven accordingly.

As an example, if the active low property for a dedicated GPIO is set, and the gpiod_set\_(array)\_value_xxx() passes "active" ("1"), the physical line level will be driven low.

To summarize:



```text
Function (example)                 line property          physical line
gpiod_set_raw_value(desc, 0);      don't care             low
gpiod_set_raw_value(desc, 1);      don't care             high
gpiod_set_value(desc, 0);          default (active high)  low
gpiod_set_value(desc, 1);          default (active high)  high
gpiod_set_value(desc, 0);          active low             high
gpiod_set_value(desc, 1);          active low             low
gpiod_set_value(desc, 0);          open drain             low
gpiod_set_value(desc, 1);          open drain             high impedance
gpiod_set_value(desc, 0);          open source            high impedance
gpiod_set_value(desc, 1);          open source            high
```

It is possible to override these semantics using the set_raw/get_raw functions but it should be avoided as much as possible, especially by system-agnostic drivers which should not need to care about the actual physical line level and worry about the logical value instead.

<a id="rst-accessing-raw-gpio-values"></a>

### Accessing raw GPIO values

Consumers exist that need to manage the logical state of a GPIO line, i.e. the value their device will actually receive, no matter what lies between it and the GPIO line.

The following set of calls ignore the active-low or open drain property of a GPIO and work on the raw line value:



```text
int gpiod_get_raw_value(const struct gpio_desc *desc)
void gpiod_set_raw_value(struct gpio_desc *desc, int value)
int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
```

The active low state of a GPIO can also be queried and toggled using the following calls:



```text
int gpiod_is_active_low(const struct gpio_desc *desc)
void gpiod_toggle_active_low(struct gpio_desc *desc)
```

Note that these functions should only be used with great moderation; a driver should not have to care about the physical line level or open drain semantics.

<a id="rst-access-multiple-gpios-with-a-single-function-call"></a>

### Access multiple GPIOs with a single function call

The following functions get or set the values of an array of GPIOs:



```text
int gpiod_get_array_value(unsigned int array_size,
                          struct gpio_desc **desc_array,
                          struct gpio_array *array_info,
                          unsigned long *value_bitmap);
int gpiod_get_raw_array_value(unsigned int array_size,
                              struct gpio_desc **desc_array,
                              struct gpio_array *array_info,
                              unsigned long *value_bitmap);
int gpiod_get_array_value_cansleep(unsigned int array_size,
                                   struct gpio_desc **desc_array,
                                   struct gpio_array *array_info,
                                   unsigned long *value_bitmap);
int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
                                   struct gpio_desc **desc_array,
                                   struct gpio_array *array_info,
                                   unsigned long *value_bitmap);

int gpiod_set_array_value(unsigned int array_size,
                          struct gpio_desc **desc_array,
                          struct gpio_array *array_info,
                          unsigned long *value_bitmap)
int gpiod_set_raw_array_value(unsigned int array_size,
                              struct gpio_desc **desc_array,
                              struct gpio_array *array_info,
                              unsigned long *value_bitmap)
int gpiod_set_array_value_cansleep(unsigned int array_size,
                                   struct gpio_desc **desc_array,
                                   struct gpio_array *array_info,
                                   unsigned long *value_bitmap)
int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
                                       struct gpio_desc **desc_array,
                                       struct gpio_array *array_info,
                                       unsigned long *value_bitmap)
```

The array can be an arbitrary set of GPIOs. The functions will try to access GPIOs belonging to the same bank or chip simultaneously if supported by the corresponding chip driver. In that case a significantly improved performance can be expected. If simultaneous access is not possible the GPIOs will be accessed sequentially.

The functions take four arguments:

> - array_size    - the number of array elements
>
> - desc_array    - an array of GPIO descriptors
>
> - array_info    - optional information obtained from gpiod_get_array()
>
> - value_bitmap  - a bitmap to store the GPIOs' values (get) or a bitmap of values to assign to the GPIOs (set)

The descriptor array can be obtained using the gpiod_get_array() function or one of its variants. If the group of descriptors returned by that function matches the desired group of GPIOs, those GPIOs can be accessed by simply using the struct gpio_descs returned by gpiod_get_array():



```text
struct gpio_descs *my_gpio_descs = gpiod_get_array(...);
gpiod_set_array_value(my_gpio_descs->ndescs, my_gpio_descs->desc,
                      my_gpio_descs->info, my_gpio_value_bitmap);
```

It is also possible to access a completely arbitrary array of descriptors. The descriptors may be obtained using any combination of gpiod_get() and gpiod_get_array(). Afterwards the array of descriptors has to be setup manually before it can be passed to one of the above functions.  In that case, array_info should be set to NULL.

Note that for optimal performance GPIOs belonging to the same chip should be contiguous within the array of descriptors.

Still better performance may be achieved if array indexes of the descriptors match hardware pin numbers of a single chip.  If an array passed to a get/set array function matches the one obtained from gpiod_get_array() and array_info associated with the array is also passed, the function may take a fast bitmap processing path, passing the value_bitmap argument directly to the respective .get/set_multiple() callback of the chip.  That allows for utilization of GPIO banks as data I/O ports without much loss of performance.

The return value of gpiod_get_array_value() and its variants is 0 on success or negative on error. Note the difference to gpiod_get_value(), which returns 0 or 1 on success to convey the GPIO value. With the array functions, the GPIO values are stored in value_array rather than passed back as return value.

<a id="rst-gpios-mapped-to-irqs"></a>

### GPIOs mapped to IRQs

GPIO lines can quite often be used as IRQs. You can get the IRQ number corresponding to a given GPIO using the following call:



```text
int gpiod_to_irq(const struct gpio_desc *desc)
```

It will return an IRQ number, or a negative errno code if the mapping can't be done (most likely because that particular GPIO cannot be used as IRQ). It is an unchecked error to use a GPIO that wasn't set up as an input using gpiod_direction_input(), or to use an IRQ number that didn't originally come from gpiod_to_irq(). gpiod_to_irq() is not allowed to sleep.

Non-error values returned from gpiod_to_irq() can be passed to request_irq() or free_irq(). They will often be stored into IRQ resources for platform devices, by the board-specific initialization code. Note that IRQ trigger options are part of the IRQ interface, e.g. IRQF_TRIGGER_FALLING, as are system wakeup capabilities.

<a id="rst-gpios-and-acpi"></a>

## GPIOs and ACPI

On ACPI systems, GPIOs are described by GpioIo()/GpioInt() resources listed by the \_CRS configuration objects of devices.  Those resources do not provide connection IDs (names) for GPIOs, so it is necessary to use an additional mechanism for this purpose.

Systems compliant with ACPI 5.1 or newer may provide a \_DSD configuration object which, among other things, may be used to provide connection IDs for specific GPIOs described by the GpioIo()/GpioInt() resources in \_CRS.  If that is the case, it will be handled by the GPIO subsystem automatically.  However, if the \_DSD is not present, the mappings between GpioIo()/GpioInt() resources and GPIO connection IDs need to be provided by device drivers.

For details refer to [Documentation/firmware-guide/acpi/gpio-properties.rst](/kernel/hardware/firmware-guide/acpi/gpio-properties.md)

<a id="rst-interacting-with-the-legacy-gpio-subsystem"></a>

## Interacting With the Legacy GPIO Subsystem

Many kernel subsystems and drivers still handle GPIOs using the legacy integer-based interface. It is strongly recommended to update these to the new gpiod interface. For cases where both interfaces need to be used, the following two functions allow to convert a GPIO descriptor into the GPIO integer namespace and vice-versa:



```text
int desc_to_gpio(const struct gpio_desc *desc)
struct gpio_desc *gpio_to_desc(unsigned gpio)
```

The GPIO number returned by desc_to_gpio() can safely be used as a parameter of the gpio\_\*() functions for as long as the GPIO descriptor `desc` is not freed. All the same, a GPIO number passed to gpio_to_desc() must first be properly acquired using e.g. gpio_request_one(), and the returned GPIO descriptor is only considered valid until that GPIO number is released using gpio_free().

Freeing a GPIO obtained by one API with the other API is forbidden and an unchecked error.

---

# GPIO Driver Interface

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> This document serves as a guide for writers of GPIO chip drivers.

<a id="rst-gpio-driver-interface"></a>

This document serves as a guide for writers of GPIO chip drivers.

Each GPIO controller driver needs to include the following header, which defines the structures used to define a GPIO driver:



```text
#include <linux/gpio/driver.h>
```

<a id="rst-internal-representation-of-gpios"></a>

## Internal Representation of GPIOs

A GPIO chip handles one or more GPIO lines. To be considered a GPIO chip, the lines must conform to the definition: General Purpose Input/Output. If the line is not general purpose, it is not GPIO and should not be handled by a GPIO chip. The use case is the indicative: certain lines in a system may be called GPIO but serve a very particular purpose thus not meeting the criteria of a general purpose I/O. On the other hand a LED driver line may be used as a GPIO and should therefore still be handled by a GPIO chip driver.

Inside a GPIO driver, individual GPIO lines are identified by their hardware number, sometime also referred to as `offset`, which is a unique number between 0 and n-1, n being the number of GPIOs managed by the chip.

The hardware GPIO number should be something intuitive to the hardware, for example if a system uses a memory-mapped set of I/O-registers where 32 GPIO lines are handled by one bit per line in a 32-bit register, it makes sense to use hardware offsets 0..31 for these, corresponding to bits 0..31 in the register.

This number is purely internal: the hardware number of a particular GPIO line is never made visible outside of the driver.

On top of this internal number, each GPIO line also needs to have a global number in the integer GPIO namespace so that it can be used with the legacy GPIO interface. Each chip must thus have a "base" number (which can be automatically assigned), and for each GPIO line the global number will be (base + hardware number). Although the integer representation is considered deprecated, it still has many users and thus needs to be maintained.

So for example one platform could use global numbers 32-159 for GPIOs, with a controller defining 128 GPIOs at a "base" of 32 ; while another platform uses global numbers 0..63 with one set of GPIO controllers, 64-79 with another type of GPIO controller, and on one particular board 80-95 with an FPGA. The legacy numbers need not be contiguous; either of those platforms could also use numbers 2000-2063 to identify GPIO lines in a bank of I2C GPIO expanders.

<a id="rst-controller-drivers-gpio-chip"></a>

## Controller Drivers: gpio_chip

In the gpiolib framework each GPIO controller is packaged as a "struct gpio_chip" (see &lt;linux/gpio/driver.h&gt; for its complete definition) with members common to each controller of that type, these should be assigned by the driver code:

> - methods to establish GPIO line direction
>
> - methods used to access GPIO line values
>
> - method to set electrical configuration for a given GPIO line
>
> - method to return the IRQ number associated to a given GPIO line
>
> - flag saying whether calls to its methods may sleep
>
> - optional line names array to identify lines
>
> - optional debugfs dump method (showing extra state information)
>
> - optional base number (will be automatically assigned if omitted)
>
> - optional label for diagnostics and GPIO chip mapping using platform data

The code implementing a gpio_chip should support multiple instances of the controller, preferably using the driver model. That code will configure each gpio_chip and issue gpiochip_add_data() or devm_gpiochip_add_data(). Removing a GPIO controller should be rare; use gpiochip_remove() when it is unavoidable.

Often a gpio_chip is part of an instance-specific structure with states not exposed by the GPIO interfaces, such as addressing, power management, and more. Chips such as audio codecs will have complex non-GPIO states.

Any debugfs dump method should normally ignore lines which haven't been requested. They can use gpiochip_is_requested(), which returns either NULL or the label associated with that GPIO line when it was requested.

Realtime considerations: the GPIO driver should not use spinlock_t or any sleepable APIs (like PM runtime) in its gpio_chip implementation (.get/.set and direction control callbacks) if it is expected to call GPIO APIs from atomic context on realtime kernels (inside hard IRQ handlers and similar contexts). Normally this should not be required.

<a id="rst-gpio-electrical-configuration"></a>

### GPIO electrical configuration

GPIO lines can be configured for several electrical modes of operation by using the .set_config() callback. Currently this API supports setting:

- Debouncing

- Single-ended modes (open drain/open source)

- Pull up and pull down resistor enablement

These settings are described below.

The .set_config() callback uses the same enumerators and configuration semantics as the generic pin control drivers. This is not a coincidence: it is possible to assign the .set_config() to the function gpiochip_generic_config() which will result in pinctrl_gpio_set_config() being called and eventually ending up in the pin control back-end "behind" the GPIO controller, usually closer to the actual pins. This way the pin controller can manage the below listed GPIO configurations.

If a pin controller back-end is used, the GPIO controller or hardware description needs to provide "GPIO ranges" mapping the GPIO line offsets to pin numbers on the pin controller so they can properly cross-reference each other.

<a id="rst-gpio-lines-with-debounce-support"></a>

### GPIO lines with debounce support

Debouncing is a configuration set to a pin indicating that it is connected to a mechanical switch or button, or similar that may bounce. Bouncing means the line is pulled high/low quickly at very short intervals for mechanical reasons. This can result in the value being unstable or irqs firing repeatedly unless the line is debounced.

Debouncing in practice involves setting up a timer when something happens on the line, wait a little while and then sample the line again, so see if it still has the same value (low or high). This could also be repeated by a clever state machine, waiting for a line to become stable. In either case, it sets a certain number of milliseconds for debouncing, or just "on/off" if that time is not configurable.

<a id="rst-gpio-lines-with-open-drain-source-support"></a>

### GPIO lines with open drain/source support

Open drain (CMOS) or open collector (TTL) means the line is not actively driven high: instead you provide the drain/collector as output, so when the transistor is not open, it will present a high-impedance (tristate) to the external rail:



```text
CMOS CONFIGURATION      TTL CONFIGURATION

         ||--- out              +--- out
  in ----||                   |/
         ||--+         in ----|
             |                |\
            GND                 GND
```

This configuration is normally used as a way to achieve one of two things:

- Level-shifting: to reach a logical level higher than that of the silicon where the output resides.

- Inverse wire-OR on an I/O line, for example a GPIO line, making it possible for any driving stage on the line to drive it low even if any other output to the same line is simultaneously driving it high. A special case of this is driving the SCL and SDA lines of an I2C bus, which is by definition a wire-OR bus.

Both use cases require that the line be equipped with a pull-up resistor. This resistor will make the line tend to high level unless one of the transistors on the rail actively pulls it down.

The level on the line will go as high as the VDD on the pull-up resistor, which may be higher than the level supported by the transistor, achieving a level-shift to the higher VDD.

Integrated electronics often have an output driver stage in the form of a CMOS "totem-pole" with one N-MOS and one P-MOS transistor where one of them drives the line high and one of them drives the line low. This is called a push-pull output. The "totem-pole" looks like so:



```text
                 VDD
                  |
        OD    ||--+
     +--/ ---o||     P-MOS-FET
     |        ||--+
IN --+            +----- out
     |        ||--+
     +--/ ----||     N-MOS-FET
        OS    ||--+
                  |
                 GND
```

The desired output signal (e.g. coming directly from some GPIO output register) arrives at IN. The switches named "OD" and "OS" are normally closed, creating a push-pull circuit.

Consider the little "switches" named "OD" and "OS" that enable/disable the P-MOS or N-MOS transistor right after the split of the input. As you can see, either transistor will go totally numb if this switch is open. The totem-pole is then halved and give high impedance instead of actively driving the line high or low respectively. That is usually how software-controlled open drain/source works.

Some GPIO hardware come in open drain / open source configuration. Some are hard-wired lines that will only support open drain or open source no matter what: there is only one transistor there. Some are software-configurable: by flipping a bit in a register the output can be configured as open drain or open source, in practice by flicking open the switches labeled "OD" and "OS" in the drawing above.

By disabling the P-MOS transistor, the output can be driven between GND and high impedance (open drain), and by disabling the N-MOS transistor, the output can be driven between VDD and high impedance (open source). In the first case, a pull-up resistor is needed on the outgoing rail to complete the circuit, and in the second case, a pull-down resistor is needed on the rail.

Hardware that supports open drain or open source or both, can implement a special callback in the gpio_chip: .set_config() that takes a generic pinconf packed value telling whether to configure the line as open drain, open source or push-pull. This will happen in response to the GPIO_OPEN_DRAIN or GPIO_OPEN_SOURCE flag set in the machine file, or coming from other hardware descriptions.

If this state can not be configured in hardware, i.e. if the GPIO hardware does not support open drain/open source in hardware, the GPIO library will instead use a trick: when a line is set as output, if the line is flagged as open drain, and the IN output value is low, it will be driven low as usual. But if the IN output value is set to high, it will instead *NOT* be driven high, instead it will be switched to input, as input mode is an equivalent to high impedance, thus achieving an "open drain emulation" of sorts: electrically the behaviour will be identical, with the exception of possible hardware glitches when switching the mode of the line.

For open source configuration the same principle is used, just that instead of actively driving the line low, it is set to input.

<a id="rst-gpio-lines-with-pull-up-down-resistor-support"></a>

### GPIO lines with pull up/down resistor support

A GPIO line can support pull-up/down using the .set_config() callback. This means that a pull up or pull-down resistor is available on the output of the GPIO line, and this resistor is software controlled.

In discrete designs, a pull-up or pull-down resistor is simply soldered on the circuit board. This is not something we deal with or model in software. The most you will think about these lines is that they will very likely be configured as open drain or open source (see the section above).

The .set_config() callback can only turn pull up or down on and off, and will no have any semantic knowledge about the resistance used. It will only say switch a bit in a register enabling or disabling pull-up or pull-down.

If the GPIO line supports shunting in different resistance values for the pull-up or pull-down resistor, the GPIO chip callback .set_config() will not suffice. For these complex use cases, a combined GPIO chip and pin controller need to be implemented, as the pin config interface of a pin controller supports more versatile control over electrical properties and can handle different pull-up or pull-down resistance values.

<a id="rst-gpio-drivers-providing-irqs"></a>

## GPIO drivers providing IRQs

It is custom that GPIO drivers (GPIO chips) are also providing interrupts, most often cascaded off a parent interrupt controller, and in some special cases the GPIO logic is melded with a SoC's primary interrupt controller.

The IRQ portions of the GPIO block are implemented using an irq_chip, using the header &lt;linux/irq.h&gt;. So this combined driver is utilizing two sub- systems simultaneously: gpio and irq.

It is legal for any IRQ consumer to request an IRQ from any irqchip even if it is a combined GPIO+IRQ driver. The basic premise is that gpio_chip and irq_chip are orthogonal, and offering their services independent of each other.

gpiod_to_irq() is just a convenience function to figure out the IRQ for a certain GPIO line and should not be relied upon to have been called before the IRQ is used.

Always prepare the hardware and make it ready for action in respective callbacks from the GPIO and irq_chip APIs. Do not rely on gpiod_to_irq() having been called first.

We can divide GPIO irqchips in two broad categories:

- CASCADED INTERRUPT CHIPS: this means that the GPIO chip has one common interrupt output line, which is triggered by any enabled GPIO line on that chip. The interrupt output line will then be routed to an parent interrupt controller one level up, in the most simple case the systems primary interrupt controller. This is modeled by an irqchip that will inspect bits inside the GPIO controller to figure out which line fired it. The irqchip part of the driver needs to inspect registers to figure this out and it will likely also need to acknowledge that it is handling the interrupt by clearing some bit (sometime implicitly, by just reading a status register) and it will often need to set up the configuration such as edge sensitivity (rising or falling edge, or high/low level interrupt for example).

- HIERARCHICAL INTERRUPT CHIPS: this means that each GPIO line has a dedicated irq line to a parent interrupt controller one level up. There is no need to inquire the GPIO hardware to figure out which line has fired, but it may still be necessary to acknowledge the interrupt and set up configuration such as edge sensitivity.

Realtime considerations: a realtime compliant GPIO driver should not use spinlock_t or any sleepable APIs (like PM runtime) as part of its irqchip implementation.

- spinlock_t should be replaced with raw_spinlock_t.\[1\]

- If sleepable APIs have to be used, these can be done from the .irq_bus_lock() and .irq_bus_unlock() callbacks, as these are the only slowpath callbacks on an irqchip. Create the callbacks if needed.\[2\]

<a id="rst-cascaded-gpio-irqchips"></a>

### Cascaded GPIO irqchips

Cascaded GPIO irqchips usually fall in one of three categories:

- CHAINED CASCADED GPIO IRQCHIPS: these are usually the type that is embedded on an SoC. This means that there is a fast IRQ flow handler for the GPIOs that gets called in a chain from the parent IRQ handler, most typically the system interrupt controller. This means that the GPIO irqchip handler will be called immediately from the parent irqchip, while holding the IRQs disabled. The GPIO irqchip will then end up calling something like this sequence in its interrupt handler:



  ```text
  static irqreturn_t foo_gpio_irq(int irq, void *data)
      chained_irq_enter(...);
      generic_handle_irq(...);
      chained_irq_exit(...);
  ```

  Chained GPIO irqchips typically can NOT set the .can_sleep flag on struct gpio_chip, as everything happens directly in the callbacks: no slow bus traffic like I2C can be used.

  Realtime considerations: Note that chained IRQ handlers will not be forced threaded on -RT. As a result, spinlock_t or any sleepable APIs (like PM runtime) can't be used in a chained IRQ handler.

  If required (and if it can't be converted to the nested threaded GPIO irqchip, see below) a chained IRQ handler can be converted to generic irq handler and this way it will become a threaded IRQ handler on -RT and a hard IRQ handler on non-RT (for example, see \[3\]).

  The generic_handle_irq() is expected to be called with IRQ disabled, so the IRQ core will complain if it is called from an IRQ handler which is forced to a thread. The "fake?" raw lock can be used to work around this problem:



  ```text
  raw_spinlock_t wa_lock;
  static irqreturn_t omap_gpio_irq_handler(int irq, void *gpiobank)
      unsigned long wa_lock_flags;
      raw_spin_lock_irqsave(&bank->wa_lock, wa_lock_flags);
      generic_handle_irq(irq_find_mapping(bank->chip.irq.domain, bit));
      raw_spin_unlock_irqrestore(&bank->wa_lock, wa_lock_flags);
  ```

- GENERIC CHAINED GPIO IRQCHIPS: these are the same as "CHAINED GPIO irqchips", but chained IRQ handlers are not used. Instead GPIO IRQs dispatching is performed by generic IRQ handler which is configured using request_irq(). The GPIO irqchip will then end up calling something like this sequence in its interrupt handler:



  ```text
  static irqreturn_t gpio_rcar_irq_handler(int irq, void *dev_id)
      for each detected GPIO IRQ
          generic_handle_irq(...);
  ```

  Realtime considerations: this kind of handlers will be forced threaded on -RT, and as result the IRQ core will complain that generic_handle_irq() is called with IRQ enabled and the same work-around as for "CHAINED GPIO irqchips" can be applied.

- NESTED THREADED GPIO IRQCHIPS: these are off-chip GPIO expanders and any other GPIO irqchip residing on the other side of a sleeping bus such as I2C or SPI.

  Of course such drivers that need slow bus traffic to read out IRQ status and similar, traffic which may in turn incur other IRQs to happen, cannot be handled in a quick IRQ handler with IRQs disabled. Instead they need to spawn a thread and then mask the parent IRQ line until the interrupt is handled by the driver. The hallmark of this driver is to call something like this in its interrupt handler:



  ```text
  static irqreturn_t foo_gpio_irq(int irq, void *data)
      ...
      handle_nested_irq(irq);
  ```

  The hallmark of threaded GPIO irqchips is that they set the .can_sleep flag on struct gpio_chip to true, indicating that this chip may sleep when accessing the GPIOs.

  These kinds of irqchips are inherently realtime tolerant as they are already set up to handle sleeping contexts.

<a id="rst-infrastructure-helpers-for-gpio-irqchips"></a>

### Infrastructure helpers for GPIO irqchips

To help out in handling the set-up and management of GPIO irqchips and the associated irqdomain and resource allocation callbacks. These are activated by selecting the Kconfig symbol GPIOLIB_IRQCHIP. If the symbol IRQ_DOMAIN_HIERARCHY is also selected, hierarchical helpers will also be provided. A big portion of overhead code will be managed by gpiolib, under the assumption that your interrupts are 1-to-1-mapped to the GPIO line index:


<table>
<thead>
<tr>
<th>


GPIO line offset

</th>
<th>


Hardware IRQ

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


0

</td>
</tr>
<tr>
<td>


1

</td>
<td>


1

</td>
</tr>
<tr>
<td>


2

</td>
<td>


2

</td>
</tr>
<tr>
<td>


...

</td>
<td>


...

</td>
</tr>
<tr>
<td>


ngpio-1

</td>
<td>


ngpio-1

</td>
</tr>
</tbody>
</table>

If some GPIO lines do not have corresponding IRQs, the bitmask valid_mask and the flag need_valid_mask in gpio_irq_chip can be used to mask off some lines as invalid for associating with IRQs.

The preferred way to set up the helpers is to fill in the struct gpio_irq_chip inside struct gpio_chip before adding the gpio_chip. If you do this, the additional irq_chip will be set up by gpiolib at the same time as setting up the rest of the GPIO functionality. The following is a typical example of a chained cascaded interrupt handler using the gpio_irq_chip. Note how the mask/unmask (or disable/enable) functions call into the core gpiolib code:



```c
/* Typical state container */
struct my_gpio {
    struct gpio_chip gc;
};

static void my_gpio_mask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    /*
     * Perform any necessary action to mask the interrupt,
     * and then call into the core code to synchronise the
     * state.
     */

    gpiochip_disable_irq(gc, hwirq);
}

static void my_gpio_unmask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    gpiochip_enable_irq(gc, hwirq);

    /*
     * Perform any necessary action to unmask the interrupt,
     * after having called into the core code to synchronise
     * the state.
     */
}

/*
 * Statically populate the irqchip. Note that it is made const
 * (further indicated by the IRQCHIP_IMMUTABLE flag), and that
 * the GPIOCHIP_IRQ_RESOURCE_HELPER macro adds some extra
 * callbacks to the structure.
 */
static const struct irq_chip my_gpio_irq_chip = {
    .name             = "my_gpio_irq",
    .irq_ack          = my_gpio_ack_irq,
    .irq_mask         = my_gpio_mask_irq,
    .irq_unmask       = my_gpio_unmask_irq,
    .irq_set_type     = my_gpio_set_irq_type,
    .flags            = IRQCHIP_IMMUTABLE,
    /* Provide the gpio resource callbacks */
    GPIOCHIP_IRQ_RESOURCE_HELPERS,
};

int irq; /* from platform etc */
struct my_gpio *g;
struct gpio_irq_chip *girq;

/* Get a pointer to the gpio_irq_chip */
girq = &g->gc.irq;
gpio_irq_chip_set_chip(girq, &my_gpio_irq_chip);
girq->parent_handler = ftgpio_gpio_irq_handler;
girq->num_parents = 1;
girq->parents = devm_kcalloc(dev, 1, sizeof(*girq->parents),
                             GFP_KERNEL);
if (!girq->parents)
    return -ENOMEM;
girq->default_type = IRQ_TYPE_NONE;
girq->handler = handle_bad_irq;
girq->parents[0] = irq;

return devm_gpiochip_add_data(dev, &g->gc, g);
```

The helper supports using threaded interrupts as well. Then you just request the interrupt separately and go with it:



```c
/* Typical state container */
struct my_gpio {
    struct gpio_chip gc;
};

static void my_gpio_mask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    /*
     * Perform any necessary action to mask the interrupt,
     * and then call into the core code to synchronise the
     * state.
     */

    gpiochip_disable_irq(gc, hwirq);
}

static void my_gpio_unmask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    gpiochip_enable_irq(gc, hwirq);

    /*
     * Perform any necessary action to unmask the interrupt,
     * after having called into the core code to synchronise
     * the state.
     */
}

/*
 * Statically populate the irqchip. Note that it is made const
 * (further indicated by the IRQCHIP_IMMUTABLE flag), and that
 * the GPIOCHIP_IRQ_RESOURCE_HELPER macro adds some extra
 * callbacks to the structure.
 */
static const struct irq_chip my_gpio_irq_chip = {
    .name             = "my_gpio_irq",
    .irq_ack          = my_gpio_ack_irq,
    .irq_mask         = my_gpio_mask_irq,
    .irq_unmask       = my_gpio_unmask_irq,
    .irq_set_type     = my_gpio_set_irq_type,
    .flags            = IRQCHIP_IMMUTABLE,
    /* Provide the gpio resource callbacks */
    GPIOCHIP_IRQ_RESOURCE_HELPERS,
};

int irq; /* from platform etc */
struct my_gpio *g;
struct gpio_irq_chip *girq;

ret = devm_request_threaded_irq(dev, irq, NULL, irq_thread_fn,
                                IRQF_ONESHOT, "my-chip", g);
if (ret < 0)
    return ret;

/* Get a pointer to the gpio_irq_chip */
girq = &g->gc.irq;
gpio_irq_chip_set_chip(girq, &my_gpio_irq_chip);
/* This will let us handle the parent IRQ in the driver */
girq->parent_handler = NULL;
girq->num_parents = 0;
girq->parents = NULL;
girq->default_type = IRQ_TYPE_NONE;
girq->handler = handle_bad_irq;

return devm_gpiochip_add_data(dev, &g->gc, g);
```

The helper supports using hierarchical interrupt controllers as well. In this case the typical set-up will look like this:



```c
/* Typical state container with dynamic irqchip */
struct my_gpio {
    struct gpio_chip gc;
    struct fwnode_handle *fwnode;
};

static void my_gpio_mask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    /*
     * Perform any necessary action to mask the interrupt,
     * and then call into the core code to synchronise the
     * state.
     */

    gpiochip_disable_irq(gc, hwirq);
    irq_mask_mask_parent(d);
}

static void my_gpio_unmask_irq(struct irq_data *d)
{
    struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
    irq_hw_number_t hwirq = irqd_to_hwirq(d);

    gpiochip_enable_irq(gc, hwirq);

    /*
     * Perform any necessary action to unmask the interrupt,
     * after having called into the core code to synchronise
     * the state.
     */

    irq_mask_unmask_parent(d);
}

/*
 * Statically populate the irqchip. Note that it is made const
 * (further indicated by the IRQCHIP_IMMUTABLE flag), and that
 * the GPIOCHIP_IRQ_RESOURCE_HELPER macro adds some extra
 * callbacks to the structure.
 */
static const struct irq_chip my_gpio_irq_chip = {
    .name             = "my_gpio_irq",
    .irq_ack          = my_gpio_ack_irq,
    .irq_mask         = my_gpio_mask_irq,
    .irq_unmask       = my_gpio_unmask_irq,
    .irq_set_type     = my_gpio_set_irq_type,
    .flags            = IRQCHIP_IMMUTABLE,
    /* Provide the gpio resource callbacks */
    GPIOCHIP_IRQ_RESOURCE_HELPERS,
};

struct my_gpio *g;
struct gpio_irq_chip *girq;

/* Get a pointer to the gpio_irq_chip */
girq = &g->gc.irq;
gpio_irq_chip_set_chip(girq, &my_gpio_irq_chip);
girq->default_type = IRQ_TYPE_NONE;
girq->handler = handle_bad_irq;
girq->fwnode = g->fwnode;
girq->parent_domain = parent;
girq->child_to_parent_hwirq = my_gpio_child_to_parent_hwirq;

return devm_gpiochip_add_data(dev, &g->gc, g);
```

As you can see pretty similar, but you do not supply a parent handler for the IRQ, instead a parent irqdomain, an fwnode for the hardware and a function .child_to_parent_hwirq() that has the purpose of looking up the parent hardware irq from a child (i.e. this gpio chip) hardware irq. As always it is good to look at examples in the kernel tree for advice on how to find the required pieces.

If there is a need to exclude certain GPIO lines from the IRQ domain handled by these helpers, we can set .irq.need_valid_mask of the gpiochip before devm_gpiochip_add_data() or gpiochip_add_data() is called. This allocates an .irq.valid_mask with as many bits set as there are GPIO lines in the chip, each bit representing line 0..n-1. Drivers can exclude GPIO lines by clearing bits from this mask. The mask can be filled in the init_valid_mask() callback that is part of the struct gpio_irq_chip.

To use the helpers please keep the following in mind:

- Make sure to assign all relevant members of the struct gpio_chip so that the irqchip can initialize. E.g. .dev and .can_sleep shall be set up properly.

- Nominally set gpio_irq_chip.handler to handle_bad_irq. Then, if your irqchip is cascaded, set the handler to handle_level_irq() and/or handle_edge_irq() in the irqchip .set_type() callback depending on what your controller supports and what is requested by the consumer.

<a id="rst-locking-irq-usage"></a>

### Locking IRQ usage

Since GPIO and irq_chip are orthogonal, we can get conflicts between different use cases. For example a GPIO line used for IRQs should be an input line, it does not make sense to fire interrupts on an output GPIO.

If there is competition inside the subsystem which side is using the resource (a certain GPIO line and register for example) it needs to deny certain operations and keep track of usage inside of the gpiolib subsystem.

Input GPIOs can be used as IRQ signals. When this happens, a driver is requested to mark the GPIO as being used as an IRQ:



```text
int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
```

This will prevent the use of non-irq related GPIO APIs until the GPIO IRQ lock is released:



```text
void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
```

When implementing an irqchip inside a GPIO driver, these two functions should typically be called in the .startup() and .shutdown() callbacks from the irqchip.

When using the gpiolib irqchip helpers, these callbacks are automatically assigned.

<a id="rst-disabling-and-enabling-irqs"></a>

### Disabling and enabling IRQs

In some (fringe) use cases, a driver may be using a GPIO line as input for IRQs, but occasionally switch that line over to drive output and then back to being an input with interrupts again. This happens on things like CEC (Consumer Electronics Control).

When a GPIO is used as an IRQ signal, then gpiolib also needs to know if the IRQ is enabled or disabled. In order to inform gpiolib about this, the irqchip driver should call:



```text
void gpiochip_disable_irq(struct gpio_chip *chip, unsigned int offset)
```

This allows drivers to drive the GPIO as an output while the IRQ is disabled. When the IRQ is enabled again, a driver should call:



```text
void gpiochip_enable_irq(struct gpio_chip *chip, unsigned int offset)
```

When implementing an irqchip inside a GPIO driver, these two functions should typically be called in the .irq_disable() and .irq_enable() callbacks from the irqchip.

When IRQCHIP_IMMUTABLE is not advertised by the irqchip, these callbacks are automatically assigned. This behaviour is deprecated and on its way to be removed from the kernel.

<a id="rst-real-time-compliance-for-gpio-irq-chips"></a>

### Real-Time compliance for GPIO IRQ chips

Any provider of irqchips needs to be carefully tailored to support Real-Time preemption. It is desirable that all irqchips in the GPIO subsystem keep this in mind and do the proper testing to assure they are real time-enabled.

So, pay attention on above realtime considerations in the documentation.

The following is a checklist to follow when preparing a driver for real-time compliance:

- ensure spinlock_t is not used as part irq_chip implementation

- ensure that sleepable APIs are not used as part irq_chip implementation If sleepable APIs have to be used, these can be done from the .irq_bus_lock() and .irq_bus_unlock() callbacks

- Chained GPIO irqchips: ensure spinlock_t or any sleepable APIs are not used from the chained IRQ handler

- Generic chained GPIO irqchips: take care about generic_handle_irq() calls and apply corresponding work-around

- Chained GPIO irqchips: get rid of the chained IRQ handler and use generic irq handler if possible

- regmap_mmio: it is possible to disable internal locking in regmap by setting .disable_locking and handling the locking in the GPIO driver

- Test your driver with the appropriate in-kernel real-time test cases for both level and edge IRQs

- \[1\] [https://lore.kernel.org/r/1437496011-11486-1-git-send-email-bigeasy@linutronix.de/](<https://lore.kernel.org/r/1437496011-11486-1-git-send-email-bigeasy@linutronix.de/>)

- \[2\] [https://lore.kernel.org/r/1443209283-20781-2-git-send-email-grygorii.strashko@ti.com](<https://lore.kernel.org/r/1443209283-20781-2-git-send-email-grygorii.strashko@ti.com>)

- \[3\] [https://lore.kernel.org/r/1443209283-20781-3-git-send-email-grygorii.strashko@ti.com](<https://lore.kernel.org/r/1443209283-20781-3-git-send-email-grygorii.strashko@ti.com>)

<a id="rst-requesting-self-owned-gpio-pins"></a>

## Requesting self-owned GPIO pins

Sometimes it is useful to allow a GPIO chip driver to request its own GPIO descriptors through the gpiolib API. A GPIO driver can use the following functions to request and free descriptors:



```text
struct gpio_desc *gpiochip_request_own_desc(struct gpio_desc *desc,
                                            u16 hwnum,
                                            const char *label,
                                            enum gpiod_flags flags)

void gpiochip_free_own_desc(struct gpio_desc *desc)
```

Descriptors requested with gpiochip_request_own_desc() must be released with gpiochip_free_own_desc().

These functions must be used with care since they do not affect module use count. Do not use the functions to request gpio descriptors not owned by the calling driver.

---

# Subsystem drivers using GPIO

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> Note that standard kernel drivers exist for common GPIO tasks and will provide the right in-kernel and userspace APIs/ABIs for the job, and that these drivers can quite easily interconnect with other kernel subsystems using hardware…

<a id="rst-subsystem-drivers-using-gpio"></a>

Note that standard kernel drivers exist for common GPIO tasks and will provide the right in-kernel and userspace APIs/ABIs for the job, and that these drivers can quite easily interconnect with other kernel subsystems using hardware descriptions such as device tree or ACPI:

- leds-gpio: drivers/leds/leds-gpio.c will handle LEDs connected to  GPIO lines, giving you the LED sysfs interface

- ledtrig-gpio: drivers/leds/trigger/ledtrig-gpio.c will provide a LED trigger, i.e. a LED will turn on/off in response to a GPIO line going high or low (and that LED may in turn use the leds-gpio as per above).

- gpio-keys: drivers/input/keyboard/gpio_keys.c is used when your GPIO line can generate interrupts in response to a key press. Also supports debounce.

- gpio-keys-polled: drivers/input/keyboard/gpio_keys_polled.c is used when your GPIO line cannot generate interrupts, so it needs to be periodically polled by a timer.

- gpio_mouse: drivers/input/mouse/gpio_mouse.c is used to provide a mouse with up to three buttons by simply using GPIOs and no mouse port. You can cut the mouse cable and connect the wires to GPIO lines or solder a mouse connector to the lines for a more permanent solution of this type.

- gpio-beeper: drivers/input/misc/gpio-beeper.c is used to provide a beep from an external speaker connected to a GPIO line. (If the beep is controlled by off/on, for an actual PWM waveform, see pwm-gpio below.)

- pwm-gpio: drivers/pwm/pwm-gpio.c is used to toggle a GPIO with a high resolution timer producing a PWM waveform on the GPIO line, as well as Linux high resolution timers can do.

- extcon-gpio: drivers/extcon/extcon-gpio.c is used when you need to read an external connector status, such as a headset line for an audio driver or an HDMI connector. It will provide a better userspace sysfs interface than GPIO.

- restart-gpio: drivers/power/reset/gpio-restart.c is used to restart/reboot the system by pulling a GPIO line and will register a restart handler so userspace can issue the right system call to restart the system.

- poweroff-gpio: drivers/power/reset/gpio-poweroff.c is used to power the system down by pulling a GPIO line and will register a pm_power_off() callback so that userspace can issue the right system call to power down the system.

- gpio-gate-clock: drivers/clk/clk-gpio.c is used to control a gated clock (off/on) that uses a GPIO, and integrated with the clock subsystem.

- i2c-gpio: drivers/i2c/busses/i2c-gpio.c is used to drive an I2C bus (two wires, SDA and SCL lines) by hammering (bitbang) two GPIO lines. It will appear as any other I2C bus to the system and makes it possible to connect drivers for the I2C devices on the bus like any other I2C bus driver.

- spi_gpio: drivers/spi/spi-gpio.c is used to drive an SPI bus (variable number of wires, at least SCK and optionally MISO, MOSI and chip select lines) using GPIO hammering (bitbang). It will appear as any other SPI bus on the system and makes it possible to connect drivers for SPI devices on the bus like any other SPI bus driver. For example any MMC/SD card can then be connected to this SPI by using the mmc_spi host from the MMC/SD card subsystem.

- w1-gpio: drivers/w1/masters/w1-gpio.c is used to drive a one-wire bus using a GPIO line, integrating with the W1 subsystem and handling devices on the bus like any other W1 device.

- gpio-fan: drivers/hwmon/gpio-fan.c is used to control a fan for cooling the system, connected to a GPIO line (and optionally a GPIO alarm line), presenting all the right in-kernel and sysfs interfaces to make your system not overheat.

- gpio-regulator: drivers/regulator/gpio-regulator.c is used to control a regulator providing a certain voltage by pulling a GPIO line, integrating with the regulator subsystem and giving you all the right interfaces.

- gpio-wdt: drivers/watchdog/gpio_wdt.c is used to provide a watchdog timer that will periodically "ping" a hardware connected to a GPIO line by toggling it from 1-to-0-to-1. If that hardware does not receive its "ping" periodically, it will reset the system.

- gpio-nand: drivers/mtd/nand/raw/gpio.c is used to connect a NAND flash chip to a set of simple GPIO lines: RDY, NCE, ALE, CLE, NWP. It interacts with the NAND flash MTD subsystem and provides chip access and partition parsing like any other NAND driving hardware.

- ps2-gpio: drivers/input/serio/ps2-gpio.c is used to drive a PS/2 (IBM) serio bus, data and clock line, by bit banging two GPIO lines. It will appear as any other serio bus to the system and makes it possible to connect drivers for e.g. keyboards and other PS/2 protocol based devices.

- cec-gpio: drivers/media/platform/cec-gpio/ is used to interact with a CEC Consumer Electronics Control bus using only GPIO. It is used to communicate with devices on the HDMI bus.

- gpio-charger: drivers/power/supply/gpio-charger.c is used if you need to do battery charging and all you have to go by to check the presence of the AC charger or more complex tasks such as indicating charging status using nothing but GPIO lines, this driver provides that and also a clearly defined way to pass the charging parameters from hardware descriptions such as the device tree.

- gpio-mux: drivers/mux/gpio.c is used for controlling a multiplexer using n GPIO lines such that you can mux in 2^n different devices by activating different GPIO lines. Often the GPIOs are on a SoC and the devices are some SoC-external entities, such as different components on a PCB that can be selectively enabled.

Apart from this there are special GPIO drivers in subsystems like MMC/SD to read card detect and write protect GPIO lines, and in the TTY serial subsystem to emulate MCTRL (modem control) signals CTS/RTS by using two GPIO lines. The MTD NOR flash has add-ons for extra GPIO lines too, though the address bus is usually connected directly to the flash.

Use those instead of talking directly to the GPIOs from userspace; they integrate with kernel frameworks better than your userspace code could. Needless to say, just using the appropriate kernel drivers will simplify and speed up your embedded hacking in particular by providing ready-made components.

---

# Introduction

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> The documents in this directory give detailed instructions on how to access GPIOs in drivers, and how to write a driver for a device that provides GPIOs itself.

<a id="rst-introduction"></a>

<a id="rst-gpio-interfaces"></a>

## GPIO Interfaces

The documents in this directory give detailed instructions on how to access GPIOs in drivers, and how to write a driver for a device that provides GPIOs itself.

<a id="rst-what-is-a-gpio"></a>

## What is a GPIO?

A "General Purpose Input/Output" (GPIO) is a flexible software-controlled digital signal. They are provided from many kinds of chips, and are familiar to Linux developers working with embedded and custom hardware. Each GPIO represents a bit connected to a particular pin, or "ball" on Ball Grid Array (BGA) packages. Board schematics show which external hardware connects to which GPIOs. Drivers can be written generically, so that board setup code passes such pin configuration data to drivers.

System-on-Chip (SOC) processors heavily rely on GPIOs. In some cases, every non-dedicated pin can be configured as a GPIO; and most chips have at least several dozen of them. Programmable logic devices (like FPGAs) can easily provide GPIOs; multifunction chips like power managers, and audio codecs often have a few such pins to help with pin scarcity on SOCs; and there are also "GPIO Expander" chips that connect using the I2C or SPI serial buses. Most PC southbridges have a few dozen GPIO-capable pins (with only the BIOS firmware knowing how they're used).

The exact capabilities of GPIOs vary between systems. Common options:

> - Output values are writable (high=1, low=0). Some chips also have options about how that value is driven, so that for example only one value might be driven, supporting "wire-OR" and similar schemes for the other value (notably, "open drain" signaling).
>
> - Input values are likewise readable (1, 0). Some chips support readback of pins configured as "output", which is very useful in such "wire-OR" cases (to support bidirectional signaling). GPIO controllers may have input de-glitch/debounce logic, sometimes with software controls.
>
> - Inputs can often be used as IRQ signals, often edge triggered but sometimes level triggered. Such IRQs may be configurable as system wakeup events, to wake the system from a low power state.
>
> - Usually a GPIO will be configurable as either input or output, as needed by different product boards; single direction ones exist too.
>
> - Most GPIOs can be accessed while holding spinlocks, but those accessed through a serial bus normally can't. Some systems support both types.

On a given board each GPIO is used for one specific purpose like monitoring MMC/SD card insertion/removal, detecting card write-protect status, driving a LED, configuring a transceiver, bit-banging a serial bus, poking a hardware watchdog, sensing a switch, and so on.

<a id="rst-common-gpio-properties"></a>

## Common GPIO Properties

These properties are met through all the other documents of the GPIO interface and it is useful to understand them, especially if you need to define GPIO mappings.

<a id="rst-active-high-and-active-low"></a>

### Active-High and Active-Low

It is natural to assume that a GPIO is "active" when its output signal is 1 ("high"), and inactive when it is 0 ("low"). However in practice the signal of a GPIO may be inverted before is reaches its destination, or a device could decide to have different conventions about what "active" means. Such decisions should be transparent to device drivers, therefore it is possible to define a GPIO as being either active-high ("1" means "active", the default) or active-low ("0" means "active") so that drivers only need to worry about the logical signal and not about what happens at the line level.

<a id="rst-open-drain-and-open-source"></a>

### Open Drain and Open Source

Sometimes shared signals need to use "open drain" (where only the low signal level is actually driven), or "open source" (where only the high signal level is driven) signaling. That term applies to CMOS transistors; "open collector" is used for TTL. A pullup or pulldown resistor causes the high or low signal level. This is sometimes called a "wire-AND"; or more practically, from the negative logic (low=true) perspective this is a "wire-OR".

One common example of an open drain signal is a shared active-low IRQ line. Also, bidirectional data bus signals sometimes use open drain signals.

Some GPIO controllers directly support open drain and open source outputs; many don't. When you need open drain signaling but your hardware doesn't directly support it, there's a common idiom you can use to emulate it with any GPIO pin that can be used as either an input or an output:

> **LOW**: `gpiod_direction_output(gpio, 0)` ... this drives the signal and overrides the pullup.
>
> **HIGH**: `gpiod_direction_input(gpio)` ... this turns off the output, so the pullup (or some other device) controls the signal.

The same logic can be applied to emulate open source signaling, by driving the high signal and configuring the GPIO as input for low. This open drain/open source emulation can be handled transparently by the GPIO framework.

If you are "driving" the signal high but gpiod_get_value(gpio) reports a low value (after the appropriate rise time passes), you know some other component is driving the shared signal low. That's not necessarily an error. As one common example, that's how I2C clocks are stretched:  a slave that needs a slower clock delays the rising edge of SCK, and the I2C master adjusts its signaling rate accordingly.

---

# Supporting Legacy Boards

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> Many drivers in the kernel, such as leds-gpio and gpio-keys, are migrating away from using board-specific platform_data to a unified device properties interface. This interface allows drivers to be simpler and more generic, as they can…

<a id="rst-supporting-legacy-boards"></a>

Many drivers in the kernel, such as `leds-gpio` and `gpio-keys`, are migrating away from using board-specific `platform_data` to a unified device properties interface. This interface allows drivers to be simpler and more generic, as they can query properties in a standardized way.

On modern systems, these properties are provided via device tree. However, some older platforms have not been converted to device tree and instead rely on board files to describe their hardware configuration. To bridge this gap and allow these legacy boards to work with modern, generic drivers, the kernel provides a mechanism called **software nodes**.

This document provides a guide on how to convert a legacy board file from using `platform_data` and `gpiod_lookup_table` to the modern software node approach for describing GPIO-connected devices.

<a id="rst-the-core-idea-software-nodes"></a>

## The Core Idea: Software Nodes

Software nodes allow board-specific code to construct an in-memory, device-tree-like structure using struct software_node and struct property_entry. This structure can then be associated with a platform device, allowing drivers to use the standard device properties API (e.g., device_property_read_u32(), device_property_read_string()) to query configuration, just as they would on an ACPI or device tree system.

The gpiolib code has support for handling software nodes, so that if GPIO is described properly, as detailed in the section below, then regular gpiolib APIs, such as gpiod_get(), gpiod_get_optional(), and others will work.

<a id="rst-requirements-for-gpio-properties"></a>

### Requirements for GPIO Properties

When using software nodes to describe GPIO connections, the following requirements must be met for the GPIO core to correctly resolve the reference:

1. **The GPIO controller's software node "name" must match the controller's "label".** The gpiolib core uses this name to find the corresponding struct gpio_chip at runtime. This software node has to be registered, but need not be attached to the device representing the GPIO controller that is providing the GPIO in question. It may be left as a "free floating" node.

2. **The GPIO property must be a reference.** The `PROPERTY_ENTRY_GPIO()` macro handles this as it is an alias for `PROPERTY_ENTRY_REF()`.

3. **The reference must have exactly two arguments:**

   - The first argument is the GPIO offset within the controller.

   - The second argument is the flags for the GPIO line (e.g., GPIO_ACTIVE_HIGH, GPIO_ACTIVE_LOW).

The `PROPERTY_ENTRY_GPIO()` macro is the preferred way of defining GPIO properties in software nodes.

<a id="rst-conversion-example"></a>

## Conversion Example

Let's walk through an example of converting a board file that defines a GPIO- connected LED and a button.

<a id="rst-before-using-platform-data"></a>

### Before: Using Platform Data

A typical legacy board file might look like this:



```c
#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/gpio_keys.h>
#include <linux/gpio/machine.h>

#define MYBOARD_GPIO_CONTROLLER "gpio-foo"

/* LED setup */
static const struct gpio_led myboard_leds[] = {
      {
              .name = "myboard:green:status",
              .default_trigger = "heartbeat",
      },
};

static const struct gpio_led_platform_data myboard_leds_pdata = {
      .num_leds = ARRAY_SIZE(myboard_leds),
      .leds = myboard_leds,
};

static struct gpiod_lookup_table myboard_leds_gpios = {
      .dev_id = "leds-gpio",
      .table = {
              GPIO_LOOKUP_IDX(MYBOARD_GPIO_CONTROLLER, 42, NULL, 0, GPIO_ACTIVE_HIGH),
              { },
      },
};

/* Button setup */
static struct gpio_keys_button myboard_buttons[] = {
      {
              .code = KEY_WPS_BUTTON,
              .desc = "WPS Button",
              .active_low = 1,
      },
};

static const struct gpio_keys_platform_data myboard_buttons_pdata = {
      .buttons = myboard_buttons,
      .nbuttons = ARRAY_SIZE(myboard_buttons),
};

static struct gpiod_lookup_table myboard_buttons_gpios = {
      .dev_id = "gpio-keys",
      .table = {
              GPIO_LOOKUP_IDX(MYBOARD_GPIO_CONTROLLER, 15, NULL, 0, GPIO_ACTIVE_LOW),
              { },
      },
};

/* Device registration */
static int __init myboard_init(void)
{
      gpiod_add_lookup_table(&myboard_leds_gpios);
      gpiod_add_lookup_table(&myboard_buttons_gpios);

      platform_device_register_data(NULL, "leds-gpio", -1,
                                    &myboard_leds_pdata, sizeof(myboard_leds_pdata));
      platform_device_register_data(NULL, "gpio-keys", -1,
                                    &myboard_buttons_pdata, sizeof(myboard_buttons_pdata));

      return 0;
}
```

<a id="rst-after-using-software-nodes"></a>

### After: Using Software Nodes

Here is how the same configuration can be expressed using software nodes.

<a id="rst-step-1-define-the-gpio-controller-node"></a>

#### Step 1: Define the GPIO Controller Node

First, define a software node that represents the GPIO controller that the LEDs and buttons are connected to. The `name` of this node must match the name of the driver for the GPIO controller (e.g., "gpio-foo").



```c
#include <linux/property.h>
#include <linux/gpio/property.h>

#define MYBOARD_GPIO_CONTROLLER "gpio-foo"

static const struct software_node myboard_gpio_controller_node = {
      .name = MYBOARD_GPIO_CONTROLLER,
};
```

<a id="rst-step-2-define-consumer-device-nodes-and-properties"></a>

#### Step 2: Define Consumer Device Nodes and Properties

Next, define the software nodes for the consumer devices (the LEDs and buttons). This involves creating a parent node for each device type and child nodes for each individual LED or button.



```c
/* LED setup */
static const struct software_node myboard_leds_node = {
      .name = "myboard-leds",
};

static const struct property_entry myboard_status_led_props[] = {
      PROPERTY_ENTRY_STRING("label", "myboard:green:status"),
      PROPERTY_ENTRY_STRING("linux,default-trigger", "heartbeat"),
      PROPERTY_ENTRY_GPIO("gpios", &myboard_gpio_controller_node, 42, GPIO_ACTIVE_HIGH),
      { }
};

static const struct software_node myboard_status_led_swnode = {
      .name = "status-led",
      .parent = &myboard_leds_node,
      .properties = myboard_status_led_props,
};

/* Button setup */
static const struct software_node myboard_keys_node = {
      .name = "myboard-keys",
};

static const struct property_entry myboard_wps_button_props[] = {
      PROPERTY_ENTRY_STRING("label", "WPS Button"),
      PROPERTY_ENTRY_U32("linux,code", KEY_WPS_BUTTON),
      PROPERTY_ENTRY_GPIO("gpios", &myboard_gpio_controller_node, 15, GPIO_ACTIVE_LOW),
      { }
};

static const struct software_node myboard_wps_button_swnode = {
      .name = "wps-button",
      .parent = &myboard_keys_node,
      .properties = myboard_wps_button_props,
};
```

<a id="rst-step-3-group-and-register-the-nodes"></a>

#### Step 3: Group and Register the Nodes

For maintainability, it is often beneficial to group all software nodes into a single array and register them with one call.



```c
static const struct software_node * const myboard_swnodes[] = {
      &myboard_gpio_controller_node,
      &myboard_leds_node,
      &myboard_status_led_swnode,
      &myboard_keys_node,
      &myboard_wps_button_swnode,
      NULL
};

static int __init myboard_init(void)
{
      int error;

      error = software_node_register_node_group(myboard_swnodes);
      if (error) {
              pr_err("Failed to register software nodes: %d\n", error);
              return error;
      }

      // ... platform device registration follows
}
```

> [!NOTE]
>
> When splitting registration of nodes by devices that they represent, it is essential that the software node representing the GPIO controller itself is registered first, before any of the nodes that reference it.

<a id="rst-step-4-register-platform-devices-with-software-nodes"></a>

#### Step 4: Register Platform Devices with Software Nodes

Finally, register the platform devices and associate them with their respective software nodes using the `fwnode` field in struct platform_device_info.



```c
static struct platform_device *leds_pdev;
static struct platform_device *keys_pdev;

static int __init myboard_init(void)
{
      struct platform_device_info pdev_info;
      int error;

      error = software_node_register_node_group(myboard_swnodes);
      if (error)
              return error;

      memset(&pdev_info, 0, sizeof(pdev_info));
      pdev_info.name = "leds-gpio";
      pdev_info.id = PLATFORM_DEVID_NONE;
      pdev_info.fwnode = software_node_fwnode(&myboard_leds_node);
      leds_pdev = platform_device_register_full(&pdev_info);
      if (IS_ERR(leds_pdev)) {
              error = PTR_ERR(leds_pdev);
              goto err_unregister_nodes;
      }

      memset(&pdev_info, 0, sizeof(pdev_info));
      pdev_info.name = "gpio-keys";
      pdev_info.id = PLATFORM_DEVID_NONE;
      pdev_info.fwnode = software_node_fwnode(&myboard_keys_node);
      keys_pdev = platform_device_register_full(&pdev_info);
      if (IS_ERR(keys_pdev)) {
              error = PTR_ERR(keys_pdev);
              platform_device_unregister(leds_pdev);
              goto err_unregister_nodes;
      }

      return 0;

err_unregister_nodes:
      software_node_unregister_node_group(myboard_swnodes);
      return error;
}

static void __exit myboard_exit(void)
{
      platform_device_unregister(keys_pdev);
      platform_device_unregister(leds_pdev);
      software_node_unregister_node_group(myboard_swnodes);
}
```

With these changes, the generic `leds-gpio` and `gpio-keys` drivers will be able to probe successfully and get their configuration from the properties defined in the software nodes, removing the need for board-specific platform data.

---

# PCA953x I²C GPIO expander compatibility list

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> I went through all the datasheets and created this note listing chip functions and register layouts.

<a id="rst-pca953x-i2c-gpio-expander-compatibility-list"></a>

**Author:** Levente Révész &lt;[levente.revesz@eilabs.com](<mailto:levente.revesz@eilabs.com>)&gt;

I went through all the datasheets and created this note listing chip functions and register layouts.

<a id="rst-overview-of-chips"></a>

## Overview of chips

<a id="rst-chips-with-the-basic-4-registers"></a>

### Chips with the basic 4 registers

These chips have 4 register banks: input, output, invert and direction. Each of these banks contains (lines/8) registers, one for each GPIO port.

Banks offset is always a power of 2:

- 4 lines  -&gt; bank offset is 1

- 8 lines  -&gt; bank offset is 1

- 16 lines -&gt; bank offset is 2

- 24 lines -&gt; bank offset is 4

- 32 lines -&gt; bank offset is 4

- 40 lines -&gt; bank offset is 8

For example, register layout of GPIO expander with 24 lines:


<table>
<thead>
<tr>
<th>


addr

</th>
<th>


function

</th>
<th>


bank

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


00

</td>
<td>


input port0

</td>
<td rowspan="3">


bank 0

</td>
</tr>
<tr>
<td>


01

</td>
<td>


input port1

</td>
</tr>
<tr>
<td>


02

</td>
<td>


input port2

</td>
</tr>
<tr>
<td>


03

</td>
<td>


n/a

</td>
<td>




</td>
</tr>
<tr>
<td>


04

</td>
<td>


output port0

</td>
<td rowspan="3">


bank 1

</td>
</tr>
<tr>
<td>


05

</td>
<td>


output port1

</td>
</tr>
<tr>
<td>


06

</td>
<td>


output port2

</td>
</tr>
<tr>
<td>


07

</td>
<td>


n/a

</td>
<td>




</td>
</tr>
<tr>
<td>


08

</td>
<td>


invert port0

</td>
<td rowspan="3">


bank 2

</td>
</tr>
<tr>
<td>


09

</td>
<td>


invert port1

</td>
</tr>
<tr>
<td>


0A

</td>
<td>


invert port2

</td>
</tr>
<tr>
<td>


0B

</td>
<td>


n/a

</td>
<td>




</td>
</tr>
<tr>
<td>


0C

</td>
<td>


direction port0

</td>
<td rowspan="3">


bank 3

</td>
</tr>
<tr>
<td>


0D

</td>
<td>


direction port1

</td>
</tr>
<tr>
<td>


0E

</td>
<td>


direction port2

</td>
</tr>
<tr>
<td>


0F

</td>
<td>


n/a

</td>
<td>




</td>
</tr>
</tbody>
</table>

> [!NOTE]
>
> This is followed by all supported chips, except by pcal6534.

The table below shows the offsets for each of the compatible chips:


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


lines

</th>
<th>


interrupt

</th>
<th>


input

</th>
<th>


output

</th>
<th>


invert

</th>
<th>


direction

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pca9536

</td>
<td>


4

</td>
<td>


no

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pca9537

</td>
<td>


4

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pca6408

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


tca6408

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pca9534

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pca9538

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pca9554

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


tca9554

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pca9556

</td>
<td>


8

</td>
<td>


no

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pca9557

</td>
<td>


8

</td>
<td>


no

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pca6107

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pca6416

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


tca6416

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


pca9535

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


pca9539

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


tca9539

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


pca9555

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


max7318

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


tca6424

</td>
<td>


24

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


04

</td>
<td>


08

</td>
<td>


0C

</td>
</tr>
</tbody>
</table>

<a id="rst-chips-with-additional-timeout-en-register"></a>

### Chips with additional timeout_en register

These Maxim chips have a bus timeout function which can be enabled in the timeout_en register. This is present in only two chips. Defaults to timeout disabled.


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


lines

</th>
<th>


interrupt

</th>
<th>


input

</th>
<th>


output

</th>
<th>


invert

</th>
<th>


direction

</th>
<th>


timeout_en

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


max7310

</td>
<td>


8

</td>
<td>


no

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
<td>


04

</td>
</tr>
<tr>
<td>


max7312

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
<td>


08

</td>
</tr>
</tbody>
</table>

<a id="rst-chips-with-additional-int-mask-register"></a>

### Chips with additional int_mask register

These chips have an interrupt mask register in addition to the 4 basic registers. The interrupt masks default to all interrupts disabled. To use interrupts with these chips, the driver has to set the int_mask register.


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


lines

</th>
<th>


interrupt

</th>
<th>


input

</th>
<th>


output

</th>
<th>


invert

</th>
<th>


direction

</th>
<th>


int_mask

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pca9505

</td>
<td>


40

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


08

</td>
<td>


10

</td>
<td>


18

</td>
<td>


20

</td>
</tr>
<tr>
<td>


pca9506

</td>
<td>


40

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


08

</td>
<td>


10

</td>
<td>


18

</td>
<td>


20

</td>
</tr>
</tbody>
</table>

<a id="rst-chips-with-additional-int-mask-and-out-conf-registers"></a>

### Chips with additional int_mask and out_conf registers

This chip has an interrupt mask register, and an output port configuration register, which can select between push-pull and open-drain modes. Each bit controls two lines. Both of these registers are present in PCAL chips as well, albeit the out_conf works differently.


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


lines

</th>
<th>


interrupt

</th>
<th>


input

</th>
<th>


output

</th>
<th>


invert

</th>
<th>


direction

</th>
<th>


int_mask

</th>
<th>


out_conf

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pca9698

</td>
<td>


40

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


08

</td>
<td>


10

</td>
<td>


18

</td>
<td>


20

</td>
<td>


28

</td>
</tr>
</tbody>
</table>

pca9698 also has a "master output" register for setting all outputs per port to the same value simultaneously, and a chip specific mode register for various additional chip settings.


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


master_output

</th>
<th>


mode

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pca9698

</td>
<td>


29

</td>
<td>


2A

</td>
</tr>
</tbody>
</table>

<a id="rst-chips-with-led-blink-and-intensity-control"></a>

### Chips with LED blink and intensity control

These Maxim chips have no invert register.

They have two sets of output registers (output0 and output1). An internal timer alternates the effective output between the values set in these registers, if blink mode is enabled in the blink register. The master_intensity register and the intensity registers together define the PWM intensity value for each pair of outputs.

These chips can be used as simple GPIO expanders if the driver handles the input, output0 and direction registers.


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


lines

</th>
<th>


interrupt

</th>
<th>


input

</th>
<th>


output0

</th>
<th>


direction

</th>
<th>


output1

</th>
<th>


master_intensity

</th>
<th>


blink

</th>
<th>


intensity

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


max7315

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


03

</td>
<td>


09

</td>
<td>


0E

</td>
<td>


0F

</td>
<td>


10

</td>
</tr>
<tr>
<td>


max7313

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


06

</td>
<td>


0A

</td>
<td>


0E

</td>
<td>


0F

</td>
<td>


10

</td>
</tr>
</tbody>
</table>

<a id="rst-basic-pcal-chips"></a>

### Basic PCAL chips


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


lines

</th>
<th>


interrupt

</th>
<th>


input

</th>
<th>


output

</th>
<th>


invert

</th>
<th>


direction

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pcal6408

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pcal9554b

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


pcal6416

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


pcal9535

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


pcal9555a

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
<tr>
<td>


tcal6408

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
</tr>
<tr>
<td>


tcal6416

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
</tr>
</tbody>
</table>

These chips have several additional features:

> 1. output drive strength setting (out_strength)
>
> 2. input latch (in_latch)
>
> 3. pull-up/pull-down (pull_in, pull_sel)
>
> 4. push-pull/open-drain outputs (out_conf)
>
> 5. interrupt mask and interrupt status (int_mask, int_status)


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


out_strength

</th>
<th>


in_latch

</th>
<th>


pull_en

</th>
<th>


pull_sel

</th>
<th>


int_mask

</th>
<th>


int_status

</th>
<th>


out_conf

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pcal6408

</td>
<td>


40

</td>
<td>


42

</td>
<td>


43

</td>
<td>


44

</td>
<td>


45

</td>
<td>


46

</td>
<td>


4F

</td>
</tr>
<tr>
<td>


pcal9554b

</td>
<td>


40

</td>
<td>


42

</td>
<td>


43

</td>
<td>


44

</td>
<td>


45

</td>
<td>


46

</td>
<td>


4F

</td>
</tr>
<tr>
<td>


pcal6416

</td>
<td>


40

</td>
<td>


44

</td>
<td>


46

</td>
<td>


48

</td>
<td>


4A

</td>
<td>


4C

</td>
<td>


4F

</td>
</tr>
<tr>
<td>


pcal9535

</td>
<td>


40

</td>
<td>


44

</td>
<td>


46

</td>
<td>


48

</td>
<td>


4A

</td>
<td>


4C

</td>
<td>


4F

</td>
</tr>
<tr>
<td>


pcal9555a

</td>
<td>


40

</td>
<td>


44

</td>
<td>


46

</td>
<td>


48

</td>
<td>


4A

</td>
<td>


4C

</td>
<td>


4F

</td>
</tr>
<tr>
<td>


tcal6408

</td>
<td>


40

</td>
<td>


42

</td>
<td>


43

</td>
<td>


44

</td>
<td>


45

</td>
<td>


46

</td>
<td>


4F

</td>
</tr>
<tr>
<td>


tcal6416

</td>
<td>


40

</td>
<td>


44

</td>
<td>


46

</td>
<td>


48

</td>
<td>


4A

</td>
<td>


4C

</td>
<td>


4F

</td>
</tr>
</tbody>
</table>

Currently the driver has support for the input latch, pull-up/pull-down and uses int_mask and int_status for interrupts.

<a id="rst-pcal-chips-with-extended-interrupt-and-output-configuration-functions"></a>

### PCAL chips with extended interrupt and output configuration functions


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


lines

</th>
<th>


interrupt

</th>
<th>


input

</th>
<th>


output

</th>
<th>


invert

</th>
<th>


direction

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pcal6524

</td>
<td>


24

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


04

</td>
<td>


08

</td>
<td>


0C

</td>
</tr>
<tr>
<td>


pcal6534

</td>
<td>


34

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


05

</td>
<td>


0A

</td>
<td>


0F

</td>
</tr>
</tbody>
</table>

These chips have the full PCAL register set, plus the following functions:

> 1. interrupt event selection: level, rising, falling, any edge
>
> 2. clear interrupt status per line
>
> 3. read input without clearing interrupt status
>
> 4. individual output config (push-pull/open-drain) per output line
>
> 5. debounce inputs


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


out_strength

</th>
<th>


in_latch

</th>
<th>


pull_en

</th>
<th>


pull_sel

</th>
<th>


int_mask

</th>
<th>


int_status

</th>
<th>


out_conf

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pcal6524

</td>
<td>


40

</td>
<td>


48

</td>
<td>


4C

</td>
<td>


50

</td>
<td>


54

</td>
<td>


58

</td>
<td>


5C

</td>
</tr>
<tr>
<td>


pcal6534

</td>
<td>


30

</td>
<td>


3A

</td>
<td>


3F

</td>
<td>


44

</td>
<td>


49

</td>
<td>


4E

</td>
<td>


53

</td>
</tr>
</tbody>
</table>


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


int_edge

</th>
<th>


int_clear

</th>
<th>


input_status

</th>
<th>


indiv_out_conf

</th>
<th>


debounce

</th>
<th>


debounce_count

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pcal6524

</td>
<td>


60

</td>
<td>


68

</td>
<td>


6C

</td>
<td>


70

</td>
<td>


74

</td>
<td>


76

</td>
</tr>
<tr>
<td>


pcal6534

</td>
<td>


54

</td>
<td>


5E

</td>
<td>


63

</td>
<td>


68

</td>
<td>


6D

</td>
<td>


6F

</td>
</tr>
</tbody>
</table>

As can be seen in the table above, pcal6534 does not follow the usual bank spacing rule. Its banks are closely packed instead.

<a id="rst-pca957x-chips-with-a-completely-different-register-layout"></a>

### PCA957X chips with a completely different register layout

These chips have the basic 4 registers, but at unusual addresses.

Additionally, they have:

> 1. pull-up/pull-down (pull_sel)
>
> 2. a global pull enable, defaults to disabled (config)
>
> 3. interrupt mask, interrupt status (int_mask, int_status)


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


lines

</th>
<th>


interrupt

</th>
<th>


input

</th>
<th>


invert

</th>
<th>


config

</th>
<th>


pull_sel

</th>
<th>


direction

</th>
<th>


output

</th>
<th>


int_mask

</th>
<th>


int_status

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pca9574

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
<td>


04

</td>
<td>


05

</td>
<td>


06

</td>
<td>


07

</td>
</tr>
<tr>
<td>


pca9575

</td>
<td>


16

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


02

</td>
<td>


04

</td>
<td>


06

</td>
<td>


08

</td>
<td>


0A

</td>
<td>


0C

</td>
<td>


0E

</td>
</tr>
</tbody>
</table>

Currently the driver supports none of the advanced features.

<a id="rst-xra1202"></a>

### XRA1202

Basic 4 registers, plus advanced features:

> 1. interrupt mask, defaults to interrupts disabled
>
> 2. interrupt status
>
> 3. interrupt event selection, level, rising, falling, any edge (int_mask, rising_mask, falling_mask)
>
> 4. pull-up (no pull-down)
>
> 5. tri-state
>
> 6. debounce


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


lines

</th>
<th>


interrupt

</th>
<th>


input

</th>
<th>


output

</th>
<th>


invert

</th>
<th>


direction

</th>
<th>


pullup_en

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


xra1202

</td>
<td>


8

</td>
<td>


yes

</td>
<td>


00

</td>
<td>


01

</td>
<td>


02

</td>
<td>


03

</td>
<td>


04

</td>
</tr>
</tbody>
</table>


<table>
<thead>
<tr>
<th>


compatible

</th>
<th>


int_mask

</th>
<th>


tristate

</th>
<th>


int_status

</th>
<th>


rising_mask

</th>
<th>


falling_mask

</th>
<th>


debounce

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


xra1202

</td>
<td>


05

</td>
<td>


06

</td>
<td>


07

</td>
<td>


08

</td>
<td>


09

</td>
<td>


0A

</td>
</tr>
</tbody>
</table>

<a id="rst-overview-of-functions"></a>

## Overview of functions

This section lists chip functions that are supported by the driver already, or are at least common in multiple chips.

<a id="rst-input-output-invert-direction"></a>

### Input, Output, Invert, Direction

The basic 4 GPIO functions are present in all but one chip category, i.e. [Chips with LED blink and intensity control](<#rst-chips-with-led-blink-and-intensity-control>) are missing the invert register.

3 different layouts are used for these registers:

> 1. - **banks 0, 1, 2, 3 with bank offsets of 2^n**
>
>      - all other chips
>
> 2. - **banks 0, 1, 2, 3 with closely packed banks**
>
>      - pcal6534
>
> 3. - **banks 0, 5, 1, 4 with bank offsets of 2^n**
>
>      - pca9574
>
>      - pca9575

<a id="rst-interrupts"></a>

### Interrupts

<a id="rst-only-an-interrupt-mask-register"></a>

#### Only an interrupt mask register

The same layout is used for all of these:

> 1. - **bank 5 with bank offsets of 2^n**
>
>      - pca9505
>
>      - pca9506
>
>      - pca9698

<a id="rst-interrupt-mask-and-interrupt-status-registers"></a>

#### Interrupt mask and interrupt status registers

These work the same way in all of the chips: mask and status have one bit per line, 1 in the mask means interrupt enabled.

Layouts:

> 1. - **base offset 0x40, bank 5 and bank 6, bank offsets of 2^n**
>
>      - pcal6408
>
>      - pcal6416
>
>      - pcal9535
>
>      - pcal9554b
>
>      - pcal9555a
>
>      - pcal6524
>
>      - tcal6408
>
>      - tcal6416
>
> 2. - **base offset 0x30, bank 5 and 6, closely packed banks**
>
>      - pcal6534
>
> 3. - **bank 6 and 7, bank offsets of 2^n**
>
>      - pca9574
>
>      - pca9575
>
> 4. - **bank 5 and 7, bank offsets of 2^n**
>
>      - xra1202

<a id="rst-interrupt-on-specific-edges"></a>

#### Interrupt on specific edges

[PCAL chips with extended interrupt and output configuration functions](<#rst-pcal-chips-with-extended-interrupt-and-output-configuration-functions>) have an int_edge register. This contains 2 bits per line, one of 4 events can be selected for each line:

> 0: level, 1: rising edge, 2: falling edge, 3: any edge

Layouts:

> 1. base offset 0x40, bank 7, bank offsets of 2^n
>
>    > - pcal6524
>
> 2. base offset 0x30, bank 7 + offset 0x01, closely packed banks (out_conf is 1 byte, not (lines/8) bytes, hence the 0x01 offset)
>
>    > - pcal6534

[XRA1202](<#rst-xra1202>) chips have a different mechanism for the same thing: they have a rising mask and a falling mask, with one bit per line.

Layout:

> 1. bank 5, bank offsets of 2^n

<a id="rst-input-latch"></a>

### Input latch

Only [Basic PCAL chips](<#rst-basic-pcal-chips>) and [PCAL chips with extended interrupt and output configuration functions](<#rst-pcal-chips-with-extended-interrupt-and-output-configuration-functions>) have this function. When the latch is enabled, the interrupt is not cleared until the input port is read. When the latch is disabled, the interrupt is cleared even if the input register is not read, if the input pin returns to the logic value it had before generating the interrupt. Defaults to latch disabled.

Currently the driver enables the latch for each line with interrupt enabled.

An interrupt status register records which pins triggered an interrupt. However, the status register and the input port register must be read separately; there is no atomic mechanism to read both simultaneously, so races are possible. Refer to the chapter [Interrupt source detection](<#rst-interrupt-source-detection>) to understand the implications of this and how the driver still makes use of the latching feature.

> 1. - **base offset 0x40, bank 2, bank offsets of 2^n**
>
>      - pcal6408
>
>      - pcal6416
>
>      - pcal9535
>
>      - pcal9554b
>
>      - pcal9555a
>
>      - pcal6524
>
>      - tcal6408
>
>      - tcal6416
>
> 2. - **base offset 0x30, bank 2, closely packed banks**
>
>      - pcal6534

<a id="rst-pull-up-and-pull-down"></a>

### Pull-up and pull-down

[Basic PCAL chips](<#rst-basic-pcal-chips>) and [PCAL chips with extended interrupt and output configuration functions](<#rst-pcal-chips-with-extended-interrupt-and-output-configuration-functions>) use the same mechanism: their pull_en register enables the pull-up or pull-down function, and their pull_sel register chooses the direction. They all use one bit per line.

> 0: pull-down, 1: pull-up

Layouts:

> 1. - **base offset 0x40, bank 3 (en) and 4 (sel), bank offsets of 2^n**
>
>      - pcal6408
>
>      - pcal6416
>
>      - pcal9535
>
>      - pcal9554b
>
>      - pcal9555a
>
>      - pcal6524
>
> 2. - **base offset 0x30, bank 3 (en) and 4 (sel), closely packed banks**
>
>      - pcal6534

[PCA957X chips with a completely different register layout](<#rst-pca957x-chips-with-a-completely-different-register-layout>) have a pull_sel register with one bit per line, and a global pull_en bit in their config register.

Layout:

> 1. - **bank 2 (config), bank 3 (sel), bank offsets of 2^n**
>
>      - pca9574
>
>      - pca9575

[XRA1202](<#rst-xra1202>) chips can only pull-up. They have a pullup_en register.

Layout:

> 1. - **bank 4, bank offsets of 2^n**
>
>      - xra1202

<a id="rst-push-pull-and-open-drain"></a>

### Push-pull and open-drain

[Chips with additional int_mask and out_conf registers](<#rst-chips-with-additional-int-mask-and-out-conf-registers>) have this function, but only for select IO ports. Register has 1 bit per 2 lines. In pca9698, only port0 and port1 have this function.

> 0: open-drain, 1: push-pull

Layout:

> 1. - **base offset 5\*bankoffset**
>
>      - pca9698

[Basic PCAL chips](<#rst-basic-pcal-chips>) have 1 bit per port in one single out_conf register. Only whole ports can be configured.

> 0: push-pull, 1: open-drain

Layout:

> 1. - **base offset 0x4F**
>
>      - pcal6408
>
>      - pcal6416
>
>      - pcal9535
>
>      - pcal9554b
>
>      - pcal9555a
>
>      - tcal6408
>
>      - tcal6416

[PCAL chips with extended interrupt and output configuration functions](<#rst-pcal-chips-with-extended-interrupt-and-output-configuration-functions>) can set this for each line individually. They have the same per-port out_conf register as [Basic PCAL chips](<#rst-basic-pcal-chips>), but they also have an indiv_out_conf register with one bit per line, which inverts the effect of the port-wise setting.

> 0: push-pull, 1: open-drain

Layouts:

> 1. base offset 0x40 + 7\*bankoffset (out_conf), base offset 0x60, bank 4 (indiv_out_conf) with bank offset of 2^n
>
>    > - pcal6524
>
> 2. base offset 0x30 + 7\*banksize (out_conf), base offset 0x54, bank 4 (indiv_out_conf), closely packed banks
>
>    > - pcal6534

This function is currently not supported by the driver.

<a id="rst-output-drive-strength"></a>

### Output drive strength

Only PCAL chips have this function. 2 bits per line.


<table>
<thead>
<tr>
<th>


bits

</th>
<th>


drive strength

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


00

</td>
<td>


0.25x

</td>
</tr>
<tr>
<td>


01

</td>
<td>


0.50x

</td>
</tr>
<tr>
<td>


10

</td>
<td>


0.75x

</td>
</tr>
<tr>
<td>


11

</td>
<td>


1.00x

</td>
</tr>
</tbody>
</table>

> 1. - **base offset 0x40, bank 0 and 1, bank offsets of 2^n**
>
>      - pcal6408
>
>      - pcal6416
>
>      - pcal9535
>
>      - pcal9554b
>
>      - pcal9555a
>
>      - pcal6524
>
>      - tcal6408
>
>      - tcal6416
>
> 2. - **base offset 0x30, bank 0 and 1, closely packed banks**
>
>      - pcal6534

Currently not supported by the driver.

<a id="rst-interrupt-source-detection"></a>

## Interrupt source detection

When triggered by the GPIO expander's interrupt, the driver determines which IRQs are pending by reading the input port register.

To be able to filter on specific interrupt events for all compatible devices, the driver keeps track of the previous input state of the lines, and emits an IRQ only for the correct edge or level. This system works irrespective of the number of enabled interrupts. Events will not be missed even if they occur between the GPIO expander's interrupt and the actual I2C read. Edges could of course be missed if the related signal level changes back to the value previously saved by the driver before the I2C read. PCAL variants offer input latching for that reason.

<a id="rst-pcal-input-latching"></a>

### PCAL input latching

The PCAL variants have an input latch and the driver enables this for all interrupt-enabled lines. The interrupt is then only cleared when the input port is read out. These variants provide an interrupt status register that records which pins triggered an interrupt, but the status and input registers cannot be read atomically. If another interrupt occurs on a different line after the status register has been read but before the input port register is sampled, that event will not be reflected in the earlier status snapshot, so relying solely on the interrupt status register is insufficient.

Thus, the PCAL variants also have to use the existing level-change logic.

For short pulses, the first edge is captured when the input register is read, but if the signal returns to its previous level before this read, the second edge is not observed. As a result, successive pulses can produce identical input values at read time and no level change is detected, causing interrupts to be missed. Below timing diagram shows this situation where the top signal is the input pin level and the bottom signal indicates the latched value:



```text
─────┐     ┌──*───────────────┐     ┌──*─────────────────┐     ┌──*───
     │     │  .               │     │  .                 │     │  .
     │     │  │               │     │  │                 │     │  │
     └──*──┘  │               └──*──┘  │                 └──*──┘  │
Input   │     │                  │     │                    │     │
        ▼     │                  ▼     │                    ▼     │
       IRQ    │                 IRQ    │                   IRQ    │
              .                        .                          .
─────┐        .┌──────────────┐        .┌────────────────┐        .┌──
     │         │              │         │                │         │
     │         │              │         │                │         │
     └────────*┘              └────────*┘                └────────*┘
Latched       │                        │                          │
              ▼                        ▼                          ▼
            READ 0                   READ 0                     READ 0
                                   NO CHANGE                  NO CHANGE
```

To deal with this, events indicated by the interrupt status register are merged with events detected through the existing level-change logic. As a result:

- short pulses, whose second edges are invisible, are detected via the interrupt status register, and

- interrupts that occur between the status and input reads are still caught by the generic level-change logic.

Note that this is still best-effort: the status and input registers are read separately, and short pulses on other lines may occur in between those reads. Such pulses can still be latched as an interrupt without leaving an observable level change at read time, and may not be attributable to a specific edge. This does not reduce detection compared to the generic path, but reflects inherent atomicity limitations.

<a id="rst-datasheets"></a>

## Datasheets

- MAX7310: [https://datasheets.maximintegrated.com/en/ds/MAX7310.pdf](<https://datasheets.maximintegrated.com/en/ds/MAX7310.pdf>)

- MAX7312: [https://datasheets.maximintegrated.com/en/ds/MAX7312.pdf](<https://datasheets.maximintegrated.com/en/ds/MAX7312.pdf>)

- MAX7313: [https://datasheets.maximintegrated.com/en/ds/MAX7313.pdf](<https://datasheets.maximintegrated.com/en/ds/MAX7313.pdf>)

- MAX7315: [https://datasheets.maximintegrated.com/en/ds/MAX7315.pdf](<https://datasheets.maximintegrated.com/en/ds/MAX7315.pdf>)

- MAX7318: [https://datasheets.maximintegrated.com/en/ds/MAX7318.pdf](<https://datasheets.maximintegrated.com/en/ds/MAX7318.pdf>)

- PCA6107: [https://pdf1.alldatasheet.com/datasheet-pdf/view/161780/TI/PCA6107.html](<https://pdf1.alldatasheet.com/datasheet-pdf/view/161780/TI/PCA6107.html>)

- PCA6408A: [https://www.nxp.com/docs/en/data-sheet/PCA6408A.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA6408A.pdf>)

- PCA6416A: [https://www.nxp.com/docs/en/data-sheet/PCA6416A.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA6416A.pdf>)

- PCA9505: [https://www.nxp.com/docs/en/data-sheet/PCA9505_9506.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9505_9506.pdf>)

- PCA9505: [https://www.nxp.com/docs/en/data-sheet/PCA9505_9506.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9505_9506.pdf>)

- PCA9534: [https://www.nxp.com/docs/en/data-sheet/PCA9534.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9534.pdf>)

- PCA9535: [https://www.nxp.com/docs/en/data-sheet/PCA9535_PCA9535C.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9535_PCA9535C.pdf>)

- PCA9536: [https://www.nxp.com/docs/en/data-sheet/PCA9536.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9536.pdf>)

- PCA9537: [https://www.nxp.com/docs/en/data-sheet/PCA9537.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9537.pdf>)

- PCA9538: [https://www.nxp.com/docs/en/data-sheet/PCA9538.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9538.pdf>)

- PCA9539: [https://www.nxp.com/docs/en/data-sheet/PCA9539_PCA9539R.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9539_PCA9539R.pdf>)

- PCA9554: [https://www.nxp.com/docs/en/data-sheet/PCA9554_9554A.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9554_9554A.pdf>)

- PCA9555: [https://www.nxp.com/docs/en/data-sheet/PCA9555.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9555.pdf>)

- PCA9556: [https://www.nxp.com/docs/en/data-sheet/PCA9556.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9556.pdf>)

- PCA9557: [https://www.nxp.com/docs/en/data-sheet/PCA9557.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9557.pdf>)

- PCA9574: [https://www.nxp.com/docs/en/data-sheet/PCA9574.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9574.pdf>)

- PCA9575: [https://www.nxp.com/docs/en/data-sheet/PCA9575.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9575.pdf>)

- PCA9698: [https://www.nxp.com/docs/en/data-sheet/PCA9698.pdf](<https://www.nxp.com/docs/en/data-sheet/PCA9698.pdf>)

- PCAL6408A: [https://www.nxp.com/docs/en/data-sheet/PCAL6408A.pdf](<https://www.nxp.com/docs/en/data-sheet/PCAL6408A.pdf>)

- PCAL6416A: [https://www.nxp.com/docs/en/data-sheet/PCAL6416A.pdf](<https://www.nxp.com/docs/en/data-sheet/PCAL6416A.pdf>)

- PCAL6524: [https://www.nxp.com/docs/en/data-sheet/PCAL6524.pdf](<https://www.nxp.com/docs/en/data-sheet/PCAL6524.pdf>)

- PCAL6534: [https://www.nxp.com/docs/en/data-sheet/PCAL6534.pdf](<https://www.nxp.com/docs/en/data-sheet/PCAL6534.pdf>)

- PCAL9535A: [https://www.nxp.com/docs/en/data-sheet/PCAL9535A.pdf](<https://www.nxp.com/docs/en/data-sheet/PCAL9535A.pdf>)

- PCAL9554B: [https://www.nxp.com/docs/en/data-sheet/PCAL9554B_PCAL9554C.pdf](<https://www.nxp.com/docs/en/data-sheet/PCAL9554B_PCAL9554C.pdf>)

- PCAL9555A: [https://www.nxp.com/docs/en/data-sheet/PCAL9555A.pdf](<https://www.nxp.com/docs/en/data-sheet/PCAL9555A.pdf>)

- TCA6408A: [https://www.ti.com/lit/gpn/tca6408a](<https://www.ti.com/lit/gpn/tca6408a>)

- TCA6416: [https://www.ti.com/lit/gpn/tca6416](<https://www.ti.com/lit/gpn/tca6416>)

- TCA6424: [https://www.ti.com/lit/gpn/tca6424](<https://www.ti.com/lit/gpn/tca6424>)

- TCA9539: [https://www.ti.com/lit/gpn/tca9539](<https://www.ti.com/lit/gpn/tca9539>)

- TCA9554: [https://www.ti.com/lit/gpn/tca9554](<https://www.ti.com/lit/gpn/tca9554>)

- XRA1202: [https://assets.maxlinear.com/web/documents/xra1202_1202p_101_042213.pdf](<https://assets.maxlinear.com/web/documents/xra1202_1202p_101_042213.pdf>)

---

# Using GPIO Lines in Linux

_Peios Kernel / Hardware and drivers / Driver development / GPIO_

> The Linux kernel exists to abstract and present hardware to users. GPIO lines as such are normally not user facing abstractions. The most obvious, natural and preferred way to use GPIO lines is to let kernel hardware drivers deal with them.

<a id="rst-using-gpio-lines-in-linux"></a>

The Linux kernel exists to abstract and present hardware to users. GPIO lines as such are normally not user facing abstractions. The most obvious, natural and preferred way to use GPIO lines is to let kernel hardware drivers deal with them.

For examples of already existing generic drivers that will also be good examples for any other kernel drivers you want to author, refer to [Documentation/driver-api/gpio/drivers-on-gpio.rst](/kernel/hardware/driver-api/gpio/drivers-on-gpio.md)

For any kind of mass produced system you want to support, such as servers, laptops, phones, tablets, routers, and any consumer or office or business goods using appropriate kernel drivers is paramount. Submit your code for inclusion in the upstream Linux kernel when you feel it is mature enough and you will get help to refine it, see [Documentation/process/submitting-patches.rst](/kernel/development/process/submitting-patches.md).

In Linux GPIO lines also have a userspace ABI.

The userspace ABI is intended for one-off deployments. Examples are prototypes, factory lines, maker community projects, workshop specimen, production tools, industrial automation, PLC-type use cases, door controllers, in short a piece of specialized equipment that is not produced by the numbers, requiring operators to have a deep knowledge of the equipment and knows about the software-hardware interface to be set up. They should not have a natural fit to any existing kernel subsystem and not be a good fit for an operating system, because of not being reusable or abstract enough, or involving a lot of non computer hardware related policy.

Applications that have a good reason to use the industrial I/O (IIO) subsystem from userspace will likely be a good fit for using GPIO lines from userspace as well.

Do not under any circumstances abuse the GPIO userspace ABI to cut corners in any product development projects. If you use it for prototyping, then do not productify the prototype: rewrite it using proper kernel drivers. Do not under any circumstances deploy any uniform products using GPIO from userspace.

The userspace ABI is a character device for each GPIO hardware unit (GPIO chip). These devices will appear on the system as `/dev/gpiochip0` thru `/dev/gpiochipN`. Examples of how to directly use the userspace ABI can be found in the kernel tree `tools/gpio` subdirectory.

For structured and managed applications, we recommend that you make use of the [libgpiod](<https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/>) library. This provides helper abstractions, command line utilities and arbitration for multiple simultaneous consumers on the same GPIO chip.

<a id="rst-libgpiod"></a>

---

# I3C subsystem

_Peios Kernel / Hardware and drivers / Driver development / I3C_

> Reference for I3C subsystem.

<a id="rst-i3c-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [I3C protocol](</kernel/hardware/driver-api/i3c/protocol.md>)
- [I3C device driver API](</kernel/hardware/driver-api/i3c/device-driver-api.md>)
- [I3C master controller driver API](</kernel/hardware/driver-api/i3c/master-driver-api.md>)

---

# I3C device driver API

_Peios Kernel / Hardware and drivers / Driver development / I3C_

> Reference for I3C device driver API.

<a id="rst-i3c-device-driver-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-enum-i3c_error_code"></a>`enum i3c_error_code`

I3C error codes

**Constants**

- `I3C_ERROR_UNKNOWN`: unknown error, usually means the error is not I3C
  related
- `I3C_ERROR_M0`: M0 error
- `I3C_ERROR_M1`: M1 error
- `I3C_ERROR_M2`: M2 error

**Description**

These are the standard error codes as defined by the I3C specification.
When -EIO is returned by the `i3c_device_do_i3c_xfers()` or
`i3c_device_send_hdr_cmds()` one can check the error code in
`struct_i3c_xfer.err` or `struct i3c_hdr_cmd`.err to get a better idea of
what went wrong.

#### <a id="c-enum-i3c_xfer_mode"></a>`enum i3c_xfer_mode`

I3C xfer mode ids

**Constants**

- `I3C_HDR_DDR`: DDR mode
- `I3C_HDR_TSP`: TSP mode
- `I3C_HDR_TSL`: TSL mode
- `I3C_SDR`: SDR mode (NOT HDR mode)

#### <a id="c-struct-i3c_xfer"></a>`struct i3c_xfer`

I3C data transfer

**Definition**

```c
struct i3c_xfer {
    union {
        u8 rnw;
        u8 cmd;
    };
    u16 len;
    u16 actual_len;
    union {
        void *in;
        const void *out;
    } data;
    enum i3c_error_code err;
};
```

**Members**

- `{unnamed_union}`: anonymous
- `rnw`: encodes the transfer direction. true for a read, false for a write
- `cmd`: Read/Write command in HDR mode, read: 0x80 - 0xff, write: 0x00 - 0x7f
- `len`: transfer length in bytes of the transfer
- `actual_len`: actual length in bytes are transferred by the controller
- `data`: input/output buffer
- `data.in`: input buffer. Must point to a DMA-able buffer
- `data.out`: output buffer. Must point to a DMA-able buffer
- `err`: I3C error code

#### <a id="c-enum-i3c_dcr"></a>`enum i3c_dcr`

I3C DCR values

**Constants**

- `I3C_DCR_GENERIC_DEVICE`: generic I3C device

#### <a id="c-struct-i3c_device_info"></a>`struct i3c_device_info`

I3C device information

**Definition**

```c
struct i3c_device_info {
    u64 pid;
    u8 bcr;
    u8 dcr;
    u8 static_addr;
    u8 dyn_addr;
    u8 hdr_cap;
    u8 max_read_ds;
    u8 max_write_ds;
    u8 max_ibi_len;
    u32 max_read_turnaround;
    u16 max_read_len;
    u16 max_write_len;
};
```

**Members**

- `pid`: Provisioned ID
- `bcr`: Bus Characteristic Register
- `dcr`: Device Characteristic Register
- `static_addr`: static/I2C address
- `dyn_addr`: dynamic address
- `hdr_cap`: supported HDR modes
- `max_read_ds`: max read speed information
- `max_write_ds`: max write speed information
- `max_ibi_len`: max IBI payload length
- `max_read_turnaround`: max read turn-around time in micro-seconds
- `max_read_len`: max private SDR read length in bytes
- `max_write_len`: max private SDR write length in bytes

**Description**

These are all basic information that should be advertised by an I3C device.
Some of them are optional depending on the device type and device
capabilities.
For each I3C slave attached to a master with
[`i3c_master_add_i3c_dev_locked()`](/kernel/hardware/driver-api/i3c/master-driver-api.md#c-i3c_master_add_i3c_dev_locked), the core will send the relevant CCC command
to retrieve these data.

#### <a id="c-struct-i3c_driver"></a>`struct i3c_driver`

I3C device driver

**Definition**

```c
struct i3c_driver {
    struct device_driver driver;
    int (*probe)(struct i3c_device *dev);
    void (*remove)(struct i3c_device *dev);
    const struct i3c_device_id *id_table;
};
```

**Members**

- `driver`: inherit from device_driver
- `probe`: I3C device probe method
- `remove`: I3C device remove method
- `id_table`: I3C device match table. Will be used by the framework to decide
  which device to bind to this driver

#### <a id="c-dev_to_i3cdev"></a>`dev_to_i3cdev()`

```c
dev_to_i3cdev(__dev)
```

Returns the I3C device containing **dev**

**Parameters**

- `__dev`: device object

**Return**

a pointer to an I3C device object.

#### <a id="c-module_i3c_driver"></a>`module_i3c_driver()`

```c
module_i3c_driver(__drv)
```

Register a module providing an I3C driver

**Parameters**

- `__drv`: the I3C driver to register

**Description**

Provide generic init/exit functions that simply register/unregister an I3C
driver.
Should be used by any driver that does not require extra init/cleanup steps.

#### <a id="c-i3c_i2c_driver_register"></a>`i3c_i2c_driver_register()`

```c
int i3c_i2c_driver_register(struct i3c_driver *i3cdrv, struct i2c_driver *i2cdrv)
```

Register an i2c and an i3c driver

**Parameters**

- `struct i3c_driver *i3cdrv`: the I3C driver to register
- `struct i2c_driver *i2cdrv`: the I2C driver to register

**Description**

This function registers both **i2cdev** and **i3cdev**, and fails if one of these
registrations fails. This is mainly useful for devices that support both I2C
and I3C modes.
Note that when CONFIG_I3C is not enabled, this function only registers the
I2C driver.

**Return**

0 if both registrations succeeds, a negative error code otherwise.

#### <a id="c-i3c_i2c_driver_unregister"></a>`i3c_i2c_driver_unregister()`

```c
void i3c_i2c_driver_unregister(struct i3c_driver *i3cdrv, struct i2c_driver *i2cdrv)
```

Unregister an i2c and an i3c driver

**Parameters**

- `struct i3c_driver *i3cdrv`: the I3C driver to register
- `struct i2c_driver *i2cdrv`: the I2C driver to register

**Description**

This function unregisters both **i3cdrv** and **i2cdrv**.
Note that when CONFIG_I3C is not enabled, this function only unregisters the
**i2cdrv**.

#### <a id="c-module_i3c_i2c_driver"></a>`module_i3c_i2c_driver()`

```c
module_i3c_i2c_driver(__i3cdrv, __i2cdrv)
```

Register a module providing an I3C and an I2C driver

**Parameters**

- `__i3cdrv`: the I3C driver to register
- `__i2cdrv`: the I2C driver to register

**Description**

Provide generic init/exit functions that simply register/unregister an I3C
and an I2C driver.
This macro can be used even if CONFIG_I3C is disabled, in this case, only
the I2C driver will be registered.
Should be used by any driver that does not require extra init/cleanup steps.

#### <a id="c-struct-i3c_ibi_setup"></a>`struct i3c_ibi_setup`

IBI setup object

**Definition**

```c
struct i3c_ibi_setup {
    unsigned int max_payload_len;
    unsigned int num_slots;
    void (*handler)(struct i3c_device *dev, const struct i3c_ibi_payload *payload);
};
```

**Members**

- `max_payload_len`: maximum length of the payload associated to an IBI. If one
  IBI appears to have a payload that is bigger than this
  number, the IBI will be rejected.
- `num_slots`: number of pre-allocated IBI slots. This should be chosen so that
  the system never runs out of IBI slots, otherwise you'll lose
  IBIs.
- `handler`: IBI handler, every time an IBI is received. This handler is called
  in a workqueue context. It is allowed to sleep and send new
  messages on the bus, though it's recommended to keep the
  processing done there as fast as possible to avoid delaying
  processing of other queued on the same workqueue.

**Description**

Temporary structure used to pass information to [`i3c_device_request_ibi()`](#c-i3c_device_request_ibi).
This object can be allocated on the stack since [`i3c_device_request_ibi()`](#c-i3c_device_request_ibi)
copies every bit of information and do not use it after
[`i3c_device_request_ibi()`](#c-i3c_device_request_ibi) has returned.



#### <a id="c-i3c_device_do_xfers"></a>`i3c_device_do_xfers()`

```c
int i3c_device_do_xfers(struct i3c_device *dev, struct i3c_xfer *xfers, int nxfers, enum i3c_xfer_mode mode)
```

do I3C transfers directed to a specific device

**Parameters**

- `struct i3c_device *dev`: device with which the transfers should be done
- `struct i3c_xfer *xfers`: array of transfers
- `int nxfers`: number of transfers
- `enum i3c_xfer_mode mode`: transfer mode

**Description**

Initiate one or several private SDR transfers with **dev**.

This function can sleep and thus cannot be called in atomic context.

**Return**

* 0 in case of success, a negative error core otherwise.
* -EAGAIN: controller lost address arbitration. Target (IBI, HJ or
  controller role request) win the bus. Client driver needs to resend the
  'xfers' some time later. See I3C spec ver 1.1.1 09-Jun-2021. Section:
  5.1.2.2.3.

#### <a id="c-i3c_device_do_setdasa"></a>`i3c_device_do_setdasa()`

```c
int i3c_device_do_setdasa(struct i3c_device *dev)
```

do I3C dynamic address assignement with static address

**Parameters**

- `struct i3c_device *dev`: device with which the DAA should be done

**Return**

0 in case of success, a negative error core otherwise.

#### <a id="c-i3c_device_get_info"></a>`i3c_device_get_info()`

```c
void i3c_device_get_info(const struct i3c_device *dev, struct i3c_device_info *info)
```

get I3C device information

**Parameters**

- `const struct i3c_device *dev`: device we want information on
- `struct i3c_device_info *info`: the information object to fill in

**Description**

Retrieve I3C dev info.

#### <a id="c-i3c_device_disable_ibi"></a>`i3c_device_disable_ibi()`

```c
int i3c_device_disable_ibi(struct i3c_device *dev)
```

Disable IBIs coming from a specific device

**Parameters**

- `struct i3c_device *dev`: device on which IBIs should be disabled

**Description**

This function disable IBIs coming from a specific device and wait for
all pending IBIs to be processed.

**Return**

0 in case of success, a negative error core otherwise.

#### <a id="c-i3c_device_enable_ibi"></a>`i3c_device_enable_ibi()`

```c
int i3c_device_enable_ibi(struct i3c_device *dev)
```

Enable IBIs coming from a specific device

**Parameters**

- `struct i3c_device *dev`: device on which IBIs should be enabled

**Description**

This function enable IBIs coming from a specific device and wait for
all pending IBIs to be processed. This should be called on a device
where [`i3c_device_request_ibi()`](#c-i3c_device_request_ibi) has succeeded.

Note that IBIs from this device might be received before this function
returns to its caller.

**Return**

0 in case of success, a negative error core otherwise.

#### <a id="c-i3c_device_request_ibi"></a>`i3c_device_request_ibi()`

```c
int i3c_device_request_ibi(struct i3c_device *dev, const struct i3c_ibi_setup *req)
```

Request an IBI

**Parameters**

- `struct i3c_device *dev`: device for which we should enable IBIs
- `const struct i3c_ibi_setup *req`: setup requested for this IBI

**Description**

This function is responsible for pre-allocating all resources needed to
process IBIs coming from **dev**. When this function returns, the IBI is not
enabled until [`i3c_device_enable_ibi()`](#c-i3c_device_enable_ibi) is called.

**Return**

0 in case of success, a negative error core otherwise.

#### <a id="c-i3c_device_free_ibi"></a>`i3c_device_free_ibi()`

```c
void i3c_device_free_ibi(struct i3c_device *dev)
```

Free all resources needed for IBI handling

**Parameters**

- `struct i3c_device *dev`: device on which you want to release IBI resources

**Description**

This function is responsible for de-allocating resources previously
allocated by [`i3c_device_request_ibi()`](#c-i3c_device_request_ibi). It should be called after disabling
IBIs with [`i3c_device_disable_ibi()`](#c-i3c_device_disable_ibi).

#### <a id="c-i3cdev_to_dev"></a>`i3cdev_to_dev()`

```c
struct device * i3cdev_to_dev(struct i3c_device *i3cdev)
```

Returns the device embedded in **i3cdev**

**Parameters**

- `struct i3c_device *i3cdev`: I3C device

**Return**

a pointer to a device object.

#### <a id="c-i3c_device_match_id"></a>`i3c_device_match_id()`

```c
const struct i3c_device_id * i3c_device_match_id(struct i3c_device *i3cdev, const struct i3c_device_id *id_table)
```

Returns the i3c_device_id entry matching **i3cdev**

**Parameters**

- `struct i3c_device *i3cdev`: I3C device
- `const struct i3c_device_id *id_table`: I3C device match table

**Return**

a pointer to an i3c_device_id object or NULL if there's no match.

#### <a id="c-i3c_device_get_supported_xfer_mode"></a>`i3c_device_get_supported_xfer_mode()`

```c
u32 i3c_device_get_supported_xfer_mode(struct i3c_device *dev)
```

Returns the supported transfer mode by connected master controller.

**Parameters**

- `struct i3c_device *dev`: I3C device

**Return**

a bit mask, which supported transfer mode, bit position is defined at
enum i3c_hdr_mode

#### <a id="c-i3c_driver_register_with_owner"></a>`i3c_driver_register_with_owner()`

```c
int i3c_driver_register_with_owner(struct i3c_driver *drv, struct module *owner)
```

register an I3C device driver

**Parameters**

- `struct i3c_driver *drv`: driver to register
- `struct module *owner`: module that owns this driver

**Description**

Register **drv** to the core.

**Return**

0 in case of success, a negative error core otherwise.

#### <a id="c-i3c_driver_unregister"></a>`i3c_driver_unregister()`

```c
void i3c_driver_unregister(struct i3c_driver *drv)
```

unregister an I3C device driver

**Parameters**

- `struct i3c_driver *drv`: driver to unregister

**Description**

Unregister **drv**.

---

# I3C master controller driver API

_Peios Kernel / Hardware and drivers / Driver development / I3C_

> Reference for I3C master controller driver API.

<a id="rst-i3c-master-controller-driver-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-i3c_bus_maintenance_lock"></a>`i3c_bus_maintenance_lock()`

```c
void i3c_bus_maintenance_lock(struct i3c_bus *bus)
```

Lock the bus for a maintenance operation

**Parameters**

- `struct i3c_bus *bus`: I3C bus to take the lock on

**Description**

This function takes the bus lock so that no other operations can occur on
the bus. This is needed for all kind of bus maintenance operation, like
- enabling/disabling slave events
- re-triggering DAA
- changing the dynamic address of a device
- relinquishing mastership
- ...

The reason for this kind of locking is that we don't want drivers and core
logic to rely on I3C device information that could be changed behind their
back.

#### <a id="c-i3c_bus_maintenance_unlock"></a>`i3c_bus_maintenance_unlock()`

```c
void i3c_bus_maintenance_unlock(struct i3c_bus *bus)
```

Release the bus lock after a maintenance operation

**Parameters**

- `struct i3c_bus *bus`: I3C bus to release the lock on

**Description**

Should be called when the bus maintenance operation is done. See
[`i3c_bus_maintenance_lock()`](#c-i3c_bus_maintenance_lock) for more details on what these maintenance
operations are.

#### <a id="c-i3c_bus_normaluse_lock"></a>`i3c_bus_normaluse_lock()`

```c
void i3c_bus_normaluse_lock(struct i3c_bus *bus)
```

Lock the bus for a normal operation

**Parameters**

- `struct i3c_bus *bus`: I3C bus to take the lock on

**Description**

This function takes the bus lock for any operation that is not a maintenance
operation (see [`i3c_bus_maintenance_lock()`](#c-i3c_bus_maintenance_lock) for a non-exhaustive list of
maintenance operations). Basically all communications with I3C devices are
normal operations (HDR, SDR transfers or CCC commands that do not change bus
state or I3C dynamic address).

Note that this lock is not guaranteeing serialization of normal operations.
In other words, transfer requests passed to the I3C master can be submitted
in parallel and I3C master drivers have to use their own locking to make
sure two different communications are not inter-mixed, or access to the
output/input queue is not done while the engine is busy.

#### <a id="c-i3c_bus_normaluse_unlock"></a>`i3c_bus_normaluse_unlock()`

```c
void i3c_bus_normaluse_unlock(struct i3c_bus *bus)
```

Release the bus lock after a normal operation

**Parameters**

- `struct i3c_bus *bus`: I3C bus to release the lock on

**Description**

Should be called when a normal operation is done. See
[`i3c_bus_normaluse_lock()`](#c-i3c_bus_normaluse_lock) for more details on what these normal operations
are.

#### <a id="c-i3c_master_get_free_addr"></a>`i3c_master_get_free_addr()`

```c
int i3c_master_get_free_addr(struct i3c_master_controller *master, u8 start_addr)
```

get a free address on the bus

**Parameters**

- `struct i3c_master_controller *master`: I3C master object
- `u8 start_addr`: where to start searching

**Description**

This function must be called with the bus lock held in write mode.

**Return**

the first free address starting at **start_addr** (included) or -ENOMEM
if there's no more address available.

#### <a id="c-i3c_master_entdaa_locked"></a>`i3c_master_entdaa_locked()`

```c
int i3c_master_entdaa_locked(struct i3c_master_controller *master)
```

start a DAA (Dynamic Address Assignment) procedure

**Parameters**

- `struct i3c_master_controller *master`: master used to send frames on the bus

**Description**

Send a ENTDAA CCC command to start a DAA procedure.

Note that this function only sends the ENTDAA CCC command, all the logic
behind dynamic address assignment has to be handled in the I3C master
driver.

This function must be called with the bus lock held in write mode.

**Return**

0 in case of success, a positive I3C error code if the error is
one of the official Mx error codes, and a negative error code otherwise.

#### <a id="c-i3c_master_disec_locked"></a>`i3c_master_disec_locked()`

```c
int i3c_master_disec_locked(struct i3c_master_controller *master, u8 addr, u8 evts)
```

send a DISEC CCC command

**Parameters**

- `struct i3c_master_controller *master`: master used to send frames on the bus
- `u8 addr`: a valid I3C slave address or `I3C_BROADCAST_ADDR`
- `u8 evts`: events to disable

**Description**

Send a DISEC CCC command to disable some or all events coming from a
specific slave, or all devices if **addr** is `I3C_BROADCAST_ADDR`.

This function must be called with the bus lock held in write mode.

**Return**

0 in case of success, a positive I3C error code if the error is
one of the official Mx error codes, and a negative error code otherwise.

#### <a id="c-i3c_master_enec_locked"></a>`i3c_master_enec_locked()`

```c
int i3c_master_enec_locked(struct i3c_master_controller *master, u8 addr, u8 evts)
```

send an ENEC CCC command

**Parameters**

- `struct i3c_master_controller *master`: master used to send frames on the bus
- `u8 addr`: a valid I3C slave address or `I3C_BROADCAST_ADDR`
- `u8 evts`: events to disable

**Description**

Sends an ENEC CCC command to enable some or all events coming from a
specific slave, or all devices if **addr** is `I3C_BROADCAST_ADDR`.

This function must be called with the bus lock held in write mode.

**Return**

0 in case of success, a positive I3C error code if the error is
one of the official Mx error codes, and a negative error code otherwise.

#### <a id="c-i3c_master_defslvs_locked"></a>`i3c_master_defslvs_locked()`

```c
int i3c_master_defslvs_locked(struct i3c_master_controller *master)
```

send a DEFSLVS CCC command

**Parameters**

- `struct i3c_master_controller *master`: master used to send frames on the bus

**Description**

Send a DEFSLVS CCC command containing all the devices known to the **master**.
This is useful when you have secondary masters on the bus to propagate
device information.

This should be called after all I3C devices have been discovered (in other
words, after the DAA procedure has finished) and instantiated in
[`i3c_master_controller_ops->bus_init()`](#c-struct-i3c_master_controller_ops).
It should also be called if a master ACKed an Hot-Join request and assigned
a dynamic address to the device joining the bus.

This function must be called with the bus lock held in write mode.

**Return**

0 in case of success, a positive I3C error code if the error is
one of the official Mx error codes, and a negative error code otherwise.

#### <a id="c-i3c_master_do_daa_ext"></a>`i3c_master_do_daa_ext()`

```c
int i3c_master_do_daa_ext(struct i3c_master_controller *master, bool rstdaa)
```

Dynamic Address Assignment (extended version)

**Parameters**

- `struct i3c_master_controller *master`: controller
- `bool rstdaa`: whether to first perform Reset of Dynamic Addresses (RSTDAA)

**Description**

Perform Dynamic Address Assignment with optional support for System
Hibernation (**rstdaa** is true).

After System Hibernation, Dynamic Addresses can have been reassigned at boot
time to different values. A simple strategy is followed to handle that.
Perform a Reset of Dynamic Addresses (RSTDAA) followed by the normal DAA
procedure which has provision for reassigning addresses that differ from the
previously recorded addresses.

**Return**

a 0 in case of success, an negative error code otherwise.

#### <a id="c-i3c_master_do_daa"></a>`i3c_master_do_daa()`

```c
int i3c_master_do_daa(struct i3c_master_controller *master)
```

do a DAA (Dynamic Address Assignment)

**Parameters**

- `struct i3c_master_controller *master`: master doing the DAA

**Description**

This function instantiates I3C device objects and adds them to the
I3C device list. All device information is automatically retrieved using
standard CCC commands.

**Return**

a 0 in case of success, an negative error code otherwise.

#### <a id="c-i3c_master_dma_map_single"></a>`i3c_master_dma_map_single()`

```c
struct i3c_dma * i3c_master_dma_map_single(struct device *dev, void *buf, size_t len, bool force_bounce, enum dma_data_direction dir)
```

Map buffer for single DMA transfer

**Parameters**

- `struct device *dev`: device object of a device doing DMA
- `void *buf`: destination/source buffer for DMA
- `size_t len`: length of transfer
- `bool force_bounce`: true, force to use a bounce buffer,
  false, function will auto check is a bounce buffer required
- `enum dma_data_direction dir`: DMA direction

**Description**

Map buffer for a DMA transfer and allocate a bounce buffer if required.

**Return**

I3C DMA transfer descriptor or NULL in case of error.

#### <a id="c-i3c_master_dma_unmap_single"></a>`i3c_master_dma_unmap_single()`

```c
void i3c_master_dma_unmap_single(struct i3c_dma *dma_xfer)
```

Unmap buffer after DMA

**Parameters**

- `struct i3c_dma *dma_xfer`: DMA transfer and mapping descriptor

**Description**

Unmap buffer and cleanup DMA transfer descriptor.

#### <a id="c-i3c_master_set_info"></a>`i3c_master_set_info()`

```c
int i3c_master_set_info(struct i3c_master_controller *master, const struct i3c_device_info *info)
```

set master device information

**Parameters**

- `struct i3c_master_controller *master`: master used to send frames on the bus
- `const struct i3c_device_info *info`: I3C device information

**Description**

Set master device info. This should be called from
[`i3c_master_controller_ops->bus_init()`](#c-struct-i3c_master_controller_ops).

Not all [`i3c_device_info`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-struct-i3c_device_info) fields are meaningful for a master device.
Here is a list of fields that should be properly filled:

- [`i3c_device_info->dyn_addr`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-struct-i3c_device_info)
- [`i3c_device_info->bcr`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-struct-i3c_device_info)
- [`i3c_device_info->dcr`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-struct-i3c_device_info)
- [`i3c_device_info->pid`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-struct-i3c_device_info)
- [`i3c_device_info->hdr_cap`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-struct-i3c_device_info) if `I3C_BCR_HDR_CAP` bit is set in
  [`i3c_device_info->bcr`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-struct-i3c_device_info)

This function must be called with the bus lock held in maintenance mode.

**Return**

0 if **info** contains valid information (not every piece of
information can be checked, but we can at least make sure **info->dyn_addr**
and **info->bcr** are correct), -EINVAL otherwise.

#### <a id="c-i3c_master_bus_init"></a>`i3c_master_bus_init()`

```c
int i3c_master_bus_init(struct i3c_master_controller *master)
```

initialize an I3C bus

**Parameters**

- `struct i3c_master_controller *master`: main master initializing the bus

**Description**

This function is following all initialisation steps described in the I3C
specification:

1. Attach I2C devs to the master so that the master can fill its internal
   device table appropriately

2. Call [`i3c_master_controller_ops->bus_init()`](#c-struct-i3c_master_controller_ops) method to initialize
   the master controller. That's usually where the bus mode is selected
   (pure bus or mixed fast/slow bus)

3. Instruct all devices on the bus to drop their dynamic address. This is
   particularly important when the bus was previously configured by someone
   else (for example the bootloader)

4. Disable all slave events.

5. Reserve address slots for I3C devices with init_dyn_addr. And if devices
   also have static_addr, try to pre-assign dynamic addresses requested by
   the FW with SETDASA and attach corresponding statically defined I3C
   devices to the master.

6. Do a DAA (Dynamic Address Assignment) to assign dynamic addresses to all
   remaining I3C devices

Once this is done, all I3C and I2C devices should be usable.

**Return**

a 0 in case of success, an negative error code otherwise.

#### <a id="c-i3c_master_add_i3c_dev_locked"></a>`i3c_master_add_i3c_dev_locked()`

```c
int i3c_master_add_i3c_dev_locked(struct i3c_master_controller *master, u8 addr)
```

add an I3C slave to the bus

**Parameters**

- `struct i3c_master_controller *master`: master used to send frames on the bus
- `u8 addr`: I3C slave dynamic address assigned to the device

**Description**

This function is instantiating an I3C device object and adding it to the
I3C device list. All device information are automatically retrieved using
standard CCC commands.

The I3C device object is returned in case the master wants to attach
private data to it using [`i3c_dev_set_master_data()`](#c-i3c_dev_set_master_data).

This function must be called with the bus lock held in write mode.

**Return**

a 0 in case of success, an negative error code otherwise.

#### <a id="c-i3c_master_queue_ibi"></a>`i3c_master_queue_ibi()`

```c
void i3c_master_queue_ibi(struct i3c_dev_desc *dev, struct i3c_ibi_slot *slot)
```

Queue an IBI

**Parameters**

- `struct i3c_dev_desc *dev`: the device this IBI is coming from
- `struct i3c_ibi_slot *slot`: the IBI slot used to store the payload

**Description**

Queue an IBI to the controller workqueue. The IBI handler attached to
the dev will be called from a workqueue context.

#### <a id="c-i3c_generic_ibi_free_pool"></a>`i3c_generic_ibi_free_pool()`

```c
void i3c_generic_ibi_free_pool(struct i3c_generic_ibi_pool *pool)
```

Free a generic IBI pool

**Parameters**

- `struct i3c_generic_ibi_pool *pool`: the IBI pool to free

**Description**

Free all IBI slots allated by a generic IBI pool.

#### <a id="c-i3c_generic_ibi_alloc_pool"></a>`i3c_generic_ibi_alloc_pool()`

```c
struct i3c_generic_ibi_pool * i3c_generic_ibi_alloc_pool(struct i3c_dev_desc *dev, const struct i3c_ibi_setup *req)
```

Create a generic IBI pool

**Parameters**

- `struct i3c_dev_desc *dev`: the device this pool will be used for
- `const struct i3c_ibi_setup *req`: IBI setup request describing what the device driver expects

**Description**

Create a generic IBI pool based on the information provided in **req**.

**Return**

a valid IBI pool in case of success, an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) otherwise.

#### <a id="c-i3c_generic_ibi_get_free_slot"></a>`i3c_generic_ibi_get_free_slot()`

```c
struct i3c_ibi_slot * i3c_generic_ibi_get_free_slot(struct i3c_generic_ibi_pool *pool)
```

Get a free slot from a generic IBI pool

**Parameters**

- `struct i3c_generic_ibi_pool *pool`: the pool to query an IBI slot on

**Description**

Search for a free slot in a generic IBI pool.
The slot should be returned to the pool using [`i3c_generic_ibi_recycle_slot()`](#c-i3c_generic_ibi_recycle_slot)
when it's no longer needed.

**Return**

a pointer to a free slot, or NULL if there's no free slot available.

#### <a id="c-i3c_generic_ibi_recycle_slot"></a>`i3c_generic_ibi_recycle_slot()`

```c
void i3c_generic_ibi_recycle_slot(struct i3c_generic_ibi_pool *pool, struct i3c_ibi_slot *s)
```

Return a slot to a generic IBI pool

**Parameters**

- `struct i3c_generic_ibi_pool *pool`: the pool to return the IBI slot to
- `struct i3c_ibi_slot *s`: IBI slot to recycle

**Description**

Add an IBI slot back to its generic IBI pool. Should be called from the
master driver struct_master_controller_ops->`recycle_ibi()` method.

#### <a id="c-i3c_master_register"></a>`i3c_master_register()`

```c
int i3c_master_register(struct i3c_master_controller *master, struct device *parent, const struct i3c_master_controller_ops *ops, bool secondary)
```

register an I3C master

**Parameters**

- `struct i3c_master_controller *master`: master used to send frames on the bus
- `struct device *parent`: the parent device (the one that provides this I3C master
  controller)
- `const struct i3c_master_controller_ops *ops`: the master controller operations
- `bool secondary`: true if you are registering a secondary master. Will return
  -EOPNOTSUPP if set to true since secondary masters are not yet
  supported

**Description**

This function takes care of everything for you:

- creates and initializes the I3C bus
- populates the bus with static I2C devs if **parent->of_node** is not
  NULL
- registers all I3C devices added by the controller during bus
  initialization
- registers the I2C adapter and all I2C devices

**Return**

0 in case of success, a negative error code otherwise.

#### <a id="c-i3c_master_unregister"></a>`i3c_master_unregister()`

```c
void i3c_master_unregister(struct i3c_master_controller *master)
```

unregister an I3C master

**Parameters**

- `struct i3c_master_controller *master`: master used to send frames on the bus

**Description**

Basically undo everything done in [`i3c_master_register()`](#c-i3c_master_register).



#### <a id="c-struct-i3c_i2c_dev_desc"></a>`struct i3c_i2c_dev_desc`

Common part of the I3C/I2C device descriptor

**Definition**

```c
struct i3c_i2c_dev_desc {
    struct list_head node;
    struct i3c_master_controller *master;
    void *master_priv;
};
```

**Members**

- `node`: node element used to insert the slot into the I2C or I3C device
  list
- `master`: I3C master that instantiated this device. Will be used to do
  I2C/I3C transfers
- `master_priv`: master private data assigned to the device. Can be used to
  add master specific information

**Description**

This structure is describing common I3C/I2C dev information.

#### <a id="c-struct-i2c_dev_boardinfo"></a>`struct i2c_dev_boardinfo`

I2C device board information

**Definition**

```c
struct i2c_dev_boardinfo {
    struct list_head node;
    struct i2c_board_info base;
    u8 lvr;
};
```

**Members**

- `node`: used to insert the boardinfo object in the I2C boardinfo list
- `base`: regular I2C board information
- `lvr`: LVR (Legacy Virtual Register) needed by the I3C core to know about
  the I2C device limitations

**Description**

This structure is used to attach board-level information to an I2C device.
Each I2C device connected on the I3C bus should have one.

#### <a id="c-struct-i2c_dev_desc"></a>`struct i2c_dev_desc`

I2C device descriptor

**Definition**

```c
struct i2c_dev_desc {
    struct i3c_i2c_dev_desc common;
    struct i2c_client *dev;
    u16 addr;
    u8 lvr;
};
```

**Members**

- `common`: common part of the I2C device descriptor
- `dev`: I2C device object registered to the I2C framework
- `addr`: I2C device address
- `lvr`: LVR (Legacy Virtual Register) needed by the I3C core to know about
  the I2C device limitations

**Description**

Each I2C device connected on the bus will have an i2c_dev_desc.
This object is created by the core and later attached to the controller
using `struct_i3c_master_controller->ops`->`attach_i2c_dev()`.

`struct _i2c_dev_desc` is the internal representation of an I2C device
connected on an I3C bus. This object is also passed to all
`struct _i3c_master_controller_ops` hooks.

#### <a id="c-struct-i3c_ibi_slot"></a>`struct i3c_ibi_slot`

I3C IBI (In-Band Interrupt) slot

**Definition**

```c
struct i3c_ibi_slot {
    struct work_struct work;
    struct i3c_dev_desc *dev;
    unsigned int len;
    void *data;
};
```

**Members**

- `work`: work associated to this slot. The IBI handler will be called from
  there
- `dev`: the I3C device that has generated this IBI
- `len`: length of the payload associated to this IBI
- `data`: payload buffer

**Description**

An IBI slot is an object pre-allocated by the controller and used when an
IBI comes in.
Every time an IBI comes in, the I3C master driver should find a free IBI
slot in its IBI slot pool, retrieve the IBI payload and queue the IBI using
[`i3c_master_queue_ibi()`](#c-i3c_master_queue_ibi).

How IBI slots are allocated is left to the I3C master driver, though, for
simple kmalloc-based allocation, the generic IBI slot pool can be used.

#### <a id="c-struct-i3c_device_ibi_info"></a>`struct i3c_device_ibi_info`

IBI information attached to a specific device

**Definition**

```c
struct i3c_device_ibi_info {
    struct completion all_ibis_handled;
    atomic_t pending_ibis;
    unsigned int max_payload_len;
    unsigned int num_slots;
    unsigned int enabled;
    struct workqueue_struct *wq;
    void (*handler)(struct i3c_device *dev, const struct i3c_ibi_payload *payload);
};
```

**Members**

- `all_ibis_handled`: used to be informed when no more IBIs are waiting to be
  processed. Used by [`i3c_device_disable_ibi()`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-i3c_device_disable_ibi) to wait for
  all IBIs to be dequeued
- `pending_ibis`: count the number of pending IBIs. Each pending IBI has its
  work element queued to the controller workqueue
- `max_payload_len`: maximum payload length for an IBI coming from this device.
  this value is specified when calling
  [`i3c_device_request_ibi()`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-i3c_device_request_ibi) and should not change at run
  time. All messages IBIs exceeding this limit should be
  rejected by the master
- `num_slots`: number of IBI slots reserved for this device
- `enabled`: reflect the IBI status
- `wq`: workqueue used to execute IBI handlers.
- `handler`: IBI handler specified at [`i3c_device_request_ibi()`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-i3c_device_request_ibi) call time. This
  handler will be called from the controller workqueue, and as such
  is allowed to sleep (though it is recommended to process the IBI
  as fast as possible to not stall processing of other IBIs queued
  on the same workqueue).
  New I3C messages can be sent from the IBI handler

**Description**

The `struct _i3c_device_ibi_info` object is allocated when
[`i3c_device_request_ibi()`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-i3c_device_request_ibi) is called and attached to a specific device. This
object is here to manage IBIs coming from a specific I3C device.

Note that this structure is the generic view of the IBI management
infrastructure. I3C master drivers may have their own internal
representation which they can associate to the device using
controller-private data.

#### <a id="c-struct-i3c_dev_boardinfo"></a>`struct i3c_dev_boardinfo`

I3C device board information

**Definition**

```c
struct i3c_dev_boardinfo {
    struct list_head node;
    u8 init_dyn_addr;
    u8 static_addr;
    u64 pid;
    struct device_node *of_node;
};
```

**Members**

- `node`: used to insert the boardinfo object in the I3C boardinfo list
- `init_dyn_addr`: initial dynamic address requested by the FW. We provide no
  guarantee that the device will end up using this address,
  but try our best to assign this specific address to the
  device
- `static_addr`: static address the I3C device listen on before it's been
  assigned a dynamic address by the master. Will be used during
  bus initialization to assign it a specific dynamic address
  before starting DAA (Dynamic Address Assignment)
- `pid`: I3C Provisioned ID exposed by the device. This is a unique identifier
  that may be used to attach boardinfo to i3c_dev_desc when the device
  does not have a static address
- `of_node`: optional DT node in case the device has been described in the DT

**Description**

This structure is used to attach board-level information to an I3C device.
Not all I3C devices connected on the bus will have a boardinfo. It's only
needed if you want to attach extra resources to a device or assign it a
specific dynamic address.

#### <a id="c-struct-i3c_dev_desc"></a>`struct i3c_dev_desc`

I3C device descriptor

**Definition**

```c
struct i3c_dev_desc {
    struct i3c_i2c_dev_desc common;
    struct i3c_device_info info;
    struct mutex ibi_lock;
    struct i3c_device_ibi_info *ibi;
    struct i3c_device *dev;
    const struct i3c_dev_boardinfo *boardinfo;
};
```

**Members**

- `common`: common part of the I3C device descriptor
- `info`: I3C device information. Will be automatically filled when you create
  your device with [`i3c_master_add_i3c_dev_locked()`](#c-i3c_master_add_i3c_dev_locked)
- `ibi_lock`: lock used to protect the `struct_i3c_device->ibi`
- `ibi`: IBI info attached to a device. Should be NULL until
  [`i3c_device_request_ibi()`](/kernel/hardware/driver-api/i3c/device-driver-api.md#c-i3c_device_request_ibi) is called
- `dev`: pointer to the I3C device object exposed to I3C device drivers. This
  should never be accessed from I3C master controller drivers. Only core
  code should manipulate it in when updating the dev \<-> desc link or
  when propagating IBI events to the driver
- `boardinfo`: pointer to the boardinfo attached to this I3C device

**Description**

Internal representation of an I3C device. This object is only used by the
core and passed to I3C master controller drivers when they're requested to
do some operations on the device.
The core maintains the link between the internal I3C dev descriptor and the
object exposed to the I3C device drivers (`struct _i3c_device`).

#### <a id="c-struct-i3c_device"></a>`struct i3c_device`

I3C device object

**Definition**

```c
struct i3c_device {
    struct device dev;
    struct i3c_dev_desc *desc;
    struct i3c_bus *bus;
};
```

**Members**

- `dev`: device object to register the I3C dev to the device model
- `desc`: pointer to an i3c device descriptor object. This link is updated
  every time the I3C device is rediscovered with a different dynamic
  address assigned
- `bus`: I3C bus this device is attached to

**Description**

I3C device object exposed to I3C device drivers. The takes care of linking
this object to the relevant `struct _i3c_dev_desc` one.
All I3C devs on the I3C bus are represented, including I3C masters. For each
of them, we have an instance of [`struct i3c_device`](#c-struct-i3c_device).

#### <a id="c-enum-i3c_bus_mode"></a>`enum i3c_bus_mode`

I3C bus mode

**Constants**

- `I3C_BUS_MODE_PURE`: only I3C devices are connected to the bus. No limitation
  expected
- `I3C_BUS_MODE_MIXED_FAST`: I2C devices with 50ns spike filter are present on
  the bus. The only impact in this mode is that the
  high SCL pulse has to stay below 50ns to trick I2C
  devices when transmitting I3C frames
- `I3C_BUS_MODE_MIXED_LIMITED`: I2C devices without 50ns spike filter are
  present on the bus. However they allow
  compliance up to the maximum SDR SCL clock
  frequency.
- `I3C_BUS_MODE_MIXED_SLOW`: I2C devices without 50ns spike filter are present
  on the bus

#### <a id="c-enum-i3c_open_drain_speed"></a>`enum i3c_open_drain_speed`

I3C open-drain speed

**Constants**

- `I3C_OPEN_DRAIN_SLOW_SPEED`: Slow open-drain speed for sending the first
  broadcast address. The first broadcast address at this speed
  will be visible to all devices on the I3C bus. I3C devices
  working in I2C mode will turn off their spike filter when
  switching into I3C mode.
- `I3C_OPEN_DRAIN_NORMAL_SPEED`: Normal open-drain speed in I3C bus mode.

#### <a id="c-enum-i3c_addr_slot_status"></a>`enum i3c_addr_slot_status`

I3C address slot status

**Constants**

- `I3C_ADDR_SLOT_FREE`: address is free
- `I3C_ADDR_SLOT_RSVD`: address is reserved
- `I3C_ADDR_SLOT_I2C_DEV`: address is assigned to an I2C device
- `I3C_ADDR_SLOT_I3C_DEV`: address is assigned to an I3C device
- `I3C_ADDR_SLOT_STATUS_MASK`: address slot mask
- `I3C_ADDR_SLOT_EXT_STATUS_MASK`: address slot mask with extended information
- `I3C_ADDR_SLOT_EXT_DESIRED`: the bitmask represents addresses that are preferred by some devices,
  such as the "assigned-address" property in a device tree source.
  On an I3C bus, addresses are assigned dynamically, and we need to know which
  addresses are free to use and which ones are already assigned.

**Description**

Addresses marked as reserved are those reserved by the I3C protocol
(broadcast address, ...).

#### <a id="c-struct-i3c_bus"></a>`struct i3c_bus`

I3C bus object

**Definition**

```c
struct i3c_bus {
    struct i3c_dev_desc *cur_master;
    int id;
    unsigned long addrslots[((I2C_MAX_ADDR + 1) * I3C_ADDR_SLOT_STATUS_BITS) / BITS_PER_LONG];
    enum i3c_bus_mode mode;
    struct {
        unsigned long i3c;
        unsigned long i2c;
    } scl_rate;
    struct {
        struct list_head i3c;
        struct list_head i2c;
    } devs;
    struct rw_semaphore lock;
};
```

**Members**

- `cur_master`: I3C master currently driving the bus. Since I3C is multi-master
  this can change over the time. Will be used to let a master
  know whether it needs to request bus ownership before sending
  a frame or not
- `id`: bus ID. Assigned by the framework when register the bus
- `addrslots`: a bitmap with 2-bits per-slot to encode the address status and
  ease the DAA (Dynamic Address Assignment) procedure (see
  [`enum i3c_addr_slot_status`](#c-enum-i3c_addr_slot_status))
- `mode`: bus mode (see [`enum i3c_bus_mode`](#c-enum-i3c_bus_mode))
- `scl_rate`: SCL signal rate for I3C and I2C mode
- `scl_rate.i3c`: maximum rate for the clock signal when doing I3C SDR/priv
  transfers
- `scl_rate.i2c`: maximum rate for the clock signal when doing I2C transfers
- `devs`: 2 lists containing all I3C/I2C devices connected to the bus
- `devs.i3c`: contains a list of I3C device descriptors representing I3C
  devices connected on the bus and successfully attached to the
  I3C master
- `devs.i2c`: contains a list of I2C device descriptors representing I2C
  devices connected on the bus and successfully attached to the
  I3C master
- `lock`: read/write lock on the bus. This is needed to protect against
  operations that have an impact on the whole bus and the devices
  connected to it. For example, when asking slaves to drop their
  dynamic address (RSTDAA CCC), we need to make sure no one is trying
  to send I3C frames to these devices.
  Note that this lock does not protect against concurrency between
  devices: several drivers can send different I3C/I2C frames through
  the same master in parallel. This is the responsibility of the
  master to guarantee that frames are actually sent sequentially and
  not interlaced

**Description**

The I3C bus is represented with its own object and not implicitly described
by the I3C master to cope with the multi-master functionality, where one bus
can be shared amongst several masters, each of them requesting bus ownership
when they need to.

#### <a id="c-struct-i3c_master_controller_ops"></a>`struct i3c_master_controller_ops`

I3C master methods

**Definition**

```c
struct i3c_master_controller_ops {
    int (*bus_init)(struct i3c_master_controller *master);
    void (*bus_cleanup)(struct i3c_master_controller *master);
    int (*attach_i3c_dev)(struct i3c_dev_desc *dev);
    int (*reattach_i3c_dev)(struct i3c_dev_desc *dev, u8 old_dyn_addr);
    void (*detach_i3c_dev)(struct i3c_dev_desc *dev);
    int (*do_daa)(struct i3c_master_controller *master);
    bool (*supports_ccc_cmd)(struct i3c_master_controller *master, const struct i3c_ccc_cmd *cmd);
    int (*send_ccc_cmd)(struct i3c_master_controller *master, struct i3c_ccc_cmd *cmd);
    int (*i3c_xfers)(struct i3c_dev_desc *dev, struct i3c_xfer *xfers, int nxfers, enum i3c_xfer_mode mode);
    int (*attach_i2c_dev)(struct i2c_dev_desc *dev);
    void (*detach_i2c_dev)(struct i2c_dev_desc *dev);
    int (*i2c_xfers)(struct i2c_dev_desc *dev, struct i2c_msg *xfers, int nxfers);
    int (*request_ibi)(struct i3c_dev_desc *dev, const struct i3c_ibi_setup *req);
    void (*free_ibi)(struct i3c_dev_desc *dev);
    int (*enable_ibi)(struct i3c_dev_desc *dev);
    int (*disable_ibi)(struct i3c_dev_desc *dev);
    void (*recycle_ibi_slot)(struct i3c_dev_desc *dev, struct i3c_ibi_slot *slot);
    int (*enable_hotjoin)(struct i3c_master_controller *master);
    int (*disable_hotjoin)(struct i3c_master_controller *master);
    int (*set_speed)(struct i3c_master_controller *master, enum i3c_open_drain_speed speed);
    int (*set_dev_nack_retry)(struct i3c_master_controller *master, unsigned long dev_nack_retry_cnt);
};
```

**Members**

- `bus_init`: hook responsible for the I3C bus initialization. You should at
  least call `master_set_info()` from there and set the bus mode.
  You can also put controller specific initialization in there.
  This method is mandatory.
- `bus_cleanup`: cleanup everything done in
  [`i3c_master_controller_ops->bus_init()`](#c-struct-i3c_master_controller_ops).
  This method is optional.
- `attach_i3c_dev`: called every time an I3C device is attached to the bus. It
  can be after a DAA or when a device is statically declared
  by the FW, in which case it will only have a static address
  and the dynamic address will be 0.
  When this function is called, device information have not
  been retrieved yet.
  This is a good place to attach master controller specific
  data to I3C devices.
  This method is optional.
- `reattach_i3c_dev`: called every time an I3C device has its addressed
  changed. It can be because the device has been powered
  down and has lost its address, or it can happen when a
  device had a static address and has been assigned a
  dynamic address with SETDASA.
  This method is optional.
- `detach_i3c_dev`: called when an I3C device is detached from the bus. Usually
  happens when the master device is unregistered.
  This method is optional.
- `do_daa`: do a DAA (Dynamic Address Assignment) procedure. This is procedure
  should send an ENTDAA CCC command and then add all devices
  discovered sure the DAA using [`i3c_master_add_i3c_dev_locked()`](#c-i3c_master_add_i3c_dev_locked).
  Add devices added with [`i3c_master_add_i3c_dev_locked()`](#c-i3c_master_add_i3c_dev_locked) will then be
  attached or re-attached to the controller.
  This method is mandatory.
- `supports_ccc_cmd`: should return true if the CCC command is supported, false
  otherwise.
  This method is optional, if not provided the core assumes
  all CCC commands are supported.
- `send_ccc_cmd`: send a CCC command
  This method is mandatory.
- `i3c_xfers`: do one or several I3C SDR or HDR transfers.
  This method is mandatory.
- `attach_i2c_dev`: called every time an I2C device is attached to the bus.
  This is a good place to attach master controller specific
  data to I2C devices.
  This method is optional.
- `detach_i2c_dev`: called when an I2C device is detached from the bus. Usually
  happens when the master device is unregistered.
  This method is optional.
- `i2c_xfers`: do one or several I2C transfers. Note that, unlike i3c
  transfers, the core does not guarantee that buffers attached to
  the transfers are DMA-safe. If drivers want to have DMA-safe
  buffers, they should use the [`i2c_get_dma_safe_msg_buf()`](/kernel/hardware/driver-api/buses/i2c.md#c-i2c_get_dma_safe_msg_buf)
  and [`i2c_put_dma_safe_msg_buf()`](/kernel/hardware/driver-api/buses/i2c.md#c-i2c_put_dma_safe_msg_buf) helpers provided by the I2C
  framework.
  This method is mandatory.
- `request_ibi`: attach an IBI handler to an I3C device. This implies defining
  an IBI handler and the constraints of the IBI (maximum payload
  length and number of pre-allocated slots).
  Some controllers support less IBI-capable devices than regular
  devices, so this method might return -`EBUSY` if there's no
  more space for an extra IBI registration
  This method is optional.
- `free_ibi`: free an IBI previously requested with ->`request_ibi()`. The IBI
  should have been disabled with ->[`disable_irq()`](/kernel/internals/core-api/genericirq.md#c-disable_irq) prior to that
  This method is mandatory only if ->request_ibi is not NULL.
- `enable_ibi`: enable the IBI. Only valid if ->`request_ibi()` has been called
  prior to ->`enable_ibi()`. The controller should first enable
  the IBI on the controller end (for example, unmask the hardware
  IRQ) and then send the ENEC CCC command (with the IBI flag set)
  to the I3C device.
  This method is mandatory only if ->request_ibi is not NULL.
- `disable_ibi`: disable an IBI. First send the DISEC CCC command with the IBI
  flag set and then deactivate the hardware IRQ on the
  controller end.
  This method is mandatory only if ->request_ibi is not NULL.
- `recycle_ibi_slot`: recycle an IBI slot. Called every time an IBI has been
  processed by its handler. The IBI slot should be put back
  in the IBI slot pool so that the controller can re-use it
  for a future IBI
  This method is mandatory only if ->request_ibi is not
  NULL.
- `enable_hotjoin`: enable hot join event detect.
- `disable_hotjoin`: disable hot join event detect.
- `set_speed`: adjust I3C open drain mode timing.
- `set_dev_nack_retry`: configure device NACK retry count for the master
  controller.

#### <a id="c-struct-i3c_master_controller"></a>`struct i3c_master_controller`

I3C master controller object

**Definition**

```c
struct i3c_master_controller {
    struct device dev;
    struct i3c_dev_desc *this;
    struct i2c_adapter i2c;
    const struct i3c_master_controller_ops *ops;
    unsigned int secondary : 1;
    unsigned int init_done : 1;
    unsigned int hotjoin: 1;
    unsigned int rpm_allowed: 1;
    unsigned int rpm_ibi_allowed: 1;
    struct {
        struct list_head i3c;
        struct list_head i2c;
    } boardinfo;
    struct i3c_bus bus;
    struct workqueue_struct *wq;
    unsigned int dev_nack_retry_count;
};
```

**Members**

- `dev`: device to be registered to the device-model
- `this`: an I3C device object representing this master. This device will be
  added to the list of I3C devs available on the bus
- `i2c`: I2C adapter used for backward compatibility. This adapter is
  registered to the I2C subsystem to be as transparent as possible to
  existing I2C drivers
- `ops`: master operations. See [`struct i3c_master_controller_ops`](#c-struct-i3c_master_controller_ops)
- `secondary`: true if the master is a secondary master
- `init_done`: true when the bus initialization is done
- `hotjoin`: true if the master support hotjoin
- `rpm_allowed`: true if Runtime PM allowed
- `rpm_ibi_allowed`: true if IBI and Hot-Join allowed while runtime suspended
- `boardinfo`: board-level information attached to devices connected on the bus
- `boardinfo.i3c`: list of I3C  boardinfo objects
- `boardinfo.i2c`: list of I2C boardinfo objects
- `bus`: I3C bus exposed by this master
- `wq`: workqueue which can be used by master
  drivers if they need to postpone operations that need to take place
  in a thread context. Typical examples are Hot Join processing which
  requires taking the bus lock in maintenance, which in turn, can only
  be done from a sleep-able context
- `dev_nack_retry_count`: retry count when slave device nack

**Description**

A [`struct i3c_master_controller`](#c-struct-i3c_master_controller) has to be registered to the I3C subsystem
through [`i3c_master_register()`](#c-i3c_master_register). None of [`struct i3c_master_controller`](#c-struct-i3c_master_controller) fields
should be set manually, just pass appropriate values to
[`i3c_master_register()`](#c-i3c_master_register).

#### <a id="c-i3c_bus_for_each_i2cdev"></a>`i3c_bus_for_each_i2cdev()`

```c
i3c_bus_for_each_i2cdev(bus, dev)
```

iterate over all I2C devices present on the bus

**Parameters**

- `bus`: the I3C bus
- `dev`: an I2C device descriptor pointer updated to point to the current slot
  at each iteration of the loop

**Description**

Iterate over all I2C devs present on the bus.

#### <a id="c-i3c_bus_for_each_i3cdev"></a>`i3c_bus_for_each_i3cdev()`

```c
i3c_bus_for_each_i3cdev(bus, dev)
```

iterate over all I3C devices present on the bus

**Parameters**

- `bus`: the I3C bus
- `dev`: and I3C device descriptor pointer updated to point to the current slot
  at each iteration of the loop

**Description**

Iterate over all I3C devs present on the bus.

#### <a id="c-struct-i3c_dma"></a>`struct i3c_dma`

DMA transfer and mapping descriptor

**Definition**

```c
struct i3c_dma {
    struct device *dev;
    void *buf;
    size_t len;
    size_t map_len;
    dma_addr_t addr;
    enum dma_data_direction dir;
    void *bounce_buf;
};
```

**Members**

- `dev`: device object of a device doing DMA
- `buf`: destination/source buffer for DMA
- `len`: length of transfer
- `map_len`: length of DMA mapping
- `addr`: mapped DMA address for a Host Controller Driver
- `dir`: DMA direction
- `bounce_buf`: an allocated bounce buffer if transfer needs it or NULL

#### <a id="c-i3c_dev_get_master_data"></a>`i3c_dev_get_master_data()`

```c
void * i3c_dev_get_master_data(const struct i3c_dev_desc *dev)
```

get master private data attached to an I3C device descriptor

**Parameters**

- `const struct i3c_dev_desc *dev`: the I3C device descriptor to get private data from

**Return**

the private data previously attached with [`i3c_dev_set_master_data()`](#c-i3c_dev_set_master_data)
or NULL if no data has been attached to the device.

#### <a id="c-i3c_dev_set_master_data"></a>`i3c_dev_set_master_data()`

```c
void i3c_dev_set_master_data(struct i3c_dev_desc *dev, void *data)
```

attach master private data to an I3C device descriptor

**Parameters**

- `struct i3c_dev_desc *dev`: the I3C device descriptor to attach private data to
- `void *data`: private data

**Description**

This functions allows a master controller to attach per-device private data
which can then be retrieved with [`i3c_dev_get_master_data()`](#c-i3c_dev_get_master_data).

#### <a id="c-i2c_dev_get_master_data"></a>`i2c_dev_get_master_data()`

```c
void * i2c_dev_get_master_data(const struct i2c_dev_desc *dev)
```

get master private data attached to an I2C device descriptor

**Parameters**

- `const struct i2c_dev_desc *dev`: the I2C device descriptor to get private data from

**Return**

the private data previously attached with [`i2c_dev_set_master_data()`](#c-i2c_dev_set_master_data)
or NULL if no data has been attached to the device.

#### <a id="c-i2c_dev_set_master_data"></a>`i2c_dev_set_master_data()`

```c
void i2c_dev_set_master_data(struct i2c_dev_desc *dev, void *data)
```

attach master private data to an I2C device descriptor

**Parameters**

- `struct i2c_dev_desc *dev`: the I2C device descriptor to attach private data to
- `void *data`: private data

**Description**

This functions allows a master controller to attach per-device private data
which can then be retrieved with `i2c_device_get_master_data()`.

#### <a id="c-i3c_dev_get_master"></a>`i3c_dev_get_master()`

```c
struct i3c_master_controller * i3c_dev_get_master(struct i3c_dev_desc *dev)
```

get master used to communicate with a device

**Parameters**

- `struct i3c_dev_desc *dev`: I3C dev

**Return**

the master controller driving **dev**

#### <a id="c-i2c_dev_get_master"></a>`i2c_dev_get_master()`

```c
struct i3c_master_controller * i2c_dev_get_master(struct i2c_dev_desc *dev)
```

get master used to communicate with a device

**Parameters**

- `struct i2c_dev_desc *dev`: I2C dev

**Return**

the master controller driving **dev**

#### <a id="c-i3c_master_get_bus"></a>`i3c_master_get_bus()`

```c
struct i3c_bus * i3c_master_get_bus(struct i3c_master_controller *master)
```

get the bus attached to a master

**Parameters**

- `struct i3c_master_controller *master`: master object

**Return**

the I3C bus **master** is connected to

---

# I3C protocol

_Peios Kernel / Hardware and drivers / Driver development / I3C_

> This chapter will focus on aspects that matter to software developers. For everything hardware related (like how things are transmitted on the bus, how collisions are prevented, ...) please have a look at the I3C specification.

<a id="rst-i3c-protocol"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-disclaimer"></a>

## Disclaimer

This chapter will focus on aspects that matter to software developers. For everything hardware related (like how things are transmitted on the bus, how collisions are prevented, ...) please have a look at the I3C specification.

This document is just a brief introduction to the I3C protocol and the concepts it brings to the table. If you need more information, please refer to the MIPI I3C specification (can be downloaded here [https://resources.mipi.org/mipi-i3c-v1-download](<https://resources.mipi.org/mipi-i3c-v1-download>)).

<a id="rst-introduction"></a>

## Introduction

The I3C (pronounced 'eye-three-see') is a MIPI standardized protocol designed to overcome I2C limitations (limited speed, external signals needed for interrupts, no automatic detection of the devices connected to the bus, ...) while remaining power-efficient.

<a id="rst-i3c-bus"></a>

## I3C Bus

An I3C bus is made of several I3C devices and possibly some I2C devices as well, but let's focus on I3C devices for now.

An I3C device on the I3C bus can have one of the following roles:

- Master: the device is driving the bus. It's the one in charge of initiating transactions or deciding who is allowed to talk on the bus (slave generated events are possible in I3C, see below).

- Slave: the device acts as a slave, and is not able to send frames to another slave on the bus. The device can still send events to the master on its own initiative if the master allowed it.

I3C is a multi-master protocol, so there might be several masters on a bus, though only one device can act as a master at a given time. In order to gain bus ownership, a master has to follow a specific procedure.

Each device on the I3C bus has to be assigned a dynamic address to be able to communicate. Until this is done, the device should only respond to a limited set of commands. If it has a static address (also called legacy I2C address), the device can reply to I2C transfers.

In addition to these per-device addresses, the protocol defines a broadcast address in order to address all devices on the bus.

Once a dynamic address has been assigned to a device, this address will be used for any direct communication with the device. Note that even after being assigned a dynamic address, the device should still process broadcast messages.

<a id="rst-i3c-device-discovery"></a>

## I3C Device discovery

The I3C protocol defines a mechanism to automatically discover devices present on the bus, their capabilities and the functionalities they provide. In this regard I3C is closer to a discoverable bus like USB than it is to I2C or SPI.

The discovery mechanism is called DAA (Dynamic Address Assignment), because it not only discovers devices but also assigns them a dynamic address.

During DAA, each I3C device reports 3 important things:

- BCR: Bus Characteristic Register. This 8-bit register describes the device bus related capabilities

- DCR: Device Characteristic Register. This 8-bit register describes the functionalities provided by the device

- Provisioned ID: A 48-bit unique identifier. On a given bus there should be no Provisioned ID collision, otherwise the discovery mechanism may fail.

<a id="rst-i3c-slave-events"></a>

## I3C slave events

The I3C protocol allows slaves to generate events on their own, and thus allows them to take temporary control of the bus.

This mechanism is called IBI for In Band Interrupts, and as stated in the name, it allows devices to generate interrupts without requiring an external signal.

During DAA, each device on the bus has been assigned an address, and this address will serve as a priority identifier to determine who wins if 2 different devices are generating an interrupt at the same moment on the bus (the lower the dynamic address the higher the priority).

Masters are allowed to inhibit interrupts if they want to. This inhibition request can be broadcast (applies to all devices) or sent to a specific device.

<a id="rst-i3c-hot-join"></a>

## I3C Hot-Join

The Hot-Join mechanism is similar to USB hotplug. This mechanism allows slaves to join the bus after it has been initialized by the master.

This covers the following use cases:

- the device is not powered when the bus is probed

- the device is hotplugged on the bus through an extension board

This mechanism is relying on slave events to inform the master that a new device joined the bus and is waiting for a dynamic address.

The master is then free to address the request as it wishes: ignore it or assign a dynamic address to the slave.

<a id="rst-i3c-transfer-types"></a>

## I3C transfer types

If you omit SMBus (which is just a standardization on how to access registers exposed by I2C devices), I2C has only one transfer type.

I3C defines 3 different classes of transfer in addition to I2C transfers which are here for backward compatibility with I2C devices.

<a id="rst-i3c-ccc-commands"></a>

### I3C CCC commands

CCC (Common Command Code) commands are meant to be used for anything that is related to bus management and all features that are common to a set of devices.

CCC commands contain an 8-bit CCC ID describing the command that is executed. The MSB of this ID specifies whether this is a broadcast command (bit7 = 0) or a unicast one (bit7 = 1).

The command ID can be followed by a payload. Depending on the command, this payload is either sent by the master sending the command (write CCC command), or sent by the slave receiving the command (read CCC command). Of course, read accesses only apply to unicast commands. Note that, when sending a CCC command to a specific device, the device address is passed in the first byte of the payload.

The payload length is not explicitly passed on the bus, and should be extracted from the CCC ID.

Note that vendors can use a dedicated range of CCC IDs for their own commands (0x61-0x7f and 0xe0-0xef).

<a id="rst-i3c-private-sdr-transfers"></a>

### I3C Private SDR transfers

Private SDR (Single Data Rate) transfers should be used for anything that is device specific and does not require high transfer speed.

It is the equivalent of I2C transfers but in the I3C world. Each transfer is passed the device address (dynamic address assigned during DAA), a payload and a direction.

The only difference with I2C is that the transfer is much faster (typical clock frequency is 12.5MHz).

<a id="rst-i3c-hdr-commands"></a>

### I3C HDR commands

HDR commands should be used for anything that is device specific and requires high transfer speed.

The first thing attached to an HDR command is the HDR mode. There are currently 3 different modes defined by the I3C specification (refer to the specification for more details):

- HDR-DDR: Double Data Rate mode

- HDR-TSP: Ternary Symbol Pure. Only usable on buses with no I2C devices

- HDR-TSL: Ternary Symbol Legacy. Usable on buses with I2C devices

When sending an HDR command, the whole bus has to enter HDR mode, which is done using a broadcast CCC command. Once the bus has entered a specific HDR mode, the master sends the HDR command. An HDR command is made of:

- one 16-bits command word in big endian

- N 16-bits data words in big endian

Those words may be wrapped with specific preambles/post-ambles which depend on the chosen HDR mode and are detailed here (see the specification for more details).

The 16-bits command word is made of:

- bit\[15\]: direction bit, read is 1, write is 0

- bit\[14:8\]: command code. Identifies the command being executed, the amount of data words and their meaning

- bit\[7:1\]: I3C address of the device this command is addressed to

- bit\[0\]: reserved/parity-bit

<a id="rst-backward-compatibility-with-i2c-devices"></a>

## Backward compatibility with I2C devices

The I3C protocol has been designed to be backward compatible with I2C devices. This backward compatibility allows one to connect a mix of I2C and I3C devices on the same bus, though, in order to be really efficient, I2C devices should be equipped with 50 ns spike filters.

I2C devices can't be discovered like I3C ones and have to be statically declared. In order to let the master know what these devices are capable of (both in terms of bus related limitations and functionalities), the software has to provide some information, which is done through the LVR (Legacy I2C Virtual Register).

---

# Industrial I/O

_Peios Kernel / Hardware and drivers / Driver development / Industrial I/O_

> Copyright © 2015 Intel Corporation

<a id="rst-industrial-i-o"></a>

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright** © 2015 Intel Corporation

Contents:

- [Introduction](</kernel/hardware/driver-api/iio/intro.md>)
- [Core elements](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/iio/core.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Buffers](</kernel/hardware/driver-api/iio/buffers.md>)
- [Triggers](</kernel/hardware/driver-api/iio/triggers.md>)
- [Triggered Buffers](</kernel/hardware/driver-api/iio/triggered-buffers.md>)
- [HW consumer](</kernel/hardware/driver-api/iio/hw-consumer.md>)

---

# Buffers

_Peios Kernel / Hardware and drivers / Driver development / Industrial I/O_

> struct iio_buffer — general buffer structure

<a id="rst-buffers"></a>

- struct iio_buffer — general buffer structure

- `iio_validate_scan_mask_onehot()` — Validates that exactly one channel is selected

- `iio_buffer_get()` — Grab a reference to the buffer

- `iio_buffer_put()` — Release the reference to the buffer

The Industrial I/O core offers a way for continuous data capture based on a trigger source. Multiple data channels can be read at once from `/dev/iio:device{X}` character device node, thus reducing the CPU load.

<a id="rst-iio-buffer-sysfs-interface"></a>

## IIO buffer sysfs interface

An IIO buffer has an associated attributes directory under `/sys/bus/iio/devices/iio:device{X}/buffer/*`. Here are some of the existing attributes:

- `length`, the total number of data samples (capacity) that can be stored by the buffer.

- `enable`, activate buffer capture.

<a id="rst-iio-buffer-setup"></a>

## IIO buffer setup

The meta information associated with a channel reading placed in a buffer is called a scan element. The important bits configuring scan elements are exposed to userspace applications via the `/sys/bus/iio/devices/iio:device{X}/scan_elements/` directory. This directory contains attributes of the following form:

- `enable`, used for enabling a channel. If and only if its attribute is non *zero*, then a triggered capture will contain data samples for this channel.

- `index`, the scan_index of the channel.

- `type`, description of the scan element data storage within the buffer and hence the form in which it is read from user space. Format is \[be\|le\]:\[s\|u\]bits/storagebits\[Xrepeat\]\[&gt;&gt;shift\] .

  - *be* or *le*, specifies big or little endian.

  - *s* or *u*, specifies if signed (2's complement) or unsigned.

  - *bits*, is the number of valid data bits.

  - *storagebits*, is the number of bits (after padding) that it occupies in the buffer.

  - *repeat*, specifies the number of bits/storagebits repetitions. When the repeat element is 0 or 1, then the repeat value is omitted.

  - *shift*, if specified, is the shift that needs to be applied prior to masking out unused bits.

For example, a driver for a 3-axis accelerometer with 12 bit resolution where data is stored in two 8-bits registers as follows:



```text
  7   6   5   4   3   2   1   0
+---+---+---+---+---+---+---+---+
|D3 |D2 |D1 |D0 | X | X | X | X | (LOW byte, address 0x06)
+---+---+---+---+---+---+---+---+

  7   6   5   4   3   2   1   0
+---+---+---+---+---+---+---+---+
|D11|D10|D9 |D8 |D7 |D6 |D5 |D4 | (HIGH byte, address 0x07)
+---+---+---+---+---+---+---+---+
```

will have the following scan element type for each axis:



```text
$ cat /sys/bus/iio/devices/iio:device0/scan_elements/in_accel_y_type
le:s12/16>>4
```

A user space application will interpret data samples read from the buffer as two byte little endian signed data, that needs a 4 bits right shift before masking out the 12 valid bits of data.

For implementing buffer support a driver should initialize the following fields in iio_chan_spec definition:



```text
struct iio_chan_spec {
/* other members */
        int scan_index
        struct {
                char sign;
                u8 realbits;
                u8 storagebits;
                u8 shift;
                u8 repeat;
                enum iio_endian endianness;
               } scan_type;
       };
```

The driver implementing the accelerometer described above will have the following channel definition:



```text
struct iio_chan_spec accel_channels[] = {
        {
                .type = IIO_ACCEL,
                .modified = 1,
                .channel2 = IIO_MOD_X,
                /* other stuff here */
                .scan_index = 0,
                .scan_type = {
                        .sign = 's',
                        .realbits = 12,
                        .storagebits = 16,
                        .shift = 4,
                        .endianness = IIO_LE,
                },
        }
        /* similar for Y (with channel2 = IIO_MOD_Y, scan_index = 1)
         * and Z (with channel2 = IIO_MOD_Z, scan_index = 2) axis
         */
 }
```

Here **scan_index** defines the order in which the enabled channels are placed inside the buffer. Channels with a lower **scan_index** will be placed before channels with a higher index. Each channel needs to have a unique **scan_index**.

Setting **scan_index** to -1 can be used to indicate that the specific channel does not support buffered capture. In this case no entries will be created for the channel in the scan_elements directory.

<a id="rst-more-details"></a>

## More details


#### <a id="c-iio_push_to_buffers_with_timestamp"></a>`iio_push_to_buffers_with_timestamp()`

```c
int iio_push_to_buffers_with_timestamp(struct iio_dev *indio_dev, void *data, int64_t timestamp)
```

push data and timestamp to buffers

**Parameters**

- `struct iio_dev *indio_dev`: iio_dev structure for device.
- `void *data`: sample data
- `int64_t timestamp`: timestamp for the sample data

**Description**

DEPRECATED: Use [`iio_push_to_buffers_with_ts()`](#c-iio_push_to_buffers_with_ts) instead.

Returns 0 on success, a negative error code otherwise.

#### <a id="c-iio_push_to_buffers_with_ts"></a>`iio_push_to_buffers_with_ts()`

```c
int iio_push_to_buffers_with_ts(struct iio_dev *indio_dev, void *data, size_t data_total_len, s64 timestamp)
```

push data and timestamp to buffers

**Parameters**

- `struct iio_dev *indio_dev`: iio_dev structure for device.
- `void *data`: Pointer to sample data buffer.
- `size_t data_total_len`: The size of **data** in bytes.
- `s64 timestamp`: Timestamp for the sample data.

**Description**

Pushes data to the IIO device's buffers. If timestamps are enabled for the
device the function will store the supplied timestamp as the last element in
the sample data buffer before pushing it to the device buffers. The sample
data buffer needs to be large enough to hold the additional timestamp
(usually the buffer should be at least indio->scan_bytes bytes large).

**Context**

Any context.

**Return**

0 on success, a negative error code otherwise.



#### <a id="c-iio_validate_scan_mask_onehot"></a>`iio_validate_scan_mask_onehot()`

```c
bool iio_validate_scan_mask_onehot(struct iio_dev *indio_dev, const unsigned long *mask)
```

Validates that exactly one channel is selected

**Parameters**

- `struct iio_dev *indio_dev`: the iio device
- `const unsigned long *mask`: scan mask to be checked

**Description**

Return true if exactly one bit is set in the scan mask, false otherwise. It
can be used for devices where only one channel can be active for sampling at
a time.

#### <a id="c-iio_push_to_buffers"></a>`iio_push_to_buffers()`

```c
int iio_push_to_buffers(struct iio_dev *indio_dev, const void *data)
```

push to a registered buffer.

**Parameters**

- `struct iio_dev *indio_dev`: iio_dev structure for device.
- `const void *data`: Full scan.

**Context**

Any context.

**Return**

0 on success, negative error code on failure.

#### <a id="c-iio_push_to_buffers_with_ts_unaligned"></a>`iio_push_to_buffers_with_ts_unaligned()`

```c
int iio_push_to_buffers_with_ts_unaligned(struct iio_dev *indio_dev, const void *data, size_t data_sz, int64_t timestamp)
```

push to registered buffer, no alignment or space requirements.

**Parameters**

- `struct iio_dev *indio_dev`: iio_dev structure for device.
- `const void *data`: channel data excluding the timestamp.
- `size_t data_sz`: size of data.
- `int64_t timestamp`: timestamp for the sample data.

**Description**

This special variant of [`iio_push_to_buffers_with_timestamp()`](#c-iio_push_to_buffers_with_timestamp) does
not require space for the timestamp, or 8 byte alignment of data.
It does however require an allocation on first call and additional
copies on all calls, so should be avoided if possible.

**Context**

May sleep.

**Return**

0 on success, negative error code on failure.

#### <a id="c-iio_buffer_get"></a>`iio_buffer_get()`

```c
struct iio_buffer * iio_buffer_get(struct iio_buffer *buffer)
```

Grab a reference to the buffer

**Parameters**

- `struct iio_buffer *buffer`: The buffer to grab a reference for, may be NULL

**Description**

Returns the pointer to the buffer that was passed into the function.

#### <a id="c-iio_buffer_put"></a>`iio_buffer_put()`

```c
void iio_buffer_put(struct iio_buffer *buffer)
```

Release the reference to the buffer

**Parameters**

- `struct iio_buffer *buffer`: The buffer to release the reference for, may be NULL

#### <a id="c-iio_device_attach_buffer"></a>`iio_device_attach_buffer()`

```c
int iio_device_attach_buffer(struct iio_dev *indio_dev, struct iio_buffer *buffer)
```

Attach a buffer to a IIO device

**Parameters**

- `struct iio_dev *indio_dev`: The device the buffer should be attached to
- `struct iio_buffer *buffer`: The buffer to attach to the device

**Description**

Return 0 if successful, negative if error.

This function attaches a buffer to a IIO device. The buffer stays attached to
the device until the device is freed. For legacy reasons, the first attached
buffer will also be assigned to 'indio_dev->buffer'.
The array allocated here, will be free'd via the `iio_device_detach_buffers()`
call which is handled by the [`iio_device_free()`](/kernel/hardware/driver-api/iio/core.md#c-iio_device_free).

---

# Core elements

_Peios Kernel / Hardware and drivers / Driver development / Industrial I/O_

> The Industrial I/O core offers both a unified framework for writing drivers for many different types of embedded sensors and a standard interface to user space applications manipulating sensors. The implementation can be found under…

<a id="rst-core-elements"></a>

The Industrial I/O core offers both a unified framework for writing drivers for many different types of embedded sensors and a standard interface to user space applications manipulating sensors. The implementation can be found under `drivers/iio/industrialio-*`

<a id="rst-industrial-i-o-devices"></a>

## Industrial I/O Devices

- struct iio\_dev - industrial I/O device

- iio\_device\_alloc() - allocate an `iio_dev` from a driver

- iio\_device\_free() - free an `iio_dev` from a driver

- iio\_device\_register() - register a device with the IIO subsystem

- iio\_device\_unregister() - unregister a device from the IIO subsystem

An IIO device usually corresponds to a single hardware sensor and it provides all the information needed by a driver handling a device. Let's first have a look at the functionality embedded in an IIO device then we will show how a device driver makes use of an IIO device.

There are two ways for a user space application to interact with an IIO driver.

1. `/sys/bus/iio/devices/iio:device{X}/`, this represents a hardware sensor and groups together the data channels of the same chip.

2. `/dev/iio:device{X}`, character device node interface used for buffered data transfer and for events information retrieval.

A typical IIO driver will register itself as an [I2C](</kernel/hardware/driver-api/buses/i2c.md>) or [SPI](</kernel/hardware/driver-api/buses/spi.md>) driver and will create two routines, probe and remove.

At probe:

1. Call iio\_device\_alloc(), which allocates memory for an IIO device.

2. Initialize IIO device fields with driver specific information (e.g. device name, device channels).

3. Call iio\_device\_register(), this registers the device with the IIO core. After this call the device is ready to accept requests from user space applications.

At remove, we free the resources allocated in probe in reverse order:

1. iio\_device\_unregister(), unregister the device from the IIO core.

2. iio\_device\_free(), free the memory allocated for the IIO device.

<a id="rst-iio-device-sysfs-interface"></a>

### IIO device sysfs interface

Attributes are sysfs files used to expose chip info and also allowing applications to set various configuration parameters. For device with index X, attributes can be found under /sys/bus/iio/devices/iio:deviceX/ directory.  Common attributes are:

- `name`, description of the physical chip.

- `dev`, shows the major:minor pair associated with `/dev/iio:deviceX` node.

- `sampling_frequency_available`, available discrete set of sampling frequency values for device.

- Available standard attributes for IIO devices are described in the :[file:Documentation/ABI/testing/sysfs-bus-iio](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/ABI/testing/sysfs-bus-iio?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) file in the Linux kernel sources.

<a id="rst-iio-device-channels"></a>

### IIO device channels

struct iio\_chan\_spec - specification of a single channel

An IIO device channel is a representation of a data channel. An IIO device can have one or multiple channels. For example:

- a thermometer sensor has one channel representing the temperature measurement.

- a light sensor with two channels indicating the measurements in the visible and infrared spectrum.

- an accelerometer can have up to 3 channels representing acceleration on X, Y and Z axes.

An IIO channel is described by the struct iio\_chan\_spec. A thermometer driver for the temperature sensor in the example above would have to describe its channel as follows:



```text
static const struct iio_chan_spec temp_channel[] = {
     {
         .type = IIO_TEMP,
         .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),
     },
};
```

Channel sysfs attributes exposed to userspace are specified in the form of bitmasks. Depending on their shared info, attributes can be set in one of the following masks:

- <strong>info\_mask\_separate</strong>, attributes will be specific to this channel

- <strong>info\_mask\_shared\_by\_type</strong>, attributes are shared by all channels of the same type

- <strong>info\_mask\_shared\_by\_dir</strong>, attributes are shared by all channels of the same direction

- <strong>info\_mask\_shared\_by\_all</strong>, attributes are shared by all channels

When there are multiple data channels per channel type we have two ways to distinguish between them:

- set <strong>.modified</strong> field of `iio_chan_spec` to 1. Modifiers are specified using <strong>.channel2</strong> field of the same `iio_chan_spec` structure and are used to indicate a physically unique characteristic of the channel such as its direction or spectral response. For example, a light sensor can have two channels, one for infrared light and one for both infrared and visible light.

- set <strong>.indexed</strong> field of `iio_chan_spec` to 1. In this case the channel is simply another instance with an index specified by the <strong>.channel</strong> field.

Here is how we can make use of the channel's modifiers:



```text
static const struct iio_chan_spec light_channels[] = {
        {
                .type = IIO_INTENSITY,
                .modified = 1,
                .channel2 = IIO_MOD_LIGHT_IR,
                .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
                .info_mask_shared = BIT(IIO_CHAN_INFO_SAMP_FREQ),
        },
        {
                .type = IIO_INTENSITY,
                .modified = 1,
                .channel2 = IIO_MOD_LIGHT_BOTH,
                .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
                .info_mask_shared = BIT(IIO_CHAN_INFO_SAMP_FREQ),
        },
        {
                .type = IIO_LIGHT,
                .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),
                .info_mask_shared = BIT(IIO_CHAN_INFO_SAMP_FREQ),
        },
   }
```

This channel's definition will generate two separate sysfs files for raw data retrieval:

- `/sys/bus/iio/devices/iio:device{X}/in_intensity_ir_raw`

- `/sys/bus/iio/devices/iio:device{X}/in_intensity_both_raw`

one file for processed data:

- `/sys/bus/iio/devices/iio:device{X}/in_illuminance_input`

and one shared sysfs file for sampling frequency:

- `/sys/bus/iio/devices/iio:device{X}/sampling_frequency`.

Here is how we can make use of the channel's indexing:



```text
static const struct iio_chan_spec light_channels[] = {
        {
                .type = IIO_VOLTAGE,
                .indexed = 1,
                .channel = 0,
                .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
        },
        {
                .type = IIO_VOLTAGE,
                .indexed = 1,
                .channel = 1,
                .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
        },
}
```

This will generate two separate attributes files for raw data retrieval:

- `/sys/bus/iio/devices/iio:device{X}/in_voltage0_raw`, representing voltage measurement for channel 0.

- `/sys/bus/iio/devices/iio:device{X}/in_voltage1_raw`, representing voltage measurement for channel 1.

<a id="rst-more-details"></a>

### More details


#### <a id="c-struct-iio_chan_spec_ext_info"></a>`struct iio_chan_spec_ext_info`

Extended channel info attribute

**Definition**

```c
struct iio_chan_spec_ext_info {
    const char *name;
    enum iio_shared_by shared;
    ssize_t (*read)(struct iio_dev *, uintptr_t private, struct iio_chan_spec const *, char *buf);
    ssize_t (*write)(struct iio_dev *, uintptr_t private, struct iio_chan_spec const *, const char *buf, size_t len);
    uintptr_t private;
};
```

**Members**

- `name`: Info attribute name
- `shared`: Whether this attribute is shared between all channels.
- `read`: Read callback for this info attribute, may be NULL.
- `write`: Write callback for this info attribute, may be NULL.
- `private`: Data private to the driver.

#### <a id="c-struct-iio_enum"></a>`struct iio_enum`

Enum channel info attribute

**Definition**

```c
struct iio_enum {
    const char * const *items;
    unsigned int num_items;
    int (*set)(struct iio_dev *, const struct iio_chan_spec *, unsigned int);
    int (*get)(struct iio_dev *, const struct iio_chan_spec *);
};
```

**Members**

- `items`: An array of strings.
- `num_items`: Length of the item array.
- `set`: Set callback function, may be NULL.
- `get`: Get callback function, may be NULL.

**Description**

The iio_enum struct can be used to implement enum style channel attributes.
Enum style attributes are those which have a set of strings which map to
unsigned integer values. The IIO enum helper code takes care of mapping
between value and string as well as generating a "_available" file which
contains a list of all available items. The set callback will be called when
the attribute is updated. The last parameter is the index to the newly
activated item. The get callback will be used to query the currently active
item and is supposed to return the index for it.

#### <a id="c-IIO_ENUM"></a>`IIO_ENUM()`

```c
IIO_ENUM(_name, _shared, _e)
```

Initialize enum extended channel attribute

**Parameters**

- `_name`: Attribute name
- `_shared`: Whether the attribute is shared between all channels
- `_e`: Pointer to an iio_enum struct

**Description**

This should usually be used together with [`IIO_ENUM_AVAILABLE()`](#c-IIO_ENUM_AVAILABLE)

#### <a id="c-IIO_ENUM_AVAILABLE"></a>`IIO_ENUM_AVAILABLE()`

```c
IIO_ENUM_AVAILABLE(_name, _shared, _e)
```

Initialize enum available extended channel attribute

**Parameters**

- `_name`: Attribute name ("_available" will be appended to the name)
- `_shared`: Whether the attribute is shared between all channels
- `_e`: Pointer to an iio_enum struct

**Description**

Creates a read only attribute which lists all the available enum items in a
space separated list. This should usually be used together with [`IIO_ENUM()`](#c-IIO_ENUM)

#### <a id="c-struct-iio_mount_matrix"></a>`struct iio_mount_matrix`

iio mounting matrix

**Definition**

```c
struct iio_mount_matrix {
    const char *rotation[9];
};
```

**Members**

- `rotation`: 3 dimensional space rotation matrix defining sensor alignment with
  main hardware

#### <a id="c-IIO_MOUNT_MATRIX"></a>`IIO_MOUNT_MATRIX()`

```c
IIO_MOUNT_MATRIX(_shared, _get)
```

Initialize mount matrix extended channel attribute

**Parameters**

- `_shared`: Whether the attribute is shared between all channels
- `_get`: Pointer to an iio_get_mount_matrix_t accessor

#### <a id="c-struct-iio_event_spec"></a>`struct iio_event_spec`

specification for a channel event

**Definition**

```c
struct iio_event_spec {
    enum iio_event_type type;
    enum iio_event_direction dir;
    unsigned long mask_separate;
    unsigned long mask_shared_by_type;
    unsigned long mask_shared_by_dir;
    unsigned long mask_shared_by_all;
};
```

**Members**

- `type`: Type of the event
- `dir`: Direction of the event
- `mask_separate`: Bit mask of enum iio_event_info values. Attributes
  set in this mask will be registered per channel.
- `mask_shared_by_type`: Bit mask of enum iio_event_info values. Attributes
  set in this mask will be shared by channel type.
- `mask_shared_by_dir`: Bit mask of enum iio_event_info values. Attributes
  set in this mask will be shared by channel type and
  direction.
- `mask_shared_by_all`: Bit mask of enum iio_event_info values. Attributes
  set in this mask will be shared by all channels.

#### <a id="c-struct-iio_scan_type"></a>`struct iio_scan_type`

specification for channel data format in buffer

**Definition**

```c
struct iio_scan_type {
    char sign;
    u8 realbits;
    u8 storagebits;
    u8 shift;
    u8 repeat;
    enum iio_endian endianness;
};
```

**Members**

- `sign`: 's' or 'u' to specify signed or unsigned
- `realbits`: Number of valid bits of data
- `storagebits`: Realbits + padding
- `shift`: Shift right by this before masking out realbits.
- `repeat`: Number of times real/storage bits repeats. When the
  repeat element is more than 1, then the type element in
  sysfs will show a repeat value. Otherwise, the number
  of repetitions is omitted.
- `endianness`: little or big endian

#### <a id="c-struct-iio_chan_spec"></a>`struct iio_chan_spec`

specification of a single channel

**Definition**

```c
struct iio_chan_spec {
    enum iio_chan_type      type;
    int channel;
    int channel2;
    unsigned long           address;
    int scan_index;
    union {
        struct iio_scan_type scan_type;
        struct {
            const struct iio_scan_type *ext_scan_type;
            unsigned int num_ext_scan_type;
        };
    };
    unsigned long                   info_mask_separate;
    unsigned long                   info_mask_separate_available;
    unsigned long                   info_mask_shared_by_type;
    unsigned long                   info_mask_shared_by_type_available;
    unsigned long                   info_mask_shared_by_dir;
    unsigned long                   info_mask_shared_by_dir_available;
    unsigned long                   info_mask_shared_by_all;
    unsigned long                   info_mask_shared_by_all_available;
    const struct iio_event_spec *event_spec;
    unsigned int            num_event_specs;
    const struct iio_chan_spec_ext_info *ext_info;
    const char              *extend_name;
    const char              *datasheet_name;
    unsigned int            modified:1;
    unsigned int            indexed:1;
    unsigned int            output:1;
    unsigned int            differential:1;
    unsigned int            has_ext_scan_type:1;
};
```

**Members**

- `type`: What type of measurement is the channel making.
- `channel`: What number do we wish to assign the channel.
- `channel2`: If there is a second number for a differential
  channel then this is it. If modified is set then the
  value here specifies the modifier.
- `address`: Driver specific identifier.
- `scan_index`: Monotonic index to give ordering in scans when read
  from a buffer.
- `{unnamed_union}`: anonymous
- `scan_type`: struct describing the scan type - mutually exclusive
  with ext_scan_type.
- `{unnamed_struct}`: anonymous
- `ext_scan_type`: Used in rare cases where there is more than one scan
  format for a channel. When this is used, the flag
  has_ext_scan_type must be set and the driver must
  implement get_current_scan_type in struct iio_info.
- `num_ext_scan_type`: Number of elements in ext_scan_type.
- `info_mask_separate`: What information is to be exported that is specific to
  this channel.
- `info_mask_separate_available`: What availability information is to be
  exported that is specific to this channel.
- `info_mask_shared_by_type`: What information is to be exported that is shared
  by all channels of the same type.
- `info_mask_shared_by_type_available`: What availability information is to be
  exported that is shared by all channels of the same
  type.
- `info_mask_shared_by_dir`: What information is to be exported that is shared
  by all channels of the same direction.
- `info_mask_shared_by_dir_available`: What availability information is to be
  exported that is shared by all channels of the same
  direction.
- `info_mask_shared_by_all`: What information is to be exported that is shared
  by all channels.
- `info_mask_shared_by_all_available`: What availability information is to be
  exported that is shared by all channels.
- `event_spec`: Array of events which should be registered for this
  channel.
- `num_event_specs`: Size of the event_spec array.
- `ext_info`: Array of extended info attributes for this channel.
  The array is NULL terminated, the last element should
  have its name field set to NULL.
- `extend_name`: Allows labeling of channel attributes with an
  informative name. Note this has no effect codes etc,
  unlike modifiers.
  This field is deprecated in favour of providing
  iio_info->`read_label()` to override the label, which
  unlike **extend_name** does not affect sysfs filenames.
- `datasheet_name`: A name used in in-kernel mapping of channels. It should
  correspond to the first name that the channel is referred
  to by in the datasheet (e.g. IND), or the nearest
  possible compound name (e.g. IND-INC).
- `modified`: Does a modifier apply to this channel. What these are
  depends on the channel type.  Modifier is set in
  channel2. Examples are IIO_MOD_X for axial sensors about
  the 'x' axis.
- `indexed`: Specify the channel has a numerical index. If not,
  the channel index number will be suppressed for sysfs
  attributes but not for event codes.
- `output`: Channel is output.
- `differential`: Channel is differential.
- `has_ext_scan_type`: True if ext_scan_type is used instead of scan_type.

#### <a id="c-iio_channel_has_info"></a>`iio_channel_has_info()`

```c
bool iio_channel_has_info(const struct iio_chan_spec *chan, enum iio_chan_info_enum type)
```

Checks whether a channel supports a info attribute

**Parameters**

- `const struct iio_chan_spec *chan`: The channel to be queried
- `enum iio_chan_info_enum type`: Type of the info attribute to be checked

**Description**

Returns true if the channels supports reporting values for the given info
attribute type, false otherwise.

#### <a id="c-iio_channel_has_available"></a>`iio_channel_has_available()`

```c
bool iio_channel_has_available(const struct iio_chan_spec *chan, enum iio_chan_info_enum type)
```

Checks if a channel has an available attribute

**Parameters**

- `const struct iio_chan_spec *chan`: The channel to be queried
- `enum iio_chan_info_enum type`: Type of the available attribute to be checked

**Description**

Returns true if the channel supports reporting available values for the
given attribute type, false otherwise.

#### <a id="c-struct-iio_info"></a>`struct iio_info`

constant information about device

**Definition**

```c
struct iio_info {
    const struct attribute_group    *event_attrs;
    const struct attribute_group    *attrs;
    int (*read_raw)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int *val, int *val2, long mask);
    int (*read_raw_multi)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int max_len, int *vals, int *val_len, long mask);
    int (*read_avail)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, const int **vals, int *type, int *length, long mask);
    int (*write_raw)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int val, int val2, long mask);
    int (*read_label)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, char *label);
    int (*write_raw_get_fmt)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, long mask);
    int (*read_event_config)(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir);
    int (*write_event_config)(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, bool state);
    int (*read_event_value)(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, enum iio_event_info info, int *val, int *val2);
    int (*write_event_value)(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, enum iio_event_info info, int val, int val2);
    int (*read_event_label)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, enum iio_event_type type, enum iio_event_direction dir, char *label);
    int (*validate_trigger)(struct iio_dev *indio_dev, struct iio_trigger *trig);
    int (*get_current_scan_type)(const struct iio_dev *indio_dev, const struct iio_chan_spec *chan);
    int (*update_scan_mode)(struct iio_dev *indio_dev, const unsigned long *scan_mask);
    int (*debugfs_reg_access)(struct iio_dev *indio_dev, unsigned int reg, unsigned int writeval, unsigned int *readval);
    int (*fwnode_xlate)(struct iio_dev *indio_dev, const struct fwnode_reference_args *iiospec);
    int (*hwfifo_set_watermark)(struct iio_dev *indio_dev, unsigned int val);
    int (*hwfifo_flush_to_buffer)(struct iio_dev *indio_dev, unsigned int count);
};
```

**Members**

- `event_attrs`: event control attributes
- `attrs`: general purpose device attributes
- `read_raw`: function to request a value from the device.
  mask specifies which value. Note 0 means a reading of
  the channel in question.  Return value will specify the
  type of value returned by the device. val and val2 will
  contain the elements making up the returned value.
- `read_raw_multi`: function to return values from the device.
  mask specifies which value. Note 0 means a reading of
  the channel in question.  Return value will specify the
  type of value returned by the device. vals pointer
  contain the elements making up the returned value.
  max_len specifies maximum number of elements
  vals pointer can contain. val_len is used to return
  length of valid elements in vals.
- `read_avail`: function to return the available values from the device.
  mask specifies which value. Note 0 means the available
  values for the channel in question.  Return value
  specifies if a IIO_AVAIL_LIST or a IIO_AVAIL_RANGE is
  returned in vals. The type of the vals are returned in
  type and the number of vals is returned in length. For
  ranges, there are always three vals returned; min, step
  and max. For lists, all possible values are enumerated.
- `write_raw`: function to write a value to the device.
  Parameters are the same as for read_raw.
- `read_label`: function to request label name for a specified label,
  for better channel identification.
- `write_raw_get_fmt`: callback function to query the expected
  format/precision. If not set by the driver, write_raw
  returns IIO_VAL_INT_PLUS_MICRO.
- `read_event_config`: find out if the event is enabled.
- `write_event_config`: set if the event is enabled.
- `read_event_value`: read a configuration value associated with the event.
- `write_event_value`: write a configuration value for the event.
- `read_event_label`: function to request label name for a specified label,
  for better event identification.
- `validate_trigger`: function to validate the trigger when the
  current trigger gets changed.
- `get_current_scan_type`: must be implemented by drivers that use ext_scan_type
  in the channel spec to return the index of the currently
  active ext_scan type for a channel.
- `update_scan_mode`: function to configure device and scan buffer when
  channels have changed
- `debugfs_reg_access`: function to read or write register value of device
- `fwnode_xlate`: fwnode based function pointer to obtain channel specifier index.
- `hwfifo_set_watermark`: function pointer to set the current hardware
  fifo watermark level; see hwfifo_* entries in
  Documentation/ABI/testing/sysfs-bus-iio for details on
  how the hardware fifo operates
- `hwfifo_flush_to_buffer`: function pointer to flush the samples stored
  in the hardware fifo to the device buffer. The driver
  should not flush more than count samples. The function
  must return the number of samples flushed, 0 if no
  samples were flushed or a negative integer if no samples
  were flushed and there was an error.

#### <a id="c-struct-iio_buffer_setup_ops"></a>`struct iio_buffer_setup_ops`

buffer setup related callbacks

**Definition**

```c
struct iio_buffer_setup_ops {
    int (*preenable)(struct iio_dev *);
    int (*postenable)(struct iio_dev *);
    int (*predisable)(struct iio_dev *);
    int (*postdisable)(struct iio_dev *);
    bool (*validate_scan_mask)(struct iio_dev *indio_dev, const unsigned long *scan_mask);
};
```

**Members**

- `preenable`: \[DRIVER\] function to run prior to marking buffer enabled
- `postenable`: \[DRIVER\] function to run after marking buffer enabled
- `predisable`: \[DRIVER\] function to run prior to marking buffer
  disabled
- `postdisable`: \[DRIVER\] function to run after marking buffer disabled
- `validate_scan_mask`: \[DRIVER\] function callback to check whether a given
  scan mask is valid for the device.

#### <a id="c-struct-iio_dev"></a>`struct iio_dev`

industrial I/O device

**Definition**

```c
struct iio_dev {
    int modes;
    struct device                   dev;
    struct iio_buffer               *buffer;
    int scan_bytes;
    const unsigned long             *available_scan_masks;
    unsigned int  masklength;
    const unsigned long             *active_scan_mask;
    bool scan_timestamp;
    struct iio_trigger              *trig;
    struct iio_poll_func            *pollfunc;
    struct iio_poll_func            *pollfunc_event;
    struct iio_chan_spec const      *channels;
    int num_channels;
    const char                      *name;
    const char                      *label;
    const struct iio_info           *info;
    const struct iio_buffer_setup_ops       *setup_ops;
    void *  priv;
};
```

**Members**

- `modes`: \[DRIVER\] bitmask listing all the operating modes
  supported by the IIO device. This list should be
  initialized before registering the IIO device. It can
  also be filed up by the IIO core, as a result of
  enabling particular features in the driver
  (see `iio_triggered_event_setup()`).
- `dev`: \[DRIVER\] device structure, should be assigned a parent
  and owner
- `buffer`: \[DRIVER\] any buffer present
- `scan_bytes`: \[INTERN\] num bytes captured to be fed to buffer demux
- `available_scan_masks`: \[DRIVER\] optional array of allowed bitmasks. Sort the
  array in order of preference, the most preferred
  masks first.
- `masklength`: \[INTERN\] the length of the mask established from
  channels
- `active_scan_mask`: \[INTERN\] union of all scan masks requested by buffers
- `scan_timestamp`: \[INTERN\] set if any buffers have requested timestamp
- `trig`: \[INTERN\] current device trigger (buffer modes)
- `pollfunc`: \[DRIVER\] function run on trigger being received
- `pollfunc_event`: \[DRIVER\] function run on events trigger being received
- `channels`: \[DRIVER\] channel specification structure table
- `num_channels`: \[DRIVER\] number of channels specified in **channels**.
- `name`: \[DRIVER\] name of the device.
- `label`: \[DRIVER\] unique name to identify which device this is
- `info`: \[DRIVER\] callbacks and constant info from driver
- `setup_ops`: \[DRIVER\] callbacks to call before and after buffer
  enable/disable
- `priv`: \[DRIVER\] reference to driver's private information
  **MUST** be accessed **ONLY** via `iio_priv()` helper

#### <a id="c-iio_device_register"></a>`iio_device_register()`

```c
iio_device_register(indio_dev)
```

register a device with the IIO subsystem

**Parameters**

- `indio_dev`: Device structure filled by the device driver

#### <a id="c-devm_iio_device_register"></a>`devm_iio_device_register()`

```c
devm_iio_device_register(dev, indio_dev)
```

Resource-managed [`iio_device_register()`](#c-iio_device_register)

**Parameters**

- `dev`: Device to allocate iio_dev for
- `indio_dev`: Device structure filled by the device driver

**Description**

Managed iio_device_register.  The IIO device registered with this
function is automatically unregistered on driver detach. This function
calls [`iio_device_register()`](#c-iio_device_register) internally. Refer to that function for more
information.

**Return**

0 on success, negative error number on failure.

#### <a id="c-iio_device_claim_direct"></a>`iio_device_claim_direct()`

```c
bool iio_device_claim_direct(struct iio_dev *indio_dev)
```

Keep device in direct mode

**Parameters**

- `struct iio_dev *indio_dev`: the iio_dev associated with the device

**Description**

If the device is in direct mode it is guaranteed to stay
that way until [`iio_device_release_direct()`](#c-iio_device_release_direct) is called.

Use with [`iio_device_release_direct()`](#c-iio_device_release_direct).

**Return**

true on success, false on failure.

#### <a id="c-iio_device_release_direct"></a>`iio_device_release_direct()`

```c
iio_device_release_direct(indio_dev)
```

Releases claim on direct mode

**Parameters**

- `indio_dev`: the iio_dev associated with the device

**Description**

Release the claim. Device is no longer guaranteed to stay
in direct mode.

Use with [`iio_device_claim_direct()`](#c-iio_device_claim_direct).

#### <a id="c-iio_device_try_claim_buffer_mode"></a>`iio_device_try_claim_buffer_mode()`

```c
bool iio_device_try_claim_buffer_mode(struct iio_dev *indio_dev)
```

Keep device in buffer mode

**Parameters**

- `struct iio_dev *indio_dev`: the iio_dev associated with the device

**Description**

If the device is in buffer mode it is guaranteed to stay
that way until [`iio_device_release_buffer_mode()`](#c-iio_device_release_buffer_mode) is called.

Use with [`iio_device_release_buffer_mode()`](#c-iio_device_release_buffer_mode).

**Return**

true on success, false on failure.

#### <a id="c-iio_device_release_buffer_mode"></a>`iio_device_release_buffer_mode()`

```c
iio_device_release_buffer_mode(indio_dev)
```

releases claim on buffer mode

**Parameters**

- `indio_dev`: the iio_dev associated with the device

**Description**

Release the claim. Device is no longer guaranteed to stay
in buffer mode.

Use with [`iio_device_try_claim_buffer_mode()`](#c-iio_device_try_claim_buffer_mode).

#### <a id="c-IIO_DEV_ACQUIRE_DIRECT_MODE"></a>`IIO_DEV_ACQUIRE_DIRECT_MODE()`

```c
IIO_DEV_ACQUIRE_DIRECT_MODE(dev, claim)
```

Tries to acquire the direct mode lock with automatic release

**Parameters**

- `dev`: IIO device instance
- `claim`: Variable identifier to store acquire result

**Description**

Tries to acquire the direct mode lock with cleanup `ACQUIRE()` semantics and
automatically releases it at the end of the scope. It most be always paired
with `IIO_DEV_ACQUIRE_ERR()`, for example (notice the scope braces):

```text
switch() {
case IIO_CHAN_INFO_RAW: {
        IIO_DEV_ACQUIRE_DIRECT_MODE(indio_dev, claim);
        if (IIO_DEV_ACQUIRE_FAILED(claim))
                return -EBUSY;

        ...
}
case IIO_CHAN_INFO_SCALE:
        ...
...
}
```

**Context**

Can sleep

#### <a id="c-IIO_DEV_ACQUIRE_FAILED"></a>`IIO_DEV_ACQUIRE_FAILED()`

```c
IIO_DEV_ACQUIRE_FAILED(claim)
```

`ACQUIRE_ERR()` wrapper

**Parameters**

- `claim`: The claim variable passed to IIO_DEV_ACQUIRE_*`_MODE()`

**Return**

true if failed to acquire the mode, otherwise false.

#### <a id="c-IIO_DEV_GUARD_CURRENT_MODE"></a>`IIO_DEV_GUARD_CURRENT_MODE()`

```c
IIO_DEV_GUARD_CURRENT_MODE(dev)
```

Acquires the mode lock with automatic release

**Parameters**

- `dev`: IIO device instance

**Description**

Acquires the mode lock with cleanup `guard()` semantics. It is usually paired
with [`iio_buffer_enabled()`](#c-iio_buffer_enabled).

This should *not* be used to protect internal driver state and it's use in
general is *strongly* discouraged. Use any of the IIO_DEV_ACQUIRE_*`_MODE()`
variants.

**Context**

Can sleep

#### <a id="c-iio_device_put"></a>`iio_device_put()`

```c
void iio_device_put(struct iio_dev *indio_dev)
```

reference counted deallocation of struct device

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure containing the device

#### <a id="c-dev_to_iio_dev"></a>`dev_to_iio_dev()`

```c
struct iio_dev * dev_to_iio_dev(struct device *dev)
```

Get IIO device struct from a device struct

**Parameters**

- `struct device *dev`: The device embedded in the IIO device

**Note**

The device must be a IIO device, otherwise the result is undefined.

#### <a id="c-iio_device_get"></a>`iio_device_get()`

```c
struct iio_dev * iio_device_get(struct iio_dev *indio_dev)
```

increment reference count for the device

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure

**Return**

The passed IIO device

#### <a id="c-iio_device_set_parent"></a>`iio_device_set_parent()`

```c
void iio_device_set_parent(struct iio_dev *indio_dev, struct device *parent)
```

assign parent device to the IIO device object

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure
- `struct device *parent`: reference to parent device object

**Description**

This utility must be called between IIO device allocation
(via [`devm_iio_device_alloc()`](#c-devm_iio_device_alloc)) & IIO device registration
(via [`iio_device_register()`](#c-iio_device_register) and [`devm_iio_device_register()`](#c-devm_iio_device_register))).
By default, the device allocation will also assign a parent device to
the IIO device object. In cases where [`devm_iio_device_alloc()`](#c-devm_iio_device_alloc) is used,
sometimes the parent device must be different than the device used to
manage the allocation.
In that case, this helper should be used to change the parent, hence the
requirement to call this between allocation & registration.

#### <a id="c-iio_device_set_drvdata"></a>`iio_device_set_drvdata()`

```c
void iio_device_set_drvdata(struct iio_dev *indio_dev, void *data)
```

Set device driver data

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure
- `void *data`: Driver specific data

**Description**

Allows to attach an arbitrary pointer to an IIO device, which can later be
retrieved by [`iio_device_get_drvdata()`](#c-iio_device_get_drvdata).

#### <a id="c-iio_device_get_drvdata"></a>`iio_device_get_drvdata()`

```c
void * iio_device_get_drvdata(const struct iio_dev *indio_dev)
```

Get device driver data

**Parameters**

- `const struct iio_dev *indio_dev`: IIO device structure

**Description**

Returns the data previously set with [`iio_device_set_drvdata()`](#c-iio_device_set_drvdata)

#### <a id="c-IIO_DECLARE_BUFFER_WITH_TS"></a>`IIO_DECLARE_BUFFER_WITH_TS()`

```c
IIO_DECLARE_BUFFER_WITH_TS(type, name, count)
```

Declare a buffer with timestamp

**Parameters**

- `type`: element type of the buffer
- `name`: identifier name of the buffer
- `count`: number of elements in the buffer

**Description**

Declares a buffer that is safe to use with [`iio_push_to_buffers_with_ts()`](/kernel/hardware/driver-api/iio/buffers.md#c-iio_push_to_buffers_with_ts). In
addition to allocating enough space for **count** elements of **type**, it also
allocates space for a s64 timestamp at the end of the buffer and ensures
proper alignment of the timestamp.

#### <a id="c-IIO_DECLARE_DMA_BUFFER_WITH_TS"></a>`IIO_DECLARE_DMA_BUFFER_WITH_TS()`

```c
IIO_DECLARE_DMA_BUFFER_WITH_TS(type, name, count)
```

Declare a DMA-aligned buffer with timestamp

**Parameters**

- `type`: element type of the buffer
- `name`: identifier name of the buffer
- `count`: number of elements in the buffer

**Description**

Same as [`IIO_DECLARE_BUFFER_WITH_TS()`](#c-IIO_DECLARE_BUFFER_WITH_TS), but is uses __aligned(IIO_DMA_MINALIGN)
to ensure that the buffer doesn't share cachelines with anything that comes
before it in a struct. This should not be used for stack-allocated buffers
as stack memory cannot generally be used for DMA.

#### <a id="c-IIO_DECLARE_QUATERNION"></a>`IIO_DECLARE_QUATERNION()`

```c
IIO_DECLARE_QUATERNION(type, name)
```

Declare a quaternion element

**Parameters**

- `type`: element type of the individual vectors
- `name`: identifier name

**Description**

Quaternions are a vector composed of 4 elements (W, X, Y, Z). Use this macro
to declare a quaternion element in a struct to ensure proper alignment in
an IIO buffer.

#### <a id="c-iio_get_debugfs_dentry"></a>`iio_get_debugfs_dentry()`

```c
struct dentry * iio_get_debugfs_dentry(struct iio_dev *indio_dev)
```

helper function to get the debugfs_dentry

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure for device

#### <a id="c-iio_device_suspend_triggering"></a>`iio_device_suspend_triggering()`

```c
int iio_device_suspend_triggering(struct iio_dev *indio_dev)
```

suspend trigger attached to an iio_dev

**Parameters**

- `struct iio_dev *indio_dev`: iio_dev associated with the device that will have triggers suspended

**Description**

Return 0 if successful, negative otherwise

#### <a id="c-iio_device_resume_triggering"></a>`iio_device_resume_triggering()`

```c
int iio_device_resume_triggering(struct iio_dev *indio_dev)
```

resume trigger attached to an iio_dev that was previously suspended with [`iio_device_suspend_triggering()`](#c-iio_device_suspend_triggering)

**Parameters**

- `struct iio_dev *indio_dev`: iio_dev associated with the device that will have triggers resumed

**Description**

Return 0 if successful, negative otherwise

#### <a id="c-iio_get_current_scan_type"></a>`iio_get_current_scan_type()`

```c
const struct iio_scan_type * iio_get_current_scan_type(const struct iio_dev *indio_dev, const struct iio_chan_spec *chan)
```

Get the current scan type for a channel

**Parameters**

- `const struct iio_dev *indio_dev`: the IIO device to get the scan type for
- `const struct iio_chan_spec *chan`: the channel to get the scan type for

**Description**

Most devices only have one scan type per channel and can just access it
directly without calling this function. Core IIO code and drivers that
implement ext_scan_type in the channel spec should use this function to
get the current scan type for a channel.

**Return**

the current scan type for the channel or error.

#### <a id="c-iio_get_masklength"></a>`iio_get_masklength()`

```c
unsigned int iio_get_masklength(const struct iio_dev *indio_dev)
```

Get length of the channels mask

**Parameters**

- `const struct iio_dev *indio_dev`: the IIO device to get the masklength for

#### <a id="c-iio_for_each_active_channel"></a>`iio_for_each_active_channel()`

```c
iio_for_each_active_channel(indio_dev, chan)
```

Iterated over active channels

**Parameters**

- `indio_dev`: the IIO device
- `chan`: Holds the index of the enabled channel

#### <a id="c-IIO_DEGREE_TO_RAD"></a>`IIO_DEGREE_TO_RAD()`

```c
IIO_DEGREE_TO_RAD(deg)
```

Convert degree to rad

**Parameters**

- `deg`: A value in degree

**Description**

Returns the given value converted from degree to rad

#### <a id="c-IIO_RAD_TO_DEGREE"></a>`IIO_RAD_TO_DEGREE()`

```c
IIO_RAD_TO_DEGREE(rad)
```

Convert rad to degree

**Parameters**

- `rad`: A value in rad

**Description**

Returns the given value converted from rad to degree

#### <a id="c-IIO_G_TO_M_S_2"></a>`IIO_G_TO_M_S_2()`

```c
IIO_G_TO_M_S_2(g)
```

Convert g to meter / second**2

**Parameters**

- `g`: A value in g

**Description**

Returns the given value converted from g to meter / second**2

#### <a id="c-IIO_M_S_2_TO_G"></a>`IIO_M_S_2_TO_G()`

```c
IIO_M_S_2_TO_G(ms2)
```

Convert meter / second**2 to g

**Parameters**

- `ms2`: A value in meter / second**2

**Description**

Returns the given value converted from meter / second**2 to g



#### <a id="c-iio_device_id"></a>`iio_device_id()`

```c
int iio_device_id(struct iio_dev *indio_dev)
```

query the unique ID for the device

**Parameters**

- `struct iio_dev *indio_dev`: Device structure whose ID is being queried

**Description**

The IIO device ID is a unique index used for example for the naming
of the character device /dev/iio\:device\[ID\].

**Return**

Unique ID for the device.

#### <a id="c-iio_buffer_enabled"></a>`iio_buffer_enabled()`

```c
bool iio_buffer_enabled(struct iio_dev *indio_dev)
```

helper function to test if the buffer is enabled

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure for device

**Return**

True, if the buffer is enabled.

#### <a id="c-iio_device_set_clock"></a>`iio_device_set_clock()`

```c
int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
```

Set current timestamping clock for the device

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure containing the device
- `clockid_t clock_id`: timestamping clock POSIX identifier to set.

**Return**

0 on success, or a negative error code.

#### <a id="c-iio_device_get_clock"></a>`iio_device_get_clock()`

```c
clockid_t iio_device_get_clock(const struct iio_dev *indio_dev)
```

Retrieve current timestamping clock for the device

**Parameters**

- `const struct iio_dev *indio_dev`: IIO device structure containing the device

**Return**

Clock ID of the current timestamping clock for the device.

#### <a id="c-iio_get_time_ns"></a>`iio_get_time_ns()`

```c
s64 iio_get_time_ns(const struct iio_dev *indio_dev)
```

utility function to get a time stamp for events etc

**Parameters**

- `const struct iio_dev *indio_dev`: device

**Return**

Timestamp of the event in nanoseconds.

#### <a id="c-iio_read_mount_matrix"></a>`iio_read_mount_matrix()`

```c
int iio_read_mount_matrix(struct device *dev, struct iio_mount_matrix *matrix)
```

retrieve iio device mounting matrix from device "mount-matrix" property

**Parameters**

- `struct device *dev`: device the mounting matrix property is assigned to
- `struct iio_mount_matrix *matrix`: where to store retrieved matrix

**Description**

If device is assigned no mounting matrix property, a default 3x3 identity
matrix will be filled in.

**Return**

0 if success, or a negative error code on failure.

#### <a id="c-iio_format_value"></a>`iio_format_value()`

```c
ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
```

Formats a IIO value into its string representation

**Parameters**

- `char *buf`: The buffer to which the formatted value gets written
  which is assumed to be big enough (i.e. PAGE_SIZE).
- `unsigned int type`: One of the IIO_VAL_* constants. This decides how the val
  and val2 parameters are formatted.
- `int size`: Number of IIO value entries contained in vals
- `int *vals`: Pointer to the values, exact meaning depends on the
  type parameter.

**Return**

0 by default, a negative number on failure or the total number of characters
written for a type that belongs to the IIO_VAL_* constant.

#### <a id="c-iio_str_to_fixpoint"></a>`iio_str_to_fixpoint()`

```c
int iio_str_to_fixpoint(const char *str, int fract_mult, int *integer, int *fract)
```

Parse a fixed-point number from a string

**Parameters**

- `const char *str`: The string to parse
- `int fract_mult`: Multiplier for the first decimal place, should be a power of 10
- `int *integer`: The integer part of the number
- `int *fract`: The fractional part of the number

**Return**

0 on success, or a negative error code if the string could not be parsed.

#### <a id="c-iio_device_alloc"></a>`iio_device_alloc()`

```c
struct iio_dev * iio_device_alloc(struct device *parent, int sizeof_priv)
```

allocate an iio_dev from a driver

**Parameters**

- `struct device *parent`: Parent device.
- `int sizeof_priv`: Space to allocate for private structure.

**Return**

Pointer to allocated iio_dev on success, NULL on failure.

#### <a id="c-iio_device_free"></a>`iio_device_free()`

```c
void iio_device_free(struct iio_dev *dev)
```

free an iio_dev from a driver

**Parameters**

- `struct iio_dev *dev`: the iio_dev associated with the device

#### <a id="c-devm_iio_device_alloc"></a>`devm_iio_device_alloc()`

```c
struct iio_dev * devm_iio_device_alloc(struct device *parent, int sizeof_priv)
```

Resource-managed [`iio_device_alloc()`](#c-iio_device_alloc)

**Parameters**

- `struct device *parent`: Device to allocate iio_dev for, and parent for this IIO device
- `int sizeof_priv`: Space to allocate for private structure.

**Description**

Managed iio_device_alloc. iio_dev allocated with this function is
automatically freed on driver detach.

**Return**

Pointer to allocated iio_dev on success, NULL on failure.

#### <a id="c-iio_active_scan_mask_index"></a>`iio_active_scan_mask_index()`

```c
int iio_active_scan_mask_index(struct iio_dev *indio_dev)
```

Get index of the active scan mask inside the available scan masks array

**Parameters**

- `struct iio_dev *indio_dev`: the IIO device containing the active and available scan masks

**Return**

the index or -EINVAL if  active_scan_mask is not set

#### <a id="c-iio_device_unregister"></a>`iio_device_unregister()`

```c
void iio_device_unregister(struct iio_dev *indio_dev)
```

unregister a device from the IIO subsystem

**Parameters**

- `struct iio_dev *indio_dev`: Device structure representing the device.

#### <a id="c-__iio_dev_mode_lock"></a>`__iio_dev_mode_lock()`

```c
void __iio_dev_mode_lock(struct iio_dev *indio_dev)
```

Locks the current IIO device mode

**Parameters**

- `struct iio_dev *indio_dev`: the iio_dev associated with the device

**Description**

If the device is either in direct or buffer mode, it's guaranteed to stay
that way until [`__iio_dev_mode_unlock()`](#c-__iio_dev_mode_unlock) is called.

This function is not meant to be used directly by drivers to protect internal
state; a driver should have it's own mechanisms for that matter.

There are very few cases where a driver actually needs to lock the current
mode unconditionally. It's recommended to use [`iio_device_claim_direct()`](#c-iio_device_claim_direct) or
[`iio_device_try_claim_buffer_mode()`](#c-iio_device_try_claim_buffer_mode) pairs or related helpers instead.

#### <a id="c-__iio_dev_mode_unlock"></a>`__iio_dev_mode_unlock()`

```c
void __iio_dev_mode_unlock(struct iio_dev *indio_dev)
```

Unlocks the current IIO device mode

**Parameters**

- `struct iio_dev *indio_dev`: the iio_dev associated with the device

#### <a id="c-iio_device_get_current_mode"></a>`iio_device_get_current_mode()`

```c
int iio_device_get_current_mode(struct iio_dev *indio_dev)
```

helper function providing read-only access to the opaque **currentmode** variable

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure for device

---

# HW consumer

_Peios Kernel / Hardware and drivers / Driver development / Industrial I/O_

> An IIO device can be directly connected to another device in hardware. In this case the buffers between IIO provider and IIO consumer are handled by hardware. The Industrial I/O HW consumer offers a way to bond these IIO devices without…

<a id="rst-hw-consumer"></a>

An IIO device can be directly connected to another device in hardware. In this case the buffers between IIO provider and IIO consumer are handled by hardware. The Industrial I/O HW consumer offers a way to bond these IIO devices without software buffer for data. The implementation can be found under `drivers/iio/buffer/hw-consumer.c`

- struct iio_hw_consumer — Hardware consumer structure

- `iio_hw_consumer_alloc()` — Allocate IIO hardware consumer

- `iio_hw_consumer_free()` — Free IIO hardware consumer

- `iio_hw_consumer_enable()` — Enable IIO hardware consumer

- `iio_hw_consumer_disable()` — Disable IIO hardware consumer

<a id="rst-hw-consumer-setup"></a>

## HW consumer setup

As standard IIO device the implementation is based on IIO provider/consumer. A typical IIO HW consumer setup looks like this:



```text
static struct iio_hw_consumer *hwc;

static const struct iio_info adc_info = {
        .read_raw = adc_read_raw,
};

static int adc_read_raw(struct iio_dev *indio_dev,
                        struct iio_chan_spec const *chan, int *val,
                        int *val2, long mask)
{
        ret = iio_hw_consumer_enable(hwc);

        /* Acquire data */

        ret = iio_hw_consumer_disable(hwc);
}

static int adc_probe(struct platform_device *pdev)
{
        hwc = devm_iio_hw_consumer_alloc(&iio->dev);
}
```

<a id="rst-more-details"></a>

## More details


#### <a id="c-iio_hw_consumer_alloc"></a>`iio_hw_consumer_alloc()`

```c
struct iio_hw_consumer * iio_hw_consumer_alloc(struct device *dev)
```

Allocate IIO hardware consumer

**Parameters**

- `struct device *dev`: Pointer to consumer device.

**Description**

Returns a valid iio_hw_consumer on success or a [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure.

#### <a id="c-iio_hw_consumer_free"></a>`iio_hw_consumer_free()`

```c
void iio_hw_consumer_free(struct iio_hw_consumer *hwc)
```

Free IIO hardware consumer

**Parameters**

- `struct iio_hw_consumer *hwc`: hw consumer to free.

#### <a id="c-devm_iio_hw_consumer_alloc"></a>`devm_iio_hw_consumer_alloc()`

```c
struct iio_hw_consumer * devm_iio_hw_consumer_alloc(struct device *dev)
```

Resource-managed [`iio_hw_consumer_alloc()`](#c-iio_hw_consumer_alloc)

**Parameters**

- `struct device *dev`: Pointer to consumer device.

**Description**

Managed iio_hw_consumer_alloc. iio_hw_consumer allocated with this function
is automatically freed on driver detach.

returns pointer to allocated iio_hw_consumer on success, NULL on failure.

#### <a id="c-iio_hw_consumer_enable"></a>`iio_hw_consumer_enable()`

```c
int iio_hw_consumer_enable(struct iio_hw_consumer *hwc)
```

Enable IIO hardware consumer

**Parameters**

- `struct iio_hw_consumer *hwc`: iio_hw_consumer to enable.

**Description**

Returns 0 on success.

#### <a id="c-iio_hw_consumer_disable"></a>`iio_hw_consumer_disable()`

```c
void iio_hw_consumer_disable(struct iio_hw_consumer *hwc)
```

Disable IIO hardware consumer

**Parameters**

- `struct iio_hw_consumer *hwc`: iio_hw_consumer to disable.

---

# Introduction

_Peios Kernel / Hardware and drivers / Driver development / Industrial I/O_

> The main purpose of the Industrial I/O subsystem (IIO) is to provide support for devices that in some sense perform either analog-to-digital conversion (ADC) or digital-to-analog conversion (DAC) or both. The aim is to fill the gap between…

<a id="rst-introduction"></a>

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

The main purpose of the Industrial I/O subsystem (IIO) is to provide support for devices that in some sense perform either analog-to-digital conversion (ADC) or digital-to-analog conversion (DAC) or both. The aim is to fill the gap between the somewhat similar hwmon and [input](</kernel/hardware/driver-api/services/input.md>) subsystems. Hwmon is directed at low sample rate sensors used to monitor and control the system itself, like fan speed control or temperature measurement. [Input](</kernel/hardware/driver-api/services/input.md>) is, as its name suggests, focused on human interaction input devices (keyboard, mouse, touchscreen). In some cases there is considerable overlap between these and IIO.

Devices that fall into this category include:

- analog to digital converters (ADCs)

- accelerometers

- capacitance to digital converters (CDCs)

- digital to analog converters (DACs)

- gyroscopes

- inertial measurement units (IMUs)

- color and light sensors

- magnetometers

- pressure sensors

- proximity sensors

- temperature sensors

Usually these sensors are connected via [SPI](</kernel/hardware/driver-api/buses/spi.md>) or [I2C](</kernel/hardware/driver-api/buses/i2c.md>). A common use case of the sensors devices is to have combined functionality (e.g. light plus proximity sensor).

---

# Triggered Buffers

_Peios Kernel / Hardware and drivers / Driver development / Industrial I/O_

> Now that we know what buffers and triggers are let's see how they work together.

<a id="rst-triggered-buffers"></a>

Now that we know what buffers and triggers are let's see how they work together.

<a id="rst-iio-triggered-buffer-setup"></a>

## IIO triggered buffer setup

- `iio_triggered_buffer_setup()` — Setup triggered buffer and pollfunc

- `iio_triggered_buffer_cleanup()` — Free resources allocated by `iio_triggered_buffer_setup()`

- struct iio_buffer_setup_ops — buffer setup related callbacks

A typical triggered buffer setup looks like this:



```text
const struct iio_buffer_setup_ops sensor_buffer_setup_ops = {
  .preenable    = sensor_buffer_preenable,
  .postenable   = sensor_buffer_postenable,
  .postdisable  = sensor_buffer_postdisable,
  .predisable   = sensor_buffer_predisable,
};

irqreturn_t sensor_iio_pollfunc(int irq, void *p)
{
    pf->timestamp = iio_get_time_ns((struct indio_dev *)p);
    return IRQ_WAKE_THREAD;
}

irqreturn_t sensor_trigger_handler(int irq, void *p)
{
    u16 buf[8];
    int i = 0;

    /* read data for each active channel */
    for_each_set_bit(bit, active_scan_mask, masklength)
        buf[i++] = sensor_get_data(bit)

    iio_push_to_buffers_with_timestamp(indio_dev, buf, timestamp);

    iio_trigger_notify_done(trigger);
    return IRQ_HANDLED;
}

/* setup triggered buffer, usually in probe function */
iio_triggered_buffer_setup(indio_dev, sensor_iio_polfunc,
                           sensor_trigger_handler,
                           sensor_buffer_setup_ops);
```

The important things to notice here are:

- `iio_buffer_setup_ops`, the buffer setup functions to be called at predefined points in the buffer configuration sequence (e.g. before enable, after disable). If not specified, the IIO core uses the default iio_triggered_buffer_setup_ops.

- **sensor_iio_pollfunc**, the function that will be used as top half of poll function. It should do as little processing as possible, because it runs in interrupt context. The most common operation is recording of the current timestamp and for this reason one can use the IIO core defined `iio_pollfunc_store_time()` function.

- **sensor_trigger_handler**, the function that will be used as bottom half of the poll function. This runs in the context of a kernel thread and all the processing takes place here. It usually reads data from the device and stores it in the internal buffer together with the timestamp recorded in the top half.

<a id="rst-more-details"></a>

## More details


#### <a id="c-iio_triggered_buffer_setup_ext"></a>`iio_triggered_buffer_setup_ext()`

```c
int iio_triggered_buffer_setup_ext(struct iio_dev *indio_dev, irqreturn_t (*h)(int irq, void *p), irqreturn_t (*thread)(int irq, void *p), enum iio_buffer_direction direction, const struct iio_buffer_setup_ops *setup_ops, const struct iio_dev_attr **buffer_attrs)
```

Setup triggered buffer and pollfunc

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure
- `irqreturn_t (*h)(int irq, void *p)`: Function which will be used as pollfunc top half
- `irqreturn_t (*thread)(int irq, void *p)`: Function which will be used as pollfunc bottom half
- `enum iio_buffer_direction direction`: Direction of the data stream (in/out).
- `const struct iio_buffer_setup_ops *setup_ops`: Buffer setup functions to use for this device.
  If NULL the default setup functions for triggered
  buffers will be used.
- `const struct iio_dev_attr **buffer_attrs`: Extra sysfs buffer attributes for this IIO buffer

**Description**

This function combines some common tasks which will normally be performed
when setting up a triggered buffer. It will allocate the buffer and the
pollfunc.

Before calling this function the indio_dev structure should already be
completely initialized, but not yet registered. In practice this means that
this function should be called right before [`iio_device_register()`](/kernel/hardware/driver-api/iio/core.md#c-iio_device_register).

To free the resources allocated by this function call
[`iio_triggered_buffer_cleanup()`](#c-iio_triggered_buffer_cleanup).

#### <a id="c-iio_triggered_buffer_cleanup"></a>`iio_triggered_buffer_cleanup()`

```c
void iio_triggered_buffer_cleanup(struct iio_dev *indio_dev)
```

Free resources allocated by [`iio_triggered_buffer_setup_ext()`](#c-iio_triggered_buffer_setup_ext)

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure

---

# Triggers

_Peios Kernel / Hardware and drivers / Driver development / Industrial I/O_

> struct iio_trigger — industrial I/O trigger device

<a id="rst-triggers"></a>

- struct iio_trigger — industrial I/O trigger device

- `devm_iio_trigger_alloc()` — Resource-managed iio_trigger_alloc

- `devm_iio_trigger_register()` — Resource-managed iio_trigger_register iio_trigger_unregister

- `iio_trigger_validate_own_device()` — Check if a trigger and IIO device belong to the same device

In many situations it is useful for a driver to be able to capture data based on some external event (trigger) as opposed to periodically polling for data. An IIO trigger can be provided by a device driver that also has an IIO device based on hardware generated events (e.g. data ready or threshold exceeded) or provided by a separate driver from an independent interrupt source (e.g. GPIO line connected to some external system, timer interrupt or user space writing a specific file in sysfs). A trigger may initiate data capture for a number of sensors and also it may be completely unrelated to the sensor itself.

<a id="rst-iio-trigger-sysfs-interface"></a>

## IIO trigger sysfs interface

There are two locations in sysfs related to triggers:

- `/sys/bus/iio/devices/trigger{Y}/*`, this file is created once an IIO trigger is registered with the IIO core and corresponds to trigger with index Y. Because triggers can be very different depending on type there are few standard attributes that we can describe here:

  - `name`, trigger name that can be later used for association with a device.

  - `sampling_frequency`, some timer based triggers use this attribute to specify the frequency for trigger calls.

- `/sys/bus/iio/devices/iio:device{X}/trigger/*`, this directory is created once the device supports a triggered buffer. We can associate a trigger with our device by writing the trigger's name in the `current_trigger` file.

<a id="rst-iio-trigger-setup"></a>

## IIO trigger setup

Let's see a simple example of how to setup a trigger to be used by a driver:



```text
struct iio_trigger_ops trigger_ops = {
    .set_trigger_state = sample_trigger_state,
    .validate_device = sample_validate_device,
}

struct iio_trigger *trig;

/* first, allocate memory for our trigger */
trig = iio_trigger_alloc(dev, "trig-%s-%d", name, idx);

/* setup trigger operations field */
trig->ops = &trigger_ops;

/* now register the trigger with the IIO core */
iio_trigger_register(trig);
```

<a id="rst-iio-trigger-ops"></a>

## IIO trigger ops

- struct iio_trigger_ops — operations structure for an iio_trigger.

Notice that a trigger has a set of operations attached:

- `set_trigger_state`, switch the trigger on/off on demand.

- `validate_device`, function to validate the device when the current trigger gets changed.

<a id="rst-more-details"></a>

## More details


#### <a id="c-struct-iio_trigger_ops"></a>`struct iio_trigger_ops`

operations structure for an iio_trigger.

**Definition**

```c
struct iio_trigger_ops {
    int (*set_trigger_state)(struct iio_trigger *trig, bool state);
    void (*reenable)(struct iio_trigger *trig);
    int (*validate_device)(struct iio_trigger *trig, struct iio_dev *indio_dev);
};
```

**Members**

- `set_trigger_state`: switch on/off the trigger on demand
- `reenable`: function to reenable the trigger when the
  use count is zero (may be NULL)
- `validate_device`: function to validate the device when the
  current trigger gets changed.

**Description**

This is typically static const within a driver and shared by
instances of a given device.

#### <a id="c-struct-iio_trigger"></a>`struct iio_trigger`

industrial I/O trigger device

**Definition**

```c
struct iio_trigger {
    const struct iio_trigger_ops    *ops;
    struct module                   *owner;
    int id;
    const char                      *name;
    struct device                   dev;
    struct list_head                list;
    struct list_head                alloc_list;
    atomic_t use_count;
    struct irq_chip                 subirq_chip;
    int subirq_base;
    struct iio_subirq subirqs[CONFIG_IIO_CONSUMERS_PER_TRIGGER];
    unsigned long pool[BITS_TO_LONGS(CONFIG_IIO_CONSUMERS_PER_TRIGGER)];
    struct mutex                    pool_lock;
    bool attached_own_device;
    struct work_struct              reenable_work;
};
```

**Members**

- `ops`: \[DRIVER\] operations structure
- `owner`: \[INTERN\] owner of this driver module
- `id`: \[INTERN\] unique id number
- `name`: \[DRIVER\] unique name
- `dev`: \[DRIVER\] associated device (if relevant)
- `list`: \[INTERN\] used in maintenance of global trigger list
- `alloc_list`: \[DRIVER\] used for driver specific trigger list
- `use_count`: \[INTERN\] use count for the trigger.
- `subirq_chip`: \[INTERN\] associate 'virtual' irq chip.
- `subirq_base`: \[INTERN\] base number for irqs provided by trigger.
- `subirqs`: \[INTERN\] information about the 'child' irqs.
- `pool`: \[INTERN\] bitmap of irqs currently in use.
- `pool_lock`: \[INTERN\] protection of the irq pool.
- `attached_own_device`: \[INTERN\] if we are using our own device as trigger,
  i.e. if we registered a poll function to the same
  device as the one providing the trigger.
- `reenable_work`: \[INTERN\] work item used to ensure reenable can sleep.

#### <a id="c-iio_trigger_set_drvdata"></a>`iio_trigger_set_drvdata()`

```c
void iio_trigger_set_drvdata(struct iio_trigger *trig, void *data)
```

Set trigger driver data

**Parameters**

- `struct iio_trigger *trig`: IIO trigger structure
- `void *data`: Driver specific data

**Description**

Allows to attach an arbitrary pointer to an IIO trigger, which can later be
retrieved by [`iio_trigger_get_drvdata()`](#c-iio_trigger_get_drvdata).

#### <a id="c-iio_trigger_get_drvdata"></a>`iio_trigger_get_drvdata()`

```c
void * iio_trigger_get_drvdata(struct iio_trigger *trig)
```

Get trigger driver data

**Parameters**

- `struct iio_trigger *trig`: IIO trigger structure

**Description**

Returns the data previously set with [`iio_trigger_set_drvdata()`](#c-iio_trigger_set_drvdata)

#### <a id="c-iio_trigger_register"></a>`iio_trigger_register()`

```c
int iio_trigger_register(struct iio_trigger *trig_info)
```

register a trigger with the IIO core

**Parameters**

- `struct iio_trigger *trig_info`: trigger to be registered

#### <a id="c-iio_trigger_unregister"></a>`iio_trigger_unregister()`

```c
void iio_trigger_unregister(struct iio_trigger *trig_info)
```

unregister a trigger from the core

**Parameters**

- `struct iio_trigger *trig_info`: trigger to be unregistered

#### <a id="c-iio_trigger_set_immutable"></a>`iio_trigger_set_immutable()`

```c
int iio_trigger_set_immutable(struct iio_dev *indio_dev, struct iio_trigger *trig)
```

set an immutable trigger on destination

**Parameters**

- `struct iio_dev *indio_dev`: IIO device structure containing the device
- `struct iio_trigger *trig`: trigger to assign to device

#### <a id="c-iio_trigger_using_own"></a>`iio_trigger_using_own()`

```c
bool iio_trigger_using_own(struct iio_dev *indio_dev)
```

tells us if we use our own HW trigger ourselves

**Parameters**

- `struct iio_dev *indio_dev`: device to check



#### <a id="c-iio_trigger_poll"></a>`iio_trigger_poll()`

```c
void iio_trigger_poll(struct iio_trigger *trig)
```

Call the IRQ trigger handler of the consumers

**Parameters**

- `struct iio_trigger *trig`: trigger which occurred

**Description**

This function should only be called from a hard IRQ context.

#### <a id="c-iio_trigger_poll_nested"></a>`iio_trigger_poll_nested()`

```c
void iio_trigger_poll_nested(struct iio_trigger *trig)
```

Call the threaded trigger handler of the consumers

**Parameters**

- `struct iio_trigger *trig`: trigger which occurred

**Description**

This function should only be called from a kernel thread context.

#### <a id="c-__iio_trigger_alloc"></a>`__iio_trigger_alloc()`

```c
struct iio_trigger * __iio_trigger_alloc(struct device *parent, struct module *this_mod, const char *fmt, ...)
```

Allocate a trigger

**Parameters**

- `struct device *parent`: Device to allocate iio_trigger for
- `struct module *this_mod`: module allocating the trigger
- `const char *fmt`: trigger name format. If it includes format
  specifiers, the additional arguments following
  format are formatted and inserted in the resulting
  string replacing their respective specifiers.
- `...`: variable arguments

**Return**

Pointer to allocated iio_trigger on success, NULL on failure.

#### <a id="c-__devm_iio_trigger_alloc"></a>`__devm_iio_trigger_alloc()`

```c
struct iio_trigger * __devm_iio_trigger_alloc(struct device *parent, struct module *this_mod, const char *fmt, ...)
```

Resource-managed `iio_trigger_alloc()` Managed iio_trigger_alloc. iio_trigger allocated with this function is automatically freed on driver detach.

**Parameters**

- `struct device *parent`: Device to allocate iio_trigger for
- `struct module *this_mod`: module allocating the trigger
- `const char *fmt`: trigger name format. If it includes format
  specifiers, the additional arguments following
  format are formatted and inserted in the resulting
  string replacing their respective specifiers.
- `...`: variable arguments

**Return**

Pointer to allocated iio_trigger on success, NULL on failure.

#### <a id="c-devm_iio_trigger_register"></a>`devm_iio_trigger_register()`

```c
int devm_iio_trigger_register(struct device *dev, struct iio_trigger *trig_info)
```

Resource-managed [`iio_trigger_register()`](#c-iio_trigger_register)

**Parameters**

- `struct device *dev`: device this trigger was allocated for
- `struct iio_trigger *trig_info`: trigger to register

**Description**

Managed [`iio_trigger_register()`](#c-iio_trigger_register).  The IIO trigger registered with this
function is automatically unregistered on driver detach. This function
calls [`iio_trigger_register()`](#c-iio_trigger_register) internally. Refer to that function for more
information.

**Return**

0 on success, negative error number on failure.

#### <a id="c-iio_validate_own_trigger"></a>`iio_validate_own_trigger()`

```c
int iio_validate_own_trigger(struct iio_dev *idev, struct iio_trigger *trig)
```

Check if a trigger and IIO device belong to the same device

**Parameters**

- `struct iio_dev *idev`: the IIO device to check
- `struct iio_trigger *trig`: the IIO trigger to check

**Description**

This function can be used as the validate_trigger callback for triggers that
can only be attached to their own device.

**Return**

0 if both the trigger and the IIO device belong to the same
device, -EINVAL otherwise.

#### <a id="c-iio_trigger_validate_own_device"></a>`iio_trigger_validate_own_device()`

```c
int iio_trigger_validate_own_device(struct iio_trigger *trig, struct iio_dev *indio_dev)
```

Check if a trigger and IIO device belong to the same device

**Parameters**

- `struct iio_trigger *trig`: The IIO trigger to check
- `struct iio_dev *indio_dev`: the IIO device to check

**Description**

This function can be used as the validate_device callback for triggers that
can only be attached to their own device.

**Return**

0 if both the trigger and the IIO device belong to the same
device, -EINVAL otherwise.

---

# RAID

_Peios Kernel / Hardware and drivers / Driver development / Multiple-device storage_

> Reference for RAID.

<a id="rst-raid"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [MD Cluster](</kernel/hardware/driver-api/md/md-cluster.md>)
- [RAID 4/5/6 cache](</kernel/hardware/driver-api/md/raid5-cache.md>)
- [Partial Parity Log](</kernel/hardware/driver-api/md/raid5-ppl.md>)

---

# MD Cluster

_Peios Kernel / Hardware and drivers / Driver development / Multiple-device storage_

> The cluster MD is a shared-device RAID for a cluster, it supports two levels: raid1 and raid10 (limited support).

<a id="rst-md-cluster"></a>

The cluster MD is a shared-device RAID for a cluster, it supports two levels: raid1 and raid10 (limited support).

<a id="rst-on-disk-format"></a>

## 1. On-disk format

Separate write-intent-bitmaps are used for each cluster node. The bitmaps record all writes that may have been started on that node, and may not yet have finished. The on-disk layout is:



```text
0                    4k                     8k                    12k
-------------------------------------------------------------------
| idle                | md super            | bm super [0] + bits |
| bm bits[0, contd]   | bm super[1] + bits  | bm bits[1, contd]   |
| bm super[2] + bits  | bm bits [2, contd]  | bm super[3] + bits  |
| bm bits [3, contd]  |                     |                     |
```

During "normal" functioning we assume the filesystem ensures that only one node writes to any given block at a time, so a write request will

> - set the appropriate bit (if not already set)
>
> - commit the write to all mirrors
>
> - schedule the bit to be cleared after a timeout.

Reads are just handled normally. It is up to the filesystem to ensure one node doesn't read from a location where another node (or the same node) is writing.

<a id="rst-dlm-locks-for-management"></a>

## 2. DLM Locks for management

There are three groups of locks for managing the device:

<a id="rst-bitmap-lock-resource-bm-lockres"></a>

### 2.1 Bitmap lock resource (bm_lockres)

> The bm_lockres protects individual node bitmaps. They are named in the form bitmap000 for node 1, bitmap001 for node 2 and so on. When a node joins the cluster, it acquires the lock in PW mode and it stays so during the lifetime the node is part of the cluster. The lock resource number is based on the slot number returned by the DLM subsystem. Since DLM starts node count from one and bitmap slots start from zero, one is subtracted from the DLM slot number to arrive at the bitmap slot number.
>
> The LVB of the bitmap lock for a particular node records the range of sectors that are being re-synced by that node.  No other node may write to those sectors.  This is used when a new nodes joins the cluster.

<a id="rst-message-passing-locks"></a>

### 2.2 Message passing locks

> Each node has to communicate with other nodes when starting or ending resync, and for metadata superblock updates.  This communication is managed through three locks: "token", "message", and "ack", together with the Lock Value Block (LVB) of one of the "message" lock.

<a id="rst-new-device-management"></a>

### 2.3 new-device management

> A single lock: "no-new-dev" is used to coordinate the addition of new devices - this must be synchronized across the array. Normally all nodes hold a concurrent-read lock on this device.

<a id="rst-communication"></a>

## 3. Communication

> Messages can be broadcast to all nodes, and the sender waits for all other nodes to acknowledge the message before proceeding.  Only one message can be processed at a time.

<a id="rst-message-types"></a>

### 3.1 Message Types

> There are six types of messages which are passed:

<a id="rst-metadata-updated"></a>

#### 3.1.1 METADATA_UPDATED

> informs other nodes that the metadata has been updated, and the node must re-read the md superblock. This is performed synchronously. It is primarily used to signal device failure.

<a id="rst-resyncing"></a>

#### 3.1.2 RESYNCING

> informs other nodes that a resync is initiated or ended so that each node may suspend or resume the region.  Each RESYNCING message identifies a range of the devices that the sending node is about to resync. This overrides any previous notification from that node: only one ranged can be resynced at a time per-node.

<a id="rst-newdisk"></a>

#### 3.1.3 NEWDISK

> informs other nodes that a device is being added to the array. Message contains an identifier for that device.  See below for further details.

<a id="rst-remove"></a>

#### 3.1.4 REMOVE

> > A failed or spare device is being removed from the array. The slot-number of the device is included in the message.
>
> 3.1.5 RE_ADD:
>
> > A failed device is being re-activated - the assumption is that it has been determined to be working again.
>
> 3.1.6 BITMAP_NEEDS_SYNC:
>
> > If a node is stopped locally but the bitmap isn't clean, then another node is informed to take the ownership of resync.

<a id="rst-communication-mechanism"></a>

### 3.2 Communication mechanism

> The DLM LVB is used to communicate within nodes of the cluster. There are three resources used for the purpose:

<a id="rst-token"></a>

#### 3.2.1 token

> The resource which protects the entire communication system. The node having the token resource is allowed to communicate.

<a id="rst-message"></a>

#### 3.2.2 message

> The lock resource which carries the data to communicate.

<a id="rst-ack"></a>

#### 3.2.3 ack

> The resource, acquiring which means the message has been acknowledged by all nodes in the cluster. The BAST of the resource is used to inform the receiving node that a node wants to communicate.

The algorithm is:

> 1. receive status - all nodes have concurrent-reader lock on "ack":
>
>
>
>    ```text
>    sender                         receiver                 receiver
>    "ack":CR                       "ack":CR                 "ack":CR
>    ```
>
> 2. sender get EX on "token", sender get EX on "message":
>
>
>
>    ```text
>    sender                        receiver                 receiver
>    "token":EX                    "ack":CR                 "ack":CR
>    "message":EX
>    "ack":CR
>    ```
>
>    Sender checks that it still needs to send a message. Messages received or other events that happened while waiting for the "token" may have made this message inappropriate or redundant.
>
> 3. sender writes LVB
>
>    sender down-convert "message" from EX to CW
>
>    sender try to get EX of "ack"
>
>
>
>    ```text
>     [ wait until all receivers have *processed* the "message" ]
>
>                                      [ triggered by bast of "ack" ]
>                                      receiver get CR on "message"
>                                      receiver read LVB
>                                      receiver processes the message
>                                      [ wait finish ]
>                                      receiver releases "ack"
>                                      receiver tries to get PR on "message"
>
>    sender                         receiver                  receiver
>    "token":EX                     "message":CR              "message":CR
>    "message":CW
>    "ack":EX
>    ```
>
> 4. triggered by grant of EX on "ack" (indicating all receivers have processed message)
>
>    sender down-converts "ack" from EX to CR
>
>    sender releases "message"
>
>    sender releases "token"
>
>
>
>    ```text
>                                receiver upconvert to PR on "message"
>                                receiver get CR of "ack"
>                                receiver release "message"
>
>    sender                      receiver                   receiver
>    "ack":CR                    "ack":CR                   "ack":CR
>    ```

<a id="rst-handling-failures"></a>

## 4. Handling Failures

<a id="rst-node-failure"></a>

### 4.1 Node Failure

> When a node fails, the DLM informs the cluster with the slot number. The node starts a cluster recovery thread. The cluster recovery thread:
>
> > - acquires the bitmap&lt;number&gt; lock of the failed node
> >
> > - opens the bitmap
> >
> > - reads the bitmap of the failed node
> >
> > - copies the set bitmap to local node
> >
> > - cleans the bitmap of the failed node
> >
> > - releases bitmap&lt;number&gt; lock of the failed node
> >
> > - initiates resync of the bitmap on the current node md_check_recovery is invoked within recover_bitmaps, then md_check_recovery -&gt; metadata_update_start/finish, it will lock the communication by lock_comm. Which means when one node is resyncing it blocks all other nodes from writing anywhere on the array.
>
> The resync process is the regular md resync. However, in a clustered environment when a resync is performed, it needs to tell other nodes of the areas which are suspended. Before a resync starts, the node send out RESYNCING with the (lo,hi) range of the area which needs to be suspended. Each node maintains a suspend_list, which contains the list of ranges which are currently suspended. On receiving RESYNCING, the node adds the range to the suspend_list. Similarly, when the node performing resync finishes, it sends RESYNCING with an empty range to other nodes and other nodes remove the corresponding entry from the suspend_list.
>
> A helper function, -&gt;area_resyncing() can be used to check if a particular I/O range should be suspended or not.

<a id="rst-device-failure"></a>

## 4.2 Device Failure

> Device failures are handled and communicated with the metadata update routine.  When a node detects a device failure it does not allow any further writes to that device until the failure has been acknowledged by all other nodes.

<a id="rst-adding-a-new-device"></a>

### 5. Adding a new Device

> For adding a new device, it is necessary that all nodes "see" the new device to be added. For this, the following algorithm is used:
>
> > 1. Node 1 issues mdadm --manage /dev/mdX --add /dev/sdYY which issues ioctl(ADD_NEW_DISK with disc.state set to MD_DISK_CLUSTER_ADD)
> >
> > 2. Node 1 sends a NEWDISK message with uuid and slot number
> >
> > 3. Other nodes issue kobject_uevent_env with uuid and slot number (Steps 4,5 could be a udev rule)
> >
> > 4. In userspace, the node searches for the disk, perhaps using blkid -t SUB_UUID=""
> >
> > 5. Other nodes issue either of the following depending on whether the disk was found: ioctl(ADD_NEW_DISK with disc.state set to MD_DISK_CANDIDATE and disc.number set to slot number) ioctl(CLUSTERED_DISK_NACK)
> >
> > 6. Other nodes drop lock on "no-new-devs" (CR) if device is found
> >
> > 7. Node 1 attempts EX lock on "no-new-dev"
> >
> > 8. If node 1 gets the lock, it sends METADATA_UPDATED after unmarking the disk as SpareLocal
> >
> > 9. If not (get "no-new-dev" lock), it fails the operation and sends METADATA_UPDATED.
> >
> > 10. Other nodes get the information whether a disk is added or not by the following METADATA_UPDATED.

<a id="rst-module-interface"></a>

## 6. Module interface

> There are 17 call-backs which the md core can make to the cluster module.  Understanding these can give a good overview of the whole process.

<a id="rst-join-nodes-and-leave"></a>

### 6.1 join(nodes) and leave()

> These are called when an array is started with a clustered bitmap, and when the array is stopped.  join() ensures the cluster is available and initializes the various resources. Only the first 'nodes' nodes in the cluster can use the array.

<a id="rst-slot-number"></a>

### 6.2 slot_number()

> Reports the slot number advised by the cluster infrastructure. Range is from 0 to nodes-1.

<a id="rst-resync-info-update"></a>

### 6.3 resync_info_update()

> This updates the resync range that is stored in the bitmap lock. The starting point is updated as the resync progresses.  The end point is always the end of the array. It does *not* send a RESYNCING message.

<a id="rst-resync-start-resync-finish"></a>

### 6.4 resync_start(), resync_finish()

> These are called when resync/recovery/reshape starts or stops. They update the resyncing range in the bitmap lock and also send a RESYNCING message.  resync_start reports the whole array as resyncing, resync_finish reports none of it.
>
> resync_finish() also sends a BITMAP_NEEDS_SYNC message which allows some other node to take over.

<a id="rst-metadata-update-start-metadata-update-finish-metadata-update-cancel"></a>

### 6.5 metadata_update_start(), metadata_update_finish(), metadata_update_cancel()

> metadata_update_start is used to get exclusive access to the metadata.  If a change is still needed once that access is gained, metadata_update_finish() will send a METADATA_UPDATE message to all other nodes, otherwise metadata_update_cancel() can be used to release the lock.

<a id="rst-area-resyncing"></a>

### 6.6 area_resyncing()

> This combines two elements of functionality.
>
> Firstly, it will check if any node is currently resyncing anything in a given range of sectors.  If any resync is found, then the caller will avoid writing or read-balancing in that range.
>
> Secondly, while node recovery is happening it reports that all areas are resyncing for READ requests.  This avoids races between the cluster-filesystem and the cluster-RAID handling a node failure.

<a id="rst-add-new-disk-start-add-new-disk-finish-new-disk-ack"></a>

### 6.7 add_new_disk_start(), add_new_disk_finish(), new_disk_ack()

> These are used to manage the new-disk protocol described above. When a new device is added, add_new_disk_start() is called before it is bound to the array and, if that succeeds, add_new_disk_finish() is called the device is fully added.
>
> When a device is added in acknowledgement to a previous request, or when the device is declared "unavailable", new_disk_ack() is called.

<a id="rst-remove-disk"></a>

### 6.8 remove_disk()

> This is called when a spare or failed device is removed from the array.  It causes a REMOVE message to be send to other nodes.

<a id="rst-gather-bitmaps"></a>

### 6.9 gather_bitmaps()

> This sends a RE_ADD message to all other nodes and then gathers bitmap information from all bitmaps.  This combined bitmap is then used to recovery the re-added device.

<a id="rst-lock-all-bitmaps-and-unlock-all-bitmaps"></a>

### 6.10 lock_all_bitmaps() and unlock_all_bitmaps()

> These are called when change bitmap to none. If a node plans to clear the cluster raid's bitmap, it need to make sure no other nodes are using the raid which is achieved by lock all bitmap locks within the cluster, and also those locks are unlocked accordingly.

<a id="rst-unsupported-features"></a>

## 7. Unsupported features

There are somethings which are not supported by cluster MD yet.

- change array_sectors.

---

# RAID 4/5/6 cache

_Peios Kernel / Hardware and drivers / Driver development / Multiple-device storage_

> Raid 4/5/6 could include an extra disk for data cache besides normal RAID disks. The role of RAID disks isn't changed with the cache disk. The cache disk caches data to the RAID disks. The cache can be in write-through (supported since…

<a id="rst-raid-4-5-6-cache"></a>

Raid 4/5/6 could include an extra disk for data cache besides normal RAID disks. The role of RAID disks isn't changed with the cache disk. The cache disk caches data to the RAID disks. The cache can be in write-through (supported since 4.4) or write-back mode (supported since 4.10). mdadm (supported since 3.4) has a new option '--write-journal' to create array with cache. Please refer to mdadm manual for details. By default (RAID array starts), the cache is in write-through mode. A user can switch it to write-back mode by:



```text
echo "write-back" > /sys/block/md0/md/journal_mode
```

And switch it back to write-through mode by:



```text
echo "write-through" > /sys/block/md0/md/journal_mode
```

In both modes, all writes to the array will hit cache disk first. This means the cache disk must be fast and sustainable.

<a id="rst-write-through-mode"></a>

## write-through mode

This mode mainly fixes the 'write hole' issue. For RAID 4/5/6 array, an unclean shutdown can cause data in some stripes to not be in consistent state, eg, data and parity don't match. The reason is that a stripe write involves several RAID disks and it's possible the writes don't hit all RAID disks yet before the unclean shutdown. We call an array degraded if it has inconsistent data. MD tries to resync the array to bring it back to normal state. But before the resync completes, any system crash will expose the chance of real data corruption in the RAID array. This problem is called 'write hole'.

The write-through cache will cache all data on cache disk first. After the data is safe on the cache disk, the data will be flushed onto RAID disks. The two-step write will guarantee MD can recover correct data after unclean shutdown even the array is degraded. Thus the cache can close the 'write hole'.

In write-through mode, MD reports IO completion to upper layer (usually filesystems) after the data is safe on RAID disks, so cache disk failure doesn't cause data loss. Of course cache disk failure means the array is exposed to 'write hole' again.

In write-through mode, the cache disk isn't required to be big. Several hundreds megabytes are enough.

<a id="rst-write-back-mode"></a>

## write-back mode

write-back mode fixes the 'write hole' issue too, since all write data is cached on cache disk. But the main goal of 'write-back' cache is to speed up write. If a write crosses all RAID disks of a stripe, we call it full-stripe write. For non-full-stripe writes, MD must read old data before the new parity can be calculated. These synchronous reads hurt write throughput. Some writes which are sequential but not dispatched in the same time will suffer from this overhead too. Write-back cache will aggregate the data and flush the data to RAID disks only after the data becomes a full stripe write. This will completely avoid the overhead, so it's very helpful for some workloads. A typical workload which does sequential write followed by fsync is an example.

In write-back mode, MD reports IO completion to upper layer (usually filesystems) right after the data hits cache disk. The data is flushed to raid disks later after specific conditions met. So cache disk failure will cause data loss.

In write-back mode, MD also caches data in memory. The memory cache includes the same data stored on cache disk, so a power loss doesn't cause data loss. The memory cache size has performance impact for the array. It's recommended the size is big. A user can configure the size by:



```text
echo "2048" > /sys/block/md0/md/stripe_cache_size
```

Too small cache disk will make the write aggregation less efficient in this mode depending on the workloads. It's recommended to use a cache disk with at least several gigabytes size in write-back mode.

<a id="rst-the-implementation"></a>

## The implementation

The write-through and write-back cache use the same disk format. The cache disk is organized as a simple write log. The log consists of 'meta data' and 'data' pairs. The meta data describes the data. It also includes checksum and sequence ID for recovery identification. Data can be IO data and parity data. Data is checksummed too. The checksum is stored in the meta data ahead of the data. The checksum is an optimization because MD can write meta and data freely without worry about the order. MD superblock has a field pointed to the valid meta data of log head.

The log implementation is pretty straightforward. The difficult part is the order in which MD writes data to cache disk and RAID disks. Specifically, in write-through mode, MD calculates parity for IO data, writes both IO data and parity to the log, writes the data and parity to RAID disks after the data and parity is settled down in log and finally the IO is finished. Read just reads from raid disks as usual.

In write-back mode, MD writes IO data to the log and reports IO completion. The data is also fully cached in memory at that time, which means read must query memory cache. If some conditions are met, MD will flush the data to RAID disks. MD will calculate parity for the data and write parity into the log. After this is finished, MD will write both data and parity into RAID disks, then MD can release the memory cache. The flush conditions could be stripe becomes a full stripe write, free cache disk space is low or free in-kernel memory cache space is low.

After an unclean shutdown, MD does recovery. MD reads all meta data and data from the log. The sequence ID and checksum will help us detect corrupted meta data and data. If MD finds a stripe with data and valid parities (1 parity for raid4/5 and 2 for raid6), MD will write the data and parities to RAID disks. If parities are incompleted, they are discarded. If part of data is corrupted, they are discarded too. MD then loads valid data and writes them to RAID disks in normal way.

---

# Partial Parity Log

_Peios Kernel / Hardware and drivers / Driver development / Multiple-device storage_

> Partial Parity Log (PPL) is a feature available for RAID5 arrays. The issue addressed by PPL is that after a dirty shutdown, parity of a particular stripe may become inconsistent with data on other member disks. If the array is also in…

<a id="rst-partial-parity-log"></a>

Partial Parity Log (PPL) is a feature available for RAID5 arrays. The issue addressed by PPL is that after a dirty shutdown, parity of a particular stripe may become inconsistent with data on other member disks. If the array is also in degraded state, there is no way to recalculate parity, because one of the disks is missing. This can lead to silent data corruption when rebuilding the array or using it is as degraded - data calculated from parity for array blocks that have not been touched by a write request during the unclean shutdown can be incorrect. Such condition is known as the RAID5 Write Hole. Because of this, md by default does not allow starting a dirty degraded array.

Partial parity for a write operation is the XOR of stripe data chunks not modified by this write. It is just enough data needed for recovering from the write hole. XORing partial parity with the modified chunks produces parity for the stripe, consistent with its state before the write operation, regardless of which chunk writes have completed. If one of the not modified data disks of this stripe is missing, this updated parity can be used to recover its contents. PPL recovery is also performed when starting an array after an unclean shutdown and all disks are available, eliminating the need to resync the array. Because of this, using write-intent bitmap and PPL together is not supported.

When handling a write request PPL writes partial parity before new data and parity are dispatched to disks. PPL is a distributed log - it is stored on array member drives in the metadata area, on the parity drive of a particular stripe.  It does not require a dedicated journaling drive. Write performance is reduced by up to 30%-40% but it scales with the number of drives in the array and the journaling drive does not become a bottleneck or a single point of failure.

Unlike raid5-cache, the other solution in md for closing the write hole, PPL is not a true journal. It does not protect from losing in-flight data, only from silent data corruption. If a dirty disk of a stripe is lost, no PPL recovery is performed for this stripe (parity is not updated). So it is possible to have arbitrary data in the written part of a stripe if that disk is lost. In such case the behavior is the same as in plain raid5.

PPL is available for md version-1 metadata and external (specifically IMSM) metadata arrays. It can be enabled using mdadm option --consistency-policy=ppl.

There is a limitation of maximum 64 disks in the array for PPL. It allows to keep data structures and implementation simple. RAID5 arrays with so many disks are not likely due to high risk of multiple disks failure. Such restriction should not be a real life limitation.

---

# Intel(R) Management Engine Interface (Intel(R) MEI)

_Peios Kernel / Hardware and drivers / Driver development / Management Engine Interface_

> Copyright © 2019 Intel Corporation

<a id="rst-intel-r-management-engine-interface-intel-r-mei"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright** © 2019 Intel Corporation

**Table of Contents**

- [Introduction](</kernel/hardware/driver-api/mei/mei.md>)
- [Intel(R) Management Engine (ME) Client bus API](</kernel/hardware/driver-api/mei/mei-client-bus.md>)
- [Intel(R) Active Management Technology (Intel AMT)](</kernel/hardware/driver-api/mei/iamt.md>)

---

# HDCP:

_Peios Kernel / Hardware and drivers / Driver development / Management Engine Interface_

> ME FW as a security engine provides the capability for setting up HDCP2.2 protocol negotiation between the Intel graphics device and an HDC2.2 sink.

<a id="rst-hdcp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

ME FW as a security engine provides the capability for setting up HDCP2.2 protocol negotiation between the Intel graphics device and an HDC2.2 sink.

ME FW prepares HDCP2.2 negotiation parameters, signs and encrypts them according the HDCP 2.2 spec. The Intel graphics sends the created blob to the HDCP2.2 sink.

Similarly, the HDCP2.2 sink's response is transferred to ME FW for decryption and verification.

Once all the steps of HDCP2.2 negotiation are completed, upon request ME FW will configure the port as authenticated and supply the HDCP encryption keys to Intel graphics hardware.

<a id="rst-mei-hdcp-driver"></a>

## mei_hdcp driver


The mei_hdcp driver acts as a translation layer between HDCP 2.2
protocol  implementer (I915) and ME FW by translating HDCP2.2
negotiation messages to ME FW command payloads and vice versa.


<a id="rst-mei-hdcp-api"></a>

## mei_hdcp api


#### <a id="c-mei_hdcp_initiate_session"></a>`mei_hdcp_initiate_session()`

```c
int mei_hdcp_initiate_session(struct device *dev, struct hdcp_port_data *data, struct hdcp2_ake_init *ake_data)
```

Initiate a Wired HDCP2.2 Tx Session in ME FW

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data
- `struct hdcp2_ake_init *ake_data`: AKE_Init msg output.

**Return**

0 on Success, \<0 on Failure.

#### <a id="c-mei_hdcp_verify_receiver_cert_prepare_km"></a>`mei_hdcp_verify_receiver_cert_prepare_km()`

```c
int mei_hdcp_verify_receiver_cert_prepare_km(struct device *dev, struct hdcp_port_data *data, struct hdcp2_ake_send_cert *rx_cert, bool *km_stored, struct hdcp2_ake_no_stored_km *ek_pub_km, size_t *msg_sz)
```

Verify the Receiver Certificate AKE_Send_Cert and prepare AKE_Stored_Km/AKE_No_Stored_Km

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data
- `struct hdcp2_ake_send_cert *rx_cert`: AKE_Send_Cert for verification
- `bool *km_stored`: Pairing status flag output
- `struct hdcp2_ake_no_stored_km *ek_pub_km`: AKE_Stored_Km/AKE_No_Stored_Km output msg
- `size_t *msg_sz`: size of AKE_XXXXX_Km output msg

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_verify_hprime"></a>`mei_hdcp_verify_hprime()`

```c
int mei_hdcp_verify_hprime(struct device *dev, struct hdcp_port_data *data, struct hdcp2_ake_send_hprime *rx_hprime)
```

Verify AKE_Send_H_prime at ME FW.

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data
- `struct hdcp2_ake_send_hprime *rx_hprime`: AKE_Send_H_prime msg for ME FW verification

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_store_pairing_info"></a>`mei_hdcp_store_pairing_info()`

```c
int mei_hdcp_store_pairing_info(struct device *dev, struct hdcp_port_data *data, struct hdcp2_ake_send_pairing_info *pairing_info)
```

Store pairing info received at ME FW

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data
- `struct hdcp2_ake_send_pairing_info *pairing_info`: AKE_Send_Pairing_Info msg input to ME FW

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_initiate_locality_check"></a>`mei_hdcp_initiate_locality_check()`

```c
int mei_hdcp_initiate_locality_check(struct device *dev, struct hdcp_port_data *data, struct hdcp2_lc_init *lc_init_data)
```

Prepare LC_Init

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data
- `struct hdcp2_lc_init *lc_init_data`: LC_Init msg output

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_verify_lprime"></a>`mei_hdcp_verify_lprime()`

```c
int mei_hdcp_verify_lprime(struct device *dev, struct hdcp_port_data *data, struct hdcp2_lc_send_lprime *rx_lprime)
```

Verify lprime.

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data
- `struct hdcp2_lc_send_lprime *rx_lprime`: LC_Send_L_prime msg for ME FW verification

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_get_session_key"></a>`mei_hdcp_get_session_key()`

```c
int mei_hdcp_get_session_key(struct device *dev, struct hdcp_port_data *data, struct hdcp2_ske_send_eks *ske_data)
```

Prepare SKE_Send_Eks.

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data
- `struct hdcp2_ske_send_eks *ske_data`: SKE_Send_Eks msg output from ME FW.

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_repeater_check_flow_prepare_ack"></a>`mei_hdcp_repeater_check_flow_prepare_ack()`

```c
int mei_hdcp_repeater_check_flow_prepare_ack(struct device *dev, struct hdcp_port_data *data, struct hdcp2_rep_send_receiverid_list *rep_topology, struct hdcp2_rep_send_ack *rep_send_ack)
```

Validate the Downstream topology and prepare rep_ack.

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data
- `struct hdcp2_rep_send_receiverid_list *rep_topology`: Receiver ID List to be validated
- `struct hdcp2_rep_send_ack *rep_send_ack`: repeater ack from ME FW.

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_verify_mprime"></a>`mei_hdcp_verify_mprime()`

```c
int mei_hdcp_verify_mprime(struct device *dev, struct hdcp_port_data *data, struct hdcp2_rep_stream_ready *stream_ready)
```

Verify mprime.

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data
- `struct hdcp2_rep_stream_ready *stream_ready`: RepeaterAuth_Stream_Ready msg for ME FW verification.

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_enable_authentication"></a>`mei_hdcp_enable_authentication()`

```c
int mei_hdcp_enable_authentication(struct device *dev, struct hdcp_port_data *data)
```

Mark a port as authenticated through ME FW

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_close_session"></a>`mei_hdcp_close_session()`

```c
int mei_hdcp_close_session(struct device *dev, struct hdcp_port_data *data)
```

Close the Wired HDCP Tx session of ME FW per port. This also disables the authenticated state of the port.

**Parameters**

- `struct device *dev`: device corresponding to the mei_cl_device
- `struct hdcp_port_data *data`: Intel HW specific hdcp data

**Return**

0 on Success, \<0 on Failure

#### <a id="c-mei_hdcp_component_match"></a>`mei_hdcp_component_match()`

```c
int mei_hdcp_component_match(struct device *dev, int subcomponent, void *data)
```

compare function for matching mei hdcp.

**Parameters**

- `struct device *dev`: master device
- `int subcomponent`: subcomponent to match (I915_COMPONENT_HDCP)
- `void *data`: compare data (mei hdcp device)

**Description**

The function checks if the driver is i915, the subcomponent is HDCP
and the grand parent of hdcp and the parent of i915 are the same
PCH device.

**Return**

* 1 - if components match
* 0 - otherwise

---

# Intel(R) Active Management Technology (Intel AMT)

_Peios Kernel / Hardware and drivers / Driver development / Management Engine Interface_

> Prominent usage of the Intel ME Interface is to communicate with Intel(R) Active Management Technology (Intel AMT) implemented in firmware running on the Intel ME.

<a id="rst-intel-r-active-management-technology-intel-amt"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Prominent usage of the Intel ME Interface is to communicate with Intel(R) Active Management Technology (Intel AMT) implemented in firmware running on the Intel ME.

Intel AMT provides the ability to manage a host remotely out-of-band (OOB) even when the operating system running on the host processor has crashed or is in a sleep state.

- **Some examples of Intel AMT usage are:**

  - Monitoring hardware state and platform components

  - Remote power off/on (useful for green computing or overnight IT maintenance)

  - OS updates

  - Storage of useful platform information such as software assets

  - Built-in hardware KVM

  - Selective network isolation of Ethernet and IP protocol flows based on policies set by a remote management console

  - IDE device redirection from remote management console

Intel AMT (OOB) communication is based on SOAP (deprecated starting with Release 6.0) over HTTP/S or WS-Management protocol over HTTP/S that are received from a remote management console application.

For more information about Intel AMT: [https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm](<https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm>)

<a id="rst-intel-amt-applications"></a>

## Intel AMT Applications

> 1. Intel Local Management Service (Intel LMS)
>
>    Applications running locally on the platform communicate with Intel AMT Release 2.0 and later releases in the same way that network applications do via SOAP over HTTP (deprecated starting with Release 6.0) or with WS-Management over SOAP over HTTP. This means that some Intel AMT features can be accessed from a local application using the same network interface as a remote application communicating with Intel AMT over the network.
>
>    When a local application sends a message addressed to the local Intel AMT host name, the Intel LMS, which listens for traffic directed to the host name, intercepts the message and routes it to the Intel MEI. For more information: [https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm](<https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm>) Under "About Intel AMT" =&gt; "Local Access"
>
>    For downloading Intel LMS: [https://github.com/intel/lms](<https://github.com/intel/lms>)
>
>    The Intel LMS opens a connection using the Intel MEI driver to the Intel LMS firmware feature using a defined GUID and then communicates with the feature using a protocol called Intel AMT Port Forwarding Protocol (Intel APF protocol). The protocol is used to maintain multiple sessions with Intel AMT from a single application.
>
>    See the protocol specification in the Intel AMT Software Development Kit (SDK) [https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm](<https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm>) Under "SDK Resources" =&gt; "Intel(R) vPro(TM) Gateway (MPS)" =&gt; "Information for Intel(R) vPro(TM) Gateway Developers" =&gt; "Description of the Intel AMT Port Forwarding (APF) Protocol"
>
> 2. Intel AMT Remote configuration using a Local Agent
>
>    A Local Agent enables IT personnel to configure Intel AMT out-of-the-box without requiring installing additional data to enable setup. The remote configuration process may involve an ISV-developed remote configuration agent that runs on the host. For more information: [https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm](<https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm>) Under "Setup and Configuration of Intel AMT" =&gt; "SDK Tools Supporting Setup and Configuration" =&gt; "Using the Local Agent Sample"

<a id="rst-intel-amt-os-health-watchdog"></a>

## Intel AMT OS Health Watchdog

The Intel AMT Watchdog is an OS Health (Hang/Crash) watchdog. Whenever the OS hangs or crashes, Intel AMT will send an event to any subscriber to this event. This mechanism means that IT knows when a platform crashes even when there is a hard failure on the host.

- **The Intel AMT Watchdog is composed of two parts:**

  1. Firmware feature - receives the heartbeats and sends an event when the heartbeats stop.

  2. Intel MEI iAMT watchdog driver - connects to the watchdog feature, configures the watchdog and sends the heartbeats.

The Intel iAMT watchdog MEI driver uses the kernel watchdog API to configure the Intel AMT Watchdog and to send heartbeats to it. The default timeout of the watchdog is 120 seconds.

If the Intel AMT is not enabled in the firmware then the watchdog client won't enumerate on the me client bus and watchdog devices won't be exposed.

--- [linux-mei@linux.intel.com](<mailto:linux-mei@linux.intel.com>)

---

# Intel(R) Management Engine (ME) Client bus API

_Peios Kernel / Hardware and drivers / Driver development / Management Engine Interface_

> The MEI character device is useful for dedicated applications to send and receive data to the many FW appliance found in Intel's ME from the user space. However, for some of the ME functionalities it makes sense to leverage existing…

<a id="rst-intel-r-management-engine-me-client-bus-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-rationale"></a>

## Rationale

The MEI character device is useful for dedicated applications to send and receive data to the many FW appliance found in Intel's ME from the user space. However, for some of the ME functionalities it makes sense to leverage existing software stack and expose them through existing kernel subsystems.

In order to plug seamlessly into the kernel device driver model we add kernel virtual bus abstraction on top of the MEI driver. This allows implementing Linux kernel drivers for the various MEI features as a stand alone entities found in their respective subsystem. Existing device drivers can even potentially be re-used by adding an MEI CL bus layer to the existing code.

<a id="rst-mei-cl-bus-api"></a>

## MEI CL bus API

A driver implementation for an MEI Client is very similar to any other existing bus based device drivers. The driver registers itself as an MEI CL bus driver through the `struct mei_cl_driver` structure defined in `include/linux/mei_cl_bus.c`



```C
struct mei_cl_driver {
        struct device_driver driver;
        const char *name;

        const struct mei_cl_device_id *id_table;

        int (*probe)(struct mei_cl_device *dev, const struct mei_cl_id *id);
        int (*remove)(struct mei_cl_device *dev);
};
```

The mei_cl_device_id structure defined in `include/linux/mod_devicetable.h` allows a driver to bind itself against a device name.



```C
struct mei_cl_device_id {
        char name[MEI_CL_NAME_SIZE];
        uuid_le uuid;
        __u8    version;
        kernel_ulong_t driver_info;
};
```

To actually register a driver on the ME Client bus one must call the `mei_cl_add_driver()` API. This is typically called at module initialization time.

Once the driver is registered and bound to the device, a driver will typically try to do some I/O on this bus and this should be done through the `mei_cl_send()` and `mei_cl_recv()` functions. More detailed information is in [API:](<#rst-api>) section.

In order for a driver to be notified about pending traffic or event, the driver should register a callback via `mei_cl_devev_register_rx_cb()` and `mei_cldev_register_notify_cb()` function respectively.

<a id="rst-api-1"></a>
<a id="rst-api"></a>

### API:


#### <a id="c-mei_cldev_send_vtag"></a>`mei_cldev_send_vtag()`

```c
ssize_t mei_cldev_send_vtag(struct mei_cl_device *cldev, const u8 *buf, size_t length, u8 vtag)
```

me device send with vtag (write)

**Parameters**

- `struct mei_cl_device *cldev`: me client device
- `const u8 *buf`: buffer to send
- `size_t length`: buffer length
- `u8 vtag`: virtual tag

**Return**

* written size in bytes
* \< 0 on error

#### <a id="c-mei_cldev_send_vtag_timeout"></a>`mei_cldev_send_vtag_timeout()`

```c
ssize_t mei_cldev_send_vtag_timeout(struct mei_cl_device *cldev, const u8 *buf, size_t length, u8 vtag, unsigned long timeout)
```

me device send with vtag and timeout (write)

**Parameters**

- `struct mei_cl_device *cldev`: me client device
- `const u8 *buf`: buffer to send
- `size_t length`: buffer length
- `u8 vtag`: virtual tag
- `unsigned long timeout`: send timeout in milliseconds, 0 for infinite timeout

**Return**

* written size in bytes
* \< 0 on error

#### <a id="c-mei_cldev_recv_vtag"></a>`mei_cldev_recv_vtag()`

```c
ssize_t mei_cldev_recv_vtag(struct mei_cl_device *cldev, u8 *buf, size_t length, u8 *vtag)
```

client receive with vtag (read)

**Parameters**

- `struct mei_cl_device *cldev`: me client device
- `u8 *buf`: buffer to receive
- `size_t length`: buffer length
- `u8 *vtag`: virtual tag

**Return**

* read size in bytes
* \< 0 on error

#### <a id="c-mei_cldev_recv_timeout"></a>`mei_cldev_recv_timeout()`

```c
ssize_t mei_cldev_recv_timeout(struct mei_cl_device *cldev, u8 *buf, size_t length, unsigned long timeout)
```

client receive with timeout (read)

**Parameters**

- `struct mei_cl_device *cldev`: me client device
- `u8 *buf`: buffer to receive
- `size_t length`: buffer length
- `unsigned long timeout`: send timeout in milliseconds, 0 for infinite timeout

**Return**

* read size in bytes
* \< 0 on error

#### <a id="c-mei_cldev_recv_vtag_timeout"></a>`mei_cldev_recv_vtag_timeout()`

```c
ssize_t mei_cldev_recv_vtag_timeout(struct mei_cl_device *cldev, u8 *buf, size_t length, u8 *vtag, unsigned long timeout)
```

client receive with vtag (read)

**Parameters**

- `struct mei_cl_device *cldev`: me client device
- `u8 *buf`: buffer to receive
- `size_t length`: buffer length
- `u8 *vtag`: virtual tag
- `unsigned long timeout`: recv timeout in milliseconds, 0 for infinite timeout

**Return**

* read size in bytes
* \< 0 on error

#### <a id="c-mei_cldev_send"></a>`mei_cldev_send()`

```c
ssize_t mei_cldev_send(struct mei_cl_device *cldev, const u8 *buf, size_t length)
```

me device send (write)

**Parameters**

- `struct mei_cl_device *cldev`: me client device
- `const u8 *buf`: buffer to send
- `size_t length`: buffer length

**Return**

* written size in bytes
* \< 0 on error

#### <a id="c-mei_cldev_send_timeout"></a>`mei_cldev_send_timeout()`

```c
ssize_t mei_cldev_send_timeout(struct mei_cl_device *cldev, const u8 *buf, size_t length, unsigned long timeout)
```

me device send with timeout (write)

**Parameters**

- `struct mei_cl_device *cldev`: me client device
- `const u8 *buf`: buffer to send
- `size_t length`: buffer length
- `unsigned long timeout`: send timeout in milliseconds, 0 for infinite timeout

**Return**

* written size in bytes
* \< 0 on error

#### <a id="c-mei_cldev_recv"></a>`mei_cldev_recv()`

```c
ssize_t mei_cldev_recv(struct mei_cl_device *cldev, u8 *buf, size_t length)
```

client receive (read)

**Parameters**

- `struct mei_cl_device *cldev`: me client device
- `u8 *buf`: buffer to receive
- `size_t length`: buffer length

**Return**

read size in bytes of \< 0 on error

#### <a id="c-mei_cldev_register_rx_cb"></a>`mei_cldev_register_rx_cb()`

```c
int mei_cldev_register_rx_cb(struct mei_cl_device *cldev, mei_cldev_cb_t rx_cb)
```

register Rx event callback

**Parameters**

- `struct mei_cl_device *cldev`: me client devices
- `mei_cldev_cb_t rx_cb`: callback function

**Return**

0 on success
-EALREADY if an callback is already registered
\<0 on other errors

#### <a id="c-mei_cldev_register_notif_cb"></a>`mei_cldev_register_notif_cb()`

```c
int mei_cldev_register_notif_cb(struct mei_cl_device *cldev, mei_cldev_cb_t notif_cb)
```

register FW notification event callback

**Parameters**

- `struct mei_cl_device *cldev`: me client devices
- `mei_cldev_cb_t notif_cb`: callback function

**Return**

0 on success
-EALREADY if an callback is already registered
\<0 on other errors

#### <a id="c-mei_cldev_get_drvdata"></a>`mei_cldev_get_drvdata()`

```c
void * mei_cldev_get_drvdata(const struct mei_cl_device *cldev)
```

driver data getter

**Parameters**

- `const struct mei_cl_device *cldev`: mei client device

**Return**

driver private data

#### <a id="c-mei_cldev_set_drvdata"></a>`mei_cldev_set_drvdata()`

```c
void mei_cldev_set_drvdata(struct mei_cl_device *cldev, void *data)
```

driver data setter

**Parameters**

- `struct mei_cl_device *cldev`: mei client device
- `void *data`: data to store

#### <a id="c-mei_cldev_ver"></a>`mei_cldev_ver()`

```c
u8 mei_cldev_ver(const struct mei_cl_device *cldev)
```

return protocol version of the underlying me client

**Parameters**

- `const struct mei_cl_device *cldev`: mei client device

**Return**

me client protocol version

#### <a id="c-mei_cldev_mtu"></a>`mei_cldev_mtu()`

```c
size_t mei_cldev_mtu(const struct mei_cl_device *cldev)
```

max message that client can send and receive

**Parameters**

- `const struct mei_cl_device *cldev`: mei client device

**Return**

mtu or 0 if client is not connected

#### <a id="c-mei_cldev_enabled"></a>`mei_cldev_enabled()`

```c
bool mei_cldev_enabled(const struct mei_cl_device *cldev)
```

check whether the device is enabled

**Parameters**

- `const struct mei_cl_device *cldev`: mei client device

**Return**

true if me client is initialized and connected

#### <a id="c-mei_cldev_enable"></a>`mei_cldev_enable()`

```c
int mei_cldev_enable(struct mei_cl_device *cldev)
```

enable me client device create connection with me client

**Parameters**

- `struct mei_cl_device *cldev`: me client device

**Return**

0 on success and \< 0 on error

#### <a id="c-mei_cldev_disable"></a>`mei_cldev_disable()`

```c
int mei_cldev_disable(struct mei_cl_device *cldev)
```

disable me client device disconnect form the me client

**Parameters**

- `struct mei_cl_device *cldev`: me client device

**Return**

0 on success and \< 0 on error

#### <a id="c-mei_cldev_send_gsc_command"></a>`mei_cldev_send_gsc_command()`

```c
ssize_t mei_cldev_send_gsc_command(struct mei_cl_device *cldev, u8 client_id, u32 fence_id, struct scatterlist *sg_in, size_t total_in_len, struct scatterlist *sg_out)
```

sends a gsc command, by sending a gsl mei message to gsc and receiving reply from gsc

**Parameters**

- `struct mei_cl_device *cldev`: me client device
- `u8 client_id`: client id to send the command to
- `u32 fence_id`: fence id to send the command to
- `struct scatterlist *sg_in`: scatter gather list containing addresses for rx message buffer
- `size_t total_in_len`: total length of data in 'in' sg, can be less than the sum of buffers sizes
- `struct scatterlist *sg_out`: scatter gather list containing addresses for tx message buffer

**Return**

* written size in bytes
* \< 0 on error


<a id="rst-example"></a>

## Example

As a theoretical example let's pretend the ME comes with a "contact" NFC IP. The driver init and exit routines for this device would look like:



```C
#define CONTACT_DRIVER_NAME "contact"

static struct mei_cl_device_id contact_mei_cl_tbl[] = {
        { CONTACT_DRIVER_NAME, },

        /* required last entry */
        { }
};
MODULE_DEVICE_TABLE(mei_cl, contact_mei_cl_tbl);

static struct mei_cl_driver contact_driver = {
        .id_table = contact_mei_tbl,
        .name = CONTACT_DRIVER_NAME,

        .probe = contact_probe,
        .remove = contact_remove,
};

static int contact_init(void)
{
        int r;

        r = mei_cl_driver_register(&contact_driver);
        if (r) {
                pr_err(CONTACT_DRIVER_NAME ": driver registration failed\n");
                return r;
        }

        return 0;
}

static void __exit contact_exit(void)
{
        mei_cl_driver_unregister(&contact_driver);
}

module_init(contact_init);
module_exit(contact_exit);
```

And the driver's simplified probe routine would look like that:



```C
int contact_probe(struct mei_cl_device *dev, struct mei_cl_device_id *id)
{
        [...]
        mei_cldev_enable(dev);

        mei_cldev_register_rx_cb(dev, contact_rx_cb);

        return 0;
}
```

In the probe routine the driver first enable the MEI device and then registers an rx handler which is as close as it can get to registering a threaded IRQ handler. The handler implementation will typically call `mei_cldev_recv()` and then process received data.



```C
#define MAX_PAYLOAD 128
#define HDR_SIZE 4
static void conntact_rx_cb(struct mei_cl_device *cldev)
{
        struct contact *c = mei_cldev_get_drvdata(cldev);
        unsigned char payload[MAX_PAYLOAD];
        ssize_t payload_sz;

        payload_sz = mei_cldev_recv(cldev, payload,  MAX_PAYLOAD)
        if (reply_size < HDR_SIZE) {
                return;
        }

        c->process_rx(payload);

}
```

<a id="rst-mei-client-bus-drivers"></a>

## MEI Client Bus Drivers

- [HDCP:](</kernel/hardware/driver-api/mei/hdcp.md>)
- [MEI NFC](</kernel/hardware/driver-api/mei/nfc.md>)

---

# Introduction

_Peios Kernel / Hardware and drivers / Driver development / Management Engine Interface_

> The Intel Management Engine (Intel ME) is an isolated and protected computing resource (Co-processor) residing inside certain Intel chipsets. The Intel ME provides support for computer/IT management and security features. The actual…

> **Peios:** Interface availability and resource limits do not grant native access. Peios applies descriptor/handle checks, its sysfs write gate and mapped privilege checks where applicable. Read inherited privileged/unprivileged terminology with [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The Intel Management Engine (Intel ME) is an isolated and protected computing resource (Co-processor) residing inside certain Intel chipsets. The Intel ME provides support for computer/IT management and security features. The actual feature set depends on the Intel chipset SKU.

The Intel Management Engine Interface (Intel MEI, previously known as HECI) is the interface between the Host and Intel ME. This interface is exposed to the host as a PCI device, actually multiple PCI devices might be exposed. The Intel MEI Driver is in charge of the communication channel between a host application and the Intel ME features.

Each Intel ME feature, or Intel ME Client is addressed by a unique GUID and each client has its own protocol. The protocol is message-based with a header and payload up to maximal number of bytes advertised by the client, upon connection.

<a id="rst-intel-mei-driver"></a>

## Intel MEI Driver

The driver exposes a character device with device nodes /dev/meiX.

An application maintains communication with an Intel ME feature while /dev/meiX is open. The binding to a specific feature is performed by calling `MEI_CONNECT_CLIENT_IOCTL`, which passes the desired GUID. The number of instances of an Intel ME feature that can be opened at the same time depends on the Intel ME feature, but most of the features allow only a single instance.

The driver is transparent to data that are passed between firmware feature and host application.

Because some of the Intel ME features can change the system configuration, the driver by default allows only a privileged user to access it.

The session is terminated calling `close(fd)`.

A code snippet for an application communicating with Intel AMTHI client:

In order to support virtualization or sandboxing a trusted supervisor can use `MEI_CONNECT_CLIENT_IOCTL_VTAG` to create virtual channels with an Intel ME feature. Not all features support virtual channels such client with answer EOPNOTSUPP.



```C
struct mei_connect_client_data data;
fd = open(MEI_DEVICE);

data.d.in_client_uuid = AMTHI_GUID;

ioctl(fd, IOCTL_MEI_CONNECT_CLIENT, &data);

printf("Ver=%d, MaxLen=%ld\n",
       data.d.in_client_uuid.protocol_version,
       data.d.in_client_uuid.max_msg_length);

[...]

write(fd, amthi_req_data, amthi_req_data_len);

[...]

read(fd, &amthi_res_data, amthi_res_data_len);

[...]
close(fd);
```

User space API

<a id="rst-ioctls"></a>

## IOCTLs:

The Intel MEI Driver supports the following IOCTL commands:

<a id="rst-ioctl-mei-connect-client"></a>

### IOCTL_MEI_CONNECT_CLIENT

Connect to firmware Feature/Client.



```none
Usage:

struct mei_connect_client_data client_data;

ioctl(fd, IOCTL_MEI_CONNECT_CLIENT, &client_data);

Inputs:

struct mei_connect_client_data - contain the following
Input field:

        in_client_uuid -        GUID of the FW Feature that needs
                                to connect to.
 Outputs:
        out_client_properties - Client Properties: MTU and Protocol Version.

 Error returns:

        ENOTTY  No such client (i.e. wrong GUID) or connection is not allowed.
        EINVAL  Wrong IOCTL Number
        ENODEV  Device or Connection is not initialized or ready.
        ENOMEM  Unable to allocate memory to client internal data.
        EFAULT  Fatal Error (e.g. Unable to access user input data)
        EBUSY   Connection Already Open
```

**Note:** max_msg_length (MTU) in client properties describes the maximum data that can be sent or received. (e.g. if MTU=2K, can send requests up to bytes 2k and received responses up to 2k bytes).

<a id="rst-ioctl-mei-connect-client-vtag"></a>

### IOCTL_MEI_CONNECT_CLIENT_VTAG:



```none
Usage:

struct mei_connect_client_data_vtag client_data_vtag;

ioctl(fd, IOCTL_MEI_CONNECT_CLIENT_VTAG, &client_data_vtag);

Inputs:

struct mei_connect_client_data_vtag - contain the following
Input field:

        in_client_uuid -  GUID of the FW Feature that needs
                          to connect to.
        vtag - virtual tag [1, 255]

 Outputs:
        out_client_properties - Client Properties: MTU and Protocol Version.

 Error returns:

        ENOTTY No such client (i.e. wrong GUID) or connection is not allowed.
        EINVAL Wrong IOCTL Number or tag == 0
        ENODEV Device or Connection is not initialized or ready.
        ENOMEM Unable to allocate memory to client internal data.
        EFAULT Fatal Error (e.g. Unable to access user input data)
        EBUSY  Connection Already Open
        EOPNOTSUPP Vtag is not supported
```

<a id="rst-ioctl-mei-notify-set"></a>

### IOCTL_MEI_NOTIFY_SET

Enable or disable event notifications.



```none
Usage:

        uint32_t enable;

        ioctl(fd, IOCTL_MEI_NOTIFY_SET, &enable);


        uint32_t enable = 1;
        or
        uint32_t enable[disable] = 0;

Error returns:


        EINVAL  Wrong IOCTL Number
        ENODEV  Device  is not initialized or the client not connected
        ENOMEM  Unable to allocate memory to client internal data.
        EFAULT  Fatal Error (e.g. Unable to access user input data)
        EOPNOTSUPP if the device doesn't support the feature
```

**Note:** The client must be connected in order to enable notification events

<a id="rst-ioctl-mei-notify-get"></a>

### IOCTL_MEI_NOTIFY_GET

Retrieve event



```none
Usage:
        uint32_t event;
        ioctl(fd, IOCTL_MEI_NOTIFY_GET, &event);

Outputs:
        1 - if an event is pending
        0 - if there is no even pending

Error returns:
        EINVAL  Wrong IOCTL Number
        ENODEV  Device is not initialized or the client not connected
        ENOMEM  Unable to allocate memory to client internal data.
        EFAULT  Fatal Error (e.g. Unable to access user input data)
        EOPNOTSUPP if the device doesn't support the feature
```

**Note:** The client must be connected and event notification has to be enabled in order to receive an event

<a id="rst-supported-chipsets"></a>

## Supported Chipsets

82X38/X48 Express and newer

[linux-mei@linux.intel.com](<mailto:linux-mei@linux.intel.com>)

---

# MEI NFC

_Peios Kernel / Hardware and drivers / Driver development / Management Engine Interface_

> Some Intel 8 and 9 Series chipsets support NFC devices connected behind the Intel Management Engine controller. MEI client bus exposes the NFC chips as NFC phy devices and enables binding with Microread and NXP PN544 NFC device driver from…

<a id="rst-mei-nfc"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Some Intel 8 and 9 Series chipsets support NFC devices connected behind the Intel Management Engine controller. MEI client bus exposes the NFC chips as NFC phy devices and enables binding with Microread and NXP PN544 NFC device driver from the Linux NFC subsystem.

```mermaid
flowchart TB
  n0(["mei/bus(nfc)"])
  n1(["me fw (nfc)"])
  n2(["drivers/nfc/mei_phy"])
  n3(["drivers/nfc/microread/mei"])
  n4(["drivers/nfc/pn544/mei"])
  n5(["net/nfc"])
  n6(["neard"])
  n0 --> n1
  n2 --> n0
  n3 --> n0
  n3 --> n2
  n4 --> n0
  n4 --> n2
  n5 --> n3
  n5 --> n4
  n6 --> n5
```

<strong>MEI NFC</strong> Stack

---

# Memory Controller drivers

_Peios Kernel / Hardware and drivers / Driver development / Memory devices_

> Reference for Memory Controller drivers.

<a id="rst-memory-controller-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [TI EMIF SDRAM Controller Driver](</kernel/hardware/driver-api/memory-devices/ti-emif.md>)
- [GPMC (General Purpose Memory Controller)](</kernel/hardware/driver-api/memory-devices/ti-gpmc.md>)

---

# TI EMIF SDRAM Controller Driver

_Peios Kernel / Hardware and drivers / Driver development / Memory devices_

> Aneesh V <aneesh@ti.com>

<a id="rst-ti-emif-sdram-controller-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-author"></a>

## Author

Aneesh V &lt;[aneesh@ti.com](<mailto:aneesh@ti.com>)&gt;

<a id="rst-location"></a>

## Location

driver/memory/emif.c

<a id="rst-supported-socs"></a>

## Supported SoCs:

TI OMAP44xx TI OMAP54xx

<a id="rst-menuconfig-option"></a>

## Menuconfig option:

- **Device Drivers**

  - **Memory devices**

    Texas Instruments EMIF driver

<a id="rst-description"></a>

## Description

This driver is for the EMIF module available in Texas Instruments SoCs. EMIF is an SDRAM controller that, based on its revision, supports one or more of DDR2, DDR3, and LPDDR2 SDRAM protocols. This driver takes care of only LPDDR2 memories presently. The functions of the driver includes re-configuring AC timing parameters and other settings during frequency, voltage and temperature changes

<a id="rst-platform-data-see-include-linux-platform-data-emif-plat-h"></a>

## Platform Data (see include/linux/platform_data/emif_plat.h)

DDR device details and other board dependent and SoC dependent information can be passed through platform data (struct emif_platform_data)

- DDR device details: 'struct ddr_device_info'

- Device AC timings: 'struct lpddr2_timings' and 'struct lpddr2_min_tck'

- Custom configurations: customizable policy options through 'struct emif_custom_configs'

- IP revision

- PHY type

<a id="rst-interface-to-the-external-world"></a>

## Interface to the external world

EMIF driver registers notifiers for voltage and frequency changes affecting EMIF and takes appropriate actions when these are invoked.

- freq_pre_notify_handling()

- freq_post_notify_handling()

- volt_notify_handling()

<a id="rst-debugfs"></a>

## Debugfs

The driver creates two debugfs entries per device.

- regcache_dump : dump of register values calculated and saved for all frequencies used so far.

- mr4 : last polled value of MR4 register in the LPDDR2 device. MR4 indicates the current temperature level of the device.

---

# GPMC (General Purpose Memory Controller)

_Peios Kernel / Hardware and drivers / Driver development / Memory devices_

> GPMC is an unified memory controller dedicated to interfacing external memory devices like

<a id="rst-gpmc-general-purpose-memory-controller"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

GPMC is an unified memory controller dedicated to interfacing external memory devices like

> - Asynchronous SRAM like memories and application specific integrated circuit devices.
>
> - Asynchronous, synchronous, and page mode burst NOR flash devices NAND flash
>
> - Pseudo-SRAM devices

GPMC is found on Texas Instruments SoC's (OMAP based) IP details: [https://www.ti.com/lit/pdf/spruh73](<https://www.ti.com/lit/pdf/spruh73>) section 7.1

<a id="rst-gpmc-generic-timing-calculation"></a>

## GPMC generic timing calculation:

GPMC has certain timings that has to be programmed for proper functioning of the peripheral, while peripheral has another set of timings. To have peripheral work with gpmc, peripheral timings has to be translated to the form gpmc can understand. The way it has to be translated depends on the connected peripheral. Also there is a dependency for certain gpmc timings on gpmc clock frequency. Hence a generic timing routine was developed to achieve above requirements.

Generic routine provides a generic method to calculate gpmc timings from gpmc peripheral timings. struct gpmc_device_timings fields has to be updated with timings from the datasheet of the peripheral that is connected to gpmc. A few of the peripheral timings can be fed either in time or in cycles, provision to handle this scenario has been provided (refer struct gpmc_device_timings definition). It may so happen that timing as specified by peripheral datasheet is not present in timing structure, in this scenario, try to correlate peripheral timing to the one available. If that doesn't work, try to add a new field as required by peripheral, educate generic timing routine to handle it, make sure that it does not break any of the existing. Then there may be cases where peripheral datasheet doesn't mention certain fields of struct gpmc_device_timings, zero those entries.

Generic timing routine has been verified to work properly on multiple onenand's and tusb6010 peripherals.

A word of caution: generic timing routine has been developed based on understanding of gpmc timings, peripheral timings, available custom timing routines, a kind of reverse engineering without most of the datasheets &amp; hardware (to be exact none of those supported in mainline having custom timing routine) and by simulation.

gpmc timing dependency on peripheral timings:

\[&lt;gpmc_timing&gt;: &lt;peripheral timing1&gt;, &lt;peripheral timing2&gt; ...\]

1. common

- **cs_on:**

  t_ceasu

- **adv_on:**

  t_avdasu, t_ceavd

2. sync common

- **sync_clk:**

  clk

- **page_burst_access:**

  t_bacc

- **clk_activation:**

  t_ces, t_avds

3. read async muxed

- **adv_rd_off:**

  t_avdp_r

- **oe_on:**

  t_oeasu, t_aavdh

- **access:**

  t_iaa, t_oe, t_ce, t_aa

- **rd_cycle:**

  t_rd_cycle, t_cez_r, t_oez

4. read async non-muxed

- **adv_rd_off:**

  t_avdp_r

- **oe_on:**

  t_oeasu

- **access:**

  t_iaa, t_oe, t_ce, t_aa

- **rd_cycle:**

  t_rd_cycle, t_cez_r, t_oez

5. read sync muxed

- **adv_rd_off:**

  t_avdp_r, t_avdh

- **oe_on:**

  t_oeasu, t_ach, cyc_aavdh_oe

- **access:**

  t_iaa, cyc_iaa, cyc_oe

- **rd_cycle:**

  t_cez_r, t_oez, t_ce_rdyz

6. read sync non-muxed

- **adv_rd_off:**

  t_avdp_r

- **oe_on:**

  t_oeasu

- **access:**

  t_iaa, cyc_iaa, cyc_oe

- **rd_cycle:**

  t_cez_r, t_oez, t_ce_rdyz

7. write async muxed

- **adv_wr_off:**

  t_avdp_w

- **we_on, wr_data_mux_bus:**

  t_weasu, t_aavdh, cyc_aavhd_we

- **we_off:**

  t_wpl

- **cs_wr_off:**

  t_wph

- **wr_cycle:**

  t_cez_w, t_wr_cycle

8. write async non-muxed

- **adv_wr_off:**

  t_avdp_w

- **we_on, wr_data_mux_bus:**

  t_weasu

- **we_off:**

  t_wpl

- **cs_wr_off:**

  t_wph

- **wr_cycle:**

  t_cez_w, t_wr_cycle

9. write sync muxed

- **adv_wr_off:**

  t_avdp_w, t_avdh

- **we_on, wr_data_mux_bus:**

  t_weasu, t_rdyo, t_aavdh, cyc_aavhd_we

- **we_off:**

  t_wpl, cyc_wpl

- **cs_wr_off:**

  t_wph

- **wr_cycle:**

  t_cez_w, t_ce_rdyz

10. write sync non-muxed

- **adv_wr_off:**

  t_avdp_w

- **we_on, wr_data_mux_bus:**

  t_weasu, t_rdyo

- **we_off:**

  t_wpl, cyc_wpl

- **cs_wr_off:**

  t_wph

- **wr_cycle:**

  t_cez_w, t_ce_rdyz

- **Note:**

  Many of gpmc timings are dependent on other gpmc timings (a few gpmc timings purely dependent on other gpmc timings, a reason that some of the gpmc timings are missing above), and it will result in indirect dependency of peripheral timings to gpmc timings other than mentioned above, refer timing routine for more details. To know what these peripheral timings correspond to, please see explanations in struct gpmc_device_timings definition. And for gpmc timings refer IP details (link above).

---

# MMC/SD/SDIO card support

_Peios Kernel / Hardware and drivers / Driver development / MMC and SD_

> Reference for MMC/SD/SDIO card support.

<a id="rst-mmc-sd-sdio-card-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [SD and MMC Block Device Attributes](</kernel/hardware/driver-api/mmc/mmc-dev-attrs.md>)
- [SD and MMC Device Partitions](</kernel/hardware/driver-api/mmc/mmc-dev-parts.md>)
- [MMC Asynchronous Request](</kernel/hardware/driver-api/mmc/mmc-async-req.md>)
- [MMC Test Framework](</kernel/hardware/driver-api/mmc/mmc-test.md>)
- [MMC tools introduction](</kernel/hardware/driver-api/mmc/mmc-tools.md>)

---

# MMC Asynchronous Request

_Peios Kernel / Hardware and drivers / Driver development / MMC and SD_

> How significant is the cache maintenance overhead?

<a id="rst-mmc-asynchronous-request"></a>

<a id="rst-rationale"></a>

## Rationale

How significant is the cache maintenance overhead?

It depends. Fast eMMC and multiple cache levels with speculative cache pre-fetch makes the cache overhead relatively significant. If the DMA preparations for the next request are done in parallel with the current transfer, the DMA preparation overhead would not affect the MMC performance.

The intention of non-blocking (asynchronous) MMC requests is to minimize the time between when an MMC request ends and another MMC request begins.

Using mmc_wait_for_req(), the MMC controller is idle while dma_map_sg and dma_unmap_sg are processing. Using non-blocking MMC requests makes it possible to prepare the caches for next job in parallel with an active MMC request.

<a id="rst-mmc-block-driver"></a>

## MMC block driver

The mmc_blk_issue_rw_rq() in the MMC block driver is made non-blocking.

The increase in throughput is proportional to the time it takes to prepare (major part of preparations are dma_map_sg() and dma_unmap_sg()) a request and how fast the memory is. The faster the MMC/SD is the more significant the prepare request time becomes. Roughly the expected performance gain is 5% for large writes and 10% on large reads on a L2 cache platform. In power save mode, when clocks run on a lower frequency, the DMA preparation may cost even more. As long as these slower preparations are run in parallel with the transfer performance won't be affected.

<a id="rst-details-on-measurements-from-iozone-and-mmc-test"></a>

## Details on measurements from IOZone and mmc_test

[https://wiki.linaro.org/WorkingGroups/Kernel/Specs/StoragePerfMMC-async-req](<https://wiki.linaro.org/WorkingGroups/Kernel/Specs/StoragePerfMMC-async-req>)

<a id="rst-mmc-core-api-extension"></a>

## MMC core API extension

There is one new public function mmc_start_req().

It starts a new MMC command request for a host. The function isn't truly non-blocking. If there is an ongoing async request it waits for completion of that request and starts the new one and returns. It doesn't wait for the new request to complete. If there is no ongoing request it starts the new request and returns immediately.

<a id="rst-mmc-host-extensions"></a>

## MMC host extensions

There are two optional members in the mmc_host_ops -- pre_req() and post_req() -- that the host driver may implement in order to move work to before and after the actual mmc_host_ops.request() function is called.

In the DMA case pre_req() may do dma_map_sg() and prepare the DMA descriptor, and post_req() runs the dma_unmap_sg().

<a id="rst-optimize-for-the-first-request"></a>

## Optimize for the first request

The first request in a series of requests can't be prepared in parallel with the previous transfer, since there is no previous request.

The argument is_first_req in pre_req() indicates that there is no previous request. The host driver may optimize for this scenario to minimize the performance loss. A way to optimize for this is to split the current request in two chunks, prepare the first chunk and start the request, and finally prepare the second chunk and start the transfer.

Pseudocode to handle is_first_req scenario with minimal prepare overhead:



```text
if (is_first_req && req->size > threshold)
   /* start MMC transfer for the complete transfer size */
   mmc_start_command(MMC_CMD_TRANSFER_FULL_SIZE);

   /*
    * Begin to prepare DMA while cmd is being processed by MMC.
    * The first chunk of the request should take the same time
    * to prepare as the "MMC process command time".
    * If prepare time exceeds MMC cmd time
    * the transfer is delayed, guesstimate max 4k as first chunk size.
    */
    prepare_1st_chunk_for_dma(req);
    /* flush pending desc to the DMAC (dmaengine.h) */
    dma_issue_pending(req->dma_desc);

    prepare_2nd_chunk_for_dma(req);
    /*
     * The second issue_pending should be called before MMC runs out
     * of the first chunk. If the MMC runs out of the first data chunk
     * before this call, the transfer is delayed.
     */
    dma_issue_pending(req->dma_desc);
```

---

# SD and MMC Block Device Attributes

_Peios Kernel / Hardware and drivers / Driver development / MMC and SD_

> These attributes are defined for the block devices associated with the SD or MMC device.

<a id="rst-sd-and-mmc-block-device-attributes"></a>

These attributes are defined for the block devices associated with the SD or MMC device.

The following attributes are read/write.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> force_ro
>
> </td>
> <td>
>
>
> Enforce read-only access even if write protect                                  switch is off.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-sd-and-mmc-device-attributes"></a>

## SD and MMC Device Attributes

All attributes are read-only.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> cid
>
> </td>
> <td>
>
>
> Card Identification Register
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> csd
>
> </td>
> <td>
>
>
> Card Specific Data Register
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> scr
>
> </td>
> <td>
>
>
> SD Card Configuration Register (SD only)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> date
>
> </td>
> <td>
>
>
> Manufacturing Date (from CID Register)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> fwrev
>
> </td>
> <td>
>
>
> Firmware/Product Revision (from CID Register) (SD and MMCv1 only)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> hwrev
>
> </td>
> <td>
>
>
> Hardware/Product Revision (from CID Register) (SD and MMCv1 only)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> manfid
>
> </td>
> <td>
>
>
> Manufacturer ID (from CID Register)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> name
>
> </td>
> <td>
>
>
> Product Name (from CID Register)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> oemid
>
> </td>
> <td>
>
>
> OEM/Application ID (from CID Register)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> prv
>
> </td>
> <td>
>
>
> Product Revision (from CID Register) (SD and MMCv4 only)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> serial
>
> </td>
> <td>
>
>
> Product Serial Number (from CID Register)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> erase_size
>
> </td>
> <td>
>
>
> Erase group size
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> preferred_erase_size
>
> </td>
> <td>
>
>
> Preferred erase size
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> raw_rpmb_size_mult
>
> </td>
> <td>
>
>
> RPMB partition size
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> rel_sectors
>
> </td>
> <td>
>
>
> Reliable write sector count
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ocr
>
> </td>
> <td>
>
>
> Operation Conditions Register
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dsr
>
> </td>
> <td>
>
>
> Driver Stage Register
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> cmdq_en
>
> </td>
> <td>
>
>
> Command Queue enabled:
>
> > 1 =&gt; enabled, 0 =&gt; not enabled
>
> </td>
> </tr>
> </tbody>
> </table>

Note on Erase Size and Preferred Erase Size:

> "erase_size" is the  minimum size, in bytes, of an erase operation.  For MMC, "erase_size" is the erase group size reported by the card.  Note that "erase_size" does not apply to trim or secure trim operations where the minimum size is always one 512 byte sector.  For SD, "erase_size" is 512 if the card is block-addressed, 0 otherwise.
>
> SD/MMC cards can erase an arbitrarily large area up to and including the whole card.  When erasing a large area it may be desirable to do it in smaller chunks for three reasons:
>
> > 1. A single erase command will make all other I/O on the card wait.  This is not a problem if the whole card is being erased, but erasing one partition will make I/O for another partition on the same card wait for the duration of the erase - which could be a several minutes.
> >
> > 2. To be able to inform the user of erase progress.
> >
> > 3. The erase timeout becomes too large to be very useful.  Because the erase timeout contains a margin which is multiplied by the size of the erase area, the value can end up being several minutes for large areas.
>
> "erase_size" is not the most efficient unit to erase (especially for SD where it is just one sector), hence "preferred_erase_size" provides a good chunk size for erasing large areas.
>
> For MMC, "preferred_erase_size" is the high-capacity erase size if a card specifies one, otherwise it is based on the capacity of the card.
>
> For SD, "preferred_erase_size" is the allocation unit size specified by the card.
>
> "preferred_erase_size" is in bytes.

Note on raw_rpmb_size_mult:

> "raw_rpmb_size_mult" is a multiple of 128kB block.
>
> RPMB size in byte is calculated by using the following equation:
>
> > RPMB partition size = 128kB x raw_rpmb_size_mult

---

# SD and MMC Device Partitions

_Peios Kernel / Hardware and drivers / Driver development / MMC and SD_

> Device partitions are additional logical block devices present on the SD/MMC device.

<a id="rst-sd-and-mmc-device-partitions"></a>

Device partitions are additional logical block devices present on the SD/MMC device.

As of this writing, MMC boot partitions as supported and exposed as /dev/mmcblkXboot0 and /dev/mmcblkXboot1, where X is the index of the parent /dev/mmcblkX.

<a id="rst-mmc-boot-partitions"></a>

## MMC Boot Partitions

Read and write access is provided to the two MMC boot partitions. Due to the sensitive nature of the boot partition contents, which often store a bootloader or bootloader configuration tables crucial to booting the platform, write access is disabled by default to reduce the chance of accidental bricking.

To enable write access to /dev/mmcblkXbootY, disable the forced read-only access with:



```text
echo 0 > /sys/block/mmcblkXbootY/force_ro
```

To re-enable read-only access:



```text
echo 1 > /sys/block/mmcblkXbootY/force_ro
```

The boot partitions can also be locked read only until the next power on, with:



```text
echo 1 > /sys/block/mmcblkXbootY/ro_lock_until_next_power_on
```

This is a feature of the card and not of the kernel. If the card does not support boot partition locking, the file will not exist. If the feature has been disabled on the card, the file will be read-only.

The boot partitions can also be locked permanently, but this feature is not accessible through sysfs in order to avoid accidental or malicious bricking.

---

# MMC Test Framework

_Peios Kernel / Hardware and drivers / Driver development / MMC and SD_

> The mmc_test framework is designed to test the performance and reliability of host controller drivers and all devices handled by the MMC subsystem. This includes not only MMC devices but also SD cards and other devices supported by the…

<a id="rst-mmc-test-framework"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

The `mmc_test` framework is designed to test the performance and reliability of host controller drivers and all devices handled by the MMC subsystem. This includes not only MMC devices but also SD cards and other devices supported by the subsystem.

The framework provides a variety of tests to evaluate different aspects of the host controller and device interactions, such as read and write performance, data integrity, and error handling. These tests help ensure that the host controller drivers and devices operate correctly under various conditions.

The `mmc_test` framework is particularly useful for:

- Verifying the functionality and performance of MMC and SD host controller drivers.

- Ensuring compatibility and reliability of MMC and SD devices.

- Identifying and diagnosing issues in the MMC subsystem.

The results of the tests are logged in the kernel log, providing detailed information about the test outcomes and any encountered issues.

Note: whatever is on your card will be overwritten by these tests.

<a id="rst-initialization"></a>

## Initialization

To use the `mmc_test` framework, follow these steps:

1. **Enable the MMC Test Framework**:

   Ensure that the `CONFIG_MMC_TEST` kernel configuration option is enabled. This can be done by configuring the kernel:



   ```none
   make menuconfig
   ```

   Navigate to:

   - **Device Drivers  ---&gt;**

     - **&lt;\*&gt; MMC/SD/SDIO card support  ---&gt;**

       \[\*\]   MMC host test driver

   Alternatively, you can enable it directly in the kernel configuration file:



   ```none
   echo "CONFIG_MMC_TEST=y" >> .config
   ```

   Rebuild and install the kernel if necessary.

2. **Load the MMC Test Module**:

   If the `mmc_test` framework is built as a module, you need to load it using `modprobe`:



   ```none
   modprobe mmc_test
   ```

<a id="rst-binding-the-mmc-card-for-testing"></a>

## Binding the MMC Card for Testing

To enable MMC testing, you need to unbind the MMC card from the `mmcblk` driver and bind it to the `mmc_test` driver. This allows the `mmc_test` framework to take control of the MMC card for testing purposes.

1. Identify the MMC card:



   ```sh
   ls /sys/bus/mmc/devices/
   ```

   This will list the MMC devices, such as `mmc0:0001`.

2. Unbind the MMC card from the `mmcblk` driver:



   ```sh
   echo 'mmc0:0001' > /sys/bus/mmc/drivers/mmcblk/unbind
   ```

3. Bind the MMC card to the `mmc_test` driver:



   ```sh
   echo 'mmc0:0001' > /sys/bus/mmc/drivers/mmc_test/bind
   ```

After binding, you should see a line in the kernel log indicating that the card has been claimed for testing:



```none
mmc_test mmc0:0001: Card claimed for testing.
```

<a id="rst-usage-debugfs-entries"></a>

## Usage - Debugfs Entries

Once the `mmc_test` framework is enabled, you can interact with the following debugfs entries located in `/sys/kernel/debug/mmc0/mmc0:0001`:

1. **test**:

   This file is used to run specific tests. Write the test number to this file to execute a test.



   ```sh
   echo <test_number> > /sys/kernel/debug/mmc0/mmc0:0001/test
   ```

   The test result is indicated in the kernel log info. You can view the kernel log using the `dmesg` command or by checking the log file in `/var/log/`.



   ```sh
   dmesg | grep mmc0
   ```

   Example:

   To run test number 4 (Basic read with data verification):



   ```sh
   echo 4 > /sys/kernel/debug/mmc0/mmc0:0001/test
   ```

   Check the kernel log for the result:



   ```sh
   dmesg | grep mmc0
   ```

2. **testlist**:

   This file lists all available tests. You can read this file to see the list of tests and their corresponding numbers.



   ```sh
   cat /sys/kernel/debug/mmc0/mmc0:0001/testlist
   ```

   The available tests are listed in the table below:


<table>
<thead>
<tr>
<th>


Test

</th>
<th>


Test Name

</th>
<th>


Test Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


Run all tests

</td>
<td>


Runs all available tests

</td>
</tr>
<tr>
<td>


1

</td>
<td>


Basic write

</td>
<td>


Performs a basic write operation of a single 512-Byte block to the MMC card without data verification.

</td>
</tr>
<tr>
<td>


2

</td>
<td>


Basic read

</td>
<td>


Same for read

</td>
</tr>
<tr>
<td>


3

</td>
<td>


Basic write (with data verification)

</td>
<td>


Performs a basic write operation of a single 512-Byte block to the MMC card with data verification by reading back the written data and comparing it.

</td>
</tr>
<tr>
<td>


4

</td>
<td>


Basic read (with data verification)

</td>
<td>


Same for read

</td>
</tr>
<tr>
<td>


5

</td>
<td>


Multi-block write

</td>
<td>


Performs a multi-block write operation of 8 blocks (each 512 bytes) to the MMC card.

</td>
</tr>
<tr>
<td>


6

</td>
<td>


Multi-block read

</td>
<td>


Same for read

</td>
</tr>
<tr>
<td>


7

</td>
<td>


Power of two block writes

</td>
<td>


Performs write operations with block sizes that are powers of two, starting from 1 byte up to 256 bytes, to the MMC card.

</td>
</tr>
<tr>
<td>


8

</td>
<td>


Power of two block reads

</td>
<td>


Same for read

</td>
</tr>
<tr>
<td>


9

</td>
<td>


Weird sized block writes

</td>
<td>


Performs write operations with varying block sizes starting from 3 bytes and increasing by 7 bytes each iteration, up to 511 bytes, to the MMC card.

</td>
</tr>
<tr>
<td>


10

</td>
<td>


Weird sized block reads

</td>
<td>


same for read

</td>
</tr>
<tr>
<td>


11

</td>
<td>


Badly aligned write

</td>
<td>


Performs write operations with buffers starting at different alignments (0 to 7 bytes offset) to test how the MMC card handles unaligned data transfers.

</td>
</tr>
<tr>
<td>


12

</td>
<td>


Badly aligned read

</td>
<td>


same for read

</td>
</tr>
<tr>
<td>


13

</td>
<td>


Badly aligned multi-block write

</td>
<td>


same for multi-write

</td>
</tr>
<tr>
<td>


14

</td>
<td>


Badly aligned multi-block read

</td>
<td>


same for multi-read

</td>
</tr>
<tr>
<td>


15

</td>
<td>


Proper xfer_size at write (Start failure)

</td>
<td>


intentionally create a broken transfer by modifying the MMC request in a way that it will not perform as expected, e.g. use MMC_WRITE_BLOCK  for a multi-block transfer

</td>
</tr>
<tr>
<td>


16

</td>
<td>


Proper xfer_size at read (Start failure)

</td>
<td>


same for read

</td>
</tr>
<tr>
<td>


17

</td>
<td>


Proper xfer_size at write (Midway failure)

</td>
<td>


same for 2 blocks

</td>
</tr>
<tr>
<td>


18

</td>
<td>


Proper xfer_size at read (Midway failure)

</td>
<td>


same for read

</td>
</tr>
<tr>
<td>


19

</td>
<td>


Highmem write

</td>
<td>


use a high memory page

</td>
</tr>
<tr>
<td>


20

</td>
<td>


Highmem read

</td>
<td>


same for read

</td>
</tr>
<tr>
<td>


21

</td>
<td>


Multi-block highmem write

</td>
<td>


same for multi-write

</td>
</tr>
<tr>
<td>


22

</td>
<td>


Multi-block highmem read

</td>
<td>


same for mult-read

</td>
</tr>
<tr>
<td>


23

</td>
<td>


Best-case read performance

</td>
<td>


Performs 512K sequential read (non sg)

</td>
</tr>
<tr>
<td>


24

</td>
<td>


Best-case write performance

</td>
<td>


same for write

</td>
</tr>
<tr>
<td>


25

</td>
<td>


Best-case read performance (Into scattered pages)

</td>
<td>


Same using sg

</td>
</tr>
<tr>
<td>


26

</td>
<td>


Best-case write performance (From scattered pages)

</td>
<td>


same for write

</td>
</tr>
<tr>
<td>


27

</td>
<td>


Single read performance

</td>
<td>


By transfer size

</td>
</tr>
<tr>
<td>


28

</td>
<td>


Single write performance

</td>
<td>


By transfer size

</td>
</tr>
<tr>
<td>


29

</td>
<td>


Single trim performance

</td>
<td>


By transfer size

</td>
</tr>
<tr>
<td>


30

</td>
<td>


Consecutive read performance

</td>
<td>


By transfer size

</td>
</tr>
<tr>
<td>


31

</td>
<td>


Consecutive write performance

</td>
<td>


By transfer size

</td>
</tr>
<tr>
<td>


32

</td>
<td>


Consecutive trim performance

</td>
<td>


By transfer size

</td>
</tr>
<tr>
<td>


33

</td>
<td>


Random read performance

</td>
<td>


By transfer size

</td>
</tr>
<tr>
<td>


34

</td>
<td>


Random write performance

</td>
<td>


By transfer size

</td>
</tr>
<tr>
<td>


35

</td>
<td>


Large sequential read

</td>
<td>


Into scattered pages

</td>
</tr>
<tr>
<td>


36

</td>
<td>


Large sequential write

</td>
<td>


From scattered pages

</td>
</tr>
<tr>
<td>


37

</td>
<td>


Write performance

</td>
<td>


With blocking req 4k to 4MB

</td>
</tr>
<tr>
<td>


38

</td>
<td>


Write performance

</td>
<td>


With non-blocking req 4k to 4MB

</td>
</tr>
<tr>
<td>


39

</td>
<td>


Read performance

</td>
<td>


With blocking req 4k to 4MB

</td>
</tr>
<tr>
<td>


40

</td>
<td>


Read performance

</td>
<td>


With non-blocking req 4k to 4MB

</td>
</tr>
<tr>
<td>


41

</td>
<td>


Write performance

</td>
<td>


Blocking req 1 to 512 sg elems

</td>
</tr>
<tr>
<td>


42

</td>
<td>


Write performance

</td>
<td>


Non-blocking req 1 to 512 sg elems

</td>
</tr>
<tr>
<td>


43

</td>
<td>


Read performance

</td>
<td>


Blocking req 1 to 512 sg elems

</td>
</tr>
<tr>
<td>


44

</td>
<td>


Read performance

</td>
<td>


Non-blocking req 1 to 512 sg elems

</td>
</tr>
<tr>
<td>


45

</td>
<td>


Reset test

</td>
<td>




</td>
</tr>
<tr>
<td>


46

</td>
<td>


Commands during read

</td>
<td>


No Set Block Count (CMD23)

</td>
</tr>
<tr>
<td>


47

</td>
<td>


Commands during write

</td>
<td>


No Set Block Count (CMD23)

</td>
</tr>
<tr>
<td>


48

</td>
<td>


Commands during read

</td>
<td>


Use Set Block Count (CMD23)

</td>
</tr>
<tr>
<td>


49

</td>
<td>


Commands during write

</td>
<td>


Use Set Block Count (CMD23)

</td>
</tr>
<tr>
<td>


50

</td>
<td>


Commands during non-blocking

</td>
<td>


Read - use Set Block Count (CMD23)

</td>
</tr>
<tr>
<td>


51

</td>
<td>


Commands during non-blocking

</td>
<td>


Write - use Set Block Count (CMD23)

</td>
</tr>
</tbody>
</table>

<a id="rst-test-results"></a>

## Test Results

The results of the tests are logged in the kernel log. Each test logs the start, end, and result of the test. The possible results are:

- **OK**: The test completed successfully.

- **FAILED**: The test failed.

- **UNSUPPORTED (by host)**: The test is unsupported by the host.

- **UNSUPPORTED (by card)**: The test is unsupported by the card.

- **ERROR**: An error occurred during the test.

<a id="rst-example-kernel-log-output"></a>

## Example Kernel Log Output

When running a test, you will see log entries similar to the following in the kernel log:



```none
[ 1234.567890] mmc0: Starting tests of card mmc0:0001...
[ 1234.567891] mmc0: Test case 4. Basic read (with data verification)...
[ 1234.567892] mmc0: Result: OK
[ 1234.567893] mmc0: Tests completed.
```

In this example, test case 4 (Basic read with data verification) was executed, and the result was OK.

<a id="rst-contributing"></a>

## Contributing

Contributions to the `mmc_test` framework are welcome. Please follow the standard Linux kernel contribution guidelines and submit patches to the appropriate maintainers.

<a id="rst-contact"></a>

## Contact

For more information or to report issues, please contact the MMC subsystem maintainers.

---

# MMC tools introduction

_Peios Kernel / Hardware and drivers / Driver development / MMC and SD_

> There is one MMC test tools called mmc-utils, which is maintained by Ulf Hansson, you can find it at the below public git repository:

<a id="rst-mmc-tools-introduction"></a>

There is one MMC test tools called mmc-utils, which is maintained by Ulf Hansson, you can find it at the below public git repository:

> [https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git](<https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git>)

<a id="rst-functions"></a>

## Functions

The mmc-utils tools can do the following:

> - Print and parse extcsd data.
>
> - Determine the eMMC writeprotect status.
>
> - Set the eMMC writeprotect status.
>
> - Set the eMMC data sector size to 4KB by disabling emulation.
>
> - Create general purpose partition.
>
> - Enable the enhanced user area.
>
> - Enable write reliability per partition.
>
> - Print the response to STATUS_SEND (CMD13).
>
> - Enable the boot partition.
>
> - Set Boot Bus Conditions.
>
> - Enable the eMMC BKOPS feature.
>
> - Permanently enable the eMMC H/W Reset feature.
>
> - Permanently disable the eMMC H/W Reset feature.
>
> - Send Sanitize command.
>
> - Program authentication key for the device.
>
> - Counter value for the rpmb device will be read to stdout.
>
> - Read from rpmb device to output.
>
> - Write to rpmb device from data file.
>
> - Enable the eMMC cache feature.
>
> - Disable the eMMC cache feature.
>
> - Print and parse CID data.
>
> - Print and parse CSD data.
>
> - Print and parse SCR data.

---

# Memory Technology Device (MTD)

_Peios Kernel / Hardware and drivers / Driver development / Flash memory (MTD)_

> Reference for Memory Technology Device (MTD).

<a id="rst-memory-technology-device-mtd"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Upgrading BIOS using spi-intel](</kernel/hardware/driver-api/mtd/spi-intel.md>)
- [NAND Error-correction Code](</kernel/hardware/driver-api/mtd/nand-ecc.md>)
- [SPI NOR framework](</kernel/hardware/driver-api/mtd/spi-nor.md>)

---

# NAND Error-correction Code

_Peios Kernel / Hardware and drivers / Driver development / Flash memory (MTD)_

> Having looked at the linux mtd/nand Hamming software ECC engine driver I felt there was room for optimisation. I bashed the code for a few hours performing tricks like table lookup removing superfluous code etc. After that the speed was…

<a id="rst-nand-error-correction-code"></a>

<a id="rst-introduction"></a>

## Introduction

Having looked at the linux mtd/nand Hamming software ECC engine driver I felt there was room for optimisation. I bashed the code for a few hours performing tricks like table lookup removing superfluous code etc. After that the speed was increased by 35-40%. Still I was not too happy as I felt there was additional room for improvement.

Bad\! I was hooked. I decided to annotate my steps in this file. Perhaps it is useful to someone or someone learns something from it.

<a id="rst-the-problem"></a>

## The problem

NAND flash (at least SLC one) typically has sectors of 256 bytes. However NAND flash is not extremely reliable so some error detection (and sometimes correction) is needed.

This is done by means of a Hamming code. I'll try to explain it in laymans terms (and apologies to all the pro's in the field in case I do not use the right terminology, my coding theory class was almost 30 years ago, and I must admit it was not one of my favourites).

As I said before the ecc calculation is performed on sectors of 256 bytes. This is done by calculating several parity bits over the rows and columns. The parity used is even parity which means that the parity bit = 1 if the data over which the parity is calculated is 1 and the parity bit = 0 if the data over which the parity is calculated is 0. So the total number of bits over the data over which the parity is calculated + the parity bit is even. (see wikipedia if you can't follow this). Parity is often calculated by means of an exclusive or operation, sometimes also referred to as xor. In C the operator for xor is ^

Back to ecc. Let's give a small figure:


<table>
<tbody>
<tr>
<td>


byte   0:

</td>
<td>


bit7

</td>
<td>


bit6

</td>
<td>


bit5

</td>
<td>


bit4

</td>
<td>


bit3

</td>
<td>


bit2

</td>
<td>


bit1

</td>
<td>


bit0

</td>
<td>


rp0

</td>
<td>


rp2

</td>
<td>


rp4

</td>
<td>


...

</td>
<td>


rp14

</td>
</tr>
<tr>
<td>


byte   1:

</td>
<td>


bit7

</td>
<td>


bit6

</td>
<td>


bit5

</td>
<td>


bit4

</td>
<td>


bit3

</td>
<td>


bit2

</td>
<td>


bit1

</td>
<td>


bit0

</td>
<td>


rp1

</td>
<td>


rp2

</td>
<td>


rp4

</td>
<td>


...

</td>
<td>


rp14

</td>
</tr>
<tr>
<td>


byte   2:

</td>
<td>


bit7

</td>
<td>


bit6

</td>
<td>


bit5

</td>
<td>


bit4

</td>
<td>


bit3

</td>
<td>


bit2

</td>
<td>


bit1

</td>
<td>


bit0

</td>
<td>


rp0

</td>
<td>


rp3

</td>
<td>


rp4

</td>
<td>


...

</td>
<td>


rp14

</td>
</tr>
<tr>
<td>


byte   3:

</td>
<td>


bit7

</td>
<td>


bit6

</td>
<td>


bit5

</td>
<td>


bit4

</td>
<td>


bit3

</td>
<td>


bit2

</td>
<td>


bit1

</td>
<td>


bit0

</td>
<td>


rp1

</td>
<td>


rp3

</td>
<td>


rp4

</td>
<td>


...

</td>
<td>


rp14

</td>
</tr>
<tr>
<td>


byte   4:

</td>
<td>


bit7

</td>
<td>


bit6

</td>
<td>


bit5

</td>
<td>


bit4

</td>
<td>


bit3

</td>
<td>


bit2

</td>
<td>


bit1

</td>
<td>


bit0

</td>
<td>


rp0

</td>
<td>


rp2

</td>
<td>


rp5

</td>
<td>


...

</td>
<td>


rp14

</td>
</tr>
<tr>
<td>


...

</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


byte 254:

</td>
<td>


bit7

</td>
<td>


bit6

</td>
<td>


bit5

</td>
<td>


bit4

</td>
<td>


bit3

</td>
<td>


bit2

</td>
<td>


bit1

</td>
<td>


bit0

</td>
<td>


rp0

</td>
<td>


rp3

</td>
<td>


rp5

</td>
<td>


...

</td>
<td>


rp15

</td>
</tr>
<tr>
<td>


byte 255:

</td>
<td>


bit7 cp1 cp3 cp5

</td>
<td>


bit6 cp0 cp3 cp5

</td>
<td>


bit5 cp1 cp2 cp5

</td>
<td>


bit4 cp0 cp2 cp5

</td>
<td>


bit3 cp1 cp3 cp4

</td>
<td>


bit2 cp0 cp3 cp4

</td>
<td>


bit1 cp1 cp2 cp4

</td>
<td>


bit0 cp0 cp2 cp4

</td>
<td>


rp1

</td>
<td>


rp3

</td>
<td>


rp5

</td>
<td>


...

</td>
<td>


rp15

</td>
</tr>
</tbody>
</table>

This figure represents a sector of 256 bytes. cp is my abbreviation for column parity, rp for row parity.

Let's start to explain column parity.

- cp0 is the parity that belongs to all bit0, bit2, bit4, bit6.

  so the sum of all bit0, bit2, bit4 and bit6 values + cp0 itself is even.

Similarly cp1 is the sum of all bit1, bit3, bit5 and bit7.

- cp2 is the parity over bit0, bit1, bit4 and bit5

- cp3 is the parity over bit2, bit3, bit6 and bit7.

- cp4 is the parity over bit0, bit1, bit2 and bit3.

- cp5 is the parity over bit4, bit5, bit6 and bit7.

Note that each of cp0 .. cp5 is exactly one bit.

Row parity actually works almost the same.

- rp0 is the parity of all even bytes (0, 2, 4, 6, ... 252, 254)

- rp1 is the parity of all odd bytes (1, 3, 5, 7, ..., 253, 255)

- rp2 is the parity of all bytes 0, 1, 4, 5, 8, 9, ... (so handle two bytes, then skip 2 bytes).

- rp3 is covers the half rp2 does not cover (bytes 2, 3, 6, 7, 10, 11, ...)

- for rp4 the rule is cover 4 bytes, skip 4 bytes, cover 4 bytes, skip 4 etc.

  so rp4 calculates parity over bytes 0, 1, 2, 3, 8, 9, 10, 11, 16, ...)

- and rp5 covers the other half, so bytes 4, 5, 6, 7, 12, 13, 14, 15, 20, ..

The story now becomes quite boring. I guess you get the idea.

- rp6 covers 8 bytes then skips 8 etc

- rp7 skips 8 bytes then covers 8 etc

- rp8 covers 16 bytes then skips 16 etc

- rp9 skips 16 bytes then covers 16 etc

- rp10 covers 32 bytes then skips 32 etc

- rp11 skips 32 bytes then covers 32 etc

- rp12 covers 64 bytes then skips 64 etc

- rp13 skips 64 bytes then covers 64 etc

- rp14 covers 128 bytes then skips 128

- rp15 skips 128 bytes then covers 128

In the end the parity bits are grouped together in three bytes as follows:


<table>
<thead>
<tr>
<th>


ECC

</th>
<th>


Bit 7

</th>
<th>


Bit 6

</th>
<th>


Bit 5

</th>
<th>


Bit 4

</th>
<th>


Bit 3

</th>
<th>


Bit 2

</th>
<th>


Bit 1

</th>
<th>


Bit 0

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


ECC 0

</td>
<td>


rp07

</td>
<td>


rp06

</td>
<td>


rp05

</td>
<td>


rp04

</td>
<td>


rp03

</td>
<td>


rp02

</td>
<td>


rp01

</td>
<td>


rp00

</td>
</tr>
<tr>
<td>


ECC 1

</td>
<td>


rp15

</td>
<td>


rp14

</td>
<td>


rp13

</td>
<td>


rp12

</td>
<td>


rp11

</td>
<td>


rp10

</td>
<td>


rp09

</td>
<td>


rp08

</td>
</tr>
<tr>
<td>


ECC 2

</td>
<td>


cp5

</td>
<td>


cp4

</td>
<td>


cp3

</td>
<td>


cp2

</td>
<td>


cp1

</td>
<td>


cp0

</td>
<td>


1

</td>
<td>


1

</td>
</tr>
</tbody>
</table>

I detected after writing this that ST application note AN1823 ([http://www.st.com/stonline/](<http://www.st.com/stonline/>)) gives a much nicer picture.(but they use line parity as term where I use row parity) Oh well, I'm graphically challenged, so suffer with me for a moment :-)

And I could not reuse the ST picture anyway for copyright reasons.

<a id="rst-attempt-0"></a>

## Attempt 0

Implementing the parity calculation is pretty simple. In C pseudocode:



```text
for (i = 0; i < 256; i++)
{
  if (i & 0x01)
     rp1 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp1;
  else
     rp0 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp0;
  if (i & 0x02)
     rp3 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp3;
  else
     rp2 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp2;
  if (i & 0x04)
    rp5 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp5;
  else
    rp4 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp4;
  if (i & 0x08)
    rp7 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp7;
  else
    rp6 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp6;
  if (i & 0x10)
    rp9 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp9;
  else
    rp8 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp8;
  if (i & 0x20)
    rp11 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp11;
  else
    rp10 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp10;
  if (i & 0x40)
    rp13 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp13;
  else
    rp12 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp12;
  if (i & 0x80)
    rp15 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp15;
  else
    rp14 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ bit3 ^ bit2 ^ bit1 ^ bit0 ^ rp14;
  cp0 = bit6 ^ bit4 ^ bit2 ^ bit0 ^ cp0;
  cp1 = bit7 ^ bit5 ^ bit3 ^ bit1 ^ cp1;
  cp2 = bit5 ^ bit4 ^ bit1 ^ bit0 ^ cp2;
  cp3 = bit7 ^ bit6 ^ bit3 ^ bit2 ^ cp3
  cp4 = bit3 ^ bit2 ^ bit1 ^ bit0 ^ cp4
  cp5 = bit7 ^ bit6 ^ bit5 ^ bit4 ^ cp5
}
```

<a id="rst-analysis-0"></a>

## Analysis 0

C does have bitwise operators but not really operators to do the above efficiently (and most hardware has no such instructions either). Therefore without implementing this it was clear that the code above was not going to bring me a Nobel prize :-)

Fortunately the exclusive or operation is commutative, so we can combine the values in any order. So instead of calculating all the bits individually, let us try to rearrange things. For the column parity this is easy. We can just xor the bytes and in the end filter out the relevant bits. This is pretty nice as it will bring all cp calculation out of the for loop.

Similarly we can first xor the bytes for the various rows. This leads to:

<a id="rst-attempt-1"></a>

## Attempt 1



```text
const char parity[256] = {
    0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
    0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
    0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
    0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
    0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
    0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
    0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
    0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0
};

void ecc1(const unsigned char *buf, unsigned char *code)
{
    int i;
    const unsigned char *bp = buf;
    unsigned char cur;
    unsigned char rp0, rp1, rp2, rp3, rp4, rp5, rp6, rp7;
    unsigned char rp8, rp9, rp10, rp11, rp12, rp13, rp14, rp15;
    unsigned char par;

    par = 0;
    rp0 = 0; rp1 = 0; rp2 = 0; rp3 = 0;
    rp4 = 0; rp5 = 0; rp6 = 0; rp7 = 0;
    rp8 = 0; rp9 = 0; rp10 = 0; rp11 = 0;
    rp12 = 0; rp13 = 0; rp14 = 0; rp15 = 0;

    for (i = 0; i < 256; i++)
    {
        cur = *bp++;
        par ^= cur;
        if (i & 0x01) rp1 ^= cur; else rp0 ^= cur;
        if (i & 0x02) rp3 ^= cur; else rp2 ^= cur;
        if (i & 0x04) rp5 ^= cur; else rp4 ^= cur;
        if (i & 0x08) rp7 ^= cur; else rp6 ^= cur;
        if (i & 0x10) rp9 ^= cur; else rp8 ^= cur;
        if (i & 0x20) rp11 ^= cur; else rp10 ^= cur;
        if (i & 0x40) rp13 ^= cur; else rp12 ^= cur;
        if (i & 0x80) rp15 ^= cur; else rp14 ^= cur;
    }
    code[0] =
        (parity[rp7] << 7) |
        (parity[rp6] << 6) |
        (parity[rp5] << 5) |
        (parity[rp4] << 4) |
        (parity[rp3] << 3) |
        (parity[rp2] << 2) |
        (parity[rp1] << 1) |
        (parity[rp0]);
    code[1] =
        (parity[rp15] << 7) |
        (parity[rp14] << 6) |
        (parity[rp13] << 5) |
        (parity[rp12] << 4) |
        (parity[rp11] << 3) |
        (parity[rp10] << 2) |
        (parity[rp9]  << 1) |
        (parity[rp8]);
    code[2] =
        (parity[par & 0xf0] << 7) |
        (parity[par & 0x0f] << 6) |
        (parity[par & 0xcc] << 5) |
        (parity[par & 0x33] << 4) |
        (parity[par & 0xaa] << 3) |
        (parity[par & 0x55] << 2);
    code[0] = ~code[0];
    code[1] = ~code[1];
    code[2] = ~code[2];
}
```

Still pretty straightforward. The last three invert statements are there to give a checksum of 0xff 0xff 0xff for an empty flash. In an empty flash all data is 0xff, so the checksum then matches.

I also introduced the parity lookup. I expected this to be the fastest way to calculate the parity, but I will investigate alternatives later on.

<a id="rst-analysis-1"></a>

## Analysis 1

The code works, but is not terribly efficient. On my system it took almost 4 times as much time as the linux driver code. But hey, if it was *that* easy this would have been done long before. No pain. no gain.

Fortunately there is plenty of room for improvement.

In step 1 we moved from bit-wise calculation to byte-wise calculation. However in C we can also use the unsigned long data type and virtually every modern microprocessor supports 32 bit operations, so why not try to write our code in such a way that we process data in 32 bit chunks.

Of course this means some modification as the row parity is byte by byte. A quick analysis: for the column parity we use the par variable. When extending to 32 bits we can in the end easily calculate rp0 and rp1 from it. (because par now consists of 4 bytes, contributing to rp1, rp0, rp1, rp0 respectively, from MSB to LSB) also rp2 and rp3 can be easily retrieved from par as rp3 covers the first two MSBs and rp2 covers the last two LSBs.

Note that of course now the loop is executed only 64 times (256/4). And note that care must taken wrt byte ordering. The way bytes are ordered in a long is machine dependent, and might affect us. Anyway, if there is an issue: this code is developed on x86 (to be precise: a DELL PC with a D920 Intel CPU)

And of course the performance might depend on alignment, but I expect that the I/O buffers in the nand driver are aligned properly (and otherwise that should be fixed to get maximum performance).

Let's give it a try...

<a id="rst-attempt-2"></a>

## Attempt 2



```text
extern const char parity[256];

void ecc2(const unsigned char *buf, unsigned char *code)
{
    int i;
    const unsigned long *bp = (unsigned long *)buf;
    unsigned long cur;
    unsigned long rp0, rp1, rp2, rp3, rp4, rp5, rp6, rp7;
    unsigned long rp8, rp9, rp10, rp11, rp12, rp13, rp14, rp15;
    unsigned long par;

    par = 0;
    rp0 = 0; rp1 = 0; rp2 = 0; rp3 = 0;
    rp4 = 0; rp5 = 0; rp6 = 0; rp7 = 0;
    rp8 = 0; rp9 = 0; rp10 = 0; rp11 = 0;
    rp12 = 0; rp13 = 0; rp14 = 0; rp15 = 0;

    for (i = 0; i < 64; i++)
    {
        cur = *bp++;
        par ^= cur;
        if (i & 0x01) rp5 ^= cur; else rp4 ^= cur;
        if (i & 0x02) rp7 ^= cur; else rp6 ^= cur;
        if (i & 0x04) rp9 ^= cur; else rp8 ^= cur;
        if (i & 0x08) rp11 ^= cur; else rp10 ^= cur;
        if (i & 0x10) rp13 ^= cur; else rp12 ^= cur;
        if (i & 0x20) rp15 ^= cur; else rp14 ^= cur;
    }
    /*
       we need to adapt the code generation for the fact that rp vars are now
       long; also the column parity calculation needs to be changed.
       we'll bring rp4 to 15 back to single byte entities by shifting and
       xoring
    */
    rp4 ^= (rp4 >> 16); rp4 ^= (rp4 >> 8); rp4 &= 0xff;
    rp5 ^= (rp5 >> 16); rp5 ^= (rp5 >> 8); rp5 &= 0xff;
    rp6 ^= (rp6 >> 16); rp6 ^= (rp6 >> 8); rp6 &= 0xff;
    rp7 ^= (rp7 >> 16); rp7 ^= (rp7 >> 8); rp7 &= 0xff;
    rp8 ^= (rp8 >> 16); rp8 ^= (rp8 >> 8); rp8 &= 0xff;
    rp9 ^= (rp9 >> 16); rp9 ^= (rp9 >> 8); rp9 &= 0xff;
    rp10 ^= (rp10 >> 16); rp10 ^= (rp10 >> 8); rp10 &= 0xff;
    rp11 ^= (rp11 >> 16); rp11 ^= (rp11 >> 8); rp11 &= 0xff;
    rp12 ^= (rp12 >> 16); rp12 ^= (rp12 >> 8); rp12 &= 0xff;
    rp13 ^= (rp13 >> 16); rp13 ^= (rp13 >> 8); rp13 &= 0xff;
    rp14 ^= (rp14 >> 16); rp14 ^= (rp14 >> 8); rp14 &= 0xff;
    rp15 ^= (rp15 >> 16); rp15 ^= (rp15 >> 8); rp15 &= 0xff;
    rp3 = (par >> 16); rp3 ^= (rp3 >> 8); rp3 &= 0xff;
    rp2 = par & 0xffff; rp2 ^= (rp2 >> 8); rp2 &= 0xff;
    par ^= (par >> 16);
    rp1 = (par >> 8); rp1 &= 0xff;
    rp0 = (par & 0xff);
    par ^= (par >> 8); par &= 0xff;

    code[0] =
        (parity[rp7] << 7) |
        (parity[rp6] << 6) |
        (parity[rp5] << 5) |
        (parity[rp4] << 4) |
        (parity[rp3] << 3) |
        (parity[rp2] << 2) |
        (parity[rp1] << 1) |
        (parity[rp0]);
    code[1] =
        (parity[rp15] << 7) |
        (parity[rp14] << 6) |
        (parity[rp13] << 5) |
        (parity[rp12] << 4) |
        (parity[rp11] << 3) |
        (parity[rp10] << 2) |
        (parity[rp9]  << 1) |
        (parity[rp8]);
    code[2] =
        (parity[par & 0xf0] << 7) |
        (parity[par & 0x0f] << 6) |
        (parity[par & 0xcc] << 5) |
        (parity[par & 0x33] << 4) |
        (parity[par & 0xaa] << 3) |
        (parity[par & 0x55] << 2);
    code[0] = ~code[0];
    code[1] = ~code[1];
    code[2] = ~code[2];
}
```

The parity array is not shown any more. Note also that for these examples I kinda deviated from my regular programming style by allowing multiple statements on a line, not using \{ \} in then and else blocks with only a single statement and by using operators like ^=

<a id="rst-analysis-2"></a>

## Analysis 2

The code (of course) works, and hurray: we are a little bit faster than the linux driver code (about 15%). But wait, don't cheer too quickly. There is more to be gained. If we look at e.g. rp14 and rp15 we see that we either xor our data with rp14 or with rp15. However we also have par which goes over all data. This means there is no need to calculate rp14 as it can be calculated from rp15 through rp14 = par ^ rp15, because par = rp14 ^ rp15; (or if desired we can avoid calculating rp15 and calculate it from rp14).  That is why some places refer to inverse parity. Of course the same thing holds for rp4/5, rp6/7, rp8/9, rp10/11 and rp12/13. Effectively this means we can eliminate the else clause from the if statements. Also we can optimise the calculation in the end a little bit by going from long to byte first. Actually we can even avoid the table lookups

<a id="rst-attempt-3"></a>

## Attempt 3

Odd replaced:



```text
if (i & 0x01) rp5 ^= cur; else rp4 ^= cur;
if (i & 0x02) rp7 ^= cur; else rp6 ^= cur;
if (i & 0x04) rp9 ^= cur; else rp8 ^= cur;
if (i & 0x08) rp11 ^= cur; else rp10 ^= cur;
if (i & 0x10) rp13 ^= cur; else rp12 ^= cur;
if (i & 0x20) rp15 ^= cur; else rp14 ^= cur;
```

with:



```text
if (i & 0x01) rp5 ^= cur;
if (i & 0x02) rp7 ^= cur;
if (i & 0x04) rp9 ^= cur;
if (i & 0x08) rp11 ^= cur;
if (i & 0x10) rp13 ^= cur;
if (i & 0x20) rp15 ^= cur;
```

and outside the loop added:



```text
rp4  = par ^ rp5;
rp6  = par ^ rp7;
rp8  = par ^ rp9;
rp10  = par ^ rp11;
rp12  = par ^ rp13;
rp14  = par ^ rp15;
```

And after that the code takes about 30% more time, although the number of statements is reduced. This is also reflected in the assembly code.

<a id="rst-analysis-3"></a>

## Analysis 3

Very weird. Guess it has to do with caching or instruction parallelism or so. I also tried on an eeePC (Celeron, clocked at 900 Mhz). Interesting observation was that this one is only 30% slower (according to time) executing the code as my 3Ghz D920 processor.

Well, it was expected not to be easy so maybe instead move to a different track: let's move back to the code from attempt2 and do some loop unrolling. This will eliminate a few if statements. I'll try different amounts of unrolling to see what works best.

<a id="rst-attempt-4"></a>

## Attempt 4

Unrolled the loop 1, 2, 3 and 4 times. For 4 the code starts with:



```text
for (i = 0; i < 4; i++)
{
    cur = *bp++;
    par ^= cur;
    rp4 ^= cur;
    rp6 ^= cur;
    rp8 ^= cur;
    rp10 ^= cur;
    if (i & 0x1) rp13 ^= cur; else rp12 ^= cur;
    if (i & 0x2) rp15 ^= cur; else rp14 ^= cur;
    cur = *bp++;
    par ^= cur;
    rp5 ^= cur;
    rp6 ^= cur;
    ...
```

<a id="rst-analysis-4"></a>

## Analysis 4

Unrolling once gains about 15%

Unrolling twice keeps the gain at about 15%

Unrolling three times gives a gain of 30% compared to attempt 2.

Unrolling four times gives a marginal improvement compared to unrolling three times.

I decided to proceed with a four time unrolled loop anyway. It was my gut feeling that in the next steps I would obtain additional gain from it.

The next step was triggered by the fact that par contains the xor of all bytes and rp4 and rp5 each contain the xor of half of the bytes. So in effect par = rp4 ^ rp5. But as xor is commutative we can also say that rp5 = par ^ rp4. So no need to keep both rp4 and rp5 around. We can eliminate rp5 (or rp4, but I already foresaw another optimisation). The same holds for rp6/7, rp8/9, rp10/11 rp12/13 and rp14/15.

<a id="rst-attempt-5"></a>

## Attempt 5

Effectively so all odd digit rp assignments in the loop were removed. This included the else clause of the if statements. Of course after the loop we need to correct things by adding code like:



```text
rp5 = par ^ rp4;
```

Also the initial assignments (rp5 = 0; etc) could be removed. Along the line I also removed the initialisation of rp0/1/2/3.

<a id="rst-analysis-5"></a>

## Analysis 5

Measurements showed this was a good move. The run-time roughly halved compared with attempt 4 with 4 times unrolled, and we only require 1/3rd of the processor time compared to the current code in the linux kernel.

However, still I thought there was more. I didn't like all the if statements. Why not keep a running parity and only keep the last if statement. Time for yet another version\!

<a id="rst-attempt-6"></a>

## Attempt 6

THe code within the for loop was changed to:



```text
for (i = 0; i < 4; i++)
{
    cur = *bp++; tmppar  = cur; rp4 ^= cur;
    cur = *bp++; tmppar ^= cur; rp6 ^= tmppar;
    cur = *bp++; tmppar ^= cur; rp4 ^= cur;
    cur = *bp++; tmppar ^= cur; rp8 ^= tmppar;

    cur = *bp++; tmppar ^= cur; rp4 ^= cur; rp6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp4 ^= cur;
    cur = *bp++; tmppar ^= cur; rp10 ^= tmppar;

    cur = *bp++; tmppar ^= cur; rp4 ^= cur; rp6 ^= cur; rp8 ^= cur;
    cur = *bp++; tmppar ^= cur; rp6 ^= cur; rp8 ^= cur;
    cur = *bp++; tmppar ^= cur; rp4 ^= cur; rp8 ^= cur;
    cur = *bp++; tmppar ^= cur; rp8 ^= cur;

    cur = *bp++; tmppar ^= cur; rp4 ^= cur; rp6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp4 ^= cur;
    cur = *bp++; tmppar ^= cur;

    par ^= tmppar;
    if ((i & 0x1) == 0) rp12 ^= tmppar;
    if ((i & 0x2) == 0) rp14 ^= tmppar;
}
```

As you can see tmppar is used to accumulate the parity within a for iteration. In the last 3 statements is added to par and, if needed, to rp12 and rp14.

While making the changes I also found that I could exploit that tmppar contains the running parity for this iteration. So instead of having: rp4 ^= cur; rp6 ^= cur; I removed the rp6 ^= cur; statement and did rp6 ^= tmppar; on next statement. A similar change was done for rp8 and rp10

<a id="rst-analysis-6"></a>

## Analysis 6

Measuring this code again showed big gain. When executing the original linux code 1 million times, this took about 1 second on my system. (using time to measure the performance). After this iteration I was back to 0.075 sec. Actually I had to decide to start measuring over 10 million iterations in order not to lose too much accuracy. This one definitely seemed to be the jackpot\!

There is a little bit more room for improvement though. There are three places with statements:



```text
rp4 ^= cur; rp6 ^= cur;
```

It seems more efficient to also maintain a variable rp4_6 in the while loop; This eliminates 3 statements per loop. Of course after the loop we need to correct by adding:



```text
rp4 ^= rp4_6;
rp6 ^= rp4_6
```

Furthermore there are 4 sequential assignments to rp8. This can be encoded slightly more efficiently by saving tmppar before those 4 lines and later do rp8 = rp8 ^ tmppar ^ notrp8; (where notrp8 is the value of rp8 before those 4 lines). Again a use of the commutative property of xor. Time for a new test\!

<a id="rst-attempt-7"></a>

## Attempt 7

The new code now looks like:



```text
for (i = 0; i < 4; i++)
{
    cur = *bp++; tmppar  = cur; rp4 ^= cur;
    cur = *bp++; tmppar ^= cur; rp6 ^= tmppar;
    cur = *bp++; tmppar ^= cur; rp4 ^= cur;
    cur = *bp++; tmppar ^= cur; rp8 ^= tmppar;

    cur = *bp++; tmppar ^= cur; rp4_6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp4 ^= cur;
    cur = *bp++; tmppar ^= cur; rp10 ^= tmppar;

    notrp8 = tmppar;
    cur = *bp++; tmppar ^= cur; rp4_6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp4 ^= cur;
    cur = *bp++; tmppar ^= cur;
    rp8 = rp8 ^ tmppar ^ notrp8;

    cur = *bp++; tmppar ^= cur; rp4_6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp6 ^= cur;
    cur = *bp++; tmppar ^= cur; rp4 ^= cur;
    cur = *bp++; tmppar ^= cur;

    par ^= tmppar;
    if ((i & 0x1) == 0) rp12 ^= tmppar;
    if ((i & 0x2) == 0) rp14 ^= tmppar;
}
rp4 ^= rp4_6;
rp6 ^= rp4_6;
```

Not a big change, but every penny counts :-)

<a id="rst-analysis-7"></a>

## Analysis 7

Actually this made things worse. Not very much, but I don't want to move into the wrong direction. Maybe something to investigate later. Could have to do with caching again.

Guess that is what there is to win within the loop. Maybe unrolling one more time will help. I'll keep the optimisations from 7 for now.

<a id="rst-attempt-8"></a>

## Attempt 8

Unrolled the loop one more time.

<a id="rst-analysis-8"></a>

## Analysis 8

This makes things worse. Let's stick with attempt 6 and continue from there. Although it seems that the code within the loop cannot be optimised further there is still room to optimize the generation of the ecc codes. We can simply calculate the total parity. If this is 0 then rp4 = rp5 etc. If the parity is 1, then rp4 = \!rp5;

But if rp4 = rp5 we do not need rp5 etc. We can just write the even bits in the result byte and then do something like:



```text
code[0] |= (code[0] << 1);
```

Lets test this.

<a id="rst-attempt-9"></a>

## Attempt 9

Changed the code but again this slightly degrades performance. Tried all kind of other things, like having dedicated parity arrays to avoid the shift after parity\[rp7\] &lt;&lt; 7; No gain. Change the lookup using the parity array by using shift operators (e.g. replace parity\[rp7\] &lt;&lt; 7 with:



```text
rp7 ^= (rp7 << 4);
rp7 ^= (rp7 << 2);
rp7 ^= (rp7 << 1);
rp7 &= 0x80;
```

No gain.

The only marginal change was inverting the parity bits, so we can remove the last three invert statements.

Ah well, pity this does not deliver more. Then again 10 million iterations using the linux driver code takes between 13 and 13.5 seconds, whereas my code now takes about 0.73 seconds for those 10 million iterations. So basically I've improved the performance by a factor 18 on my system. Not that bad. Of course on different hardware you will get different results. No warranties\!

But of course there is no such thing as a free lunch. The codesize almost tripled (from 562 bytes to 1434 bytes). Then again, it is not that much.

<a id="rst-correcting-errors"></a>

## Correcting errors

For correcting errors I again used the ST application note as a starter, but I also peeked at the existing code.

The algorithm itself is pretty straightforward. Just xor the given and the calculated ecc. If all bytes are 0 there is no problem. If 11 bits are 1 we have one correctable bit error. If there is 1 bit 1, we have an error in the given ecc code.

It proved to be fastest to do some table lookups. Performance gain introduced by this is about a factor 2 on my system when a repair had to be done, and 1% or so if no repair had to be done.

Code size increased from 330 bytes to 686 bytes for this function. (gcc 4.2, -O3)

<a id="rst-conclusion"></a>

## Conclusion

The gain when calculating the ecc is tremendous. Om my development hardware a speedup of a factor of 18 for ecc calculation was achieved. On a test on an embedded system with a MIPS core a factor 7 was obtained.

On a test with a Linksys NSLU2 (ARMv5TE processor) the speedup was a factor 5 (big endian mode, gcc 4.1.2, -O3)

For correction not much gain could be obtained (as bitflips are rare). Then again there are also much less cycles spent there.

It seems there is not much more gain possible in this, at least when programmed in C. Of course it might be possible to squeeze something more out of it with an assembler program, but due to pipeline behaviour etc this is very tricky (at least for intel hw).

Author: Frans Meulenbroeks

Copyright (C) 2008 Koninklijke Philips Electronics NV.

---

# Upgrading BIOS using spi-intel

_Peios Kernel / Hardware and drivers / Driver development / Flash memory (MTD)_

> Many Intel CPUs like Baytrail and Braswell include SPI serial flash host controller which is used to hold BIOS and other platform specific data. Since contents of the SPI serial flash is crucial for machine to function, it is typically…

<a id="rst-upgrading-bios-using-spi-intel"></a>

Many Intel CPUs like Baytrail and Braswell include SPI serial flash host controller which is used to hold BIOS and other platform specific data. Since contents of the SPI serial flash is crucial for machine to function, it is typically protected by different hardware protection mechanisms to avoid accidental (or on purpose) overwrite of the content.

Not all manufacturers protect the SPI serial flash, mainly because it allows upgrading the BIOS image directly from an OS.

The spi-intel driver makes it possible to read and write the SPI serial flash, if certain protection bits are not set and locked. If it finds any of them set, the whole MTD device is made read-only to prevent partial overwrites. By default the driver exposes SPI serial flash contents as read-only but it can be changed from kernel command line, passing "spi_intel.writeable=1".

Please keep in mind that overwriting the BIOS image on SPI serial flash might render the machine unbootable and requires special equipment like Dediprog to revive. You have been warned\!

Below are the steps how to upgrade MinnowBoard MAX BIOS directly from Linux.

> 1. Download and extract the latest Minnowboard MAX BIOS SPI image \[1\]. At the time writing this the latest image is v92.
>
> 2. Install mtd-utils package \[2\]. We need this in order to erase the SPI serial flash. Distros like Debian and Fedora have this prepackaged with name "mtd-utils".
>
> 3. Add "spi_intel.writeable=1" to the kernel command line and reboot the board (you can also reload the driver passing "writeable=1" as module parameter to modprobe).
>
> 4. Once the board is up and running again, find the right MTD partition (it is named as "BIOS"):
>
>
>
>    ```text
>    # cat /proc/mtd
>    dev:    size   erasesize  name
>    mtd0: 00800000 00001000 "BIOS"
>    ```
>
>    So here it will be /dev/mtd0 but it may vary.
>
> 5. Make backup of the existing image first:
>
>
>
>    ```text
>    # dd if=/dev/mtd0ro of=bios.bak
>    16384+0 records in
>    16384+0 records out
>    8388608 bytes (8.4 MB) copied, 10.0269 s, 837 kB/s
>    ```
>
> 6. Verify the backup:
>
>
>
>    ```text
>    # sha1sum /dev/mtd0ro bios.bak
>    fdbb011920572ca6c991377c4b418a0502668b73  /dev/mtd0ro
>    fdbb011920572ca6c991377c4b418a0502668b73  bios.bak
>    ```
>
>    The SHA1 sums must match. Otherwise do not continue any further\!
>
> 7. Erase the SPI serial flash. After this step, do not reboot the board\! Otherwise it will not start anymore:
>
>
>
>    ```text
>    # flash_erase /dev/mtd0 0 0
>    Erasing 4 Kibyte @ 7ff000 -- 100 % complete
>    ```
>
> 8. Once completed without errors you can write the new BIOS image:
>
>
>
>    ```text
>    # dd if=MNW2MAX1.X64.0092.R01.1605221712.bin of=/dev/mtd0
>    ```
>
> 9. Verify that the new content of the SPI serial flash matches the new BIOS image:
>
>
>
>    ```text
>    # sha1sum /dev/mtd0ro MNW2MAX1.X64.0092.R01.1605221712.bin
>    9b4df9e4be2057fceec3a5529ec3d950836c87a2  /dev/mtd0ro
>    9b4df9e4be2057fceec3a5529ec3d950836c87a2 MNW2MAX1.X64.0092.R01.1605221712.bin
>    ```
>
>    The SHA1 sums should match.
>
> 10. Now you can reboot your board and observe the new BIOS starting up properly.

<a id="rst-references"></a>

## References

\[1\] [https://firmware.intel.com/sites/default/files/MinnowBoard%2EMAX\_%2EX64%2E92%2ER01%2Ezip](<https://firmware.intel.com/sites/default/files/MinnowBoard%2EMAX_%2EX64%2E92%2ER01%2Ezip>)

\[2\] [http://www.linux-mtd.infradead.org/](<http://www.linux-mtd.infradead.org/>)

---

# SPI NOR framework

_Peios Kernel / Hardware and drivers / Driver development / Flash memory (MTD)_

> Most SPI NOR flashes comply with the JEDEC JESD216 Serial Flash Discoverable Parameter (SFDP) standard. SFDP describes the functional and feature capabilities of serial flash devices in a standard set of internal read-only parameter tables.

<a id="rst-spi-nor-framework"></a>

<a id="rst-how-to-propose-a-new-flash-addition"></a>

## How to propose a new flash addition

Most SPI NOR flashes comply with the JEDEC JESD216 Serial Flash Discoverable Parameter (SFDP) standard. SFDP describes the functional and feature capabilities of serial flash devices in a standard set of internal read-only parameter tables.

The SPI NOR driver queries the SFDP tables in order to determine the flash's parameters and settings. If the flash defines the SFDP tables it's likely that you won't need a flash entry at all, and instead rely on the generic flash driver which probes the flash solely based on its SFDP data. All one has to do is to specify the "jedec,spi-nor" compatible in the device tree.

There are cases however where you need to define an explicit flash entry. This typically happens when the flash has settings or support that is not covered by the SFDP tables (e.g. Block Protection), or when the flash contains mangled SFDP data. If the later, one needs to implement the `spi_nor_fixups` hooks in order to amend the SFDP parameters with the correct values.

<a id="rst-minimum-testing-requirements"></a>

## Minimum testing requirements

Do all the tests from below and paste them in the commit's comments section, after the `---` marker.

1. Specify the controller that you used to test the flash and specify the frequency at which the flash was operated, e.g.:



   ```text
   This flash is populated on the X board and was tested at Y
   frequency using the Z (put compatible) SPI controller.
   ```

2. Dump the sysfs entries and print the md5/sha1/sha256 SFDP checksum:



   ```text
   root@1:~# cat /sys/bus/spi/devices/spi0.0/spi-nor/partname
   sst26vf064b
   root@1:~# cat /sys/bus/spi/devices/spi0.0/spi-nor/jedec_id
   bf2643
   root@1:~# cat /sys/bus/spi/devices/spi0.0/spi-nor/manufacturer
   sst
   root@1:~# xxd -p /sys/bus/spi/devices/spi0.0/spi-nor/sfdp
   53464450060102ff00060110300000ff81000106000100ffbf0001180002
   0001fffffffffffffffffffffffffffffffffd20f1ffffffff0344eb086b
   083b80bbfeffffffffff00ffffff440b0c200dd80fd810d820914824806f
   1d81ed0f773830b030b0f7ffffff29c25cfff030c080ffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffff0004fff37f0000f57f0000f9ff
   7d00f57f0000f37f0000ffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
   ffffbf2643ffb95ffdff30f260f332ff0a122346ff0f19320f1919ffffff
   ffffffff00669938ff05013506040232b03072428de89888a585c09faf5a
   ffff06ec060c0003080bffffffffff07ffff0202ff060300fdfd040700fc
   0300fefe0202070e
   root@1:~# sha256sum /sys/bus/spi/devices/spi0.0/spi-nor/sfdp
   428f34d0461876f189ac97f93e68a05fa6428c6650b3b7baf736a921e5898ed1  /sys/bus/spi/devices/spi0.0/spi-nor/sfdp
   ```

   Please dump the SFDP tables using `xxd -p`. It enables us to do the reverse operation and convert the hexdump to binary with `xxd -rp`. Dumping the SFDP data with `hexdump -Cv` is accepted, but less desirable.

3. Dump debugfs data:



   ```text
   root@1:~# cat /sys/kernel/debug/spi-nor/spi0.0/capabilities
   Supported read modes by the flash
    1S-1S-1S
     opcode            0x03
     mode cycles       0
     dummy cycles      0
    1S-1S-1S (fast read)
     opcode            0x0b
     mode cycles       0
     dummy cycles      8
    1S-1S-2S
     opcode            0x3b
     mode cycles       0
     dummy cycles      8
    1S-2S-2S
     opcode            0xbb
     mode cycles       4
     dummy cycles      0
    1S-1S-4S
     opcode            0x6b
     mode cycles       0
     dummy cycles      8
    1S-4S-4S
     opcode            0xeb
     mode cycles       2
     dummy cycles      4
    4S-4S-4S
     opcode            0x0b
     mode cycles       2
     dummy cycles      4

   Supported page program modes by the flash
    1S-1S-1S
     opcode    0x02

   root@1:~# cat /sys/kernel/debug/spi-nor/spi0.0/params
   name                sst26vf064b
   id                  bf 26 43 bf 26 43
   size                8.00 MiB
   write size          1
   page size           256
   address nbytes      3
   flags               HAS_LOCK | HAS_16BIT_SR | SOFT_RESET | SWP_IS_VOLATILE

   opcodes
    read               0xeb
     dummy cycles      6
    erase              0x20
    program            0x02
    8D extension       none

   protocols
    read               1S-4S-4S
    write              1S-1S-1S
    register           1S-1S-1S

   erase commands
    20 (4.00 KiB) [0]
    d8 (8.00 KiB) [1]
    d8 (32.0 KiB) [2]
    d8 (64.0 KiB) [3]
    c7 (8.00 MiB)

   sector map
    region (in hex)   | erase mask | flags
    ------------------+------------+----------
    00000000-00007fff |     [01  ] |
    00008000-0000ffff |     [0 2 ] |
    00010000-007effff |     [0  3] |
    007f0000-007f7fff |     [0 2 ] |
    007f8000-007fffff |     [01  ] |
   ```

4. Use [mtd-utils](<https://git.infradead.org/mtd-utils.git>) and verify that erase, read and page program operations work fine:



   ```text
   root@1:~# dd if=/dev/urandom of=./spi_test bs=1M count=2
   2+0 records in
   2+0 records out
   2097152 bytes (2.1 MB, 2.0 MiB) copied, 0.848566 s, 2.5 MB/s

   root@1:~# mtd_debug erase /dev/mtd0 0 2097152
   Erased 2097152 bytes from address 0x00000000 in flash

   root@1:~# mtd_debug read /dev/mtd0 0 2097152 spi_read
   Copied 2097152 bytes from address 0x00000000 in flash to spi_read

   root@1:~# hexdump spi_read
   0000000 ffff ffff ffff ffff ffff ffff ffff ffff
   *
   0200000

   root@1:~# sha256sum spi_read
   4bda3a28f4ffe603c0ec1258c0034d65a1a0d35ab7bd523a834608adabf03cc5  spi_read

   root@1:~# mtd_debug write /dev/mtd0 0 2097152 spi_test
   Copied 2097152 bytes from spi_test to address 0x00000000 in flash

   root@1:~# mtd_debug read /dev/mtd0 0 2097152 spi_read
   Copied 2097152 bytes from address 0x00000000 in flash to spi_read

   root@1:~# sha256sum spi*
   c444216a6ba2a4a66cccd60a0dd062bce4b865dd52b200ef5e21838c4b899ac8  spi_read
   c444216a6ba2a4a66cccd60a0dd062bce4b865dd52b200ef5e21838c4b899ac8  spi_test
   ```

   If the flash comes erased by default and the previous erase was ignored, we won't catch it, thus test the erase again:



   ```text
   root@1:~# mtd_debug erase /dev/mtd0 0 2097152
   Erased 2097152 bytes from address 0x00000000 in flash

   root@1:~# mtd_debug read /dev/mtd0 0 2097152 spi_read
   Copied 2097152 bytes from address 0x00000000 in flash to spi_read

   root@1:~# sha256sum spi*
   4bda3a28f4ffe603c0ec1258c0034d65a1a0d35ab7bd523a834608adabf03cc5  spi_read
   c444216a6ba2a4a66cccd60a0dd062bce4b865dd52b200ef5e21838c4b899ac8  spi_test
   ```

   Dump some other relevant data:



   ```text
   root@1:~# mtd_debug info /dev/mtd0
   mtd.type = MTD_NORFLASH
   mtd.flags = MTD_CAP_NORFLASH
   mtd.size = 8388608 (8M)
   mtd.erasesize = 4096 (4K)
   mtd.writesize = 1
   mtd.oobsize = 0
   regions = 0
   ```

---

# Near Field Communication

_Peios Kernel / Hardware and drivers / Driver development / NFC_

> Reference for Near Field Communication.

<a id="rst-near-field-communication"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [HCI backend for NFC Core](</kernel/hardware/driver-api/nfc/nfc-hci.md>)
- [Kernel driver for the NXP Semiconductors PN544 Near Field Communication chip](</kernel/hardware/driver-api/nfc/nfc-pn544.md>)

---

# HCI backend for NFC Core

_Peios Kernel / Hardware and drivers / Driver development / NFC_

> Author: Eric Lapuyade, Samuel Ortiz

<a id="rst-hci-backend-for-nfc-core"></a>

- Author: Eric Lapuyade, Samuel Ortiz

- Contact: [eric.lapuyade@intel.com](<mailto:eric.lapuyade@intel.com>), [samuel.ortiz@intel.com](<mailto:samuel.ortiz@intel.com>)

<a id="rst-general"></a>

## General

The HCI layer implements much of the ETSI TS 102 622 V10.2.0 specification. It enables easy writing of HCI-based NFC drivers. The HCI layer runs as an NFC Core backend, implementing an abstract nfc device and translating NFC Core API to HCI commands and events.

<a id="rst-hci"></a>

## HCI

HCI registers as an nfc device with NFC Core. Requests coming from userspace are routed through netlink sockets to NFC Core and then to HCI. From this point, they are translated in a sequence of HCI commands sent to the HCI layer in the host controller (the chip). Commands can be executed synchronously (the sending context blocks waiting for response) or asynchronously (the response is returned from HCI Rx context). HCI events can also be received from the host controller. They will be handled and a translation will be forwarded to NFC Core as needed. There are hooks to let the HCI driver handle proprietary events or override standard behavior. HCI uses 2 execution contexts:

- one for executing commands : nfc_hci_msg_tx_work(). Only one command can be executing at any given moment.

- one for dispatching received events and commands : nfc_hci_msg_rx_work().

<a id="rst-hci-session-initialization"></a>

## HCI Session initialization

The Session initialization is an HCI standard which must unfortunately support proprietary gates. This is the reason why the driver will pass a list of proprietary gates that must be part of the session. HCI will ensure all those gates have pipes connected when the hci device is set up. In case the chip supports pre-opened gates and pseudo-static pipes, the driver can pass that information to HCI core.

<a id="rst-hci-gates-and-pipes"></a>

## HCI Gates and Pipes

A gate defines the 'port' where some service can be found. In order to access a service, one must create a pipe to that gate and open it. In this implementation, pipes are totally hidden. The public API only knows gates. This is consistent with the driver need to send commands to proprietary gates without knowing the pipe connected to it.

<a id="rst-driver-interface"></a>

## Driver interface

A driver is generally written in two parts : the physical link management and the HCI management. This makes it easier to maintain a driver for a chip that can be connected using various phy (i2c, spi, ...)

<a id="rst-hci-management"></a>

## HCI Management

A driver would normally register itself with HCI and provide the following entry points:



```text
struct nfc_hci_ops {
      int (*open)(struct nfc_hci_dev *hdev);
      void (*close)(struct nfc_hci_dev *hdev);
      int (*hci_ready) (struct nfc_hci_dev *hdev);
      int (*xmit) (struct nfc_hci_dev *hdev, struct sk_buff *skb);
      int (*start_poll) (struct nfc_hci_dev *hdev,
                         u32 im_protocols, u32 tm_protocols);
      int (*dep_link_up)(struct nfc_hci_dev *hdev, struct nfc_target *target,
                         u8 comm_mode, u8 *gb, size_t gb_len);
      int (*dep_link_down)(struct nfc_hci_dev *hdev);
      int (*target_from_gate) (struct nfc_hci_dev *hdev, u8 gate,
                               struct nfc_target *target);
      int (*complete_target_discovered) (struct nfc_hci_dev *hdev, u8 gate,
                                         struct nfc_target *target);
      int (*im_transceive) (struct nfc_hci_dev *hdev,
                            struct nfc_target *target, struct sk_buff *skb,
                            data_exchange_cb_t cb, void *cb_context);
      int (*tm_send)(struct nfc_hci_dev *hdev, struct sk_buff *skb);
      int (*check_presence)(struct nfc_hci_dev *hdev,
                            struct nfc_target *target);
      int (*event_received)(struct nfc_hci_dev *hdev, u8 gate, u8 event,
                            struct sk_buff *skb);
};
```

- open() and close() shall turn the hardware on and off.

- hci_ready() is an optional entry point that is called right after the hci session has been set up. The driver can use it to do additional initialization that must be performed using HCI commands.

- xmit() shall simply write a frame to the physical link.

- start_poll() is an optional entrypoint that shall set the hardware in polling mode. This must be implemented only if the hardware uses proprietary gates or a mechanism slightly different from the HCI standard.

- dep_link_up() is called after a p2p target has been detected, to finish the p2p connection setup with hardware parameters that need to be passed back to nfc core.

- dep_link_down() is called to bring the p2p link down.

- target_from_gate() is an optional entrypoint to return the nfc protocols corresponding to a proprietary gate.

- complete_target_discovered() is an optional entry point to let the driver perform additional proprietary processing necessary to auto activate the discovered target.

- im_transceive() must be implemented by the driver if proprietary HCI commands are required to send data to the tag. Some tag types will require custom commands, others can be written to using the standard HCI commands. The driver can check the tag type and either do proprietary processing, or return 1 to ask for standard processing. The data exchange command itself must be sent asynchronously.

- tm_send() is called to send data in the case of a p2p connection

- check_presence() is an optional entry point that will be called regularly by the core to check that an activated tag is still in the field. If this is not implemented, the core will not be able to push tag_lost events to the user space

- event_received() is called to handle an event coming from the chip. Driver can handle the event or return 1 to let HCI attempt standard processing.

On the rx path, the driver is responsible to push incoming HCP frames to HCI using nfc_hci_recv_frame(). HCI will take care of re-aggregation and handling This must be done from a context that can sleep.

<a id="rst-phy-management"></a>

## PHY Management

The physical link (i2c, ...) management is defined by the following structure:



```text
struct nfc_phy_ops {
      int (*write)(void *dev_id, struct sk_buff *skb);
      int (*enable)(void *dev_id);
      void (*disable)(void *dev_id);
};
```

- **enable():**

  turn the phy on (power on), make it ready to transfer data

- **disable():**

  turn the phy off

- **write():**

  Send a data frame to the chip. Note that to enable higher layers such as an llc to store the frame for re-emission, this function must not alter the skb. It must also not return a positive result (return 0 for success, negative for failure).

Data coming from the chip shall be sent directly to nfc_hci_recv_frame().

<a id="rst-llc"></a>

## LLC

Communication between the CPU and the chip often requires some link layer protocol. Those are isolated as modules managed by the HCI layer. There are currently two modules : nop (raw transfer) and shdlc. A new llc must implement the following functions:



```text
struct nfc_llc_ops {
      void *(*init) (struct nfc_hci_dev *hdev, xmit_to_drv_t xmit_to_drv,
                     rcv_to_hci_t rcv_to_hci, int tx_headroom,
                     int tx_tailroom, int *rx_headroom, int *rx_tailroom,
                     llc_failure_t llc_failure);
      void (*deinit) (struct nfc_llc *llc);
      int (*start) (struct nfc_llc *llc);
      int (*stop) (struct nfc_llc *llc);
      void (*rcv_from_drv) (struct nfc_llc *llc, struct sk_buff *skb);
      int (*xmit_from_hci) (struct nfc_llc *llc, struct sk_buff *skb);
};
```

- **init():**

  allocate and init your private storage

- **deinit():**

  cleanup

- **start():**

  establish the logical connection

- **stop ():**

  terminate the logical connection

- **rcv_from_drv():**

  handle data coming from the chip, going to HCI

- **xmit_from_hci():**

  handle data sent by HCI, going to the chip

The llc must be registered with nfc before it can be used. Do that by calling:



```text
nfc_llc_register(const char *name, const struct nfc_llc_ops *ops);
```

Again, note that the llc does not handle the physical link. It is thus very easy to mix any physical link with any llc for a given chip driver.

<a id="rst-included-drivers"></a>

## Included Drivers

An HCI based driver for an NXP PN544, connected through I2C bus, and using shdlc is included.

<a id="rst-execution-contexts"></a>

## Execution Contexts

The execution contexts are the following: - IRQ handler (IRQH): fast, cannot sleep. sends incoming frames to HCI where they are passed to the current llc. In case of shdlc, the frame is queued in shdlc rx queue.

- SHDLC State Machine worker (SMW)

  Only when llc_shdlc is used: handles shdlc rx &amp; tx queues.

  Dispatches HCI cmd responses.

- HCI Tx Cmd worker (MSGTXWQ)

  Serializes execution of HCI commands.

  Completes execution in case of response timeout.

- HCI Rx worker (MSGRXWQ)

  Dispatches incoming HCI commands or events.

- Syscall context from a userspace call (SYSCALL)

  Any entrypoint in HCI called from NFC Core

<a id="rst-workflow-executing-an-hci-command-using-shdlc"></a>

## Workflow executing an HCI command (using shdlc)

Executing an HCI command can easily be performed synchronously using the following API:



```text
int nfc_hci_send_cmd (struct nfc_hci_dev *hdev, u8 gate, u8 cmd,
                      const u8 *param, size_t param_len, struct sk_buff **skb)
```

The API must be invoked from a context that can sleep. Most of the time, this will be the syscall context. skb will return the result that was received in the response.

Internally, execution is asynchronous. So all this API does is to enqueue the HCI command, setup a local wait queue on stack, and wait_event() for completion. The wait is not interruptible because it is guaranteed that the command will complete after some short timeout anyway.

MSGTXWQ context will then be scheduled and invoke nfc_hci_msg_tx_work(). This function will dequeue the next pending command and send its HCP fragments to the lower layer which happens to be shdlc. It will then start a timer to be able to complete the command with a timeout error if no response arrive.

SMW context gets scheduled and invokes nfc_shdlc_sm_work(). This function handles shdlc framing in and out. It uses the driver xmit to send frames and receives incoming frames in an skb queue filled from the driver IRQ handler. SHDLC I(nformation) frames payload are HCP fragments. They are aggregated to form complete HCI frames, which can be a response, command, or event.

HCI Responses are dispatched immediately from this context to unblock waiting command execution. Response processing involves invoking the completion callback that was provided by nfc_hci_msg_tx_work() when it sent the command. The completion callback will then wake the syscall context.

It is also possible to execute the command asynchronously using this API:



```text
static int nfc_hci_execute_cmd_async(struct nfc_hci_dev *hdev, u8 pipe, u8 cmd,
                                     const u8 *param, size_t param_len,
                                     data_exchange_cb_t cb, void *cb_context)
```

The workflow is the same, except that the API call returns immediately, and the callback will be called with the result from the SMW context.

<a id="rst-workflow-receiving-an-hci-event-or-command"></a>

## Workflow receiving an HCI event or command

HCI commands or events are not dispatched from SMW context. Instead, they are queued to HCI rx_queue and will be dispatched from HCI rx worker context (MSGRXWQ). This is done this way to allow a cmd or event handler to also execute other commands (for example, handling the NFC_HCI_EVT_TARGET_DISCOVERED event from PN544 requires to issue an ANY_GET_PARAMETER to the reader A gate to get information on the target that was discovered).

Typically, such an event will be propagated to NFC Core from MSGRXWQ context.

<a id="rst-error-management"></a>

## Error management

Errors that occur synchronously with the execution of an NFC Core request are simply returned as the execution result of the request. These are easy.

Errors that occur asynchronously (e.g. in a background protocol handling thread) must be reported such that upper layers don't stay ignorant that something went wrong below and know that expected events will probably never happen. Handling of these errors is done as follows:

- driver (pn544) fails to deliver an incoming frame: it stores the error such that any subsequent call to the driver will result in this error. Then it calls the standard nfc_shdlc_recv_frame() with a NULL argument to report the problem above. shdlc stores a EREMOTEIO sticky status, which will trigger SMW to report above in turn.

- SMW is basically a background thread to handle incoming and outgoing shdlc frames. This thread will also check the shdlc sticky status and report to HCI when it discovers it is not able to run anymore because of an unrecoverable error that happened within shdlc or below. If the problem occurs during shdlc connection, the error is reported through the connect completion.

- HCI: if an internal HCI error happens (frame is lost), or HCI is reported an error from a lower layer, HCI will either complete the currently executing command with that error, or notify NFC Core directly if no command is executing.

- NFC Core: when NFC Core is notified of an error from below and polling is active, it will send a tag discovered event with an empty tag list to the user space to let it know that the poll operation will never be able to detect a tag. If polling is not active and the error was sticky, lower levels will return it at next invocation.

---

# Kernel driver for the NXP Semiconductors PN544 Near Field Communication chip

_Peios Kernel / Hardware and drivers / Driver development / NFC_

> The PN544 is an integrated transmission module for contactless communication. The driver goes under drives/nfc/ and is compiled as a module named "pn544".

<a id="rst-kernel-driver-for-the-nxp-semiconductors-pn544-near-field-communication-chip"></a>

<a id="rst-general"></a>

## General

The PN544 is an integrated transmission module for contactless communication. The driver goes under drives/nfc/ and is compiled as a module named "pn544".

Host Interfaces: I2C, SPI and HSU, this driver supports currently only I2C.

<a id="rst-protocols"></a>

## Protocols

In the normal (HCI) mode and in the firmware update mode read and write functions behave a bit differently because the message formats or the protocols are different.

In the normal (HCI) mode the protocol used is derived from the ETSI HCI specification. The firmware is updated using a specific protocol, which is different from HCI.

HCI messages consist of an eight bit header and the message body. The header contains the message length. Maximum size for an HCI message is 33. In HCI mode sent messages are tested for a correct checksum. Firmware update messages have the length in the second (MSB) and third (LSB) bytes of the message. The maximum FW message length is 1024 bytes.

For the ETSI HCI specification see [http://www.etsi.org/WebSite/Technologies/ProtocolSpecification.aspx](<http://www.etsi.org/WebSite/Technologies/ProtocolSpecification.aspx>)

---

# Non-Volatile Memory Device (NVDIMM)

_Peios Kernel / Hardware and drivers / Driver development / Persistent memory_

> Reference for Non-Volatile Memory Device (NVDIMM).

<a id="rst-non-volatile-memory-device-nvdimm"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [LIBNVDIMM: Non-Volatile Devices](</kernel/hardware/driver-api/nvdimm/nvdimm.md>)
- [BTT - Block Translation Table](</kernel/hardware/driver-api/nvdimm/btt.md>)
- [NVDIMM Security](</kernel/hardware/driver-api/nvdimm/security.md>)
- [NVDIMM Runtime Firmware Activation](</kernel/hardware/driver-api/nvdimm/firmware-activate.md>)

---

# BTT - Block Translation Table

_Peios Kernel / Hardware and drivers / Driver development / Persistent memory_

> Persistent memory based storage is able to perform IO at byte (or more accurately, cache line) granularity. However, we often want to expose such storage as traditional block devices. The block drivers for persistent memory will do exactly…

<a id="rst-btt-block-translation-table"></a>

<a id="rst-introduction"></a>

## 1. Introduction

Persistent memory based storage is able to perform IO at byte (or more accurately, cache line) granularity. However, we often want to expose such storage as traditional block devices. The block drivers for persistent memory will do exactly this. However, they do not provide any atomicity guarantees. Traditional SSDs typically provide protection against torn sectors in hardware, using stored energy in capacitors to complete in-flight block writes, or perhaps in firmware. We don't have this luxury with persistent memory - if a write is in progress, and we experience a power failure, the block will contain a mix of old and new data. Applications may not be prepared to handle such a scenario.

The Block Translation Table (BTT) provides atomic sector update semantics for persistent memory devices, so that applications that rely on sector writes not being torn can continue to do so. The BTT manifests itself as a stacked block device, and reserves a portion of the underlying storage for its metadata. At the heart of it, is an indirection table that re-maps all the blocks on the volume. It can be thought of as an extremely simple file system that only provides atomic sector updates.

<a id="rst-static-layout"></a>

## 2. Static Layout

The underlying storage on which a BTT can be laid out is not limited in any way. The BTT, however, splits the available space into chunks of up to 512 GiB, called "Arenas".

Each arena follows the same layout for its metadata, and all references in an arena are internal to it (with the exception of one field that points to the next arena). The following depicts the "On-disk" metadata layout:



```text
  Backing Store     +------->  Arena
+---------------+   |   +------------------+
|               |   |   | Arena info block |
|    Arena 0    +---+   |       4K         |
|     512G      |       +------------------+
|               |       |                  |
+---------------+       |                  |
|               |       |                  |
|    Arena 1    |       |   Data Blocks    |
|     512G      |       |                  |
|               |       |                  |
+---------------+       |                  |
|       .       |       |                  |
|       .       |       |                  |
|       .       |       |                  |
|               |       |                  |
|               |       |                  |
+---------------+       +------------------+
                        |                  |
                        |     BTT Map      |
                        |                  |
                        |                  |
                        +------------------+
                        |                  |
                        |     BTT Flog     |
                        |                  |
                        +------------------+
                        | Info block copy  |
                        |       4K         |
                        +------------------+
```

<a id="rst-theory-of-operation"></a>

## 3. Theory of Operation

<a id="rst-a-the-btt-map"></a>

### a. The BTT Map

The map is a simple lookup/indirection table that maps an LBA to an internal block. Each map entry is 32 bits. The two most significant bits are special flags, and the remaining form the internal block number.


<table>
<thead>
<tr>
<th>


Bit

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


31 - 30

</td>
<td>


Error and Zero flags - Used in the following way:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> 31
>
> </th>
> <th>
>
>
> 30
>
> </th>
> <th>
>
>
> Description
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> Initial state. Reads return zeroes; Premap = Postmap
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> Zero state: Reads return zeroes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> Error state: Reads fail; Writes clear 'E' bit
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> Normal Block – has valid postmap
>
> </td>
> </tr>
> </tbody>
> </table>

</td>
</tr>
<tr>
<td>


29 - 0

</td>
<td>


Mappings to internal 'postmap' blocks

</td>
</tr>
</tbody>
</table>

Some of the terminology that will be subsequently used:


<table>
<tbody>
<tr>
<td>


External LBA

</td>
<td>


LBA as made visible to upper layers.

</td>
</tr>
<tr>
<td>


ABA

</td>
<td>


Arena Block Address - Block offset/number within an arena

</td>
</tr>
<tr>
<td>


Premap ABA

</td>
<td>


The block offset into an arena, which was decided upon by range checking the External LBA

</td>
</tr>
<tr>
<td>


Postmap ABA

</td>
<td>


The block number in the "Data Blocks" area obtained after indirection from the map

</td>
</tr>
<tr>
<td>


nfree

</td>
<td>


The number of free blocks that are maintained at any given time. This is the number of concurrent writes that can happen to the arena.

</td>
</tr>
</tbody>
</table>

For example, after adding a BTT, we surface a disk of 1024G. We get a read for the external LBA at 768G. This falls into the second arena, and of the 512G worth of blocks that this arena contributes, this block is at 256G. Thus, the premap ABA is 256G. We now refer to the map, and find out the mapping for block 'X' (256G) points to block 'Y', say '64'. Thus the postmap ABA is 64.

<a id="rst-b-the-btt-flog"></a>

### b. The BTT Flog

The BTT provides sector atomicity by making every write an "allocating write", i.e. Every write goes to a "free" block. A running list of free blocks is maintained in the form of the BTT flog. 'Flog' is a combination of the words "free list" and "log". The flog contains 'nfree' entries, and an entry contains:


<table>
<tbody>
<tr>
<td>


lba

</td>
<td>


The premap ABA that is being written to

</td>
</tr>
<tr>
<td>


old_map

</td>
<td>


The old postmap ABA - after 'this' write completes, this will be a free block.

</td>
</tr>
<tr>
<td>


new_map

</td>
<td>


The new postmap ABA. The map will up updated to reflect this lba-&gt;postmap_aba mapping, but we log it here in case we have to recover.

</td>
</tr>
<tr>
<td>


seq

</td>
<td>


Sequence number to mark which of the 2 sections of this flog entry is valid/newest. It cycles between 01-&gt;10-&gt;11-&gt;01 (binary) under normal operation, with 00 indicating an uninitialized state.

</td>
</tr>
<tr>
<td>


lba'

</td>
<td>


alternate lba entry

</td>
</tr>
<tr>
<td>


old_map'

</td>
<td>


alternate old postmap entry

</td>
</tr>
<tr>
<td>


new_map'

</td>
<td>


alternate new postmap entry

</td>
</tr>
<tr>
<td>


seq'

</td>
<td>


alternate sequence number.

</td>
</tr>
</tbody>
</table>

Each of the above fields is 32-bit, making one entry 32 bytes. Entries are also padded to 64 bytes to avoid cache line sharing or aliasing. Flog updates are done such that for any entry being written, it: a. overwrites the 'old' section in the entry based on sequence numbers b. writes the 'new' section such that the sequence number is written last.

<a id="rst-c-the-concept-of-lanes"></a>

### c. The concept of lanes

While 'nfree' describes the number of concurrent IOs an arena can process concurrently, 'nlanes' is the number of IOs the BTT device as a whole can process:



```text
nlanes = min(nfree, num_cpus)
```

A lane number is obtained at the start of any IO, and is used for indexing into all the on-disk and in-memory data structures for the duration of the IO. If there are more CPUs than the max number of available lanes, than lanes are protected by spinlocks.

<a id="rst-d-in-memory-data-structure-read-tracking-table-rtt"></a>

### d. In-memory data structure: Read Tracking Table (RTT)

Consider a case where we have two threads, one doing reads and the other, writes. We can hit a condition where the writer thread grabs a free block to do a new IO, but the (slow) reader thread is still reading from it. In other words, the reader consulted a map entry, and started reading the corresponding block. A writer started writing to the same external LBA, and finished the write updating the map for that external LBA to point to its new postmap ABA. At this point the internal, postmap block that the reader is (still) reading has been inserted into the list of free blocks. If another write comes in for the same LBA, it can grab this free block, and start writing to it, causing the reader to read incorrect data. To prevent this, we introduce the RTT.

The RTT is a simple, per arena table with 'nfree' entries. Every reader inserts into rtt\[lane_number\], the postmap ABA it is reading, and clears it after the read is complete. Every writer thread, after grabbing a free block, checks the RTT for its presence. If the postmap free block is in the RTT, it waits till the reader clears the RTT entry, and only then starts writing to it.

<a id="rst-e-in-memory-data-structure-map-locks"></a>

### e. In-memory data structure: map locks

Consider a case where two writer threads are writing to the same LBA. There can be a race in the following sequence of steps:



```text
free[lane] = map[premap_aba]
map[premap_aba] = postmap_aba
```

Both threads can update their respective free\[lane\] with the same old, freed postmap_aba. This has made the layout inconsistent by losing a free entry, and at the same time, duplicating another free entry for two lanes.

To solve this, we could have a single map lock (per arena) that has to be taken before performing the above sequence, but we feel that could be too contentious. Instead we use an array of (nfree) map_locks that is indexed by (premap_aba modulo nfree).

<a id="rst-f-reconstruction-from-the-flog"></a>

### f. Reconstruction from the Flog

On startup, we analyze the BTT flog to create our list of free blocks. We walk through all the entries, and for each lane, of the set of two possible 'sections', we always look at the most recent one only (based on the sequence number). The reconstruction rules/steps are simple:

- Read map\[log_entry.lba\].

- If log_entry.new matches the map entry, then log_entry.old is free.

- If log_entry.new does not match the map entry, then log_entry.new is free. (This case can only be caused by power-fails/unsafe shutdowns)

<a id="rst-g-summarizing-read-and-write-flows"></a>

### g. Summarizing - Read and Write flows

Read:

1. Convert external LBA to arena number + pre-map ABA

2. Get a lane (and take lane_lock)

3. Read map to get the entry for this pre-map ABA

4. Enter post-map ABA into RTT\[lane\]

5. If TRIM flag set in map, return zeroes, and end IO (go to step 8)

6. If ERROR flag set in map, end IO with EIO (go to step 8)

7. Read data from this block

8. Remove post-map ABA entry from RTT\[lane\]

9. Release lane (and lane_lock)

Write:

1. Convert external LBA to Arena number + pre-map ABA

2. Get a lane (and take lane_lock)

3. Use lane to index into in-memory free list and obtain a new block, next flog index, next sequence number

4. Scan the RTT to check if free block is present, and spin/wait if it is.

5. Write data to this free block

6. Read map to get the existing post-map ABA entry for this pre-map ABA

7. Write flog entry: \[premap_aba / old postmap_aba / new postmap_aba / seq_num\]

8. Write new post-map ABA into map.

9. Write old post-map entry into the free list

10. Calculate next sequence number and write into the free list entry

11. Release lane (and lane_lock)

<a id="rst-error-handling"></a>

## 4. Error Handling

An arena would be in an error state if any of the metadata is corrupted irrecoverably, either due to a bug or a media error. The following conditions indicate an error:

- Info block checksum does not match (and recovering from the copy also fails)

- All internal available blocks are not uniquely and entirely addressed by the sum of mapped blocks and free blocks (from the BTT flog).

- Rebuilding free list from the flog reveals missing/duplicate/impossible entries

- A map entry is out of bounds

If any of these error conditions are encountered, the arena is put into a read only state using a flag in the info block.

<a id="rst-usage"></a>

## 5. Usage

The BTT can be set up on any disk (namespace) exposed by the libnvdimm subsystem (pmem, or blk mode). The easiest way to set up such a namespace is using the 'ndctl' utility \[1\]:

For example, the ndctl command line to setup a btt with a 4k sector size is:



```text
ndctl create-namespace -f -e namespace0.0 -m sector -l 4k
```

See ndctl create-namespace --help for more options.

\[1\]: [https://github.com/pmem/ndctl](<https://github.com/pmem/ndctl>)

---

# NVDIMM Runtime Firmware Activation

_Peios Kernel / Hardware and drivers / Driver development / Persistent memory_

> Some persistent memory devices run a firmware locally on the device / "DIMM" to perform tasks like media management, capacity provisioning, and health monitoring. The process of updating that firmware typically involves a reboot because it…

<a id="rst-nvdimm-runtime-firmware-activation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Some persistent memory devices run a firmware locally on the device / "DIMM" to perform tasks like media management, capacity provisioning, and health monitoring. The process of updating that firmware typically involves a reboot because it has implications for in-flight memory transactions. However, reboots are disruptive and at least the Intel persistent memory platform implementation, described by the Intel ACPI DSM specification \[1\], has added support for activating firmware at runtime.

A native sysfs interface is implemented in libnvdimm to allow platform to advertise and control their local runtime firmware activation capability.

The libnvdimm bus object, ndbusX, implements an ndbusX/firmware/activate attribute that shows the state of the firmware activation as one of 'idle', 'armed', 'overflow', and 'busy'.

- idle: No devices are set / armed to activate firmware

- armed: At least one device is armed

- busy: In the busy state armed devices are in the process of transitioning back to idle and completing an activation cycle.

- overflow: If the platform has a concept of incremental work needed to perform the activation it could be the case that too many DIMMs are armed for activation. In that scenario the potential for firmware activation to timeout is indicated by the 'overflow' state.

The 'ndbusX/firmware/activate' property can be written with a value of either 'live', or 'quiesce'. A value of 'quiesce' triggers the kernel to run firmware activation from within the equivalent of the hibernation 'freeze' state where drivers and applications are notified to stop their modifications of system memory. A value of 'live' attempts firmware activation without this hibernation cycle. The 'ndbusX/firmware/activate' property will be elided completely if no firmware activation capability is detected.

Another property 'ndbusX/firmware/capability' indicates a value of 'live' or 'quiesce', where 'live' indicates that the firmware does not require or inflict any quiesce period on the system to update firmware. A capability value of 'quiesce' indicates that firmware does expect and injects a quiet period for the memory controller, but 'live' may still be written to 'ndbusX/firmware/activate' as an override to assume the risk of racing firmware update with in-flight device and application activity. The 'ndbusX/firmware/capability' property will be elided completely if no firmware activation capability is detected.

The libnvdimm memory-device / DIMM object, nmemX, implements 'nmemX/firmware/activate' and 'nmemX/firmware/result' attributes to communicate the per-device firmware activation state. Similar to the 'ndbusX/firmware/activate' attribute, the 'nmemX/firmware/activate' attribute indicates 'idle', 'armed', or 'busy'. The state transitions from 'armed' to 'idle' when the system is prepared to activate firmware, firmware staged + state set to armed, and 'ndbusX/firmware/activate' is triggered. After that activation event the nmemX/firmware/result attribute reflects the state of the last activation as one of:

- none: No runtime activation triggered since the last time the device was reset

- success: The last runtime activation completed successfully.

- fail: The last runtime activation failed for device-specific reasons.

- not_staged: The last runtime activation failed due to a sequencing error of the firmware image not being staged.

- need_reset: Runtime firmware activation failed, but the firmware can still be activated via the legacy method of power-cycling the system.

\[1\]: [https://docs.pmem.io/persistent-memory/](<https://docs.pmem.io/persistent-memory/>)

---

# LIBNVDIMM: Non-Volatile Devices

_Peios Kernel / Hardware and drivers / Driver development / Persistent memory_

> libnvdimm - kernel / libndctl - userspace helper library

<a id="rst-libnvdimm-non-volatile-devices"></a>

libnvdimm - kernel / libndctl - userspace helper library

[nvdimm@lists.linux.dev](<mailto:nvdimm@lists.linux.dev>)

Version 13

<!-- contents:

Glossary
Overview
    Supporting Documents
    Git Trees
LIBNVDIMM PMEM
    PMEM-REGIONs, Atomic Sectors, and DAX
Example NVDIMM Platform
LIBNVDIMM Kernel Device Model and LIBNDCTL Userspace API
    LIBNDCTL: Context
        libndctl: instantiate a new library context example
    LIBNVDIMM/LIBNDCTL: Bus
        libnvdimm: control class device in /sys/class
        libnvdimm: bus
        libndctl: bus enumeration example
    LIBNVDIMM/LIBNDCTL: DIMM (NMEM)
        libnvdimm: DIMM (NMEM)
        libndctl: DIMM enumeration example
    LIBNVDIMM/LIBNDCTL: Region
        libnvdimm: region
        libndctl: region enumeration example
        Why Not Encode the Region Type into the Region Name?
        How Do I Determine the Major Type of a Region?
    LIBNVDIMM/LIBNDCTL: Namespace
        libnvdimm: namespace
        libndctl: namespace enumeration example
        libndctl: namespace creation example
        Why the Term "namespace"?
    LIBNVDIMM/LIBNDCTL: Block Translation Table "btt"
        libnvdimm: btt layout
        libndctl: btt creation example
Summary LIBNDCTL Diagram -->

<a id="rst-glossary"></a>

## Glossary

- **PMEM:**

  A system-physical-address range where writes are persistent.  A block device composed of PMEM is capable of DAX.  A PMEM address range may span an interleave of several DIMMs.

- **DPA:**

  DIMM Physical Address, is a DIMM-relative offset.  With one DIMM in the system there would be a 1:1 system-physical-address:DPA association. Once more DIMMs are added a memory controller interleave must be decoded to determine the DPA associated with a given system-physical-address.

- **DAX:**

  File system extensions to bypass the page cache and block layer to mmap persistent memory, from a PMEM block device, directly into a process address space.

- **DSM:**

  Device Specific Method: ACPI method to control specific device - in this case the firmware.

- **DCR:**

  NVDIMM Control Region Structure defined in ACPI 6 Section 5.2.25.5. It defines a vendor-id, device-id, and interface format for a given DIMM.

- **BTT:**

  Block Translation Table: Persistent memory is byte addressable. Existing software may have an expectation that the power-fail-atomicity of writes is at least one sector, 512 bytes.  The BTT is an indirection table with atomic update semantics to front a PMEM block device driver and present arbitrary atomic sector sizes.

- **LABEL:**

  Metadata stored on a DIMM device that partitions and identifies (persistently names) capacity allocated to different PMEM namespaces. It also indicates whether an address abstraction like a BTT is applied to the namespace.  Note that traditional partition tables, GPT/MBR, are layered on top of a PMEM namespace, or an address abstraction like BTT if present, but partition support is deprecated going forward.

<a id="rst-overview"></a>

## Overview

The LIBNVDIMM subsystem provides support for PMEM described by platform firmware or a device driver. On ACPI based systems the platform firmware conveys persistent memory resource via the ACPI NFIT "NVDIMM Firmware Interface Table" in ACPI 6. While the LIBNVDIMM subsystem implementation is generic and supports pre-NFIT platforms, it was guided by the superset of capabilities need to support this ACPI 6 definition for NVDIMM resources. The original implementation supported the block-window-aperture capability described in the NFIT, but that support has since been abandoned and never shipped in a product.

<a id="rst-supporting-documents"></a>

### Supporting Documents

- **ACPI 6:**

  [https://www.uefi.org/sites/default/files/resources/ACPI_6.0.pdf](<https://www.uefi.org/sites/default/files/resources/ACPI_6.0.pdf>)

- **NVDIMM Namespace:**

  [https://pmem.io/documents/NVDIMM_Namespace_Spec.pdf](<https://pmem.io/documents/NVDIMM_Namespace_Spec.pdf>)

- **DSM Interface Example:**

  [https://pmem.io/documents/NVDIMM_DSM_Interface_Example.pdf](<https://pmem.io/documents/NVDIMM_DSM_Interface_Example.pdf>)

- **Driver Writer's Guide:**

  [https://pmem.io/documents/NVDIMM_Driver_Writers_Guide.pdf](<https://pmem.io/documents/NVDIMM_Driver_Writers_Guide.pdf>)

<a id="rst-git-trees"></a>

### Git Trees

- **LIBNVDIMM:**

  [https://git.kernel.org/cgit/linux/kernel/git/nvdimm/nvdimm.git](<https://git.kernel.org/cgit/linux/kernel/git/nvdimm/nvdimm.git>)

- **LIBNDCTL:**

  [https://github.com/pmem/ndctl.git](<https://github.com/pmem/ndctl.git>)

<a id="rst-libnvdimm-pmem"></a>

## LIBNVDIMM PMEM

Prior to the arrival of the NFIT, non-volatile memory was described to a system in various ad-hoc ways.  Usually only the bare minimum was provided, namely, a single system-physical-address range where writes are expected to be durable after a system power loss.  Now, the NFIT specification standardizes not only the description of PMEM, but also platform message-passing entry points for control and configuration.

PMEM (nd_pmem.ko): Drives a system-physical-address range.  This range is contiguous in system memory and may be interleaved (hardware memory controller striped) across multiple DIMMs.  When interleaved the platform may optionally provide details of which DIMMs are participating in the interleave.

It is worth noting that when the labeling capability is detected (a EFI namespace label index block is found), then no block device is created by default as userspace needs to do at least one allocation of DPA to the PMEM range.  In contrast ND_NAMESPACE_IO ranges, once registered, can be immediately attached to nd_pmem. This latter mode is called label-less or "legacy".

<a id="rst-pmem-regions-atomic-sectors-and-dax"></a>

### PMEM-REGIONs, Atomic Sectors, and DAX

For the cases where an application or filesystem still needs atomic sector update guarantees it can register a BTT on a PMEM device or partition.  See LIBNVDIMM/NDCTL: Block Translation Table "btt"

<a id="rst-example-nvdimm-platform"></a>

## Example NVDIMM Platform

For the remainder of this document the following diagram will be referenced for any example sysfs layouts:



```text
                             (a)               (b)           DIMM
          +-------------------+--------+--------+--------+
+------+  |       pm0.0       |  free  | pm1.0  |  free  |    0
| imc0 +--+- - - region0- - - +--------+        +--------+
+--+---+  |       pm0.0       |  free  | pm1.0  |  free  |    1
   |      +-------------------+--------v        v--------+
+--+---+                               |                 |
| cpu0 |                                     region1
+--+---+                               |                 |
   |      +----------------------------^        ^--------+
+--+---+  |           free             | pm1.0  |  free  |    2
| imc1 +--+----------------------------|        +--------+
+------+  |           free             | pm1.0  |  free  |    3
          +----------------------------+--------+--------+
```

In this platform we have four DIMMs and two memory controllers in one socket.  Each PMEM interleave set is identified by a region device with a dynamically assigned id.

> 1. The first portion of DIMM0 and DIMM1 are interleaved as REGION0. A single PMEM namespace is created in the REGION0-SPA-range that spans most of DIMM0 and DIMM1 with a user-specified name of "pm0.0". Some of that interleaved system-physical-address range is left free for another PMEM namespace to be defined.
>
> 2. In the last portion of DIMM0 and DIMM1 we have an interleaved system-physical-address range, REGION1, that spans those two DIMMs as well as DIMM2 and DIMM3.  Some of REGION1 is allocated to a PMEM namespace named "pm1.0".
>
> This bus is provided by the kernel under the device /sys/devices/platform/nfit_test.0 when the nfit_test.ko module from tools/testing/nvdimm is loaded. This module is a unit test for LIBNVDIMM and the  acpi_nfit.ko driver.

<a id="rst-libnvdimm-kernel-device-model-and-libndctl-userspace-api"></a>

## LIBNVDIMM Kernel Device Model and LIBNDCTL Userspace API

What follows is a description of the LIBNVDIMM sysfs layout and a corresponding object hierarchy diagram as viewed through the LIBNDCTL API.  The example sysfs paths and diagrams are relative to the Example NVDIMM Platform which is also the LIBNVDIMM bus used in the LIBNDCTL unit test.

<a id="rst-libndctl-context"></a>

### LIBNDCTL: Context

Every API call in the LIBNDCTL library requires a context that holds the logging parameters and other library instance state.  The library is based on the libabc template:

> [https://git.kernel.org/cgit/linux/kernel/git/kay/libabc.git](<https://git.kernel.org/cgit/linux/kernel/git/kay/libabc.git>)

<a id="rst-libndctl-instantiate-a-new-library-context-example"></a>

#### LIBNDCTL: instantiate a new library context example



```text
struct ndctl_ctx *ctx;

if (ndctl_new(&ctx) == 0)
        return ctx;
else
        return NULL;
```

<a id="rst-libnvdimm-libndctl-bus"></a>

### LIBNVDIMM/LIBNDCTL: Bus

A bus has a 1:1 relationship with an NFIT.  The current expectation for ACPI based systems is that there is only ever one platform-global NFIT. That said, it is trivial to register multiple NFITs, the specification does not preclude it.  The infrastructure supports multiple buses and we use this capability to test multiple NFIT configurations in the unit test.

<a id="rst-libnvdimm-control-class-device-in-sys-class"></a>

### LIBNVDIMM: control class device in /sys/class

This character device accepts DSM messages to be passed to DIMM identified by its NFIT handle:



```text
/sys/class/nd/ndctl0
|-- dev
|-- device -> ../../../ndbus0
|-- subsystem -> ../../../../../../../class/nd
```

<a id="rst-libnvdimm-bus"></a>

### LIBNVDIMM: bus



```text
struct nvdimm_bus *nvdimm_bus_register(struct device *parent,
       struct nvdimm_bus_descriptor *nfit_desc);
```



```text
/sys/devices/platform/nfit_test.0/ndbus0
|-- commands
|-- nd
|-- nfit
|-- nmem0
|-- nmem1
|-- nmem2
|-- nmem3
|-- power
|-- provider
|-- region0
|-- region1
|-- region2
|-- region3
|-- region4
|-- region5
|-- uevent
`-- wait_probe
```

<a id="rst-libndctl-bus-enumeration-example"></a>

#### LIBNDCTL: bus enumeration example

Find the bus handle that describes the bus from Example NVDIMM Platform:



```text
static struct ndctl_bus *get_bus_by_provider(struct ndctl_ctx *ctx,
                const char *provider)
{
        struct ndctl_bus *bus;

        ndctl_bus_foreach(ctx, bus)
                if (strcmp(provider, ndctl_bus_get_provider(bus)) == 0)
                        return bus;

        return NULL;
}

bus = get_bus_by_provider(ctx, "nfit_test.0");
```

<a id="rst-libnvdimm-libndctl-dimm-nmem"></a>

### LIBNVDIMM/LIBNDCTL: DIMM (NMEM)

The DIMM device provides a character device for sending commands to hardware, and it is a container for LABELs.  If the DIMM is defined by NFIT then an optional 'nfit' attribute sub-directory is available to add NFIT-specifics.

Note that the kernel device name for "DIMMs" is "nmemX".  The NFIT describes these devices via "Memory Device to System Physical Address Range Mapping Structure", and there is no requirement that they actually be physical DIMMs, so we use a more generic name.

<a id="rst-libnvdimm-dimm-nmem"></a>

#### LIBNVDIMM: DIMM (NMEM)



```text
struct nvdimm *nvdimm_create(struct nvdimm_bus *nvdimm_bus, void *provider_data,
                const struct attribute_group **groups, unsigned long flags,
                unsigned long *dsm_mask);
```



```text
/sys/devices/platform/nfit_test.0/ndbus0
|-- nmem0
|   |-- available_slots
|   |-- commands
|   |-- dev
|   |-- devtype
|   |-- driver -> ../../../../../bus/nd/drivers/nvdimm
|   |-- modalias
|   |-- nfit
|   |   |-- device
|   |   |-- format
|   |   |-- handle
|   |   |-- phys_id
|   |   |-- rev_id
|   |   |-- serial
|   |   `-- vendor
|   |-- state
|   |-- subsystem -> ../../../../../bus/nd
|   `-- uevent
|-- nmem1
[..]
```

<a id="rst-libndctl-dimm-enumeration-example"></a>

#### LIBNDCTL: DIMM enumeration example

Note, in this example we are assuming NFIT-defined DIMMs which are identified by an "nfit_handle" a 32-bit value where:

> - Bit 3:0 DIMM number within the memory channel
>
> - Bit 7:4 memory channel number
>
> - Bit 11:8 memory controller ID
>
> - Bit 15:12 socket ID (within scope of a Node controller if node controller is present)
>
> - Bit 27:16 Node Controller ID
>
> - Bit 31:28 Reserved



```text
static struct ndctl_dimm *get_dimm_by_handle(struct ndctl_bus *bus,
       unsigned int handle)
{
        struct ndctl_dimm *dimm;

        ndctl_dimm_foreach(bus, dimm)
                if (ndctl_dimm_get_handle(dimm) == handle)
                        return dimm;

        return NULL;
}

#define DIMM_HANDLE(n, s, i, c, d) \
        (((n & 0xfff) << 16) | ((s & 0xf) << 12) | ((i & 0xf) << 8) \
         | ((c & 0xf) << 4) | (d & 0xf))

dimm = get_dimm_by_handle(bus, DIMM_HANDLE(0, 0, 0, 0, 0));
```

<a id="rst-libnvdimm-libndctl-region"></a>

### LIBNVDIMM/LIBNDCTL: Region

A generic REGION device is registered for each PMEM interleave-set / range. Per the example there are 2 PMEM regions on the "nfit_test.0" bus. The primary role of regions are to be a container of "mappings".  A mapping is a tuple of &lt;DIMM, DPA-start-offset, length&gt;.

LIBNVDIMM provides a built-in driver for REGION devices.  This driver is responsible for all parsing LABELs, if present, and then emitting NAMESPACE devices for the nd_pmem driver to consume.

In addition to the generic attributes of "mapping"s, "interleave_ways" and "size" the REGION device also exports some convenience attributes. "nstype" indicates the integer type of namespace-device this region emits, "devtype" duplicates the DEVTYPE variable stored by udev at the 'add' event, "modalias" duplicates the MODALIAS variable stored by udev at the 'add' event, and finally, the optional "spa_index" is provided in the case where the region is defined by a SPA.

LIBNVDIMM: region:



```text
struct nd_region *nvdimm_pmem_region_create(struct nvdimm_bus *nvdimm_bus,
                struct nd_region_desc *ndr_desc);
```



```text
/sys/devices/platform/nfit_test.0/ndbus0
|-- region0
|   |-- available_size
|   |-- btt0
|   |-- btt_seed
|   |-- devtype
|   |-- driver -> ../../../../../bus/nd/drivers/nd_region
|   |-- init_namespaces
|   |-- mapping0
|   |-- mapping1
|   |-- mappings
|   |-- modalias
|   |-- namespace0.0
|   |-- namespace_seed
|   |-- numa_node
|   |-- nfit
|   |   `-- spa_index
|   |-- nstype
|   |-- set_cookie
|   |-- size
|   |-- subsystem -> ../../../../../bus/nd
|   `-- uevent
|-- region1
[..]
```

<a id="rst-libndctl-region-enumeration-example"></a>

#### LIBNDCTL: region enumeration example

Sample region retrieval routines based on NFIT-unique data like "spa_index" (interleave set id).



```text
static struct ndctl_region *get_pmem_region_by_spa_index(struct ndctl_bus *bus,
                unsigned int spa_index)
{
        struct ndctl_region *region;

        ndctl_region_foreach(bus, region) {
                if (ndctl_region_get_type(region) != ND_DEVICE_REGION_PMEM)
                        continue;
                if (ndctl_region_get_spa_index(region) == spa_index)
                        return region;
        }
        return NULL;
}
```

<a id="rst-libnvdimm-libndctl-namespace"></a>

### LIBNVDIMM/LIBNDCTL: Namespace

A REGION, after resolving DPA aliasing and LABEL specified boundaries, surfaces one or more "namespace" devices.  The arrival of a "namespace" device currently triggers the nd_pmem driver to load and register a disk/block device.

<a id="rst-libnvdimm-namespace"></a>

#### LIBNVDIMM: namespace

Here is a sample layout from the 2 major types of NAMESPACE where namespace0.0 represents DIMM-info-backed PMEM (note that it has a 'uuid' attribute), and namespace1.0 represents an anonymous PMEM namespace (note that has no 'uuid' attribute due to not support a LABEL)



```text
/sys/devices/platform/nfit_test.0/ndbus0/region0/namespace0.0
|-- alt_name
|-- devtype
|-- dpa_extents
|-- force_raw
|-- modalias
|-- numa_node
|-- resource
|-- size
|-- subsystem -> ../../../../../../bus/nd
|-- type
|-- uevent
`-- uuid
/sys/devices/platform/nfit_test.1/ndbus1/region1/namespace1.0
|-- block
|   `-- pmem0
|-- devtype
|-- driver -> ../../../../../../bus/nd/drivers/pmem
|-- force_raw
|-- modalias
|-- numa_node
|-- resource
|-- size
|-- subsystem -> ../../../../../../bus/nd
|-- type
`-- uevent
```

<a id="rst-libndctl-namespace-enumeration-example"></a>

#### LIBNDCTL: namespace enumeration example

Namespaces are indexed relative to their parent region, example below. These indexes are mostly static from boot to boot, but subsystem makes no guarantees in this regard.  For a static namespace identifier use its 'uuid' attribute.



```text
static struct ndctl_namespace
*get_namespace_by_id(struct ndctl_region *region, unsigned int id)
{
        struct ndctl_namespace *ndns;

        ndctl_namespace_foreach(region, ndns)
                if (ndctl_namespace_get_id(ndns) == id)
                        return ndns;

        return NULL;
}
```

<a id="rst-libndctl-namespace-creation-example"></a>

#### LIBNDCTL: namespace creation example

Idle namespaces are automatically created by the kernel if a given region has enough available capacity to create a new namespace. Namespace instantiation involves finding an idle namespace and configuring it.  For the most part the setting of namespace attributes can occur in any order, the only constraint is that 'uuid' must be set before 'size'.  This enables the kernel to track DPA allocations internally with a static identifier:



```text
static int configure_namespace(struct ndctl_region *region,
                struct ndctl_namespace *ndns,
                struct namespace_parameters *parameters)
{
        char devname[50];

        snprintf(devname, sizeof(devname), "namespace%d.%d",
                        ndctl_region_get_id(region), parameters->id);

        ndctl_namespace_set_alt_name(ndns, devname);
        /* 'uuid' must be set prior to setting size! */
        ndctl_namespace_set_uuid(ndns, parameters->uuid);
        ndctl_namespace_set_size(ndns, parameters->size);
        /* unlike pmem namespaces, blk namespaces have a sector size */
        if (parameters->lbasize)
                ndctl_namespace_set_sector_size(ndns, parameters->lbasize);
        ndctl_namespace_enable(ndns);
}
```

<a id="rst-why-the-term-namespace"></a>

#### Why the Term "namespace"?

> 1. Why not "volume" for instance?  "volume" ran the risk of confusing ND (libnvdimm subsystem) to a volume manager like device-mapper.
>
> 2. The term originated to describe the sub-devices that can be created within a NVME controller (see the nvme specification: [https://www.nvmexpress.org/specifications/](<https://www.nvmexpress.org/specifications/>)), and NFIT namespaces are meant to parallel the capabilities and configurability of NVME-namespaces.

<a id="rst-libnvdimm-libndctl-block-translation-table-btt"></a>

### LIBNVDIMM/LIBNDCTL: Block Translation Table "btt"

A BTT (design document: [https://pmem.io/2014/09/23/btt.html](<https://pmem.io/2014/09/23/btt.html>)) is a personality driver for a namespace that fronts entire namespace as an 'address abstraction'.

<a id="rst-libnvdimm-btt-layout"></a>

#### LIBNVDIMM: btt layout

Every region will start out with at least one BTT device which is the seed device.  To activate it set the "namespace", "uuid", and "sector_size" attributes and then bind the device to the nd_pmem or nd_blk driver depending on the region type:



```text
/sys/devices/platform/nfit_test.1/ndbus0/region0/btt0/
|-- namespace
|-- delete
|-- devtype
|-- modalias
|-- numa_node
|-- sector_size
|-- subsystem -> ../../../../../bus/nd
|-- uevent
`-- uuid
```

<a id="rst-libndctl-btt-creation-example"></a>

#### LIBNDCTL: btt creation example

Similar to namespaces an idle BTT device is automatically created per region.  Each time this "seed" btt device is configured and enabled a new seed is created.  Creating a BTT configuration involves two steps of finding and idle BTT and assigning it to consume a namespace.



```text
static struct ndctl_btt *get_idle_btt(struct ndctl_region *region)
{
        struct ndctl_btt *btt;

        ndctl_btt_foreach(region, btt)
                if (!ndctl_btt_is_enabled(btt)
                                && !ndctl_btt_is_configured(btt))
                        return btt;

        return NULL;
}

static int configure_btt(struct ndctl_region *region,
                struct btt_parameters *parameters)
{
        btt = get_idle_btt(region);

        ndctl_btt_set_uuid(btt, parameters->uuid);
        ndctl_btt_set_sector_size(btt, parameters->sector_size);
        ndctl_btt_set_namespace(btt, parameters->ndns);
        /* turn off raw mode device */
        ndctl_namespace_disable(parameters->ndns);
        /* turn on btt access */
        ndctl_btt_enable(btt);
}
```

Once instantiated a new inactive btt seed device will appear underneath the region.

Once a "namespace" is removed from a BTT that instance of the BTT device will be deleted or otherwise reset to default values.  This deletion is only at the device model level.  In order to destroy a BTT the "info block" needs to be destroyed.  Note, that to destroy a BTT the media needs to be written in raw mode.  By default, the kernel will autodetect the presence of a BTT and disable raw mode.  This autodetect behavior can be suppressed by enabling raw mode for the namespace via the ndctl_namespace_set_raw_mode() API.

<a id="rst-summary-libndctl-diagram"></a>

### Summary LIBNDCTL Diagram

For the given example above, here is the view of the objects as seen by the LIBNDCTL API:



```text
            +---+
            |CTX|
            +-+-+
              |
+-------+     |
| DIMM0 <-+   |      +---------+   +--------------+  +---------------+
+-------+ |   |    +-> REGION0 +---> NAMESPACE0.0 +--> PMEM8 "pm0.0" |
| DIMM1 <-+ +-v--+ | +---------+   +--------------+  +---------------+
+-------+ +-+BUS0+-| +---------+   +--------------+  +----------------------+
| DIMM2 <-+ +----+ +-> REGION1 +---> NAMESPACE1.0 +--> PMEM6 "pm1.0" | BTT1 |
+-------+ |        | +---------+   +--------------+  +---------------+------+
| DIMM3 <-+
+-------+
```

---

# NVDIMM Security

_Peios Kernel / Hardware and drivers / Driver development / Persistent memory_

> With the introduction of Intel Device Specific Methods (DSM) v1.8 specification [1], security DSMs are introduced. The spec added the following security DSMs: "get security state", "set passphrase", "disable passphrase", "unlock unit",…

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-nvdimm-security"></a>

<a id="rst-introduction"></a>

## 1. Introduction

With the introduction of Intel Device Specific Methods (DSM) v1.8 specification \[1\], security DSMs are introduced. The spec added the following security DSMs: "get security state", "set passphrase", "disable passphrase", "unlock unit", "freeze lock", "secure erase", and "overwrite". A security_ops data structure has been added to struct dimm in order to support the security operations and generic APIs are exposed to allow vendor neutral operations.

<a id="rst-sysfs-interface"></a>

## 2. Sysfs Interface

The "security" sysfs attribute is provided in the nvdimm sysfs directory. For example: /sys/devices/LNXSYSTM:00/LNXSYBUS:00/ACPI0012:00/ndbus0/nmem0/security

The "show" attribute of that attribute will display the security state for that DIMM. The following states are available: disabled, unlocked, locked, frozen, and overwrite. If security is not supported, the sysfs attribute will not be visible.

The "store" attribute takes several commands when it is being written to in order to support some of the security functionalities: update &lt;old_keyid&gt; &lt;new_keyid&gt; - enable or update passphrase. disable &lt;keyid&gt; - disable enabled security and remove key. freeze - freeze changing of security states. erase &lt;keyid&gt; - delete existing user encryption key. overwrite &lt;keyid&gt; - wipe the entire nvdimm. master_update &lt;keyid&gt; &lt;new_keyid&gt; - enable or update master passphrase. master_erase &lt;keyid&gt; - delete existing user encryption key.

<a id="rst-key-management"></a>

## 3. Key Management

The key is associated to the payload by the DIMM id. For example: \# cat /sys/devices/LNXSYSTM:00/LNXSYBUS:00/ACPI0012:00/ndbus0/nmem0/nfit/id 8089-a2-1740-00000133 The DIMM id would be provided along with the key payload (passphrase) to the kernel.

The security keys are managed on the basis of a single key per DIMM. The key "passphrase" is expected to be 32bytes long. This is similar to the ATA security specification \[2\]. A key is initially acquired via the request_key() kernel API call during nvdimm unlock. It is up to the user to make sure that all the keys are in the kernel user keyring for unlock.

A nvdimm encrypted-key of format enc32 has the description format of: nvdimm:&lt;bus-provider-specific-unique-id&gt;

See file `Documentation/security/keys/trusted-encrypted.rst` for creating encrypted-keys of enc32 format. TPM usage with a master trusted key is preferred for sealing the encrypted-keys.

<a id="rst-unlocking"></a>

## 4. Unlocking

When the DIMMs are being enumerated by the kernel, the kernel will attempt to retrieve the key from the kernel user keyring. This is the only time a locked DIMM can be unlocked. Once unlocked, the DIMM will remain unlocked until reboot. Typically an entity (i.e. shell script) will inject all the relevant encrypted-keys into the kernel user keyring during the initramfs phase. This provides the unlock function access to all the related keys that contain the passphrase for the respective nvdimms.  It is also recommended that the keys are injected before libnvdimm is loaded by modprobe.

<a id="rst-update"></a>

## 5. Update

When doing an update, it is expected that the existing key is removed from the kernel user keyring and reinjected as different (old) key. It's irrelevant what the key description is for the old key since we are only interested in the keyid when doing the update operation. It is also expected that the new key is injected with the description format described from earlier in this document.  The update command written to the sysfs attribute will be with the format: update &lt;old keyid&gt; &lt;new keyid&gt;

If there is no old keyid due to a security enabling, then a 0 should be passed in.

<a id="rst-freeze"></a>

## 6. Freeze

The freeze operation does not require any keys. The security config can be frozen by a user with root privilege.

<a id="rst-disable"></a>

## 7. Disable

The security disable command format is: disable &lt;keyid&gt;

An key with the current passphrase payload that is tied to the nvdimm should be in the kernel user keyring.

<a id="rst-secure-erase"></a>

## 8. Secure Erase

The command format for doing a secure erase is: erase &lt;keyid&gt;

An key with the current passphrase payload that is tied to the nvdimm should be in the kernel user keyring.

<a id="rst-overwrite"></a>

## 9. Overwrite

The command format for doing an overwrite is: overwrite &lt;keyid&gt;

Overwrite can be done without a key if security is not enabled. A key serial of 0 can be passed in to indicate no key.

The sysfs attribute "security" can be polled to wait on overwrite completion. Overwrite can last tens of minutes or more depending on nvdimm size.

An encrypted-key with the current user passphrase that is tied to the nvdimm should be injected and its keyid should be passed in via sysfs.

<a id="rst-master-update"></a>

## 10. Master Update

The command format for doing a master update is: update &lt;old keyid&gt; &lt;new keyid&gt;

The operating mechanism for master update is identical to update except the master passphrase key is passed to the kernel. The master passphrase key is just another encrypted-key.

This command is only available when security is disabled.

<a id="rst-master-erase"></a>

## 11. Master Erase

The command format for doing a master erase is: master_erase &lt;current keyid&gt;

This command has the same operating mechanism as erase except the master passphrase key is passed to the kernel. The master passphrase key is just another encrypted-key.

This command is only available when the master security is enabled, indicated by the extended security status.

\[1\]: [https://pmem.io/documents/NVDIMM_DSM_Interface-V1.8.pdf](<https://pmem.io/documents/NVDIMM_DSM_Interface-V1.8.pdf>)

\[2\]: [http://www.t13.org/documents/UploadedDocuments/docs2006/e05179r4-ACS-SecurityClarifications.pdf](<http://www.t13.org/documents/UploadedDocuments/docs2006/e05179r4-ACS-SecurityClarifications.pdf>)

---

# The Linux PCI driver implementer's API guide

_Peios Kernel / Hardware and drivers / Driver development / PCI_

> Reference for The Linux PCI driver implementer's API guide.

<a id="rst-the-linux-pci-driver-implementer-s-api-guide"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Table of contents**

- [PCI Support Library](</kernel/hardware/driver-api/pci/pci.md>)
- [PCI Peer-to-Peer DMA Support](</kernel/hardware/driver-api/pci/p2pdma.md>)
- [PCI Trusted Execution Environment Security Manager (TSM)](</kernel/hardware/driver-api/pci/tsm.md>)

---

# PCI Peer-to-Peer DMA Support

_Peios Kernel / Hardware and drivers / Driver development / PCI_

> The PCI bus has pretty decent support for performing DMA transfers between two devices on the bus. This type of transaction is henceforth called Peer-to-Peer (or P2P). However, there are a number of issues that make P2P transactions tricky…

<a id="rst-pci-peer-to-peer-dma-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The PCI bus has pretty decent support for performing DMA transfers between two devices on the bus. This type of transaction is henceforth called Peer-to-Peer (or P2P). However, there are a number of issues that make P2P transactions tricky to do in a perfectly safe way.

For PCIe the routing of Transaction Layer Packets (TLPs) is well-defined up until they reach a host bridge or root port. If the path includes PCIe switches then based on the ACS settings the transaction can route entirely within the PCIe hierarchy and never reach the root port. The kernel will evaluate the PCIe topology and always permit P2P in these well-defined cases.

However, if the P2P transaction reaches the host bridge then it might have to hairpin back out the same root port, be routed inside the CPU SOC to another PCIe root port, or routed internally to the SOC.

The PCIe specification doesn't define the forwarding of transactions between hierarchy domains and kernel defaults to blocking such routing. There is an allow list to allow detecting known-good HW, in which case P2P between any two PCIe devices will be permitted.

Since P2P inherently is doing transactions between two devices it requires two drivers to be co-operating inside the kernel. The providing driver has to convey its MMIO to the consuming driver. To meet the driver model lifecycle rules the MMIO must have all DMA mapping removed, all CPU accesses prevented, all page table mappings undone before the providing driver completes remove().

This requires the providing and consuming driver to actively work together to guarantee that the consuming driver has stopped using the MMIO during a removal cycle. This is done by either a synchronous invalidation shutdown or waiting for all usage refcounts to reach zero.

At the lowest level the P2P subsystem offers a naked struct p2p_provider that delegates lifecycle management to the providing driver. It is expected that drivers using this option will wrap their MMIO memory in DMABUF and use DMABUF to provide an invalidation shutdown. These MMIO addresess have no struct page, and if used with mmap() must create special PTEs. As such there are very few kernel uAPIs that can accept pointers to them; in particular they cannot be used with read()/write(), including O_DIRECT.

Building on this, the subsystem offers a layer to wrap the MMIO in a ZONE_DEVICE pgmap of MEMORY_DEVICE_PCI_P2PDMA to create struct pages. The lifecycle of pgmap ensures that when the pgmap is destroyed all other drivers have stopped using the MMIO. This option works with O_DIRECT flows, in some cases, if the underlying subsystem supports handling MEMORY_DEVICE_PCI_P2PDMA through FOLL_PCI_P2PDMA. The use of FOLL_LONGTERM is prevented. As this relies on pgmap it also relies on architecture support along with alignment and minimum size limitations.

<a id="rst-driver-writer-s-guide"></a>

## Driver Writer's Guide

In a given P2P implementation there may be three or more different types of kernel drivers in play:

- Provider - A driver which provides or publishes P2P resources like memory or doorbell registers to other drivers.

- Client - A driver which makes use of a resource by setting up a DMA transaction to or from it.

- Orchestrator - A driver which orchestrates the flow of data between clients and providers.

In many cases there could be overlap between these three types (i.e., it may be typical for a driver to be both a provider and a client).

For example, in the NVMe Target Copy Offload implementation:

- The NVMe PCI driver is both a client, provider and orchestrator in that it exposes any CMB (Controller Memory Buffer) as a P2P memory resource (provider), it accepts P2P memory pages as buffers in requests to be used directly (client) and it can also make use of the CMB as submission queue entries (orchestrator).

- The RDMA driver is a client in this arrangement so that an RNIC can DMA directly to the memory exposed by the NVMe device.

- The NVMe Target driver (nvmet) can orchestrate the data from the RNIC to the P2P memory (CMB) and then to the NVMe device (and vice versa).

This is currently the only arrangement supported by the kernel but one could imagine slight tweaks to this that would allow for the same functionality. For example, if a specific RNIC added a BAR with some memory behind it, its driver could add support as a P2P provider and then the NVMe Target could use the RNIC's memory instead of the CMB in cases where the NVMe cards in use do not have CMB support.

<a id="rst-provider-drivers"></a>

### Provider Drivers

A provider simply needs to register a BAR (or a portion of a BAR) as a P2P DMA resource using `pci_p2pdma_add_resource()`. This will register struct pages for all the specified memory.

After that it may optionally publish all of its resources as P2P memory using `pci_p2pmem_publish()`. This will allow any orchestrator drivers to find and use the memory. When marked in this way, the resource must be regular memory with no side effects.

For the time being this is fairly rudimentary in that all resources are typically going to be P2P memory. Future work will likely expand this to include other types of resources like doorbells.

<a id="rst-client-drivers"></a>

### Client Drivers

A client driver only has to use the mapping API `dma_map_sg()` and `dma_unmap_sg()` functions as usual, and the implementation will do the right thing for the P2P capable memory.

<a id="rst-orchestrator-drivers"></a>

### Orchestrator Drivers

The first task an orchestrator driver must do is compile a list of all client devices that will be involved in a given transaction. For example, the NVMe Target driver creates a list including the namespace block device and the RNIC in use. If the orchestrator has access to a specific P2P provider to use it may check compatibility using `pci_p2pdma_distance()` otherwise it may find a memory provider that's compatible with all clients using  `pci_p2pmem_find()`. If more than one provider is supported, the one nearest to all the clients will be chosen first. If more than one provider is an equal distance away, the one returned will be chosen at random (it is not an arbitrary but truly random). This function returns the PCI device to use for the provider with a reference taken and therefore when it's no longer needed it should be returned with pci_dev_put().

Once a provider is selected, the orchestrator can then use `pci_alloc_p2pmem()` and `pci_free_p2pmem()` to allocate P2P memory from the provider. `pci_p2pmem_alloc_sgl()` and `pci_p2pmem_free_sgl()` are convenience functions for allocating scatter-gather lists with P2P memory.

<a id="rst-struct-page-caveats"></a>

### Struct Page Caveats

While the MEMORY_DEVICE_PCI_P2PDMA pages can be installed in VMAs, pin_user_pages() and related will not return them unless FOLL_PCI_P2PDMA is set.

The MEMORY_DEVICE_PCI_P2PDMA pages require care to support in the kernel. The KVA is still MMIO and must still be accessed through the normal readX()/writeX()/etc helpers. Direct CPU access (e.g. memcpy) is forbidden, just like any other MMIO mapping. While this will actually work on some architectures, others will experience corruption or just crash in the kernel. Supporting FOLL_PCI_P2PDMA in a subsystem requires scrubbing it to ensure no CPU access happens.

<a id="rst-usage-with-dmabuf"></a>

## Usage With DMABUF

DMABUF provides an alternative to the above struct page-based client/provider/orchestrator system and should be used when struct page doesn't exist. In this mode the exporting driver will wrap some of its MMIO in a DMABUF and give the DMABUF FD to userspace.

Userspace can then pass the FD to an importing driver which will ask the exporting driver to map it to the importer.

In this case the initiator and target pci_devices are known and the P2P subsystem is used to determine the mapping type. The phys_addr_t-based DMA API is used to establish the dma_addr_t.

Lifecycle is controlled by DMABUF move_notify(). When the exporting driver wants to remove() it must deliver an invalidation shutdown to all DMABUF importing drivers through move_notify() and synchronously DMA unmap all the MMIO.

No importing driver can continue to have a DMA map to the MMIO after the exporting driver has destroyed its p2p_provider.

<a id="rst-p2p-dma-support-library"></a>

## P2P DMA Support Library


#### <a id="c-pcim_p2pdma_init"></a>`pcim_p2pdma_init()`

```c
int pcim_p2pdma_init(struct pci_dev *pdev)
```

Initialise peer-to-peer DMA providers

**Parameters**

- `struct pci_dev *pdev`: The PCI device to enable P2PDMA for

**Description**

This function initializes the peer-to-peer DMA infrastructure
for a PCI device. It allocates and sets up the necessary data
structures to support P2PDMA operations, including mapping type
tracking.

#### <a id="c-pcim_p2pdma_provider"></a>`pcim_p2pdma_provider()`

```c
struct p2pdma_provider * pcim_p2pdma_provider(struct pci_dev *pdev, int bar)
```

Get peer-to-peer DMA provider

**Parameters**

- `struct pci_dev *pdev`: The PCI device to enable P2PDMA for
- `int bar`: BAR index to get provider

**Description**

This function gets peer-to-peer DMA provider for a PCI device. The lifetime
of the provider (and of course the MMIO) is bound to the lifetime of the
driver. A driver calling this function must ensure that all references to the
provider, and any DMA mappings created for any MMIO, are all cleaned up
before the driver `remove()` completes.

Since P2P is almost always shared with a second driver this means some system
to notify, invalidate and revoke the MMIO's DMA must be in place to use this
function. For example a revoke can be built using DMABUF.

#### <a id="c-pci_p2pdma_add_resource"></a>`pci_p2pdma_add_resource()`

```c
int pci_p2pdma_add_resource(struct pci_dev *pdev, int bar, size_t size, u64 offset)
```

add memory for use as p2p memory

**Parameters**

- `struct pci_dev *pdev`: the device to add the memory to
- `int bar`: PCI BAR to add
- `size_t size`: size of the memory to add, may be zero to use the whole BAR
- `u64 offset`: offset into the PCI BAR

**Description**

The memory will be given ZONE_DEVICE struct pages so that it may
be used with any DMA request.

#### <a id="c-pci_p2pdma_distance_many"></a>`pci_p2pdma_distance_many()`

```c
int pci_p2pdma_distance_many(struct pci_dev *provider, struct device **clients, int num_clients, bool verbose)
```

Determine the cumulative distance between a p2pdma provider and the clients in use.

**Parameters**

- `struct pci_dev *provider`: p2pdma provider to check against the client list
- `struct device **clients`: array of devices to check (NULL-terminated)
- `int num_clients`: number of clients in the array
- `bool verbose`: if true, print warnings for devices when we return -1

**Description**

Returns -1 if any of the clients are not compatible, otherwise returns a
positive number where a lower number is the preferable choice. (If there's
one client that's the same as the provider it will return 0, which is best
choice).

"compatible" means the provider and the clients are either all behind
the same PCI root port or the host bridges connected to each of the devices
are listed in the 'pci_p2pdma_whitelist'.

#### <a id="c-pci_p2pmem_find_many"></a>`pci_p2pmem_find_many()`

```c
struct pci_dev * pci_p2pmem_find_many(struct device **clients, int num_clients)
```

find a peer-to-peer DMA memory device compatible with the specified list of clients and shortest distance

**Parameters**

- `struct device **clients`: array of devices to check (NULL-terminated)
- `int num_clients`: number of client devices in the list

**Description**

If multiple devices are behind the same switch, the one "closest" to the
client devices in use will be chosen first. (So if one of the providers is
the same as one of the clients, that provider will be used ahead of any
other providers that are unrelated). If multiple providers are an equal
distance away, one will be chosen at random.

Returns a pointer to the PCI device with a reference taken (use pci_dev_put
to return the reference) or NULL if no compatible device is found. The
found provider will also be assigned to the client list.

#### <a id="c-pci_alloc_p2pmem"></a>`pci_alloc_p2pmem()`

```c
void * pci_alloc_p2pmem(struct pci_dev *pdev, size_t size)
```

allocate peer-to-peer DMA memory

**Parameters**

- `struct pci_dev *pdev`: the device to allocate memory from
- `size_t size`: number of bytes to allocate

**Description**

Returns the allocated memory or NULL on error.

#### <a id="c-pci_free_p2pmem"></a>`pci_free_p2pmem()`

```c
void pci_free_p2pmem(struct pci_dev *pdev, void *addr, size_t size)
```

free peer-to-peer DMA memory

**Parameters**

- `struct pci_dev *pdev`: the device the memory was allocated from
- `void *addr`: address of the memory that was allocated
- `size_t size`: number of bytes that were allocated

#### <a id="c-pci_p2pmem_virt_to_bus"></a>`pci_p2pmem_virt_to_bus()`

```c
pci_bus_addr_t pci_p2pmem_virt_to_bus(struct pci_dev *pdev, void *addr)
```

return the PCI bus address for a given virtual address obtained with [`pci_alloc_p2pmem()`](#c-pci_alloc_p2pmem)

**Parameters**

- `struct pci_dev *pdev`: the device the memory was allocated from
- `void *addr`: address of the memory that was allocated

#### <a id="c-pci_p2pmem_alloc_sgl"></a>`pci_p2pmem_alloc_sgl()`

```c
struct scatterlist * pci_p2pmem_alloc_sgl(struct pci_dev *pdev, unsigned int *nents, u32 length)
```

allocate peer-to-peer DMA memory in a scatterlist

**Parameters**

- `struct pci_dev *pdev`: the device to allocate memory from
- `unsigned int *nents`: the number of SG entries in the list
- `u32 length`: number of bytes to allocate

**Return**

`NULL` on error or `struct scatterlist` pointer and **nents** on success

#### <a id="c-pci_p2pmem_free_sgl"></a>`pci_p2pmem_free_sgl()`

```c
void pci_p2pmem_free_sgl(struct pci_dev *pdev, struct scatterlist *sgl)
```

free a scatterlist allocated by [`pci_p2pmem_alloc_sgl()`](#c-pci_p2pmem_alloc_sgl)

**Parameters**

- `struct pci_dev *pdev`: the device to allocate memory from
- `struct scatterlist *sgl`: the allocated scatterlist

#### <a id="c-pci_p2pmem_publish"></a>`pci_p2pmem_publish()`

```c
void pci_p2pmem_publish(struct pci_dev *pdev, bool publish)
```

publish the peer-to-peer DMA memory for use by other devices with `pci_p2pmem_find()`

**Parameters**

- `struct pci_dev *pdev`: the device with peer-to-peer DMA memory to publish
- `bool publish`: set to true to publish the memory, false to unpublish it

**Description**

Published memory can be used by other PCI device drivers for
peer-2-peer DMA operations. Non-published memory is reserved for
exclusive use of the device driver that registers the peer-to-peer
memory.

#### <a id="c-pci_p2pdma_enable_store"></a>`pci_p2pdma_enable_store()`

```c
int pci_p2pdma_enable_store(const char *page, struct pci_dev **p2p_dev, bool *use_p2pdma)
```

parse a configfs/sysfs attribute store to enable p2pdma

**Parameters**

- `const char *page`: contents of the value to be stored
- `struct pci_dev **p2p_dev`: returns the PCI device that was selected to be used
  (if one was specified in the stored value)
- `bool *use_p2pdma`: returns whether to enable p2pdma or not

**Description**

Parses an attribute value to decide whether to enable p2pdma.
The value can select a PCI device (using its full BDF device
name) or a boolean (in any format [`kstrtobool()`](/kernel/internals/core-api/kernel-api.md#c-kstrtobool) accepts). A false
value disables p2pdma, a true value expects the caller
to automatically find a compatible device and specifying a PCI device
expects the caller to use the specific provider.

[`pci_p2pdma_enable_show()`](#c-pci_p2pdma_enable_show) should be used as the show operation for
the attribute.

Returns 0 on success

#### <a id="c-pci_p2pdma_enable_show"></a>`pci_p2pdma_enable_show()`

```c
ssize_t pci_p2pdma_enable_show(char *page, struct pci_dev *p2p_dev, bool use_p2pdma)
```

show a configfs/sysfs attribute indicating whether p2pdma is enabled

**Parameters**

- `char *page`: contents of the stored value
- `struct pci_dev *p2p_dev`: the selected p2p device (NULL if no device is selected)
- `bool use_p2pdma`: whether p2pdma has been enabled

**Description**

Attributes that use [`pci_p2pdma_enable_store()`](#c-pci_p2pdma_enable_store) should use this function
to show the value of the attribute.

Returns 0 on success

---

# PCI Support Library

_Peios Kernel / Hardware and drivers / Driver development / PCI_

> Reference for PCI Support Library.

<a id="rst-pci-support-library"></a>

## PCI Support Library


#### <a id="c-pci_bus_max_busnr"></a>`pci_bus_max_busnr()`

```c
unsigned char pci_bus_max_busnr(struct pci_bus *bus)
```

returns maximum PCI bus number of given bus' children

**Parameters**

- `struct pci_bus *bus`: pointer to PCI bus structure to search

**Description**

Given a PCI bus, returns the highest PCI bus number present in the set
including the given PCI bus and its list of child PCI buses.

#### <a id="c-pci_status_get_and_clear_errors"></a>`pci_status_get_and_clear_errors()`

```c
int pci_status_get_and_clear_errors(struct pci_dev *pdev)
```

return and clear error bits in PCI_STATUS

**Parameters**

- `struct pci_dev *pdev`: the PCI device

**Description**

Returns error bits set in PCI_STATUS and clears them.

#### <a id="c-pci_find_capability"></a>`pci_find_capability()`

```c
u8 pci_find_capability(struct pci_dev *dev, int cap)
```

query for devices' capabilities

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `int cap`: capability code

**Description**

Tell if a device supports a given PCI capability.
Returns the address of the requested capability structure within the
device's PCI configuration space or 0 in case the device does not
support it.  Possible values for **cap** include:

`PCI_CAP_ID_PM`           Power Management
`PCI_CAP_ID_AGP`          Accelerated Graphics Port
`PCI_CAP_ID_VPD`          Vital Product Data
`PCI_CAP_ID_SLOTID`       Slot Identification
`PCI_CAP_ID_MSI`          Message Signalled Interrupts
`PCI_CAP_ID_CHSWP`        CompactPCI HotSwap
`PCI_CAP_ID_PCIX`         PCI-X
`PCI_CAP_ID_EXP`          PCI Express

#### <a id="c-pci_bus_find_capability"></a>`pci_bus_find_capability()`

```c
u8 pci_bus_find_capability(struct pci_bus *bus, unsigned int devfn, int cap)
```

query for devices' capabilities

**Parameters**

- `struct pci_bus *bus`: the PCI bus to query
- `unsigned int devfn`: PCI device to query
- `int cap`: capability code

**Description**

Like [`pci_find_capability()`](#c-pci_find_capability) but works for PCI devices that do not have a
pci_dev structure set up yet.

Returns the address of the requested capability structure within the
device's PCI configuration space or 0 in case the device does not
support it.

#### <a id="c-pci_find_next_ext_capability"></a>`pci_find_next_ext_capability()`

```c
u16 pci_find_next_ext_capability(struct pci_dev *dev, u16 start, int cap)
```

Find an extended capability

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `u16 start`: address at which to start looking (0 to start at beginning of list)
- `int cap`: capability code

**Description**

Returns the address of the next matching extended capability structure
within the device's PCI configuration space or 0 if the device does
not support it.  Some capabilities can occur several times, e.g., the
vendor-specific capability, and this provides a way to find them all.

#### <a id="c-pci_find_ext_capability"></a>`pci_find_ext_capability()`

```c
u16 pci_find_ext_capability(struct pci_dev *dev, int cap)
```

Find an extended capability

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `int cap`: capability code

**Description**

Returns the address of the requested extended capability structure
within the device's PCI configuration space or 0 if the device does
not support it.  Possible values for **cap** include:

`PCI_EXT_CAP_ID_ERR`         Advanced Error Reporting
`PCI_EXT_CAP_ID_VC`          Virtual Channel
`PCI_EXT_CAP_ID_DSN`         Device Serial Number
`PCI_EXT_CAP_ID_PWR`         Power Budgeting

#### <a id="c-pci_get_dsn"></a>`pci_get_dsn()`

```c
u64 pci_get_dsn(struct pci_dev *dev)
```

Read and return the 8-byte Device Serial Number

**Parameters**

- `struct pci_dev *dev`: PCI device to query

**Description**

Looks up the PCI_EXT_CAP_ID_DSN and reads the 8 bytes of the Device Serial
Number.

Returns the DSN, or zero if the capability does not exist.

#### <a id="c-pci_find_next_ht_capability"></a>`pci_find_next_ht_capability()`

```c
u8 pci_find_next_ht_capability(struct pci_dev *dev, u8 pos, int ht_cap)
```

query a device's HyperTransport capabilities

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `u8 pos`: Position from which to continue searching
- `int ht_cap`: HyperTransport capability code

**Description**

To be used in conjunction with [`pci_find_ht_capability()`](#c-pci_find_ht_capability) to search for
all capabilities matching **ht_cap**. **pos** should always be a value returned
from [`pci_find_ht_capability()`](#c-pci_find_ht_capability).

NB. To be 100% safe against broken PCI devices, the caller should take
steps to avoid an infinite loop.

#### <a id="c-pci_find_ht_capability"></a>`pci_find_ht_capability()`

```c
u8 pci_find_ht_capability(struct pci_dev *dev, int ht_cap)
```

query a device's HyperTransport capabilities

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `int ht_cap`: HyperTransport capability code

**Description**

Tell if a device supports a given HyperTransport capability.
Returns an address within the device's PCI configuration space
or 0 in case the device does not support the request capability.
The address points to the PCI capability, of type PCI_CAP_ID_HT,
which has a HyperTransport capability matching **ht_cap**.

#### <a id="c-pci_find_vsec_capability"></a>`pci_find_vsec_capability()`

```c
u16 pci_find_vsec_capability(struct pci_dev *dev, u16 vendor, int cap)
```

Find a vendor-specific extended capability

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `u16 vendor`: Vendor ID for which capability is defined
- `int cap`: Vendor-specific capability ID

**Description**

If **dev** has Vendor ID **vendor**, search for a VSEC capability with
VSEC ID **cap**. If found, return the capability offset in
config space; otherwise return 0.

#### <a id="c-pci_find_dvsec_capability"></a>`pci_find_dvsec_capability()`

```c
u16 pci_find_dvsec_capability(struct pci_dev *dev, u16 vendor, u16 dvsec)
```

Find DVSEC for vendor

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `u16 vendor`: Vendor ID to match for the DVSEC
- `u16 dvsec`: Designated Vendor-specific capability ID

**Description**

If DVSEC has Vendor ID **vendor** and DVSEC ID **dvsec** return the capability
offset in config space; otherwise return 0.

#### <a id="c-pci_find_parent_resource"></a>`pci_find_parent_resource()`

```c
struct resource * pci_find_parent_resource(const struct pci_dev *dev, struct resource *res)
```

return resource region of parent bus of given region

**Parameters**

- `const struct pci_dev *dev`: PCI device structure contains resources to be searched
- `struct resource *res`: child resource record for which parent is sought

**Description**

For given resource region of given device, return the resource region of
parent bus the given region is contained in.

#### <a id="c-pci_find_resource"></a>`pci_find_resource()`

```c
struct resource * pci_find_resource(struct pci_dev *dev, struct resource *res)
```

Return matching PCI device resource

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `struct resource *res`: Resource to look for

**Description**

Goes over standard PCI resources (BARs) and checks if the given resource
is partially or fully contained in any of them. In that case the
matching resource is returned, `NULL` otherwise.

#### <a id="c-pci_platform_power_transition"></a>`pci_platform_power_transition()`

```c
int pci_platform_power_transition(struct pci_dev *dev, pci_power_t state)
```

Use platform to change device power state

**Parameters**

- `struct pci_dev *dev`: PCI device to handle.
- `pci_power_t state`: State to put the device into.

#### <a id="c-pci_set_power_state"></a>`pci_set_power_state()`

```c
int pci_set_power_state(struct pci_dev *dev, pci_power_t state)
```

Set the power state of a PCI device

**Parameters**

- `struct pci_dev *dev`: PCI device to handle.
- `pci_power_t state`: PCI power state (D0, D1, D2, D3hot) to put the device into.

**Description**

Transition a device to a new power state, using the platform firmware and/or
the device's PCI PM registers.

RETURN VALUE:
-EINVAL if the requested state is invalid.
-EIO if device does not support PCI PM or its PM capabilities register has a
wrong version, or device doesn't support the requested state.
0 if the transition is to D1 or D2 but D1 and D2 are not supported.
0 if device already is in the requested state.
0 if the transition is to D3 but D3 is not supported.
0 if device's power state has been successfully changed.

#### <a id="c-pci_save_state"></a>`pci_save_state()`

```c
int pci_save_state(struct pci_dev *dev)
```

save the PCI configuration space of a device before suspending

**Parameters**

- `struct pci_dev *dev`: PCI device that we're dealing with

#### <a id="c-pci_restore_state"></a>`pci_restore_state()`

```c
void pci_restore_state(struct pci_dev *dev)
```

Restore the saved state of a PCI device

**Parameters**

- `struct pci_dev *dev`: PCI device that we're dealing with

#### <a id="c-pci_store_saved_state"></a>`pci_store_saved_state()`

```c
struct pci_saved_state * pci_store_saved_state(struct pci_dev *dev)
```

Allocate and return an opaque struct containing the device saved state.

**Parameters**

- `struct pci_dev *dev`: PCI device that we're dealing with

**Description**

Return NULL if no state or error.

#### <a id="c-pci_load_saved_state"></a>`pci_load_saved_state()`

```c
int pci_load_saved_state(struct pci_dev *dev, struct pci_saved_state *state)
```

Reload the provided save state into struct pci_dev.

**Parameters**

- `struct pci_dev *dev`: PCI device that we're dealing with
- `struct pci_saved_state *state`: Saved state returned from [`pci_store_saved_state()`](#c-pci_store_saved_state)

#### <a id="c-pci_load_and_free_saved_state"></a>`pci_load_and_free_saved_state()`

```c
int pci_load_and_free_saved_state(struct pci_dev *dev, struct pci_saved_state **state)
```

Reload the save state pointed to by state, and free the memory allocated for it.

**Parameters**

- `struct pci_dev *dev`: PCI device that we're dealing with
- `struct pci_saved_state **state`: Pointer to saved state returned from [`pci_store_saved_state()`](#c-pci_store_saved_state)

#### <a id="c-pci_reenable_device"></a>`pci_reenable_device()`

```c
int pci_reenable_device(struct pci_dev *dev)
```

Resume abandoned device

**Parameters**

- `struct pci_dev *dev`: PCI device to be resumed

**NOTE**

This function is a backend of `pci_default_resume()` and is not supposed
to be called by normal code, write proper resume handler and use it instead.

#### <a id="c-pci_enable_device_mem"></a>`pci_enable_device_mem()`

```c
int pci_enable_device_mem(struct pci_dev *dev)
```

Initialize a device for use with Memory space

**Parameters**

- `struct pci_dev *dev`: PCI device to be initialized

**Description**

Initialize device before it's used by a driver. Ask low-level code
to enable Memory resources. Wake up the device if it was suspended.
Beware, this function can fail.

#### <a id="c-pci_enable_device"></a>`pci_enable_device()`

```c
int pci_enable_device(struct pci_dev *dev)
```

Initialize device before it's used by a driver.

**Parameters**

- `struct pci_dev *dev`: PCI device to be initialized

**Description**

Initialize device before it's used by a driver. Ask low-level code
to enable I/O and memory. Wake up the device if it was suspended.
Beware, this function can fail.

Note we don't actually enable the device many times if we call
this function repeatedly (we just increment the count).

#### <a id="c-pci_disable_device"></a>`pci_disable_device()`

```c
void pci_disable_device(struct pci_dev *dev)
```

Disable PCI device after use

**Parameters**

- `struct pci_dev *dev`: PCI device to be disabled

**Description**

Signal to the system that the PCI device is not in use by the system
anymore.  This only involves disabling PCI bus-mastering, if active.

Note we don't actually disable the device until all callers of
[`pci_enable_device()`](#c-pci_enable_device) have called [`pci_disable_device()`](#c-pci_disable_device).

#### <a id="c-pci_set_pcie_reset_state"></a>`pci_set_pcie_reset_state()`

```c
int pci_set_pcie_reset_state(struct pci_dev *dev, enum pcie_reset_state state)
```

set reset state for device dev

**Parameters**

- `struct pci_dev *dev`: the PCIe device reset
- `enum pcie_reset_state state`: Reset state to enter into

**Description**

Sets the PCI reset state for the device.

#### <a id="c-pci_pme_capable"></a>`pci_pme_capable()`

```c
bool pci_pme_capable(struct pci_dev *dev, pci_power_t state)
```

check the capability of PCI device to generate PME#

**Parameters**

- `struct pci_dev *dev`: PCI device to handle.
- `pci_power_t state`: PCI state from which device will issue PME#.

#### <a id="c-pci_pme_active"></a>`pci_pme_active()`

```c
void pci_pme_active(struct pci_dev *dev, bool enable)
```

enable or disable PCI device's PME# function

**Parameters**

- `struct pci_dev *dev`: PCI device to handle.
- `bool enable`: 'true' to enable PME# generation; 'false' to disable it.

**Description**

The caller must verify that the device is capable of generating PME# before
calling this function with **enable** equal to 'true'.

#### <a id="c-pci_enable_wake"></a>`pci_enable_wake()`

```c
int pci_enable_wake(struct pci_dev *pci_dev, pci_power_t state, bool enable)
```

change wakeup settings for a PCI device

**Parameters**

- `struct pci_dev *pci_dev`: Target device
- `pci_power_t state`: PCI state from which device will issue wakeup events
- `bool enable`: Whether or not to enable event generation

**Description**

If **enable** is set, check `device_may_wakeup()` for the device before calling
`__pci_enable_wake()` for it.

#### <a id="c-pci_wake_from_d3"></a>`pci_wake_from_d3()`

```c
int pci_wake_from_d3(struct pci_dev *dev, bool enable)
```

enable/disable device to wake up from D3_hot or D3_cold

**Parameters**

- `struct pci_dev *dev`: PCI device to prepare
- `bool enable`: True to enable wake-up event generation; false to disable

**Description**

Many drivers want the device to wake up the system from D3_hot or D3_cold
and this function allows them to set that up cleanly - [`pci_enable_wake()`](#c-pci_enable_wake)
should not be called twice in a row to enable wake-up due to PCI PM vs ACPI
ordering constraints.

This function only returns error code if the device is not allowed to wake
up the system from sleep or it is not capable of generating PME# from both
D3_hot and D3_cold and the platform is unable to enable wake-up power for it.

#### <a id="c-pci_prepare_to_sleep"></a>`pci_prepare_to_sleep()`

```c
int pci_prepare_to_sleep(struct pci_dev *dev)
```

prepare PCI device for system-wide transition into a sleep state

**Parameters**

- `struct pci_dev *dev`: Device to handle.

**Description**

Choose the power state appropriate for the device depending on whether
it can wake up the system and/or is power manageable by the platform
(PCI_D3hot is the default) and put the device into that state.

#### <a id="c-pci_back_from_sleep"></a>`pci_back_from_sleep()`

```c
int pci_back_from_sleep(struct pci_dev *dev)
```

turn PCI device on during system-wide transition into working state

**Parameters**

- `struct pci_dev *dev`: Device to handle.

**Description**

Disable device's system wake-up capability and put it into D0.

#### <a id="c-pci_dev_run_wake"></a>`pci_dev_run_wake()`

```c
bool pci_dev_run_wake(struct pci_dev *dev)
```

Check if device can generate run-time wake-up events.

**Parameters**

- `struct pci_dev *dev`: Device to check.

**Description**

Return true if the device itself is capable of generating wake-up events
(through the platform or using the native PCIe PME) or if the device supports
PME and one of its upstream bridges can generate wake-up events.

#### <a id="c-pci_choose_state"></a>`pci_choose_state()`

```c
pci_power_t pci_choose_state(struct pci_dev *dev, pm_message_t state)
```

Choose the power state of a PCI device.

**Parameters**

- `struct pci_dev *dev`: Target PCI device.
- `pm_message_t state`: Target state for the whole system.

**Description**

Returns PCI power state suitable for **dev** and **state**.

#### <a id="c-pci_d3cold_enable"></a>`pci_d3cold_enable()`

```c
void pci_d3cold_enable(struct pci_dev *dev)
```

Enable D3cold for device

**Parameters**

- `struct pci_dev *dev`: PCI device to handle

**Description**

This function can be used in drivers to enable D3cold from the device
they handle.  It also updates upstream PCI bridge PM capabilities
accordingly.

#### <a id="c-pci_d3cold_disable"></a>`pci_d3cold_disable()`

```c
void pci_d3cold_disable(struct pci_dev *dev)
```

Disable D3cold for device

**Parameters**

- `struct pci_dev *dev`: PCI device to handle

**Description**

This function can be used in drivers to disable D3cold from the device
they handle.  It also updates upstream PCI bridge PM capabilities
accordingly.

#### <a id="c-pci_enable_atomic_ops_to_root"></a>`pci_enable_atomic_ops_to_root()`

```c
int pci_enable_atomic_ops_to_root(struct pci_dev *dev, u32 cap_mask)
```

enable AtomicOp requests to root port

**Parameters**

- `struct pci_dev *dev`: the PCI device
- `u32 cap_mask`: mask of desired AtomicOp sizes, including one or more of:
  PCI_EXP_DEVCAP2_ATOMIC_COMP32
  PCI_EXP_DEVCAP2_ATOMIC_COMP64
  PCI_EXP_DEVCAP2_ATOMIC_COMP128

**Description**

Return 0 if all upstream bridges support AtomicOp routing, egress
blocking is disabled on all upstream ports, and the root port supports
the requested completion capabilities (32-bit, 64-bit and/or 128-bit
AtomicOp completion), or negative otherwise.

#### <a id="c-pci_release_region"></a>`pci_release_region()`

```c
void pci_release_region(struct pci_dev *pdev, int bar)
```

Release a PCI bar

**Parameters**

- `struct pci_dev *pdev`: PCI device whose resources were previously reserved by
  [`pci_request_region()`](#c-pci_request_region)
- `int bar`: BAR to release

**Description**

Releases the PCI I/O and memory resources previously reserved by a
successful call to [`pci_request_region()`](#c-pci_request_region).  Call this function only
after all use of the PCI regions has ceased.

#### <a id="c-pci_request_region"></a>`pci_request_region()`

```c
int pci_request_region(struct pci_dev *pdev, int bar, const char *name)
```

Reserve PCI I/O and memory resource

**Parameters**

- `struct pci_dev *pdev`: PCI device whose resources are to be reserved
- `int bar`: BAR to be reserved
- `const char *name`: name of the driver requesting the resource

**Return**

0 on success, negative error code on failure.

**Description**

Mark the PCI region associated with PCI device **pdev** BAR **bar** as being
reserved by owner **name**. Do not access any address inside the PCI regions
unless this call returns successfully.

Returns 0 on success, or `EBUSY` on error.  A warning
message is also printed on failure.

#### <a id="c-pci_release_selected_regions"></a>`pci_release_selected_regions()`

```c
void pci_release_selected_regions(struct pci_dev *pdev, int bars)
```

Release selected PCI I/O and memory resources

**Parameters**

- `struct pci_dev *pdev`: PCI device whose resources were previously reserved
- `int bars`: Bitmask of BARs to be released

**Description**

Release selected PCI I/O and memory resources previously reserved.
Call this function only after all use of the PCI regions has ceased.

#### <a id="c-pci_request_selected_regions"></a>`pci_request_selected_regions()`

```c
int pci_request_selected_regions(struct pci_dev *pdev, int bars, const char *name)
```

Reserve selected PCI I/O and memory resources

**Parameters**

- `struct pci_dev *pdev`: PCI device whose resources are to be reserved
- `int bars`: Bitmask of BARs to be requested
- `const char *name`: Name of the driver requesting the resources

**Return**

0 on success, negative error code on failure.

#### <a id="c-pci_request_selected_regions_exclusive"></a>`pci_request_selected_regions_exclusive()`

```c
int pci_request_selected_regions_exclusive(struct pci_dev *pdev, int bars, const char *name)
```

Request regions exclusively

**Parameters**

- `struct pci_dev *pdev`: PCI device to request regions from
- `int bars`: bit mask of BARs to request
- `const char *name`: name of the driver requesting the resources

**Return**

0 on success, negative error code on failure.

#### <a id="c-pci_release_regions"></a>`pci_release_regions()`

```c
void pci_release_regions(struct pci_dev *pdev)
```

Release reserved PCI I/O and memory resources

**Parameters**

- `struct pci_dev *pdev`: PCI device whose resources were previously reserved by
  [`pci_request_regions()`](#c-pci_request_regions)

**Description**

Releases all PCI I/O and memory resources previously reserved by a
successful call to [`pci_request_regions()`](#c-pci_request_regions).  Call this function only
after all use of the PCI regions has ceased.

#### <a id="c-pci_request_regions"></a>`pci_request_regions()`

```c
int pci_request_regions(struct pci_dev *pdev, const char *name)
```

Reserve PCI I/O and memory resources

**Parameters**

- `struct pci_dev *pdev`: PCI device whose resources are to be reserved
- `const char *name`: name of the driver requesting the resources

**Description**

Mark all PCI regions associated with PCI device **pdev** as being reserved by
owner **name**. Do not access any address inside the PCI regions unless this
call returns successfully.

Returns 0 on success, or `EBUSY` on error.  A warning
message is also printed on failure.

#### <a id="c-pci_request_regions_exclusive"></a>`pci_request_regions_exclusive()`

```c
int pci_request_regions_exclusive(struct pci_dev *pdev, const char *name)
```

Reserve PCI I/O and memory resources

**Parameters**

- `struct pci_dev *pdev`: PCI device whose resources are to be reserved
- `const char *name`: name of the driver requesting the resources

**Return**

0 on success, negative error code on failure.

**Description**

Mark all PCI regions associated with PCI device **pdev** as being reserved
by owner **name**. Do not access any address inside the PCI regions
unless this call returns successfully.

[`pci_request_regions_exclusive()`](#c-pci_request_regions_exclusive) will mark the region so that /dev/mem
and the sysfs MMIO access will not be allowed.

Returns 0 on success, or `EBUSY` on error.  A warning message is also
printed on failure.

#### <a id="c-pci_remap_iospace"></a>`pci_remap_iospace()`

```c
int pci_remap_iospace(const struct resource *res, phys_addr_t phys_addr)
```

Remap the memory mapped I/O space

**Parameters**

- `const struct resource *res`: Resource describing the I/O space
- `phys_addr_t phys_addr`: physical address of range to be mapped

**Description**

Remap the memory mapped I/O space described by the **res** and the CPU
physical address **phys_addr** into virtual address space.  Only
architectures that have memory mapped IO functions defined (and the
PCI_IOBASE value defined) should call this function.

#### <a id="c-pci_unmap_iospace"></a>`pci_unmap_iospace()`

```c
void pci_unmap_iospace(struct resource *res)
```

Unmap the memory mapped I/O space

**Parameters**

- `struct resource *res`: resource to be unmapped

**Description**

Unmap the CPU virtual address **res** from virtual address space.  Only
architectures that have memory mapped IO functions defined (and the
PCI_IOBASE value defined) should call this function.

#### <a id="c-pci_set_master"></a>`pci_set_master()`

```c
void pci_set_master(struct pci_dev *dev)
```

enables bus-mastering for device dev

**Parameters**

- `struct pci_dev *dev`: the PCI device to enable

**Description**

Enables bus-mastering on the device and calls `pcibios_set_master()`
to do the needed arch specific settings.

#### <a id="c-pci_clear_master"></a>`pci_clear_master()`

```c
void pci_clear_master(struct pci_dev *dev)
```

disables bus-mastering for device dev

**Parameters**

- `struct pci_dev *dev`: the PCI device to disable

#### <a id="c-pci_set_cacheline_size"></a>`pci_set_cacheline_size()`

```c
int pci_set_cacheline_size(struct pci_dev *dev)
```

ensure the CACHE_LINE_SIZE register is programmed

**Parameters**

- `struct pci_dev *dev`: the PCI device for which MWI is to be enabled

**Description**

Helper function for pci_set_mwi.
Originally copied from drivers/net/acenic.c.
Copyright 1998-2001 by Jes Sorensen, \<jes@trained-monkey.org>.

**Return**

An appropriate -ERRNO error value on error, or zero for success.

#### <a id="c-pci_set_mwi"></a>`pci_set_mwi()`

```c
int pci_set_mwi(struct pci_dev *dev)
```

enables memory-write-invalidate PCI transaction

**Parameters**

- `struct pci_dev *dev`: the PCI device for which MWI is enabled

**Description**

Enables the Memory-Write-Invalidate transaction in `PCI_COMMAND`.

**Return**

An appropriate -ERRNO error value on error, or zero for success.

#### <a id="c-pci_try_set_mwi"></a>`pci_try_set_mwi()`

```c
int pci_try_set_mwi(struct pci_dev *dev)
```

enables memory-write-invalidate PCI transaction

**Parameters**

- `struct pci_dev *dev`: the PCI device for which MWI is enabled

**Description**

Enables the Memory-Write-Invalidate transaction in `PCI_COMMAND`.
Callers are not required to check the return value.

**Return**

An appropriate -ERRNO error value on error, or zero for success.

#### <a id="c-pci_clear_mwi"></a>`pci_clear_mwi()`

```c
void pci_clear_mwi(struct pci_dev *dev)
```

disables Memory-Write-Invalidate for device dev

**Parameters**

- `struct pci_dev *dev`: the PCI device to disable

**Description**

Disables PCI Memory-Write-Invalidate transaction on the device

#### <a id="c-pci_intx"></a>`pci_intx()`

```c
void pci_intx(struct pci_dev *pdev, int enable)
```

enables/disables PCI INTx for device dev

**Parameters**

- `struct pci_dev *pdev`: the PCI device to operate on
- `int enable`: boolean: whether to enable or disable PCI INTx

**Description**

Enables/disables PCI INTx for device **pdev**

#### <a id="c-pci_wait_for_pending_transaction"></a>`pci_wait_for_pending_transaction()`

```c
int pci_wait_for_pending_transaction(struct pci_dev *dev)
```

wait for pending transaction

**Parameters**

- `struct pci_dev *dev`: the PCI device to operate on

**Description**

Return 0 if transaction is pending 1 otherwise.

#### <a id="c-pcie_flr"></a>`pcie_flr()`

```c
int pcie_flr(struct pci_dev *dev)
```

initiate a PCIe function level reset

**Parameters**

- `struct pci_dev *dev`: device to reset

**Description**

Initiate a function level reset unconditionally on **dev** without
checking any flags and DEVCAP

#### <a id="c-pcie_reset_flr"></a>`pcie_reset_flr()`

```c
int pcie_reset_flr(struct pci_dev *dev, bool probe)
```

initiate a PCIe function level reset

**Parameters**

- `struct pci_dev *dev`: device to reset
- `bool probe`: if true, return 0 if device can be reset this way

**Description**

Initiate a function level reset on **dev**.

#### <a id="c-pci_bridge_secondary_bus_reset"></a>`pci_bridge_secondary_bus_reset()`

```c
int pci_bridge_secondary_bus_reset(struct pci_dev *dev)
```

Reset the secondary bus on a PCI bridge.

**Parameters**

- `struct pci_dev *dev`: Bridge device

**Description**

Use the bridge control register to assert reset on the secondary bus.
Devices on the secondary bus are left in power-on state.

#### <a id="c-__pci_reset_function_locked"></a>`__pci_reset_function_locked()`

```c
int __pci_reset_function_locked(struct pci_dev *dev)
```

reset a PCI device function while holding the **dev** mutex lock.

**Parameters**

- `struct pci_dev *dev`: PCI device to reset

**Description**

Some devices allow an individual function to be reset without affecting
other functions in the same device.  The PCI device must be responsive
to PCI config space in order to use this function.

The device function is presumed to be unused and the caller is holding
the device mutex lock when this function is called.

Resetting the device will make the contents of PCI configuration space
random, so any caller of this must be prepared to reinitialise the
device including MSI, bus mastering, BARs, decoding IO and memory spaces,
etc.

**Context**

The caller must hold the device lock.

**Return**

0 if the device function was successfully reset or negative if the
device doesn't support resetting a single function.

#### <a id="c-pci_reset_function"></a>`pci_reset_function()`

```c
int pci_reset_function(struct pci_dev *dev)
```

quiesce and reset a PCI device function

**Parameters**

- `struct pci_dev *dev`: PCI device to reset

**Description**

Some devices allow an individual function to be reset without affecting
other functions in the same device.  The PCI device must be responsive
to PCI config space in order to use this function.

This function does not just reset the PCI portion of a device, but
clears all the state associated with the device.  This function differs
from [`__pci_reset_function_locked()`](#c-__pci_reset_function_locked) in that it saves and restores device state
over the reset and takes the PCI device lock.

Returns 0 if the device function was successfully reset or negative if the
device doesn't support resetting a single function.

#### <a id="c-pci_reset_function_locked"></a>`pci_reset_function_locked()`

```c
int pci_reset_function_locked(struct pci_dev *dev)
```

quiesce and reset a PCI device function

**Parameters**

- `struct pci_dev *dev`: PCI device to reset

**Description**

Some devices allow an individual function to be reset without affecting
other functions in the same device.  The PCI device must be responsive
to PCI config space in order to use this function.

This function does not just reset the PCI portion of a device, but
clears all the state associated with the device.  This function differs
from [`__pci_reset_function_locked()`](#c-__pci_reset_function_locked) in that it saves and restores device state
over the reset.  It also differs from [`pci_reset_function()`](#c-pci_reset_function) in that it
requires the PCI device lock to be held.

**Context**

The caller must hold the device lock.

**Return**

0 if the device function was successfully reset or negative if the
device doesn't support resetting a single function.

#### <a id="c-pci_try_reset_function"></a>`pci_try_reset_function()`

```c
int pci_try_reset_function(struct pci_dev *dev)
```

quiesce and reset a PCI device function

**Parameters**

- `struct pci_dev *dev`: PCI device to reset

**Description**

Same as above, except return -EAGAIN if unable to lock device.

#### <a id="c-pci_probe_reset_slot"></a>`pci_probe_reset_slot()`

```c
int pci_probe_reset_slot(struct pci_slot *slot)
```

probe whether a PCI slot can be reset

**Parameters**

- `struct pci_slot *slot`: PCI slot to probe

**Description**

Return 0 if slot can be reset, negative if a slot reset is not supported.

#### <a id="c-pci_probe_reset_bus"></a>`pci_probe_reset_bus()`

```c
int pci_probe_reset_bus(struct pci_bus *bus)
```

probe whether a PCI bus can be reset

**Parameters**

- `struct pci_bus *bus`: PCI bus to probe

**Description**

Return 0 if bus can be reset, negative if a bus reset is not supported.

#### <a id="c-pci_reset_bus"></a>`pci_reset_bus()`

```c
int pci_reset_bus(struct pci_dev *pdev)
```

Try to reset a PCI bus

**Parameters**

- `struct pci_dev *pdev`: top level PCI device to reset via slot/bus

**Description**

Same as above except return -EAGAIN if the bus cannot be locked

#### <a id="c-pcix_get_max_mmrbc"></a>`pcix_get_max_mmrbc()`

```c
int pcix_get_max_mmrbc(struct pci_dev *dev)
```

get PCI-X maximum designed memory read byte count

**Parameters**

- `struct pci_dev *dev`: PCI device to query

**Description**

Returns mmrbc: maximum designed memory read count in bytes or
appropriate error value.

#### <a id="c-pcix_get_mmrbc"></a>`pcix_get_mmrbc()`

```c
int pcix_get_mmrbc(struct pci_dev *dev)
```

get PCI-X maximum memory read byte count

**Parameters**

- `struct pci_dev *dev`: PCI device to query

**Description**

Returns mmrbc: maximum memory read count in bytes or appropriate error
value.

#### <a id="c-pcix_set_mmrbc"></a>`pcix_set_mmrbc()`

```c
int pcix_set_mmrbc(struct pci_dev *dev, int mmrbc)
```

set PCI-X maximum memory read byte count

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `int mmrbc`: maximum memory read count in bytes
  valid values are 512, 1024, 2048, 4096

**Description**

If possible sets maximum memory read byte count, some bridges have errata
that prevent this.

#### <a id="c-pcie_get_readrq"></a>`pcie_get_readrq()`

```c
int pcie_get_readrq(struct pci_dev *dev)
```

get PCI Express read request size

**Parameters**

- `struct pci_dev *dev`: PCI device to query

**Description**

Returns maximum memory read request in bytes or appropriate error value.

#### <a id="c-pcie_set_readrq"></a>`pcie_set_readrq()`

```c
int pcie_set_readrq(struct pci_dev *dev, int rq)
```

set PCI Express maximum memory read request

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `int rq`: maximum memory read count in bytes
  valid values are 128, 256, 512, 1024, 2048, 4096

**Description**

If possible sets maximum memory read request in bytes

#### <a id="c-pcie_get_mps"></a>`pcie_get_mps()`

```c
int pcie_get_mps(struct pci_dev *dev)
```

get PCI Express maximum payload size

**Parameters**

- `struct pci_dev *dev`: PCI device to query

**Description**

Returns maximum payload size in bytes

#### <a id="c-pcie_set_mps"></a>`pcie_set_mps()`

```c
int pcie_set_mps(struct pci_dev *dev, int mps)
```

set PCI Express maximum payload size

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `int mps`: maximum payload size in bytes
  valid values are 128, 256, 512, 1024, 2048, 4096

**Description**

If possible sets maximum payload size

#### <a id="c-pcie_bandwidth_available"></a>`pcie_bandwidth_available()`

```c
u32 pcie_bandwidth_available(struct pci_dev *dev, struct pci_dev **limiting_dev, enum pci_bus_speed *speed, enum pcie_link_width *width)
```

determine minimum link settings of a PCIe device and its bandwidth limitation

**Parameters**

- `struct pci_dev *dev`: PCI device to query
- `struct pci_dev **limiting_dev`: storage for device causing the bandwidth limitation
- `enum pci_bus_speed *speed`: storage for speed of limiting device
- `enum pcie_link_width *width`: storage for width of limiting device

**Description**

Walk up the PCI device chain and find the point where the minimum
bandwidth is available.  Return the bandwidth available there and (if
limiting_dev, speed, and width pointers are supplied) information about
that point.  The bandwidth returned is in Mb/s, i.e., megabits/second of
raw bandwidth.

#### <a id="c-pcie_get_speed_cap"></a>`pcie_get_speed_cap()`

```c
enum pci_bus_speed pcie_get_speed_cap(struct pci_dev *dev)
```

query for the PCI device's link speed capability

**Parameters**

- `struct pci_dev *dev`: PCI device to query

**Description**

Query the PCI device speed capability.

**Return**

the maximum link speed supported by the device.

#### <a id="c-pcie_get_width_cap"></a>`pcie_get_width_cap()`

```c
enum pcie_link_width pcie_get_width_cap(struct pci_dev *dev)
```

query for the PCI device's link width capability

**Parameters**

- `struct pci_dev *dev`: PCI device to query

**Description**

Query the PCI device width capability.  Return the maximum link width
supported by the device.

#### <a id="c-pcie_print_link_status"></a>`pcie_print_link_status()`

```c
void pcie_print_link_status(struct pci_dev *dev)
```

Report the PCI device's link speed and width

**Parameters**

- `struct pci_dev *dev`: PCI device to query

**Description**

Report the available bandwidth at the device.

#### <a id="c-pci_select_bars"></a>`pci_select_bars()`

```c
int pci_select_bars(struct pci_dev *dev, unsigned long flags)
```

Make BAR mask from the type of resource

**Parameters**

- `struct pci_dev *dev`: the PCI device for which BAR mask is made
- `unsigned long flags`: resource type mask to be selected

**Description**

This helper routine makes bar mask from the type of resource.

#### <a id="c-pci_bus_find_emul_domain_nr"></a>`pci_bus_find_emul_domain_nr()`

```c
int pci_bus_find_emul_domain_nr(u32 hint, u32 min, u32 max)
```

allocate a PCI domain number per constraints

**Parameters**

- `u32 hint`: desired domain, 0 if any ID in the range of **min** to **max** is acceptable
- `u32 min`: minimum allowable domain
- `u32 max`: maximum allowable domain, no IDs higher than INT_MAX will be returned



#### <a id="c-pci_iomap_range"></a>`pci_iomap_range()`

```c
void __iomem * pci_iomap_range(struct pci_dev *dev, int bar, unsigned long offset, unsigned long maxlen)
```

create a virtual mapping cookie for a PCI BAR

**Parameters**

- `struct pci_dev *dev`: PCI device that owns the BAR
- `int bar`: BAR number
- `unsigned long offset`: map memory at the given offset in BAR
- `unsigned long maxlen`: max length of the memory to map

**Description**

Using this function you will get a __iomem address to your device BAR.
You can access it using ioread*() and iowrite*(). These functions hide
the details if this is a MMIO or PIO address space and will just do what
you expect from them in the correct way.

**maxlen** specifies the maximum length to map. If you want to get access to
the complete BAR from offset to the end, pass `0` here.

#### <a id="c-pci_iomap_wc_range"></a>`pci_iomap_wc_range()`

```c
void __iomem * pci_iomap_wc_range(struct pci_dev *dev, int bar, unsigned long offset, unsigned long maxlen)
```

create a virtual WC mapping cookie for a PCI BAR

**Parameters**

- `struct pci_dev *dev`: PCI device that owns the BAR
- `int bar`: BAR number
- `unsigned long offset`: map memory at the given offset in BAR
- `unsigned long maxlen`: max length of the memory to map

**Description**

Using this function you will get a __iomem address to your device BAR.
You can access it using ioread*() and iowrite*(). These functions hide
the details if this is a MMIO or PIO address space and will just do what
you expect from them in the correct way. When possible write combining
is used.

**maxlen** specifies the maximum length to map. If you want to get access to
the complete BAR from offset to the end, pass `0` here.

#### <a id="c-pci_iomap"></a>`pci_iomap()`

```c
void __iomem * pci_iomap(struct pci_dev *dev, int bar, unsigned long maxlen)
```

create a virtual mapping cookie for a PCI BAR

**Parameters**

- `struct pci_dev *dev`: PCI device that owns the BAR
- `int bar`: BAR number
- `unsigned long maxlen`: length of the memory to map

**Description**

Using this function you will get a __iomem address to your device BAR.
You can access it using ioread*() and iowrite*(). These functions hide
the details if this is a MMIO or PIO address space and will just do what
you expect from them in the correct way.

**maxlen** specifies the maximum length to map. If you want to get access to
the complete BAR without checking for its length first, pass `0` here.

#### <a id="c-pci_iomap_wc"></a>`pci_iomap_wc()`

```c
void __iomem * pci_iomap_wc(struct pci_dev *dev, int bar, unsigned long maxlen)
```

create a virtual WC mapping cookie for a PCI BAR

**Parameters**

- `struct pci_dev *dev`: PCI device that owns the BAR
- `int bar`: BAR number
- `unsigned long maxlen`: length of the memory to map

**Description**

Using this function you will get a __iomem address to your device BAR.
You can access it using ioread*() and iowrite*(). These functions hide
the details if this is a MMIO or PIO address space and will just do what
you expect from them in the correct way. When possible write combining
is used.

**maxlen** specifies the maximum length to map. If you want to get access to
the complete BAR without checking for its length first, pass `0` here.



#### <a id="c-devm_pci_remap_iospace"></a>`devm_pci_remap_iospace()`

```c
int devm_pci_remap_iospace(struct device *dev, const struct resource *res, phys_addr_t phys_addr)
```

Managed [`pci_remap_iospace()`](#c-pci_remap_iospace)

**Parameters**

- `struct device *dev`: Generic device to remap IO address for
- `const struct resource *res`: Resource describing the I/O space
- `phys_addr_t phys_addr`: physical address of range to be mapped

**Description**

Managed [`pci_remap_iospace()`](#c-pci_remap_iospace).  Map is automatically unmapped on driver
detach.

#### <a id="c-devm_pci_remap_cfgspace"></a>`devm_pci_remap_cfgspace()`

```c
void __iomem * devm_pci_remap_cfgspace(struct device *dev, resource_size_t offset, resource_size_t size)
```

Managed `pci_remap_cfgspace()`

**Parameters**

- `struct device *dev`: Generic device to remap IO address for
- `resource_size_t offset`: Resource address to map
- `resource_size_t size`: Size of map

**Description**

Managed `pci_remap_cfgspace()`.  Map is automatically unmapped on driver
detach.

#### <a id="c-devm_pci_remap_cfg_resource"></a>`devm_pci_remap_cfg_resource()`

```c
void __iomem * devm_pci_remap_cfg_resource(struct device *dev, struct resource *res)
```

check, request region and ioremap cfg resource

**Parameters**

- `struct device *dev`: generic device to handle the resource for
- `struct resource *res`: configuration space resource to be handled

**Description**

Checks that a resource is a valid memory region, requests the memory
region and ioremaps with `pci_remap_cfgspace()` API that ensures the
proper PCI configuration space memory attributes are guaranteed.

All operations are managed and will be undone on driver detach.

Returns a pointer to the remapped memory or an `IOMEM_ERR_PTR()` encoded error
code on failure. Usage example:

```text
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
base = devm_pci_remap_cfg_resource(&pdev->dev, res);
if (IS_ERR(base))
        return PTR_ERR(base);
```

#### <a id="c-pcim_set_mwi"></a>`pcim_set_mwi()`

```c
int pcim_set_mwi(struct pci_dev *pdev)
```

a device-managed [`pci_set_mwi()`](#c-pci_set_mwi)

**Parameters**

- `struct pci_dev *pdev`: the PCI device for which MWI is enabled

**Description**

Managed [`pci_set_mwi()`](#c-pci_set_mwi).

**Return**

An appropriate -ERRNO error value on error, or zero for success.

#### <a id="c-pcim_intx"></a>`pcim_intx()`

```c
int pcim_intx(struct pci_dev *pdev, int enable)
```

managed [`pci_intx()`](#c-pci_intx)

**Parameters**

- `struct pci_dev *pdev`: the PCI device to operate on
- `int enable`: boolean: whether to enable or disable PCI INTx

**Return**

0 on success, -ENOMEM on error.

**Description**

Enable/disable PCI INTx for device **pdev**.
Restore the original state on driver detach.

#### <a id="c-pcim_enable_device"></a>`pcim_enable_device()`

```c
int pcim_enable_device(struct pci_dev *pdev)
```

Managed [`pci_enable_device()`](#c-pci_enable_device)

**Parameters**

- `struct pci_dev *pdev`: PCI device to be initialized

**Return**

0 on success, negative error code on failure.

**Description**

Managed [`pci_enable_device()`](#c-pci_enable_device). Device will automatically be disabled on
driver detach.

#### <a id="c-pcim_pin_device"></a>`pcim_pin_device()`

```c
void pcim_pin_device(struct pci_dev *pdev)
```

Pin managed PCI device

**Parameters**

- `struct pci_dev *pdev`: PCI device to pin

**Description**

Pin managed PCI device **pdev**. Pinned device won't be disabled on driver
detach. **pdev** must have been enabled with [`pcim_enable_device()`](#c-pcim_enable_device).

#### <a id="c-pcim_iomap_table"></a>`pcim_iomap_table()`

```c
void __iomem * const * pcim_iomap_table(struct pci_dev *pdev)
```

access iomap allocation table (DEPRECATED)

**Parameters**

- `struct pci_dev *pdev`: PCI device to access iomap table for

**Return**

Const pointer to array of __iomem pointers on success, NULL on failure.

**Description**

Access iomap allocation table for **dev**.  If iomap table doesn't
exist and **pdev** is managed, it will be allocated.  All iomaps
recorded in the iomap table are automatically unmapped on driver
detach.

This function might sleep when the table is first allocated but can
be safely called without context and guaranteed to succeed once
allocated.

This function is DEPRECATED. Do not use it in new code. Instead, obtain a
mapping's address directly from one of the pcim_* mapping functions. For

**example**

void __iomem \*mappy = pcim_iomap(pdev, bar, length);

#### <a id="c-pcim_iomap"></a>`pcim_iomap()`

```c
void __iomem * pcim_iomap(struct pci_dev *pdev, int bar, unsigned long maxlen)
```

Managed [`pcim_iomap()`](#c-pcim_iomap)

**Parameters**

- `struct pci_dev *pdev`: PCI device to iomap for
- `int bar`: BAR to iomap
- `unsigned long maxlen`: Maximum length of iomap

**Return**

__iomem pointer on success, NULL on failure.

**Description**

Managed [`pci_iomap()`](#c-pci_iomap). Map is automatically unmapped on driver detach. If
desired, unmap manually only with [`pcim_iounmap()`](#c-pcim_iounmap).

This SHOULD only be used once per BAR.

**NOTE**

Contrary to the other pcim_* functions, this function does not return an
`IOMEM_ERR_PTR()` on failure, but a simple NULL. This is done for backwards
compatibility.

#### <a id="c-pcim_iounmap"></a>`pcim_iounmap()`

```c
void pcim_iounmap(struct pci_dev *pdev, void __iomem *addr)
```

Managed `pci_iounmap()`

**Parameters**

- `struct pci_dev *pdev`: PCI device to iounmap for
- `void __iomem *addr`: Address to unmap

**Description**

Managed `pci_iounmap()`. **addr** must have been mapped using a pcim_* mapping
function.

#### <a id="c-pcim_iomap_region"></a>`pcim_iomap_region()`

```c
void __iomem * pcim_iomap_region(struct pci_dev *pdev, int bar, const char *name)
```

Request and iomap a PCI BAR

**Parameters**

- `struct pci_dev *pdev`: PCI device to map IO resources for
- `int bar`: Index of a BAR to map
- `const char *name`: Name of the driver requesting the resource

**Return**

__iomem pointer on success, an IOMEM_ERR_PTR on failure.

**Description**

Mapping and region will get automatically released on driver detach. If
desired, release manually only with [`pcim_iounmap_region()`](#c-pcim_iounmap_region).

#### <a id="c-pcim_iounmap_region"></a>`pcim_iounmap_region()`

```c
void pcim_iounmap_region(struct pci_dev *pdev, int bar)
```

Unmap and release a PCI BAR

**Parameters**

- `struct pci_dev *pdev`: PCI device to operate on
- `int bar`: Index of BAR to unmap and release

**Description**

Unmap a BAR and release its region manually. Only pass BARs that were
previously mapped by [`pcim_iomap_region()`](#c-pcim_iomap_region).

#### <a id="c-pcim_iomap_regions"></a>`pcim_iomap_regions()`

```c
int pcim_iomap_regions(struct pci_dev *pdev, int mask, const char *name)
```

Request and iomap PCI BARs (DEPRECATED)

**Parameters**

- `struct pci_dev *pdev`: PCI device to map IO resources for
- `int mask`: Mask of BARs to request and iomap
- `const char *name`: Name of the driver requesting the resources

**Return**

0 on success, negative error code on failure.

**Description**

Request and iomap regions specified by **mask**.

This function is DEPRECATED. Do not use it in new code.
Use [`pcim_iomap_region()`](#c-pcim_iomap_region) instead.

#### <a id="c-pcim_request_region"></a>`pcim_request_region()`

```c
int pcim_request_region(struct pci_dev *pdev, int bar, const char *name)
```

Request a PCI BAR

**Parameters**

- `struct pci_dev *pdev`: PCI device to request region for
- `int bar`: Index of BAR to request
- `const char *name`: Name of the driver requesting the resource

**Return**

0 on success, a negative error code on failure.

**Description**

Request region specified by **bar**.

The region will automatically be released on driver detach. If desired,
release manually only with `pcim_release_region()`.

#### <a id="c-pcim_request_all_regions"></a>`pcim_request_all_regions()`

```c
int pcim_request_all_regions(struct pci_dev *pdev, const char *name)
```

Request all regions

**Parameters**

- `struct pci_dev *pdev`: PCI device to map IO resources for
- `const char *name`: name of the driver requesting the resources

**Return**

0 on success, negative error code on failure.

**Description**

Requested regions will automatically be released at driver detach. If
desired, release individual regions with `pcim_release_region()` or all of
them at once with `pcim_release_all_regions()`.

#### <a id="c-pcim_iomap_range"></a>`pcim_iomap_range()`

```c
void __iomem * pcim_iomap_range(struct pci_dev *pdev, int bar, unsigned long offset, unsigned long len)
```

Create a ranged __iomap mapping within a PCI BAR

**Parameters**

- `struct pci_dev *pdev`: PCI device to map IO resources for
- `int bar`: Index of the BAR
- `unsigned long offset`: Offset from the begin of the BAR
- `unsigned long len`: Length in bytes for the mapping

**Return**

__iomem pointer on success, an IOMEM_ERR_PTR on failure.

**Description**

Creates a new IO-Mapping within the specified **bar**, ranging from **offset** to
**offset** + **len**.

The mapping will automatically get unmapped on driver detach. If desired,
release manually only with [`pcim_iounmap()`](#c-pcim_iounmap).



#### <a id="c-pci_add_dynid"></a>`pci_add_dynid()`

```c
int pci_add_dynid(struct pci_driver *drv, unsigned int vendor, unsigned int device, unsigned int subvendor, unsigned int subdevice, unsigned int class, unsigned int class_mask, unsigned long driver_data)
```

add a new PCI device ID to this driver and re-probe devices

**Parameters**

- `struct pci_driver *drv`: target pci driver
- `unsigned int vendor`: PCI vendor ID
- `unsigned int device`: PCI device ID
- `unsigned int subvendor`: PCI subvendor ID
- `unsigned int subdevice`: PCI subdevice ID
- `unsigned int class`: PCI class
- `unsigned int class_mask`: PCI class mask
- `unsigned long driver_data`: private driver data

**Description**

Adds a new dynamic pci device ID to this driver and causes the
driver to probe for all devices again.  **drv** must have been
registered prior to calling this function.

**Context**

Does GFP_KERNEL allocation.

**Return**

0 on success, -errno on failure.

#### <a id="c-pci_match_id"></a>`pci_match_id()`

```c
const struct pci_device_id * pci_match_id(const struct pci_device_id *ids, struct pci_dev *dev)
```

See if a PCI device matches a given pci_id table

**Parameters**

- `const struct pci_device_id *ids`: array of PCI device ID structures to search in
- `struct pci_dev *dev`: the PCI device structure to match against.

**Description**

Used by a driver to check whether a PCI device is in its list of
supported devices.  Returns the matching pci_device_id structure or
`NULL` if there is no match.

Deprecated; don't use this as it will not catch any dynamic IDs
that a driver might want to check for.

#### <a id="c-__pci_register_driver"></a>`__pci_register_driver()`

```c
int __pci_register_driver(struct pci_driver *drv, struct module *owner, const char *mod_name)
```

register a new pci driver

**Parameters**

- `struct pci_driver *drv`: the driver structure to register
- `struct module *owner`: owner module of drv
- `const char *mod_name`: module name string

**Description**

Adds the driver structure to the list of registered drivers.
Returns a negative value on error, otherwise 0.
If no error occurred, the driver remains registered even if
no device was claimed during registration.

#### <a id="c-pci_unregister_driver"></a>`pci_unregister_driver()`

```c
void pci_unregister_driver(struct pci_driver *drv)
```

unregister a pci driver

**Parameters**

- `struct pci_driver *drv`: the driver structure to unregister

**Description**

Deletes the driver structure from the list of registered PCI drivers,
gives it a chance to clean up by calling its `remove()` function for
each device it was responsible for, and marks those devices as
driverless.

#### <a id="c-pci_dev_driver"></a>`pci_dev_driver()`

```c
struct pci_driver * pci_dev_driver(const struct pci_dev *dev)
```

get the pci_driver of a device

**Parameters**

- `const struct pci_dev *dev`: the device to query

**Description**

Returns the appropriate pci_driver structure or `NULL` if there is no
registered driver for the device.

#### <a id="c-pci_dev_get"></a>`pci_dev_get()`

```c
struct pci_dev * pci_dev_get(struct pci_dev *dev)
```

increments the reference count of the pci device structure

**Parameters**

- `struct pci_dev *dev`: the device being referenced

**Description**

Each live reference to a device should be refcounted.

Drivers for PCI devices should normally record such references in
their `probe()` methods, when they bind to a device, and release
them by calling [`pci_dev_put()`](#c-pci_dev_put), in their `disconnect()` methods.

A pointer to the device with the incremented reference counter is returned.

#### <a id="c-pci_dev_put"></a>`pci_dev_put()`

```c
void pci_dev_put(struct pci_dev *dev)
```

release a use of the pci device structure

**Parameters**

- `struct pci_dev *dev`: device that's been disconnected

**Description**

Must be called when a user of a device is finished with it.  When the last
user of the device calls this function, the memory of the device is freed.



#### <a id="c-pci_stop_and_remove_bus_device"></a>`pci_stop_and_remove_bus_device()`

```c
void pci_stop_and_remove_bus_device(struct pci_dev *dev)
```

remove a PCI device and any children

**Parameters**

- `struct pci_dev *dev`: the device to remove

**Description**

Remove a PCI device from the device lists, informing the drivers
that the device has been removed.  We also remove any subordinate
buses and children in a depth-first manner.

For each device we remove, delete the device structure from the
device lists, remove the /proc entry, and notify userspace
(/sbin/hotplug).



#### <a id="c-pci_find_bus"></a>`pci_find_bus()`

```c
struct pci_bus * pci_find_bus(int domain, int busnr)
```

locate PCI bus from a given domain and bus number

**Parameters**

- `int domain`: number of PCI domain to search
- `int busnr`: number of desired PCI bus

**Description**

Given a PCI bus number and domain number, the desired PCI bus is located
in the global list of PCI buses.  If the bus is found, a pointer to its
data structure is returned.  If no bus is found, `NULL` is returned.

#### <a id="c-pci_find_next_bus"></a>`pci_find_next_bus()`

```c
struct pci_bus * pci_find_next_bus(const struct pci_bus *from)
```

begin or continue searching for a PCI bus

**Parameters**

- `const struct pci_bus *from`: Previous PCI bus found, or `NULL` for new search.

**Description**

Iterates through the list of known PCI buses.  A new search is
initiated by passing `NULL` as the **from** argument.  Otherwise if
**from** is not `NULL`, searches continue from next device on the
global list.

#### <a id="c-pci_get_slot"></a>`pci_get_slot()`

```c
struct pci_dev * pci_get_slot(struct pci_bus *bus, unsigned int devfn)
```

locate PCI device for a given PCI slot

**Parameters**

- `struct pci_bus *bus`: PCI bus on which desired PCI device resides
- `unsigned int devfn`: encodes number of PCI slot in which the desired PCI
  device resides and the logical device number within that slot
  in case of multi-function devices.

**Description**

Given a PCI bus and slot/function number, the desired PCI device
is located in the list of PCI devices.
If the device is found, its reference count is increased and this
function returns a pointer to its data structure.  The caller must
decrement the reference count by calling [`pci_dev_put()`](#c-pci_dev_put).
If no device is found, `NULL` is returned.

#### <a id="c-pci_get_domain_bus_and_slot"></a>`pci_get_domain_bus_and_slot()`

```c
struct pci_dev * pci_get_domain_bus_and_slot(int domain, unsigned int bus, unsigned int devfn)
```

locate PCI device for a given PCI domain (segment), bus, and slot

**Parameters**

- `int domain`: PCI domain/segment on which the PCI device resides.
- `unsigned int bus`: PCI bus on which desired PCI device resides
- `unsigned int devfn`: encodes number of PCI slot in which the desired PCI device
  resides and the logical device number within that slot in case of
  multi-function devices.

**Description**

Given a PCI domain, bus, and slot/function number, the desired PCI
device is located in the list of PCI devices. If the device is
found, its reference count is increased and this function returns a
pointer to its data structure.  The caller must decrement the
reference count by calling [`pci_dev_put()`](#c-pci_dev_put).  If no device is found,
`NULL` is returned.

#### <a id="c-pci_get_subsys"></a>`pci_get_subsys()`

```c
struct pci_dev * pci_get_subsys(unsigned int vendor, unsigned int device, unsigned int ss_vendor, unsigned int ss_device, struct pci_dev *from)
```

begin or continue searching for a PCI device by vendor/subvendor/device/subdevice id

**Parameters**

- `unsigned int vendor`: PCI vendor id to match, or `PCI_ANY_ID` to match all vendor ids
- `unsigned int device`: PCI device id to match, or `PCI_ANY_ID` to match all device ids
- `unsigned int ss_vendor`: PCI subsystem vendor id to match, or `PCI_ANY_ID` to match all vendor ids
- `unsigned int ss_device`: PCI subsystem device id to match, or `PCI_ANY_ID` to match all device ids
- `struct pci_dev *from`: Previous PCI device found in search, or `NULL` for new search.

**Description**

Iterates through the list of known PCI devices.  If a PCI device is found
with a matching **vendor**, **device**, **ss_vendor** and **ss_device**, a pointer to its
device structure is returned, and the reference count to the device is
incremented.  Otherwise, `NULL` is returned.  A new search is initiated by
passing `NULL` as the **from** argument.  Otherwise if **from** is not `NULL`,
searches continue from next device on the global list.
The reference count for **from** is always decremented if it is not `NULL`.

#### <a id="c-pci_get_device"></a>`pci_get_device()`

```c
struct pci_dev * pci_get_device(unsigned int vendor, unsigned int device, struct pci_dev *from)
```

begin or continue searching for a PCI device by vendor/device id

**Parameters**

- `unsigned int vendor`: PCI vendor id to match, or `PCI_ANY_ID` to match all vendor ids
- `unsigned int device`: PCI device id to match, or `PCI_ANY_ID` to match all device ids
- `struct pci_dev *from`: Previous PCI device found in search, or `NULL` for new search.

**Description**

Iterates through the list of known PCI devices.  If a PCI device is
found with a matching **vendor** and **device**, the reference count to the
device is incremented and a pointer to its device structure is returned.
Otherwise, `NULL` is returned.  A new search is initiated by passing `NULL`
as the **from** argument.  Otherwise if **from** is not `NULL`, searches continue
from next device on the global list.  The reference count for **from** is
always decremented if it is not `NULL`.

#### <a id="c-pci_get_class"></a>`pci_get_class()`

```c
struct pci_dev * pci_get_class(unsigned int class, struct pci_dev *from)
```

begin or continue searching for a PCI device by class

**Parameters**

- `unsigned int class`: search for a PCI device with this class designation
- `struct pci_dev *from`: Previous PCI device found in search, or `NULL` for new search.

**Description**

Iterates through the list of known PCI devices.  If a PCI device is
found with a matching **class**, the reference count to the device is
incremented and a pointer to its device structure is returned.
Otherwise, `NULL` is returned.
A new search is initiated by passing `NULL` as the **from** argument.
Otherwise if **from** is not `NULL`, searches continue from next device
on the global list.  The reference count for **from** is always decremented
if it is not `NULL`.

#### <a id="c-pci_get_base_class"></a>`pci_get_base_class()`

```c
struct pci_dev * pci_get_base_class(unsigned int class, struct pci_dev *from)
```

searching for a PCI device by matching against the base class code only

**Parameters**

- `unsigned int class`: search for a PCI device with this base class code
- `struct pci_dev *from`: Previous PCI device found in search, or `NULL` for new search.

**Description**

Iterates through the list of known PCI devices. If a PCI device is found
with a matching base class code, the reference count to the device is
incremented. See `pci_match_one_device()` to figure out how does this works.
A new search is initiated by passing `NULL` as the **from** argument.
Otherwise if **from** is not `NULL`, searches continue from next device on the
global list. The reference count for **from** is always decremented if it is
not `NULL`.

**Return**

A pointer to a matched PCI device, `NULL` Otherwise.

#### <a id="c-pci_dev_present"></a>`pci_dev_present()`

```c
int pci_dev_present(const struct pci_device_id *ids)
```

Returns 1 if device matching the device list is present, 0 if not.

**Parameters**

- `const struct pci_device_id *ids`: A pointer to a null terminated list of struct pci_device_id structures
  that describe the type of PCI device the caller is trying to find.

**Description**

Obvious fact: You do not have a reference to any device that might be found
by this function, so if that device is removed from the system right after
this function is finished, the value will be stale.  Use this function to
find devices that are usually built into a system, or for a general hint as
to if another device happens to be present at this specific moment in time.



#### <a id="c-pci_msi_mask_irq"></a>`pci_msi_mask_irq()`

```c
void pci_msi_mask_irq(struct irq_data *data)
```

Generic IRQ chip callback to mask PCI/MSI interrupts

**Parameters**

- `struct irq_data *data`: pointer to irqdata associated to that interrupt

#### <a id="c-pci_msi_unmask_irq"></a>`pci_msi_unmask_irq()`

```c
void pci_msi_unmask_irq(struct irq_data *data)
```

Generic IRQ chip callback to unmask PCI/MSI interrupts

**Parameters**

- `struct irq_data *data`: pointer to irqdata associated to that interrupt

#### <a id="c-pci_msi_vec_count"></a>`pci_msi_vec_count()`

```c
int pci_msi_vec_count(struct pci_dev *dev)
```

Return the number of MSI vectors a device can send

**Parameters**

- `struct pci_dev *dev`: device to report about

**Description**

This function returns the number of MSI vectors a device requested via
Multiple Message Capable register. It returns a negative errno if the
device is not capable sending MSI interrupts. Otherwise, the call succeeds
and returns a power of two, up to a maximum of 2^5 (32), according to the
MSI specification.



#### <a id="c-pci_bus_alloc_resource"></a>`pci_bus_alloc_resource()`

```c
int pci_bus_alloc_resource(struct pci_bus *bus, struct resource *res, resource_size_t size, resource_size_t align, resource_size_t min, unsigned long type_mask, resource_alignf alignf, void *alignf_data)
```

allocate a resource from a parent bus

**Parameters**

- `struct pci_bus *bus`: PCI bus
- `struct resource *res`: resource to allocate
- `resource_size_t size`: size of resource to allocate
- `resource_size_t align`: alignment of resource to allocate
- `resource_size_t min`: minimum /proc/iomem address to allocate
- `unsigned long type_mask`: IORESOURCE_* type flags
- `resource_alignf alignf`: resource alignment function
- `void *alignf_data`: data argument for resource alignment function

**Description**

Given the PCI bus a device resides on, the size, minimum address,
alignment and type, try to find an acceptable resource allocation
for a specific device resource.

#### <a id="c-pci_bus_add_device"></a>`pci_bus_add_device()`

```c
void pci_bus_add_device(struct pci_dev *dev)
```

start driver for a single device

**Parameters**

- `struct pci_dev *dev`: device to add

**Description**

This adds add sysfs entries and start device drivers

#### <a id="c-pci_bus_add_devices"></a>`pci_bus_add_devices()`

```c
void pci_bus_add_devices(const struct pci_bus *bus)
```

start driver for PCI devices

**Parameters**

- `const struct pci_bus *bus`: bus to check for new devices

**Description**

Start driver for PCI devices and add some sysfs entries.

#### <a id="c-pci_walk_bus"></a>`pci_walk_bus()`

```c
void pci_walk_bus(struct pci_bus *top, int (*cb)(struct pci_dev *, void *), void *userdata)
```

walk devices on/under bus, calling callback.

**Parameters**

- `struct pci_bus *top`: bus whose devices should be walked
- `int (*cb)(struct pci_dev *, void *)`: callback to be called for each device found
- `void *userdata`: arbitrary pointer to be passed to callback

**Description**

Walk the given bus, including any bridged devices
on buses under this bus.  Call the provided callback
on each device found.

We check the return of **cb** each time. If it returns anything
other than 0, we break out.

#### <a id="c-pci_walk_bus_reverse"></a>`pci_walk_bus_reverse()`

```c
void pci_walk_bus_reverse(struct pci_bus *top, int (*cb)(struct pci_dev *, void *), void *userdata)
```

walk devices on/under bus, calling callback.

**Parameters**

- `struct pci_bus *top`: bus whose devices should be walked
- `int (*cb)(struct pci_dev *, void *)`: callback to be called for each device found
- `void *userdata`: arbitrary pointer to be passed to callback

**Description**

Same semantics as [`pci_walk_bus()`](#c-pci_walk_bus), but walks the bus in reverse order.



#### <a id="c-pci_bus_set_ops"></a>`pci_bus_set_ops()`

```c
struct pci_ops * pci_bus_set_ops(struct pci_bus *bus, struct pci_ops *ops)
```

Set raw operations of pci bus

**Parameters**

- `struct pci_bus *bus`: pci bus struct
- `struct pci_ops *ops`: new raw operations

**Description**

Return previous raw operations

#### <a id="c-pci_cfg_access_lock"></a>`pci_cfg_access_lock()`

```c
void pci_cfg_access_lock(struct pci_dev *dev)
```

Lock PCI config reads/writes

**Parameters**

- `struct pci_dev *dev`: pci device struct

**Description**

When access is locked, any userspace reads or writes to config
space and concurrent lock requests will sleep until access is
allowed via [`pci_cfg_access_unlock()`](#c-pci_cfg_access_unlock) again.

#### <a id="c-pci_cfg_access_trylock"></a>`pci_cfg_access_trylock()`

```c
bool pci_cfg_access_trylock(struct pci_dev *dev)
```

try to lock PCI config reads/writes

**Parameters**

- `struct pci_dev *dev`: pci device struct

**Description**

Same as pci_cfg_access_lock, but will return 0 if access is
already locked, 1 otherwise. This function can be used from
atomic contexts.

#### <a id="c-pci_cfg_access_unlock"></a>`pci_cfg_access_unlock()`

```c
void pci_cfg_access_unlock(struct pci_dev *dev)
```

Unlock PCI config reads/writes

**Parameters**

- `struct pci_dev *dev`: pci device struct

**Description**

This function allows PCI config accesses to resume.



#### <a id="c-pci_request_irq"></a>`pci_request_irq()`

```c
int pci_request_irq(struct pci_dev *dev, unsigned int nr, irq_handler_t handler, irq_handler_t thread_fn, void *dev_id, const char *fmt, ...)
```

allocate an interrupt line for a PCI device

**Parameters**

- `struct pci_dev *dev`: PCI device to operate on
- `unsigned int nr`: device-relative interrupt vector index (0-based).
- `irq_handler_t handler`: Function to be called when the IRQ occurs.
  Primary handler for threaded interrupts.
  If NULL and thread_fn != NULL the default primary handler is
  installed.
- `irq_handler_t thread_fn`: Function called from the IRQ handler thread
  If NULL, no IRQ thread is created
- `void *dev_id`: Cookie passed back to the handler function
- `const char *fmt`: Printf-like format string naming the handler
- `...`: variable arguments

**Description**

This call allocates interrupt resources and enables the interrupt line and
IRQ handling. From the point this call is made **handler** and **thread_fn** may
be invoked.  All interrupts requested using this function might be shared.

**dev_id** must not be NULL and must be globally unique.

#### <a id="c-pci_free_irq"></a>`pci_free_irq()`

```c
void pci_free_irq(struct pci_dev *dev, unsigned int nr, void *dev_id)
```

free an interrupt allocated with pci_request_irq

**Parameters**

- `struct pci_dev *dev`: PCI device to operate on
- `unsigned int nr`: device-relative interrupt vector index (0-based).
- `void *dev_id`: Device identity to free

**Description**

Remove an interrupt handler. The handler is removed and if the interrupt
line is no longer in use by any driver it is disabled.  The caller must
ensure the interrupt is disabled on the device before calling this function.
The function does not return until any executing interrupts for this IRQ
have completed.

This function must not be called from interrupt context.

#### <a id="c-pci_common_swizzle"></a>`pci_common_swizzle()`

```c
u8 pci_common_swizzle(struct pci_dev *dev, u8 *pinp)
```

swizzle INTx all the way to root bridge

**Parameters**

- `struct pci_dev *dev`: the PCI device
- `u8 *pinp`: pointer to the INTx pin value (1=INTA, 2=INTB, 3=INTD, 4=INTD)

**Description**

Perform INTx swizzling for a device.  This traverses through all PCI-to-PCI
bridges all the way up to a PCI root bus.

#### <a id="c-pci_check_and_mask_intx"></a>`pci_check_and_mask_intx()`

```c
bool pci_check_and_mask_intx(struct pci_dev *dev)
```

mask INTx on pending interrupt

**Parameters**

- `struct pci_dev *dev`: the PCI device to operate on

**Description**

Check if the device dev has its INTx line asserted, mask it and return
true in that case. False is returned if no interrupt was pending.

#### <a id="c-pci_check_and_unmask_intx"></a>`pci_check_and_unmask_intx()`

```c
bool pci_check_and_unmask_intx(struct pci_dev *dev)
```

unmask INTx if no interrupt is pending

**Parameters**

- `struct pci_dev *dev`: the PCI device to operate on

**Description**

Check if the device dev has its INTx line asserted, unmask it if not and
return true. False is returned and the mask remains active if there was
still an interrupt pending.



#### <a id="c-pcie_relaxed_ordering_enabled"></a>`pcie_relaxed_ordering_enabled()`

```c
bool pcie_relaxed_ordering_enabled(struct pci_dev *dev)
```

Probe for PCIe relaxed ordering enable

**Parameters**

- `struct pci_dev *dev`: PCI device to query

**Description**

Returns true if the device has enabled relaxed ordering attribute.

#### <a id="c-pci_scan_slot"></a>`pci_scan_slot()`

```c
int pci_scan_slot(struct pci_bus *bus, int devfn)
```

Scan a PCI slot on a bus for devices

**Parameters**

- `struct pci_bus *bus`: PCI bus to scan
- `int devfn`: slot number to scan (must have zero function)

**Description**

Scan a PCI slot on the specified PCI bus for devices, adding
discovered devices to the **bus->devices** list.  New devices
will not have is_added set.

Returns the number of new devices found.

#### <a id="c-pci_scan_child_bus"></a>`pci_scan_child_bus()`

```c
unsigned int pci_scan_child_bus(struct pci_bus *bus)
```

Scan devices below a bus

**Parameters**

- `struct pci_bus *bus`: Bus to scan for devices

**Description**

Scans devices below **bus** including subordinate buses. Returns new
subordinate number including all the found devices.

#### <a id="c-pci_rescan_bus"></a>`pci_rescan_bus()`

```c
unsigned int pci_rescan_bus(struct pci_bus *bus)
```

Scan a PCI bus for devices

**Parameters**

- `struct pci_bus *bus`: PCI bus to scan

**Description**

Scan a PCI bus and child buses for new devices, add them,
and enable them.

Returns the max number of subordinate bus discovered.



#### <a id="c-pci_create_slot"></a>`pci_create_slot()`

```c
struct pci_slot * pci_create_slot(struct pci_bus *parent, int slot_nr, const char *name, struct hotplug_slot *hotplug)
```

create or increment refcount for physical PCI slot

**Parameters**

- `struct pci_bus *parent`: struct pci_bus of parent bridge
- `int slot_nr`: PCI_SLOT(pci_dev->devfn) or -1 for placeholder
- `const char *name`: user visible string presented in /sys/bus/pci/slots/\<name>
- `struct hotplug_slot *hotplug`: set if caller is hotplug driver, NULL otherwise

**Description**

PCI slots have first class attributes such as address, speed, width,
and a `struct pci_slot` is used to manage them. This interface will
either return a new `struct pci_slot` to the caller, or if the pci_slot
already exists, its refcount will be incremented.

Slots are uniquely identified by a **pci_bus**, **slot_nr** tuple.

There are known platforms with broken firmware that assign the same
name to multiple slots. Workaround these broken platforms by renaming
the slots on behalf of the caller. If firmware assigns name N to
multiple slots:

The first slot is assigned N
The second slot is assigned N-1
The third slot is assigned N-2
etc.

Placeholder slots:
In most cases, **pci_bus**, **slot_nr** will be sufficient to uniquely identify
a slot. There is one notable exception - pSeries (rpaphp), where the
**slot_nr** cannot be determined until a device is actually inserted into
the slot. In this scenario, the caller may pass -1 for **slot_nr**.

The following semantics are imposed when the caller passes **slot_nr** ==
-1. First, we no longer check for an existing `struct` pci_slot, as there
may be many slots with **slot_nr** of -1.  The other change in semantics is
user-visible, which is the 'address' parameter presented in sysfs will
consist solely of a dddd:bb tuple, where dddd is the PCI domain of the
`struct` pci_bus and bb is the bus number. In other words, the devfn of
the 'placeholder' slot will not be displayed.

#### <a id="c-pci_destroy_slot"></a>`pci_destroy_slot()`

```c
void pci_destroy_slot(struct pci_slot *slot)
```

decrement refcount for physical PCI slot

**Parameters**

- `struct pci_slot *slot`: struct pci_slot to decrement

**Description**

`struct` pci_slot is refcounted, so destroying them is really easy; we
just call kobject_put on its kobj and let our release methods do the
rest.



#### <a id="c-pci_rebar_bytes_to_size"></a>`pci_rebar_bytes_to_size()`

```c
int pci_rebar_bytes_to_size(u64 bytes)
```

Convert size in bytes to PCI BAR Size

**Parameters**

- `u64 bytes`: size in bytes

**Description**

Convert size in bytes to encoded BAR Size in Resizable BAR Capability
(PCIe r6.2, sec. 7.8.6.3).

**Return**

encoded BAR Size as defined in the PCIe spec (0=1MB, 31=128TB)

#### <a id="c-pci_rebar_size_to_bytes"></a>`pci_rebar_size_to_bytes()`

```c
resource_size_t pci_rebar_size_to_bytes(int size)
```

Convert encoded BAR Size to size in bytes

**Parameters**

- `int size`: encoded BAR Size as defined in the PCIe spec (0=1MB, 31=128TB)

**Return**

BAR size in bytes

#### <a id="c-pci_rebar_get_possible_sizes"></a>`pci_rebar_get_possible_sizes()`

```c
u64 pci_rebar_get_possible_sizes(struct pci_dev *pdev, int bar)
```

get possible sizes for Resizable BAR

**Parameters**

- `struct pci_dev *pdev`: PCI device
- `int bar`: BAR to query

**Description**

Get the possible sizes of a resizable BAR as bitmask.

**Return**

A bitmask of possible sizes (bit 0=1MB, bit 31=128TB), or `0` if
BAR isn't resizable.

#### <a id="c-pci_rebar_size_supported"></a>`pci_rebar_size_supported()`

```c
bool pci_rebar_size_supported(struct pci_dev *pdev, int bar, int size)
```

check if size is supported for BAR

**Parameters**

- `struct pci_dev *pdev`: PCI device
- `int bar`: BAR to check
- `int size`: encoded size as defined in the PCIe spec (0=1MB, 31=128TB)

**Return**

`true` if **bar** is resizable and **size** is supported, otherwise
`false`.

#### <a id="c-pci_rebar_get_max_size"></a>`pci_rebar_get_max_size()`

```c
int pci_rebar_get_max_size(struct pci_dev *pdev, int bar)
```

get the maximum supported size of a BAR

**Parameters**

- `struct pci_dev *pdev`: PCI device
- `int bar`: BAR to query

**Description**

Get the largest supported size of a resizable BAR as a size.

**Return**

the encoded maximum BAR size as defined in the PCIe spec
(0=1MB, 31=128TB), or `-NOENT` on error.

#### <a id="c-pci_resize_resource"></a>`pci_resize_resource()`

```c
int pci_resize_resource(struct pci_dev *dev, int resno, int size, int exclude_bars)
```

reconfigure a Resizable BAR and resources

**Parameters**

- `struct pci_dev *dev`: the PCI device
- `int resno`: index of the BAR to be resized
- `int size`: new size as defined in the spec (0=1MB, 31=128TB)
- `int exclude_bars`: a mask of BARs that should not be released

**Description**

Reconfigure **resno** to **size** and re-run resource assignment algorithm
with the new size.

Prior to resize, release **dev** resources that share a bridge window with
**resno**.  This unpins the bridge window resource to allow changing it.

The caller may prevent releasing a particular BAR by providing
**exclude_bars** mask, but this may result in the resize operation failing
due to insufficient space.

**Return**

0 on success, or negative on error. In case of an error, the
resources are restored to their original places.



#### <a id="c-pci_enable_rom"></a>`pci_enable_rom()`

```c
int pci_enable_rom(struct pci_dev *pdev)
```

enable ROM decoding for a PCI device

**Parameters**

- `struct pci_dev *pdev`: PCI device to enable

**Description**

Enable ROM decoding on **dev**.  This involves simply turning on the last
bit of the PCI ROM BAR.  Note that some cards may share address decoders
between the ROM and other resources, so enabling it may disable access
to MMIO registers or other card memory.

#### <a id="c-pci_disable_rom"></a>`pci_disable_rom()`

```c
void pci_disable_rom(struct pci_dev *pdev)
```

disable ROM decoding for a PCI device

**Parameters**

- `struct pci_dev *pdev`: PCI device to disable

**Description**

Disable ROM decoding on a PCI device by turning off the last bit in the
ROM BAR.

#### <a id="c-pci_map_rom"></a>`pci_map_rom()`

```c
void __iomem * pci_map_rom(struct pci_dev *pdev, size_t *size)
```

map a PCI ROM to kernel space

**Parameters**

- `struct pci_dev *pdev`: pointer to pci device struct
- `size_t *size`: pointer to receive size of pci window over ROM

**Return**

kernel virtual pointer to image of ROM

**Description**

Map a PCI ROM into kernel space. If ROM is boot video ROM,
the shadow BIOS copy will be returned instead of the
actual ROM.

#### <a id="c-pci_unmap_rom"></a>`pci_unmap_rom()`

```c
void pci_unmap_rom(struct pci_dev *pdev, void __iomem *rom)
```

unmap the ROM from kernel space

**Parameters**

- `struct pci_dev *pdev`: pointer to pci device struct
- `void __iomem *rom`: virtual address of the previous mapping

**Description**

Remove a mapping of a previously mapped ROM



#### <a id="c-pci_iov_get_pf_drvdata"></a>`pci_iov_get_pf_drvdata()`

```c
void * pci_iov_get_pf_drvdata(struct pci_dev *dev, struct pci_driver *pf_driver)
```

Return the drvdata of a PF

**Parameters**

- `struct pci_dev *dev`: VF pci_dev
- `struct pci_driver *pf_driver`: Device driver required to own the PF

**Description**

This must be called from a context that ensures that a VF driver is attached.
The value returned is invalid once the VF driver completes its `remove()`
callback.

Locking is achieved by the driver core. A VF driver cannot be probed until
[`pci_enable_sriov()`](#c-pci_enable_sriov) is called and [`pci_disable_sriov()`](#c-pci_disable_sriov) does not return until
all VF drivers have completed their `remove()`.

The PF driver must call [`pci_disable_sriov()`](#c-pci_disable_sriov) before it begins to destroy the
drvdata.

#### <a id="c-pci_enable_sriov"></a>`pci_enable_sriov()`

```c
int pci_enable_sriov(struct pci_dev *dev, int nr_virtfn)
```

enable the SR-IOV capability

**Parameters**

- `struct pci_dev *dev`: the PCI device
- `int nr_virtfn`: number of virtual functions to enable

**Description**

Returns 0 on success, or negative on failure.

#### <a id="c-pci_disable_sriov"></a>`pci_disable_sriov()`

```c
void pci_disable_sriov(struct pci_dev *dev)
```

disable the SR-IOV capability

**Parameters**

- `struct pci_dev *dev`: the PCI device

#### <a id="c-pci_num_vf"></a>`pci_num_vf()`

```c
int pci_num_vf(struct pci_dev *dev)
```

return number of VFs associated with a PF device_release_driver

**Parameters**

- `struct pci_dev *dev`: the PCI device

**Description**

Returns number of VFs, or 0 if SR-IOV is not enabled.

#### <a id="c-pci_vfs_assigned"></a>`pci_vfs_assigned()`

```c
int pci_vfs_assigned(struct pci_dev *dev)
```

returns number of VFs are assigned to a guest

**Parameters**

- `struct pci_dev *dev`: the PCI device

**Description**

Returns number of VFs belonging to this device that are assigned to a guest.
If device is not a physical function returns 0.

#### <a id="c-pci_sriov_set_totalvfs"></a>`pci_sriov_set_totalvfs()`

```c
int pci_sriov_set_totalvfs(struct pci_dev *dev, u16 numvfs)
```

- reduce the TotalVFs available

**Parameters**

- `struct pci_dev *dev`: the PCI PF device
- `u16 numvfs`: number that should be used for TotalVFs supported

**Description**

Should be called from PF driver's probe routine with
device's mutex held.

Returns 0 if PF is an SRIOV-capable device and
value of numvfs valid. If not a PF return -ENOSYS;
if numvfs is invalid return -EINVAL;
if VFs already enabled, return -EBUSY.

#### <a id="c-pci_sriov_get_totalvfs"></a>`pci_sriov_get_totalvfs()`

```c
int pci_sriov_get_totalvfs(struct pci_dev *dev)
```

- get total VFs supported on this device

**Parameters**

- `struct pci_dev *dev`: the PCI PF device

**Description**

For a PCIe device with SRIOV support, return the PCIe
SRIOV capability value of TotalVFs or the value of driver_max_VFs
if the driver reduced it.  Otherwise 0.

#### <a id="c-pci_sriov_configure_simple"></a>`pci_sriov_configure_simple()`

```c
int pci_sriov_configure_simple(struct pci_dev *dev, int nr_virtfn)
```

helper to configure SR-IOV

**Parameters**

- `struct pci_dev *dev`: the PCI device
- `int nr_virtfn`: number of virtual functions to enable, 0 to disable

**Description**

Enable or disable SR-IOV for devices that don't require any PF setup
before enabling SR-IOV.  Return value is negative on error, or number of
VFs allocated on success.

#### <a id="c-pci_iov_vf_bar_set_size"></a>`pci_iov_vf_bar_set_size()`

```c
int pci_iov_vf_bar_set_size(struct pci_dev *dev, int resno, int size)
```

set a new size for a VF BAR

**Parameters**

- `struct pci_dev *dev`: the PCI device
- `int resno`: the resource number
- `int size`: new size as defined in the spec (0=1MB, 31=128TB)

**Description**

Set the new size of a VF BAR that supports VF resizable BAR capability.
Unlike [`pci_resize_resource()`](#c-pci_resize_resource), this does not cause the resource that
reserves the MMIO space (originally up to total_VFs) to be resized, which
means that following calls to [`pci_enable_sriov()`](#c-pci_enable_sriov) can fail if the resources
no longer fit.

**Return**

0 on success, or negative on failure.

#### <a id="c-pci_iov_vf_bar_get_sizes"></a>`pci_iov_vf_bar_get_sizes()`

```c
u32 pci_iov_vf_bar_get_sizes(struct pci_dev *dev, int resno, int num_vfs)
```

get VF BAR sizes allowing to create up to num_vfs

**Parameters**

- `struct pci_dev *dev`: the PCI device
- `int resno`: the resource number
- `int num_vfs`: number of VFs

**Description**

Get the sizes of a VF resizable BAR that can accommodate **num_vfs** within
the currently assigned size of the resource **resno**.

**Return**

A bitmask of sizes in format defined in the spec (bit 0=1MB,
bit 31=128TB).



#### <a id="c-pci_read_legacy_io"></a>`pci_read_legacy_io()`

```c
ssize_t pci_read_legacy_io(struct file *filp, struct kobject *kobj, const struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count)
```

read byte(s) from legacy I/O port space

**Parameters**

- `struct file *filp`: open sysfs file
- `struct kobject *kobj`: kobject corresponding to file to read from
- `const struct bin_attribute *bin_attr`: struct bin_attribute for this file
- `char *buf`: buffer to store results
- `loff_t off`: offset into legacy I/O port space
- `size_t count`: number of bytes to read

**Description**

Reads 1, 2, or 4 bytes from legacy I/O port space using an arch specific
callback routine (pci_legacy_read).

#### <a id="c-pci_write_legacy_io"></a>`pci_write_legacy_io()`

```c
ssize_t pci_write_legacy_io(struct file *filp, struct kobject *kobj, const struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count)
```

write byte(s) to legacy I/O port space

**Parameters**

- `struct file *filp`: open sysfs file
- `struct kobject *kobj`: kobject corresponding to file to read from
- `const struct bin_attribute *bin_attr`: struct bin_attribute for this file
- `char *buf`: buffer containing value to be written
- `loff_t off`: offset into legacy I/O port space
- `size_t count`: number of bytes to write

**Description**

Writes 1, 2, or 4 bytes from legacy I/O port space using an arch specific
callback routine (pci_legacy_write).

#### <a id="c-pci_mmap_legacy_mem"></a>`pci_mmap_legacy_mem()`

```c
int pci_mmap_legacy_mem(struct file *filp, struct kobject *kobj, const struct bin_attribute *attr, struct vm_area_struct *vma)
```

map legacy PCI memory into user memory space

**Parameters**

- `struct file *filp`: open sysfs file
- `struct kobject *kobj`: kobject corresponding to device to be mapped
- `const struct bin_attribute *attr`: struct bin_attribute for this file
- `struct vm_area_struct *vma`: struct vm_area_struct passed to mmap

**Description**

Uses an arch specific callback, pci_mmap_legacy_mem_page_range, to mmap
legacy memory space (first meg of bus space) into application virtual
memory space.

#### <a id="c-pci_mmap_legacy_io"></a>`pci_mmap_legacy_io()`

```c
int pci_mmap_legacy_io(struct file *filp, struct kobject *kobj, const struct bin_attribute *attr, struct vm_area_struct *vma)
```

map legacy PCI IO into user memory space

**Parameters**

- `struct file *filp`: open sysfs file
- `struct kobject *kobj`: kobject corresponding to device to be mapped
- `const struct bin_attribute *attr`: struct bin_attribute for this file
- `struct vm_area_struct *vma`: struct vm_area_struct passed to mmap

**Description**

Uses an arch specific callback, pci_mmap_legacy_io_page_range, to mmap
legacy IO space (first meg of bus space) into application virtual
memory space. Returns -ENOSYS if the operation isn't supported

#### <a id="c-pci_adjust_legacy_attr"></a>`pci_adjust_legacy_attr()`

```c
void pci_adjust_legacy_attr(struct pci_bus *b, enum pci_mmap_state mmap_type)
```

adjustment of legacy file attributes

**Parameters**

- `struct pci_bus *b`: bus to create files under
- `enum pci_mmap_state mmap_type`: I/O port or memory

**Description**

Stub implementation. Can be overridden by arch if necessary.

#### <a id="c-pci_create_legacy_files"></a>`pci_create_legacy_files()`

```c
void pci_create_legacy_files(struct pci_bus *b)
```

create legacy I/O port and memory files

**Parameters**

- `struct pci_bus *b`: bus to create files under

**Description**

Some platforms allow access to legacy I/O port and ISA memory space on
a per-bus basis.  This routine creates the files and ties them into
their associated read, write and mmap files from pci-sysfs.c

On error unwind, but don't propagate the error to the caller
as it is ok to set up the PCI bus without these files.

#### <a id="c-pci_mmap_resource"></a>`pci_mmap_resource()`

```c
int pci_mmap_resource(struct kobject *kobj, const struct bin_attribute *attr, struct vm_area_struct *vma, int write_combine)
```

map a PCI resource into user memory space

**Parameters**

- `struct kobject *kobj`: kobject for mapping
- `const struct bin_attribute *attr`: struct bin_attribute for the file being mapped
- `struct vm_area_struct *vma`: struct vm_area_struct passed into the mmap
- `int write_combine`: 1 for write_combine mapping

**Description**

Use the regular PCI mapping routines to map a PCI resource into userspace.

#### <a id="c-pci_remove_resource_files"></a>`pci_remove_resource_files()`

```c
void pci_remove_resource_files(struct pci_dev *pdev)
```

cleanup resource files

**Parameters**

- `struct pci_dev *pdev`: dev to cleanup

**Description**

If we created resource files for **pdev**, remove them from sysfs and
free their resources.

#### <a id="c-pci_create_resource_files"></a>`pci_create_resource_files()`

```c
int pci_create_resource_files(struct pci_dev *pdev)
```

create resource files in sysfs for **dev**

**Parameters**

- `struct pci_dev *pdev`: dev in question

**Description**

Walk the resources in **pdev** creating files for each resource available.

#### <a id="c-pci_write_rom"></a>`pci_write_rom()`

```c
ssize_t pci_write_rom(struct file *filp, struct kobject *kobj, const struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count)
```

used to enable access to the PCI ROM display

**Parameters**

- `struct file *filp`: sysfs file
- `struct kobject *kobj`: kernel object handle
- `const struct bin_attribute *bin_attr`: struct bin_attribute for this file
- `char *buf`: user input
- `loff_t off`: file offset
- `size_t count`: number of byte in input

**Description**

writing anything except 0 enables it

#### <a id="c-pci_read_rom"></a>`pci_read_rom()`

```c
ssize_t pci_read_rom(struct file *filp, struct kobject *kobj, const struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count)
```

read a PCI ROM

**Parameters**

- `struct file *filp`: sysfs file
- `struct kobject *kobj`: kernel object handle
- `const struct bin_attribute *bin_attr`: struct bin_attribute for this file
- `char *buf`: where to put the data we read from the ROM
- `loff_t off`: file offset
- `size_t count`: number of bytes to read

**Description**

Put **count** bytes starting at **off** into **buf** from the ROM in the PCI
device corresponding to **kobj**.

#### <a id="c-pci_remove_sysfs_dev_files"></a>`pci_remove_sysfs_dev_files()`

```c
void pci_remove_sysfs_dev_files(struct pci_dev *pdev)
```

cleanup PCI specific sysfs files

**Parameters**

- `struct pci_dev *pdev`: device whose entries we should free

**Description**

Cleanup when **pdev** is removed from sysfs.



#### <a id="c-pcie_tph_get_st_table_loc"></a>`pcie_tph_get_st_table_loc()`

```c
u32 pcie_tph_get_st_table_loc(struct pci_dev *pdev)
```

Return the device's ST table location

**Parameters**

- `struct pci_dev *pdev`: PCI device to query

**Return**

PCI_TPH_LOC_NONE - Not present
PCI_TPH_LOC_CAP  - Located in the TPH Requester Extended Capability
PCI_TPH_LOC_MSIX - Located in the MSI-X Table

#### <a id="c-pcie_tph_get_cpu_st"></a>`pcie_tph_get_cpu_st()`

```c
int pcie_tph_get_cpu_st(struct pci_dev *pdev, enum tph_mem_type mem_type, unsigned int cpu_uid, u16 *tag)
```

Retrieve Steering Tag for a target memory associated with a specific CPU

**Parameters**

- `struct pci_dev *pdev`: PCI device
- `enum tph_mem_type mem_type`: target memory type (volatile or persistent RAM)
- `unsigned int cpu_uid`: associated CPU id
- `u16 *tag`: Steering Tag to be returned

**Description**

Return the Steering Tag for a target memory that is associated with a
specific CPU as indicated by cpu_uid.

**Return**

0 if success, otherwise negative value (-errno)

#### <a id="c-pcie_tph_set_st_entry"></a>`pcie_tph_set_st_entry()`

```c
int pcie_tph_set_st_entry(struct pci_dev *pdev, unsigned int index, u16 tag)
```

Set Steering Tag in the ST table entry

**Parameters**

- `struct pci_dev *pdev`: PCI device
- `unsigned int index`: ST table entry index
- `u16 tag`: Steering Tag to be written

**Description**

Figure out the proper location of ST table, either in the MSI-X table or
in the TPH Extended Capability space, and write the Steering Tag into
the ST entry pointed by index.

**Return**

0 if success, otherwise negative value (-errno)

#### <a id="c-pcie_disable_tph"></a>`pcie_disable_tph()`

```c
void pcie_disable_tph(struct pci_dev *pdev)
```

Turn off TPH support for device

**Parameters**

- `struct pci_dev *pdev`: PCI device

**Return**

none

#### <a id="c-pcie_enable_tph"></a>`pcie_enable_tph()`

```c
int pcie_enable_tph(struct pci_dev *pdev, int mode)
```

Enable TPH support for device using a specific ST mode

**Parameters**

- `struct pci_dev *pdev`: PCI device
- `int mode`: ST mode to enable. Current supported modes include:

**Description**

- PCI_TPH_ST_NS_MODE: NO ST Mode
- PCI_TPH_ST_IV_MODE: Interrupt Vector Mode
- PCI_TPH_ST_DS_MODE: Device Specific Mode

Check whether the mode is actually supported by the device before enabling
and return an error if not. Additionally determine what types of requests,
TPH or extended TPH, can be issued by the device based on its TPH requester
capability and the Root Port's completer capability.

**Return**

0 on success, otherwise negative value (-errno)


<a id="rst-pci-hotplug-support-library"></a>

## PCI Hotplug Support Library


#### <a id="c-__pci_hp_register"></a>`__pci_hp_register()`

```c
int __pci_hp_register(struct hotplug_slot *slot, struct pci_bus *bus, int devnr, const char *name, struct module *owner, const char *mod_name)
```

register a hotplug_slot with the PCI hotplug subsystem

**Parameters**

- `struct hotplug_slot *slot`: pointer to the `struct hotplug_slot` to register
- `struct pci_bus *bus`: bus this slot is on
- `int devnr`: device number
- `const char *name`: name registered with kobject core
- `struct module *owner`: caller module owner
- `const char *mod_name`: caller module name

**Description**

Prepares a hotplug slot for in-kernel use and immediately publishes it to
user space in one go.  Drivers may alternatively carry out the two steps
separately by invoking `pci_hp_initialize()` and [`pci_hp_add()`](#c-pci_hp_add).

Returns 0 if successful, anything else for an error.

#### <a id="c-__pci_hp_initialize"></a>`__pci_hp_initialize()`

```c
int __pci_hp_initialize(struct hotplug_slot *slot, struct pci_bus *bus, int devnr, const char *name, struct module *owner, const char *mod_name)
```

prepare hotplug slot for in-kernel use

**Parameters**

- `struct hotplug_slot *slot`: pointer to the `struct hotplug_slot` to initialize
- `struct pci_bus *bus`: bus this slot is on
- `int devnr`: slot number
- `const char *name`: name registered with kobject core
- `struct module *owner`: caller module owner
- `const char *mod_name`: caller module name

**Description**

Allocate and fill in a PCI slot for use by a hotplug driver.  Once this has
been called, the driver may invoke `hotplug_slot_name()` to get the slot's
unique name.  The driver must be prepared to handle a ->reset_slot callback
from this point on.

Returns 0 on success or a negative int on error.

#### <a id="c-pci_hp_add"></a>`pci_hp_add()`

```c
int pci_hp_add(struct hotplug_slot *slot)
```

publish hotplug slot to user space

**Parameters**

- `struct hotplug_slot *slot`: pointer to the `struct hotplug_slot` to publish

**Description**

Make a hotplug slot's sysfs interface available and inform user space of its
addition by sending a uevent.  The hotplug driver must be prepared to handle
all `struct hotplug_slot_ops` callbacks from this point on.

Returns 0 on success or a negative int on error.

#### <a id="c-pci_hp_deregister"></a>`pci_hp_deregister()`

```c
void pci_hp_deregister(struct hotplug_slot *slot)
```

deregister a hotplug_slot with the PCI hotplug subsystem

**Parameters**

- `struct hotplug_slot *slot`: pointer to the `struct hotplug_slot` to deregister

**Description**

The **slot** must have been registered with the pci hotplug subsystem
previously with a call to `pci_hp_register()`.

#### <a id="c-pci_hp_del"></a>`pci_hp_del()`

```c
void pci_hp_del(struct hotplug_slot *slot)
```

unpublish hotplug slot from user space

**Parameters**

- `struct hotplug_slot *slot`: pointer to the `struct hotplug_slot` to unpublish

**Description**

Remove a hotplug slot's sysfs interface.

#### <a id="c-pci_hp_destroy"></a>`pci_hp_destroy()`

```c
void pci_hp_destroy(struct hotplug_slot *slot)
```

remove hotplug slot from in-kernel use

**Parameters**

- `struct hotplug_slot *slot`: pointer to the `struct hotplug_slot` to destroy

**Description**

Destroy a PCI slot used by a hotplug driver.  Once this has been called,
the driver may no longer invoke `hotplug_slot_name()` to get the slot's
unique name.  The driver no longer needs to handle a ->reset_slot callback
from this point on.

---

# PCI Trusted Execution Environment Security Manager (TSM)

_Peios Kernel / Hardware and drivers / Driver development / PCI_

> Reference for PCI Trusted Execution Environment Security Manager (TSM).

<a id="rst-pci-trusted-execution-environment-security-manager-tsm"></a>

<a id="rst-subsystem-interfaces"></a>

## Subsystem Interfaces

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->


#### <a id="c-struct-pci_ide_partner"></a>`struct pci_ide_partner`

Per port pair Selective IDE Stream settings

**Definition**

```c
struct pci_ide_partner {
    u16 rid_start;
    u16 rid_end;
    u8 stream_index;
    struct pci_bus_region mem_assoc;
    struct pci_bus_region pref_assoc;
    unsigned int default_stream:1;
    unsigned int setup:1;
    unsigned int enable:1;
};
```

**Members**

- `rid_start`: Partner Port Requester ID range start
- `rid_end`: Partner Port Requester ID range end (inclusive)
- `stream_index`: Selective IDE Stream Register Block selection
- `mem_assoc`: PCI bus memory address association for targeting peer partner
- `pref_assoc`: PCI bus prefetchable memory address association for
  targeting peer partner
- `default_stream`: Endpoint uses this stream for all upstream TLPs regardless of
  address and RID association registers
- `setup`: flag to track whether to run [`pci_ide_stream_teardown()`](#c-pci_ide_stream_teardown) for this
  partner slot
- `enable`: flag whether to run [`pci_ide_stream_disable()`](#c-pci_ide_stream_disable) for this partner slot

**Description**

By default, [`pci_ide_stream_alloc()`](#c-pci_ide_stream_alloc) initializes **mem_assoc** and **pref_assoc**
with the immediate ancestor downstream port memory ranges (i.e. Type 1
Configuration Space Header values). Caller may zero size ({0, -1}) the range
to drop it from consideration at [`pci_ide_stream_setup()`](#c-pci_ide_stream_setup) time.

#### <a id="c-struct-pci_ide_regs"></a>`struct pci_ide_regs`

Hardware register association settings for Selective IDE Streams

**Definition**

```c
struct pci_ide_regs {
    u32 rid1;
    u32 rid2;
    struct {
        u32 assoc1;
        u32 assoc2;
        u32 assoc3;
    } addr[2];
    int nr_addr;
};
```

**Members**

- `rid1`: IDE RID Association Register 1
- `rid2`: IDE RID Association Register 2
- `addr`: Up to two address association blocks (IDE Address Association Register
  1 through 3) for MMIO and prefetchable MMIO
- `nr_addr`: Number of address association blocks initialized

**Description**

See `pci_ide_stream_to_regs()`

#### <a id="c-struct-pci_ide"></a>`struct pci_ide`

PCIe Selective IDE Stream descriptor

**Definition**

```c
struct pci_ide {
    struct pci_dev *pdev;
    struct pci_ide_partner partner[PCI_IDE_PARTNER_MAX];
    u8 host_bridge_stream;
    int stream_id;
    const char *name;
};
```

**Members**

- `pdev`: PCIe Endpoint in the pci_ide_partner pair
- `partner`: per-partner settings
- `host_bridge_stream`: allocated from host bridge **ide_stream_ida** pool
- `stream_id`: unique Stream ID (within Partner Port pairing)
- `name`: name of the established Selective IDE Stream in sysfs

**Description**

Negative **stream_id** values indicate "uninitialized" on the
expectation that with TSM established IDE the TSM owns the stream_id
allocation.



#### <a id="c-pci_ide_stream_alloc"></a>`pci_ide_stream_alloc()`

```c
struct pci_ide * pci_ide_stream_alloc(struct pci_dev *pdev)
```

Reserve stream indices and probe for settings

**Parameters**

- `struct pci_dev *pdev`: IDE capable PCIe Endpoint Physical Function

**Description**

Retrieve the Requester ID range of **pdev** for programming its Root
Port IDE RID Association registers, and conversely retrieve the
Requester ID of the Root Port for programming **pdev**'s IDE RID
Association registers.

Allocate a Selective IDE Stream Register Block instance per port.

Allocate a platform stream resource from the associated host bridge.
Retrieve stream association parameters for Requester ID range and
address range restrictions for the stream.

#### <a id="c-pci_ide_stream_free"></a>`pci_ide_stream_free()`

```c
void pci_ide_stream_free(struct pci_ide *ide)
```

unwind [`pci_ide_stream_alloc()`](#c-pci_ide_stream_alloc)

**Parameters**

- `struct pci_ide *ide`: idle IDE settings descriptor

**Description**

Free all of the stream index (register block) allocations acquired by
[`pci_ide_stream_alloc()`](#c-pci_ide_stream_alloc). The stream represented by **ide** is assumed to
be unregistered and not instantiated in any device.

#### <a id="c-pci_ide_stream_release"></a>`pci_ide_stream_release()`

```c
void pci_ide_stream_release(struct pci_ide *ide)
```

unwind and release an **ide** context

**Parameters**

- `struct pci_ide *ide`: partially or fully registered IDE settings descriptor

**Description**

In support of automatic cleanup of IDE setup routines perform IDE
teardown in expected reverse order of setup and with respect to which
aspects of IDE setup have successfully completed.

Be careful that setup order mirrors this shutdown order. Otherwise,
open code releasing the IDE context.

#### <a id="c-pci_ide_stream_register"></a>`pci_ide_stream_register()`

```c
int pci_ide_stream_register(struct pci_ide *ide)
```

Prepare to activate an IDE Stream

**Parameters**

- `struct pci_ide *ide`: IDE settings descriptor

**Description**

After a Stream ID has been acquired for **ide**, record the presence of
the stream in sysfs. The expectation is that **ide** is immutable while
registered.

#### <a id="c-pci_ide_stream_unregister"></a>`pci_ide_stream_unregister()`

```c
void pci_ide_stream_unregister(struct pci_ide *ide)
```

unwind [`pci_ide_stream_register()`](#c-pci_ide_stream_register)

**Parameters**

- `struct pci_ide *ide`: idle IDE settings descriptor

**Description**

In preparation for freeing **ide**, remove sysfs enumeration for the
stream.

#### <a id="c-pci_ide_stream_setup"></a>`pci_ide_stream_setup()`

```c
void pci_ide_stream_setup(struct pci_dev *pdev, struct pci_ide *ide)
```

program settings to Selective IDE Stream registers

**Parameters**

- `struct pci_dev *pdev`: PCIe device object for either a Root Port or Endpoint Partner Port
- `struct pci_ide *ide`: registered IDE settings descriptor

**Description**

When **pdev** is a PCI_EXP_TYPE_ENDPOINT then the PCI_IDE_EP partner
settings are written to **pdev**'s Selective IDE Stream register block,
and when **pdev** is a PCI_EXP_TYPE_ROOT_PORT, the PCI_IDE_RP settings
are selected.

#### <a id="c-pci_ide_stream_teardown"></a>`pci_ide_stream_teardown()`

```c
void pci_ide_stream_teardown(struct pci_dev *pdev, struct pci_ide *ide)
```

disable the stream and clear all settings

**Parameters**

- `struct pci_dev *pdev`: PCIe device object for either a Root Port or Endpoint Partner Port
- `struct pci_ide *ide`: registered IDE settings descriptor

**Description**

For stream destruction, zero all registers that may have been written
by [`pci_ide_stream_setup()`](#c-pci_ide_stream_setup). Consider [`pci_ide_stream_disable()`](#c-pci_ide_stream_disable) to leave
settings in place while temporarily disabling the stream.

#### <a id="c-pci_ide_stream_enable"></a>`pci_ide_stream_enable()`

```c
int pci_ide_stream_enable(struct pci_dev *pdev, struct pci_ide *ide)
```

enable a Selective IDE Stream

**Parameters**

- `struct pci_dev *pdev`: PCIe device object for either a Root Port or Endpoint Partner Port
- `struct pci_ide *ide`: registered and setup IDE settings descriptor

**Description**

Activate the stream by writing to the Selective IDE Stream Control
Register.

Note that the state may go "insecure" at any point after returning 0, but
those events are equivalent to a "link down" event and handled via
asynchronous error reporting.

Caller is responsible to clear the enable bit in the -ENXIO case.

**Return**

0 if the stream successfully entered the "secure" state, and -EINVAL
if **ide** is invalid, and -ENXIO if the stream fails to enter the secure state.

#### <a id="c-pci_ide_stream_disable"></a>`pci_ide_stream_disable()`

```c
void pci_ide_stream_disable(struct pci_dev *pdev, struct pci_ide *ide)
```

disable a Selective IDE Stream

**Parameters**

- `struct pci_dev *pdev`: PCIe device object for either a Root Port or Endpoint Partner Port
- `struct pci_ide *ide`: registered and setup IDE settings descriptor

**Description**

Clear the Selective IDE Stream Control Register, but leave all other
registers untouched.

#### <a id="c-pci_ide_set_nr_streams"></a>`pci_ide_set_nr_streams()`

```c
void pci_ide_set_nr_streams(struct pci_host_bridge *hb, u16 nr)
```

sets size of the pool of IDE Stream resources

**Parameters**

- `struct pci_host_bridge *hb`: host bridge boundary for the stream pool
- `u16 nr`: number of streams

**Description**

Platform PCI init and/or expert test module use only. Limit IDE
Stream establishment by setting the number of stream resources
available at the host bridge. Platform init code must set this before
the first [`pci_ide_stream_alloc()`](#c-pci_ide_stream_alloc) call if the platform has less than the
default of 256 streams per host-bridge.

The "PCI_IDE" symbol namespace is required because this is typically
a detail that is settled in early PCI init. I.e. this export is not
for endpoint drivers.



#### <a id="c-struct-pci_tdi"></a>`struct pci_tdi`

Core TEE I/O Device Interface (TDI) context

**Definition**

```c
struct pci_tdi {
    struct pci_dev *pdev;
    struct kvm *kvm;
    u32 tdi_id;
};
```

**Members**

- `pdev`: host side representation of guest-side TDI
- `kvm`: TEE VM context of bound TDI
- `tdi_id`: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM

#### <a id="c-struct-pci_tsm"></a>`struct pci_tsm`

Core TSM context for a given PCIe endpoint

**Definition**

```c
struct pci_tsm {
    struct pci_dev *pdev;
    struct pci_dev *dsm_dev;
    struct tsm_dev *tsm_dev;
    struct pci_tdi *tdi;
};
```

**Members**

- `pdev`: Back ref to device function, distinguishes type of pci_tsm context
- `dsm_dev`: PCI Device Security Manager for link operations on **pdev**
- `tsm_dev`: PCI TEE Security Manager device for Link Confidentiality or Device
  Function Security operations
- `tdi`: TDI context established by the **bind** link operation

**Description**

This structure is wrapped by low level TSM driver data and returned by
`probe()`/`lock()`, it is freed by the corresponding `remove()`/`unlock()`.

For link operations it serves to cache the association between a Device
Security Manager (DSM) and the functions that manager can assign to a TVM.
That can be "self", for assigning function0 of a TEE I/O device, a
sub-function (SR-IOV virtual function, or non-function0
multifunction-device), or a downstream endpoint (PCIe upstream switch-port as
DSM).

#### <a id="c-struct-pci_tsm_pf0"></a>`struct pci_tsm_pf0`

Physical Function 0 TDISP link context

**Definition**

```c
struct pci_tsm_pf0 {
    struct pci_tsm base_tsm;
    struct mutex lock;
    struct pci_doe_mb *doe_mb;
};
```

**Members**

- `base_tsm`: generic core "tsm" context
- `lock`: mutual exclustion for pci_tsm_ops invocation
- `doe_mb`: PCIe Data Object Exchange mailbox

#### <a id="c-enum-pci_tsm_req_scope"></a>`enum pci_tsm_req_scope`

Scope of guest requests to be validated by TSM

**Constants**

- `PCI_TSM_REQ_INFO`: Read-only, without side effects, request for
  typical TDISP collateral information like Device Interface Reports.
  No device secrets are permitted, and no device state is changed.
- `PCI_TSM_REQ_STATE_CHANGE`: Request to change the TDISP state from
  UNLOCKED->LOCKED, LOCKED->RUN, or other architecture specific state
  changes to support those transitions for a TDI. No other (unrelated
  to TDISP) device / host state, configuration, or data change is
  permitted.
- `PCI_TSM_REQ_DEBUG_READ`: Read-only request for debug information

  A method to facilitate TVM information retrieval outside of typical
  TDISP operational requirements. No device secrets are permitted.
- `PCI_TSM_REQ_DEBUG_WRITE`: Device state changes for debug purposes

  The request may affect the operational state of the device outside of
  the TDISP operational model. If allowed, requires CAP_SYS_RAW_IO, and
  will taint the kernel.

**Description**

Guest requests are a transport for a TVM to communicate with a TSM + DSM for
a given TDI. A TSM driver is responsible for maintaining the kernel security
model and limit commands that may affect the host, or are otherwise outside
the typical TDISP operational model.



#### <a id="c-pci_tsm_bind"></a>`pci_tsm_bind()`

```c
int pci_tsm_bind(struct pci_dev *pdev, struct kvm *kvm, u32 tdi_id)
```

Bind **pdev** as a TDI for **kvm**

**Parameters**

- `struct pci_dev *pdev`: PCI device function to bind
- `struct kvm *kvm`: Private memory attach context
- `u32 tdi_id`: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM

**Description**

Returns 0 on success, or a negative error code on failure.

**Context**

Caller is responsible for constraining the bind lifetime to the
registered state of the device. For example, [`pci_tsm_bind()`](#c-pci_tsm_bind) /
`pci_tsm_unbind()` limited to the VFIO driver bound state of the device.

#### <a id="c-pci_tsm_guest_req"></a>`pci_tsm_guest_req()`

```c
ssize_t pci_tsm_guest_req(struct pci_dev *pdev, enum pci_tsm_req_scope scope, sockptr_t req_in, size_t in_len, sockptr_t req_out, size_t out_len, u64 *tsm_code)
```

helper to marshal guest requests to the TSM driver

**Parameters**

- `struct pci_dev *pdev`:

  **pdev** representing a bound tdi
- `enum pci_tsm_req_scope scope`: caller asserts this passthrough request is limited to TDISP operations
- `sockptr_t req_in`: Input payload forwarded from the guest
- `size_t in_len`: Length of **req_in**
- `sockptr_t req_out`: Output payload buffer response to the guest
- `size_t out_len`: Length of **req_out** on input, bytes filled in **req_out** on output
- `u64 *tsm_code`: Optional TSM arch specific result code for the guest TSM

**Description**

This is a common entry point for requests triggered by userspace KVM-exit
service handlers responding to TDI information or state change requests. The
scope parameter limits requests to TDISP state management, or limited debug.
This path is only suitable for commands and results that are the host kernel
has no use, the host is only facilitating guest to TSM communication.

Returns 0 on success and -error on failure and positive "residue" on success
but **req_out** is filled with less then **out_len**, or **req_out** is NULL and a
residue number of bytes were not consumed from **req_in**.  On success or
failure **tsm_code** may be populated with a TSM implementation specific result
code for the guest to consume.

**Context**

Caller is responsible for calling this within the [`pci_tsm_bind()`](#c-pci_tsm_bind)
state of the TDI.

#### <a id="c-pci_tsm_tdi_constructor"></a>`pci_tsm_tdi_constructor()`

```c
void pci_tsm_tdi_constructor(struct pci_dev *pdev, struct pci_tdi *tdi, struct kvm *kvm, u32 tdi_id)
```

base 'struct pci_tdi' initialization for link TSMs

**Parameters**

- `struct pci_dev *pdev`: PCI device function representing the TDI
- `struct pci_tdi *tdi`: context to initialize
- `struct kvm *kvm`: Private memory attach context
- `u32 tdi_id`: Identifier (virtual BDF) for the TDI as referenced by the TSM and DSM

#### <a id="c-pci_tsm_link_constructor"></a>`pci_tsm_link_constructor()`

```c
int pci_tsm_link_constructor(struct pci_dev *pdev, struct pci_tsm *tsm, struct tsm_dev *tsm_dev)
```

base 'struct pci_tsm' initialization for link TSMs

**Parameters**

- `struct pci_dev *pdev`: The PCI device
- `struct pci_tsm *tsm`: context to initialize
- `struct tsm_dev *tsm_dev`: Platform TEE Security Manager, initiator of security operations

#### <a id="c-pci_tsm_pf0_constructor"></a>`pci_tsm_pf0_constructor()`

```c
int pci_tsm_pf0_constructor(struct pci_dev *pdev, struct pci_tsm_pf0 *tsm, struct tsm_dev *tsm_dev)
```

common 'struct pci_tsm_pf0' (DSM) initialization

**Parameters**

- `struct pci_dev *pdev`: Physical Function 0 PCI device (as indicated by `is_pci_tsm_pf0()`)
- `struct pci_tsm_pf0 *tsm`: context to initialize
- `struct tsm_dev *tsm_dev`: Platform TEE Security Manager, initiator of security operations

---

# Generic PHY Framework

_Peios Kernel / Hardware and drivers / Driver development / Physical interfaces_

> Reference for Generic PHY Framework.

<a id="rst-generic-phy-framework"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [PHY subsystem](</kernel/hardware/driver-api/phy/phy.md>)
- [Samsung USB 2.0 PHY adaptation layer](</kernel/hardware/driver-api/phy/samsung-usb2.md>)

---

# PHY subsystem

_Peios Kernel / Hardware and drivers / Driver development / Physical interfaces_

> This document explains the Generic PHY Framework along with the APIs provided, and how-to-use.

<a id="rst-phy-subsystem"></a>

**Author:** Kishon Vijay Abraham I &lt;[kishon@ti.com](<mailto:kishon@ti.com>)&gt;

This document explains the Generic PHY Framework along with the APIs provided, and how-to-use.

<a id="rst-introduction"></a>

## Introduction

*PHY* is the abbreviation for physical layer. It is used to connect a device to the physical medium e.g., the USB controller has a PHY to provide functions such as serialization, de-serialization, encoding, decoding and is responsible for obtaining the required data transmission rate. Note that some USB controllers have PHY functionality embedded into it and others use an external PHY. Other peripherals that use PHY include Wireless LAN, Ethernet, SATA etc.

The intention of creating this framework is to bring the PHY drivers spread all over the Linux kernel to drivers/phy to increase code reuse and for better code maintainability.

This framework will be of use only to devices that use external PHY (PHY functionality is not embedded within the controller).

<a id="rst-registering-unregistering-the-phy-provider"></a>

## Registering/Unregistering the PHY provider

PHY provider refers to an entity that implements one or more PHY instances. For the simple case where the PHY provider implements only a single instance of the PHY, the framework provides its own implementation of of_xlate in of_phy_simple_xlate. If the PHY provider implements multiple instances, it should provide its own implementation of of_xlate. of_xlate is used only for dt boot case.



```text
#define of_phy_provider_register(dev, xlate)    \
        __of_phy_provider_register((dev), NULL, THIS_MODULE, (xlate))

#define devm_of_phy_provider_register(dev, xlate)       \
        __devm_of_phy_provider_register((dev), NULL, THIS_MODULE,
                                        (xlate))
```

of_phy_provider_register and devm_of_phy_provider_register macros can be used to register the phy_provider and it takes device and of_xlate as arguments. For the dt boot case, all PHY providers should use one of the above 2 macros to register the PHY provider.

Often the device tree nodes associated with a PHY provider will contain a set of children that each represent a single PHY. Some bindings may nest the child nodes within extra levels for context and extensibility, in which case the low level of_phy_provider_register_full() and devm_of_phy_provider_register_full() macros can be used to override the node containing the children.



```text
#define of_phy_provider_register_full(dev, children, xlate) \
        __of_phy_provider_register(dev, children, THIS_MODULE, xlate)

#define devm_of_phy_provider_register_full(dev, children, xlate) \
        __devm_of_phy_provider_register_full(dev, children,
                                             THIS_MODULE, xlate)

void devm_of_phy_provider_unregister(struct device *dev,
        struct phy_provider *phy_provider);
void of_phy_provider_unregister(struct phy_provider *phy_provider);
```

devm_of_phy_provider_unregister and of_phy_provider_unregister can be used to unregister the PHY.

<a id="rst-creating-the-phy"></a>

## Creating the PHY

The PHY driver should create the PHY in order for other peripheral controllers to make use of it. The PHY framework provides 2 APIs to create the PHY.



```text
struct phy *phy_create(struct device *dev, struct device_node *node,
                       const struct phy_ops *ops);
struct phy *devm_phy_create(struct device *dev,
                            struct device_node *node,
                            const struct phy_ops *ops);
```

The PHY drivers can use one of the above 2 APIs to create the PHY by passing the device pointer and phy ops. phy_ops is a set of function pointers for performing PHY operations such as init, exit, power_on and power_off.

Inorder to dereference the private data (in phy_ops), the phy provider driver can use phy_set_drvdata() after creating the PHY and use phy_get_drvdata() in phy_ops to get back the private data.

<a id="rst-getting-a-reference-to-the-phy"></a>

## Getting a reference to the PHY

Before the controller can make use of the PHY, it has to get a reference to it. This framework provides the following APIs to get a reference to the PHY.



```text
struct phy *phy_get(struct device *dev, const char *string);
struct phy *devm_phy_get(struct device *dev, const char *string);
struct phy *devm_phy_optional_get(struct device *dev,
                                  const char *string);
struct phy *devm_of_phy_get(struct device *dev, struct device_node *np,
                            const char *con_id);
struct phy *devm_of_phy_optional_get(struct device *dev,
                                     struct device_node *np,
                                     const char *con_id);
struct phy *devm_of_phy_get_by_index(struct device *dev,
                                     struct device_node *np,
                                     int index);
```

phy_get, devm_phy_get and devm_phy_optional_get can be used to get the PHY. In the case of dt boot, the string arguments should contain the phy name as given in the dt data and in the case of non-dt boot, it should contain the label of the PHY.  The two devm_phy_get associates the device with the PHY using devres on successful PHY get. On driver detach, release function is invoked on the devres data and devres data is freed. The \_optional_get variants should be used when the phy is optional. These functions will never return -ENODEV, but instead return NULL when the phy cannot be found. Some generic drivers, such as ehci, may use multiple phys. In this case, devm_of_phy_get or devm_of_phy_get_by_index can be used to get a phy reference based on name or index.

It should be noted that NULL is a valid phy reference. All phy consumer calls on the NULL phy become NOPs. That is the release calls, the phy_init() and phy_exit() calls, and phy_power_on() and phy_power_off() calls are all NOP when applied to a NULL phy. The NULL phy is useful in devices for handling optional phy devices.

<a id="rst-order-of-api-calls"></a>

## Order of API calls

The general order of calls should be:



```text
[devm_][of_]phy_get()
phy_init()
phy_power_on()
[phy_set_mode[_ext]()]
...
phy_power_off()
phy_exit()
[[of_]phy_put()]
```

Some PHY drivers may not implement `phy_init()` or `phy_power_on()`, but controllers should always call these functions to be compatible with other PHYs. Some PHYs may require `phy_set_mode <phy_set_mode_ext>()`, while others may use a default mode (typically configured via devicetree or other firmware). For compatibility, you should always call this function if you know what mode you will be using. Generally, this function should be called after `phy_power_on()`, although some PHY drivers may allow it at any time.

<a id="rst-releasing-a-reference-to-the-phy"></a>

## Releasing a reference to the PHY

When the controller no longer needs the PHY, it has to release the reference to the PHY it has obtained using the APIs mentioned in the above section. The PHY framework provides 2 APIs to release a reference to the PHY.



```text
void phy_put(struct phy *phy);
void devm_phy_put(struct device *dev, struct phy *phy);
```

Both these APIs are used to release a reference to the PHY and devm_phy_put destroys the devres associated with this PHY.

<a id="rst-destroying-the-phy"></a>

## Destroying the PHY

When the driver that created the PHY is unloaded, it should destroy the PHY it created using one of the following 2 APIs:



```text
void phy_destroy(struct phy *phy);
void devm_phy_destroy(struct device *dev, struct phy *phy);
```

Both these APIs destroy the PHY and devm_phy_destroy destroys the devres associated with this PHY.

<a id="rst-pm-runtime"></a>

## PM Runtime

This subsystem is pm runtime enabled. So while creating the PHY, pm_runtime_enable of the phy device created by this subsystem is called and while destroying the PHY, pm_runtime_disable is called. Note that the phy device created by this subsystem will be a child of the device that calls phy_create (PHY provider device).

So pm_runtime_get_sync of the phy_device created by this subsystem will invoke pm_runtime_get_sync of PHY provider device because of parent-child relationship. It should also be noted that phy_power_on and phy_power_off performs phy_pm_runtime_get_sync and phy_pm_runtime_put respectively. There are exported APIs like phy_pm_runtime_get, phy_pm_runtime_get_sync, phy_pm_runtime_put and phy_pm_runtime_put_sync for performing PM operations.

<a id="rst-phy-mappings"></a>

## PHY Mappings

In order to get reference to a PHY without help from DeviceTree, the framework offers lookups which can be compared to clkdev that allow clk structures to be bound to devices. A lookup can be made during runtime when a handle to the struct phy already exists.

The framework offers the following API for registering and unregistering the lookups:



```text
int phy_create_lookup(struct phy *phy, const char *con_id,
                      const char *dev_id);
void phy_remove_lookup(struct phy *phy, const char *con_id,
                       const char *dev_id);
```

<a id="rst-devicetree-binding"></a>

## DeviceTree Binding

The documentation for PHY dt binding can be found @ [Documentation/devicetree/bindings/phy/phy-bindings.txt](/kernel/hardware/devicetree/bindings-phy/phy-bindings.md)

---

# Samsung USB 2.0 PHY adaptation layer

_Peios Kernel / Hardware and drivers / Driver development / Physical interfaces_

> The architecture of the USB 2.0 PHY module in Samsung SoCs is similar among many SoCs. In spite of the similarities it proved difficult to create a one driver that would fit all these PHY controllers. Often the differences were minor and…

<a id="rst-samsung-usb-2-0-phy-adaptation-layer"></a>

<a id="rst-description"></a>

## 1. Description

The architecture of the USB 2.0 PHY module in Samsung SoCs is similar among many SoCs. In spite of the similarities it proved difficult to create a one driver that would fit all these PHY controllers. Often the differences were minor and were found in particular bits of the registers of the PHY. In some rare cases the order of register writes or the PHY powering up process had to be altered. This adaptation layer is a compromise between having separate drivers and having a single driver with added support for many special cases.

<a id="rst-files-description"></a>

## 2. Files description

- - **phy-samsung-usb2.c**

    This is the main file of the adaptation layer. This file contains the probe function and provides two callbacks to the Generic PHY Framework. This two callbacks are used to power on and power off the phy. They carry out the common work that has to be done on all version of the PHY module. Depending on which SoC was chosen they execute SoC specific callbacks. The specific SoC version is selected by choosing the appropriate compatible string. In addition, this file contains struct of_device_id definitions for particular SoCs.

- - **phy-samsung-usb2.h**

    This is the include file. It declares the structures used by this driver. In addition it should contain extern declarations for structures that describe particular SoCs.

<a id="rst-supporting-socs"></a>

## 3. Supporting SoCs

To support a new SoC a new file should be added to the drivers/phy directory. Each SoC's configuration is stored in an instance of the struct samsung_usb2_phy_config:



```text
struct samsung_usb2_phy_config {
      const struct samsung_usb2_common_phy *phys;
      int (*rate_to_clk)(unsigned long, u32 *);
      unsigned int num_phys;
      bool has_mode_switch;
};
```

The num_phys is the number of phys handled by the driver. `*phys` is an array that contains the configuration for each phy. The has_mode_switch property is a boolean flag that determines whether the SoC has USB host and device on a single pair of pins. If so, a special register has to be modified to change the internal routing of these pins between a USB device or host module.

For example the configuration for Exynos 4210 is following:



```text
const struct samsung_usb2_phy_config exynos4210_usb2_phy_config = {
      .has_mode_switch        = 0,
      .num_phys               = EXYNOS4210_NUM_PHYS,
      .phys                   = exynos4210_phys,
      .rate_to_clk            = exynos4210_rate_to_clk,
}
```

- `int (*rate_to_clk)(unsigned long, u32 *)`

  > The rate_to_clk callback is to convert the rate of the clock used as the reference clock for the PHY module to the value that should be written in the hardware register.

The exynos4210_phys configuration array is as follows:



```text
static const struct samsung_usb2_common_phy exynos4210_phys[] = {
      {
              .label          = "device",
              .id             = EXYNOS4210_DEVICE,
              .power_on       = exynos4210_power_on,
              .power_off      = exynos4210_power_off,
      },
      {
              .label          = "host",
              .id             = EXYNOS4210_HOST,
              .power_on       = exynos4210_power_on,
              .power_off      = exynos4210_power_off,
      },
      {
              .label          = "hsic0",
              .id             = EXYNOS4210_HSIC0,
              .power_on       = exynos4210_power_on,
              .power_off      = exynos4210_power_off,
      },
      {
              .label          = "hsic1",
              .id             = EXYNOS4210_HSIC1,
              .power_on       = exynos4210_power_on,
              .power_off      = exynos4210_power_off,
      },
      {},
};
```

- `int (*power_on)(struct samsung_usb2_phy_instance *);` `int (*power_off)(struct samsung_usb2_phy_instance *);`

  > These two callbacks are used to power on and power off the phy by modifying appropriate registers.

Final change to the driver is adding appropriate compatible value to the phy-samsung-usb2.c file. In case of Exynos 4210 the following lines were added to the struct of_device_id samsung_usb2_phy_of_match\[\] array:



```text
#ifdef CONFIG_PHY_EXYNOS4210_USB2
      {
              .compatible = "samsung,exynos4210-usb2-phy",
              .data = &exynos4210_usb2_phy_config,
      },
#endif
```

To add further flexibility to the driver the Kconfig file enables to include support for selected SoCs in the compiled driver. The Kconfig entry for Exynos 4210 is following:



```text
config PHY_EXYNOS4210_USB2
      bool "Support for Exynos 4210"
      depends on PHY_SAMSUNG_USB2
      depends on CPU_EXYNOS4210
      help
        Enable USB PHY support for Exynos 4210. This option requires that
        Samsung USB 2.0 PHY driver is enabled and means that support for this
        particular SoC is compiled in the driver. In case of Exynos 4210 four
        phys are available - device, host, HSCI0 and HSCI1.
```

The newly created file that supports the new SoC has to be also added to the Makefile. In case of Exynos 4210 the added line is following:



```text
obj-$(CONFIG_PHY_EXYNOS4210_USB2)       += phy-exynos4210-usb2.o
```

After completing these steps the support for the new SoC should be ready.

---

# The Linux RapidIO Subsystem

_Peios Kernel / Hardware and drivers / Driver development / RapidIO_

> Reference for The Linux RapidIO Subsystem.

<a id="rst-the-linux-rapidio-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Introduction](</kernel/hardware/driver-api/rapidio/rapidio.md>)
- [Sysfs entries](</kernel/hardware/driver-api/rapidio/sysfs.md>)
- [RapidIO subsystem mport driver for IDT Tsi721 PCI Express-to-SRIO bridge.](</kernel/hardware/driver-api/rapidio/tsi721.md>)
- [RapidIO subsystem mport character device driver (rio_mport_cdev.c)](</kernel/hardware/driver-api/rapidio/mport-cdev.md>)
- [RapidIO subsystem Channelized Messaging character device driver (rio_cm.c)](</kernel/hardware/driver-api/rapidio/rio-cm.md>)

---

# RapidIO subsystem mport character device driver (rio_mport_cdev.c)

_Peios Kernel / Hardware and drivers / Driver development / RapidIO_

> This device driver is the result of collaboration within the RapidIO.org Software Task Group (STG) between Texas Instruments, Freescale, Prodrive Technologies, Nokia Networks, BAE and IDT. Additional input was received from other members…

<a id="rst-rapidio-subsystem-mport-character-device-driver-rio-mport-cdev-c"></a>

<a id="rst-overview"></a>

## 1. Overview

This device driver is the result of collaboration within the RapidIO.org Software Task Group (STG) between Texas Instruments, Freescale, Prodrive Technologies, Nokia Networks, BAE and IDT.  Additional input was received from other members of RapidIO.org. The objective was to create a character mode driver interface which exposes the capabilities of RapidIO devices directly to applications, in a manner that allows the numerous and varied RapidIO implementations to interoperate.

This driver (MPORT_CDEV) provides access to basic RapidIO subsystem operations for user-space applications. Most of RapidIO operations are supported through 'ioctl' system calls.

When loaded this device driver creates filesystem nodes named rio_mportX in /dev directory for each registered RapidIO mport device. 'X' in the node name matches to unique port ID assigned to each local mport device.

Using available set of ioctl commands user-space applications can perform following RapidIO bus and subsystem operations:

- Reads and writes from/to configuration registers of mport devices (RIO_MPORT_MAINT_READ_LOCAL/RIO_MPORT_MAINT_WRITE_LOCAL)

- Reads and writes from/to configuration registers of remote RapidIO devices. This operations are defined as RapidIO Maintenance reads/writes in RIO spec. (RIO_MPORT_MAINT_READ_REMOTE/RIO_MPORT_MAINT_WRITE_REMOTE)

- Set RapidIO Destination ID for mport devices (RIO_MPORT_MAINT_HDID_SET)

- Set RapidIO Component Tag for mport devices (RIO_MPORT_MAINT_COMPTAG_SET)

- Query logical index of mport devices (RIO_MPORT_MAINT_PORT_IDX_GET)

- Query capabilities and RapidIO link configuration of mport devices (RIO_MPORT_GET_PROPERTIES)

- Enable/Disable reporting of RapidIO doorbell events to user-space applications (RIO_ENABLE_DOORBELL_RANGE/RIO_DISABLE_DOORBELL_RANGE)

- Enable/Disable reporting of RIO port-write events to user-space applications (RIO_ENABLE_PORTWRITE_RANGE/RIO_DISABLE_PORTWRITE_RANGE)

- Query/Control type of events reported through this driver: doorbells, port-writes or both (RIO_SET_EVENT_MASK/RIO_GET_EVENT_MASK)

- Configure/Map mport's outbound requests window(s) for specific size, RapidIO destination ID, hopcount and request type (RIO_MAP_OUTBOUND/RIO_UNMAP_OUTBOUND)

- Configure/Map mport's inbound requests window(s) for specific size, RapidIO base address and local memory base address (RIO_MAP_INBOUND/RIO_UNMAP_INBOUND)

- Allocate/Free contiguous DMA coherent memory buffer for DMA data transfers to/from remote RapidIO devices (RIO_ALLOC_DMA/RIO_FREE_DMA)

- Initiate DMA data transfers to/from remote RapidIO devices (RIO_TRANSFER). Supports blocking, asynchronous and posted (a.k.a 'fire-and-forget') data transfer modes.

- Check/Wait for completion of asynchronous DMA data transfer (RIO_WAIT_FOR_ASYNC)

- Manage device objects supported by RapidIO subsystem (RIO_DEV_ADD/RIO_DEV_DEL). This allows implementation of various RapidIO fabric enumeration algorithms as user-space applications while using remaining functionality provided by kernel RapidIO subsystem.

<a id="rst-hardware-compatibility"></a>

## 2. Hardware Compatibility

This device driver uses standard interfaces defined by kernel RapidIO subsystem and therefore it can be used with any mport device driver registered by RapidIO subsystem with limitations set by available mport implementation.

At this moment the most common limitation is availability of RapidIO-specific DMA engine framework for specific mport device. Users should verify available functionality of their platform when planning to use this driver:

- IDT Tsi721 PCIe-to-RapidIO bridge device and its mport device driver are fully compatible with this driver.

- Freescale SoCs 'fsl_rio' mport driver does not have implementation for RapidIO specific DMA engine support and therefore DMA data transfers mport_cdev driver are not available.

<a id="rst-module-parameters"></a>

## 3. Module parameters

- - **'dma_timeout'**

    - DMA transfer completion timeout (in msec, default value 3000). This parameter set a maximum completion wait time for SYNC mode DMA transfer requests and for RIO_WAIT_FOR_ASYNC ioctl requests.

- - **'dbg_level'**

    - This parameter allows to control amount of debug information generated by this device driver. This parameter is formed by set of bit masks that correspond to the specific functional blocks. For mask definitions see 'drivers/rapidio/devices/rio_mport_cdev.c' This parameter can be changed dynamically. Use CONFIG_RAPIDIO_DEBUG=y to enable debug output at the top level.

<a id="rst-known-problems"></a>

## 4. Known problems

> None.

<a id="rst-user-space-applications-and-api"></a>

## 5. User-space Applications and API

API library and applications that use this device driver are available from RapidIO.org.

<a id="rst-todo-list"></a>

## 6. TODO List

- Add support for sending/receiving "raw" RapidIO messaging packets.

- Add memory mapped DMA data transfers as an option when RapidIO-specific DMA is not available.

---

# Introduction

_Peios Kernel / Hardware and drivers / Driver development / RapidIO_

> The RapidIO standard is a packet-based fabric interconnect standard designed for use in embedded systems. Development of the RapidIO standard is directed by the RapidIO Trade Association (RTA). The current version of the RapidIO…

<a id="rst-introduction"></a>

The RapidIO standard is a packet-based fabric interconnect standard designed for use in embedded systems. Development of the RapidIO standard is directed by the RapidIO Trade Association (RTA). The current version of the RapidIO specification is publicly available for download from the RTA web-site \[1\].

This document describes the basics of the Linux RapidIO subsystem and provides information on its major components.

<a id="rst-overview"></a>

## 1 Overview

Because the RapidIO subsystem follows the Linux device model it is integrated into the kernel similarly to other buses by defining RapidIO-specific device and bus types and registering them within the device model.

The Linux RapidIO subsystem is architecture independent and therefore defines architecture-specific interfaces that provide support for common RapidIO subsystem operations.

<a id="rst-core-components"></a>

## 2. Core Components

A typical RapidIO network is a combination of endpoints and switches. Each of these components is represented in the subsystem by an associated data structure. The core logical components of the RapidIO subsystem are defined in include/linux/rio.h file.

<a id="rst-master-port"></a>

### 2.1 Master Port

A master port (or mport) is a RapidIO interface controller that is local to the processor executing the Linux code. A master port generates and receives RapidIO packets (transactions). In the RapidIO subsystem each master port is represented by a rio_mport data structure. This structure contains master port specific resources such as mailboxes and doorbells. The rio_mport also includes a unique host device ID that is valid when a master port is configured as an enumerating host.

RapidIO master ports are serviced by subsystem specific mport device drivers that provide functionality defined for this subsystem. To provide a hardware independent interface for RapidIO subsystem operations, rio_mport structure includes rio_ops data structure which contains pointers to hardware specific implementations of RapidIO functions.

<a id="rst-device"></a>

### 2.2 Device

A RapidIO device is any endpoint (other than mport) or switch in the network. All devices are presented in the RapidIO subsystem by corresponding rio_dev data structure. Devices form one global device list and per-network device lists (depending on number of available mports and networks).

<a id="rst-switch"></a>

### 2.3 Switch

A RapidIO switch is a special class of device that routes packets between its ports towards their final destination. The packet destination port within a switch is defined by an internal routing table. A switch is presented in the RapidIO subsystem by rio_dev data structure expanded by additional rio_switch data structure, which contains switch specific information such as copy of the routing table and pointers to switch specific functions.

The RapidIO subsystem defines the format and initialization method for subsystem specific switch drivers that are designed to provide hardware-specific implementation of common switch management routines.

<a id="rst-network"></a>

### 2.4 Network

A RapidIO network is a combination of interconnected endpoint and switch devices. Each RapidIO network known to the system is represented by corresponding rio_net data structure. This structure includes lists of all devices and local master ports that form the same network. It also contains a pointer to the default master port that is used to communicate with devices within the network.

<a id="rst-device-drivers"></a>

### 2.5 Device Drivers

RapidIO device-specific drivers follow Linux Kernel Driver Model and are intended to support specific RapidIO devices attached to the RapidIO network.

<a id="rst-subsystem-interfaces"></a>

### 2.6 Subsystem Interfaces

RapidIO interconnect specification defines features that may be used to provide one or more common service layers for all participating RapidIO devices. These common services may act separately from device-specific drivers or be used by device-specific drivers. Example of such service provider is the RIONET driver which implements Ethernet-over-RapidIO interface. Because only one driver can be registered for a device, all common RapidIO services have to be registered as subsystem interfaces. This allows to have multiple common services attached to the same device without blocking attachment of a device-specific driver.

<a id="rst-subsystem-initialization"></a>

## 3. Subsystem Initialization

In order to initialize the RapidIO subsystem, a platform must initialize and register at least one master port within the RapidIO network. To register mport within the subsystem controller driver's initialization code calls function rio_register_mport() for each available master port.

After all active master ports are registered with a RapidIO subsystem, an enumeration and/or discovery routine may be called automatically or by user-space command.

RapidIO subsystem can be configured to be built as a statically linked or modular component of the kernel (see details below).

<a id="rst-enumeration-and-discovery"></a>

## 4. Enumeration and Discovery

<a id="rst-overview-1"></a>

### 4.1 Overview

RapidIO subsystem configuration options allow users to build enumeration and discovery methods as statically linked components or loadable modules. An enumeration/discovery method implementation and available input parameters define how any given method can be attached to available RapidIO mports: simply to all available mports OR individually to the specified mport device.

Depending on selected enumeration/discovery build configuration, there are several methods to initiate an enumeration and/or discovery process:

> (a) Statically linked enumeration and discovery process can be started automatically during kernel initialization time using corresponding module parameters. This was the original method used since introduction of RapidIO subsystem. Now this method relies on enumerator module parameter which is 'rio-scan.scan' for existing basic enumeration/discovery method. When automatic start of enumeration/discovery is used a user has to ensure that all discovering endpoints are started before the enumerating endpoint and are waiting for enumeration to be completed. Configuration option CONFIG_RAPIDIO_DISC_TIMEOUT defines time that discovering endpoint waits for enumeration to be completed. If the specified timeout expires the discovery process is terminated without obtaining RapidIO network information. NOTE: a timed out discovery process may be restarted later using a user-space command as it is described below (if the given endpoint was enumerated successfully).
>
> (b) Statically linked enumeration and discovery process can be started by a command from user space. This initiation method provides more flexibility for a system startup compared to the option (a) above. After all participating endpoints have been successfully booted, an enumeration process shall be started first by issuing a user-space command, after an enumeration is completed a discovery process can be started on all remaining endpoints.
>
> (c) Modular enumeration and discovery process can be started by a command from user space. After an enumeration/discovery module is loaded, a network scan process can be started by issuing a user-space command. Similar to the option (b) above, an enumerator has to be started first.
>
> (d) Modular enumeration and discovery process can be started by a module initialization routine. In this case an enumerating module shall be loaded first.

When a network scan process is started it calls an enumeration or discovery routine depending on the configured role of a master port: host or agent.

Enumeration is performed by a master port if it is configured as a host port by assigning a host destination ID greater than or equal to zero. The host destination ID can be assigned to a master port using various methods depending on RapidIO subsystem build configuration:

> (a) For a statically linked RapidIO subsystem core use command line parameter "rapidio.hdid=" with a list of destination ID assignments in order of mport device registration. For example, in a system with two RapidIO controllers the command line parameter "rapidio.hdid=-1,7" will result in assignment of the host destination ID=7 to the second RapidIO controller, while the first one will be assigned destination ID=-1.
>
> (b) If the RapidIO subsystem core is built as a loadable module, in addition to the method shown above, the host destination ID(s) can be specified using traditional methods of passing module parameter "hdid=" during its loading:
>
> - from command line: "modprobe rapidio hdid=-1,7", or
>
> - from modprobe configuration file using configuration command "options", like in this example: "options rapidio hdid=-1,7". An example of modprobe configuration file is provided in the section below.

- **NOTES:**

  (i) if "hdid=" parameter is omitted all available mport will be assigned destination ID = -1;

  (ii) the "hdid=" parameter in systems with multiple mports can have destination ID assignments omitted from the end of list (default = -1).

If the host device ID for a specific master port is set to -1, the discovery process will be performed for it.

The enumeration and discovery routines use RapidIO maintenance transactions to access the configuration space of devices.

NOTE: If RapidIO switch-specific device drivers are built as loadable modules they must be loaded before enumeration/discovery process starts. This requirement is cased by the fact that enumeration/discovery methods invoke vendor-specific callbacks on early stages.

<a id="rst-automatic-start-of-enumeration-and-discovery"></a>

### 4.2 Automatic Start of Enumeration and Discovery

Automatic enumeration/discovery start method is applicable only to built-in enumeration/discovery RapidIO configuration selection. To enable automatic enumeration/discovery start by existing basic enumerator method set use boot command line parameter "rio-scan.scan=1".

This configuration requires synchronized start of all RapidIO endpoints that form a network which will be enumerated/discovered. Discovering endpoints have to be started before an enumeration starts to ensure that all RapidIO controllers have been initialized and are ready to be discovered. Configuration parameter CONFIG_RAPIDIO_DISC_TIMEOUT defines time (in seconds) which a discovering endpoint will wait for enumeration to be completed.

When automatic enumeration/discovery start is selected, basic method's initialization routine calls rio_init_mports() to perform enumeration or discovery for all known mport devices.

Depending on RapidIO network size and configuration this automatic enumeration/discovery start method may be difficult to use due to the requirement for synchronized start of all endpoints.

<a id="rst-user-space-start-of-enumeration-and-discovery"></a>

### 4.3 User-space Start of Enumeration and Discovery

User-space start of enumeration and discovery can be used with built-in and modular build configurations. For user-space controlled start RapidIO subsystem creates the sysfs write-only attribute file '/sys/bus/rapidio/scan'. To initiate an enumeration or discovery process on specific mport device, a user needs to write mport_ID (not RapidIO destination ID) into that file. The mport_ID is a sequential number (0 ... RIO_MAX_MPORTS) assigned during mport device registration. For example for machine with single RapidIO controller, mport_ID for that controller always will be 0.

To initiate RapidIO enumeration/discovery on all available mports a user may write '-1' (or RIO_MPORT_ANY) into the scan attribute file.

<a id="rst-basic-enumeration-method"></a>

### 4.4 Basic Enumeration Method

This is an original enumeration/discovery method which is available since first release of RapidIO subsystem code. The enumeration process is implemented according to the enumeration algorithm outlined in the RapidIO Interconnect Specification: Annex I \[1\].

This method can be configured as statically linked or loadable module. The method's single parameter "scan" allows to trigger the enumeration/discovery process from module initialization routine.

This enumeration/discovery method can be started only once and does not support unloading if it is built as a module.

The enumeration process traverses the network using a recursive depth-first algorithm. When a new device is found, the enumerator takes ownership of that device by writing into the Host Device ID Lock CSR. It does this to ensure that the enumerator has exclusive right to enumerate the device. If device ownership is successfully acquired, the enumerator allocates a new rio_dev structure and initializes it according to device capabilities.

If the device is an endpoint, a unique device ID is assigned to it and its value is written into the device's Base Device ID CSR.

If the device is a switch, the enumerator allocates an additional rio_switch structure to store switch specific information. Then the switch's vendor ID and device ID are queried against a table of known RapidIO switches. Each switch table entry contains a pointer to a switch-specific initialization routine that initializes pointers to the rest of switch specific operations, and performs hardware initialization if necessary. A RapidIO switch does not have a unique device ID; it relies on hopcount and routing for device ID of an attached endpoint if access to its configuration registers is required. If a switch (or chain of switches) does not have any endpoint (except enumerator) attached to it, a fake device ID will be assigned to configure a route to that switch. In the case of a chain of switches without endpoint, one fake device ID is used to configure a route through the entire chain and switches are differentiated by their hopcount value.

For both endpoints and switches the enumerator writes a unique component tag into device's Component Tag CSR. That unique value is used by the error management notification mechanism to identify a device that is reporting an error management event.

Enumeration beyond a switch is completed by iterating over each active egress port of that switch. For each active link, a route to a default device ID (0xFF for 8-bit systems and 0xFFFF for 16-bit systems) is temporarily written into the routing table. The algorithm recurs by calling itself with hopcount + 1 and the default device ID in order to access the device on the active port.

After the host has completed enumeration of the entire network it releases devices by clearing device ID locks (calls rio_clear_locks()). For each endpoint in the system, it sets the Discovered bit in the Port General Control CSR to indicate that enumeration is completed and agents are allowed to execute passive discovery of the network.

The discovery process is performed by agents and is similar to the enumeration process that is described above. However, the discovery process is performed without changes to the existing routing because agents only gather information about RapidIO network structure and are building an internal map of discovered devices. This way each Linux-based component of the RapidIO subsystem has a complete view of the network. The discovery process can be performed simultaneously by several agents. After initializing its RapidIO master port each agent waits for enumeration completion by the host for the configured wait time period. If this wait time period expires before enumeration is completed, an agent skips RapidIO discovery and continues with remaining kernel initialization.

<a id="rst-adding-new-enumeration-discovery-method"></a>

### 4.5 Adding New Enumeration/Discovery Method

RapidIO subsystem code organization allows addition of new enumeration/discovery methods as new configuration options without significant impact to the core RapidIO code.

A new enumeration/discovery method has to be attached to one or more mport devices before an enumeration/discovery process can be started. Normally, method's module initialization routine calls rio_register_scan() to attach an enumerator to a specified mport device (or devices). The basic enumerator implementation demonstrates this process.

<a id="rst-using-loadable-rapidio-switch-drivers"></a>

### 4.6 Using Loadable RapidIO Switch Drivers

In the case when RapidIO switch drivers are built as loadable modules a user must ensure that they are loaded before the enumeration/discovery starts. This process can be automated by specifying pre- or post- dependencies in the RapidIO-specific modprobe configuration file as shown in the example below.

File /etc/modprobe.d/rapidio.conf:



```text
# Configure RapidIO subsystem modules

# Set enumerator host destination ID (overrides kernel command line option)
options rapidio hdid=-1,2

# Load RapidIO switch drivers immediately after rapidio core module was loaded
softdep rapidio post: idt_gen2 idtcps tsi57x

# OR :

# Load RapidIO switch drivers just before rio-scan enumerator module is loaded
softdep rio-scan pre: idt_gen2 idtcps tsi57x

--------------------------
```

- **NOTE:**

  In the example above, one of "softdep" commands must be removed or commented out to keep required module loading sequence.

<a id="rst-references"></a>

## 5. References

- **\[1\] RapidIO Trade Association. RapidIO Interconnect Specifications.**

  [http://www.rapidio.org](<http://www.rapidio.org>).

- **\[2\] Rapidio TA. Technology Comparisons.**

  [http://www.rapidio.org/education/technology_comparisons/](<http://www.rapidio.org/education/technology_comparisons/>)

- **\[3\] RapidIO support for Linux.**

  [https://lwn.net/Articles/139118/](<https://lwn.net/Articles/139118/>)

- **\[4\] Matt Porter. RapidIO for Linux. Ottawa Linux Symposium, 2005**

  [https://www.kernel.org/doc/ols/2005/ols2005v2-pages-43-56.pdf](<https://www.kernel.org/doc/ols/2005/ols2005v2-pages-43-56.pdf>)

---

# RapidIO subsystem Channelized Messaging character device driver (rio_cm.c)

_Peios Kernel / Hardware and drivers / Driver development / RapidIO_

> This device driver is the result of collaboration within the RapidIO.org Software Task Group (STG) between Texas Instruments, Prodrive Technologies, Nokia Networks, BAE and IDT. Additional input was received from other members of…

<a id="rst-rapidio-subsystem-channelized-messaging-character-device-driver-rio-cm-c"></a>

<a id="rst-overview"></a>

## 1. Overview

This device driver is the result of collaboration within the RapidIO.org Software Task Group (STG) between Texas Instruments, Prodrive Technologies, Nokia Networks, BAE and IDT.  Additional input was received from other members of RapidIO.org.

The objective was to create a character mode driver interface which exposes messaging capabilities of RapidIO endpoint devices (mports) directly to applications, in a manner that allows the numerous and varied RapidIO implementations to interoperate.

This driver (RIO_CM) provides to user-space applications shared access to RapidIO mailbox messaging resources.

RapidIO specification (Part 2) defines that endpoint devices may have up to four messaging mailboxes in case of multi-packet message (up to 4KB) and up to 64 mailboxes if single-packet messages (up to 256 B) are used. In addition to protocol definition limitations, a particular hardware implementation can have reduced number of messaging mailboxes.  RapidIO aware applications must therefore share the messaging resources of a RapidIO endpoint.

Main purpose of this device driver is to provide RapidIO mailbox messaging capability to large number of user-space processes by introducing socket-like operations using a single messaging mailbox.  This allows applications to use the limited RapidIO messaging hardware resources efficiently.

Most of device driver's operations are supported through 'ioctl' system calls.

When loaded this device driver creates a single file system node named rio_cm in /dev directory common for all registered RapidIO mport devices.

Following ioctl commands are available to user-space applications:

- - **RIO_CM_MPORT_GET_LIST:**

    Returns to caller list of local mport devices that support messaging operations (number of entries up to RIO_MAX_MPORTS). Each list entry is combination of mport's index in the system and RapidIO destination ID assigned to the port.

- - **RIO_CM_EP_GET_LIST_SIZE:**

    Returns number of messaging capable remote endpoints in a RapidIO network associated with the specified mport device.

- - **RIO_CM_EP_GET_LIST:**

    Returns list of RapidIO destination IDs for messaging capable remote endpoints (peers) available in a RapidIO network associated with the specified mport device.

- - **RIO_CM_CHAN_CREATE:**

    Creates RapidIO message exchange channel data structure with channel ID assigned automatically or as requested by a caller.

- - **RIO_CM_CHAN_BIND:**

    Binds the specified channel data structure to the specified mport device.

- - **RIO_CM_CHAN_LISTEN:**

    Enables listening for connection requests on the specified channel.

- - **RIO_CM_CHAN_ACCEPT:**

    Accepts a connection request from peer on the specified channel. If wait timeout for this request is specified by a caller it is a blocking call. If timeout set to 0 this is non-blocking call - ioctl handler checks for a pending connection request and if one is not available exits with -EGAIN error status immediately.

- - **RIO_CM_CHAN_CONNECT:**

    Sends a connection request to a remote peer/channel.

- - **RIO_CM_CHAN_SEND:**

    Sends a data message through the specified channel. The handler for this request assumes that message buffer specified by a caller includes the reserved space for a packet header required by this driver.

- - **RIO_CM_CHAN_RECEIVE:**

    Receives a data message through a connected channel. If the channel does not have an incoming message ready to return this ioctl handler will wait for new message until timeout specified by a caller expires. If timeout value is set to 0, ioctl handler uses a default value defined by MAX_SCHEDULE_TIMEOUT.

- - **RIO_CM_CHAN_CLOSE:**

    Closes a specified channel and frees associated buffers. If the specified channel is in the CONNECTED state, sends close notification to the remote peer.

The ioctl command codes and corresponding data structures intended for use by user-space applications are defined in 'include/uapi/linux/rio_cm_cdev.h'.

<a id="rst-hardware-compatibility"></a>

## 2. Hardware Compatibility

This device driver uses standard interfaces defined by kernel RapidIO subsystem and therefore it can be used with any mport device driver registered by RapidIO subsystem with limitations set by available mport HW implementation of messaging mailboxes.

<a id="rst-module-parameters"></a>

## 3. Module parameters

- - **'dbg_level'**

    - This parameter allows to control amount of debug information generated by this device driver. This parameter is formed by set of bit masks that correspond to the specific functional block. For mask definitions see 'drivers/rapidio/devices/rio_cm.c' This parameter can be changed dynamically. Use CONFIG_RAPIDIO_DEBUG=y to enable debug output at the top level.

- - **'cmbox'**

    - Number of RapidIO mailbox to use (default value is 1). This parameter allows to set messaging mailbox number that will be used within entire RapidIO network. It can be used when default mailbox is used by other device drivers or is not supported by some nodes in the RapidIO network.

- - **'chstart'**

    - Start channel number for dynamic assignment. Default value - 256. Allows to exclude channel numbers below this parameter from dynamic allocation to avoid conflicts with software components that use reserved predefined channel numbers.

<a id="rst-known-problems"></a>

## 4. Known problems

> None.

<a id="rst-user-space-applications-and-api-library"></a>

## 5. User-space Applications and API Library

Messaging API library and applications that use this device driver are available from RapidIO.org.

<a id="rst-todo-list"></a>

## 6. TODO List

- Add support for system notification messages (reserved channel 0).

---

# Sysfs entries

_Peios Kernel / Hardware and drivers / Driver development / RapidIO_

> The RapidIO sysfs files have moved to: Documentation/ABI/testing/sysfs-bus-rapidio and Documentation/ABI/testing/sysfs-class-rapidio

<a id="rst-sysfs-entries"></a>

The RapidIO sysfs files have moved to: Documentation/ABI/testing/sysfs-bus-rapidio and Documentation/ABI/testing/sysfs-class-rapidio

---

# RapidIO subsystem mport driver for IDT Tsi721 PCI Express-to-SRIO bridge.

_Peios Kernel / Hardware and drivers / Driver development / RapidIO_

> This driver implements all currently defined RapidIO mport callback functions. It supports maintenance read and write operations, inbound and outbound RapidIO doorbells, inbound maintenance port-writes and RapidIO messaging.

<a id="rst-rapidio-subsystem-mport-driver-for-idt-tsi721-pci-express-to-srio-bridge"></a>

<a id="rst-overview"></a>

## 1. Overview

This driver implements all currently defined RapidIO mport callback functions. It supports maintenance read and write operations, inbound and outbound RapidIO doorbells, inbound maintenance port-writes and RapidIO messaging.

To generate SRIO maintenance transactions this driver uses one of Tsi721 DMA channels. This mechanism provides access to larger range of hop counts and destination IDs without need for changes in outbound window translation.

RapidIO messaging support uses dedicated messaging channels for each mailbox. For inbound messages this driver uses destination ID matching to forward messages into the corresponding message queue. Messaging callbacks are implemented to be fully compatible with RIONET driver (Ethernet over RapidIO messaging services).

1. Module parameters:

- - **'dbg_level'**

    - This parameter allows to control amount of debug information generated by this device driver. This parameter is formed by set of This parameter can be changed bit masks that correspond to the specific functional block. For mask definitions see 'drivers/rapidio/devices/tsi721.h' This parameter can be changed dynamically. Use CONFIG_RAPIDIO_DEBUG=y to enable debug output at the top level.

- - **'dma_desc_per_channel'**

    - This parameter defines number of hardware buffer descriptors allocated for each registered Tsi721 DMA channel. Its default value is 128.

- - **'dma_txqueue_sz'**

    - DMA transactions queue size. Defines number of pending transaction requests that can be accepted by each DMA channel. Default value is 16.

- - **'dma_sel'**

    - DMA channel selection mask. Bitmask that defines which hardware DMA channels (0 ... 6) will be registered with DmaEngine core. If bit is set to 1, the corresponding DMA channel will be registered. DMA channels not selected by this mask will not be used by this device driver. Default value is 0x7f (use all channels).

- - **'pcie_mrrs'**

    - override value for PCIe Maximum Read Request Size (MRRS). This parameter gives an ability to override MRRS value set during PCIe configuration process. Tsi721 supports read request sizes up to 4096B. Value for this parameter must be set as defined by PCIe specification: 0 = 128B, 1 = 256B, 2 = 512B, 3 = 1024B, 4 = 2048B and 5 = 4096B. Default value is '-1' (= keep platform setting).

- - **'mbox_sel'**

    - RIO messaging MBOX selection mask. This is a bitmask that defines messaging MBOXes are managed by this device driver. Mask bits 0 - 3 correspond to MBOX0 - MBOX3. MBOX is under driver's control if the corresponding bit is set to '1'. Default value is 0x0f (= all).

<a id="rst-known-problems"></a>

## 2. Known problems

> None.

<a id="rst-dma-engine-support"></a>

## 3. DMA Engine Support

Tsi721 mport driver supports DMA data transfers between local system memory and remote RapidIO devices. This functionality is implemented according to SLAVE mode API defined by common Linux kernel DMA Engine framework.

Depending on system requirements RapidIO DMA operations can be included/excluded by setting CONFIG_RAPIDIO_DMA_ENGINE option. Tsi721 miniport driver uses seven out of eight available BDMA channels to support DMA data transfers. One BDMA channel is reserved for generation of maintenance read/write requests.

If Tsi721 mport driver have been built with RAPIDIO_DMA_ENGINE support included, this driver will accept DMA-specific module parameter:

> - **"dma_desc_per_channel"**
>
>   - defines number of hardware buffer descriptors used by each BDMA channel of Tsi721 (by default - 128).

4. Version History

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> 1.1.0
>
> </td>
> <td>
>
>
> DMA operations re-worked to support data scatter/gather lists larger than hardware buffer descriptors ring.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1.0.0
>
> </td>
> <td>
>
>
> Initial driver release.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-license"></a>

## 5.  License

> Copyright(c) 2011 Integrated Device Technology, Inc. All rights reserved.
>
> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
>
> This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
>
> You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

---

# Support for Serial devices

_Peios Kernel / Hardware and drivers / Driver development / Serial ports_

> Reference for Support for Serial devices.

<a id="rst-support-for-serial-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Low Level Serial API](</kernel/hardware/driver-api/serial/driver.md>)

<a id="rst-serial-drivers"></a>

## Serial drivers

- [ISO7816 Serial Communications](</kernel/hardware/driver-api/serial/serial-iso7816.md>)
- [RS485 Serial Communications](</kernel/hardware/driver-api/serial/serial-rs485.md>)

---

# Low Level Serial API

_Peios Kernel / Hardware and drivers / Driver development / Serial ports_

> This document is meant as a brief overview of some aspects of the new serial driver. It is not complete, any questions you have should be directed to <rmk@arm.linux.org.uk>

<a id="rst-low-level-serial-api"></a>

This document is meant as a brief overview of some aspects of the new serial driver.  It is not complete, any questions you have should be directed to &lt;[rmk@arm.linux.org.uk](<mailto:rmk@arm.linux.org.uk>)&gt;

The reference implementation is contained within amba-pl011.c.

<a id="rst-low-level-serial-hardware-driver"></a>

## Low Level Serial Hardware Driver

The low level serial hardware driver is responsible for supplying port information (defined by uart_port) and a set of control methods (defined by uart_ops) to the core serial driver.  The low level driver is also responsible for handling interrupts for the port, and providing any console support.

<a id="rst-console-support"></a>

## Console Support

The serial core provides a few helper functions.  This includes decoding command line arguments (uart_parse_options()).

There is also a helper function (uart_console_write()) which performs a character by character write, translating newlines to CRLF sequences. Driver writers are recommended to use this function rather than implementing their own version.

<a id="rst-locking"></a>

## Locking

It is the responsibility of the low level hardware driver to perform the necessary locking using port-&gt;lock.  There are some exceptions (which are described in the struct uart_ops listing below.)

There are two locks.  A per-port spinlock, and an overall semaphore.

From the core driver perspective, the port-&gt;lock locks the following data:



```text
port->mctrl
port->icount
port->state->xmit.head (circ_buf->head)
port->state->xmit.tail (circ_buf->tail)
```

The low level driver is free to use this lock to provide any additional locking.

The port_sem semaphore is used to protect against ports being added/ removed or reconfigured at inappropriate times. Since v2.6.27, this semaphore has been the 'mutex' member of the tty_port struct, and commonly referred to as the port mutex.

<a id="rst-uart-ops"></a>

## uart_ops


#### <a id="c-struct-uart_ops"></a>`struct uart_ops`

- interface between serial_core and the driver

**Definition**

```c
struct uart_ops {
        unsigned int    (*tx_empty)(struct uart_port *);
        void (*set_mctrl)(struct uart_port *, unsigned int mctrl);
        unsigned int    (*get_mctrl)(struct uart_port *);
        void (*stop_tx)(struct uart_port *);
        void (*start_tx)(struct uart_port *);
        void (*throttle)(struct uart_port *);
        void (*unthrottle)(struct uart_port *);
        void (*send_xchar)(struct uart_port *, char ch);
        void (*stop_rx)(struct uart_port *);
        void (*start_rx)(struct uart_port *);
        void (*enable_ms)(struct uart_port *);
        void (*break_ctl)(struct uart_port *, int ctl);
        int (*startup)(struct uart_port *);
        void (*shutdown)(struct uart_port *);
        void (*flush_buffer)(struct uart_port *);
        void (*set_termios)(struct uart_port *, struct ktermios *new, const struct ktermios *old);
        void (*set_ldisc)(struct uart_port *, struct ktermios *);
        void (*pm)(struct uart_port *, unsigned int state, unsigned int oldstate);
        const char      *(*type)(struct uart_port *);
        void (*release_port)(struct uart_port *);
        int (*request_port)(struct uart_port *);
        void (*config_port)(struct uart_port *, int);
        int (*verify_port)(struct uart_port *, struct serial_struct *);
        int (*ioctl)(struct uart_port *, unsigned int, unsigned long);
    #ifdef CONFIG_CONSOLE_POLL;
        int (*poll_init)(struct uart_port *);
        void (*poll_put_char)(struct uart_port *, unsigned char);
        int (*poll_get_char)(struct uart_port *);
    #endif;
};
```

**Members**

- `tx_empty`: `unsigned int ()(struct uart_port *port)`
- `set_mctrl`: `void ()(struct uart_port *port, unsigned int mctrl)`
- `get_mctrl`: `unsigned int ()(struct uart_port *port)`
- `stop_tx`: `void ()(struct uart_port *port)`
- `start_tx`: `void ()(struct uart_port *port)`
- `throttle`: `void ()(struct uart_port *port)`
- `unthrottle`: `void ()(struct uart_port *port)`
- `send_xchar`: `void ()(struct uart_port *port, char ch)`
- `stop_rx`: `void ()(struct uart_port *port)`
- `start_rx`: `void ()(struct uart_port *port)`
- `enable_ms`: `void ()(struct uart_port *port)`
- `break_ctl`: `void ()(struct uart_port *port, int ctl)`
- `startup`: `int ()(struct uart_port *port)`
- `shutdown`: `void ()(struct uart_port *port)`
- `flush_buffer`: `void ()(struct uart_port *port)`
- `set_termios`: `void ()(struct uart_port *port, struct ktermios *new, struct ktermios *old)`
- `set_ldisc`: `void ()(struct uart_port *port, struct ktermios *termios)`
- `pm`: `void ()(struct uart_port *port, unsigned int state, unsigned int oldstate)`
- `type`: `const char *()(struct uart_port *port)`
- `release_port`: `void ()(struct uart_port *port)`
- `request_port`: `int ()(struct uart_port *port)`
- `config_port`: `void ()(struct uart_port *port, int type)`
- `verify_port`: `int ()(struct uart_port *port, struct serial_struct *serinfo)`
- `ioctl`: `int ()(struct uart_port *port, unsigned int cmd, unsigned long arg)`
- `poll_init`: `int ()(struct uart_port *port)`
- `poll_put_char`: `void ()(struct uart_port *port, unsigned char ch)`
- `poll_get_char`: `int ()(struct uart_port *port)`

**Description**

This structure describes all the operations that can be done on the
physical hardware.

This function tests whether the transmitter fifo and shifter for the
**port** is empty. If it is empty, this function should return
`TIOCSER_TEMT`, otherwise return 0. If the port does not support this
operation, then it should return `TIOCSER_TEMT`.

Locking: none.
Interrupts: caller dependent.
This call must not sleep

This function sets the modem control lines for **port** to the state
described by **mctrl**. The relevant bits of **mctrl** are:

- `TIOCM_RTS`    RTS signal.
- `TIOCM_DTR`    DTR signal.
- `TIOCM_OUT1`   OUT1 signal.
- `TIOCM_OUT2`   OUT2 signal.
- `TIOCM_LOOP`   Set the port into loopback mode.

  If the appropriate bit is set, the signal should be driven
  active.  If the bit is clear, the signal should be driven
  inactive.

  Locking: **port->lock** taken.
  Interrupts: locally disabled.
  This call must not sleep

  Returns the current state of modem control inputs of **port**. The state
  of the outputs should not be returned, since the core keeps track of
  their state. The state information should include:

- `TIOCM_CAR`    state of DCD signal
- `TIOCM_CTS`    state of CTS signal
- `TIOCM_DSR`    state of DSR signal
- `TIOCM_RI`     state of RI signal

  The bit is set if the signal is currently driven active.  If
  the port does not support CTS, DCD or DSR, the driver should
  indicate that the signal is permanently active. If RI is
  not available, the signal should not be indicated as active.

  Locking: **port->lock** taken.
  Interrupts: locally disabled.
  This call must not sleep

  Stop transmitting characters. This might be due to the CTS line
  becoming inactive or the tty layer indicating we want to stop
  transmission due to an `XOFF` character.

  The driver should stop transmitting characters as soon as possible.

  Locking: **port->lock** taken.
  Interrupts: locally disabled.
  This call must not sleep

  Start transmitting characters.

  Locking: **port->lock** taken.
  Interrupts: locally disabled.
  This call must not sleep

  Notify the serial driver that input buffers for the line discipline are
  close to full, and it should somehow signal that no more characters
  should be sent to the serial port.
  This will be called only if hardware assisted flow control is enabled.

  Locking: serialized with **unthrottle()** and termios modification by the
  tty layer.

  Notify the serial driver that characters can now be sent to the serial
  port without fear of overrunning the input buffers of the line
  disciplines.

  This will be called only if hardware assisted flow control is enabled.

  Locking: serialized with **throttle()** and termios modification by the
  tty layer.

  Transmit a high priority character, even if the port is stopped. This
  is used to implement XON/XOFF flow control and `tcflow()`. If the serial
  driver does not implement this function, the tty core will append the
  character to the circular buffer and then call `start_tx()` / `stop_tx()`
  to flush the data out.

  Do not transmit if **ch** == '\0' (`__DISABLED_CHAR`).

  Locking: none.
  Interrupts: caller dependent.

  Start receiving characters.

  Locking: **port->lock** taken.
  Interrupts: locally disabled.
  This call must not sleep

  Stop receiving characters; the **port** is in the process of being closed.

  Locking: **port->lock** taken.
  Interrupts: locally disabled.
  This call must not sleep

  Enable the modem status interrupts.

  This method may be called multiple times. Modem status interrupts
  should be disabled when the **shutdown()** method is called.

  Locking: **port->lock** taken.
  Interrupts: locally disabled.
  This call must not sleep

  Control the transmission of a break signal. If **ctl** is nonzero, the
  break signal should be transmitted. The signal should be terminated
  when another call is made with a zero **ctl**.

  Locking: caller holds tty_port->mutex

  Grab any interrupt resources and initialise any low level driver state.
  Enable the port for reception. It should not activate RTS nor DTR;
  this will be done via a separate call to **set_mctrl()**.

  This method will only be called when the port is initially opened.

  Locking: port_sem taken.
  Interrupts: globally disabled.

  Disable the **port**, disable any break condition that may be in effect,
  and free any interrupt resources. It should not disable RTS nor DTR;
  this will have already been done via a separate call to **set_mctrl()**.

  Drivers must not access **port->state** once this call has completed.

  This method will only be called when there are no more users of this
  **port**.

  Locking: port_sem taken.
  Interrupts: caller dependent.

  Flush any write buffers, reset any DMA state and stop any ongoing DMA
  transfers.

  This will be called whenever the **port->state->xmit** circular buffer is
  cleared.

  Locking: **port->lock** taken.
  Interrupts: locally disabled.
  This call must not sleep

  Change the **port** parameters, including word length, parity, stop bits.
  Update **port->read_status_mask** and **port->ignore_status_mask** to
  indicate the types of events we are interested in receiving. Relevant
  ktermios::c_cflag bits are:

- `CSIZE` - word size
- `CSTOPB` - 2 stop bits
- `PARENB` - parity enable
- `PARODD` - odd parity (when `PARENB` is in force)
- `ADDRB` - address bit (changed through uart_port::`rs485_config()`).
- `CREAD` - enable reception of characters (if not set, still receive
  characters from the port, but throw them away).
- `CRTSCTS` - if set, enable CTS status change reporting.
- `CLOCAL` - if not set, enable modem status change reporting.

  Relevant ktermios::c_iflag bits are:

- `INPCK` - enable frame and parity error events to be passed to the TTY
  layer.
- `BRKINT` / `PARMRK` - both of these enable break events to be passed to
  the TTY layer.
- `IGNPAR` - ignore parity and framing errors.
- `IGNBRK` - ignore break errors. If `IGNPAR` is also set, ignore overrun
  errors as well.

  The interaction of the ktermios::c_iflag bits is as follows (parity
  error given as an example):

```text
============ ======= ======= =========================================
Parity error INPCK   IGNPAR
============ ======= ======= =========================================
n/a          0       n/a     character received, marked as %TTY_NORMAL
None         1       n/a     character received, marked as %TTY_NORMAL
Yes          1       0       character received, marked as %TTY_PARITY
Yes          1       1       character discarded
============ ======= ======= =========================================
```

Other flags may be used (eg, xon/xoff characters) if your hardware
supports hardware "soft" flow control.

Locking: caller holds tty_port->mutex
Interrupts: caller dependent.
This call must not sleep

Notifier for discipline change. See
Documentation/driver-api/tty/tty_ldisc.rst.

Locking: caller holds tty_port->mutex

Perform any power management related activities on the specified **port**.
**state** indicates the new state (defined by enum uart_pm_state),
**oldstate** indicates the previous state.

This function should not be used to grab any resources.

This will be called when the **port** is initially opened and finally
closed, except when the **port** is also the system console. This will
occur even if `CONFIG_PM` is not set.

Locking: none.
Interrupts: caller dependent.

Return a pointer to a string constant describing the specified **port**,
or return `NULL`, in which case the string 'unknown' is substituted.

Locking: none.
Interrupts: caller dependent.

Release any memory and IO region resources currently in use by the
**port**.

Locking: none.
Interrupts: caller dependent.

Request any memory and IO region resources required by the port. If any
fail, no resources should be registered when this function returns, and
it should return -`EBUSY` on failure.

Locking: none.
Interrupts: caller dependent.

Perform any autoconfiguration steps required for the **port**. **type**
contains a bit mask of the required configuration. `UART_CONFIG_TYPE`
indicates that the port requires detection and identification.
**port->type** should be set to the type found, or `PORT_UNKNOWN` if no
port was detected.

`UART_CONFIG_IRQ` indicates autoconfiguration of the interrupt signal,
which should be probed using standard kernel autoprobing techniques.
This is not necessary on platforms where ports have interrupts
internally hard wired (eg, system on a chip implementations).

Locking: none.
Interrupts: caller dependent.

Verify the new serial port information contained within **serinfo** is
suitable for this port type.

Locking: none.
Interrupts: caller dependent.

Perform any port specific IOCTLs. IOCTL commands must be defined using
the standard numbering system found in \<asm/ioctl.h>.

Locking: none.
Interrupts: caller dependent.

Called by kgdb to perform the minimal hardware initialization needed to
support **poll_put_char()** and **poll_get_char()**. Unlike **startup()**, this
should not request interrupts.

Locking: `tty_mutex` and tty_port->mutex taken.
Interrupts: n/a.

Called by kgdb to write a single character **ch** directly to the serial
**port**. It can and should block until there is space in the TX FIFO.

Locking: none.
Interrupts: caller dependent.
This call must not sleep

Called by kgdb to read a single character directly from the serial
port. If data is available, it should be returned; otherwise the
function should return `NO_POLL_CHAR` immediately.

Locking: none.
Interrupts: caller dependent.
This call must not sleep


<a id="rst-other-functions"></a>

## Other functions


#### <a id="c-uart_write_wakeup"></a>`uart_write_wakeup()`

```c
void uart_write_wakeup(struct uart_port *port)
```

schedule write processing

**Parameters**

- `struct uart_port *port`: port to be processed

**Description**

This routine is used by the interrupt handler to schedule processing in the
software interrupt portion of the driver. A driver is expected to call this
function when the number of characters in the transmit buffer have dropped
below a threshold.

Locking: **port->lock** should be held

#### <a id="c-uart_update_timeout"></a>`uart_update_timeout()`

```c
void uart_update_timeout(struct uart_port *port, unsigned int cflag, unsigned int baud)
```

update per-port frame timing information

**Parameters**

- `struct uart_port *port`: uart_port structure describing the port
- `unsigned int cflag`: termios cflag value
- `unsigned int baud`: speed of the port

**Description**

Set the **port** frame timing information from which the FIFO timeout value is
derived. The **cflag** value should reflect the actual hardware settings as
number of bits, parity, stop bits and baud rate is taken into account here.

Locking: caller is expected to take **port->lock**

#### <a id="c-uart_get_baud_rate"></a>`uart_get_baud_rate()`

```c
unsigned int uart_get_baud_rate(struct uart_port *port, struct ktermios *termios, const struct ktermios *old, unsigned int min, unsigned int max)
```

return baud rate for a particular port

**Parameters**

- `struct uart_port *port`: uart_port structure describing the port in question.
- `struct ktermios *termios`: desired termios settings
- `const struct ktermios *old`: old termios (or `NULL`)
- `unsigned int min`: minimum acceptable baud rate
- `unsigned int max`: maximum acceptable baud rate

**Description**

Decode the termios structure into a numeric baud rate, taking account of the
magic 38400 baud rate (with spd_* flags), and mapping the `B0` rate to 9600
baud.

If the new baud rate is invalid, try the **old** termios setting. If it's still
invalid, we try 9600 baud. If that is also invalid 0 is returned.

The **termios** structure is updated to reflect the baud rate we're actually
going to be using. Don't do this for the case where B0 is requested ("hang
up").

Locking: caller dependent

#### <a id="c-uart_get_divisor"></a>`uart_get_divisor()`

```c
unsigned int uart_get_divisor(struct uart_port *port, unsigned int baud)
```

return uart clock divisor

**Parameters**

- `struct uart_port *port`: uart_port structure describing the port
- `unsigned int baud`: desired baud rate

**Description**

Calculate the divisor (baud_base / baud) for the specified **baud**,
appropriately rounded.

If 38400 baud and custom divisor is selected, return the custom divisor
instead.

Locking: caller dependent

#### <a id="c-uart_get_lsr_info"></a>`uart_get_lsr_info()`

```c
int uart_get_lsr_info(struct tty_struct *tty, struct uart_state *state, unsigned int __user *value)
```

get line status register info

**Parameters**

- `struct tty_struct *tty`: tty associated with the UART
- `struct uart_state *state`: UART being queried
- `unsigned int __user *value`: returned modem value

#### <a id="c-uart_console_write"></a>`uart_console_write()`

```c
void uart_console_write(struct uart_port *port, const char *s, unsigned int count, void (*putchar)(struct uart_port *, unsigned char))
```

write a console message to a serial port

**Parameters**

- `struct uart_port *port`: the port to write the message
- `const char *s`: array of characters
- `unsigned int count`: number of characters in string to write
- `void (*putchar)(struct uart_port *, unsigned char)`: function to write character to port

#### <a id="c-uart_parse_earlycon"></a>`uart_parse_earlycon()`

```c
int uart_parse_earlycon(char *p, enum uart_iotype *iotype, resource_size_t *addr, char **options)
```

Parse earlycon options

**Parameters**

- `char *p`: ptr to 2nd field (ie., just beyond '\<name>,')
- `enum uart_iotype *iotype`: ptr for decoded iotype (out)
- `resource_size_t *addr`: ptr for decoded mapbase/iobase (out)
- `char **options`: ptr for \<options> field; `NULL` if not present (out)

**Description**

- Decodes earlycon kernel command line parameters of the form:
  * earlycon=\<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,\<addr>,\<options>
  * console=\<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,\<addr>,\<options>

- The optional form:
  * earlycon=\<name>,0x\<addr>,\<options>
  * console=\<name>,0x\<addr>,\<options>

is also accepted; the returned **iotype** will be `UPIO_MEM`.

**Return**

0 on success or -`EINVAL` on failure

#### <a id="c-uart_parse_options"></a>`uart_parse_options()`

```c
void uart_parse_options(const char *options, int *baud, int *parity, int *bits, int *flow)
```

Parse serial port baud/parity/bits/flow control.

**Parameters**

- `const char *options`: pointer to option string
- `int *baud`: pointer to an 'int' variable for the baud rate.
- `int *parity`: pointer to an 'int' variable for the parity.
- `int *bits`: pointer to an 'int' variable for the number of data bits.
- `int *flow`: pointer to an 'int' variable for the flow control character.

**Description**

[`uart_parse_options()`](#c-uart_parse_options) decodes a string containing the serial console
options. The format of the string is \<baud>\<parity>\<bits>\<flow>,
eg: 115200n8r

#### <a id="c-uart_set_options"></a>`uart_set_options()`

```c
int uart_set_options(struct uart_port *port, struct console *co, int baud, int parity, int bits, int flow)
```

setup the serial console parameters

**Parameters**

- `struct uart_port *port`: pointer to the serial ports uart_port structure
- `struct console *co`: console pointer
- `int baud`: baud rate
- `int parity`: parity character - 'n' (none), 'o' (odd), 'e' (even)
- `int bits`: number of data bits
- `int flow`: flow control character - 'r' (rts)

**Description**

Locking: Caller must hold console_list_lock in order to serialize
early initialization of the serial-console lock.

#### <a id="c-uart_register_driver"></a>`uart_register_driver()`

```c
int uart_register_driver(struct uart_driver *drv)
```

register a driver with the uart core layer

**Parameters**

- `struct uart_driver *drv`: low level driver structure

**Description**

Register a uart driver with the core driver. We in turn register with the
tty layer, and initialise the core driver per-port state.

We have a proc file in /proc/tty/driver which is named after the normal
driver.

**drv->port** should be `NULL`, and the per-port structures should be registered
using `uart_add_one_port()` after this call has succeeded.

Locking: none, Interrupts: enabled

#### <a id="c-uart_unregister_driver"></a>`uart_unregister_driver()`

```c
void uart_unregister_driver(struct uart_driver *drv)
```

remove a driver from the uart core layer

**Parameters**

- `struct uart_driver *drv`: low level driver structure

**Description**

Remove all references to a driver from the core driver. The low level
driver must have removed all its ports via the `uart_remove_one_port()` if it
registered them with `uart_add_one_port()`. (I.e. **drv->port** is `NULL`.)

Locking: none, Interrupts: enabled

#### <a id="c-uart_match_port"></a>`uart_match_port()`

```c
bool uart_match_port(const struct uart_port *port1, const struct uart_port *port2)
```

are the two ports equivalent?

**Parameters**

- `const struct uart_port *port1`: first port
- `const struct uart_port *port2`: second port

**Description**

This utility function can be used to determine whether two uart_port
structures describe the same port.

#### <a id="c-uart_handle_dcd_change"></a>`uart_handle_dcd_change()`

```c
void uart_handle_dcd_change(struct uart_port *uport, bool active)
```

handle a change of carrier detect state

**Parameters**

- `struct uart_port *uport`: uart_port structure for the open port
- `bool active`: new carrier detect status

**Description**

Caller must hold uport->lock.

#### <a id="c-uart_handle_cts_change"></a>`uart_handle_cts_change()`

```c
void uart_handle_cts_change(struct uart_port *uport, bool active)
```

handle a change of clear-to-send state

**Parameters**

- `struct uart_port *uport`: uart_port structure for the open port
- `bool active`: new clear-to-send status

**Description**

Caller must hold uport->lock.

#### <a id="c-uart_try_toggle_sysrq"></a>`uart_try_toggle_sysrq()`

```c
bool uart_try_toggle_sysrq(struct uart_port *port, u8 ch)
```

Enables SysRq from serial line

**Parameters**

- `struct uart_port *port`: uart_port structure where char(s) after BREAK met
- `u8 ch`: new character in the sequence after received BREAK

**Description**

Enables magic SysRq when the required sequence is met on port
(see CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE).

**Return**

`false` if **ch** is out of enabling sequence and should be
handled some other way, `true` if **ch** was consumed.



#### <a id="c-uart_port_tx_limited"></a>`uart_port_tx_limited()`

```c
uart_port_tx_limited(port, ch, count, tx_ready, put_char, tx_done)
```

- transmit helper for uart_port with count limiting

**Parameters**

- `port`: uart port
- `ch`: variable to store a character to be written to the HW
- `count`: a limit of characters to send
- `tx_ready`: can HW accept more data function
- `put_char`: function to write a character
- `tx_done`: function to call after the loop is done

**Description**

This helper transmits characters from the xmit buffer to the hardware using
**put_char()**. It does so until **count** characters are sent and while **tx_ready**
evaluates to true.

- The expression in macro parameters shall be designed as follows:
  * **tx_ready:** should evaluate to true if the HW can accept more data to
    be sent. This parameter can be `true`, which means the HW is always ready.
  * **put_char:** shall write **ch** to the device of **port**.
  * **tx_done:** when the write loop is done, this can perform arbitrary
    action before potential invocation of ops->`stop_tx()` happens. If the
    driver does not need to do anything, use e.g. ({}).

For all of them, **port->lock** is held, interrupts are locally disabled and
the expressions must not sleep.

**Return**

the number of characters in the xmit buffer when done.

#### <a id="c-uart_port_tx"></a>`uart_port_tx()`

```c
uart_port_tx(port, ch, tx_ready, put_char)
```

- transmit helper for uart_port

**Parameters**

- `port`: uart port
- `ch`: variable to store a character to be written to the HW
- `tx_ready`: can HW accept more data function
- `put_char`: function to write a character

**Description**

See [`uart_port_tx_limited()`](#c-uart_port_tx_limited) for more details.


<a id="rst-other-notes"></a>

## Other notes

It is intended some day to drop the 'unused' entries from uart_port, and allow low level drivers to register their own individual uart_port's with the core.  This will allow drivers to use uart_port as a pointer to a structure containing both the uart_port entry with their own extensions, thus:



```text
struct my_port {
        struct uart_port        port;
        int                     my_stuff;
};
```

<a id="rst-modem-control-lines-via-gpio"></a>

## Modem control lines via GPIO

Some helpers are provided in order to set/get modem control lines via GPIO.


#### <a id="c-mctrl_gpio_set"></a>`mctrl_gpio_set()`

```c
void mctrl_gpio_set(struct mctrl_gpios *gpios, unsigned int mctrl)
```

set gpios according to mctrl state

**Parameters**

- `struct mctrl_gpios *gpios`: gpios to set
- `unsigned int mctrl`: state to set

**Description**

Set the gpios according to the mctrl state.

#### <a id="c-mctrl_gpio_to_gpiod"></a>`mctrl_gpio_to_gpiod()`

```c
struct gpio_desc * mctrl_gpio_to_gpiod(struct mctrl_gpios *gpios, enum mctrl_gpio_idx gidx)
```

obtain gpio_desc of modem line index

**Parameters**

- `struct mctrl_gpios *gpios`: gpios to look into
- `enum mctrl_gpio_idx gidx`: index of the modem line

**Return**

the gpio_desc structure associated to the modem line index

#### <a id="c-mctrl_gpio_get"></a>`mctrl_gpio_get()`

```c
unsigned int mctrl_gpio_get(struct mctrl_gpios *gpios, unsigned int *mctrl)
```

update mctrl with the gpios values.

**Parameters**

- `struct mctrl_gpios *gpios`: gpios to get the info from
- `unsigned int *mctrl`: mctrl to set

**Return**

modified mctrl (the same value as in **mctrl**)

**Description**

Update mctrl with the gpios values.

#### <a id="c-mctrl_gpio_init"></a>`mctrl_gpio_init()`

```c
struct mctrl_gpios * mctrl_gpio_init(struct uart_port *port, unsigned int idx)
```

initialize uart gpios

**Parameters**

- `struct uart_port *port`: port to initialize gpios for
- `unsigned int idx`: index of the gpio in the **port**'s device

**Description**

This will get the {cts,rts,...}-gpios from device tree if they are present
and request them, set direction etc, and return an allocated structure.
`devm_*` functions are used, so there's no need to explicitly free.
As this sets up the irq handling, make sure to not handle changes to the
gpio input lines in your driver, too.

#### <a id="c-mctrl_gpio_enable_ms"></a>`mctrl_gpio_enable_ms()`

```c
void mctrl_gpio_enable_ms(struct mctrl_gpios *gpios)
```

enable irqs and handling of changes to the ms lines

**Parameters**

- `struct mctrl_gpios *gpios`: gpios to enable

#### <a id="c-mctrl_gpio_disable_ms_sync"></a>`mctrl_gpio_disable_ms_sync()`

```c
void mctrl_gpio_disable_ms_sync(struct mctrl_gpios *gpios)
```

disable irqs and handling of changes to the ms lines, and wait for any pending IRQ to be processed

**Parameters**

- `struct mctrl_gpios *gpios`: gpios to disable

#### <a id="c-mctrl_gpio_disable_ms_no_sync"></a>`mctrl_gpio_disable_ms_no_sync()`

```c
void mctrl_gpio_disable_ms_no_sync(struct mctrl_gpios *gpios)
```

disable irqs and handling of changes to the ms lines, and return immediately

**Parameters**

- `struct mctrl_gpios *gpios`: gpios to disable

---

# ISO7816 Serial Communications

_Peios Kernel / Hardware and drivers / Driver development / Serial ports_

> ISO/IEC7816 is a series of standards specifying integrated circuit cards (ICC) also known as smart cards.

<a id="rst-iso7816-serial-communications"></a>

<a id="rst-introduction"></a>

## 1. Introduction

> ISO/IEC7816 is a series of standards specifying integrated circuit cards (ICC) also known as smart cards.

<a id="rst-hardware-related-considerations"></a>

## 2. Hardware-related considerations

> Some CPUs/UARTs (e.g., Microchip AT91) contain a built-in mode capable of handling communication with a smart card.
>
> For these microcontrollers, the Linux driver should be made capable of working in both modes, and proper ioctls (see later) should be made available at user-level to allow switching from one mode to the other, and vice versa.

<a id="rst-data-structures-already-available-in-the-kernel"></a>

## 3. Data Structures Already Available in the Kernel

> The Linux kernel provides the serial_iso7816 structure (see \[1\]) to handle ISO7816 communications. This data structure is used to set and configure ISO7816 parameters in ioctls.
>
> Any driver for devices capable of working both as RS232 and ISO7816 should implement the iso7816_config callback in the uart_port structure. The serial_core calls iso7816_config to do the device specific part in response to TIOCGISO7816 and TIOCSISO7816 ioctls (see below). The iso7816_config callback receives a pointer to struct serial_iso7816.

<a id="rst-usage-from-user-level"></a>

## 4. Usage from user-level

> From user-level, ISO7816 configuration can be get/set using the previous ioctls. For instance, to set ISO7816 you can use the following code:
>
>
>
> ```text
> #include <linux/serial.h>
>
> /* Include definition for ISO7816 ioctls: TIOCSISO7816 and TIOCGISO7816 */
> #include <sys/ioctl.h>
>
> /* Open your specific device (e.g., /dev/mydevice): */
> int fd = open ("/dev/mydevice", O_RDWR);
> if (fd < 0) {
>         /* Error handling. See errno. */
> }
>
> struct serial_iso7816 iso7816conf;
>
> /* Reserved fields as to be zeroed */
> memset(&iso7816conf, 0, sizeof(iso7816conf));
>
> /* Enable ISO7816 mode: */
> iso7816conf.flags |= SER_ISO7816_ENABLED;
>
> /* Select the protocol: */
> /* T=0 */
> iso7816conf.flags |= SER_ISO7816_T(0);
> /* or T=1 */
> iso7816conf.flags |= SER_ISO7816_T(1);
>
> /* Set the guard time: */
> iso7816conf.tg = 2;
>
> /* Set the clock frequency*/
> iso7816conf.clk = 3571200;
>
> /* Set transmission factors: */
> iso7816conf.sc_fi = 372;
> iso7816conf.sc_di = 1;
>
> if (ioctl(fd_usart, TIOCSISO7816, &iso7816conf) < 0) {
>         /* Error handling. See errno. */
> }
>
> /* Use read() and write() syscalls here... */
>
> /* Close the device when finished: */
> if (close (fd) < 0) {
>         /* Error handling. See errno. */
> }
> ```

<a id="rst-references"></a>

## 5. References

> \[1\]    include/uapi/linux/serial.h

---

# RS485 Serial Communications

_Peios Kernel / Hardware and drivers / Driver development / Serial ports_

> EIA-485, also known as TIA/EIA-485 or RS-485, is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems. This standard is widely used for communications in industrial…

<a id="rst-rs485-serial-communications"></a>

<a id="rst-introduction"></a>

## 1. Introduction

> EIA-485, also known as TIA/EIA-485 or RS-485, is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems. This standard is widely used for communications in industrial automation because it can be used effectively over long distances and in electrically noisy environments.

<a id="rst-hardware-related-considerations"></a>

## 2. Hardware-related Considerations

> Some CPUs/UARTs (e.g., Atmel AT91 or 16C950 UART) contain a built-in half-duplex mode capable of automatically controlling line direction by toggling RTS or DTR signals. That can be used to control external half-duplex hardware like an RS485 transceiver or any RS232-connected half-duplex devices like some modems.
>
> For these microcontrollers, the Linux driver should be made capable of working in both modes, and proper ioctls (see later) should be made available at user-level to allow switching from one mode to the other, and vice versa.

<a id="rst-data-structures-already-available-in-the-kernel"></a>

## 3. Data Structures Already Available in the Kernel

> The Linux kernel provides the struct serial_rs485 to handle RS485 communications. This data structure is used to set and configure RS485 parameters in the platform data and in ioctls.
>
> The device tree can also provide RS485 boot time parameters <a id="rst-footnote-reference-1"></a>[1](#rst-dt-bindings). The serial core fills the struct serial_rs485 from the values given by the device tree when the driver calls uart_get_rs485_mode().
>
> Any driver for devices capable of working both as RS232 and RS485 should implement the `rs485_config` callback and provide `rs485_supported` in the `struct uart_port`. The serial core calls `rs485_config` to do the device specific part in response to TIOCSRS485 ioctl (see below). The `rs485_config` callback receives a pointer to a sanitizated struct serial_rs485. The struct serial_rs485 userspace provides is sanitized before calling `rs485_config` using `rs485_supported` that indicates what RS485 features the driver supports for the `struct uart_port`. TIOCGRS485 ioctl can be used to read back the struct serial_rs485 matching to the current configuration.


#### <a id="c-struct-serial_rs485"></a>`struct serial_rs485`

serial interface for controlling RS485 settings.

**Definition**

```c
struct serial_rs485 {
        __u32 flags;
    #define SER_RS485_ENABLED               _BITUL(0);
    #define SER_RS485_RTS_ON_SEND           _BITUL(1);
    #define SER_RS485_RTS_AFTER_SEND        _BITUL(2);
    #define SER_RS485_RX_DURING_TX          _BITUL(4);
    #define SER_RS485_TERMINATE_BUS         _BITUL(5);
    #define SER_RS485_ADDRB                 _BITUL(6);
    #define SER_RS485_ADDR_RECV             _BITUL(7);
    #define SER_RS485_ADDR_DEST             _BITUL(8);
    #define SER_RS485_MODE_RS422            _BITUL(9);
        __u32 delay_rts_before_send;
        __u32 delay_rts_after_send;
        union {
            __u32 padding[5];
            struct {
                __u8 addr_recv;
                __u8 addr_dest;
                __u8 padding0[2];
                __u32 padding1[4];
            };
        };
};
```

**Members**

- `flags`: RS485 feature flags.
- `delay_rts_before_send`: Delay before send (milliseconds).
- `delay_rts_after_send`: Delay after send (milliseconds).
- `{unnamed_union}`: anonymous
- `padding`: Deprecated, use **padding0** and **padding1** instead.
  Do not use with **addr_recv** and **addr_dest** (due to
  overlap).
- `{unnamed_struct}`: anonymous
- `addr_recv`: Receive filter for RS485 addressing mode
  (used only when `SER_RS485_ADDR_RECV` is set).
- `addr_dest`: Destination address for RS485 addressing mode
  (used only when `SER_RS485_ADDR_DEST` is set).
- `padding0`: Padding (set to zero).
- `padding1`: Padding (set to zero).

**Description**

Serial interface for controlling RS485 settings on chips with suitable
support. Set with TIOCSRS485 and get with TIOCGRS485 if supported by your
platform. The set function returns the new state, with any unsupported bits
reverted appropriately.

The flag bits are:

* `SER_RS485_ENABLED`         - RS485 enabled.
* `SER_RS485_RTS_ON_SEND`     - Logical level for RTS pin when sending.
* `SER_RS485_RTS_AFTER_SEND`  - Logical level for RTS pin after sent.
* `SER_RS485_RX_DURING_TX`    - Full-duplex RS485 line.
* `SER_RS485_TERMINATE_BUS`   - Enable bus termination (if supported).
* `SER_RS485_ADDRB`           - Enable RS485 addressing mode.
* `SER_RS485_ADDR_RECV` - Receive address filter (enables **addr_recv**). Requires `SER_RS485_ADDRB`.
* `SER_RS485_ADDR_DEST` - Destination address (enables **addr_dest**). Requires `SER_RS485_ADDRB`.
* `SER_RS485_MODE_RS422`      - Enable RS422. Requires `SER_RS485_ENABLED`.


<a id="rst-usage-from-user-level"></a>

## 4. Usage from user-level

> From user-level, RS485 configuration can be get/set using the previous ioctls. For instance, to set RS485 you can use the following code:
>
>
>
> ```text
> #include <linux/serial.h>
>
> /* Include definition for RS485 ioctls: TIOCGRS485 and TIOCSRS485 */
> #include <sys/ioctl.h>
>
> /* Open your specific device (e.g., /dev/mydevice): */
> int fd = open ("/dev/mydevice", O_RDWR);
> if (fd < 0) {
>         /* Error handling. See errno. */
> }
>
> struct serial_rs485 rs485conf;
>
> /* Enable RS485 mode: */
> rs485conf.flags |= SER_RS485_ENABLED;
>
> /* Set logical level for RTS pin equal to 1 when sending: */
> rs485conf.flags |= SER_RS485_RTS_ON_SEND;
> /* or, set logical level for RTS pin equal to 0 when sending: */
> rs485conf.flags &= ~(SER_RS485_RTS_ON_SEND);
>
> /* Set logical level for RTS pin equal to 1 after sending: */
> rs485conf.flags |= SER_RS485_RTS_AFTER_SEND;
> /* or, set logical level for RTS pin equal to 0 after sending: */
> rs485conf.flags &= ~(SER_RS485_RTS_AFTER_SEND);
>
> /* Set rts delay before send, if needed: */
> rs485conf.delay_rts_before_send = ...;
>
> /* Set rts delay after send, if needed: */
> rs485conf.delay_rts_after_send = ...;
>
> /* Set this flag if you want to receive data even while sending data */
> rs485conf.flags |= SER_RS485_RX_DURING_TX;
>
> if (ioctl (fd, TIOCSRS485, &rs485conf) < 0) {
>         /* Error handling. See errno. */
> }
>
> /* Use read() and write() syscalls here... */
>
> /* Close the device when finished: */
> if (close (fd) < 0) {
>         /* Error handling. See errno. */
> }
> ```

<a id="rst-multipoint-addressing"></a>

## 5. Multipoint Addressing

> The Linux kernel provides addressing mode for multipoint RS-485 serial communications line. The addressing mode is enabled with `SER_RS485_ADDRB` flag in struct serial_rs485. The struct serial_rs485 has two additional flags and fields for enabling receive and destination addresses.
>
> - **Address mode flags:**
>
>   - `SER_RS485_ADDRB`: Enabled addressing mode (sets also ADDRB in termios).
>
>   - `SER_RS485_ADDR_RECV`: Receive (filter) address enabled.
>
>   - `SER_RS485_ADDR_DEST`: Set destination address.
>
> - **Address fields (enabled with corresponding `SER_RS485_ADDR_*` flag):**
>
>   - `addr_recv`: Receive address.
>
>   - `addr_dest`: Destination address.
>
> Once a receive address is set, the communication can occur only with the particular device and other peers are filtered out. It is left up to the receiver side to enforce the filtering. Receive address will be cleared if `SER_RS485_ADDR_RECV` is not set.
>
> Note: not all devices supporting RS485 support multipoint addressing.

<a id="rst-references"></a>

## 6. References

<a id="rst-dt-bindings"></a>



**[1]** [Documentation/devicetree/bindings/serial/rs485.txt](/kernel/hardware/devicetree/bindings-serial/rs485.md)

---

# TTY

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Teletypewriter (TTY) layer takes care of all those serial devices. Including the virtual ones like pseudoterminal (PTY).

<a id="rst-tty"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Teletypewriter (TTY) layer takes care of all those serial devices. Including the virtual ones like pseudoterminal (PTY).

<a id="rst-tty-structures"></a>

## TTY structures

There are several major TTY structures. Every TTY device in a system has a corresponding struct tty_port. These devices are maintained by a TTY driver which is struct tty_driver. This structure describes the driver but also contains a reference to operations which could be performed on the TTYs. It is struct tty_operations. Then, upon open, a struct tty_struct is allocated and lives until the final close. During this time, several callbacks from struct tty_operations are invoked by the TTY layer.

Every character received by the kernel (both from devices and users) is passed through a preselected [TTY Line Discipline](</kernel/hardware/driver-api/tty/tty-ldisc.md>) (in short ldisc; in C, struct tty_ldisc_ops). Its task is to transform characters as defined by a particular ldisc or by user too. The default one is n_tty, implementing echoes, signal handling, jobs control, special characters processing, and more. The transformed characters are passed further to user/device, depending on the source.

In-detail description of the named TTY structures is in separate documents:

- [TTY Driver and TTY Operations](</kernel/hardware/driver-api/tty/tty-driver.md>)
- [TTY Port](</kernel/hardware/driver-api/tty/tty-port.md>)
- [TTY Struct](</kernel/hardware/driver-api/tty/tty-struct.md>)
- [TTY Line Discipline](</kernel/hardware/driver-api/tty/tty-ldisc.md>)
- [TTY Buffer](</kernel/hardware/driver-api/tty/tty-buffer.md>)
- [TTY IOCTL Helpers](</kernel/hardware/driver-api/tty/tty-ioctl.md>)
- [TTY Internals](</kernel/hardware/driver-api/tty/tty-internals.md>)
- [Console](</kernel/hardware/driver-api/tty/console.md>)

<a id="rst-writing-tty-driver"></a>

## Writing TTY Driver

Before one starts writing a TTY driver, they must consider [Serial](</kernel/hardware/driver-api/serial/driver.md>) and [USB Serial](</kernel/hardware/usb/usb-serial.md>) layers first. Drivers for serial devices can often use one of these specific layers to implement a serial driver. Only special devices should be handled directly by the TTY Layer. If you are about to write such a driver, read on.

A *typical* sequence a TTY driver performs is as follows:

1. Allocate and register a TTY driver (module init)

2. Create and register TTY devices as they are probed (probe function)

3. Handle TTY operations and events like interrupts (TTY core invokes the former, the device the latter)

4. Remove devices as they are going away (remove function)

5. Unregister and free the TTY driver (module exit)

Steps regarding driver, i.e. 1., 3., and 5. are described in detail in [TTY Driver and TTY Operations](</kernel/hardware/driver-api/tty/tty-driver.md>). For the other two (devices handling), look into [TTY Port](</kernel/hardware/driver-api/tty/tty-port.md>).

<a id="rst-other-documentation"></a>

## Other Documentation

Miscellaneous documentation can be further found in these documents:

- [MOXA Smartio/Industio Family Device Driver Installation Guide](</kernel/hardware/driver-api/tty/moxa-smartio.md>)
- [GSM 0710 tty multiplexor HOWTO](</kernel/hardware/driver-api/tty/n-gsm.md>)
- [N_TTY](</kernel/hardware/driver-api/tty/n-tty.md>)

---

# Console

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Struct Console

<a id="rst-console"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



<a id="rst-struct-console"></a>

## Struct Console


#### <a id="c-enum-cons_flags"></a>`enum cons_flags`

General console flags

**Constants**

- `CON_PRINTBUFFER`: Used by newly registered consoles to avoid duplicate
  output of messages that were already shown by boot
  consoles or read by userspace via `syslog()` syscall.
- `CON_CONSDEV`: Indicates that the console driver is backing
  /dev/console.
- `CON_ENABLED`: Indicates if a console is allowed to print records. If
  false, the console also will not advance to later
  records.
- `CON_BOOT`: Marks the console driver as early console driver which
  is used during boot before the real driver becomes
  available. It will be automatically unregistered
  when the real console driver is registered unless
  "keep_bootcon" parameter is used.
- `CON_ANYTIME`: A misnomed historical flag which tells the core code
  that the legacy **console**::write callback can be invoked
  on a CPU which is marked OFFLINE. That is misleading as
  it suggests that there is no contextual limit for
  invoking the callback. The original motivation was
  readiness of the per-CPU areas.
- `CON_BRL`: Indicates a braille device which is exempt from
  receiving the printk spam for obvious reasons.
- `CON_EXTENDED`: The console supports the extended output format of
  /dev/kmesg which requires a larger output buffer.
- `CON_SUSPENDED`: Indicates if a console is suspended. If true, the
  printing callbacks must not be called.
- `CON_NBCON`: Console can operate outside of the legacy style console_lock
  constraints.
- `CON_NBCON_ATOMIC_UNSAFE`: The `write_atomic()` callback is not safe and is
  therefore only used by `nbcon_atomic_flush_unsafe()`.

#### <a id="c-struct-console"></a>`struct console`

The console descriptor structure

**Definition**

```c
struct console {
    char name[16];
    void (*write)(struct console *co, const char *s, unsigned int count);
    int (*read)(struct console *co, char *s, unsigned int count);
    struct tty_driver       *(*device)(struct console *co, int *index);
    void (*unblank)(void);
    int (*setup)(struct console *co, char *options);
    int (*exit)(struct console *co);
    int (*match)(struct console *co, char *name, int idx, char *options);
    short flags;
    short index;
    int cflag;
    uint ispeed;
    uint ospeed;
    u64 seq;
    unsigned long           dropped;
    void *data;
    struct hlist_node       node;
    void (*write_atomic)(struct console *con, struct nbcon_write_context *wctxt);
    void (*write_thread)(struct console *con, struct nbcon_write_context *wctxt);
    void (*device_lock)(struct console *con, unsigned long *flags);
    void (*device_unlock)(struct console *con, unsigned long flags);
    atomic_t nbcon_state;
    atomic_long_t nbcon_seq;
    struct nbcon_context  nbcon_device_ctxt;
    atomic_long_t nbcon_prev_seq;
    struct printk_buffers   *pbufs;
    struct task_struct      *kthread;
    struct rcuwait          rcuwait;
    struct irq_work         irq_work;
};
```

**Members**

- `name`: The name of the console driver
- `write`: Legacy write callback to output messages (Optional)
- `read`: Read callback for console input (Optional)
- `device`: The underlying TTY device driver (Optional)
- `unblank`: Callback to unblank the console (Optional)
- `setup`: Callback for initializing the console (Optional)
- `exit`: Callback for teardown of the console (Optional)
- `match`: Callback for matching a console (Optional)
- `flags`: Console flags. See enum cons_flags
- `index`: Console index, e.g. port number
- `cflag`: TTY control mode flags
- `ispeed`: TTY input speed
- `ospeed`: TTY output speed
- `seq`: Sequence number of the next ringbuffer record to print
- `dropped`: Number of unreported dropped ringbuffer records
- `data`: Driver private data
- `node`: hlist node for the console list
- `write_atomic`: NBCON callback to write out text in any context. (Optional)

  This callback is called with the console already acquired. However,
  a higher priority context is allowed to take it over by default.

  The callback must call `nbcon_enter_unsafe()` and `nbcon_exit_unsafe()`
  around any code where the takeover is not safe, for example, when
  manipulating the serial port registers.

  `nbcon_enter_unsafe()` will fail if the context has lost the console
  ownership in the meantime. In this case, the callback is no longer
  allowed to go forward. It must back out immediately and carefully.
  The buffer content is also no longer trusted since it no longer
  belongs to the context.

  The callback should allow the takeover whenever it is safe. It
  increases the chance to see messages when the system is in trouble.
  If the driver must reacquire ownership in order to finalize or
  revert hardware changes, `nbcon_reacquire_nobuf()` can be used.
  However, on reacquire the buffer content is no longer available. A
  reacquire cannot be used to resume printing.

  The callback can be called from any context (including NMI).
  Therefore it must avoid usage of any locking and instead rely
  on the console ownership for synchronization.
- `write_thread`: NBCON callback to write out text in task context.

  This callback must be called only in task context with both
  `device_lock()` and the nbcon console acquired with
  NBCON_PRIO_NORMAL.

  The same rules for console ownership verification and unsafe
  sections handling applies as with `write_atomic()`.

  The console ownership handling is necessary for synchronization
  against `write_atomic()` which is synchronized only via the context.

  The `device_lock()` provides the primary serialization for operations
  on the device. It might be as relaxed (mutex)\[*\] or as tight
  (disabled preemption and interrupts) as needed. It allows
  the kthread to operate in the least restrictive mode\[**\].

  - \[*\] Standalone `nbcon_context_try_acquire()` is not safe with

    the preemption enabled, see `nbcon_owner_matches()`. But it
    can be safe when always called in the preemptive context
    under the `device_lock()`.

  - \[**\] The `device_lock()` makes sure that `nbcon_context_try_acquire()`

    would never need to spin which is important especially with
    PREEMPT_RT.
- `device_lock`: NBCON callback to begin synchronization with driver code.

  Console drivers typically must deal with access to the hardware
  via user input/output (such as an interactive login shell) and
  output of kernel messages via [`printk()`](/kernel/internals/core-api/printk-basics.md#c-printk) calls. This callback is
  called by the printk-subsystem whenever it needs to synchronize
  with hardware access by the driver. It should be implemented to
  use whatever synchronization mechanism the driver is using for
  itself (for example, the port lock for uart serial consoles).

  The callback is always called from task context. It may use any
  synchronization method required by the driver.

  - IMPORTANT: The callback MUST disable migration. The console driver

    may be using a synchronization mechanism that already takes
    care of this (such as spinlocks). Otherwise this function must
    explicitly call `migrate_disable()`.

  The flags argument is provided as a convenience to the driver. It
  will be passed again to `device_unlock()`. It can be ignored if the
  driver does not need it.
- `device_unlock`: NBCON callback to finish synchronization with driver code.

  It is the counterpart to `device_lock()`.

  This callback is always called from task context. It must
  appropriately re-enable migration (depending on how `device_lock()`
  disabled migration).

  The flags argument is the value of the same variable that was
  passed to `device_lock()`.
- `nbcon_state`: State for nbcon consoles
- `nbcon_seq`: Sequence number of the next record for nbcon to print
- `nbcon_device_ctxt`: Context available for non-printing operations
- `nbcon_prev_seq`: Seq num the previous nbcon owner was assigned to print
- `pbufs`: Pointer to nbcon private buffer
- `kthread`: Printer kthread for this console
- `rcuwait`: RCU-safe wait object for **kthread** waking
- `irq_work`: Defer **kthread** waking to IRQ work context


<a id="rst-internals"></a>

### Internals


#### <a id="c-struct-nbcon_state"></a>`struct nbcon_state`

console state for nbcon consoles

**Definition**

```c
struct nbcon_state {
    union {
        unsigned int    atom;
        struct {
            unsigned int prio               :  2;
            unsigned int req_prio           :  2;
            unsigned int unsafe             :  1;
            unsigned int unsafe_takeover    :  1;
            unsigned int cpu                : 24;
        };
    };
};
```

**Members**

- `{unnamed_union}`: anonymous
- `atom`: Compound of the state fields for atomic operations
- `{unnamed_struct}`: anonymous
- `prio`: The priority of the current owner
- `req_prio`: The priority of a handover request
- `unsafe`: Console is busy in a non takeover region
- `unsafe_takeover`: A hostile takeover in an unsafe state happened in the
  past. The console cannot be safe until re-initialized.
- `cpu`: The CPU on which the owner runs

**Description**

To be used for reading and preparing of the value stored in the nbcon
state variable **console**::nbcon_state.

The **prio** and **req_prio** fields are particularly important to allow
spin-waiting to timeout and give up without the risk of a waiter being
assigned the lock after giving up.

#### <a id="c-enum-nbcon_prio"></a>`enum nbcon_prio`

console owner priority for nbcon consoles

**Constants**

- `NBCON_PRIO_NONE`: Unused
- `NBCON_PRIO_NORMAL`: Normal (non-emergency) usage
- `NBCON_PRIO_EMERGENCY`: Emergency output (WARN/OOPS...)
- `NBCON_PRIO_PANIC`: Panic output
- `NBCON_PRIO_MAX`: The number of priority levels

**Description**

A higher priority context can takeover the console when it is
in the safe state. The final attempt to flush consoles in `panic()`
can be allowed to do so even in an unsafe state (Hope and pray).

#### <a id="c-struct-nbcon_context"></a>`struct nbcon_context`

Context for console acquire/release

**Definition**

```c
struct nbcon_context {
    struct console          *console;
    unsigned int            spinwait_max_us;
    enum nbcon_prio         prio;
    unsigned int            allow_unsafe_takeover   : 1;
    unsigned int            backlog                 : 1;
    struct printk_buffers   *pbufs;
    u64 seq;
};
```

**Members**

- `console`: The associated console
- `spinwait_max_us`: Limit for spin-wait acquire
- `prio`: Priority of the context
- `allow_unsafe_takeover`: Allow performing takeover even if unsafe. Can
  be used only with NBCON_PRIO_PANIC **prio**. It
  might cause a system freeze when the console
  is used later.
- `backlog`: Ringbuffer has pending records
- `pbufs`: Pointer to the text buffer for this context
- `seq`: The sequence number to print for this context

#### <a id="c-struct-nbcon_write_context"></a>`struct nbcon_write_context`

Context handed to the nbcon write callbacks

**Definition**

```c
struct nbcon_write_context {
        struct nbcon_context  ctxt;
        char *outbuf;
        unsigned int            len;
        bool unsafe_takeover;
    #ifdef CONFIG_PRINTK_EXECUTION_CTX;
        int cpu;
        pid_t pid;
        char comm[TASK_COMM_LEN];
    #endif;
};
```

**Members**

- `ctxt`: The core console context
- `outbuf`: Pointer to the text buffer for output
- `len`: Length to write
- `unsafe_takeover`: If a hostile takeover in an unsafe state has occurred
- `cpu`: CPU on which the message was generated
- `pid`: PID of the task that generated the message
- `comm`: Name of the task that generated the message


<a id="rst-struct-consw"></a>

## Struct Consw


#### <a id="c-struct-consw"></a>`struct consw`

callbacks for consoles

**Definition**

```c
struct consw {
    struct module *owner;
    const char *(*con_startup)(void);
    void (*con_init)(struct vc_data *vc, bool init);
    void (*con_deinit)(struct vc_data *vc);
    void (*con_clear)(struct vc_data *vc, unsigned int y, unsigned int x, unsigned int count);
    void (*con_putc)(struct vc_data *vc, u16 ca, unsigned int y, unsigned int x);
    void (*con_putcs)(struct vc_data *vc, const u16 *s, unsigned int count, unsigned int ypos, unsigned int xpos);
    void (*con_cursor)(struct vc_data *vc, bool enable);
    bool (*con_scroll)(struct vc_data *vc, unsigned int top, unsigned int bottom, enum con_scroll dir, unsigned int lines);
    bool (*con_switch)(struct vc_data *vc);
    bool (*con_blank)(struct vc_data *vc, enum vesa_blank_mode blank, bool mode_switch);
    int (*con_font_set)(struct vc_data *vc, const struct console_font *font, unsigned int vpitch, unsigned int flags);
    int (*con_font_get)(struct vc_data *vc, struct console_font *font, unsigned int vpitch);
    int (*con_font_default)(struct vc_data *vc, struct console_font *font, const char *name);
    int (*con_resize)(struct vc_data *vc, unsigned int width, unsigned int height, bool from_user);
    void (*con_set_palette)(struct vc_data *vc, const unsigned char *table);
    void (*con_scrolldelta)(struct vc_data *vc, int lines);
    bool (*con_set_origin)(struct vc_data *vc);
    void (*con_save_screen)(struct vc_data *vc);
    u8 (*con_build_attr)(struct vc_data *vc, u8 color, enum vc_intensity intensity, bool blink, bool underline, bool reverse, bool italic);
    void (*con_invert_region)(struct vc_data *vc, u16 *p, int count);
};
```

**Members**

- `owner`: the module to get references of when this console is used
- `con_startup`: set up the console and return its name (like VGA, EGA, ...)
- `con_init`: initialize the console on **vc**. **init** is true for the very first
  call on this **vc**.
- `con_deinit`: deinitialize the console from **vc**.
- `con_clear`: erase **count** characters at \[**x**, **y**\] on **vc**. **count** >= 1.
- `con_putc`: emit one character with attributes **ca** to \[**x**, **y**\] on **vc**.
  (optional -- **con_putcs** would be called instead)
- `con_putcs`: emit **count** characters with attributes **s** to \[**x**, **y**\] on **vc**.
- `con_cursor`: enable/disable cursor depending on **enable**
- `con_scroll`: move lines from **top** to **bottom** in direction **dir** by **lines**.
  Return true if no generic handling should be done.
  Invoked by csi_M and printing to the console.
- `con_switch`: notifier about the console switch; it is supposed to return
  true if a redraw is needed.
- `con_blank`: blank/unblank the console. The target mode is passed in **blank**.
  **mode_switch** is set if changing from/to text/graphics. The hook
  is supposed to return true if a redraw is needed.
- `con_font_set`: set console **vc** font to **font** with height **vpitch**. **flags** can
  be `KD_FONT_FLAG_DONT_RECALC`. (optional)
- `con_font_get`: fetch the current font on **vc** of height **vpitch** into **font**.
  (optional)
- `con_font_default`: set default font on **vc**. **name** can be `NULL` or font name
  to search for. **font** can be filled back. (optional)
- `con_resize`: resize the **vc** console to **width** x **height**. **from_user** is true
  when this change comes from the user space.
- `con_set_palette`: sets the palette of the console **vc** to **table** (optional)
- `con_scrolldelta`: the contents of the console should be scrolled by **lines**.
  Invoked by user. (optional)
- `con_set_origin`: set origin (see `vc_data`::vc_origin) of the **vc**. If not
  provided or returns false, the origin is set to
  **vc->vc_screenbuf**. (optional)
- `con_save_screen`: save screen content into **vc->vc_screenbuf**. Called e.g.
  upon entering graphics. (optional)
- `con_build_attr`: build attributes based on **color**, **intensity** and other
  parameters. The result is used for both normal and erase
  characters. (optional)
- `con_invert_region`: invert a region of length **count** on **vc** starting at **p**.
  (optional)


<a id="rst-console-functions"></a>

## Console functions


#### <a id="c-console_srcu_read_flags"></a>`console_srcu_read_flags()`

```c
short console_srcu_read_flags(const struct console *con)
```

Locklessly read flags of a possibly registered console

**Parameters**

- `const struct console *con`: struct console pointer of console to read flags from

**Description**

Locklessly reading **con->flags** provides a consistent read value because
there is at most one CPU modifying **con->flags** and that CPU is using only
read-modify-write operations to do so.

Requires console_srcu_read_lock to be held, which implies that **con** might
be a registered console. The purpose of holding console_srcu_read_lock is
to guarantee that the console state is valid (CON_SUSPENDED/CON_ENABLED)
and that no exit/cleanup routines will run if the console is currently
undergoing unregistration.

If the caller is holding the console_list_lock or it is _certain_ that
**con** is not and will not become registered, the caller may read
**con->flags** directly instead.

**Context**

Any context.

**Return**

The current value of the **con->flags** field.

#### <a id="c-console_srcu_write_flags"></a>`console_srcu_write_flags()`

```c
void console_srcu_write_flags(struct console *con, short flags)
```

Write flags for a registered console

**Parameters**

- `struct console *con`: struct console pointer of console to write flags to
- `short flags`: new flags value to write

**Description**

Only use this function to write flags for registered consoles. It
requires holding the console_list_lock.

**Context**

Any context.

#### <a id="c-for_each_console_srcu"></a>`for_each_console_srcu()`

```c
for_each_console_srcu(con)
```

Iterator over registered consoles

**Parameters**

- `con`: struct console pointer used as loop cursor

**Description**

Although SRCU guarantees the console list will be consistent, the
struct console fields may be updated by other CPUs while iterating.

Requires console_srcu_read_lock to be held. Can be invoked from
any context.

#### <a id="c-for_each_console"></a>`for_each_console()`

```c
for_each_console(con)
```

Iterator over registered consoles

**Parameters**

- `con`: struct console pointer used as loop cursor

**Description**

The console list and the [`console.flags`](#c-struct-console) are immutable while iterating.

Requires console_list_lock to be held.



#### <a id="c-clear_selection"></a>`clear_selection()`

```c
void clear_selection(void)
```

remove current selection

**Parameters**

- `void`: no arguments

**Description**

Remove the current selection highlight, if any from the console holding the
selection.

Locking: The caller must hold the console lock.



#### <a id="c-__vc_resize"></a>`__vc_resize()`

```c
int __vc_resize(struct vc_data *vc, unsigned int cols, unsigned int rows, bool from_user)
```

resize a VT

**Parameters**

- `struct vc_data *vc`: virtual console
- `unsigned int cols`: columns
- `unsigned int rows`: rows
- `bool from_user`: invoked by a user?

**Description**

Resize a virtual console as seen from the console end of things. We use the
common [`vc_do_resize()`](#c-vc_do_resize) method to update the structures.

Locking: The caller must hold the console sem to protect console internals
and **vc->port.tty**.

#### <a id="c-con_is_bound"></a>`con_is_bound()`

```c
int con_is_bound(const struct consw *csw)
```

checks if driver is bound to the console

**Parameters**

- `const struct consw *csw`: console driver

**Return**

zero if unbound, nonzero if bound

**Description**

Drivers can call this and if zero, they should release
all resources allocated on [`consw.con_startup()`](#c-struct-consw)

#### <a id="c-con_is_visible"></a>`con_is_visible()`

```c
bool con_is_visible(const struct vc_data *vc)
```

checks whether the current console is visible

**Parameters**

- `const struct vc_data *vc`: virtual console

**Return**

zero if not visible, nonzero if visible

#### <a id="c-con_debug_enter"></a>`con_debug_enter()`

```c
void con_debug_enter(struct vc_data *vc)
```

prepare the console for the kernel debugger

**Parameters**

- `struct vc_data *vc`: virtual console

**Description**

Called when the console is taken over by the kernel debugger, this
function needs to save the current console state, then put the console
into a state suitable for the kernel debugger.

#### <a id="c-con_debug_leave"></a>`con_debug_leave()`

```c
void con_debug_leave(void)
```

restore console state

**Parameters**

- `void`: no arguments

**Description**

Restore the console state to what it was before the kernel debugger
was invoked.

#### <a id="c-do_unregister_con_driver"></a>`do_unregister_con_driver()`

```c
int do_unregister_con_driver(const struct consw *csw)
```

unregister console driver from console layer

**Parameters**

- `const struct consw *csw`: console driver

**Description**

All drivers that registers to the console layer must
call this function upon exit, or if the console driver is in a state
where it won't be able to handle console services, such as the
framebuffer console without loaded framebuffer drivers.

The driver must unbind first prior to unregistration.


<a id="rst-internals-1"></a>

### Internals


#### <a id="c-sel_loadlut"></a>`sel_loadlut()`

```c
int sel_loadlut(u32 __user *lut)
```

load the LUT table

**Parameters**

- `u32 __user *lut`: user table

**Description**

Load the LUT table from user space. Make a temporary copy so a partial
update doesn't make a mess.

Locking: The console lock is acquired.

#### <a id="c-set_selection_user"></a>`set_selection_user()`

```c
int set_selection_user(const struct tiocl_selection __user *sel, struct tty_struct *tty)
```

set the current selection.

**Parameters**

- `const struct tiocl_selection __user *sel`: user selection info
- `struct tty_struct *tty`: the console tty

**Description**

Invoked by the ioctl handle for the vt layer.

Locking: The entire selection process is managed under the console_lock.
It's a lot under the lock but its hardly a performance path.



#### <a id="c-vc_do_resize"></a>`vc_do_resize()`

```c
int vc_do_resize(struct tty_struct *tty, struct vc_data *vc, unsigned int cols, unsigned int lines, bool from_user)
```

resizing method for the tty

**Parameters**

- `struct tty_struct *tty`: tty being resized
- `struct vc_data *vc`: virtual console private data
- `unsigned int cols`: columns
- `unsigned int lines`: lines
- `bool from_user`: invoked by a user?

**Description**

Resize a virtual console, clipping according to the actual constraints. If
the caller passes a tty structure then update the termios winsize
information and perform any necessary signal handling.

Locking: Caller must hold the console semaphore. Takes the termios rwsem and
ctrl.lock of the tty IFF a tty is passed.

#### <a id="c-vt_resize"></a>`vt_resize()`

```c
int vt_resize(struct tty_struct *tty, struct winsize *ws)
```

resize a VT

**Parameters**

- `struct tty_struct *tty`: tty to resize
- `struct winsize *ws`: winsize attributes

**Description**

Resize a virtual terminal. This is called by the tty layer as we register
our own handler for resizing. The mutual helper does all the actual work.

Locking: Takes the console sem and the called methods then take the tty
termios_rwsem and the tty ctrl.lock in that order.

#### <a id="c-enum-vc_ctl_state"></a>`enum vc_ctl_state`

control characters state of a vt

**Constants**

- `ESnormal`: initial state, no control characters parsed
- `ESesc`: ESC parsed
- `ESsquare`: CSI parsed -- modifiers/parameters/ctrl chars expected
- `ESgetpars`: CSI parsed -- parameters/ctrl chars expected
- `ESfunckey`: CSI \[ parsed
- `EShash`: ESC # parsed
- `ESsetG0`: ESC ( parsed
- `ESsetG1`: ESC ) parsed
- `ESpercent`: ESC % parsed
- `EScsiignore`: CSI \[0x20-0x3f\] parsed
- `ESnonstd`: OSC parsed
- `ESpalette`: OSC P parsed
- `ESosc`: OSC \[0-9\] parsed
- `ESANSI_first`: first state for ignoring ansi control sequences
- `ESapc`: ESC _ parsed
- `ESpm`: ESC ^ parsed
- `ESdcs`: ESC P parsed
- `ESANSI_last`: last state for ignoring ansi control sequences

#### <a id="c-vc_sanitize_unicode"></a>`vc_sanitize_unicode()`

```c
int vc_sanitize_unicode(const int c)
```

Replace invalid Unicode code points with `U+FFFD`

**Parameters**

- `const int c`: the received code point

#### <a id="c-vc_translate_unicode"></a>`vc_translate_unicode()`

```c
int vc_translate_unicode(struct vc_data *vc, int c, bool *rescan)
```

Combine UTF-8 into Unicode in `vc_data.vc_utf_char`

**Parameters**

- `struct vc_data *vc`: virtual console
- `int c`: UTF-8 byte to translate
- `bool *rescan`: set to true iff **c** wasn't consumed here and needs to be re-processed

**Description**

* `vc_data.vc_utf_char` is the being-constructed Unicode code point.
* `vc_data.vc_utf_count` is the number of continuation bytes still expected to
  arrive.
* `vc_data.vc_npar` is the number of continuation bytes arrived so far.

**Return**

* `-1` - Input OK so far, **c** consumed, further bytes expected.
* `0xFFFD` - Possibility 1: input invalid, **c** may have been consumed (see
  desc. of **rescan**). Possibility 2: input OK, **c** consumed,
  `U+FFFD` is the resulting code point. `U+FFFD` is valid,
  `REPLACEMENT CHARACTER`.
* otherwise - Input OK, **c** consumed, resulting code point returned.

#### <a id="c-vt_kmsg_redirect"></a>`vt_kmsg_redirect()`

```c
int vt_kmsg_redirect(int new)
```

sets/gets the kernel message console

**Parameters**

- `int new`: the new virtual terminal number or -1 if the console should stay
  unchanged

**Description**

By default, the kernel messages are always printed on the current virtual
console. However, the user may modify that default with the
`TIOCL_SETKMSGREDIRECT` ioctl call.

This function sets the kernel message console to be **new**. It returns the old
virtual console number. The virtual terminal number `0` (both as parameter and
return value) means no redirection (i.e. always printed on the currently
active console).

The parameter -1 means that only the current console is returned, but the
value is not modified. You may use the macro `vt_get_kmsg_redirect()` in that
case to make the code more understandable.

When the kernel is compiled without `CONFIG_VT_CONSOLE`, this function ignores
the parameter and always returns `0`.

---

# MOXA Smartio/Industio Family Device Driver Installation Guide

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Copyright (C) 2008, Moxa Inc. Copyright (C) 2021, Jiri Slaby

<a id="rst-moxa-smartio-industio-family-device-driver-installation-guide"></a>

Copyright (C) 2008, Moxa Inc. Copyright (C) 2021, Jiri Slaby

<!-- Content

1. Introduction
2. System Requirement
3. Installation
   3.1 Hardware installation
   3.2 Device naming convention
4. Utilities
5. Setserial
6. Troubleshooting -->

<a id="rst-introduction"></a>

## 1. Introduction

> The Smartio/Industio/UPCI family Linux driver supports following multiport boards:
>
> > - - **2 ports multiport board**
> >
> >     CP-102U, CP-102UL, CP-102UF CP-132U-I, CP-132UL, CP-132, CP-132I, CP132S, CP-132IS, (CP-102, CP-102S)
> >
> > - - **4 ports multiport board**
> >
> >     CP-104EL, CP-104UL, CP-104JU, CP-134U, CP-134U-I, C104H/PCI, C104HS/PCI, CP-114, CP-114I, CP-114S, CP-114IS, CP-114UL, (C114HI, CT-114I), POS-104UL, CB-114, CB-134I
> >
> > - - **8 ports multiport board**
> >
> >     CP-118EL, CP-168EL, CP-118U, CP-168U, C168H/PCI, CB-108
>
> If a compatibility problem occurs, please contact Moxa at [support@moxa.com.tw](<mailto:support@moxa.com.tw>).
>
> In addition to device driver, useful utilities are also provided in this version. They are:
>
> > - - **msdiag**
> >
> >     Diagnostic program for displaying installed Moxa Smartio/Industio boards.
> >
> > - - **msmon**
> >
> >     Monitor program to observe data count and line status signals.
> >
> > - - **msterm     A simple terminal program which is useful in testing serial**
> >
> >     ports.
>
> All the drivers and utilities are published in form of source code under GNU General Public License in this version. Please refer to GNU General Public License announcement in each source code file for more detail.
>
> In Moxa's Web sites, you may always find the latest driver at [https://www.moxa.com/](<https://www.moxa.com/>).
>
> This version of driver can be installed as a Loadable Module (Module driver) or built-in into kernel (Static driver). Before you install the driver, please refer to hardware installation procedure in the User's Manual.
>
> We assume the user should be familiar with following documents:
>
> - Serial-HOWTO
>
> - Kernel-HOWTO

<a id="rst-system-requirement"></a>

## 2. System Requirement

> - Maximum 4 boards can be installed in combination

<a id="rst-installation"></a>

## 3. Installation

<a id="rst-hardware-installation"></a>

### 3.1 Hardware installation

<a id="rst-pci-upci-board"></a>

#### PCI/UPCI board

> You may need to adjust IRQ usage in BIOS to avoid IRQ conflict with other ISA devices. Please refer to hardware installation procedure in User's Manual in advance.

<a id="rst-pci-irq-sharing"></a>

#### PCI IRQ Sharing

> Each port within the same multiport board shares the same IRQ. Up to 4 Moxa Smartio/Industio PCI Family multiport boards can be installed together on one system and they can share the same IRQ.

<a id="rst-device-naming-convention"></a>

### 3.2 Device naming convention

> The device node is named "ttyMxx".

<a id="rst-device-naming-when-more-than-2-boards-installed"></a>

#### Device naming when more than 2 boards installed

> Naming convention for each Smartio/Industio multiport board is pre-defined as below.
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> Board Num.
>
> </td>
> <td>
>
>
> Device node
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1st board
>
> </td>
> <td>
>
>
> ttyM0  - ttyM7
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2nd board
>
> </td>
> <td>
>
>
> ttyM8  - ttyM15
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3rd board
>
> </td>
> <td>
>
>
> ttyM16 - ttyM23
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4th board
>
> </td>
> <td>
>
>
> ttyM24 - ttyM31
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-utilities"></a>

## 4. Utilities

> There are 3 utilities contained in this driver. They are msdiag, msmon and msterm. These 3 utilities are released in form of source code. They should be compiled into executable file and copied into /usr/bin.

<a id="rst-msdiag-diagnostic"></a>

### msdiag - Diagnostic

> This utility provides the function to display what Moxa Smartio/Industio board was found by the driver in the system.

<a id="rst-msmon-port-monitoring"></a>

### msmon - Port Monitoring

> This utility gives the user a quick view about all the MOXA ports' activities. One can easily learn each port's total received/transmitted (Rx/Tx) character count since the time when the monitoring is started.
>
> Rx/Tx throughputs per second are also reported in interval basis (e.g. the last 5 seconds) and in average basis (since the time the monitoring is started). You can reset all ports' count by &lt;HOME&gt; key. &lt;+&gt; &lt;-&gt; (plus/minus) keys to change the displaying time interval. Press &lt;ENTER&gt; on the port, that cursor stay, to view the port's communication parameters, signal status, and input/output queue.

<a id="rst-msterm-terminal-emulation"></a>

### msterm - Terminal Emulation

> This utility provides data sending and receiving ability of all tty ports, especially for MOXA ports. It is quite useful for testing simple application, for example, sending AT command to a modem connected to the port or used as a terminal for login purpose. Note that this is only a dumb terminal emulation without handling full screen operation.

<a id="rst-setserial"></a>

## 5. Setserial

> Supported Setserial parameters are listed as below.
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> uart
>
> </td>
> <td>
>
>
> set UART type(16450 --&gt; disable FIFO, 16550A --&gt; enable FIFO)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> close_delay
>
> </td>
> <td>
>
>
> set the amount of time (in 1/100 of a second) that DTR should be kept low while being closed.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> closing_wait
>
> </td>
> <td>
>
>
> set the amount of time (in 1/100 of a second) that the serial port should wait for data to be drained while being closed, before the receiver is disabled.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_hi
>
> </td>
> <td>
>
>
> Use 57.6kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_vhi
>
> </td>
> <td>
>
>
> Use 115.2kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_shi
>
> </td>
> <td>
>
>
> Use 230.4kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_warp
>
> </td>
> <td>
>
>
> Use 460.8kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_normal
>
> </td>
> <td>
>
>
> Use 38.4kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_cust
>
> </td>
> <td>
>
>
> Use the custom divisor to set the speed when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> divisor
>
> </td>
> <td>
>
>
> This option sets the custom division.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> baud_base
>
> </td>
> <td>
>
>
> This option sets the base baud rate.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-troubleshooting"></a>

## 6. Troubleshooting

> The boot time error messages and solutions are stated as clearly as possible. If all the possible solutions fail, please contact our technical support team to get more help.
>
> - **Error msg:**
>
>   More than 4 Moxa Smartio/Industio family boards found. Fifth board and after are ignored.
>
> Solution: To avoid this problem, please unplug fifth and after board, because Moxa driver supports up to 4 boards.

---

# GSM 0710 tty multiplexor HOWTO

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> How to use it

<a id="rst-gsm-0710-tty-multiplexor-howto"></a>

<a id="rst-contents"></a>



This line discipline implements the GSM 07.10 multiplexing protocol detailed in the following 3GPP document:

> [https://www.3gpp.org/ftp/Specs/archive/07_series/07.10/0710-720.zip](<https://www.3gpp.org/ftp/Specs/archive/07_series/07.10/0710-720.zip>)

This document give some hints on how to use this driver with GPRS and 3G modems connected to a physical serial port.

<a id="rst-how-to-use-it"></a>

## How to use it

<a id="rst-config-initiator"></a>

### Config Initiator

1. Initialize the modem in 0710 mux mode (usually `AT+CMUX=` command) through its serial port. Depending on the modem used, you can pass more or less parameters to this command.

2. Switch the serial line to using the n_gsm line discipline by using `TIOCSETD` ioctl.

3. Configure the mux using `GSMIOC_GETCONF_EXT`/`GSMIOC_SETCONF_EXT` ioctl if needed.

4. Configure the mux using `GSMIOC_GETCONF`/`GSMIOC_SETCONF` ioctl.

5. Configure DLCs using `GSMIOC_GETCONF_DLCI`/`GSMIOC_SETCONF_DLCI` ioctl for non-defaults.

6. Obtain base gsmtty number for the used serial port.

   Major parts of the initialization program (a good starting point is util-linux-ng/sys-utils/ldattach.c):



   ```text
   #include <stdio.h>
   #include <stdint.h>
   #include <linux/gsmmux.h>
   #include <linux/tty.h>

   #define DEFAULT_SPEED     B115200
   #define SERIAL_PORT       /dev/ttyS0

   int ldisc = N_GSM0710;
   struct gsm_config c;
   struct gsm_config_ext ce;
   struct gsm_dlci_config dc;
   struct termios configuration;
   uint32_t first;

   /* open the serial port connected to the modem */
   fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY);

   /* configure the serial port : speed, flow control ... */

   /* send the AT commands to switch the modem to CMUX mode
      and check that it's successful (should return OK) */
   write(fd, "AT+CMUX=0\r", 10);

   /* experience showed that some modems need some time before
      being able to answer to the first MUX packet so a delay
      may be needed here in some case */
   sleep(3);

   /* use n_gsm line discipline */
   ioctl(fd, TIOCSETD, &ldisc);

   /* get n_gsm extended configuration */
   ioctl(fd, GSMIOC_GETCONF_EXT, &ce);
   /* use keep-alive once every 5s for modem connection supervision */
   ce.keep_alive = 500;
   /* set the new extended configuration */
   ioctl(fd, GSMIOC_SETCONF_EXT, &ce);
   /* get n_gsm configuration */
   ioctl(fd, GSMIOC_GETCONF, &c);
   /* we are initiator and need encoding 0 (basic) */
   c.initiator = 1;
   c.encapsulation = 0;
   /* our modem defaults to a maximum size of 127 bytes */
   c.mru = 127;
   c.mtu = 127;
   /* set the new configuration */
   ioctl(fd, GSMIOC_SETCONF, &c);
   /* get DLC 1 configuration */
   dc.channel = 1;
   ioctl(fd, GSMIOC_GETCONF_DLCI, &dc);
   /* the first user channel gets a higher priority */
   dc.priority = 1;
   /* set the new DLC 1 specific configuration */
   ioctl(fd, GSMIOC_SETCONF_DLCI, &dc);
   /* get first gsmtty device node */
   ioctl(fd, GSMIOC_GETFIRST, &first);
   printf("first muxed line: /dev/gsmtty%i\n", first);

   /* and wait for ever to keep the line discipline enabled */
   daemon(0,0);
   pause();
   ```

7. Use these devices as plain serial ports.

   For example, it's possible:

   - to use *gnokii* to send / receive SMS on `ttygsm1`

   - to use *ppp* to establish a datalink on `ttygsm2`

8. First close all virtual ports before closing the physical port.

   Note that after closing the physical port the modem is still in multiplexing mode. This may prevent a successful re-opening of the port later. To avoid this situation either reset the modem if your hardware allows that or send a disconnect command frame manually before initializing the multiplexing mode for the second time. The byte sequence for the disconnect command frame is:



   ```text
   0xf9, 0x03, 0xef, 0x03, 0xc3, 0x16, 0xf9
   ```

<a id="rst-config-requester"></a>

### Config Requester

1. Receive `AT+CMUX=` command through its serial port, initialize mux mode config.

2. Switch the serial line to using the *n_gsm* line discipline by using `TIOCSETD` ioctl.

3. Configure the mux using `GSMIOC_GETCONF_EXT`/`GSMIOC_SETCONF_EXT` ioctl if needed.

4. Configure the mux using `GSMIOC_GETCONF`/`GSMIOC_SETCONF` ioctl.

5. Configure DLCs using `GSMIOC_GETCONF_DLCI`/`GSMIOC_SETCONF_DLCI` ioctl for non-defaults.

6. Obtain base gsmtty number for the used serial port:



   ```text
   #include <stdio.h>
   #include <stdint.h>
   #include <linux/gsmmux.h>
   #include <linux/tty.h>
   #define DEFAULT_SPEED   B115200
   #define SERIAL_PORT     /dev/ttyS0

   int ldisc = N_GSM0710;
   struct gsm_config c;
   struct gsm_config_ext ce;
   struct gsm_dlci_config dc;
   struct termios configuration;
   uint32_t first;

   /* open the serial port */
   fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY);

   /* configure the serial port : speed, flow control ... */

   /* get serial data and check "AT+CMUX=command" parameter ... */

   /* use n_gsm line discipline */
   ioctl(fd, TIOCSETD, &ldisc);

   /* get n_gsm extended configuration */
   ioctl(fd, GSMIOC_GETCONF_EXT, &ce);
   /* use keep-alive once every 5s for peer connection supervision */
   ce.keep_alive = 500;
   /* set the new extended configuration */
   ioctl(fd, GSMIOC_SETCONF_EXT, &ce);
   /* get n_gsm configuration */
   ioctl(fd, GSMIOC_GETCONF, &c);
   /* we are requester and need encoding 0 (basic) */
   c.initiator = 0;
   c.encapsulation = 0;
   /* our modem defaults to a maximum size of 127 bytes */
   c.mru = 127;
   c.mtu = 127;
   /* set the new configuration */
   ioctl(fd, GSMIOC_SETCONF, &c);
   /* get DLC 1 configuration */
   dc.channel = 1;
   ioctl(fd, GSMIOC_GETCONF_DLCI, &dc);
   /* the first user channel gets a higher priority */
   dc.priority = 1;
   /* set the new DLC 1 specific configuration */
   ioctl(fd, GSMIOC_SETCONF_DLCI, &dc);
   /* get first gsmtty device node */
   ioctl(fd, GSMIOC_GETFIRST, &first);
   printf("first muxed line: /dev/gsmtty%i\n", first);

   /* and wait for ever to keep the line discipline enabled */
   daemon(0,0);
   pause();
   ```

11-03-08 - Eric Bénard - &lt;[eric@eukrea.com](<mailto:eric@eukrea.com>)&gt;

---

# N_TTY

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> External Functions

<a id="rst-n-tty"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



The default (and fallback) [TTY line discipline](</kernel/hardware/driver-api/tty/tty-ldisc.md>). It tries to handle characters as per POSIX.

<a id="rst-external-functions"></a>

## External Functions


#### <a id="c-n_tty_inherit_ops"></a>`n_tty_inherit_ops()`

```c
void n_tty_inherit_ops(struct tty_ldisc_ops *ops)
```

inherit N_TTY methods

**Parameters**

- `struct tty_ldisc_ops *ops`: struct tty_ldisc_ops where to save N_TTY methods

**Description**

Enables a 'subclass' line discipline to 'inherit' N_TTY methods.


<a id="rst-internal-functions"></a>

## Internal Functions


#### <a id="c-n_tty_kick_worker"></a>`n_tty_kick_worker()`

```c
void n_tty_kick_worker(const struct tty_struct *tty)
```

start input worker (if required)

**Parameters**

- `const struct tty_struct *tty`: terminal

**Description**

Re-schedules the flip buffer work if it may have stopped.

- Locking:
  * Caller holds exclusive `termios_rwsem`, or
  * [`n_tty_read()`](#c-n_tty_read)/consumer path:
    holds non-exclusive `termios_rwsem`

#### <a id="c-n_tty_write_wakeup"></a>`n_tty_write_wakeup()`

```c
void n_tty_write_wakeup(struct tty_struct *tty)
```

asynchronous I/O notifier

**Parameters**

- `struct tty_struct *tty`: tty device

**Description**

Required for the ptys, serial driver etc. since processes that attach
themselves to the master and rely on ASYNC IO must be woken up.

#### <a id="c-put_tty_queue"></a>`put_tty_queue()`

```c
void put_tty_queue(u8 c, struct n_tty_data *ldata)
```

add character to tty

**Parameters**

- `u8 c`: character
- `struct n_tty_data *ldata`: n_tty data

**Description**

Add a character to the tty read_buf queue.

- Locking:
  * `n_tty_receive_buf()`/producer path:
    caller holds non-exclusive `termios_rwsem`

#### <a id="c-reset_buffer_flags"></a>`reset_buffer_flags()`

```c
void reset_buffer_flags(struct n_tty_data *ldata)
```

reset buffer state

**Parameters**

- `struct n_tty_data *ldata`: line disc data to reset

**Description**

Reset the read buffer counters and clear the flags. Called from
[`n_tty_open()`](#c-n_tty_open) and [`n_tty_flush_buffer()`](#c-n_tty_flush_buffer).

- Locking:
  * caller holds exclusive `termios_rwsem`, or
  * (locking is not required)

#### <a id="c-n_tty_flush_buffer"></a>`n_tty_flush_buffer()`

```c
void n_tty_flush_buffer(struct tty_struct *tty)
```

clean input queue

**Parameters**

- `struct tty_struct *tty`: terminal device

**Description**

Flush the input buffer. Called when the tty layer wants the buffer flushed
(eg at hangup) or when the `N_TTY` line discipline internally has to clean
the pending queue (for example some signals).

Holds `termios_rwsem` to exclude producer/consumer while buffer indices are
reset.

Locking: `ctrl`.lock, exclusive `termios_rwsem`

#### <a id="c-is_utf8_continuation"></a>`is_utf8_continuation()`

```c
int is_utf8_continuation(u8 c)
```

utf8 multibyte check

**Parameters**

- `u8 c`: byte to check

**Return**

true if the utf8 character **c** is a multibyte continuation
character. We use this to correctly compute the on-screen size of the
character when printing.

#### <a id="c-is_continuation"></a>`is_continuation()`

```c
int is_continuation(u8 c, const struct tty_struct *tty)
```

multibyte check

**Parameters**

- `u8 c`: byte to check
- `const struct tty_struct *tty`: terminal device

**Return**

true if the utf8 character **c** is a multibyte continuation character
and the terminal is in unicode mode.

#### <a id="c-do_output_char"></a>`do_output_char()`

```c
int do_output_char(u8 c, struct tty_struct *tty, int space)
```

output one character

**Parameters**

- `u8 c`: character (or partial unicode symbol)
- `struct tty_struct *tty`: terminal device
- `int space`: space available in tty driver write buffer

**Description**

This is a helper function that handles one output character (including
special characters like TAB, CR, LF, etc.), doing OPOST processing and
putting the results in the tty driver's write buffer.

Note that Linux currently ignores TABDLY, CRDLY, VTDLY, FFDLY and NLDLY.
They simply aren't relevant in the world today. If you ever need them, add
them here.

Locking: should be called under the `output_lock` to protect the column state
and space left in the buffer.

**Return**

the number of bytes of buffer space used or -1 if no space left.

#### <a id="c-process_output"></a>`process_output()`

```c
int process_output(u8 c, struct tty_struct *tty)
```

output post processor

**Parameters**

- `u8 c`: character (or partial unicode symbol)
- `struct tty_struct *tty`: terminal device

**Description**

Output one character with OPOST processing.

Locking: `output_lock` to protect column state and space left (also, this is
called from [`n_tty_write()`](#c-n_tty_write) under the tty layer write lock).

**Return**

-1 when the output device is full and the character must be
retried.

#### <a id="c-process_output_block"></a>`process_output_block()`

```c
ssize_t process_output_block(struct tty_struct *tty, const u8 *buf, unsigned int nr)
```

block post processor

**Parameters**

- `struct tty_struct *tty`: terminal device
- `const u8 *buf`: character buffer
- `unsigned int nr`: number of bytes to output

**Description**

Output a block of characters with OPOST processing.

This path is used to speed up block console writes, among other things when
processing blocks of output data. It handles only the simple cases normally
found and helps to generate blocks of symbols for the console driver and
thus improve performance.

Locking: `output_lock` to protect column state and space left (also, this is
called from [`n_tty_write()`](#c-n_tty_write) under the tty layer write lock).

**Return**

the number of characters output.

#### <a id="c-__process_echoes"></a>`__process_echoes()`

```c
size_t __process_echoes(struct tty_struct *tty)
```

write pending echo characters

**Parameters**

- `struct tty_struct *tty`: terminal device

**Description**

Write previously buffered echo (and other ldisc-generated) characters to the
tty.

Characters generated by the ldisc (including echoes) need to be buffered
because the driver's write buffer can fill during heavy program output.
Echoing straight to the driver will often fail under these conditions,
causing lost characters and resulting mismatches of ldisc state information.

Since the ldisc state must represent the characters actually sent to the
driver at the time of the write, operations like certain changes in column
state are also saved in the buffer and executed here.

A circular fifo buffer is used so that the most recent characters are
prioritized. Also, when control characters are echoed with a prefixed "^",
the pair is treated atomically and thus not separated.

Locking: callers must hold `output_lock`.

#### <a id="c-add_echo_byte"></a>`add_echo_byte()`

```c
void add_echo_byte(u8 c, struct n_tty_data *ldata)
```

add a byte to the echo buffer

**Parameters**

- `u8 c`: unicode byte to echo
- `struct n_tty_data *ldata`: n_tty data

**Description**

Add a character or operation byte to the echo buffer.

#### <a id="c-echo_move_back_col"></a>`echo_move_back_col()`

```c
void echo_move_back_col(struct n_tty_data *ldata)
```

add operation to move back a column

**Parameters**

- `struct n_tty_data *ldata`: n_tty data

**Description**

Add an operation to the echo buffer to move back one column.

#### <a id="c-echo_set_canon_col"></a>`echo_set_canon_col()`

```c
void echo_set_canon_col(struct n_tty_data *ldata)
```

add operation to set the canon column

**Parameters**

- `struct n_tty_data *ldata`: n_tty data

**Description**

Add an operation to the echo buffer to set the canon column to the current
column.

#### <a id="c-echo_erase_tab"></a>`echo_erase_tab()`

```c
void echo_erase_tab(unsigned int num_chars, int after_tab, struct n_tty_data *ldata)
```

add operation to erase a tab

**Parameters**

- `unsigned int num_chars`: number of character columns already used
- `int after_tab`: true if num_chars starts after a previous tab
- `struct n_tty_data *ldata`: n_tty data

**Description**

Add an operation to the echo buffer to erase a tab.

Called by the eraser function, which knows how many character columns have
been used since either a previous tab or the start of input. This
information will be used later, along with canon column (if applicable), to
go back the correct number of columns.

#### <a id="c-echo_char_raw"></a>`echo_char_raw()`

```c
void echo_char_raw(u8 c, struct n_tty_data *ldata)
```

echo a character raw

**Parameters**

- `u8 c`: unicode byte to echo
- `struct n_tty_data *ldata`: line disc data

**Description**

Echo user input back onto the screen. This must be called only when
L_ECHO(tty) is true. Called from the [`tty_driver.receive_buf()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) path.

This variant does not treat control characters specially.

#### <a id="c-echo_char"></a>`echo_char()`

```c
void echo_char(u8 c, const struct tty_struct *tty)
```

echo a character

**Parameters**

- `u8 c`: unicode byte to echo
- `const struct tty_struct *tty`: terminal device

**Description**

Echo user input back onto the screen. This must be called only when
L_ECHO(tty) is true. Called from the [`tty_driver.receive_buf()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) path.

This variant tags control characters to be echoed as "^X" (where X is the
letter representing the control char).

#### <a id="c-finish_erasing"></a>`finish_erasing()`

```c
void finish_erasing(struct n_tty_data *ldata)
```

complete erase

**Parameters**

- `struct n_tty_data *ldata`: n_tty data

#### <a id="c-eraser"></a>`eraser()`

```c
void eraser(u8 c, const struct tty_struct *tty)
```

handle erase function

**Parameters**

- `u8 c`: character input
- `const struct tty_struct *tty`: terminal device

**Description**

Perform erase and necessary output when an erase character is present in the
stream from the driver layer. Handles the complexities of UTF-8 multibyte
symbols.

- Locking: `n_tty_receive_buf()`/producer path:
  caller holds non-exclusive `termios_rwsem`

#### <a id="c-isig"></a>`isig()`

```c
void isig(int sig, struct tty_struct *tty)
```

handle the ISIG optio

**Parameters**

- `int sig`: signal
- `struct tty_struct *tty`: terminal

**Description**

Called when a signal is being sent due to terminal input. Called from the
[`tty_driver.receive_buf()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) path, so serialized.

Performs input and output flush if !NOFLSH. In this context, the echo
buffer is 'output'. The signal is processed first to alert any current
readers or writers to discontinue and exit their i/o loops.

Locking: `ctrl`.lock

#### <a id="c-n_tty_receive_break"></a>`n_tty_receive_break()`

```c
void n_tty_receive_break(struct tty_struct *tty)
```

handle break

**Parameters**

- `struct tty_struct *tty`: terminal

**Description**

An RS232 break event has been hit in the incoming bitstream. This can cause
a variety of events depending upon the termios settings.

- Locking: `n_tty_receive_buf()`/producer path:
  caller holds non-exclusive termios_rwsem

**Note**

may get exclusive `termios_rwsem` if flushing input buffer

#### <a id="c-n_tty_receive_overrun"></a>`n_tty_receive_overrun()`

```c
void n_tty_receive_overrun(const struct tty_struct *tty)
```

handle overrun reporting

**Parameters**

- `const struct tty_struct *tty`: terminal

**Description**

Data arrived faster than we could process it. While the tty driver has
flagged this the bits that were missed are gone forever.

Called from the receive_buf path so single threaded. Does not need locking
as num_overrun and overrun_time are function private.

#### <a id="c-n_tty_receive_parity_error"></a>`n_tty_receive_parity_error()`

```c
void n_tty_receive_parity_error(const struct tty_struct *tty, u8 c)
```

error notifier

**Parameters**

- `const struct tty_struct *tty`: terminal device
- `u8 c`: character

**Description**

Process a parity error and queue the right data to indicate the error case
if necessary.

- Locking: `n_tty_receive_buf()`/producer path:
  caller holds non-exclusive `termios_rwsem`

#### <a id="c-n_tty_receive_char_flow_ctrl"></a>`n_tty_receive_char_flow_ctrl()`

```c
bool n_tty_receive_char_flow_ctrl(struct tty_struct *tty, u8 c, bool lookahead_done)
```

receive flow control chars

**Parameters**

- `struct tty_struct *tty`: terminal device
- `u8 c`: character
- `bool lookahead_done`: lookahead has processed this character already

**Description**

Receive and process flow control character actions.

In case lookahead for flow control chars already handled the character in
advance to the normal receive, the actions are skipped during normal
receive.

Returns true if **c** is consumed as flow-control character, the character
must not be treated as normal character.

#### <a id="c-n_tty_receive_char"></a>`n_tty_receive_char()`

```c
void n_tty_receive_char(struct tty_struct *tty, u8 c)
```

perform processing

**Parameters**

- `struct tty_struct *tty`: terminal device
- `u8 c`: character

**Description**

Process an individual character of input received from the driver.  This is
serialized with respect to itself by the rules for the driver above.

- Locking: `n_tty_receive_buf()`/producer path:
  caller holds non-exclusive `termios_rwsem`
  publishes canon_head if canonical mode is active

#### <a id="c-n_tty_receive_buf_common"></a>`n_tty_receive_buf_common()`

```c
size_t n_tty_receive_buf_common(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count, bool flow)
```

process input

**Parameters**

- `struct tty_struct *tty`: device to receive input
- `const u8 *cp`: input chars
- `const u8 *fp`: flags for each char (if `NULL`, all chars are `TTY_NORMAL`)
- `size_t count`: number of input chars in **cp**
- `bool flow`: enable flow control

**Description**

Called by the terminal driver when a block of characters has been received.
This function must be called from soft contexts not from interrupt context.
The driver is responsible for making calls one at a time and in order (or
using [`flush_to_ldisc()`](/kernel/hardware/driver-api/tty/tty-buffer.md#c-flush_to_ldisc)).

In canonical mode, the maximum line length is 4096 chars (including the line
termination char); lines longer than 4096 chars are truncated. After 4095
chars, input data is still processed but not stored. Overflow processing
ensures the tty can always receive more input until at least one line can be
read.

In non-canonical mode, the read buffer will only accept 4095 chars; this
provides the necessary space for a newline char if the input mode is
switched to canonical.

Note it is possible for the read buffer to _contain_ 4096 chars in
non-canonical mode: the read buffer could already contain the maximum canon
line of 4096 chars when the mode is switched to non-canonical.

- Locking: `n_tty_receive_buf()`/producer path:
  claims non-exclusive `termios_rwsem`
  publishes commit_head or canon_head

**Return**

the # of input chars from **cp** which were processed.

#### <a id="c-n_tty_set_termios"></a>`n_tty_set_termios()`

```c
void n_tty_set_termios(struct tty_struct *tty, const struct ktermios *old)
```

termios data changed

**Parameters**

- `struct tty_struct *tty`: terminal
- `const struct ktermios *old`: previous data

**Description**

Called by the tty layer when the user changes termios flags so that the line
discipline can plan ahead. This function cannot sleep and is protected from
re-entry by the tty layer. The user is guaranteed that this function will
not be re-entered or in progress when the ldisc is closed.

Locking: Caller holds **tty->termios_rwsem**

#### <a id="c-n_tty_close"></a>`n_tty_close()`

```c
void n_tty_close(struct tty_struct *tty)
```

close the ldisc for this tty

**Parameters**

- `struct tty_struct *tty`: device

**Description**

Called from the terminal layer when this line discipline is being shut down,
either because of a close or becsuse of a discipline change. The function
will not be called while other ldisc methods are in progress.

#### <a id="c-n_tty_open"></a>`n_tty_open()`

```c
int n_tty_open(struct tty_struct *tty)
```

open an ldisc

**Parameters**

- `struct tty_struct *tty`: terminal to open

**Description**

Called when this line discipline is being attached to the terminal device.
Can sleep. Called serialized so that no other events will occur in parallel.
No further open will occur until a close.

#### <a id="c-copy_from_read_buf"></a>`copy_from_read_buf()`

```c
bool copy_from_read_buf(const struct tty_struct *tty, u8 **kbp, size_t *nr)
```

copy read data directly

**Parameters**

- `const struct tty_struct *tty`: terminal device
- `u8 **kbp`: data
- `size_t *nr`: size of data

**Description**

Helper function to speed up [`n_tty_read()`](#c-n_tty_read). It is only called when `ICANON` is
off; it copies characters straight from the tty queue.

- Locking:
  * called under the **ldata->atomic_read_lock** sem
  * [`n_tty_read()`](#c-n_tty_read)/consumer path:
    caller holds non-exclusive `termios_rwsem`;
    read_tail published

**Return**

true if it successfully copied data, but there is still more data
to be had.

#### <a id="c-canon_copy_from_read_buf"></a>`canon_copy_from_read_buf()`

```c
bool canon_copy_from_read_buf(const struct tty_struct *tty, u8 **kbp, size_t *nr)
```

copy read data in canonical mode

**Parameters**

- `const struct tty_struct *tty`: terminal device
- `u8 **kbp`: data
- `size_t *nr`: size of data

**Description**

Helper function for [`n_tty_read()`](#c-n_tty_read). It is only called when `ICANON` is on; it
copies one line of input up to and including the line-delimiting character
into the result buffer.

**Note**

When termios is changed from non-canonical to canonical mode and the
read buffer contains data, [`n_tty_set_termios()`](#c-n_tty_set_termios) simulates an EOF push (as if
C-d were input) _without_ the `DISABLED_CHAR` in the buffer. This causes data
already processed as input to be immediately available as input although a
newline has not been received.

- Locking:
  * called under the `atomic_read_lock` mutex
  * [`n_tty_read()`](#c-n_tty_read)/consumer path:
    caller holds non-exclusive `termios_rwsem`;
    read_tail published

#### <a id="c-job_control"></a>`job_control()`

```c
int job_control(struct tty_struct *tty, struct file *file)
```

check job control

**Parameters**

- `struct tty_struct *tty`: tty
- `struct file *file`: file handle

**Description**

Perform job control management checks on this **file**/**tty** descriptor and if
appropriate send any needed signals and return a negative error code if
action should be taken.

- Locking:
  * redirected write test is safe
  * current->signal->tty check is safe
  * ctrl.lock to safely reference **tty->ctrl.pgrp**

#### <a id="c-n_tty_read"></a>`n_tty_read()`

```c
ssize_t n_tty_read(struct tty_struct *tty, struct file *file, u8 *kbuf, size_t nr, void **cookie, unsigned long offset)
```

read function for tty

**Parameters**

- `struct tty_struct *tty`: tty device
- `struct file *file`: file object
- `u8 *kbuf`: kernelspace buffer pointer
- `size_t nr`: size of I/O
- `void **cookie`: if non-`NULL`, this is a continuation read
- `unsigned long offset`: where to continue reading from (unused in n_tty)

**Description**

Perform reads for the line discipline. We are guaranteed that the line
discipline will not be closed under us but we may get multiple parallel
readers and must handle this ourselves. We may also get a hangup. Always
called in user context, may sleep.

This code must be sure never to sleep through a hangup.

- Locking: [`n_tty_read()`](#c-n_tty_read)/consumer path:
  claims non-exclusive termios_rwsem;
  publishes read_tail

#### <a id="c-n_tty_write"></a>`n_tty_write()`

```c
ssize_t n_tty_write(struct tty_struct *tty, struct file *file, const u8 *buf, size_t nr)
```

write function for tty

**Parameters**

- `struct tty_struct *tty`: tty device
- `struct file *file`: file object
- `const u8 *buf`: userspace buffer pointer
- `size_t nr`: size of I/O

**Description**

Write function of the terminal device. This is serialized with respect to
other write callers but not to termios changes, reads and other such events.
Since the receive code will echo characters, thus calling driver write
methods, the `output_lock` is used in the output processing functions called
here as well as in the echo processing function to protect the column state
and space left in the buffer.

This code must be sure never to sleep through a hangup.

- Locking: output_lock to protect column state and space left

  (note that the process_output*() functions take this lock themselves)

#### <a id="c-n_tty_poll"></a>`n_tty_poll()`

```c
__poll_t n_tty_poll(struct tty_struct *tty, struct file *file, poll_table *wait)
```

poll method for N_TTY

**Parameters**

- `struct tty_struct *tty`: terminal device
- `struct file *file`: file accessing it
- `poll_table *wait`: poll table

**Description**

Called when the line discipline is asked to `poll()` for data or for special
events. This code is not serialized with respect to other events save
open/close.

This code must be sure never to sleep through a hangup.

Locking: called without the kernel lock held -- fine.

---

# TTY Buffer

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Flip Buffer Management

<a id="rst-tty-buffer"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



Here, we document functions for taking care of tty buffer and their flipping. Drivers are supposed to fill the buffer by one of those functions below and then flip the buffer, so that the data are passed to [line discipline](</kernel/hardware/driver-api/tty/tty-ldisc.md>) for further processing.

<a id="rst-flip-buffer-management"></a>

## Flip Buffer Management


#### <a id="c-tty_prepare_flip_string"></a>`tty_prepare_flip_string()`

```c
size_t tty_prepare_flip_string(struct tty_port *port, u8 **chars, size_t size)
```

make room for characters

**Parameters**

- `struct tty_port *port`: tty port
- `u8 **chars`: return pointer for character write area
- `size_t size`: desired size

**Description**

Prepare a block of space in the buffer for data.

This is used for drivers that need their own block copy routines into the
buffer. There is no guarantee the buffer is a DMA target!

**Return**

the length available and buffer pointer (**chars**) to the space which
is now allocated and accounted for as ready for normal characters.

#### <a id="c-tty_ldisc_receive_buf"></a>`tty_ldisc_receive_buf()`

```c
size_t tty_ldisc_receive_buf(struct tty_ldisc *ld, const u8 *p, const u8 *f, size_t count)
```

forward data to line discipline

**Parameters**

- `struct tty_ldisc *ld`: line discipline to process input
- `const u8 *p`: char buffer
- `const u8 *f`: `TTY_NORMAL`, `TTY_BREAK`, etc. flags buffer
- `size_t count`: number of bytes to process

**Description**

Callers other than [`flush_to_ldisc()`](#c-flush_to_ldisc) need to exclude the kworker from
concurrent use of the line discipline, see `paste_selection()`.

**Return**

the number of bytes processed.

#### <a id="c-tty_flip_buffer_push"></a>`tty_flip_buffer_push()`

```c
void tty_flip_buffer_push(struct tty_port *port)
```

push terminal buffers

**Parameters**

- `struct tty_port *port`: tty port to push

**Description**

Queue a push of the terminal flip buffers to the line discipline. Can be
called from IRQ/atomic context.

In the event of the queue being busy for flipping the work will be held off
and retried later.



#### <a id="c-tty_insert_flip_string_fixed_flag"></a>`tty_insert_flip_string_fixed_flag()`

```c
size_t tty_insert_flip_string_fixed_flag(struct tty_port *port, const u8 *chars, u8 flag, size_t size)
```

add characters to the tty buffer

**Parameters**

- `struct tty_port *port`: tty port
- `const u8 *chars`: characters
- `u8 flag`: flag value for each character
- `size_t size`: size

**Description**

Queue a series of bytes to the tty buffering. All the characters passed are
marked with the supplied flag.

**Return**

the number added.

#### <a id="c-tty_insert_flip_string_flags"></a>`tty_insert_flip_string_flags()`

```c
size_t tty_insert_flip_string_flags(struct tty_port *port, const u8 *chars, const u8 *flags, size_t size)
```

add characters to the tty buffer

**Parameters**

- `struct tty_port *port`: tty port
- `const u8 *chars`: characters
- `const u8 *flags`: flag bytes
- `size_t size`: size

**Description**

Queue a series of bytes to the tty buffering. For each character the flags
array indicates the status of the character.

**Return**

the number added.

#### <a id="c-tty_insert_flip_char"></a>`tty_insert_flip_char()`

```c
size_t tty_insert_flip_char(struct tty_port *port, u8 ch, u8 flag)
```

add one character to the tty buffer

**Parameters**

- `struct tty_port *port`: tty port
- `u8 ch`: character
- `u8 flag`: flag byte

**Description**

Queue a single byte **ch** to the tty buffering, with an optional flag.


---

<a id="rst-other-functions"></a>

## Other Functions


#### <a id="c-tty_buffer_space_avail"></a>`tty_buffer_space_avail()`

```c
unsigned int tty_buffer_space_avail(struct tty_port *port)
```

return unused buffer space

**Parameters**

- `struct tty_port *port`: tty port owning the flip buffer

**Return**

the # of bytes which can be written by the driver without reaching
the buffer limit.

**Note**

this does not guarantee that memory is available to write the returned
\# of bytes (use [`tty_prepare_flip_string()`](#c-tty_prepare_flip_string) to pre-allocate if memory
guarantee is required).

#### <a id="c-tty_buffer_set_limit"></a>`tty_buffer_set_limit()`

```c
int tty_buffer_set_limit(struct tty_port *port, int limit)
```

change the tty buffer memory limit

**Parameters**

- `struct tty_port *port`: tty port to change
- `int limit`: memory limit to set

**Description**

Change the tty buffer memory limit.

Must be called before the other tty buffer functions are used.


---

<a id="rst-buffer-locking"></a>

## Buffer Locking

These are used only in special circumstances. Avoid them.


#### <a id="c-tty_buffer_lock_exclusive"></a>`tty_buffer_lock_exclusive()`

```c
void tty_buffer_lock_exclusive(struct tty_port *port)
```

gain exclusive access to buffer

**Parameters**

- `struct tty_port *port`: tty port owning the flip buffer

**Description**

Guarantees safe use of the [`tty_ldisc_ops.receive_buf()`](/kernel/hardware/driver-api/tty/tty-ldisc.md#c-struct-tty_ldisc_ops) method by excluding
the buffer work and any pending flush from using the flip buffer. Data can
continue to be added concurrently to the flip buffer from the driver side.

See also [`tty_buffer_unlock_exclusive()`](#c-tty_buffer_unlock_exclusive).

#### <a id="c-tty_buffer_unlock_exclusive"></a>`tty_buffer_unlock_exclusive()`

```c
void tty_buffer_unlock_exclusive(struct tty_port *port)
```

release exclusive access

**Parameters**

- `struct tty_port *port`: tty port owning the flip buffer

**Description**

The buffer work is restarted if there is data in the flip buffer.

See also [`tty_buffer_lock_exclusive()`](#c-tty_buffer_lock_exclusive).


---

<a id="rst-internal-functions"></a>

## Internal Functions


#### <a id="c-tty_buffer_free_all"></a>`tty_buffer_free_all()`

```c
void tty_buffer_free_all(struct tty_port *port)
```

free buffers used by a tty

**Parameters**

- `struct tty_port *port`: tty port to free from

**Description**

Remove all the buffers pending on a tty whether queued with data or in the
free ring. Must be called when the tty is no longer in use.

#### <a id="c-tty_buffer_alloc"></a>`tty_buffer_alloc()`

```c
struct tty_buffer * tty_buffer_alloc(struct tty_port *port, size_t size)
```

allocate a tty buffer

**Parameters**

- `struct tty_port *port`: tty port
- `size_t size`: desired size (characters)

**Description**

Allocate a new tty buffer to hold the desired number of characters. We
round our buffers off in 256 character chunks to get better allocation
behaviour.

**Return**

`NULL` if out of memory or the allocation would exceed the per
device queue.

#### <a id="c-tty_buffer_free"></a>`tty_buffer_free()`

```c
void tty_buffer_free(struct tty_port *port, struct tty_buffer *b)
```

free a tty buffer

**Parameters**

- `struct tty_port *port`: tty port owning the buffer
- `struct tty_buffer *b`: the buffer to free

**Description**

Free a tty buffer, or add it to the free list according to our internal
strategy.

#### <a id="c-tty_buffer_flush"></a>`tty_buffer_flush()`

```c
void tty_buffer_flush(struct tty_struct *tty, struct tty_ldisc *ld)
```

flush full tty buffers

**Parameters**

- `struct tty_struct *tty`: tty to flush
- `struct tty_ldisc *ld`: optional ldisc ptr (must be referenced)

**Description**

Flush all the buffers containing receive data. If **ld** != `NULL`, flush the
ldisc input buffer.

Locking: takes buffer lock to ensure single-threaded flip buffer 'consumer'.

#### <a id="c-__tty_buffer_request_room"></a>`__tty_buffer_request_room()`

```c
int __tty_buffer_request_room(struct tty_port *port, size_t size, bool flags)
```

grow tty buffer if needed

**Parameters**

- `struct tty_port *port`: tty port
- `size_t size`: size desired
- `bool flags`: buffer has to store flags along character data

**Description**

Make at least **size** bytes of linear space available for the tty buffer.

Will change over to a new buffer if the current buffer is encoded as
`TTY_NORMAL` (so has no flags buffer) and the new buffer requires a flags
buffer.

**Return**

the size we managed to find.

#### <a id="c-flush_to_ldisc"></a>`flush_to_ldisc()`

```c
void flush_to_ldisc(struct work_struct *work)
```

flush data from buffer to ldisc

**Parameters**

- `struct work_struct *work`: tty structure passed from work queue.

**Description**

This routine is called out of the software interrupt to flush data from the
buffer chain to the line discipline.

The `receive_buf()` method is single threaded for each tty instance.

Locking: takes buffer lock to ensure single-threaded flip buffer 'consumer'.

#### <a id="c-tty_insert_flip_string_and_push_buffer"></a>`tty_insert_flip_string_and_push_buffer()`

```c
int tty_insert_flip_string_and_push_buffer(struct tty_port *port, const u8 *chars, size_t size)
```

add characters to the tty buffer and push

**Parameters**

- `struct tty_port *port`: tty port
- `const u8 *chars`: characters
- `size_t size`: size

**Description**

The function combines `tty_insert_flip_string()` and [`tty_flip_buffer_push()`](#c-tty_flip_buffer_push)
with the exception of properly holding the **port->lock**.

To be used only internally (by pty currently).

**Return**

the number added.

#### <a id="c-tty_buffer_init"></a>`tty_buffer_init()`

```c
void tty_buffer_init(struct tty_port *port)
```

prepare a tty buffer structure

**Parameters**

- `struct tty_port *port`: tty port to initialise

**Description**

Set up the initial state of the buffer management for a tty device. Must be
called before the other tty buffer functions are used.

---

# TTY Driver and TTY Operations

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Allocation

<a id="rst-tty-driver-and-tty-operations"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



<a id="rst-allocation"></a>

## Allocation

The first thing a driver needs to do is to allocate a struct tty_driver. This is done by tty_alloc_driver() (or \__tty_alloc_driver()). Next, the newly allocated structure is filled with information. See [TTY Driver Reference](<#rst-tty-driver-reference>) at the end of this document on what actually shall be filled in.

The allocation routines expect a number of devices the driver can handle at most and flags. Flags are those starting `TTY_DRIVER_` listed and described in [TTY Driver Flags](<#rst-tty-driver-flags>) below.

When the driver is about to be freed, tty_driver_kref_put() is called on that. It will decrements the reference count and if it reaches zero, the driver is freed.

For reference, both allocation and deallocation functions are explained here in detail:


#### <a id="c-tty_alloc_driver"></a>`tty_alloc_driver()`

```c
tty_alloc_driver(lines, flags)
```

allocate tty driver

**Parameters**

- `lines`: count of lines this driver can handle at most
- `flags`: some of enum tty_driver_flag, will be set in driver->flags

**Return**

struct tty_driver or a PTR-encoded error (use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) and friends).



#### <a id="c-__tty_alloc_driver"></a>`__tty_alloc_driver()`

```c
struct tty_driver * __tty_alloc_driver(unsigned int lines, struct module *owner, unsigned long flags)
```

allocate tty driver

**Parameters**

- `unsigned int lines`: count of lines this driver can handle at most
- `struct module *owner`: module which is responsible for this driver
- `unsigned long flags`: some of enum tty_driver_flag, will be set in driver->flags

**Description**

This should not be called directly, [`tty_alloc_driver()`](#c-tty_alloc_driver) should be used
instead.

**Return**

struct tty_driver or a PTR-encoded error (use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) and friends).

#### <a id="c-tty_driver_kref_put"></a>`tty_driver_kref_put()`

```c
void tty_driver_kref_put(struct tty_driver *driver)
```

drop a reference to a tty driver

**Parameters**

- `struct tty_driver *driver`: driver of which to drop the reference

**Description**

The final put will destroy and free up the driver.


<a id="rst-tty-driver-flags"></a>

### TTY Driver Flags

Here comes the documentation of flags accepted by tty_alloc_driver() (or \__tty_alloc_driver()):


#### <a id="c-enum-tty_driver_flag"></a>`enum tty_driver_flag`

- TTY Driver Flags

**Constants**

- `TTY_DRIVER_INSTALLED`: Whether this driver was succesfully installed. This is a tty internal
  flag. Do not touch.
- `TTY_DRIVER_RESET_TERMIOS`: Requests the tty layer to reset the termios setting when the last
  process has closed the device. Used for PTYs, in particular.
- `TTY_DRIVER_REAL_RAW`: Indicates that the driver will guarantee not to set any special
  character handling flags if this is set for the tty:
- `TTY_DRIVER_DYNAMIC_DEV`: The individual tty devices need to be registered with a call to
  [`tty_register_device()`](#c-tty_register_device) when the device is found in the system and
  unregistered with a call to [`tty_unregister_device()`](#c-tty_unregister_device) so the devices will
  be show up properly in sysfs.  If not set, all [`tty_driver.num`](#c-struct-tty_driver) entries
  will be created by the tty core in sysfs when [`tty_register_driver()`](#c-tty_register_driver) is
  called.  This is to be used by drivers that have tty devices that can
  appear and disappear while the main tty driver is registered with the
  tty core.
- `TTY_DRIVER_DEVPTS_MEM`: Don't use the standard arrays ([`tty_driver.ttys`](#c-struct-tty_driver) and
  [`tty_driver.termios`](#c-struct-tty_driver)), instead use dynamic memory keyed through the
  devpts filesystem. This is only applicable to the PTY driver.
- `TTY_DRIVER_HARDWARE_BREAK`: Hardware handles break signals. Pass the requested timeout to the
  [`tty_operations.break_ctl`](#c-struct-tty_operations) instead of using a simple on/off interface.
- `TTY_DRIVER_DYNAMIC_ALLOC`: Do not allocate structures which are needed per line for this driver
  ([`tty_driver.ports`](#c-struct-tty_driver)) as it would waste memory. The driver will take
  care. This is only applicable to the PTY driver.
- `TTY_DRIVER_UNNUMBERED_NODE`: Do not create numbered `/dev` nodes. For example, create
  `/dev/ttyprintk` and not `/dev/ttyprintk0`. Applicable only when a
  driver for a single tty device is being allocated.

**Description**

These are flags passed to [`tty_alloc_driver()`](#c-tty_alloc_driver).

`(IGNBRK || (!BRKINT && !PARMRK)) && (IGNPAR || !INPCK)`

That is, if there is no reason for the driver to
send notifications of parity and break characters up to the line
driver, it won't do so.  This allows the line driver to optimize for
this case if this flag is set.  (Note that there is also a promise, if
the above case is true, not to signal overruns, either.)


---

<a id="rst-registration"></a>

## Registration

When a struct tty_driver is allocated and filled in, it can be registered using tty_register_driver(). It is recommended to pass `TTY_DRIVER_DYNAMIC_DEV` in flags of tty_alloc_driver(). If it is not passed, *all* devices are also registered during tty_register_driver() and the following paragraph of registering devices can be skipped for such drivers. However, the struct tty_port part in [Registering Devices](<#rst-registering-devices>) is still relevant there.


#### <a id="c-tty_register_driver"></a>`tty_register_driver()`

```c
int tty_register_driver(struct tty_driver *driver)
```

register a tty driver

**Parameters**

- `struct tty_driver *driver`: driver to register

**Description**

Called by a tty driver to register itself.

#### <a id="c-tty_unregister_driver"></a>`tty_unregister_driver()`

```c
void tty_unregister_driver(struct tty_driver *driver)
```

unregister a tty driver

**Parameters**

- `struct tty_driver *driver`: driver to unregister

**Description**

Called by a tty driver to unregister itself.


<a id="rst-registering-devices"></a>

### Registering Devices

Every TTY device shall be backed by a struct tty_port. Usually, TTY drivers embed tty_port into device's private structures. Further details about handling tty_port can be found in [TTY Port](</kernel/hardware/driver-api/tty/tty-port.md>). The driver is also recommended to use tty_port's reference counting by tty_port_get() and tty_port_put(). The final put is supposed to free the tty_port including the device's private struct.

Unless `TTY_DRIVER_DYNAMIC_DEV` was passed as flags to tty_alloc_driver(), TTY driver is supposed to register every device discovered in the system (the latter is preferred). This is performed by tty_register_device(). Or by tty_register_device_attr() if the driver wants to expose some information through struct attribute_group. Both of them register `index`'th device and upon return, the device can be opened. There are also preferred tty_port variants described in [Linking Devices to Ports](<#rst-linking-devices-to-ports>) later. It is up to driver to manage free indices and choosing the right one. The TTY layer only refuses to register more devices than passed to tty_alloc_driver().

When the device is opened, the TTY layer allocates struct tty_struct and starts calling operations from `tty_driver.ops`, see [TTY Operations Reference](<#rst-tty-operations-reference>).

The registration routines are documented as follows:


#### <a id="c-tty_register_device"></a>`tty_register_device()`

```c
struct device * tty_register_device(struct tty_driver *driver, unsigned index, struct device *device)
```

register a tty device

**Parameters**

- `struct tty_driver *driver`: the tty driver that describes the tty device
- `unsigned index`: the index in the tty driver for this tty device
- `struct device *device`: a struct device that is associated with this tty device.
  This field is optional, if there is no known struct device
  for this tty device it can be set to NULL safely.

**Description**

This call is required to be made to register an individual tty device
if the tty driver's flags have the `TTY_DRIVER_DYNAMIC_DEV` bit set.  If
that bit is not set, this function should not be called by a tty
driver.

Locking: ??

**Return**

A pointer to the struct device for this tty device (or
ERR_PTR(-EFOO) on error).

#### <a id="c-tty_register_device_attr"></a>`tty_register_device_attr()`

```c
struct device * tty_register_device_attr(struct tty_driver *driver, unsigned index, struct device *device, void *drvdata, const struct attribute_group **attr_grp)
```

register a tty device

**Parameters**

- `struct tty_driver *driver`: the tty driver that describes the tty device
- `unsigned index`: the index in the tty driver for this tty device
- `struct device *device`: a struct device that is associated with this tty device.
  This field is optional, if there is no known struct device
  for this tty device it can be set to `NULL` safely.
- `void *drvdata`: Driver data to be set to device.
- `const struct attribute_group **attr_grp`: Attribute group to be set on device.

**Description**

This call is required to be made to register an individual tty device if the
tty driver's flags have the `TTY_DRIVER_DYNAMIC_DEV` bit set. If that bit is
not set, this function should not be called by a tty driver.

Locking: ??

**Return**

A pointer to the struct device for this tty device (or
ERR_PTR(-EFOO) on error).

#### <a id="c-tty_unregister_device"></a>`tty_unregister_device()`

```c
void tty_unregister_device(struct tty_driver *driver, unsigned index)
```

unregister a tty device

**Parameters**

- `struct tty_driver *driver`: the tty driver that describes the tty device
- `unsigned index`: the index in the tty driver for this tty device

**Description**

If a tty device is registered with a call to [`tty_register_device()`](#c-tty_register_device) then
this function must be called when the tty device is gone.

Locking: ??


---

<a id="rst-linking-devices-to-ports"></a>

### Linking Devices to Ports

As stated earlier, every TTY device shall have a struct tty_port assigned to it. It must be known to the TTY layer at `tty_driver.ops.install()` at latest.  There are few helpers to *link* the two. Ideally, the driver uses tty_port_register_device() or tty_port_register_device_attr() instead of tty_register_device() and tty_register_device_attr() at the registration time. This way, the driver needs not care about linking later on.

If that is not possible, the driver still can link the tty_port to a specific index *before* the actual registration by tty_port_link_device(). If it still does not fit, tty_port_install() can be used from the `tty_driver.ops.install` hook as a last resort. The last one is dedicated mostly for in-memory devices like PTY where tty_ports are allocated on demand.

The linking routines are documented here:


#### <a id="c-tty_port_link_device"></a>`tty_port_link_device()`

```c
void tty_port_link_device(struct tty_port *port, struct tty_driver *driver, unsigned index)
```

link tty and tty_port

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_driver *driver`: tty_driver for this device
- `unsigned index`: index of the tty

**Description**

Provide the tty layer with a link from a tty (specified by **index**) to a
tty_port (**port**). Use this only if neither [`tty_port_register_device()`](#c-tty_port_register_device) nor
[`tty_port_install()`](/kernel/hardware/driver-api/tty/tty-port.md#c-tty_port_install) is used in the driver. If used, this has to be called
before [`tty_register_driver()`](#c-tty_register_driver).

#### <a id="c-tty_port_register_device"></a>`tty_port_register_device()`

```c
struct device * tty_port_register_device(struct tty_port *port, struct tty_driver *driver, unsigned index, struct device *device)
```

register tty device

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_driver *driver`: tty_driver for this device
- `unsigned index`: index of the tty
- `struct device *device`: parent if exists, otherwise NULL

**Description**

It is the same as [`tty_register_device()`](#c-tty_register_device) except the provided **port** is linked
to a concrete tty specified by **index**. Use this or [`tty_port_install()`](/kernel/hardware/driver-api/tty/tty-port.md#c-tty_port_install) (or
both). Call [`tty_port_link_device()`](#c-tty_port_link_device) as a last resort.

#### <a id="c-tty_port_register_device_attr"></a>`tty_port_register_device_attr()`

```c
struct device * tty_port_register_device_attr(struct tty_port *port, struct tty_driver *driver, unsigned index, struct device *device, void *drvdata, const struct attribute_group **attr_grp)
```

register tty device

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_driver *driver`: tty_driver for this device
- `unsigned index`: index of the tty
- `struct device *device`: parent if exists, otherwise NULL
- `void *drvdata`: Driver data to be set to device.
- `const struct attribute_group **attr_grp`: Attribute group to be set on device.

**Description**

It is the same as [`tty_register_device_attr()`](#c-tty_register_device_attr) except the provided **port** is
linked to a concrete tty specified by **index**. Use this or [`tty_port_install()`](/kernel/hardware/driver-api/tty/tty-port.md#c-tty_port_install)
(or both). Call [`tty_port_link_device()`](#c-tty_port_link_device) as a last resort.


---

<a id="rst-tty-driver-reference"></a>

## TTY Driver Reference

All members of struct tty_driver are documented here. The required members are noted at the end. struct tty_operations are documented next.


#### <a id="c-struct-tty_driver"></a>`struct tty_driver`

- driver for TTY devices

**Definition**

```c
struct tty_driver {
    struct kref kref;
    struct cdev **cdevs;
    struct module   *owner;
    const char      *driver_name;
    const char      *name;
    int name_base;
    int major;
    int minor_start;
    unsigned int    num;
    enum tty_driver_type type;
    enum tty_driver_subtype subtype;
    struct ktermios init_termios;
    unsigned long   flags;
    struct proc_dir_entry *proc_entry;
    struct tty_driver *other;
    struct tty_struct **ttys;
    struct tty_port **ports;
    struct ktermios **termios;
    void *driver_state;
    const struct tty_operations *ops;
    struct list_head tty_drivers;
};
```

**Members**

- `kref`: reference counting. Reaching zero frees all the internals and the
  driver.
- `cdevs`: allocated/registered character /dev devices
- `owner`: modules owning this driver. Used drivers cannot be rmmod'ed.
  Automatically set by [`tty_alloc_driver()`](#c-tty_alloc_driver).
- `driver_name`: name of the driver used in /proc/tty
- `name`: used for constructing /dev node name
- `name_base`: used as a number base for constructing /dev node name
- `major`: major /dev device number (zero for autoassignment)
- `minor_start`: the first minor /dev device number
- `num`: number of devices allocated
- `type`: type of tty driver (enum tty_driver_type)
- `subtype`: subtype of tty driver (enum tty_driver_subtype)
- `init_termios`: termios to set to each tty initially (e.g. `tty_std_termios`)
- `flags`: tty driver flags (`TTY_DRIVER_`)
- `proc_entry`: proc fs entry, used internally
- `other`: driver of the linked tty; only used for the PTY driver
- `ttys`: array of active [`struct tty_struct`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct), set by [`tty_standard_install()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-tty_standard_install)
- `ports`: array of [`struct tty_port`](/kernel/hardware/driver-api/tty/tty-port.md#c-struct-tty_port); can be set during initialization by
  [`tty_port_link_device()`](#c-tty_port_link_device) and similar
- `termios`: storage for termios at each TTY close for the next open
- `driver_state`: pointer to driver's arbitrary data
- `ops`: driver hooks for TTYs. Set them using `tty_set_operations()`. Use [`struct tty_port`](/kernel/hardware/driver-api/tty/tty-port.md#c-struct-tty_port) helpers in them as much as possible.
- `tty_drivers`: used internally to link tty_drivers together

**Description**

The usual handling of [`struct tty_driver`](#c-struct-tty_driver) is to allocate it by
[`tty_alloc_driver()`](#c-tty_alloc_driver), set up all the necessary members, and register it by
[`tty_register_driver()`](#c-tty_register_driver). At last, the driver is torn down by calling
[`tty_unregister_driver()`](#c-tty_unregister_driver) followed by [`tty_driver_kref_put()`](#c-tty_driver_kref_put).

The fields required to be set before calling [`tty_register_driver()`](#c-tty_register_driver) include
**driver_name**, **name**, **type**, **subtype**, **init_termios**, and **ops**.


---

<a id="rst-tty-operations-reference"></a>

## TTY Operations Reference

When a TTY is registered, these driver hooks can be invoked by the TTY layer:


#### <a id="c-struct-tty_operations"></a>`struct tty_operations`

- interface between driver and tty

**Definition**

```c
struct tty_operations {
        struct tty_struct * (*lookup)(struct tty_driver *driver, struct file *filp, int idx);
        int (*install)(struct tty_driver *driver, struct tty_struct *tty);
        void (*remove)(struct tty_driver *driver, struct tty_struct *tty);
        int (*open)(struct tty_struct * tty, struct file * filp);
        void (*close)(struct tty_struct * tty, struct file * filp);
        void (*shutdown)(struct tty_struct *tty);
        void (*cleanup)(struct tty_struct *tty);
        ssize_t (*write)(struct tty_struct *tty, const u8 *buf, size_t count);
        int (*put_char)(struct tty_struct *tty, u8 ch);
        void (*flush_chars)(struct tty_struct *tty);
        unsigned int (*write_room)(struct tty_struct *tty);
        unsigned int (*chars_in_buffer)(struct tty_struct *tty);
        int (*ioctl)(struct tty_struct *tty, unsigned int cmd, unsigned long arg);
        long (*compat_ioctl)(struct tty_struct *tty, unsigned int cmd, unsigned long arg);
        void (*set_termios)(struct tty_struct *tty, const struct ktermios *old);
        void (*throttle)(struct tty_struct * tty);
        void (*unthrottle)(struct tty_struct * tty);
        void (*stop)(struct tty_struct *tty);
        void (*start)(struct tty_struct *tty);
        void (*hangup)(struct tty_struct *tty);
        int (*break_ctl)(struct tty_struct *tty, int state);
        void (*flush_buffer)(struct tty_struct *tty);
        int (*ldisc_ok)(struct tty_struct *tty, int ldisc);
        void (*set_ldisc)(struct tty_struct *tty);
        void (*wait_until_sent)(struct tty_struct *tty, int timeout);
        void (*send_xchar)(struct tty_struct *tty, u8 ch);
        int (*tiocmget)(struct tty_struct *tty);
        int (*tiocmset)(struct tty_struct *tty, unsigned int set, unsigned int clear);
        int (*resize)(struct tty_struct *tty, struct winsize *ws);
        int (*get_icount)(struct tty_struct *tty, struct serial_icounter_struct *icount);
        int (*get_serial)(struct tty_struct *tty, struct serial_struct *p);
        int (*set_serial)(struct tty_struct *tty, struct serial_struct *p);
        void (*show_fdinfo)(struct tty_struct *tty, struct seq_file *m);
    #ifdef CONFIG_CONSOLE_POLL;
        int (*poll_init)(struct tty_driver *driver, int line, char *options);
        int (*poll_get_char)(struct tty_driver *driver, int line);
        void (*poll_put_char)(struct tty_driver *driver, int line, char ch);
    #endif;
        int (*proc_show)(struct seq_file *m, void *driver);
};
```

**Members**

- `lookup`: `struct tty_struct *()(struct tty_driver *self, struct file *, int idx)`
- `install`: `int ()(struct tty_driver *self, struct tty_struct *tty)`
- `remove`: `void ()(struct tty_driver *self, struct tty_struct *tty)`
- `open`: `int ()(struct tty_struct *tty, struct file *)`
- `close`: `void ()(struct tty_struct *tty, struct file *)`
- `shutdown`: `void ()(struct tty_struct *tty)`
- `cleanup`: `void ()(struct tty_struct *tty)`
- `write`: `ssize_t ()(struct tty_struct *tty, const u8 *buf, size_t count)`
- `put_char`: `int ()(struct tty_struct *tty, u8 ch)`
- `flush_chars`: `void ()(struct tty_struct *tty)`
- `write_room`: `unsigned int ()(struct tty_struct *tty)`
- `chars_in_buffer`: `unsigned int ()(struct tty_struct *tty)`
- `ioctl`: `int ()(struct tty_struct *tty, unsigned int cmd, unsigned long arg)`
- `compat_ioctl`: `long ()(struct tty_struct *tty, unsigned int cmd, unsigned long arg)`
- `set_termios`: `void ()(struct tty_struct *tty, const struct ktermios *old)`
- `throttle`: `void ()(struct tty_struct *tty)`
- `unthrottle`: `void ()(struct tty_struct *tty)`
- `stop`: `void ()(struct tty_struct *tty)`
- `start`: `void ()(struct tty_struct *tty)`
- `hangup`: `void ()(struct tty_struct *tty)`
- `break_ctl`: `int ()(struct tty_struct *tty, int state)`
- `flush_buffer`: `void ()(struct tty_struct *tty)`
- `ldisc_ok`: `int ()(struct tty_struct *tty, int ldisc)`
- `set_ldisc`: `void ()(struct tty_struct *tty)`
- `wait_until_sent`: `void ()(struct tty_struct *tty, int timeout)`
- `send_xchar`: `void ()(struct tty_struct *tty, u8 ch)`
- `tiocmget`: `int ()(struct tty_struct *tty)`
- `tiocmset`: `int ()(struct tty_struct *tty, unsigned int set, unsigned int clear)`
- `resize`: `int ()(struct tty_struct *tty, struct winsize *ws)`
- `get_icount`: `int ()(struct tty_struct *tty, struct serial_icounter *icount)`
- `get_serial`: `int ()(struct tty_struct *tty, struct serial_struct *p)`
- `set_serial`: `int ()(struct tty_struct *tty, struct serial_struct *p)`
- `show_fdinfo`: `void ()(struct tty_struct *tty, struct seq_file *m)`
- `poll_init`: `int ()(struct tty_driver *driver, int line, char *options)`
- `poll_get_char`: `int ()(struct tty_driver *driver, int line)`
- `poll_put_char`: `void ()(struct tty_driver *driver, int line, char ch)`
- `proc_show`: `int ()(struct seq_file *m, void *driver)`

**Description**

Return the tty device corresponding to **idx**, `NULL` if there is not
one currently in use and an `ERR_PTR` value on error. Called under
`tty_mutex` (for now!)

Optional method. Default behaviour is to use the **self->ttys** array.

Install a new **tty** into the **self**'s internal tables. Used in
conjunction with **lookup** and **remove** methods.

Optional method. Default behaviour is to use the **self->ttys** array.

Remove a closed **tty** from the **self**'s internal tables. Used in
conjunction with **lookup** and **remove** methods.

Optional method. Default behaviour is to use the **self->ttys** array.

This routine is called when a particular **tty** device is opened. This
routine is mandatory; if this routine is not filled in, the attempted
open will fail with `ENODEV`.

Required method. Called with tty lock held. May sleep.

This routine is called when a particular **tty** device is closed. At the
point of return from this call the driver must make no further ldisc
calls of any kind.

Remark: called even if the corresponding **open()** failed.

Required method. Called with tty lock held. May sleep.

This routine is called under the tty lock when a particular **tty** device
is closed for the last time. It executes before the **tty** resources
are freed so may execute while another function holds a **tty** kref.

This routine is called asynchronously when a particular **tty** device
is closed for the last time freeing up the resources. This is
actually the second part of shutdown for routines that might sleep.

This routine is called by the kernel to write a series (**count**) of
characters (**buf**) to the **tty** device. The characters may come from
user space or kernel space.  This routine will return the
number of characters actually accepted for writing.

May occur in parallel in special cases. Because this includes panic
paths drivers generally shouldn't try and do clever locking here.

Optional: Required for writable devices. May not sleep.

This routine is called by the kernel to write a single character **ch** to
the **tty** device. If the kernel uses this routine, it must call the
**flush_chars()** routine (if defined) when it is done stuffing characters
into the driver. If there is no room in the queue, the character is
ignored.

Optional: Kernel will use the **write** method if not provided. Do not
call this function directly, call [`tty_put_char()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-tty_put_char).

This routine is called by the kernel after it has written a
series of characters to the tty device using **put_char()**.

Optional. Do not call this function directly, call
`tty_driver_flush_chars()`.

This routine returns the numbers of characters the **tty** driver
will accept for queuing to be written.  This number is subject
to change as output buffers get emptied, or if the output flow
control is acted.

The ldisc is responsible for being intelligent about multi-threading of
write_room/write calls

Required if **write** method is provided else not needed. Do not call this
function directly, call [`tty_write_room()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_write_room)

This routine returns the number of characters in the device private
output queue. Used in [`tty_wait_until_sent()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_wait_until_sent) and for `poll()`
implementation.

Optional: if not provided, it is assumed there is no queue on the
device. Do not call this function directly, call [`tty_chars_in_buffer()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_chars_in_buffer).

This routine allows the **tty** driver to implement device-specific
ioctls. If the ioctl number passed in **cmd** is not recognized by the
driver, it should return `ENOIOCTLCMD`.

Optional.

Implement ioctl processing for 32 bit process on 64 bit system.

Optional.

This routine allows the **tty** driver to be notified when device's
termios settings have changed. New settings are in **tty->termios**.
Previous settings are passed in the **old** argument.

The API is defined such that the driver should return the actual modes
selected. This means that the driver is responsible for modifying any
bits in **tty->termios** it cannot fulfill to indicate the actual modes
being used.

Optional. Called under the **tty->termios_rwsem**. May sleep.

This routine allows the **tty** driver to decide if it can deal
with a particular **ldisc**.

Optional. Called under the **tty->ldisc_sem** and **tty->termios_rwsem**.

This routine allows the **tty** driver to be notified when the device's
line discipline is being changed. At the point this is done the
discipline is not yet usable.

Optional. Called under the **tty->ldisc_sem** and **tty->termios_rwsem**.

This routine notifies the **tty** driver that input buffers for the line
discipline are close to full, and it should somehow signal that no more
characters should be sent to the **tty**.

Serialization including with **unthrottle()** is the job of the ldisc
layer.

Optional: Always invoke via [`tty_throttle_safe()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_throttle_safe). Called under the
**tty->termios_rwsem**.

This routine notifies the **tty** driver that it should signal that
characters can now be sent to the **tty** without fear of overrunning the
input buffers of the line disciplines.

Optional. Always invoke via [`tty_unthrottle()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_unthrottle). Called under the
**tty->termios_rwsem**.

This routine notifies the **tty** driver that it should stop outputting
characters to the tty device.

Called with **tty->flow.lock** held. Serialized with **start()** method.

Optional. Always invoke via [`stop_tty()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-stop_tty).

This routine notifies the **tty** driver that it resumed sending
characters to the **tty** device.

Called with **tty->flow.lock** held. Serialized with `stop()` method.

Optional. Always invoke via [`start_tty()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-start_tty).

This routine notifies the **tty** driver that it should hang up the **tty**
device.

Optional. Called with tty lock held.

This optional routine requests the **tty** driver to turn on or off BREAK
status on the RS-232 port. If **state** is -1, then the BREAK status
should be turned on; if **state** is 0, then BREAK should be turned off.

If this routine is implemented, the high-level tty driver will handle
the following ioctls: `TCSBRK`, `TCSBRKP`, `TIOCSBRK`, `TIOCCBRK`.

If the driver sets `TTY_DRIVER_HARDWARE_BREAK` in [`tty_alloc_driver()`](#c-tty_alloc_driver),
then the interface will also be called with actual times and the
hardware is expected to do the delay work itself. 0 and -1 are still
used for on/off.

Optional: Required for `TCSBRK`/`BRKP`/etc. handling. May sleep.

This routine discards device private output buffer. Invoked on close,
hangup, to implement `TCOFLUSH` ioctl and similar.

Optional: if not provided, it is assumed there is no queue on the
device. Do not call this function directly, call
[`tty_driver_flush_buffer()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_driver_flush_buffer).

This routine waits until the device has written out all of the
characters in its transmitter FIFO. Or until **timeout** (in jiffies) is
reached.

Optional: If not provided, the device is assumed to have no FIFO.
Usually correct to invoke via [`tty_wait_until_sent()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_wait_until_sent). May sleep.

This routine is used to send a high-priority XON/XOFF character (**ch**)
to the **tty** device.

Optional: If not provided, then the **write** method is called under
the **tty->atomic_write_lock** to keep it serialized with the ldisc.

This routine is used to obtain the modem status bits from the **tty**
driver.

Optional: If not provided, then `ENOTTY` is returned from the `TIOCMGET`
ioctl. Do not call this function directly, call [`tty_tiocmget()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-tty_tiocmget).

This routine is used to set the modem status bits to the **tty** driver.
First, **clear** bits should be cleared, then **set** bits set.

Optional: If not provided, then `ENOTTY` is returned from the `TIOCMSET`
ioctl. Do not call this function directly, call [`tty_tiocmset()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-tty_tiocmset).

Called when a termios request is issued which changes the requested
terminal geometry to **ws**.

Optional: the default action is to update the termios structure
without error. This is usually the correct behaviour. Drivers should
not force errors here if they are not resizable objects (e.g. a serial
line). See [`tty_do_resize()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-tty_do_resize) if you need to wrap the standard method
in your own logic -- the usual case.

Called when the **tty** device receives a `TIOCGICOUNT` ioctl. Passed a
kernel structure **icount** to complete.

Optional: called only if provided, otherwise `ENOTTY` will be returned.

Called when the **tty** device receives a `TIOCGSERIAL` ioctl. Passed a
kernel structure **p** (`struct serial_struct`) to complete.

Optional: called only if provided, otherwise `ENOTTY` will be returned.
Do not call this function directly, call `tty_tiocgserial()`.

Called when the **tty** device receives a `TIOCSSERIAL` ioctl. Passed a
kernel structure **p** (`struct serial_struct`) to set the values from.

Optional: called only if provided, otherwise `ENOTTY` will be returned.
Do not call this function directly, call `tty_tiocsserial()`.

Called when the **tty** device file descriptor receives a fdinfo request
from VFS (to show in /proc/\<pid>/fdinfo/). **m** should be filled with
information.

Optional: called only if provided, otherwise nothing is written to **m**.
Do not call this function directly, call `tty_show_fdinfo()`.

kgdboc support (Documentation/process/debugging/kgdb.rst). This routine is
called to initialize the HW for later use by calling **poll_get_char** or
**poll_put_char**.

Optional: called only if provided, otherwise skipped as a non-polling
driver.

kgdboc support (see **poll_init**). **driver** should read a character from a
tty identified by **line** and return it.

Optional: called only if **poll_init** provided.

kgdboc support (see **poll_init**). **driver** should write character **ch** to
a tty identified by **line**.

Optional: called only if **poll_init** provided.

Driver **driver** (cast to [`struct tty_driver`](#c-struct-tty_driver)) can show additional info in
/proc/tty/driver/\<driver_name>. It is enough to fill in the information
into **m**.

Optional: called only if provided, otherwise no /proc entry created.

This structure defines the interface between the low-level tty driver and
the tty routines. These routines can be defined. Unless noted otherwise,
they are optional, and can be filled in with a `NULL` pointer.

---

# TTY Internals

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Kopen

<a id="rst-tty-internals"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



<a id="rst-kopen"></a>

## Kopen

These functions serve for opening a TTY from the kernelspace:


#### <a id="c-tty_kclose"></a>`tty_kclose()`

```c
void tty_kclose(struct tty_struct *tty)
```

closes tty opened by tty_kopen

**Parameters**

- `struct tty_struct *tty`: tty device

**Description**

Performs the final steps to release and free a tty device. It is the same as
[`tty_release_struct()`](#c-tty_release_struct) except that it also resets `TTY_PORT_KOPENED` flag on
**tty->port**.

#### <a id="c-tty_kopen_exclusive"></a>`tty_kopen_exclusive()`

```c
struct tty_struct * tty_kopen_exclusive(dev_t device)
```

open a tty device for kernel

**Parameters**

- `dev_t device`: dev_t of device to open

**Description**

Opens tty exclusively for kernel. Performs the driver lookup, makes sure
it's not already opened and performs the first-time tty initialization.

- Claims the global `tty_mutex` to serialize:
  * concurrent first-time tty initialization
  * concurrent tty driver removal w/ lookup
  * concurrent tty removal from driver table

**Return**

the locked initialized [`tty_struct`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct)

#### <a id="c-tty_kopen_shared"></a>`tty_kopen_shared()`

```c
struct tty_struct * tty_kopen_shared(dev_t device)
```

open a tty device for shared in-kernel use

**Parameters**

- `dev_t device`: dev_t of device to open

**Description**

Opens an already existing tty for in-kernel use. Compared to
[`tty_kopen_exclusive()`](#c-tty_kopen_exclusive) above it doesn't ensure to be the only user.

Locking: identical to `tty_kopen()` above.


---

<a id="rst-exported-internal-functions"></a>

## Exported Internal Functions


#### <a id="c-tty_dev_name_to_number"></a>`tty_dev_name_to_number()`

```c
int tty_dev_name_to_number(const char *name, dev_t *number)
```

return dev_t for device name

**Parameters**

- `const char *name`: user space name of device under /dev
- `dev_t *number`: pointer to dev_t that this function will populate

**Description**

This function converts device names like ttyS0 or ttyUSB1 into dev_t like
(4, 64) or (188, 1). If no corresponding driver is registered then the
function returns -`ENODEV`.

- Locking: this acquires tty_mutex to protect the tty_drivers list from

  being modified while we are traversing it, and makes sure to
  release it before exiting.

#### <a id="c-tty_release_struct"></a>`tty_release_struct()`

```c
void tty_release_struct(struct tty_struct *tty, int idx)
```

release a tty struct

**Parameters**

- `struct tty_struct *tty`: tty device
- `int idx`: index of the tty

**Description**

Performs the final steps to release and free a tty device. It is roughly the
reverse of [`tty_init_dev()`](#c-tty_init_dev).

#### <a id="c-tty_get_icount"></a>`tty_get_icount()`

```c
int tty_get_icount(struct tty_struct *tty, struct serial_icounter_struct *icount)
```

get tty statistics

**Parameters**

- `struct tty_struct *tty`: tty device
- `struct serial_icounter_struct *icount`: output parameter

**Description**

Gets a copy of the **tty**'s icount statistics.

Locking: none (up to the driver)


---

<a id="rst-internal-functions"></a>

## Internal Functions


#### <a id="c-free_tty_struct"></a>`free_tty_struct()`

```c
void free_tty_struct(struct tty_struct *tty)
```

free a disused tty

**Parameters**

- `struct tty_struct *tty`: tty struct to free

**Description**

Free the write buffers, tty queue and tty memory itself.

Locking: none. Must be called after tty is definitely unused

#### <a id="c-tty_free_file"></a>`tty_free_file()`

```c
void tty_free_file(struct file *file)
```

free file->private_data

**Parameters**

- `struct file *file`: to free private_data of

**Description**

This shall be used only for fail path handling when tty_add_file was not
called yet.

#### <a id="c-get_tty_driver"></a>`get_tty_driver()`

```c
struct tty_driver * get_tty_driver(dev_t device, int *index)
```

find device of a tty

**Parameters**

- `dev_t device`: device identifier
- `int *index`: returns the index of the tty

**Description**

This routine returns a tty driver structure, given a device number and also
passes back the index number.

Locking: caller must hold tty_mutex

#### <a id="c-tty_release_redirect"></a>`tty_release_redirect()`

```c
struct file * tty_release_redirect(struct tty_struct *tty)
```

Release a redirect on a pty if present

**Parameters**

- `struct tty_struct *tty`: tty device

**Description**

This is available to the pty code so if the master closes, if the slave is a
redirect it can release the redirect.

#### <a id="c-__tty_hangup"></a>`__tty_hangup()`

```c
void __tty_hangup(struct tty_struct *tty, int exit_session)
```

actual handler for hangup events

**Parameters**

- `struct tty_struct *tty`: tty device
- `int exit_session`: if non-zero, signal all foreground group processes

**Description**

This can be called by a "kworker" kernel thread. That is process synchronous
but doesn't hold any locks, so we need to make sure we have the appropriate
locks for what we're doing.

The hangup event clears any pending redirections onto the hung up device. It
ensures future writes will error and it does the needed line discipline
hangup and signal delivery. The tty object itself remains intact.

- Locking:
  * BTM

    * redirect lock for undoing redirection
    * file list lock for manipulating list of ttys
    * tty_ldiscs_lock from called functions
    * termios_rwsem resetting termios data
    * tasklist_lock to walk task list for hangup event

      * ->siglock to protect ->signal/->sighand

#### <a id="c-tty_vhangup_self"></a>`tty_vhangup_self()`

```c
void tty_vhangup_self(void)
```

process vhangup for own ctty

**Parameters**

- `void`: no arguments

**Description**

Perform a vhangup on the current controlling tty

#### <a id="c-tty_vhangup_session"></a>`tty_vhangup_session()`

```c
void tty_vhangup_session(struct tty_struct *tty)
```

hangup session leader exit

**Parameters**

- `struct tty_struct *tty`: tty to hangup

**Description**

The session leader is exiting and hanging up its controlling terminal.
Every process in the foreground process group is signalled `SIGHUP`.

We do this synchronously so that when the syscall returns the process is
complete. That guarantee is necessary for security reasons.

#### <a id="c-tty_read"></a>`tty_read()`

```c
ssize_t tty_read(struct kiocb *iocb, struct iov_iter *to)
```

read method for tty device files

**Parameters**

- `struct kiocb *iocb`: kernel I/O control block
- `struct iov_iter *to`: destination for the data read

**Description**

Perform the read system call function on this terminal device. Checks
for hung up devices before calling the line discipline method.

- Locking:
  Locks the line discipline internally while needed. Multiple read calls
  may be outstanding in parallel.

#### <a id="c-tty_write_message"></a>`tty_write_message()`

```c
void tty_write_message(struct tty_struct *tty, char *msg)
```

write a message to a certain tty, not just the console.

**Parameters**

- `struct tty_struct *tty`: the destination tty_struct
- `char *msg`: the message to write

**Description**

This is used for messages that need to be redirected to a specific tty. We
don't put it into the syslog queue right now maybe in the future if really
needed.

We must still hold the BTM and test the CLOSING flag for the moment.

This function is DEPRECATED, do not use in new code.

#### <a id="c-tty_write"></a>`tty_write()`

```c
ssize_t tty_write(struct kiocb *iocb, struct iov_iter *from)
```

write method for tty device file

**Parameters**

- `struct kiocb *iocb`: kernel I/O control block
- `struct iov_iter *from`: iov_iter with data to write

**Description**

Write data to a tty device via the line discipline.

- Locking:
  Locks the line discipline as required
  Writes to the tty driver are serialized by the atomic_write_lock
  and are then processed in chunks to the device. The line
  discipline write method will not be invoked in parallel for
  each device.

#### <a id="c-tty_send_xchar"></a>`tty_send_xchar()`

```c
int tty_send_xchar(struct tty_struct *tty, u8 ch)
```

send priority character

**Parameters**

- `struct tty_struct *tty`: the tty to send to
- `u8 ch`: xchar to send

**Description**

Send a high priority character to the tty even if stopped.

Locking: none for xchar method, write ordering for write method.

#### <a id="c-pty_line_name"></a>`pty_line_name()`

```c
void pty_line_name(struct tty_driver *driver, int index, char *p)
```

generate name for a pty

**Parameters**

- `struct tty_driver *driver`: the tty driver in use
- `int index`: the minor number
- `char *p`: output buffer of at least 6 bytes

**Description**

Generate a name from a **driver** reference and write it to the output buffer
**p**.

Locking: None

#### <a id="c-tty_line_name"></a>`tty_line_name()`

```c
ssize_t tty_line_name(struct tty_driver *driver, int index, char *p)
```

generate name for a tty

**Parameters**

- `struct tty_driver *driver`: the tty driver in use
- `int index`: the minor number
- `char *p`: output buffer of at least 7 bytes

**Description**

Generate a name from a **driver** reference and write it to the output buffer
**p**.

Locking: None

#### <a id="c-tty_driver_lookup_tty"></a>`tty_driver_lookup_tty()`

```c
struct tty_struct * tty_driver_lookup_tty(struct tty_driver *driver, struct file *file, int idx)
```

find an existing tty, if any

**Parameters**

- `struct tty_driver *driver`: the driver for the tty
- `struct file *file`: file object
- `int idx`: the minor number

**Return**

the tty, if found. If not found, return `NULL` or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) if the
driver `lookup()` method returns an error.

**Description**

Locking: tty_mutex must be held. If the tty is found, bump the tty kref.

#### <a id="c-tty_driver_install_tty"></a>`tty_driver_install_tty()`

```c
int tty_driver_install_tty(struct tty_driver *driver, struct tty_struct *tty)
```

install a tty entry in the driver

**Parameters**

- `struct tty_driver *driver`: the driver for the tty
- `struct tty_struct *tty`: the tty

**Description**

Install a tty object into the driver tables. The **tty->index** field will be
set by the time this is called. This method is responsible for ensuring any
need additional structures are allocated and configured.

Locking: tty_mutex for now

#### <a id="c-tty_driver_remove_tty"></a>`tty_driver_remove_tty()`

```c
void tty_driver_remove_tty(struct tty_driver *driver, struct tty_struct *tty)
```

remove a tty from the driver tables

**Parameters**

- `struct tty_driver *driver`: the driver for the tty
- `struct tty_struct *tty`: tty to remove

**Description**

Remove a tty object from the driver tables. The tty->index field will be set
by the time this is called.

Locking: tty_mutex for now

#### <a id="c-tty_reopen"></a>`tty_reopen()`

```c
int tty_reopen(struct tty_struct *tty)
```

fast re-open of an open tty

**Parameters**

- `struct tty_struct *tty`: the tty to open

**Description**

Re-opens on master ptys are not allowed and return -`EIO`.

Locking: Caller must hold tty_lock

**Return**

0 on success, -errno on error.

#### <a id="c-tty_init_dev"></a>`tty_init_dev()`

```c
struct tty_struct * tty_init_dev(struct tty_driver *driver, int idx)
```

initialise a tty device

**Parameters**

- `struct tty_driver *driver`: tty driver we are opening a device on
- `int idx`: device index

**Description**

Prepare a tty device. This may not be a "new" clean device but could also be
an active device. The pty drivers require special handling because of this.

- Locking:
  The function is called under the tty_mutex, which protects us from the
  tty struct or driver itself going away.

On exit the tty device has the line discipline attached and a reference
count of 1. If a pair was created for pty/tty use and the other was a pty
master then it too has a reference count of 1.

WSH 06/09/97: Rewritten to remove races and properly clean up after a failed
open. The new code protects the open with a mutex, so it's really quite
straightforward. The mutex locking can probably be relaxed for the (most
common) case of reopening a tty.

**Return**

new tty structure

#### <a id="c-tty_flush_works"></a>`tty_flush_works()`

```c
void tty_flush_works(struct tty_struct *tty)
```

flush all works of a tty/pty pair

**Parameters**

- `struct tty_struct *tty`: tty device to flush works for (or either end of a pty pair)

**Description**

Sync flush all works belonging to **tty** (and the 'other' tty).

#### <a id="c-release_one_tty"></a>`release_one_tty()`

```c
void release_one_tty(struct work_struct *work)
```

release tty structure memory

**Parameters**

- `struct work_struct *work`: work of tty we are obliterating

**Description**

Releases memory associated with a tty structure, and clears out the
driver table slots. This function is called when a device is no longer
in use. It also gets called when setup of a device fails.

- Locking:
  takes the file list lock internally when working on the list of ttys
  that the driver keeps.

This method gets called from a work queue so that the driver private
cleanup ops can sleep (needed for USB at least)

#### <a id="c-release_tty"></a>`release_tty()`

```c
void release_tty(struct tty_struct *tty, int idx)
```

release tty structure memory

**Parameters**

- `struct tty_struct *tty`: tty device release
- `int idx`: index of the tty device release

**Description**

Release both **tty** and a possible linked partner (think pty pair),
and decrement the refcount of the backing module.

- Locking:
  tty_mutex
  takes the file list lock internally when working on the list of ttys
  that the driver keeps.

#### <a id="c-tty_release_checks"></a>`tty_release_checks()`

```c
int tty_release_checks(struct tty_struct *tty, int idx)
```

check a tty before real release

**Parameters**

- `struct tty_struct *tty`: tty to check
- `int idx`: index of the tty

**Description**

Performs some paranoid checking before true release of the **tty**. This is a
no-op unless `TTY_PARANOIA_CHECK` is defined.

#### <a id="c-tty_release"></a>`tty_release()`

```c
int tty_release(struct inode *inode, struct file *filp)
```

vfs callback for close

**Parameters**

- `struct inode *inode`: inode of tty
- `struct file *filp`: file pointer for handle to tty

**Description**

Called the last time each file handle is closed that references this tty.
There may however be several such references.

- Locking:
  Takes BKL. See `tty_release_dev()`.

Even releasing the tty structures is a tricky business. We have to be very
careful that the structures are all released at the same time, as interrupts
might otherwise get the wrong pointers.

WSH 09/09/97: rewritten to avoid some nasty race conditions that could
lead to double frees or releasing memory still in use.

#### <a id="c-tty_open_current_tty"></a>`tty_open_current_tty()`

```c
struct tty_struct * tty_open_current_tty(dev_t device, struct file *filp)
```

get locked tty of current task

**Parameters**

- `dev_t device`: device number
- `struct file *filp`: file pointer to tty

**Return**

locked tty of the current task iff **device** is /dev/tty

**Description**

Performs a re-open of the current task's controlling tty.

We cannot return driver and index like for the other nodes because devpts
will not work then. It expects inodes to be from devpts FS.

#### <a id="c-tty_lookup_driver"></a>`tty_lookup_driver()`

```c
struct tty_driver * tty_lookup_driver(dev_t device, struct file *filp, int *index)
```

lookup a tty driver for a given device file

**Parameters**

- `dev_t device`: device number
- `struct file *filp`: file pointer to tty
- `int *index`: index for the device in the **return** driver

**Description**

If returned value is not erroneous, the caller is responsible to decrement
the refcount by [`tty_driver_kref_put()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-tty_driver_kref_put).

Locking: `tty_mutex` protects [`get_tty_driver()`](#c-get_tty_driver)

**Return**

driver for this inode (with increased refcount)

#### <a id="c-tty_open_by_driver"></a>`tty_open_by_driver()`

```c
struct tty_struct * tty_open_by_driver(dev_t device, struct file *filp)
```

open a tty device

**Parameters**

- `dev_t device`: dev_t of device to open
- `struct file *filp`: file pointer to tty

**Description**

Performs the driver lookup, checks for a reopen, or otherwise performs the
first-time tty initialization.

- Claims the global tty_mutex to serialize:
  * concurrent first-time tty initialization
  * concurrent tty driver removal w/ lookup
  * concurrent tty removal from driver table

**Return**

the locked initialized or re-opened [`tty_struct`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct)

#### <a id="c-tty_open"></a>`tty_open()`

```c
int tty_open(struct inode *inode, struct file *filp)
```

open a tty device

**Parameters**

- `struct inode *inode`: inode of device file
- `struct file *filp`: file pointer to tty

**Description**

[`tty_open()`](#c-tty_open) and [`tty_release()`](#c-tty_release) keep up the tty count that contains the number
of opens done on a tty. We cannot use the inode-count, as different inodes
might point to the same tty.

Open-counting is needed for pty masters, as well as for keeping track of
serial lines: DTR is dropped when the last close happens.
(This is not done solely through tty->count, now.  - Ted 1/27/92)

The termios state of a pty is reset on the first open so that settings don't
persist across reuse.

- Locking:
  * `tty_mutex` protects tty, [`tty_lookup_driver()`](#c-tty_lookup_driver) and [`tty_init_dev()`](#c-tty_init_dev).
  * **tty->count** should protect the rest.
  * ->siglock protects ->signal/->sighand

**Note**

the tty_unlock/lock cases without a ref are only safe due to `tty_mutex`

#### <a id="c-tty_poll"></a>`tty_poll()`

```c
__poll_t tty_poll(struct file *filp, poll_table *wait)
```

check tty status

**Parameters**

- `struct file *filp`: file being polled
- `poll_table *wait`: poll wait structures to update

**Description**

Call the line discipline polling method to obtain the poll status of the
device.

Locking: locks called line discipline but ldisc poll method may be
re-entered freely by other callers.

#### <a id="c-tiocsti"></a>`tiocsti()`

```c
int tiocsti(struct tty_struct *tty, u8 __user *p)
```

fake input character

**Parameters**

- `struct tty_struct *tty`: tty to fake input into
- `u8 __user *p`: pointer to character

**Description**

Fake input to a tty device. Does the necessary locking and input management.

FIXME: does not honour flow control ??

- Locking:
  * Called functions take tty_ldiscs_lock
  * current->signal->tty check is safe without locks

#### <a id="c-tiocgwinsz"></a>`tiocgwinsz()`

```c
int tiocgwinsz(struct tty_struct *tty, struct winsize __user *arg)
```

implement window query ioctl

**Parameters**

- `struct tty_struct *tty`: tty
- `struct winsize __user *arg`: user buffer for result

**Description**

Copies the kernel idea of the window size into the user buffer.

Locking: **tty->winsize_mutex** is taken to ensure the winsize data is
consistent.

#### <a id="c-tiocswinsz"></a>`tiocswinsz()`

```c
int tiocswinsz(struct tty_struct *tty, struct winsize __user *arg)
```

implement window size set ioctl

**Parameters**

- `struct tty_struct *tty`: tty side of tty
- `struct winsize __user *arg`: user buffer for result

**Description**

Copies the user idea of the window size to the kernel. Traditionally this is
just advisory information but for the Linux console it actually has driver
level meaning and triggers a VC resize.

- Locking:
  Driver dependent. The default do_resize method takes the tty termios
  mutex and ctrl.lock. The console takes its own lock then calls into the
  default method.

#### <a id="c-tioccons"></a>`tioccons()`

```c
int tioccons(struct file *file)
```

allow admin to move logical console

**Parameters**

- `struct file *file`: the file to become console

**Description**

Allow the administrator to move the redirected console device.

Locking: uses redirect_lock to guard the redirect information

#### <a id="c-tiocsetd"></a>`tiocsetd()`

```c
int tiocsetd(struct tty_struct *tty, int __user *p)
```

set line discipline

**Parameters**

- `struct tty_struct *tty`: tty device
- `int __user *p`: pointer to user data

**Description**

Set the line discipline according to user request.

Locking: see [`tty_set_ldisc()`](/kernel/hardware/driver-api/tty/tty-ldisc.md#c-tty_set_ldisc), this function is just a helper

#### <a id="c-tiocgetd"></a>`tiocgetd()`

```c
int tiocgetd(struct tty_struct *tty, int __user *p)
```

get line discipline

**Parameters**

- `struct tty_struct *tty`: tty device
- `int __user *p`: pointer to user data

**Description**

Retrieves the line discipline id directly from the ldisc.

Locking: waits for ldisc reference (in case the line discipline is changing
or the **tty** is being hungup)

#### <a id="c-send_break"></a>`send_break()`

```c
int send_break(struct tty_struct *tty, unsigned int duration)
```

performed time break

**Parameters**

- `struct tty_struct *tty`: device to break on
- `unsigned int duration`: timeout in mS

**Description**

Perform a timed break on hardware that lacks its own driver level timed
break functionality.

- Locking:
  **tty->atomic_write_lock** serializes

#### <a id="c-tty_tiocmget"></a>`tty_tiocmget()`

```c
int tty_tiocmget(struct tty_struct *tty, int __user *p)
```

get modem status

**Parameters**

- `struct tty_struct *tty`: tty device
- `int __user *p`: pointer to result

**Description**

Obtain the modem status bits from the tty driver if the feature is
supported. Return -`ENOTTY` if it is not available.

Locking: none (up to the driver)

#### <a id="c-tty_tiocmset"></a>`tty_tiocmset()`

```c
int tty_tiocmset(struct tty_struct *tty, unsigned int cmd, unsigned __user *p)
```

set modem status

**Parameters**

- `struct tty_struct *tty`: tty device
- `unsigned int cmd`: command - clear bits, set bits or set all
- `unsigned __user *p`: pointer to desired bits

**Description**

Set the modem status bits from the tty driver if the feature
is supported. Return -`ENOTTY` if it is not available.

Locking: none (up to the driver)

#### <a id="c-alloc_tty_struct"></a>`alloc_tty_struct()`

```c
struct tty_struct * alloc_tty_struct(struct tty_driver *driver, int idx)
```

allocate a new tty

**Parameters**

- `struct tty_driver *driver`: driver which will handle the returned tty
- `int idx`: minor of the tty

**Description**

This subroutine allocates and initializes a tty structure.

Locking: none - **tty** in question is not exposed at this point

---

# TTY IOCTL Helpers

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Reference for TTY IOCTL Helpers.

<a id="rst-tty-ioctl-helpers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-tty_chars_in_buffer"></a>`tty_chars_in_buffer()`

```c
unsigned int tty_chars_in_buffer(struct tty_struct *tty)
```

characters pending

**Parameters**

- `struct tty_struct *tty`: terminal

**Return**

the number of bytes of data in the device private output queue. If
no private method is supplied there is assumed to be no queue on the device.

#### <a id="c-tty_write_room"></a>`tty_write_room()`

```c
unsigned int tty_write_room(struct tty_struct *tty)
```

write queue space

**Parameters**

- `struct tty_struct *tty`: terminal

**Return**

the number of bytes that can be queued to this device at the present
time. The result should be treated as a guarantee and the driver cannot
offer a value it later shrinks by more than the number of bytes written. If
no method is provided, 2K is always returned and data may be lost as there
will be no flow control.

#### <a id="c-tty_driver_flush_buffer"></a>`tty_driver_flush_buffer()`

```c
void tty_driver_flush_buffer(struct tty_struct *tty)
```

discard internal buffer

**Parameters**

- `struct tty_struct *tty`: terminal

**Description**

Discard the internal output buffer for this device. If no method is provided,
then either the buffer cannot be hardware flushed or there is no buffer
driver side.

#### <a id="c-tty_unthrottle"></a>`tty_unthrottle()`

```c
void tty_unthrottle(struct tty_struct *tty)
```

flow control

**Parameters**

- `struct tty_struct *tty`: terminal

**Description**

Indicate that a **tty** may continue transmitting data down the stack. Takes
the [`tty_struct->termios_rwsem`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct) to protect against parallel
throttle/unthrottle and also to ensure the driver can consistently reference
its own termios data at this point when implementing software flow control.

Drivers should however remember that the stack can issue a throttle, then
change flow control method, then unthrottle.

#### <a id="c-tty_throttle_safe"></a>`tty_throttle_safe()`

```c
bool tty_throttle_safe(struct tty_struct *tty)
```

flow control

**Parameters**

- `struct tty_struct *tty`: terminal

**Description**

Indicate that a **tty** should stop transmitting data down the stack.
[`tty_throttle_safe()`](#c-tty_throttle_safe) will only attempt throttle if **tty->flow_change** is
`TTY_THROTTLE_SAFE`. Prevents an accidental throttle due to race conditions
when throttling is conditional on factors evaluated prior to throttling.

**Return**

`true` if **tty** is throttled (or was already throttled)

#### <a id="c-tty_unthrottle_safe"></a>`tty_unthrottle_safe()`

```c
bool tty_unthrottle_safe(struct tty_struct *tty)
```

flow control

**Parameters**

- `struct tty_struct *tty`: terminal

**Description**

Similar to [`tty_unthrottle()`](#c-tty_unthrottle) but will only attempt unthrottle if
**tty->flow_change** is `TTY_UNTHROTTLE_SAFE`. Prevents an accidental unthrottle
due to race conditions when unthrottling is conditional on factors evaluated
prior to unthrottling.

**Return**

`true` if **tty** is unthrottled (or was already unthrottled)

#### <a id="c-tty_wait_until_sent"></a>`tty_wait_until_sent()`

```c
void tty_wait_until_sent(struct tty_struct *tty, long timeout)
```

wait for I/O to finish

**Parameters**

- `struct tty_struct *tty`: tty we are waiting for
- `long timeout`: how long we will wait

**Description**

Wait for characters pending in a tty driver to hit the wire, or for a
timeout to occur (eg due to flow control).

Locking: none

#### <a id="c-tty_termios_copy_hw"></a>`tty_termios_copy_hw()`

```c
void tty_termios_copy_hw(struct ktermios *new, const struct ktermios *old)
```

copy hardware settings

**Parameters**

- `struct ktermios *new`: new termios
- `const struct ktermios *old`: old termios

**Description**

Propagate the hardware specific terminal setting bits from the **old** termios
structure to the **new** one. This is used in cases where the hardware does not
support reconfiguration or as a helper in some cases where only minimal
reconfiguration is supported.

#### <a id="c-tty_termios_hw_change"></a>`tty_termios_hw_change()`

```c
bool tty_termios_hw_change(const struct ktermios *a, const struct ktermios *b)
```

check for setting change

**Parameters**

- `const struct ktermios *a`: termios
- `const struct ktermios *b`: termios to compare

**Description**

Check if any of the bits that affect a dumb device have changed between the
two termios structures, or a speed change is needed.

**Return**

`true` if change is needed

#### <a id="c-tty_get_char_size"></a>`tty_get_char_size()`

```c
unsigned char tty_get_char_size(unsigned int cflag)
```

get size of a character

**Parameters**

- `unsigned int cflag`: termios cflag value

**Return**

size (in bits) of a character depending on **cflag**'s `CSIZE` setting

#### <a id="c-tty_get_frame_size"></a>`tty_get_frame_size()`

```c
unsigned char tty_get_frame_size(unsigned int cflag)
```

get size of a frame

**Parameters**

- `unsigned int cflag`: termios cflag value

**Description**

Get the size (in bits) of a frame depending on **cflag**'s `CSIZE`, `CSTOPB`, and
`PARENB` setting. The result is a sum of character size, start and stop bits
-- one bit each -- second stop bit (if set), and parity bit (if set).

**Return**

size (in bits) of a frame depending on **cflag**'s setting.

#### <a id="c-tty_set_termios"></a>`tty_set_termios()`

```c
int tty_set_termios(struct tty_struct *tty, struct ktermios *new_termios)
```

update termios values

**Parameters**

- `struct tty_struct *tty`: tty to update
- `struct ktermios *new_termios`: desired new value

**Description**

Perform updates to the termios values set on this **tty**. A master pty's
termios should never be set.

Locking: [`tty_struct->termios_rwsem`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct)

#### <a id="c-set_termios"></a>`set_termios()`

```c
int set_termios(struct tty_struct *tty, void __user *arg, int opt)
```

set termios values for a tty

**Parameters**

- `struct tty_struct *tty`: terminal device
- `void __user *arg`: user data
- `int opt`: option information

**Description**

Helper function to prepare termios data and run necessary other functions
before using [`tty_set_termios()`](#c-tty_set_termios) to do the actual changes.

Locking: called functions take [`tty_struct->ldisc_sem`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct) and
[`tty_struct->termios_rwsem`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct) locks

**Return**

0 on success, an error otherwise

#### <a id="c-set_sgttyb"></a>`set_sgttyb()`

```c
int set_sgttyb(struct tty_struct *tty, struct sgttyb __user *sgttyb)
```

set legacy terminal values

**Parameters**

- `struct tty_struct *tty`: tty structure
- `struct sgttyb __user *sgttyb`: pointer to old style terminal structure

**Description**

Updates a terminal from the legacy BSD style terminal information structure.

Locking: [`tty_struct->termios_rwsem`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct)

**Return**

0 on success, an error otherwise

#### <a id="c-tty_change_softcar"></a>`tty_change_softcar()`

```c
int tty_change_softcar(struct tty_struct *tty, bool enable)
```

carrier change ioctl helper

**Parameters**

- `struct tty_struct *tty`: tty to update
- `bool enable`: enable/disable `CLOCAL`

**Description**

Perform a change to the `CLOCAL` state and call into the driver layer to make
it visible.

Locking: [`tty_struct->termios_rwsem`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct).

**Return**

0 on success, an error otherwise

#### <a id="c-tty_mode_ioctl"></a>`tty_mode_ioctl()`

```c
int tty_mode_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg)
```

mode related ioctls

**Parameters**

- `struct tty_struct *tty`: tty for the ioctl
- `unsigned int cmd`: command
- `unsigned long arg`: ioctl argument

**Description**

Perform non-line discipline specific mode control ioctls. This is designed
to be called by line disciplines to ensure they provide consistent mode
setting.



#### <a id="c-tty_get_baud_rate"></a>`tty_get_baud_rate()`

```c
speed_t tty_get_baud_rate(const struct tty_struct *tty)
```

get tty bit rates

**Parameters**

- `const struct tty_struct *tty`: tty to query

**Return**

the baud rate as an integer for this terminal

**Description**

Locking: The termios lock must be held by the caller.

---

# TTY Line Discipline

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Registration

<a id="rst-tty-line-discipline"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



TTY line discipline process all incoming and outgoing character from/to a tty device. The default line discipline is [N_TTY](</kernel/hardware/driver-api/tty/n-tty.md>). It is also a fallback if establishing any other discipline for a tty fails. If even N_TTY fails, N_NULL takes over. That never fails, but also does not process any characters -- it throws them away.

<a id="rst-registration"></a>

## Registration

Line disciplines are registered with tty_register_ldisc() passing the ldisc structure. At the point of registration the discipline must be ready to use and it is possible it will get used before the call returns success. If the call returns an error then it won’t get called. Do not reuse ldisc numbers as they are part of the userspace ABI and writing over an existing ldisc will cause demons to eat your computer. You must not re-register over the top of the line discipline even with the same data or your computer again will be eaten by demons. In order to remove a line discipline call tty_unregister_ldisc().

Heed this warning: the reference count field of the registered copies of the tty_ldisc structure in the ldisc table counts the number of lines using this discipline. The reference count of the tty_ldisc structure within a tty counts the number of active users of the ldisc at this instant. In effect it counts the number of threads of execution within an ldisc method (plus those about to enter and exit although this detail matters not).


#### <a id="c-tty_register_ldisc"></a>`tty_register_ldisc()`

```c
int tty_register_ldisc(struct tty_ldisc_ops *new_ldisc)
```

install a line discipline

**Parameters**

- `struct tty_ldisc_ops *new_ldisc`: pointer to the ldisc object

**Description**

Installs a new line discipline into the kernel. The discipline is set up as
unreferenced and then made available to the kernel from this point onwards.

Locking: takes `tty_ldiscs_lock` to guard against ldisc races

#### <a id="c-tty_unregister_ldisc"></a>`tty_unregister_ldisc()`

```c
void tty_unregister_ldisc(struct tty_ldisc_ops *ldisc)
```

unload a line discipline

**Parameters**

- `struct tty_ldisc_ops *ldisc`: ldisc number

**Description**

Remove a line discipline from the kernel providing it is not currently in
use.

Locking: takes `tty_ldiscs_lock` to guard against ldisc races


<a id="rst-other-functions"></a>

## Other Functions


#### <a id="c-tty_ldisc_flush"></a>`tty_ldisc_flush()`

```c
void tty_ldisc_flush(struct tty_struct *tty)
```

flush line discipline queue

**Parameters**

- `struct tty_struct *tty`: tty to flush ldisc for

**Description**

Flush the line discipline queue (if any) and the tty flip buffers for this
**tty**.

#### <a id="c-tty_set_ldisc"></a>`tty_set_ldisc()`

```c
int tty_set_ldisc(struct tty_struct *tty, int disc)
```

set line discipline

**Parameters**

- `struct tty_struct *tty`: the terminal to set
- `int disc`: the line discipline number

**Description**

Set the discipline of a tty line. Must be called from a process context. The
ldisc change logic has to protect itself against any overlapping ldisc
change (including on the other end of pty pairs), the close of one side of a
tty/pty pair, and eventually hangup.


<a id="rst-line-discipline-operations-reference"></a>

## Line Discipline Operations Reference


#### <a id="c-struct-tty_ldisc_ops"></a>`struct tty_ldisc_ops`

ldisc operations

**Definition**

```c
struct tty_ldisc_ops {
    char *name;
    int num;
    int (*open)(struct tty_struct *tty);
    void (*close)(struct tty_struct *tty);
    void (*flush_buffer)(struct tty_struct *tty);
    ssize_t (*read)(struct tty_struct *tty, struct file *file, u8 *buf, size_t nr, void **cookie, unsigned long offset);
    ssize_t (*write)(struct tty_struct *tty, struct file *file, const u8 *buf, size_t nr);
    int (*ioctl)(struct tty_struct *tty, unsigned int cmd, unsigned long arg);
    int (*compat_ioctl)(struct tty_struct *tty, unsigned int cmd, unsigned long arg);
    void (*set_termios)(struct tty_struct *tty, const struct ktermios *old);
    __poll_t (*poll)(struct tty_struct *tty, struct file *file, struct poll_table_struct *wait);
    void (*hangup)(struct tty_struct *tty);
    void (*receive_buf)(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count);
    void (*write_wakeup)(struct tty_struct *tty);
    void (*dcd_change)(struct tty_struct *tty, bool active);
    size_t (*receive_buf2)(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count);
    void (*lookahead_buf)(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count);
    struct module *owner;
};
```

**Members**

- `name`: name of this ldisc rendered in /proc/tty/ldiscs
- `num`: `N_*` number (`N_TTY`, `N_HDLC`, ...) reserved to this ldisc
- `open`: \[TTY\] `int ()(struct tty_struct *tty)`
- `close`: \[TTY\] `void ()(struct tty_struct *tty)`
- `flush_buffer`: \[TTY\] `void ()(struct tty_struct *tty)`
- `read`: \[TTY\] `ssize_t ()(struct tty_struct *tty, struct file *file, u8 *buf, size_t nr)`
- `write`: \[TTY\] `ssize_t ()(struct tty_struct *tty, struct file *file, const u8 *buf, size_t nr)`
- `ioctl`: \[TTY\] `int ()(struct tty_struct *tty, unsigned int cmd, unsigned long arg)`
- `compat_ioctl`: \[TTY\] `int ()(struct tty_struct *tty, unsigned int cmd, unsigned long arg)`
- `set_termios`: \[TTY\] `void ()(struct tty_struct *tty, const struct ktermios *old)`
- `poll`: \[TTY\] `int ()(struct tty_struct *tty, struct file *file, struct poll_table_struct *wait)`
- `hangup`: \[TTY\] `void ()(struct tty_struct *tty)`
- `receive_buf`: \[DRV\] `void ()(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count)`
- `write_wakeup`: \[DRV\] `void ()(struct tty_struct *tty)`
- `dcd_change`: \[DRV\] `void ()(struct tty_struct *tty, bool active)`
- `receive_buf2`: \[DRV\] `ssize_t ()(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count)`
- `lookahead_buf`: \[DRV\] `void ()(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count)`
- `owner`: module containting this ldisc (for reference counting)

**Description**

This function is called when the line discipline is associated with the
**tty**. No other call into the line discipline for this tty will occur
until it completes successfully. It should initialize any state needed
by the ldisc, and set **tty->receive_room** to the maximum amount of data
the line discipline is willing to accept from the driver with a single
call to **receive_buf()**. Returning an error will prevent the ldisc from
being attached.

Optional. Can sleep.

This function is called when the line discipline is being shutdown,
either because the **tty** is being closed or because the **tty** is being
changed to use a new line discipline. At the point of execution no
further users will enter the ldisc code for this tty.

Optional. Can sleep.

This function instructs the line discipline to clear its buffers of any
input characters it may have queued to be delivered to the user mode
process. It may be called at any point between open and close.

Optional.

This function is called when the user requests to read from the **tty**.
The line discipline will return whatever characters it has buffered up
for the user. If this function is not defined, the user will receive
an `EIO` error. Multiple read calls may occur in parallel and the ldisc
must deal with serialization issues.

Optional: `EIO` unless provided. Can sleep.

This function is called when the user requests to write to the **tty**.
The line discipline will deliver the characters to the low-level tty
device for transmission, optionally performing some processing on the
characters first. If this function is not defined, the user will
receive an `EIO` error.

Optional: `EIO` unless provided. Can sleep.

This function is called when the user requests an ioctl which is not
handled by the tty layer or the low-level tty driver. It is intended
for ioctls which affect line discpline operation.  Note that the search
order for ioctls is (1) tty layer, (2) tty low-level driver, (3) line
discpline. So a low-level driver can "grab" an ioctl request before
the line discpline has a chance to see it.

Optional.

Process ioctl calls from 32-bit process on 64-bit system.

Note that only ioctls that are neither "pointer to compatible
structure" nor tty-generic.  Something private that takes an integer or
a pointer to wordsize-sensitive structure belongs here, but most of
ldiscs will happily leave it `NULL`.

Optional.

This function notifies the line discpline that a change has been made
to the termios structure.

Optional.

This function is called when a user attempts to select/poll on a **tty**
device. It is solely the responsibility of the line discipline to
handle poll requests.

Optional.

Called on a hangup. Tells the discipline that it should cease I/O to
the tty driver. The driver should seek to perform this action quickly
but should wait until any pending driver I/O is completed. No further
calls into the ldisc code will occur.

Optional. Can sleep.

This function is called by the low-level tty driver to send characters
received by the hardware to the line discpline for processing. **cp** is
a pointer to the buffer of input character received by the device. **fp**
is a pointer to an array of flag bytes which indicate whether a
character was received with a parity error, etc. **fp** may be `NULL` to
indicate all data received is `TTY_NORMAL`.

Optional.

This function is called by the low-level tty driver to signal that line
discpline should try to send more characters to the low-level driver
for transmission. If the line discpline does not have any more data to
send, it can just return. If the line discipline does have some data to
send, please arise a tasklet or workqueue to do the real data transfer.
Do not send data in this hook, it may lead to a deadlock.

Optional.

Tells the discipline that the DCD pin has changed its status. Used
exclusively by the `N_PPS` (Pulse-Per-Second) line discipline.

Optional.

This function is called by the low-level tty driver to send characters
received by the hardware to the line discpline for processing. **cp** is a
pointer to the buffer of input character received by the device.  **fp**
is a pointer to an array of flag bytes which indicate whether a
character was received with a parity error, etc. **fp** may be `NULL` to
indicate all data received is `TTY_NORMAL`. If assigned, prefer this
function for automatic flow control.

Optional.

This function is called by the low-level tty driver for characters
not eaten by ->`receive_buf()` or ->`receive_buf2()`. It is useful for
processing high-priority characters such as software flow-control
characters that could otherwise get stuck into the intermediate
buffer until tty has room to receive them. Ldisc must be able to
handle later a ->`receive_buf()` or ->`receive_buf2()` call for the
same characters (e.g. by skipping the actions for high-priority
characters already handled by ->`lookahead_buf()`).

Optional.

This structure defines the interface between the tty line discipline
implementation and the tty routines. The above routines can be defined.
Unless noted otherwise, they are optional, and can be filled in with a `NULL`
pointer.

Hooks marked \[TTY\] are invoked from the TTY core, the \[DRV\] ones from the
tty_driver side.


<a id="rst-driver-access"></a>

## Driver Access

Line discipline methods can call the methods of the underlying hardware driver. These are documented as a part of struct tty_operations.

<a id="rst-tty-flags"></a>

## TTY Flags

Line discipline methods have access to `tty_struct.flags` field. See [TTY Struct](</kernel/hardware/driver-api/tty/tty-struct.md>).

<a id="rst-locking"></a>

## Locking

Callers to the line discipline functions from the tty layer are required to take line discipline locks. The same is true of calls from the driver side but not yet enforced.


#### <a id="c-tty_ldisc_ref_wait"></a>`tty_ldisc_ref_wait()`

```c
struct tty_ldisc * tty_ldisc_ref_wait(struct tty_struct *tty)
```

wait for the tty ldisc

**Parameters**

- `struct tty_struct *tty`: tty device

**Description**

Dereference the line discipline for the terminal and take a reference to it.
If the line discipline is in flux then wait patiently until it changes.

Note 1: Must not be called from an IRQ/timer context. The caller must also
be careful not to hold other locks that will deadlock against a discipline
change, such as an existing ldisc reference (which we check for).

Note 2: a file_operations routine (read/poll/write) should use this function
to wait for any ldisc lifetime events to finish.

**Return**

`NULL` if the tty has been hungup and not re-opened with a new file
descriptor, otherwise valid ldisc reference

#### <a id="c-tty_ldisc_ref"></a>`tty_ldisc_ref()`

```c
struct tty_ldisc * tty_ldisc_ref(struct tty_struct *tty)
```

get the tty ldisc

**Parameters**

- `struct tty_struct *tty`: tty device

**Description**

Dereference the line discipline for the terminal and take a reference to it.
If the line discipline is in flux then return `NULL`. Can be called from IRQ
and timer functions.

#### <a id="c-tty_ldisc_deref"></a>`tty_ldisc_deref()`

```c
void tty_ldisc_deref(struct tty_ldisc *ld)
```

free a tty ldisc reference

**Parameters**

- `struct tty_ldisc *ld`: reference to free up

**Description**

Undoes the effect of [`tty_ldisc_ref()`](#c-tty_ldisc_ref) or [`tty_ldisc_ref_wait()`](#c-tty_ldisc_ref_wait). May be called
in IRQ context.


While these functions are slightly slower than the old code they should have minimal impact as most receive logic uses the flip buffers and they only need to take a reference when they push bits up through the driver.

A caution: The `tty_ldisc_ops.open()`, `tty_ldisc_ops.close()` and `tty_driver.set_ldisc()` functions are called with the ldisc unavailable. Thus tty_ldisc_ref() will fail in this situation if used within these functions.  Ldisc and driver code calling its own functions must be careful in this case.

<a id="rst-internal-functions"></a>

## Internal Functions


#### <a id="c-tty_ldisc_get"></a>`tty_ldisc_get()`

```c
struct tty_ldisc * tty_ldisc_get(struct tty_struct *tty, int disc)
```

take a reference to an ldisc

**Parameters**

- `struct tty_struct *tty`: tty device
- `int disc`: ldisc number

**Description**

Takes a reference to a line discipline. Deals with refcounts and module
locking counts. If the discipline is not available, its module loaded, if
possible.

Locking: takes `tty_ldiscs_lock` to guard against ldisc races

**Return**

* -`EINVAL` if the discipline index is not \[`N_TTY` .. `NR_LDISCS`\] or if the
  discipline is not registered
* -`EAGAIN` if `request_module()` failed to load or register the discipline
* -`ENOMEM` if allocation failure
* Otherwise, returns a pointer to the discipline and bumps the ref count

#### <a id="c-tty_ldisc_put"></a>`tty_ldisc_put()`

```c
void tty_ldisc_put(struct tty_ldisc *ld)
```

release the ldisc

**Parameters**

- `struct tty_ldisc *ld`: lisdsc to release

**Description**

Complement of [`tty_ldisc_get()`](#c-tty_ldisc_get).

#### <a id="c-tty_set_termios_ldisc"></a>`tty_set_termios_ldisc()`

```c
void tty_set_termios_ldisc(struct tty_struct *tty, int disc)
```

set ldisc field

**Parameters**

- `struct tty_struct *tty`: tty structure
- `int disc`: line discipline number

**Description**

This is probably overkill for real world processors but they are not on hot
paths so a little discipline won't do any harm.

The line discipline-related tty_struct fields are reset to prevent the ldisc
driver from re-using stale information for the new ldisc instance.

Locking: takes termios_rwsem

#### <a id="c-tty_ldisc_open"></a>`tty_ldisc_open()`

```c
int tty_ldisc_open(struct tty_struct *tty, struct tty_ldisc *ld)
```

open a line discipline

**Parameters**

- `struct tty_struct *tty`: tty we are opening the ldisc on
- `struct tty_ldisc *ld`: discipline to open

**Description**

A helper opening method. Also a convenient debugging and check point.

Locking: always called with BTM already held.

#### <a id="c-tty_ldisc_close"></a>`tty_ldisc_close()`

```c
void tty_ldisc_close(struct tty_struct *tty, struct tty_ldisc *ld)
```

close a line discipline

**Parameters**

- `struct tty_struct *tty`: tty we are opening the ldisc on
- `struct tty_ldisc *ld`: discipline to close

**Description**

A helper close method. Also a convenient debugging and check point.

#### <a id="c-tty_ldisc_failto"></a>`tty_ldisc_failto()`

```c
int tty_ldisc_failto(struct tty_struct *tty, int ld)
```

helper for ldisc failback

**Parameters**

- `struct tty_struct *tty`: tty to open the ldisc on
- `int ld`: ldisc we are trying to fail back to

**Description**

Helper to try and recover a tty when switching back to the old ldisc fails
and we need something attached.

#### <a id="c-tty_ldisc_restore"></a>`tty_ldisc_restore()`

```c
void tty_ldisc_restore(struct tty_struct *tty, struct tty_ldisc *old)
```

helper for tty ldisc change

**Parameters**

- `struct tty_struct *tty`: tty to recover
- `struct tty_ldisc *old`: previous ldisc

**Description**

Restore the previous line discipline or `N_TTY` when a line discipline change
fails due to an open error

#### <a id="c-tty_ldisc_kill"></a>`tty_ldisc_kill()`

```c
void tty_ldisc_kill(struct tty_struct *tty)
```

teardown ldisc

**Parameters**

- `struct tty_struct *tty`: tty being released

**Description**

Perform final close of the ldisc and reset **tty->ldisc**

#### <a id="c-tty_reset_termios"></a>`tty_reset_termios()`

```c
void tty_reset_termios(struct tty_struct *tty)
```

reset terminal state

**Parameters**

- `struct tty_struct *tty`: tty to reset

**Description**

Restore a terminal to the driver default state.

#### <a id="c-tty_ldisc_reinit"></a>`tty_ldisc_reinit()`

```c
int tty_ldisc_reinit(struct tty_struct *tty, int disc)
```

reinitialise the tty ldisc

**Parameters**

- `struct tty_struct *tty`: tty to reinit
- `int disc`: line discipline to reinitialize

**Description**

Completely reinitialize the line discipline state, by closing the current
instance, if there is one, and opening a new instance. If an error occurs
opening the new non-`N_TTY` instance, the instance is dropped and **tty->ldisc**
reset to `NULL`. The caller can then retry with `N_TTY` instead.

**Return**

0 if successful, otherwise error code \< 0

#### <a id="c-tty_ldisc_hangup"></a>`tty_ldisc_hangup()`

```c
void tty_ldisc_hangup(struct tty_struct *tty, bool reinit)
```

hangup ldisc reset

**Parameters**

- `struct tty_struct *tty`: tty being hung up
- `bool reinit`: whether to re-initialise the tty

**Description**

Some tty devices reset their termios when they receive a hangup event. In
that situation we must also switch back to `N_TTY` properly before we reset
the termios data.

Locking: We can take the ldisc mutex as the rest of the code is careful to
allow for this.

In the pty pair case this occurs in the `close()` path of the tty itself so we
must be careful about locking rules.

#### <a id="c-tty_ldisc_setup"></a>`tty_ldisc_setup()`

```c
int tty_ldisc_setup(struct tty_struct *tty, struct tty_struct *o_tty)
```

open line discipline

**Parameters**

- `struct tty_struct *tty`: tty being shut down
- `struct tty_struct *o_tty`: pair tty for pty/tty pairs

**Description**

Called during the initial open of a tty/pty pair in order to set up the line
disciplines and bind them to the **tty**. This has no locking issues as the
device isn't yet active.

#### <a id="c-tty_ldisc_release"></a>`tty_ldisc_release()`

```c
void tty_ldisc_release(struct tty_struct *tty)
```

release line discipline

**Parameters**

- `struct tty_struct *tty`: tty being shut down (or one end of pty pair)

**Description**

Called during the final close of a tty or a pty pair in order to shut down
the line discpline layer. On exit, each tty's ldisc is `NULL`.

#### <a id="c-tty_ldisc_init"></a>`tty_ldisc_init()`

```c
int tty_ldisc_init(struct tty_struct *tty)
```

ldisc setup for new tty

**Parameters**

- `struct tty_struct *tty`: tty being allocated

**Description**

Set up the line discipline objects for a newly allocated tty. Note that the
tty structure is not completely set up when this call is made.

#### <a id="c-tty_ldisc_deinit"></a>`tty_ldisc_deinit()`

```c
void tty_ldisc_deinit(struct tty_struct *tty)
```

ldisc cleanup for new tty

**Parameters**

- `struct tty_struct *tty`: tty that was allocated recently

**Description**

The tty structure must not be completely set up ([`tty_ldisc_setup()`](#c-tty_ldisc_setup)) when
this call is made.

---

# TTY Port

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> TTY Port Functions

<a id="rst-tty-port"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



The TTY drivers are advised to use struct tty_port helpers as much as possible. If the drivers implement `tty_port.ops.activate()` and `tty_port.ops.shutdown()`, they can use tty_port_open(), tty_port_close(), and tty_port_hangup() in respective `tty_struct.ops` hooks.

The reference and details are contained in the [TTY Port Reference](<#rst-tty-port-reference>) and [TTY Port Operations Reference](<#rst-tty-port-operations-reference>) sections at the bottom.

<a id="rst-tty-port-functions"></a>

## TTY Port Functions

<a id="rst-init-destroy"></a>

### Init &amp; Destroy


#### <a id="c-tty_port_init"></a>`tty_port_init()`

```c
void tty_port_init(struct tty_port *port)
```

initialize tty_port

**Parameters**

- `struct tty_port *port`: tty_port to initialize

**Description**

Initializes the state of struct tty_port. When a port was initialized using
this function, one has to destroy the port by [`tty_port_destroy()`](#c-tty_port_destroy). Either
indirectly by using [`tty_port`](#c-struct-tty_port) refcounting ([`tty_port_put()`](#c-tty_port_put)) or directly if
refcounting is not used.

#### <a id="c-tty_port_destroy"></a>`tty_port_destroy()`

```c
void tty_port_destroy(struct tty_port *port)
```

destroy inited port

**Parameters**

- `struct tty_port *port`: tty port to be destroyed

**Description**

When a port was initialized using [`tty_port_init()`](#c-tty_port_init), one has to destroy the
port by this function. Either indirectly by using [`tty_port`](#c-struct-tty_port) refcounting
([`tty_port_put()`](#c-tty_port_put)) or directly if refcounting is not used.

#### <a id="c-tty_port_put"></a>`tty_port_put()`

```c
void tty_port_put(struct tty_port *port)
```

drop a reference to tty_port

**Parameters**

- `struct tty_port *port`: port to drop a reference of (can be NULL)

**Description**

The final put will destroy and free up the **port** using
**port->ops->destruct()** hook, or using [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) if not provided.


<a id="rst-open-close-hangup-helpers"></a>

### Open/Close/Hangup Helpers


#### <a id="c-tty_port_shutdown"></a>`tty_port_shutdown()`

```c
void tty_port_shutdown(struct tty_port *port, struct tty_struct *tty)
```

internal helper to shutdown the device

**Parameters**

- `struct tty_port *port`: tty port to be shut down
- `struct tty_struct *tty`: the associated tty

**Description**

It is used by [`tty_port_hangup()`](#c-tty_port_hangup) and [`tty_port_close()`](#c-tty_port_close). Its task is to
shutdown the device if it was initialized (note consoles remain
functioning). It lowers DTR/RTS (if **tty** has HUPCL set) and invokes
**port->ops->shutdown()**.

#### <a id="c-tty_port_hangup"></a>`tty_port_hangup()`

```c
void tty_port_hangup(struct tty_port *port)
```

hangup helper

**Parameters**

- `struct tty_port *port`: tty port

**Description**

Perform port level tty hangup flag and count changes. Drop the tty
reference.

Caller holds tty lock.

#### <a id="c-tty_port_block_til_ready"></a>`tty_port_block_til_ready()`

```c
int tty_port_block_til_ready(struct tty_port *port, struct tty_struct *tty, struct file *filp)
```

Waiting logic for tty open

**Parameters**

- `struct tty_port *port`: the tty port being opened
- `struct tty_struct *tty`: the tty device being bound
- `struct file *filp`: the file pointer of the opener or `NULL`

**Description**

Implement the core POSIX/SuS tty behaviour when opening a tty device.
Handles:

- hangup (both before and during)
- non blocking open
- rts/dtr/dcd
- signals
- port flags and counts

The passed **port** must implement the **port->ops->carrier_raised** method if it
can do carrier detect and the **port->ops->dtr_rts** method if it supports
software management of these lines. Note that the dtr/rts raise is done each
iteration as a hangup may have previously dropped them while we wait.

Caller holds tty lock.

**Note**

May drop and reacquire tty lock when blocking, so **tty** and **port** may
have changed state (eg., may have been hung up).

#### <a id="c-tty_port_close_start"></a>`tty_port_close_start()`

```c
int tty_port_close_start(struct tty_port *port, struct tty_struct *tty, struct file *filp)
```

helper for tty->ops->close, part 1/2

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_struct *tty`: tty being closed
- `struct file *filp`: passed file pointer

**Description**

Decrements and checks open count. Flushes the port if this is the last
close. That means, dropping the data from the outpu buffer on the device and
waiting for sending logic to finish. The rest of close handling is performed
in [`tty_port_close_end()`](#c-tty_port_close_end).

Locking: Caller holds tty lock.

**Return**

1 if this is the last close, otherwise 0

#### <a id="c-tty_port_close_end"></a>`tty_port_close_end()`

```c
void tty_port_close_end(struct tty_port *port, struct tty_struct *tty)
```

helper for tty->ops->close, part 2/2

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_struct *tty`: tty being closed

**Description**

This is a continuation of the first part: [`tty_port_close_start()`](#c-tty_port_close_start). This
should be called after turning off the device. It flushes the data from the
line discipline and delays the close by **port->close_delay**.

Locking: Caller holds tty lock.

#### <a id="c-tty_port_close"></a>`tty_port_close()`

```c
void tty_port_close(struct tty_port *port, struct tty_struct *tty, struct file *filp)
```

generic tty->ops->close handler

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_struct *tty`: tty being closed
- `struct file *filp`: passed file pointer

**Description**

It is a generic helper to be used in driver's **tty->ops->close**. It wraps a
sequence of [`tty_port_close_start()`](#c-tty_port_close_start), [`tty_port_shutdown()`](#c-tty_port_shutdown), and
[`tty_port_close_end()`](#c-tty_port_close_end). The latter two are called only if this is the last
close. See the respective functions for the details.

Locking: Caller holds tty lock

#### <a id="c-tty_port_install"></a>`tty_port_install()`

```c
int tty_port_install(struct tty_port *port, struct tty_driver *driver, struct tty_struct *tty)
```

generic tty->ops->install handler

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_driver *driver`: tty_driver for this device
- `struct tty_struct *tty`: tty to be installed

**Description**

It is the same as [`tty_standard_install()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-tty_standard_install) except the provided **port** is linked
to a concrete tty specified by **tty**. Use this or [`tty_port_register_device()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-tty_port_register_device)
(or both). Call [`tty_port_link_device()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-tty_port_link_device) as a last resort.

#### <a id="c-tty_port_open"></a>`tty_port_open()`

```c
int tty_port_open(struct tty_port *port, struct tty_struct *tty, struct file *filp)
```

generic tty->ops->open handler

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_struct *tty`: tty to be opened
- `struct file *filp`: passed file pointer

**Description**

It is a generic helper to be used in driver's **tty->ops->open**. It activates
the devices using **port->ops->activate** if not active already. And waits for
the device to be ready using [`tty_port_block_til_ready()`](#c-tty_port_block_til_ready) (e.g.  raises
DTR/CTS and waits for carrier).

Note that **port->ops->shutdown** is not called when **port->ops->activate**
returns an error (on the contrary, **tty->ops->close** is).

Locking: Caller holds tty lock.

**Note**

may drop and reacquire tty lock (in [`tty_port_block_til_ready()`](#c-tty_port_block_til_ready)) so
**tty** and **port** may have changed state (eg., may be hung up now).


<a id="rst-tty-refcounting"></a>

### TTY Refcounting


#### <a id="c-tty_port_tty_get"></a>`tty_port_tty_get()`

```c
struct tty_struct * tty_port_tty_get(struct tty_port *port)
```

get a tty reference

**Parameters**

- `struct tty_port *port`: tty port

**Description**

Return a refcount protected tty instance or `NULL` if the port is not
associated with a tty (eg due to close or hangup).

#### <a id="c-tty_port_tty_set"></a>`tty_port_tty_set()`

```c
void tty_port_tty_set(struct tty_port *port, struct tty_struct *tty)
```

set the tty of a port

**Parameters**

- `struct tty_port *port`: tty port
- `struct tty_struct *tty`: the tty

**Description**

Associate the port and tty pair. Manages any internal refcounts. Pass `NULL`
to deassociate a port.


<a id="rst-tty-helpers"></a>

### TTY Helpers


#### <a id="c-tty_port_tty_hangup"></a>`tty_port_tty_hangup()`

```c
void tty_port_tty_hangup(struct tty_port *port, bool check_clocal)
```

helper to hang up a tty asynchronously

**Parameters**

- `struct tty_port *port`: tty port
- `bool check_clocal`: hang only ttys with `CLOCAL` unset?

#### <a id="c-tty_port_tty_vhangup"></a>`tty_port_tty_vhangup()`

```c
void tty_port_tty_vhangup(struct tty_port *port)
```

helper to hang up a tty synchronously

**Parameters**

- `struct tty_port *port`: tty port



#### <a id="c-tty_port_tty_wakeup"></a>`tty_port_tty_wakeup()`

```c
void tty_port_tty_wakeup(struct tty_port *port)
```

helper to wake up a tty

**Parameters**

- `struct tty_port *port`: tty port


<a id="rst-modem-signals"></a>

### Modem Signals


#### <a id="c-tty_port_carrier_raised"></a>`tty_port_carrier_raised()`

```c
bool tty_port_carrier_raised(struct tty_port *port)
```

carrier raised check

**Parameters**

- `struct tty_port *port`: tty port

**Description**

Wrapper for the carrier detect logic. For the moment this is used
to hide some internal details. This will eventually become entirely
internal to the tty port.

#### <a id="c-tty_port_raise_dtr_rts"></a>`tty_port_raise_dtr_rts()`

```c
void tty_port_raise_dtr_rts(struct tty_port *port)
```

Raise DTR/RTS

**Parameters**

- `struct tty_port *port`: tty port

**Description**

Wrapper for the DTR/RTS raise logic. For the moment this is used to hide
some internal details. This will eventually become entirely internal to the
tty port.

#### <a id="c-tty_port_lower_dtr_rts"></a>`tty_port_lower_dtr_rts()`

```c
void tty_port_lower_dtr_rts(struct tty_port *port)
```

Lower DTR/RTS

**Parameters**

- `struct tty_port *port`: tty port

**Description**

Wrapper for the DTR/RTS raise logic. For the moment this is used to hide
some internal details. This will eventually become entirely internal to the
tty port.


---

<a id="rst-tty-port-reference"></a>

## TTY Port Reference


#### <a id="c-struct-tty_port"></a>`struct tty_port`

- port level information

**Definition**

```c
struct tty_port {
    struct tty_bufhead      buf;
    struct tty_struct       *tty;
    struct tty_struct       *itty;
    const struct tty_port_operations *ops;
    const struct tty_port_client_operations *client_ops;
    spinlock_t lock;
    int blocked_open;
    int count;
    wait_queue_head_t open_wait;
    wait_queue_head_t delta_msr_wait;
    unsigned long           flags;
    unsigned long           iflags;
    unsigned char           console:1;
    struct mutex            mutex;
    struct mutex            buf_mutex;
    u8 *xmit_buf;
    u8 *xmit_fifo;
    unsigned int            close_delay;
    unsigned int            closing_wait;
    int drain_delay;
    struct kref             kref;
    void *client_data;
};
```

**Members**

- `buf`: buffer for this port, locked internally
- `tty`: back pointer to [`struct tty_struct`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct), valid only if the tty is open. Use
  [`tty_port_tty_get()`](#c-tty_port_tty_get) to obtain it (and [`tty_kref_put()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-tty_kref_put) to release).
- `itty`: internal back pointer to [`struct tty_struct`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct). Avoid this. It should be
  eliminated in the long term.
- `ops`: tty port operations (like activate, shutdown), see [`struct tty_port_operations`](#c-struct-tty_port_operations)
- `client_ops`: tty port client operations (like receive_buf, write_wakeup).
  By default, tty_port_default_client_ops is used.
- `lock`: lock protecting **tty**
- `blocked_open`: \# of procs waiting for open in [`tty_port_block_til_ready()`](#c-tty_port_block_til_ready)
- `count`: usage count
- `open_wait`: open waiters queue (waiting e.g. for a carrier)
- `delta_msr_wait`: modem status change queue (waiting for MSR changes)
- `flags`: user TTY flags (`ASYNC_`)
- `iflags`: internal flags (`TTY_PORT_`)
- `console`: when set, the port is a console
- `mutex`: locking, for open, shutdown and other port operations
- `buf_mutex`:

  **xmit_buf** alloc lock
- `xmit_buf`: optional xmit buffer used by some drivers
- `xmit_fifo`: optional xmit buffer used by some drivers
- `close_delay`: delay in jiffies to wait when closing the port
- `closing_wait`: delay in jiffies for output to be sent before closing
- `drain_delay`: set to zero if no pure time based drain is needed else set to
  size of fifo
- `kref`: references counter. Reaching zero calls **ops->destruct()** if non-`NULL`
  or frees the port otherwise.
- `client_data`: pointer to private data, for **client_ops**

**Description**

Each device keeps its own port level information. [`struct tty_port`](#c-struct-tty_port) was
introduced as a common structure for such information. As every TTY device
shall have a backing tty_port structure, every driver can use these members.

The tty port has a different lifetime to the tty so must be kept apart.
In addition be careful as tty -> port mappings are valid for the life
of the tty object but in many cases port -> tty mappings are valid only
until a hangup so don't use the wrong path.

Tty port shall be initialized by [`tty_port_init()`](#c-tty_port_init) and shut down either by
[`tty_port_destroy()`](#c-tty_port_destroy) (refcounting not used), or [`tty_port_put()`](#c-tty_port_put) (refcounting).

There is a lot of helpers around [`struct tty_port`](#c-struct-tty_port) too. To name the most
significant ones: [`tty_port_open()`](#c-tty_port_open), [`tty_port_close()`](#c-tty_port_close) (or
[`tty_port_close_start()`](#c-tty_port_close_start) and [`tty_port_close_end()`](#c-tty_port_close_end) separately if need be), and
[`tty_port_hangup()`](#c-tty_port_hangup). These call **ops->activate()** and **ops->shutdown()** as
needed.


---

<a id="rst-tty-port-operations-reference"></a>

## TTY Port Operations Reference


#### <a id="c-struct-tty_port_operations"></a>`struct tty_port_operations`

- operations on tty_port

**Definition**

```c
struct tty_port_operations {
    bool (*carrier_raised)(struct tty_port *port);
    void (*dtr_rts)(struct tty_port *port, bool active);
    void (*shutdown)(struct tty_port *port);
    int (*activate)(struct tty_port *port, struct tty_struct *tty);
    void (*destruct)(struct tty_port *port);
};
```

**Members**

- `carrier_raised`: return true if the carrier is raised on **port**
- `dtr_rts`: raise the DTR line if **active** is true, otherwise lower DTR
- `shutdown`: called when the last close completes or a hangup finishes IFF the
  port was initialized. Do not use to free resources. Turn off the device
  only. Called under the port mutex to serialize against **activate** and
  **shutdown**.
- `activate`: called under the port mutex from [`tty_port_open()`](#c-tty_port_open), serialized using
  the port mutex. Supposed to turn on the device.
- `destruct`: called on the final put of a port. Free resources, possibly incl.
  the port itself.

**Description**

FIXME: long term getting the tty argument *out* of this would be good
for consoles.

---

# TTY Struct

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Initialization

<a id="rst-tty-struct"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



struct tty_struct is allocated by the TTY layer upon the first open of the TTY device and released after the last close. The TTY layer passes this structure to most of struct tty_operation's hooks. Members of tty_struct are documented in [TTY Struct Reference](<#rst-tty-struct-reference>) at the bottom.

<a id="rst-initialization"></a>

## Initialization


#### <a id="c-tty_init_termios"></a>`tty_init_termios()`

```c
void tty_init_termios(struct tty_struct *tty)
```

helper for termios setup

**Parameters**

- `struct tty_struct *tty`: the tty to set up

**Description**

Initialise the termios structure for this tty. This runs under the
`tty_mutex` currently so we can be relaxed about ordering.


<a id="rst-name"></a>

## Name


#### <a id="c-tty_name"></a>`tty_name()`

```c
const char * tty_name(const struct tty_struct *tty)
```

return tty naming

**Parameters**

- `const struct tty_struct *tty`: tty structure

**Description**

Convert a tty structure into a name. The name reflects the kernel naming
policy and if udev is in use may not reflect user space

Locking: none


<a id="rst-reference-counting"></a>

## Reference counting


#### <a id="c-tty_kref_get"></a>`tty_kref_get()`

```c
struct tty_struct * tty_kref_get(struct tty_struct *tty)
```

get a tty reference

**Parameters**

- `struct tty_struct *tty`: tty device

**Return**

a new reference to a tty object

**Description**

Locking: The caller must hold sufficient locks/counts to ensure that their
existing reference cannot go away.



#### <a id="c-tty_kref_put"></a>`tty_kref_put()`

```c
void tty_kref_put(struct tty_struct *tty)
```

release a tty kref

**Parameters**

- `struct tty_struct *tty`: tty device

**Description**

Release a reference to the **tty** device and if need be let the kref layer
destruct the object for us.


<a id="rst-install"></a>

## Install


#### <a id="c-tty_standard_install"></a>`tty_standard_install()`

```c
int tty_standard_install(struct tty_driver *driver, struct tty_struct *tty)
```

usual tty->ops->install

**Parameters**

- `struct tty_driver *driver`: the driver for the tty
- `struct tty_struct *tty`: the tty

**Description**

If the **driver** overrides **tty->ops->install**, it still can call this function
to perform the standard install operations.


<a id="rst-read-write"></a>

## Read &amp; Write


#### <a id="c-tty_put_char"></a>`tty_put_char()`

```c
int tty_put_char(struct tty_struct *tty, u8 ch)
```

write one character to a tty

**Parameters**

- `struct tty_struct *tty`: tty
- `u8 ch`: character to write

**Description**

Write one byte to the **tty** using the provided **tty->ops->put_char()** method
if present.

**Note**

the specific put_char operation in the driver layer may go
away soon. Don't call it directly, use this method

**Return**

the number of characters successfully output.


<a id="rst-start-stop"></a>

## Start &amp; Stop


#### <a id="c-stop_tty"></a>`stop_tty()`

```c
void stop_tty(struct tty_struct *tty)
```

propagate flow control

**Parameters**

- `struct tty_struct *tty`: tty to stop

**Description**

Perform flow control to the driver. May be called on an already stopped
device and will not re-call the [`tty_driver->stop()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) method.

This functionality is used by both the line disciplines for halting incoming
flow and by the driver. It may therefore be called from any context, may be
under the tty `atomic_write_lock` but not always.

- Locking:
  flow.lock

#### <a id="c-start_tty"></a>`start_tty()`

```c
void start_tty(struct tty_struct *tty)
```

propagate flow control

**Parameters**

- `struct tty_struct *tty`: tty to start

**Description**

Start a tty that has been stopped if at all possible. If **tty** was previously
stopped and is now being started, the [`tty_driver->start()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) method is invoked
and the line discipline woken.

- Locking:
  flow.lock


<a id="rst-wakeup"></a>

## Wakeup


#### <a id="c-tty_wakeup"></a>`tty_wakeup()`

```c
void tty_wakeup(struct tty_struct *tty)
```

request more data

**Parameters**

- `struct tty_struct *tty`: terminal

**Description**

Internal and external helper for wakeups of tty. This function informs the
line discipline if present that the driver is ready to receive more output
data.


<a id="rst-hangup"></a>

## Hangup


#### <a id="c-tty_hangup"></a>`tty_hangup()`

```c
void tty_hangup(struct tty_struct *tty)
```

trigger a hangup event

**Parameters**

- `struct tty_struct *tty`: tty to hangup

**Description**

A carrier loss (virtual or otherwise) has occurred on **tty**. Schedule a
hangup sequence to run after this event.

#### <a id="c-tty_vhangup"></a>`tty_vhangup()`

```c
void tty_vhangup(struct tty_struct *tty)
```

process vhangup

**Parameters**

- `struct tty_struct *tty`: tty to hangup

**Description**

The user has asked via system call for the terminal to be hung up. We do
this synchronously so that when the syscall returns the process is complete.
That guarantee is necessary for security reasons.

#### <a id="c-tty_hung_up_p"></a>`tty_hung_up_p()`

```c
int tty_hung_up_p(struct file *filp)
```

was tty hung up

**Parameters**

- `struct file *filp`: file pointer of tty

**Return**

true if the tty has been subject to a vhangup or a carrier loss


<a id="rst-misc"></a>

## Misc


#### <a id="c-tty_do_resize"></a>`tty_do_resize()`

```c
int tty_do_resize(struct tty_struct *tty, struct winsize *ws)
```

resize event

**Parameters**

- `struct tty_struct *tty`: tty being resized
- `struct winsize *ws`: new dimensions

**Description**

Update the termios variables and send the necessary signals to peform a
terminal resize correctly.


<a id="rst-tty-struct-flags"></a>

## TTY Struct Flags


#### <a id="c-enum-tty_struct_flags"></a>`enum tty_struct_flags`

TTY Struct Flags

**Constants**

- `TTY_THROTTLED`: Driver input is throttled. The ldisc should call
  `tty_driver.unthrottle()` in order to resume reception when
  it is ready to process more data (at threshold min).
- `TTY_IO_ERROR`: If set, causes all subsequent userspace read/write calls on the tty to
  fail, returning -`EIO`. (May be no ldisc too.)
- `TTY_OTHER_CLOSED`: Device is a pty and the other side has closed.
- `TTY_EXCLUSIVE`: Exclusive open mode (a single opener).
- `TTY_DO_WRITE_WAKEUP`: If set, causes the driver to call the
  `tty_ldisc_ops.write_wakeup()` method in order to resume
  transmission when it can accept more data to transmit.
- `TTY_LDISC_OPEN`: Indicates that a line discipline is open. For debugging purposes only.
- `TTY_PTY_LOCK`: A flag private to pty code to implement `TIOCSPTLCK`/`TIOCGPTLCK` logic.
- `TTY_NO_WRITE_SPLIT`: Prevent driver from splitting up writes into smaller chunks (preserve
  write boundaries to driver).
- `TTY_HUPPED`: The TTY was hung up. This is set post `tty_driver.hangup()`.
- `TTY_HUPPING`: The TTY is in the process of hanging up to abort potential readers.
- `TTY_LDISC_CHANGING`: Line discipline for this TTY is being changed. I/O should not block
  when this is set. Use `tty_io_nonblock()` to check.
- `TTY_LDISC_HALTED`: Line discipline for this TTY was stopped. No work should be queued to
  this ldisc.

**Description**

These bits are used in the `tty_struct.flags` field.

So that interrupts won't be able to mess up the queues,
copy_to_cooked must be atomic with respect to itself, as must
tty->write.  Thus, you must use the inline functions [`set_bit()`](/kernel/internals/core-api/kernel-api.md#c-set_bit) and
[`clear_bit()`](/kernel/internals/core-api/kernel-api.md#c-clear_bit) to make things atomic.


<a id="rst-tty-struct-reference"></a>

## TTY Struct Reference


#### <a id="c-struct-tty_struct"></a>`struct tty_struct`

state associated with a tty while open

**Definition**

```c
struct tty_struct {
    struct kref kref;
    int index;
    struct device *dev;
    struct tty_driver *driver;
    struct tty_port *port;
    const struct tty_operations *ops;
    struct tty_ldisc *ldisc;
    struct ld_semaphore ldisc_sem;
    struct mutex atomic_write_lock;
    struct mutex legacy_mutex;
    struct mutex throttle_mutex;
    struct rw_semaphore termios_rwsem;
    struct mutex winsize_mutex;
    struct ktermios termios, termios_locked;
    char name[64];
    unsigned long flags;
    int count;
    unsigned int receive_room;
    struct winsize winsize;
    struct {
        spinlock_t lock;
        bool stopped;
        bool tco_stopped;
    } flow;
    struct {
        struct pid *pgrp;
        struct pid *session;
        spinlock_t lock;
        unsigned char pktstatus;
        bool packet;
    } ctrl;
    bool hw_stopped;
    bool closing;
    int flow_change;
    struct tty_struct *link;
    struct fasync_struct *fasync;
    wait_queue_head_t write_wait;
    wait_queue_head_t read_wait;
    struct work_struct hangup_work;
    void *disc_data;
    void *driver_data;
    spinlock_t files_lock;
    int write_cnt;
    u8 *write_buf;
    struct list_head tty_files;
    struct work_struct SAK_work;
};
```

**Members**

- `kref`: reference counting by [`tty_kref_get()`](#c-tty_kref_get) and [`tty_kref_put()`](#c-tty_kref_put), reaching zero
  frees the structure
- `index`: index of this tty (e.g. to construct **name** like tty12)
- `dev`: class device or `NULL` (e.g. ptys, serdev)
- `driver`: [`struct tty_driver`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) operating this tty
- `port`: persistent storage for this device (i.e. [`struct tty_port`](/kernel/hardware/driver-api/tty/tty-port.md#c-struct-tty_port))
- `ops`: [`struct tty_operations`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_operations) of **driver** for this tty (open, close, etc.)
- `ldisc`: the current line discipline for this tty (n_tty by default)
- `ldisc_sem`: protects line discipline changes (**ldisc**) -- lock tty not pty
- `atomic_write_lock`: protects against concurrent writers, i.e. locks
  **write_cnt**, **write_buf** and similar
- `legacy_mutex`: leftover from history (BKL -> BTM -> **legacy_mutex**),
  protecting several operations on this tty
- `throttle_mutex`: protects against concurrent [`tty_throttle_safe()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_throttle_safe) and
  [`tty_unthrottle_safe()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_unthrottle_safe) (but not [`tty_unthrottle()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_unthrottle))
- `termios_rwsem`: protects **termios** and **termios_locked**
- `winsize_mutex`: protects **winsize**
- `termios`: termios for the current tty, copied from/to **driver.termios**
- `termios_locked`: locked termios (by `TIOCGLCKTRMIOS` and `TIOCSLCKTRMIOS`
  ioctls)
- `name`: name of the tty constructed by [`tty_line_name()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-tty_line_name) (e.g. ttyS3)
- `flags`: bitwise OR of `TTY_THROTTLED`, `TTY_IO_ERROR`, ...
- `count`: count of open processes, reaching zero cancels all the work for
  this tty and drops a **kref** too (but does not free this tty)
- `receive_room`: bytes permitted to feed to **ldisc** without any being lost
- `winsize`: size of the terminal "window" (cf. **winsize_mutex**)
- `flow`: flow settings grouped together
- `flow.lock`: lock for **flow** members
- `flow.stopped`: tty stopped/started by [`stop_tty()`](#c-stop_tty)/[`start_tty()`](#c-start_tty)
- `flow.tco_stopped`: tty stopped/started by `TCOOFF`/`TCOON` ioctls (it has
  precedence over **flow.stopped**)
- `ctrl`: control settings grouped together
- `ctrl.pgrp`: process group of this tty (setpgrp(2))
- `ctrl.session`: session of this tty (setsid(2)). Writes are protected by both
  **ctrl.lock** and **legacy_mutex**, readers must use at least one of
  them.
- `ctrl.lock`: lock for **ctrl** members
- `ctrl.pktstatus`: packet mode status (bitwise OR of `TIOCPKT_` constants)
- `ctrl.packet`: packet mode enabled
- `hw_stopped`: not controlled by the tty layer, under **driver**'s control for CTS
  handling
- `closing`: when set during close, n_tty processes only START & STOP chars
- `flow_change`: controls behavior of throttling, see [`tty_throttle_safe()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_throttle_safe) and
  [`tty_unthrottle_safe()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_unthrottle_safe)
- `link`: link to another pty (master -> slave and vice versa)
- `fasync`: state for `O_ASYNC` (for `SIGIO`); managed by `fasync_helper()`
- `write_wait`: concurrent writers are waiting in this queue until they are
  allowed to write
- `read_wait`: readers wait for data in this queue
- `hangup_work`: normally a work to perform a hangup (`do_tty_hangup()`); while
  freeing the tty, (re)used to [`release_one_tty()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-release_one_tty)
- `disc_data`: pointer to **ldisc**'s private data (e.g. to `struct n_tty_data`)
- `driver_data`: pointer to **driver**'s private data (e.g. `struct uart_state`)
- `files_lock`: protects **tty_files** list
- `write_cnt`: count of bytes written in [`tty_write()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-tty_write) to **write_buf**
- `write_buf`: temporary buffer used during [`tty_write()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-tty_write) to copy user data to
- `tty_files`: list of (re)openers of this tty (i.e. linked `struct tty_file_private`)
- `SAK_work`: if the tty has a pending do_SAK, it is queued here

**Description**

All of the state associated with a tty while the tty is open. Persistent
storage for tty devices is referenced here as **port** and is documented in
[`struct tty_port`](/kernel/hardware/driver-api/tty/tty-port.md#c-struct-tty_port).

---

# Linux USB API

_Peios Kernel / Hardware and drivers / Driver development / USB_

> Reference for Linux USB API.

<a id="rst-linux-usb-api"></a>

- [The Linux-USB Host Side API](</kernel/hardware/driver-api/usb/usb.md>)
- [USB Gadget API for Linux](</kernel/hardware/driver-api/usb/gadget.md>)
- [USB Anchors](</kernel/hardware/driver-api/usb/anchors.md>)
- [USB bulk streams](</kernel/hardware/driver-api/usb/bulk-streams.md>)
- [USB core callbacks](</kernel/hardware/driver-api/usb/callbacks.md>)
- [USB DMA](</kernel/hardware/driver-api/usb/dma.md>)
- [USB Request Block (URB)](</kernel/hardware/driver-api/usb/urb.md>)
- [Power Management for USB](</kernel/hardware/driver-api/usb/power-management.md>)
- [USB hotplugging](</kernel/hardware/driver-api/usb/hotplug.md>)
- [USB device persistence during system suspend](</kernel/hardware/driver-api/usb/persist.md>)
- [USB Error codes](</kernel/hardware/driver-api/usb/error-codes.md>)
- [Writing USB Device Drivers](</kernel/hardware/driver-api/usb/writing-usb-driver.md>)
- [Synopsys DesignWare Core SuperSpeed USB 3.0 Controller](</kernel/hardware/driver-api/usb/dwc3.md>)
- [writing_musb_glue_layer](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/usb/writing_musb_glue_layer.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [USB Type-C connector class](</kernel/hardware/driver-api/usb/typec.md>)
- [API for USB Type-C Alternate Mode drivers](</kernel/hardware/driver-api/usb/typec-bus.md>)
- [USB3 debug port](</kernel/hardware/driver-api/usb/usb3-debug-port.md>)

---

# USB Request Block (URB)

_Peios Kernel / Hardware and drivers / Driver development / USB_

> The basic idea of the new driver is message passing, the message itself is called USB Request Block, or URB for short.

<a id="rst-usb-request-block-urb"></a>
<a id="rst-usb-urb"></a>

**Revised:** 2000-Dec-05

**Again:** 2002-Jul-06

**Again:** 2005-Sep-19

**Again:** 2017-Mar-29

> [!NOTE]
>
> The USB subsystem now has a substantial section at [The Linux-USB Host Side API](</kernel/hardware/driver-api/usb/usb.md#rst-usb-hostside-api>) section, generated from the current source code. This particular documentation file isn't complete and may not be updated to the last version; don't rely on it except for a quick overview.

<a id="rst-basic-concept-or-what-is-an-urb"></a>

## Basic concept or 'What is an URB?'

The basic idea of the new driver is message passing, the message itself is called USB Request Block, or URB for short.

- An URB consists of all relevant information to execute any USB transaction and deliver the data and status back.

- Execution of an URB is inherently an asynchronous operation, i.e. the `usb_submit_urb()` call returns immediately after it has successfully queued the requested action.

- Transfers for one URB can be canceled with `usb_unlink_urb()` at any time.

- Each URB has a completion handler, which is called after the action has been successfully completed or canceled. The URB also contains a context-pointer for passing information to the completion handler.

- Each endpoint for a device logically supports a queue of requests. You can fill that queue, so that the USB hardware can still transfer data to an endpoint while your driver handles completion of another. This maximizes use of USB bandwidth, and supports seamless streaming of data to (or from) devices when using periodic transfer modes.

<a id="rst-the-urb-structure"></a>

## The URB structure

Some of the fields in struct urb are:



```text
struct urb
{
// (IN) device and pipe specify the endpoint queue
      struct usb_device *dev;         // pointer to associated USB device
      unsigned int pipe;              // endpoint information

      unsigned int transfer_flags;    // URB_ISO_ASAP, URB_SHORT_NOT_OK, etc.

// (IN) all urbs need completion routines
      void *context;                  // context for completion routine
      usb_complete_t complete;        // pointer to completion routine

// (OUT) status after each completion
      int status;                     // returned status

// (IN) buffer used for data transfers
      void *transfer_buffer;          // associated data buffer
      u32 transfer_buffer_length;     // data buffer length
      int number_of_packets;          // size of iso_frame_desc

// (OUT) sometimes only part of CTRL/BULK/INTR transfer_buffer is used
      u32 actual_length;              // actual data buffer length

// (IN) setup stage for CTRL (pass a struct usb_ctrlrequest)
      unsigned char *setup_packet;    // setup packet (control only)

// Only for PERIODIC transfers (ISO, INTERRUPT)
  // (IN/OUT) start_frame is set unless URB_ISO_ASAP isn't set
      int start_frame;                // start frame
      int interval;                   // polling interval

  // ISO only: packets are only "best effort"; each can have errors
      int error_count;                // number of errors
      struct usb_iso_packet_descriptor iso_frame_desc[0];
};
```

Your driver must create the "pipe" value using values from the appropriate endpoint descriptor in an interface that it's claimed.

<a id="rst-how-to-get-an-urb"></a>

## How to get an URB?

URBs are allocated by calling `usb_alloc_urb()`:



```text
struct urb *usb_alloc_urb(int isoframes, int mem_flags)
```

Return value is a pointer to the allocated URB, 0 if allocation failed. The parameter isoframes specifies the number of isochronous transfer frames you want to schedule. For CTRL/BULK/INT, use 0.  The mem_flags parameter holds standard memory allocation flags, letting you control (among other things) whether the underlying code may block or not.

To free an URB, use `usb_free_urb()`:



```text
void usb_free_urb(struct urb *urb)
```

You may free an urb that you've submitted, but which hasn't yet been returned to you in a completion callback.  It will automatically be deallocated when it is no longer in use.

<a id="rst-what-has-to-be-filled-in"></a>

## What has to be filled in?

Depending on the type of transaction, there are some inline functions defined in `linux/usb.h` to simplify the initialization, such as `usb_fill_control_urb()`, `usb_fill_bulk_urb()` and `usb_fill_int_urb()`.  In general, they need the usb device pointer, the pipe (usual format from usb.h), the transfer buffer, the desired transfer length, the completion handler, and its context. Take a look at the some existing drivers to see how they're used.

Flags:

- For ISO there are two startup behaviors: Specified start_frame or ASAP.

- For ASAP set `URB_ISO_ASAP` in transfer_flags.

If short packets should NOT be tolerated, set `URB_SHORT_NOT_OK` in transfer_flags.

<a id="rst-how-to-submit-an-urb"></a>

## How to submit an URB?

Just call `usb_submit_urb()`:



```text
int usb_submit_urb(struct urb *urb, int mem_flags)
```

The `mem_flags` parameter, such as `GFP_ATOMIC`, controls memory allocation, such as whether the lower levels may block when memory is tight.

It immediately returns, either with status 0 (request queued) or some error code, usually caused by the following:

- Out of memory (`-ENOMEM`)

- Unplugged device (`-ENODEV`)

- Stalled endpoint (`-EPIPE`)

- Too many queued ISO transfers (`-EAGAIN`)

- Too many requested ISO frames (`-EFBIG`)

- Invalid INT interval (`-EINVAL`)

- More than one packet for INT (`-EINVAL`)

After submission, `urb->status` is `-EINPROGRESS`; however, you should never look at that value except in your completion callback.

For isochronous endpoints, your completion handlers should (re)submit URBs to the same endpoint with the `URB_ISO_ASAP` flag, using multi-buffering, to get seamless ISO streaming.

<a id="rst-how-to-cancel-an-already-running-urb"></a>

## How to cancel an already running URB?

There are two ways to cancel an URB you've submitted but which hasn't been returned to your driver yet.  For an asynchronous cancel, call `usb_unlink_urb()`:



```text
int usb_unlink_urb(struct urb *urb)
```

It removes the urb from the internal list and frees all allocated HW descriptors. The status is changed to reflect unlinking.  Note that the URB will not normally have finished when `usb_unlink_urb()` returns; you must still wait for the completion handler to be called.

To cancel an URB synchronously, call `usb_kill_urb()`:



```text
void usb_kill_urb(struct urb *urb)
```

It does everything `usb_unlink_urb()` does, and in addition it waits until after the URB has been returned and the completion handler has finished.  It also marks the URB as temporarily unusable, so that if the completion handler or anyone else tries to resubmit it they will get a `-EPERM` error.  Thus you can be sure that when `usb_kill_urb()` returns, the URB is totally idle.

There is a lifetime issue to consider.  An URB may complete at any time, and the completion handler may free the URB.  If this happens while `usb_unlink_urb()` or `usb_kill_urb()` is running, it will cause a memory-access violation.  The driver is responsible for avoiding this, which often means some sort of lock will be needed to prevent the URB from being deallocated while it is still in use.

On the other hand, since usb_unlink_urb may end up calling the completion handler, the handler must not take any lock that is held when usb_unlink_urb is invoked.  The general solution to this problem is to increment the URB's reference count while holding the lock, then drop the lock and call usb_unlink_urb or usb_kill_urb, and then decrement the URB's reference count.  You increment the reference count by calling :c:func\`usb_get_urb\`:



```text
struct urb *usb_get_urb(struct urb *urb)
```

(ignore the return value; it is the same as the argument) and decrement the reference count by calling `usb_free_urb()`.  Of course, none of this is necessary if there's no danger of the URB being freed by the completion handler.

<a id="rst-what-about-the-completion-handler"></a>

## What about the completion handler?

The handler is of the following type:



```text
typedef void (*usb_complete_t)(struct urb *)
```

I.e., it gets the URB that caused the completion call. In the completion handler, you should have a look at `urb->status` to detect any USB errors. Since the context parameter is included in the URB, you can pass information to the completion handler.

Note that even when an error (or unlink) is reported, data may have been transferred.  That's because USB transfers are packetized; it might take sixteen packets to transfer your 1KByte buffer, and ten of them might have transferred successfully before the completion was called.

> [!WARNING]
>
> NEVER SLEEP IN A COMPLETION HANDLER.
>
> These are often called in atomic context.

In the current kernel, completion handlers run with local interrupts disabled, but in the future this will be changed, so don't assume that local IRQs are always disabled inside completion handlers.

<a id="rst-how-to-do-isochronous-iso-transfers"></a>

## How to do isochronous (ISO) transfers?

Besides the fields present on a bulk transfer, for ISO, you also have to set `urb->interval` to say how often to make transfers; it's often one per frame (which is once every microframe for highspeed devices). The actual interval used will be a power of two that's no bigger than what you specify. You can use the `usb_fill_int_urb()` macro to fill most ISO transfer fields.

For ISO transfers you also have to fill a `usb_iso_packet_descriptor` structure, allocated at the end of the URB by `usb_alloc_urb()`, for each packet you want to schedule.

The `usb_submit_urb()` call modifies `urb->interval` to the implemented interval value that is less than or equal to the requested interval value.  If `URB_ISO_ASAP` scheduling is used, `urb->start_frame` is also updated.

For each entry you have to specify the data offset for this frame (base is transfer_buffer), and the length you want to write/expect to read. After completion, actual_length contains the actual transferred length and status contains the resulting status for the ISO transfer for this frame. It is allowed to specify a varying length from frame to frame (e.g. for audio synchronisation/adaptive transfer rates). You can also use the length 0 to omit one or more frames (striping).

For scheduling you can choose your own start frame or `URB_ISO_ASAP`. As explained earlier, if you always keep at least one URB queued and your completion keeps (re)submitting a later URB, you'll get smooth ISO streaming (if usb bandwidth utilization allows).

If you specify your own start frame, make sure it's several frames in advance of the current frame.  You might want this model if you're synchronizing ISO data with some other event stream.

<a id="rst-how-to-start-interrupt-int-transfers"></a>

## How to start interrupt (INT) transfers?

Interrupt transfers, like isochronous transfers, are periodic, and happen in intervals that are powers of two (1, 2, 4 etc) units.  Units are frames for full and low speed devices, and microframes for high speed ones. You can use the `usb_fill_int_urb()` macro to fill INT transfer fields.

The `usb_submit_urb()` call modifies `urb->interval` to the implemented interval value that is less than or equal to the requested interval value.

In Linux 2.6, unlike earlier versions, interrupt URBs are not automagically restarted when they complete.  They end when the completion handler is called, just like other URBs.  If you want an interrupt URB to be restarted, your completion handler must resubmit it. s

---

# USB Anchors

_Peios Kernel / Hardware and drivers / Driver development / USB_

> A USB driver needs to support some callbacks requiring a driver to cease all IO to an interface. To do so, a driver has to keep track of the URBs it has submitted to know they've all completed or to call usb_kill_urb for them. The anchor…

<a id="rst-usb-anchors"></a>

<a id="rst-what-is-anchor"></a>

## What is anchor?

A USB driver needs to support some callbacks requiring a driver to cease all IO to an interface. To do so, a driver has to keep track of the URBs it has submitted to know they've all completed or to call usb_kill_urb for them. The anchor is a data structure takes care of keeping track of URBs and provides methods to deal with multiple URBs.

<a id="rst-allocation-and-initialisation"></a>

## Allocation and Initialisation

There's no API to allocate an anchor. It is simply declared as struct usb_anchor. `init_usb_anchor()` must be called to initialise the data structure.

<a id="rst-deallocation"></a>

## Deallocation

Once it has no more URBs associated with it, the anchor can be freed with normal memory management operations.

<a id="rst-association-and-disassociation-of-urbs-with-anchors"></a>

## Association and disassociation of URBs with anchors

An association of URBs to an anchor is made by an explicit call to `usb_anchor_urb()`. The association is maintained until an URB is finished by (successful) completion. Thus disassociation is automatic. A function is provided to forcibly finish (kill) all URBs associated with an anchor. Furthermore, disassociation can be made with `usb_unanchor_urb()`

<a id="rst-operations-on-multitudes-of-urbs"></a>

## Operations on multitudes of URBs

<a id="rst-usb-kill-anchored-urbs"></a>

### `usb_kill_anchored_urbs()`

This function kills all URBs associated with an anchor. The URBs are called in the reverse temporal order they were submitted. This way no data can be reordered.

<a id="rst-usb-scuttle-anchored-urbs"></a>

### `usb_scuttle_anchored_urbs()`

All URBs of an anchor are unanchored en masse.

<a id="rst-usb-wait-anchor-empty-timeout"></a>

### `usb_wait_anchor_empty_timeout()`

This function waits for all URBs associated with an anchor to finish or a timeout, whichever comes first. Its return value will tell you whether the timeout was reached.

<a id="rst-usb-anchor-empty"></a>

### `usb_anchor_empty()`

Returns true if no URBs are associated with an anchor. Locking is the caller's responsibility.

<a id="rst-usb-get-from-anchor"></a>

### `usb_get_from_anchor()`

Returns the oldest anchored URB of an anchor. The URB is unanchored and returned with a reference. As you may mix URBs to several destinations in one anchor you have no guarantee the chronologically first submitted URB is returned.

---

# USB bulk streams

_Peios Kernel / Hardware and drivers / Driver development / USB_

> Bulk endpoint streams were added in the USB 3.0 specification. Streams allow a device driver to overload a bulk endpoint so that multiple transfers can be queued at once.

<a id="rst-usb-bulk-streams"></a>

<a id="rst-background"></a>

## Background

Bulk endpoint streams were added in the USB 3.0 specification.  Streams allow a device driver to overload a bulk endpoint so that multiple transfers can be queued at once.

Streams are defined in sections 4.4.6.4 and 8.12.1.4 of the Universal Serial Bus 3.0 specification at [https://www.usb.org/developers/docs/](<https://www.usb.org/developers/docs/>)  The USB Attached SCSI Protocol, which uses streams to queue multiple SCSI commands, can be found on the T10 website ([https://t10.org/](<https://t10.org/>)).

<a id="rst-device-side-implications"></a>

## Device-side implications

Once a buffer has been queued to a stream ring, the device is notified (through an out-of-band mechanism on another endpoint) that data is ready for that stream ID.  The device then tells the host which "stream" it wants to start.  The host can also initiate a transfer on a stream without the device asking, but the device can refuse that transfer.  Devices can switch between streams at any time.

<a id="rst-driver-implications"></a>

## Driver implications



```text
int usb_alloc_streams(struct usb_interface *interface,
              struct usb_host_endpoint **eps, unsigned int num_eps,
              unsigned int num_streams, gfp_t mem_flags);
```

Device drivers will call this API to request that the host controller driver allocate memory so the driver can use up to num_streams stream IDs.  They must pass an array of usb_host_endpoints that need to be setup with similar stream IDs.  This is to ensure that a UASP driver will be able to use the same stream ID for the bulk IN and OUT endpoints used in a Bi-directional command sequence.

The return value is an error condition (if one of the endpoints doesn't support streams, or the xHCI driver ran out of memory), or the number of streams the host controller allocated for this endpoint.  The xHCI host controller hardware declares how many stream IDs it can support, and each bulk endpoint on a SuperSpeed device will say how many stream IDs it can handle.  Therefore, drivers should be able to deal with being allocated less stream IDs than they requested.

Do NOT call this function if you have URBs enqueued for any of the endpoints passed in as arguments.  Do not call this function to request less than two streams.

Drivers will only be allowed to call this API once for the same endpoint without calling usb_free_streams().  This is a simplification for the xHCI host controller driver, and may change in the future.

<a id="rst-picking-new-stream-ids-to-use"></a>

## Picking new Stream IDs to use

Stream ID 0 is reserved, and should not be used to communicate with devices.  If usb_alloc_streams() returns with a value of N, you may use streams 1 though N. To queue an URB for a specific stream, set the urb-&gt;stream_id value.  If the endpoint does not support streams, an error will be returned.

Note that new API to choose the next stream ID will have to be added if the xHCI driver supports secondary stream IDs.

<a id="rst-clean-up"></a>

## Clean up

If a driver wishes to stop using streams to communicate with the device, it should call:



```text
void usb_free_streams(struct usb_interface *interface,
              struct usb_host_endpoint **eps, unsigned int num_eps,
              gfp_t mem_flags);
```

All stream IDs will be deallocated when the driver releases the interface, to ensure that drivers that don't support streams will be able to use the endpoint.

---

# USB core callbacks

_Peios Kernel / Hardware and drivers / Driver development / USB_

> Usbcore will call into a driver through callbacks defined in the driver structure and through the completion handler of URBs a driver submits. Only the former are in the scope of this document. These two kinds of callbacks are completely…

<a id="rst-usb-core-callbacks"></a>

<a id="rst-what-callbacks-will-usbcore-do"></a>

## What callbacks will usbcore do?

Usbcore will call into a driver through callbacks defined in the driver structure and through the completion handler of URBs a driver submits. Only the former are in the scope of this document. These two kinds of callbacks are completely independent of each other. Information on the completion callback can be found in [USB Request Block (URB)](</kernel/hardware/driver-api/usb/urb.md#rst-usb-urb>).

The callbacks defined in the driver structure are:

1. Hotplugging callbacks:

> - - **@probe:**
>
>     Called to see if the driver is willing to manage a particular interface on a device.
>
> - - **@disconnect:**
>
>     Called when the interface is no longer accessible, usually because its device has been (or is being) disconnected or the driver module is being unloaded.

2. Odd backdoor through usbfs:

> - - **@ioctl:**
>
>     Used for drivers that want to talk to userspace through the "usbfs" filesystem.  This lets devices provide ways to expose information to user space regardless of where they do (or don't) show up otherwise in the filesystem.

3. Power management (PM) callbacks:

> - - **@suspend:**
>
>     Called when the device is going to be suspended.
>
> - - **@resume:**
>
>     Called when the device is being resumed.
>
> - - **@reset_resume:**
>
>     Called when the suspended device has been reset instead of being resumed.

4. Device level operations:

> - - **@pre_reset:**
>
>     Called when the device is about to be reset.
>
> - - **@post_reset:**
>
>     Called after the device has been reset

The ioctl interface (2) should be used only if you have a very good reason. Sysfs is preferred these days. The PM callbacks are covered separately in [Power Management for USB](</kernel/hardware/driver-api/usb/power-management.md#rst-usb-power-management>).

<a id="rst-calling-conventions"></a>

## Calling conventions

All callbacks are mutually exclusive. There's no need for locking against other USB callbacks. All callbacks are called from a task context. You may sleep. However, it is important that all sleeps have a small fixed upper limit in time. In particular you must not call out to user space and await results.

<a id="rst-hotplugging-callbacks"></a>

## Hotplugging callbacks

These callbacks are intended to associate and disassociate a driver with an interface. A driver's bond to an interface is exclusive.

<a id="rst-the-probe-callback"></a>

### The probe() callback



```text
int (*probe) (struct usb_interface *intf,
              const struct usb_device_id *id);
```

Accept or decline an interface. If you accept the device return 0, otherwise -ENODEV or -ENXIO. Other error codes should be used only if a genuine error occurred during initialisation which prevented a driver from accepting a device that would else have been accepted. You are strongly encouraged to use usbcore's facility, usb_set_intfdata(), to associate a data structure with an interface, so that you know which internal state and identity you associate with a particular interface. The device will not be suspended and you may do IO to the interface you are called for and endpoint 0 of the device. Device initialisation that doesn't take too long is a good idea here.

<a id="rst-the-disconnect-callback"></a>

### The disconnect() callback



```text
void (*disconnect) (struct usb_interface *intf);
```

This callback is a signal to break any connection with an interface. You are not allowed any IO to a device after returning from this callback. You also may not do any other operation that may interfere with another driver bound to the interface, eg. a power management operation. Outstanding operations on the device must be completed or aborted before this callback may return.

If you are called due to a physical disconnection, all your URBs will be killed by usbcore. Note that in this case disconnect will be called some time after the physical disconnection. Thus your driver must be prepared to deal with failing IO even prior to the callback.

<a id="rst-device-level-callbacks"></a>

## Device level callbacks

<a id="rst-pre-reset"></a>

### pre_reset



```text
int (*pre_reset)(struct usb_interface *intf);
```

A driver or user space is triggering a reset on the device which contains the interface passed as an argument. Cease IO, wait for all outstanding URBs to complete, and save any device state you need to restore.  No more URBs may be submitted until the post_reset method is called.

If you need to allocate memory here, use GFP_NOIO or GFP_ATOMIC, if you are in atomic context.

<a id="rst-post-reset"></a>

### post_reset



```text
int (*post_reset)(struct usb_interface *intf);
```

The reset has completed.  Restore any saved device state and begin using the device again.

If you need to allocate memory here, use GFP_NOIO or GFP_ATOMIC, if you are in atomic context.

<a id="rst-call-sequences"></a>

## Call sequences

No callbacks other than probe will be invoked for an interface that isn't bound to your driver.

Probe will never be called for an interface bound to a driver. Hence following a successful probe, disconnect will be called before there is another probe for the same interface.

Once your driver is bound to an interface, disconnect can be called at any time except in between pre_reset and post_reset. pre_reset is always followed by post_reset, even if the reset failed or the device has been unplugged.

suspend is always followed by one of: resume, reset_resume, or disconnect.

---

# USB DMA

_Peios Kernel / Hardware and drivers / Driver development / USB_

> In Linux 2.5 kernels (and later), USB device drivers have additional control over how DMA may be used to perform I/O operations. The APIs are detailed in the kernel usb programming guide (kerneldoc, from the source code).

<a id="rst-usb-dma"></a>

In Linux 2.5 kernels (and later), USB device drivers have additional control over how DMA may be used to perform I/O operations.  The APIs are detailed in the kernel usb programming guide (kerneldoc, from the source code).

<a id="rst-api-overview"></a>

## API overview

The big picture is that USB drivers can continue to ignore most DMA issues, though they still must provide DMA-ready buffers (see [Documentation/core-api/dma-api-howto.rst](/kernel/internals/core-api/dma-api-howto.md)).  That's how they've worked through the 2.4 (and earlier) kernels, or they can now be DMA-aware.

DMA-aware usb drivers:

- New calls enable DMA-aware drivers, letting them allocate dma buffers and manage dma mappings for existing dma-ready buffers (see below).

- URBs have an additional "transfer_dma" field, as well as a transfer_flags bit saying if it's valid.  (Control requests also have "setup_dma", but drivers must not use it.)

- "usbcore" will map this DMA address, if a DMA-aware driver didn't do it first and set `URB_NO_TRANSFER_DMA_MAP`.  HCDs don't manage dma mappings for URBs.

- There's a new "generic DMA API", parts of which are usable by USB device drivers.  Never use dma_set_mask() on any USB interface or device; that would potentially break all devices sharing that bus.

<a id="rst-eliminating-copies"></a>

## Eliminating copies

It's good to avoid making CPUs copy data needlessly.  The costs can add up, and effects like cache-trashing can impose subtle penalties.

- If you're doing lots of small data transfers from the same buffer all the time, that can really burn up resources on systems which use an IOMMU to manage the DMA mappings.  It can cost MUCH more to set up and tear down the IOMMU mappings with each request than perform the I/O\!

  For those specific cases, USB has primitives to allocate less expensive memory.  They work like kmalloc and kfree versions that give you the right kind of addresses to store in urb-&gt;transfer_buffer and urb-&gt;transfer_dma. You'd also set `URB_NO_TRANSFER_DMA_MAP` in urb-&gt;transfer_flags:



  ```text
  void *usb_alloc_coherent (struct usb_device *dev, size_t size,
          int mem_flags, dma_addr_t *dma);

  void usb_free_coherent (struct usb_device *dev, size_t size,
          void *addr, dma_addr_t dma);
  ```

  Most drivers should **NOT** be using these primitives; they don't need to use this type of memory ("dma-coherent"), and memory returned from `kmalloc()` will work just fine.

  The memory buffer returned is "dma-coherent"; sometimes you might need to force a consistent memory access ordering by using memory barriers.  It's not using a streaming DMA mapping, so it's good for small transfers on systems where the I/O would otherwise thrash an IOMMU mapping.  (See [Documentation/core-api/dma-api-howto.rst](/kernel/internals/core-api/dma-api-howto.md) for definitions of "coherent" and "streaming" DMA mappings.)

  Asking for 1/Nth of a page (as well as asking for N pages) is reasonably space-efficient.

  On most systems the memory returned will be uncached, because the semantics of dma-coherent memory require either bypassing CPU caches or using cache hardware with bus-snooping support.  While x86 hardware has such bus-snooping, many other systems use software to flush cache lines to prevent DMA conflicts.

- Devices on some EHCI controllers could handle DMA to/from high memory.

  Unfortunately, the current Linux DMA infrastructure doesn't have a sane way to expose these capabilities ... and in any case, HIGHMEM is mostly a design wart specific to x86_32.  So your best bet is to ensure you never pass a highmem buffer into a USB driver.  That's easy; it's the default behavior.  Just don't override it; e.g. with `NETIF_F_HIGHDMA`.

  This may force your callers to do some bounce buffering, copying from high memory to "normal" DMA memory.  If you can come up with a good way to fix this issue (for x86_32 machines with over 1 GByte of memory), feel free to submit patches.

<a id="rst-working-with-existing-buffers"></a>

## Working with existing buffers

Existing buffers aren't usable for DMA without first being mapped into the DMA address space of the device.  However, most buffers passed to your driver can safely be used with such DMA mapping.  (See the first section of [Documentation/core-api/dma-api-howto.rst](/kernel/internals/core-api/dma-api-howto.md), titled "What memory is DMA-able?")

- When you have the scatterlists which have been mapped for the USB controller, you could use the new `usb_sg_*()` calls, which would turn scatterlist into URBs:



  ```text
  int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
          unsigned pipe, unsigned period, struct scatterlist *sg,
          int nents, size_t length, gfp_t mem_flags);

  void usb_sg_wait(struct usb_sg_request *io);

  void usb_sg_cancel(struct usb_sg_request *io);
  ```

  When the USB controller doesn't support DMA, the `usb_sg_init()` would try to submit URBs in PIO way as long as the page in scatterlists is not in the Highmem, which could be very rare in modern architectures.

---

# Synopsys DesignWare Core SuperSpeed USB 3.0 Controller

_Peios Kernel / Hardware and drivers / Driver development / USB_

> The Synopsys DesignWare Core SuperSpeed USB 3.0 Controller (hereinafter referred to as DWC3) is a USB SuperSpeed compliant controller which can be configured in one of 4 ways:

<a id="rst-synopsys-designware-core-superspeed-usb-3-0-controller"></a>

**Author:** Felipe Balbi &lt;[felipe.balbi@linux.intel.com](<mailto:felipe.balbi@linux.intel.com>)&gt;

**Date:** April 2017

<a id="rst-introduction"></a>

## Introduction

The *Synopsys DesignWare Core SuperSpeed USB 3.0 Controller* (hereinafter referred to as *DWC3*) is a USB SuperSpeed compliant controller which can be configured in one of 4 ways:

> 1. Peripheral-only configuration
>
> 2. Host-only configuration
>
> 3. Dual-Role configuration
>
> 4. Hub configuration

Linux currently supports several versions of this controller. In all likelihood, the version in your SoC is already supported. At the time of this writing, known tested versions range from 2.02a to 3.10a. As a rule of thumb, anything above 2.02a should work reliably well.

Currently, we have many known users for this driver. In alphabetical order:

> 1. Cavium
>
> 2. Intel Corporation
>
> 3. Qualcomm
>
> 4. Rockchip
>
> 5. ST
>
> 6. Samsung
>
> 7. Texas Instruments
>
> 8. Xilinx

<a id="rst-summary-of-features"></a>

## Summary of Features

For details about features supported by your version of DWC3, consult your IP team and/or *Synopsys DesignWare Core SuperSpeed USB 3.0 Controller Databook*. Following is a list of features supported by the driver at the time of this writing:

> 1. Up to 16 bidirectional endpoints (including the control pipe - ep0)
>
> 2. Flexible endpoint configuration
>
> 3. Simultaneous IN and OUT transfer support
>
> 4. Scatter-list support
>
> 5. Up to 256 TRBs <a id="rst-footnote-reference-1"></a>[1](#rst-trb) per endpoint
>
> 6. Support for all transfer types (*Control*, *Bulk*, *Interrupt*, and *Isochronous*)
>
> 7. SuperSpeed Bulk Streams
>
> 8. Link Power Management
>
> 9. Trace Events for debugging
>
> 10. DebugFS <a id="rst-footnote-reference-2"></a>[3](#rst-debugfs-1) interface

These features have all been exercised with many of the **in-tree** gadget drivers. We have verified both *ConfigFS* <a id="rst-footnote-reference-3"></a>[4](#rst-configfs) and legacy gadget drivers.

<a id="rst-driver-design"></a>

## Driver Design

The DWC3 driver sits on the *drivers/usb/dwc3/* directory. All files related to this driver are in this one directory. This makes it easy for new-comers to read the code and understand how it behaves.

Because of DWC3's configuration flexibility, the driver is a little complex in some places but it should be rather straightforward to understand.

The biggest part of the driver refers to the Gadget API.

<a id="rst-known-limitations"></a>

## Known Limitations

Like any other HW, DWC3 has its own set of limitations. To avoid constant questions about such problems, we decided to document them here and have a single location to where we could point users.

<a id="rst-out-transfer-size-requirements"></a>

### OUT Transfer Size Requirements

According to Synopsys Databook, all OUT transfer TRBs <a id="rst-footnote-reference-4"></a>[1](#rst-trb) must have their *size* field set to a value which is integer divisible by the endpoint's *wMaxPacketSize*. This means that *e.g.* in order to receive a Mass Storage *CBW* <a id="rst-footnote-reference-5"></a>[5](#rst-cbw), req-&gt;length must either be set to a value that's divisible by *wMaxPacketSize* (1024 on SuperSpeed, 512 on HighSpeed, etc), or DWC3 driver must add a Chained TRB pointing to a throw-away buffer for the remaining length. Without this, OUT transfers will **NOT** start.

Note that as of this writing, this won't be a problem because DWC3 is fully capable of appending a chained TRB for the remaining length and completely hide this detail from the gadget driver. It's still worth mentioning because this seems to be the largest source of queries about DWC3 and *non-working transfers*.

<a id="rst-trb-ring-size-limitation"></a>

### TRB Ring Size Limitation

We, currently, have a hard limit of 256 TRBs <a id="rst-footnote-reference-6"></a>[1](#rst-trb) per endpoint, with the last TRB being a Link TRB <a id="rst-footnote-reference-7"></a>[2](#rst-link-trb) pointing back to the first. This limit is arbitrary but it has the benefit of adding up to exactly 4096 bytes, or 1 Page.

DWC3 driver will try its best to cope with more than 255 requests and, for the most part, it should work normally. However this is not something that has been exercised very frequently. If you experience any problems, see section **Reporting Bugs** below.

<a id="rst-reporting-bugs"></a>

## Reporting Bugs

Whenever you encounter a problem with DWC3, first and foremost you should make sure that:

> 1. You're running latest tag from [Linus' tree](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/>)
>
> 2. You can reproduce the error without any out-of-tree changes to DWC3
>
> 3. You have checked that it's not a fault on the host machine

After all these are verified, then here's how to capture enough information so we can be of any help to you.

<a id="rst-required-information"></a>

### Required Information

DWC3 relies exclusively on Trace Events for debugging. Everything is exposed there, with some extra bits being exposed to DebugFS <a id="rst-footnote-reference-8"></a>[3](#rst-debugfs-1).

In order to capture DWC3's Trace Events you should run the following commands **before** plugging the USB cable to a host machine:



```sh
# mkdir -p /d
# mkdir -p /t
# mount -t debugfs none /d
# mount -t tracefs none /t
# echo 81920 > /t/buffer_size_kb
# echo 1 > /t/events/dwc3/enable
```

After this is done, you can connect your USB cable and reproduce the problem. As soon as the fault is reproduced, make a copy of files `trace` and `regdump`, like so:



```sh
# cp /t/trace /root/trace.txt
# cat /d/*dwc3*/regdump > /root/regdump.txt
```

Make sure to compress `trace.txt` and `regdump.txt` in a tarball and email it to [me](<mailto:felipe.balbi@linux.intel.com>) with [linux-usb](<mailto:linux-usb@vger.kernel.org>) in Cc. If you want to be extra sure that I'll help you, write your subject line in the following format:

> **\[BUG REPORT\] usb: dwc3: Bug while doing XYZ**

On the email body, make sure to detail what you doing, which gadget driver you were using, how to reproduce the problem, what SoC you're using, which OS (and its version) was running on the Host machine.

With all this information, we should be able to understand what's going on and be helpful to you.

<a id="rst-debugging"></a>

## Debugging

First and foremost a disclaimer:



```text
DISCLAIMER: The information available on DebugFS and/or TraceFS can
change at any time at any Major Linux Kernel Release. If writing
scripts, do **NOT** assume information to be available in the
current format.
```

With that out of the way, let's carry on.

If you're willing to debug your own problem, you deserve a round of applause :-)

Anyway, there isn't much to say here other than Trace Events will be really helpful in figuring out issues with DWC3. Also, access to Synopsys Databook will be **really** valuable in this case.

A USB Sniffer can be helpful at times but it's not entirely required, there's a lot that can be understood without looking at the wire.

Feel free to email [me](<mailto:felipe.balbi@linux.intel.com>) and Cc [linux-usb](<mailto:linux-usb@vger.kernel.org>) if you need any help.

<a id="rst-debugfs"></a>

### `DebugFS`

`DebugFS` is very good for gathering snapshots of what's going on with DWC3 and/or any endpoint.

On DWC3's `DebugFS` directory, you will find the following files and directories:

`ep[0..15]{in,out}/` `link_state` `regdump` `testmode`

<a id="rst-link-state"></a>

#### `link_state`

When read, `link_state` will print out one of `U0`, `U1`, `U2`, `U3`, `SS.Disabled`, `RX.Detect`, `SS.Inactive`, `Polling`, `Recovery`, `Hot Reset`, `Compliance`, `Loopback`, `Reset`, `Resume` or `UNKNOWN link state`.

This file can also be written to in order to force link to one of the states above.

<a id="rst-regdump"></a>

#### `regdump`

File name is self-explanatory. When read, `regdump` will print out a register dump of DWC3. Note that this file can be grepped to find the information you want.

<a id="rst-testmode"></a>

#### `testmode`

When read, `testmode` will print out a name of one of the specified USB 2.0 Testmodes (`test_j`, `test_k`, `test_se0_nak`, `test_packet`, `test_force_enable`) or the string `no test` in case no tests are currently being executed.

In order to start any of these test modes, the same strings can be written to the file and DWC3 will enter the requested test mode.

<a id="rst-ep-0-15-in-out"></a>

#### `ep[0..15]{in,out}`

For each endpoint we expose one directory following the naming convention `ep$num$dir` *(ep0in, ep0out, ep1in, ...)*. Inside each of these directories you will find the following files:

`descriptor_fetch_queue` `event_queue` `rx_fifo_queue` `rx_info_queue` `rx_request_queue` `transfer_type` `trb_ring` `tx_fifo_queue` `tx_request_queue`

With access to Synopsys Databook, you can decode the information on them.

<a id="rst-transfer-type"></a>

##### `transfer_type`

When read, `transfer_type` will print out one of `control`, `bulk`, `interrupt` or `isochronous` depending on what the endpoint descriptor says. If the endpoint hasn't been enabled yet, it will print `--`.

<a id="rst-trb-ring"></a>

##### `trb_ring`

When read, `trb_ring` will print out details about all TRBs on the ring. It will also tell you where our enqueue and dequeue pointers are located in the ring:



```sh
buffer_addr,size,type,ioc,isp_imi,csp,chn,lst,hwo
000000002c754000,481,normal,1,0,1,0,0,0
000000002c75c000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c754000,481,normal,1,0,1,0,0,0
000000002c75c000,481,normal,1,0,1,0,0,0
000000002c784000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c784000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c754000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c784000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c784000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c754000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c75c000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c754000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c754000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c754000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c75c000,481,normal,1,0,1,0,0,0
000000002c780000,481,normal,1,0,1,0,0,0
000000002c784000,481,normal,1,0,1,0,0,0
000000002c788000,481,normal,1,0,1,0,0,0
000000002c78c000,481,normal,1,0,1,0,0,0
000000002c790000,481,normal,1,0,1,0,0,0
000000002c754000,481,normal,1,0,1,0,0,0
000000002c758000,481,normal,1,0,1,0,0,0
000000002c75c000,512,normal,1,0,1,0,0,1        D
0000000000000000,0,UNKNOWN,0,0,0,0,0,0       E
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
0000000000000000,0,UNKNOWN,0,0,0,0,0,0
00000000381ab000,0,link,0,0,0,0,0,1
```

<a id="rst-trace-events"></a>

### Trace Events

DWC3 also provides several trace events which help us gathering information about the behavior of the driver during runtime.

In order to use these events, you must enable `CONFIG_FTRACE` in your kernel config.

For details about how enable DWC3 events, see section **Reporting Bugs**.

The following subsections will give details about each Event Class and each Event defined by DWC3.

<a id="rst-mmio"></a>

#### MMIO

It is sometimes useful to look at every MMIO access when looking for bugs. Because of that, DWC3 offers two Trace Events (one for dwc3_readl() and one for dwc3_writel()). `TP_printk` follows:



```text
TP_printk("addr %p value %08x", __entry->base + __entry->offset,
              __entry->value)
```

<a id="rst-interrupt-events"></a>

#### Interrupt Events

Every IRQ event can be logged and decoded into a human readable string. Because every event will be different, we don't give an example other than the `TP_printk` format used:



```text
TP_printk("event (%08x): %s", __entry->event,
              dwc3_decode_event(__entry->event, __entry->ep0state))
```

<a id="rst-control-request"></a>

#### Control Request

Every USB Control Request can be logged to the trace buffer. The output format is:



```text
TP_printk("%s", dwc3_decode_ctrl(__entry->bRequestType,
                              __entry->bRequest, __entry->wValue,
                              __entry->wIndex, __entry->wLength)
)
```

Note that Standard Control Requests will be decoded into human-readable strings with their respective arguments. Class and Vendor requests will be printed out a sequence of 8 bytes in hex format.

<a id="rst-lifetime-of-a-struct-usb-request"></a>

#### Lifetime of a `struct usb_request`

The entire lifetime of a `struct usb_request` can be tracked on the trace buffer. We have one event for each of allocation, free, queueing, dequeueing, and giveback. Output format is:



```text
TP_printk("%s: req %p length %u/%u %s%s%s ==> %d",
      __get_str(name), __entry->req, __entry->actual, __entry->length,
      __entry->zero ? "Z" : "z",
      __entry->short_not_ok ? "S" : "s",
      __entry->no_interrupt ? "i" : "I",
      __entry->status
)
```

<a id="rst-generic-commands"></a>

#### Generic Commands

We can log and decode every Generic Command with its completion code. Format is:



```text
TP_printk("cmd '%s' [%x] param %08x --> status: %s",
      dwc3_gadget_generic_cmd_string(__entry->cmd),
      __entry->cmd, __entry->param,
      dwc3_gadget_generic_cmd_status_string(__entry->status)
)
```

<a id="rst-endpoint-commands"></a>

#### Endpoint Commands

Endpoints commands can also be logged together with completion code. Format is:



```text
TP_printk("%s: cmd '%s' [%d] params %08x %08x %08x --> status: %s",
      __get_str(name), dwc3_gadget_ep_cmd_string(__entry->cmd),
      __entry->cmd, __entry->param0,
      __entry->param1, __entry->param2,
      dwc3_ep_cmd_status_string(__entry->cmd_status)
)
```

<a id="rst-lifetime-of-a-trb"></a>

#### Lifetime of a `TRB`

A `TRB` Lifetime is simple. We are either preparing a `TRB` or completing it. With these two events, we can see how a `TRB` changes over time. Format is:



```text
TP_printk("%s: %d/%d trb %p buf %08x%08x size %s%d ctrl %08x (%c%c%c%c:%c%c:%s)",
      __get_str(name), __entry->queued, __entry->allocated,
      __entry->trb, __entry->bph, __entry->bpl,
      ({char *s;
      int pcm = ((__entry->size >> 24) & 3) + 1;
      switch (__entry->type) {
      case USB_ENDPOINT_XFER_INT:
      case USB_ENDPOINT_XFER_ISOC:
              switch (pcm) {
              case 1:
                      s = "1x ";
                      break;
              case 2:
                      s = "2x ";
                      break;
              case 3:
                      s = "3x ";
                      break;
              }
      default:
              s = "";
      } s; }),
      DWC3_TRB_SIZE_LENGTH(__entry->size), __entry->ctrl,
      __entry->ctrl & DWC3_TRB_CTRL_HWO ? 'H' : 'h',
      __entry->ctrl & DWC3_TRB_CTRL_LST ? 'L' : 'l',
      __entry->ctrl & DWC3_TRB_CTRL_CHN ? 'C' : 'c',
      __entry->ctrl & DWC3_TRB_CTRL_CSP ? 'S' : 's',
      __entry->ctrl & DWC3_TRB_CTRL_ISP_IMI ? 'S' : 's',
      __entry->ctrl & DWC3_TRB_CTRL_IOC ? 'C' : 'c',
    dwc3_trb_type_string(DWC3_TRBCTL_TYPE(__entry->ctrl))
)
```

<a id="rst-lifetime-of-an-endpoint"></a>

#### Lifetime of an Endpoint

And endpoint's lifetime is summarized with enable and disable operations, both of which can be traced. Format is:



```text
TP_printk("%s: mps %d/%d streams %d burst %d ring %d/%d flags %c:%c%c%c%c%c:%c:%c",
      __get_str(name), __entry->maxpacket,
      __entry->maxpacket_limit, __entry->max_streams,
      __entry->maxburst, __entry->trb_enqueue,
      __entry->trb_dequeue,
      __entry->flags & DWC3_EP_ENABLED ? 'E' : 'e',
      __entry->flags & DWC3_EP_STALL ? 'S' : 's',
      __entry->flags & DWC3_EP_WEDGE ? 'W' : 'w',
      __entry->flags & DWC3_EP_TRANSFER_STARTED ? 'B' : 'b',
      __entry->flags & DWC3_EP_PENDING_REQUEST ? 'P' : 'p',
      __entry->flags & DWC3_EP_END_TRANSFER_PENDING ? 'E' : 'e',
      __entry->direction ? '<' : '>'
)
```

<a id="rst-structures-methods-and-definitions"></a>

## Structures, Methods and Definitions


#### <a id="c-struct-dwc3_event_buffer"></a>`struct dwc3_event_buffer`

Software event buffer representation

**Definition**

```c
struct dwc3_event_buffer {
        void *buf;
        void *cache;
        unsigned int            length;
        unsigned int            lpos;
        unsigned int            count;
        unsigned int            flags;
    #define DWC3_EVENT_PENDING      BIT(0);
        dma_addr_t dma;
        struct dwc3             *dwc;
};
```

**Members**

- `buf`: _THE_ buffer
- `cache`: The buffer cache used in the threaded interrupt
- `length`: size of this buffer
- `lpos`: event offset
- `count`: cache of last read event count register
- `flags`: flags related to this event buffer
- `dma`: dma_addr_t
- `dwc`: pointer to DWC controller

#### <a id="c-struct-dwc3_ep"></a>`struct dwc3_ep`

device side endpoint representation

**Definition**

```c
struct dwc3_ep {
        struct usb_ep           endpoint;
        struct delayed_work     nostream_work;
        struct list_head        cancelled_list;
        struct list_head        pending_list;
        struct list_head        started_list;
        struct dwc3_trb         *trb_pool;
        dma_addr_t trb_pool_dma;
        struct dwc3             *dwc;
        u32 saved_state;
        unsigned int            flags;
    #define DWC3_EP_ENABLED                 BIT(0);
    #define DWC3_EP_STALL                   BIT(1);
    #define DWC3_EP_WEDGE                   BIT(2);
    #define DWC3_EP_TRANSFER_STARTED        BIT(3);
    #define DWC3_EP_END_TRANSFER_PENDING    BIT(4);
    #define DWC3_EP_PENDING_REQUEST         BIT(5);
    #define DWC3_EP_DELAY_START             BIT(6);
    #define DWC3_EP_WAIT_TRANSFER_COMPLETE  BIT(7);
    #define DWC3_EP_IGNORE_NEXT_NOSTREAM    BIT(8);
    #define DWC3_EP_FORCE_RESTART_STREAM    BIT(9);
    #define DWC3_EP_STREAM_PRIMED           BIT(10);
    #define DWC3_EP_PENDING_CLEAR_STALL     BIT(11);
    #define DWC3_EP_TXFIFO_RESIZED          BIT(12);
    #define DWC3_EP_DELAY_STOP             BIT(13);
    #define DWC3_EP_RESOURCE_ALLOCATED      BIT(14);
    #define DWC3_EP0_DIR_IN                 BIT(31);
        u8 trb_enqueue;
        u8 trb_dequeue;
        u8 number;
        u8 type;
        u8 resource_index;
        u32 frame_number;
        u32 interval;
        char name[20];
        unsigned direction:1;
        unsigned stream_capable:1;
        u8 combo_num;
        int start_cmd_status;
};
```

**Members**

- `endpoint`: usb endpoint
- `nostream_work`: work for handling bulk NoStream
- `cancelled_list`: list of cancelled requests for this endpoint
- `pending_list`: list of pending requests for this endpoint
- `started_list`: list of started requests on this endpoint
- `trb_pool`: array of transaction buffers
- `trb_pool_dma`: dma address of **trb_pool**
- `dwc`: pointer to DWC controller
- `saved_state`: ep state saved during hibernation
- `flags`: endpoint flags (wedged, stalled, ...)
- `trb_enqueue`: enqueue 'pointer' into TRB array
- `trb_dequeue`: dequeue 'pointer' into TRB array
- `number`: endpoint number (1 - 15)
- `type`: set to bmAttributes & USB_ENDPOINT_XFERTYPE_MASK
- `resource_index`: Resource transfer index
- `frame_number`: set to the frame number we want this transfer to start (ISOC)
- `interval`: the interval on which the ISOC transfer is started
- `name`: a human readable name e.g. ep1out-bulk
- `direction`: true for TX, false for RX
- `stream_capable`: true when streams are enabled
- `combo_num`: the test combination BIT\[15:14\] of the frame number to test
  isochronous START TRANSFER command failure workaround
- `start_cmd_status`: the status of testing START TRANSFER command with
  combo_num = 'b00

#### <a id="c-struct-dwc3_trb"></a>`struct dwc3_trb`

transfer request block (hw format)

**Definition**

```c
struct dwc3_trb {
    u32 bpl;
    u32 bph;
    u32 size;
    u32 ctrl;
};
```

**Members**

- `bpl`: DW0-3
- `bph`: DW4-7
- `size`: DW8-B
- `ctrl`: DWC-F

#### <a id="c-struct-dwc3_hwparams"></a>`struct dwc3_hwparams`

copy of HWPARAMS registers

**Definition**

```c
struct dwc3_hwparams {
    u32 hwparams0;
    u32 hwparams1;
    u32 hwparams2;
    u32 hwparams3;
    u32 hwparams4;
    u32 hwparams5;
    u32 hwparams6;
    u32 hwparams7;
    u32 hwparams8;
    u32 hwparams9;
};
```

**Members**

- `hwparams0`: GHWPARAMS0
- `hwparams1`: GHWPARAMS1
- `hwparams2`: GHWPARAMS2
- `hwparams3`: GHWPARAMS3
- `hwparams4`: GHWPARAMS4
- `hwparams5`: GHWPARAMS5
- `hwparams6`: GHWPARAMS6
- `hwparams7`: GHWPARAMS7
- `hwparams8`: GHWPARAMS8
- `hwparams9`: GHWPARAMS9

#### <a id="c-struct-dwc3_request"></a>`struct dwc3_request`

representation of a transfer request

**Definition**

```c
struct dwc3_request {
        struct usb_request      request;
        struct list_head        list;
        struct dwc3_ep          *dep;
        struct scatterlist      *start_sg;
        unsigned int            num_pending_sgs;
        unsigned int            remaining;
        unsigned int            status;
    #define DWC3_REQUEST_STATUS_QUEUED              0;
    #define DWC3_REQUEST_STATUS_STARTED             1;
    #define DWC3_REQUEST_STATUS_DISCONNECTED        2;
    #define DWC3_REQUEST_STATUS_DEQUEUED            3;
    #define DWC3_REQUEST_STATUS_STALLED             4;
    #define DWC3_REQUEST_STATUS_COMPLETED           5;
    #define DWC3_REQUEST_STATUS_UNKNOWN             -1;
        u8 epnum;
        struct dwc3_trb         *trb;
        dma_addr_t trb_dma;
        unsigned int            num_trbs;
        unsigned int            direction:1;
        unsigned int            mapped:1;
};
```

**Members**

- `request`: struct usb_request to be transferred
- `list`: a list_head used for request queueing
- `dep`: struct dwc3_ep owning this request
- `start_sg`: pointer to the sg which should be queued next
- `num_pending_sgs`: counter to pending sgs
- `remaining`: amount of data remaining
- `status`: internal dwc3 request status tracking
- `epnum`: endpoint number to which this request refers
- `trb`: pointer to struct dwc3_trb
- `trb_dma`: DMA address of **trb**
- `num_trbs`: number of TRBs used by this request
- `direction`: IN or OUT direction flag
- `mapped`: true when request has been dma-mapped

#### <a id="c-struct-dwc3_glue_ops"></a>`struct dwc3_glue_ops`

The ops indicate the notifications that need to be passed on to glue layer

**Definition**

```c
struct dwc3_glue_ops {
    void (*pre_set_role)(struct dwc3 *dwc, enum usb_role role);
    void (*pre_run_stop)(struct dwc3 *dwc, bool is_on);
};
```

**Members**

- `pre_set_role`: Notify glue of role switch notifications
- `pre_run_stop`: Notify run stop enable/disable information to glue

#### <a id="c-struct-dwc3"></a>`struct dwc3`

representation of our controller

**Definition**

```c
struct dwc3 {
        struct work_struct      drd_work;
        struct dwc3_trb         *ep0_trb;
        void *bounce;
        u8 *setup_buf;
        dma_addr_t ep0_trb_addr;
        dma_addr_t bounce_addr;
        struct dwc3_request     ep0_usb_req;
        struct completion       ep0_in_setup;
        spinlock_t lock;
        struct mutex            mutex;
        struct device           *dev;
        struct device           *sysdev;
        struct platform_device  *xhci;
        struct resource         xhci_resources[DWC3_XHCI_RESOURCES_NUM];
        struct dwc3_event_buffer *ev_buf;
        struct dwc3_ep          *eps[DWC3_ENDPOINTS_NUM];
        struct usb_gadget       *gadget;
        struct usb_gadget_driver *gadget_driver;
        const struct dwc3_glue_ops      *glue_ops;
        struct clk              *bus_clk;
        struct clk              *ref_clk;
        struct clk              *susp_clk;
        struct clk              *utmi_clk;
        struct clk              *pipe_clk;
        struct reset_control    *reset;
        struct usb_phy          *usb2_phy;
        struct usb_phy          *usb3_phy;
        struct phy              *usb2_generic_phy[DWC3_USB2_MAX_PORTS];
        struct phy              *usb3_generic_phy[DWC3_USB3_MAX_PORTS];
        u8 num_usb2_ports;
        u8 num_usb3_ports;
        bool phys_ready;
        struct ulpi             *ulpi;
        bool ulpi_ready;
        void __iomem            *regs;
        size_t regs_size;
        enum usb_dr_mode        dr_mode;
        u32 current_dr_role;
        u32 desired_dr_role;
        struct extcon_dev       *edev;
        struct notifier_block   edev_nb;
        enum usb_phy_interface  hsphy_mode;
        struct usb_role_switch  *role_sw;
        enum usb_dr_mode        role_switch_default_mode;
        struct power_supply     *usb_psy;
        struct work_struct      vbus_draw_work;
        unsigned int            current_limit;
        u32 fladj;
        u32 ref_clk_per;
        u32 irq_gadget;
        u32 otg_irq;
        u32 current_otg_role;
        u32 desired_otg_role;
        bool otg_restart_host;
        u32 u1u2;
        u32 maximum_speed;
        u32 gadget_max_speed;
        enum usb_ssp_rate       max_ssp_rate;
        enum usb_ssp_rate       gadget_ssp_rate;
        u32 ip;
    #define DWC3_IP                 0x5533;
    #define DWC31_IP                0x3331;
    #define DWC32_IP                0x3332;
    #define DWC4_IP                 0x3430;
        u32 revision;
    #define DWC3_REVISION_ANY       0x0;
    #define DWC3_REVISION_173A      0x5533173a;
    #define DWC3_REVISION_175A      0x5533175a;
    #define DWC3_REVISION_180A      0x5533180a;
    #define DWC3_REVISION_183A      0x5533183a;
    #define DWC3_REVISION_185A      0x5533185a;
    #define DWC3_REVISION_187A      0x5533187a;
    #define DWC3_REVISION_188A      0x5533188a;
    #define DWC3_REVISION_190A      0x5533190a;
    #define DWC3_REVISION_194A      0x5533194a;
    #define DWC3_REVISION_200A      0x5533200a;
    #define DWC3_REVISION_202A      0x5533202a;
    #define DWC3_REVISION_210A      0x5533210a;
    #define DWC3_REVISION_220A      0x5533220a;
    #define DWC3_REVISION_230A      0x5533230a;
    #define DWC3_REVISION_240A      0x5533240a;
    #define DWC3_REVISION_250A      0x5533250a;
    #define DWC3_REVISION_260A      0x5533260a;
    #define DWC3_REVISION_270A      0x5533270a;
    #define DWC3_REVISION_280A      0x5533280a;
    #define DWC3_REVISION_290A      0x5533290a;
    #define DWC3_REVISION_300A      0x5533300a;
    #define DWC3_REVISION_310A      0x5533310a;
    #define DWC3_REVISION_320A      0x5533320a;
    #define DWC3_REVISION_330A      0x5533330a;
    #define DWC31_REVISION_ANY      0x0;
    #define DWC31_REVISION_110A     0x3131302a;
    #define DWC31_REVISION_120A     0x3132302a;
    #define DWC31_REVISION_160A     0x3136302a;
    #define DWC31_REVISION_170A     0x3137302a;
    #define DWC31_REVISION_180A     0x3138302a;
    #define DWC31_REVISION_190A     0x3139302a;
    #define DWC31_REVISION_200A     0x3230302a;
    #define DWC32_REVISION_ANY      0x0;
    #define DWC32_REVISION_100A     0x3130302a;
        u32 version_type;
    #define DWC31_VERSIONTYPE_ANY           0x0;
    #define DWC31_VERSIONTYPE_EA01          0x65613031;
    #define DWC31_VERSIONTYPE_EA02          0x65613032;
    #define DWC31_VERSIONTYPE_EA03          0x65613033;
    #define DWC31_VERSIONTYPE_EA04          0x65613034;
    #define DWC31_VERSIONTYPE_EA05          0x65613035;
    #define DWC31_VERSIONTYPE_EA06          0x65613036;
        enum dwc3_ep0_next      ep0_next_event;
        enum dwc3_ep0_state     ep0state;
        enum dwc3_link_state    link_state;
        u16 u2sel;
        u16 u2pel;
        u8 u1sel;
        u8 u1pel;
        u8 speed;
        u8 num_eps;
        struct dwc3_hwparams    hwparams;
        struct debugfs_regset32 *regset;
        u32 dbg_lsp_select;
        u8 test_mode;
        u8 test_mode_nr;
        u8 lpm_nyet_threshold;
        u8 hird_threshold;
        u8 rx_thr_num_pkt;
        u8 rx_max_burst;
        u8 tx_thr_num_pkt;
        u8 tx_max_burst;
        u8 rx_thr_num_pkt_prd;
        u8 rx_max_burst_prd;
        u8 tx_thr_num_pkt_prd;
        u8 tx_max_burst_prd;
        u8 tx_fifo_resize_max_num;
        u8 clear_stall_protocol;
        u16 num_hc_interrupters;
        const char              *hsphy_interface;
        unsigned connected:1;
        unsigned softconnect:1;
        unsigned delayed_status:1;
        unsigned ep0_bounced:1;
        unsigned ep0_expect_in:1;
        unsigned sysdev_is_parent:1;
        unsigned has_lpm_erratum:1;
        unsigned is_utmi_l1_suspend:1;
        unsigned is_fpga:1;
        unsigned pending_events:1;
        unsigned do_fifo_resize:1;
        unsigned pullups_connected:1;
        unsigned setup_packet_pending:1;
        unsigned three_stage_setup:1;
        unsigned dis_start_transfer_quirk:1;
        unsigned usb3_lpm_capable:1;
        unsigned usb2_lpm_disable:1;
        unsigned usb2_gadget_lpm_disable:1;
        unsigned disable_scramble_quirk:1;
        unsigned u2exit_lfps_quirk:1;
        unsigned u2ss_inp3_quirk:1;
        unsigned req_p1p2p3_quirk:1;
        unsigned del_p1p2p3_quirk:1;
        unsigned del_phy_power_chg_quirk:1;
        unsigned lfps_filter_quirk:1;
        unsigned rx_detect_poll_quirk:1;
        unsigned dis_u3_susphy_quirk:1;
        unsigned dis_u2_susphy_quirk:1;
        unsigned dis_enblslpm_quirk:1;
        unsigned dis_u1_entry_quirk:1;
        unsigned dis_u2_entry_quirk:1;
        unsigned dis_rxdet_inp3_quirk:1;
        unsigned dis_u2_freeclk_exists_quirk:1;
        unsigned dis_del_phy_power_chg_quirk:1;
        unsigned dis_tx_ipgap_linecheck_quirk:1;
        unsigned resume_hs_terminations:1;
        unsigned ulpi_ext_vbus_drv:1;
        unsigned parkmode_disable_ss_quirk:1;
        unsigned parkmode_disable_hs_quirk:1;
        unsigned gfladj_refclk_lpm_sel:1;
        unsigned tx_de_emphasis_quirk:1;
        unsigned tx_de_emphasis:2;
        unsigned dis_metastability_quirk:1;
        unsigned dis_split_quirk:1;
        unsigned async_callbacks:1;
        unsigned sys_wakeup:1;
        unsigned wakeup_configured:1;
        unsigned suspended:1;
        unsigned susphy_state:1;
        u16 imod_interval;
        int max_cfg_eps;
        int last_fifo_depth;
        int num_ep_resized;
        struct dentry           *debug_root;
        u32 gsbuscfg0_reqinfo;
        u32 wakeup_pending_funcs;
};
```

**Members**

- `drd_work`: workqueue used for role swapping
- `ep0_trb`: trb which is used for the ctrl_req
- `bounce`: address of bounce buffer
- `setup_buf`: used while precessing STD USB requests
- `ep0_trb_addr`: dma address of **ep0_trb**
- `bounce_addr`: dma address of **bounce**
- `ep0_usb_req`: dummy req used while handling STD USB requests
- `ep0_in_setup`: one control transfer is completed and enter setup phase
- `lock`: for synchronizing
- `mutex`: for mode switching
- `dev`: pointer to our struct device
- `sysdev`: pointer to the DMA-capable device
- `xhci`: pointer to our xHCI child
- `xhci_resources`: struct resources for our **xhci** child
- `ev_buf`: struct dwc3_event_buffer pointer
- `eps`: endpoint array
- `gadget`: device side representation of the peripheral controller
- `gadget_driver`: pointer to the gadget driver
- `glue_ops`: Vendor callbacks for flattened device implementations.
- `bus_clk`: clock for accessing the registers
- `ref_clk`: reference clock
- `susp_clk`: clock used when the SS phy is in low power (S3) state
- `utmi_clk`: clock used for USB2 PHY communication
- `pipe_clk`: clock used for USB3 PHY communication
- `reset`: reset control
- `usb2_phy`: pointer to USB2 PHY
- `usb3_phy`: pointer to USB3 PHY
- `usb2_generic_phy`: pointer to array of USB2 PHYs
- `usb3_generic_phy`: pointer to array of USB3 PHYs
- `num_usb2_ports`: number of USB2 ports
- `num_usb3_ports`: number of USB3 ports
- `phys_ready`: flag to indicate that PHYs are ready
- `ulpi`: pointer to ulpi interface
- `ulpi_ready`: flag to indicate that ULPI is initialized
- `regs`: base address for our registers
- `regs_size`: address space size
- `dr_mode`: requested mode of operation
- `current_dr_role`: current role of operation when in dual-role mode
- `desired_dr_role`: desired role of operation when in dual-role mode
- `edev`: extcon handle
- `edev_nb`: extcon notifier
- `hsphy_mode`: UTMI phy mode, one of following:
  - USBPHY_INTERFACE_MODE_UTMI
  - USBPHY_INTERFACE_MODE_UTMIW
- `role_sw`: usb_role_switch handle
- `role_switch_default_mode`: default operation mode of controller while
  usb role is USB_ROLE_NONE.
- `usb_psy`: pointer to power supply interface.
- `vbus_draw_work`: Work to set the vbus drawing limit
- `current_limit`: How much current to draw from vbus, in milliAmperes.
- `fladj`: frame length adjustment
- `ref_clk_per`: reference clock period configuration
- `irq_gadget`: peripheral controller's IRQ number
- `otg_irq`: IRQ number for OTG IRQs
- `current_otg_role`: current role of operation while using the OTG block
- `desired_otg_role`: desired role of operation while using the OTG block
- `otg_restart_host`: flag that OTG controller needs to restart host
- `u1u2`: only used on revisions \<1.83a for workaround
- `maximum_speed`: maximum speed requested (mainly for testing purposes)
- `gadget_max_speed`: maximum gadget speed requested
- `max_ssp_rate`: SuperSpeed Plus maximum signaling rate and lane count
- `gadget_ssp_rate`: Gadget driver's maximum supported SuperSpeed Plus signaling
  rate and lane count.
- `ip`: controller's ID
- `revision`: controller's version of an IP
- `version_type`: VERSIONTYPE register contents, a sub release of a revision
- `ep0_next_event`: hold the next expected event
- `ep0state`: state of endpoint zero
- `link_state`: link state
- `u2sel`: parameter from Set SEL request.
- `u2pel`: parameter from Set SEL request.
- `u1sel`: parameter from Set SEL request.
- `u1pel`: parameter from Set SEL request.
- `speed`: device speed (super, high, full, low)
- `num_eps`: number of endpoints
- `hwparams`: copy of hwparams registers
- `regset`: debugfs pointer to regdump file
- `dbg_lsp_select`: current debug lsp mux register selection
- `test_mode`: true when we're entering a USB test mode
- `test_mode_nr`: test feature selector
- `lpm_nyet_threshold`: LPM NYET response threshold
- `hird_threshold`: HIRD threshold
- `rx_thr_num_pkt`: USB receive packet count
- `rx_max_burst`: max USB receive burst size
- `tx_thr_num_pkt`: USB transmit packet count
- `tx_max_burst`: max USB transmit burst size
- `rx_thr_num_pkt_prd`: periodic ESS receive packet count
- `rx_max_burst_prd`: max periodic ESS receive burst size
- `tx_thr_num_pkt_prd`: periodic ESS transmit packet count
- `tx_max_burst_prd`: max periodic ESS transmit burst size
- `tx_fifo_resize_max_num`: max number of fifos allocated during txfifo resize
- `clear_stall_protocol`: endpoint number that requires a delayed status phase
- `num_hc_interrupters`: number of host controller interrupters
- `hsphy_interface`: "utmi" or "ulpi"
- `connected`: true when we're connected to a host, false otherwise
- `softconnect`: true when gadget connect is called, false when disconnect runs
- `delayed_status`: true when gadget driver asks for delayed status
- `ep0_bounced`: true when we used bounce buffer
- `ep0_expect_in`: true when we expect a DATA IN transfer
- `sysdev_is_parent`: true when dwc3 device has a parent driver
- `has_lpm_erratum`: true when core was configured with LPM Erratum. Note that
  there's now way for software to detect this in runtime.
- `is_utmi_l1_suspend`: the core asserts output signal
  0       - utmi_sleep_n
  1       - utmi_l1_suspend_n
- `is_fpga`: true when we are using the FPGA board
- `pending_events`: true when we have pending IRQs to be handled
- `do_fifo_resize`: true when txfifo resizing is enabled for dwc3 endpoints
- `pullups_connected`: true when Run/Stop bit is set
- `setup_packet_pending`: true when there's a Setup Packet in FIFO. Workaround
- `three_stage_setup`: set if we perform a three phase setup
- `dis_start_transfer_quirk`: set if start_transfer failure SW workaround is
  not needed for DWC_usb31 version 1.70a-ea06 and below
- `usb3_lpm_capable`: set if hadrware supports Link Power Management
- `usb2_lpm_disable`: set to disable usb2 lpm for host
- `usb2_gadget_lpm_disable`: set to disable usb2 lpm for gadget
- `disable_scramble_quirk`: set if we enable the disable scramble quirk
- `u2exit_lfps_quirk`: set if we enable u2exit lfps quirk
- `u2ss_inp3_quirk`: set if we enable P3 OK for U2/SS Inactive quirk
- `req_p1p2p3_quirk`: set if we enable request p1p2p3 quirk
- `del_p1p2p3_quirk`: set if we enable delay p1p2p3 quirk
- `del_phy_power_chg_quirk`: set if we enable delay phy power change quirk
- `lfps_filter_quirk`: set if we enable LFPS filter quirk
- `rx_detect_poll_quirk`: set if we enable rx_detect to polling lfps quirk
- `dis_u3_susphy_quirk`: set if we disable usb3 suspend phy
- `dis_u2_susphy_quirk`: set if we disable usb2 suspend phy
- `dis_enblslpm_quirk`: set if we clear enblslpm in GUSB2PHYCFG,
  disabling the suspend signal to the PHY.
- `dis_u1_entry_quirk`: set if link entering into U1 state needs to be disabled.
- `dis_u2_entry_quirk`: set if link entering into U2 state needs to be disabled.
- `dis_rxdet_inp3_quirk`: set if we disable Rx.Detect in P3
- `dis_u2_freeclk_exists_quirk`: set if we clear u2_freeclk_exists
  in GUSB2PHYCFG, specify that USB2 PHY doesn't
  provide a free-running PHY clock.
- `dis_del_phy_power_chg_quirk`: set if we disable delay phy power
  change quirk.
- `dis_tx_ipgap_linecheck_quirk`: set if we disable u2mac linestate
  check during HS transmit.
- `resume_hs_terminations`: Set if we enable quirk for fixing improper crc
  generation after resume from suspend.
- `ulpi_ext_vbus_drv`: Set to confiure the upli chip to drives CPEN pin
  VBUS with an external supply.
- `parkmode_disable_ss_quirk`: set if we need to disable all SuperSpeed
  instances in park mode.
- `parkmode_disable_hs_quirk`: set if we need to disable all HishSpeed
  instances in park mode.
- `gfladj_refclk_lpm_sel`: set if we need to enable SOF/ITP counter
  running based on ref_clk
- `tx_de_emphasis_quirk`: set if we enable Tx de-emphasis quirk
- `tx_de_emphasis`: Tx de-emphasis value
  0       - -6dB de-emphasis
  1       - -3.5dB de-emphasis
  2       - No de-emphasis
  3       - Reserved
- `dis_metastability_quirk`: set to disable metastability quirk.
- `dis_split_quirk`: set to disable split boundary.
- `async_callbacks`: if set, indicate that async callbacks will be used.
- `sys_wakeup`: set if the device may do system wakeup.
- `wakeup_configured`: set if the device is configured for remote wakeup.
- `suspended`: set to track suspend event due to U3/L2.
- `susphy_state`: state of DWC3_GUSB2PHYCFG_SUSPHY + DWC3_GUSB3PIPECTL_SUSPHY
  before PM suspend.
- `imod_interval`: set the interrupt moderation interval in 250ns
  increments or 0 to disable.
- `max_cfg_eps`: current max number of IN eps used across all USB configs.
- `last_fifo_depth`: last fifo depth used to determine next fifo ram start
  address.
- `num_ep_resized`: carries the current number endpoints which have had its tx
  fifo resized.
- `debug_root`: root debugfs directory for this device to put its files in.
- `gsbuscfg0_reqinfo`: store GSBUSCFG0.DATRDREQINFO, DESRDREQINFO,
  DATWRREQINFO, and DESWRREQINFO value passed from
  glue driver.
- `wakeup_pending_funcs`: Indicates whether any interface has requested for
  function wakeup in bitmap format where bit position
  represents interface_id.

#### <a id="c-struct-dwc3_event_depevt"></a>`struct dwc3_event_depevt`

Device Endpoint Events

**Definition**

```c
struct dwc3_event_depevt {
        u32 one_bit:1;
        u32 endpoint_number:5;
        u32 endpoint_event:4;
        u32 reserved11_10:2;
        u32 status:4;
    #define DEPEVT_STATUS_TRANSFER_ACTIVE   BIT(3);
    #define DEPEVT_STATUS_BUSERR    BIT(0);
    #define DEPEVT_STATUS_SHORT     BIT(1);
    #define DEPEVT_STATUS_IOC       BIT(2);
    #define DEPEVT_STATUS_LST       BIT(3);
    #define DEPEVT_STATUS_MISSED_ISOC BIT(3);
    #define DEPEVT_STREAMEVT_FOUND          1;
    #define DEPEVT_STREAMEVT_NOTFOUND       2;
    #define DEPEVT_STREAM_PRIME             0xfffe;
    #define DEPEVT_STREAM_NOSTREAM          0x0;
    #define DEPEVT_STATUS_CONTROL_DATA      1;
    #define DEPEVT_STATUS_CONTROL_STATUS    2;
    #define DEPEVT_STATUS_CONTROL_PHASE(n)  ((n) & 3);
    #define DEPEVT_TRANSFER_NO_RESOURCE     1;
    #define DEPEVT_TRANSFER_BUS_EXPIRY      2;
        u32 parameters:16;
    #define DEPEVT_PARAMETER_CMD(n) (((n) & (0xf << 8)) >> 8);
};
```

**Members**

- `one_bit`: indicates this is an endpoint event (not used)
- `endpoint_number`: number of the endpoint
- `endpoint_event`: The event we have:
  0x00    - Reserved
  0x01    - XferComplete
  0x02    - XferInProgress
  0x03    - XferNotReady
  0x04    - RxTxFifoEvt (IN->Underrun, OUT->Overrun)
  0x05    - Reserved
  0x06    - StreamEvt
  0x07    - EPCmdCmplt
- `reserved11_10`: Reserved, don't use.
- `status`: Indicates the status of the event. Refer to databook for
  more information.
- `parameters`: Parameters of the current event. Refer to databook for
  more information.

#### <a id="c-struct-dwc3_event_devt"></a>`struct dwc3_event_devt`

Device Events

**Definition**

```c
struct dwc3_event_devt {
    u32 one_bit:1;
    u32 device_event:7;
    u32 type:4;
    u32 reserved15_12:4;
    u32 event_info:9;
    u32 reserved31_25:7;
};
```

**Members**

- `one_bit`: indicates this is a non-endpoint event (not used)
- `device_event`: indicates it's a device event. Should read as 0x00
- `type`: indicates the type of device event.
  0       - DisconnEvt
  1       - USBRst
  2       - ConnectDone
  3       - ULStChng
  4       - WkUpEvt
  5       - Reserved
  6       - Suspend (EOPF on revisions 2.10a and prior)
  7       - SOF
  8       - Reserved
  9       - ErrticErr
  10      - CmdCmplt
  11      - EvntOverflow
  12      - VndrDevTstRcved
- `reserved15_12`: Reserved, not used
- `event_info`: Information about this event
- `reserved31_25`: Reserved, not used

#### <a id="c-struct-dwc3_event_gevt"></a>`struct dwc3_event_gevt`

Other Core Events

**Definition**

```c
struct dwc3_event_gevt {
    u32 one_bit:1;
    u32 device_event:7;
    u32 phy_port_number:4;
    u32 reserved31_12:20;
};
```

**Members**

- `one_bit`: indicates this is a non-endpoint event (not used)
- `device_event`: indicates it's (0x03) Carkit or (0x04) I2C event.
- `phy_port_number`: self-explanatory
- `reserved31_12`: Reserved, not used.

#### <a id="c-union-dwc3_event"></a>`union dwc3_event`

representation of Event Buffer contents

**Definition**

```c
union dwc3_event {
    u32 raw;
    struct dwc3_event_type          type;
    struct dwc3_event_depevt        depevt;
    struct dwc3_event_devt          devt;
    struct dwc3_event_gevt          gevt;
};
```

**Members**

- `raw`: raw 32-bit event
- `type`: the type of the event
- `depevt`: Device Endpoint Event
- `devt`: Device Event
- `gevt`: Global Event

#### <a id="c-struct-dwc3_gadget_ep_cmd_params"></a>`struct dwc3_gadget_ep_cmd_params`

representation of endpoint command parameters

**Definition**

```c
struct dwc3_gadget_ep_cmd_params {
    u32 param2;
    u32 param1;
    u32 param0;
};
```

**Members**

- `param2`: third parameter
- `param1`: second parameter
- `param0`: first parameter

#### <a id="c-dwc3_mdwidth"></a>`dwc3_mdwidth()`

```c
u32 dwc3_mdwidth(struct dwc3 *dwc)
```

get MDWIDTH value in bits

**Parameters**

- `struct dwc3 *dwc`: pointer to our context structure

**Description**

Return MDWIDTH configuration value in bits.



#### <a id="c-next_request"></a>`next_request()`

```c
struct dwc3_request * next_request(struct list_head *list)
```

gets the next request on the given list

**Parameters**

- `struct list_head *list`: the request list to operate on

**Description**

Caller should take care of locking. This function return `NULL` or the first
request available on **list**.

#### <a id="c-dwc3_gadget_move_started_request"></a>`dwc3_gadget_move_started_request()`

```c
void dwc3_gadget_move_started_request(struct dwc3_request *req)
```

move **req** to the started_list

**Parameters**

- `struct dwc3_request *req`: the request to be moved

**Description**

Caller should take care of locking. This function will move **req** from its
current list to the endpoint's started_list.

#### <a id="c-dwc3_gadget_move_cancelled_request"></a>`dwc3_gadget_move_cancelled_request()`

```c
void dwc3_gadget_move_cancelled_request(struct dwc3_request *req, unsigned int reason)
```

move **req** to the cancelled_list

**Parameters**

- `struct dwc3_request *req`: the request to be moved
- `unsigned int reason`: cancelled reason for the dwc3 request

**Description**

Caller should take care of locking. This function will move **req** from its
current list to the endpoint's cancelled_list.

#### <a id="c-dwc3_gadget_ep_get_transfer_index"></a>`dwc3_gadget_ep_get_transfer_index()`

```c
void dwc3_gadget_ep_get_transfer_index(struct dwc3_ep *dep)
```

Gets transfer index from HW

**Parameters**

- `struct dwc3_ep *dep`: dwc3 endpoint

**Description**

Caller should take care of locking. Returns the transfer resource
index for a given endpoint.

#### <a id="c-dwc3_gadget_dctl_write_safe"></a>`dwc3_gadget_dctl_write_safe()`

```c
void dwc3_gadget_dctl_write_safe(struct dwc3 *dwc, u32 value)
```

write to DCTL safe from link state change

**Parameters**

- `struct dwc3 *dwc`: pointer to our context structure
- `u32 value`: value to write to DCTL

**Description**

Use this function when doing read-modify-write to DCTL. It will not
send link state change request.



#### <a id="c-dwc3_gadget_set_test_mode"></a>`dwc3_gadget_set_test_mode()`

```c
int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode)
```

enables usb2 test modes

**Parameters**

- `struct dwc3 *dwc`: pointer to our context structure
- `int mode`: the mode to set (J, K SE0 NAK, Force Enable)

**Description**

Caller should take care of locking. This function will return 0 on
success or -EINVAL if wrong Test Selector is passed.

#### <a id="c-dwc3_gadget_get_link_state"></a>`dwc3_gadget_get_link_state()`

```c
int dwc3_gadget_get_link_state(struct dwc3 *dwc)
```

gets current state of usb link

**Parameters**

- `struct dwc3 *dwc`: pointer to our context structure

**Description**

Caller should take care of locking. This function will
return the link state on success (>= 0) or -ETIMEDOUT.

#### <a id="c-dwc3_gadget_set_link_state"></a>`dwc3_gadget_set_link_state()`

```c
int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state)
```

sets usb link to a particular state

**Parameters**

- `struct dwc3 *dwc`: pointer to our context structure
- `enum dwc3_link_state state`: the state to put link into

**Description**

Caller should take care of locking. This function will
return 0 on success or -ETIMEDOUT.

#### <a id="c-dwc3_ep_inc_trb"></a>`dwc3_ep_inc_trb()`

```c
void dwc3_ep_inc_trb(u8 *index)
```

increment a trb index.

**Parameters**

- `u8 *index`: Pointer to the TRB index to increment.

**Description**

The index should never point to the link TRB. After incrementing,
if it is point to the link TRB, wrap around to the beginning. The
link TRB is always at the last TRB entry.

#### <a id="c-dwc3_ep_inc_enq"></a>`dwc3_ep_inc_enq()`

```c
void dwc3_ep_inc_enq(struct dwc3_ep *dep)
```

increment endpoint's enqueue pointer

**Parameters**

- `struct dwc3_ep *dep`: The endpoint whose enqueue pointer we're incrementing

#### <a id="c-dwc3_ep_inc_deq"></a>`dwc3_ep_inc_deq()`

```c
void dwc3_ep_inc_deq(struct dwc3_ep *dep)
```

increment endpoint's dequeue pointer

**Parameters**

- `struct dwc3_ep *dep`: The endpoint whose enqueue pointer we're incrementing

#### <a id="c-dwc3_gadget_giveback"></a>`dwc3_gadget_giveback()`

```c
void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req, int status)
```

call struct usb_request's ->complete callback

**Parameters**

- `struct dwc3_ep *dep`: The endpoint to whom the request belongs to
- `struct dwc3_request *req`: The request we're giving back
- `int status`: completion code for the request

**Description**

Must be called with controller's lock held and interrupts disabled. This
function will unmap **req** and call its ->`complete()` callback to notify upper
layers that it has completed.

#### <a id="c-dwc3_send_gadget_generic_command"></a>`dwc3_send_gadget_generic_command()`

```c
int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd, u32 param)
```

issue a generic command for the controller

**Parameters**

- `struct dwc3 *dwc`: pointer to the controller context
- `unsigned int cmd`: the command to be issued
- `u32 param`: command parameter

**Description**

Caller should take care of locking. Issue **cmd** with a given **param** to **dwc**
and wait for its completion.

#### <a id="c-dwc3_send_gadget_ep_cmd"></a>`dwc3_send_gadget_ep_cmd()`

```c
int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd, struct dwc3_gadget_ep_cmd_params *params)
```

issue an endpoint command

**Parameters**

- `struct dwc3_ep *dep`: the endpoint to which the command is going to be issued
- `unsigned int cmd`: the command to be issued
- `struct dwc3_gadget_ep_cmd_params *params`: parameters to the command

**Description**

Caller should handle locking. This function will issue **cmd** with given
**params** to **dep** and wait for its completion.

According to the programming guide, if the link state is in L1/L2/U3,
then sending the Start Transfer command may not complete. The
programming guide suggested to bring the link state back to ON/U0 by
performing remote wakeup prior to sending the command. However, don't
initiate remote wakeup when the user/function does not send wakeup
request via wakeup ops. Send the command when it's allowed.

**Notes**

For L1 link state, issuing a command requires the clearing of
GUSB2PHYCFG.SUSPENDUSB2, which turns on the signal required to complete
the given command (usually within 50us). This should happen within the
command timeout set by driver. No additional step is needed.

For L2 or U3 link state, the gadget is in USB suspend. Care should be
taken when sending Start Transfer command to ensure that it's done after
USB resume.

#### <a id="c-dwc3_gadget_start_config"></a>`dwc3_gadget_start_config()`

```c
int dwc3_gadget_start_config(struct dwc3 *dwc, unsigned int resource_index)
```

reset endpoint resources

**Parameters**

- `struct dwc3 *dwc`: pointer to the DWC3 context
- `unsigned int resource_index`: DEPSTARTCFG.XferRscIdx value (must be 0 or 2)

**Description**

Set resource_index=0 to reset all endpoints' resources allocation. Do this as
part of the power-on/soft-reset initialization.

Set resource_index=2 to reset only non-control endpoints' resources. Do this
on receiving the SET_CONFIGURATION request or hibernation resume.

#### <a id="c-dwc3_gadget_calc_tx_fifo_size"></a>`dwc3_gadget_calc_tx_fifo_size()`

```c
int dwc3_gadget_calc_tx_fifo_size(struct dwc3 *dwc, int mult)
```

calculates the txfifo size value

**Parameters**

- `struct dwc3 *dwc`: pointer to the DWC3 context
- `int mult`: multiplier to be used when calculating the fifo_size

**Description**

Calculates the size value based on the equation below:

DWC3 revision 280A and prior:
fifo_size = mult * (max_packet / mdwidth) + 1;

DWC3 revision 290A and onwards:
fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1

The max packet size is set to 1024, as the txfifo requirements mainly apply
to super speed USB use cases.  However, it is safe to overestimate the fifo
allocations for other scenarios, i.e. high speed USB.

#### <a id="c-dwc3_gadget_calc_ram_depth"></a>`dwc3_gadget_calc_ram_depth()`

```c
int dwc3_gadget_calc_ram_depth(struct dwc3 *dwc)
```

calculates the ram depth for txfifo

**Parameters**

- `struct dwc3 *dwc`: pointer to the DWC3 context

#### <a id="c-dwc3_gadget_clear_tx_fifos"></a>`dwc3_gadget_clear_tx_fifos()`

```c
void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc)
```

Clears txfifo allocation

**Parameters**

- `struct dwc3 *dwc`: pointer to the DWC3 context

**Description**

Iterates through all the endpoint registers and clears the previous txfifo
allocations.

#### <a id="c-__dwc3_gadget_ep_enable"></a>`__dwc3_gadget_ep_enable()`

```c
int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
```

initializes a hw endpoint

**Parameters**

- `struct dwc3_ep *dep`: endpoint to be initialized
- `unsigned int action`: one of INIT, MODIFY or RESTORE

**Description**

Caller should take care of locking. Execute all necessary commands to
initialize a HW endpoint so it can be used by a gadget driver.

#### <a id="c-__dwc3_gadget_ep_disable"></a>`__dwc3_gadget_ep_disable()`

```c
int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
```

disables a hw endpoint

**Parameters**

- `struct dwc3_ep *dep`: the endpoint to disable

**Description**

This function undoes what __dwc3_gadget_ep_enable did and also removes
requests which are currently being processed by the hardware and those which
are not yet scheduled.

Caller should take care of locking.

#### <a id="c-dwc3_ep_prev_trb"></a>`dwc3_ep_prev_trb()`

```c
struct dwc3_trb * dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
```

returns the previous TRB in the ring

**Parameters**

- `struct dwc3_ep *dep`: The endpoint with the TRB ring
- `u8 index`: The index of the current TRB in the ring

**Description**

Returns the TRB prior to the one pointed to by the index. If the
index is 0, we will wrap backwards, skip the link TRB, and return
the one just before that.

#### <a id="c-dwc3_prepare_one_trb"></a>`dwc3_prepare_one_trb()`

```c
void dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_request *req, unsigned int trb_length, unsigned int chain, unsigned int node, bool use_bounce_buffer, bool must_interrupt)
```

setup one TRB from one request

**Parameters**

- `struct dwc3_ep *dep`: endpoint for which this request is prepared
- `struct dwc3_request *req`: dwc3_request pointer
- `unsigned int trb_length`: buffer size of the TRB
- `unsigned int chain`: should this TRB be chained to the next?
- `unsigned int node`: only for isochronous endpoints. First TRB needs different type.
- `bool use_bounce_buffer`: set to use bounce buffer
- `bool must_interrupt`: set to interrupt on TRB completion

#### <a id="c-dwc3_prepare_last_sg"></a>`dwc3_prepare_last_sg()`

```c
int dwc3_prepare_last_sg(struct dwc3_ep *dep, struct dwc3_request *req, unsigned int entry_length, unsigned int node)
```

prepare TRBs for the last SG entry

**Parameters**

- `struct dwc3_ep *dep`: The endpoint that the request belongs to
- `struct dwc3_request *req`: The request to prepare
- `unsigned int entry_length`: The last SG entry size
- `unsigned int node`: Indicates whether this is not the first entry (for isoc only)

**Description**

Return the number of TRBs prepared.

#### <a id="c-__dwc3_stop_active_transfer"></a>`__dwc3_stop_active_transfer()`

```c
int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool interrupt)
```

stop the current active transfer

**Parameters**

- `struct dwc3_ep *dep`: isoc endpoint
- `bool force`: set forcerm bit in the command
- `bool interrupt`: command complete interrupt after End Transfer command

**Description**

When setting force, the ForceRM bit will be set. In that case
the controller won't update the TRB progress on command
completion. It also won't clear the HWO bit in the TRB.
The command will also not complete immediately in that case.

#### <a id="c-dwc3_gadget_start_isoc_quirk"></a>`dwc3_gadget_start_isoc_quirk()`

```c
int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep)
```

workaround invalid frame number

**Parameters**

- `struct dwc3_ep *dep`: isoc endpoint

**Description**

This function tests for the correct combination of BIT\[15:14\] from the 16-bit
microframe number reported by the XferNotReady event for the future frame
number to start the isoc transfer.

In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed
isochronous IN, BIT\[15:14\] of the 16-bit microframe number reported by the
XferNotReady event are invalid. The driver uses this number to schedule the
isochronous transfer and passes it to the START TRANSFER command. Because
this number is invalid, the command may fail. If BIT\[15:14\] matches the
internal 16-bit microframe, the START TRANSFER command will pass and the
transfer will start at the scheduled time, if it is off by 1, the command
will still pass, but the transfer will start 2 seconds in the future. For all
other conditions, the START TRANSFER command will fail with bus-expiry.

In order to workaround this issue, we can test for the correct combination of
BIT\[15:14\] by sending START TRANSFER commands with different values of
BIT\[15:14\]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart
(or 2 seconds). 4 seconds into the future will result in a bus-expiry status.
As the result, within the 4 possible combinations for BIT\[15:14\], there will
be 2 successful and 2 failure START COMMAND status. One of the 2 successful
command status will result in a 2-second delay start. The smaller BIT\[15:14\]
value is the correct combination.

Since there are only 4 outcomes and the results are ordered, we can simply
test 2 START TRANSFER commands with BIT\[15:14\] combinations 'b00 and 'b01 to
deduce the smaller successful combination.

Let test0 = test status for combination 'b00 and test1 = test status for 'b01
of BIT\[15:14\]. The correct combination is as follow:

if test0 fails and test1 passes, BIT\[15:14\] is 'b01
if test0 fails and test1 fails, BIT\[15:14\] is 'b10
if test0 passes and test1 fails, BIT\[15:14\] is 'b11
if test0 passes and test1 passes, BIT\[15:14\] is 'b00

Synopsys STAR 9001202023: Wrong microframe number for isochronous IN
endpoints.

#### <a id="c-dwc3_gadget_setup_nump"></a>`dwc3_gadget_setup_nump()`

```c
void dwc3_gadget_setup_nump(struct dwc3 *dwc)
```

calculate and initialize NUMP field of `DWC3_DCFG`

**Parameters**

- `struct dwc3 *dwc`: pointer to our context structure

**Description**

The following looks like complex but it's actually very simple. In order to
calculate the number of packets we can burst at once on OUT transfers, we're
gonna use RxFIFO size.

To calculate RxFIFO size we need two numbers:
MDWIDTH = size, in bits, of the internal memory bus
RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)

Given these two numbers, the formula is simple:

RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;

24 bytes is for 3x SETUP packets
16 bytes is a clock domain crossing tolerance

Given RxFIFO Size, NUMP = RxFIFOSize / 1024;

#### <a id="c-dwc3_gadget_check_config"></a>`dwc3_gadget_check_config()`

```c
int dwc3_gadget_check_config(struct usb_gadget *g)
```

ensure dwc3 can support the USB configuration

**Parameters**

- `struct usb_gadget *g`: pointer to the USB gadget

**Description**

Used to record the maximum number of endpoints being used in a USB composite
device. (across all configurations)  This is to be used in the calculation
of the TXFIFO sizes when resizing internal memory for individual endpoints.
It will help ensured that the resizing logic reserves enough space for at
least one max packet.



#### <a id="c-dwc3_get_dr_mode"></a>`dwc3_get_dr_mode()`

```c
int dwc3_get_dr_mode(struct dwc3 *dwc)
```

Validates and sets dr_mode

**Parameters**

- `struct dwc3 *dwc`: pointer to our context structure

#### <a id="c-dwc3_core_soft_reset"></a>`dwc3_core_soft_reset()`

```c
int dwc3_core_soft_reset(struct dwc3 *dwc)
```

Issues core soft reset and PHY reset

**Parameters**

- `struct dwc3 *dwc`: pointer to our context structure

#### <a id="c-dwc3_ref_clk_period"></a>`dwc3_ref_clk_period()`

```c
void dwc3_ref_clk_period(struct dwc3 *dwc)
```

Reference clock period configuration Default reference clock period depends on hardware configuration. For systems with reference clock that differs from the default, this will set clock period in DWC3_GUCTL register.

**Parameters**

- `struct dwc3 *dwc`: Pointer to our controller context structure

#### <a id="c-dwc3_free_one_event_buffer"></a>`dwc3_free_one_event_buffer()`

```c
void dwc3_free_one_event_buffer(struct dwc3 *dwc, struct dwc3_event_buffer *evt)
```

Frees one event buffer

**Parameters**

- `struct dwc3 *dwc`: Pointer to our controller context structure
- `struct dwc3_event_buffer *evt`: Pointer to event buffer to be freed

#### <a id="c-dwc3_alloc_one_event_buffer"></a>`dwc3_alloc_one_event_buffer()`

```c
struct dwc3_event_buffer * dwc3_alloc_one_event_buffer(struct dwc3 *dwc, unsigned int length)
```

Allocates one event buffer structure

**Parameters**

- `struct dwc3 *dwc`: Pointer to our controller context structure
- `unsigned int length`: size of the event buffer

**Description**

Returns a pointer to the allocated event buffer structure on success
otherwise ERR_PTR(errno).

#### <a id="c-dwc3_free_event_buffers"></a>`dwc3_free_event_buffers()`

```c
void dwc3_free_event_buffers(struct dwc3 *dwc)
```

frees all allocated event buffers

**Parameters**

- `struct dwc3 *dwc`: Pointer to our controller context structure

#### <a id="c-dwc3_alloc_event_buffers"></a>`dwc3_alloc_event_buffers()`

```c
int dwc3_alloc_event_buffers(struct dwc3 *dwc, unsigned int length)
```

Allocates **num** event buffers of size **length**

**Parameters**

- `struct dwc3 *dwc`: pointer to our controller context structure
- `unsigned int length`: size of event buffer

**Description**

Returns 0 on success otherwise negative errno. In the error case, dwc
may contain some buffers allocated but not all which were requested.

#### <a id="c-dwc3_event_buffers_setup"></a>`dwc3_event_buffers_setup()`

```c
int dwc3_event_buffers_setup(struct dwc3 *dwc)
```

setup our allocated event buffers

**Parameters**

- `struct dwc3 *dwc`: pointer to our controller context structure

**Description**

Returns 0 on success otherwise negative errno.

#### <a id="c-dwc3_phy_setup"></a>`dwc3_phy_setup()`

```c
int dwc3_phy_setup(struct dwc3 *dwc)
```

Configure USB PHY Interface of DWC3 Core

**Parameters**

- `struct dwc3 *dwc`: Pointer to our controller context structure

**Description**

Returns 0 on success. The USB PHY interfaces are configured but not
initialized. The PHY interfaces and the PHYs get initialized together with
the core in dwc3_core_init.


<a id="rst-trb"></a>



**[1]** Transfer Request Block

<a id="rst-link-trb"></a>



**[2]** Transfer Request Block pointing to another Transfer Request Block.

<a id="rst-debugfs-1"></a>



**[3]** The Debug File System

<a id="rst-configfs"></a>



**[4]** The Config File System

<a id="rst-cbw"></a>



**[5]** Command Block Wrapper

<a id="rst-linus-tree"></a>



<a id="rst-me"></a>



<a id="rst-linux-usb"></a>

---

# USB Error codes

_Peios Kernel / Hardware and drivers / Driver development / USB_

> This is the documentation of (hopefully) all possible error codes (and their interpretation) that can be returned from usbcore.

<a id="rst-usb-error-codes-1"></a>
<a id="rst-usb-error-codes"></a>

**Revised:** 2004-Oct-21

This is the documentation of (hopefully) all possible error codes (and their interpretation) that can be returned from usbcore.

Some of them are returned by the Host Controller Drivers (HCDs), which device drivers only see through usbcore.  As a rule, all the HCDs should behave the same except for transfer speed dependent behaviors and the way certain faults are reported.

<a id="rst-error-codes-returned-by-usb-submit-urb"></a>

## Error codes returned by `usb_submit_urb()`

Non-USB-specific:


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


URB submission went fine

</td>
</tr>
<tr>
<td>


`-ENOMEM`

</td>
<td>


no memory for allocation of internal structures

</td>
</tr>
</tbody>
</table>

USB-specific:


<table>
<tbody>
<tr>
<td>


`-EBUSY`

</td>
<td>


The URB is already active.

</td>
</tr>
<tr>
<td>


`-ENODEV`

</td>
<td>


specified USB-device or bus doesn't exist

</td>
</tr>
<tr>
<td>


`-ENOENT`

</td>
<td>


specified interface or endpoint does not exist or is not enabled

</td>
</tr>
<tr>
<td>


`-ENXIO`

</td>
<td>


host controller driver does not support queuing of this type of urb.  (treat as a host controller bug.)

</td>
</tr>
<tr>
<td>


`-EINVAL`

</td>
<td>


- **a)** Invalid transfer type specified (or not supported)

- **b)** Invalid or unsupported periodic transfer interval

- **c)** ISO: attempted to change transfer interval

- **d)** ISO: `number_of_packets` is &lt; 0

- **e)** various other cases

</td>
</tr>
<tr>
<td>


`-EXDEV`

</td>
<td>


ISO: `URB_ISO_ASAP` wasn't specified and all the frames the URB would be scheduled in have already expired.

</td>
</tr>
<tr>
<td>


`-EFBIG`

</td>
<td>


Host controller driver can't schedule that many ISO frames.

</td>
</tr>
<tr>
<td>


`-EPIPE`

</td>
<td>


The pipe type specified in the URB doesn't match the endpoint's actual type.

</td>
</tr>
<tr>
<td>


`-EMSGSIZE`

</td>
<td>


- **(a)** endpoint maxpacket size is zero; it is not usable in the current interface altsetting.

- **(b)** ISO packet is larger than the endpoint maxpacket.

- **(c)** requested data transfer length is invalid: negative or too large for the host controller.

</td>
</tr>
<tr>
<td>


`-EBADR`

</td>
<td>


The wLength value in a control URB's setup packet does not match the URB's transfer_buffer_length.

</td>
</tr>
<tr>
<td>


`-ENOSPC`

</td>
<td>


This request would overcommit the usb bandwidth reserved for periodic transfers (interrupt, isochronous).

</td>
</tr>
<tr>
<td>


`-ESHUTDOWN`

</td>
<td>


The device or host controller has been disabled due to some problem that could not be worked around.

</td>
</tr>
<tr>
<td>


`-EPERM`

</td>
<td>


Submission failed because `urb->reject` was set.

</td>
</tr>
<tr>
<td>


`-EHOSTUNREACH`

</td>
<td>


URB was rejected because the device is suspended.

</td>
</tr>
<tr>
<td>


`-ENOEXEC`

</td>
<td>


A control URB doesn't contain a Setup packet.

</td>
</tr>
</tbody>
</table>

<a id="rst-error-codes-returned-by-in-urb-status-or-in-iso-frame-desc-n-status-for-iso"></a>

## Error codes returned by `in urb->status` or in `iso_frame_desc[n].status` (for ISO)

USB device drivers may only test urb status values in completion handlers. This is because otherwise there would be a race between HCDs updating these values on one CPU, and device drivers testing them on another CPU.

A transfer's actual_length may be positive even when an error has been reported.  That's because transfers often involve several packets, so that one or more packets could finish before an error stops further endpoint I/O.

For isochronous URBs, the urb status value is non-zero only if the URB is unlinked, the device is removed, the host controller is disabled, or the total transferred length is less than the requested length and the `URB_SHORT_NOT_OK` flag is set.  Completion handlers for isochronous URBs should only see `urb->status` set to zero, `-ENOENT`, `-ECONNRESET`, `-ESHUTDOWN`, or `-EREMOTEIO`. Individual frame descriptor status fields may report more status codes.


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


Transfer completed successfully

</td>
</tr>
<tr>
<td>


`-ENOENT`

</td>
<td>


URB was synchronously unlinked by `usb_unlink_urb()`

</td>
</tr>
<tr>
<td>


`-EINPROGRESS`

</td>
<td>


URB still pending, no results yet (That is, if drivers see this it's a bug.)

</td>
</tr>
<tr>
<td>


`-EPROTO` <a id="rst-footnote-reference-1"></a>[1](#rst-f1), <a id="rst-footnote-reference-2"></a>[2](#rst-f2)

</td>
<td>


- **a)** bitstuff error

- **b)** no response packet received within the prescribed bus turn-around time

- **c)** unknown USB error

</td>
</tr>
<tr>
<td>


`-EILSEQ` <a id="rst-footnote-reference-3"></a>[1](#rst-f1), <a id="rst-footnote-reference-4"></a>[2](#rst-f2)

</td>
<td>


- **a)** CRC mismatch

- **b)** no response packet received within the prescribed bus turn-around time

- **c)** unknown USB error

Note that often the controller hardware does not distinguish among cases a), b), and c), so a driver cannot tell whether there was a protocol error, a failure to respond (often caused by device disconnect), or some other fault.

</td>
</tr>
<tr>
<td>


`-ETIME` <a id="rst-footnote-reference-5"></a>[2](#rst-f2)

</td>
<td>


No response packet received within the prescribed bus turn-around time.  This error may instead be reported as `-EPROTO` or `-EILSEQ`.

</td>
</tr>
<tr>
<td>


`-ETIMEDOUT`

</td>
<td>


Synchronous USB message functions use this code to indicate timeout expired before the transfer completed, and no other error was reported by HC.

</td>
</tr>
<tr>
<td>


`-EPIPE` <a id="rst-footnote-reference-6"></a>[2](#rst-f2)

</td>
<td>


Endpoint stalled.  For non-control endpoints, reset this status with `usb_clear_halt()`.

</td>
</tr>
<tr>
<td>


`-ECOMM`

</td>
<td>


During an IN transfer, the host controller received data from an endpoint faster than it could be written to system memory

</td>
</tr>
<tr>
<td>


`-ENOSR`

</td>
<td>


During an OUT transfer, the host controller could not retrieve data from system memory fast enough to keep up with the USB data rate

</td>
</tr>
<tr>
<td>


`-EOVERFLOW` <a id="rst-footnote-reference-7"></a>[1](#rst-f1)

</td>
<td>


The amount of data returned by the endpoint was greater than either the max packet size of the endpoint or the remaining buffer size. "Babble".

</td>
</tr>
<tr>
<td>


`-EREMOTEIO`

</td>
<td>


The data read from the endpoint did not fill the specified buffer, and `URB_SHORT_NOT_OK` was set in `urb->transfer_flags`.

</td>
</tr>
<tr>
<td>


`-ENODEV`

</td>
<td>


Device was removed.  Often preceded by a burst of other errors, since the hub driver doesn't detect device removal events immediately.

</td>
</tr>
<tr>
<td>


`-EXDEV`

</td>
<td>


ISO transfer only partially completed (only set in `iso_frame_desc[n].status`, not `urb->status`)

</td>
</tr>
<tr>
<td>


`-EINVAL`

</td>
<td>


ISO madness, if this happens: Log off and go home

</td>
</tr>
<tr>
<td>


`-ECONNRESET`

</td>
<td>


URB was asynchronously unlinked by `usb_unlink_urb()`

</td>
</tr>
<tr>
<td>


`-ESHUTDOWN`

</td>
<td>


The device or host controller has been disabled due to some problem that could not be worked around, such as a physical disconnect.

</td>
</tr>
</tbody>
</table>

<a id="rst-f1"></a>



**[1]** Error codes like `-EPROTO`, `-EILSEQ` and `-EOVERFLOW` normally indicate hardware problems such as bad devices (including firmware) or cables.

<a id="rst-f2"></a>



**[2]** This is also one of several codes that different kinds of host controller use to indicate a transfer has failed because of device disconnect.  In the interval before the hub driver starts disconnect processing, devices may receive such fault reports for every request.

<a id="rst-error-codes-returned-by-usbcore-functions"></a>

## Error codes returned by usbcore-functions

> [!NOTE]
>
> expect also other submit and transfer status codes

`usb_register()`:


<table>
<tbody>
<tr>
<td>


`-EINVAL`

</td>
<td>


error during registering new driver

</td>
</tr>
</tbody>
</table>

`usb_get_*/usb_set_*()`, `usb_control_msg()`, `usb_bulk_msg()`:


<table>
<tbody>
<tr>
<td>


`-ETIMEDOUT`

</td>
<td>


Timeout expired before the transfer completed.

</td>
</tr>
</tbody>
</table>

---

# USB Gadget API for Linux

_Peios Kernel / Hardware and drivers / Driver development / USB_

> This document presents a Linux-USB "Gadget" kernel mode API, for use within peripherals and other USB devices that embed Linux. It provides an overview of the API structure, and shows how that fits into a system development project. This…

<a id="rst-usb-gadget-api-for-linux"></a>

**Author:** David Brownell

**Date:** 20 August 2004

<a id="rst-introduction"></a>

## Introduction

This document presents a Linux-USB "Gadget" kernel mode API, for use within peripherals and other USB devices that embed Linux. It provides an overview of the API structure, and shows how that fits into a system development project. This is the first such API released on Linux to address a number of important problems, including:

- Supports USB 2.0, for high speed devices which can stream data at several dozen megabytes per second.

- Handles devices with dozens of endpoints just as well as ones with just two fixed-function ones. Gadget drivers can be written so they're easy to port to new hardware.

- Flexible enough to expose more complex USB device capabilities such as multiple configurations, multiple interfaces, composite devices, and alternate interface settings.

- USB "On-The-Go" (OTG) support, in conjunction with updates to the Linux-USB host side.

- Sharing data structures and API models with the Linux-USB host side API. This helps the OTG support, and looks forward to more-symmetric frameworks (where the same I/O model is used by both host and device side drivers).

- Minimalist, so it's easier to support new device controller hardware. I/O processing doesn't imply large demands for memory or CPU resources.

Most Linux developers will not be able to use this API, since they have USB `host` hardware in a PC, workstation, or server. Linux users with embedded systems are more likely to have USB peripheral hardware. To distinguish drivers running inside such hardware from the more familiar Linux "USB device drivers", which are host side proxies for the real USB devices, a different term is used: the drivers inside the peripherals are "USB gadget drivers". In USB protocol interactions, the device driver is the master (or "client driver") and the gadget driver is the slave (or "function driver").

The gadget API resembles the host side Linux-USB API in that both use queues of request objects to package I/O buffers, and those requests may be submitted or canceled. They share common definitions for the standard USB *Chapter 9* messages, structures, and constants. Also, both APIs bind and unbind drivers to devices. The APIs differ in detail, since the host side's current URB framework exposes a number of implementation details and assumptions that are inappropriate for a gadget API. While the model for control transfers and configuration management is necessarily different (one side is a hardware-neutral master, the other is a hardware-aware slave), the endpoint I/0 API used here should also be usable for an overhead-reduced host side API.

<a id="rst-structure-of-gadget-drivers"></a>

## Structure of Gadget Drivers

A system running inside a USB peripheral normally has at least three layers inside the kernel to handle USB protocol processing, and may have additional layers in user space code. The `gadget` API is used by the middle layer to interact with the lowest level (which directly handles hardware).

In Linux, from the bottom up, these layers are:

- ***USB Controller Driver***

  This is the lowest software level. It is the only layer that talks to hardware, through registers, fifos, dma, irqs, and the like. The `<linux/usb/gadget.h>` API abstracts the peripheral controller endpoint hardware. That hardware is exposed through endpoint objects, which accept streams of IN/OUT buffers, and through callbacks that interact with gadget drivers. Since normal USB devices only have one upstream port, they only have one of these drivers. The controller driver can support any number of different gadget drivers, but only one of them can be used at a time.

  Examples of such controller hardware include the PCI-based NetChip 2280 USB 2.0 high speed controller, the SA-11x0 or PXA-25x UDC (found within many PDAs), and a variety of other products.

- ***Gadget Driver***

  The lower boundary of this driver implements hardware-neutral USB functions, using calls to the controller driver. Because such hardware varies widely in capabilities and restrictions, and is used in embedded environments where space is at a premium, the gadget driver is often configured at compile time to work with endpoints supported by one particular controller. Gadget drivers may be portable to several different controllers, using conditional compilation. (Recent kernels substantially simplify the work involved in supporting new hardware, by *autoconfiguring* endpoints automatically for many bulk-oriented drivers.) Gadget driver responsibilities include:

  - handling setup requests (ep0 protocol responses) possibly including class-specific functionality

  - returning configuration and string descriptors

  - (re)setting configurations and interface altsettings, including enabling and configuring endpoints

  - handling life cycle events, such as managing bindings to hardware, USB suspend/resume, remote wakeup, and disconnection from the USB host.

  - managing IN and OUT transfers on all currently enabled endpoints

  Such drivers may be modules of proprietary code, although that approach is discouraged in the Linux community.

- ***Upper Level***

  Most gadget drivers have an upper boundary that connects to some Linux driver or framework in Linux. Through that boundary flows the data which the gadget driver produces and/or consumes through protocol transfers over USB. Examples include:

  - user mode code, using generic (gadgetfs) or application specific files in `/dev`

  - networking subsystem (for network gadgets, like the CDC Ethernet Model gadget driver)

  - data capture drivers, perhaps video4Linux or a scanner driver; or test and measurement hardware.

  - input subsystem (for HID gadgets)

  - sound subsystem (for audio gadgets)

  - file system (for PTP gadgets)

  - block i/o subsystem (for usb-storage gadgets)

  - ... and more

- ***Additional Layers***

  Other layers may exist. These could include kernel layers, such as network protocol stacks, as well as user mode applications building on standard POSIX system call APIs such as `open()`, `close()`, `read()` and `write()`. On newer systems, POSIX Async I/O calls may be an option. Such user mode code will not necessarily be subject to the GNU General Public License (GPL).

OTG-capable systems will also need to include a standard Linux-USB host side stack, with `usbcore`, one or more *Host Controller Drivers* (HCDs), *USB Device Drivers* to support the OTG "Targeted Peripheral List", and so forth. There will also be an *OTG Controller Driver*, which is visible to gadget and device driver developers only indirectly. That helps the host and device side USB controllers implement the two new OTG protocols (HNP and SRP). Roles switch (host to peripheral, or vice versa) using HNP during USB suspend processing, and SRP can be viewed as a more battery-friendly kind of device wakeup protocol.

Over time, reusable utilities are evolving to help make some gadget driver tasks simpler. For example, building configuration descriptors from vectors of descriptors for the configurations interfaces and endpoints is now automated, and many drivers now use autoconfiguration to choose hardware endpoints and initialize their descriptors. A potential example of particular interest is code implementing standard USB-IF protocols for HID, networking, storage, or audio classes. Some developers are interested in KDB or KGDB hooks, to let target hardware be remotely debugged. Most such USB protocol code doesn't need to be hardware-specific, any more than network protocols like X11, HTTP, or NFS are. Such gadget-side interface drivers should eventually be combined, to implement composite devices.

<a id="rst-kernel-mode-gadget-api"></a>

## Kernel Mode Gadget API

Gadget drivers declare themselves through a struct `usb_gadget_driver`, which is responsible for most parts of enumeration for a struct usb_gadget. The response to a set_configuration usually involves enabling one or more of the struct usb_ep objects exposed by the gadget, and submitting one or more struct usb_request buffers to transfer data. Understand those four data types, and their operations, and you will understand how this API works.

> [!NOTE]
>
> Other than the "Chapter 9" data types, most of the significant data types and functions are described here.
>
> However, some relevant information is likely omitted from what you are reading. One example of such information is endpoint autoconfiguration. You'll have to read the header file, and use example source code (such as that for "Gadget Zero"), to fully understand the API.
>
> The part of the API implementing some basic driver capabilities is specific to the version of the Linux kernel that's in use. The 2.6 and upper kernel versions include a *driver model* framework that has no analogue on earlier kernels; so those parts of the gadget API are not fully portable. (They are implemented on 2.4 kernels, but in a different way.) The driver model state is another part of this API that is ignored by the kerneldoc tools.

The core API does not expose every possible hardware feature, only the most widely available ones. There are significant hardware features, such as device-to-device DMA (without temporary storage in a memory buffer) that would be added using hardware-specific APIs.

This API allows drivers to use conditional compilation to handle endpoint capabilities of different hardware, but doesn't require that. Hardware tends to have arbitrary restrictions, relating to transfer types, addressing, packet sizes, buffering, and availability. As a rule, such differences only matter for "endpoint zero" logic that handles device configuration and management. The API supports limited run-time detection of capabilities, through naming conventions for endpoints. Many drivers will be able to at least partially autoconfigure themselves. In particular, driver init sections will often have endpoint autoconfiguration logic that scans the hardware's list of endpoints to find ones matching the driver requirements (relying on those conventions), to eliminate some of the most common reasons for conditional compilation.

Like the Linux-USB host side API, this API exposes the "chunky" nature of USB messages: I/O requests are in terms of one or more "packets", and packet boundaries are visible to drivers. Compared to RS-232 serial protocols, USB resembles synchronous protocols like HDLC (N bytes per frame, multipoint addressing, host as the primary station and devices as secondary stations) more than asynchronous ones (tty style: 8 data bits per frame, no parity, one stop bit). So for example the controller drivers won't buffer two single byte writes into a single two-byte USB IN packet, although gadget drivers may do so when they implement protocols where packet boundaries (and "short packets") are not significant.

<a id="rst-driver-life-cycle"></a>

### Driver Life Cycle

Gadget drivers make endpoint I/O requests to hardware without needing to know many details of the hardware, but driver setup/configuration code needs to handle some differences. Use the API like this:

1. Register a driver for the particular device side usb controller hardware, such as the net2280 on PCI (USB 2.0), sa11x0 or pxa25x as found in Linux PDAs, and so on. At this point the device is logically in the USB ch9 initial state (`attached`), drawing no power and not usable (since it does not yet support enumeration). Any host should not see the device, since it's not activated the data line pullup used by the host to detect a device, even if VBUS power is available.

2. Register a gadget driver that implements some higher level device function. That will then bind() to a `usb_gadget`, which activates the data line pullup sometime after detecting VBUS.

3. The hardware driver can now start enumerating. The steps it handles are to accept USB `power` and `set_address` requests. Other steps are handled by the gadget driver. If the gadget driver module is unloaded before the host starts to enumerate, steps before step 7 are skipped.

4. The gadget driver's `setup()` call returns usb descriptors, based both on what the bus interface hardware provides and on the functionality being implemented. That can involve alternate settings or configurations, unless the hardware prevents such operation. For OTG devices, each configuration descriptor includes an OTG descriptor.

5. The gadget driver handles the last step of enumeration, when the USB host issues a `set_configuration` call. It enables all endpoints used in that configuration, with all interfaces in their default settings. That involves using a list of the hardware's endpoints, enabling each endpoint according to its descriptor. It may also involve using `usb_gadget_vbus_draw` to let more power be drawn from VBUS, as allowed by that configuration. For OTG devices, setting a configuration may also involve reporting HNP capabilities through a user interface.

6. Do real work and perform data transfers, possibly involving changes to interface settings or switching to new configurations, until the device is disconnect()ed from the host. Queue any number of transfer requests to each endpoint. It may be suspended and resumed several times before being disconnected. On disconnect, the drivers go back to step 3 (above).

7. When the gadget driver module is being unloaded, the driver unbind() callback is issued. That lets the controller driver be unloaded.

Drivers will normally be arranged so that just loading the gadget driver module (or statically linking it into a Linux kernel) allows the peripheral device to be enumerated, but some drivers will defer enumeration until some higher level component (like a user mode daemon) enables it. Note that at this lowest level there are no policies about how ep0 configuration logic is implemented, except that it should obey USB specifications. Such issues are in the domain of gadget drivers, including knowing about implementation constraints imposed by some USB controllers or understanding that composite devices might happen to be built by integrating reusable components.

Note that the lifecycle above can be slightly different for OTG devices. Other than providing an additional OTG descriptor in each configuration, only the HNP-related differences are particularly visible to driver code. They involve reporting requirements during the `SET_CONFIGURATION` request, and the option to invoke HNP during some suspend callbacks. Also, SRP changes the semantics of `usb_gadget_wakeup` slightly.

<a id="rst-usb-2-0-chapter-9-types-and-constants"></a>

### USB 2.0 Chapter 9 Types and Constants

Gadget drivers rely on common USB structures and constants defined in the [linux/usb/ch9.h](</kernel/hardware/driver-api/usb/usb.md#rst-usb-chapter9>) header file, which is standard in Linux 2.6+ kernels. These are the same types and constants used by host side drivers (and usbcore).

<a id="rst-core-objects-and-methods"></a>

### Core Objects and Methods

These are declared in `<linux/usb/gadget.h>`, and are used by gadget drivers to interact with USB peripheral controller drivers.


#### <a id="c-struct-usb_request"></a>`struct usb_request`

describes one i/o request

**Definition**

```c
struct usb_request {
    struct usb_ep           *ep;
    void *buf;
    unsigned length;
    dma_addr_t dma;
    struct scatterlist      *sg;
    unsigned num_sgs;
    unsigned num_mapped_sgs;
    unsigned stream_id:16;
    unsigned is_last:1;
    unsigned no_interrupt:1;
    unsigned zero:1;
    unsigned short_not_ok:1;
    unsigned dma_mapped:1;
    unsigned sg_was_mapped:1;
    void (*complete)(struct usb_ep *ep, struct usb_request *req);
    void *context;
    struct list_head        list;
    unsigned frame_number;
    int status;
    unsigned actual;
};
```

**Members**

- `ep`: The associated endpoint set by `usb_ep_alloc_request()`.
- `buf`: Buffer used for data.  Always provide this; some controllers
  only use PIO, or don't use DMA for some endpoints.
- `length`: Length of that data
- `dma`: DMA address corresponding to 'buf'.  If you don't set this
  field, and the usb controller needs one, it is responsible
  for mapping and unmapping the buffer.
- `sg`: a scatterlist for SG-capable controllers.
- `num_sgs`: number of SG entries
- `num_mapped_sgs`: number of SG entries mapped to DMA (internal)
- `stream_id`: The stream id, when USB3.0 bulk streams are being used
- `is_last`: Indicates if this is the last request of a stream_id before
  switching to a different stream (required for DWC3 controllers).
- `no_interrupt`: If true, hints that no completion irq is needed.
  Helpful sometimes with deep request queues that are handled
  directly by DMA controllers.
- `zero`: If true, when writing data, makes the last packet be "short"
  by adding a zero length packet as needed;
- `short_not_ok`: When reading data, makes short packets be
  treated as errors (queue stops advancing till cleanup).
- `dma_mapped`: Indicates if request has been mapped to DMA (internal)
- `sg_was_mapped`: Set if the scatterlist has been mapped before the request
- `complete`: Function called when request completes, so this request and
  its buffer may be re-used.  The function will always be called with
  interrupts disabled, and it must not sleep.
  Reads terminate with a short packet, or when the buffer fills,
  whichever comes first.  When writes terminate, some data bytes
  will usually still be in flight (often in a hardware fifo).
  Errors (for reads or writes) stop the queue from advancing
  until the completion function returns, so that any transfers
  invalidated by the error may first be dequeued.
- `context`: For use by the completion callback
- `list`: For use by the gadget driver.
- `frame_number`: Reports the interval number in (micro)frame in which the
  isochronous transfer was transmitted or received.
- `status`: Reports completion code, zero or a negative errno.
  Normally, faults block the transfer queue from advancing until
  the completion callback returns.
  Code "-ESHUTDOWN" indicates completion caused by device disconnect,
  or when the driver disabled the endpoint.
- `actual`: Reports bytes transferred to/from the buffer.  For reads (OUT
  transfers) this may be less than the requested length.  If the
  short_not_ok flag is set, short reads are treated as errors
  even when status otherwise indicates successful completion.
  Note that for writes (IN transfers) some data bytes may still
  reside in a device-side FIFO when the request is reported as
  complete.

**Description**

These are allocated/freed through the endpoint they're used with.  The
hardware's driver can add extra per-request data to the memory it returns,
which often avoids separate memory allocations (potential failures),
later when the request is queued.

Request flags affect request handling, such as whether a zero length
packet is written (the "zero" flag), whether a short read should be
treated as an error (blocking request queue advance, the "short_not_ok"
flag), or hinting that an interrupt is not required (the "no_interrupt"
flag, for use with deep request queues).

Bulk endpoints can use any size buffers, and can also be used for interrupt
transfers. interrupt-only endpoints can be much less functional.

**NOTE**

this is analogous to 'struct urb' on the host side, except that
it's thinner and promotes more pre-allocation.

#### <a id="c-struct-usb_ep_caps"></a>`struct usb_ep_caps`

endpoint capabilities description

**Definition**

```c
struct usb_ep_caps {
    unsigned type_control:1;
    unsigned type_iso:1;
    unsigned type_bulk:1;
    unsigned type_int:1;
    unsigned dir_in:1;
    unsigned dir_out:1;
};
```

**Members**

- `type_control`: Endpoint supports control type (reserved for ep0).
- `type_iso`: Endpoint supports isochronous transfers.
- `type_bulk`: Endpoint supports bulk transfers.
- `type_int`: Endpoint supports interrupt transfers.
- `dir_in`: Endpoint supports IN direction.
- `dir_out`: Endpoint supports OUT direction.

#### <a id="c-struct-usb_ep"></a>`struct usb_ep`

device side representation of USB endpoint

**Definition**

```c
struct usb_ep {
    void *driver_data;
    const char              *name;
    const struct usb_ep_ops *ops;
    const struct usb_endpoint_descriptor    *desc;
    const struct usb_ss_ep_comp_descriptor  *comp_desc;
    struct list_head        ep_list;
    struct usb_ep_caps      caps;
    bool claimed;
    bool enabled;
    unsigned mult:2;
    unsigned maxburst:5;
    u8 address;
    u16 maxpacket;
    u16 maxpacket_limit;
    u16 max_streams;
};
```

**Members**

- `driver_data`: for use by the gadget driver.
- `name`: identifier for the endpoint, such as "ep-a" or "ep9in-bulk"
- `ops`: Function pointers used to access hardware-specific operations.
- `desc`: endpoint descriptor.  This pointer is set before the endpoint is
  enabled and remains valid until the endpoint is disabled.
- `comp_desc`: In case of SuperSpeed support, this is the endpoint companion
  descriptor that is used to configure the endpoint
- `ep_list`: the gadget's ep_list holds all of its endpoints
- `caps`: The structure describing types and directions supported by endpoint.
- `claimed`: True if this endpoint is claimed by a function.
- `enabled`: The current endpoint enabled/disabled state.
- `mult`: multiplier, 'mult' value for SS Isoc EPs
- `maxburst`: the maximum number of bursts supported by this EP (for usb3)
- `address`: used to identify the endpoint when finding descriptor that
  matches connection speed
- `maxpacket`: The maximum packet size used on this endpoint.  The initial
  value can sometimes be reduced (hardware allowing), according to
  the endpoint descriptor used to configure the endpoint.
- `maxpacket_limit`: The maximum packet size value which can be handled by this
  endpoint. It's set once by UDC driver when endpoint is initialized, and
  should not be changed. Should not be confused with maxpacket.
- `max_streams`: The maximum number of streams supported
  by this EP (0 - 16, actual number is 2^n)

**Description**

the bus controller driver lists all the general purpose endpoints in
gadget->ep_list.  the control endpoint (gadget->ep0) is not in that list,
and is accessed only in response to a driver `setup()` callback.

#### <a id="c-free_usb_request"></a>`free_usb_request()`

```c
void free_usb_request(struct usb_request *req)
```

frees a usb_request object and its buffer

**Parameters**

- `struct usb_request *req`: the request being freed

**Description**

This helper function frees both the request's buffer and the request object
itself by calling `usb_ep_free_request()`. Its signature is designed to be used
with `DEFINE_FREE()` to enable automatic, scope-based cleanup for usb_request
pointers.

#### <a id="c-struct-usb_gadget"></a>`struct usb_gadget`

represents a usb device

**Definition**

```c
struct usb_gadget {
    struct work_struct              work;
    struct usb_udc                  *udc;
    const struct usb_gadget_ops     *ops;
    struct usb_ep                   *ep0;
    struct list_head                ep_list;
    enum usb_device_speed           speed;
    enum usb_device_speed           max_speed;
    enum usb_ssp_rate               ssp_rate;
    enum usb_ssp_rate               max_ssp_rate;
    enum usb_device_state           state;
    spinlock_t state_lock;
    bool teardown;
    const char                      *name;
    struct device                   dev;
    unsigned isoch_delay;
    unsigned out_epnum;
    unsigned in_epnum;
    unsigned mA;
    struct usb_otg_caps             *otg_caps;
    unsigned sg_supported:1;
    unsigned is_otg:1;
    unsigned is_a_peripheral:1;
    unsigned b_hnp_enable:1;
    unsigned a_hnp_support:1;
    unsigned a_alt_hnp_support:1;
    unsigned hnp_polling_support:1;
    unsigned host_request_flag:1;
    unsigned quirk_ep_out_aligned_size:1;
    unsigned quirk_altset_not_supp:1;
    unsigned quirk_stall_not_supp:1;
    unsigned quirk_zlp_not_supp:1;
    unsigned quirk_avoids_skb_reserve:1;
    unsigned is_selfpowered:1;
    unsigned deactivated:1;
    unsigned connected:1;
    unsigned lpm_capable:1;
    unsigned wakeup_capable:1;
    unsigned wakeup_armed:1;
    int irq;
    int id_number;
};
```

**Members**

- `work`: (internal use) Workqueue to be used for `sysfs_notify()`
- `udc`: struct usb_udc pointer for this gadget
- `ops`: Function pointers used to access hardware-specific operations.
- `ep0`: Endpoint zero, used when reading or writing responses to
  driver `setup()` requests
- `ep_list`: List of other endpoints supported by the device.
- `speed`: Speed of current connection to USB host.
- `max_speed`: Maximal speed the UDC can handle.  UDC must support this
  and all slower speeds.
- `ssp_rate`: Current connected SuperSpeed Plus signaling rate and lane count.
- `max_ssp_rate`: Maximum SuperSpeed Plus signaling rate and lane count the UDC
  can handle. The UDC must support this and all slower speeds and lower
  number of lanes.
- `state`: the state we are now (attached, suspended, configured, etc)
- `state_lock`: Spinlock protecting the `state` and `teardown` members.
- `teardown`: True if the device is undergoing teardown, used to prevent
  new work from being scheduled during cleanup.
- `name`: Identifies the controller hardware type.  Used in diagnostics
  and sometimes configuration.
- `dev`: Driver model state for this abstract device.
- `isoch_delay`: value from Set Isoch Delay request. Only valid on SS/SSP
- `out_epnum`: last used out ep number
- `in_epnum`: last used in ep number
- `mA`: last set mA value
- `otg_caps`: OTG capabilities of this gadget.
- `sg_supported`: true if we can handle scatter-gather
- `is_otg`: True if the USB device port uses a Mini-AB jack, so that the
  gadget driver must provide a USB OTG descriptor.
- `is_a_peripheral`: False unless is_otg, the "A" end of a USB cable
  is in the Mini-AB jack, and HNP has been used to switch roles
  so that the "A" device currently acts as A-Peripheral, not A-Host.
- `b_hnp_enable`: OTG device feature flag, indicating that the A-Host
  enabled HNP support.
- `a_hnp_support`: OTG device feature flag, indicating that the A-Host
  supports HNP at this port.
- `a_alt_hnp_support`: OTG device feature flag, indicating that the A-Host
  only supports HNP on a different root port.
- `hnp_polling_support`: OTG device feature flag, indicating if the OTG device
  in peripheral mode can support HNP polling.
- `host_request_flag`: OTG device feature flag, indicating if A-Peripheral
  or B-Peripheral wants to take host role.
- `quirk_ep_out_aligned_size`: epout requires buffer size to be aligned to
  MaxPacketSize.
- `quirk_altset_not_supp`: UDC controller doesn't support alt settings.
- `quirk_stall_not_supp`: UDC controller doesn't support stalling.
- `quirk_zlp_not_supp`: UDC controller doesn't support ZLP.
- `quirk_avoids_skb_reserve`: udc/platform wants to avoid [`skb_reserve()`](/kernel/internals/networking/kapi.md#c-skb_reserve) in
  u_ether.c to improve performance.
- `is_selfpowered`: if the gadget is self-powered.
- `deactivated`: True if gadget is deactivated - in deactivated state it cannot
  be connected.
- `connected`: True if gadget is connected.
- `lpm_capable`: If the gadget max_speed is FULL or HIGH, this flag
  indicates that it supports LPM as per the LPM ECN & errata.
- `wakeup_capable`: True if gadget is capable of sending remote wakeup.
- `wakeup_armed`: True if gadget is armed by the host for remote wakeup.
- `irq`: the interrupt number for device controller.
- `id_number`: a unique ID number for ensuring that gadget names are distinct

**Description**

Gadgets have a mostly-portable "gadget driver" implementing device
functions, handling all usb configurations and interfaces.  Gadget
drivers talk to hardware-specific code indirectly, through ops vectors.
That insulates the gadget driver from hardware details, and packages
the hardware endpoints through generic i/o queues.  The "usb_gadget"
and "usb_ep" interfaces provide that insulation from the hardware.

Except for the driver data, all fields in this structure are
read-only to the gadget driver.  That driver data is part of the
"driver model" infrastructure in 2.6 (and later) kernels, and for
earlier systems is grouped in a similar structure that's not known
to the rest of the kernel.

Values of the three OTG device feature flags are updated before the
`setup()` call corresponding to USB_REQ_SET_CONFIGURATION, and before
driver `suspend()` calls.  They are valid only when is_otg, and when the
device is acting as a B-Peripheral (so is_a_peripheral is false).

#### <a id="c-usb_ep_align"></a>`usb_ep_align()`

```c
size_t usb_ep_align(struct usb_ep *ep, size_t len)
```

returns **len** aligned to ep's maxpacketsize.

**Parameters**

- `struct usb_ep *ep`: the endpoint whose maxpacketsize is used to align **len**
- `size_t len`: buffer size's length to align to **ep**'s maxpacketsize

**Description**

This helper is used to align buffer's size to an ep's maxpacketsize.

#### <a id="c-usb_ep_align_maybe"></a>`usb_ep_align_maybe()`

```c
size_t usb_ep_align_maybe(struct usb_gadget *g, struct usb_ep *ep, size_t len)
```

returns **len** aligned to ep's maxpacketsize if gadget requires quirk_ep_out_aligned_size, otherwise returns len.

**Parameters**

- `struct usb_gadget *g`: controller to check for quirk
- `struct usb_ep *ep`: the endpoint whose maxpacketsize is used to align **len**
- `size_t len`: buffer size's length to align to **ep**'s maxpacketsize

**Description**

This helper is used in case it's required for any reason to check and maybe
align buffer's size to an ep's maxpacketsize.

#### <a id="c-gadget_is_altset_supported"></a>`gadget_is_altset_supported()`

```c
int gadget_is_altset_supported(struct usb_gadget *g)
```

return true iff the hardware supports altsettings

**Parameters**

- `struct usb_gadget *g`: controller to check for quirk

#### <a id="c-gadget_is_stall_supported"></a>`gadget_is_stall_supported()`

```c
int gadget_is_stall_supported(struct usb_gadget *g)
```

return true iff the hardware supports stalling

**Parameters**

- `struct usb_gadget *g`: controller to check for quirk

#### <a id="c-gadget_is_zlp_supported"></a>`gadget_is_zlp_supported()`

```c
int gadget_is_zlp_supported(struct usb_gadget *g)
```

return true iff the hardware supports zlp

**Parameters**

- `struct usb_gadget *g`: controller to check for quirk

#### <a id="c-gadget_avoids_skb_reserve"></a>`gadget_avoids_skb_reserve()`

```c
int gadget_avoids_skb_reserve(struct usb_gadget *g)
```

return true iff the hardware would like to avoid skb_reserve to improve performance.

**Parameters**

- `struct usb_gadget *g`: controller to check for quirk

#### <a id="c-gadget_is_dualspeed"></a>`gadget_is_dualspeed()`

```c
int gadget_is_dualspeed(struct usb_gadget *g)
```

return true iff the hardware handles high speed

**Parameters**

- `struct usb_gadget *g`: controller that might support both high and full speeds

#### <a id="c-gadget_is_superspeed"></a>`gadget_is_superspeed()`

```c
int gadget_is_superspeed(struct usb_gadget *g)
```

return true if the hardware handles superspeed

**Parameters**

- `struct usb_gadget *g`: controller that might support superspeed

#### <a id="c-gadget_is_superspeed_plus"></a>`gadget_is_superspeed_plus()`

```c
int gadget_is_superspeed_plus(struct usb_gadget *g)
```

return true if the hardware handles superspeed plus

**Parameters**

- `struct usb_gadget *g`: controller that might support superspeed plus

#### <a id="c-gadget_is_otg"></a>`gadget_is_otg()`

```c
int gadget_is_otg(struct usb_gadget *g)
```

return true iff the hardware is OTG-ready

**Parameters**

- `struct usb_gadget *g`: controller that might have a Mini-AB connector

**Description**

This is a runtime test, since kernels with a USB-OTG stack sometimes
run on boards which only have a Mini-B (or Mini-A) connector.

#### <a id="c-struct-usb_gadget_driver"></a>`struct usb_gadget_driver`

driver for usb gadget devices

**Definition**

```c
struct usb_gadget_driver {
    char *function;
    enum usb_device_speed   max_speed;
    int (*bind)(struct usb_gadget *gadget, struct usb_gadget_driver *driver);
    void (*unbind)(struct usb_gadget *);
    int (*setup)(struct usb_gadget *, const struct usb_ctrlrequest *);
    void (*disconnect)(struct usb_gadget *);
    void (*suspend)(struct usb_gadget *);
    void (*resume)(struct usb_gadget *);
    void (*reset)(struct usb_gadget *);
    struct device_driver    driver;
    char *udc_name;
    unsigned match_existing_only:1;
    bool is_bound:1;
};
```

**Members**

- `function`: String describing the gadget's function
- `max_speed`: Highest speed the driver handles.
- `bind`: the driver's bind callback
- `unbind`: Invoked when the driver is unbound from a gadget,
  usually from rmmod (after a disconnect is reported).
  Called in a context that permits sleeping.
- `setup`: Invoked for ep0 control requests that aren't handled by
  the hardware level driver. Most calls must be handled by
  the gadget driver, including descriptor and configuration
  management.  The 16 bit members of the setup data are in
  USB byte order. Called in_interrupt; this may not sleep.  Driver
  queues a response to ep0, or returns negative to stall.
- `disconnect`: Invoked after all transfers have been stopped,
  when the host is disconnected.  May be called in_interrupt; this
  may not sleep.  Some devices can't detect disconnect, so this might
  not be called except as part of controller shutdown.
- `suspend`: Invoked on USB suspend.  May be called in_interrupt.
- `resume`: Invoked on USB resume.  May be called in_interrupt.
- `reset`: Invoked on USB bus reset. It is mandatory for all gadget drivers
  and should be called in_interrupt.
- `driver`: Driver model state for this driver.
- `udc_name`: A name of UDC this driver should be bound to. If udc_name is NULL,
  this driver will be bound to any available UDC.
- `match_existing_only`: If udc is not found, return an error and fail
  the driver registration
- `is_bound`: Allow a driver to be bound to only one gadget

**Description**

Devices are disabled till a gadget driver successfully `bind()`s, which
means the driver will handle `setup()` requests needed to enumerate (and
meet "chapter 9" requirements) then do some useful work.

If gadget->is_otg is true, the gadget driver must provide an OTG
descriptor during enumeration, or else fail the `bind()` call.  In such
cases, no USB traffic may flow until both `bind()` returns without
having called `usb_gadget_disconnect()`, and the USB host stack has
initialized.

Drivers use hardware-specific knowledge to configure the usb hardware.
endpoint addressing is only one of several hardware characteristics that
are in descriptors the ep0 implementation returns from `setup()` calls.

Except for ep0 implementation, most driver code shouldn't need change to
run on top of different usb controllers.  It'll use endpoints set up by
that ep0 implementation.

The usb controller driver handles a few standard usb requests.  Those
include set_address, and feature flags for devices, interfaces, and
endpoints (the get_status, set_feature, and clear_feature requests).

Accordingly, the driver's `setup()` callback must always implement all
get_descriptor requests, returning at least a device descriptor and
a configuration descriptor.  Drivers must make sure the endpoint
descriptors match any hardware constraints. Some hardware also constrains
other descriptors. (The pxa250 allows only configurations 1, 2, or 3).

The driver's `setup()` callback must also implement set_configuration,
and should also implement set_interface, get_configuration, and
get_interface.  Setting a configuration (or interface) is where
endpoints should be activated or (config 0) shut down.

The gadget driver's `setup()` callback does not have to queue a response to
ep0 within the `setup()` call, the driver can do it after `setup()` returns.
The UDC driver must wait until such a response is queued before proceeding
with the data/status stages of the control transfer.

**NOTE**

Currently, a number of UDC drivers rely on USB_GADGET_DELAYED_STATUS
being returned from the `setup()` callback, which is a bug. See the comment
next to USB_GADGET_DELAYED_STATUS for details.

(Note that only the default control endpoint is supported.  Neither
hosts nor devices generally support control traffic except to ep0.)

Most devices will ignore USB suspend/resume operations, and so will
not provide those callbacks.  However, some may need to change modes
when the host is not longer directing those activities.  For example,
local controls (buttons, dials, etc) may need to be re-enabled since
the (remote) host can't do that any longer; or an error state might
be cleared, to make the device behave identically whether or not
power is maintained.

#### <a id="c-usb_gadget_register_driver_owner"></a>`usb_gadget_register_driver_owner()`

```c
int usb_gadget_register_driver_owner(struct usb_gadget_driver *driver, struct module *owner, const char *mod_name)
```

register a gadget driver

**Parameters**

- `struct usb_gadget_driver *driver`: the driver being registered
- `struct module *owner`: the driver module
- `const char *mod_name`: the driver module's build name

**Context**

can sleep

**Description**

Call this in your gadget driver's module initialization function,
to tell the underlying UDC controller driver about your driver.
The **bind()** function will be called to bind it to a gadget before this
registration call returns.  It's expected that the **bind()** function will
be in init sections.

Use the macro defined below instead of calling this directly.

#### <a id="c-usb_gadget_unregister_driver"></a>`usb_gadget_unregister_driver()`

```c
int usb_gadget_unregister_driver(struct usb_gadget_driver *driver)
```

unregister a gadget driver

**Parameters**

- `struct usb_gadget_driver *driver`: the driver being unregistered

**Context**

can sleep

**Description**

Call this in your gadget driver's module cleanup function,
to tell the underlying usb controller that your driver is
going away.  If the controller is connected to a USB host,
it will first `disconnect()`.  The driver is also requested
to `unbind()` and clean up any device state, before this procedure
finally returns.  It's expected that the `unbind()` functions
will be in exit sections, so may not be linked in some kernels.

#### <a id="c-struct-usb_string"></a>`struct usb_string`

wraps a C string and its USB id

**Definition**

```c
struct usb_string {
    u8 id;
    const char              *s;
};
```

**Members**

- `id`: the (nonzero) ID for this string
- `s`: the string, in UTF-8 encoding

**Description**

If you're using [`usb_gadget_get_string()`](#c-usb_gadget_get_string), use this to wrap a string
together with its ID.

#### <a id="c-struct-usb_gadget_strings"></a>`struct usb_gadget_strings`

a set of USB strings in a given language

**Definition**

```c
struct usb_gadget_strings {
    u16 language;
    struct usb_string       *strings;
};
```

**Members**

- `language`: identifies the strings' language (0x0409 for en-us)
- `strings`: array of strings with their ids

**Description**

If you're using [`usb_gadget_get_string()`](#c-usb_gadget_get_string), use this to wrap all the
strings for a given language.

#### <a id="c-usb_free_descriptors"></a>`usb_free_descriptors()`

```c
void usb_free_descriptors(struct usb_descriptor_header **v)
```

free descriptors returned by [`usb_copy_descriptors()`](#c-usb_copy_descriptors)

**Parameters**

- `struct usb_descriptor_header **v`: vector of descriptors


<a id="rst-optional-utilities"></a>

### Optional Utilities

The core API is sufficient for writing a USB Gadget Driver, but some optional utilities are provided to simplify common tasks. These utilities include endpoint autoconfiguration.


#### <a id="c-usb_gadget_get_string"></a>`usb_gadget_get_string()`

```c
int usb_gadget_get_string(const struct usb_gadget_strings *table, int id, u8 *buf)
```

fill out a string descriptor

**Parameters**

- `const struct usb_gadget_strings *table`: of c strings encoded using UTF-8
- `int id`: string id, from low byte of wValue in get string descriptor
- `u8 *buf`: at least 256 bytes, must be 16-bit aligned

**Description**

Finds the UTF-8 string matching the ID, and converts it into a
string descriptor in utf16-le.
Returns length of descriptor (always even) or negative errno

If your driver needs stings in multiple languages, you'll probably
"switch (wIndex) { ... }"  in your ep0 string descriptor logic,
using this routine after choosing which set of UTF-8 strings to use.
Note that US-ASCII is a strict subset of UTF-8; any string bytes with
the eighth bit set will be multibyte UTF-8 characters, not ISO-8859/1
characters (which are also widely used in C strings).

#### <a id="c-usb_validate_langid"></a>`usb_validate_langid()`

```c
bool usb_validate_langid(u16 langid)
```

validate usb language identifiers

**Parameters**

- `u16 langid`: usb language identifier

**Description**

Returns true for valid language identifier, otherwise false.



#### <a id="c-usb_descriptor_fillbuf"></a>`usb_descriptor_fillbuf()`

```c
int usb_descriptor_fillbuf(void *buf, unsigned buflen, const struct usb_descriptor_header **src)
```

fill buffer with descriptors

**Parameters**

- `void *buf`: Buffer to be filled
- `unsigned buflen`: Size of buf
- `const struct usb_descriptor_header **src`: Array of descriptor pointers, terminated by null pointer.

**Description**

Copies descriptors into the buffer, returning the length or a
negative error code if they can't all be copied.  Useful when
assembling descriptors for an associated set of interfaces used
as part of configuring a composite device; or in other cases where
sets of descriptors need to be marshaled.

#### <a id="c-usb_copy_descriptors"></a>`usb_copy_descriptors()`

```c
struct usb_descriptor_header ** usb_copy_descriptors(struct usb_descriptor_header **src)
```

copy a vector of USB descriptors

**Parameters**

- `struct usb_descriptor_header **src`: null-terminated vector to copy

**Context**

initialization code, which may sleep

**Description**

This makes a copy of a vector of USB descriptors.  Its primary use
is to support usb_function objects which can have multiple copies,
each needing different descriptors.  Functions may have static
tables of descriptors, which are used as templates and customized
with identifiers (for interfaces, strings, endpoints, and more)
as needed by a given function instance.


<a id="rst-composite-device-framework"></a>

### Composite Device Framework

The core API is sufficient for writing drivers for composite USB devices (with more than one function in a given configuration), and also multi-configuration devices (also more than one function, but not necessarily sharing a given configuration). There is however an optional framework which makes it easier to reuse and combine functions.

Devices using this framework provide a struct usb_composite_driver, which in turn provides one or more struct usb_configuration instances. Each such configuration includes at least one struct `usb_function`, which packages a user visible role such as "network link" or "mass storage device". Management functions may also exist, such as "Device Firmware Upgrade".


#### <a id="c-struct-usb_os_desc_ext_prop"></a>`struct usb_os_desc_ext_prop`

describes one "Extended Property"

**Definition**

```c
struct usb_os_desc_ext_prop {
    struct list_head        entry;
    u8 type;
    int name_len;
    char *name;
    int data_len;
    char *data;
    struct config_item      item;
};
```

**Members**

- `entry`: used to keep a list of extended properties
- `type`: Extended Property type
- `name_len`: Extended Property unicode name length, including terminating '\0'
- `name`: Extended Property name
- `data_len`: Length of Extended Property blob (for unicode store double len)
- `data`: Extended Property blob
- `item`: Represents this Extended Property in configfs

#### <a id="c-struct-usb_os_desc"></a>`struct usb_os_desc`

describes OS descriptors associated with one interface

**Definition**

```c
struct usb_os_desc {
    char *ext_compat_id;
    struct list_head        ext_prop;
    int ext_prop_len;
    int ext_prop_count;
    struct mutex            *opts_mutex;
    struct config_group     group;
    struct module           *owner;
};
```

**Members**

- `ext_compat_id`: 16 bytes of "Compatible ID" and "Subcompatible ID"
- `ext_prop`: Extended Properties list
- `ext_prop_len`: Total length of Extended Properties blobs
- `ext_prop_count`: Number of Extended Properties
- `opts_mutex`: Optional mutex protecting config data of a usb_function_instance
- `group`: Represents OS descriptors associated with an interface in configfs
- `owner`: Module associated with this OS descriptor

#### <a id="c-struct-usb_os_desc_table"></a>`struct usb_os_desc_table`

describes OS descriptors associated with one interface of a usb_function

**Definition**

```c
struct usb_os_desc_table {
    int if_id;
    struct usb_os_desc      *os_desc;
};
```

**Members**

- `if_id`: Interface id
- `os_desc`: "Extended Compatibility ID" and "Extended Properties" of the
  interface

**Description**

Each interface can have at most one "Extended Compatibility ID" and a
number of "Extended Properties".

#### <a id="c-struct-usb_function"></a>`struct usb_function`

describes one function of a configuration

**Definition**

```c
struct usb_function {
    const char                      *name;
    struct usb_gadget_strings       **strings;
    struct usb_descriptor_header    **fs_descriptors;
    struct usb_descriptor_header    **hs_descriptors;
    struct usb_descriptor_header    **ss_descriptors;
    struct usb_descriptor_header    **ssp_descriptors;
    struct usb_configuration        *config;
    struct usb_os_desc_table        *os_desc_table;
    unsigned os_desc_n;
    int (*bind)(struct usb_configuration *, struct usb_function *);
    void (*unbind)(struct usb_configuration *, struct usb_function *);
    void (*free_func)(struct usb_function *f);
    struct module           *mod;
    int (*set_alt)(struct usb_function *, unsigned interface, unsigned alt);
    int (*get_alt)(struct usb_function *, unsigned interface);
    void (*disable)(struct usb_function *);
    int (*setup)(struct usb_function *, const struct usb_ctrlrequest *);
    bool (*req_match)(struct usb_function *, const struct usb_ctrlrequest *, bool config0);
    void (*suspend)(struct usb_function *);
    void (*resume)(struct usb_function *);
    int (*get_status)(struct usb_function *);
    int (*func_suspend)(struct usb_function *, u8 suspend_opt);
    bool func_suspended;
    bool func_wakeup_armed;
};
```

**Members**

- `name`: For diagnostics, identifies the function.
- `strings`: tables of strings, keyed by identifiers assigned during `bind()`
  and by language IDs provided in control requests
- `fs_descriptors`: Table of full (or low) speed descriptors, using interface and
  string identifiers assigned during **bind()**.  If this pointer is null,
  the function will not be available at full speed (or at low speed).
- `hs_descriptors`: Table of high speed descriptors, using interface and
  string identifiers assigned during **bind()**.  If this pointer is null,
  the function will not be available at high speed.
- `ss_descriptors`: Table of super speed descriptors, using interface and
  string identifiers assigned during **bind()**. If this
  pointer is null after initiation, the function will not
  be available at super speed.
- `ssp_descriptors`: Table of super speed plus descriptors, using
  interface and string identifiers assigned during **bind()**. If
  this pointer is null after initiation, the function will not
  be available at super speed plus.
- `config`: assigned when **usb_add_function()** is called; this is the
  configuration with which this function is associated.
- `os_desc_table`: Table of (interface id, os descriptors) pairs. The function
  can expose more than one interface. If an interface is a member of
  an IAD, only the first interface of IAD has its entry in the table.
- `os_desc_n`: Number of entries in os_desc_table
- `bind`: Before the gadget can register, all of its functions `bind()` to the
  available resources including string and interface identifiers used
  in interface or class descriptors; endpoints; I/O buffers; and so on.
- `unbind`: Reverses **bind**; called as a side effect of unregistering the
  driver which added this function.
- `free_func`: free the struct usb_function.
- `mod`: (internal) points to the module that created this structure.
- `set_alt`: (REQUIRED) Reconfigures altsettings; function drivers may
  initialize usb_ep.driver data at this time (when it is used).
  Note that setting an interface to its current altsetting resets
  interface state, and that all interfaces have a disabled state.
- `get_alt`: Returns the active altsetting.  If this is not provided,
  then only altsetting zero is supported.
- `disable`: (REQUIRED) Indicates the function should be disabled.  Reasons
  include host resetting or reconfiguring the gadget, and disconnection.
- `setup`: Used for interface-specific control requests.
- `req_match`: Tests if a given class request can be handled by this function.
- `suspend`: Notifies functions when the host stops sending USB traffic.
- `resume`: Notifies functions when the host restarts USB traffic.
- `get_status`: Returns function status as a reply to
  `GetStatus()` request when the recipient is Interface.
- `func_suspend`: callback to be called when
  SetFeature(FUNCTION_SUSPEND) is reseived
- `func_suspended`: Indicates whether the function is in function suspend state.
- `func_wakeup_armed`: Indicates whether the function is armed by the host for
  wakeup signaling.

**Description**

A single USB function uses one or more interfaces, and should in most
cases support operation at both full and high speeds.  Each function is
associated by **usb_add_function()** with a one configuration; that function
causes **bind()** to be called so resources can be allocated as part of
setting up a gadget driver.  Those resources include endpoints, which
should be allocated using **usb_ep_autoconfig()**.

To support dual speed operation, a function driver provides descriptors
for both high and full speed operation.  Except in rare cases that don't
involve bulk endpoints, each speed needs different endpoint descriptors.

Function drivers choose their own strategies for managing instance data.
The simplest strategy just declares it "static', which means the function
can only be activated once.  If the function needs to be exposed in more
than one configuration at a given speed, it needs to support multiple
usb_function structures (one for each configuration).

A more complex strategy might encapsulate a **usb_function** structure inside
a driver-specific instance structure to allows multiple activations.  An
example of multiple activations might be a CDC ACM function that supports
two or more distinct instances within the same configuration, providing
several independent logical data links to a USB host.

#### <a id="c-struct-usb_configuration"></a>`struct usb_configuration`

represents one gadget configuration

**Definition**

```c
struct usb_configuration {
    const char                      *label;
    struct usb_gadget_strings       **strings;
    const struct usb_descriptor_header **descriptors;
    void (*unbind)(struct usb_configuration *);
    int (*setup)(struct usb_configuration *, const struct usb_ctrlrequest *);
    u8 bConfigurationValue;
    u8 iConfiguration;
    u8 bmAttributes;
    u16 MaxPower;
    struct usb_composite_dev        *cdev;
};
```

**Members**

- `label`: For diagnostics, describes the configuration.
- `strings`: Tables of strings, keyed by identifiers assigned during **bind()**
  and by language IDs provided in control requests.
- `descriptors`: Table of descriptors preceding all function descriptors.
  Examples include OTG and vendor-specific descriptors.
- `unbind`: Reverses **bind**; called as a side effect of unregistering the
  driver which added this configuration.
- `setup`: Used to delegate control requests that aren't handled by standard
  device infrastructure or directed at a specific interface.
- `bConfigurationValue`: Copied into configuration descriptor.
- `iConfiguration`: Copied into configuration descriptor.
- `bmAttributes`: Copied into configuration descriptor.
- `MaxPower`: Power consumption in mA. Used to compute bMaxPower in the
  configuration descriptor after considering the bus speed.
- `cdev`: assigned by **usb_add_config()** before calling **bind()**; this is
  the device associated with this configuration.

**Description**

Configurations are building blocks for gadget drivers structured around
function drivers.  Simple USB gadgets require only one function and one
configuration, and handle dual-speed hardware by always providing the same
functionality.  Slightly more complex gadgets may have more than one
single-function configuration at a given speed; or have configurations
that only work at one speed.

Composite devices are, by definition, ones with configurations which
include more than one function.

The lifecycle of a usb_configuration includes allocation, initialization
of the fields described above, and calling **usb_add_config()** to set up
internal data and bind it to a specific device.  The configuration's
**bind()** method is then used to initialize all the functions and then
call **usb_add_function()** for them.

Those functions would normally be independent of each other, but that's
not mandatory.  CDC WMC devices are an example where functions often
depend on other functions, with some functions subsidiary to others.
Such interdependency may be managed in any way, so long as all of the
descriptors complete by the time the composite driver returns from
its `bind()` routine.

#### <a id="c-struct-usb_composite_driver"></a>`struct usb_composite_driver`

groups configurations into a gadget

**Definition**

```c
struct usb_composite_driver {
    const char                              *name;
    const struct usb_device_descriptor      *dev;
    struct usb_gadget_strings               **strings;
    enum usb_device_speed                   max_speed;
    unsigned needs_serial:1;
    int (*bind)(struct usb_composite_dev *cdev);
    int (*unbind)(struct usb_composite_dev *);
    void (*disconnect)(struct usb_composite_dev *);
    void (*suspend)(struct usb_composite_dev *);
    void (*resume)(struct usb_composite_dev *);
    struct usb_gadget_driver                gadget_driver;
};
```

**Members**

- `name`: For diagnostics, identifies the driver.
- `dev`: Template descriptor for the device, including default device
  identifiers.
- `strings`: tables of strings, keyed by identifiers assigned during **bind**
  and language IDs provided in control requests. Note: The first entries
  are predefined. The first entry that may be used is
  USB_GADGET_FIRST_AVAIL_IDX
- `max_speed`: Highest speed the driver supports.
- `needs_serial`: set to 1 if the gadget needs userspace to provide
  a serial number.  If one is not provided, warning will be printed.
- `bind`: (REQUIRED) Used to allocate resources that are shared across the
  whole device, such as string IDs, and add its configurations using
  **usb_add_config()**. This may fail by returning a negative errno
  value; it should return zero on successful initialization.
- `unbind`: Reverses **bind**; called as a side effect of unregistering
  this driver.
- `disconnect`: optional driver disconnect method
- `suspend`: Notifies when the host stops sending USB traffic,
  after function notifications
- `resume`: Notifies configuration when the host restarts USB traffic,
  before function notifications
- `gadget_driver`: Gadget driver controlling this driver

**Description**

Devices default to reporting self powered operation.  Devices which rely
on bus powered operation should report this in their **bind** method.

Before returning from **bind**, various fields in the template descriptor
may be overridden.  These include the idVendor/idProduct/bcdDevice values
normally to bind the appropriate host side driver, and the three strings
(iManufacturer, iProduct, iSerialNumber) normally used to provide user
meaningful device identifiers.  (The strings will not be defined unless
they are defined in **dev** and **strings**.)  The correct ep0 maxpacket size
is also reported, as defined by the underlying controller driver.

#### <a id="c-module_usb_composite_driver"></a>`module_usb_composite_driver()`

```c
module_usb_composite_driver(__usb_composite_driver)
```

Helper macro for registering a USB gadget composite driver

**Parameters**

- `__usb_composite_driver`: usb_composite_driver struct

**Description**

Helper macro for USB gadget composite drivers which do not do anything
special in module init/exit. This eliminates a lot of boilerplate. Each
module may only use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init)
and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)

#### <a id="c-struct-usb_composite_dev"></a>`struct usb_composite_dev`

represents one composite usb gadget

**Definition**

```c
struct usb_composite_dev {
    struct usb_gadget               *gadget;
    struct usb_request              *req;
    struct usb_request              *os_desc_req;
    struct usb_configuration        *config;
    u8 qw_sign[OS_STRING_QW_SIGN_LEN];
    u8 b_vendor_code;
    struct usb_configuration        *os_desc_config;
    unsigned int                    use_os_string:1;
    u16 bcd_webusb_version;
    u8 b_webusb_vendor_code;
    char landing_page[WEBUSB_URL_RAW_MAX_LENGTH];
    unsigned int                    use_webusb:1;
    unsigned int                    setup_pending:1;
    unsigned int                    os_desc_pending:1;
};
```

**Members**

- `gadget`: read-only, abstracts the gadget's usb peripheral controller
- `req`: used for control responses; buffer is pre-allocated
- `os_desc_req`: used for OS descriptors responses; buffer is pre-allocated
- `config`: the currently active configuration
- `qw_sign`: qwSignature part of the OS string
- `b_vendor_code`: bMS_VendorCode part of the OS string
- `os_desc_config`: the configuration to be used with OS descriptors
- `use_os_string`: false by default, interested gadgets set it
- `bcd_webusb_version`: 0x0100 by default, WebUSB specification version
- `b_webusb_vendor_code`: 0x0 by default, vendor code for WebUSB
- `landing_page`: empty by default, landing page to announce in WebUSB
- `use_webusb`: false by default, interested gadgets set it
- `setup_pending`: true when setup request is queued but not completed
- `os_desc_pending`: true when os_desc request is queued but not completed

**Description**

One of these devices is allocated and initialized before the
associated device driver's `bind()` is called.



#### <a id="c-config_ep_by_speed_and_alt"></a>`config_ep_by_speed_and_alt()`

```c
int config_ep_by_speed_and_alt(struct usb_gadget *g, struct usb_function *f, struct usb_ep *_ep, u8 alt)
```

configures the given endpoint according to gadget speed.

**Parameters**

- `struct usb_gadget *g`: pointer to the gadget
- `struct usb_function *f`: usb function
- `struct usb_ep *_ep`: the endpoint to configure
- `u8 alt`: alternate setting number

**Return**

error code, 0 on success

**Description**

This function chooses the right descriptors for a given
endpoint according to gadget speed and saves it in the
endpoint desc field. If the endpoint already has a descriptor
assigned to it - overwrites it with currently corresponding
descriptor. The endpoint maxpacket field is updated according
to the chosen descriptor.

**Note**

the supplied function should hold all the descriptors
for supported speeds

#### <a id="c-config_ep_by_speed"></a>`config_ep_by_speed()`

```c
int config_ep_by_speed(struct usb_gadget *g, struct usb_function *f, struct usb_ep *_ep)
```

configures the given endpoint according to gadget speed.

**Parameters**

- `struct usb_gadget *g`: pointer to the gadget
- `struct usb_function *f`: usb function
- `struct usb_ep *_ep`: the endpoint to configure

**Return**

error code, 0 on success

**Description**

This function chooses the right descriptors for a given
endpoint according to gadget speed and saves it in the
endpoint desc field. If the endpoint already has a descriptor
assigned to it - overwrites it with currently corresponding
descriptor. The endpoint maxpacket field is updated according
to the chosen descriptor.

**Note**

the supplied function should hold all the descriptors
for supported speeds

#### <a id="c-usb_add_function"></a>`usb_add_function()`

```c
int usb_add_function(struct usb_configuration *config, struct usb_function *function)
```

add a function to a configuration

**Parameters**

- `struct usb_configuration *config`: the configuration
- `struct usb_function *function`: the function being added

**Context**

single threaded during gadget setup

**Description**

After initialization, each configuration must have one or more
functions added to it.  Adding a function involves calling its **bind()**
method to allocate resources such as interface and string identifiers
and endpoints.

This function returns the value of the function's `bind()`, which is
zero for success else a negative errno value.

#### <a id="c-usb_function_deactivate"></a>`usb_function_deactivate()`

```c
int usb_function_deactivate(struct usb_function *function)
```

prevent function and gadget enumeration

**Parameters**

- `struct usb_function *function`: the function that isn't yet ready to respond

**Description**

Blocks response of the gadget driver to host enumeration by
preventing the data line pullup from being activated.  This is
normally called during **bind()** processing to change from the
initial "ready to respond" state, or when a required resource
becomes available.

For example, drivers that serve as a passthrough to a userspace
daemon can block enumeration unless that daemon (such as an OBEX,
MTP, or print server) is ready to handle host requests.

Not all systems support software control of their USB peripheral
data pullups.

Returns zero on success, else negative errno.

#### <a id="c-usb_function_activate"></a>`usb_function_activate()`

```c
int usb_function_activate(struct usb_function *function)
```

allow function and gadget enumeration

**Parameters**

- `struct usb_function *function`: function on which [`usb_function_activate()`](#c-usb_function_activate) was called

**Description**

Reverses effect of [`usb_function_deactivate()`](#c-usb_function_deactivate).  If no more functions
are delaying their activation, the gadget driver will respond to
host enumeration procedures.

Returns zero on success, else negative errno.

#### <a id="c-usb_interface_id"></a>`usb_interface_id()`

```c
int usb_interface_id(struct usb_configuration *config, struct usb_function *function)
```

allocate an unused interface ID

**Parameters**

- `struct usb_configuration *config`: configuration associated with the interface
- `struct usb_function *function`: function handling the interface

**Context**

single threaded during gadget setup

**Description**

[`usb_interface_id()`](#c-usb_interface_id) is called from usb_function.`bind()` callbacks to
allocate new interface IDs.  The function driver will then store that
ID in interface, association, CDC union, and other descriptors.  It
will also handle any control requests targeted at that interface,
particularly changing its altsetting via `set_alt()`.  There may
also be class-specific or vendor-specific requests to handle.

All interface identifier should be allocated using this routine, to
ensure that for example different functions don't wrongly assign
different meanings to the same identifier.  Note that since interface
identifiers are configuration-specific, functions used in more than
one configuration (or more than once in a given configuration) need
multiple versions of the relevant descriptors.

Returns the interface ID which was allocated; or -ENODEV if no
more interface IDs can be allocated.

#### <a id="c-usb_func_wakeup"></a>`usb_func_wakeup()`

```c
int usb_func_wakeup(struct usb_function *func)
```

sends function wake notification to the host.

**Parameters**

- `struct usb_function *func`: function that sends the remote wakeup notification.

**Description**

Applicable to devices operating at enhanced superspeed when usb
functions are put in function suspend state and armed for function
remote wakeup. On completion, function wake notification is sent. If
the device is in low power state it tries to bring the device to active
state before sending the wake notification. Since it is a synchronous
call, caller must take care of not calling it in interrupt context.
For devices operating at lower speeds  returns negative errno.

Returns zero on success, else negative errno.

#### <a id="c-usb_add_config"></a>`usb_add_config()`

```c
int usb_add_config(struct usb_composite_dev *cdev, struct usb_configuration *config, int (*bind)(struct usb_configuration *))
```

add a configuration to a device.

**Parameters**

- `struct usb_composite_dev *cdev`: wraps the USB gadget
- `struct usb_configuration *config`: the configuration, with bConfigurationValue assigned
- `int (*bind)(struct usb_configuration *)`: the configuration's bind function

**Context**

single threaded during gadget setup

**Description**

One of the main tasks of a composite **bind()** routine is to
add each of the configurations it supports, using this routine.

This function returns the value of the configuration's **bind()**, which
is zero for success else a negative errno value.  Binding configurations
assigns global resources including string IDs, and per-configuration
resources such as interface IDs and endpoints.

#### <a id="c-usb_string_id"></a>`usb_string_id()`

```c
int usb_string_id(struct usb_composite_dev *cdev)
```

allocate an unused string ID

**Parameters**

- `struct usb_composite_dev *cdev`: the device whose string descriptor IDs are being allocated

**Context**

single threaded during gadget setup

**Description**

**usb_string_id()** is called from `bind()` callbacks to allocate
string IDs.  Drivers for functions, configurations, or gadgets will
then store that ID in the appropriate descriptors and string table.

All string identifier should be allocated using this,
**usb_string_ids_tab()** or **usb_string_ids_n()** routine, to ensure
that for example different functions don't wrongly assign different
meanings to the same identifier.

#### <a id="c-usb_string_ids_tab"></a>`usb_string_ids_tab()`

```c
int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
```

allocate unused string IDs in batch

**Parameters**

- `struct usb_composite_dev *cdev`: the device whose string descriptor IDs are being allocated
- `struct usb_string *str`: an array of usb_string objects to assign numbers to

**Context**

single threaded during gadget setup

**Description**

**usb_string_ids()** is called from `bind()` callbacks to allocate
string IDs.  Drivers for functions, configurations, or gadgets will
then copy IDs from the string table to the appropriate descriptors
and string table for other languages.

All string identifier should be allocated using this,
**usb_string_id()** or **usb_string_ids_n()** routine, to ensure that for
example different functions don't wrongly assign different meanings
to the same identifier.

#### <a id="c-usb_gstrings_attach"></a>`usb_gstrings_attach()`

```c
struct usb_string * usb_gstrings_attach(struct usb_composite_dev *cdev, struct usb_gadget_strings **sp, unsigned n_strings)
```

attach gadget strings to a cdev and assign ids

**Parameters**

- `struct usb_composite_dev *cdev`: the device whose string descriptor IDs are being allocated
  and attached.
- `struct usb_gadget_strings **sp`: an array of usb_gadget_strings to attach.
- `unsigned n_strings`: number of entries in each usb_strings array (sp\[\]->strings)

**Description**

This function will create a deep copy of usb_gadget_strings and usb_string
and attach it to the cdev. The actual string (usb_string.s) will not be
copied but only a referenced will be made. The struct usb_gadget_strings
array may contain multiple languages and should be NULL terminated.
The ->language pointer of each struct usb_gadget_strings has to contain the
same amount of entries.
For instance: sp\[0\] is en-US, sp\[1\] is es-ES. It is expected that the first
usb_string entry of es-ES contains the translation of the first usb_string
entry of en-US. Therefore both entries become the same id assign.

#### <a id="c-usb_string_ids_n"></a>`usb_string_ids_n()`

```c
int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
```

allocate unused string IDs in batch

**Parameters**

- `struct usb_composite_dev *c`: the device whose string descriptor IDs are being allocated
- `unsigned n`: number of string IDs to allocate

**Context**

single threaded during gadget setup

**Description**

Returns the first requested ID.  This ID and next **n**-1 IDs are now
valid IDs.  At least provided that **n** is non-zero because if it
is, returns last requested ID which is now very useful information.

**usb_string_ids_n()** is called from `bind()` callbacks to allocate
string IDs.  Drivers for functions, configurations, or gadgets will
then store that ID in the appropriate descriptors and string table.

All string identifier should be allocated using this,
**usb_string_id()** or **usb_string_ids_n()** routine, to ensure that for
example different functions don't wrongly assign different meanings
to the same identifier.

#### <a id="c-usb_composite_probe"></a>`usb_composite_probe()`

```c
int usb_composite_probe(struct usb_composite_driver *driver)
```

register a composite driver

**Parameters**

- `struct usb_composite_driver *driver`: the driver to register

**Context**

single threaded during gadget setup

**Description**

This function is used to register drivers using the composite driver
framework.  The return value is zero, or a negative errno value.
Those values normally come from the driver's **bind** method, which does
all the work of setting up the driver to match the hardware.

On successful return, the gadget is ready to respond to requests from
the host, unless one of its components invokes `usb_gadget_disconnect()`
while it was binding.  That would usually be done in order to wait for
some userspace participation.

#### <a id="c-usb_composite_unregister"></a>`usb_composite_unregister()`

```c
void usb_composite_unregister(struct usb_composite_driver *driver)
```

unregister a composite driver

**Parameters**

- `struct usb_composite_driver *driver`: the driver to unregister

**Description**

This function is used to unregister drivers using the composite
driver framework.

#### <a id="c-usb_composite_setup_continue"></a>`usb_composite_setup_continue()`

```c
void usb_composite_setup_continue(struct usb_composite_dev *cdev)
```

Continue with the control transfer

**Parameters**

- `struct usb_composite_dev *cdev`: the composite device who's control transfer was kept waiting

**Description**

This function must be called by the USB function driver to continue
with the control transfer's data/status stage in case it had requested to
delay the data/status stages. A USB function's setup handler (e.g. `set_alt()`)
can request the composite framework to delay the setup request's data/status
stages by returning USB_GADGET_DELAYED_STATUS.


<a id="rst-composite-device-functions"></a>

### Composite Device Functions

At this writing, a few of the current gadget drivers have been converted to this framework. Near-term plans include converting all of them, except for `gadgetfs`.

<a id="rst-peripheral-controller-drivers"></a>

## Peripheral Controller Drivers

The first hardware supporting this API was the NetChip 2280 controller, which supports USB 2.0 high speed and is based on PCI. This is the `net2280` driver module. The driver supports Linux kernel versions 2.4 and 2.6; contact NetChip Technologies for development boards and product information.

Other hardware working in the `gadget` framework includes: Intel's PXA 25x and IXP42x series processors (`pxa2xx_udc`), Toshiba TC86c001 "Goku-S" (`goku_udc`), Renesas SH7705/7727 (`sh_udc`), MediaQ 11xx (`mq11xx_udc`), Hynix HMS30C7202 (`h7202_udc`), National 9303/4 (`n9604_udc`), Texas Instruments OMAP (`omap_udc`), Sharp LH7A40x (`lh7a40x_udc`), and more. Most of those are full speed controllers.

At this writing, there are people at work on drivers in this framework for several other USB device controllers, with plans to make many of them be widely available.

A partial USB simulator, the `dummy_hcd` driver, is available. It can act like a net2280, a pxa25x, or an sa11x0 in terms of available endpoints and device speeds; and it simulates control, bulk, and to some extent interrupt transfers. That lets you develop some parts of a gadget driver on a normal PC, without any special hardware, and perhaps with the assistance of tools such as GDB running with User Mode Linux. At least one person has expressed interest in adapting that approach, hooking it up to a simulator for a microcontroller. Such simulators can help debug subsystems where the runtime hardware is unfriendly to software development, or is not yet available.

Support for other controllers is expected to be developed and contributed over time, as this driver framework evolves.

<a id="rst-gadget-drivers"></a>

## Gadget Drivers

In addition to *Gadget Zero* (used primarily for testing and development with drivers for usb controller hardware), other gadget drivers exist.

There's an `ethernet` gadget driver, which implements one of the most useful *Communications Device Class* (CDC) models. One of the standards for cable modem interoperability even specifies the use of this ethernet model as one of two mandatory options. Gadgets using this code look to a USB host as if they're an Ethernet adapter. It provides access to a network where the gadget's CPU is one host, which could easily be bridging, routing, or firewalling access to other networks. Since some hardware can't fully implement the CDC Ethernet requirements, this driver also implements a "good parts only" subset of CDC Ethernet. (That subset doesn't advertise itself as CDC Ethernet, to avoid creating problems.)

Support for Microsoft's `RNDIS` protocol has been contributed by Pengutronix and Auerswald GmbH. This is like CDC Ethernet, but it runs on more slightly USB hardware (but less than the CDC subset). However, its main claim to fame is being able to connect directly to recent versions of Windows, using drivers that Microsoft bundles and supports, making it much simpler to network with Windows.

There is also support for user mode gadget drivers, using `gadgetfs`. This provides a *User Mode API* that presents each endpoint as a single file descriptor. I/O is done using normal `read()` and `read()` calls. Familiar tools like GDB and pthreads can be used to develop and debug user mode drivers, so that once a robust controller driver is available many applications for it won't require new kernel mode software. Linux 2.6 *Async I/O (AIO)* support is available, so that user mode software can stream data with only slightly more overhead than a kernel driver.

There's a USB Mass Storage class driver, which provides a different solution for interoperability with systems such as MS-Windows and MacOS. That *Mass Storage* driver uses a file or block device as backing store for a drive, like the `loop` driver. The USB host uses the BBB, CB, or CBI versions of the mass storage class specification, using transparent SCSI commands to access the data from the backing store.

There's a "serial line" driver, useful for TTY style operation over USB. The latest version of that driver supports CDC ACM style operation, like a USB modem, and so on most hardware it can interoperate easily with MS-Windows. One interesting use of that driver is in boot firmware (like a BIOS), which can sometimes use that model with very small systems without real serial lines.

Support for other kinds of gadget is expected to be developed and contributed over time, as this driver framework evolves.

<a id="rst-usb-on-the-go-otg"></a>

## USB On-The-GO (OTG)

USB OTG support on Linux 2.6 was initially developed by Texas Instruments for [OMAP](<http://www.omap.com>) 16xx and 17xx series processors. Other OTG systems should work in similar ways, but the hardware level details could be very different.

Systems need specialized hardware support to implement OTG, notably including a special *Mini-AB* jack and associated transceiver to support *Dual-Role* operation: they can act either as a host, using the standard Linux-USB host side driver stack, or as a peripheral, using this `gadget` framework. To do that, the system software relies on small additions to those programming interfaces, and on a new internal component (here called an "OTG Controller") affecting which driver stack connects to the OTG port. In each role, the system can reuse the existing pool of hardware-neutral drivers, layered on top of the controller driver interfaces (`usb_bus` or `usb_gadget`). Such drivers need at most minor changes, and most of the calls added to support OTG can also benefit non-OTG products.

- Gadget drivers test the `is_otg` flag, and use it to determine whether or not to include an OTG descriptor in each of their configurations.

- Gadget drivers may need changes to support the two new OTG protocols, exposed in new gadget attributes such as `b_hnp_enable` flag. HNP support should be reported through a user interface (two LEDs could suffice), and is triggered in some cases when the host suspends the peripheral. SRP support can be user-initiated just like remote wakeup, probably by pressing the same button.

- On the host side, USB device drivers need to be taught to trigger HNP at appropriate moments, using `usb_suspend_device()`. That also conserves battery power, which is useful even for non-OTG configurations.

- Also on the host side, a driver must support the OTG "Targeted Peripheral List". That's just a whitelist, used to reject peripherals not supported with a given Linux OTG host. *This whitelist is product-specific; each product must modify* `otg_whitelist.h` *to match its interoperability specification.*

  Non-OTG Linux hosts, like PCs and workstations, normally have some solution for adding drivers, so that peripherals that aren't recognized can eventually be supported. That approach is unreasonable for consumer products that may never have their firmware upgraded, and where it's usually unrealistic to expect traditional PC/workstation/server kinds of support model to work. For example, it's often impractical to change device firmware once the product has been distributed, so driver bugs can't normally be fixed if they're found after shipment.

Additional changes are needed below those hardware-neutral `usb_bus` and `usb_gadget` driver interfaces; those aren't discussed here in any detail. Those affect the hardware-specific code for each USB Host or Peripheral controller, and how the HCD initializes (since OTG can be active only on a single port). They also involve what may be called an *OTG Controller Driver*, managing the OTG transceiver and the OTG state machine logic as well as much of the root hub behavior for the OTG port. The OTG controller driver needs to activate and deactivate USB controllers depending on the relevant device role. Some related changes were needed inside usbcore, so that it can identify OTG-capable devices and respond appropriately to HNP or SRP protocols.

---

# USB hotplugging

_Peios Kernel / Hardware and drivers / Driver development / USB_

> In hotpluggable buses like USB (and Cardbus PCI), end-users plug devices into the bus with power on. In most cases, users expect the devices to become immediately usable. That means the system must do many things, including:

<a id="rst-usb-hotplugging"></a>

<a id="rst-linux-hotplugging"></a>

## Linux Hotplugging

In hotpluggable buses like USB (and Cardbus PCI), end-users plug devices into the bus with power on.  In most cases, users expect the devices to become immediately usable.  That means the system must do many things, including:

> - Find a driver that can handle the device.  That may involve loading a kernel module; newer drivers can use module-init-tools to publish their device (and class) support to user utilities.
>
> - Bind a driver to that device.  Bus frameworks do that using a device driver's probe() routine.
>
> - Tell other subsystems to configure the new device.  Print queues may need to be enabled, networks brought up, disk partitions mounted, and so on.  In some cases these will be driver-specific actions.

This involves a mix of kernel mode and user mode actions.  Making devices be immediately usable means that any user mode actions can't wait for an administrator to do them:  the kernel must trigger them, either passively (triggering some monitoring daemon to invoke a helper program) or actively (calling such a user mode helper program directly).

Those triggered actions must support a system's administrative policies; such programs are called "policy agents" here.  Typically they involve shell scripts that dispatch to more familiar administration tools.

Because some of those actions rely on information about drivers (metadata) that is currently available only when the drivers are dynamically linked, you get the best hotplugging when you configure a highly modular system.

<a id="rst-kernel-hotplug-helper-sbin-hotplug"></a>

## Kernel Hotplug Helper (`/sbin/hotplug`)

There is a kernel parameter: `/proc/sys/kernel/hotplug`, which normally holds the pathname `/sbin/hotplug`.  That parameter names a program which the kernel may invoke at various times.

The /sbin/hotplug program can be invoked by any subsystem as part of its reaction to a configuration change, from a thread in that subsystem. Only one parameter is required: the name of a subsystem being notified of some kernel event.  That name is used as the first key for further event dispatch; any other argument and environment parameters are specified by the subsystem making that invocation.

Hotplug software and other resources is available at:

> [http://linux-hotplug.sourceforge.net](<http://linux-hotplug.sourceforge.net>)

Mailing list information is also available at that site.

<a id="rst-usb-policy-agent"></a>

## USB Policy Agent

The USB subsystem currently invokes `/sbin/hotplug` when USB devices are added or removed from system.  The invocation is done by the kernel hub workqueue \[hub_wq\], or else as part of root hub initialization (done by init, modprobe, kapmd, etc).  Its single command line parameter is the string "usb", and it passes these environment variables:


<table>
<tbody>
<tr>
<td>


ACTION

</td>
<td>


`add`, `remove`

</td>
</tr>
<tr>
<td>


PRODUCT

</td>
<td>


USB vendor, product, and version codes (hex)

</td>
</tr>
<tr>
<td>


TYPE

</td>
<td>


device class codes (decimal)

</td>
</tr>
<tr>
<td>


INTERFACE

</td>
<td>


interface 0 class codes (decimal)

</td>
</tr>
</tbody>
</table>

If "usbdevfs" is configured, DEVICE and DEVFS are also passed.  DEVICE is the pathname of the device, and is useful for devices with multiple and/or alternate interfaces that complicate driver selection.  By design, USB hotplugging is independent of `usbdevfs`:  you can do most essential parts of USB device setup without using that filesystem, and without running a user mode daemon to detect changes in system configuration.

Currently available policy agent implementations can load drivers for modules, and can invoke driver-specific setup scripts.  The newest ones leverage USB module-init-tools support.  Later agents might unload drivers.

<a id="rst-usb-modutils-support"></a>

## USB Modutils Support

Current versions of module-init-tools will create a `modules.usbmap` file which contains the entries from each driver's `MODULE_DEVICE_TABLE`.  Such files can be used by various user mode policy agents to make sure all the right driver modules get loaded, either at boot time or later.

See `linux/usb.h` for full information about such table entries; or look at existing drivers.  Each table entry describes one or more criteria to be used when matching a driver to a device or class of devices.  The specific criteria are identified by bits set in "match_flags", paired with field values.  You can construct the criteria directly, or with macros such as these, and use driver_info to store more information:



```text
USB_DEVICE (vendorId, productId)
    ... matching devices with specified vendor and product ids
USB_DEVICE_VER (vendorId, productId, lo, hi)
    ... like USB_DEVICE with lo <= productversion <= hi
USB_INTERFACE_INFO (class, subclass, protocol)
    ... matching specified interface class info
USB_DEVICE_INFO (class, subclass, protocol)
    ... matching specified device class info
```

A short example, for a driver that supports several specific USB devices and their quirks, might have a MODULE_DEVICE_TABLE like this:



```text
static const struct usb_device_id mydriver_id_table[] = {
    { USB_DEVICE (0x9999, 0xaaaa), driver_info: QUIRK_X },
    { USB_DEVICE (0xbbbb, 0x8888), driver_info: QUIRK_Y|QUIRK_Z },
    ...
    { } /* end with an all-zeroes entry */
};
MODULE_DEVICE_TABLE(usb, mydriver_id_table);
```

Most USB device drivers should pass these tables to the USB subsystem as well as to the module management subsystem.  Not all, though: some driver frameworks connect using interfaces layered over USB, and so they won't need such a struct usb_driver.

Drivers that connect directly to the USB subsystem should be declared something like this:



```text
static struct usb_driver mydriver = {
    .name           = "mydriver",
    .id_table       = mydriver_id_table,
    .probe          = my_probe,
    .disconnect     = my_disconnect,

    /*
    if using the usb chardev framework:
        .minor              = MY_USB_MINOR_START,
        .fops               = my_file_ops,
    if exposing any operations through usbdevfs:
        .ioctl              = my_ioctl,
    */
};
```

When the USB subsystem knows about a driver's device ID table, it's used when choosing drivers to probe().  The thread doing new device processing checks drivers' device ID entries from the `MODULE_DEVICE_TABLE` against interface and device descriptors for the device.  It will only call `probe()` if there is a match, and the third argument to `probe()` will be the entry that matched.

If you don't provide an `id_table` for your driver, then your driver may get probed for each new device; the third parameter to `probe()` will be `NULL`.

---

# USB device persistence during system suspend

_Peios Kernel / Hardware and drivers / Driver development / USB_

> According to the USB specification, when a USB bus is suspended the bus must continue to supply suspend current (around 1-5 mA). This is so that devices can maintain their internal state and hubs can detect connect-change events (devices…

<a id="rst-usb-device-persistence-during-system-suspend"></a>
<a id="rst-usb-persist"></a>

**Author:** Alan Stern &lt;[stern@rowland.harvard.edu](<mailto:stern@rowland.harvard.edu>)&gt;

**Date:** September 2, 2006 (Updated February 25, 2008)

<a id="rst-what-is-the-problem"></a>

## What is the problem?

According to the USB specification, when a USB bus is suspended the bus must continue to supply suspend current (around 1-5 mA).  This is so that devices can maintain their internal state and hubs can detect connect-change events (devices being plugged in or unplugged). The technical term is "power session".

If a USB device's power session is interrupted then the system is required to behave as though the device has been unplugged.  It's a conservative approach; in the absence of suspend current the computer has no way to know what has actually happened.  Perhaps the same device is still attached or perhaps it was removed and a different device plugged into the port.  The system must assume the worst.

By default, Linux behaves according to the spec.  If a USB host controller loses power during a system suspend, then when the system wakes up all the devices attached to that controller are treated as though they had disconnected.  This is always safe and it is the "officially correct" thing to do.

For many sorts of devices this behavior doesn't matter in the least. If the kernel wants to believe that your USB keyboard was unplugged while the system was asleep and a new keyboard was plugged in when the system woke up, who cares?  It'll still work the same when you type on it.

Unfortunately problems \_can\_ arise, particularly with mass-storage devices.  The effect is exactly the same as if the device really had been unplugged while the system was suspended.  If you had a mounted filesystem on the device, you're out of luck -- everything in that filesystem is now inaccessible.  This is especially annoying if your root filesystem was located on the device, since your system will instantly crash.

Loss of power isn't the only mechanism to worry about.  Anything that interrupts a power session will have the same effect.  For example, even though suspend current may have been maintained while the system was asleep, on many systems during the initial stages of wakeup the firmware (i.e., the BIOS) resets the motherboard's USB host controllers.  Result: all the power sessions are destroyed and again it's as though you had unplugged all the USB devices.  Yes, it's entirely the BIOS's fault, but that doesn't do \_you\_ any good unless you can convince the BIOS supplier to fix the problem (lots of luck\!).

On many systems the USB host controllers will get reset after a suspend-to-RAM.  On almost all systems, no suspend current is available during hibernation (also known as swsusp or suspend-to-disk). You can check the kernel log after resuming to see if either of these has happened; look for lines saying "root hub lost power or was reset".

In practice, people are forced to unmount any filesystems on a USB device before suspending.  If the root filesystem is on a USB device, the system can't be suspended at all.  (All right, it \_can\_ be suspended -- but it will crash as soon as it wakes up, which isn't much better.)

<a id="rst-what-is-the-solution"></a>

## What is the solution?

The kernel includes a feature called USB-persist.  It tries to work around these issues by allowing the core USB device data structures to persist across a power-session disruption.

It works like this.  If the kernel sees that a USB host controller is not in the expected state during resume (i.e., if the controller was reset or otherwise had lost power) then it applies a persistence check to each of the USB devices below that controller for which the "persist" attribute is set.  It doesn't try to resume the device; that can't work once the power session is gone.  Instead it issues a USB port reset and then re-enumerates the device.  (This is exactly the same thing that happens whenever a USB device is reset.)  If the re-enumeration shows that the device now attached to that port has the same descriptors as before, including the Vendor and Product IDs, then the kernel continues to use the same device structure.  In effect, the kernel treats the device as though it had merely been reset instead of unplugged.

The same thing happens if the host controller is in the expected state but a USB device was unplugged and then replugged, or if a USB device fails to carry out a normal resume.

If no device is now attached to the port, or if the descriptors are different from what the kernel remembers, then the treatment is what you would expect.  The kernel destroys the old device structure and behaves as though the old device had been unplugged and a new device plugged in.

The end result is that the USB device remains available and usable. Filesystem mounts and memory mappings are unaffected, and the world is now a good and happy place.

Note that the "USB-persist" feature will be applied only to those devices for which it is enabled.  You can enable the feature by doing (as root):



```text
echo 1 >/sys/bus/usb/devices/.../power/persist
```

where the "..." should be filled in the with the device's ID.  Disable the feature by writing 0 instead of 1.  For hubs the feature is automatically and permanently enabled and the power/persist file doesn't even exist, so you only have to worry about setting it for devices where it really matters.

<a id="rst-is-this-the-best-solution"></a>

## Is this the best solution?

Perhaps not.  Arguably, keeping track of mounted filesystems and memory mappings across device disconnects should be handled by a centralized Logical Volume Manager.  Such a solution would allow you to plug in a USB flash device, create a persistent volume associated with it, unplug the flash device, plug it back in later, and still have the same persistent volume associated with the device.  As such it would be more far-reaching than USB-persist.

On the other hand, writing a persistent volume manager would be a big job and using it would require significant input from the user.  This solution is much quicker and easier -- and it exists now, a giant point in its favor\!

Furthermore, the USB-persist feature applies to \_all\_ USB devices, not just mass-storage devices.  It might turn out to be equally useful for other device types, such as network interfaces.

<a id="rst-warning-usb-persist-can-be-dangerous"></a>

## WARNING: USB-persist can be dangerous\!\!

When recovering an interrupted power session the kernel does its best to make sure the USB device hasn't been changed; that is, the same device is still plugged into the port as before.  But the checks aren't guaranteed to be 100% accurate.

If you replace one USB device with another of the same type (same manufacturer, same IDs, and so on) there's an excellent chance the kernel won't detect the change.  The serial number string and other descriptors are compared with the kernel's stored values, but this might not help since manufacturers frequently omit serial numbers entirely in their devices.

Furthermore it's quite possible to leave a USB device exactly the same while changing its media.  If you replace the flash memory card in a USB card reader while the system is asleep, the kernel will have no way to know you did it.  The kernel will assume that nothing has happened and will continue to use the partition tables, inodes, and memory mappings for the old card.

If the kernel gets fooled in this way, it's almost certain to cause data corruption and to crash your system.  You'll have no one to blame but yourself.

For those devices with avoid_reset_quirk attribute being set, persist maybe fail because they may morph after reset.

YOU HAVE BEEN WARNED\!  USE AT YOUR OWN RISK\!

That having been said, most of the time there shouldn't be any trouble at all.  The USB-persist feature can be extremely useful.  Make the most of it.

---

# Power Management for USB

_Peios Kernel / Hardware and drivers / Driver development / USB_

> Power Management (PM) is the practice of saving energy by suspending parts of a computer system when they aren't being used. While a component is suspended it is in a nonfunctional low-power state; it might even be turned off completely. A…

<a id="rst-power-management-for-usb"></a>
<a id="rst-usb-power-management"></a>

**Author:** Alan Stern &lt;[stern@rowland.harvard.edu](<mailto:stern@rowland.harvard.edu>)&gt;

**Date:** Last-updated: February 2014

<!-- Contents:
---------
* What is Power Management?
* What is Remote Wakeup?
* When is a USB device idle?
* Forms of dynamic PM
* The user interface for dynamic PM
* Changing the default idle-delay time
* Warnings
* The driver interface for Power Management
* The driver interface for autosuspend and autoresume
* Other parts of the driver interface
* Mutual exclusion
* Interaction between dynamic PM and system PM
* xHCI hardware link PM
* USB Port Power Control
* User Interface for Port Power Control
* Suggested Userspace Port Power Policy -->

<a id="rst-what-is-power-management"></a>

## What is Power Management?

Power Management (PM) is the practice of saving energy by suspending parts of a computer system when they aren't being used.  While a component is `suspended` it is in a nonfunctional low-power state; it might even be turned off completely.  A suspended component can be `resumed` (returned to a functional full-power state) when the kernel needs to use it.  (There also are forms of PM in which components are placed in a less functional but still usable state instead of being suspended; an example would be reducing the CPU's clock rate.  This document will not discuss those other forms.)

When the parts being suspended include the CPU and most of the rest of the system, we speak of it as a "system suspend".  When a particular device is turned off while the system as a whole remains running, we call it a "dynamic suspend" (also known as a "runtime suspend" or "selective suspend").  This document concentrates mostly on how dynamic PM is implemented in the USB subsystem, although system PM is covered to some extent (see `Documentation/power/*.rst` for more information about system PM).

System PM support is present only if the kernel was built with `CONFIG_SUSPEND` or `CONFIG_HIBERNATION` enabled.  Dynamic PM support

for USB is present whenever the kernel was built with `CONFIG_PM` enabled.

\[Historically, dynamic PM support for USB was present only if the kernel had been built with `CONFIG_USB_SUSPEND` enabled (which depended on `CONFIG_PM_RUNTIME`).  Starting with the 3.10 kernel release, dynamic PM support for USB was present whenever the kernel was built with `CONFIG_PM_RUNTIME` enabled.  The `CONFIG_USB_SUSPEND` option had been eliminated.\]

<a id="rst-what-is-remote-wakeup"></a>

## What is Remote Wakeup?

When a device has been suspended, it generally doesn't resume until the computer tells it to.  Likewise, if the entire computer has been suspended, it generally doesn't resume until the user tells it to, say by pressing a power button or opening the cover.

However some devices have the capability of resuming by themselves, or asking the kernel to resume them, or even telling the entire computer to resume.  This capability goes by several names such as "Wake On LAN"; we will refer to it generically as "remote wakeup".  When a device is enabled for remote wakeup and it is suspended, it may resume itself (or send a request to be resumed) in response to some external event.  Examples include a suspended keyboard resuming when a key is pressed, or a suspended USB hub resuming when a device is plugged in.

<a id="rst-when-is-a-usb-device-idle"></a>

## When is a USB device idle?

A device is idle whenever the kernel thinks it's not busy doing anything important and thus is a candidate for being suspended.  The exact definition depends on the device's driver; drivers are allowed to declare that a device isn't idle even when there's no actual communication taking place.  (For example, a hub isn't considered idle unless all the devices plugged into that hub are already suspended.) In addition, a device isn't considered idle so long as a program keeps its usbfs file open, whether or not any I/O is going on.

If a USB device has no driver, its usbfs file isn't open, and it isn't being accessed through sysfs, then it definitely is idle.

<a id="rst-forms-of-dynamic-pm"></a>

## Forms of dynamic PM

Dynamic suspends occur when the kernel decides to suspend an idle device.  This is called `autosuspend` for short.  In general, a device won't be autosuspended unless it has been idle for some minimum period of time, the so-called idle-delay time.

Of course, nothing the kernel does on its own initiative should prevent the computer or its devices from working properly.  If a device has been autosuspended and a program tries to use it, the kernel will automatically resume the device (autoresume).  For the same reason, an autosuspended device will usually have remote wakeup enabled, if the device supports remote wakeup.

It is worth mentioning that many USB drivers don't support autosuspend.  In fact, at the time of this writing (Linux 2.6.23) the only drivers which do support it are the hub driver, kaweth, asix, usblp, usblcd, and usb-skeleton (which doesn't count).  If a non-supporting driver is bound to a device, the device won't be autosuspended.  In effect, the kernel pretends the device is never idle.

We can categorize power management events in two broad classes: external and internal.  External events are those triggered by some agent outside the USB stack: system suspend/resume (triggered by userspace), manual dynamic resume (also triggered by userspace), and remote wakeup (triggered by the device).  Internal events are those triggered within the USB stack: autosuspend and autoresume.  Note that all dynamic suspend events are internal; external agents are not allowed to issue dynamic suspends.

<a id="rst-the-user-interface-for-dynamic-pm"></a>

## The user interface for dynamic PM

The user interface for controlling dynamic PM is located in the `power/` subdirectory of each USB device's sysfs directory, that is, in `/sys/bus/usb/devices/.../power/` where "..." is the device's ID.  The relevant attribute files are: wakeup, control, and `autosuspend_delay_ms`.  (There may also be a file named `level`; this file was deprecated as of the 2.6.35 kernel and replaced by the `control` file.  In 2.6.38 the `autosuspend` file will be deprecated and replaced by the `autosuspend_delay_ms` file.  The only difference is that the newer file expresses the delay in milliseconds whereas the older file uses seconds.  Confusingly, both files are present in 2.6.37 but only `autosuspend` works.)

> `power/wakeup`
>
> > This file is empty if the device does not support remote wakeup.  Otherwise the file contains either the word `enabled` or the word `disabled`, and you can write those words to the file.  The setting determines whether or not remote wakeup will be enabled when the device is next suspended.  (If the setting is changed while the device is suspended, the change won't take effect until the following suspend.)
>
> `power/control`
>
> > This file contains one of two words: `on` or `auto`. You can write those words to the file to change the device's setting.
> >
> > - `on` means that the device should be resumed and autosuspend is not allowed.  (Of course, system suspends are still allowed.)
> >
> > - `auto` is the normal state in which the kernel is allowed to autosuspend and autoresume the device.
> >
> > (In kernels up to 2.6.32, you could also specify `suspend`, meaning that the device should remain suspended and autoresume was not allowed.  This setting is no longer supported.)
>
> `power/autosuspend_delay_ms`
>
> > This file contains an integer value, which is the number of milliseconds the device should remain idle before the kernel will autosuspend it (the idle-delay time).  The default is 2000.  0 means to autosuspend as soon as the device becomes idle, and negative values mean never to autosuspend.  You can write a number to the file to change the autosuspend idle-delay time.

Writing `-1` to `power/autosuspend_delay_ms` and writing `on` to `power/control` do essentially the same thing -- they both prevent the device from being autosuspended.  Yes, this is a redundancy in the API.

(In 2.6.21 writing `0` to `power/autosuspend` would prevent the device from being autosuspended; the behavior was changed in 2.6.22.  The `power/autosuspend` attribute did not exist prior to 2.6.21, and the `power/level` attribute did not exist prior to 2.6.22.  `power/control` was added in 2.6.34, and `power/autosuspend_delay_ms` was added in 2.6.37 but did not become functional until 2.6.38.)

<a id="rst-changing-the-default-idle-delay-time"></a>

## Changing the default idle-delay time

The default autosuspend idle-delay time (in seconds) is controlled by a module parameter in usbcore.  You can specify the value when usbcore is loaded.  For example, to set it to 5 seconds instead of 2 you would do:



```text
modprobe usbcore autosuspend=5
```

Equivalently, you could add to a configuration file in /etc/modprobe.d a line saying:



```text
options usbcore autosuspend=5
```

Some distributions load the usbcore module very early during the boot process, by means of a program or script running from an initramfs image.  To alter the parameter value you would have to rebuild that image.

If usbcore is compiled into the kernel rather than built as a loadable module, you can add:



```text
usbcore.autosuspend=5
```

to the kernel's boot command line.

Finally, the parameter value can be changed while the system is running.  If you do:



```text
echo 5 >/sys/module/usbcore/parameters/autosuspend
```

then each new USB device will have its autosuspend idle-delay initialized to 5.  (The idle-delay values for already existing devices will not be affected.)

Setting the initial default idle-delay to -1 will prevent any autosuspend of any USB device.  This has the benefit of allowing you then to enable autosuspend for selected devices.

<a id="rst-warnings"></a>

## Warnings

The USB specification states that all USB devices must support power management.  Nevertheless, the sad fact is that many devices do not support it very well.  You can suspend them all right, but when you try to resume them they disconnect themselves from the USB bus or they stop working entirely.  This seems to be especially prevalent among printers and scanners, but plenty of other types of device have the same deficiency.

For this reason, by default the kernel disables autosuspend (the `power/control` attribute is initialized to `on`) for all devices other than hubs.  Hubs, at least, appear to be reasonably well-behaved in this regard.

(In 2.6.21 and 2.6.22 this wasn't the case.  Autosuspend was enabled by default for almost all USB devices.  A number of people experienced problems as a result.)

This means that non-hub devices won't be autosuspended unless the user or a program explicitly enables it.  As of this writing there aren't any widespread programs which will do this; we hope that in the near future device managers such as HAL will take on this added responsibility.  In the meantime you can always carry out the necessary operations by hand or add them to a udev script.  You can also change the idle-delay time; 2 seconds is not the best choice for every device.

If a driver knows that its device has proper suspend/resume support, it can enable autosuspend all by itself.  For example, the video driver for a laptop's webcam might do this (in recent kernels they do), since these devices are rarely used and so should normally be autosuspended.

Sometimes it turns out that even when a device does work okay with autosuspend there are still problems.  For example, the usbhid driver, which manages keyboards and mice, has autosuspend support.  Tests with a number of keyboards show that typing on a suspended keyboard, while causing the keyboard to do a remote wakeup all right, will nonetheless frequently result in lost keystrokes.  Tests with mice show that some of them will issue a remote-wakeup request in response to button presses but not to motion, and some in response to neither.

The kernel will not prevent you from enabling autosuspend on devices that can't handle it.  It is even possible in theory to damage a device by suspending it at the wrong time.  (Highly unlikely, but possible.)  Take care.

<a id="rst-the-driver-interface-for-power-management"></a>

## The driver interface for Power Management

The requirements for a USB driver to support external power management are pretty modest; the driver need only define:



```text
.suspend
.resume
.reset_resume
```

methods in its `usb_driver` structure, and the `reset_resume` method is optional.  The methods' jobs are quite simple:

> - The `suspend` method is called to warn the driver that the device is going to be suspended.  If the driver returns a negative error code, the suspend will be aborted.  Normally the driver will return 0, in which case it must cancel all outstanding URBs (`usb_kill_urb()`) and not submit any more.
>
> - The `resume` method is called to tell the driver that the device has been resumed and the driver can return to normal operation.  URBs may once more be submitted.
>
> - The `reset_resume` method is called to tell the driver that the device has been resumed and it also has been reset. The driver should redo any necessary device initialization, since the device has probably lost most or all of its state (although the interfaces will be in the same altsettings as before the suspend).

If the device is disconnected or powered down while it is suspended, the `disconnect` method will be called instead of the `resume` or `reset_resume` method.  This is also quite likely to happen when waking up from hibernation, as many systems do not maintain suspend current to the USB host controllers during hibernation.  (It's possible to work around the hibernation-forces-disconnect problem by using the USB Persist facility.)

The `reset_resume` method is used by the USB Persist facility (see [USB device persistence during system suspend](</kernel/hardware/driver-api/usb/persist.md#rst-usb-persist>)) and it can also be used under certain circumstances when `CONFIG_USB_PERSIST` is not enabled.  Currently, if a device is reset during a resume and the driver does not have a `reset_resume` method, the driver won't receive any notification about the resume.  Later kernels will call the driver's `disconnect` method; 2.6.23 doesn't do this.

USB drivers are bound to interfaces, so their `suspend` and `resume` methods get called when the interfaces are suspended or resumed.  In principle one might want to suspend some interfaces on a device (i.e., force the drivers for those interface to stop all activity) without suspending the other interfaces.  The USB core doesn't allow this; all interfaces are suspended when the device itself is suspended and all interfaces are resumed when the device is resumed.  It isn't possible to suspend or resume some but not all of a device's interfaces.  The closest you can come is to unbind the interfaces' drivers.

<a id="rst-the-driver-interface-for-autosuspend-and-autoresume"></a>

## The driver interface for autosuspend and autoresume

To support autosuspend and autoresume, a driver should implement all three of the methods listed above.  In addition, a driver indicates that it supports autosuspend by setting the `.supports_autosuspend` flag in its usb_driver structure.  It is then responsible for informing the USB core whenever one of its interfaces becomes busy or idle.  The driver does so by calling these six functions:



```text
int  usb_autopm_get_interface(struct usb_interface *intf);
void usb_autopm_put_interface(struct usb_interface *intf);
int  usb_autopm_get_interface_async(struct usb_interface *intf);
void usb_autopm_put_interface_async(struct usb_interface *intf);
void usb_autopm_get_interface_no_resume(struct usb_interface *intf);
void usb_autopm_put_interface_no_suspend(struct usb_interface *intf);
```

The functions work by maintaining a usage counter in the usb_interface's embedded device structure.  When the counter is &gt; 0 then the interface is deemed to be busy, and the kernel will not autosuspend the interface's device.  When the usage counter is = 0 then the interface is considered to be idle, and the kernel may autosuspend the device.

Drivers must be careful to balance their overall changes to the usage counter.  Unbalanced "get"s will remain in effect when a driver is unbound from its interface, preventing the device from going into runtime suspend should the interface be bound to a driver again.  On the other hand, drivers are allowed to achieve this balance by calling the `usb_autopm_*` functions even after their `disconnect` routine has returned -- say from within a work-queue routine -- provided they retain an active reference to the interface (via `usb_get_intf` and `usb_put_intf`).

Drivers using the async routines are responsible for their own synchronization and mutual exclusion.

> `usb_autopm_get_interface()` increments the usage counter and does an autoresume if the device is suspended.  If the autoresume fails, the counter is decremented back.
>
> `usb_autopm_put_interface()` decrements the usage counter and attempts an autosuspend if the new value is = 0.
>
> `usb_autopm_get_interface_async()` and `usb_autopm_put_interface_async()` do almost the same things as their non-async counterparts.  The big difference is that they use a workqueue to do the resume or suspend part of their jobs.  As a result they can be called in an atomic context, such as an URB's completion handler, but when they return the device will generally not yet be in the desired state.
>
> `usb_autopm_get_interface_no_resume()` and `usb_autopm_put_interface_no_suspend()` merely increment or decrement the usage counter; they do not attempt to carry out an autoresume or an autosuspend.  Hence they can be called in an atomic context.

The simplest usage pattern is that a driver calls `usb_autopm_get_interface()` in its open routine and `usb_autopm_put_interface()` in its close or release routine.  But other patterns are possible.

The autosuspend attempts mentioned above will often fail for one reason or another.  For example, the `power/control` attribute might be set to `on`, or another interface in the same device might not be idle.  This is perfectly normal.  If the reason for failure was that the device hasn't been idle for long enough, a timer is scheduled to carry out the operation automatically when the autosuspend idle-delay has expired.

Autoresume attempts also can fail, although failure would mean that the device is no longer present or operating properly.  Unlike autosuspend, there's no idle-delay for an autoresume.

<a id="rst-other-parts-of-the-driver-interface"></a>

## Other parts of the driver interface

Drivers can enable autosuspend for their devices by calling:



```text
usb_enable_autosuspend(struct usb_device *udev);
```

in their `probe()` routine, if they know that the device is capable of suspending and resuming correctly.  This is exactly equivalent to writing `auto` to the device's `power/control` attribute.  Likewise, drivers can disable autosuspend by calling:



```text
usb_disable_autosuspend(struct usb_device *udev);
```

This is exactly the same as writing `on` to the `power/control` attribute.

Sometimes a driver needs to make sure that remote wakeup is enabled during autosuspend.  For example, there's not much point autosuspending a keyboard if the user can't cause the keyboard to do a remote wakeup by typing on it.  If the driver sets `intf->needs_remote_wakeup` to 1, the kernel won't autosuspend the device if remote wakeup isn't available.  (If the device is already autosuspended, though, setting this flag won't cause the kernel to autoresume it.  Normally a driver would set this flag in its `probe` method, at which time the device is guaranteed not to be autosuspended.)

If a driver does its I/O asynchronously in interrupt context, it should call `usb_autopm_get_interface_async()` before starting output and `usb_autopm_put_interface_async()` when the output queue drains.  When it receives an input event, it should call:



```text
usb_mark_last_busy(struct usb_device *udev);
```

in the event handler.  This tells the PM core that the device was just busy and therefore the next autosuspend idle-delay expiration should be pushed back.  Many of the usb_autopm\_\* routines also make this call, so drivers need to worry only when interrupt-driven input arrives.

Asynchronous operation is always subject to races.  For example, a driver may call the `usb_autopm_get_interface_async()` routine at a time when the core has just finished deciding the device has been idle for long enough but not yet gotten around to calling the driver's `suspend` method.  The `suspend` method must be responsible for synchronizing with the I/O request routine and the URB completion handler; it should cause autosuspends to fail with -EBUSY if the driver needs to use the device.

External suspend calls should never be allowed to fail in this way, only autosuspend calls.  The driver can tell them apart by applying the `PMSG_IS_AUTO()` macro to the message argument to the `suspend` method; it will return True for internal PM events (autosuspend) and False for external PM events.

<a id="rst-mutual-exclusion"></a>

## Mutual exclusion

For external events -- but not necessarily for autosuspend or autoresume -- the device semaphore (udev-&gt;dev.sem) will be held when a `suspend` or `resume` method is called.  This implies that external suspend/resume events are mutually exclusive with calls to `probe`, `disconnect`, `pre_reset`, and `post_reset`; the USB core guarantees that this is true of autosuspend/autoresume events as well.

If a driver wants to block all suspend/resume calls during some critical section, the best way is to lock the device and call `usb_autopm_get_interface()` (and do the reverse at the end of the critical section).  Holding the device semaphore will block all external PM calls, and the `usb_autopm_get_interface()` will prevent any internal PM calls, even if it fails.  (Exercise: Why?)

<a id="rst-interaction-between-dynamic-pm-and-system-pm"></a>

## Interaction between dynamic PM and system PM

Dynamic power management and system power management can interact in a couple of ways.

Firstly, a device may already be autosuspended when a system suspend occurs.  Since system suspends are supposed to be as transparent as possible, the device should remain suspended following the system resume.  But this theory may not work out well in practice; over time the kernel's behavior in this regard has changed.  As of 2.6.37 the policy is to resume all devices during a system resume and let them handle their own runtime suspends afterward.

Secondly, a dynamic power-management event may occur as a system suspend is underway.  The window for this is short, since system suspends don't take long (a few seconds usually), but it can happen. For example, a suspended device may send a remote-wakeup signal while the system is suspending.  The remote wakeup may succeed, which would cause the system suspend to abort.  If the remote wakeup doesn't succeed, it may still remain active and thus cause the system to resume as soon as the system suspend is complete.  Or the remote wakeup may fail and get lost.  Which outcome occurs depends on timing and on the hardware and firmware design.

<a id="rst-xhci-hardware-link-pm"></a>

## xHCI hardware link PM

xHCI host controller provides hardware link power management to usb2.0 (xHCI 1.0 feature) and usb3.0 devices which support link PM. By enabling hardware LPM, the host can automatically put the device into lower power state(L1 for usb2.0 devices, or U1/U2 for usb3.0 devices), which state device can enter and resume very quickly.

The user interface for controlling hardware LPM is located in the `power/` subdirectory of each USB device's sysfs directory, that is, in `/sys/bus/usb/devices/.../power/` where "..." is the device's ID. The relevant attribute files are `usb2_hardware_lpm` and `usb3_hardware_lpm`.

> `power/usb2_hardware_lpm`
>
> > When a USB2 device which support LPM is plugged to a xHCI host root hub which support software LPM, the host will run a software LPM test for it; if the device enters L1 state and resume successfully and the host supports USB2 hardware LPM, this file will show up and driver will enable hardware LPM for the device. You can write y/Y/1 or n/N/0 to the file to enable/disable USB2 hardware LPM manually. This is for test purpose mainly.
>
> `power/usb3_hardware_lpm_u1` `power/usb3_hardware_lpm_u2`
>
> > When a USB 3.0 lpm-capable device is plugged in to a xHCI host which supports link PM, it will check if U1 and U2 exit latencies have been set in the BOS descriptor; if the check is passed and the host supports USB3 hardware LPM, USB3 hardware LPM will be enabled for the device and these files will be created. The files hold a string value (enable or disable) indicating whether or not USB3 hardware LPM U1 or U2 is enabled for the device.

<a id="rst-usb-port-power-control"></a>

## USB Port Power Control

In addition to suspending endpoint devices and enabling hardware controlled link power management, the USB subsystem also has the capability to disable power to ports under some conditions.  Power is controlled through `Set/ClearPortFeature(PORT_POWER)` requests to a hub. In the case of a root or platform-internal hub the host controller driver translates `PORT_POWER` requests into platform firmware (ACPI) method calls to set the port power state. For more background see the Linux Plumbers Conference 2012 slides <a id="rst-footnote-reference-1"></a>[1](#rst-f1) and video <a id="rst-footnote-reference-2"></a>[2](#rst-f2):

Upon receiving a `ClearPortFeature(PORT_POWER)` request a USB port is logically off, and may trigger the actual loss of VBUS to the port <a id="rst-footnote-reference-3"></a>[3](#rst-f3). VBUS may be maintained in the case where a hub gangs multiple ports into a shared power well causing power to remain until all ports in the gang are turned off.  VBUS may also be maintained by hub ports configured for a charging application.  In any event a logically off port will lose connection with its device, not respond to hotplug events, and not respond to remote wakeup events.

> [!WARNING]
>
> turning off a port may result in the inability to hot add a device. Please see "User Interface for Port Power Control" for details.

As far as the effect on the device itself it is similar to what a device goes through during system suspend, i.e. the power session is lost.  Any USB device or driver that misbehaves with system suspend will be similarly affected by a port power cycle event.  For this reason the implementation shares the same device recovery path (and honors the same quirks) as the system resume path for the hub.

<a id="rst-f1"></a>



**[1]** [http://dl.dropbox.com/u/96820575/sarah-sharp-lpt-port-power-off2-mini.pdf](<http://dl.dropbox.com/u/96820575/sarah-sharp-lpt-port-power-off2-mini.pdf>)

<a id="rst-f2"></a>



**[2]** [http://linuxplumbers.ubicast.tv/videos/usb-port-power-off-kerneluserspace-api/](<http://linuxplumbers.ubicast.tv/videos/usb-port-power-off-kerneluserspace-api/>)

<a id="rst-f3"></a>



**[3]** USB 3.1 Section 10.12

wakeup note: if a device is configured to send wakeup events the port power control implementation will block poweroff attempts on that port.

<a id="rst-user-interface-for-port-power-control"></a>

## User Interface for Port Power Control

The port power control mechanism uses the PM runtime system.  Poweroff is requested by clearing the `power/pm_qos_no_power_off` flag of the port device (defaults to 1).  If the port is disconnected it will immediately receive a `ClearPortFeature(PORT_POWER)` request.  Otherwise, it will honor the pm runtime rules and require the attached child device and all descendants to be suspended. This mechanism is dependent on the hub advertising port power switching in its hub descriptor (wHubCharacteristics logical power switching mode field).

Note, some interface devices/drivers do not support autosuspend.  Userspace may need to unbind the interface drivers before the `usb_device` will suspend.  An unbound interface device is suspended by default.  When unbinding, be careful to unbind interface drivers, not the driver of the parent usb device.  Also, leave hub interface drivers bound.  If the driver for the usb device (not interface) is unbound the kernel is no longer able to resume the device.  If a hub interface driver is unbound, control of its child ports is lost and all attached child-devices will disconnect.  A good rule of thumb is that if the 'driver/module' link for a device points to `/sys/module/usbcore` then unbinding it will interfere with port power control.

Example of the relevant files for port power control.  Note, in this example these files are relative to a usb hub device (prefix):



```text
prefix=/sys/devices/pci0000:00/0000:00:14.0/usb3/3-1

                 attached child device +
             hub port device +         |
hub interface device +       |         |
                     v       v         v
             $prefix/3-1:1.0/3-1-port1/device

$prefix/3-1:1.0/3-1-port1/power/pm_qos_no_power_off
$prefix/3-1:1.0/3-1-port1/device/power/control
$prefix/3-1:1.0/3-1-port1/device/3-1.1:<intf0>/driver/unbind
$prefix/3-1:1.0/3-1-port1/device/3-1.1:<intf1>/driver/unbind
...
$prefix/3-1:1.0/3-1-port1/device/3-1.1:<intfN>/driver/unbind
```

In addition to these files some ports may have a 'peer' link to a port on another hub.  The expectation is that all superspeed ports have a hi-speed peer:



```text
$prefix/3-1:1.0/3-1-port1/peer -> ../../../../usb2/2-1/2-1:1.0/2-1-port1
../../../../usb2/2-1/2-1:1.0/2-1-port1/peer -> ../../../../usb3/3-1/3-1:1.0/3-1-port1
```

Distinct from 'companion ports', or 'ehci/xhci shared switchover ports' peer ports are simply the hi-speed and superspeed interface pins that are combined into a single usb3 connector.  Peer ports share the same ancestor XHCI device.

While a superspeed port is powered off a device may downgrade its connection and attempt to connect to the hi-speed pins.  The implementation takes steps to prevent this:

1. Port suspend is sequenced to guarantee that hi-speed ports are powered-off before their superspeed peer is permitted to power-off.  The implication is that the setting `pm_qos_no_power_off` to zero on a superspeed port may not cause the port to power-off until its highspeed peer has gone to its runtime suspend state.  Userspace must take care to order the suspensions if it wants to guarantee that a superspeed port will power-off.

2. Port resume is sequenced to force a superspeed port to power-on prior to its highspeed peer.

3. Port resume always triggers an attached child device to resume.  After a power session is lost the device may have been removed, or need reset. Resuming the child device when the parent port regains power resolves those states and clamps the maximum port power cycle frequency at the rate the child device can suspend (autosuspend-delay) and resume (reset-resume latency).

Sysfs files relevant for port power control:

> - **`<hubdev-portX>/power/pm_qos_no_power_off`:**
>
>   This writable flag controls the state of an idle port. Once all children and descendants have suspended the port may suspend/poweroff provided that pm_qos_no_power_off is '0'.  If pm_qos_no_power_off is '1' the port will remain active/powered regardless of the stats of descendants.  Defaults to 1.
>
> - **`<hubdev-portX>/power/runtime_status`:**
>
>   This file reflects whether the port is 'active' (power is on) or 'suspended' (logically off).  There is no indication to userspace whether VBUS is still supplied.
>
> - **`<hubdev-portX>/connect_type`:**
>
>   An advisory read-only flag to userspace indicating the location and connection type of the port.  It returns one of four values 'hotplug', 'hardwired', 'not used', and 'unknown'.  All values, besides unknown, are set by platform firmware.
>
>   `hotplug` indicates an externally connectable/visible port on the platform.  Typically userspace would choose to keep such a port powered to handle new device connection events.
>
>   `hardwired` refers to a port that is not visible but connectable. Examples are internal ports for USB bluetooth that can be disconnected via an external switch or a port with a hardwired USB camera.  It is expected to be safe to allow these ports to suspend provided pm_qos_no_power_off is coordinated with any switch that gates connections.  Userspace must arrange for the device to be connected prior to the port powering off, or to activate the port prior to enabling connection via a switch.
>
>   `not used` refers to an internal port that is expected to never have a device connected to it.  These may be empty internal ports, or ports that are not physically exposed on a platform.  Considered safe to be powered-off at all times.
>
>   `unknown` means platform firmware does not provide information for this port.  Most commonly refers to external hub ports which should be considered 'hotplug' for policy decisions.
>
>   > [!NOTE]
>   >
>   > - since we are relying on the BIOS to get this ACPI information correct, the USB port descriptions may be missing or wrong.
>   >
>   > - Take care in clearing `pm_qos_no_power_off`. Once power is off this port will not respond to new connect events.
>
> Once a child device is attached additional constraints are applied before the port is allowed to poweroff.
>
> - **`<child>/power/control`:**
>
>   Must be `auto`, and the port will not power down until `<child>/power/runtime_status` reflects the 'suspended' state.  Default value is controlled by child device driver.
>
> - **`<child>/power/persist`:**
>
>   This defaults to `1` for most devices and indicates if kernel can persist the device's configuration across a power session loss (suspend / port-power event).  When this value is `0` (quirky devices), port poweroff is disabled.
>
> - **`<child>/driver/unbind`:**
>
>   Wakeup capable devices will block port poweroff.  At this time the only mechanism to clear the usb-internal wakeup-capability for an interface device is to unbind its driver.

Summary of poweroff pre-requisite settings relative to a port device:



```text
echo 0 > power/pm_qos_no_power_off
echo 0 > peer/power/pm_qos_no_power_off # if it exists
echo auto > power/control # this is the default value
echo auto > <child>/power/control
echo 1 > <child>/power/persist # this is the default value
```

<a id="rst-suggested-userspace-port-power-policy"></a>

## Suggested Userspace Port Power Policy

As noted above userspace needs to be careful and deliberate about what ports are enabled for poweroff.

The default configuration is that all ports start with `power/pm_qos_no_power_off` set to `1` causing ports to always remain active.

Given confidence in the platform firmware's description of the ports (ACPI \_PLD record for a port populates 'connect_type') userspace can clear pm_qos_no_power_off for all 'not used' ports.  The same can be done for 'hardwired' ports provided poweroff is coordinated with any connection switch for the port.

A more aggressive userspace policy is to enable USB port power off for all ports (set `<hubdev-portX>/power/pm_qos_no_power_off` to `0`) when some external factor indicates the user has stopped interacting with the system.  For example, a distro may want to enable power off all USB ports when the screen blanks, and re-power them when the screen becomes active.  Smart phones and tablets may want to power off USB ports when the user pushes the power button.

---

# USB Type-C connector class

_Peios Kernel / Hardware and drivers / Driver development / USB_

> The typec class is meant for describing the USB Type-C ports in a system to the user space in unified fashion. The class is designed to provide nothing else except the user space interface implementation in hope that it can be utilized on…

<a id="rst-usb-type-c-connector-class"></a>
<a id="rst-typec"></a>

<a id="rst-introduction"></a>

## Introduction

The typec class is meant for describing the USB Type-C ports in a system to the user space in unified fashion. The class is designed to provide nothing else except the user space interface implementation in hope that it can be utilized on as many platforms as possible.

The platforms are expected to register every USB Type-C port they have with the class. In a normal case the registration will be done by a USB Type-C or PD PHY driver, but it may be a driver for firmware interface such as UCSI, driver for USB PD controller or even driver for Thunderbolt3 controller. This document considers the component registering the USB Type-C ports with the class as "port driver".

On top of showing the capabilities, the class also offer user space control over the roles and alternate modes of ports, partners and cable plugs when the port driver is capable of supporting those features.

The class provides an API for the port drivers described in this document. The attributes are described in Documentation/ABI/testing/sysfs-class-typec.

<a id="rst-user-space-interface"></a>

## User space interface

Every port will be presented as its own device under /sys/class/typec/. The first port will be named "port0", the second "port1" and so on.

When connected, the partner will be presented also as its own device under /sys/class/typec/. The parent of the partner device will always be the port it is attached to. The partner attached to port "port0" will be named "port0-partner". Full path to the device would be /sys/class/typec/port0/port0-partner/.

The cable and the two plugs on it may also be optionally presented as their own devices under /sys/class/typec/. The cable attached to the port "port0" port will be named port0-cable and the plug on the SOP Prime end (see USB Power Delivery Specification ch. 2.4) will be named "port0-plug0" and on the SOP Double Prime end "port0-plug1". The parent of a cable will always be the port, and the parent of the cable plugs will always be the cable.

If the port, partner or cable plug supports Alternate Modes, every supported Alternate Mode SVID will have their own device describing them. Note that the Alternate Mode devices will not be attached to the typec class. The parent of an alternate mode will be the device that supports it, so for example an alternate mode of port0-partner will be presented under /sys/class/typec/port0-partner/. Every mode that is supported will have its own group under the Alternate Mode device named "mode&lt;index&gt;", for example /sys/class/typec/port0/&lt;alternate mode&gt;/mode1/. The requests for entering/exiting a mode can be done with "active" attribute file in that group.

<a id="rst-driver-api"></a>

## Driver API

<a id="rst-registering-the-ports"></a>

### Registering the ports

The port drivers will describe every Type-C port they control with struct typec_capability data structure, and register them with the following API:


#### <a id="c-typec_register_port"></a>`typec_register_port()`

```c
struct typec_port * typec_register_port(struct device *parent, const struct typec_capability *cap)
```

Register a USB Type-C Port

**Parameters**

- `struct device *parent`: Parent device
- `const struct typec_capability *cap`: Description of the port

**Description**

Registers a device for USB Type-C Port described in **cap**.

Returns handle to the port on success or ERR_PTR on failure.

#### <a id="c-typec_unregister_port"></a>`typec_unregister_port()`

```c
void typec_unregister_port(struct typec_port *port)
```

Unregister a USB Type-C Port

**Parameters**

- `struct typec_port *port`: The port to be unregistered

**Description**

Unregister device created with [`typec_register_port()`](#c-typec_register_port).


When registering the ports, the prefer_role member in struct typec_capability deserves special notice. If the port that is being registered does not have initial role preference, which means the port does not execute Try.SNK or Try.SRC by default, the member must have value TYPEC_NO_PREFERRED_ROLE. Otherwise if the port executes Try.SNK by default, the member must have value TYPEC_DEVICE, and with Try.SRC the value must be TYPEC_HOST.

<a id="rst-registering-partners"></a>

### Registering Partners

After successful connection of a partner, the port driver needs to register the partner with the class. Details about the partner need to be described in struct typec_partner_desc. The class copies the details of the partner during registration. The class offers the following API for registering/unregistering partners.


#### <a id="c-typec_register_partner"></a>`typec_register_partner()`

```c
struct typec_partner * typec_register_partner(struct typec_port *port, struct typec_partner_desc *desc)
```

Register a USB Type-C Partner

**Parameters**

- `struct typec_port *port`: The USB Type-C Port the partner is connected to
- `struct typec_partner_desc *desc`: Description of the partner

**Description**

Registers a device for USB Type-C Partner described in **desc**.

Returns handle to the partner on success or ERR_PTR on failure.

#### <a id="c-typec_unregister_partner"></a>`typec_unregister_partner()`

```c
void typec_unregister_partner(struct typec_partner *partner)
```

Unregister a USB Type-C Partner

**Parameters**

- `struct typec_partner *partner`: The partner to be unregistered

**Description**

Unregister device created with [`typec_register_partner()`](#c-typec_register_partner).


The class will provide a handle to struct typec_partner if the registration was successful, or NULL.

If the partner is USB Power Delivery capable, and the port driver is able to show the result of Discover Identity command, the partner descriptor structure should include handle to struct usb_pd_identity instance. The class will then create a sysfs directory for the identity under the partner device. The result of Discover Identity command can then be reported with the following API:


#### <a id="c-typec_partner_set_identity"></a>`typec_partner_set_identity()`

```c
int typec_partner_set_identity(struct typec_partner *partner)
```

Report result from Discover Identity command

**Parameters**

- `struct typec_partner *partner`: The partner updated identity values

**Description**

This routine is used to report that the result of Discover Identity USB power
delivery command has become available.


<a id="rst-registering-cables"></a>

### Registering Cables

After successful connection of a cable that supports USB Power Delivery Structured VDM "Discover Identity", the port driver needs to register the cable and one or two plugs, depending if there is CC Double Prime controller present in the cable or not. So a cable capable of SOP Prime communication, but not SOP Double Prime communication, should only have one plug registered. For more information about SOP communication, please read chapter about it from the latest USB Power Delivery specification.

The plugs are represented as their own devices. The cable is registered first, followed by registration of the cable plugs. The cable will be the parent device for the plugs. Details about the cable need to be described in struct typec_cable_desc and about a plug in struct typec_plug_desc. The class copies the details during registration. The class offers the following API for registering/unregistering cables and their plugs:


#### <a id="c-typec_register_plug"></a>`typec_register_plug()`

```c
struct typec_plug * typec_register_plug(struct typec_cable *cable, struct typec_plug_desc *desc)
```

Register a USB Type-C Cable Plug

**Parameters**

- `struct typec_cable *cable`: USB Type-C Cable with the plug
- `struct typec_plug_desc *desc`: Description of the cable plug

**Description**

Registers a device for USB Type-C Cable Plug described in **desc**. A USB Type-C
Cable Plug represents a plug with electronics in it that can response to USB
Power Delivery SOP Prime or SOP Double Prime packages.

Returns handle to the cable plug on success or ERR_PTR on failure.

#### <a id="c-typec_unregister_plug"></a>`typec_unregister_plug()`

```c
void typec_unregister_plug(struct typec_plug *plug)
```

Unregister a USB Type-C Cable Plug

**Parameters**

- `struct typec_plug *plug`: The cable plug to be unregistered

**Description**

Unregister device created with [`typec_register_plug()`](#c-typec_register_plug).

#### <a id="c-typec_register_cable"></a>`typec_register_cable()`

```c
struct typec_cable * typec_register_cable(struct typec_port *port, struct typec_cable_desc *desc)
```

Register a USB Type-C Cable

**Parameters**

- `struct typec_port *port`: The USB Type-C Port the cable is connected to
- `struct typec_cable_desc *desc`: Description of the cable

**Description**

Registers a device for USB Type-C Cable described in **desc**. The cable will be
parent for the optional cable plug devises.

Returns handle to the cable on success or ERR_PTR on failure.

#### <a id="c-typec_unregister_cable"></a>`typec_unregister_cable()`

```c
void typec_unregister_cable(struct typec_cable *cable)
```

Unregister a USB Type-C Cable

**Parameters**

- `struct typec_cable *cable`: The cable to be unregistered

**Description**

Unregister device created with [`typec_register_cable()`](#c-typec_register_cable).


The class will provide a handle to struct typec_cable and struct typec_plug if the registration is successful, or NULL if it isn't.

If the cable is USB Power Delivery capable, and the port driver is able to show the result of Discover Identity command, the cable descriptor structure should include handle to struct usb_pd_identity instance. The class will then create a sysfs directory for the identity under the cable device. The result of Discover Identity command can then be reported with the following API:


#### <a id="c-typec_cable_set_identity"></a>`typec_cable_set_identity()`

```c
int typec_cable_set_identity(struct typec_cable *cable)
```

Report result from Discover Identity command

**Parameters**

- `struct typec_cable *cable`: The cable updated identity values

**Description**

This routine is used to report that the result of Discover Identity USB power
delivery command has become available.


<a id="rst-notifications"></a>

### Notifications

When the partner has executed a role change, or when the default roles change during connection of a partner or cable, the port driver must use the following APIs to report it to the class:


#### <a id="c-typec_set_data_role"></a>`typec_set_data_role()`

```c
void typec_set_data_role(struct typec_port *port, enum typec_data_role role)
```

Report data role change

**Parameters**

- `struct typec_port *port`: The USB Type-C Port where the role was changed
- `enum typec_data_role role`: The new data role

**Description**

This routine is used by the port drivers to report data role changes.

#### <a id="c-typec_set_pwr_role"></a>`typec_set_pwr_role()`

```c
void typec_set_pwr_role(struct typec_port *port, enum typec_role role)
```

Report power role change

**Parameters**

- `struct typec_port *port`: The USB Type-C Port where the role was changed
- `enum typec_role role`: The new data role

**Description**

This routine is used by the port drivers to report power role changes.

#### <a id="c-typec_set_vconn_role"></a>`typec_set_vconn_role()`

```c
void typec_set_vconn_role(struct typec_port *port, enum typec_role role)
```

Report VCONN source change

**Parameters**

- `struct typec_port *port`: The USB Type-C Port which VCONN role changed
- `enum typec_role role`: Source when **port** is sourcing VCONN, or Sink when it's not

**Description**

This routine is used by the port drivers to report if the VCONN source is
changes.

#### <a id="c-typec_set_pwr_opmode"></a>`typec_set_pwr_opmode()`

```c
void typec_set_pwr_opmode(struct typec_port *port, enum typec_pwr_opmode opmode)
```

Report changed power operation mode

**Parameters**

- `struct typec_port *port`: The USB Type-C Port where the mode was changed
- `enum typec_pwr_opmode opmode`: New power operation mode

**Description**

This routine is used by the port drivers to report changed power operation
mode in **port**. The modes are USB (default), 1.5A, 3.0A as defined in USB
Type-C specification, and "USB Power Delivery" when the power levels are
negotiated with methods defined in USB Power Delivery specification.


<a id="rst-alternate-modes"></a>

### Alternate Modes

USB Type-C ports, partners and cable plugs may support Alternate Modes. Each Alternate Mode will have identifier called SVID, which is either a Standard ID given by USB-IF or vendor ID, and each supported SVID can have 1 - 6 modes. The class provides struct typec_mode_desc for describing individual mode of a SVID, and struct typec_altmode_desc which is a container for all the supported modes.

Ports that support Alternate Modes need to register each SVID they support with the following API:


#### <a id="c-typec_port_register_altmode"></a>`typec_port_register_altmode()`

```c
struct typec_altmode * typec_port_register_altmode(struct typec_port *port, const struct typec_altmode_desc *desc)
```

Register USB Type-C Port Alternate Mode

**Parameters**

- `struct typec_port *port`: USB Type-C Port that supports the alternate mode
- `const struct typec_altmode_desc *desc`: Description of the alternate mode

**Description**

This routine is used to register an alternate mode that **port** is capable of
supporting.

Returns handle to the alternate mode on success or ERR_PTR on failure.


If a partner or cable plug provides a list of SVIDs as response to USB Power Delivery Structured VDM Discover SVIDs message, each SVID needs to be registered.

API for the partners:


#### <a id="c-typec_partner_register_altmode"></a>`typec_partner_register_altmode()`

```c
struct typec_altmode * typec_partner_register_altmode(struct typec_partner *partner, const struct typec_altmode_desc *desc)
```

Register USB Type-C Partner Alternate Mode

**Parameters**

- `struct typec_partner *partner`: USB Type-C Partner that supports the alternate mode
- `const struct typec_altmode_desc *desc`: Description of the alternate mode

**Description**

This routine is used to register each alternate mode individually that
**partner** has listed in response to Discover SVIDs command. The modes for a
SVID listed in response to Discover Modes command need to be listed in an
array in **desc**.

Returns handle to the alternate mode on success or ERR_PTR on failure.


API for the Cable Plugs:


#### <a id="c-typec_plug_register_altmode"></a>`typec_plug_register_altmode()`

```c
struct typec_altmode * typec_plug_register_altmode(struct typec_plug *plug, const struct typec_altmode_desc *desc)
```

Register USB Type-C Cable Plug Alternate Mode

**Parameters**

- `struct typec_plug *plug`: USB Type-C Cable Plug that supports the alternate mode
- `const struct typec_altmode_desc *desc`: Description of the alternate mode

**Description**

This routine is used to register each alternate mode individually that **plug**
has listed in response to Discover SVIDs command. The modes for a SVID that
the plug lists in response to Discover Modes command need to be listed in an
array in **desc**.

Returns handle to the alternate mode on success or ERR_PTR on failure.


So ports, partners and cable plugs will register the alternate modes with their own functions, but the registration will always return a handle to struct typec_altmode on success, or NULL. The unregistration will happen with the same function:


#### <a id="c-typec_unregister_altmode"></a>`typec_unregister_altmode()`

```c
void typec_unregister_altmode(struct typec_altmode *adev)
```

Unregister Alternate Mode

**Parameters**

- `struct typec_altmode *adev`: The alternate mode to be unregistered

**Description**

Unregister device created with [`typec_partner_register_altmode()`](#c-typec_partner_register_altmode),
[`typec_plug_register_altmode()`](#c-typec_plug_register_altmode) or [`typec_port_register_altmode()`](#c-typec_port_register_altmode).


If a partner or cable plug enters or exits a mode, the port driver needs to notify the class with the following API:


#### <a id="c-typec_altmode_update_active"></a>`typec_altmode_update_active()`

```c
void typec_altmode_update_active(struct typec_altmode *adev, bool active)
```

Report Enter/Exit mode

**Parameters**

- `struct typec_altmode *adev`: Handle to the alternate mode
- `bool active`: True when the mode has been entered

**Description**

If a partner or cable plug executes Enter/Exit Mode command successfully, the
drivers use this routine to report the updated state of the mode.


<a id="rst-multiplexer-demultiplexer-switches"></a>

### Multiplexer/DeMultiplexer Switches

USB Type-C connectors may have one or more mux/demux switches behind them. Since the plugs can be inserted right-side-up or upside-down, a switch is needed to route the correct data pairs from the connector to the USB controllers. If Alternate or Accessory Modes are supported, another switch is needed that can route the pins on the connector to some other component besides USB. USB Type-C Connector Class supplies an API for registering those switches.


#### <a id="c-typec_switch_register"></a>`typec_switch_register()`

```c
struct typec_switch_dev * typec_switch_register(struct device *parent, const struct typec_switch_desc *desc)
```

Register USB Type-C orientation switch

**Parameters**

- `struct device *parent`: Parent device
- `const struct typec_switch_desc *desc`: Orientation switch description

**Description**

This function registers a switch that can be used for routing the correct
data pairs depending on the cable plug orientation from the USB Type-C
connector to the USB controllers. USB Type-C plugs can be inserted
right-side-up or upside-down.

#### <a id="c-typec_switch_unregister"></a>`typec_switch_unregister()`

```c
void typec_switch_unregister(struct typec_switch_dev *sw_dev)
```

Unregister USB Type-C orientation switch

**Parameters**

- `struct typec_switch_dev *sw_dev`: USB Type-C orientation switch

**Description**

Unregister switch that was registered with [`typec_switch_register()`](#c-typec_switch_register).

#### <a id="c-typec_mux_register"></a>`typec_mux_register()`

```c
struct typec_mux_dev * typec_mux_register(struct device *parent, const struct typec_mux_desc *desc)
```

Register Multiplexer routing USB Type-C pins

**Parameters**

- `struct device *parent`: Parent device
- `const struct typec_mux_desc *desc`: Multiplexer description

**Description**

USB Type-C connectors can be used for alternate modes of operation besides
USB when Accessory/Alternate Modes are supported. With some of those modes,
the pins on the connector need to be reconfigured. This function registers
multiplexer switches routing the pins on the connector.

#### <a id="c-typec_mux_unregister"></a>`typec_mux_unregister()`

```c
void typec_mux_unregister(struct typec_mux_dev *mux_dev)
```

Unregister Multiplexer Switch

**Parameters**

- `struct typec_mux_dev *mux_dev`: USB Type-C Connector Multiplexer/DeMultiplexer

**Description**

Unregister mux that was registered with [`typec_mux_register()`](#c-typec_mux_register).


In most cases the same physical mux will handle both the orientation and mode. However, as the port drivers will be responsible for the orientation, and the alternate mode drivers for the mode, the two are always separated into their own logical components: "mux" for the mode and "switch" for the orientation.

When a port is registered, USB Type-C Connector Class requests both the mux and the switch for the port. The drivers can then use the following API for controlling them:


#### <a id="c-typec_set_orientation"></a>`typec_set_orientation()`

```c
int typec_set_orientation(struct typec_port *port, enum typec_orientation orientation)
```

Set USB Type-C cable plug orientation

**Parameters**

- `struct typec_port *port`: USB Type-C Port
- `enum typec_orientation orientation`: USB Type-C cable plug orientation

**Description**

Set cable plug orientation for **port**.

#### <a id="c-typec_set_mode"></a>`typec_set_mode()`

```c
int typec_set_mode(struct typec_port *port, int mode)
```

Set mode of operation for USB Type-C connector

**Parameters**

- `struct typec_port *port`: USB Type-C connector
- `int mode`: Accessory Mode, USB Operation or Safe State

**Description**

Configure **port** for Accessory Mode **mode**. This function will configure the
muxes needed for **mode**.


If the connector is dual-role capable, there may also be a switch for the data role. USB Type-C Connector Class does not supply separate API for them. The port drivers can use USB Role Class API with those.

Illustration of the muxes behind a connector that supports an alternate mode:



```text
               ------------------------
               |       Connector      |
               ------------------------
                      |         |
               ------------------------
                \     Orientation    /
                 --------------------
                          |
                 --------------------
                /        Mode        \
               ------------------------
                   /              \
------------------------        --------------------
|       Alt Mode       |       /      USB Role      \
------------------------      ------------------------
                                   /            \
               ------------------------      ------------------------
               |       USB Host       |      |       USB Device     |
               ------------------------      ------------------------
```

---

# API for USB Type-C Alternate Mode drivers

_Peios Kernel / Hardware and drivers / Driver development / USB_

> Alternate modes require communication with the partner using Vendor Defined Messages (VDM) as defined in USB Type-C and USB Power Delivery Specifications. The communication is SVID (Standard or Vendor ID) specific, i.e. specific for every…

<a id="rst-api-for-usb-type-c-alternate-mode-drivers"></a>

<a id="rst-introduction"></a>

## Introduction

Alternate modes require communication with the partner using Vendor Defined Messages (VDM) as defined in USB Type-C and USB Power Delivery Specifications. The communication is SVID (Standard or Vendor ID) specific, i.e. specific for every alternate mode, so every alternate mode will need a custom driver.

USB Type-C bus allows binding a driver to the discovered partner alternate modes by using the SVID and the mode number.

[USB Type-C Connector Class](</kernel/hardware/driver-api/usb/typec.md#rst-typec>) provides a device for every alternate mode a port supports, and separate device for every alternate mode the partner supports. The drivers for the alternate modes are bound to the partner alternate mode devices, and the port alternate mode devices must be handled by the port drivers.

When a new partner alternate mode device is registered, it is linked to the alternate mode device of the port that the partner is attached to, that has matching SVID and mode. Communication between the port driver and alternate mode driver will happen using the same API.

The port alternate mode devices are used as a proxy between the partner and the alternate mode drivers, so the port drivers are only expected to pass the SVID specific commands from the alternate mode drivers to the partner, and from the partners to the alternate mode drivers. No direct SVID specific communication is needed from the port drivers, but the port drivers need to provide the operation callbacks for the port alternate mode devices, just like the alternate mode drivers need to provide them for the partner alternate mode devices.

<a id="rst-usage"></a>

## Usage:

<a id="rst-general"></a>

### General

By default, the alternate mode drivers are responsible for entering the mode. It is also possible to leave the decision about entering the mode to the user space (See Documentation/ABI/testing/sysfs-class-typec). Port drivers should not enter any modes on their own.

`->vdm` is the most important callback in the operation callbacks vector. It will be used to deliver all the SVID specific commands from the partner to the alternate mode driver, and vice versa in case of port drivers. The drivers send the SVID specific commands to each other using `typec_altmode_vdm()`.

If the communication with the partner using the SVID specific commands results in need to reconfigure the pins on the connector, the alternate mode driver needs to notify the bus using `typec_altmode_notify()`. The driver passes the negotiated SVID specific pin configuration value to the function as parameter. The bus driver will then configure the mux behind the connector using that value as the state value for the mux.

NOTE: The SVID specific pin configuration values must always start from `TYPEC_STATE_MODAL`. USB Type-C specification defines two default states for the connector: `TYPEC_STATE_USB` and `TYPEC_STATE_SAFE`. These values are reserved by the bus as the first possible values for the state. When the alternate mode is entered, the bus will put the connector into `TYPEC_STATE_SAFE` before sending Enter or Exit Mode command as defined in USB Type-C Specification, and also put the connector back to `TYPEC_STATE_USB` after the mode has been exited.

An example of working definitions for SVID specific pin configurations would look like this:



```text
enum {
    ALTMODEX_CONF_A = TYPEC_STATE_MODAL,
    ALTMODEX_CONF_B,
    ...
};
```

Helper macro `TYPEC_MODAL_STATE()` can also be used:



```text
#define ALTMODEX_CONF_A = TYPEC_MODAL_STATE(0);
#define ALTMODEX_CONF_B = TYPEC_MODAL_STATE(1);
```

<a id="rst-cable-plug-alternate-modes"></a>

### Cable plug alternate modes

The alternate mode drivers are not bound to cable plug alternate mode devices, only to the partner alternate mode devices. If the alternate mode supports, or requires, a cable that responds to SOP Prime, and optionally SOP Double Prime messages, the driver for that alternate mode must request handle to the cable plug alternate modes using `typec_altmode_get_plug()`, and take over their control.

<a id="rst-driver-api"></a>

## Driver API

<a id="rst-alternate-mode-structs"></a>

### Alternate mode structs


#### <a id="c-struct-typec_altmode_ops"></a>`struct typec_altmode_ops`

Alternate mode specific operations vector

**Definition**

```c
struct typec_altmode_ops {
    int (*enter)(struct typec_altmode *altmode, u32 *vdo);
    int (*exit)(struct typec_altmode *altmode);
    void (*attention)(struct typec_altmode *altmode, u32 vdo);
    int (*vdm)(struct typec_altmode *altmode, const u32 hdr, const u32 *vdo, int cnt);
    int (*notify)(struct typec_altmode *altmode, unsigned long conf, void *data);
    int (*activate)(struct typec_altmode *altmode, int activate);
};
```

**Members**

- `enter`: Operations to be executed with Enter Mode Command
- `exit`: Operations to be executed with Exit Mode Command
- `attention`: Callback for Attention Command
- `vdm`: Callback for SVID specific commands
- `notify`: Communication channel for platform and the alternate mode
- `activate`: User callback for Enter/Exit Mode

#### <a id="c-struct-typec_altmode_driver"></a>`struct typec_altmode_driver`

USB Type-C alternate mode device driver

**Definition**

```c
struct typec_altmode_driver {
    const struct typec_device_id *id_table;
    int (*probe)(struct typec_altmode *altmode);
    void (*remove)(struct typec_altmode *altmode);
    struct device_driver driver;
};
```

**Members**

- `id_table`: Null terminated array of SVIDs
- `probe`: Callback for device binding
- `remove`: Callback for device unbinding
- `driver`: Device driver model driver

**Description**

These drivers will be bind to the partner alternate mode devices. They will
handle all SVID specific communication.


<a id="rst-alternate-mode-driver-registering-unregistering"></a>

### Alternate mode driver registering/unregistering


#### <a id="c-typec_altmode_register_driver"></a>`typec_altmode_register_driver()`

```c
typec_altmode_register_driver(drv)
```

registers a USB Type-C alternate mode device driver

**Parameters**

- `drv`: pointer to struct typec_altmode_driver

**Description**

These drivers will be bind to the partner alternate mode devices. They will
handle all SVID specific communication.

#### <a id="c-typec_altmode_unregister_driver"></a>`typec_altmode_unregister_driver()`

```c
void typec_altmode_unregister_driver(struct typec_altmode_driver *drv)
```

unregisters a USB Type-C alternate mode device driver

**Parameters**

- `struct typec_altmode_driver *drv`: pointer to struct typec_altmode_driver

**Description**

These drivers will be bind to the partner alternate mode devices. They will
handle all SVID specific communication.


<a id="rst-alternate-mode-driver-operations"></a>

### Alternate mode driver operations


#### <a id="c-typec_altmode_notify"></a>`typec_altmode_notify()`

```c
int typec_altmode_notify(struct typec_altmode *adev, unsigned long conf, void *data)
```

Communication between the OS and alternate mode driver

**Parameters**

- `struct typec_altmode *adev`: Handle to the alternate mode
- `unsigned long conf`: Alternate mode specific configuration value
- `void *data`: Alternate mode specific data

**Description**

The primary purpose for this function is to allow the alternate mode drivers
to tell which pin configuration has been negotiated with the partner. That
information will then be used for example to configure the muxes.
Communication to the other direction is also possible, and low level device
drivers can also send notifications to the alternate mode drivers. The actual
communication will be specific for every SVID.

#### <a id="c-typec_altmode_enter"></a>`typec_altmode_enter()`

```c
int typec_altmode_enter(struct typec_altmode *adev, u32 *vdo)
```

Enter Mode

**Parameters**

- `struct typec_altmode *adev`: The alternate mode
- `u32 *vdo`: VDO for the Enter Mode command

**Description**

The alternate mode drivers use this function to enter mode. The port drivers
use this to inform the alternate mode drivers that the partner has initiated
Enter Mode command. If the alternate mode does not require VDO, **vdo** must be
NULL.

#### <a id="c-typec_altmode_exit"></a>`typec_altmode_exit()`

```c
int typec_altmode_exit(struct typec_altmode *adev)
```

Exit Mode

**Parameters**

- `struct typec_altmode *adev`: The alternate mode

**Description**

The partner of **adev** has initiated Exit Mode command.

#### <a id="c-typec_altmode_attention"></a>`typec_altmode_attention()`

```c
int typec_altmode_attention(struct typec_altmode *adev, u32 vdo)
```

Attention command

**Parameters**

- `struct typec_altmode *adev`: The alternate mode
- `u32 vdo`: VDO for the Attention command

**Description**

Notifies the partner of **adev** about Attention command.

#### <a id="c-typec_altmode_vdm"></a>`typec_altmode_vdm()`

```c
int typec_altmode_vdm(struct typec_altmode *adev, const u32 header, const u32 *vdo, int count)
```

Send Vendor Defined Messages (VDM) to the partner

**Parameters**

- `struct typec_altmode *adev`: Alternate mode handle
- `const u32 header`: VDM Header
- `const u32 *vdo`: Array of Vendor Defined Data Objects
- `int count`: Number of Data Objects

**Description**

The alternate mode drivers use this function for SVID specific communication
with the partner. The port drivers use it to deliver the Structured VDMs
received from the partners to the alternate mode drivers.


<a id="rst-api-for-the-port-drivers"></a>

### API for the port drivers


#### <a id="c-typec_match_altmode"></a>`typec_match_altmode()`

```c
struct typec_altmode * typec_match_altmode(struct typec_altmode **altmodes, size_t n, u16 svid, u8 mode)
```

Match SVID and mode to an array of alternate modes

**Parameters**

- `struct typec_altmode **altmodes`: Array of alternate modes
- `size_t n`: Number of elements in the array, or -1 for NULL terminated arrays
- `u16 svid`: Standard or Vendor ID to match with
- `u8 mode`: Mode to match with

**Description**

Return pointer to an alternate mode with SVID matching **svid**, or NULL when no
match is found.


<a id="rst-cable-plug-operations"></a>

### Cable Plug operations


#### <a id="c-typec_altmode_get_plug"></a>`typec_altmode_get_plug()`

```c
struct typec_altmode * typec_altmode_get_plug(struct typec_altmode *adev, enum typec_plug_index index)
```

Find cable plug alternate mode

**Parameters**

- `struct typec_altmode *adev`: Handle to partner alternate mode
- `enum typec_plug_index index`: Cable plug index

**Description**

Increment reference count for cable plug alternate mode device. Returns
handle to the cable plug alternate mode, or NULL if none is found.

#### <a id="c-typec_altmode_put_plug"></a>`typec_altmode_put_plug()`

```c
void typec_altmode_put_plug(struct typec_altmode *plug)
```

Decrement cable plug alternate mode reference count

**Parameters**

- `struct typec_altmode *plug`: Handle to the cable plug alternate mode

---

# The Linux-USB Host Side API

_Peios Kernel / Hardware and drivers / Driver development / USB_

> A Universal Serial Bus (USB) is used to connect a host, such as a PC or workstation, to a number of peripheral devices. USB uses a tree structure, with the host as the root (the system's master), hubs as interior nodes, and peripherals as…

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-the-linux-usb-host-side-api"></a>
<a id="rst-usb-hostside-api"></a>

<a id="rst-introduction-to-usb-on-linux"></a>

## Introduction to USB on Linux

A Universal Serial Bus (USB) is used to connect a host, such as a PC or workstation, to a number of peripheral devices. USB uses a tree structure, with the host as the root (the system's master), hubs as interior nodes, and peripherals as leaves (and slaves). Modern PCs support several such trees of USB devices, usually a few USB 3.0 (5 GBit/s) or USB 3.1 (10 GBit/s) and some legacy USB 2.0 (480 MBit/s) buses just in case.

That master/slave asymmetry was designed-in for a number of reasons, one being ease of use. It is not physically possible to mistake upstream and downstream or it does not matter with a type C plug (or they are built into the peripheral). Also, the host software doesn't need to deal with distributed auto-configuration since the pre-designated master node manages all that.

Kernel developers added USB support to Linux early in the 2.2 kernel series and have been developing it further since then. Besides support for each new generation of USB, various host controllers gained support, new drivers for peripherals have been added and advanced features for latency measurement and improved power management introduced.

Linux can run inside USB devices as well as on the hosts that control the devices. But USB device drivers running inside those peripherals don't do the same things as the ones running inside hosts, so they've been given a different name: *gadget drivers*. This document does not cover gadget drivers.

<a id="rst-usb-host-side-api-model"></a>

## USB Host-Side API Model

Host-side drivers for USB devices talk to the "usbcore" APIs. There are two. One is intended for *general-purpose* drivers (exposed through driver frameworks), and the other is for drivers that are *part of the core*. Such core drivers include the *hub* driver (which manages trees of USB devices) and several different kinds of *host controller drivers*, which control individual buses.

The device model seen by USB drivers is relatively complex.

- USB supports four kinds of data transfers (control, bulk, interrupt, and isochronous). Two of them (control and bulk) use bandwidth as it's available, while the other two (interrupt and isochronous) are scheduled to provide guaranteed bandwidth.

- The device description model includes one or more "configurations" per device, only one of which is active at a time. Devices are supposed to be capable of operating at lower than their top speeds and may provide a BOS descriptor showing the lowest speed they remain fully operational at.

- From USB 3.0 on configurations have one or more "functions", which provide a common functionality and are grouped together for purposes of power management.

- Configurations or functions have one or more "interfaces", each of which may have "alternate settings". Interfaces may be standardized by USB "Class" specifications, or may be specific to a vendor or device.

  USB device drivers actually bind to interfaces, not devices. Think of them as "interface drivers", though you may not see many devices where the distinction is important. *Most USB devices are simple, with only one function, one configuration, one interface, and one alternate setting.*

- Interfaces have one or more "endpoints", each of which supports one type and direction of data transfer such as "bulk out" or "interrupt in". The entire configuration may have up to sixteen endpoints in each direction, allocated as needed among all the interfaces.

- Data transfer on USB is packetized; each endpoint has a maximum packet size. Drivers must often be aware of conventions such as flagging the end of bulk transfers using "short" (including zero length) packets.

- The Linux USB API supports synchronous calls for control and bulk messages. It also supports asynchronous calls for all kinds of data transfer, using request structures called "URBs" (USB Request Blocks).

Accordingly, the USB Core API exposed to device drivers covers quite a lot of territory. You'll probably need to consult the USB 3.0 specification, available online from www.usb.org at no cost, as well as class or device specifications.

The only host-side drivers that actually touch hardware (reading/writing registers, handling IRQs, and so on) are the HCDs. In theory, all HCDs provide the same functionality through the same API. In practice, that's becoming more true, but there are still differences that crop up especially with fault handling on the less common controllers. Different controllers don't necessarily report the same aspects of failures, and recovery from faults (including software-induced ones like unlinking an URB) isn't yet fully consistent. Device driver authors should make a point of doing disconnect testing (while the device is active) with each different host controller driver, to make sure drivers don't have bugs of their own as well as to make sure they aren't relying on some HCD-specific behavior.

<a id="rst-usb-standard-types"></a>
<a id="rst-usb-chapter9"></a>

## USB-Standard Types

In `include/uapi/linux/usb/ch9.h` you will find the USB data types defined in chapter 9 of the USB specification. These data types are used throughout USB, and in APIs including this host side API, gadget APIs, usb character devices and debugfs interfaces. That file is itself included by `include/linux/usb/ch9.h`, which also contains declarations of a few utility routines for manipulating these data types; the implementations are in `drivers/usb/common/common.c`.


#### <a id="c-usb_ep_type_string"></a>`usb_ep_type_string()`

```c
const char * usb_ep_type_string(int ep_type)
```

Returns human readable-name of the endpoint type.

**Parameters**

- `int ep_type`: The endpoint type to return human-readable name for.  If it's not
  any of the types: USB_ENDPOINT_XFER_{CONTROL, ISOC, BULK, INT},
  usually got by `usb_endpoint_type()`, the string 'unknown' will be returned.

#### <a id="c-usb_otg_state_string"></a>`usb_otg_state_string()`

```c
const char * usb_otg_state_string(enum usb_otg_state state)
```

returns human readable name of OTG state.

**Parameters**

- `enum usb_otg_state state`: the OTG state to return the human readable name of. If it's not
  any of the states defined in usb_otg_state enum, 'UNDEFINED' will be
  returned.

#### <a id="c-usb_speed_string"></a>`usb_speed_string()`

```c
const char * usb_speed_string(enum usb_device_speed speed)
```

Returns human readable-name of the speed.

**Parameters**

- `enum usb_device_speed speed`: The speed to return human-readable name for.  If it's not
  any of the speeds defined in usb_device_speed enum, string for
  USB_SPEED_UNKNOWN will be returned.

#### <a id="c-usb_get_maximum_speed"></a>`usb_get_maximum_speed()`

```c
enum usb_device_speed usb_get_maximum_speed(struct device *dev)
```

Get maximum requested speed for a given USB controller.

**Parameters**

- `struct device *dev`: Pointer to the given USB controller device

**Description**

The function gets the maximum speed string from property "maximum-speed",
and returns the corresponding enum usb_device_speed.

#### <a id="c-usb_get_maximum_ssp_rate"></a>`usb_get_maximum_ssp_rate()`

```c
enum usb_ssp_rate usb_get_maximum_ssp_rate(struct device *dev)
```

Get the signaling rate generation and lane count of a SuperSpeed Plus capable device.

**Parameters**

- `struct device *dev`: Pointer to the given USB controller device

**Description**

If the string from "maximum-speed" property is super-speed-plus-genXxY where
'X' is the generation number and 'Y' is the number of lanes, then this
function returns the corresponding enum usb_ssp_rate.

#### <a id="c-usb_state_string"></a>`usb_state_string()`

```c
const char * usb_state_string(enum usb_device_state state)
```

Returns human readable name for the state.

**Parameters**

- `enum usb_device_state state`: The state to return a human-readable name for. If it's not
  any of the states devices in usb_device_state_string enum,
  the string UNKNOWN will be returned.

#### <a id="c-usb_get_role_switch_default_mode"></a>`usb_get_role_switch_default_mode()`

```c
enum usb_dr_mode usb_get_role_switch_default_mode(struct device *dev)
```

Get default mode for given device

**Parameters**

- `struct device *dev`: Pointer to the given device

**Description**

The function gets string from property 'role-switch-default-mode',
and returns the corresponding enum usb_dr_mode.

#### <a id="c-usb_decode_interval"></a>`usb_decode_interval()`

```c
unsigned int usb_decode_interval(const struct usb_endpoint_descriptor *epd, enum usb_device_speed speed)
```

Decode bInterval into the time expressed in 1us unit

**Parameters**

- `const struct usb_endpoint_descriptor *epd`: The descriptor of the endpoint
- `enum usb_device_speed speed`: The speed that the endpoint works as

**Description**

Function returns the interval expressed in 1us unit for servicing
endpoint for data transfers.

#### <a id="c-of_usb_get_dr_mode_by_phy"></a>`of_usb_get_dr_mode_by_phy()`

```c
enum usb_dr_mode of_usb_get_dr_mode_by_phy(struct device_node *np, int arg0)
```

Get dual role mode for the controller device which is associated with the given phy device_node

**Parameters**

- `struct device_node *np`: Pointer to the given phy device_node
- `int arg0`: phandle args\[0\] for phy's with #phy-cells >= 1, or -1 for
  phys which do not have phy-cells

**Description**

In dts a usb controller associates with phy devices.  The function gets
the string from property 'dr_mode' of the controller associated with the
given phy device node, and returns the correspondig enum usb_dr_mode.

#### <a id="c-of_usb_host_tpl_support"></a>`of_usb_host_tpl_support()`

```c
bool of_usb_host_tpl_support(struct device_node *np)
```

to get if Targeted Peripheral List is supported for given targeted hosts (non-PC hosts)

**Parameters**

- `struct device_node *np`: Pointer to the given device_node

**Description**

The function gets if the targeted hosts support TPL or not

#### <a id="c-of_usb_update_otg_caps"></a>`of_usb_update_otg_caps()`

```c
int of_usb_update_otg_caps(struct device_node *np, struct usb_otg_caps *otg_caps)
```

to update usb otg capabilities according to the passed properties in DT.

**Parameters**

- `struct device_node *np`: Pointer to the given device_node
- `struct usb_otg_caps *otg_caps`: Pointer to the target usb_otg_caps to be set

**Description**

The function updates the otg capabilities

#### <a id="c-usb_of_get_companion_dev"></a>`usb_of_get_companion_dev()`

```c
struct device * usb_of_get_companion_dev(struct device *dev)
```

Find the companion device

**Parameters**

- `struct device *dev`: the device pointer to find a companion

**Description**

Find the companion device from platform bus.

Takes a reference to the returned struct device which needs to be dropped
after use.

**Return**

On success, a pointer to the companion device, `NULL` on failure.


In addition, some functions useful for creating debugging output are defined in `drivers/usb/common/debug.c`.

<a id="rst-host-side-data-types-and-macros"></a>
<a id="rst-usb-header"></a>

## Host-Side Data Types and Macros

The host side API exposes several layers to drivers, some of which are more necessary than others. These support lifecycle models for host side drivers and devices, and support passing buffers through usbcore to some HCD that performs the I/O for the device driver.


#### <a id="c-struct-usb_host_endpoint"></a>`struct usb_host_endpoint`

host-side endpoint descriptor and queue

**Definition**

```c
struct usb_host_endpoint {
    struct usb_endpoint_descriptor                  desc;
    struct usb_ss_ep_comp_descriptor                ss_ep_comp;
    struct usb_ssp_isoc_ep_comp_descriptor          ssp_isoc_ep_comp;
    struct usb_eusb2_isoc_ep_comp_descriptor        eusb2_isoc_ep_comp;
    struct list_head                urb_list;
    void *hcpriv;
    struct ep_device                *ep_dev;
    unsigned char *extra;
    int extralen;
    int enabled;
    int streams;
};
```

**Members**

- `desc`: descriptor for this endpoint, wMaxPacketSize in native byteorder
- `ss_ep_comp`: SuperSpeed companion descriptor for this endpoint
- `ssp_isoc_ep_comp`: SuperSpeedPlus isoc companion descriptor for this endpoint
- `eusb2_isoc_ep_comp`: eUSB2 isoc companion descriptor for this endpoint
- `urb_list`: urbs queued to this endpoint; maintained by usbcore
- `hcpriv`: for use by HCD; typically holds hardware dma queue head (QH)
  with one or more transfer descriptors (TDs) per urb; must be preserved
  by core while BW is allocated for the endpoint
- `ep_dev`: ep_device for sysfs info
- `extra`: descriptors following this endpoint in the configuration
- `extralen`: how many bytes of "extra" are valid
- `enabled`: URBs may be submitted to this endpoint
- `streams`: number of USB-3 streams allocated on the endpoint

**Description**

USB requests are always queued to a given endpoint, identified by a
descriptor within an active interface in a given USB configuration.

#### <a id="c-struct-usb_interface"></a>`struct usb_interface`

what usb device drivers talk to

**Definition**

```c
struct usb_interface {
    struct usb_host_interface *altsetting;
    struct usb_host_interface *cur_altsetting;
    unsigned num_altsetting;
    struct usb_interface_assoc_descriptor *intf_assoc;
    int minor;
    enum usb_interface_condition condition;
    unsigned sysfs_files_created:1;
    unsigned ep_devs_created:1;
    unsigned unregistering:1;
    unsigned needs_remote_wakeup:1;
    unsigned needs_altsetting0:1;
    unsigned needs_binding:1;
    unsigned resetting_device:1;
    unsigned authorized:1;
    enum usb_wireless_status wireless_status;
    struct work_struct wireless_status_work;
    struct device dev;
    struct device *usb_dev;
    struct work_struct reset_ws;
};
```

**Members**

- `altsetting`: array of interface structures, one for each alternate
  setting that may be selected.  Each one includes a set of
  endpoint configurations.  They will be in no particular order.
- `cur_altsetting`: the current altsetting.
- `num_altsetting`: number of altsettings defined.
- `intf_assoc`: interface association descriptor
- `minor`: the minor number assigned to this interface, if this
  interface is bound to a driver that uses the USB major number.
  If this interface does not use the USB major, this field should
  be unused.  The driver should set this value in the `probe()`
  function of the driver, after it has been assigned a minor
  number from the USB core by calling [`usb_register_dev()`](#c-usb_register_dev).
- `condition`: binding state of the interface: not bound, binding
  (in `probe()`), bound to a driver, or unbinding (in `disconnect()`)
- `sysfs_files_created`: sysfs attributes exist
- `ep_devs_created`: endpoint child pseudo-devices exist
- `unregistering`: flag set when the interface is being unregistered
- `needs_remote_wakeup`: flag set when the driver requires remote-wakeup
  capability during autosuspend.
- `needs_altsetting0`: flag set when a set-interface request for altsetting 0
  has been deferred.
- `needs_binding`: flag set when the driver should be re-probed or unbound
  following a reset or suspend operation it doesn't support.
- `resetting_device`: USB core reset the device, so use alt setting 0 as
  current; needs bandwidth alloc after reset.
- `authorized`: This allows to (de)authorize individual interfaces instead
  a whole device in contrast to the device authorization.
- `wireless_status`: if the USB device uses a receiver/emitter combo, whether
  the emitter is connected.
- `wireless_status_work`: Used for scheduling wireless status changes
  from atomic context.
- `dev`: driver model's view of this device
- `usb_dev`: if an interface is bound to the USB major, this will point
  to the sysfs representation for that device.
- `reset_ws`: Used for scheduling resets from atomic context.

**Description**

USB device drivers attach to interfaces on a physical device.  Each
interface encapsulates a single high level function, such as feeding
an audio stream to a speaker or reporting a change in a volume control.
Many USB devices only have one interface.  The protocol used to talk to
an interface's endpoints can be defined in a usb "class" specification,
or by a product's vendor.  The (default) control endpoint is part of
every interface, but is never listed among the interface's descriptors.

The driver that is bound to the interface can use standard driver model
calls such as `dev_get_drvdata()` on the dev member of this structure.

Each interface may have alternate settings.  The initial configuration
of a device sets altsetting 0, but the device driver can change
that setting using [`usb_set_interface()`](#c-usb_set_interface).  Alternate settings are often
used to control the use of periodic endpoints, such as by having
different endpoints use different amounts of reserved USB bandwidth.
All standards-conformant USB devices that use isochronous endpoints
will use them in non-default settings.

The USB specification says that alternate setting numbers must run from
0 to one less than the total number of alternate settings.  But some
devices manage to mess this up, and the structures aren't necessarily
stored in numerical order anyhow.  Use [`usb_altnum_to_altsetting()`](#c-usb_altnum_to_altsetting) to
look up an alternate setting in the altsetting array based on its number.

#### <a id="c-usb_set_intfdata"></a>`usb_set_intfdata()`

```c
void usb_set_intfdata(struct usb_interface *intf, void *data)
```

associate driver-specific data with an interface

**Parameters**

- `struct usb_interface *intf`: USB interface
- `void *data`: driver data

**Description**

Drivers can use this function in their `probe()` callbacks to associate
driver-specific data with an interface.

Note that there is generally no need to clear the driver-data pointer even
if some drivers do so for historical or implementation-specific reasons.

#### <a id="c-struct-usb_interface_cache"></a>`struct usb_interface_cache`

long-term representation of a device interface

**Definition**

```c
struct usb_interface_cache {
    unsigned num_altsetting;
    struct kref ref;
    struct usb_host_interface altsetting[];
};
```

**Members**

- `num_altsetting`: number of altsettings defined.
- `ref`: reference counter.
- `altsetting`: variable-length array of interface structures, one for
  each alternate setting that may be selected.  Each one includes a
  set of endpoint configurations.  They will be in no particular order.

**Description**

These structures persist for the lifetime of a usb_device, unlike
struct usb_interface (which persists only as long as its configuration
is installed).  The altsetting arrays can be accessed through these
structures at any time, permitting comparison of configurations and
providing support for the /sys/kernel/debug/usb/devices pseudo-file.

#### <a id="c-struct-usb_host_config"></a>`struct usb_host_config`

representation of a device's configuration

**Definition**

```c
struct usb_host_config {
    struct usb_config_descriptor    desc;
    char *string;
    struct usb_interface_assoc_descriptor *intf_assoc[USB_MAXIADS];
    struct usb_interface *interface[USB_MAXINTERFACES];
    struct usb_interface_cache *intf_cache[USB_MAXINTERFACES];
    unsigned char *extra;
    int extralen;
};
```

**Members**

- `desc`: the device's configuration descriptor.
- `string`: pointer to the cached version of the iConfiguration string, if
  present for this configuration.
- `intf_assoc`: list of any interface association descriptors in this config
- `interface`: array of pointers to usb_interface structures, one for each
  interface in the configuration.  The number of interfaces is stored
  in desc.bNumInterfaces.  These pointers are valid only while the
  configuration is active.
- `intf_cache`: array of pointers to usb_interface_cache structures, one
  for each interface in the configuration.  These structures exist
  for the entire life of the device.
- `extra`: pointer to buffer containing all extra descriptors associated
  with this configuration (those preceding the first interface
  descriptor).
- `extralen`: length of the extra descriptors buffer.

**Description**

USB devices may have multiple configurations, but only one can be active
at any time.  Each encapsulates a different operational environment;
for example, a dual-speed device would have separate configurations for
full-speed and high-speed operation.  The number of configurations
available is stored in the device descriptor as bNumConfigurations.

A configuration can contain multiple interfaces.  Each corresponds to
a different function of the USB device, and all are available whenever
the configuration is active.  The USB standard says that interfaces
are supposed to be numbered from 0 to desc.bNumInterfaces-1, but a lot
of devices get this wrong.  In addition, the interface array is not
guaranteed to be sorted in numerical order.  Use [`usb_ifnum_to_if()`](#c-usb_ifnum_to_if) to
look up an interface entry based on its number.

Device drivers should not attempt to activate configurations.  The choice
of which configuration to install is a policy decision based on such
considerations as available power, functionality provided, and the user's
desires (expressed through userspace tools).  However, drivers can call
[`usb_reset_configuration()`](#c-usb_reset_configuration) to reinitialize the current configuration and
all its interfaces.

#### <a id="c-struct-usb_device"></a>`struct usb_device`

kernel's representation of a USB device

**Definition**

```c
struct usb_device {
    int devnum;
    char devpath[16];
    u32 route;
    enum usb_device_state   state;
    enum usb_device_speed   speed;
    unsigned int            rx_lanes;
    unsigned int            tx_lanes;
    enum usb_ssp_rate       ssp_rate;
    struct usb_tt   *tt;
    int ttport;
    unsigned int toggle[2];
    struct usb_device *parent;
    struct usb_bus *bus;
    struct usb_host_endpoint ep0;
    struct device dev;
    struct usb_device_descriptor descriptor;
    struct usb_host_bos *bos;
    struct usb_host_config *config;
    struct usb_host_config *actconfig;
    struct usb_host_endpoint *ep_in[16];
    struct usb_host_endpoint *ep_out[16];
    char **rawdescriptors;
    unsigned short bus_mA;
    u8 portnum;
    u8 level;
    u8 devaddr;
    unsigned can_submit:1;
    unsigned persist_enabled:1;
    unsigned reset_in_progress:1;
    unsigned have_langid:1;
    unsigned authorized:1;
    unsigned authenticated:1;
    unsigned lpm_capable:1;
    unsigned lpm_devinit_allow:1;
    unsigned usb2_hw_lpm_capable:1;
    unsigned usb2_hw_lpm_besl_capable:1;
    unsigned usb2_hw_lpm_enabled:1;
    unsigned usb2_hw_lpm_allowed:1;
    unsigned usb3_lpm_u1_enabled:1;
    unsigned usb3_lpm_u2_enabled:1;
    int string_langid;
    char *product;
    char *manufacturer;
    char *serial;
    struct list_head filelist;
    int maxchild;
    u32 quirks;
    atomic_t urbnum;
    unsigned long active_duration;
    unsigned long connect_time;
    unsigned do_remote_wakeup:1;
    unsigned reset_resume:1;
    unsigned port_is_suspended:1;
    unsigned offload_pm_locked:1;
    int offload_usage;
    spinlock_t offload_lock;
    enum usb_link_tunnel_mode tunnel_mode;
    struct device_link *usb4_link;
    int slot_id;
    struct usb2_lpm_parameters l1_params;
    struct usb3_lpm_parameters u1_params;
    struct usb3_lpm_parameters u2_params;
    unsigned lpm_disable_count;
    u16 hub_delay;
    unsigned use_generic_driver:1;
};
```

**Members**

- `devnum`: device number; address on a USB bus
- `devpath`: device ID string for use in messages (e.g., /port/...)
- `route`: tree topology hex string for use with xHCI
- `state`: device state: configured, not attached, etc.
- `speed`: device speed: high/full/low (or error)
- `rx_lanes`: number of rx lanes in use, USB 3.2 adds dual-lane support
- `tx_lanes`: number of tx lanes in use, USB 3.2 adds dual-lane support
- `ssp_rate`: SuperSpeed Plus phy signaling rate and lane count
- `tt`: Transaction Translator info; used with low/full speed dev, highspeed hub
- `ttport`: device port on that tt hub
- `toggle`: one bit for each endpoint, with (\[0\] = IN, \[1\] = OUT) endpoints
- `parent`: our hub, unless we're the root
- `bus`: bus we're part of
- `ep0`: endpoint 0 data (default control pipe)
- `dev`: generic device interface
- `descriptor`: USB device descriptor
- `bos`: USB device BOS descriptor set
- `config`: all of the device's configs
- `actconfig`: the active configuration
- `ep_in`: array of IN endpoints
- `ep_out`: array of OUT endpoints
- `rawdescriptors`: raw descriptors for each config
- `bus_mA`: Current available from the bus
- `portnum`: parent port number (origin 1)
- `level`: number of USB hub ancestors
- `devaddr`: device address, XHCI: assigned by HW, others: same as devnum
- `can_submit`: URBs may be submitted
- `persist_enabled`: USB_PERSIST enabled for this device
- `reset_in_progress`: the device is being reset
- `have_langid`: whether string_langid is valid
- `authorized`: policy has said we can use it;
  (user space) policy determines if we authorize this device to be
  used or not. By default, wired USB devices are authorized.
  WUSB devices are not, until we authorize them from user space.
  FIXME -- complete doc
- `authenticated`: Crypto authentication passed
- `lpm_capable`: device supports LPM
- `lpm_devinit_allow`: Allow USB3 device initiated LPM, exit latency is in range
- `usb2_hw_lpm_capable`: device can perform USB2 hardware LPM
- `usb2_hw_lpm_besl_capable`: device can perform USB2 hardware BESL LPM
- `usb2_hw_lpm_enabled`: USB2 hardware LPM is enabled
- `usb2_hw_lpm_allowed`: Userspace allows USB 2.0 LPM to be enabled
- `usb3_lpm_u1_enabled`: USB3 hardware U1 LPM enabled
- `usb3_lpm_u2_enabled`: USB3 hardware U2 LPM enabled
- `string_langid`: language ID for strings
- `product`: iProduct string, if present (static)
- `manufacturer`: iManufacturer string, if present (static)
- `serial`: iSerialNumber string, if present (static)
- `filelist`: usbfs files that are open to this device
- `maxchild`: number of ports if hub
- `quirks`: quirks of the whole device
- `urbnum`: number of URBs submitted for the whole device
- `active_duration`: total time device is not suspended
- `connect_time`: time device was first connected
- `do_remote_wakeup`: remote wakeup should be enabled
- `reset_resume`: needs reset instead of resume
- `port_is_suspended`: the upstream port is suspended (L2 or U3)
- `offload_pm_locked`: prevents offload_usage changes during PM transitions.
- `offload_usage`: number of offload activities happening on this usb device.
- `offload_lock`: protects offload_usage and offload_pm_locked
- `tunnel_mode`: Connection native or tunneled over USB4
- `usb4_link`: device link to the USB4 host interface
- `slot_id`: Slot ID assigned by xHCI
- `l1_params`: best effor service latency for USB2 L1 LPM state, and L1 timeout.
- `u1_params`: exit latencies for USB3 U1 LPM state, and hub-initiated timeout.
- `u2_params`: exit latencies for USB3 U2 LPM state, and hub-initiated timeout.
- `lpm_disable_count`: Ref count used by `usb_disable_lpm()` and `usb_enable_lpm()`
  to keep track of the number of functions that require USB 3.0 Link Power
  Management to be disabled for this usb_device.  This count should only
  be manipulated by those functions, with the bandwidth_mutex is held.
- `hub_delay`: cached value consisting of:
  parent->hub_delay + wHubDelay + tTPTransmissionDelay (40ns)
  Will be used as wValue for SetIsochDelay requests.
- `use_generic_driver`: ask driver core to reprobe using the generic driver.

**Notes**

Usbcore drivers should not set usbdev->state directly.  Instead use
[`usb_set_device_state()`](#c-usb_set_device_state).

#### <a id="c-usb_hub_for_each_child"></a>`usb_hub_for_each_child()`

```c
usb_hub_for_each_child(hdev, port1, child)
```

iterate over all child devices on the hub

**Parameters**

- `hdev`: USB device belonging to the usb hub
- `port1`: portnum associated with child device
- `child`: child device pointer

#### <a id="c-usb_interface_claimed"></a>`usb_interface_claimed()`

```c
int usb_interface_claimed(struct usb_interface *iface)
```

returns true iff an interface is claimed

**Parameters**

- `struct usb_interface *iface`: the interface being checked

**Return**

`true` (nonzero) iff the interface is claimed, else `false`
(zero).

**Note**

Callers must own the driver model's usb bus readlock.  So driver
`probe()` entries don't need extra locking, but other call contexts
may need to explicitly claim that lock.

#### <a id="c-usb_make_path"></a>`usb_make_path()`

```c
int usb_make_path(struct usb_device *dev, char *buf, size_t size)
```

returns stable device path in the usb tree

**Parameters**

- `struct usb_device *dev`: the device whose path is being constructed
- `char *buf`: where to put the string
- `size_t size`: how big is "buf"?

**Return**

Length of the string (> 0) or negative if size was too small.

**Note**

This identifier is intended to be "stable", reflecting physical paths in
hardware such as physical bus addresses for host controllers or ports on
USB hubs.  That makes it stay the same until systems are physically
reconfigured, by re-cabling a tree of USB devices or by moving USB host
controllers.  Adding and removing devices, including virtual root hubs
in host controller driver modules, does not change these path identifiers;
neither does rebooting or re-enumerating.  These are more useful identifiers
than changeable ("unstable") ones like bus numbers or device addresses.

With a partial exception for devices connected to USB 2.0 root hubs, these
identifiers are also predictable.  So long as the device tree isn't changed,
plugging any USB device into a given hub port always gives it the same path.
Because of the use of "companion" controllers, devices connected to ports on
USB 2.0 root hubs (EHCI host controllers) will get one path ID if they are
high speed, and a different one if they are full or low speed.

#### <a id="c-USB_DEVICE"></a>`USB_DEVICE()`

```c
USB_DEVICE(vend, prod)
```

macro used to describe a specific usb device

**Parameters**

- `vend`: the 16 bit USB Vendor ID
- `prod`: the 16 bit USB Product ID

**Description**

This macro is used to create a struct usb_device_id that matches a
specific device.

#### <a id="c-USB_DEVICE_VER"></a>`USB_DEVICE_VER()`

```c
USB_DEVICE_VER(vend, prod, lo, hi)
```

describe a specific usb device with a version range

**Parameters**

- `vend`: the 16 bit USB Vendor ID
- `prod`: the 16 bit USB Product ID
- `lo`: the bcdDevice_lo value
- `hi`: the bcdDevice_hi value

**Description**

This macro is used to create a struct usb_device_id that matches a
specific device, with a version range.

#### <a id="c-USB_DEVICE_INTERFACE_CLASS"></a>`USB_DEVICE_INTERFACE_CLASS()`

```c
USB_DEVICE_INTERFACE_CLASS(vend, prod, cl)
```

describe a usb device with a specific interface class

**Parameters**

- `vend`: the 16 bit USB Vendor ID
- `prod`: the 16 bit USB Product ID
- `cl`: bInterfaceClass value

**Description**

This macro is used to create a struct usb_device_id that matches a
specific interface class of devices.

#### <a id="c-USB_DEVICE_INTERFACE_PROTOCOL"></a>`USB_DEVICE_INTERFACE_PROTOCOL()`

```c
USB_DEVICE_INTERFACE_PROTOCOL(vend, prod, pr)
```

describe a usb device with a specific interface protocol

**Parameters**

- `vend`: the 16 bit USB Vendor ID
- `prod`: the 16 bit USB Product ID
- `pr`: bInterfaceProtocol value

**Description**

This macro is used to create a struct usb_device_id that matches a
specific interface protocol of devices.

#### <a id="c-USB_DEVICE_INTERFACE_NUMBER"></a>`USB_DEVICE_INTERFACE_NUMBER()`

```c
USB_DEVICE_INTERFACE_NUMBER(vend, prod, num)
```

describe a usb device with a specific interface number

**Parameters**

- `vend`: the 16 bit USB Vendor ID
- `prod`: the 16 bit USB Product ID
- `num`: bInterfaceNumber value

**Description**

This macro is used to create a struct usb_device_id that matches a
specific interface number of devices.

#### <a id="c-USB_DEVICE_INFO"></a>`USB_DEVICE_INFO()`

```c
USB_DEVICE_INFO(cl, sc, pr)
```

macro used to describe a class of usb devices

**Parameters**

- `cl`: bDeviceClass value
- `sc`: bDeviceSubClass value
- `pr`: bDeviceProtocol value

**Description**

This macro is used to create a struct usb_device_id that matches a
specific class of devices.

#### <a id="c-USB_INTERFACE_INFO"></a>`USB_INTERFACE_INFO()`

```c
USB_INTERFACE_INFO(cl, sc, pr)
```

macro used to describe a class of usb interfaces

**Parameters**

- `cl`: bInterfaceClass value
- `sc`: bInterfaceSubClass value
- `pr`: bInterfaceProtocol value

**Description**

This macro is used to create a struct usb_device_id that matches a
specific class of interfaces.

#### <a id="c-USB_DEVICE_AND_INTERFACE_INFO"></a>`USB_DEVICE_AND_INTERFACE_INFO()`

```c
USB_DEVICE_AND_INTERFACE_INFO(vend, prod, cl, sc, pr)
```

describe a specific usb device with a class of usb interfaces

**Parameters**

- `vend`: the 16 bit USB Vendor ID
- `prod`: the 16 bit USB Product ID
- `cl`: bInterfaceClass value
- `sc`: bInterfaceSubClass value
- `pr`: bInterfaceProtocol value

**Description**

This macro is used to create a struct usb_device_id that matches a
specific device with a specific class of interfaces.

This is especially useful when explicitly matching devices that have
vendor specific bDeviceClass values, but standards-compliant interfaces.

#### <a id="c-USB_VENDOR_AND_INTERFACE_INFO"></a>`USB_VENDOR_AND_INTERFACE_INFO()`

```c
USB_VENDOR_AND_INTERFACE_INFO(vend, cl, sc, pr)
```

describe a specific usb vendor with a class of usb interfaces

**Parameters**

- `vend`: the 16 bit USB Vendor ID
- `cl`: bInterfaceClass value
- `sc`: bInterfaceSubClass value
- `pr`: bInterfaceProtocol value

**Description**

This macro is used to create a struct usb_device_id that matches a
specific vendor with a specific class of interfaces.

This is especially useful when explicitly matching devices that have
vendor specific bDeviceClass values, but standards-compliant interfaces.

#### <a id="c-struct-usb_driver"></a>`struct usb_driver`

identifies USB interface driver to usbcore

**Definition**

```c
struct usb_driver {
    const char *name;
    int (*probe) (struct usb_interface *intf, const struct usb_device_id *id);
    void (*disconnect) (struct usb_interface *intf);
    int (*unlocked_ioctl) (struct usb_interface *intf, unsigned int code, void *buf);
    int (*suspend) (struct usb_interface *intf, pm_message_t message);
    int (*resume) (struct usb_interface *intf);
    int (*reset_resume)(struct usb_interface *intf);
    int (*pre_reset)(struct usb_interface *intf);
    int (*post_reset)(struct usb_interface *intf);
    void (*shutdown)(struct usb_interface *intf);
    const struct usb_device_id *id_table;
    const struct attribute_group **dev_groups;
    struct usb_dynids dynids;
    struct device_driver driver;
    unsigned int no_dynamic_id:1;
    unsigned int supports_autosuspend:1;
    unsigned int disable_hub_initiated_lpm:1;
    unsigned int soft_unbind:1;
};
```

**Members**

- `name`: The driver name should be unique among USB drivers,
  and should normally be the same as the module name.
- `probe`: Called to see if the driver is willing to manage a particular
  interface on a device.  If it is, probe returns zero and uses
  [`usb_set_intfdata()`](#c-usb_set_intfdata) to associate driver-specific data with the
  interface.  It may also use [`usb_set_interface()`](#c-usb_set_interface) to specify the
  appropriate altsetting.  If unwilling to manage the interface,
  return -ENODEV, if genuine IO errors occurred, an appropriate
  negative errno value.
- `disconnect`: Called when the interface is no longer accessible, usually
  because its device has been (or is being) disconnected or the
  driver module is being unloaded.
- `unlocked_ioctl`: Used for drivers that want to talk to userspace through
  the "usbfs" filesystem.  This lets devices provide ways to
  expose information to user space regardless of where they
  do (or don't) show up otherwise in the filesystem.
- `suspend`: Called when the device is going to be suspended by the
  system either from system sleep or runtime suspend context. The
  return value will be ignored in system sleep context, so do NOT
  try to continue using the device if suspend fails in this case.
  Instead, let the resume or reset-resume routine recover from
  the failure.
- `resume`: Called when the device is being resumed by the system.
- `reset_resume`: Called when the suspended device has been reset instead
  of being resumed.
- `pre_reset`: Called by [`usb_reset_device()`](#c-usb_reset_device) when the device is about to be
  reset.  This routine must not return until the driver has no active
  URBs for the device, and no more URBs may be submitted until the
  post_reset method is called.
- `post_reset`: Called by [`usb_reset_device()`](#c-usb_reset_device) after the device
  has been reset
- `shutdown`: Called at shut-down time to quiesce the device.
- `id_table`: USB drivers use ID table to support hotplugging.
  Export this with MODULE_DEVICE_TABLE(usb,...).  This must be set
  or your driver's probe function will never get called.
- `dev_groups`: Attributes attached to the device that will be created once it
  is bound to the driver.
- `dynids`: used internally to hold the list of dynamically added device
  ids for this driver.
- `driver`: The driver-model core driver structure.
- `no_dynamic_id`: if set to 1, the USB core will not allow dynamic ids to be
  added to this driver by preventing the sysfs file from being created.
- `supports_autosuspend`: if set to 0, the USB core will not allow autosuspend
  for interfaces bound to this driver.
- `disable_hub_initiated_lpm`: if set to 1, the USB core will not allow hubs
  to initiate lower power link state transitions when an idle timeout
  occurs.  Device-initiated USB 3.0 link PM will still be allowed.
- `soft_unbind`: if set to 1, the USB core will not kill URBs and disable
  endpoints before calling the driver's disconnect method.

**Description**

USB interface drivers must provide a name, `probe()` and `disconnect()`
methods, and an id_table.  Other driver fields are optional.

The id_table is used in hotplugging.  It holds a set of descriptors,
and specialized data may be associated with each entry.  That table
is used by both user and kernel mode hotplugging support.

The `probe()` and `disconnect()` methods are called in a context where
they can sleep, but they should avoid abusing the privilege.  Most
work to connect to a device should be done when the device is opened,
and undone at the last close.  The disconnect code needs to address
concurrency issues with respect to `open()` and `close()` methods, as
well as forcing all pending I/O requests to complete (by unlinking
them as necessary, and blocking until the unlinks complete).

#### <a id="c-struct-usb_device_driver"></a>`struct usb_device_driver`

identifies USB device driver to usbcore

**Definition**

```c
struct usb_device_driver {
    const char *name;
    bool (*match) (struct usb_device *udev);
    int (*probe) (struct usb_device *udev);
    void (*disconnect) (struct usb_device *udev);
    int (*suspend) (struct usb_device *udev, pm_message_t message);
    int (*resume) (struct usb_device *udev, pm_message_t message);
    int (*choose_configuration) (struct usb_device *udev);
    const struct attribute_group **dev_groups;
    struct device_driver driver;
    const struct usb_device_id *id_table;
    unsigned int supports_autosuspend:1;
    unsigned int generic_subclass:1;
};
```

**Members**

- `name`: The driver name should be unique among USB drivers,
  and should normally be the same as the module name.
- `match`: If set, used for better device/driver matching.
- `probe`: Called to see if the driver is willing to manage a particular
  device.  If it is, probe returns zero and uses `dev_set_drvdata()`
  to associate driver-specific data with the device.  If unwilling
  to manage the device, return a negative errno value.
- `disconnect`: Called when the device is no longer accessible, usually
  because it has been (or is being) disconnected or the driver's
  module is being unloaded.
- `suspend`: Called when the device is going to be suspended by the system.
- `resume`: Called when the device is being resumed by the system.
- `choose_configuration`: If non-NULL, called instead of the default
  `usb_choose_configuration()`. If this returns an error then we'll go
  on to call the normal `usb_choose_configuration()`.
- `dev_groups`: Attributes attached to the device that will be created once it
  is bound to the driver.
- `driver`: The driver-model core driver structure.
- `id_table`: used with **match()** to select better matching driver at
  `probe()` time.
- `supports_autosuspend`: if set to 0, the USB core will not allow autosuspend
  for devices bound to this driver.
- `generic_subclass`: if set to 1, the generic USB driver's probe, disconnect,
  resume and suspend functions will be called in addition to the driver's
  own, so this part of the setup does not need to be replicated.

**Description**

USB device drivers must provide a name, other driver fields are optional.

#### <a id="c-struct-usb_class_driver"></a>`struct usb_class_driver`

identifies a USB driver that wants to use the USB major number

**Definition**

```c
struct usb_class_driver {
    char *name;
    char *(*devnode)(const struct device *dev, umode_t *mode);
    const struct file_operations *fops;
    int minor_base;
};
```

**Members**

- `name`: the usb class device name for this driver.  Will show up in sysfs.
- `devnode`: Callback to provide a naming hint for a possible
  device node to create.
- `fops`: pointer to the struct file_operations of this driver.
- `minor_base`: the start of the minor range for this driver.

**Description**

This structure is used for the [`usb_register_dev()`](#c-usb_register_dev) and
[`usb_deregister_dev()`](#c-usb_deregister_dev) functions, to consolidate a number of the
parameters used for them.

#### <a id="c-module_usb_driver"></a>`module_usb_driver()`

```c
module_usb_driver(__usb_driver)
```

Helper macro for registering a USB driver

**Parameters**

- `__usb_driver`: usb_driver struct

**Description**

Helper macro for USB drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)

#### <a id="c-struct-urb"></a>`struct urb`

USB Request Block

**Definition**

```c
struct urb {
    struct list_head urb_list;
    struct list_head anchor_list;
    struct usb_anchor *anchor;
    struct usb_device *dev;
    struct usb_host_endpoint *ep;
    unsigned int pipe;
    unsigned int stream_id;
    int status;
    unsigned int transfer_flags;
    void *transfer_buffer;
    dma_addr_t transfer_dma;
    struct scatterlist *sg;
    struct sg_table *sgt;
    int num_mapped_sgs;
    int num_sgs;
    u32 transfer_buffer_length;
    u32 actual_length;
    unsigned char *setup_packet;
    dma_addr_t setup_dma;
    int start_frame;
    int number_of_packets;
    int interval;
    int error_count;
    void *context;
    usb_complete_t complete;
    struct usb_iso_packet_descriptor iso_frame_desc[];
};
```

**Members**

- `urb_list`: For use by current owner of the URB.
- `anchor_list`: membership in the list of an anchor
- `anchor`: to anchor URBs to a common mooring
- `dev`: Identifies the USB device to perform the request.
- `ep`: Points to the endpoint's data structure.  Will eventually
  replace **pipe**.
- `pipe`: Holds endpoint number, direction, type, and more.
  Create these values with the eight macros available;
  usb_{snd,rcv}TYPEpipe(dev,endpoint), where the TYPE is "ctrl"
  (control), "bulk", "int" (interrupt), or "iso" (isochronous).
  For example `usb_sndbulkpipe()` or `usb_rcvintpipe()`.  Endpoint
  numbers range from zero to fifteen.  Note that "in" endpoint two
  is a different endpoint (and pipe) from "out" endpoint two.
  The current configuration controls the existence, type, and
  maximum packet size of any given endpoint.
- `stream_id`: the endpoint's stream ID for bulk streams
- `status`: This is read in non-iso completion functions to get the
  status of the particular request.  ISO requests only use it
  to tell whether the URB was unlinked; detailed status for
  each frame is in the fields of the iso_frame-desc.
- `transfer_flags`: A variety of flags may be used to affect how URB
  submission, unlinking, or operation are handled.  Different
  kinds of URB can use different flags.
- `transfer_buffer`: This identifies the buffer to (or from) which the I/O
  request will be performed unless URB_NO_TRANSFER_DMA_MAP is set
  (however, do not leave garbage in transfer_buffer even then).
  This buffer must be suitable for DMA; allocate it with
  [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) or equivalent.  For transfers to "in" endpoints, contents
  of this buffer will be modified.  This buffer is used for the data
  stage of control transfers.
- `transfer_dma`: When transfer_flags includes URB_NO_TRANSFER_DMA_MAP,
  the device driver is saying that it provided this DMA address,
  which the host controller driver should use in preference to the
  transfer_buffer.
- `sg`: scatter gather buffer list, the buffer size of each element in
  the list (except the last) must be divisible by the endpoint's
  max packet size if no_sg_constraint isn't set in 'struct usb_bus'
- `sgt`: used to hold a scatter gather table returned by [`usb_alloc_noncoherent()`](#c-usb_alloc_noncoherent),
  which describes the allocated non-coherent and possibly non-contiguous
  memory and is guaranteed to have 1 single DMA mapped segment. The
  allocated memory needs to be freed by [`usb_free_noncoherent()`](#c-usb_free_noncoherent).
- `num_mapped_sgs`: (internal) number of mapped sg entries
- `num_sgs`: number of entries in the sg list
- `transfer_buffer_length`: How big is transfer_buffer.  The transfer may
  be broken up into chunks according to the current maximum packet
  size for the endpoint, which is a function of the configuration
  and is encoded in the pipe.  When the length is zero, neither
  transfer_buffer nor transfer_dma is used.
- `actual_length`: This is read in non-iso completion functions, and
  it tells how many bytes (out of transfer_buffer_length) were
  transferred.  It will normally be the same as requested, unless
  either an error was reported or a short read was performed.
  The URB_SHORT_NOT_OK transfer flag may be used to make such
  short reads be reported as errors.
- `setup_packet`: Only used for control transfers, this points to eight bytes
  of setup data.  Control transfers always start by sending this data
  to the device.  Then transfer_buffer is read or written, if needed.
- `setup_dma`: DMA pointer for the setup packet.  The caller must not use
  this field; setup_packet must point to a valid buffer.
- `start_frame`: Returns the initial frame for isochronous transfers.
- `number_of_packets`: Lists the number of ISO transfer buffers.
- `interval`: Specifies the polling interval for interrupt or isochronous
  transfers.  The units are frames (milliseconds) for full and low
  speed devices, and microframes (1/8 millisecond) for highspeed
  and SuperSpeed devices.
- `error_count`: Returns the number of ISO transfers that reported errors.
- `context`: For use in completion functions.  This normally points to
  request-specific driver context.
- `complete`: Completion handler. This URB is passed as the parameter to the
  completion function.  The completion function may then do what
  it likes with the URB, including resubmitting or freeing it.
- `iso_frame_desc`: Used to provide arrays of ISO transfer buffers and to
  collect the transfer status for each buffer.

**Description**

This structure identifies USB transfer requests.  URBs must be allocated by
calling [`usb_alloc_urb()`](#c-usb_alloc_urb) and freed with a call to [`usb_free_urb()`](#c-usb_free_urb).
Initialization may be done using various usb_fill_*`_urb()` functions.  URBs
are submitted using [`usb_submit_urb()`](#c-usb_submit_urb), and pending requests may be canceled
using [`usb_unlink_urb()`](#c-usb_unlink_urb) or [`usb_kill_urb()`](#c-usb_kill_urb).

Data Transfer Buffers:

Normally drivers provide I/O buffers allocated with [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) or otherwise
taken from the general page pool.  That is provided by transfer_buffer
(control requests also use setup_packet), and host controller drivers
perform a dma mapping (and unmapping) for each buffer transferred.  Those
mapping operations can be expensive on some platforms (perhaps using a dma
bounce buffer or talking to an IOMMU),
although they're cheap on commodity x86 and ppc hardware.

Alternatively, drivers may pass the URB_NO_TRANSFER_DMA_MAP transfer flag,
which tells the host controller driver that no such mapping is needed for
the transfer_buffer since
the device driver is DMA-aware.  For example, a device driver might
allocate a DMA buffer with [`usb_alloc_coherent()`](#c-usb_alloc_coherent) or call `usb_buffer_map()`.
When this transfer flag is provided, host controller drivers will
attempt to use the dma address found in the transfer_dma
field rather than determining a dma address themselves.

Note that transfer_buffer must still be set if the controller
does not support DMA (as indicated by `hcd_uses_dma()`) and when talking
to root hub. If you have to transfer between highmem zone and the device
on such controller, create a bounce buffer or bail out with an error.
If transfer_buffer cannot be set (is in highmem) and the controller is DMA
capable, assign NULL to it, so that usbmon knows not to use the value.
The setup_packet must always be set, so it cannot be located in highmem.

Initialization:

All URBs submitted must initialize the dev, pipe, transfer_flags (may be
zero), and complete fields.  All URBs must also initialize
transfer_buffer and transfer_buffer_length.  They may provide the
URB_SHORT_NOT_OK transfer flag, indicating that short reads are
to be treated as errors; that flag is invalid for write requests.

Bulk URBs may
use the URB_ZERO_PACKET transfer flag, indicating that bulk OUT transfers
should always terminate with a short packet, even if it means adding an
extra zero length packet.

Control URBs must provide a valid pointer in the setup_packet field.
Unlike the transfer_buffer, the setup_packet may not be mapped for DMA
beforehand.

Interrupt URBs must provide an interval, saying how often (in milliseconds
or, for highspeed devices, 125 microsecond units)
to poll for transfers.  After the URB has been submitted, the interval
field reflects how the transfer was actually scheduled.
The polling interval may be more frequent than requested.
For example, some controllers have a maximum interval of 32 milliseconds,
while others support intervals of up to 1024 milliseconds.
Isochronous URBs also have transfer intervals.  (Note that for isochronous
endpoints, as well as high speed interrupt endpoints, the encoding of
the transfer interval in the endpoint descriptor is logarithmic.
Device drivers must convert that value to linear units themselves.)

If an isochronous endpoint queue isn't already running, the host
controller will schedule a new URB to start as soon as bandwidth
utilization allows.  If the queue is running then a new URB will be
scheduled to start in the first transfer slot following the end of the
preceding URB, if that slot has not already expired.  If the slot has
expired (which can happen when IRQ delivery is delayed for a long time),
the scheduling behavior depends on the URB_ISO_ASAP flag.  If the flag
is clear then the URB will be scheduled to start in the expired slot,
implying that some of its packets will not be transferred; if the flag
is set then the URB will be scheduled in the first unexpired slot,
breaking the queue's synchronization.  Upon URB completion, the
start_frame field will be set to the (micro)frame number in which the
transfer was scheduled.  Ranges for frame counter values are HC-specific
and can go from as low as 256 to as high as 65536 frames.

Isochronous URBs have a different data transfer model, in part because
the quality of service is only "best effort".  Callers provide specially
allocated URBs, with number_of_packets worth of iso_frame_desc structures
at the end.  Each such packet is an individual ISO transfer.  Isochronous
URBs are normally queued, submitted by drivers to arrange that
transfers are at least double buffered, and then explicitly resubmitted
in completion handlers, so
that data (such as audio or video) streams at as constant a rate as the
host controller scheduler can support.

Completion Callbacks:

The completion callback is made `in_interrupt()`, and one of the first
things that a completion handler should do is check the status field.
The status field is provided for all URBs.  It is used to report
unlinked URBs, and status for all non-ISO transfers.  It should not
be examined before the URB is returned to the completion handler.

The context field is normally used to link URBs back to the relevant
driver or request state.

When the completion callback is invoked for non-isochronous URBs, the
actual_length field tells how many bytes were transferred.  This field
is updated even when the URB terminated with an error or was unlinked.

ISO transfer status is reported in the status and actual_length fields
of the iso_frame_desc array, and the number of errors is reported in
error_count.  Completion callbacks for ISO transfers will normally
(re)submit URBs to ensure a constant transfer rate.

Note that even fields marked "public" should not be touched by the driver
when the urb is owned by the hcd, that is, since the call to
[`usb_submit_urb()`](#c-usb_submit_urb) till the entry into the completion routine.

#### <a id="c-usb_fill_control_urb"></a>`usb_fill_control_urb()`

```c
void usb_fill_control_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe, unsigned char *setup_packet, void *transfer_buffer, int buffer_length, usb_complete_t complete_fn, void *context)
```

initializes a control urb

**Parameters**

- `struct urb *urb`: pointer to the urb to initialize.
- `struct usb_device *dev`: pointer to the struct usb_device for this urb.
- `unsigned int pipe`: the endpoint pipe
- `unsigned char *setup_packet`: pointer to the setup_packet buffer. The buffer must be
  suitable for DMA.
- `void *transfer_buffer`: pointer to the transfer buffer. The buffer must be
  suitable for DMA.
- `int buffer_length`: length of the transfer buffer
- `usb_complete_t complete_fn`: pointer to the usb_complete_t function
- `void *context`: what to set the urb context to.

**Description**

Initializes a control urb with the proper information needed to submit
it to a device.

The transfer buffer and the setup_packet buffer will most likely be filled
or read via DMA. The simplest way to get a buffer that can be DMAed to is
allocating it via [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) or equivalent, even for very small buffers.
If the buffers are embedded in a bigger structure, there is a risk that
the buffer itself, the previous fields and/or the next fields are corrupted
due to cache incoherencies; or slowed down if they are evicted from the
cache. For more information, check [`struct urb`](#c-struct-urb).

#### <a id="c-usb_fill_bulk_urb"></a>`usb_fill_bulk_urb()`

```c
void usb_fill_bulk_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe, void *transfer_buffer, int buffer_length, usb_complete_t complete_fn, void *context)
```

macro to help initialize a bulk urb

**Parameters**

- `struct urb *urb`: pointer to the urb to initialize.
- `struct usb_device *dev`: pointer to the struct usb_device for this urb.
- `unsigned int pipe`: the endpoint pipe
- `void *transfer_buffer`: pointer to the transfer buffer. The buffer must be
  suitable for DMA.
- `int buffer_length`: length of the transfer buffer
- `usb_complete_t complete_fn`: pointer to the usb_complete_t function
- `void *context`: what to set the urb context to.

**Description**

Initializes a bulk urb with the proper information needed to submit it
to a device.

Refer to [`usb_fill_control_urb()`](#c-usb_fill_control_urb) for a description of the requirements for
transfer_buffer.

#### <a id="c-usb_fill_int_urb"></a>`usb_fill_int_urb()`

```c
void usb_fill_int_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe, void *transfer_buffer, int buffer_length, usb_complete_t complete_fn, void *context, int interval)
```

macro to help initialize a interrupt urb

**Parameters**

- `struct urb *urb`: pointer to the urb to initialize.
- `struct usb_device *dev`: pointer to the struct usb_device for this urb.
- `unsigned int pipe`: the endpoint pipe
- `void *transfer_buffer`: pointer to the transfer buffer. The buffer must be
  suitable for DMA.
- `int buffer_length`: length of the transfer buffer
- `usb_complete_t complete_fn`: pointer to the usb_complete_t function
- `void *context`: what to set the urb context to.
- `int interval`: what to set the urb interval to, encoded like
  the endpoint descriptor's bInterval value.

**Description**

Initializes a interrupt urb with the proper information needed to submit
it to a device.

Refer to [`usb_fill_control_urb()`](#c-usb_fill_control_urb) for a description of the requirements for
transfer_buffer.

Note that High Speed and SuperSpeed(+) interrupt endpoints use a logarithmic
encoding of the endpoint interval, and express polling intervals in
microframes (eight per millisecond) rather than in frames (one per
millisecond).

#### <a id="c-usb_urb_dir_in"></a>`usb_urb_dir_in()`

```c
int usb_urb_dir_in(struct urb *urb)
```

check if an URB describes an IN transfer

**Parameters**

- `struct urb *urb`: URB to be checked

**Return**

1 if **urb** describes an IN transfer (device-to-host),
otherwise 0.

#### <a id="c-usb_urb_dir_out"></a>`usb_urb_dir_out()`

```c
int usb_urb_dir_out(struct urb *urb)
```

check if an URB describes an OUT transfer

**Parameters**

- `struct urb *urb`: URB to be checked

**Return**

1 if **urb** describes an OUT transfer (host-to-device),
otherwise 0.

#### <a id="c-struct-usb_sg_request"></a>`struct usb_sg_request`

support for scatter/gather I/O

**Definition**

```c
struct usb_sg_request {
    int status;
    size_t bytes;
};
```

**Members**

- `status`: zero indicates success, else negative errno
- `bytes`: counts bytes transferred.

**Description**

These requests are initialized using [`usb_sg_init()`](#c-usb_sg_init), and then are used
as request handles passed to [`usb_sg_wait()`](#c-usb_sg_wait) or [`usb_sg_cancel()`](#c-usb_sg_cancel).  Most
members of the request object aren't for driver access.

The status and bytecount values are valid only after [`usb_sg_wait()`](#c-usb_sg_wait)
returns.  If the status is zero, then the bytecount matches the total
from the request.

After an error completion, drivers may need to clear a halt condition
on the endpoint.


<a id="rst-usb-core-apis"></a>

## USB Core APIs

There are two basic I/O models in the USB API. The most elemental one is asynchronous: drivers submit requests in the form of an URB, and the URB's completion callback handles the next step. All USB transfer types support that model, although there are special cases for control URBs (which always have setup and status stages, but may not have a data stage) and isochronous URBs (which allow large packets and include per-packet fault reports). Built on top of that is synchronous API support, where a driver calls a routine that allocates one or more URBs, submits them, and waits until they complete. There are synchronous wrappers for single-buffer control and bulk transfers (which are awkward to use in some driver disconnect scenarios), and for scatterlist based streaming i/o (bulk or interrupt).

USB drivers need to provide buffers that can be used for DMA, although they don't necessarily need to provide the DMA mapping themselves. There are APIs to use used when allocating DMA buffers, which can prevent use of bounce buffers on some systems. In some cases, drivers may be able to rely on 64bit DMA to eliminate another kind of bounce buffer.


#### <a id="c-usb_init_urb"></a>`usb_init_urb()`

```c
void usb_init_urb(struct urb *urb)
```

initializes a urb so that it can be used by a USB driver

**Parameters**

- `struct urb *urb`: pointer to the urb to initialize

**Description**

Initializes a urb so that the USB subsystem can use it properly.

If a urb is created with a call to [`usb_alloc_urb()`](#c-usb_alloc_urb) it is not
necessary to call this function.  Only use this if you allocate the
space for a struct urb on your own.  If you call this function, be
careful when freeing the memory for your urb that it is no longer in
use by the USB core.

Only use this function if you _really_ understand what you are doing.

#### <a id="c-usb_alloc_urb"></a>`usb_alloc_urb()`

```c
struct urb * usb_alloc_urb(int iso_packets, gfp_t mem_flags)
```

creates a new urb for a USB driver to use

**Parameters**

- `int iso_packets`: number of iso packets for this urb
- `gfp_t mem_flags`: the type of memory to allocate, see [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) for a list of
  valid options for this.

**Description**

Creates an urb for the USB driver to use, initializes a few internal
structures, increments the usage counter, and returns a pointer to it.

If the driver want to use this urb for interrupt, control, or bulk
endpoints, pass '0' as the number of iso packets.

The driver must call [`usb_free_urb()`](#c-usb_free_urb) when it is finished with the urb.

**Return**

A pointer to the new urb, or `NULL` if no memory is available.

#### <a id="c-usb_free_urb"></a>`usb_free_urb()`

```c
void usb_free_urb(struct urb *urb)
```

frees the memory used by a urb when all users of it are finished

**Parameters**

- `struct urb *urb`: pointer to the urb to free, may be NULL

**Description**

Must be called when a user of a urb is finished with it.  When the last user
of the urb calls this function, the memory of the urb is freed.

**Note**

The transfer buffer associated with the urb is not freed unless the
URB_FREE_BUFFER transfer flag is set.

#### <a id="c-usb_get_urb"></a>`usb_get_urb()`

```c
struct urb * usb_get_urb(struct urb *urb)
```

increments the reference count of the urb

**Parameters**

- `struct urb *urb`: pointer to the urb to modify, may be NULL

**Description**

This must be  called whenever a urb is transferred from a device driver to a
host controller driver.  This allows proper reference counting to happen
for urbs.

**Return**

A pointer to the urb with the incremented reference counter.

#### <a id="c-usb_anchor_urb"></a>`usb_anchor_urb()`

```c
void usb_anchor_urb(struct urb *urb, struct usb_anchor *anchor)
```

anchors an URB while it is processed

**Parameters**

- `struct urb *urb`: pointer to the urb to anchor
- `struct usb_anchor *anchor`: pointer to the anchor

**Description**

This can be called to have access to URBs which are to be executed
without bothering to track them

#### <a id="c-usb_unanchor_urb"></a>`usb_unanchor_urb()`

```c
void usb_unanchor_urb(struct urb *urb)
```

unanchors an URB

**Parameters**

- `struct urb *urb`: pointer to the urb to anchor

**Description**

Call this to stop the system keeping track of this URB

#### <a id="c-usb_pipe_type_check"></a>`usb_pipe_type_check()`

```c
int usb_pipe_type_check(struct usb_device *dev, unsigned int pipe)
```

sanity check of a specific pipe for a usb device

**Parameters**

- `struct usb_device *dev`: struct usb_device to be checked
- `unsigned int pipe`: pipe to check

**Description**

This performs a light-weight sanity check for the endpoint in the
given usb device.  It returns 0 if the pipe is valid for the specific usb
device, otherwise a negative error code.

#### <a id="c-usb_urb_ep_type_check"></a>`usb_urb_ep_type_check()`

```c
int usb_urb_ep_type_check(const struct urb *urb)
```

sanity check of endpoint in the given urb

**Parameters**

- `const struct urb *urb`: urb to be checked

**Description**

This performs a light-weight sanity check for the endpoint in the
given urb.  It returns 0 if the urb contains a valid endpoint, otherwise
a negative error code.

#### <a id="c-usb_submit_urb"></a>`usb_submit_urb()`

```c
int usb_submit_urb(struct urb *urb, gfp_t mem_flags)
```

issue an asynchronous transfer request for an endpoint

**Parameters**

- `struct urb *urb`: pointer to the urb describing the request
- `gfp_t mem_flags`: the type of memory to allocate, see [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) for a list
  of valid options for this.

**Description**

This submits a transfer request, and transfers control of the URB
describing that request to the USB subsystem.  Request completion will
be indicated later, asynchronously, by calling the completion handler.
The three types of completion are success, error, and unlink
(a software-induced fault, also called "request cancellation").

URBs may be submitted in interrupt context.

The caller must have correctly initialized the URB before submitting
it.  Functions such as [`usb_fill_bulk_urb()`](#c-usb_fill_bulk_urb) and [`usb_fill_control_urb()`](#c-usb_fill_control_urb) are
available to ensure that most fields are correctly initialized, for
the particular kind of transfer, although they will not initialize
any transfer flags.

If the submission is successful, the `complete()` callback from the URB
will be called exactly once, when the USB core and Host Controller Driver
(HCD) are finished with the URB.  When the completion function is called,
control of the URB is returned to the device driver which issued the
request.  The completion handler may then immediately free or reuse that
URB.

With few exceptions, USB device drivers should never access URB fields
provided by usbcore or the HCD until its `complete()` is called.
The exceptions relate to periodic transfer scheduling.  For both
interrupt and isochronous urbs, as part of successful URB submission
urb->interval is modified to reflect the actual transfer period used
(normally some power of two units).  And for isochronous urbs,
urb->start_frame is modified to reflect when the URB's transfers were
scheduled to start.

Not all isochronous transfer scheduling policies will work, but most
host controller drivers should easily handle ISO queues going from now
until 10-200 msec into the future.  Drivers should try to keep at
least one or two msec of data in the queue; many controllers require
that new transfers start at least 1 msec in the future when they are
added.  If the driver is unable to keep up and the queue empties out,
the behavior for new submissions is governed by the URB_ISO_ASAP flag.
If the flag is set, or if the queue is idle, then the URB is always
assigned to the first available (and not yet expired) slot in the
endpoint's schedule.  If the flag is not set and the queue is active
then the URB is always assigned to the next slot in the schedule
following the end of the endpoint's previous URB, even if that slot is
in the past.  When a packet is assigned in this way to a slot that has
already expired, the packet is not transmitted and the corresponding
usb_iso_packet_descriptor's status field will return -EXDEV.  If this
would happen to all the packets in the URB, submission fails with a
-EXDEV error code.

For control endpoints, the synchronous [`usb_control_msg()`](#c-usb_control_msg) call is
often used (in non-interrupt context) instead of this call.
That is often used through convenience wrappers, for the requests
that are standardized in the USB 2.0 specification.  For bulk
endpoints, a synchronous [`usb_bulk_msg()`](#c-usb_bulk_msg) call is available.

Request Queuing:

URBs may be submitted to endpoints before previous ones complete, to
minimize the impact of interrupt latencies and system overhead on data
throughput.  With that queuing policy, an endpoint's queue would never
be empty.  This is required for continuous isochronous data streams,
and may also be required for some kinds of interrupt transfers. Such
queuing also maximizes bandwidth utilization by letting USB controllers
start work on later requests before driver software has finished the
completion processing for earlier (successful) requests.

As of Linux 2.6, all USB endpoint transfer queues support depths greater
than one.  This was previously a HCD-specific behavior, except for ISO
transfers.  Non-isochronous endpoint queues are inactive during cleanup
after faults (transfer errors or cancellation).

Reserved Bandwidth Transfers:

Periodic transfers (interrupt or isochronous) are performed repeatedly,
using the interval specified in the urb.  Submitting the first urb to
the endpoint reserves the bandwidth necessary to make those transfers.
If the USB subsystem can't allocate sufficient bandwidth to perform
the periodic request, submitting such a periodic request should fail.

For devices under xHCI, the bandwidth is reserved at configuration time, or
when the alt setting is selected.  If there is not enough bus bandwidth, the
configuration/alt setting request will fail.  Therefore, submissions to
periodic endpoints on devices under xHCI should never fail due to bandwidth
constraints.

Device drivers must explicitly request that repetition, by ensuring that
some URB is always on the endpoint's queue (except possibly for short
periods during completion callbacks).  When there is no longer an urb
queued, the endpoint's bandwidth reservation is canceled.  This means
drivers can use their completion handlers to ensure they keep bandwidth
they need, by reinitializing and resubmitting the just-completed urb
until the driver longer needs that periodic bandwidth.

Memory Flags:

The general rules for how to decide which mem_flags to use
are the same as for kmalloc.  There are four
different possible values; GFP_KERNEL, GFP_NOFS, GFP_NOIO and
GFP_ATOMIC.

GFP_NOFS is not ever used, as it has not been implemented yet.

- GFP_ATOMIC is used when

  (a) you are inside a completion handler, an interrupt, bottom half,
  tasklet or timer, or
  (b) you are holding a spinlock or rwlock (does not apply to
  semaphores), or
  (c) current->state != TASK_RUNNING, this is the case only after
  you've changed it.

GFP_NOIO is used in the block io path and error handling of storage
devices.

All other situations use GFP_KERNEL.

- Some more specific rules for mem_flags can be inferred, such as

  (1) start_xmit, timeout, and receive methods of network drivers must
  use GFP_ATOMIC (they are called with a spinlock held);
  (2) queuecommand methods of scsi drivers must use GFP_ATOMIC (also
  called with a spinlock held);
  (3) If you use a kernel thread with a network driver you must use
  GFP_NOIO, unless (b) or (c) apply;
  (4) after you have done a `down()` you can use GFP_KERNEL, unless (b) or (c)
  apply or your are in a storage driver's block io path;
  (5) USB probe and disconnect can use GFP_KERNEL unless (b) or (c) apply; and
  (6) changing firmware on a running storage or net device uses
  GFP_NOIO, unless b) or c) apply

**Return**

0 on successful submissions. A negative error number otherwise.

#### <a id="c-usb_unlink_urb"></a>`usb_unlink_urb()`

```c
int usb_unlink_urb(struct urb *urb)
```

abort/cancel a transfer request for an endpoint

**Parameters**

- `struct urb *urb`: pointer to urb describing a previously submitted request,
  may be NULL

**Description**

This routine cancels an in-progress request.  URBs complete only once
per submission, and may be canceled only once per submission.
Successful cancellation means termination of **urb** will be expedited
and the completion handler will be called with a status code
indicating that the request has been canceled (rather than any other
code).

Drivers should not call this routine or related routines, such as
[`usb_kill_urb()`](#c-usb_kill_urb), after their disconnect method has returned. The
disconnect function should synchronize with a driver's I/O routines
to insure that all URB-related activity has completed before it returns.

This request is asynchronous, however the HCD might call the ->`complete()`
callback during unlink. Therefore when drivers call [`usb_unlink_urb()`](#c-usb_unlink_urb), they
must not hold any locks that may be taken by the completion function.
Success is indicated by returning -EINPROGRESS, at which time the URB will
probably not yet have been given back to the device driver. When it is
eventually called, the completion function will see **urb->status** ==
-ECONNRESET.
Failure is indicated by [`usb_unlink_urb()`](#c-usb_unlink_urb) returning any other value.
Unlinking will fail when **urb** is not currently "linked" (i.e., it was
never submitted, or it was unlinked before, or the hardware is already
finished with it), even if the completion handler has not yet run.

The URB must not be deallocated while this routine is running.  In
particular, when a driver calls this routine, it must insure that the
completion handler cannot deallocate the URB.

Unlinking and Endpoint Queues:

\[The behaviors and guarantees described below do not apply to virtual
root hubs but only to endpoint queues for physical USB devices.\]

Host Controller Drivers (HCDs) place all the URBs for a particular
endpoint in a queue.  Normally the queue advances as the controller
hardware processes each request.  But when an URB terminates with an
error its queue generally stops (see below), at least until that URB's
completion routine returns.  It is guaranteed that a stopped queue
will not restart until all its unlinked URBs have been fully retired,
with their completion routines run, even if that's not until some time
after the original completion handler returns.  The same behavior and
guarantee apply when an URB terminates because it was unlinked.

Bulk and interrupt endpoint queues are guaranteed to stop whenever an
URB terminates with any sort of error, including -ECONNRESET, -ENOENT,
and -EREMOTEIO.  Control endpoint queues behave the same way except
that they are not guaranteed to stop for -EREMOTEIO errors.  Queues
for isochronous endpoints are treated differently, because they must
advance at fixed rates.  Such queues do not stop when an URB
encounters an error or is unlinked.  An unlinked isochronous URB may
leave a gap in the stream of packets; it is undefined whether such
gaps can be filled in.

Note that early termination of an URB because a short packet was
received will generate a -EREMOTEIO error if and only if the
URB_SHORT_NOT_OK flag is set.  By setting this flag, USB device
drivers can build deep queues for large or complex bulk transfers
and clean them up reliably after any sort of aborted transfer by
unlinking all pending URBs at the first fault.

When a control URB terminates with an error other than -EREMOTEIO, it
is quite likely that the status stage of the transfer will not take
place.

**Return**

-EINPROGRESS on success. See description for other values on
failure.

#### <a id="c-usb_kill_urb"></a>`usb_kill_urb()`

```c
void usb_kill_urb(struct urb *urb)
```

cancel a transfer request and wait for it to finish

**Parameters**

- `struct urb *urb`: pointer to URB describing a previously submitted request,
  may be NULL

**Description**

This routine cancels an in-progress request.  It is guaranteed that
upon return all completion handlers will have finished and the URB
will be totally idle and available for reuse.  These features make
this an ideal way to stop I/O in a `disconnect()` callback or `close()`
function.  If the request has not already finished or been unlinked
the completion handler will see urb->status == -ENOENT.

While the routine is running, attempts to resubmit the URB will fail
with error -EPERM.  Thus even if the URB's completion handler always
tries to resubmit, it will not succeed and the URB will become idle.

The URB must not be deallocated while this routine is running.  In
particular, when a driver calls this routine, it must insure that the
completion handler cannot deallocate the URB.

This routine may not be used in an interrupt context (such as a bottom
half or a completion handler), or when holding a spinlock, or in other
situations where the caller can't `schedule()`.

This routine should not be called by a driver after its disconnect
method has returned.

#### <a id="c-usb_poison_urb"></a>`usb_poison_urb()`

```c
void usb_poison_urb(struct urb *urb)
```

reliably kill a transfer and prevent further use of an URB

**Parameters**

- `struct urb *urb`: pointer to URB describing a previously submitted request,
  may be NULL

**Description**

This routine cancels an in-progress request.  It is guaranteed that
upon return all completion handlers will have finished and the URB
will be totally idle and cannot be reused.  These features make
this an ideal way to stop I/O in a `disconnect()` callback.
If the request has not already finished or been unlinked
the completion handler will see urb->status == -ENOENT.

After and while the routine runs, attempts to resubmit the URB will fail
with error -EPERM.  Thus even if the URB's completion handler always
tries to resubmit, it will not succeed and the URB will become idle.

The URB must not be deallocated while this routine is running.  In
particular, when a driver calls this routine, it must insure that the
completion handler cannot deallocate the URB.

This routine may not be used in an interrupt context (such as a bottom
half or a completion handler), or when holding a spinlock, or in other
situations where the caller can't `schedule()`.

This routine should not be called by a driver after its disconnect
method has returned.

#### <a id="c-usb_block_urb"></a>`usb_block_urb()`

```c
void usb_block_urb(struct urb *urb)
```

reliably prevent further use of an URB

**Parameters**

- `struct urb *urb`: pointer to URB to be blocked, may be NULL

**Description**

After the routine has run, attempts to resubmit the URB will fail
with error -EPERM.  Thus even if the URB's completion handler always
tries to resubmit, it will not succeed and the URB will become idle.

The URB must not be deallocated while this routine is running.  In
particular, when a driver calls this routine, it must insure that the
completion handler cannot deallocate the URB.

#### <a id="c-usb_kill_anchored_urbs"></a>`usb_kill_anchored_urbs()`

```c
void usb_kill_anchored_urbs(struct usb_anchor *anchor)
```

kill all URBs associated with an anchor

**Parameters**

- `struct usb_anchor *anchor`: anchor the requests are bound to

**Description**

This kills all outstanding URBs starting from the back of the queue,
with guarantee that no completer callbacks will take place from the
anchor after this function returns.

This routine should not be called by a driver after its disconnect
method has returned.

#### <a id="c-usb_poison_anchored_urbs"></a>`usb_poison_anchored_urbs()`

```c
void usb_poison_anchored_urbs(struct usb_anchor *anchor)
```

cease all traffic from an anchor

**Parameters**

- `struct usb_anchor *anchor`: anchor the requests are bound to

**Description**

this allows all outstanding URBs to be poisoned starting
from the back of the queue. Newly added URBs will also be
poisoned

This routine should not be called by a driver after its disconnect
method has returned.

#### <a id="c-usb_unpoison_anchored_urbs"></a>`usb_unpoison_anchored_urbs()`

```c
void usb_unpoison_anchored_urbs(struct usb_anchor *anchor)
```

let an anchor be used successfully again

**Parameters**

- `struct usb_anchor *anchor`: anchor the requests are bound to

**Description**

Reverses the effect of usb_poison_anchored_urbs
the anchor can be used normally after it returns

#### <a id="c-usb_anchor_suspend_wakeups"></a>`usb_anchor_suspend_wakeups()`

```c
void usb_anchor_suspend_wakeups(struct usb_anchor *anchor)
```

**Parameters**

- `struct usb_anchor *anchor`: the anchor you want to suspend wakeups on

**Description**

Call this to stop the last urb being unanchored from waking up any
usb_wait_anchor_empty_timeout waiters. This is used in the hcd urb give-
back path to delay waking up until after the completion handler has run.

#### <a id="c-usb_anchor_resume_wakeups"></a>`usb_anchor_resume_wakeups()`

```c
void usb_anchor_resume_wakeups(struct usb_anchor *anchor)
```

**Parameters**

- `struct usb_anchor *anchor`: the anchor you want to resume wakeups on

**Description**

Allow usb_wait_anchor_empty_timeout waiters to be woken up again, and
wake up any current waiters if the anchor is empty.

#### <a id="c-usb_wait_anchor_empty_timeout"></a>`usb_wait_anchor_empty_timeout()`

```c
int usb_wait_anchor_empty_timeout(struct usb_anchor *anchor, unsigned int timeout)
```

wait for an anchor to be unused

**Parameters**

- `struct usb_anchor *anchor`: the anchor you want to become unused
- `unsigned int timeout`: how long you are willing to wait in milliseconds

**Description**

Call this is you want to be sure all an anchor's
URBs have finished

**Return**

Non-zero if the anchor became unused. Zero on timeout.

#### <a id="c-usb_get_from_anchor"></a>`usb_get_from_anchor()`

```c
struct urb * usb_get_from_anchor(struct usb_anchor *anchor)
```

get an anchor's oldest urb

**Parameters**

- `struct usb_anchor *anchor`: the anchor whose urb you want

**Description**

This will take the oldest urb from an anchor,
unanchor and return it

**Return**

The oldest urb from **anchor**, or `NULL` if **anchor** has no
urbs associated with it.

#### <a id="c-usb_scuttle_anchored_urbs"></a>`usb_scuttle_anchored_urbs()`

```c
void usb_scuttle_anchored_urbs(struct usb_anchor *anchor)
```

unanchor all an anchor's urbs

**Parameters**

- `struct usb_anchor *anchor`: the anchor whose urbs you want to unanchor

**Description**

use this to get rid of all an anchor's urbs

#### <a id="c-usb_anchor_empty"></a>`usb_anchor_empty()`

```c
int usb_anchor_empty(struct usb_anchor *anchor)
```

is an anchor empty

**Parameters**

- `struct usb_anchor *anchor`: the anchor you want to query

**Return**

1 if the anchor has no urbs associated with it.


<!-- c:namespace: usb_core -->


#### <a id="c-usb_control_msg"></a>`usb_control_msg()`

```c
int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *data, __u16 size, int timeout)
```

Builds a control urb, sends it off and waits for completion

**Parameters**

- `struct usb_device *dev`: pointer to the usb device to send the message to
- `unsigned int pipe`: endpoint "pipe" to send the message to
- `__u8 request`: USB message request value
- `__u8 requesttype`: USB message request type value
- `__u16 value`: USB message value
- `__u16 index`: USB message index value
- `void *data`: pointer to the data to send
- `__u16 size`: length in bytes of the data to send
- `int timeout`: time in msecs to wait for the message to complete before timing out

**Context**

task context, might sleep.

**Description**

This function sends a simple control message to a specified endpoint and
waits for the message to complete, or timeout.

Don't use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use [`usb_submit_urb()`](#c-usb_submit_urb). If a thread in your driver uses this call,
make sure your `disconnect()` method can wait for it to complete. Since you
don't have a handle on the URB used, you can't cancel the request.

**Return**

If successful, the number of bytes transferred. Otherwise, a negative
error number.

#### <a id="c-usb_control_msg_send"></a>`usb_control_msg_send()`

```c
int usb_control_msg_send(struct usb_device *dev, __u8 endpoint, __u8 request, __u8 requesttype, __u16 value, __u16 index, const void *driver_data, __u16 size, int timeout, gfp_t memflags)
```

Builds a control "send" message, sends it off and waits for completion

**Parameters**

- `struct usb_device *dev`: pointer to the usb device to send the message to
- `__u8 endpoint`: endpoint to send the message to
- `__u8 request`: USB message request value
- `__u8 requesttype`: USB message request type value
- `__u16 value`: USB message value
- `__u16 index`: USB message index value
- `const void *driver_data`: pointer to the data to send
- `__u16 size`: length in bytes of the data to send
- `int timeout`: time in msecs to wait for the message to complete before timing out
- `gfp_t memflags`: the flags for memory allocation for buffers

**Context**

!in_interrupt ()

**Description**

This function sends a control message to a specified endpoint that is not
expected to fill in a response (i.e. a "send message") and waits for the
message to complete, or timeout.

Do not use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use [`usb_submit_urb()`](#c-usb_submit_urb). If a thread in your driver uses this call,
make sure your `disconnect()` method can wait for it to complete. Since you
don't have a handle on the URB used, you can't cancel the request.

The data pointer can be made to a reference on the stack, or anywhere else,
as it will not be modified at all.  This does not have the restriction that
[`usb_control_msg()`](#c-usb_control_msg) has where the data pointer must be to dynamically allocated
memory (i.e. memory that can be successfully DMAed to a device).

**Return**

If successful, 0 is returned, Otherwise, a negative error number.

#### <a id="c-usb_control_msg_recv"></a>`usb_control_msg_recv()`

```c
int usb_control_msg_recv(struct usb_device *dev, __u8 endpoint, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *driver_data, __u16 size, int timeout, gfp_t memflags)
```

Builds a control "receive" message, sends it off and waits for completion

**Parameters**

- `struct usb_device *dev`: pointer to the usb device to send the message to
- `__u8 endpoint`: endpoint to send the message to
- `__u8 request`: USB message request value
- `__u8 requesttype`: USB message request type value
- `__u16 value`: USB message value
- `__u16 index`: USB message index value
- `void *driver_data`: pointer to the data to be filled in by the message
- `__u16 size`: length in bytes of the data to be received
- `int timeout`: time in msecs to wait for the message to complete before timing out
- `gfp_t memflags`: the flags for memory allocation for buffers

**Context**

!in_interrupt ()

**Description**

This function sends a control message to a specified endpoint that is
expected to fill in a response (i.e. a "receive message") and waits for the
message to complete, or timeout.

Do not use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use [`usb_submit_urb()`](#c-usb_submit_urb). If a thread in your driver uses this call,
make sure your `disconnect()` method can wait for it to complete. Since you
don't have a handle on the URB used, you can't cancel the request.

The data pointer can be made to a reference on the stack, or anywhere else
that can be successfully written to.  This function does not have the
restriction that [`usb_control_msg()`](#c-usb_control_msg) has where the data pointer must be to
dynamically allocated memory (i.e. memory that can be successfully DMAed to a
device).

The "whole" message must be properly received from the device in order for
this function to be successful.  If a device returns less than the expected
amount of data, then the function will fail.  Do not use this for messages
where a variable amount of data might be returned.

**Return**

If successful, 0 is returned, Otherwise, a negative error number.

#### <a id="c-usb_interrupt_msg"></a>`usb_interrupt_msg()`

```c
int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout)
```

Builds an interrupt urb, sends it off and waits for completion

**Parameters**

- `struct usb_device *usb_dev`: pointer to the usb device to send the message to
- `unsigned int pipe`: endpoint "pipe" to send the message to
- `void *data`: pointer to the data to send
- `int len`: length in bytes of the data to send
- `int *actual_length`: pointer to a location to put the actual length transferred
  in bytes
- `int timeout`: time in msecs to wait for the message to complete before timing out

**Context**

task context, might sleep.

**Description**

This function sends a simple interrupt message to a specified endpoint and
waits for the message to complete, or timeout.

Don't use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use [`usb_submit_urb()`](#c-usb_submit_urb) If a thread in your driver uses this call,
make sure your `disconnect()` method can wait for it to complete. Since you
don't have a handle on the URB used, you can't cancel the request.

**Return**

If successful, 0. Otherwise a negative error number. The number of actual
bytes transferred will be stored in the **actual_length** parameter.

#### <a id="c-usb_bulk_msg"></a>`usb_bulk_msg()`

```c
int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout)
```

Builds a bulk urb, sends it off and waits for completion

**Parameters**

- `struct usb_device *usb_dev`: pointer to the usb device to send the message to
- `unsigned int pipe`: endpoint "pipe" to send the message to
- `void *data`: pointer to the data to send
- `int len`: length in bytes of the data to send
- `int *actual_length`: pointer to a location to put the actual length transferred
  in bytes
- `int timeout`: time in msecs to wait for the message to complete before timing out

**Context**

task context, might sleep.

**Description**

This function sends a simple bulk message to a specified endpoint
and waits for the message to complete, or timeout.

Don't use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use [`usb_submit_urb()`](#c-usb_submit_urb) If a thread in your driver uses this call,
make sure your `disconnect()` method can wait for it to complete. Since you
don't have a handle on the URB used, you can't cancel the request.

Because there is no [`usb_interrupt_msg()`](#c-usb_interrupt_msg) and no USBDEVFS_INTERRUPT ioctl,
users are forced to abuse this routine by using it to submit URBs for
interrupt endpoints.  We will take the liberty of creating an interrupt URB
(with the default interval) if the target is an interrupt endpoint.

**Return**

If successful, 0. Otherwise a negative error number. The number of actual
bytes transferred will be stored in the **actual_length** parameter.

#### <a id="c-usb_bulk_msg_killable"></a>`usb_bulk_msg_killable()`

```c
int usb_bulk_msg_killable(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout)
```

Builds a bulk urb, sends it off and waits for completion in a killable state

**Parameters**

- `struct usb_device *usb_dev`: pointer to the usb device to send the message to
- `unsigned int pipe`: endpoint "pipe" to send the message to
- `void *data`: pointer to the data to send
- `int len`: length in bytes of the data to send
- `int *actual_length`: pointer to a location to put the actual length transferred
  in bytes
- `int timeout`: time in msecs to wait for the message to complete before
  timing out (if \<= 0, the wait is as long as possible)

**Context**

task context, might sleep.

**Description**

This function is just like `usb_blk_msg()`, except that it waits in a
killable state and there is no limit on the timeout length.

**Return**

If successful, 0. Otherwise a negative error number. The number of actual
bytes transferred will be stored in the **actual_length** parameter.

#### <a id="c-usb_sg_init"></a>`usb_sg_init()`

```c
int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev, unsigned pipe, unsigned period, struct scatterlist *sg, int nents, size_t length, gfp_t mem_flags)
```

initializes scatterlist-based bulk/interrupt I/O request

**Parameters**

- `struct usb_sg_request *io`: request block being initialized.  until [`usb_sg_wait()`](#c-usb_sg_wait) returns,
  treat this as a pointer to an opaque block of memory,
- `struct usb_device *dev`: the usb device that will send or receive the data
- `unsigned pipe`: endpoint "pipe" used to transfer the data
- `unsigned period`: polling rate for interrupt endpoints, in frames or
  (for high speed endpoints) microframes; ignored for bulk
- `struct scatterlist *sg`: scatterlist entries
- `int nents`: how many entries in the scatterlist
- `size_t length`: how many bytes to send from the scatterlist, or zero to
  send every byte identified in the list.
- `gfp_t mem_flags`: SLAB_* flags affecting memory allocations in this call

**Description**

This initializes a scatter/gather request, allocating resources such as
I/O mappings and urb memory (except maybe memory used by USB controller
drivers).

The request must be issued using [`usb_sg_wait()`](#c-usb_sg_wait), which waits for the I/O to
complete (or to be canceled) and then cleans up all resources allocated by
[`usb_sg_init()`](#c-usb_sg_init).

The request may be canceled with [`usb_sg_cancel()`](#c-usb_sg_cancel), either before or after
[`usb_sg_wait()`](#c-usb_sg_wait) is called.

**Return**

Zero for success, else a negative errno value.

#### <a id="c-usb_sg_wait"></a>`usb_sg_wait()`

```c
void usb_sg_wait(struct usb_sg_request *io)
```

synchronously execute scatter/gather request

**Parameters**

- `struct usb_sg_request *io`: request block handle, as initialized with [`usb_sg_init()`](#c-usb_sg_init).
  some fields become accessible when this call returns.

**Context**

task context, might sleep.

**Description**

This function blocks until the specified I/O operation completes.  It
leverages the grouping of the related I/O requests to get good transfer
rates, by queueing the requests.  At higher speeds, such queuing can
significantly improve USB throughput.

There are three kinds of completion for this function.

- (1) success, where io->status is zero.  The number of io->bytes

  transferred is as requested.
- (2) error, where io->status is a negative errno value.  The number

  of io->bytes transferred before the error is usually less
  than requested, and can be nonzero.
- (3) cancellation, a type of error with status -ECONNRESET that

  is initiated by [`usb_sg_cancel()`](#c-usb_sg_cancel).

When this function returns, all memory allocated through [`usb_sg_init()`](#c-usb_sg_init) or
this call will have been freed.  The request block parameter may still be
passed to [`usb_sg_cancel()`](#c-usb_sg_cancel), or it may be freed.  It could also be
reinitialized and then reused.

Data Transfer Rates:

Bulk transfers are valid for full or high speed endpoints.
The best full speed data rate is 19 packets of 64 bytes each
per frame, or 1216 bytes per millisecond.
The best high speed data rate is 13 packets of 512 bytes each
per microframe, or 52 KBytes per millisecond.

The reason to use interrupt transfers through this API would most likely
be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
could be transferred.  That capability is less useful for low or full
speed interrupt endpoints, which allow at most one packet per millisecond,
of at most 8 or 64 bytes (respectively).

It is not necessary to call this function to reserve bandwidth for devices
under an xHCI host controller, as the bandwidth is reserved when the
configuration or interface alt setting is selected.

#### <a id="c-usb_sg_cancel"></a>`usb_sg_cancel()`

```c
void usb_sg_cancel(struct usb_sg_request *io)
```

stop scatter/gather i/o issued by [`usb_sg_wait()`](#c-usb_sg_wait)

**Parameters**

- `struct usb_sg_request *io`: request block, initialized with [`usb_sg_init()`](#c-usb_sg_init)

**Description**

This stops a request after it has been started by [`usb_sg_wait()`](#c-usb_sg_wait).
It can also prevents one initialized by [`usb_sg_init()`](#c-usb_sg_init) from starting,
so that call just frees resources allocated to the request.

#### <a id="c-usb_get_descriptor"></a>`usb_get_descriptor()`

```c
int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
```

issues a generic GET_DESCRIPTOR request

**Parameters**

- `struct usb_device *dev`: the device whose descriptor is being retrieved
- `unsigned char type`: the descriptor type (USB_DT_*)
- `unsigned char index`: the number of the descriptor
- `void *buf`: where to put the descriptor
- `int size`: how big is "buf"?

**Context**

task context, might sleep.

**Description**

Gets a USB descriptor.  Convenience functions exist to simplify
getting some types of descriptors.  Use
`usb_get_string()` or [`usb_string()`](#c-usb_string) for USB_DT_STRING.
Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
are part of the device structure.
In addition to a number of USB-standard descriptors, some
devices also use class-specific or vendor-specific descriptors.

This call is synchronous, and may not be used in an interrupt context.

**Return**

The number of bytes received on success, or else the status code
returned by the underlying [`usb_control_msg()`](#c-usb_control_msg) call.

#### <a id="c-usb_string"></a>`usb_string()`

```c
int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
```

returns UTF-8 version of a string descriptor

**Parameters**

- `struct usb_device *dev`: the device whose string descriptor is being retrieved
- `int index`: the number of the descriptor
- `char *buf`: where to put the string
- `size_t size`: how big is "buf"?

**Context**

task context, might sleep.

**Description**

This converts the UTF-16LE encoded strings returned by devices, from
`usb_get_string_descriptor()`, to null-terminated UTF-8 encoded ones
that are more usable in most kernel contexts.  Note that this function
chooses strings in the first language supported by the device.

This call is synchronous, and may not be used in an interrupt context.

**Return**

length of the string (>= 0) or usb_control_msg status (\< 0).

#### <a id="c-usb_cache_string"></a>`usb_cache_string()`

```c
char * usb_cache_string(struct usb_device *udev, int index)
```

read a string descriptor and cache it for later use

**Parameters**

- `struct usb_device *udev`: the device whose string descriptor is being read
- `int index`: the descriptor index

**Return**

A pointer to a kmalloc'ed buffer containing the descriptor string,
or `NULL` if the index is 0 or the string could not be read.

#### <a id="c-usb_get_status"></a>`usb_get_status()`

```c
int usb_get_status(struct usb_device *dev, int recip, int type, int target, void *data)
```

issues a GET_STATUS call

**Parameters**

- `struct usb_device *dev`: the device whose status is being checked
- `int recip`: USB_RECIP_*; for device, interface, or endpoint
- `int type`: USB_STATUS_TYPE_*; for standard or PTM status types
- `int target`: zero (for device), else interface or endpoint number
- `void *data`: pointer to two bytes of bitmap data

**Context**

task context, might sleep.

**Description**

Returns device, interface, or endpoint status.  Normally only of
interest to see if the device is self powered, or has enabled the
remote wakeup facility; or whether a bulk or interrupt endpoint
is halted ("stalled").

Bits in these status bitmaps are set using the SET_FEATURE request,
and cleared using the CLEAR_FEATURE request.  The [`usb_clear_halt()`](#c-usb_clear_halt)
function should be used to clear halt ("stall") status.

This call is synchronous, and may not be used in an interrupt context.

Returns 0 and the status value in **\*data** (in host byte order) on success,
or else the status code from the underlying [`usb_control_msg()`](#c-usb_control_msg) call.

#### <a id="c-usb_clear_halt"></a>`usb_clear_halt()`

```c
int usb_clear_halt(struct usb_device *dev, int pipe)
```

tells device to clear endpoint halt/stall condition

**Parameters**

- `struct usb_device *dev`: device whose endpoint is halted
- `int pipe`: endpoint "pipe" being cleared

**Context**

task context, might sleep.

**Description**

This is used to clear halt conditions for bulk and interrupt endpoints,
as reported by URB completion status.  Endpoints that are halted are
sometimes referred to as being "stalled".  Such endpoints are unable
to transmit or receive data until the halt status is cleared.  Any URBs
queued for such an endpoint should normally be unlinked by the driver
before clearing the halt condition, as described in sections 5.7.5
and 5.8.5 of the USB 2.0 spec.

Note that control and isochronous endpoints don't halt, although control
endpoints report "protocol stall" (for unsupported requests) using the
same status code used to report a true stall.

This call is synchronous, and may not be used in an interrupt context.
If a thread in your driver uses this call, make sure your `disconnect()`
method can wait for it to complete.

**Return**

Zero on success, or else the status code returned by the
underlying [`usb_control_msg()`](#c-usb_control_msg) call.

#### <a id="c-usb_reset_endpoint"></a>`usb_reset_endpoint()`

```c
void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
```

Reset an endpoint's state.

**Parameters**

- `struct usb_device *dev`: the device whose endpoint is to be reset
- `unsigned int epaddr`: the endpoint's address.  Endpoint number for output,
  endpoint number + USB_DIR_IN for input

**Description**

Resets any host-side endpoint state such as the toggle bit,
sequence number or current window.

#### <a id="c-usb_set_interface"></a>`usb_set_interface()`

```c
int usb_set_interface(struct usb_device *dev, int interface, int alternate)
```

Makes a particular alternate setting be current

**Parameters**

- `struct usb_device *dev`: the device whose interface is being updated
- `int interface`: the interface being updated
- `int alternate`: the setting being chosen.

**Context**

task context, might sleep.

**Description**

This is used to enable data transfers on interfaces that may not
be enabled by default.  Not all devices support such configurability.
Only the driver bound to an interface may change its setting.

Within any given configuration, each interface may have several
alternative settings.  These are often used to control levels of
bandwidth consumption.  For example, the default setting for a high
speed interrupt endpoint may not send more than 64 bytes per microframe,
while interrupt transfers of up to 3KBytes per microframe are legal.
Also, isochronous endpoints may never be part of an
interface's default setting.  To access such bandwidth, alternate
interface settings must be made current.

Note that in the Linux USB subsystem, bandwidth associated with
an endpoint in a given alternate setting is not reserved until an URB
is submitted that needs that bandwidth.  Some other operating systems
allocate bandwidth early, when a configuration is chosen.

xHCI reserves bandwidth and configures the alternate setting in
`usb_hcd_alloc_bandwidth()`. If it fails the original interface altsetting
may be disabled. Drivers cannot rely on any particular alternate
setting being in effect after a failure.

This call is synchronous, and may not be used in an interrupt context.
Also, drivers must not change altsettings while urbs are scheduled for
endpoints in that interface; all such urbs must first be completed
(perhaps forced by unlinking). If a thread in your driver uses this call,
make sure your `disconnect()` method can wait for it to complete.

**Return**

Zero on success, or else the status code returned by the
underlying [`usb_control_msg()`](#c-usb_control_msg) call.

#### <a id="c-usb_reset_configuration"></a>`usb_reset_configuration()`

```c
int usb_reset_configuration(struct usb_device *dev)
```

lightweight device reset

**Parameters**

- `struct usb_device *dev`: the device whose configuration is being reset

**Description**

This issues a standard SET_CONFIGURATION request to the device using
the current configuration.  The effect is to reset most USB-related
state in the device, including interface altsettings (reset to zero),
endpoint halts (cleared), and endpoint state (only for bulk and interrupt
endpoints).  Other usbcore state is unchanged, including bindings of
usb device drivers to interfaces.

Because this affects multiple interfaces, avoid using this with composite
(multi-interface) devices.  Instead, the driver for each interface may
use [`usb_set_interface()`](#c-usb_set_interface) on the interfaces it claims.  Be careful though;
some devices don't support the SET_INTERFACE request, and others won't
reset all the interface state (notably endpoint state).  Resetting the whole
configuration would affect other drivers' interfaces.

The caller must own the device lock.

If this routine fails the device will probably be in an unusable state
with endpoints disabled, and interfaces only partially enabled.

**Return**

Zero on success, else a negative error code.

#### <a id="c-usb_set_wireless_status"></a>`usb_set_wireless_status()`

```c
int usb_set_wireless_status(struct usb_interface *iface, enum usb_wireless_status status)
```

sets the wireless_status struct member

**Parameters**

- `struct usb_interface *iface`: the interface to modify
- `enum usb_wireless_status status`: the new wireless status

**Description**

Set the wireless_status struct member to the new value, and emit
sysfs changes as necessary.

**Return**

0 on success, -EALREADY if already set.

#### <a id="c-usb_driver_set_configuration"></a>`usb_driver_set_configuration()`

```c
int usb_driver_set_configuration(struct usb_device *udev, int config)
```

Provide a way for drivers to change device configurations

**Parameters**

- `struct usb_device *udev`: the device whose configuration is being updated
- `int config`: the configuration being chosen.

**Context**

In process context, must be able to sleep

**Description**

Device interface drivers are not allowed to change device configurations.
This is because changing configurations will destroy the interface the
driver is bound to and create new ones; it would be like a floppy-disk
driver telling the computer to replace the floppy-disk drive with a
tape drive!

Still, in certain specialized circumstances the need may arise.  This
routine gets around the normal restrictions by using a work thread to
submit the change-config request.

**Return**

0 if the request was successfully queued, error code otherwise.
The caller has no way to know whether the queued request will eventually
succeed.

#### <a id="c-cdc_parse_cdc_header"></a>`cdc_parse_cdc_header()`

```c
int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen)
```

parse the extra headers present in CDC devices

**Parameters**

- `struct usb_cdc_parsed_header *hdr`: the place to put the results of the parsing
- `struct usb_interface *intf`: the interface for which parsing is requested
- `u8 *buffer`: pointer to the extra headers to be parsed
- `int buflen`: length of the extra headers

**Description**

This evaluates the extra headers present in CDC devices which
bind the interfaces for data and control and provide details
about the capabilities of the device.

**Return**

number of descriptors parsed or -EINVAL
if the header is contradictory beyond salvage



#### <a id="c-usb_register_dev"></a>`usb_register_dev()`

```c
int usb_register_dev(struct usb_interface *intf, struct usb_class_driver *class_driver)
```

register a USB device, and ask for a minor number

**Parameters**

- `struct usb_interface *intf`: pointer to the usb_interface that is being registered
- `struct usb_class_driver *class_driver`: pointer to the usb_class_driver for this device

**Description**

This should be called by all USB drivers that use the USB major number.
If CONFIG_USB_DYNAMIC_MINORS is enabled, the minor number will be
dynamically allocated out of the list of available ones.  If it is not
enabled, the minor number will be based on the next available free minor,
starting at the class_driver->minor_base.

This function also creates a usb class device in the sysfs tree.

[`usb_deregister_dev()`](#c-usb_deregister_dev) must be called when the driver is done with
the minor numbers given out by this function.

**Return**

-EINVAL if something bad happens with trying to register a
device, and 0 on success.

#### <a id="c-usb_deregister_dev"></a>`usb_deregister_dev()`

```c
void usb_deregister_dev(struct usb_interface *intf, struct usb_class_driver *class_driver)
```

deregister a USB device's dynamic minor.

**Parameters**

- `struct usb_interface *intf`: pointer to the usb_interface that is being deregistered
- `struct usb_class_driver *class_driver`: pointer to the usb_class_driver for this device

**Description**

Used in conjunction with [`usb_register_dev()`](#c-usb_register_dev).  This function is called
when the USB driver is finished with the minor numbers gotten from a
call to [`usb_register_dev()`](#c-usb_register_dev) (usually when the device is disconnected
from the system.)

This function also removes the usb class device from the sysfs tree.

This should be called by all drivers that use the USB major number.



#### <a id="c-usb_driver_claim_interface"></a>`usb_driver_claim_interface()`

```c
int usb_driver_claim_interface(struct usb_driver *driver, struct usb_interface *iface, void *data)
```

bind a driver to an interface

**Parameters**

- `struct usb_driver *driver`: the driver to be bound
- `struct usb_interface *iface`: the interface to which it will be bound; must be in the
  usb device's active configuration
- `void *data`: driver data associated with that interface

**Description**

This is used by usb device drivers that need to claim more than one
interface on a device when probing (audio and acm are current examples).
No device driver should directly modify internal usb_interface or
usb_device structure members.

Callers must own the device lock, so driver `probe()` entries don't need
extra locking, but other call contexts may need to explicitly claim that
lock.

**Return**

0 on success.

#### <a id="c-usb_driver_release_interface"></a>`usb_driver_release_interface()`

```c
void usb_driver_release_interface(struct usb_driver *driver, struct usb_interface *iface)
```

unbind a driver from an interface

**Parameters**

- `struct usb_driver *driver`: the driver to be unbound
- `struct usb_interface *iface`: the interface from which it will be unbound

**Description**

This can be used by drivers to release an interface without waiting
for their `disconnect()` methods to be called.  In typical cases this
also causes the driver `disconnect()` method to be called.

This call is synchronous, and may not be used in an interrupt context.
Callers must own the device lock, so driver `disconnect()` entries don't
need extra locking, but other call contexts may need to explicitly claim
that lock.

#### <a id="c-usb_match_id"></a>`usb_match_id()`

```c
const struct usb_device_id * usb_match_id(struct usb_interface *interface, const struct usb_device_id *id)
```

find first usb_device_id matching device or interface

**Parameters**

- `struct usb_interface *interface`: the interface of interest
- `const struct usb_device_id *id`: array of usb_device_id structures, terminated by zero entry

**Description**

usb_match_id searches an array of usb_device_id's and returns
the first one matching the device or interface, or null.
This is used when binding (or rebinding) a driver to an interface.
Most USB device drivers will use this indirectly, through the usb core,
but some layered driver frameworks use it directly.
These device tables are exported with MODULE_DEVICE_TABLE, through
modutils, to support the driver loading functionality of USB hotplugging.

What Matches:

The "match_flags" element in a usb_device_id controls which
members are used.  If the corresponding bit is set, the
value in the device_id must match its corresponding member
in the device or interface descriptor, or else the device_id
does not match.

"driver_info" is normally used only by device drivers,
but you can create a wildcard "matches anything" usb_device_id
as a driver's "modules.usbmap" entry if you provide an id with
only a nonzero "driver_info" field.  If you do this, the USB device
driver's `probe()` routine should use additional intelligence to
decide whether to bind to the specified interface.

What Makes Good usb_device_id Tables:

The match algorithm is very simple, so that intelligence in
driver selection must come from smart driver id records.
Unless you have good reasons to use another selection policy,
provide match elements only in related groups, and order match
specifiers from specific to general.  Use the macros provided
for that purpose if you can.

The most specific match specifiers use device descriptor
data.  These are commonly used with product-specific matches;
the USB_DEVICE macro lets you provide vendor and product IDs,
and you can also match against ranges of product revisions.
These are widely used for devices with application or vendor
specific bDeviceClass values.

Matches based on device class/subclass/protocol specifications
are slightly more general; use the USB_DEVICE_INFO macro, or
its siblings.  These are used with single-function devices
where bDeviceClass doesn't specify that each interface has
its own class.

Matches based on interface class/subclass/protocol are the
most general; they let drivers bind to any interface on a
multiple-function device.  Use the USB_INTERFACE_INFO
macro, or its siblings, to match class-per-interface style
devices (as recorded in bInterfaceClass).

Note that an entry created by USB_INTERFACE_INFO won't match
any interface if the device class is set to Vendor-Specific.
This is deliberate; according to the USB spec the meanings of
the interface class/subclass/protocol for these devices are also
vendor-specific, and hence matching against a standard product
class wouldn't work anyway.  If you really want to use an
interface-based match for such a device, create a match record
that also specifies the vendor ID.  (Unforunately there isn't a
standard macro for creating records like this.)

Within those groups, remember that not all combinations are
meaningful.  For example, don't give a product version range
without vendor and product IDs; or specify a protocol without
its associated class and subclass.

**Return**

The first matching usb_device_id, or `NULL`.

#### <a id="c-usb_register_device_driver"></a>`usb_register_device_driver()`

```c
int usb_register_device_driver(struct usb_device_driver *new_udriver, struct module *owner)
```

register a USB device (not interface) driver

**Parameters**

- `struct usb_device_driver *new_udriver`: USB operations for the device driver
- `struct module *owner`: module owner of this driver.

**Description**

Registers a USB device driver with the USB core.  The list of
unattached devices will be rescanned whenever a new driver is
added, allowing the new driver to attach to any recognized devices.

**Return**

A negative error code on failure and 0 on success.

#### <a id="c-usb_deregister_device_driver"></a>`usb_deregister_device_driver()`

```c
void usb_deregister_device_driver(struct usb_device_driver *udriver)
```

unregister a USB device (not interface) driver

**Parameters**

- `struct usb_device_driver *udriver`: USB operations of the device driver to unregister

**Context**

must be able to sleep

**Description**

Unlinks the specified driver from the internal USB driver list.

#### <a id="c-usb_register_driver"></a>`usb_register_driver()`

```c
int usb_register_driver(struct usb_driver *new_driver, struct module *owner, const char *mod_name)
```

register a USB interface driver

**Parameters**

- `struct usb_driver *new_driver`: USB operations for the interface driver
- `struct module *owner`: module owner of this driver.
- `const char *mod_name`: module name string

**Description**

Registers a USB interface driver with the USB core.  The list of
unattached interfaces will be rescanned whenever a new driver is
added, allowing the new driver to attach to any recognized interfaces.

**Return**

A negative error code on failure and 0 on success.

**NOTE**

if you want your driver to use the USB major number, you must call
[`usb_register_dev()`](#c-usb_register_dev) to enable that functionality.  This function no longer
takes care of that.

#### <a id="c-usb_deregister"></a>`usb_deregister()`

```c
void usb_deregister(struct usb_driver *driver)
```

unregister a USB interface driver

**Parameters**

- `struct usb_driver *driver`: USB operations of the interface driver to unregister

**Context**

must be able to sleep

**Description**

Unlinks the specified driver from the internal USB driver list.

**NOTE**

If you called [`usb_register_dev()`](#c-usb_register_dev), you still need to call
[`usb_deregister_dev()`](#c-usb_deregister_dev) to clean up your driver's allocated minor numbers,
this * call will no longer do it for you.

#### <a id="c-usb_enable_autosuspend"></a>`usb_enable_autosuspend()`

```c
void usb_enable_autosuspend(struct usb_device *udev)
```

allow a USB device to be autosuspended

**Parameters**

- `struct usb_device *udev`: the USB device which may be autosuspended

**Description**

This routine allows **udev** to be autosuspended.  An autosuspend won't
take place until the autosuspend_delay has elapsed and all the other
necessary conditions are satisfied.

The caller must hold **udev**'s device lock.

#### <a id="c-usb_disable_autosuspend"></a>`usb_disable_autosuspend()`

```c
void usb_disable_autosuspend(struct usb_device *udev)
```

prevent a USB device from being autosuspended

**Parameters**

- `struct usb_device *udev`: the USB device which may not be autosuspended

**Description**

This routine prevents **udev** from being autosuspended and wakes it up
if it is already autosuspended.

The caller must hold **udev**'s device lock.

#### <a id="c-usb_autopm_put_interface"></a>`usb_autopm_put_interface()`

```c
void usb_autopm_put_interface(struct usb_interface *intf)
```

decrement a USB interface's PM-usage counter

**Parameters**

- `struct usb_interface *intf`: the usb_interface whose counter should be decremented

**Description**

This routine should be called by an interface driver when it is
finished using **intf** and wants to allow it to autosuspend.  A typical
example would be a character-device driver when its device file is
closed.

The routine decrements **intf**'s usage counter.  When the counter reaches
0, a delayed autosuspend request for **intf**'s device is attempted.  The
attempt may fail (see `autosuspend_check()`).

This routine can run only in process context.

#### <a id="c-usb_autopm_put_interface_async"></a>`usb_autopm_put_interface_async()`

```c
void usb_autopm_put_interface_async(struct usb_interface *intf)
```

decrement a USB interface's PM-usage counter

**Parameters**

- `struct usb_interface *intf`: the usb_interface whose counter should be decremented

**Description**

This routine does much the same thing as [`usb_autopm_put_interface()`](#c-usb_autopm_put_interface):
It decrements **intf**'s usage counter and schedules a delayed
autosuspend request if the counter is \<= 0.  The difference is that it
does not perform any synchronization; callers should hold a private
lock and handle all synchronization issues themselves.

Typically a driver would call this routine during an URB's completion
handler, if no more URBs were pending.

This routine can run in atomic context.

#### <a id="c-usb_autopm_put_interface_no_suspend"></a>`usb_autopm_put_interface_no_suspend()`

```c
void usb_autopm_put_interface_no_suspend(struct usb_interface *intf)
```

decrement a USB interface's PM-usage counter

**Parameters**

- `struct usb_interface *intf`: the usb_interface whose counter should be decremented

**Description**

This routine decrements **intf**'s usage counter but does not carry out an
autosuspend.

This routine can run in atomic context.

#### <a id="c-usb_autopm_get_interface"></a>`usb_autopm_get_interface()`

```c
int usb_autopm_get_interface(struct usb_interface *intf)
```

increment a USB interface's PM-usage counter

**Parameters**

- `struct usb_interface *intf`: the usb_interface whose counter should be incremented

**Description**

This routine should be called by an interface driver when it wants to
use **intf** and needs to guarantee that it is not suspended.  In addition,
the routine prevents **intf** from being autosuspended subsequently.  (Note
that this will not prevent suspend events originating in the PM core.)
This prevention will persist until [`usb_autopm_put_interface()`](#c-usb_autopm_put_interface) is called
or **intf** is unbound.  A typical example would be a character-device
driver when its device file is opened.

**intf**'s usage counter is incremented to prevent subsequent autosuspends.
However if the autoresume fails then the counter is re-decremented.

This routine can run only in process context.

**Return**

0 on success.

#### <a id="c-usb_autopm_get_interface_async"></a>`usb_autopm_get_interface_async()`

```c
int usb_autopm_get_interface_async(struct usb_interface *intf)
```

increment a USB interface's PM-usage counter

**Parameters**

- `struct usb_interface *intf`: the usb_interface whose counter should be incremented

**Description**

This routine does much the same thing as
[`usb_autopm_get_interface()`](#c-usb_autopm_get_interface): It increments **intf**'s usage counter and
queues an autoresume request if the device is suspended.  The
differences are that it does not perform any synchronization (callers
should hold a private lock and handle all synchronization issues
themselves), and it does not autoresume the device directly (it only
queues a request).  After a successful call, the device may not yet be
resumed.

This routine can run in atomic context.

**Return**

0 on success. A negative error code otherwise.

#### <a id="c-usb_autopm_get_interface_no_resume"></a>`usb_autopm_get_interface_no_resume()`

```c
void usb_autopm_get_interface_no_resume(struct usb_interface *intf)
```

increment a USB interface's PM-usage counter

**Parameters**

- `struct usb_interface *intf`: the usb_interface whose counter should be incremented

**Description**

This routine increments **intf**'s usage counter but does not carry out an
autoresume.

This routine can run in atomic context.



#### <a id="c-usb_find_common_endpoints"></a>`usb_find_common_endpoints()`

```c
int usb_find_common_endpoints(struct usb_host_interface *alt, struct usb_endpoint_descriptor **bulk_in, struct usb_endpoint_descriptor **bulk_out, struct usb_endpoint_descriptor **int_in, struct usb_endpoint_descriptor **int_out)
```

- look up common endpoint descriptors

**Parameters**

- `struct usb_host_interface *alt`: alternate setting to search
- `struct usb_endpoint_descriptor **bulk_in`: pointer to descriptor pointer, or NULL
- `struct usb_endpoint_descriptor **bulk_out`: pointer to descriptor pointer, or NULL
- `struct usb_endpoint_descriptor **int_in`: pointer to descriptor pointer, or NULL
- `struct usb_endpoint_descriptor **int_out`: pointer to descriptor pointer, or NULL

**Description**

Search the alternate setting's endpoint descriptors for the first bulk-in,
bulk-out, interrupt-in and interrupt-out endpoints and return them in the
provided pointers (unless they are NULL).

If a requested endpoint is not found, the corresponding pointer is set to
NULL.

**Return**

Zero if all requested descriptors were found, or -ENXIO otherwise.

#### <a id="c-usb_find_common_endpoints_reverse"></a>`usb_find_common_endpoints_reverse()`

```c
int usb_find_common_endpoints_reverse(struct usb_host_interface *alt, struct usb_endpoint_descriptor **bulk_in, struct usb_endpoint_descriptor **bulk_out, struct usb_endpoint_descriptor **int_in, struct usb_endpoint_descriptor **int_out)
```

- look up common endpoint descriptors

**Parameters**

- `struct usb_host_interface *alt`: alternate setting to search
- `struct usb_endpoint_descriptor **bulk_in`: pointer to descriptor pointer, or NULL
- `struct usb_endpoint_descriptor **bulk_out`: pointer to descriptor pointer, or NULL
- `struct usb_endpoint_descriptor **int_in`: pointer to descriptor pointer, or NULL
- `struct usb_endpoint_descriptor **int_out`: pointer to descriptor pointer, or NULL

**Description**

Search the alternate setting's endpoint descriptors for the last bulk-in,
bulk-out, interrupt-in and interrupt-out endpoints and return them in the
provided pointers (unless they are NULL).

If a requested endpoint is not found, the corresponding pointer is set to
NULL.

**Return**

Zero if all requested descriptors were found, or -ENXIO otherwise.

#### <a id="c-usb_check_bulk_endpoints"></a>`usb_check_bulk_endpoints()`

```c
bool usb_check_bulk_endpoints(const struct usb_interface *intf, const u8 *ep_addrs)
```

Check whether an interface's current altsetting contains a set of bulk endpoints with the given addresses.

**Parameters**

- `const struct usb_interface *intf`: the interface whose current altsetting should be searched
- `const u8 *ep_addrs`: 0-terminated array of the endpoint addresses (number and
  direction) to look for

**Description**

Search for endpoints with the specified addresses and check their types.

**Return**

`true` if all the endpoints are found and are bulk, `false` otherwise.

#### <a id="c-usb_check_int_endpoints"></a>`usb_check_int_endpoints()`

```c
bool usb_check_int_endpoints(const struct usb_interface *intf, const u8 *ep_addrs)
```

Check whether an interface's current altsetting contains a set of interrupt endpoints with the given addresses.

**Parameters**

- `const struct usb_interface *intf`: the interface whose current altsetting should be searched
- `const u8 *ep_addrs`: 0-terminated array of the endpoint addresses (number and
  direction) to look for

**Description**

Search for endpoints with the specified addresses and check their types.

**Return**

`true` if all the endpoints are found and are interrupt,
`false` otherwise.

#### <a id="c-usb_find_alt_setting"></a>`usb_find_alt_setting()`

```c
struct usb_host_interface * usb_find_alt_setting(struct usb_host_config *config, unsigned int iface_num, unsigned int alt_num)
```

Given a configuration, find the alternate setting for the given interface.

**Parameters**

- `struct usb_host_config *config`: the configuration to search (not necessarily the current config).
- `unsigned int iface_num`: interface number to search in
- `unsigned int alt_num`: alternate interface setting number to search for.

**Description**

Search the configuration's interface cache for the given alt setting.

**Return**

The alternate setting, if found. `NULL` otherwise.

#### <a id="c-usb_ifnum_to_if"></a>`usb_ifnum_to_if()`

```c
struct usb_interface * usb_ifnum_to_if(const struct usb_device *dev, unsigned ifnum)
```

get the interface object with a given interface number

**Parameters**

- `const struct usb_device *dev`: the device whose current configuration is considered
- `unsigned ifnum`: the desired interface

**Description**

This walks the device descriptor for the currently active configuration
to find the interface object with the particular interface number.

Note that configuration descriptors are not required to assign interface
numbers sequentially, so that it would be incorrect to assume that
the first interface in that descriptor corresponds to interface zero.
This routine helps device drivers avoid such mistakes.
However, you should make sure that you do the right thing with any
alternate settings available for this interfaces.

Don't call this function unless you are bound to one of the interfaces
on this device or you have locked the device!

**Return**

A pointer to the interface that has **ifnum** as interface number,
if found. `NULL` otherwise.

#### <a id="c-usb_altnum_to_altsetting"></a>`usb_altnum_to_altsetting()`

```c
struct usb_host_interface * usb_altnum_to_altsetting(const struct usb_interface *intf, unsigned int altnum)
```

get the altsetting structure with a given alternate setting number.

**Parameters**

- `const struct usb_interface *intf`: the interface containing the altsetting in question
- `unsigned int altnum`: the desired alternate setting number

**Description**

This searches the altsetting array of the specified interface for
an entry with the correct bAlternateSetting value.

Note that altsettings need not be stored sequentially by number, so
it would be incorrect to assume that the first altsetting entry in
the array corresponds to altsetting zero.  This routine helps device
drivers avoid such mistakes.

Don't call this function unless you are bound to the intf interface
or you have locked the device!

**Return**

A pointer to the entry of the altsetting array of **intf** that
has **altnum** as the alternate setting number. `NULL` if not found.

#### <a id="c-usb_find_interface"></a>`usb_find_interface()`

```c
struct usb_interface * usb_find_interface(struct usb_driver *drv, int minor)
```

find usb_interface pointer for driver and device

**Parameters**

- `struct usb_driver *drv`: the driver whose current configuration is considered
- `int minor`: the minor number of the desired device

**Description**

This walks the bus device list and returns a pointer to the interface
with the matching minor and driver.  Note, this only works for devices
that share the USB major number.

**Return**

A pointer to the interface with the matching major and **minor**.

#### <a id="c-usb_for_each_dev"></a>`usb_for_each_dev()`

```c
int usb_for_each_dev(void *data, int (*fn)(struct usb_device *, void *))
```

iterate over all USB devices in the system

**Parameters**

- `void *data`: data pointer that will be handed to the callback function
- `int (*fn)(struct usb_device *, void *)`: callback function to be called for each USB device

**Description**

Iterate over all USB devices and call **fn** for each, passing it **data**. If it
returns anything other than 0, we break the iteration prematurely and return
that value.

#### <a id="c-usb_alloc_dev"></a>`usb_alloc_dev()`

```c
struct usb_device * usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus, unsigned port1)
```

usb device constructor (usbcore-internal)

**Parameters**

- `struct usb_device *parent`: hub to which device is connected; null to allocate a root hub
- `struct usb_bus *bus`: bus used to access the device
- `unsigned port1`: one-based index of port; ignored for root hubs

**Context**

task context, might sleep.

**Description**

Only hub drivers (including virtual root hub drivers for host
controllers) should ever call this.

This call may not be used in a non-sleeping context.

**Return**

On success, a pointer to the allocated usb device. `NULL` on
failure.

#### <a id="c-usb_get_dev"></a>`usb_get_dev()`

```c
struct usb_device * usb_get_dev(struct usb_device *dev)
```

increments the reference count of the usb device structure

**Parameters**

- `struct usb_device *dev`: the device being referenced

**Description**

Each live reference to a device should be refcounted.

Drivers for USB interfaces should normally record such references in
their `probe()` methods, when they bind to an interface, and release
them by calling [`usb_put_dev()`](#c-usb_put_dev), in their `disconnect()` methods.
However, if a driver does not access the usb_device structure after
its `disconnect()` method returns then refcounting is not necessary,
because the USB core guarantees that a usb_device will not be
deallocated until after all of its interface drivers have been unbound.

**Return**

A pointer to the device with the incremented reference counter.

#### <a id="c-usb_put_dev"></a>`usb_put_dev()`

```c
void usb_put_dev(struct usb_device *dev)
```

release a use of the usb device structure

**Parameters**

- `struct usb_device *dev`: device that's been disconnected

**Description**

Must be called when a user of a device is finished with it.  When the last
user of the device calls this function, the memory of the device is freed.

#### <a id="c-usb_get_intf"></a>`usb_get_intf()`

```c
struct usb_interface * usb_get_intf(struct usb_interface *intf)
```

increments the reference count of the usb interface structure

**Parameters**

- `struct usb_interface *intf`: the interface being referenced

**Description**

Each live reference to a interface must be refcounted.

Drivers for USB interfaces should normally record such references in
their `probe()` methods, when they bind to an interface, and release
them by calling [`usb_put_intf()`](#c-usb_put_intf), in their `disconnect()` methods.
However, if a driver does not access the usb_interface structure after
its `disconnect()` method returns then refcounting is not necessary,
because the USB core guarantees that a usb_interface will not be
deallocated until after its driver has been unbound.

**Return**

A pointer to the interface with the incremented reference counter.

#### <a id="c-usb_put_intf"></a>`usb_put_intf()`

```c
void usb_put_intf(struct usb_interface *intf)
```

release a use of the usb interface structure

**Parameters**

- `struct usb_interface *intf`: interface that's been decremented

**Description**

Must be called when a user of an interface is finished with it.  When the
last user of the interface calls this function, the memory of the interface
is freed.

#### <a id="c-usb_intf_get_dma_device"></a>`usb_intf_get_dma_device()`

```c
struct device * usb_intf_get_dma_device(struct usb_interface *intf)
```

acquire a reference on the usb interface's DMA endpoint

**Parameters**

- `struct usb_interface *intf`: the usb interface

**Description**

While a USB device cannot perform DMA operations by itself, many USB
controllers can. A call to [`usb_intf_get_dma_device()`](#c-usb_intf_get_dma_device) returns the DMA endpoint
for the given USB interface, if any. The returned device structure must be
released with [`put_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-put_device).

See also `usb_get_dma_device()`.

**Return**

A reference to the usb interface's DMA endpoint; or NULL if none
exists.

#### <a id="c-usb_lock_device_for_reset"></a>`usb_lock_device_for_reset()`

```c
int usb_lock_device_for_reset(struct usb_device *udev, const struct usb_interface *iface)
```

cautiously acquire the lock for a usb device structure

**Parameters**

- `struct usb_device *udev`: device that's being locked
- `const struct usb_interface *iface`: interface bound to the driver making the request (optional)

**Description**

Attempts to acquire the device lock, but fails if the device is
NOTATTACHED or SUSPENDED, or if iface is specified and the interface
is neither BINDING nor BOUND.  Rather than sleeping to wait for the
lock, the routine polls repeatedly.  This is to prevent deadlock with
disconnect; in some drivers (such as usb-storage) the `disconnect()`
or `suspend()` method will block waiting for a device reset to complete.

**Return**

A negative error code for failure, otherwise 0.

#### <a id="c-usb_get_current_frame_number"></a>`usb_get_current_frame_number()`

```c
int usb_get_current_frame_number(struct usb_device *dev)
```

return current bus frame number

**Parameters**

- `struct usb_device *dev`: the device whose bus is being queried

**Return**

The current frame number for the USB host controller used
with the given USB device. This can be used when scheduling
isochronous requests.

**Note**

Different kinds of host controller have different "scheduling
horizons". While one type might support scheduling only 32 frames
into the future, others could support scheduling up to 1024 frames
into the future.

#### <a id="c-usb_alloc_coherent"></a>`usb_alloc_coherent()`

```c
void * usb_alloc_coherent(struct usb_device *dev, size_t size, gfp_t mem_flags, dma_addr_t *dma)
```

allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP

**Parameters**

- `struct usb_device *dev`: device the buffer will be used with
- `size_t size`: requested buffer size
- `gfp_t mem_flags`: affect whether allocation may block
- `dma_addr_t *dma`: used to return DMA address of buffer

**Return**

Either null (indicating no buffer could be allocated), or the
cpu-space pointer to a buffer that may be used to perform DMA to the
specified device.  Such cpu-space buffers are returned along with the DMA
address (through the pointer provided).

**Note**

These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
to avoid behaviors like using "DMA bounce buffers", or thrashing IOMMU
hardware during URB completion/resubmit.  The implementation varies between
platforms, depending on details of how DMA will work to this device.
Using these buffers also eliminates cacheline sharing problems on
architectures where CPU caches are not DMA-coherent.  On systems without
bus-snooping caches, these buffers are uncached.

When the buffer is no longer used, free it with [`usb_free_coherent()`](#c-usb_free_coherent).

#### <a id="c-usb_free_coherent"></a>`usb_free_coherent()`

```c
void usb_free_coherent(struct usb_device *dev, size_t size, void *addr, dma_addr_t dma)
```

free memory allocated with [`usb_alloc_coherent()`](#c-usb_alloc_coherent)

**Parameters**

- `struct usb_device *dev`: device the buffer was used with
- `size_t size`: requested buffer size
- `void *addr`: CPU address of buffer
- `dma_addr_t dma`: DMA address of buffer

**Description**

This reclaims an I/O buffer, letting it be reused.  The memory must have
been allocated using [`usb_alloc_coherent()`](#c-usb_alloc_coherent), and the parameters must match
those provided in that allocation request.

#### <a id="c-usb_alloc_noncoherent"></a>`usb_alloc_noncoherent()`

```c
void * usb_alloc_noncoherent(struct usb_device *dev, size_t size, gfp_t mem_flags, dma_addr_t *dma, enum dma_data_direction dir, struct sg_table **table)
```

allocate dma-noncoherent buffer for URB_NO_xxx_DMA_MAP

**Parameters**

- `struct usb_device *dev`: device the buffer will be used with
- `size_t size`: requested buffer size
- `gfp_t mem_flags`: affect whether allocation may block
- `dma_addr_t *dma`: used to return DMA address of buffer
- `enum dma_data_direction dir`: DMA transfer direction
- `struct sg_table **table`: used to return sg_table of allocated memory

**Description**

To explicit manage the memory ownership for the kernel vs the device by
USB core, the user needs save sg_table to urb->sgt. Then USB core will
do DMA sync for CPU and device properly.

When the buffer is no longer used, free it with [`usb_free_noncoherent()`](#c-usb_free_noncoherent).

**Return**

Either null (indicating no buffer could be allocated), or the
cpu-space pointer to a buffer that may be used to perform DMA to the
specified device.  Such cpu-space buffers are returned along with the DMA
address (through the pointer provided).

#### <a id="c-usb_free_noncoherent"></a>`usb_free_noncoherent()`

```c
void usb_free_noncoherent(struct usb_device *dev, size_t size, void *addr, enum dma_data_direction dir, struct sg_table *table)
```

free memory allocated with [`usb_alloc_noncoherent()`](#c-usb_alloc_noncoherent)

**Parameters**

- `struct usb_device *dev`: device the buffer was used with
- `size_t size`: requested buffer size
- `void *addr`: CPU address of buffer
- `enum dma_data_direction dir`: DMA transfer direction
- `struct sg_table *table`: describe the allocated and DMA mapped memory,

**Description**

This reclaims an I/O buffer, letting it be reused.  The memory must have
been allocated using [`usb_alloc_noncoherent()`](#c-usb_alloc_noncoherent), and the parameters must match
those provided in that allocation request.

#### <a id="c-usb_endpoint_max_periodic_payload"></a>`usb_endpoint_max_periodic_payload()`

```c
u32 usb_endpoint_max_periodic_payload(struct usb_device *udev, const struct usb_host_endpoint *ep)
```

Get maximum payload bytes per service interval

**Parameters**

- `struct usb_device *udev`: The USB device
- `const struct usb_host_endpoint *ep`: The endpoint

**Return**

the maximum number of bytes isochronous or interrupt endpoint **ep**
can transfer during a service interval, or 0 for other endpoints.

#### <a id="c-usb_endpoint_is_hs_isoc_double"></a>`usb_endpoint_is_hs_isoc_double()`

```c
bool usb_endpoint_is_hs_isoc_double(struct usb_device *udev, const struct usb_host_endpoint *ep)
```

Tell whether an endpoint uses USB 2 Isochronous Double IN Bandwidth

**Parameters**

- `struct usb_device *udev`: The USB device
- `const struct usb_host_endpoint *ep`: The endpoint

**Return**

true if an endpoint **ep** conforms to USB 2 Isochronous Double IN
Bandwidth ECN, false otherwise.



#### <a id="c-usb_hub_clear_tt_buffer"></a>`usb_hub_clear_tt_buffer()`

```c
int usb_hub_clear_tt_buffer(struct urb *urb)
```

clear control/bulk TT state in high speed hub

**Parameters**

- `struct urb *urb`: an URB associated with the failed or incomplete split transaction

**Description**

High speed HCDs use this to tell the hub driver that some split control or
bulk transaction failed in a way that requires clearing internal state of
a transaction translator.  This is normally detected (and reported) from
interrupt context.

It may not be possible for that hub to handle additional full (or low)
speed transactions until that state is fully cleared out.

**Return**

0 if successful. A negative error code otherwise.

#### <a id="c-usb_set_device_state"></a>`usb_set_device_state()`

```c
void usb_set_device_state(struct usb_device *udev, enum usb_device_state new_state)
```

change a device's current state (usbcore, hcds)

**Parameters**

- `struct usb_device *udev`: pointer to device whose state should be changed
- `enum usb_device_state new_state`: new state value to be stored

**Description**

udev->state is _not_ fully protected by the device lock.  Although
most transitions are made only while holding the lock, the state can
can change to USB_STATE_NOTATTACHED at almost any time.  This
is so that devices can be marked as disconnected as soon as possible,
without having to wait for any semaphores to be released.  As a result,
all changes to any device's state must be protected by the
device_state_lock spinlock.

Once a device has been added to the device tree, all changes to its state
should be made using this routine.  The state should _not_ be set directly.

If udev->state is already USB_STATE_NOTATTACHED then no change is made.
Otherwise udev->state is set to new_state, and if new_state is
USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
to USB_STATE_NOTATTACHED.

#### <a id="c-usb_root_hub_lost_power"></a>`usb_root_hub_lost_power()`

```c
void usb_root_hub_lost_power(struct usb_device *rhdev)
```

called by HCD if the root hub lost Vbus power

**Parameters**

- `struct usb_device *rhdev`: struct usb_device for the root hub

**Description**

The USB host controller driver calls this function when its root hub
is resumed and Vbus power has been interrupted or the controller
has been reset.  The routine marks **rhdev** as having lost power.
When the hub driver is resumed it will take notice and carry out
power-session recovery for all the "USB-PERSIST"-enabled child devices;
the others will be disconnected.

#### <a id="c-usb_reset_device"></a>`usb_reset_device()`

```c
int usb_reset_device(struct usb_device *udev)
```

warn interface drivers and perform a USB port reset

**Parameters**

- `struct usb_device *udev`: device to reset (not in NOTATTACHED state)

**Description**

Warns all drivers bound to registered interfaces (using their pre_reset
method), performs the port reset, and then lets the drivers know that
the reset is over (using their post_reset method).

**Return**

The same as for `usb_reset_and_verify_device()`.
However, if a reset is already in progress (for instance, if a
driver doesn't have `pre_reset()` or `post_reset()` callbacks, and while
being unbound or re-bound during the ongoing reset its `disconnect()`
or `probe()` routine tries to perform a second, nested reset), the
routine returns -EINPROGRESS.

**Note**

The caller must own the device lock.  For example, it's safe to use
this from a driver `probe()` routine after downloading new firmware.
For calls that might not occur during `probe()`, drivers should lock
the device using [`usb_lock_device_for_reset()`](#c-usb_lock_device_for_reset).

If an interface is currently being probed or disconnected, we assume
its driver knows how to handle resets.  For all other interfaces,
if the driver doesn't have pre_reset and post_reset methods then
we attempt to unbind it and rebind afterward.

#### <a id="c-usb_queue_reset_device"></a>`usb_queue_reset_device()`

```c
void usb_queue_reset_device(struct usb_interface *iface)
```

Reset a USB device from an atomic context

**Parameters**

- `struct usb_interface *iface`: USB interface belonging to the device to reset

**Description**

This function can be used to reset a USB device from an atomic
context, where [`usb_reset_device()`](#c-usb_reset_device) won't work (as it blocks).

Doing a reset via this method is functionally equivalent to calling
[`usb_reset_device()`](#c-usb_reset_device), except for the fact that it is delayed to a
workqueue. This means that any drivers bound to other interfaces
might be unbound, as well as users from usbfs in user space.

Corner cases:

- Scheduling two resets at the same time from two different drivers
  attached to two different interfaces of the same device is
  possible; depending on how the driver attached to each interface
  handles ->`pre_reset()`, the second reset might happen or not.

- If the reset is delayed so long that the interface is unbound from
  its driver, the reset will be skipped.

- This function can be called during .`probe()`.  It can also be called
  during .`disconnect()`, but doing so is pointless because the reset
  will not occur.  If you really want to reset the device during
  .`disconnect()`, call [`usb_reset_device()`](#c-usb_reset_device) directly -- but watch out
  for nested unbinding issues!

#### <a id="c-usb_hub_find_child"></a>`usb_hub_find_child()`

```c
struct usb_device * usb_hub_find_child(struct usb_device *hdev, int port1)
```

Get the pointer of child device attached to the port which is specified by **port1**.

**Parameters**

- `struct usb_device *hdev`: USB device belonging to the usb hub
- `int port1`: port num to indicate which port the child device
  is attached to.

**Description**

USB drivers call this function to get hub's child device
pointer.

**Return**

`NULL` if input param is invalid and
child's usb_device pointer if non-NULL.


<a id="rst-host-controller-apis"></a>

## Host Controller APIs

These APIs are only for use by host controller drivers, most of which implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI was one of the first interfaces, designed by Intel and also used by VIA; it doesn't do much in hardware. OHCI was designed later, to have the hardware do more work (bigger transfers, tracking protocol state, and so on). EHCI was designed with USB 2.0; its design has features that resemble OHCI (hardware does much more work) as well as UHCI (some parts of ISO support, TD list processing). XHCI was designed with USB 3.0. It continues to shift support for functionality into hardware.

There are host controllers other than the "big three", although most PCI based controllers (and a few non-PCI based ones) use one of those interfaces. Not all host controllers use DMA; some use PIO, and there is also a simulator and a virtual host controller to pipe USB over the network.

The same basic APIs are available to drivers for all those controllers. For historical reasons they are in two layers: `struct usb_bus <usb_bus>` is a rather thin layer that became available in the 2.2 kernels, while `struct usb_hcd <usb_hcd>` is a more featureful layer that lets HCDs share common code, to shrink driver size and significantly reduce hcd-specific behaviors.


#### <a id="c-usb_calc_bus_time"></a>`usb_calc_bus_time()`

```c
long usb_calc_bus_time(int speed, int is_input, int isoc, int bytecount)
```

approximate periodic transaction time in nanoseconds

**Parameters**

- `int speed`: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
- `int is_input`: true iff the transaction sends data to the host
- `int isoc`: true for isochronous transactions, false for interrupt ones
- `int bytecount`: how many bytes in the transaction.

**Return**

Approximate bus time in nanoseconds for a periodic transaction.

**Note**

See USB 2.0 spec section 5.11.3; only periodic transfers need to be
scheduled in software, this function is only used for such scheduling.

#### <a id="c-usb_hcd_link_urb_to_ep"></a>`usb_hcd_link_urb_to_ep()`

```c
int usb_hcd_link_urb_to_ep(struct usb_hcd *hcd, struct urb *urb)
```

add an URB to its endpoint queue

**Parameters**

- `struct usb_hcd *hcd`: host controller to which **urb** was submitted
- `struct urb *urb`: URB being submitted

**Description**

Host controller drivers should call this routine in their `enqueue()`
method.  The HCD's private spinlock must be held and interrupts must
be disabled.  The actions carried out here are required for URB
submission, as well as for endpoint shutdown and for usb_kill_urb.

**Return**

0 for no error, otherwise a negative error code (in which case
the `enqueue()` method must fail).  If no error occurs but `enqueue()` fails
anyway, it must call [`usb_hcd_unlink_urb_from_ep()`](#c-usb_hcd_unlink_urb_from_ep) before releasing
the private spinlock and returning.

#### <a id="c-usb_hcd_check_unlink_urb"></a>`usb_hcd_check_unlink_urb()`

```c
int usb_hcd_check_unlink_urb(struct usb_hcd *hcd, struct urb *urb, int status)
```

check whether an URB may be unlinked

**Parameters**

- `struct usb_hcd *hcd`: host controller to which **urb** was submitted
- `struct urb *urb`: URB being checked for unlinkability
- `int status`: error code to store in **urb** if the unlink succeeds

**Description**

Host controller drivers should call this routine in their `dequeue()`
method.  The HCD's private spinlock must be held and interrupts must
be disabled.  The actions carried out here are required for making
sure than an unlink is valid.

- -EIDRM: **urb** was not submitted or has already completed.

  The completion function may not have been called yet.

  -EBUSY: **urb** has already been unlinked.

**Return**

0 for no error, otherwise a negative error code (in which case
the `dequeue()` method must fail).  The possible error codes are:

#### <a id="c-usb_hcd_unlink_urb_from_ep"></a>`usb_hcd_unlink_urb_from_ep()`

```c
void usb_hcd_unlink_urb_from_ep(struct usb_hcd *hcd, struct urb *urb)
```

remove an URB from its endpoint queue

**Parameters**

- `struct usb_hcd *hcd`: host controller to which **urb** was submitted
- `struct urb *urb`: URB being unlinked

**Description**

Host controller drivers should call this routine before calling
[`usb_hcd_giveback_urb()`](#c-usb_hcd_giveback_urb).  The HCD's private spinlock must be held and
interrupts must be disabled.  The actions carried out here are required
for URB completion.

#### <a id="c-usb_hcd_giveback_urb"></a>`usb_hcd_giveback_urb()`

```c
void usb_hcd_giveback_urb(struct usb_hcd *hcd, struct urb *urb, int status)
```

return URB from HCD to device driver

**Parameters**

- `struct usb_hcd *hcd`: host controller returning the URB
- `struct urb *urb`: urb being returned to the USB device driver.
- `int status`: completion status code for the URB.

**Context**

atomic. The completion callback is invoked either in a work queue
(BH) context or in the caller's context, depending on whether the HCD_BH
flag is set in the **hcd** structure, except that URBs submitted to the
root hub always complete in BH context.

**Description**

This hands the URB from HCD to its USB device driver, using its
completion function.  The HCD has freed all per-urb resources
(and is done using urb->hcpriv).  It also released all HCD locks;
the device driver won't cause problems if it frees, modifies,
or resubmits this URB.

If **urb** was unlinked, the value of **status** will be overridden by
**urb->unlinked**.  Erroneous short transfers are detected in case
the HCD hasn't checked for them.

#### <a id="c-usb_alloc_streams"></a>`usb_alloc_streams()`

```c
int usb_alloc_streams(struct usb_interface *interface, struct usb_host_endpoint **eps, unsigned int num_eps, unsigned int num_streams, gfp_t mem_flags)
```

allocate bulk endpoint stream IDs.

**Parameters**

- `struct usb_interface *interface`: alternate setting that includes all endpoints.
- `struct usb_host_endpoint **eps`: array of endpoints that need streams.
- `unsigned int num_eps`: number of endpoints in the array.
- `unsigned int num_streams`: number of streams to allocate.
- `gfp_t mem_flags`: flags hcd should use to allocate memory.

**Description**

Sets up a group of bulk endpoints to have **num_streams** stream IDs available.
Drivers may queue multiple transfers to different stream IDs, which may
complete in a different order than they were queued.

**Return**

On success, the number of allocated streams. On failure, a negative
error code.

#### <a id="c-usb_free_streams"></a>`usb_free_streams()`

```c
int usb_free_streams(struct usb_interface *interface, struct usb_host_endpoint **eps, unsigned int num_eps, gfp_t mem_flags)
```

free bulk endpoint stream IDs.

**Parameters**

- `struct usb_interface *interface`: alternate setting that includes all endpoints.
- `struct usb_host_endpoint **eps`: array of endpoints to remove streams from.
- `unsigned int num_eps`: number of endpoints in the array.
- `gfp_t mem_flags`: flags hcd should use to allocate memory.

**Description**

Reverts a group of bulk endpoints back to not using stream IDs.
Can fail if we are given bad arguments, or HCD is broken.

**Return**

0 on success. On failure, a negative error code.

#### <a id="c-usb_hcd_resume_root_hub"></a>`usb_hcd_resume_root_hub()`

```c
void usb_hcd_resume_root_hub(struct usb_hcd *hcd)
```

called by HCD to resume its root hub

**Parameters**

- `struct usb_hcd *hcd`: host controller for this root hub

**Description**

The USB host controller calls this function when its root hub is
suspended (with the remote wakeup feature enabled) and a remote
wakeup request is received.  The routine submits a workqueue request
to resume the root hub (that is, manage its downstream ports again).

#### <a id="c-usb_bus_start_enum"></a>`usb_bus_start_enum()`

```c
int usb_bus_start_enum(struct usb_bus *bus, unsigned port_num)
```

start immediate enumeration (for OTG)

**Parameters**

- `struct usb_bus *bus`: the bus (must use hcd framework)
- `unsigned port_num`: 1-based number of port; usually bus->otg_port

**Context**

atomic

**Description**

Starts enumeration, with an immediate reset followed later by
hub_wq identifying and possibly configuring the device.
This is needed by OTG controller drivers, where it helps meet
HNP protocol timing requirements for starting a port reset.

**Return**

0 if successful.

#### <a id="c-usb_hcd_irq"></a>`usb_hcd_irq()`

```c
irqreturn_t usb_hcd_irq(int irq, void *__hcd)
```

hook IRQs to HCD framework (bus glue)

**Parameters**

- `int irq`: the IRQ being raised
- `void *__hcd`: pointer to the HCD whose IRQ is being signaled

**Description**

If the controller isn't HALTed, calls the driver's irq handler.
Checks whether the controller is now dead.

**Return**

`IRQ_HANDLED` if the IRQ was handled. `IRQ_NONE` otherwise.

#### <a id="c-usb_hc_died"></a>`usb_hc_died()`

```c
void usb_hc_died(struct usb_hcd *hcd)
```

report abnormal shutdown of a host controller (bus glue)

**Parameters**

- `struct usb_hcd *hcd`: pointer to the HCD representing the controller

**Description**

This is called by bus glue to report a USB host controller that died
while operations may still have been pending.  It's called automatically
by the PCI glue, so only glue for non-PCI busses should need to call it.

Only call this function with the primary HCD.

#### <a id="c-usb_create_shared_hcd"></a>`usb_create_shared_hcd()`

```c
struct usb_hcd * usb_create_shared_hcd(const struct hc_driver *driver, struct device *dev, const char *bus_name, struct usb_hcd *primary_hcd)
```

create and initialize an HCD structure

**Parameters**

- `const struct hc_driver *driver`: HC driver that will use this hcd
- `struct device *dev`: device for this HC, stored in hcd->self.controller
- `const char *bus_name`: value to store in hcd->self.bus_name
- `struct usb_hcd *primary_hcd`: a pointer to the usb_hcd structure that is sharing the
  PCI device.  Only allocate certain resources for the primary HCD

**Context**

task context, might sleep.

**Description**

Allocate a struct usb_hcd, with extra space at the end for the
HC driver's private data.  Initialize the generic members of the
hcd structure.

**Return**

On success, a pointer to the created and initialized HCD structure.
On failure (e.g. if memory is unavailable), `NULL`.

#### <a id="c-usb_create_hcd"></a>`usb_create_hcd()`

```c
struct usb_hcd * usb_create_hcd(const struct hc_driver *driver, struct device *dev, const char *bus_name)
```

create and initialize an HCD structure

**Parameters**

- `const struct hc_driver *driver`: HC driver that will use this hcd
- `struct device *dev`: device for this HC, stored in hcd->self.controller
- `const char *bus_name`: value to store in hcd->self.bus_name

**Context**

task context, might sleep.

**Description**

Allocate a struct usb_hcd, with extra space at the end for the
HC driver's private data.  Initialize the generic members of the
hcd structure.

**Return**

On success, a pointer to the created and initialized HCD
structure. On failure (e.g. if memory is unavailable), `NULL`.

#### <a id="c-usb_add_hcd"></a>`usb_add_hcd()`

```c
int usb_add_hcd(struct usb_hcd *hcd, unsigned int irqnum, unsigned long irqflags)
```

finish generic HCD structure initialization and register

**Parameters**

- `struct usb_hcd *hcd`: the usb_hcd structure to initialize
- `unsigned int irqnum`: Interrupt line to allocate
- `unsigned long irqflags`: Interrupt type flags

**Description**

Finish the remaining parts of generic HCD initialization: allocate the
buffers of consistent memory, register the bus, request the IRQ line,
and call the driver's `reset()` and `start()` routines.

#### <a id="c-usb_remove_hcd"></a>`usb_remove_hcd()`

```c
void usb_remove_hcd(struct usb_hcd *hcd)
```

shutdown processing for generic HCDs

**Parameters**

- `struct usb_hcd *hcd`: the usb_hcd structure to remove

**Context**

task context, might sleep.

**Description**

Disconnects the root hub, then reverses the effects of [`usb_add_hcd()`](#c-usb_add_hcd),
invoking the HCD's `stop()` method.



#### <a id="c-usb_hcd_pci_probe"></a>`usb_hcd_pci_probe()`

```c
int usb_hcd_pci_probe(struct pci_dev *dev, const struct hc_driver *driver)
```

initialize PCI-based HCDs

**Parameters**

- `struct pci_dev *dev`: USB Host Controller being probed
- `const struct hc_driver *driver`: USB HC driver handle

**Context**

task context, might sleep

**Description**

Allocates basic PCI resources for this USB host controller, and
then invokes the `start()` method for the HCD associated with it
through the hotplug entry's driver_data.

Store this function in the HCD's struct pci_driver as `probe()`.

**Return**

0 if successful.

#### <a id="c-usb_hcd_pci_remove"></a>`usb_hcd_pci_remove()`

```c
void usb_hcd_pci_remove(struct pci_dev *dev)
```

shutdown processing for PCI-based HCDs

**Parameters**

- `struct pci_dev *dev`: USB Host Controller being removed

**Context**

task context, might sleep

**Description**

Reverses the effect of [`usb_hcd_pci_probe()`](#c-usb_hcd_pci_probe), first invoking
the HCD's `stop()` method.  It is always called from a thread
context, normally "rmmod", "apmd", or something similar.

Store this function in the HCD's struct pci_driver as `remove()`.

#### <a id="c-usb_hcd_pci_shutdown"></a>`usb_hcd_pci_shutdown()`

```c
void usb_hcd_pci_shutdown(struct pci_dev *dev)
```

shutdown host controller

**Parameters**

- `struct pci_dev *dev`: USB Host Controller being shutdown



#### <a id="c-hcd_buffer_create"></a>`hcd_buffer_create()`

```c
int hcd_buffer_create(struct usb_hcd *hcd)
```

initialize buffer pools

**Parameters**

- `struct usb_hcd *hcd`: the bus whose buffer pools are to be initialized

**Context**

task context, might sleep

**Description**

Call this as part of initializing a host controller that uses the dma
memory allocators.  It initializes some pools of dma-coherent memory that
will be shared by all drivers using that controller.

Call [`hcd_buffer_destroy()`](#c-hcd_buffer_destroy) to clean up after using those pools.

**Return**

0 if successful. A negative errno value otherwise.

#### <a id="c-hcd_buffer_destroy"></a>`hcd_buffer_destroy()`

```c
void hcd_buffer_destroy(struct usb_hcd *hcd)
```

deallocate buffer pools

**Parameters**

- `struct usb_hcd *hcd`: the bus whose buffer pools are to be destroyed

**Context**

task context, might sleep

**Description**

This frees the buffer pools created by [`hcd_buffer_create()`](#c-hcd_buffer_create).


<a id="rst-the-usb-character-device-nodes"></a>

## The USB character device nodes

This chapter presents the Linux character device nodes. You may prefer to avoid writing new kernel code for your USB driver. User mode device drivers are usually packaged as applications or libraries, and may use character devices through some programming library that wraps it. Such libraries include:

> - [libusb](<http://libusb.sourceforge.net>) for C/C++, and
>
> - [jUSB](<http://jUSB.sourceforge.net>) for Java.

Some old information about it can be seen at the "USB Device Filesystem" section of the USB Guide. The latest copy of the USB Guide can be found at [http://www.linux-usb.org/](<http://www.linux-usb.org/>)

> [!NOTE]
>
> - They were used to be implemented via *usbfs*, but this is not part of the sysfs debug interface.
>
> > - This particular documentation is incomplete, especially with respect to the asynchronous mode. As of kernel 2.5.66 the code and this (new) documentation need to be cross-reviewed.

<a id="rst-what-files-are-in-devtmpfs"></a>

### What files are in "devtmpfs"?

Conventionally mounted at `/dev/bus/usb/`, usbfs features include:

- `/dev/bus/usb/BBB/DDD` ... magic files exposing the each device's configuration descriptors, and supporting a series of ioctls for making device requests, including I/O to devices. (Purely for access by programs.)

Each bus is given a number (`BBB`) based on when it was enumerated; within each bus, each device is given a similar number (`DDD`). Those `BBB/DDD` paths are not "stable" identifiers; expect them to change even if you always leave the devices plugged in to the same hub port. *Don't even think of saving these in application configuration files.* Stable identifiers are available, for user mode applications that want to use them. HID and networking devices expose these stable IDs, so that for example you can be sure that you told the right UPS to power down its second server. Pleast note that it doesn't (yet) expose those IDs.

<a id="rst-dev-bus-usb-bbb-ddd"></a>

### /dev/bus/usb/BBB/DDD

Use these files in one of these basic ways:

- *They can be read,* producing first the device descriptor (18 bytes) and then the descriptors for the current configuration. See the USB 2.0 spec for details about those binary data formats. You'll need to convert most multibyte values from little endian format to your native host byte order, although a few of the fields in the device descriptor (both of the BCD-encoded fields, and the vendor and product IDs) will be byteswapped for you. Note that configuration descriptors include descriptors for interfaces, altsettings, endpoints, and maybe additional class descriptors.

- *Perform USB operations* using *ioctl()* requests to make endpoint I/O requests (synchronously or asynchronously) or manage the device. These requests need the `CAP_SYS_RAWIO` capability, as well as filesystem access permissions. Only one ioctl request can be made on one of these device files at a time. This means that if you are synchronously reading an endpoint from one thread, you won't be able to write to a different endpoint from another thread until the read completes. This works for *half duplex* protocols, but otherwise you'd use asynchronous i/o requests.

Each connected USB device has one file.  The `BBB` indicates the bus number.  The `DDD` indicates the device address on that bus.  Both of these numbers are assigned sequentially, and can be reused, so you can't rely on them for stable access to devices.  For example, it's relatively common for devices to re-enumerate while they are still connected (perhaps someone jostled their power supply, hub, or USB cable), so a device might be `002/027` when you first connect it and `002/048` sometime later.

These files can be read as binary data.  The binary data consists of first the device descriptor, then the descriptors for each configuration of the device.  Multi-byte fields in the device descriptor are converted to host endianness by the kernel.  The configuration descriptors are in bus endian format\! The configuration descriptor are wTotalLength bytes apart. If a device returns less configuration descriptor data than indicated by wTotalLength there will be a hole in the file for the missing bytes.  This information is also shown in text form by the `/sys/kernel/debug/usb/devices` file, described later.

These files may also be used to write user-level drivers for the USB devices.  You would open the `/dev/bus/usb/BBB/DDD` file read/write, read its descriptors to make sure it's the device you expect, and then bind to an interface (or perhaps several) using an ioctl call.  You would issue more ioctls to the device to communicate to it using control, bulk, or other kinds of USB transfers.  The IOCTLs are listed in the `<linux/usbdevice_fs.h>` file, and at this writing the source code (`linux/drivers/usb/core/devio.c`) is the primary reference for how to access devices through those files.

The inherited Unix mode settings on `BBB/DDD` files are not a Peios access grant. A userspace driver needs native authorization to open and operate on the device, including the relevant handle and ioctl rights. `chmod` or a `devmode=0666` mount option alone does not delegate that authority. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).

<a id="rst-life-cycle-of-user-mode-drivers"></a>

### Life Cycle of User Mode Drivers

Such a driver first needs to find a device file for a device it knows how to handle. Maybe it was told about it because a `/sbin/hotplug` event handling agent chose that driver to handle the new device. Or maybe it's an application that scans all the `/dev/bus/usb` device files, and ignores most devices. In either case, it should `read()` all the descriptors from the device file, and check them against what it knows how to handle. It might just reject everything except a particular vendor and product ID, or need a more complex policy.

Never assume there will only be one such device on the system at a time\! If your code can't handle more than one device at a time, at least detect when there's more than one, and have your users choose which device to use.

Once your user mode driver knows what device to use, it interacts with it in either of two styles. The simple style is to make only control requests; some devices don't need more complex interactions than those. (An example might be software using vendor-specific control requests for some initialization or configuration tasks, with a kernel driver for the rest.)

More likely, you need a more complex style driver: one using non-control endpoints, reading or writing data and claiming exclusive use of an interface. *Bulk* transfers are easiest to use, but only their sibling *interrupt* transfers work with low speed devices. Both interrupt and *isochronous* transfers offer service guarantees because their bandwidth is reserved. Such "periodic" transfers are awkward to use through usbfs, unless you're using the asynchronous calls. However, interrupt transfers can also be used in a synchronous "one shot" style.

Your user-mode driver should never need to worry about cleaning up request state when the device is disconnected, although it should close its open file descriptors as soon as it starts seeing the ENODEV errors.

<a id="rst-the-ioctl-requests"></a>

### The ioctl() Requests

To use these ioctls, you need to include the following headers in your userspace program:



```text
#include <linux/usb.h>
#include <linux/usbdevice_fs.h>
#include <asm/byteorder.h>
```

The standard USB device model requests, from "Chapter 9" of the USB 2.0 specification, are automatically included from the `<linux/usb/ch9.h>` header.

Unless noted otherwise, the ioctl requests described here will update the modification time on the usbfs file to which they are applied (unless they fail). A return of zero indicates success; otherwise, a standard USB error code is returned (These are documented in [USB Error codes](</kernel/hardware/driver-api/usb/error-codes.md#rst-usb-error-codes>)).

Each of these files multiplexes access to several I/O streams, one per endpoint. Each device has one control endpoint (endpoint zero) which supports a limited RPC style RPC access. Devices are configured by hub_wq (in the kernel) setting a device-wide *configuration* that affects things like power consumption and basic functionality. The endpoints are part of USB *interfaces*, which may have *altsettings* affecting things like which endpoints are available. Many devices only have a single configuration and interface, so drivers for them will ignore configurations and altsettings.

<a id="rst-management-status-requests"></a>

#### Management/Status Requests

A number of usbfs requests don't deal very directly with device I/O. They mostly relate to device management and status. These are all synchronous requests.

- **USBDEVFS_CLAIMINTERFACE**

  This is used to force usbfs to claim a specific interface, which has not previously been claimed by usbfs or any other kernel driver. The ioctl parameter is an integer holding the number of the interface (bInterfaceNumber from descriptor).

  Note that if your driver doesn't claim an interface before trying to use one of its endpoints, and no other driver has bound to it, then the interface is automatically claimed by usbfs.

  This claim will be released by a RELEASEINTERFACE ioctl, or by closing the file descriptor. File modification time is not updated by this request.

- **USBDEVFS_CONNECTINFO**

  Says whether the device is lowspeed. The ioctl parameter points to a structure like this:



  ```text
  struct usbdevfs_connectinfo {
          unsigned int   devnum;
          unsigned char  slow;
  };
  ```

  File modification time is not updated by this request.

  *You can't tell whether a "not slow" device is connected at high speed (480 MBit/sec) or just full speed (12 MBit/sec).* You should know the devnum value already, it's the DDD value of the device file name.

- **USBDEVFS_GET_SPEED**

  Returns the speed of the device. The speed is returned as a numerical value in accordance with enum usb_device_speed

  File modification time is not updated by this request.

- **USBDEVFS_GETDRIVER**

  Returns the name of the kernel driver bound to a given interface (a string). Parameter is a pointer to this structure, which is modified:



  ```text
  struct usbdevfs_getdriver {
          unsigned int  interface;
          char          driver[USBDEVFS_MAXDRIVERNAME + 1];
  };
  ```

  File modification time is not updated by this request.

- **USBDEVFS_IOCTL**

  Passes a request from userspace through to a kernel driver that has an ioctl entry in the *struct usb_driver* it registered:



  ```text
  struct usbdevfs_ioctl {
          int     ifno;
          int     ioctl_code;
          void    *data;
  };

  /* user mode call looks like this.
   * 'request' becomes the driver->ioctl() 'code' parameter.
   * the size of 'param' is encoded in 'request', and that data
   * is copied to or from the driver->ioctl() 'buf' parameter.
   */
  static int
  usbdev_ioctl (int fd, int ifno, unsigned request, void *param)
  {
          struct usbdevfs_ioctl   wrapper;

          wrapper.ifno = ifno;
          wrapper.ioctl_code = request;
          wrapper.data = param;

          return ioctl (fd, USBDEVFS_IOCTL, &wrapper);
  }
  ```

  File modification time is not updated by this request.

  This request lets kernel drivers talk to user mode code through filesystem operations even when they don't create a character or block special device. It's also been used to do things like ask devices what device special file should be used. Two pre-defined ioctls are used to disconnect and reconnect kernel drivers, so that user mode code can completely manage binding and configuration of devices.

- **USBDEVFS_RELEASEINTERFACE**

  This is used to release the claim usbfs made on interface, either implicitly or because of a USBDEVFS_CLAIMINTERFACE call, before the file descriptor is closed. The ioctl parameter is an integer holding the number of the interface (bInterfaceNumber from descriptor); File modification time is not updated by this request.

  > [!WARNING]
  >
  > *No security check is made to ensure that the task which made the claim is the one which is releasing it. This means that user mode driver may interfere other ones.*

- **USBDEVFS_RESETEP**

  Resets the data toggle value for an endpoint (bulk or interrupt) to DATA0. The ioctl parameter is an integer endpoint number (1 to 15, as identified in the endpoint descriptor), with USB_DIR_IN added if the device's endpoint sends data to the host.

  > [!WARNING]
  >
  > *Avoid using this request. It should probably be removed.* Using it typically means the device and driver will lose toggle synchronization. If you really lost synchronization, you likely need to completely handshake with the device, using a request like CLEAR_HALT or SET_INTERFACE.

- **USBDEVFS_DROP_PRIVILEGES**

  This is used to relinquish the ability to do certain operations which are considered to be privileged on a usbfs file descriptor. This includes claiming arbitrary interfaces, resetting a device on which there are currently claimed interfaces from other users, and issuing USBDEVFS_IOCTL calls. The ioctl parameter is a 32 bit mask of interfaces the user is allowed to claim on this file descriptor. You may issue this ioctl more than one time to narrow said mask.

<a id="rst-synchronous-i-o-support"></a>

#### Synchronous I/O Support

Synchronous requests involve the kernel blocking until the user mode request completes, either by finishing successfully or by reporting an error. In most cases this is the simplest way to use usbfs, although as noted above it does prevent performing I/O to more than one endpoint at a time.

- **USBDEVFS_BULK**

  Issues a bulk read or write request to the device. The ioctl parameter is a pointer to this structure:



  ```text
  struct usbdevfs_bulktransfer {
          unsigned int  ep;
          unsigned int  len;
          unsigned int  timeout; /* in milliseconds */
          void          *data;
  };
  ```

  The `ep` value identifies a bulk endpoint number (1 to 15, as identified in an endpoint descriptor), masked with USB_DIR_IN when referring to an endpoint which sends data to the host from the device. The length of the data buffer is identified by `len`; Recent kernels support requests up to about 128KBytes. *FIXME say how read length is returned, and how short reads are handled.*.

- **USBDEVFS_CLEAR_HALT**

  Clears endpoint halt (stall) and resets the endpoint toggle. This is only meaningful for bulk or interrupt endpoints. The ioctl parameter is an integer endpoint number (1 to 15, as identified in an endpoint descriptor), masked with USB_DIR_IN when referring to an endpoint which sends data to the host from the device.

  Use this on bulk or interrupt endpoints which have stalled, returning `-EPIPE` status to a data transfer request. Do not issue the control request directly, since that could invalidate the host's record of the data toggle.

- **USBDEVFS_CONTROL**

  Issues a control request to the device. The ioctl parameter points to a structure like this:



  ```text
  struct usbdevfs_ctrltransfer {
          __u8   bRequestType;
          __u8   bRequest;
          __u16  wValue;
          __u16  wIndex;
          __u16  wLength;
          __u32  timeout;  /* in milliseconds */
          void   *data;
  };
  ```

  The first eight bytes of this structure are the contents of the SETUP packet to be sent to the device; see the USB 2.0 specification for details. The bRequestType value is composed by combining a `USB_TYPE_*` value, a `USB_DIR_*` value, and a `USB_RECIP_*` value (from `linux/usb.h`). If wLength is nonzero, it describes the length of the data buffer, which is either written to the device (USB_DIR_OUT) or read from the device (USB_DIR_IN).

  At this writing, you can't transfer more than 4 KBytes of data to or from a device; usbfs has a limit, and some host controller drivers have a limit. (That's not usually a problem.) *Also* there's no way to say it's not OK to get a short read back from the device.

- **USBDEVFS_RESET**

  Does a USB level device reset. The ioctl parameter is ignored. After the reset, this rebinds all device interfaces. File modification time is not updated by this request.

> [!WARNING]
>
> *Avoid using this call* until some usbcore bugs get fixed, since it does not fully synchronize device, interface, and driver (not just usbfs) state.

- **USBDEVFS_SETINTERFACE**

  Sets the alternate setting for an interface. The ioctl parameter is a pointer to a structure like this:



  ```text
  struct usbdevfs_setinterface {
          unsigned int  interface;
          unsigned int  altsetting;
  };
  ```

  File modification time is not updated by this request.

  Those struct members are from some interface descriptor applying to the current configuration. The interface number is the bInterfaceNumber value, and the altsetting number is the bAlternateSetting value. (This resets each endpoint in the interface.)

- **USBDEVFS_SETCONFIGURATION**

  Issues the `usb_set_configuration()` call for the device. The parameter is an integer holding the number of a configuration (bConfigurationValue from descriptor). File modification time is not updated by this request.

> [!WARNING]
>
> *Avoid using this call* until some usbcore bugs get fixed, since it does not fully synchronize device, interface, and driver (not just usbfs) state.

<a id="rst-asynchronous-i-o-support"></a>

#### Asynchronous I/O Support

As mentioned above, there are situations where it may be important to initiate concurrent operations from user mode code. This is particularly important for periodic transfers (interrupt and isochronous), but it can be used for other kinds of USB requests too. In such cases, the asynchronous requests described here are essential. Rather than submitting one request and having the kernel block until it completes, the blocking is separate.

These requests are packaged into a structure that resembles the URB used by kernel device drivers. (No POSIX Async I/O support here, sorry.) It identifies the endpoint type (`USBDEVFS_URB_TYPE_*`), endpoint (number, masked with USB_DIR_IN as appropriate), buffer and length, and a user "context" value serving to uniquely identify each request. (It's usually a pointer to per-request data.) Flags can modify requests (not as many as supported for kernel drivers).

Each request can specify a realtime signal number (between SIGRTMIN and SIGRTMAX, inclusive) to request a signal be sent when the request completes.

When usbfs returns these urbs, the status value is updated, and the buffer may have been modified. Except for isochronous transfers, the actual_length is updated to say how many bytes were transferred; if the USBDEVFS_URB_DISABLE_SPD flag is set ("short packets are not OK"), if fewer bytes were read than were requested then you get an error report:



```text
struct usbdevfs_iso_packet_desc {
        unsigned int                     length;
        unsigned int                     actual_length;
        unsigned int                     status;
};

struct usbdevfs_urb {
        unsigned char                    type;
        unsigned char                    endpoint;
        int                              status;
        unsigned int                     flags;
        void                             *buffer;
        int                              buffer_length;
        int                              actual_length;
        int                              start_frame;
        int                              number_of_packets;
        int                              error_count;
        unsigned int                     signr;
        void                             *usercontext;
        struct usbdevfs_iso_packet_desc  iso_frame_desc[];
};
```

For these asynchronous requests, the file modification time reflects when the request was initiated. This contrasts with their use with the synchronous requests, where it reflects when requests complete.

- **USBDEVFS_DISCARDURB**

  *TBS* File modification time is not updated by this request.

- **USBDEVFS_DISCSIGNAL**

  *TBS* File modification time is not updated by this request.

- **USBDEVFS_REAPURB**

  *TBS* File modification time is not updated by this request.

- **USBDEVFS_REAPURBNDELAY**

  *TBS* File modification time is not updated by this request.

- **USBDEVFS_SUBMITURB**

  *TBS*

<a id="rst-the-usb-devices"></a>

## The USB devices

The USB devices are now exported via debugfs:

- `/sys/kernel/debug/usb/devices` ... a text file showing each of the USB devices on known to the kernel, and their configuration descriptors. You can also poll() this to learn about new devices.

<a id="rst-sys-kernel-debug-usb-devices"></a>

### /sys/kernel/debug/usb/devices

This file is handy for status viewing tools in user mode, which can scan the text format and ignore most of it. More detailed device status (including class and vendor status) is available from device-specific files. For information about the current format of this file, see below.

This file, in combination with the poll() system call, can also be used to detect when devices are added or removed:



```text
int fd;
struct pollfd pfd;

fd = open("/sys/kernel/debug/usb/devices", O_RDONLY);
pfd = { fd, POLLIN, 0 };
for (;;) {
    /* The first time through, this call will return immediately. */
    poll(&pfd, 1, -1);

    /* To see what's changed, compare the file's previous and current
       contents or scan the filesystem.  (Scanning is more precise.) */
}
```

Note that this behavior is intended to be used for informational and debug purposes. It would be more appropriate to use programs such as udev or HAL to initialize a device or start a user-mode helper program, for instance.

In this file, each device's output has multiple lines of ASCII output.

I made it ASCII instead of binary on purpose, so that someone can obtain some useful data from it without the use of an auxiliary program.  However, with an auxiliary program, the numbers in the first 4 columns of each `T:` line (topology info: Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.

Each line is tagged with a one-character ID for that line:



```text
T = Topology (etc.)
B = Bandwidth (applies only to USB host controllers, which are
virtualized as root hubs)
D = Device descriptor info.
P = Product ID info. (from Device descriptor, but they won't fit
together on one line)
S = String descriptors.
C = Configuration descriptor info. (* = active configuration)
I = Interface descriptor info.
E = Endpoint descriptor info.
```

<a id="rst-sys-kernel-debug-usb-devices-output-format"></a>

#### /sys/kernel/debug/usb/devices output format

- **Legend::**

  d = decimal number (may have leading spaces or 0's) x = hexadecimal number (may have leading spaces or 0's) s = string

<a id="rst-topology-info"></a>

##### Topology info



```text
T:  Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=dddd MxCh=dd
|   |      |      |       |       |      |        |        |__MaxChildren
|   |      |      |       |       |      |        |__Device Speed in Mbps
|   |      |      |       |       |      |__DeviceNumber
|   |      |      |       |       |__Count of devices at this level
|   |      |      |       |__Connector/Port on Parent for this device
|   |      |      |__Parent DeviceNumber
|   |      |__Level in topology for this bus
|   |__Bus number
|__Topology info tag
```

Speed may be:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> 1.5
>
> </td>
> <td>
>
>
> Mbit/s for low speed USB
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 12
>
> </td>
> <td>
>
>
> Mbit/s for full speed USB
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 480
>
> </td>
> <td>
>
>
> Mbit/s for high speed USB (added for USB 2.0)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 5000
>
> </td>
> <td>
>
>
> Mbit/s for SuperSpeed USB (added for USB 3.0)
>
> </td>
> </tr>
> </tbody>
> </table>

For reasons lost in the mists of time, the Port number is always too low by 1.  For example, a device plugged into port 4 will show up with `Port=03`.

<a id="rst-bandwidth-info"></a>

##### Bandwidth info



```text
B:  Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
|   |                       |         |__Number of isochronous requests
|   |                       |__Number of interrupt requests
|   |__Total Bandwidth allocated to this bus
|__Bandwidth info tag
```

Bandwidth allocation is an approximation of how much of one frame (millisecond) is in use.  It reflects only periodic transfers, which are the only transfers that reserve bandwidth.  Control and bulk transfers use all other bandwidth, including reserved bandwidth that is not used for transfers (such as for short packets).

The percentage is how much of the "reserved" bandwidth is scheduled by those transfers.  For a low or full speed bus (loosely, "USB 1.1"), 90% of the bus bandwidth is reserved.  For a high speed bus (loosely, "USB 2.0") 80% is reserved.

<a id="rst-device-descriptor-info-product-id-info"></a>

##### Device descriptor info &amp; Product ID info



```text
D:  Ver=x.xx Cls=xx(s) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx
```

where:



```text
D:  Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
|   |        |             |      |       |       |__NumberConfigurations
|   |        |             |      |       |__MaxPacketSize of Default Endpoint
|   |        |             |      |__DeviceProtocol
|   |        |             |__DeviceSubClass
|   |        |__DeviceClass
|   |__Device USB version
|__Device info tag #1
```

where:



```text
P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx
|   |           |           |__Product revision number
|   |           |__Product ID code
|   |__Vendor ID code
|__Device info tag #2
```

<a id="rst-string-descriptor-info"></a>

##### String descriptor info



```text
S:  Manufacturer=ssss
|   |__Manufacturer of this device as read from the device.
|      For USB host controller drivers (virtual root hubs) this may
|      be omitted, or (for newer drivers) will identify the kernel
|      version and the driver which provides this hub emulation.
|__String info tag

S:  Product=ssss
|   |__Product description of this device as read from the device.
|      For older USB host controller drivers (virtual root hubs) this
|      indicates the driver; for newer ones, it's a product (and vendor)
|      description that often comes from the kernel's PCI ID database.
|__String info tag

S:  SerialNumber=ssss
|   |__Serial Number of this device as read from the device.
|      For USB host controller drivers (virtual root hubs) this is
|      some unique ID, normally a bus ID (address or slot name) that
|      can't be shared with any other device.
|__String info tag
```

<a id="rst-configuration-descriptor-info"></a>

##### Configuration descriptor info



```text
C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
| | |       |       |      |__MaxPower in mA
| | |       |       |__Attributes
| | |       |__ConfiguratioNumber
| | |__NumberOfInterfaces
| |__ "*" indicates the active configuration (others are " ")
|__Config info tag
```

USB devices may have multiple configurations, each of which act rather differently.  For example, a bus-powered configuration might be much less capable than one that is self-powered.  Only one device configuration can be active at a time; most devices have only one configuration.

Each configuration consists of one or more interfaces.  Each interface serves a distinct "function", which is typically bound to a different USB device driver.  One common example is a USB speaker with an audio interface for playback, and a HID interface for use with software volume control.

<a id="rst-interface-descriptor-info-can-be-multiple-per-config"></a>

##### Interface descriptor info (can be multiple per Config)



```text
I:* If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
| | |      |      |       |             |      |       |__Driver name
| | |      |      |       |             |      |          or "(none)"
| | |      |      |       |             |      |__InterfaceProtocol
| | |      |      |       |             |__InterfaceSubClass
| | |      |      |       |__InterfaceClass
| | |      |      |__NumberOfEndpoints
| | |      |__AlternateSettingNumber
| | |__InterfaceNumber
| |__ "*" indicates the active altsetting (others are " ")
|__Interface info tag
```

A given interface may have one or more "alternate" settings. For example, default settings may not use more than a small amount of periodic bandwidth.  To use significant fractions of bus bandwidth, drivers must select a non-default altsetting.

Only one setting for an interface may be active at a time, and only one driver may bind to an interface at a time.  Most devices have only one alternate setting per interface.

<a id="rst-endpoint-descriptor-info-can-be-multiple-per-interface"></a>

##### Endpoint descriptor info (can be multiple per Interface)



```text
E:  Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddss
|   |        |            |         |__Interval (max) between transfers
|   |        |            |__EndpointMaxPacketSize
|   |        |__Attributes(EndpointType)
|   |__EndpointAddress(I=In,O=Out)
|__Endpoint info tag
```

The interval is nonzero for all periodic (interrupt or isochronous) endpoints.  For high speed endpoints the transfer interval may be measured in microseconds rather than milliseconds.

For high speed periodic endpoints, the `EndpointMaxPacketSize` reflects the per-microframe data transfer size.  For "high bandwidth" endpoints, that can reflect two or three packets (for up to 3KBytes every 125 usec) per endpoint.

With the Linux-USB stack, periodic bandwidth reservations use the transfer intervals and sizes provided by URBs, which can be less than those found in endpoint descriptor.

<a id="rst-usage-examples"></a>

#### Usage examples

If a user or script is interested only in Topology info, for example, use something like `grep ^T: /sys/kernel/debug/usb/devices` for only the Topology lines.  A command like `grep -i ^[tdp]: /sys/kernel/debug/usb/devices` can be used to list only the lines that begin with the characters in square brackets, where the valid characters are TDPCIE.  With a slightly more able script, it can display any selected lines (for example, only T, D, and P lines) and change their output format.  (The `procusb` Perl script is the beginning of this idea.  It will list only selected lines \[selected from TBDPSCIE\] or "All" lines from `/sys/kernel/debug/usb/devices`.)

The Topology lines can be used to generate a graphic/pictorial of the USB devices on a system's root hub.  (See more below on how to do this.)

The Interface lines can be used to determine what driver is being used for each device, and which altsetting it activated.

The Configuration lines could be used to list maximum power (in milliamps) that a system's USB devices are using. For example, `grep ^C: /sys/kernel/debug/usb/devices`.

Here's an example, from a system which has a UHCI root hub, an external hub connected to the root hub, and a mouse and a serial converter connected to the external hub.



```text
T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 2
B:  Alloc= 28/900 us ( 3%), #Int=  2, #Iso=  0
D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
P:  Vendor=0000 ProdID=0000 Rev= 0.00
S:  Product=USB UHCI Root Hub
S:  SerialNumber=dce0
C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr=  0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
E:  Ad=81(I) Atr=03(Int.) MxPS=   8 Ivl=255ms

T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 4
D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
P:  Vendor=0451 ProdID=1446 Rev= 1.00
C:* #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=100mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
E:  Ad=81(I) Atr=03(Int.) MxPS=   1 Ivl=255ms

T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 0
D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
P:  Vendor=04b4 ProdID=0001 Rev= 0.00
C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse
E:  Ad=81(I) Atr=03(Int.) MxPS=   3 Ivl= 10ms

T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
P:  Vendor=0565 ProdID=0001 Rev= 1.08
S:  Manufacturer=Peracom Networks, Inc.
S:  Product=Peracom USB to Serial Converter
C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=100mA
I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
E:  Ad=81(I) Atr=02(Bulk) MxPS=  64 Ivl= 16ms
E:  Ad=01(O) Atr=02(Bulk) MxPS=  16 Ivl= 16ms
E:  Ad=82(I) Atr=03(Int.) MxPS=   8 Ivl=  8ms
```

Selecting only the `T:` and `I:` lines from this (for example, by using `procusb ti`), we have



```text
T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 2
T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 4
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 0
I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse
T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
```

Physically this looks like (or could be converted to):



```text
                    +------------------+
                    |  PC/root_hub (12)|   Dev# = 1
                    +------------------+   (nn) is Mbps.
  Level 0           |  CN.0   |  CN.1  |   [CN = connector/port #]
                    +------------------+
                        /
                       /
          +-----------------------+
Level 1   | Dev#2: 4-port hub (12)|
          +-----------------------+
          |CN.0 |CN.1 |CN.2 |CN.3 |
          +-----------------------+
              \           \____________________
               \_____                          \
                     \                          \
             +--------------------+      +--------------------+
Level 2      | Dev# 3: mouse (1.5)|      | Dev# 4: serial (12)|
             +--------------------+      +--------------------+
```

Or, in a more tree-like structure (ports \[Connectors\] without connections could be omitted):



```text
PC:  Dev# 1, root hub, 2 ports, 12 Mbps
|_ CN.0:  Dev# 2, hub, 4 ports, 12 Mbps
     |_ CN.0:  Dev #3, mouse, 1.5 Mbps
     |_ CN.1:
     |_ CN.2:  Dev #4, serial, 12 Mbps
     |_ CN.3:
|_ CN.1:
```

---

# USB3 debug port

_Peios Kernel / Hardware and drivers / Driver development / USB_

> This is a HOWTO for using the USB3 debug port on x86 systems.

<a id="rst-usb3-debug-port"></a>

**Author:** Lu Baolu &lt;[baolu.lu@linux.intel.com](<mailto:baolu.lu@linux.intel.com>)&gt;

**Date:** March 2017

<a id="rst-general"></a>

## GENERAL

This is a HOWTO for using the USB3 debug port on x86 systems.

Before using any kernel debugging functionality based on USB3 debug port, you need to:



```text
1) check whether any USB3 debug port is available in
   your system;
2) check which port is used for debugging purposes;
3) have a USB 3.0 super-speed A-to-A debugging cable.
```

<a id="rst-introduction"></a>

## INTRODUCTION

The xHCI debug capability (DbC) is an optional but standalone functionality provided by the xHCI host controller. The xHCI specification describes DbC in the section 7.6.

When DbC is initialized and enabled, it will present a debug device through the debug port (normally the first USB3 super-speed port). The debug device is fully compliant with the USB framework and provides the equivalent of a very high performance full-duplex serial link between the debug target (the system under debugging) and a debug host.

<a id="rst-early-printk"></a>

## EARLY PRINTK

DbC has been designed to log early printk messages. One use for this feature is kernel debugging. For example, when your machine crashes very early before the regular console code is initialized. Other uses include simpler, lockless logging instead of a full- blown printk console driver and klogd.

On the debug target system, you need to customize a debugging kernel with CONFIG_EARLY_PRINTK_USB_XDBC enabled. And, add below kernel boot parameter:



```text
"earlyprintk=xdbc"
```

If there are multiple xHCI controllers in your system, you can append a host controller index to this kernel parameter. This index starts from 0.

Current design doesn't support DbC runtime suspend/resume. As the result, you'd better disable runtime power management for USB subsystem by adding below kernel boot parameter:



```text
"usbcore.autosuspend=-1"
```

Before starting the debug target, you should connect the debug port to a USB port (root port or port of any external hub) on the debug host. The cable used to connect these two ports should be a USB 3.0 super-speed A-to-A debugging cable.

During early boot of the debug target, DbC will be detected and initialized. After initialization, the debug host should be able to enumerate the debug device in debug target. The debug host will then bind the debug device with the usb_debug driver module and create the /dev/ttyUSB device.

If the debug device enumeration goes smoothly, you should be able to see below kernel messages on the debug host:



```text
# tail -f /var/log/kern.log
[ 1815.983374] usb 4-3: new SuperSpeed USB device number 4 using xhci_hcd
[ 1815.999595] usb 4-3: LPM exit latency is zeroed, disabling LPM.
[ 1815.999899] usb 4-3: New USB device found, idVendor=1d6b, idProduct=0004
[ 1815.999902] usb 4-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 1815.999903] usb 4-3: Product: Remote GDB
[ 1815.999904] usb 4-3: Manufacturer: Linux
[ 1815.999905] usb 4-3: SerialNumber: 0001
[ 1816.000240] usb_debug 4-3:1.0: xhci_dbc converter detected
[ 1816.000360] usb 4-3: xhci_dbc converter now attached to ttyUSB0
```

You can use any communication program, for example minicom, to read and view the messages. Below simple bash scripts can help you to check the sanity of the setup.



```sh
===== start of bash scripts =============
#!/bin/bash

while true ; do
        while [ ! -d /sys/class/tty/ttyUSB0 ] ; do
                :
        done
cat /dev/ttyUSB0
done
===== end of bash scripts ===============
```

<a id="rst-serial-tty"></a>

## Serial TTY

The DbC support has been added to the xHCI driver. You can get a debug device provided by the DbC at runtime.

In order to use this, you need to make sure your kernel has been configured to support USB_XHCI_DBGCAP. A sysfs attribute under the xHCI device node is used to enable or disable DbC. By default, DbC is disabled:



```text
root@target:/sys/bus/pci/devices/0000:00:14.0# cat dbc
disabled
```

Enable DbC with the following command:



```text
root@target:/sys/bus/pci/devices/0000:00:14.0# echo enable > dbc
```

You can check the DbC state at anytime:



```text
root@target:/sys/bus/pci/devices/0000:00:14.0# cat dbc
enabled
```

Connect the debug target to the debug host with a USB 3.0 super- speed A-to-A debugging cable. You can see /dev/ttyDBC0 created on the debug target. You will see below kernel message lines:



```text
root@target: tail -f /var/log/kern.log
[  182.730103] xhci_hcd 0000:00:14.0: DbC connected
[  191.169420] xhci_hcd 0000:00:14.0: DbC configured
[  191.169597] xhci_hcd 0000:00:14.0: DbC now attached to /dev/ttyDBC0
```

Accordingly, the DbC state has been brought up to:



```text
root@target:/sys/bus/pci/devices/0000:00:14.0# cat dbc
configured
```

On the debug host, you will see the debug device has been enumerated. You will see below kernel message lines:



```text
root@host: tail -f /var/log/kern.log
[   79.454780] usb 2-2.1: new SuperSpeed USB device number 3 using xhci_hcd
[   79.475003] usb 2-2.1: LPM exit latency is zeroed, disabling LPM.
[   79.475389] usb 2-2.1: New USB device found, idVendor=1d6b, idProduct=0010
[   79.475390] usb 2-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[   79.475391] usb 2-2.1: Product: Linux USB Debug Target
[   79.475392] usb 2-2.1: Manufacturer: Linux Foundation
[   79.475393] usb 2-2.1: SerialNumber: 0001
```

The debug device works now. You can use any communication or debugging program to talk between the host and the target.

---

# Writing a MUSB Glue Layer

_Peios Kernel / Hardware and drivers / Driver development / USB_

> The Linux MUSB subsystem is part of the larger Linux USB subsystem. It provides support for embedded USB Device Controllers (UDC) that do not use Universal Host Controller Interface (UHCI) or Open Host Controller Interface (OHCI).

<a id="rst-writing-a-musb-glue-layer"></a>

**Author:** Apelete Seketeli

<a id="rst-introduction"></a>

## Introduction

The Linux MUSB subsystem is part of the larger Linux USB subsystem. It provides support for embedded USB Device Controllers (UDC) that do not use Universal Host Controller Interface (UHCI) or Open Host Controller Interface (OHCI).

Instead, these embedded UDC rely on the USB On-the-Go (OTG) specification which they implement at least partially. The silicon reference design used in most cases is the Multipoint USB Highspeed Dual-Role Controller (MUSB HDRC) found in the Mentor Graphics Inventra™ design.

As a self-taught exercise I have written an MUSB glue layer for the Ingenic JZ4740 SoC, modelled after the many MUSB glue layers in the kernel source tree. This layer can be found at `drivers/usb/musb/jz4740.c`. In this documentation I will walk through the basics of the `jz4740.c` glue layer, explaining the different pieces and what needs to be done in order to write your own device glue layer.

<a id="rst-linux-musb-basics"></a>
<a id="rst-musb-basics"></a>

## Linux MUSB Basics

To get started on the topic, please read USB On-the-Go Basics (see Resources) which provides an introduction of USB OTG operation at the hardware level. A couple of wiki pages by Texas Instruments and Analog Devices also provide an overview of the Linux kernel MUSB configuration, albeit focused on some specific devices provided by these companies. Finally, getting acquainted with the USB specification at USB home page may come in handy, with practical instance provided through the Writing USB Device Drivers documentation (again, see Resources).

Linux USB stack is a layered architecture in which the MUSB controller hardware sits at the lowest. The MUSB controller driver abstract the MUSB controller hardware to the Linux USB stack:



```text
    ------------------------
    |                      | <------- drivers/usb/gadget
    | Linux USB Core Stack | <------- drivers/usb/host
    |                      | <------- drivers/usb/core
    ------------------------
               ⬍
   --------------------------
   |                        | <------ drivers/usb/musb/musb_gadget.c
   | MUSB Controller driver | <------ drivers/usb/musb/musb_host.c
   |                        | <------ drivers/usb/musb/musb_core.c
   --------------------------
               ⬍
---------------------------------
| MUSB Platform Specific Driver |
|                               | <-- drivers/usb/musb/jz4740.c
|       aka "Glue Layer"        |
---------------------------------
               ⬍
---------------------------------
|   MUSB Controller Hardware    |
---------------------------------
```

As outlined above, the glue layer is actually the platform specific code sitting in between the controller driver and the controller hardware.

Just like a Linux USB driver needs to register itself with the Linux USB subsystem, the MUSB glue layer needs first to register itself with the MUSB controller driver. This will allow the controller driver to know about which device the glue layer supports and which functions to call when a supported device is detected or released; remember we are talking about an embedded controller chip here, so no insertion or removal at run-time.

All of this information is passed to the MUSB controller driver through a `platform_driver` structure defined in the glue layer as:



```text
static struct platform_driver jz4740_driver = {
    .probe      = jz4740_probe,
    .remove     = jz4740_remove,
    .driver     = {
        .name   = "musb-jz4740",
    },
};
```

The probe and remove function pointers are called when a matching device is detected and, respectively, released. The name string describes the device supported by this glue layer. In the current case it matches a platform\_device structure declared in `arch/mips/jz4740/platform.c`. Note that we are not using device tree bindings here.

In order to register itself to the controller driver, the glue layer goes through a few steps, basically allocating the controller hardware resources and initialising a couple of circuits. To do so, it needs to keep track of the information used throughout these steps. This is done by defining a private `jz4740_glue` structure:



```text
struct jz4740_glue {
    struct device           *dev;
    struct platform_device  *musb;
    struct clk      *clk;
};
```

The dev and musb members are both device structure variables. The first one holds generic information about the device, since it's the basic device structure, and the latter holds information more closely related to the subsystem the device is registered to. The clk variable keeps information related to the device clock operation.

Let's go through the steps of the probe function that leads the glue layer to register itself to the controller driver.

> [!NOTE]
>
> For the sake of readability each function will be split in logical parts, each part being shown as if it was independent from the others.



```c
static int jz4740_probe(struct platform_device *pdev)
{
    struct platform_device      *musb;
    struct jz4740_glue      *glue;
    struct clk                      *clk;
    int             ret;

    glue = devm_kzalloc(&pdev->dev, sizeof(*glue), GFP_KERNEL);
    if (!glue)
        return -ENOMEM;

    musb = platform_device_alloc("musb-hdrc", PLATFORM_DEVID_AUTO);
    if (!musb) {
        dev_err(&pdev->dev, "failed to allocate musb device\n");
        return -ENOMEM;
    }

    clk = devm_clk_get(&pdev->dev, "udc");
    if (IS_ERR(clk)) {
        dev_err(&pdev->dev, "failed to get clock\n");
        ret = PTR_ERR(clk);
        goto err_platform_device_put;
    }

    ret = clk_prepare_enable(clk);
    if (ret) {
        dev_err(&pdev->dev, "failed to enable clock\n");
        goto err_platform_device_put;
    }

    musb->dev.parent        = &pdev->dev;

    glue->dev           = &pdev->dev;
    glue->musb          = musb;
    glue->clk           = clk;

    return 0;

err_platform_device_put:
    platform_device_put(musb);
    return ret;
}
```

The first few lines of the probe function allocate and assign the glue, musb and clk variables. The `GFP_KERNEL` flag (line 8) allows the allocation process to sleep and wait for memory, thus being usable in a locking situation. The `PLATFORM_DEVID_AUTO` flag (line 12) allows automatic allocation and management of device IDs in order to avoid device namespace collisions with explicit IDs. With `devm_clk_get()` (line 18) the glue layer allocates the clock -- the `devm_` prefix indicates that `clk_get()` is managed: it automatically frees the allocated clock resource data when the device is released -- and enable it.

Then comes the registration steps:



```c
static int jz4740_probe(struct platform_device *pdev)
{
    struct musb_hdrc_platform_data  *pdata = &jz4740_musb_platform_data;

    pdata->platform_ops     = &jz4740_musb_ops;

    platform_set_drvdata(pdev, glue);

    ret = platform_device_add_resources(musb, pdev->resource,
                        pdev->num_resources);
    if (ret) {
        dev_err(&pdev->dev, "failed to add resources\n");
        goto err_clk_disable;
    }

    ret = platform_device_add_data(musb, pdata, sizeof(*pdata));
    if (ret) {
        dev_err(&pdev->dev, "failed to add platform_data\n");
        goto err_clk_disable;
    }

    return 0;

err_clk_disable:
    clk_disable_unprepare(clk);
err_platform_device_put:
    platform_device_put(musb);
    return ret;
}
```

The first step is to pass the device data privately held by the glue layer on to the controller driver through `platform_set_drvdata()` (line 7). Next is passing on the device resources information, also privately held at that point, through `platform_device_add_resources()` (line 9).

Finally comes passing on the platform specific data to the controller driver (line 16). Platform data will be discussed in [Device Platform Data](<#rst-musb-dev-platform-data>), but here we are looking at the `platform_ops` function pointer (line 5) in `musb_hdrc_platform_data` structure (line 3). This function pointer allows the MUSB controller driver to know which function to call for device operation:



```text
static const struct musb_platform_ops jz4740_musb_ops = {
    .init       = jz4740_musb_init,
    .exit       = jz4740_musb_exit,
};
```

Here we have the minimal case where only init and exit functions are called by the controller driver when needed. Fact is the JZ4740 MUSB controller is a basic controller, lacking some features found in other controllers, otherwise we may also have pointers to a few other functions like a power management function or a function to switch between OTG and non-OTG modes, for instance.

At that point of the registration process, the controller driver actually calls the init function:

>
>
> ```c
> static int jz4740_musb_init(struct musb *musb)
> {
>     musb->xceiv = usb_get_phy(USB_PHY_TYPE_USB2);
>     if (!musb->xceiv) {
>         pr_err("HS UDC: no transceiver configured\n");
>         return -ENODEV;
>     }
>
>     /* Silicon does not implement ConfigData register.
>      * Set dyn_fifo to avoid reading EP config from hardware.
>      */
>     musb->dyn_fifo = true;
>
>     musb->isr = jz4740_musb_interrupt;
>
>     return 0;
> }
> ```

The goal of `jz4740_musb_init()` is to get hold of the transceiver driver data of the MUSB controller hardware and pass it on to the MUSB controller driver, as usual. The transceiver is the circuitry inside the controller hardware responsible for sending/receiving the USB data. Since it is an implementation of the physical layer of the OSI model, the transceiver is also referred to as PHY.

Getting hold of the `MUSB PHY` driver data is done with `usb_get_phy()` which returns a pointer to the structure containing the driver instance data. The next couple of instructions (line 12 and 14) are used as a quirk and to setup IRQ handling respectively. Quirks and IRQ handling will be discussed later in [Device Quirks](<#rst-musb-dev-quirks>) and [Handling IRQs](<#rst-musb-handling-irqs>)



```text
static int jz4740_musb_exit(struct musb *musb)
{
    usb_put_phy(musb->xceiv);

    return 0;
}
```

Acting as the counterpart of init, the exit function releases the MUSB PHY driver when the controller hardware itself is about to be released.

Again, note that init and exit are fairly simple in this case due to the basic set of features of the JZ4740 controller hardware. When writing an musb glue layer for a more complex controller hardware, you might need to take care of more processing in those two functions.

Returning from the init function, the MUSB controller driver jumps back into the probe function:



```text
static int jz4740_probe(struct platform_device *pdev)
{
    ret = platform_device_add(musb);
    if (ret) {
        dev_err(&pdev->dev, "failed to register musb device\n");
        goto err_clk_disable;
    }

    return 0;

err_clk_disable:
    clk_disable_unprepare(clk);
err_platform_device_put:
    platform_device_put(musb);
    return ret;
}
```

This is the last part of the device registration process where the glue layer adds the controller hardware device to Linux kernel device hierarchy: at this stage, all known information about the device is passed on to the Linux USB core stack:

>
>
> ```c
> static int jz4740_remove(struct platform_device *pdev)
> {
>     struct jz4740_glue  *glue = platform_get_drvdata(pdev);
>
>     platform_device_unregister(glue->musb);
>     clk_disable_unprepare(glue->clk);
>
>     return 0;
> }
> ```

Acting as the counterpart of probe, the remove function unregister the MUSB controller hardware (line 5) and disable the clock (line 6), allowing it to be gated.

<a id="rst-handling-irqs"></a>
<a id="rst-musb-handling-irqs"></a>

## Handling IRQs

Additionally to the MUSB controller hardware basic setup and registration, the glue layer is also responsible for handling the IRQs:

>
>
> ```c
> static irqreturn_t jz4740_musb_interrupt(int irq, void *__hci)
> {
>     unsigned long   flags;
>     irqreturn_t     retval = IRQ_NONE;
>     struct musb     *musb = __hci;
>
>     spin_lock_irqsave(&musb->lock, flags);
>
>     musb->int_usb = musb_readb(musb->mregs, MUSB_INTRUSB);
>     musb->int_tx = musb_readw(musb->mregs, MUSB_INTRTX);
>     musb->int_rx = musb_readw(musb->mregs, MUSB_INTRRX);
>
>     /*
>      * The controller is gadget only, the state of the host mode IRQ bits is
>      * undefined. Mask them to make sure that the musb driver core will
>      * never see them set
>      */
>     musb->int_usb &= MUSB_INTR_SUSPEND | MUSB_INTR_RESUME |
>         MUSB_INTR_RESET | MUSB_INTR_SOF;
>
>     if (musb->int_usb || musb->int_tx || musb->int_rx)
>         retval = musb_interrupt(musb);
>
>     spin_unlock_irqrestore(&musb->lock, flags);
>
>     return retval;
> }
> ```

Here the glue layer mostly has to read the relevant hardware registers and pass their values on to the controller driver which will handle the actual event that triggered the IRQ.

The interrupt handler critical section is protected by the `spin_lock_irqsave()` and counterpart `spin_unlock_irqrestore()` functions (line 7 and 24 respectively), which prevent the interrupt handler code to be run by two different threads at the same time.

Then the relevant interrupt registers are read (line 9 to 11):

- `MUSB_INTRUSB`: indicates which USB interrupts are currently active,

- `MUSB_INTRTX`: indicates which of the interrupts for TX endpoints are currently active,

- `MUSB_INTRRX`: indicates which of the interrupts for TX endpoints are currently active.

Note that `musb_readb()` is used to read 8-bit registers at most, while `musb_readw()` allows us to read at most 16-bit registers. There are other functions that can be used depending on the size of your device registers. See `musb_io.h` for more information.

Instruction on line 18 is another quirk specific to the JZ4740 USB device controller, which will be discussed later in [Device Quirks](<#rst-musb-dev-quirks>).

The glue layer still needs to register the IRQ handler though. Remember the instruction on line 14 of the init function:



```text
static int jz4740_musb_init(struct musb *musb)
{
    musb->isr = jz4740_musb_interrupt;

    return 0;
}
```

This instruction sets a pointer to the glue layer IRQ handler function, in order for the controller hardware to call the handler back when an IRQ comes from the controller hardware. The interrupt handler is now implemented and registered.

<a id="rst-device-platform-data"></a>
<a id="rst-musb-dev-platform-data"></a>

## Device Platform Data

In order to write an MUSB glue layer, you need to have some data describing the hardware capabilities of your controller hardware, which is called the platform data.

Platform data is specific to your hardware, though it may cover a broad range of devices, and is generally found somewhere in the `arch/` directory, depending on your device architecture.

For instance, platform data for the JZ4740 SoC is found in `arch/mips/jz4740/platform.c`. In the `platform.c` file each device of the JZ4740 SoC is described through a set of structures.

Here is the part of `arch/mips/jz4740/platform.c` that covers the USB Device Controller (UDC):

>
>
> ```c
> /* USB Device Controller */
> struct platform_device jz4740_udc_xceiv_device = {
>     .name = "usb_phy_gen_xceiv",
>     .id   = 0,
> };
>
> static struct resource jz4740_udc_resources[] = {
>     [0] = {
>         .start = JZ4740_UDC_BASE_ADDR,
>         .end   = JZ4740_UDC_BASE_ADDR + 0x10000 - 1,
>         .flags = IORESOURCE_MEM,
>     },
>     [1] = {
>         .start = JZ4740_IRQ_UDC,
>         .end   = JZ4740_IRQ_UDC,
>         .flags = IORESOURCE_IRQ,
>         .name  = "mc",
>     },
> };
>
> struct platform_device jz4740_udc_device = {
>     .name = "musb-jz4740",
>     .id   = -1,
>     .dev  = {
>         .dma_mask          = &jz4740_udc_device.dev.coherent_dma_mask,
>         .coherent_dma_mask = DMA_BIT_MASK(32),
>     },
>     .num_resources = ARRAY_SIZE(jz4740_udc_resources),
>     .resource      = jz4740_udc_resources,
> };
> ```

The `jz4740_udc_xceiv_device` platform device structure (line 2) describes the UDC transceiver with a name and id number.

At the time of this writing, note that `usb_phy_gen_xceiv` is the specific name to be used for all transceivers that are either built-in with reference USB IP or autonomous and doesn't require any PHY programming. You will need to set `CONFIG_NOP_USB_XCEIV=y` in the kernel configuration to make use of the corresponding transceiver driver. The id field could be set to -1 (equivalent to `PLATFORM_DEVID_NONE`), -2 (equivalent to `PLATFORM_DEVID_AUTO`) or start with 0 for the first device of this kind if we want a specific id number.

The `jz4740_udc_resources` resource structure (line 7) defines the UDC registers base addresses.

The first array (line 9 to 11) defines the UDC registers base memory addresses: start points to the first register memory address, end points to the last register memory address and the flags member defines the type of resource we are dealing with. So `IORESOURCE_MEM` is used to define the registers memory addresses. The second array (line 14 to 17) defines the UDC IRQ registers addresses. Since there is only one IRQ register available for the JZ4740 UDC, start and end point at the same address. The `IORESOURCE_IRQ` flag tells that we are dealing with IRQ resources, and the name `mc` is in fact hard-coded in the MUSB core in order for the controller driver to retrieve this IRQ resource by querying it by its name.

Finally, the `jz4740_udc_device` platform device structure (line 21) describes the UDC itself.

The `musb-jz4740` name (line 22) defines the MUSB driver that is used for this device; remember this is in fact the name that we used in the `jz4740_driver` platform driver structure in [Linux MUSB Basics](<#rst-musb-basics>). The id field (line 23) is set to -1 (equivalent to `PLATFORM_DEVID_NONE`) since we do not need an id for the device: the MUSB controller driver was already set to allocate an automatic id in [Linux MUSB Basics](<#rst-musb-basics>). In the dev field we care for DMA related information here. The `dma_mask` field (line 25) defines the width of the DMA mask that is going to be used, and `coherent_dma_mask` (line 26) has the same purpose but for the `alloc_coherent` DMA mappings: in both cases we are using a 32 bits mask. Then the resource field (line 29) is simply a pointer to the resource structure defined before, while the `num_resources` field (line 28) keeps track of the number of arrays defined in the resource structure (in this case there were two resource arrays defined before).

With this quick overview of the UDC platform data at the `arch/` level now done, let's get back to the MUSB glue layer specific platform data in `drivers/usb/musb/jz4740.c`:

>
>
> ```c
> static struct musb_hdrc_config jz4740_musb_config = {
>     /* Silicon does not implement USB OTG. */
>     .multipoint = 0,
>     /* Max EPs scanned, driver will decide which EP can be used. */
>     .num_eps    = 4,
>     /* RAMbits needed to configure EPs from table */
>     .ram_bits   = 9,
>     .fifo_cfg = jz4740_musb_fifo_cfg,
>     .fifo_cfg_size = ARRAY_SIZE(jz4740_musb_fifo_cfg),
> };
>
> static struct musb_hdrc_platform_data jz4740_musb_platform_data = {
>     .mode   = MUSB_PERIPHERAL,
>     .config = &jz4740_musb_config,
> };
> ```

First the glue layer configures some aspects of the controller driver operation related to the controller hardware specifics. This is done through the `jz4740_musb_config` `musb_hdrc_config` structure.

Defining the OTG capability of the controller hardware, the multipoint member (line 3) is set to 0 (equivalent to false) since the JZ4740 UDC is not OTG compatible. Then `num_eps` (line 5) defines the number of USB endpoints of the controller hardware, including endpoint 0: here we have 3 endpoints + endpoint 0. Next is `ram_bits` (line 7) which is the width of the RAM address bus for the MUSB controller hardware. This information is needed when the controller driver cannot automatically configure endpoints by reading the relevant controller hardware registers. This issue will be discussed when we get to device quirks in [Device Quirks](<#rst-musb-dev-quirks>). Last two fields (line 8 and 9) are also about device quirks: `fifo_cfg` points to the USB endpoints configuration table and `fifo_cfg_size` keeps track of the size of the number of entries in that configuration table. More on that later in [Device Quirks](<#rst-musb-dev-quirks>).

Then this configuration is embedded inside `jz4740_musb_platform_data` `musb_hdrc_platform_data` structure (line 11): config is a pointer to the configuration structure itself, and mode tells the controller driver if the controller hardware may be used as `MUSB_HOST` only, `MUSB_PERIPHERAL` only or `MUSB_OTG` which is a dual mode.

Remember that `jz4740_musb_platform_data` is then used to convey platform data information as we have seen in the probe function in [Linux MUSB Basics](<#rst-musb-basics>).

<a id="rst-device-quirks"></a>
<a id="rst-musb-dev-quirks"></a>

## Device Quirks

Completing the platform data specific to your device, you may also need to write some code in the glue layer to work around some device specific limitations. These quirks may be due to some hardware bugs, or simply be the result of an incomplete implementation of the USB On-the-Go specification.

The JZ4740 UDC exhibits such quirks, some of which we will discuss here for the sake of insight even though these might not be found in the controller hardware you are working on.

Let's get back to the init function first:

>
>
> ```c
> static int jz4740_musb_init(struct musb *musb)
> {
>     musb->xceiv = usb_get_phy(USB_PHY_TYPE_USB2);
>     if (!musb->xceiv) {
>         pr_err("HS UDC: no transceiver configured\n");
>         return -ENODEV;
>     }
>
>     /* Silicon does not implement ConfigData register.
>      * Set dyn_fifo to avoid reading EP config from hardware.
>      */
>     musb->dyn_fifo = true;
>
>     musb->isr = jz4740_musb_interrupt;
>
>     return 0;
> }
> ```

Instruction on line 12 helps the MUSB controller driver to work around the fact that the controller hardware is missing registers that are used for USB endpoints configuration.

Without these registers, the controller driver is unable to read the endpoints configuration from the hardware, so we use line 12 instruction to bypass reading the configuration from silicon, and rely on a hard-coded table that describes the endpoints configuration instead:



```text
static const struct musb_fifo_cfg jz4740_musb_fifo_cfg[] = {
    { .hw_ep_num = 1, .style = FIFO_TX, .maxpacket = 512, },
    { .hw_ep_num = 1, .style = FIFO_RX, .maxpacket = 512, },
    { .hw_ep_num = 2, .style = FIFO_TX, .maxpacket = 64, },
};
```

Looking at the configuration table above, we see that each endpoints is described by three fields: `hw_ep_num` is the endpoint number, style is its direction (either `FIFO_TX` for the controller driver to send packets in the controller hardware, or `FIFO_RX` to receive packets from hardware), and maxpacket defines the maximum size of each data packet that can be transmitted over that endpoint. Reading from the table, the controller driver knows that endpoint 1 can be used to send and receive USB data packets of 512 bytes at once (this is in fact a bulk in/out endpoint), and endpoint 2 can be used to send data packets of 64 bytes at once (this is in fact an interrupt endpoint).

Note that there is no information about endpoint 0 here: that one is implemented by default in every silicon design, with a predefined configuration according to the USB specification. For more examples of endpoint configuration tables, see `musb_core.c`.

Let's now get back to the interrupt handler function:

>
>
> ```c
> static irqreturn_t jz4740_musb_interrupt(int irq, void *__hci)
> {
>     unsigned long   flags;
>     irqreturn_t     retval = IRQ_NONE;
>     struct musb     *musb = __hci;
>
>     spin_lock_irqsave(&musb->lock, flags);
>
>     musb->int_usb = musb_readb(musb->mregs, MUSB_INTRUSB);
>     musb->int_tx = musb_readw(musb->mregs, MUSB_INTRTX);
>     musb->int_rx = musb_readw(musb->mregs, MUSB_INTRRX);
>
>     /*
>      * The controller is gadget only, the state of the host mode IRQ bits is
>      * undefined. Mask them to make sure that the musb driver core will
>      * never see them set
>      */
>     musb->int_usb &= MUSB_INTR_SUSPEND | MUSB_INTR_RESUME |
>         MUSB_INTR_RESET | MUSB_INTR_SOF;
>
>     if (musb->int_usb || musb->int_tx || musb->int_rx)
>         retval = musb_interrupt(musb);
>
>     spin_unlock_irqrestore(&musb->lock, flags);
>
>     return retval;
> }
> ```

Instruction on line 18 above is a way for the controller driver to work around the fact that some interrupt bits used for USB host mode operation are missing in the `MUSB_INTRUSB` register, thus left in an undefined hardware state, since this MUSB controller hardware is used in peripheral mode only. As a consequence, the glue layer masks these missing bits out to avoid parasite interrupts by doing a logical AND operation between the value read from `MUSB_INTRUSB` and the bits that are actually implemented in the register.

These are only a couple of the quirks found in the JZ4740 USB device controller. Some others were directly addressed in the MUSB core since the fixes were generic enough to provide a better handling of the issues for others controller hardware eventually.

<a id="rst-conclusion"></a>

## Conclusion

Writing a Linux MUSB glue layer should be a more accessible task, as this documentation tries to show the ins and outs of this exercise.

The JZ4740 USB device controller being fairly simple, I hope its glue layer serves as a good example for the curious mind. Used with the current MUSB glue layers, this documentation should provide enough guidance to get started; should anything gets out of hand, the linux-usb mailing list archive is another helpful resource to browse through.

<a id="rst-acknowledgements"></a>

## Acknowledgements

Many thanks to Lars-Peter Clausen and Maarten ter Huurne for answering my questions while I was writing the JZ4740 glue layer and for helping me out getting the code in good shape.

I would also like to thank the Qi-Hardware community at large for its cheerful guidance and support.

<a id="rst-resources"></a>

## Resources

USB Home Page: [https://www.usb.org](<https://www.usb.org>)

linux-usb Mailing List Archives: [https://lore.kernel.org/linux-usb](<https://lore.kernel.org/linux-usb>)

USB On-the-Go Basics: [https://www.maximintegrated.com/app-notes/index.mvp/id/1822](<https://www.maximintegrated.com/app-notes/index.mvp/id/1822>)

[Writing USB Device Drivers](</kernel/hardware/driver-api/usb/writing-usb-driver.md#rst-writing-usb-driver>)

Texas Instruments USB Configuration Wiki Page: [https://web.archive.org/web/20201215135015/http://processors.wiki.ti.com/index.php/Usbgeneralpage](<https://web.archive.org/web/20201215135015/http://processors.wiki.ti.com/index.php/Usbgeneralpage>)

---

# Writing USB Device Drivers

_Peios Kernel / Hardware and drivers / Driver development / USB_

> The Linux USB subsystem has grown from supporting only two different types of devices in the 2.2.7 kernel (mice and keyboards), to over 20 different types of devices in the 2.4 kernel. Linux currently supports almost all USB class devices…

<a id="rst-writing-usb-device-drivers"></a>
<a id="rst-writing-usb-driver"></a>

**Author:** Greg Kroah-Hartman

<a id="rst-introduction"></a>

## Introduction

The Linux USB subsystem has grown from supporting only two different types of devices in the 2.2.7 kernel (mice and keyboards), to over 20 different types of devices in the 2.4 kernel. Linux currently supports almost all USB class devices (standard types of devices like keyboards, mice, modems, printers and speakers) and an ever-growing number of vendor-specific devices (such as USB to serial converters, digital cameras, Ethernet devices and MP3 players). For a full list of the different USB devices currently supported, see Resources.

The remaining kinds of USB devices that do not have support on Linux are almost all vendor-specific devices. Each vendor decides to implement a custom protocol to talk to their device, so a custom driver usually needs to be created. Some vendors are open with their USB protocols and help with the creation of Linux drivers, while others do not publish them, and developers are forced to reverse-engineer. See Resources for some links to handy reverse-engineering tools.

Because each different protocol causes a new driver to be created, I have written a generic USB driver skeleton, modelled after the pci-skeleton.c file in the kernel source tree upon which many PCI network drivers have been based. This USB skeleton can be found at drivers/usb/usb-skeleton.c in the kernel source tree. In this article I will walk through the basics of the skeleton driver, explaining the different pieces and what needs to be done to customize it to your specific device.

<a id="rst-linux-usb-basics"></a>

## Linux USB Basics

If you are going to write a Linux USB driver, please become familiar with the USB protocol specification. It can be found, along with many other useful documents, at the USB home page (see Resources). An excellent introduction to the Linux USB subsystem can be found at the USB Working Devices List (see Resources). It explains how the Linux USB subsystem is structured and introduces the reader to the concept of USB urbs (USB Request Blocks), which are essential to USB drivers.

The first thing a Linux USB driver needs to do is register itself with the Linux USB subsystem, giving it some information about which devices the driver supports and which functions to call when a device supported by the driver is inserted or removed from the system. All of this information is passed to the USB subsystem in the `usb_driver` structure. The skeleton driver declares a `usb_driver` as:



```text
static struct usb_driver skel_driver = {
        .name        = "skeleton",
        .probe       = skel_probe,
        .disconnect  = skel_disconnect,
        .suspend     = skel_suspend,
        .resume      = skel_resume,
        .pre_reset   = skel_pre_reset,
        .post_reset  = skel_post_reset,
        .id_table    = skel_table,
        .supports_autosuspend = 1,
};
```

The variable name is a string that describes the driver. It is used in informational messages printed to the system log. The probe and disconnect function pointers are called when a device that matches the information provided in the `id_table` variable is either seen or removed.

The fops and minor variables are optional. Most USB drivers hook into another kernel subsystem, such as the SCSI, network or TTY subsystem. These types of drivers register themselves with the other kernel subsystem, and any user-space interactions are provided through that interface. But for drivers that do not have a matching kernel subsystem, such as MP3 players or scanners, a method of interacting with user space is needed. The USB subsystem provides a way to register a minor device number and a set of `file_operations` function pointers that enable this user-space interaction. The skeleton driver needs this kind of interface, so it provides a minor starting number and a pointer to its `file_operations` functions.

The USB driver is then registered with a call to usb_register(), usually in the driver's init function, as shown here:



```text
static int __init usb_skel_init(void)
{
        int result;

        /* register this driver with the USB subsystem */
        result = usb_register(&skel_driver);
        if (result < 0) {
                pr_err("usb_register failed for the %s driver. Error number %d\n",
                       skel_driver.name, result);
                return -1;
        }

        return 0;
}
module_init(usb_skel_init);
```

When the driver is unloaded from the system, it needs to deregister itself with the USB subsystem. This is done with usb_deregister() function:



```text
static void __exit usb_skel_exit(void)
{
        /* deregister this driver with the USB subsystem */
        usb_deregister(&skel_driver);
}
module_exit(usb_skel_exit);
```

To enable the linux-hotplug system to load the driver automatically when the device is plugged in, you need to create a `MODULE_DEVICE_TABLE`. The following code tells the hotplug scripts that this module supports a single device with a specific vendor and product ID:



```text
/* table of devices that work with this driver */
static struct usb_device_id skel_table [] = {
        { USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
        { }                      /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, skel_table);
```

There are other macros that can be used in describing a struct `usb_device_id` for drivers that support a whole class of USB drivers. See [usb.h](</kernel/hardware/driver-api/usb/usb.md#rst-usb-header>) for more information on this.

<a id="rst-device-operation"></a>

## Device operation

When a device is plugged into the USB bus that matches the device ID pattern that your driver registered with the USB core, the probe function is called. The `usb_device` structure, interface number and the interface ID are passed to the function:



```text
static int skel_probe(struct usb_interface *interface,
    const struct usb_device_id *id)
```

The driver now needs to verify that this device is actually one that it can accept. If so, it returns 0. If not, or if any error occurs during initialization, an errorcode (such as `-ENOMEM` or `-ENODEV`) is returned from the probe function.

In the skeleton driver, we determine what end points are marked as bulk-in and bulk-out. We create buffers to hold the data that will be sent and received from the device, and a USB urb to write data to the device is initialized.

Conversely, when the device is removed from the USB bus, the disconnect function is called with the device pointer. The driver needs to clean any private data that has been allocated at this time and to shut down any pending urbs that are in the USB system.

Now that the device is plugged into the system and the driver is bound to the device, any of the functions in the `file_operations` structure that were passed to the USB subsystem will be called from a user program trying to talk to the device. The first function called will be open, as the program tries to open the device for I/O. We increment our private usage count and save a pointer to our internal structure in the file structure. This is done so that future calls to file operations will enable the driver to determine which device the user is addressing. All of this is done with the following code:



```text
/* increment our usage count for the device */
kref_get(&dev->kref);

/* save our object in the file's private structure */
file->private_data = dev;
```

After the open function is called, the read and write functions are called to receive and send data to the device. In the `skel_write` function, we receive a pointer to some data that the user wants to send to the device and the size of the data. The function determines how much data it can send to the device based on the size of the write urb it has created (this size depends on the size of the bulk out end point that the device has). Then it copies the data from user space to kernel space, points the urb to the data and submits the urb to the USB subsystem. This can be seen in the following code:



```text
/* we can only write as much as 1 urb will hold */
size_t writesize = min_t(size_t, count, MAX_TRANSFER);

/* copy the data from user space into our urb */
copy_from_user(buf, user_buffer, writesize);

/* set up our urb */
usb_fill_bulk_urb(urb,
                  dev->udev,
                  usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
                  buf,
                  writesize,
                  skel_write_bulk_callback,
                  dev);

/* send the data out the bulk port */
retval = usb_submit_urb(urb, GFP_KERNEL);
if (retval) {
        dev_err(&dev->interface->dev,
            "%s - failed submitting write urb, error %d\n",
            __func__, retval);
}
```

When the write urb is filled up with the proper information using the `usb_fill_bulk_urb()` function, we point the urb's completion callback to call our own `skel_write_bulk_callback` function. This function is called when the urb is finished by the USB subsystem. The callback function is called in interrupt context, so caution must be taken not to do very much processing at that time. Our implementation of `skel_write_bulk_callback` merely reports if the urb was completed successfully or not and then returns.

The read function works a bit differently from the write function in that we do not use an urb to transfer data from the device to the driver. Instead we call the `usb_bulk_msg()` function, which can be used to send or receive data from a device without having to create urbs and handle urb completion callback functions. We call the `usb_bulk_msg()` function, giving it a buffer into which to place any data received from the device and a timeout value. If the timeout period expires without receiving any data from the device, the function will fail and return an error message. This can be shown with the following code:



```text
/* do an immediate bulk read to get data from the device */
retval = usb_bulk_msg (skel->dev,
                       usb_rcvbulkpipe (skel->dev,
                       skel->bulk_in_endpointAddr),
                       skel->bulk_in_buffer,
                       skel->bulk_in_size,
                       &count, 5000);
/* if the read was successful, copy the data to user space */
if (!retval) {
        if (copy_to_user (buffer, skel->bulk_in_buffer, count))
                retval = -EFAULT;
        else
                retval = count;
}
```

The `usb_bulk_msg()` function can be very useful for doing single reads or writes to a device; however, if you need to read or write constantly to a device, it is recommended to set up your own urbs and submit them to the USB subsystem.

When the user program releases the file handle that it has been using to talk to the device, the release function in the driver is called. In this function we decrement our private usage count and wait for possible pending writes:



```text
/* decrement our usage count for the device */
--skel->open_count;
```

One of the more difficult problems that USB drivers must be able to handle smoothly is the fact that the USB device may be removed from the system at any point in time, even if a program is currently talking to it. It needs to be able to shut down any current reads and writes and notify the user-space programs that the device is no longer there. The following code (function `skel_delete`) is an example of how to do this:



```text
static inline void skel_delete (struct usb_skel *dev)
{
    kfree (dev->bulk_in_buffer);
    if (dev->bulk_out_buffer != NULL)
        usb_free_coherent (dev->udev, dev->bulk_out_size,
            dev->bulk_out_buffer,
            dev->write_urb->transfer_dma);
    usb_free_urb (dev->write_urb);
    kfree (dev);
}
```

If a program currently has an open handle to the device, we reset the flag `device_present`. For every read, write, release and other functions that expect a device to be present, the driver first checks this flag to see if the device is still present. If not, it releases that the device has disappeared, and a `-ENODEV` error is returned to the user-space program. When the release function is eventually called, it determines if there is no device and if not, it does the cleanup that the `skel_disconnect` function normally does if there are no open files on the device (see Listing 5).

<a id="rst-isochronous-data"></a>

## Isochronous Data

This usb-skeleton driver does not have any examples of interrupt or isochronous data being sent to or from the device. Interrupt data is sent almost exactly as bulk data is, with a few minor exceptions. Isochronous data works differently with continuous streams of data being sent to or from the device. The audio and video camera drivers are very good examples of drivers that handle isochronous data and will be useful if you also need to do this.

<a id="rst-conclusion"></a>

## Conclusion

Writing Linux USB device drivers is not a difficult task as the usb-skeleton driver shows. This driver, combined with the other current USB drivers, should provide enough examples to help a beginning author create a working driver in a minimal amount of time. The linux-usb-devel mailing list archives also contain a lot of helpful information.

<a id="rst-resources"></a>

## Resources

The Linux USB Project: [http://www.linux-usb.org/](<http://www.linux-usb.org/>)

Linux Hotplug Project: [http://linux-hotplug.sourceforge.net/](<http://linux-hotplug.sourceforge.net/>)

linux-usb Mailing List Archives: [https://lore.kernel.org/linux-usb/](<https://lore.kernel.org/linux-usb/>)

Programming Guide for Linux USB Device Drivers: [https://lmu.web.psi.ch/docu/manuals/software_manuals/linux_sl/usb_linux_programming_guide.pdf](<https://lmu.web.psi.ch/docu/manuals/software_manuals/linux_sl/usb_linux_programming_guide.pdf>)

USB Home Page: [https://www.usb.org](<https://www.usb.org>)

---

# Virtio

_Peios Kernel / Hardware and drivers / Driver development / Virtio_

> Reference for Virtio.

<a id="rst-virtio"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Virtio on Linux](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/virtio/virtio.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Writing Virtio Drivers](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/virtio/writing_virtio_drivers.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

---

# Virtio on Linux

_Peios Kernel / Hardware and drivers / Driver development / Virtio_

> Virtio is an open standard that defines a protocol for communication between drivers and devices of different types, see Chapter 5 ("Device Types") of the virtio spec ([1]). Originally developed as a standard for paravirtualized devices…

<a id="rst-virtio-on-linux"></a>
<a id="rst-virtio"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

Virtio is an open standard that defines a protocol for communication between drivers and devices of different types, see Chapter 5 ("Device Types") of the virtio spec ([\[1\]](<#rst-target-1>)). Originally developed as a standard for paravirtualized devices implemented by a hypervisor, it can be used to interface any compliant device (real or emulated) with a driver.

For illustrative purposes, this document will focus on the common case of a Linux kernel running in a virtual machine and using paravirtualized devices provided by the hypervisor, which exposes them as virtio devices via standard mechanisms such as PCI.

<a id="rst-device-driver-communication-virtqueues"></a>

## Device - Driver communication: virtqueues

Although the virtio devices are really an abstraction layer in the hypervisor, they're exposed to the guest as if they are physical devices using a specific transport method -- PCI, MMIO or CCW -- that is orthogonal to the device itself. The virtio spec defines these transport methods in detail, including device discovery, capabilities and interrupt handling.

The communication between the driver in the guest OS and the device in the hypervisor is done through shared memory (that's what makes virtio devices so efficient) using specialized data structures called virtqueues, which are actually ring buffers <a id="rst-footnote-reference-1"></a>[1](#rst-f1) of buffer descriptors similar to the ones used in a network device:


#### <a id="c-struct-vring_desc"></a>`struct vring_desc`

Virtio ring descriptors, 16 bytes long. These can chain together via **next**.

**Definition**

```c
struct vring_desc {
    __virtio64 addr;
    __virtio32 len;
    __virtio16 flags;
    __virtio16 next;
};
```

**Members**

- `addr`: buffer address (guest-physical)
- `len`: buffer length
- `flags`: descriptor flags
- `next`: index of the next descriptor in the chain,
  if the VRING_DESC_F_NEXT flag is set. We chain unused
  descriptors via this, too.


All the buffers the descriptors point to are allocated by the guest and used by the host either for reading or for writing but not for both.

Refer to Chapter 2.5 ("Virtqueues") of the virtio spec ([\[1\]](<#rst-target-1>)) for the reference definitions of virtqueues and "Virtqueues and virtio ring: How the data travels" blog post ([\[2\]](<#rst-target-2>)) for an illustrated overview of how the host device and the guest driver communicate.

The `vring_virtqueue` struct models a virtqueue, including the ring buffers and management data. Embedded in this struct is the `virtqueue` struct, which is the data structure that's ultimately used by virtio drivers:


#### <a id="c-struct-virtqueue"></a>`struct virtqueue`

a queue to register buffers for sending or receiving.

**Definition**

```c
struct virtqueue {
    struct list_head list;
    void (*callback)(struct virtqueue *vq);
    const char *name;
    struct virtio_device *vdev;
    unsigned int index;
    unsigned int num_free;
    unsigned int num_max;
    bool reset;
    void *priv;
};
```

**Members**

- `list`: the chain of virtqueues for this device
- `callback`: the function to call when buffers are consumed (can be NULL).
- `name`: the name of this virtqueue (mainly for debugging)
- `vdev`: the virtio device this queue was created for.
- `index`: the zero-based ordinal number for this queue.
- `num_free`: number of elements we expect to be able to fit.
- `num_max`: the maximum number of elements supported by the device.
- `reset`: vq is in reset state or not.
- `priv`: a pointer for the virtqueue implementation to use.

**Description**

A note on **num_free**: with indirect buffers, each buffer needs one
element in the queue, otherwise a buffer will need one element per
sg element.


The callback function pointed by this struct is triggered when the device has consumed the buffers provided by the driver. More specifically, the trigger will be an interrupt issued by the hypervisor (see vring\_interrupt()). Interrupt request handlers are registered for a virtqueue during the virtqueue setup process (transport-specific).


#### <a id="c-vring_interrupt"></a>`vring_interrupt()`

```c
irqreturn_t vring_interrupt(int irq, void *_vq)
```

notify a virtqueue on an interrupt

**Parameters**

- `int irq`: the IRQ number (ignored)
- `void *_vq`: the struct virtqueue to notify

**Description**

Calls the callback function of **_vq** to process the virtqueue
notification.


<a id="rst-device-discovery-and-probing"></a>

## Device discovery and probing

In the kernel, the virtio core contains the virtio bus driver and transport-specific drivers like `virtio-pci` and `virtio-mmio`. Then there are individual virtio drivers for specific device types that are registered to the virtio bus driver.

How a virtio device is found and configured by the kernel depends on how the hypervisor defines it. Taking the [QEMU virtio-console](<https://gitlab.com/qemu-project/qemu/-/blob/master/hw/char/virtio-console.c>) device as an example. When using PCI as a transport method, the device will present itself on the PCI bus with vendor 0x1af4 (Red Hat, Inc.) and device id 0x1003 (virtio console), as defined in the spec, so the kernel will detect it as it would do with any other PCI device.

During the PCI enumeration process, if a device is found to match the virtio-pci driver (according to the virtio-pci device table, any PCI device with vendor id = 0x1af4):



```text
/* Qumranet donated their vendor ID for devices 0x1000 thru 0x10FF. */
static const struct pci_device_id virtio_pci_id_table[] = {
        { PCI_DEVICE(PCI_VENDOR_ID_REDHAT_QUMRANET, PCI_ANY_ID) },
        { 0 }
};
```

then the virtio-pci driver is probed and, if the probing goes well, the device is registered to the virtio bus:



```text
static int virtio_pci_probe(struct pci_dev *pci_dev,
                            const struct pci_device_id *id)
{
        ...

        if (force_legacy) {
                rc = virtio_pci_legacy_probe(vp_dev);
                /* Also try modern mode if we can't map BAR0 (no IO space). */
                if (rc == -ENODEV || rc == -ENOMEM)
                        rc = virtio_pci_modern_probe(vp_dev);
                if (rc)
                        goto err_probe;
        } else {
                rc = virtio_pci_modern_probe(vp_dev);
                if (rc == -ENODEV)
                        rc = virtio_pci_legacy_probe(vp_dev);
                if (rc)
                        goto err_probe;
        }

        ...

        rc = register_virtio_device(&vp_dev->vdev);
```

When the device is registered to the virtio bus the kernel will look for a driver in the bus that can handle the device and call that driver's `probe` method.

At this point, the virtqueues will be allocated and configured by calling the appropriate `virtio_find` helper function, such as virtio\_find\_single\_vq() or virtio\_find\_vqs(), which will end up calling a transport-specific `find_vqs` method.

<a id="rst-references"></a>

## References

<a id="rst-target-1"></a>\[1\] Virtio Spec v1.2: [https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html](<https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html>)

<!-- Check for later versions of the spec as well. -->

<a id="rst-target-2"></a>\[2\] Virtqueues and virtio ring: How the data travels [https://www.redhat.com/en/blog/virtqueues-and-virtio-ring-how-data-travels](<https://www.redhat.com/en/blog/virtqueues-and-virtio-ring-how-data-travels>)

**Footnotes**

<a id="rst-f1"></a>



**[1]** that's why they may be also referred to as virtrings.

---

# Writing Virtio Drivers

_Peios Kernel / Hardware and drivers / Driver development / Virtio_

> This document serves as a basic guideline for driver programmers that need to hack a new virtio driver or understand the essentials of the existing ones. See Virtio on Linux <virtio> for a general overview of virtio.

<a id="rst-writing-virtio-drivers-1"></a>
<a id="rst-writing-virtio-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

This document serves as a basic guideline for driver programmers that need to hack a new virtio driver or understand the essentials of the existing ones. See [Virtio on Linux](</kernel/hardware/driver-api/virtio/virtio.md#rst-virtio>) for a general overview of virtio.

<a id="rst-driver-boilerplate"></a>

## Driver boilerplate

As a bare minimum, a virtio driver needs to register in the virtio bus and configure the virtqueues for the device according to its spec, the configuration of the virtqueues in the driver side must match the virtqueue definitions in the device. A basic driver skeleton could look like this:



```text
#include <linux/virtio.h>
#include <linux/virtio_ids.h>
#include <linux/virtio_config.h>
#include <linux/module.h>

/* device private data (one per device) */
struct virtio_dummy_dev {
        struct virtqueue *vq;
};

static void virtio_dummy_recv_cb(struct virtqueue *vq)
{
        struct virtio_dummy_dev *dev = vq->vdev->priv;
        char *buf;
        unsigned int len;

        while ((buf = virtqueue_get_buf(dev->vq, &len)) != NULL) {
                /* process the received data */
        }
}

static int virtio_dummy_probe(struct virtio_device *vdev)
{
        struct virtio_dummy_dev *dev = NULL;

        /* initialize device data */
        dev = kzalloc(sizeof(struct virtio_dummy_dev), GFP_KERNEL);
        if (!dev)
                return -ENOMEM;

        /* the device has a single virtqueue */
        dev->vq = virtio_find_single_vq(vdev, virtio_dummy_recv_cb, "input");
        if (IS_ERR(dev->vq)) {
                kfree(dev);
                return PTR_ERR(dev->vq);

        }
        vdev->priv = dev;

        /* from this point on, the device can notify and get callbacks */
        virtio_device_ready(vdev);

        return 0;
}

static void virtio_dummy_remove(struct virtio_device *vdev)
{
        struct virtio_dummy_dev *dev = vdev->priv;

        /*
         * disable vq interrupts: equivalent to
         * vdev->config->reset(vdev)
         */
        virtio_reset_device(vdev);

        /* detach unused buffers */
        while ((buf = virtqueue_detach_unused_buf(dev->vq)) != NULL) {
                kfree(buf);
        }

        /* remove virtqueues */
        vdev->config->del_vqs(vdev);

        kfree(dev);
}

static const struct virtio_device_id id_table[] = {
        { VIRTIO_ID_DUMMY, VIRTIO_DEV_ANY_ID },
        { 0 },
};

static struct virtio_driver virtio_dummy_driver = {
        .driver.name =  KBUILD_MODNAME,
        .id_table =     id_table,
        .probe =        virtio_dummy_probe,
        .remove =       virtio_dummy_remove,
};

module_virtio_driver(virtio_dummy_driver);
MODULE_DEVICE_TABLE(virtio, id_table);
MODULE_DESCRIPTION("Dummy virtio driver");
MODULE_LICENSE("GPL");
```

The device id `VIRTIO_ID_DUMMY` here is a placeholder, virtio drivers should be added only for devices that are defined in the spec, see include/uapi/linux/virtio\_ids.h. Device ids need to be at least reserved in the virtio spec before being added to that file.

If your driver doesn't have to do anything special in its `init` and `exit` methods, you can use the module\_virtio\_driver() helper to reduce the amount of boilerplate code.

The `probe` method does the minimum driver setup in this case (memory allocation for the device data) and initializes the virtqueue. virtio\_device\_ready() is used to enable the virtqueue and to notify the device that the driver is ready to manage the device ("DRIVER\_OK"). The virtqueues are anyway enabled automatically by the core after `probe` returns.


#### <a id="c-virtio_device_ready"></a>`virtio_device_ready()`

```c
void virtio_device_ready(struct virtio_device *dev)
```

enable vq use in probe function

**Parameters**

- `struct virtio_device *dev`: the virtio device

**Description**

Driver must call this to use vqs in the probe function.

**Note**

vqs are enabled automatically after probe returns.


In any case, the virtqueues need to be enabled before adding buffers to them.

<a id="rst-sending-and-receiving-data"></a>

## Sending and receiving data

The virtio\_dummy\_recv\_cb() callback in the code above will be triggered when the device notifies the driver after it finishes processing a descriptor or descriptor chain, either for reading or writing. However, that's only the second half of the virtio device-driver communication process, as the communication is always started by the driver regardless of the direction of the data transfer.

To configure a buffer transfer from the driver to the device, first you have to add the buffers -- packed as `scatterlists` -- to the appropriate virtqueue using any of the virtqueue\_add\_inbuf(), virtqueue\_add\_outbuf() or virtqueue\_add\_sgs(), depending on whether you need to add one input `scatterlist` (for the device to fill in), one output `scatterlist` (for the device to consume) or multiple `scatterlists`, respectively. Then, once the virtqueue is set up, a call to virtqueue\_kick() sends a notification that will be serviced by the hypervisor that implements the device:



```text
struct scatterlist sg[1];
sg_init_one(sg, buffer, BUFLEN);
virtqueue_add_inbuf(dev->vq, sg, 1, buffer, GFP_ATOMIC);
virtqueue_kick(dev->vq);
```


#### <a id="c-virtqueue_add_inbuf"></a>`virtqueue_add_inbuf()`

```c
int virtqueue_add_inbuf(struct virtqueue *vq, struct scatterlist *sg, unsigned int num, void *data, gfp_t gfp)
```

expose input buffers to other end

**Parameters**

- `struct virtqueue *vq`: the struct virtqueue we're talking about.
- `struct scatterlist *sg`: scatterlist (must be well-formed and terminated!)
- `unsigned int num`: the number of entries in **sg** writable by other side
- `void *data`: the token identifying the buffer.
- `gfp_t gfp`: how to do memory allocations (if necessary).

**Description**

Caller must ensure we don't call this with other virtqueue operations
at the same time (except where noted).

Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).



#### <a id="c-virtqueue_add_outbuf"></a>`virtqueue_add_outbuf()`

```c
int virtqueue_add_outbuf(struct virtqueue *vq, struct scatterlist *sg, unsigned int num, void *data, gfp_t gfp)
```

expose output buffers to other end

**Parameters**

- `struct virtqueue *vq`: the struct virtqueue we're talking about.
- `struct scatterlist *sg`: scatterlist (must be well-formed and terminated!)
- `unsigned int num`: the number of entries in **sg** readable by other side
- `void *data`: the token identifying the buffer.
- `gfp_t gfp`: how to do memory allocations (if necessary).

**Description**

Caller must ensure we don't call this with other virtqueue operations
at the same time (except where noted).

Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).



#### <a id="c-virtqueue_add_sgs"></a>`virtqueue_add_sgs()`

```c
int virtqueue_add_sgs(struct virtqueue *_vq, struct scatterlist *sgs[], unsigned int out_sgs, unsigned int in_sgs, void *data, gfp_t gfp)
```

expose buffers to other end

**Parameters**

- `struct virtqueue *_vq`: the struct virtqueue we're talking about.
- `struct scatterlist *sgs[]`: array of terminated scatterlists.
- `unsigned int out_sgs`: the number of scatterlists readable by other side
- `unsigned int in_sgs`: the number of scatterlists which are writable (after readable ones)
- `void *data`: the token identifying the buffer.
- `gfp_t gfp`: how to do memory allocations (if necessary).

**Description**

Caller must ensure we don't call this with other virtqueue operations
at the same time (except where noted).

Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).

NB: ENOSPC is a special code that is only returned on an attempt to add a
buffer to a full VQ. It indicates that some buffers are outstanding and that
the operation can be retried after some buffers have been used.


Then, after the device has read or written the buffers prepared by the driver and notifies it back, the driver can call virtqueue\_get\_buf() to read the data produced by the device (if the virtqueue was set up with input buffers) or simply to reclaim the buffers if they were already consumed by the device:


#### <a id="c-virtqueue_get_buf_ctx"></a>`virtqueue_get_buf_ctx()`

```c
void * virtqueue_get_buf_ctx(struct virtqueue *_vq, unsigned int *len, void **ctx)
```

get the next used buffer

**Parameters**

- `struct virtqueue *_vq`: the struct virtqueue we're talking about.
- `unsigned int *len`: the length written into the buffer
- `void **ctx`: extra context for the token

**Description**

If the device wrote data into the buffer, **len** will be set to the
amount written.  This means you don't need to clear the buffer
beforehand to ensure there's no data leakage in the case of short
writes.

Caller must ensure we don't call this with other virtqueue
operations at the same time (except where noted).

Returns NULL if there are no used buffers, or the "data" token
handed to virtqueue_add_*().


The virtqueue callbacks can be disabled and re-enabled using the virtqueue\_disable\_cb() and the family of virtqueue\_enable\_cb() functions respectively. See drivers/virtio/virtio\_ring.c for more details:


#### <a id="c-virtqueue_disable_cb"></a>`virtqueue_disable_cb()`

```c
void virtqueue_disable_cb(struct virtqueue *_vq)
```

disable callbacks

**Parameters**

- `struct virtqueue *_vq`: the struct virtqueue we're talking about.

**Description**

Note that this is not necessarily synchronous, hence unreliable and only
useful as an optimization.

Unlike other operations, this need not be serialized.



#### <a id="c-virtqueue_enable_cb"></a>`virtqueue_enable_cb()`

```c
bool virtqueue_enable_cb(struct virtqueue *_vq)
```

restart callbacks after disable_cb.

**Parameters**

- `struct virtqueue *_vq`: the struct virtqueue we're talking about.

**Description**

This re-enables callbacks; it returns "false" if there are pending
buffers in the queue, to detect a possible race between the driver
checking for more work, and enabling callbacks.

Caller must ensure we don't call this with other virtqueue
operations at the same time (except where noted).


But note that some spurious callbacks can still be triggered under certain scenarios. The way to disable callbacks reliably is to reset the device or the virtqueue (virtio\_reset\_device()).

<a id="rst-references"></a>

## References

<a id="rst-target-1"></a>\[1\] Virtio Spec v1.2: [https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html](<https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html>)

Check for later versions of the spec as well.

---

# Xilinx FPGA

_Peios Kernel / Hardware and drivers / Driver development / xilinx_

> Reference for Xilinx FPGA.

<a id="rst-xilinx-fpga"></a>

- [Xilinx Zynq MPSoC EEMI Documentation](</kernel/hardware/driver-api/xilinx/eemi.md>)

---

# Xilinx Zynq MPSoC EEMI Documentation

_Peios Kernel / Hardware and drivers / Driver development / xilinx_

> The zynqmp-firmware node describes the interface to platform firmware. ZynqMP has an interface to communicate with secure firmware. Firmware driver provides an interface to firmware APIs. Interface APIs can be used by any driver to…

<a id="rst-xilinx-zynq-mpsoc-eemi-documentation"></a>

<a id="rst-xilinx-zynq-mpsoc-firmware-interface"></a>

## Xilinx Zynq MPSoC Firmware Interface

The zynqmp-firmware node describes the interface to platform firmware. ZynqMP has an interface to communicate with secure firmware. Firmware driver provides an interface to firmware APIs. Interface APIs can be used by any driver to communicate with PMC(Platform Management Controller).

<a id="rst-embedded-energy-management-interface-eemi"></a>

## Embedded Energy Management Interface (EEMI)

The embedded energy management interface is used to allow software components running across different processing clusters on a chip or device to communicate with a power management controller (PMC) on a device to issue or respond to power management requests.

Any driver who wants to communicate with PMC using EEMI APIs use the functions provided for each function.

<a id="rst-ioctl"></a>

## IOCTL

IOCTL API is for device control and configuration. It is not a system IOCTL but it is an EEMI API. This API can be used by master to control any device specific configuration. IOCTL definitions can be platform specific. This API also manage shared device configuration.

The following IOCTL IDs are valid for device control: - IOCTL_SET_PLL_FRAC_MODE       8 - IOCTL_GET_PLL_FRAC_MODE       9 - IOCTL_SET_PLL_FRAC_DATA       10 - IOCTL_GET_PLL_FRAC_DATA       11

Refer EEMI API guide \[0\] for IOCTL specific parameters and other EEMI APIs.

<a id="rst-references"></a>

## References

- **\[0\] Embedded Energy Management Interface (EEMI) API guide:**

  [https://www.xilinx.com/support/documentation/user_guides/ug1200-eemi-api.pdf](<https://www.xilinx.com/support/documentation/user_guides/ug1200-eemi-api.pdf>)
