# Driver fundamentals

---

# 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).
