# Bus programming reference

---

# Auxiliary Bus

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> Reference for Auxiliary Bus.

<a id="rst-auxiliary-bus-1"></a>
<a id="rst-auxiliary-bus"></a>

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


In some subsystems, the functionality of the core device (PCI/ACPI/other) is
too complex for a single device to be managed by a monolithic driver (e.g.
Sound Open Firmware), multiple devices might implement a common intersection
of functionality (e.g. NICs + RDMA), or a driver may want to export an
interface for another subsystem to drive (e.g. SIOV Physical Function export
Virtual Function management).  A split of the functionality into child-
devices representing sub-domains of functionality makes it possible to
compartmentalize, layer, and distribute domain-specific concerns via a Linux
device-driver model.

An example for this kind of requirement is the audio subsystem where a
single IP is handling multiple entities such as HDMI, Soundwire, local
devices such as mics/speakers etc. The split for the core's functionality
can be arbitrary or be defined by the DSP firmware topology and include
hooks for test/debug. This allows for the audio core device to be minimal
and focused on hardware-specific control and communication.

Each auxiliary_device represents a part of its parent functionality. The
generic behavior can be extended and specialized as needed by encapsulating
an auxiliary_device within other domain-specific structures and the use of
.ops callbacks. Devices on the auxiliary bus do not share any structures and
the use of a communication channel with the parent is domain-specific.

Note that ops are intended as a way to augment instance behavior within a
class of auxiliary devices, it is not the mechanism for exporting common
infrastructure from the parent. Consider `EXPORT_SYMBOL_NS()` to convey
infrastructure from the parent module to the auxiliary module(s).


<a id="rst-when-should-the-auxiliary-bus-be-used"></a>

## When Should the Auxiliary Bus Be Used


The auxiliary bus is to be used when a driver and one or more kernel
modules, who share a common header file with the driver, need a mechanism to
connect and provide access to a shared object allocated by the
auxiliary_device's registering driver.  The registering driver for the
auxiliary_device(s) and the kernel module(s) registering auxiliary_drivers
can be from the same subsystem, or from multiple subsystems.

The emphasis here is on a common generic interface that keeps subsystem
customization out of the bus infrastructure.

One example is a PCI network device that is RDMA-capable and exports a child
device to be driven by an auxiliary_driver in the RDMA subsystem.  The PCI
driver allocates and registers an auxiliary_device for each physical
function on the NIC.  The RDMA driver registers an auxiliary_driver that
claims each of these auxiliary_devices.  This conveys data/ops published by
the parent PCI device/driver to the RDMA auxiliary_driver.

Another use case is for the PCI device to be split out into multiple sub
functions.  For each sub function an auxiliary_device is created.  A PCI sub
function driver binds to such devices that creates its own one or more class
devices.  A PCI sub function auxiliary device is likely to be contained in a
struct with additional attributes such as user defined sub function number
and optional attributes such as resources and a link to the parent device.
These attributes could be used by systemd/udev; and hence should be
initialized before a driver binds to an auxiliary_device.

A key requirement for utilizing the auxiliary bus is that there is no
dependency on a physical bus, device, register accesses or regmap support.
These individual devices split from the core cannot live on the platform bus
as they are not physical devices that are controlled by DT/ACPI.  The same
argument applies for not using MFD in this scenario as MFD relies on
individual function devices being physical devices.


<a id="rst-auxiliary-device-creation"></a>

## Auxiliary Device Creation


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

auxiliary device object.

**Definition**

```c
struct auxiliary_device {
    struct device dev;
    const char *name;
    u32 id;
    struct {
        struct xarray irqs;
        struct mutex lock;
        bool irq_dir_exists;
    } sysfs;
};
```

**Members**

- `dev`: Device,
  The release and parent fields of the device structure must be filled
  in
- `name`: Match name found by the auxiliary device driver,
- `id`: unique identitier if multiple devices of the same name are exported,
- `sysfs`: embedded struct which hold all sysfs related fields,
- `sysfs.irqs`: irqs xarray contains irq indices which are used by the device,
- `sysfs.lock`: Synchronize irq sysfs creation,
- `sysfs.irq_dir_exists`: whether "irqs" directory exists,

**Description**

An auxiliary_device represents a part of its parent device's functionality.
It is given a name that, combined with the registering drivers
KBUILD_MODNAME, creates a match_name that is used for driver binding, and an
id that combined with the match_name provide a unique name to register with
the bus subsystem.  For example, a driver registering an auxiliary device is
named 'foo_mod.ko' and the subdevice is named 'foo_dev'.  The match name is
therefore 'foo_mod.foo_dev'.

Registering an auxiliary_device is a three-step process.

First, a 'struct auxiliary_device' needs to be defined or allocated for each
sub-device desired.  The name, id, dev.release, and dev.parent fields of
this structure must be filled in as follows.

The 'name' field is to be given a name that is recognized by the auxiliary
driver.  If two auxiliary_devices with the same match_name, eg
"foo_mod.foo_dev", are registered onto the bus, they must have unique id
values (e.g. "x" and "y") so that the registered devices names are
"foo_mod.foo_dev.x" and "foo_mod.foo_dev.y".  If match_name + id are not
unique, then the device_add fails and generates an error message.

The auxiliary_device.dev.type.release or auxiliary_device.dev.release must
be populated with a non-NULL pointer to successfully register the
auxiliary_device.  This release call is where resources associated with the
auxiliary device must be free'ed.  Because once the device is placed on the
bus the parent driver can not tell what other code may have a reference to
this data.

The auxiliary_device.dev.parent should be set.  Typically to the registering
drivers device.

Second, call [`auxiliary_device_init()`](#c-auxiliary_device_init), which checks several aspects of the
auxiliary_device struct and performs a [`device_initialize()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-device_initialize).  After this step
completes, any error state must have a call to `auxiliary_device_uninit()` in
its resolution path.

The third and final step in registering an auxiliary_device is to perform a
call to `auxiliary_device_add()`, which sets the name of the device and adds
the device to the bus.

```c
#define MY_DEVICE_NAME "foo_dev"

...

struct auxiliary_device *my_aux_dev = my_aux_dev_alloc(xxx);

// Step 1:
my_aux_dev->name = MY_DEVICE_NAME;
my_aux_dev->id = my_unique_id_alloc(xxx);
my_aux_dev->dev.release = my_aux_dev_release;
my_aux_dev->dev.parent = my_dev;

// Step 2:
if (auxiliary_device_init(my_aux_dev))
        goto fail;

// Step 3:
if (auxiliary_device_add(my_aux_dev)) {
        auxiliary_device_uninit(my_aux_dev);
        goto fail;
}

...
```

Unregistering an auxiliary_device is a two-step process to mirror the
register process.  First call `auxiliary_device_delete()`, then call
`auxiliary_device_uninit()`.

```c
auxiliary_device_delete(my_dev->my_aux_dev);
auxiliary_device_uninit(my_dev->my_aux_dev);
```



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

```c
int auxiliary_device_init(struct auxiliary_device *auxdev)
```

check auxiliary_device and initialize

**Parameters**

- `struct auxiliary_device *auxdev`: auxiliary device struct

**Description**

This is the second step in the three-step process to register an
auxiliary_device.

When this function returns an error code, then the device_initialize will
*not* have been performed, and the caller will be responsible to free any
memory allocated for the auxiliary_device in the error path directly.

It returns 0 on success.  On success, the device_initialize has been
performed.  After this point any error unwinding will need to include a call
to `auxiliary_device_uninit()`.  In this post-initialize error scenario, a call
to the device's .release callback will be triggered, and all memory clean-up
is expected to be handled there.

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

```c
int __auxiliary_device_add(struct auxiliary_device *auxdev, const char *modname)
```

add an auxiliary bus device

**Parameters**

- `struct auxiliary_device *auxdev`: auxiliary bus device to add to the bus
- `const char *modname`: name of the parent device's driver module

**Description**

This is the third step in the three-step process to register an
auxiliary_device.

This function must be called after a successful call to
[`auxiliary_device_init()`](#c-auxiliary_device_init), which will perform the device_initialize.  This
means that if this returns an error code, then a call to
`auxiliary_device_uninit()` must be performed so that the .release callback
will be triggered to free the memory associated with the auxiliary_device.

The expectation is that users will call the "auxiliary_device_add" macro so
that the caller's KBUILD_MODNAME is automatically inserted for the modname
parameter.  Only if a user requires a custom name would this version be
called directly.


<a id="rst-auxiliary-device-memory-model-and-lifespan"></a>

### Auxiliary Device Memory Model and Lifespan


The registering driver is the entity that allocates memory for the
auxiliary_device and registers it on the auxiliary bus.  It is important to
note that, as opposed to the platform bus, the registering driver is wholly
responsible for the management of the memory used for the device object.

To be clear the memory for the auxiliary_device is freed in the `release()`
callback defined by the registering driver.  The registering driver should
only call `auxiliary_device_delete()` and then `auxiliary_device_uninit()` when
it is done with the device.  The `release()` function is then automatically
called if and when other code releases their reference to the devices.

A parent object, defined in the shared header file, contains the
auxiliary_device.  It also contains a pointer to the shared object(s), which
also is defined in the shared header.  Both the parent object and the shared
object(s) are allocated by the registering driver.  This layout allows the
auxiliary_driver's registering module to perform a [`container_of()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-container_of) call to go
from the pointer to the auxiliary_device, that is passed during the call to
the auxiliary_driver's probe function, up to the parent object, and then
have access to the shared object(s).

The memory for the shared object(s) must have a lifespan equal to, or
greater than, the lifespan of the memory for the auxiliary_device.  The
auxiliary_driver should only consider that the shared object is valid as
long as the auxiliary_device is still registered on the auxiliary bus.  It
is up to the registering driver to manage (e.g. free or keep available) the
memory for the shared object beyond the life of the auxiliary_device.

The registering driver must unregister all auxiliary devices before its own
driver.`remove()` is completed.  An easy way to ensure this is to use the
`devm_add_action_or_reset()` call to register a function against the parent
device which unregisters the auxiliary device object(s).

Finally, any operations which operate on the auxiliary devices must continue
to function (if only to return an error) after the registering driver
unregisters the auxiliary device.


<a id="rst-auxiliary-drivers"></a>

## Auxiliary Drivers


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

Definition of an auxiliary bus driver

**Definition**

```c
struct auxiliary_driver {
    int (*probe)(struct auxiliary_device *auxdev, const struct auxiliary_device_id *id);
    void (*remove)(struct auxiliary_device *auxdev);
    void (*shutdown)(struct auxiliary_device *auxdev);
    int (*suspend)(struct auxiliary_device *auxdev, pm_message_t state);
    int (*resume)(struct auxiliary_device *auxdev);
    const char *name;
    struct device_driver driver;
    const struct auxiliary_device_id *id_table;
};
```

**Members**

- `probe`: Called when a matching device is added to the bus.
- `remove`: Called when device is removed from the bus.
- `shutdown`: Called at shut-down time to quiesce the device.
- `suspend`: Called to put the device to sleep mode. Usually to a power state.
- `resume`: Called to bring a device from sleep mode.
- `name`: Driver name.
- `driver`: Core driver structure.
- `id_table`: Table of devices this driver should match on the bus.

**Description**

Auxiliary drivers follow the standard driver model convention, where
discovery/enumeration is handled by the core, and drivers provide `probe()`
and `remove()` methods. They support power management and shutdown
notifications using the standard conventions.

Auxiliary drivers register themselves with the bus by calling
`auxiliary_driver_register()`. The id_table contains the match_names of
auxiliary devices that a driver can bind with.

```c
static const struct auxiliary_device_id my_auxiliary_id_table[] = {
        { .name = "foo_mod.foo_dev" },
        {},
};

MODULE_DEVICE_TABLE(auxiliary, my_auxiliary_id_table);

struct auxiliary_driver my_drv = {
        .name = "myauxiliarydrv",
        .id_table = my_auxiliary_id_table,
        .probe = my_drv_probe,
        .remove = my_drv_remove
};
```

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

```c
module_auxiliary_driver(__auxiliary_driver)
```

Helper macro for registering an auxiliary driver

**Parameters**

- `__auxiliary_driver`: auxiliary driver struct

**Description**

Helper macro for auxiliary drivers which do not do anything special in
module init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)

```c
module_auxiliary_driver(my_drv);
```



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

```c
int __auxiliary_driver_register(struct auxiliary_driver *auxdrv, struct module *owner, const char *modname)
```

register a driver for auxiliary bus devices

**Parameters**

- `struct auxiliary_driver *auxdrv`: auxiliary_driver structure
- `struct module *owner`: owning module/driver
- `const char *modname`: KBUILD_MODNAME for parent driver

**Description**

The expectation is that users will call the "auxiliary_driver_register"
macro so that the caller's KBUILD_MODNAME is automatically inserted for the
modname parameter.  Only if a user requires a custom name would this version
be called directly.

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

```c
void auxiliary_driver_unregister(struct auxiliary_driver *auxdrv)
```

unregister a driver

**Parameters**

- `struct auxiliary_driver *auxdrv`: auxiliary_driver structure


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

## Example Usage


Auxiliary devices are created and registered by a subsystem-level core
device that needs to break up its functionality into smaller fragments. One
way to extend the scope of an auxiliary_device is to encapsulate it within a
domain-specific structure defined by the parent device. This structure
contains the auxiliary_device and any associated shared data/callbacks
needed to establish the connection with the parent.

An example is:

```c
 struct foo {
      struct auxiliary_device auxdev;
      void (*connect)(struct auxiliary_device *auxdev);
      void (*disconnect)(struct auxiliary_device *auxdev);
      void *data;
};
```

The parent device then registers the auxiliary_device by calling
[`auxiliary_device_init()`](#c-auxiliary_device_init), and then `auxiliary_device_add()`, with the pointer
to the auxdev member of the above structure. The parent provides a name for
the auxiliary_device that, combined with the parent's KBUILD_MODNAME,
creates a match_name that is be used for matching and binding with a driver.

Whenever an auxiliary_driver is registered, based on the match_name, the
auxiliary_driver's `probe()` is invoked for the matching devices.  The
auxiliary_driver can also be encapsulated inside custom drivers that make
the core device's functionality extensible by adding additional
domain-specific ops as follows:

```c
struct my_ops {
        void (*send)(struct auxiliary_device *auxdev);
        void (*receive)(struct auxiliary_device *auxdev);
};


struct my_driver {
        struct auxiliary_driver auxiliary_drv;
        const struct my_ops ops;
};
```

An example of this type of usage is:

```c
const struct auxiliary_device_id my_auxiliary_id_table[] = {
        { .name = "foo_mod.foo_dev" },
        { },
};

const struct my_ops my_custom_ops = {
        .send = my_tx,
        .receive = my_rx,
};

const struct my_driver my_drv = {
        .auxiliary_drv = {
                .name = "myauxiliarydrv",
                .id_table = my_auxiliary_id_table,
                .probe = my_probe,
                .remove = my_remove,
                .shutdown = my_shutdown,
        },
        .ops = my_custom_ops,
};
```

Please note that such custom ops approach is valid, but it is hard to implement
it right without global locks per-device to protect from auxiliary_drv removal
during call to that ops. In addition, this implementation lacks proper module
dependency, which causes to load/unload races between auxiliary parent and devices
modules.

The most easiest way to provide these ops reliably without needing to
have a lock is to EXPORT_SYMBOL*() them and rely on already existing
modules infrastructure for validity and correct dependencies chains.

---

# EISA bus support

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> This document groups random notes about porting EISA drivers to the new EISA/sysfs API.

<a id="rst-eisa-bus-support"></a>

**Author:** Marc Zyngier &lt;[maz@wild-wind.fr.eu.org](<mailto:maz@wild-wind.fr.eu.org>)&gt;

This document groups random notes about porting EISA drivers to the new EISA/sysfs API.

Starting from version 2.5.59, the EISA bus is almost given the same status as other much more mainstream buses such as PCI or USB. This has been possible through sysfs, which defines a nice enough set of abstractions to manage buses, devices and drivers.

Although the new API is quite simple to use, converting existing drivers to the new infrastructure is not an easy task (mostly because detection code is generally also used to probe ISA cards). Moreover, most EISA drivers are among the oldest Linux drivers so, as you can imagine, some dust has settled here over the years.

The EISA infrastructure is made up of three parts:

> - The bus code implements most of the generic code. It is shared among all the architectures that the EISA code runs on. It implements bus probing (detecting EISA cards available on the bus), allocates I/O resources, allows fancy naming through sysfs, and offers interfaces for driver to register.
>
> - The bus root driver implements the glue between the bus hardware and the generic bus code. It is responsible for discovering the device implementing the bus, and setting it up to be latter probed by the bus code. This can go from something as simple as reserving an I/O region on x86, to the rather more complex, like the hppa EISA code. This is the part to implement in order to have EISA running on an "new" platform.
>
> - The driver offers the bus a list of devices that it manages, and implements the necessary callbacks to probe and release devices whenever told to.

Every function/structure below lives in &lt;linux/eisa.h&gt;, which depends heavily on &lt;linux/device.h&gt;.

<a id="rst-bus-root-driver"></a>

## Bus root driver



```text
int eisa_root_register (struct eisa_root_device *root);
```

The eisa_root_register function is used to declare a device as the root of an EISA bus. The eisa_root_device structure holds a reference to this device, as well as some parameters for probing purposes:



```text
struct eisa_root_device {
        struct device   *dev;    /* Pointer to bridge device */
        struct resource *res;
        unsigned long    bus_base_addr;
        int              slots;  /* Max slot number */
        int              force_probe; /* Probe even when no slot 0 */
        u64              dma_mask; /* from bridge device */
        int              bus_nr; /* Set by eisa_root_register */
        struct resource  eisa_root_res; /* ditto */
};
```


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


node

</td>
<td>


used for eisa_root_register internal purpose

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


dev

</td>
<td>


pointer to the root device

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


res

</td>
<td>


root device I/O resource

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


bus_base_addr

</td>
<td>


slot 0 address on this bus

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


slots

</td>
<td>


max slot number to probe

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


force_probe

</td>
<td>


Probe even when slot 0 is empty (no EISA mainboard)

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


dma_mask

</td>
<td>


Default DMA mask. Usually the bridge device dma_mask.

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


bus_nr

</td>
<td>


unique bus id, set by eisa_root_register

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

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

## Driver



```text
int eisa_driver_register (struct eisa_driver *edrv);
void eisa_driver_unregister (struct eisa_driver *edrv);
```

Clear enough ?



```text
struct eisa_device_id {
        char sig[EISA_SIG_LEN];
        unsigned long driver_data;
};

struct eisa_driver {
        const struct eisa_device_id *id_table;
        struct device_driver         driver;
};
```


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


id_table

</td>
<td>


an array of NULL terminated EISA id strings, followed by an empty string. Each string can optionally be paired with a driver-dependent value (driver_data).

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


driver

</td>
<td>


a generic driver, such as described in [Documentation/driver-api/driver-model/driver.rst](/kernel/hardware/driver-api/driver-model/driver.md). Only .name, .probe and .remove members are mandatory.

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

An example is the 3c59x driver:



```text
static struct eisa_device_id vortex_eisa_ids[] = {
        { "TCM5920", EISA_3C592_OFFSET },
        { "TCM5970", EISA_3C597_OFFSET },
        { "" }
};

static struct eisa_driver vortex_eisa_driver = {
        .id_table = vortex_eisa_ids,
        .driver   = {
                .name    = "3c59x",
                .probe   = vortex_eisa_probe,
                .remove  = vortex_eisa_remove
        }
};
```

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

## Device

The sysfs framework calls .probe and .remove functions upon device discovery and removal (note that the .remove function is only called when driver is built as a module).

Both functions are passed a pointer to a 'struct device', which is encapsulated in a 'struct eisa_device' described as follows:



```text
struct eisa_device {
        struct eisa_device_id id;
        int                   slot;
        int                   state;
        unsigned long         base_addr;
        struct resource       res[EISA_MAX_RESOURCES];
        u64                   dma_mask;
        struct device         dev; /* generic device */
};
```


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


id

</td>
<td>


EISA id, as read from device. id.driver_data is set from the matching driver EISA id.

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


slot

</td>
<td>


slot number which the device was detected on

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


state

</td>
<td>


set of flags indicating the state of the device. Current flags are EISA_CONFIG_ENABLED and EISA_CONFIG_FORCED.

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


res

</td>
<td>


set of four 256 bytes I/O regions allocated to this device

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


dma_mask

</td>
<td>


DMA mask set from the parent device.

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


dev

</td>
<td>


generic device (see [Documentation/driver-api/driver-model/device.rst](/kernel/hardware/driver-api/driver-model/device.md))

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

You can get the 'struct eisa_device' from 'struct device' using the 'to_eisa_device' macro.

<a id="rst-misc-stuff"></a>

## Misc stuff



```text
void eisa_set_drvdata (struct eisa_device *edev, void *data);
```

Stores data into the device's driver_data area.



```text
void *eisa_get_drvdata (struct eisa_device *edev):
```

Gets the pointer previously stored into the device's driver_data area.



```text
int eisa_get_region_index (void *addr);
```

Returns the region number (0 &lt;= x &lt; EISA_MAX_RESOURCES) of a given address.

<a id="rst-kernel-parameters"></a>

## Kernel parameters

- **eisa_bus.enable_dev**

  A comma-separated list of slots to be enabled, even if the firmware set the card as disabled. The driver must be able to properly initialize the device in such conditions.

- **eisa_bus.disable_dev**

  A comma-separated list of slots to be disabled, even if the firmware set the card as enabled. The driver won't be called to handle this device.

- **virtual_root.force_probe**

  Force the probing code to probe EISA slots even when it cannot find an EISA compliant mainboard (nothing appears on slot 0). Defaults to 0 (don't force), and set to 1 (force probing) when CONFIG_EISA_VLB_PRIMING is set.

<a id="rst-random-notes"></a>

## Random notes

Converting an EISA driver to the new API mostly involves *deleting* code (since probing is now in the core EISA code). Unfortunately, most drivers share their probing routine between ISA, and EISA. Special care must be taken when ripping out the EISA code, so other buses won't suffer from these surgical strikes...

You *must not* expect any EISA device to be detected when returning from eisa_driver_register, since the chances are that the bus has not yet been probed. In fact, that's what happens most of the time (the bus root driver usually kicks in rather late in the boot process). Unfortunately, most drivers are doing the probing by themselves, and expect to have explored the whole machine when they exit their probe routine.

For example, switching your favorite EISA SCSI card to the "hotplug" model is "the right thing"(tm).

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

## Thanks

I'd like to thank the following people for their help:

- Xavier Benigni for lending me a wonderful Alpha Jensen,

- James Bottomley, Jeff Garzik for getting this stuff into the kernel,

- Andries Brouwer for contributing numerous EISA ids,

- Catrin Jones for coping with far too many machines at home.

---

# Firewire (IEEE 1394) driver Interface Guide

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> use/maintain+any resource on IEEE 1394 bus.

<a id="rst-firewire-ieee-1394-driver-interface-guide"></a>

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

## Introduction and Overview

- **The Linux FireWire subsystem adds some interfaces into the Linux system to**

  use/maintain+any resource on IEEE 1394 bus.

The main purpose of these interfaces is to access address space on each node on IEEE 1394 bus by ISO/IEC 13213 (IEEE 1212) procedure, and to control isochronous resources on the bus by IEEE 1394 procedure.

Two types of interfaces are added, according to consumers of the interface. A set of userspace interfaces is available via `firewire character devices`. A set of kernel interfaces is available via exported symbols in `firewire-core` module.

<a id="rst-firewire-char-device-data-structures"></a>

## Firewire char device data structures




```text
What:           /dev/fw[0-9]+
Date:           May 2007
KernelVersion:  2.6.22
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                The character device files /dev/fw* are the interface between
                firewire-core and IEEE 1394 device drivers implemented in
                userspace.  The ioctl(2)- and read(2)-based ABI is defined and
                documented in <linux/firewire-cdev.h>.

                This ABI offers most of the features which firewire-core also
                exposes to kernelspace IEEE 1394 drivers.

                Each /dev/fw* is associated with one IEEE 1394 node, which can
                be remote or local nodes.  Operations on a /dev/fw* file have
                different scope:

                  - The 1394 node which is associated with the file:

                          - Asynchronous request transmission
                          - Get the Configuration ROM
                          - Query node ID
                          - Query maximum speed of the path between this node
                            and local node

                  - The 1394 bus (i.e. "card") to which the node is attached to:

                          - Isochronous stream transmission and reception
                          - Asynchronous stream transmission and reception
                          - Asynchronous broadcast request transmission
                          - PHY packet transmission and reception
                          - Allocate, reallocate, deallocate isochronous
                            resources (channels, bandwidth) at the bus's IRM
                          - Query node IDs of local node, root node, IRM, bus
                            manager
                          - Query cycle time
                          - Bus reset initiation, bus reset event reception

                  - All 1394 buses:

                          - Allocation of IEEE 1212 address ranges on the local
                            link layers, reception of inbound requests to such
                            an address range, asynchronous response transmission
                            to inbound requests
                          - Addition of descriptors or directories to the local
                            nodes' Configuration ROM

                Due to the different scope of operations and in order to let
                userland implement different access permission models, some
                operations are restricted to /dev/fw* files that are associated
                with a local node:

                          - Addition of descriptors or directories to the local
                            nodes' Configuration ROM
                          - PHY packet transmission and reception

                A /dev/fw* file remains associated with one particular node
                during its entire life time.  Bus topology changes, and hence
                node ID changes, are tracked by firewire-core.  ABI users do not
                need to be aware of topology.

                The following file operations are supported:

                open(2)
                    Currently the only useful flags are O_RDWR.

                ioctl(2)
                    Initiate various actions.  Some take immediate effect, others
                    are performed asynchronously while or after the ioctl returns.
                    See the inline documentation in <linux/firewire-cdev.h> for
                    descriptions of all ioctls.

                poll(2), select(2), epoll_wait(2) etc.
                    Watch for events to become available to be read.

                read(2)
                    Receive various events.  There are solicited events like
                    outbound asynchronous transaction completion or isochronous
                    buffer completion, and unsolicited events such as bus resets,
                    request reception, or PHY packet reception.  Always use a read
                    buffer which is large enough to receive the largest event that
                    could ever arrive.  See <linux/firewire-cdev.h> for descriptions
                    of all event types and for which ioctls affect reception of
                    events.

                mmap(2)
                    Allocate a DMA buffer for isochronous reception or transmission
                    and map it into the process address space.  The arguments should
                    be used as follows:  addr = NULL, length = the desired buffer
                    size, i.e. number of packets times size of largest packet,
                    prot = at least PROT_READ for reception and at least PROT_WRITE
                    for transmission, flags = MAP_SHARED, fd = the handle to the
                    /dev/fw*, offset = 0.

                Isochronous reception works in packet-per-buffer fashion except
                for multichannel reception which works in buffer-fill mode.

                munmap(2)
                    Unmap the isochronous I/O buffer from the process address space.

                close(2)
                    Besides stopping and freeing I/O contexts that were associated
                    with the file descriptor, back out any changes to the local
                    nodes' Configuration ROM.  Deallocate isochronous channels and
                    bandwidth at the IRM that were marked for kernel-assisted
                    re- and deallocation.

Users:          libraw1394;
                libdc1394;
                libhinawa;
                tools like linux-firewire-utils, fwhack, ...

```



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

Common part of all fw_cdev_event_* types

**Definition**

```c
struct fw_cdev_event_common {
    __u64 closure;
    __u32 type;
};
```

**Members**

- `closure`: For arbitrary use by userspace
- `type`: Discriminates the fw_cdev_event_* types

**Description**

This struct may be used to access generic members of all fw_cdev_event_*
types regardless of the specific type.

Data passed in the **closure** field for a request will be returned in the
corresponding event.  It is big enough to hold a pointer on all platforms.
The ioctl used to set **closure** depends on the **type** of event.

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

Sent when a bus reset occurred

**Definition**

```c
struct fw_cdev_event_bus_reset {
    __u64 closure;
    __u32 type;
    __u32 node_id;
    __u32 local_node_id;
    __u32 bm_node_id;
    __u32 irm_node_id;
    __u32 root_node_id;
    __u32 generation;
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_GET_INFO` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_BUS_RESET`
- `node_id`: New node ID of this node
- `local_node_id`: Node ID of the local node, i.e. of the controller
- `bm_node_id`: Node ID of the bus manager
- `irm_node_id`: Node ID of the iso resource manager
- `root_node_id`: Node ID of the root node
- `generation`: New bus generation

**Description**

This event is sent when the bus the device belongs to goes through a bus
reset.  It provides information about the new bus configuration, such as
new node ID for this device, new root ID, and others.

If **bm_node_id** is 0xffff right after bus reset it can be reread by an
`FW_CDEV_IOC_GET_INFO` ioctl after bus manager selection was finished.
Kernels with ABI version \< 4 do not set **bm_node_id**.

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

Sent when a response packet was received

**Definition**

```c
struct fw_cdev_event_response {
    __u64 closure;
    __u32 type;
    __u32 rcode;
    __u32 length;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_SEND_REQUEST`
  or `FW_CDEV_IOC_SEND_BROADCAST_REQUEST`
  or `FW_CDEV_IOC_SEND_STREAM_PACKET` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_RESPONSE`
- `rcode`: Response code returned by the remote node
- `length`: Data length, i.e. the response's payload size in bytes
- `data`: Payload data, if any

**Description**

This event is sent instead of [`fw_cdev_event_response`](#c-struct-fw_cdev_event_response) if the kernel or the client implements
ABI version \<= 5. It has the lack of time stamp field comparing to [`fw_cdev_event_response2`](#c-struct-fw_cdev_event_response2).

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

Sent when a response packet was received

**Definition**

```c
struct fw_cdev_event_response2 {
    __u64 closure;
    __u32 type;
    __u32 rcode;
    __u32 length;
    __u32 request_tstamp;
    __u32 response_tstamp;
    __u32 padding;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_SEND_REQUEST`
  or `FW_CDEV_IOC_SEND_BROADCAST_REQUEST`
  or `FW_CDEV_IOC_SEND_STREAM_PACKET` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_RESPONSE`
- `rcode`: Response code returned by the remote node
- `length`: Data length, i.e. the response's payload size in bytes
- `request_tstamp`: The time stamp of isochronous cycle at which the request was sent.
- `response_tstamp`: The time stamp of isochronous cycle at which the response was sent.
- `padding`: Padding to keep the size of structure as multiples of 8 in various architectures
  since 4 byte alignment is used for 8 byte of object type in System V ABI for i386
  architecture.
- `data`: Payload data, if any

**Description**

This event is sent when the stack receives a response to an outgoing request
sent by `FW_CDEV_IOC_SEND_REQUEST` ioctl.  The payload data for responses
carrying data (read and lock responses) follows immediately and can be
accessed through the **data** field.

The event is also generated after conclusions of transactions that do not
involve response packets.  This includes unified write transactions,
broadcast write transactions, and transmission of asynchronous stream
packets.  **rcode** indicates success or failure of such transmissions.

The value of **request_tstamp** expresses the isochronous cycle at which the request was sent to
initiate the transaction. The value of **response_tstamp** expresses the isochronous cycle at which
the response arrived to complete the transaction. Each value is unsigned 16 bit integer
containing three low order bits of second field and all 13 bits of cycle field in format of
CYCLE_TIMER register.

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

Old version of [`fw_cdev_event_request2`](#c-struct-fw_cdev_event_request2)

**Definition**

```c
struct fw_cdev_event_request {
    __u64 closure;
    __u32 type;
    __u32 tcode;
    __u64 offset;
    __u32 handle;
    __u32 length;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_ALLOCATE` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_REQUEST`
- `tcode`: Transaction code of the incoming request
- `offset`: The offset into the 48-bit per-node address space
- `handle`: Reference to the kernel-side pending request
- `length`: Data length, i.e. the request's payload size in bytes
- `data`: Incoming data, if any

**Description**

This event is sent instead of [`fw_cdev_event_request2`](#c-struct-fw_cdev_event_request2) if the kernel or
the client implements ABI version \<= 3.  [`fw_cdev_event_request`](#c-struct-fw_cdev_event_request) lacks
essential information; use [`fw_cdev_event_request2`](#c-struct-fw_cdev_event_request2) instead.

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

Sent on incoming request to an address region

**Definition**

```c
struct fw_cdev_event_request2 {
    __u64 closure;
    __u32 type;
    __u32 tcode;
    __u64 offset;
    __u32 source_node_id;
    __u32 destination_node_id;
    __u32 card;
    __u32 generation;
    __u32 handle;
    __u32 length;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_ALLOCATE` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_REQUEST2`
- `tcode`: Transaction code of the incoming request
- `offset`: The offset into the 48-bit per-node address space
- `source_node_id`: Sender node ID
- `destination_node_id`: Destination node ID
- `card`: The index of the card from which the request came
- `generation`: Bus generation in which the request is valid
- `handle`: Reference to the kernel-side pending request
- `length`: Data length, i.e. the request's payload size in bytes
- `data`: Incoming data, if any

**Description**

This event is sent instead of [`fw_cdev_event_request3`](#c-struct-fw_cdev_event_request3) if the kernel or the client implements
ABI version \<= 5. It has the lack of time stamp field comparing to [`fw_cdev_event_request3`](#c-struct-fw_cdev_event_request3).

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

Sent on incoming request to an address region

**Definition**

```c
struct fw_cdev_event_request3 {
    __u64 closure;
    __u32 type;
    __u32 tcode;
    __u64 offset;
    __u32 source_node_id;
    __u32 destination_node_id;
    __u32 card;
    __u32 generation;
    __u32 handle;
    __u32 length;
    __u32 tstamp;
    __u32 padding;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_ALLOCATE` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_REQUEST2`
- `tcode`: Transaction code of the incoming request
- `offset`: The offset into the 48-bit per-node address space
- `source_node_id`: Sender node ID
- `destination_node_id`: Destination node ID
- `card`: The index of the card from which the request came
- `generation`: Bus generation in which the request is valid
- `handle`: Reference to the kernel-side pending request
- `length`: Data length, i.e. the request's payload size in bytes
- `tstamp`: The time stamp of isochronous cycle at which the request arrived.
- `padding`: Padding to keep the size of structure as multiples of 8 in various architectures
  since 4 byte alignment is used for 8 byte of object type in System V ABI for i386
  architecture.
- `data`: Incoming data, if any

**Description**

This event is sent when the stack receives an incoming request to an address
region registered using the `FW_CDEV_IOC_ALLOCATE` ioctl.  The request is
guaranteed to be completely contained in the specified region.  Userspace is
responsible for sending the response by `FW_CDEV_IOC_SEND_RESPONSE` ioctl,
using the same **handle**.

The payload data for requests carrying data (write and lock requests)
follows immediately and can be accessed through the **data** field.

Unlike [`fw_cdev_event_request`](#c-struct-fw_cdev_event_request), **tcode** of lock requests is one of the
firewire-core specific `TCODE_LOCK_MASK_SWAP`...`TCODE_LOCK_VENDOR_DEPENDENT`,
i.e. encodes the extended transaction code.

**card** may differ from [`fw_cdev_get_info.card`](#c-struct-fw_cdev_get_info) because requests are received
from all cards of the Linux host.  **source_node_id**, **destination_node_id**, and
**generation** pertain to that card.  Destination node ID and bus generation may
therefore differ from the corresponding fields of the last
[`fw_cdev_event_bus_reset`](#c-struct-fw_cdev_event_bus_reset).

**destination_node_id** may also differ from the current node ID because of a
non-local bus ID part or in case of a broadcast write request.  Note, a
client must call an `FW_CDEV_IOC_SEND_RESPONSE` ioctl even in case of a
broadcast write request; the kernel will then release the kernel-side pending
request but will not actually send a response packet.

In case of a write request to FCP_REQUEST or FCP_RESPONSE, the kernel already
sent a write response immediately after the request was received; in this
case the client must still call an `FW_CDEV_IOC_SEND_RESPONSE` ioctl to
release the kernel-side pending request, though another response won't be
sent.

If the client subsequently needs to initiate requests to the sender node of
an [`fw_cdev_event_request3`](#c-struct-fw_cdev_event_request3), it needs to use a device file with matching
card index, node ID, and generation for outbound requests.

**tstamp** is isochronous cycle at which the request arrived. It is 16 bit integer value and the
higher 3 bits expresses three low order bits of second field in the format of CYCLE_TIME
register and the rest 13 bits expresses cycle field.

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

Sent when an iso packet was completed

**Definition**

```c
struct fw_cdev_event_iso_interrupt {
    __u64 closure;
    __u32 type;
    __u32 cycle;
    __u32 header_length;
    __u32 header[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common);
  set by `FW_CDEV_CREATE_ISO_CONTEXT` ioctl
- `type`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); always `FW_CDEV_EVENT_ISO_INTERRUPT`
- `cycle`: Cycle counter of the last completed packet
- `header_length`: Total length of following headers, in bytes
- `header`: Stripped headers, if any

**Description**

This event is sent when the controller has completed an [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet)
with the `FW_CDEV_ISO_INTERRUPT` bit set, when explicitly requested with
`FW_CDEV_IOC_FLUSH_ISO`, or when there have been so many completed packets
without the interrupt bit set that the kernel's internal buffer for **header**
is about to overflow.  (In the last case, ABI versions \< 5 drop header data
up to the next interrupt packet.)

Isochronous transmit events (context type `FW_CDEV_ISO_CONTEXT_TRANSMIT`):

In version 3 and some implementations of version 2 of the ABI, `header_length`
is a multiple of 4 and `header` contains timestamps of all packets up until
the interrupt packet.  The format of the timestamps is as described below for
isochronous reception.  In version 1 of the ABI, `header_length` was 0.

Isochronous receive events (context type `FW_CDEV_ISO_CONTEXT_RECEIVE`):

The headers stripped of all packets up until and including the interrupt
packet are returned in the **header** field.  The amount of header data per
packet is as specified at iso context creation by
[`fw_cdev_create_iso_context.header_size`](#c-struct-fw_cdev_create_iso_context).

Hence, _interrupt.header_length / _context.header_size is the number of
packets received in this interrupt event.  The client can now iterate
through the `mmap()`'ed DMA buffer according to this number of packets and
to the buffer sizes as the client specified in [`fw_cdev_queue_iso`](#c-struct-fw_cdev_queue_iso).

Since version 2 of this ABI, the portion for each packet in _interrupt.header
consists of the 1394 isochronous packet header, followed by a timestamp
quadlet if [`fw_cdev_create_iso_context.header_size`](#c-struct-fw_cdev_create_iso_context) > 4, followed by quadlets
from the packet payload if [`fw_cdev_create_iso_context.header_size`](#c-struct-fw_cdev_create_iso_context) > 8.

Format of 1394 iso packet header:  16 bits data_length, 2 bits tag, 6 bits
channel, 4 bits tcode, 4 bits sy, in big endian byte order.
data_length is the actual received size of the packet without the four
1394 iso packet header bytes.

Format of timestamp:  16 bits invalid, 3 bits cycleSeconds, 13 bits
cycleCount, in big endian byte order.

In version 1 of the ABI, no timestamp quadlet was inserted; instead, payload
data followed directly after the 1394 is header if header_size > 4.
Behaviour of ver. 1 of this ABI is no longer available since ABI ver. 2.

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

An iso buffer chunk was completed

**Definition**

```c
struct fw_cdev_event_iso_interrupt_mc {
    __u64 closure;
    __u32 type;
    __u32 completed;
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common);
  set by `FW_CDEV_CREATE_ISO_CONTEXT` ioctl
- `type`: `FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL`
- `completed`: Offset into the receive buffer; data before this offset is valid

**Description**

This event is sent in multichannel contexts (context type
`FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL`) for [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet) buffer
chunks that have been completely filled and that have the
`FW_CDEV_ISO_INTERRUPT` bit set, or when explicitly requested with
`FW_CDEV_IOC_FLUSH_ISO`.

- The buffer is continuously filled with the following data, per packet:
  - the 1394 iso packet header as described at [`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt),
    but in little endian byte order,
  - packet payload (as many bytes as specified in the data_length field of
    the 1394 iso packet header) in big endian byte order,
  - 0...3 padding bytes as needed to align the following trailer quadlet,
  - trailer quadlet, containing the reception timestamp as described at
    [`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt), but in little endian byte order.

Hence the per-packet size is data_length (rounded up to a multiple of 4) + 8.
When processing the data, stop before a packet that would cross the
**completed** offset.

A packet near the end of a buffer chunk will typically spill over into the
next queued buffer chunk.  It is the responsibility of the client to check
for this condition, assemble a broken-up packet from its parts, and not to
re-queue any buffer chunks in which as yet unread packet parts reside.

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

Iso resources were allocated or freed

**Definition**

```c
struct fw_cdev_event_iso_resource {
    __u64 closure;
    __u32 type;
    __u32 handle;
    __s32 channel;
    __s32 bandwidth;
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common);
  set by`FW_CDEV_IOC_(DE)ALLOCATE_ISO_RESOURCE(_ONCE)` ioctl
- `type`: `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` or
  `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED`
- `handle`: Reference by which an allocated resource can be deallocated
- `channel`: Isochronous channel which was (de)allocated, if any
- `bandwidth`: Bandwidth allocation units which were (de)allocated, if any

**Description**

An `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` event is sent after an isochronous
resource was allocated at the IRM.  The client has to check **channel** and
**bandwidth** for whether the allocation actually succeeded.

An `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED` event is sent after an isochronous
resource was deallocated at the IRM.  It is also sent when automatic
reallocation after a bus reset failed.

**channel** is \<0 if no channel was (de)allocated or if reallocation failed.
**bandwidth** is 0 if no bandwidth was (de)allocated or if reallocation failed.

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

A PHY packet was transmitted or received

**Definition**

```c
struct fw_cdev_event_phy_packet {
    __u64 closure;
    __u32 type;
    __u32 rcode;
    __u32 length;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_SEND_PHY_PACKET`
  or `FW_CDEV_IOC_RECEIVE_PHY_PACKETS` ioctl
- `type`: `FW_CDEV_EVENT_PHY_PACKET_SENT` or %..._RECEIVED
- `rcode`: `RCODE_`..., indicates success or failure of transmission
- `length`: Data length in bytes
- `data`: Incoming data for `FW_CDEV_IOC_RECEIVE_PHY_PACKETS`. For `FW_CDEV_IOC_SEND_PHY_PACKET`
  the field has the same data in the request, thus the length of 8 bytes.

**Description**

This event is sent instead of [`fw_cdev_event_phy_packet2`](#c-struct-fw_cdev_event_phy_packet2) if the kernel or
the client implements ABI version \<= 5. It has the lack of time stamp field comparing to
[`fw_cdev_event_phy_packet2`](#c-struct-fw_cdev_event_phy_packet2).

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

A PHY packet was transmitted or received with time stamp.

**Definition**

```c
struct fw_cdev_event_phy_packet2 {
    __u64 closure;
    __u32 type;
    __u32 rcode;
    __u32 length;
    __u32 tstamp;
    __u32 data[];
};
```

**Members**

- `closure`: See [`fw_cdev_event_common`](#c-struct-fw_cdev_event_common); set by `FW_CDEV_IOC_SEND_PHY_PACKET`
  or `FW_CDEV_IOC_RECEIVE_PHY_PACKETS` ioctl
- `type`: `FW_CDEV_EVENT_PHY_PACKET_SENT2` or `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`
- `rcode`: `RCODE_`..., indicates success or failure of transmission
- `length`: Data length in bytes
- `tstamp`: For `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`, the time stamp of isochronous cycle at
  which the packet arrived. For `FW_CDEV_EVENT_PHY_PACKET_SENT2` and non-ping packet,
  the time stamp of isochronous cycle at which the packet was sent. For ping packet,
  the tick count for round-trip time measured by 1394 OHCI controller.
- `data`: Incoming data

**Description**

The time stamp of isochronous cycle at which either the response was sent for
`FW_CDEV_EVENT_PHY_PACKET_SENT2` or the request arrived for
`FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`.

If **type** is `FW_CDEV_EVENT_PHY_PACKET_SENT2`, **length** is 8 and **data** consists of the two PHY
packet quadlets to be sent, in host byte order,

If **type** is `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`, **length** is 8 and **data** consists of the two PHY
packet quadlets, in host byte order.

For `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`, the **tstamp** is the isochronous cycle at which the
packet arrived. It is 16 bit integer value and the higher 3 bits expresses three low order bits
of second field and the rest 13 bits expresses cycle field in the format of CYCLE_TIME register.

For `FW_CDEV_EVENT_PHY_PACKET_SENT2`, the **tstamp** has different meanings whether to sent the
packet for ping or not. If it's not for ping, the **tstamp** is the isochronous cycle at which the
packet was sent, and use the same format as the case of `FW_CDEV_EVENT_PHY_PACKET_SENT2`. If it's
for ping, the **tstamp** is for round-trip time measured by 1394 OHCI controller with 42.195 MHz
resolution.

#### <a id="c-union-fw_cdev_event"></a>`union fw_cdev_event`

Convenience union of fw_cdev_event_* types

**Definition**

```c
union fw_cdev_event {
    struct fw_cdev_event_common             common;
    struct fw_cdev_event_bus_reset          bus_reset;
    struct fw_cdev_event_response           response;
    struct fw_cdev_event_request            request;
    struct fw_cdev_event_request2           request2;
    struct fw_cdev_event_iso_interrupt      iso_interrupt;
    struct fw_cdev_event_iso_interrupt_mc   iso_interrupt_mc;
    struct fw_cdev_event_iso_resource       iso_resource;
    struct fw_cdev_event_phy_packet         phy_packet;
    struct fw_cdev_event_request3           request3;
    struct fw_cdev_event_response2          response2;
    struct fw_cdev_event_phy_packet2        phy_packet2;
};
```

**Members**

- `common`: Valid for all types
- `bus_reset`: Valid if **common.type** == `FW_CDEV_EVENT_BUS_RESET`
- `response`: Valid if **common.type** == `FW_CDEV_EVENT_RESPONSE`
- `request`: Valid if **common.type** == `FW_CDEV_EVENT_REQUEST`
- `request2`: Valid if **common.type** == `FW_CDEV_EVENT_REQUEST2`
- `iso_interrupt`: Valid if **common.type** == `FW_CDEV_EVENT_ISO_INTERRUPT`
- `iso_interrupt_mc`: Valid if **common.type** ==
  `FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL`
- `iso_resource`: Valid if **common.type** ==
  `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` or
  `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED`
- `phy_packet`: Valid if **common.type** ==
  `FW_CDEV_EVENT_PHY_PACKET_SENT` or
  `FW_CDEV_EVENT_PHY_PACKET_RECEIVED`
- `request3`: Valid if **common.type** == `FW_CDEV_EVENT_REQUEST3`
- `response2`: Valid if **common.type** == `FW_CDEV_EVENT_RESPONSE2`
- `phy_packet2`: Valid if **common.type** == `FW_CDEV_EVENT_PHY_PACKET_SENT2` or
  `FW_CDEV_EVENT_PHY_PACKET_RECEIVED2`

**Description**

Convenience union for userspace use.  Events could be read(2) into an
appropriately aligned char buffer and then cast to this union for further
processing.  Note that for a request, response or iso_interrupt event,
the data\[\] or header\[\] may make the size of the full event larger than
sizeof(union fw_cdev_event).  Also note that if you attempt to read(2)
an event into a buffer that is not large enough for it, the data that does
not fit will be discarded so that the next read(2) will return a new event.

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

General purpose information ioctl

**Definition**

```c
struct fw_cdev_get_info {
    __u32 version;
    __u32 rom_length;
    __u64 rom;
    __u64 bus_reset;
    __u64 bus_reset_closure;
    __u32 card;
};
```

**Members**

- `version`: The version field is just a running serial number.  Both an
  input parameter (ABI version implemented by the client) and
  output parameter (ABI version implemented by the kernel).
  A client shall fill in the ABI **version** for which the client
  was implemented.  This is necessary for forward compatibility.
- `rom_length`: If **rom** is non-zero, up to **rom_length** bytes of Configuration
  ROM will be copied into that user space address.  In either
  case, **rom_length** is updated with the actual length of the
  Configuration ROM.
- `rom`: If non-zero, address of a buffer to be filled by a copy of the
  device's Configuration ROM
- `bus_reset`: If non-zero, address of a buffer to be filled by a
  [`struct fw_cdev_event_bus_reset`](#c-struct-fw_cdev_event_bus_reset) with the current state
  of the bus.  This does not cause a bus reset to happen.
- `bus_reset_closure`: Value of `closure` in this and subsequent bus reset events
- `card`: The index of the card this device belongs to

**Description**

The `FW_CDEV_IOC_GET_INFO` ioctl is usually the very first one which a client
performs right after it opened a /dev/fw* file.

As a side effect, reception of `FW_CDEV_EVENT_BUS_RESET` events to be read(2)
is started by this ioctl.

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

Send an asynchronous request packet

**Definition**

```c
struct fw_cdev_send_request {
    __u32 tcode;
    __u32 length;
    __u64 offset;
    __u64 closure;
    __u64 data;
    __u32 generation;
};
```

**Members**

- `tcode`: Transaction code of the request
- `length`: Length of outgoing payload, in bytes
- `offset`: 48-bit offset at destination node
- `closure`: Passed back to userspace in the response event
- `data`: Userspace pointer to payload
- `generation`: The bus generation where packet is valid

**Description**

Send a request to the device.  This ioctl implements all outgoing requests. Both quadlet and
block request specify the payload as a pointer to the data in the **data** field. Once the
transaction completes, the kernel writes either [`fw_cdev_event_response`](#c-struct-fw_cdev_event_response) event or
[`fw_cdev_event_response`](#c-struct-fw_cdev_event_response) event back. The **closure** field is passed back to user space in the
response event.

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

Send an asynchronous response packet

**Definition**

```c
struct fw_cdev_send_response {
    __u32 rcode;
    __u32 length;
    __u64 data;
    __u32 handle;
};
```

**Members**

- `rcode`: Response code as determined by the userspace handler
- `length`: Length of outgoing payload, in bytes
- `data`: Userspace pointer to payload
- `handle`: The handle from the [`fw_cdev_event_request`](#c-struct-fw_cdev_event_request)

**Description**

Send a response to an incoming request.  By setting up an address range using
the `FW_CDEV_IOC_ALLOCATE` ioctl, userspace can listen for incoming requests.  An
incoming request will generate an `FW_CDEV_EVENT_REQUEST`, and userspace must
send a reply using this ioctl.  The event has a handle to the kernel-side
pending transaction, which should be used with this ioctl.

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

Allocate a CSR in an address range

**Definition**

```c
struct fw_cdev_allocate {
    __u64 offset;
    __u64 closure;
    __u32 length;
    __u32 handle;
    __u64 region_end;
};
```

**Members**

- `offset`: Start offset of the address range
- `closure`: To be passed back to userspace in request events
- `length`: Length of the CSR, in bytes
- `handle`: Handle to the allocation, written by the kernel
- `region_end`: First address above the address range (added in ABI v4, 2.6.36)

**Description**

Allocate an address range in the 48-bit address space on the local node
(the controller).  This allows userspace to listen for requests with an
offset within that address range.  Every time when the kernel receives a
request within the range, an [`fw_cdev_event_request2`](#c-struct-fw_cdev_event_request2) event will be emitted.
(If the kernel or the client implements ABI version \<= 3, an
[`fw_cdev_event_request`](#c-struct-fw_cdev_event_request) will be generated instead.)

The **closure** field is passed back to userspace in these request events.
The **handle** field is an out parameter, returning a handle to the allocated
range to be used for later deallocation of the range.

The address range is allocated on all local nodes.  The address allocation
is exclusive except for the FCP command and response registers.  If an
exclusive address region is already in use, the ioctl fails with errno set
to `EBUSY`.

If kernel and client implement ABI version >= 4, the kernel looks up a free
spot of size **length** inside \[**offset**..**region_end**) and, if found, writes
the start address of the new CSR back in **offset**.  I.e. **offset** is an
in and out parameter.  If this automatic placement of a CSR in a bigger
address range is not desired, the client simply needs to set **region_end**
= **offset** + **length**.

If the kernel or the client implements ABI version \<= 3, **region_end** is
ignored and effectively assumed to be **offset** + **length**.

**region_end** is only present in a kernel header >= 2.6.36.  If necessary,
this can for example be tested by #ifdef FW_CDEV_EVENT_REQUEST2.

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

Free a CSR address range or isochronous resource

**Definition**

```c
struct fw_cdev_deallocate {
    __u32 handle;
};
```

**Members**

- `handle`: Handle to the address range or iso resource, as returned by the
  kernel when the range or resource was allocated

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

Initiate a bus reset

**Definition**

```c
struct fw_cdev_initiate_bus_reset {
    __u32 type;
};
```

**Members**

- `type`: `FW_CDEV_SHORT_RESET` or `FW_CDEV_LONG_RESET`

**Description**

Initiate a bus reset for the bus this device is on.  The bus reset can be
either the original (long) bus reset or the arbitrated (short) bus reset
introduced in 1394a-2000.

The ioctl returns immediately.  A subsequent [`fw_cdev_event_bus_reset`](#c-struct-fw_cdev_event_bus_reset)
indicates when the reset actually happened.  Since ABI v4, this may be
considerably later than the ioctl because the kernel ensures a grace period
between subsequent bus resets as per IEEE 1394 bus management specification.

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

Add contents to the local node's config ROM

**Definition**

```c
struct fw_cdev_add_descriptor {
    __u32 immediate;
    __u32 key;
    __u64 data;
    __u32 length;
    __u32 handle;
};
```

**Members**

- `immediate`: If non-zero, immediate key to insert before pointer
- `key`: Upper 8 bits of root directory pointer
- `data`: Userspace pointer to contents of descriptor block
- `length`: Length of descriptor block data, in quadlets
- `handle`: Handle to the descriptor, written by the kernel

**Description**

Add a descriptor block and optionally a preceding immediate key to the local
node's Configuration ROM.

The **key** field specifies the upper 8 bits of the descriptor root directory
pointer and the **data** and **length** fields specify the contents. The **key**
should be of the form 0xXX000000. The offset part of the root directory entry
will be filled in by the kernel.

If not 0, the **immediate** field specifies an immediate key which will be
inserted before the root directory pointer.

**immediate**, **key**, and **data** array elements are CPU-endian quadlets.

If successful, the kernel adds the descriptor and writes back a **handle** to
the kernel-side object to be used for later removal of the descriptor block
and immediate key.  The kernel will also generate a bus reset to signal the
change of the Configuration ROM to other nodes.

This ioctl affects the Configuration ROMs of all local nodes.
The ioctl only succeeds on device files which represent a local node.

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

Remove contents from the Configuration ROM

**Definition**

```c
struct fw_cdev_remove_descriptor {
    __u32 handle;
};
```

**Members**

- `handle`: Handle to the descriptor, as returned by the kernel when the
  descriptor was added

**Description**

Remove a descriptor block and accompanying immediate key from the local
nodes' Configuration ROMs.  The kernel will also generate a bus reset to
signal the change of the Configuration ROM to other nodes.

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

Create a context for isochronous I/O

**Definition**

```c
struct fw_cdev_create_iso_context {
    __u32 type;
    __u32 header_size;
    __u32 channel;
    __u32 speed;
    __u64 closure;
    __u32 handle;
};
```

**Members**

- `type`: `FW_CDEV_ISO_CONTEXT_TRANSMIT` or `FW_CDEV_ISO_CONTEXT_RECEIVE` or
  `FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL`
- `header_size`: Header size to strip in single-channel reception
- `channel`: Channel to bind to in single-channel reception or transmission
- `speed`: Transmission speed
- `closure`: To be returned in [`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt) or
  `fw_cdev_event_iso_interrupt_multichannel`
- `handle`: Handle to context, written back by kernel

**Description**

Prior to sending or receiving isochronous I/O, a context must be created.
The context records information about the transmit or receive configuration
and typically maps to an underlying hardware resource.  A context is set up
for either sending or receiving.  It is bound to a specific isochronous
**channel**.

In case of multichannel reception, **header_size** and **channel** are ignored
and the channels are selected by `FW_CDEV_IOC_SET_ISO_CHANNELS`.

For `FW_CDEV_ISO_CONTEXT_RECEIVE` contexts, **header_size** must be at least 4
and must be a multiple of 4.  It is ignored in other context types.

**speed** is ignored in receive context types.

If a context was successfully created, the kernel writes back a handle to the
context, which must be passed in for subsequent operations on that context.

Limitations:
No more than one iso context can be created per fd.
The total number of contexts that all userspace and kernelspace drivers can
create on a card at a time is a hardware limit, typically 4 or 8 contexts per
direction, and of them at most one multichannel receive context.

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

Select channels in multichannel reception

**Definition**

```c
struct fw_cdev_set_iso_channels {
    __u64 channels;
    __u32 handle;
};
```

**Members**

- `channels`: Bitmask of channels to listen to
- `handle`: Handle of the mutichannel receive context

**Description**

**channels** is the bitwise or of 1ULL \<\< n for each channel n to listen to.

The ioctl fails with errno `EBUSY` if there is already another receive context
on a channel in **channels**.  In that case, the bitmask of all unoccupied
channels is returned in **channels**.

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

Isochronous packet

**Definition**

```c
struct fw_cdev_iso_packet {
    __u32 control;
    __u32 header[];
};
```

**Members**

- `control`: Contains the header length (8 uppermost bits),
  the sy field (4 bits), the tag field (2 bits), a sync flag
  or a skip flag (1 bit), an interrupt flag (1 bit), and the
  payload length (16 lowermost bits)
- `header`: Header and payload in case of a transmit context.

**Description**

[`struct fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet) is used to describe isochronous packet queues.
Use the FW_CDEV_ISO_* macros to fill in **control**.
The **header** array is empty in case of receive contexts.

Context type `FW_CDEV_ISO_CONTEXT_TRANSMIT`:

**control.HEADER_LENGTH** must be a multiple of 4.  It specifies the numbers of
bytes in **header** that will be prepended to the packet's payload.  These bytes
are copied into the kernel and will not be accessed after the ioctl has
returned.

The **control.SY** and TAG fields are copied to the iso packet header.  These
fields are specified by IEEE 1394a and IEC 61883-1.

The **control.SKIP** flag specifies that no packet is to be sent in a frame.
When using this, all other fields except **control.INTERRUPT** must be zero.

When a packet with the **control.INTERRUPT** flag set has been completed, an
[`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt) event will be sent.

Context type `FW_CDEV_ISO_CONTEXT_RECEIVE`:

**control.HEADER_LENGTH** must be a multiple of the context's header_size.
If the HEADER_LENGTH is larger than the context's header_size, multiple
packets are queued for this entry.

The **control.SY** and TAG fields are ignored.

If the **control.SYNC** flag is set, the context drops all packets until a
packet with a sy field is received which matches [`fw_cdev_start_iso.sync`](#c-struct-fw_cdev_start_iso).

**control.PAYLOAD_LENGTH** defines how many payload bytes can be received for
one packet (in addition to payload quadlets that have been defined as headers
and are stripped and returned in the [`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt) structure).
If more bytes are received, the additional bytes are dropped.  If less bytes
are received, the remaining bytes in this part of the payload buffer will not
be written to, not even by the next packet.  I.e., packets received in
consecutive frames will not necessarily be consecutive in memory.  If an
entry has queued multiple packets, the PAYLOAD_LENGTH is divided equally
among them.

When a packet with the **control.INTERRUPT** flag set has been completed, an
[`fw_cdev_event_iso_interrupt`](#c-struct-fw_cdev_event_iso_interrupt) event will be sent.  An entry that has queued
multiple receive packets is completed when its last packet is completed.

Context type `FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL`:

Here, [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet) would be more aptly named _iso_buffer_chunk since
it specifies a chunk of the `mmap()`'ed buffer, while the number and alignment
of packets to be placed into the buffer chunk is not known beforehand.

**control.PAYLOAD_LENGTH** is the size of the buffer chunk and specifies room
for header, payload, padding, and trailer bytes of one or more packets.
It must be a multiple of 4.

**control.HEADER_LENGTH**, TAG and SY are ignored.  SYNC is treated as described
for single-channel reception.

When a buffer chunk with the **control.INTERRUPT** flag set has been filled
entirely, an [`fw_cdev_event_iso_interrupt_mc`](#c-struct-fw_cdev_event_iso_interrupt_mc) event will be sent.

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

Queue isochronous packets for I/O

**Definition**

```c
struct fw_cdev_queue_iso {
    __u64 packets;
    __u64 data;
    __u32 size;
    __u32 handle;
};
```

**Members**

- `packets`: Userspace pointer to an array of [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet)
- `data`: Pointer into `mmap()`'ed payload buffer
- `size`: Size of the **packets** array, in bytes
- `handle`: Isochronous context handle

**Description**

Queue a number of isochronous packets for reception or transmission.
This ioctl takes a pointer to an array of [`fw_cdev_iso_packet`](#c-struct-fw_cdev_iso_packet) structs,
which describe how to transmit from or receive into a contiguous region
of a `mmap()`'ed payload buffer.  As part of transmit packet descriptors,
a series of headers can be supplied, which will be prepended to the
payload during DMA.

The kernel may or may not queue all packets, but will write back updated
values of the **packets**, **data** and **size** fields, so the ioctl can be
resubmitted easily.

In case of a multichannel receive context, **data** must be quadlet-aligned
relative to the buffer start.

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

Start an isochronous transmission or reception

**Definition**

```c
struct fw_cdev_start_iso {
    __s32 cycle;
    __u32 sync;
    __u32 tags;
    __u32 handle;
};
```

**Members**

- `cycle`: Cycle in which to start I/O.  If **cycle** is greater than or
  equal to 0, the I/O will start on that cycle.
- `sync`: Determines the value to wait for receive packets that have
  the `FW_CDEV_ISO_SYNC` bit set
- `tags`: Tag filter bit mask.  Only valid for isochronous reception.
  Determines the tag values for which packets will be accepted.
  Use FW_CDEV_ISO_CONTEXT_MATCH_* macros to set **tags**.
- `handle`: Isochronous context handle within which to transmit or receive

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

Stop an isochronous transmission or reception

**Definition**

```c
struct fw_cdev_stop_iso {
    __u32 handle;
};
```

**Members**

- `handle`: Handle of isochronous context to stop

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

flush completed iso packets

**Definition**

```c
struct fw_cdev_flush_iso {
    __u32 handle;
};
```

**Members**

- `handle`: handle of isochronous context to flush

**Description**

For `FW_CDEV_ISO_CONTEXT_TRANSMIT` or `FW_CDEV_ISO_CONTEXT_RECEIVE` contexts,
report any completed packets.

For `FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL` contexts, report the current
offset in the receive buffer, if it has changed; this is typically in the
middle of some buffer chunk.

Any `FW_CDEV_EVENT_ISO_INTERRUPT` or `FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL`
events generated by this ioctl are sent synchronously, i.e., are available
for reading from the file descriptor when this ioctl returns.

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

read cycle timer register

**Definition**

```c
struct fw_cdev_get_cycle_timer {
    __u64 local_time;
    __u32 cycle_timer;
};
```

**Members**

- `local_time`: system time, in microseconds since the Epoch
- `cycle_timer`: Cycle Time register contents

**Description**

Same as `FW_CDEV_IOC_GET_CYCLE_TIMER2`, but fixed to use `CLOCK_REALTIME`
and only with microseconds resolution.

In version 1 and 2 of the ABI, this ioctl returned unreliable (non-
monotonic) **cycle_timer** values on certain controllers.

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

read cycle timer register

**Definition**

```c
struct fw_cdev_get_cycle_timer2 {
    __s64 tv_sec;
    __s32 tv_nsec;
    __s32 clk_id;
    __u32 cycle_timer;
};
```

**Members**

- `tv_sec`: system time, seconds
- `tv_nsec`: system time, sub-seconds part in nanoseconds
- `clk_id`: input parameter, clock from which to get the system time
- `cycle_timer`: Cycle Time register contents

**Description**

The `FW_CDEV_IOC_GET_CYCLE_TIMER2` ioctl reads the isochronous cycle timer
and also the system clock.  This allows to correlate reception time of
isochronous packets with system time.

**clk_id** lets you choose a clock like with POSIX' clock_gettime function.
Supported **clk_id** values are POSIX' `CLOCK_REALTIME` and `CLOCK_MONOTONIC`
and Linux' `CLOCK_MONOTONIC_RAW`.

**cycle_timer** consists of 7 bits cycleSeconds, 13 bits cycleCount, and
12 bits cycleOffset, in host byte order.  Cf. the Cycle Time register
per IEEE 1394 or Isochronous Cycle Timer register per OHCI-1394.

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

(De)allocate a channel or bandwidth

**Definition**

```c
struct fw_cdev_allocate_iso_resource {
    __u64 closure;
    __u64 channels;
    __u32 bandwidth;
    __u32 handle;
};
```

**Members**

- `closure`: Passed back to userspace in corresponding iso resource events
- `channels`: Isochronous channels of which one is to be (de)allocated
- `bandwidth`: Isochronous bandwidth units to be (de)allocated
- `handle`: Handle to the allocation, written by the kernel (only valid in
  case of `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE` ioctls)

**Description**

The `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE` ioctl initiates allocation of an
isochronous channel and/or of isochronous bandwidth at the isochronous
resource manager (IRM).  Only one of the channels specified in **channels** is
allocated.  An `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` is sent after
communication with the IRM, indicating success or failure in the event data.
The kernel will automatically reallocate the resources after bus resets.
Should a reallocation fail, an `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED` event
will be sent.  The kernel will also automatically deallocate the resources
when the file descriptor is closed.

The `FW_CDEV_IOC_DEALLOCATE_ISO_RESOURCE` ioctl can be used to initiate
deallocation of resources which were allocated as described above.
An `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED` event concludes this operation.

The `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE` ioctl is a variant of allocation
without automatic re- or deallocation.
An `FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED` event concludes this operation,
indicating success or failure in its data.

The `FW_CDEV_IOC_DEALLOCATE_ISO_RESOURCE_ONCE` ioctl works like
`FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE` except that resources are freed
instead of allocated.
An `FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED` event concludes this operation.

To summarize, `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE` allocates iso resources
for the lifetime of the fd or **handle**.
In contrast, `FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE` allocates iso resources
for the duration of a bus generation.

**channels** is a host-endian bitfield with the least significant bit
representing channel 0 and the most significant bit representing channel 63:
1ULL \<\< c for each channel c that is a candidate for (de)allocation.

**bandwidth** is expressed in bandwidth allocation units, i.e. the time to send
one quadlet of data (payload or header data) at speed S1600.

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

send an asynchronous stream packet

**Definition**

```c
struct fw_cdev_send_stream_packet {
    __u32 length;
    __u32 tag;
    __u32 channel;
    __u32 sy;
    __u64 closure;
    __u64 data;
    __u32 generation;
    __u32 speed;
};
```

**Members**

- `length`: Length of outgoing payload, in bytes
- `tag`: Data format tag
- `channel`: Isochronous channel to transmit to
- `sy`: Synchronization code
- `closure`: Passed back to userspace in the response event
- `data`: Userspace pointer to payload
- `generation`: The bus generation where packet is valid
- `speed`: Speed to transmit at

**Description**

The `FW_CDEV_IOC_SEND_STREAM_PACKET` ioctl sends an asynchronous stream packet to every device
which is listening to the specified channel. The kernel writes either [`fw_cdev_event_response`](#c-struct-fw_cdev_event_response)
event or [`fw_cdev_event_response2`](#c-struct-fw_cdev_event_response2) event which indicates success or failure of the transmission.

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

send a PHY packet

**Definition**

```c
struct fw_cdev_send_phy_packet {
    __u64 closure;
    __u32 data[2];
    __u32 generation;
};
```

**Members**

- `closure`: Passed back to userspace in the PHY-packet-sent event
- `data`: First and second quadlet of the PHY packet
- `generation`: The bus generation where packet is valid

**Description**

The `FW_CDEV_IOC_SEND_PHY_PACKET` ioctl sends a PHY packet to all nodes on the same card as this
device.  After transmission, either `FW_CDEV_EVENT_PHY_PACKET_SENT` event or
`FW_CDEV_EVENT_PHY_PACKET_SENT` event is generated.

The payload **data**\\[\\] shall be specified in host byte order.  Usually,
**data**\\[1\\] needs to be the bitwise inverse of **data**\\[0\\].  VersaPHY packets
are an exception to this rule.

The ioctl is only permitted on device files which represent a local node.

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

start reception of PHY packets

**Definition**

```c
struct fw_cdev_receive_phy_packets {
    __u64 closure;
};
```

**Members**

- `closure`: Passed back to userspace in phy packet events

**Description**

This ioctl activates issuing of either `FW_CDEV_EVENT_PHY_PACKET_RECEIVED` or
`FW_CDEV_EVENT_PHY_PACKET_RECEIVED2` due to incoming PHY packets from any node on the same bus
as the device.

The ioctl is only permitted on device files which represent a local node.


<a id="rst-firewire-device-probing-and-sysfs-interfaces"></a>

## Firewire device probing and sysfs interfaces




```text
What:           /sys/bus/firewire/devices/fw[0-9]+/
Date:           May 2007
KernelVersion:  2.6.22
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                IEEE 1394 node device attributes.
                Read-only.  Mutable during the node device's lifetime.
                See IEEE 1212 for semantic definitions.

                config_rom
                        Contents of the Configuration ROM register.
                        Binary attribute; an array of host-endian u32.

                guid
                        The node's EUI-64 in the bus information block of
                        Configuration ROM.
                        Hexadecimal string representation of an u64.


What:           /sys/bus/firewire/devices/fw[0-9]+/units
Date:           June 2009
KernelVersion:  2.6.31
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                IEEE 1394 node device attribute.
                Read-only.  Mutable during the node device's lifetime.
                See IEEE 1212 for semantic definitions.

                units
                        Summary of all units present in an IEEE 1394 node.
                        Contains space-separated tuples of specifier_id and
                        version of each unit present in the node.  Specifier_id
                        and version are hexadecimal string representations of
                        u24 of the respective unit directory entries.
                        Specifier_id and version within each tuple are separated
                        by a colon.

Users:          udev rules to set ownership and access permissions or ACLs of
                /dev/fw[0-9]+ character device files


What:           /sys/bus/firewire/devices/fw[0-9]+/is_local
Date:           July 2012
KernelVersion:  3.6
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                IEEE 1394 node device attribute.
                Read-only and immutable.
Values:         1: The sysfs entry represents a local node (a controller card).

                0: The sysfs entry represents a remote node.


What:           /sys/bus/firewire/devices/fw[0-9]+[.][0-9]+/
Date:           May 2007
KernelVersion:  2.6.22
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                IEEE 1394 unit device attributes.
                Read-only.  Immutable during the unit device's lifetime.
                See IEEE 1212 for semantic definitions.

                modalias
                        Same as MODALIAS in the uevent at device creation.

                rom_index
                        Offset of the unit directory within the parent device's
                        (node device's) Configuration ROM, in quadlets.
                        Decimal string representation.


What:           /sys/bus/firewire/devices/*/
Date:           May 2007
KernelVersion:  2.6.22
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                Attributes common to IEEE 1394 node devices and unit devices.
                Read-only.  Mutable during the node device's lifetime.
                Immutable during the unit device's lifetime.
                See IEEE 1212 for semantic definitions.

                These attributes are only created if the root directory of an
                IEEE 1394 node or the unit directory of an IEEE 1394 unit
                actually contains according entries.

                hardware_version
                        Hexadecimal string representation of an u24.

                hardware_version_name
                        Contents of a respective textual descriptor leaf.

                model
                        Hexadecimal string representation of an u24.

                model_name
                        Contents of a respective textual descriptor leaf.

                specifier_id
                        Hexadecimal string representation of an u24.
                        Mandatory in unit directories according to IEEE 1212.

                vendor
                        Hexadecimal string representation of an u24.
                        Mandatory in the root directory according to IEEE 1212.

                vendor_name
                        Contents of a respective textual descriptor leaf.

                version
                        Hexadecimal string representation of an u24.
                        Mandatory in unit directories according to IEEE 1212.


What:           /sys/bus/firewire/drivers/sbp2/fw*/host*/target*/*:*:*:*/ieee1394_id
                formerly
                /sys/bus/ieee1394/drivers/sbp2/fw*/host*/target*/*:*:*:*/ieee1394_id
Date:           Feb 2004
KernelVersion:  2.6.4
Contact:        linux1394-devel@lists.sourceforge.net
Description:
                SCSI target port identifier and logical unit identifier of a
                logical unit of an SBP-2 target.  The identifiers are specified
                in SAM-2...SAM-4 annex A.  They are persistent and world-wide
                unique properties the SBP-2 attached target.

                Read-only attribute, immutable during the target's lifetime.
                Format, as exposed by firewire-sbp2 since 2.6.22, May 2007:
                Colon-separated hexadecimal string representations of

                        u64 EUI-64 : u24 directory_ID : u16 LUN

                without 0x prefixes, without whitespace.  The former sbp2 driver
                (removed in 2.6.37 after being superseded by firewire-sbp2) used
                a somewhat shorter format which was not as close to SAM.

Users:          udev rules to create /dev/disk/by-id/ symlinks

```



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

```c
int fw_csr_string(const u32 *directory, int key, char *buf, size_t size)
```

reads a string from the configuration ROM

**Parameters**

- `const u32 *directory`: e.g. root directory or unit directory
- `int key`: the key of the preceding directory entry
- `char *buf`: where to put the string
- `size_t size`: size of **buf**, in bytes

**Description**

The string is taken from a minimal ASCII text descriptor leaf just after the entry with the
**key**. The string is zero-terminated. An overlong string is silently truncated such that it
and the zero byte fit into **size**.

Returns strlen(buf) or a negative error code.


<a id="rst-firewire-core-transaction-interfaces"></a>

## Firewire core transaction interfaces


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

```c
void __fw_send_request(struct fw_card *card, struct fw_transaction *t, int tcode, int destination_id, int generation, int speed, unsigned long long offset, void *payload, size_t length, union fw_transaction_callback callback, bool with_tstamp, void *callback_data)
```

submit a request packet for transmission to generate callback for response subaction with or without time stamp.

**Parameters**

- `struct fw_card *card`: interface to send the request at
- `struct fw_transaction *t`: transaction instance to which the request belongs
- `int tcode`: transaction code
- `int destination_id`: destination node ID, consisting of bus_ID and phy_ID
- `int generation`: bus generation in which request and response are valid
- `int speed`: transmission speed
- `unsigned long long offset`: 48bit wide offset into destination's address space
- `void *payload`: data payload for the request subaction
- `size_t length`: length of the payload, in bytes
- `union fw_transaction_callback callback`: union of two functions whether to receive time stamp or not for response
  subaction.
- `bool with_tstamp`: Whether to receive time stamp or not for response subaction.
- `void *callback_data`: data to be passed to the transaction completion callback

**Description**

Submit a request packet into the asynchronous request transmission queue.
Can be called from atomic context.  If you prefer a blocking API, use
[`fw_run_transaction()`](#c-fw_run_transaction) in a context that can sleep.

In case of lock requests, specify one of the firewire-core specific `TCODE_`
constants instead of `TCODE_LOCK_REQUEST` in **tcode**.

Make sure that the value in **destination_id** is not older than the one in
**generation**.  Otherwise the request is in danger to be sent to a wrong node.

In case of asynchronous stream packets i.e. `TCODE_STREAM_DATA`, the caller
needs to synthesize **destination_id** with `fw_stream_packet_destination_id()`.
It will contain tag, channel, and sy data instead of a node ID then.

The payload buffer at **data** is going to be DMA-mapped except in case of
**length** \<= 8 or of local (loopback) requests.  Hence make sure that the
buffer complies with the restrictions of the streaming DMA mapping API.
**payload** must not be freed before the **callback** is called.

In case of request types without payload, **data** is NULL and **length** is 0.

After the transaction is completed successfully or unsuccessfully, the
**callback** will be called.  Among its parameters is the response code which
is either one of the rcodes per IEEE 1394 or, in case of internal errors,
the firewire-core specific `RCODE_SEND_ERROR`.  The other firewire-core
specific rcodes (`RCODE_CANCELLED`, `RCODE_BUSY`, `RCODE_GENERATION`,
`RCODE_NO_ACK`) denote transaction timeout, busy responder, stale request
generation, or missing ACK respectively.

Note some timing corner cases:  `fw_send_request()` may complete much earlier
than when the request packet actually hits the wire.  On the other hand,
transaction completion and hence execution of **callback** may happen even
before `fw_send_request()` returns.

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

```c
int fw_run_transaction(struct fw_card *card, int tcode, int destination_id, int generation, int speed, unsigned long long offset, void *payload, size_t length)
```

send request and sleep until transaction is completed

**Parameters**

- `struct fw_card *card`: card interface for this request
- `int tcode`: transaction code
- `int destination_id`: destination node ID, consisting of bus_ID and phy_ID
- `int generation`: bus generation in which request and response are valid
- `int speed`: transmission speed
- `unsigned long long offset`: 48bit wide offset into destination's address space
- `void *payload`: data payload for the request subaction
- `size_t length`: length of the payload, in bytes

**Description**

Returns the RCODE.  See `fw_send_request()` for parameter documentation.
Unlike `fw_send_request()`, **data** points to the payload of the request or/and
to the payload of the response.  DMA mapping restrictions apply to outbound
request payloads of >= 8 bytes but not to inbound response payloads.

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

```c
int fw_core_add_address_handler(struct fw_address_handler *handler, const struct fw_address_region *region)
```

register for incoming requests

**Parameters**

- `struct fw_address_handler *handler`: callback
- `const struct fw_address_region *region`: region in the IEEE 1212 node space address range

**Description**

region->start, ->end, and handler->length have to be quadlet-aligned.

When a request is received that falls within the specified address range, the specified callback
is invoked.  The parameters passed to the callback give the details of the particular request.
The callback is invoked in the workqueue context in most cases. However, if the request is
initiated by the local node, the callback is invoked in the initiator's context.

To be called in process context.
Return value:  0 on success, non-zero otherwise.

The start offset of the handler's address region is determined by
[`fw_core_add_address_handler()`](#c-fw_core_add_address_handler) and is returned in handler->offset.

Address allocations are exclusive, except for the FCP registers.

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

```c
void fw_core_remove_address_handler(struct fw_address_handler *handler)
```

unregister an address handler

**Parameters**

- `struct fw_address_handler *handler`: callback

**Description**

To be called in process context.

When [`fw_core_remove_address_handler()`](#c-fw_core_remove_address_handler) returns, **handler->callback()** is
guaranteed to not run on any CPU anymore.

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

```c
void fw_send_response(struct fw_card *card, struct fw_request *request, int rcode)
```

- send response packet for asynchronous transaction.

**Parameters**

- `struct fw_card *card`: interface to send the response at.
- `struct fw_request *request`: firewire request data for the transaction.
- `int rcode`: response code to send.

**Description**

Submit a response packet into the asynchronous response transmission queue. The **request**
is going to be released when the transmission successfully finishes later.

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

```c
int fw_get_request_speed(struct fw_request *request)
```

returns speed at which the **request** was received

**Parameters**

- `struct fw_request *request`: firewire request data

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

```c
u32 fw_request_get_timestamp(const struct fw_request *request)
```

Get timestamp of the request.

**Parameters**

- `const struct fw_request *request`: The opaque pointer to request structure.

**Description**

Get timestamp when 1394 OHCI controller receives the asynchronous request subaction. The
timestamp consists of the low order 3 bits of second field and the full 13 bits of count
field of isochronous cycle time register.

**Return**

timestamp of the request.

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

```c
const char * fw_rcode_string(int rcode)
```

convert a firewire result code to an error description

**Parameters**

- `int rcode`: the result code


<a id="rst-firewire-isochronous-i-o-interfaces"></a>

## Firewire Isochronous I/O interfaces


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

```c
void fw_iso_context_schedule_flush_completions(struct fw_iso_context *ctx)
```

schedule work item to process isochronous context.

**Parameters**

- `struct fw_iso_context *ctx`: the isochronous context

**Description**

Schedule a work item on workqueue to process the isochronous context. The registered callback
function is called by the worker when a queued packet buffer with the interrupt flag is
completed, either after transmission in the IT context or after being filled in the IR context.
The callback function is also called when the header buffer in the context becomes full, If it
is required to process the context in the current context, [`fw_iso_context_flush_completions()`](#c-fw_iso_context_flush_completions) is
available instead.

**Context**

Any context.



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

```c
int fw_iso_context_flush_completions(struct fw_iso_context *ctx)
```

process isochronous context in current process context.

**Parameters**

- `struct fw_iso_context *ctx`: the isochronous context

**Description**

Process the isochronous context in the current process context. The registered callback function
is called when a queued packet buffer with the interrupt flag is completed, either after
transmission in the IT context or after being filled in the IR context. Additionally, the
callback function is also called for the packet buffer completed at last. Furthermore, the
callback function is called as well when the header buffer in the context becomes full. If it is
required to process the context asynchronously, [`fw_iso_context_schedule_flush_completions()`](#c-fw_iso_context_schedule_flush_completions) is
available instead.

**Context**

Process context. May sleep due to [`disable_work_sync()`](/kernel/internals/core-api/workqueue.md#c-disable_work_sync).

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

```c
void fw_iso_resource_manage(struct fw_card *card, int generation, u64 channels_mask, int *channel, int *bandwidth, bool allocate)
```

Allocate or deallocate a channel and/or bandwidth

**Parameters**

- `struct fw_card *card`: card interface for this action
- `int generation`: bus generation
- `u64 channels_mask`: bitmask for channel allocation
- `int *channel`: pointer for returning channel allocation result
- `int *bandwidth`: pointer for returning bandwidth allocation result
- `bool allocate`: whether to allocate (true) or deallocate (false)

**Description**

In parameters: card, generation, channels_mask, bandwidth, allocate
Out parameters: channel, bandwidth

This function blocks (sleeps) during communication with the IRM.

Allocates or deallocates at most one channel out of channels_mask.
channels_mask is a bitfield with MSB for channel 63 and LSB for channel 0.
(Note, the IRM's CHANNELS_AVAILABLE is a big-endian bitfield with MSB for
channel 0 and LSB for channel 63.)
Allocates or deallocates as many bandwidth allocation units as specified.

Returns channel \< 0 if no channel was allocated or deallocated.
Returns bandwidth = 0 if no bandwidth was allocated or deallocated.

If generation is stale, deallocations succeed but allocations fail with
channel = -EAGAIN.

If channel allocation fails, no bandwidth will be allocated either.
If bandwidth allocation fails, no channel will be allocated either.
But deallocations of channel and bandwidth are tried independently
of each other's success.

---

# High Speed Synchronous Serial Interface (HSI)

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> High Speed Synchronous Interface (HSI) is a full duplex, low latency protocol, that is optimized for die-level interconnect between an Application Processor and a Baseband chipset. It has been specified by the MIPI alliance in 2003 and…

<a id="rst-high-speed-synchronous-serial-interface-hsi"></a>

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

## Introduction

High Speed Synchronous Interface (HSI) is a full duplex, low latency protocol, that is optimized for die-level interconnect between an Application Processor and a Baseband chipset. It has been specified by the MIPI alliance in 2003 and implemented by multiple vendors since then.

The HSI interface supports full duplex communication over multiple channels (typically 8) and is capable of reaching speeds up to 200 Mbit/s.

The serial protocol uses two signals, DATA and FLAG as combined data and clock signals and an additional READY signal for flow control. An additional WAKE signal can be used to wakeup the chips from standby modes. The signals are commonly prefixed by AC for signals going from the application die to the cellular die and CA for signals going the other way around.



```text
+------------+                                 +---------------+
|  Cellular  |                                 |  Application  |
|    Die     |                                 |      Die      |
|            | - - - - - - CAWAKE - - - - - - >|               |
|           T|------------ CADATA ------------>|R              |
|           X|------------ CAFLAG ------------>|X              |
|            |<----------- ACREADY ------------|               |
|            |                                 |               |
|            |                                 |               |
|            |< - - - - -  ACWAKE - - - - - - -|               |
|           R|<----------- ACDATA -------------|T              |
|           X|<----------- ACFLAG -------------|X              |
|            |------------ CAREADY ----------->|               |
|            |                                 |               |
|            |                                 |               |
+------------+                                 +---------------+
```

<a id="rst-hsi-subsystem-in-linux"></a>

## HSI Subsystem in Linux

In the Linux kernel the hsi subsystem is supposed to be used for HSI devices. The hsi subsystem contains drivers for hsi controllers including support for multi-port controllers and provides a generic API for using the HSI ports.

It also contains HSI client drivers, which make use of the generic API to implement a protocol used on the HSI interface. These client drivers can use an arbitrary number of channels.

<a id="rst-hsi-char-device"></a>

## hsi-char Device

Each port automatically registers a generic client driver called hsi_char, which provides a character device for userspace representing the HSI port. It can be used to communicate via HSI from userspace. Userspace may configure the hsi_char device using the following ioctl commands:

- **HSC_RESET**

  flush the HSI port

- **HSC_SET_PM**

  enable or disable the client.

- **HSC_SEND_BREAK**

  send break

- **HSC_SET_RX**

  set RX configuration

- **HSC_GET_RX**

  get RX configuration

- **HSC_SET_TX**

  set TX configuration

- **HSC_GET_TX**

  get TX configuration

<a id="rst-the-kernel-hsi-api"></a>

## The kernel HSI API


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

channel resource used by the hsi clients

**Definition**

```c
struct hsi_channel {
    unsigned int    id;
    const char      *name;
};
```

**Members**

- `id`: Channel number
- `name`: Channel name

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

Configuration for RX/TX HSI modules

**Definition**

```c
struct hsi_config {
    unsigned int            mode;
    struct hsi_channel      *channels;
    unsigned int            num_channels;
    unsigned int            num_hw_channels;
    unsigned int            speed;
    union {
        unsigned int    flow;
        unsigned int    arb_mode;
    };
};
```

**Members**

- `mode`: Bit transmission mode (STREAM or FRAME)
- `channels`: Channel resources used by the client
- `num_channels`: Number of channel resources
- `num_hw_channels`: Number of channels the transceiver is configured for \[1..16\]
- `speed`: Max bit transmission speed (Kbit/s)
- `{unnamed_union}`: anonymous
- `flow`: RX flow type (SYNCHRONIZED or PIPELINE)
- `arb_mode`: Arbitration mode for TX frame (Round robin, priority)

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

HSI client board info

**Definition**

```c
struct hsi_board_info {
    const char              *name;
    unsigned int            hsi_id;
    unsigned int            port;
    struct hsi_config       tx_cfg;
    struct hsi_config       rx_cfg;
    void *platform_data;
    struct dev_archdata     *archdata;
};
```

**Members**

- `name`: Name for the HSI device
- `hsi_id`: HSI controller id where the client sits
- `port`: Port number in the controller where the client sits
- `tx_cfg`: HSI TX configuration
- `rx_cfg`: HSI RX configuration
- `platform_data`: Platform related data
- `archdata`: Architecture-dependent device data

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

HSI client attached to an HSI port

**Definition**

```c
struct hsi_client {
    struct device           device;
    struct hsi_config       tx_cfg;
    struct hsi_config       rx_cfg;
};
```

**Members**

- `device`: Driver model representation of the device
- `tx_cfg`: HSI TX configuration
- `rx_cfg`: HSI RX configuration

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

Driver associated to an HSI client

**Definition**

```c
struct hsi_client_driver {
    struct device_driver    driver;
};
```

**Members**

- `driver`: Driver model representation of the driver

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

HSI message descriptor

**Definition**

```c
struct hsi_msg {
    struct list_head        link;
    struct hsi_client       *cl;
    struct sg_table         sgt;
    void *context;
    void (*complete)(struct hsi_msg *msg);
    void (*destructor)(struct hsi_msg *msg);
    int status;
    unsigned int            actual_len;
    unsigned int            channel;
    unsigned int            ttype:1;
    unsigned int            break_frame:1;
};
```

**Members**

- `link`: Free to use by the current descriptor owner
- `cl`: HSI device client that issues the transfer
- `sgt`: Head of the scatterlist array
- `context`: Client context data associated to the transfer
- `complete`: Transfer completion callback
- `destructor`: Destructor to free resources when flushing
- `status`: Status of the transfer when completed
- `actual_len`: Actual length of data transferred on completion
- `channel`: Channel were to TX/RX the message
- `ttype`: Transfer type (TX if set, RX otherwise)
- `break_frame`: if true HSI will send/receive a break frame. Data buffers are
  ignored in the request.

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

HSI port device

**Definition**

```c
struct hsi_port {
    struct device                   device;
    struct hsi_config               tx_cfg;
    struct hsi_config               rx_cfg;
    unsigned int                    num;
    unsigned int                    shared:1;
    int claimed;
    struct mutex                    lock;
    int (*async)(struct hsi_msg *msg);
    int (*setup)(struct hsi_client *cl);
    int (*flush)(struct hsi_client *cl);
    int (*start_tx)(struct hsi_client *cl);
    int (*stop_tx)(struct hsi_client *cl);
    int (*release)(struct hsi_client *cl);
    struct blocking_notifier_head   n_head;
};
```

**Members**

- `device`: Driver model representation of the device
- `tx_cfg`: Current TX path configuration
- `rx_cfg`: Current RX path configuration
- `num`: Port number
- `shared`: Set when port can be shared by different clients
- `claimed`: Reference count of clients which claimed the port
- `lock`: Serialize port claim
- `async`: Asynchronous transfer callback
- `setup`: Callback to set the HSI client configuration
- `flush`: Callback to clean the HW state and destroy all pending transfers
- `start_tx`: Callback to inform that a client wants to TX data
- `stop_tx`: Callback to inform that a client no longer wishes to TX data
- `release`: Callback to inform that a client no longer uses the port
- `n_head`: Notifier chain for signaling port events to the clients.

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

HSI controller device

**Definition**

```c
struct hsi_controller {
    struct device           device;
    struct module           *owner;
    unsigned int            id;
    unsigned int            num_ports;
    struct hsi_port         **port;
};
```

**Members**

- `device`: Driver model representation of the device
- `owner`: Pointer to the module owning the controller
- `id`: HSI controller ID
- `num_ports`: Number of ports in the HSI controller
- `port`: Array of HSI ports

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

```c
unsigned int hsi_id(struct hsi_client *cl)
```

Get HSI controller ID associated to a client

**Parameters**

- `struct hsi_client *cl`: Pointer to a HSI client

**Description**

Return the controller id where the client is attached to

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

```c
unsigned int hsi_port_id(struct hsi_client *cl)
```

Gets the port number a client is attached to

**Parameters**

- `struct hsi_client *cl`: Pointer to HSI client

**Description**

Return the port number associated to the client

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

```c
int hsi_setup(struct hsi_client *cl)
```

Configure the client's port

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client

**Description**

When sharing ports, clients should either relay on a single
client setup or have the same setup for all of them.

Return -errno on failure, 0 on success

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

```c
int hsi_flush(struct hsi_client *cl)
```

Flush all pending transactions on the client's port

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client

**Description**

This function will destroy all pending hsi_msg in the port and reset
the HW port so it is ready to receive and transmit from a clean state.

Return -errno on failure, 0 on success

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

```c
int hsi_async_read(struct hsi_client *cl, struct hsi_msg *msg)
```

Submit a read transfer

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client
- `struct hsi_msg *msg`: HSI message descriptor of the transfer

**Description**

Return -errno on failure, 0 on success

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

```c
int hsi_async_write(struct hsi_client *cl, struct hsi_msg *msg)
```

Submit a write transfer

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client
- `struct hsi_msg *msg`: HSI message descriptor of the transfer

**Description**

Return -errno on failure, 0 on success

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

```c
int hsi_start_tx(struct hsi_client *cl)
```

Signal the port that the client wants to start a TX

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client

**Description**

Return -errno on failure, 0 on success

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

```c
int hsi_stop_tx(struct hsi_client *cl)
```

Signal the port that the client no longer wants to transmit

**Parameters**

- `struct hsi_client *cl`: Pointer to the HSI client

**Description**

Return -errno on failure, 0 on success



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

```c
void hsi_port_unregister_clients(struct hsi_port *port)
```

Unregister an HSI port

**Parameters**

- `struct hsi_port *port`: The HSI port to unregister

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

```c
void hsi_unregister_controller(struct hsi_controller *hsi)
```

Unregister an HSI controller

**Parameters**

- `struct hsi_controller *hsi`: The HSI controller to register

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

```c
int hsi_register_controller(struct hsi_controller *hsi)
```

Register an HSI controller and its ports

**Parameters**

- `struct hsi_controller *hsi`: The HSI controller to register

**Description**

Returns -errno on failure, 0 on success.

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

```c
int hsi_register_client_driver(struct hsi_client_driver *drv)
```

Register an HSI client to the HSI bus

**Parameters**

- `struct hsi_client_driver *drv`: HSI client driver to register

**Description**

Returns -errno on failure, 0 on success.

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

```c
void hsi_put_controller(struct hsi_controller *hsi)
```

Free an HSI controller

**Parameters**

- `struct hsi_controller *hsi`: Pointer to the HSI controller to freed

**Description**

HSI controller drivers should only use this function if they need
to free their allocated hsi_controller structures before a successful
call to hsi_register_controller. Other use is not allowed.

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

```c
struct hsi_controller * hsi_alloc_controller(unsigned int n_ports, gfp_t flags)
```

Allocate an HSI controller and its ports

**Parameters**

- `unsigned int n_ports`: Number of ports on the HSI controller
- `gfp_t flags`: Kernel allocation flags

**Description**

Return NULL on failure or a pointer to an hsi_controller on success.

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

```c
void hsi_free_msg(struct hsi_msg *msg)
```

Free an HSI message

**Parameters**

- `struct hsi_msg *msg`: Pointer to the HSI message

**Description**

Client is responsible to free the buffers pointed by the scatterlists.

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

```c
struct hsi_msg * hsi_alloc_msg(unsigned int nents, gfp_t flags)
```

Allocate an HSI message

**Parameters**

- `unsigned int nents`: Number of memory entries
- `gfp_t flags`: Kernel allocation flags

**Description**

nents can be 0. This mainly makes sense for read transfer.
In that case, HSI drivers will call the complete callback when
there is data to be read without consuming it.

Return NULL on failure or a pointer to an hsi_msg on success.

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

```c
int hsi_async(struct hsi_client *cl, struct hsi_msg *msg)
```

Submit an HSI transfer to the controller

**Parameters**

- `struct hsi_client *cl`: HSI client sending the transfer
- `struct hsi_msg *msg`: The HSI transfer passed to controller

**Description**

The HSI message must have the channel, ttype, complete and destructor
fields set beforehand. If nents > 0 then the client has to initialize
also the scatterlists to point to the buffers to write to or read from.

HSI controllers relay on pre-allocated buffers from their clients and they
do not allocate buffers on their own.

Once the HSI message transfer finishes, the HSI controller calls the
complete callback with the status and actual_len fields of the HSI message
updated. The complete callback can be called before returning from
hsi_async.

Returns -errno on failure or 0 on success

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

```c
int hsi_claim_port(struct hsi_client *cl, unsigned int share)
```

Claim the HSI client's port

**Parameters**

- `struct hsi_client *cl`: HSI client that wants to claim its port
- `unsigned int share`: Flag to indicate if the client wants to share the port or not.

**Description**

Returns -errno on failure, 0 on success.

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

```c
void hsi_release_port(struct hsi_client *cl)
```

Release the HSI client's port

**Parameters**

- `struct hsi_client *cl`: HSI client which previously claimed its port

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

```c
int hsi_register_port_event(struct hsi_client *cl, void (*handler)(struct hsi_client *, unsigned long))
```

Register a client to receive port events

**Parameters**

- `struct hsi_client *cl`: HSI client that wants to receive port events
- `void (*handler)(struct hsi_client *, unsigned long)`: Event handler callback

**Description**

Clients should register a callback to be able to receive
events from the ports. Registration should happen after
claiming the port.
The handler can be called in interrupt context.

Returns -errno on error, or 0 on success.

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

```c
int hsi_unregister_port_event(struct hsi_client *cl)
```

Stop receiving port events for a client

**Parameters**

- `struct hsi_client *cl`: HSI client that wants to stop receiving port events

**Description**

Clients should call this function before releasing their associated
port.

Returns -errno on error, or 0 on success.

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

```c
int hsi_event(struct hsi_port *port, unsigned long event)
```

Notifies clients about port events

**Parameters**

- `struct hsi_port *port`: Port where the event occurred
- `unsigned long event`: The event type

**Description**

Clients should not be concerned about wake line behavior. However, due
to a race condition in HSI HW protocol, clients need to be notified
about wake line changes, so they can implement a workaround for it.

Events:
HSI_EVENT_START_RX - Incoming wake line high
HSI_EVENT_STOP_RX - Incoming wake line down

Returns -errno on error, or 0 on success.

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

```c
int hsi_get_channel_id_by_name(struct hsi_client *cl, char *name)
```

acquire channel id by channel name

**Parameters**

- `struct hsi_client *cl`: HSI client, which uses the channel
- `char *name`: name the channel is known under

**Description**

Clients can call this function to get the hsi channel ids similar to
requesting IRQs or GPIOs by name. This function assumes the same
channel configuration is used for RX and TX.

Returns -errno on error or channel id on success.

---

# I2C and SMBus Subsystem

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> I2C (or without fancy typography, "I2C") is an acronym for the "Inter-IC" bus, a simple bus protocol which is widely used where low data rate communications suffice. Since it's also a licensed trademark, some vendors use another name (such…

<a id="rst-i2c-and-smbus-subsystem"></a>

I<sup>2</sup>C (or without fancy typography, "I2C") is an acronym for the "Inter-IC" bus, a simple bus protocol which is widely used where low data rate communications suffice. Since it's also a licensed trademark, some vendors use another name (such as "Two-Wire Interface", TWI) for the same bus. I2C only needs two signals (SCL for clock, SDA for data), conserving board real estate and minimizing signal quality issues. Most I2C devices use seven bit addresses, and bus speeds of up to 400 kHz; there's a high speed extension (3.4 MHz) that's not yet found wide use. I2C is a multi-master bus; open drain signaling is used to arbitrate between masters, as well as to handshake and to synchronize clocks from slower clients.

The Linux I2C programming interfaces support the master side of bus interactions and the slave side. The programming interface is structured around two kinds of driver, and two kinds of device. An I2C "Adapter Driver" abstracts the controller hardware; it binds to a physical device (perhaps a PCI device or platform_device) and exposes a `struct i2c_adapter <i2c_adapter>` representing each I2C bus segment it manages. On each I2C bus segment will be I2C devices represented by a `struct i2c_client <i2c_client>`. Those devices will be bound to a `struct i2c_driver <i2c_driver>`, which should follow the standard Linux driver model. There are functions to perform various I2C protocol operations; at this writing all such functions are usable only from task context.

The System Management Bus (SMBus) is a sibling protocol. Most SMBus systems are also I2C conformant. The electrical constraints are tighter for SMBus, and it standardizes particular protocol messages and idioms. Controllers that support I2C can also support most SMBus operations, but SMBus controllers don't support all the protocol options that an I2C controller will. There are functions to perform various SMBus protocol operations, either using I2C primitives or by issuing SMBus commands to i2c_adapter devices which don't support those I2C operations.


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

```c
int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
```

issue a single I2C message in master receive mode

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `char *buf`: Where to store data read from slave
- `int count`: How many bytes to read, must be less than 64k since msg.len is u16

**Description**

Returns negative errno, or else the number of bytes read.

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

```c
int i2c_master_recv_dmasafe(const struct i2c_client *client, char *buf, int count)
```

issue a single I2C message in master receive mode using a DMA safe buffer

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `char *buf`: Where to store data read from slave, must be safe to use with DMA
- `int count`: How many bytes to read, must be less than 64k since msg.len is u16

**Description**

Returns negative errno, or else the number of bytes read.

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

```c
int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
```

issue a single I2C message in master transmit mode

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `const char *buf`: Data that will be written to the slave
- `int count`: How many bytes to write, must be less than 64k since msg.len is u16

**Description**

Returns negative errno, or else the number of bytes written.

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

```c
int i2c_master_send_dmasafe(const struct i2c_client *client, const char *buf, int count)
```

issue a single I2C message in master transmit mode using a DMA safe buffer

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `const char *buf`: Data that will be written to the slave, must be safe to use with DMA
- `int count`: How many bytes to write, must be less than 64k since msg.len is u16

**Description**

Returns negative errno, or else the number of bytes written.

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

i2c client device identification

**Definition**

```c
struct i2c_device_identity {
        u16 manufacturer_id;
    #define I2C_DEVICE_ID_NXP_SEMICONDUCTORS                0;
    #define I2C_DEVICE_ID_NXP_SEMICONDUCTORS_1              1;
    #define I2C_DEVICE_ID_NXP_SEMICONDUCTORS_2              2;
    #define I2C_DEVICE_ID_NXP_SEMICONDUCTORS_3              3;
    #define I2C_DEVICE_ID_RAMTRON_INTERNATIONAL             4;
    #define I2C_DEVICE_ID_ANALOG_DEVICES                    5;
    #define I2C_DEVICE_ID_STMICROELECTRONICS                6;
    #define I2C_DEVICE_ID_ON_SEMICONDUCTOR                  7;
    #define I2C_DEVICE_ID_SPRINTEK_CORPORATION              8;
    #define I2C_DEVICE_ID_ESPROS_PHOTONICS_AG               9;
    #define I2C_DEVICE_ID_FUJITSU_SEMICONDUCTOR            10;
    #define I2C_DEVICE_ID_FLIR                             11;
    #define I2C_DEVICE_ID_O2MICRO                          12;
    #define I2C_DEVICE_ID_ATMEL                            13;
    #define I2C_DEVICE_ID_NONE                         0xffff;
        u16 part_id;
        u8 die_revision;
};
```

**Members**

- `manufacturer_id`: 0 - 4095, database maintained by NXP
- `part_id`: 0 - 511, according to manufacturer
- `die_revision`: 0 - 7, according to manufacturer

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

Flags for an I2C device driver

**Constants**

- `I2C_DRV_ACPI_WAIVE_D0_PROBE`: Don't put the device in D0 state for probe

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

represent an I2C device driver

**Definition**

```c
struct i2c_driver {
    unsigned int class;
    int (*probe)(struct i2c_client *client);
    void (*remove)(struct i2c_client *client);
    void (*shutdown)(struct i2c_client *client);
    void (*alert)(struct i2c_client *client, enum i2c_alert_protocol protocol, unsigned int data);
    int (*command)(struct i2c_client *client, unsigned int cmd, void *arg);
    struct device_driver driver;
    const struct i2c_device_id *id_table;
    int (*detect)(struct i2c_client *client, struct i2c_board_info *info);
    const unsigned short *address_list;
    struct list_head clients;
    u32 flags;
};
```

**Members**

- `class`: What kind of i2c device we instantiate (for detect)
- `probe`: Callback for device binding
- `remove`: Callback for device unbinding
- `shutdown`: Callback for device shutdown
- `alert`: Alert callback, for example for the SMBus alert protocol
- `command`: Callback for bus-wide signaling (optional)
- `driver`: Device driver model driver
- `id_table`: List of I2C devices supported by this driver
- `detect`: Callback for device detection
- `address_list`: The I2C addresses to probe (for detect)
- `clients`: List of detected clients we created (for i2c-core use only)
- `flags`: A bitmask of flags defined in [`enum i2c_driver_flags`](#c-enum-i2c_driver_flags)

**Description**

The driver.owner field should be set to the module owner of this driver.
The driver.name field should be set to the name of this driver.

For automatic device detection, both **detect** and **address_list** must
be defined. **class** should also be set, otherwise only devices forced
with module parameters will be created. The detect function must
fill at least the name field of the i2c_board_info structure it is
handed upon successful detection, and possibly also the flags field.

If **detect** is missing, the driver will still work fine for enumerated
devices. Detected devices simply won't be supported. This is expected
for the many I2C/SMBus devices which can't be detected reliably, and
the ones which can always be enumerated in practice.

The i2c_client structure which is handed to the **detect** callback is
not a real i2c_client. It is initialized just enough so that you can
call i2c_smbus_read_byte_data and friends on it. Don't do anything
else with it. In particular, calling dev_dbg and friends on it is
not allowed.

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

represent an I2C slave device

**Definition**

```c
struct i2c_client {
        unsigned short flags;
    #define I2C_CLIENT_PEC          0x04;
    #define I2C_CLIENT_TEN          0x10;
    #define I2C_CLIENT_SLAVE        0x20;
    #define I2C_CLIENT_HOST_NOTIFY  0x40;
    #define I2C_CLIENT_WAKE         0x80;
    #define I2C_CLIENT_SCCB         0x9000;
        unsigned short addr;
        char name[I2C_NAME_SIZE];
        struct i2c_adapter *adapter;
        struct device dev;
        int init_irq;
        int irq;
        struct list_head detected;
    #if IS_ENABLED(CONFIG_I2C_SLAVE);
        i2c_slave_cb_t slave_cb;
    #endif;
        void *devres_group_id;
        struct dentry *debugfs;
};
```

**Members**

- `flags`: see I2C_CLIENT_* for possible flags
- `addr`: Address used on the I2C bus connected to the parent adapter.
- `name`: Indicates the type of the device, usually a chip name that's
  generic enough to hide second-sourcing and compatible revisions.
- `adapter`: manages the bus segment hosting this I2C device
- `dev`: Driver model device node for the slave.
- `init_irq`: IRQ that was set at initialization
- `irq`: indicates the IRQ generated by this device (if any)
- `detected`: member of an i2c_driver.clients list or i2c-core's
  userspace_devices list
- `slave_cb`: Callback when I2C slave mode of an adapter is used. The adapter
  calls it to pass on slave events to the slave driver.
- `devres_group_id`: id of the devres group that will be created for resources
  acquired when probing this device.
- `debugfs`: pointer to the debugfs subdirectory which the I2C core created
  for this client.

**Description**

An i2c_client identifies a single device (i.e. chip) connected to an
i2c bus. The behaviour exposed to Linux is defined by the driver
managing the device.

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

template for device creation

**Definition**

```c
struct i2c_board_info {
    char type[I2C_NAME_SIZE];
    unsigned short  flags;
    unsigned short  addr;
    const char      *dev_name;
    void *platform_data;
    struct fwnode_handle *fwnode;
    const struct software_node *swnode;
    const struct resource *resources;
    unsigned int    num_resources;
    int irq;
};
```

**Members**

- `type`: chip type, to initialize i2c_client.name
- `flags`: to initialize i2c_client.flags
- `addr`: stored in i2c_client.addr
- `dev_name`: Overrides the default \<busnr>-\<addr> dev_name if set
- `platform_data`: stored in i2c_client.dev.platform_data
- `fwnode`: device node supplied by the platform firmware
- `swnode`: software node for the device
- `resources`: resources associated with the device
- `num_resources`: number of resources in the **resources** array
- `irq`: stored in i2c_client.irq

**Description**

I2C doesn't actually support hardware probing, although controllers and
devices may be able to use I2C_SMBUS_QUICK to tell whether or not there's
a device at a given address.  Drivers commonly need more information than
that, such as chip type, configuration, associated IRQ, and so on.

i2c_board_info is used to build tables of information listing I2C devices
that are present.  This information is used to grow the driver model tree.
For mainboards this is done statically using [`i2c_register_board_info()`](#c-i2c_register_board_info);
bus numbers identify adapters that aren't yet available.  For add-on boards,
[`i2c_new_client_device()`](#c-i2c_new_client_device) does this dynamically with the adapter already known.

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

```c
I2C_BOARD_INFO(dev_type, dev_addr)
```

macro used to list an i2c device and its address

**Parameters**

- `dev_type`: identifies the device type
- `dev_addr`: the device's address on the bus.

**Description**

This macro initializes essential fields of a struct i2c_board_info,
declaring what has been provided on a particular board.  Optional
fields (such as associated irq, or device-specific platform_data)
are provided using conventional syntax.

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

represent I2C transfer methods

**Definition**

```c
struct i2c_algorithm {
        union {
            int (*xfer)(struct i2c_adapter *adap, struct i2c_msg *msgs, int num);
            int (*master_xfer)(struct i2c_adapter *adap, struct i2c_msg *msgs, int num);
        };
        union {
            int (*xfer_atomic)(struct i2c_adapter *adap, struct i2c_msg *msgs, int num);
            int (*master_xfer_atomic)(struct i2c_adapter *adap, struct i2c_msg *msgs, int num);
        };
        int (*smbus_xfer)(struct i2c_adapter *adap, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data);
        int (*smbus_xfer_atomic)(struct i2c_adapter *adap, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data);
        u32 (*functionality)(struct i2c_adapter *adap);
    #if IS_ENABLED(CONFIG_I2C_SLAVE);
        union {
            int (*reg_target)(struct i2c_client *client);
            int (*reg_slave)(struct i2c_client *client);
        };
        union {
            int (*unreg_target)(struct i2c_client *client);
            int (*unreg_slave)(struct i2c_client *client);
        };
    #endif;
};
```

**Members**

- `{unnamed_union}`: anonymous
- `xfer`: Transfer a given number of messages defined by the msgs array via
  the specified adapter.
- `master_xfer`: deprecated, use **xfer**
- `{unnamed_union}`: anonymous
- `xfer_atomic`: Same as **xfer**. Yet, only using atomic context so e.g. PMICs
  can be accessed very late before shutdown. Optional.
- `master_xfer_atomic`: deprecated, use **xfer_atomic**
- `smbus_xfer`: Issue SMBus transactions to the given I2C adapter. If this
  is not present, then the bus layer will try and convert the SMBus calls
  into I2C transfers instead.
- `smbus_xfer_atomic`: Same as **smbus_xfer**. Yet, only using atomic context
  so e.g. PMICs can be accessed very late before shutdown. Optional.
- `functionality`: Return the flags that this algorithm/adapter pair supports
  from the `I2C_FUNC_*` flags.
- `{unnamed_union}`: anonymous
- `reg_target`: Register given client to local target mode of this adapter
- `reg_slave`: deprecated, use **reg_target**
- `{unnamed_union}`: anonymous
- `unreg_target`: Unregister given client from local target mode of this adapter
- `unreg_slave`: deprecated, use **unreg_target**

**Description**

i2c_algorithm is the interface to a class of hardware solutions which can
be addressed using the same bus algorithms - i.e. bit-banging or the PCF8584
to name two of the most common.

The return codes from the `xfer{_atomic}` fields should indicate the
type of error code that occurred during the transfer, as documented in the
Kernel Documentation file Documentation/i2c/fault-codes.rst. Otherwise, the
number of messages executed should be returned.

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

represent I2C locking operations

**Definition**

```c
struct i2c_lock_operations {
    void (*lock_bus)(struct i2c_adapter *adapter, unsigned int flags);
    int (*trylock_bus)(struct i2c_adapter *adapter, unsigned int flags);
    void (*unlock_bus)(struct i2c_adapter *adapter, unsigned int flags);
};
```

**Members**

- `lock_bus`: Get exclusive access to an I2C bus segment
- `trylock_bus`: Try to get exclusive access to an I2C bus segment
- `unlock_bus`: Release exclusive access to an I2C bus segment

**Description**

The main operations are wrapped by i2c_lock_bus and i2c_unlock_bus.

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

I2C timing information

**Definition**

```c
struct i2c_timings {
    u32 bus_freq_hz;
    u32 scl_rise_ns;
    u32 scl_fall_ns;
    u32 scl_int_delay_ns;
    u32 sda_fall_ns;
    u32 sda_hold_ns;
    u32 digital_filter_width_ns;
    u32 analog_filter_cutoff_freq_hz;
};
```

**Members**

- `bus_freq_hz`: the bus frequency in Hz
- `scl_rise_ns`: time SCL signal takes to rise in ns; t(r) in the I2C specification
- `scl_fall_ns`: time SCL signal takes to fall in ns; t(f) in the I2C specification
- `scl_int_delay_ns`: time IP core additionally needs to setup SCL in ns
- `sda_fall_ns`: time SDA signal takes to fall in ns; t(f) in the I2C specification
- `sda_hold_ns`: time IP core additionally needs to hold SDA in ns
- `digital_filter_width_ns`: width in ns of spikes on i2c lines that the IP core
  digital filter can filter out
- `analog_filter_cutoff_freq_hz`: threshold frequency for the low pass IP core
  analog filter

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

I2C bus recovery information

**Definition**

```c
struct i2c_bus_recovery_info {
    int (*recover_bus)(struct i2c_adapter *adap);
    int (*get_scl)(struct i2c_adapter *adap);
    void (*set_scl)(struct i2c_adapter *adap, int val);
    int (*get_sda)(struct i2c_adapter *adap);
    void (*set_sda)(struct i2c_adapter *adap, int val);
    int (*get_bus_free)(struct i2c_adapter *adap);
    void (*prepare_recovery)(struct i2c_adapter *adap);
    void (*unprepare_recovery)(struct i2c_adapter *adap);
    struct gpio_desc *scl_gpiod;
    struct gpio_desc *sda_gpiod;
    struct pinctrl *pinctrl;
    struct pinctrl_state *pins_default;
    struct pinctrl_state *pins_gpio;
};
```

**Members**

- `recover_bus`: Recover routine. Either pass driver's `recover_bus()` routine, or
  `i2c_generic_scl_recovery()`.
- `get_scl`: This gets current value of SCL line. Mandatory for generic SCL
  recovery. Populated internally for generic GPIO recovery.
- `set_scl`: This sets/clears the SCL line. Mandatory for generic SCL recovery.
  Populated internally for generic GPIO recovery.
- `get_sda`: This gets current value of SDA line. This or `set_sda()` is mandatory
  for generic SCL recovery. Populated internally, if sda_gpio is a valid
  GPIO, for generic GPIO recovery.
- `set_sda`: This sets/clears the SDA line. This or `get_sda()` is mandatory for
  generic SCL recovery. Populated internally, if sda_gpio is a valid GPIO,
  for generic GPIO recovery.
- `get_bus_free`: Returns the bus free state as seen from the IP core in case it
  has a more complex internal logic than just reading SDA. Optional.
- `prepare_recovery`: This will be called before starting recovery. Platform may
  configure padmux here for SDA/SCL line or something else they want.
- `unprepare_recovery`: This will be called after completing recovery. Platform
  may configure padmux here for SDA/SCL line or something else they want.
- `scl_gpiod`: gpiod of the SCL line. Only required for GPIO recovery.
- `sda_gpiod`: gpiod of the SDA line. Only required for GPIO recovery.
- `pinctrl`: pinctrl used by GPIO recovery to change the state of the I2C pins.
  Optional.
- `pins_default`: default pinctrl state of SCL/SDA lines, when they are assigned
  to the I2C bus. Optional. Populated internally for GPIO recovery, if
  state with the name PINCTRL_STATE_DEFAULT is found and pinctrl is valid.
- `pins_gpio`: recovery pinctrl state of SCL/SDA lines, when they are used as
  GPIOs. Optional. Populated internally for GPIO recovery, if this state
  is called "gpio" or "recovery" and pinctrl is valid.

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

describe flaws of an i2c adapter

**Definition**

```c
struct i2c_adapter_quirks {
    u64 flags;
    int max_num_msgs;
    u16 max_write_len;
    u16 max_read_len;
    u16 max_comb_1st_msg_len;
    u16 max_comb_2nd_msg_len;
};
```

**Members**

- `flags`: see I2C_AQ_* for possible flags and read below
- `max_num_msgs`: maximum number of messages per transfer
- `max_write_len`: maximum length of a write message
- `max_read_len`: maximum length of a read message
- `max_comb_1st_msg_len`: maximum length of the first msg in a combined message
- `max_comb_2nd_msg_len`: maximum length of the second msg in a combined message

**Description**

Note about combined messages: Some I2C controllers can only send one message
per transfer, plus something called combined message or write-then-read.
This is (usually) a small write message followed by a read message and
barely enough to access register based devices like EEPROMs. There is a flag
to support this mode. It implies max_num_msg = 2 and does the length checks
with max_comb_*_len because combined message mode usually has its own
limitations. Because of HW implementations, some controllers can actually do
write-then-anything or other variants. To support that, write-then-read has
been broken out into smaller bits like write-first and read-second which can
be combined as needed.

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

```c
void i2c_lock_bus(struct i2c_adapter *adapter, unsigned int flags)
```

Get exclusive access to an I2C bus segment

**Parameters**

- `struct i2c_adapter *adapter`: Target I2C bus segment
- `unsigned int flags`: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
  locks only this branch in the adapter tree

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

```c
int i2c_trylock_bus(struct i2c_adapter *adapter, unsigned int flags)
```

Try to get exclusive access to an I2C bus segment

**Parameters**

- `struct i2c_adapter *adapter`: Target I2C bus segment
- `unsigned int flags`: I2C_LOCK_ROOT_ADAPTER tries to locks the root i2c adapter,
  I2C_LOCK_SEGMENT tries to lock only this branch in the adapter tree

**Return**

true if the I2C bus segment is locked, false otherwise

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

```c
void i2c_unlock_bus(struct i2c_adapter *adapter, unsigned int flags)
```

Release exclusive access to an I2C bus segment

**Parameters**

- `struct i2c_adapter *adapter`: Target I2C bus segment
- `unsigned int flags`: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
  unlocks only this branch in the adapter tree

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

```c
void i2c_mark_adapter_suspended(struct i2c_adapter *adap)
```

Report suspended state of the adapter to the core

**Parameters**

- `struct i2c_adapter *adap`: Adapter to mark as suspended

**Description**

When using this helper to mark an adapter as suspended, the core will reject
further transfers to this adapter. The usage of this helper is optional but
recommended for devices having distinct handlers for system suspend and
runtime suspend. More complex devices are free to implement custom solutions
to reject transfers when suspended.

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

```c
void i2c_mark_adapter_resumed(struct i2c_adapter *adap)
```

Report resumed state of the adapter to the core

**Parameters**

- `struct i2c_adapter *adap`: Adapter to mark as resumed

**Description**

When using this helper to mark an adapter as resumed, the core will allow
further transfers to this adapter. See also further notes to
**i2c_mark_adapter_suspended()**.

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

```c
bool i2c_check_quirks(struct i2c_adapter *adap, u64 quirks)
```

Function for checking the quirk flags in an i2c adapter

**Parameters**

- `struct i2c_adapter *adap`: i2c adapter
- `u64 quirks`: quirk flags

**Return**

true if the adapter has all the specified quirk flags, false if not

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

```c
module_i2c_driver(__i2c_driver)
```

Helper macro for registering a modular I2C driver

**Parameters**

- `__i2c_driver`: i2c_driver struct

**Description**

Helper macro for I2C drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)

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

```c
builtin_i2c_driver(__i2c_driver)
```

Helper macro for registering a builtin I2C driver

**Parameters**

- `__i2c_driver`: i2c_driver struct

**Description**

Helper macro for I2C drivers which do not do anything special in their
init. This eliminates a lot of boilerplate. Each driver may only
use this macro once, and calling it replaces `device_initcall()`.



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

```c
int i2c_register_board_info(int busnum, struct i2c_board_info const *info, unsigned len)
```

statically declare I2C devices

**Parameters**

- `int busnum`: identifies the bus to which these devices belong
- `struct i2c_board_info const *info`: vector of i2c device descriptors
- `unsigned len`: how many descriptors in the vector; may be zero to reserve
  the specified bus number.

**Description**

Systems using the Linux I2C driver stack can declare tables of board info
while they initialize.  This should be done in board-specific init code
near `arch_initcall()` time, or equivalent, before any I2C adapter driver is
registered.  For example, mainboard init code could define several devices,
as could the init code for each daughtercard in a board stack.

The I2C devices will be created later, after the adapter for the relevant
bus has been registered.  After that moment, standard driver model tools
are used to bind "new style" I2C drivers to the devices.  The bus number
for any device declared using this routine is not available for dynamic
allocation.

The board info passed can safely be __initdata, but be careful of embedded
pointers (for platform_data, functions, etc) since that won't be copied.



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

```c
struct i2c_client * i2c_verify_client(struct device *dev)
```

return parameter as i2c_client, or NULL

**Parameters**

- `struct device *dev`: device, probably from some driver model iterator

**Description**

When traversing the driver model tree, perhaps using driver model
iterators like **device_for_each_child()**, you can't assume very much
about the nodes you find.  Use this function to avoid oopses caused
by wrongly treating some non-I2C device as an i2c_client.

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

```c
struct i2c_client * i2c_new_client_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
```

instantiate an i2c device

**Parameters**

- `struct i2c_adapter *adap`: the adapter managing the device
- `struct i2c_board_info const *info`: describes one I2C device; bus_num is ignored

**Context**

can sleep

**Description**

Create an i2c device. Binding is handled through driver model
`probe()`/`remove()` methods.  A driver may be bound to this device when we
return from this function, or any later moment (e.g. maybe hotplugging will
load the driver module).  This call is not appropriate for use by mainboard
initialization logic, which usually runs during an `arch_initcall()` long
before any i2c_adapter could exist.

This returns the new i2c client, which may be saved for later use with
[`i2c_unregister_device()`](#c-i2c_unregister_device); or an ERR_PTR to describe the error.

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

```c
void i2c_unregister_device(struct i2c_client *client)
```

reverse effect of i2c_new_*`_device()`

**Parameters**

- `struct i2c_client *client`: value returned from i2c_new_*`_device()`

**Context**

can sleep

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

```c
struct i2c_client * i2c_find_device_by_fwnode(struct fwnode_handle *fwnode)
```

find an i2c_client for the fwnode

**Parameters**

- `struct fwnode_handle *fwnode`: `struct fwnode_handle` corresponding to the [`struct i2c_client`](#c-struct-i2c_client)

**Description**

Look up and return the [`struct i2c_client`](#c-struct-i2c_client) corresponding to the **fwnode**.
If no client can be found, or **fwnode** is NULL, this returns NULL.

The user must call put_device(`client->dev`) once done with the i2c client.

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

```c
struct i2c_client * i2c_new_dummy_device(struct i2c_adapter *adapter, u16 address)
```

return a new i2c device bound to a dummy driver

**Parameters**

- `struct i2c_adapter *adapter`: the adapter managing the device
- `u16 address`: seven bit address to be used

**Context**

can sleep

**Description**

This returns an I2C client bound to the "dummy" driver, intended for use
with devices that consume multiple addresses.  Examples of such chips
include various EEPROMS (like 24c04 and 24c08 models).

These dummy devices have two main uses.  First, most I2C and SMBus calls
except [`i2c_transfer()`](#c-i2c_transfer) need a client handle; the dummy will be that handle.
And second, this prevents the specified address from being bound to a
different driver.

This returns the new i2c client, which should be saved for later use with
[`i2c_unregister_device()`](#c-i2c_unregister_device); or an ERR_PTR to describe the error.

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

```c
struct i2c_client * devm_i2c_new_dummy_device(struct device *dev, struct i2c_adapter *adapter, u16 address)
```

return a new i2c device bound to a dummy driver

**Parameters**

- `struct device *dev`: device the managed resource is bound to
- `struct i2c_adapter *adapter`: the adapter managing the device
- `u16 address`: seven bit address to be used

**Context**

can sleep

**Description**

This is the device-managed version of **i2c_new_dummy_device**. It returns the
new i2c client or an ERR_PTR in case of an error.

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

```c
struct i2c_client * i2c_new_ancillary_device(struct i2c_client *client, const char *name, u16 default_addr)
```

Helper to get the instantiated secondary address and create the associated device

**Parameters**

- `struct i2c_client *client`: Handle to the primary client
- `const char *name`: Handle to specify which secondary address to get
- `u16 default_addr`: Used as a fallback if no secondary address was specified

**Context**

can sleep

**Description**

I2C clients can be composed of multiple I2C slaves bound together in a single
component. The I2C client driver then binds to the master I2C slave and needs
to create I2C dummy clients to communicate with all the other slaves.

This function creates and returns an I2C dummy client whose I2C address is
retrieved from the platform firmware based on the given slave name. If no
address is specified by the firmware default_addr is used.

On DT-based platforms the address is retrieved from the "reg" property entry
cell whose "reg-names" value matches the slave name.

This returns the new i2c client, which should be saved for later use with
[`i2c_unregister_device()`](#c-i2c_unregister_device); or an ERR_PTR to describe the error.

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

```c
struct i2c_adapter * i2c_verify_adapter(struct device *dev)
```

return parameter as i2c_adapter or NULL

**Parameters**

- `struct device *dev`: device, probably from some driver model iterator

**Description**

When traversing the driver model tree, perhaps using driver model
iterators like **device_for_each_child()**, you can't assume very much
about the nodes you find.  Use this function to avoid oopses caused
by wrongly treating some non-I2C device as an i2c_adapter.

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

```c
int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
```

Forward a Host Notify event to the correct I2C client.

**Parameters**

- `struct i2c_adapter *adap`: the adapter
- `unsigned short addr`: the I2C address of the notifying device

**Context**

can't sleep

**Description**

Helper function to be called from an I2C bus driver's interrupt
handler. It will schedule the Host Notify IRQ.

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

```c
int i2c_add_adapter(struct i2c_adapter *adapter)
```

declare i2c adapter, use dynamic bus number

**Parameters**

- `struct i2c_adapter *adapter`: the adapter to add

**Context**

can sleep

**Description**

This routine is used to declare an I2C adapter when its bus number
doesn't matter or when its bus number is specified by an dt alias.
Examples of bases when the bus number doesn't matter: I2C adapters
dynamically added by USB links or PCI plugin cards.

When this returns zero, a new bus number was allocated and stored
in adap->nr, and the specified adapter became available for clients.
Otherwise, a negative errno value is returned.

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

```c
int i2c_add_numbered_adapter(struct i2c_adapter *adap)
```

declare i2c adapter, use static bus number

**Parameters**

- `struct i2c_adapter *adap`: the adapter to register (with adap->nr initialized)

**Context**

can sleep

**Description**

This routine is used to declare an I2C adapter when its bus number
matters.  For example, use it for I2C adapters from system-on-chip CPUs,
or otherwise built in to the system's mainboard, and where i2c_board_info
is used to properly configure I2C devices.

If the requested bus number is set to -1, then this function will behave
identically to i2c_add_adapter, and will dynamically assign a bus number.

If no devices have pre-been declared for this bus, then be sure to
register the adapter before any dynamically allocated ones.  Otherwise
the required bus ID may not be available.

When this returns zero, the specified adapter became available for
clients using the bus number provided in adap->nr.  Also, the table
of I2C devices pre-declared using [`i2c_register_board_info()`](#c-i2c_register_board_info) is scanned,
and the appropriate driver model device nodes are created.  Otherwise, a
negative errno value is returned.

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

```c
void i2c_del_adapter(struct i2c_adapter *adap)
```

unregister I2C adapter

**Parameters**

- `struct i2c_adapter *adap`: the adapter being unregistered

**Context**

can sleep

**Description**

This unregisters an I2C adapter which was previously registered
by **i2c_add_adapter** or **i2c_add_numbered_adapter**.

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

```c
int devm_i2c_add_adapter(struct device *dev, struct i2c_adapter *adapter)
```

device-managed variant of [`i2c_add_adapter()`](#c-i2c_add_adapter)

**Parameters**

- `struct device *dev`: managing device for adding this I2C adapter
- `struct i2c_adapter *adapter`: the adapter to add

**Context**

can sleep

**Description**

Add adapter with dynamic bus number, same with [`i2c_add_adapter()`](#c-i2c_add_adapter)
but the adapter will be auto deleted on driver detach.

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

```c
struct i2c_adapter * i2c_find_adapter_by_fwnode(struct fwnode_handle *fwnode)
```

find an i2c_adapter for the fwnode

**Parameters**

- `struct fwnode_handle *fwnode`: `struct fwnode_handle` corresponding to the `struct i2c_adapter`

**Description**

Look up and return the `struct i2c_adapter` corresponding to the **fwnode**.
If no adapter can be found, or **fwnode** is NULL, this returns NULL.

The user must call put_device(`adapter->dev`) once done with the i2c adapter.

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

```c
struct i2c_adapter * i2c_get_adapter_by_fwnode(struct fwnode_handle *fwnode)
```

find an i2c_adapter for the fwnode

**Parameters**

- `struct fwnode_handle *fwnode`: `struct fwnode_handle` corresponding to the `struct i2c_adapter`

**Description**

Look up and return the `struct i2c_adapter` corresponding to the **fwnode**,
and increment the adapter module's use count. If no adapter can be found,
or **fwnode** is NULL, this returns NULL.

The user must call i2c_put_adapter(adapter) once done with the i2c adapter.
Note that this is different from `i2c_find_adapter_by_node()`.

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

```c
void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
```

get I2C related timing parameters from firmware

**Parameters**

- `struct device *dev`: The device to scan for I2C timing properties
- `struct i2c_timings *t`: the i2c_timings struct to be filled with values
- `bool use_defaults`: bool to use sane defaults derived from the I2C specification
  when properties are not found, otherwise don't update

**Description**

Scan the device for the generic I2C properties describing timing parameters
for the signal and fill the given struct with the results. If a property was
not found and use_defaults was true, then maximum timings are assumed which
are derived from the I2C specification. If use_defaults is not used, the
results will be as before, so drivers can apply their own defaults before
calling this helper. The latter is mainly intended for avoiding regressions
of existing drivers which want to switch to this function. New drivers
almost always should use the defaults.

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

```c
void i2c_del_driver(struct i2c_driver *driver)
```

unregister I2C driver

**Parameters**

- `struct i2c_driver *driver`: the driver being unregistered

**Context**

can sleep

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

```c
int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
```

unlocked flavor of i2c_transfer

**Parameters**

- `struct i2c_adapter *adap`: Handle to I2C bus
- `struct i2c_msg *msgs`: One or more messages to execute before STOP is issued to
  terminate the operation; each message begins with a START.
- `int num`: Number of messages to be executed.

**Description**

Returns negative errno, else the number of messages executed.

Adapter lock must be held when calling this function. No debug logging
takes place.

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

```c
int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
```

execute a single or combined I2C message

**Parameters**

- `struct i2c_adapter *adap`: Handle to I2C bus
- `struct i2c_msg *msgs`: One or more messages to execute before STOP is issued to
  terminate the operation; each message begins with a START.
- `int num`: Number of messages to be executed.

**Description**

Returns negative errno, else the number of messages executed.

Note that there is no requirement that each message be sent to
the same slave address, although that is the most common model.

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

```c
int i2c_transfer_buffer_flags(const struct i2c_client *client, char *buf, int count, u16 flags)
```

issue a single I2C message transferring data to/from a buffer

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `char *buf`: Where the data is stored
- `int count`: How many bytes to transfer, must be less than 64k since msg.len is u16
- `u16 flags`: The flags to be used for the message, e.g. I2C_M_RD for reads

**Description**

Returns negative errno, or else the number of bytes transferred.

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

```c
int i2c_get_device_id(const struct i2c_client *client, struct i2c_device_identity *id)
```

get manufacturer, part id and die revision of a device

**Parameters**

- `const struct i2c_client *client`: The device to query
- `struct i2c_device_identity *id`: The queried information

**Description**

Returns negative errno on error, zero on success.

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

```c
const struct i2c_device_id * i2c_client_get_device_id(const struct i2c_client *client)
```

get the driver match table entry of a device

**Parameters**

- `const struct i2c_client *client`: the device to query. The device must be bound to a driver

**Description**

Returns a pointer to the matching entry if found, NULL otherwise.

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

```c
u8 * i2c_get_dma_safe_msg_buf(struct i2c_msg *msg, unsigned int threshold)
```

get a DMA safe buffer for the given i2c_msg

**Parameters**

- `struct i2c_msg *msg`: the message to be checked
- `unsigned int threshold`: the minimum number of bytes for which using DMA makes sense.
  Should at least be 1.

**Return**

NULL if a DMA safe buffer was not obtained. Use msg->buf with PIO.
Or a valid pointer to be used with DMA. After use, release it by
calling [`i2c_put_dma_safe_msg_buf()`](#c-i2c_put_dma_safe_msg_buf).

**Description**

This function must only be called from process context!

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

```c
void i2c_put_dma_safe_msg_buf(u8 *buf, struct i2c_msg *msg, bool xferred)
```

release DMA safe buffer and sync with i2c_msg

**Parameters**

- `u8 *buf`: the buffer obtained from [`i2c_get_dma_safe_msg_buf()`](#c-i2c_get_dma_safe_msg_buf). May be NULL.
- `struct i2c_msg *msg`: the message which the buffer corresponds to
- `bool xferred`: bool saying if the message was transferred



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

```c
u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
```

Incremental CRC8 over the given input data array

**Parameters**

- `u8 crc`: previous return crc8 value
- `u8 *p`: pointer to data buffer.
- `size_t count`: number of bytes in data buffer.

**Description**

Incremental CRC8 over count bytes in the array pointed to by p

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

```c
s32 i2c_smbus_read_byte(const struct i2c_client *client)
```

SMBus "receive byte" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device

**Description**

This executes the SMBus "receive byte" protocol, returning negative errno
else the byte received from the device.

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

```c
s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
```

SMBus "send byte" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 value`: Byte to be sent

**Description**

This executes the SMBus "send byte" protocol, returning negative errno
else zero on success.

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

```c
s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
```

SMBus "read byte" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave

**Description**

This executes the SMBus "read byte" protocol, returning negative errno
else a data byte received from the device.

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

```c
s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command, u8 value)
```

SMBus "write byte" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u8 value`: Byte being written

**Description**

This executes the SMBus "write byte" protocol, returning negative errno
else zero on success.

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

```c
s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
```

SMBus "read word" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave

**Description**

This executes the SMBus "read word" protocol, returning negative errno
else a 16-bit unsigned "word" received from the device.

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

```c
s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command, u16 value)
```

SMBus "write word" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u16 value`: 16-bit "word" being written

**Description**

This executes the SMBus "write word" protocol, returning negative errno
else zero on success.

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

```c
s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command, u8 *values)
```

SMBus "block read" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u8 *values`: Byte array into which data will be read; big enough to hold
  the data returned by the slave.  SMBus allows at most 32 bytes.

**Description**

This executes the SMBus "block read" protocol, returning negative errno
else the number of data bytes in the slave's response.

Note that using this function requires that the client's adapter support
the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality.  Not all adapter drivers
support this; its emulation through I2C messaging relies on a specific
mechanism (I2C_M_RECV_LEN) which may not be implemented.

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

```c
s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command, u8 length, const u8 *values)
```

SMBus "block write" protocol

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u8 length`: Size of data block; SMBus allows at most 32 bytes
- `const u8 *values`: Byte array which will be written.

**Description**

This executes the SMBus "block write" protocol, returning negative errno
else zero on success.

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

```c
s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags, char read_write, u8 command, int protocol, union i2c_smbus_data *data)
```

execute SMBus protocol operations

**Parameters**

- `struct i2c_adapter *adapter`: Handle to I2C bus
- `u16 addr`: Address of SMBus slave on that bus
- `unsigned short flags`: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
- `char read_write`: I2C_SMBUS_READ or I2C_SMBUS_WRITE
- `u8 command`: Byte interpreted by slave, for protocols which use such bytes
- `int protocol`: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
- `union i2c_smbus_data *data`: Data to be read or written

**Description**

This executes an SMBus protocol operation, and returns a negative
errno code else zero on success.

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

```c
s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client, u8 command, u8 length, u8 *values)
```

read block or emulate

**Parameters**

- `const struct i2c_client *client`: Handle to slave device
- `u8 command`: Byte interpreted by slave
- `u8 length`: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
- `u8 *values`: Byte array into which data will be read; big enough to hold
  the data returned by the slave.  SMBus allows at most
  I2C_SMBUS_BLOCK_MAX bytes.

**Description**

This executes the SMBus "block read" protocol if supported by the adapter.
If block read is not supported, it emulates it using either word or byte
read protocols depending on availability.

The addresses of the I2C slave device that are accessed with this function
must be mapped to a linear region, so that a block read will have the same
effect as a byte read. Before using this function you must double-check
if the I2C slave does support exchanging a block transfer with a byte
transfer.

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

```c
struct i2c_client * i2c_new_smbus_alert_device(struct i2c_adapter *adapter, struct i2c_smbus_alert_setup *setup)
```

get ara client for SMBus alert support

**Parameters**

- `struct i2c_adapter *adapter`: the target adapter
- `struct i2c_smbus_alert_setup *setup`: setup data for the SMBus alert handler

**Context**

can sleep

**Description**

Setup handling of the SMBus alert protocol on a given I2C bus segment.

Handling can be done either through our IRQ handler, or by the
adapter (from its handler, periodic polling, or whatever).

This returns the ara client, which should be saved for later use with
`i2c_handle_smbus_alert()` and ultimately [`i2c_unregister_device()`](#c-i2c_unregister_device); or an
ERRPTR to indicate an error.

---

# InfiniBand and Remote DMA (RDMA) Interfaces

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> TBD

<a id="rst-infiniband-and-remote-dma-rdma-interfaces"></a>

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

## Introduction and Overview

TBD

<a id="rst-infiniband-core-interfaces"></a>

## InfiniBand core interfaces


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

```c
struct iwpm_nlmsg_request * iwpm_get_nlmsg_request(__u32 nlmsg_seq, u8 nl_client, gfp_t gfp)
```

Allocate and initialize netlink message request

**Parameters**

- `__u32 nlmsg_seq`: Sequence number of the netlink message
- `u8 nl_client`: The index of the netlink client
- `gfp_t gfp`: Indicates how the memory for the request should be allocated

**Description**

Returns the newly allocated netlink request object if successful,
otherwise returns NULL

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

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

Deallocate netlink message request

**Parameters**

- `struct kref *kref`: Holds reference of netlink message request

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

```c
struct iwpm_nlmsg_request * iwpm_find_nlmsg_request(__u32 echo_seq)
```

Find netlink message request in the request list

**Parameters**

- `__u32 echo_seq`: Sequence number of the netlink request to find

**Description**

Returns the found netlink message request,
if not found, returns NULL

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

```c
int iwpm_wait_complete_req(struct iwpm_nlmsg_request *nlmsg_request)
```

Block while servicing the netlink request

**Parameters**

- `struct iwpm_nlmsg_request *nlmsg_request`: Netlink message request to service

**Description**

Wakes up, after the request is completed or expired
Returns 0 if the request is complete without error

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

```c
int iwpm_get_nlmsg_seq(void)
```

Get the sequence number for a netlink message to send to the port mapper

**Parameters**

- `void`: no arguments

**Description**

Returns the sequence number for the netlink message.

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

```c
void iwpm_add_remote_info(struct iwpm_remote_info *reminfo)
```

Add remote address info of the connecting peer to the remote info hash table

**Parameters**

- `struct iwpm_remote_info *reminfo`: The remote info to be added

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

```c
u32 iwpm_check_registration(u8 nl_client, u32 reg)
```

Check if the client registration matches the given one

**Parameters**

- `u8 nl_client`: The index of the netlink client
- `u32 reg`: The given registration type to compare with

**Description**

Call `iwpm_register_pid()` to register a client
Returns true if the client registration matches reg,
otherwise returns false

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

```c
void iwpm_set_registration(u8 nl_client, u32 reg)
```

Set the client registration

**Parameters**

- `u8 nl_client`: The index of the netlink client
- `u32 reg`: Registration type to set

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

```c
u32 iwpm_get_registration(u8 nl_client)
```

Get the client registration

**Parameters**

- `u8 nl_client`: The index of the netlink client

**Description**

Returns the client registration type

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

```c
int iwpm_send_mapinfo(u8 nl_client, int iwpm_pid)
```

Send local and mapped IPv4/IPv6 address info of a client to the user space port mapper

**Parameters**

- `u8 nl_client`: The index of the netlink client
- `int iwpm_pid`: The pid of the user space port mapper

**Description**

If successful, returns the number of sent mapping info records

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

```c
int iwpm_mapinfo_available(void)
```

Check if any mapping info records is available in the hash table

**Parameters**

- `void`: no arguments

**Description**

Returns 1 if mapping information is available, otherwise returns 0

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

```c
int iwpm_compare_sockaddr(struct sockaddr_storage *a_sockaddr, struct sockaddr_storage *b_sockaddr)
```

Compare two sockaddr storage structs

**Parameters**

- `struct sockaddr_storage *a_sockaddr`: first sockaddr to compare
- `struct sockaddr_storage *b_sockaddr`: second sockaddr to compare

**Return**

0 if they are holding the same ip/tcp address info,
otherwise returns 1

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

```c
int iwpm_validate_nlmsg_attr(struct nlattr *nltb[], int nla_count)
```

Check for NULL netlink attributes

**Parameters**

- `struct nlattr *nltb[]`: Holds address of each netlink message attributes
- `int nla_count`: Number of netlink message attributes

**Description**

Returns error if any of the nla_count attributes is NULL

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

```c
struct sk_buff * iwpm_create_nlmsg(u32 nl_op, struct nlmsghdr **nlh, int nl_client)
```

Allocate skb and form a netlink message

**Parameters**

- `u32 nl_op`: Netlink message opcode
- `struct nlmsghdr **nlh`: Holds address of the netlink message header in skb
- `int nl_client`: The index of the netlink client

**Description**

Returns the newly allcated skb, or NULL if the tailroom of the skb
is insufficient to store the message header and payload

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

```c
int iwpm_parse_nlmsg(struct netlink_callback *cb, int policy_max, const struct nla_policy *nlmsg_policy, struct nlattr *nltb[], const char *msg_type)
```

Validate and parse the received netlink message

**Parameters**

- `struct netlink_callback *cb`: Netlink callback structure
- `int policy_max`: Maximum attribute type to be expected
- `const struct nla_policy *nlmsg_policy`: Validation policy
- `struct nlattr *nltb[]`: Array to store policy_max parsed elements
- `const char *msg_type`: Type of netlink message

**Description**

Returns 0 on success or a negative error code

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

```c
void iwpm_print_sockaddr(struct sockaddr_storage *sockaddr, char *msg)
```

Print IPv4/IPv6 address and TCP port

**Parameters**

- `struct sockaddr_storage *sockaddr`: Socket address to print
- `char *msg`: Message to print

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

```c
int iwpm_send_hello(u8 nl_client, int iwpm_pid, u16 abi_version)
```

Send hello response to iwpmd

**Parameters**

- `u8 nl_client`: The index of the netlink client
- `int iwpm_pid`: The pid of the user space port mapper
- `u16 abi_version`: The kernel's abi_version

**Description**

Returns 0 on success or a negative error code



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

```c
int ib_process_cq_direct(struct ib_cq *cq, int budget)
```

process a CQ in caller context

**Parameters**

- `struct ib_cq *cq`: CQ to process
- `int budget`: number of CQEs to poll for

**Description**

This function is used to process all outstanding CQ entries.
It does not offload CQ processing to a different context and does
not ask for completion interrupts from the HCA.
Using direct processing on CQ with non IB_POLL_DIRECT type may trigger
concurrent processing.

**Note**

do not pass -1 as `budget` unless it is guaranteed that the number
of completions that will be processed is small.

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

```c
struct ib_cq * __ib_alloc_cq(struct ib_device *dev, void *private, int nr_cqe, int comp_vector, enum ib_poll_context poll_ctx, const char *caller)
```

allocate a completion queue

**Parameters**

- `struct ib_device *dev`: device to allocate the CQ for
- `void *private`: driver private data, accessible from cq->cq_context
- `int nr_cqe`: number of CQEs to allocate
- `int comp_vector`: HCA completion vectors for this CQ
- `enum ib_poll_context poll_ctx`: context to poll the CQ from.
- `const char *caller`: module owner name.

**Description**

This is the proper interface to allocate a CQ for in-kernel users. A
CQ allocated with this interface will automatically be polled from the
specified context. The ULP must use wr->wr_cqe instead of wr->wr_id
to use this CQ abstraction.

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

```c
struct ib_cq * __ib_alloc_cq_any(struct ib_device *dev, void *private, int nr_cqe, enum ib_poll_context poll_ctx, const char *caller)
```

allocate a completion queue

**Parameters**

- `struct ib_device *dev`: device to allocate the CQ for
- `void *private`: driver private data, accessible from cq->cq_context
- `int nr_cqe`: number of CQEs to allocate
- `enum ib_poll_context poll_ctx`: context to poll the CQ from
- `const char *caller`: module owner name

**Description**

Attempt to spread ULP Completion Queues over each device's interrupt
vectors. A simple best-effort mechanism is used.

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

```c
void ib_free_cq(struct ib_cq *cq)
```

free a completion queue

**Parameters**

- `struct ib_cq *cq`: completion queue to free.

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

```c
struct ib_cq * ib_cq_pool_get(struct ib_device *dev, unsigned int nr_cqe, int comp_vector_hint, enum ib_poll_context poll_ctx)
```

Find the least used completion queue that matches a given cpu hint (or least used for wild card affinity) and fits nr_cqe.

**Parameters**

- `struct ib_device *dev`: rdma device
- `unsigned int nr_cqe`: number of needed cqe entries
- `int comp_vector_hint`: completion vector hint (-1) for the driver to assign
  a comp vector based on internal counter
- `enum ib_poll_context poll_ctx`: cq polling context

**Description**

Finds a cq that satisfies **comp_vector_hint** and **nr_cqe** requirements and
claim entries in it for us.  In case there is no available cq, allocate
a new cq with the requirements and add it to the device pool.
IB_POLL_DIRECT cannot be used for shared cqs so it is not a valid value
for **poll_ctx**.

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

```c
void ib_cq_pool_put(struct ib_cq *cq, unsigned int nr_cqe)
```

Return a CQ taken from a shared pool.

**Parameters**

- `struct ib_cq *cq`: The CQ to return.
- `unsigned int nr_cqe`: The max number of cqes that the user had requested.



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

```c
int ib_cm_listen(struct ib_cm_id *cm_id, __be64 service_id)
```

Initiates listening on the specified service ID for connection and service ID resolution requests.

**Parameters**

- `struct ib_cm_id *cm_id`: Connection identifier associated with the listen request.
- `__be64 service_id`: Service identifier matched against incoming connection
  and service ID resolution requests.  The service ID should be specified
  network-byte order.  If set to IB_CM_ASSIGN_SERVICE_ID, the CM will
  assign a service ID to the caller.

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

```c
struct ib_cm_id * ib_cm_insert_listen(struct ib_device *device, ib_cm_handler cm_handler, __be64 service_id)
```

Create a new listening ib_cm_id and listen on the given service ID.

**Parameters**

- `struct ib_device *device`: Device associated with the cm_id.  All related communication will
  be associated with the specified device.
- `ib_cm_handler cm_handler`: Callback invoked to notify the user of CM events.
- `__be64 service_id`: Service identifier matched against incoming connection
  and service ID resolution requests.  The service ID should be specified
  network-byte order.  If set to IB_CM_ASSIGN_SERVICE_ID, the CM will
  assign a service ID to the caller.

**Description**

If there's an existing ID listening on that same device and service ID,
return it.

Callers should call ib_destroy_cm_id when done with the listener ID.



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

```c
int rdma_rw_ctx_init(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct scatterlist *sg, u32 sg_cnt, u32 sg_offset, u64 remote_addr, u32 rkey, enum dma_data_direction dir)
```

initialize a RDMA READ/WRITE context

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to initialize
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct scatterlist *sg`: scatterlist to READ/WRITE from/to
- `u32 sg_cnt`: number of entries in **sg**
- `u32 sg_offset`: current byte offset into **sg**
- `u64 remote_addr`: remote address to read/write (relative to **rkey**)
- `u32 rkey`: remote key to operate on
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

**Description**

Returns the number of WQEs that will be needed on the workqueue if
successful, or a negative error code.

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

```c
int rdma_rw_ctx_init_bvec(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, const struct bio_vec *bvecs, u32 nr_bvec, struct bvec_iter iter, u64 remote_addr, u32 rkey, enum dma_data_direction dir)
```

initialize a RDMA READ/WRITE context from bio_vec

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to initialize
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `const struct bio_vec *bvecs`: bio_vec array to READ/WRITE from/to
- `u32 nr_bvec`: number of entries in **bvecs**
- `struct bvec_iter iter`: bvec iterator describing offset and length
- `u64 remote_addr`: remote address to read/write (relative to **rkey**)
- `u32 rkey`: remote key to operate on
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

**Description**

Maps the bio_vec array directly, avoiding intermediate scatterlist
conversion. Supports MR registration for iWARP devices and force_mr mode.

Returns the number of WQEs that will be needed on the workqueue if
successful, or a negative error code:

* -EINVAL  - **nr_bvec** is zero or **iter.bi_size** is zero
* -ENOMEM - DMA mapping or memory allocation failed

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

```c
int rdma_rw_ctx_signature_init(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct scatterlist *sg, u32 sg_cnt, struct scatterlist *prot_sg, u32 prot_sg_cnt, struct ib_sig_attrs *sig_attrs, u64 remote_addr, u32 rkey, enum dma_data_direction dir)
```

initialize a RW context with signature offload

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to initialize
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct scatterlist *sg`: scatterlist to READ/WRITE from/to
- `u32 sg_cnt`: number of entries in **sg**
- `struct scatterlist *prot_sg`: scatterlist to READ/WRITE protection information from/to
- `u32 prot_sg_cnt`: number of entries in **prot_sg**
- `struct ib_sig_attrs *sig_attrs`: signature offloading algorithms
- `u64 remote_addr`: remote address to read/write (relative to **rkey**)
- `u32 rkey`: remote key to operate on
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

**Description**

Returns the number of WQEs that will be needed on the workqueue if
successful, or a negative error code.

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

```c
struct ib_send_wr * rdma_rw_ctx_wrs(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct ib_cqe *cqe, struct ib_send_wr *chain_wr)
```

return chain of WRs for a RDMA READ or WRITE operation

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to operate on
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct ib_cqe *cqe`: completion queue entry for the last WR
- `struct ib_send_wr *chain_wr`: WR to append to the posted chain

**Description**

Return the WR chain for the set of RDMA READ/WRITE operations described by
**ctx**, as well as any memory registration operations needed.  If **chain_wr**
is non-NULL the WR it points to will be appended to the chain of WRs posted.
If **chain_wr** is not set **cqe** must be set so that the caller gets a
completion notification.

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

```c
int rdma_rw_ctx_post(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct ib_cqe *cqe, struct ib_send_wr *chain_wr)
```

post a RDMA READ or RDMA WRITE operation

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to operate on
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct ib_cqe *cqe`: completion queue entry for the last WR
- `struct ib_send_wr *chain_wr`: WR to append to the posted chain

**Description**

Post the set of RDMA READ/WRITE operations described by **ctx**, as well as
any memory registration operations needed.  If **chain_wr** is non-NULL the
WR it points to will be appended to the chain of WRs posted.  If **chain_wr**
is not set **cqe** must be set so that the caller gets a completion
notification.

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

```c
void rdma_rw_ctx_destroy(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct scatterlist *sg, u32 sg_cnt, enum dma_data_direction dir)
```

release all resources allocated by rdma_rw_ctx_init

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to release
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct scatterlist *sg`: scatterlist that was used for the READ/WRITE
- `u32 sg_cnt`: number of entries in **sg**
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

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

```c
void rdma_rw_ctx_destroy_bvec(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 __maybe_unused port_num, const struct bio_vec __maybe_unused *bvecs, u32 nr_bvec, enum dma_data_direction dir)
```

release resources from rdma_rw_ctx_init_bvec

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to release
- `struct ib_qp *qp`: queue pair to operate on
- `u32 __maybe_unused port_num`: port num to which the connection is bound (unused)
- `const struct bio_vec __maybe_unused *bvecs`: bio_vec array that was used for the READ/WRITE (unused)
- `u32 nr_bvec`: number of entries in **bvecs**
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

**Description**

Releases all resources allocated by a successful [`rdma_rw_ctx_init_bvec()`](#c-rdma_rw_ctx_init_bvec)
call. Must not be called if [`rdma_rw_ctx_init_bvec()`](#c-rdma_rw_ctx_init_bvec) returned an error.

The **port_num** and **bvecs** parameters are unused but present for API
symmetry with [`rdma_rw_ctx_destroy()`](#c-rdma_rw_ctx_destroy).

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

```c
void rdma_rw_ctx_destroy_signature(struct rdma_rw_ctx *ctx, struct ib_qp *qp, u32 port_num, struct scatterlist *sg, u32 sg_cnt, struct scatterlist *prot_sg, u32 prot_sg_cnt, enum dma_data_direction dir)
```

release all resources allocated by rdma_rw_ctx_signature_init

**Parameters**

- `struct rdma_rw_ctx *ctx`: context to release
- `struct ib_qp *qp`: queue pair to operate on
- `u32 port_num`: port num to which the connection is bound
- `struct scatterlist *sg`: scatterlist that was used for the READ/WRITE
- `u32 sg_cnt`: number of entries in **sg**
- `struct scatterlist *prot_sg`: scatterlist that was used for the READ/WRITE of the PI
- `u32 prot_sg_cnt`: number of entries in **prot_sg**
- `enum dma_data_direction dir`: `DMA_TO_DEVICE` for RDMA WRITE, `DMA_FROM_DEVICE` for RDMA READ

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

```c
unsigned int rdma_rw_mr_factor(struct ib_device *device, u32 port_num, unsigned int maxpages)
```

return number of MRs required for a payload

**Parameters**

- `struct ib_device *device`: device handling the connection
- `u32 port_num`: port num to which the connection is bound
- `unsigned int maxpages`: maximum payload pages per rdma_rw_ctx

**Description**

Returns the number of MRs the device requires to move **maxpayload**
bytes. The returned value is used during transport creation to
compute max_rdma_ctxts and the size of the transport's Send and
Send Completion Queues.

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

```c
unsigned int rdma_rw_max_send_wr(struct ib_device *dev, u32 port_num, unsigned int max_rdma_ctxs, u32 create_flags)
```

compute max Send WRs needed for RDMA R/W contexts

**Parameters**

- `struct ib_device *dev`: RDMA device
- `u32 port_num`: port number
- `unsigned int max_rdma_ctxs`: number of rdma_rw_ctx structures
- `u32 create_flags`: QP create flags (pass IB_QP_CREATE_INTEGRITY_EN if
  data integrity will be enabled on the QP)

**Description**

Returns the total number of Send Queue entries needed for
**max_rdma_ctxs**. The result accounts for memory registration and
invalidation work requests when the device requires them.

ULPs use this to size Send Queues and Send CQs before creating a
Queue Pair.



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

```c
bool rdma_dev_access_netns(const struct ib_device *dev, const struct net *net)
```

Return whether an rdma device can be accessed from a specified net namespace or not.

**Parameters**

- `const struct ib_device *dev`: Pointer to rdma device which needs to be checked
- `const struct net *net`: Pointer to net namesapce for which access to be checked

**Description**

When the rdma device is in shared mode, it ignores the net namespace.
When the rdma device is exclusive to a net namespace, rdma device net
namespace is checked against the specified one.

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

```c
bool rdma_dev_has_raw_cap(const struct ib_device *dev)
```

Returns whether a specified rdma device has CAP_NET_RAW capability or not.

**Parameters**

- `const struct ib_device *dev`: Pointer to rdma device whose capability to be checked

**Description**

Returns true if a rdma device's owning user namespace has CAP_NET_RAW
capability, otherwise false. When rdma subsystem is in legacy shared network,
namespace mode, the default net namespace is considered.

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

```c
void ib_device_put(struct ib_device *device)
```

Release IB device reference

**Parameters**

- `struct ib_device *device`: device whose reference to be released

**Description**

[`ib_device_put()`](#c-ib_device_put) releases reference to the IB device to allow it to be
unregistered and eventually free.

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

```c
struct ib_device * _ib_alloc_device(size_t size, struct net *net)
```

allocate an IB device struct

**Parameters**

- `size_t size`: size of structure to allocate
- `struct net *net`: network namespace device should be located in, namespace
  must stay valid until [`ib_register_device()`](#c-ib_register_device) is completed.

**Description**

Low-level drivers should use `ib_alloc_device()` to allocate `struct ib_device`.  **size** is the size of the structure to be allocated,
including any private data used by the low-level driver.
[`ib_dealloc_device()`](#c-ib_dealloc_device) must be used to free structures allocated with
`ib_alloc_device()`.

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

```c
void ib_dealloc_device(struct ib_device *device)
```

free an IB device struct

**Parameters**

- `struct ib_device *device`: structure to free

**Description**

Free a structure allocated with `ib_alloc_device()`.

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

```c
const struct ib_port_immutable* ib_port_immutable_read(struct ib_device *dev, unsigned int port)
```

Read rdma port's immutable data

**Parameters**

- `struct ib_device *dev`: IB device
- `unsigned int port`: port number whose immutable data to read. It starts with index 1 and
  valid upto including `rdma_end_port()`.

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

```c
int ib_register_device(struct ib_device *device, const char *name, struct device *dma_device)
```

Register an IB device with IB core

**Parameters**

- `struct ib_device *device`: Device to register
- `const char *name`: unique string device name. This may include a '%' which will
  cause a unique index to be added to the passed device name.
- `struct device *dma_device`: pointer to a DMA-capable device. If `NULL`, then the IB
  device will be used. In this case the caller should fully
  setup the ibdev for DMA. This usually means using dma_virt_ops.

**Description**

Low-level drivers use [`ib_register_device()`](#c-ib_register_device) to register their
devices with the IB core.  All registered clients will receive a
callback for each device that is added. **device** must be allocated
with `ib_alloc_device()`.

If the driver uses ops.dealloc_driver and calls any [`ib_unregister_device()`](#c-ib_unregister_device)
asynchronously then the device pointer may become freed as soon as this
function returns.

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

```c
void ib_unregister_device(struct ib_device *ib_dev)
```

Unregister an IB device

**Parameters**

- `struct ib_device *ib_dev`: The device to unregister

**Description**

Unregister an IB device.  All clients will receive a remove callback.

Callers should call this routine only once, and protect against races with
registration. Typically it should only be called as part of a remove
callback in an implementation of driver core's struct device_driver and
related.

If ops.dealloc_driver is used then ib_dev will be freed upon return from
this function.

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

```c
void ib_unregister_device_and_put(struct ib_device *ib_dev)
```

Unregister a device while holding a 'get'

**Parameters**

- `struct ib_device *ib_dev`: The device to unregister

**Description**

This is the same as [`ib_unregister_device()`](#c-ib_unregister_device), except it includes an internal
[`ib_device_put()`](#c-ib_device_put) that should match a 'get' obtained by the caller.

It is safe to call this routine concurrently from multiple threads while
holding the 'get'. When the function returns the device is fully
unregistered.

Drivers using this flow MUST use the driver_unregister callback to clean up
their resources associated with the device and dealloc it.

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

```c
void ib_unregister_driver(enum rdma_driver_id driver_id)
```

Unregister all IB devices for a driver

**Parameters**

- `enum rdma_driver_id driver_id`: The driver to unregister

**Description**

This implements a fence for device unregistration. It only returns once all
devices associated with the driver_id have fully completed their
unregistration and returned from ib_unregister_device*().

If device's are not yet unregistered it goes ahead and starts unregistering
them.

This does not block creation of new devices with the given driver_id, that
is the responsibility of the caller.

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

```c
void ib_unregister_device_queued(struct ib_device *ib_dev)
```

Unregister a device using a work queue

**Parameters**

- `struct ib_device *ib_dev`: The device to unregister

**Description**

This schedules an asynchronous unregistration using a WQ for the device. A
driver should use this to avoid holding locks while doing unregistration,
such as holding the RTNL lock.

Drivers using this API must use ib_unregister_driver before module unload
to ensure that all scheduled unregistrations have completed.

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

```c
int ib_register_client(struct ib_client *client)
```

Register an IB client

**Parameters**

- `struct ib_client *client`: Client to register

**Description**

Upper level users of the IB drivers can use [`ib_register_client()`](#c-ib_register_client) to
register callbacks for IB device addition and removal.  When an IB
device is added, each registered client's add method will be called
(in the order the clients were registered), and when a device is
removed, each client's remove method will be called (in the reverse
order that clients were registered).  In addition, when
[`ib_register_client()`](#c-ib_register_client) is called, the client will receive an add
callback for all devices already registered.

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

```c
void ib_unregister_client(struct ib_client *client)
```

Unregister an IB client

**Parameters**

- `struct ib_client *client`: Client to unregister

**Description**

Upper level users use [`ib_unregister_client()`](#c-ib_unregister_client) to remove their client
registration.  When [`ib_unregister_client()`](#c-ib_unregister_client) is called, the client
will receive a remove callback for each IB device still registered.

This is a full fence, once it returns no client callbacks will be called,
or are running in another thread.

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

```c
void ib_set_client_data(struct ib_device *device, struct ib_client *client, void *data)
```

Set IB client context

**Parameters**

- `struct ib_device *device`: Device to set context for
- `struct ib_client *client`: Client to set context for
- `void *data`: Context to set

**Description**

[`ib_set_client_data()`](#c-ib_set_client_data) sets client context data that can be retrieved with
`ib_get_client_data()`. This can only be called while the client is
registered to the device, once the ib_client `remove()` callback returns this
cannot be called.

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

```c
void ib_register_event_handler(struct ib_event_handler *event_handler)
```

Register an IB event handler

**Parameters**

- `struct ib_event_handler *event_handler`: Handler to register

**Description**

[`ib_register_event_handler()`](#c-ib_register_event_handler) registers an event handler that will be
called back when asynchronous IB events occur (as defined in
chapter 11 of the InfiniBand Architecture Specification). This
callback occurs in workqueue context.

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

```c
void ib_unregister_event_handler(struct ib_event_handler *event_handler)
```

Unregister an event handler

**Parameters**

- `struct ib_event_handler *event_handler`: Handler to unregister

**Description**

Unregister an event handler registered with
[`ib_register_event_handler()`](#c-ib_register_event_handler).

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

```c
int ib_query_port(struct ib_device *device, u32 port_num, struct ib_port_attr *port_attr)
```

Query IB port attributes

**Parameters**

- `struct ib_device *device`: Device to query
- `u32 port_num`: Port number to query
- `struct ib_port_attr *port_attr`: Port attributes

**Description**

[`ib_query_port()`](#c-ib_query_port) returns the attributes of a port through the
**port_attr** pointer.

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

```c
int ib_device_set_netdev(struct ib_device *ib_dev, struct net_device *ndev, u32 port)
```

Associate the ib_dev with an underlying net_device

**Parameters**

- `struct ib_device *ib_dev`: Device to modify
- `struct net_device *ndev`: net_device to affiliate, may be NULL
- `u32 port`: IB port the net_device is connected to

**Description**

Drivers should use this to link the ib_device to a netdev so the netdev
shows up in interfaces like ib_enum_roce_netdev. Only one netdev may be
affiliated with any port.

The caller must ensure that the given ndev is not unregistered or
unregistering, and that either the ib_device is unregistered or
[`ib_device_set_netdev()`](#c-ib_device_set_netdev) is called with NULL when the ndev sends a
NETDEV_UNREGISTER event.

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

```c
int ib_query_netdev_port(struct ib_device *ibdev, struct net_device *ndev, u32 *port)
```

Query the port number of a net_device associated with an ibdev

**Parameters**

- `struct ib_device *ibdev`: IB device
- `struct net_device *ndev`: Network device
- `u32 *port`: IB port the net_device is connected to

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

```c
struct ib_device * ib_device_get_by_netdev(struct net_device *ndev, enum rdma_driver_id driver_id)
```

Find an IB device associated with a netdev

**Parameters**

- `struct net_device *ndev`: netdev to locate
- `enum rdma_driver_id driver_id`: The driver ID that must match (RDMA_DRIVER_UNKNOWN matches all)

**Description**

Find and hold an ib_device that is associated with a netdev via
[`ib_device_set_netdev()`](#c-ib_device_set_netdev). The caller must call [`ib_device_put()`](#c-ib_device_put) on the
returned pointer.

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

```c
int ib_query_pkey(struct ib_device *device, u32 port_num, u16 index, u16 *pkey)
```

Get P_Key table entry

**Parameters**

- `struct ib_device *device`: Device to query
- `u32 port_num`: Port number to query
- `u16 index`: P_Key table index to query
- `u16 *pkey`: Returned P_Key

**Description**

[`ib_query_pkey()`](#c-ib_query_pkey) fetches the specified P_Key table entry.

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

```c
int ib_modify_device(struct ib_device *device, int device_modify_mask, struct ib_device_modify *device_modify)
```

Change IB device attributes

**Parameters**

- `struct ib_device *device`: Device to modify
- `int device_modify_mask`: Mask of attributes to change
- `struct ib_device_modify *device_modify`: New attribute values

**Description**

[`ib_modify_device()`](#c-ib_modify_device) changes a device's attributes as specified by
the **device_modify_mask** and **device_modify** structure.

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

```c
int ib_modify_port(struct ib_device *device, u32 port_num, int port_modify_mask, struct ib_port_modify *port_modify)
```

Modifies the attributes for the specified port.

**Parameters**

- `struct ib_device *device`: The device to modify.
- `u32 port_num`: The number of the port to modify.
- `int port_modify_mask`: Mask used to specify which attributes of the port
  to change.
- `struct ib_port_modify *port_modify`: New attribute values for the port.

**Description**

[`ib_modify_port()`](#c-ib_modify_port) changes a port's attributes as specified by the
**port_modify_mask** and **port_modify** structure.

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

```c
int ib_find_gid(struct ib_device *device, union ib_gid *gid, u32 *port_num, u16 *index)
```

Returns the port number and GID table index where a specified GID value occurs. Its searches only for IB link layer.

**Parameters**

- `struct ib_device *device`: The device to query.
- `union ib_gid *gid`: The GID value to search for.
- `u32 *port_num`: The port number of the device where the GID value was found.
- `u16 *index`: The index into the GID table where the GID was found.  This
  parameter may be NULL.

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

```c
int ib_find_pkey(struct ib_device *device, u32 port_num, u16 pkey, u16 *index)
```

Returns the PKey table index where a specified PKey value occurs.

**Parameters**

- `struct ib_device *device`: The device to query.
- `u32 port_num`: The port number of the device to search for the PKey.
- `u16 pkey`: The PKey value to search for.
- `u16 *index`: The index into the PKey table where the PKey was found.

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

```c
struct net_device * ib_get_net_dev_by_params(struct ib_device *dev, u32 port, u16 pkey, const union ib_gid *gid, const struct sockaddr *addr)
```

Return the appropriate net_dev for a received CM request

**Parameters**

- `struct ib_device *dev`: An RDMA device on which the request has been received.
- `u32 port`: Port number on the RDMA device.
- `u16 pkey`: The Pkey the request came on.
- `const union ib_gid *gid`: A GID that the net_dev uses to communicate.
- `const struct sockaddr *addr`: Contains the IP address that the request specified as its
  destination.



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

```c
struct ib_pd * __ib_alloc_pd(struct ib_device *device, unsigned int flags, const char *caller)
```

Allocates an unused protection domain.

**Parameters**

- `struct ib_device *device`: The device on which to allocate the protection domain.
- `unsigned int flags`: protection domain flags
- `const char *caller`: caller's build-time module name

**Description**

A protection domain object provides an association between QPs, shared
receive queues, address handles, memory regions, and memory windows.

Every PD has a local_dma_lkey which can be used as the lkey value for local
memory operations.

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

```c
int ib_dealloc_pd_user(struct ib_pd *pd, struct ib_udata *udata)
```

Deallocates a protection domain.

**Parameters**

- `struct ib_pd *pd`: The protection domain to deallocate.
- `struct ib_udata *udata`: Valid user data or NULL for kernel object

**Description**

It is an error to call this function while any resources in the pd still
exist.  The caller is responsible to synchronously destroy them and
guarantee no new allocations will happen.

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

```c
void rdma_copy_ah_attr(struct rdma_ah_attr *dest, const struct rdma_ah_attr *src)
```

Copy rdma ah attribute from source to destination.

**Parameters**

- `struct rdma_ah_attr *dest`: Pointer to destination ah_attr. Contents of the destination
  pointer is assumed to be invalid and attribute are overwritten.
- `const struct rdma_ah_attr *src`: Pointer to source ah_attr.

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

```c
void rdma_replace_ah_attr(struct rdma_ah_attr *old, const struct rdma_ah_attr *new)
```

Replace valid ah_attr with new one.

**Parameters**

- `struct rdma_ah_attr *old`: Pointer to existing ah_attr which needs to be replaced.
  old is assumed to be valid or zero'd
- `const struct rdma_ah_attr *new`: Pointer to the new ah_attr.

**Description**

[`rdma_replace_ah_attr()`](#c-rdma_replace_ah_attr) first releases any reference in the old ah_attr if
old the ah_attr is valid; after that it copies the new attribute and holds
the reference to the replaced ah_attr.

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

```c
void rdma_move_ah_attr(struct rdma_ah_attr *dest, struct rdma_ah_attr *src)
```

Move ah_attr pointed by source to destination.

**Parameters**

- `struct rdma_ah_attr *dest`: Pointer to destination ah_attr to copy to.
  dest is assumed to be valid or zero'd
- `struct rdma_ah_attr *src`: Pointer to the new ah_attr.

**Description**

[`rdma_move_ah_attr()`](#c-rdma_move_ah_attr) first releases any reference in the destination ah_attr
if it is valid. This also transfers ownership of internal references from
src to dest, making src invalid in the process. No new reference of the src
ah_attr is taken.

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

```c
struct ib_ah * rdma_create_ah(struct ib_pd *pd, struct rdma_ah_attr *ah_attr, u32 flags)
```

Creates an address handle for the given address vector.

**Parameters**

- `struct ib_pd *pd`: The protection domain associated with the address handle.
- `struct rdma_ah_attr *ah_attr`: The attributes of the address vector.
- `u32 flags`: Create address handle flags (see enum rdma_create_ah_flags).

**Description**

It returns 0 on success and returns appropriate error code on error.
The address handle is used to reference a local or global destination
in all UD QP post sends.

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

```c
struct ib_ah * rdma_create_user_ah(struct ib_pd *pd, struct rdma_ah_attr *ah_attr, struct ib_udata *udata)
```

Creates an address handle for the given address vector. It resolves destination mac address for ah attribute of RoCE type.

**Parameters**

- `struct ib_pd *pd`: The protection domain associated with the address handle.
- `struct rdma_ah_attr *ah_attr`: The attributes of the address vector.
- `struct ib_udata *udata`: pointer to user's input output buffer information need by
  provider driver.

**Description**

It returns 0 on success and returns appropriate error code on error.
The address handle is used to reference a local or global destination
in all UD QP post sends.

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

```c
void rdma_move_grh_sgid_attr(struct rdma_ah_attr *attr, union ib_gid *dgid, u32 flow_label, u8 hop_limit, u8 traffic_class, const struct ib_gid_attr *sgid_attr)
```

Sets the sgid attribute of GRH, taking ownership of the reference

**Parameters**

- `struct rdma_ah_attr *attr`: Pointer to AH attribute structure
- `union ib_gid *dgid`: Destination GID
- `u32 flow_label`: Flow label
- `u8 hop_limit`: Hop limit
- `u8 traffic_class`: traffic class
- `const struct ib_gid_attr *sgid_attr`: Pointer to SGID attribute

**Description**

This takes ownership of the sgid_attr reference. The caller must ensure
[`rdma_destroy_ah_attr()`](#c-rdma_destroy_ah_attr) is called before destroying the rdma_ah_attr after
calling this function.

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

```c
void rdma_destroy_ah_attr(struct rdma_ah_attr *ah_attr)
```

Release reference to SGID attribute of ah attribute.

**Parameters**

- `struct rdma_ah_attr *ah_attr`: Pointer to ah attribute

**Description**

Release reference to the SGID attribute of the ah attribute if it is
non NULL. It is safe to call this multiple times, and safe to call it on
a zero initialized ah_attr.

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

```c
struct ib_srq * ib_create_srq_user(struct ib_pd *pd, struct ib_srq_init_attr *srq_init_attr, struct ib_usrq_object *uobject, struct ib_udata *udata)
```

Creates a SRQ associated with the specified protection domain.

**Parameters**

- `struct ib_pd *pd`: The protection domain associated with the SRQ.
- `struct ib_srq_init_attr *srq_init_attr`: A list of initial attributes required to create the
  SRQ.  If SRQ creation succeeds, then the attributes are updated to
  the actual capabilities of the created SRQ.
- `struct ib_usrq_object *uobject`: uobject pointer if this is not a kernel SRQ
- `struct ib_udata *udata`: udata pointer if this is not a kernel SRQ

**Description**

srq_attr->max_wr and srq_attr->max_sge are read the determine the
requested size of the SRQ, and set to the actual values allocated
on return.  If `ib_create_srq()` succeeds, then max_wr and max_sge
will always be at least as large as the requested values.

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

```c
struct ib_qp * ib_create_qp_user(struct ib_device *dev, struct ib_pd *pd, struct ib_qp_init_attr *attr, struct ib_udata *udata, struct ib_uqp_object *uobj, const char *caller)
```

Creates a QP associated with the specified protection domain.

**Parameters**

- `struct ib_device *dev`: IB device
- `struct ib_pd *pd`: The protection domain associated with the QP.
- `struct ib_qp_init_attr *attr`: A list of initial attributes required to create the
  QP.  If QP creation succeeds, then the attributes are updated to
  the actual capabilities of the created QP.
- `struct ib_udata *udata`: User data
- `struct ib_uqp_object *uobj`: uverbs obect
- `const char *caller`: caller's build-time module name

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

```c
int ib_modify_qp_with_udata(struct ib_qp *ib_qp, struct ib_qp_attr *attr, int attr_mask, struct ib_udata *udata)
```

Modifies the attributes for the specified QP.

**Parameters**

- `struct ib_qp *ib_qp`: The QP to modify.
- `struct ib_qp_attr *attr`: On input, specifies the QP attributes to modify.  On output,
  the current values of selected QP attributes are returned.
- `int attr_mask`: A bit-mask used to specify which attributes of the QP
  are being modified.
- `struct ib_udata *udata`: pointer to user's input output buffer information
  are being modified.
  It returns 0 on success and returns appropriate error code on error.

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

```c
struct ib_mr * ib_alloc_mr(struct ib_pd *pd, enum ib_mr_type mr_type, u32 max_num_sg)
```

Allocates a memory region

**Parameters**

- `struct ib_pd *pd`: protection domain associated with the region
- `enum ib_mr_type mr_type`: memory region type
- `u32 max_num_sg`: maximum sg entries available for registration.

**Notes**

Memory registeration page/sg lists must not exceed max_num_sg.
For mr_type IB_MR_TYPE_MEM_REG, the total length cannot exceed
max_num_sg * used_page_size.

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

```c
struct ib_mr * ib_alloc_mr_integrity(struct ib_pd *pd, u32 max_num_data_sg, u32 max_num_meta_sg)
```

Allocates an integrity memory region

**Parameters**

- `struct ib_pd *pd`: protection domain associated with the region
- `u32 max_num_data_sg`: maximum data sg entries available for registration
- `u32 max_num_meta_sg`: maximum metadata sg entries available for
  registration

**Notes**

Memory registration page/sg lists must not exceed max_num_sg,
also the integrity page/sg lists must not exceed max_num_meta_sg.

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

```c
struct ib_xrcd * ib_alloc_xrcd_user(struct ib_device *device, struct inode *inode, struct ib_udata *udata)
```

Allocates an XRC domain.

**Parameters**

- `struct ib_device *device`: The device on which to allocate the XRC domain.
- `struct inode *inode`: inode to connect XRCD
- `struct ib_udata *udata`: Valid user data or NULL for kernel object

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

```c
int ib_dealloc_xrcd_user(struct ib_xrcd *xrcd, struct ib_udata *udata)
```

Deallocates an XRC domain.

**Parameters**

- `struct ib_xrcd *xrcd`: The XRC domain to deallocate.
- `struct ib_udata *udata`: Valid user data or NULL for kernel object

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

```c
struct ib_wq * ib_create_wq(struct ib_pd *pd, struct ib_wq_init_attr *wq_attr)
```

Creates a WQ associated with the specified protection domain.

**Parameters**

- `struct ib_pd *pd`: The protection domain associated with the WQ.
- `struct ib_wq_init_attr *wq_attr`: A list of initial attributes required to create the
  WQ. If WQ creation succeeds, then the attributes are updated to
  the actual capabilities of the created WQ.

**Description**

wq_attr->max_wr and wq_attr->max_sge determine
the requested size of the WQ, and set to the actual values allocated
on return.
If [`ib_create_wq()`](#c-ib_create_wq) succeeds, then max_wr and max_sge will always be
at least as large as the requested values.

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

```c
int ib_destroy_wq_user(struct ib_wq *wq, struct ib_udata *udata)
```

Destroys the specified user WQ.

**Parameters**

- `struct ib_wq *wq`: The WQ to destroy.
- `struct ib_udata *udata`: Valid user data

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

```c
int ib_map_mr_sg_pi(struct ib_mr *mr, struct scatterlist *data_sg, int data_sg_nents, unsigned int *data_sg_offset, struct scatterlist *meta_sg, int meta_sg_nents, unsigned int *meta_sg_offset, unsigned int page_size)
```

Map the dma mapped SG lists for PI (protection information) and set an appropriate memory region for registration.

**Parameters**

- `struct ib_mr *mr`: memory region
- `struct scatterlist *data_sg`: dma mapped scatterlist for data
- `int data_sg_nents`: number of entries in data_sg
- `unsigned int *data_sg_offset`: offset in bytes into data_sg
- `struct scatterlist *meta_sg`: dma mapped scatterlist for metadata
- `int meta_sg_nents`: number of entries in meta_sg
- `unsigned int *meta_sg_offset`: offset in bytes into meta_sg
- `unsigned int page_size`: page vector desired page size

**Description**

Constraints:
- The MR must be allocated with type IB_MR_TYPE_INTEGRITY.

After this completes successfully, the  memory region
is ready for registration.

**Return**

0 on success.

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

```c
int ib_map_mr_sg(struct ib_mr *mr, struct scatterlist *sg, int sg_nents, unsigned int *sg_offset, unsigned int page_size)
```

Map the largest prefix of a dma mapped SG list and set it the memory region.

**Parameters**

- `struct ib_mr *mr`: memory region
- `struct scatterlist *sg`: dma mapped scatterlist
- `int sg_nents`: number of entries in sg
- `unsigned int *sg_offset`: offset in bytes into sg
- `unsigned int page_size`: page vector desired page size

**Description**

Constraints:

- The first sg element is allowed to have an offset.
- Each sg element must either be aligned to page_size or virtually
  contiguous to the previous element. In case an sg element has a
  non-contiguous offset, the mapping prefix will not include it.
- The last sg element is allowed to have length less than page_size.
- If sg_nents total byte length exceeds the mr max_num_sge * page_size
  then only max_num_sg entries will be mapped.
- If the MR was allocated with type IB_MR_TYPE_SG_GAPS, none of these
  constraints holds and the page_size argument is ignored.

Returns the number of sg elements that were mapped to the memory region.

After this completes successfully, the  memory region
is ready for registration.

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

```c
int ib_sg_to_pages(struct ib_mr *mr, struct scatterlist *sgl, int sg_nents, unsigned int *sg_offset_p, int (*set_page)(struct ib_mr *, u64))
```

Convert the largest prefix of a sg list to a page vector

**Parameters**

- `struct ib_mr *mr`: memory region
- `struct scatterlist *sgl`: dma mapped scatterlist
- `int sg_nents`: number of entries in sg
- `unsigned int *sg_offset_p`:

  ```text
  ==== =======================================================
  IN   start offset in bytes into sg
  OUT  offset in bytes for element n of the sg of the first
       byte that has not been processed where n is the return
       value of this function.
  ==== =======================================================
  ```
- `int (*set_page)(struct ib_mr *, u64)`: driver page assignment function pointer

**Description**

Core service helper for drivers to convert the largest
prefix of given sg list to a page vector. The sg list
prefix converted is the prefix that meet the requirements
of ib_map_mr_sg.

Returns the number of sg elements that were assigned to
a page vector.

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

```c
void ib_drain_sq(struct ib_qp *qp)
```

Block until all SQ CQEs have been consumed by the application.

**Parameters**

- `struct ib_qp *qp`: queue pair to drain

**Description**

If the device has a provider-specific drain function, then
call that.  Otherwise call the generic drain function
`__ib_drain_sq()`.

The caller must:

ensure there is room in the CQ and SQ for the drain work request and
completion.

allocate the CQ using `ib_alloc_cq()`.

ensure that there are no other contexts that are posting WRs concurrently.
Otherwise the drain is not guaranteed.

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

```c
void ib_drain_rq(struct ib_qp *qp)
```

Block until all RQ CQEs have been consumed by the application.

**Parameters**

- `struct ib_qp *qp`: queue pair to drain

**Description**

If the device has a provider-specific drain function, then
call that.  Otherwise call the generic drain function
`__ib_drain_rq()`.

The caller must:

ensure there is room in the CQ and RQ for the drain work request and
completion.

allocate the CQ using `ib_alloc_cq()`.

ensure that there are no other contexts that are posting WRs concurrently.
Otherwise the drain is not guaranteed.

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

```c
void ib_drain_qp(struct ib_qp *qp)
```

Block until all CQEs have been consumed by the application on both the RQ and SQ.

**Parameters**

- `struct ib_qp *qp`: queue pair to drain

**Description**

The caller must:

ensure there is room in the CQ(s), SQ, and RQ for drain work requests
and completions.

allocate the CQs using `ib_alloc_cq()`.

ensure that there are no other contexts that are posting WRs concurrently.
Otherwise the drain is not guaranteed.

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

```c
struct rdma_hw_stats * rdma_alloc_hw_stats_struct(const struct rdma_stat_desc *descs, int num_counters, unsigned long lifespan)
```

Helper function to allocate dynamic struct for the drivers.

**Parameters**

- `const struct rdma_stat_desc *descs`: array of static descriptors
- `int num_counters`: number of elements in array
- `unsigned long lifespan`: milliseconds between updates

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

```c
void rdma_free_hw_stats_struct(struct rdma_hw_stats *stats)
```

Helper function to release rdma_hw_stats

**Parameters**

- `struct rdma_hw_stats *stats`: statistics to release



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

```c
void ib_pack(const struct ib_field *desc, int desc_len, void *structure, void *buf)
```

Pack a structure into a buffer

**Parameters**

- `const struct ib_field *desc`: Array of structure field descriptions
- `int desc_len`: Number of entries in **desc**
- `void *structure`: Structure to pack from
- `void *buf`: Buffer to pack into

**Description**

[`ib_pack()`](#c-ib_pack) packs a list of structure fields into a buffer,
controlled by the array of fields in **desc**.

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

```c
void ib_unpack(const struct ib_field *desc, int desc_len, void *buf, void *structure)
```

Unpack a buffer into a structure

**Parameters**

- `const struct ib_field *desc`: Array of structure field descriptions
- `int desc_len`: Number of entries in **desc**
- `void *buf`: Buffer to unpack from
- `void *structure`: Structure to unpack into

**Description**

[`ib_pack()`](#c-ib_pack) unpacks a list of structure fields from a buffer,
controlled by the array of fields in **desc**.



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

```c
void ib_sa_cancel_query(int id, struct ib_sa_query *query)
```

try to cancel an SA query

**Parameters**

- `int id`: ID of query to cancel
- `struct ib_sa_query *query`: query pointer to cancel

**Description**

Try to cancel an SA query.  If the id and query don't match up or
the query has already completed, nothing is done.  Otherwise the
query is canceled and will complete with a status of -EINTR.

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

```c
int ib_init_ah_attr_from_path(struct ib_device *device, u32 port_num, struct sa_path_rec *rec, struct rdma_ah_attr *ah_attr, const struct ib_gid_attr *gid_attr)
```

Initialize address handle attributes based on an SA path record.

**Parameters**

- `struct ib_device *device`: Device associated ah attributes initialization.
- `u32 port_num`: Port on the specified device.
- `struct sa_path_rec *rec`: path record entry to use for ah attributes initialization.
- `struct rdma_ah_attr *ah_attr`: address handle attributes to initialization from path record.
- `const struct ib_gid_attr *gid_attr`: SGID attribute to consider during initialization.

**Description**

When [`ib_init_ah_attr_from_path()`](#c-ib_init_ah_attr_from_path) returns success,
(a) for IB link layer it optionally contains a reference to SGID attribute
when GRH is present for IB link layer.
(b) for RoCE link layer it contains a reference to SGID attribute.
User must invoke [`rdma_destroy_ah_attr()`](#c-rdma_destroy_ah_attr) to release reference to SGID
attributes which are initialized using [`ib_init_ah_attr_from_path()`](#c-ib_init_ah_attr_from_path).

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

```c
int ib_sa_path_rec_get(struct ib_sa_client *client, struct ib_device *device, u32 port_num, struct sa_path_rec *rec, ib_sa_comp_mask comp_mask, unsigned long timeout_ms, gfp_t gfp_mask, void (*callback)(int status, struct sa_path_rec *resp, unsigned int num_paths, void *context), void *context, struct ib_sa_query **sa_query)
```

Start a Path get query

**Parameters**

- `struct ib_sa_client *client`: SA client
- `struct ib_device *device`: device to send query on
- `u32 port_num`: port number to send query on
- `struct sa_path_rec *rec`: Path Record to send in query
- `ib_sa_comp_mask comp_mask`: component mask to send in query
- `unsigned long timeout_ms`: time to wait for response
- `gfp_t gfp_mask`: GFP mask to use for internal allocations
- `void (*callback)(int status, struct sa_path_rec *resp, unsigned int num_paths, void *context)`: function called when query completes, times out or is
  canceled
- `void *context`: opaque user context passed to callback
- `struct ib_sa_query **sa_query`: query context, used to cancel query

**Description**

Send a Path Record Get query to the SA to look up a path.  The
callback function will be called when the query completes (or
fails); status is 0 for a successful response, -EINTR if the query
is canceled, -ETIMEDOUT is the query timed out, or -EIO if an error
occurred sending the query.  The resp parameter of the callback is
only valid if status is 0.

If the return value of [`ib_sa_path_rec_get()`](#c-ib_sa_path_rec_get) is negative, it is an
error code.  Otherwise it is a query ID that can be used to cancel
the query.

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

```c
int ib_sa_service_rec_get(struct ib_sa_client *client, struct ib_device *device, u32 port_num, struct sa_service_rec *rec, ib_sa_comp_mask comp_mask, unsigned long timeout_ms, gfp_t gfp_mask, void (*callback)(int status, struct sa_service_rec *resp, unsigned int num_services, void *context), void *context, struct ib_sa_query **sa_query)
```

Start a Service get query

**Parameters**

- `struct ib_sa_client *client`: SA client
- `struct ib_device *device`: device to send query on
- `u32 port_num`: port number to send query on
- `struct sa_service_rec *rec`: Service Record to send in query
- `ib_sa_comp_mask comp_mask`: component mask to send in query
- `unsigned long timeout_ms`: time to wait for response
- `gfp_t gfp_mask`: GFP mask to use for internal allocations
- `void (*callback)(int status, struct sa_service_rec *resp, unsigned int num_services, void *context)`: function called when query completes, times out or is
  canceled
- `void *context`: opaque user context passed to callback
- `struct ib_sa_query **sa_query`: query context, used to cancel query

**Description**

Send a Service Record Get query to the SA to look up a path.  The
callback function will be called when the query completes (or
fails); status is 0 for a successful response, -EINTR if the query
is canceled, -ETIMEDOUT is the query timed out, or -EIO if an error
occurred sending the query.  The resp parameter of the callback is
only valid if status is 0.

If the return value of [`ib_sa_service_rec_get()`](#c-ib_sa_service_rec_get) is negative, it is an
error code. Otherwise it is a query ID that can be used to cancel
the query.



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

```c
int ib_ud_header_init(int payload_bytes, int lrh_present, int eth_present, int vlan_present, int grh_present, int ip_version, int udp_present, int immediate_present, struct ib_ud_header *header)
```

Initialize UD header structure

**Parameters**

- `int payload_bytes`: Length of packet payload
- `int lrh_present`: specify if LRH is present
- `int eth_present`: specify if Eth header is present
- `int vlan_present`: packet is tagged vlan
- `int grh_present`: GRH flag (if non-zero, GRH will be included)
- `int ip_version`: if non-zero, IP header, V4 or V6, will be included
- `int udp_present`: if non-zero, UDP header will be included
- `int immediate_present`: specify if immediate data is present
- `struct ib_ud_header *header`: Structure to initialize

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

```c
int ib_ud_header_pack(struct ib_ud_header *header, void *buf)
```

Pack UD header struct into wire format

**Parameters**

- `struct ib_ud_header *header`: UD header struct
- `void *buf`: Buffer to pack into

**Description**

[`ib_ud_header_pack()`](#c-ib_ud_header_pack) packs the UD header structure **header** into wire
format in the buffer **buf**.



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

```c
unsigned long ib_umem_find_best_pgsz(struct ib_umem *umem, unsigned long pgsz_bitmap, unsigned long virt)
```

Find best HW page size to use for this MR

**Parameters**

- `struct ib_umem *umem`: umem struct
- `unsigned long pgsz_bitmap`: bitmap of HW supported page sizes
- `unsigned long virt`: IOVA

**Description**

This helper is intended for HW that support multiple page
sizes but can do only a single page size in an MR.

Returns 0 if the umem requires page sizes not supported by
the driver to be mapped. Drivers always supporting PAGE_SIZE
or smaller will never see a 0 result.

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

```c
struct ib_umem * ib_umem_get(struct ib_device *device, unsigned long addr, size_t size, int access)
```

Pin and DMA map userspace memory.

**Parameters**

- `struct ib_device *device`: IB device to connect UMEM
- `unsigned long addr`: userspace virtual address to start at
- `size_t size`: length of region to pin
- `int access`: IB_ACCESS_xxx flags for memory being pinned

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

```c
void ib_umem_release(struct ib_umem *umem)
```

release memory pinned with ib_umem_get

**Parameters**

- `struct ib_umem *umem`: umem struct to release



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

```c
struct ib_umem_odp * ib_umem_odp_alloc_implicit(struct ib_device *device, int access)
```

Allocate a parent implicit ODP umem

**Parameters**

- `struct ib_device *device`: IB device to create UMEM
- `int access`: ib_reg_mr access flags

**Description**

Implicit ODP umems do not have a VA range and do not have any page lists.
They exist only to hold the per_mm reference to help the driver create
children umems.

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

```c
struct ib_umem_odp * ib_umem_odp_alloc_child(struct ib_umem_odp *root, unsigned long addr, size_t size, const struct mmu_interval_notifier_ops *ops)
```

Allocate a child ODP umem under an implicit parent ODP umem

**Parameters**

- `struct ib_umem_odp *root`: The parent umem enclosing the child. This must be allocated using
  `ib_alloc_implicit_odp_umem()`
- `unsigned long addr`: The starting userspace VA
- `size_t size`: The length of the userspace VA
- `const struct mmu_interval_notifier_ops *ops`: MMU interval ops, currently only **invalidate**

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

```c
struct ib_umem_odp * ib_umem_odp_get(struct ib_device *device, unsigned long addr, size_t size, int access, const struct mmu_interval_notifier_ops *ops)
```

Create a umem_odp for a userspace va

**Parameters**

- `struct ib_device *device`: IB device struct to get UMEM
- `unsigned long addr`: userspace virtual address to start at
- `size_t size`: length of region to pin
- `int access`: IB_ACCESS_xxx flags for memory being pinned
- `const struct mmu_interval_notifier_ops *ops`: MMU interval ops, currently only **invalidate**

**Description**

The driver should use when the access flags indicate ODP memory. It avoids
pinning, instead, stores the mm for future page fault handling in
conjunction with MMU notifiers.

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

```c
int ib_umem_odp_map_dma_and_lock(struct ib_umem_odp *umem_odp, u64 user_virt, u64 bcnt, u64 access_mask, bool fault)
```

DMA map userspace memory in an ODP MR and lock it.

**Parameters**

- `struct ib_umem_odp *umem_odp`: the umem to map and pin
- `u64 user_virt`: the address from which we need to map.
- `u64 bcnt`: the minimal number of bytes to pin and map. The mapping might be
  bigger due to alignment, and may also be smaller in case of an error
  pinning or mapping a page. The actual pages mapped is returned in
  the return value.
- `u64 access_mask`: bit mask of the requested access permissions for the given
  range.
- `bool fault`: is faulting required for the given range

**Description**

Maps the range passed in the argument to DMA addresses.
Upon success the ODP MR will be locked to let caller complete its device
page table update.

Returns the number of pages mapped in success, negative error code
for failure.


<a id="rst-rdma-verbs-transport-library"></a>

## RDMA Verbs transport library


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

```c
int rvt_fast_reg_mr(struct rvt_qp *qp, struct ib_mr *ibmr, u32 key, int access)
```

fast register physical MR

**Parameters**

- `struct rvt_qp *qp`: the queue pair where the work request comes from
- `struct ib_mr *ibmr`: the memory region to be registered
- `u32 key`: updated key for this memory region
- `int access`: access flags for this memory region

**Description**

Returns 0 on success.

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

```c
int rvt_invalidate_rkey(struct rvt_qp *qp, u32 rkey)
```

invalidate an MR rkey

**Parameters**

- `struct rvt_qp *qp`: queue pair associated with the invalidate op
- `u32 rkey`: rkey to invalidate

**Description**

Returns 0 on success.

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

```c
int rvt_lkey_ok(struct rvt_lkey_table *rkt, struct rvt_pd *pd, struct rvt_sge *isge, struct rvt_sge *last_sge, struct ib_sge *sge, int acc)
```

check IB SGE for validity and initialize

**Parameters**

- `struct rvt_lkey_table *rkt`: table containing lkey to check SGE against
- `struct rvt_pd *pd`: protection domain
- `struct rvt_sge *isge`: outgoing internal SGE
- `struct rvt_sge *last_sge`: last outgoing SGE written
- `struct ib_sge *sge`: SGE to check
- `int acc`: access flags

**Description**

Check the IB SGE for validity and initialize our internal version
of it.

Increments the reference count when a new sge is stored.

**Return**

0 if compressed, 1 if added , otherwise returns -errno.

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

```c
int rvt_rkey_ok(struct rvt_qp *qp, struct rvt_sge *sge, u32 len, u64 vaddr, u32 rkey, int acc)
```

check the IB virtual address, length, and RKEY

**Parameters**

- `struct rvt_qp *qp`: qp for validation
- `struct rvt_sge *sge`: SGE state
- `u32 len`: length of data
- `u64 vaddr`: virtual address to place data
- `u32 rkey`: rkey to check
- `int acc`: access flags

**Return**

1 if successful, otherwise 0.

**Description**

increments the reference count upon success



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

```c
__be32 rvt_compute_aeth(struct rvt_qp *qp)
```

compute the AETH (syndrome + MSN)

**Parameters**

- `struct rvt_qp *qp`: the queue pair to compute the AETH for

**Description**

Returns the AETH.

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

```c
void rvt_get_credit(struct rvt_qp *qp, u32 aeth)
```

flush the send work queue of a QP

**Parameters**

- `struct rvt_qp *qp`: the qp who's send work queue to flush
- `u32 aeth`: the Acknowledge Extended Transport Header

**Description**

The QP s_lock should be held.

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

```c
u32 rvt_restart_sge(struct rvt_sge_state *ss, struct rvt_swqe *wqe, u32 len)
```

rewind the sge state for a wqe

**Parameters**

- `struct rvt_sge_state *ss`: the sge state pointer
- `struct rvt_swqe *wqe`: the wqe to rewind
- `u32 len`: the data length from the start of the wqe in bytes

**Description**

Returns the remaining data length.



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

```c
int rvt_check_ah(struct ib_device *ibdev, struct rdma_ah_attr *ah_attr)
```

validate the attributes of AH

**Parameters**

- `struct ib_device *ibdev`: the ib device
- `struct rdma_ah_attr *ah_attr`: the attributes of the AH

**Description**

If driver supports a more detailed check_ah function call back to it
otherwise just check the basics.

**Return**

0 on success



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

```c
struct rvt_dev_info * rvt_alloc_device(size_t size, int nports)
```

allocate rdi

**Parameters**

- `size_t size`: how big of a structure to allocate
- `int nports`: number of ports to allocate array slots for

**Description**

Use IB core device alloc to allocate space for the rdi which is assumed to be
inside of the ib_device. Any extra space that drivers require should be
included in size.

We also allocate a port array based on the number of ports.

**Return**

pointer to allocated rdi

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

```c
void rvt_dealloc_device(struct rvt_dev_info *rdi)
```

deallocate rdi

**Parameters**

- `struct rvt_dev_info *rdi`: structure to free

**Description**

Free a structure allocated with [`rvt_alloc_device()`](#c-rvt_alloc_device)

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

```c
int rvt_register_device(struct rvt_dev_info *rdi)
```

register a driver

**Parameters**

- `struct rvt_dev_info *rdi`: main dev structure for all of rdmavt operations

**Description**

It is up to drivers to allocate the rdi and fill in the appropriate
information.

**Return**

0 on success otherwise an errno.

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

```c
void rvt_unregister_device(struct rvt_dev_info *rdi)
```

remove a driver

**Parameters**

- `struct rvt_dev_info *rdi`: rvt dev struct

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

```c
int rvt_init_port(struct rvt_dev_info *rdi, struct rvt_ibport *port, int port_index, u16 *pkey_table)
```

init internal data for driver port

**Parameters**

- `struct rvt_dev_info *rdi`: rvt_dev_info struct
- `struct rvt_ibport *port`: rvt port
- `int port_index`: 0 based index of ports, different from IB core port num
- `u16 *pkey_table`: pkey_table for **port**

**Description**

Keep track of a list of ports. No need to have a detach port.
They persist until the driver goes away.

**Return**

always 0



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

```c
bool rvt_cq_enter(struct rvt_cq *cq, struct ib_wc *entry, bool solicited)
```

add a new entry to the completion queue

**Parameters**

- `struct rvt_cq *cq`: completion queue
- `struct ib_wc *entry`: work completion entry to add
- `bool solicited`: true if **entry** is solicited

**Description**

This may be called with qp->s_lock held.

**Return**

return true on success, else return
false if cq is full.



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

```c
int rvt_error_qp(struct rvt_qp *qp, enum ib_wc_status err)
```

put a QP into the error state

**Parameters**

- `struct rvt_qp *qp`: the QP to put into the error state
- `enum ib_wc_status err`: the receive completion error to signal if a RWQE is active

**Description**

Flushes both send and receive work queues.

**Return**

true if last WQE event should be generated.
The QP r_lock and s_lock should be held and interrupts disabled.
If we are already in error state, just return.

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

```c
int rvt_get_rwqe(struct rvt_qp *qp, bool wr_id_only)
```

copy the next RWQE into the QP's RWQE

**Parameters**

- `struct rvt_qp *qp`: the QP
- `bool wr_id_only`: update qp->r_wr_id only, not qp->r_sge

**Description**

Return -1 if there is a local error, 0 if no RWQE is available,
otherwise return 1.

Can be called from interrupt level.

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

```c
void rvt_comm_est(struct rvt_qp *qp)
```

handle trap with QP established

**Parameters**

- `struct rvt_qp *qp`: the QP

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

```c
void rvt_add_rnr_timer(struct rvt_qp *qp, u32 aeth)
```

add/start an rnr timer on the QP

**Parameters**

- `struct rvt_qp *qp`: the QP
- `u32 aeth`: aeth of RNR timeout, simulated aeth for loopback

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

```c
void rvt_stop_rc_timers(struct rvt_qp *qp)
```

stop all timers

**Parameters**

- `struct rvt_qp *qp`: the QP
  stop any pending timers

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

```c
void rvt_del_timers_sync(struct rvt_qp *qp)
```

wait for any timeout routines to exit

**Parameters**

- `struct rvt_qp *qp`: the QP

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

```c
struct rvt_qp_iter * rvt_qp_iter_init(struct rvt_dev_info *rdi, u64 v, void (*cb)(struct rvt_qp *qp, u64 v))
```

initial for QP iteration

**Parameters**

- `struct rvt_dev_info *rdi`: rvt devinfo
- `u64 v`: u64 value
- `void (*cb)(struct rvt_qp *qp, u64 v)`: user-defined callback

**Description**

This returns an iterator suitable for iterating QPs
in the system.

The **cb** is a user-defined callback and **v** is a 64-bit
value passed to and relevant for processing in the
**cb**.  An example use case would be to alter QP processing
based on criteria not part of the rvt_qp.

Use cases that require memory allocation to succeed
must preallocate appropriately.

**Return**

a pointer to an rvt_qp_iter or NULL

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

```c
int rvt_qp_iter_next(struct rvt_qp_iter *iter)
```

return the next QP in iter

**Parameters**

- `struct rvt_qp_iter *iter`: the iterator

**Description**

Fine grained QP iterator suitable for use
with debugfs seq_file mechanisms.

Updates iter->qp with the current QP when the return
value is 0.

**Return**

0 - iter->qp is valid 1 - no more QPs

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

```c
void rvt_qp_iter(struct rvt_dev_info *rdi, u64 v, void (*cb)(struct rvt_qp *qp, u64 v))
```

iterate all QPs

**Parameters**

- `struct rvt_dev_info *rdi`: rvt devinfo
- `u64 v`: a 64-bit value
- `void (*cb)(struct rvt_qp *qp, u64 v)`: a callback

**Description**

This provides a way for iterating all QPs.

The **cb** is a user-defined callback and **v** is a 64-bit
value passed to and relevant for processing in the
cb.  An example use case would be to alter QP processing
based on criteria not part of the rvt_qp.

The code has an internal iterator to simplify
non seq_file use cases.

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

```c
void rvt_copy_sge(struct rvt_qp *qp, struct rvt_sge_state *ss, void *data, u32 length, bool release, bool copy_last)
```

copy data to SGE memory

**Parameters**

- `struct rvt_qp *qp`: associated QP
- `struct rvt_sge_state *ss`: the SGE state
- `void *data`: the data to copy
- `u32 length`: the length of the data
- `bool release`: boolean to release MR
- `bool copy_last`: do a separate copy of the last 8 bytes

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

```c
void rvt_ruc_loopback(struct rvt_qp *sqp)
```

handle UC and RC loopback requests

**Parameters**

- `struct rvt_qp *sqp`: the sending QP

**Description**

This is called from `rvt_do_send()` to forward a WQE addressed to the same HFI
Note that although we are single threaded due to the send engine, we still
have to protect against `post_send()`.  We don't have to worry about
receive interrupts since this is a connected protocol and all packets
will pass through here.



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

```c
struct rvt_mcast * rvt_mcast_find(struct rvt_ibport *ibp, union ib_gid *mgid, u16 lid)
```

search the global table for the given multicast GID/LID

**Parameters**

- `struct rvt_ibport *ibp`: the IB port structure
- `union ib_gid *mgid`: the multicast GID to search for
- `u16 lid`: the multicast LID portion of the multicast address (host order)

**NOTE**

It is valid to have 1 MLID with multiple MGIDs.  It is not valid
to have 1 MGID with multiple MLIDs.

**Description**

The caller is responsible for decrementing the reference count if found.

**Return**

NULL if not found.


<a id="rst-upper-layer-protocols"></a>

## Upper Layer Protocols

<a id="rst-iscsi-extensions-for-rdma-iser"></a>

### iSCSI Extensions for RDMA (iSER)


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

iSER data buffer

**Definition**

```c
struct iser_data_buf {
    struct scatterlist *sg;
    int size;
    unsigned long      data_len;
    int dma_nents;
};
```

**Members**

- `sg`: pointer to the sg list
- `size`: num entries of this sg
- `data_len`: total buffer byte len
- `dma_nents`: returned by dma_map_sg

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

iSER memory registration info

**Definition**

```c
struct iser_mem_reg {
    struct ib_sge sge;
    u32 rkey;
    struct iser_fr_desc *desc;
};
```

**Members**

- `sge`: memory region sg element
- `rkey`: memory region remote key
- `desc`: pointer to fast registration context

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

iSER TX descriptor

**Definition**

```c
struct iser_tx_desc {
    struct iser_ctrl             iser_header;
    struct iscsi_hdr             iscsi_header;
    enum iser_desc_type        type;
    u64 dma_addr;
    struct ib_sge                tx_sg[2];
    int num_sge;
    struct ib_cqe                cqe;
    bool mapped;
    struct ib_reg_wr             reg_wr;
    struct ib_send_wr            send_wr;
    struct ib_send_wr            inv_wr;
};
```

**Members**

- `iser_header`: iser header
- `iscsi_header`: iscsi header
- `type`: command/control/dataout
- `dma_addr`: header buffer dma_address
- `tx_sg`: sg\[0\] points to iser/iscsi headers
  sg\[1\] optionally points to either of immediate data
  unsolicited data-out or control
- `num_sge`: number sges used on this TX task
- `cqe`: completion handler
- `mapped`: Is the task header mapped
- `reg_wr`: registration WR
- `send_wr`: send WR
- `inv_wr`: invalidate WR

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

iSER RX descriptor

**Definition**

```c
struct iser_rx_desc {
    struct iser_ctrl             iser_header;
    struct iscsi_hdr             iscsi_header;
    char data[ISER_RECV_DATA_SEG_LEN];
    u64 dma_addr;
    struct ib_sge                rx_sg;
    struct ib_cqe                cqe;
    char pad[ISER_RX_PAD_SIZE];
};
```

**Members**

- `iser_header`: iser header
- `iscsi_header`: iscsi header
- `data`: received data segment
- `dma_addr`: receive buffer dma address
- `rx_sg`: ib_sge of receive buffer
- `cqe`: completion handler
- `pad`: for sense data TODO: Modify to maximum sense length supported

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

iSER login descriptor

**Definition**

```c
struct iser_login_desc {
    void *req;
    void *rsp;
    u64 req_dma;
    u64 rsp_dma;
    struct ib_sge                sge;
    struct ib_cqe                cqe;
};
```

**Members**

- `req`: pointer to login request buffer
- `rsp`: pointer to login response buffer
- `req_dma`: DMA address of login request buffer
- `rsp_dma`: DMA address of login response buffer
- `sge`: IB sge for login post recv
- `cqe`: completion handler

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

iSER device handle

**Definition**

```c
struct iser_device {
    struct ib_device             *ib_device;
    struct ib_pd                 *pd;
    struct ib_event_handler      event_handler;
    struct list_head             ig_list;
    int refcount;
};
```

**Members**

- `ib_device`: RDMA device
- `pd`: Protection Domain for this device
- `event_handler`: IB events handle routine
- `ig_list`: entry in devices list
- `refcount`: Reference counter, dominated by open iser connections

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

Fast registration resources

**Definition**

```c
struct iser_reg_resources {
    struct ib_mr                     *mr;
    struct ib_mr                     *sig_mr;
};
```

**Members**

- `mr`: memory region
- `sig_mr`: signature memory region

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

Fast registration descriptor

**Definition**

```c
struct iser_fr_desc {
    struct list_head                  list;
    struct iser_reg_resources         rsc;
    bool sig_protected;
    struct list_head                  all_list;
};
```

**Members**

- `list`: entry in connection fastreg pool
- `rsc`: data buffer registration resources
- `sig_protected`: is region protected indicator
- `all_list`: first and last list members

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

connection fast registration pool

**Definition**

```c
struct iser_fr_pool {
    struct list_head        list;
    spinlock_t lock;
    int size;
    struct list_head        all_list;
};
```

**Members**

- `list`: list of fastreg descriptors
- `lock`: protects fastreg pool
- `size`: size of the pool
- `all_list`: first and last list members

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

Infiniband related objects

**Definition**

```c
struct ib_conn {
    struct rdma_cm_id           *cma_id;
    struct ib_qp                *qp;
    struct ib_cq                *cq;
    u32 cq_size;
    struct iser_device          *device;
    struct iser_fr_pool          fr_pool;
    bool pi_support;
    struct ib_cqe                reg_cqe;
};
```

**Members**

- `cma_id`: rdma_cm connection maneger handle
- `qp`: Connection Queue-pair
- `cq`: Connection completion queue
- `cq_size`: The number of max outstanding completions
- `device`: reference to iser device
- `fr_pool`: connection fast registration pool
- `pi_support`: Indicate device T10-PI support
- `reg_cqe`: completion handler

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

iSER connection context

**Definition**

```c
struct iser_conn {
    struct ib_conn               ib_conn;
    struct iscsi_conn            *iscsi_conn;
    struct iscsi_endpoint        *ep;
    enum iser_conn_state         state;
    unsigned qp_max_recv_dtos;
    u16 max_cmds;
    char name[ISER_OBJECT_NAME_SIZE];
    struct work_struct           release_work;
    struct mutex                 state_mutex;
    struct completion            stop_completion;
    struct completion            ib_completion;
    struct completion            up_completion;
    struct list_head             conn_list;
    struct iser_login_desc       login_desc;
    struct iser_rx_desc          *rx_descs;
    u32 num_rx_descs;
    unsigned short               scsi_sg_tablesize;
    unsigned short               pages_per_mr;
    bool snd_w_inv;
};
```

**Members**

- `ib_conn`: connection RDMA resources
- `iscsi_conn`: link to matching iscsi connection
- `ep`: transport handle
- `state`: connection logical state
- `qp_max_recv_dtos`: maximum number of data outs, corresponds
  to max number of post recvs
- `max_cmds`: maximum cmds allowed for this connection
- `name`: connection peer portal
- `release_work`: deferred work for release job
- `state_mutex`: protects iser onnection state
- `stop_completion`: conn_stop completion
- `ib_completion`: RDMA cleanup completion
- `up_completion`: connection establishment completed
  (state is ISER_CONN_UP)
- `conn_list`: entry in ig conn list
- `login_desc`: login descriptor
- `rx_descs`: rx buffers array (cyclic buffer)
- `num_rx_descs`: number of rx descriptors
- `scsi_sg_tablesize`: scsi host sg_tablesize
- `pages_per_mr`: maximum pages available for registration
- `snd_w_inv`: connection uses remote invalidation

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

iser task context

**Definition**

```c
struct iscsi_iser_task {
    struct iser_tx_desc          desc;
    struct iser_conn             *iser_conn;
    enum iser_task_status        status;
    struct scsi_cmnd             *sc;
    int command_sent;
    int dir[ISER_DIRS_NUM];
    struct iser_mem_reg          rdma_reg[ISER_DIRS_NUM];
    struct iser_data_buf         data[ISER_DIRS_NUM];
    struct iser_data_buf         prot[ISER_DIRS_NUM];
};
```

**Members**

- `desc`: TX descriptor
- `iser_conn`: link to iser connection
- `status`: current task status
- `sc`: link to scsi command
- `command_sent`: indicate if command was sent
- `dir`: iser data direction
- `rdma_reg`: task rdma registration desc
- `data`: iser data buffer desc
- `prot`: iser protection buffer desc

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

iSER global context

**Definition**

```c
struct iser_global {
    struct mutex      device_list_mutex;
    struct list_head  device_list;
    struct mutex      connlist_mutex;
    struct list_head  connlist;
    struct kmem_cache *desc_cache;
};
```

**Members**

- `device_list_mutex`: protects device_list
- `device_list`: iser devices global list
- `connlist_mutex`: protects connlist
- `connlist`: iser connections global list
- `desc_cache`: kmem cache for tx dataout



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

```c
int iscsi_iser_pdu_alloc(struct iscsi_task *task, uint8_t opcode)
```

allocate an iscsi-iser PDU

**Parameters**

- `struct iscsi_task *task`: iscsi task
- `uint8_t opcode`: iscsi command opcode

**Description**

- Netes: This routine can't fail, just assign iscsi task

  hdr and max hdr size.

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

```c
int iser_initialize_task_headers(struct iscsi_task *task, struct iser_tx_desc *tx_desc)
```

Initialize task headers

**Parameters**

- `struct iscsi_task *task`: iscsi task
- `struct iser_tx_desc *tx_desc`: iser tx descriptor

**Notes**

This routine may race with iser teardown flow for scsi
error handling TMFs. So for TMF we should acquire the
state mutex to avoid dereferencing the IB device which
may have already been terminated.

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

```c
int iscsi_iser_task_init(struct iscsi_task *task)
```

Initialize iscsi-iser task

**Parameters**

- `struct iscsi_task *task`: iscsi task

**Description**

Initialize the task for the scsi command or mgmt command.

**Return**

Returns zero on success or -ENOMEM when failing
to init task headers (dma mapping error).

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

```c
int iscsi_iser_mtask_xmit(struct iscsi_conn *conn, struct iscsi_task *task)
```

xmit management (immediate) task

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection
- `struct iscsi_task *task`: task management task

**Notes**

The function can return -EAGAIN in which case caller must
call it again later, or recover. '0' return code means successful
xmit.

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

```c
int iscsi_iser_task_xmit(struct iscsi_task *task)
```

xmit iscsi-iser task

**Parameters**

- `struct iscsi_task *task`: iscsi task

**Return**

zero on success or escalates $error on failure.

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

```c
void iscsi_iser_cleanup_task(struct iscsi_task *task)
```

cleanup an iscsi-iser task

**Parameters**

- `struct iscsi_task *task`: iscsi task

**Notes**

- In case the RDMA device is already NULL (might have

  been removed in DEVICE_REMOVAL CM event it will bail-out
  without doing dma unmapping.

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

```c
u8 iscsi_iser_check_protection(struct iscsi_task *task, sector_t *sector)
```

check protection information status of task.

**Parameters**

- `struct iscsi_task *task`: iscsi task
- `sector_t *sector`: error sector if exsists (output)

**Return**

zero if no data-integrity errors have occurred
0x1: data-integrity error occurred in the guard-block
0x2: data-integrity error occurred in the reference tag
0x3: data-integrity error occurred in the application tag

**Description**

In addition the error sector is marked.

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

```c
struct iscsi_cls_conn * iscsi_iser_conn_create(struct iscsi_cls_session *cls_session, uint32_t conn_idx)
```

create a new iscsi-iser connection

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi class connection
- `uint32_t conn_idx`: connection index within the session (for MCS)

**Return**

iscsi_cls_conn when iscsi_conn_setup succeeds or NULL
otherwise.

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

```c
int iscsi_iser_conn_bind(struct iscsi_cls_session *cls_session, struct iscsi_cls_conn *cls_conn, uint64_t transport_eph, int is_leading)
```

bind iscsi and iser connection structures

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi class session
- `struct iscsi_cls_conn *cls_conn`: iscsi class connection
- `uint64_t transport_eph`: transport end-point handle
- `int is_leading`: indicate if this is the session leading connection (MCS)

**Return**

zero on success, $error if iscsi_conn_bind fails and
-EINVAL in case end-point doesn't exists anymore or iser connection
state is not UP (teardown already started).

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

```c
int iscsi_iser_conn_start(struct iscsi_cls_conn *cls_conn)
```

start iscsi-iser connection

**Parameters**

- `struct iscsi_cls_conn *cls_conn`: iscsi class connection

**Notes**

- Here iser intialize (or re-initialize) stop_completion as

  from this point iscsi must call conn_stop in session/connection
  teardown so iser transport must wait for it.

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

```c
void iscsi_iser_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
```

stop iscsi-iser connection

**Parameters**

- `struct iscsi_cls_conn *cls_conn`: iscsi class connection
- `int flag`: indicate if recover or terminate (passed as is)

**Notes**

- Calling iscsi_conn_stop might theoretically race with

  DEVICE_REMOVAL event and dereference a previously freed RDMA device
  handle, so we call it under iser the state lock to protect against
  this kind of race.

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

```c
void iscsi_iser_session_destroy(struct iscsi_cls_session *cls_session)
```

destroy iscsi-iser session

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi class session

**Description**

Removes and free iscsi host.

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

```c
struct iscsi_cls_session * iscsi_iser_session_create(struct iscsi_endpoint *ep, uint16_t cmds_max, uint16_t qdepth, uint32_t initial_cmdsn)
```

create an iscsi-iser session

**Parameters**

- `struct iscsi_endpoint *ep`: iscsi end-point handle
- `uint16_t cmds_max`: maximum commands in this session
- `uint16_t qdepth`: session command queue depth
- `uint32_t initial_cmdsn`: initiator command sequnce number

**Description**

Allocates and adds a scsi host, expose DIF supprot if
exists, and sets up an iscsi session.

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

```c
struct iscsi_endpoint * iscsi_iser_ep_connect(struct Scsi_Host *shost, struct sockaddr *dst_addr, int non_blocking)
```

Initiate iSER connection establishment

**Parameters**

- `struct Scsi_Host *shost`: scsi_host
- `struct sockaddr *dst_addr`: destination address
- `int non_blocking`: indicate if routine can block

**Description**

Allocate an iscsi endpoint, an iser_conn structure and bind them.
After that start RDMA connection establishment via rdma_cm. We
don't allocate iser_conn embedded in iscsi_endpoint since in teardown
the endpoint will be destroyed at ep_disconnect while iser_conn will
cleanup its resources asynchronuously.

**Return**

iscsi_endpoint created by iscsi layer or ERR_PTR(error)
if fails.

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

```c
int iscsi_iser_ep_poll(struct iscsi_endpoint *ep, int timeout_ms)
```

poll for iser connection establishment to complete

**Parameters**

- `struct iscsi_endpoint *ep`: iscsi endpoint (created at ep_connect)
- `int timeout_ms`: polling timeout allowed in ms.

**Description**

This routine boils down to waiting for up_completion signaling
that cma_id got CONNECTED event.

**Return**

1 if succeeded in connection establishment, 0 if timeout expired
(libiscsi will retry will kick in) or -1 if interrupted by signal
or more likely iser connection state transitioned to TEMINATING or
DOWN during the wait period.

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

```c
void iscsi_iser_ep_disconnect(struct iscsi_endpoint *ep)
```

Initiate connection teardown process

**Parameters**

- `struct iscsi_endpoint *ep`: iscsi endpoint handle

**Description**

This routine is not blocked by iser and RDMA termination process
completion as we queue a deffered work for iser/RDMA destruction
and cleanup or actually call it immediately in case we didn't pass
iscsi conn bind/start stage, thus it is safe.



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

```c
int iser_send_command(struct iscsi_conn *conn, struct iscsi_task *task)
```

send command PDU

**Parameters**

- `struct iscsi_conn *conn`: link to matching iscsi connection
- `struct iscsi_task *task`: SCSI command task

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

```c
int iser_send_data_out(struct iscsi_conn *conn, struct iscsi_task *task, struct iscsi_data *hdr)
```

send data out PDU

**Parameters**

- `struct iscsi_conn *conn`: link to matching iscsi connection
- `struct iscsi_task *task`: SCSI command task
- `struct iscsi_data *hdr`: pointer to the LLD's iSCSI message header



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

```c
int iser_alloc_fastreg_pool(struct ib_conn *ib_conn, unsigned cmds_max, unsigned int size)
```

Creates pool of fast_reg descriptors for fast registration work requests.

**Parameters**

- `struct ib_conn *ib_conn`: connection RDMA resources
- `unsigned cmds_max`: max number of SCSI commands for this connection
- `unsigned int size`: max number of pages per map request

**Return**

0 on success, or errno code on failure

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

```c
void iser_free_fastreg_pool(struct ib_conn *ib_conn)
```

releases the pool of fast_reg descriptors

**Parameters**

- `struct ib_conn *ib_conn`: connection RDMA resources

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

```c
void iser_free_ib_conn_res(struct iser_conn *iser_conn, bool destroy)
```

release IB related resources

**Parameters**

- `struct iser_conn *iser_conn`: iser connection struct
- `bool destroy`: indicator if we need to try to release the
  iser device and memory regoins pool (only iscsi
  shutdown and DEVICE_REMOVAL will use this).

**Description**

This routine is called with the iser state mutex held
so the cm_id removal is out of here. It is Safe to
be invoked multiple times.

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

```c
void iser_conn_release(struct iser_conn *iser_conn)
```

Frees all conn objects and deallocs conn descriptor

**Parameters**

- `struct iser_conn *iser_conn`: iSER connection context

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

```c
int iser_conn_terminate(struct iser_conn *iser_conn)
```

triggers start of the disconnect procedures and waits for them to be done

**Parameters**

- `struct iser_conn *iser_conn`: iSER connection context

**Description**

Called with state mutex held

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

```c
int iser_post_send(struct ib_conn *ib_conn, struct iser_tx_desc *tx_desc)
```

Initiate a Send DTO operation

**Parameters**

- `struct ib_conn *ib_conn`: connection RDMA resources
- `struct iser_tx_desc *tx_desc`: iSER TX descriptor

**Return**

0 on success, -1 on failure


<a id="rst-omni-path-opa-virtual-nic-support"></a>

### Omni-Path (OPA) Virtual NIC support


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

OPA virtual NIC control port

**Definition**

```c
struct opa_vnic_ctrl_port {
    struct ib_device           *ibdev;
    struct opa_vnic_ctrl_ops   *ops;
    u8 num_ports;
};
```

**Members**

- `ibdev`: pointer to ib device
- `ops`: opa vnic control operations
- `num_ports`: number of opa ports

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

OPA VNIC netdev private data structure

**Definition**

```c
struct opa_vnic_adapter {
    struct net_device             *netdev;
    struct ib_device              *ibdev;
    struct opa_vnic_ctrl_port     *cport;
    const struct net_device_ops   *rn_ops;
    u8 port_num;
    u8 vport_num;
    struct mutex lock;
    struct __opa_veswport_info  info;
    u8 vema_mac_addr[ETH_ALEN];
    u32 umac_hash;
    u32 mmac_hash;
    struct hlist_head    *mactbl;
    struct mutex mactbl_lock;
    spinlock_t stats_lock;
    u8 flow_tbl[OPA_VNIC_FLOW_TBL_SIZE];
    unsigned long trap_timeout;
    u8 trap_count;
};
```

**Members**

- `netdev`: pointer to associated netdev
- `ibdev`: ib device
- `cport`: pointer to opa vnic control port
- `rn_ops`: rdma netdev's net_device_ops
- `port_num`: OPA port number
- `vport_num`: vesw port number
- `lock`: adapter lock
- `info`: virtual ethernet switch port information
- `vema_mac_addr`: mac address configured by vema
- `umac_hash`: unicast maclist hash
- `mmac_hash`: multicast maclist hash
- `mactbl`: hash table of MAC entries
- `mactbl_lock`: mac table lock
- `stats_lock`: statistics lock
- `flow_tbl`: flow to default port redirection table
- `trap_timeout`: trap timeout
- `trap_count`: no. of traps allowed within timeout period

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

OPA VNIC mac table node

**Definition**

```c
struct opa_vnic_mac_tbl_node {
    struct hlist_node                    hlist;
    u16 index;
    struct __opa_vnic_mactable_entry     entry;
};
```

**Members**

- `hlist`: hash list handle
- `index`: index of entry in the mac table
- `entry`: entry in the table



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

OPA vnic switch information

**Definition**

```c
struct opa_vesw_info {
    __be16 fabric_id;
    __be16 vesw_id;
    u8 rsvd0[6];
    __be16 def_port_mask;
    u8 rsvd1[2];
    __be16 pkey;
    u8 rsvd2[4];
    __be32 u_mcast_dlid;
    __be32 u_ucast_dlid[OPA_VESW_MAX_NUM_DEF_PORT];
    __be32 rc;
    u8 rsvd3[56];
    __be16 eth_mtu;
    u8 rsvd4[2];
};
```

**Members**

- `fabric_id`: 10-bit fabric id
- `vesw_id`: 12-bit virtual ethernet switch id
- `rsvd0`: reserved bytes
- `def_port_mask`: bitmask of default ports
- `rsvd1`: reserved bytes
- `pkey`: partition key
- `rsvd2`: reserved bytes
- `u_mcast_dlid`: unknown multicast dlid
- `u_ucast_dlid`: array of unknown unicast dlids
- `rc`: routing control
- `rsvd3`: reserved bytes
- `eth_mtu`: Ethernet MTU
- `rsvd4`: reserved bytes

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

OPA vnic per port information

**Definition**

```c
struct opa_per_veswport_info {
    __be32 port_num;
    u8 eth_link_status;
    u8 rsvd0[3];
    u8 base_mac_addr[ETH_ALEN];
    u8 config_state;
    u8 oper_state;
    __be16 max_mac_tbl_ent;
    __be16 max_smac_ent;
    __be32 mac_tbl_digest;
    u8 rsvd1[4];
    __be32 encap_slid;
    u8 pcp_to_sc_uc[OPA_VNIC_MAX_NUM_PCP];
    u8 pcp_to_vl_uc[OPA_VNIC_MAX_NUM_PCP];
    u8 pcp_to_sc_mc[OPA_VNIC_MAX_NUM_PCP];
    u8 pcp_to_vl_mc[OPA_VNIC_MAX_NUM_PCP];
    u8 non_vlan_sc_uc;
    u8 non_vlan_vl_uc;
    u8 non_vlan_sc_mc;
    u8 non_vlan_vl_mc;
    u8 rsvd2[48];
    __be16 uc_macs_gen_count;
    __be16 mc_macs_gen_count;
    u8 rsvd3[8];
};
```

**Members**

- `port_num`: port number
- `eth_link_status`: current ethernet link state
- `rsvd0`: reserved bytes
- `base_mac_addr`: base mac address
- `config_state`: configured port state
- `oper_state`: operational port state
- `max_mac_tbl_ent`: max number of mac table entries
- `max_smac_ent`: max smac entries in mac table
- `mac_tbl_digest`: mac table digest
- `rsvd1`: reserved bytes
- `encap_slid`: base slid for the port
- `pcp_to_sc_uc`: sc by pcp index for unicast ethernet packets
- `pcp_to_vl_uc`: vl by pcp index for unicast ethernet packets
- `pcp_to_sc_mc`: sc by pcp index for multicast ethernet packets
- `pcp_to_vl_mc`: vl by pcp index for multicast ethernet packets
- `non_vlan_sc_uc`: sc for non-vlan unicast ethernet packets
- `non_vlan_vl_uc`: vl for non-vlan unicast ethernet packets
- `non_vlan_sc_mc`: sc for non-vlan multicast ethernet packets
- `non_vlan_vl_mc`: vl for non-vlan multicast ethernet packets
- `rsvd2`: reserved bytes
- `uc_macs_gen_count`: generation count for unicast macs list
- `mc_macs_gen_count`: generation count for multicast macs list
- `rsvd3`: reserved bytes

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

OPA vnic port information

**Definition**

```c
struct opa_veswport_info {
    struct opa_vesw_info          vesw;
    struct opa_per_veswport_info  vport;
};
```

**Members**

- `vesw`: OPA vnic switch information
- `vport`: OPA vnic per port information

**Description**

On host, each of the virtual ethernet ports belongs
to a different virtual ethernet switches.

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

single entry in the forwarding table

**Definition**

```c
struct opa_veswport_mactable_entry {
    u8 mac_addr[ETH_ALEN];
    u8 mac_addr_mask[ETH_ALEN];
    __be32 dlid_sd;
};
```

**Members**

- `mac_addr`: MAC address
- `mac_addr_mask`: MAC address bit mask
- `dlid_sd`: Matching DLID and side data

**Description**

On the host each virtual ethernet port will have
a forwarding table. These tables are used to
map a MAC to a LID and other data. For more
details see struct opa_veswport_mactable_entries.
This is the structure of a single mactable entry

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

Forwarding table array

**Definition**

```c
struct opa_veswport_mactable {
    __be16 offset;
    __be16 num_entries;
    __be32 mac_tbl_digest;
    struct opa_veswport_mactable_entry  tbl_entries[];
};
```

**Members**

- `offset`: mac table starting offset
- `num_entries`: Number of entries to get or set
- `mac_tbl_digest`: mac table digest
- `tbl_entries`: Array of table entries

**Description**

The EM sends down this structure in a MAD indicating
the starting offset in the forwarding table that this
entry is to be loaded into and the number of entries
that that this MAD instance contains
The mac_tbl_digest has been added to this MAD structure. It will be set by
the EM and it will be used by the EM to check if there are any
discrepancies with this value and the value
maintained by the EM in the case of VNIC port being deleted or unloaded
A new instantiation of a VNIC will always have a value of zero.
This value is stored as part of the vnic adapter structure and will be
accessed by the GET and SET routines for both the mactable entries and the
veswport info.

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

summary counters

**Definition**

```c
struct opa_veswport_summary_counters {
    __be16 vp_instance;
    __be16 vesw_id;
    __be32 veswport_num;
    __be64 tx_errors;
    __be64 rx_errors;
    __be64 tx_packets;
    __be64 rx_packets;
    __be64 tx_bytes;
    __be64 rx_bytes;
    __be64 tx_unicast;
    __be64 tx_mcastbcast;
    __be64 tx_untagged;
    __be64 tx_vlan;
    __be64 tx_64_size;
    __be64 tx_65_127;
    __be64 tx_128_255;
    __be64 tx_256_511;
    __be64 tx_512_1023;
    __be64 tx_1024_1518;
    __be64 tx_1519_max;
    __be64 rx_unicast;
    __be64 rx_mcastbcast;
    __be64 rx_untagged;
    __be64 rx_vlan;
    __be64 rx_64_size;
    __be64 rx_65_127;
    __be64 rx_128_255;
    __be64 rx_256_511;
    __be64 rx_512_1023;
    __be64 rx_1024_1518;
    __be64 rx_1519_max;
    __be64 reserved[16];
};
```

**Members**

- `vp_instance`: vport instance on the OPA port
- `vesw_id`: virtual ethernet switch id
- `veswport_num`: virtual ethernet switch port number
- `tx_errors`: transmit errors
- `rx_errors`: receive errors
- `tx_packets`: transmit packets
- `rx_packets`: receive packets
- `tx_bytes`: transmit bytes
- `rx_bytes`: receive bytes
- `tx_unicast`: unicast packets transmitted
- `tx_mcastbcast`: multicast/broadcast packets transmitted
- `tx_untagged`: non-vlan packets transmitted
- `tx_vlan`: vlan packets transmitted
- `tx_64_size`: transmit packet length is 64 bytes
- `tx_65_127`: transmit packet length is >=65 and \< 127 bytes
- `tx_128_255`: transmit packet length is >=128 and \< 255 bytes
- `tx_256_511`: transmit packet length is >=256 and \< 511 bytes
- `tx_512_1023`: transmit packet length is >=512 and \< 1023 bytes
- `tx_1024_1518`: transmit packet length is >=1024 and \< 1518 bytes
- `tx_1519_max`: transmit packet length >= 1519 bytes
- `rx_unicast`: unicast packets received
- `rx_mcastbcast`: multicast/broadcast packets received
- `rx_untagged`: non-vlan packets received
- `rx_vlan`: vlan packets received
- `rx_64_size`: received packet length is 64 bytes
- `rx_65_127`: received packet length is >=65 and \< 127 bytes
- `rx_128_255`: received packet length is >=128 and \< 255 bytes
- `rx_256_511`: received packet length is >=256 and \< 511 bytes
- `rx_512_1023`: received packet length is >=512 and \< 1023 bytes
- `rx_1024_1518`: received packet length is >=1024 and \< 1518 bytes
- `rx_1519_max`: received packet length >= 1519 bytes
- `reserved`: reserved bytes

**Description**

All the above are counters of corresponding conditions.

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

error counters

**Definition**

```c
struct opa_veswport_error_counters {
    __be16 vp_instance;
    __be16 vesw_id;
    __be32 veswport_num;
    __be64 tx_errors;
    __be64 rx_errors;
    __be64 rsvd0;
    __be64 tx_smac_filt;
    __be64 rsvd1;
    __be64 rsvd2;
    __be64 rsvd3;
    __be64 tx_dlid_zero;
    __be64 rsvd4;
    __be64 tx_logic;
    __be64 rsvd5;
    __be64 tx_drop_state;
    __be64 rx_bad_veswid;
    __be64 rsvd6;
    __be64 rx_runt;
    __be64 rx_oversize;
    __be64 rsvd7;
    __be64 rx_eth_down;
    __be64 rx_drop_state;
    __be64 rx_logic;
    __be64 rsvd8;
    __be64 rsvd9[16];
};
```

**Members**

- `vp_instance`: vport instance on the OPA port
- `vesw_id`: virtual ethernet switch id
- `veswport_num`: virtual ethernet switch port number
- `tx_errors`: transmit errors
- `rx_errors`: receive errors
- `rsvd0`: reserved bytes
- `tx_smac_filt`: smac filter errors
- `rsvd1`: reserved bytes
- `rsvd2`: reserved bytes
- `rsvd3`: reserved bytes
- `tx_dlid_zero`: transmit packets with invalid dlid
- `rsvd4`: reserved bytes
- `tx_logic`: other transmit errors
- `rsvd5`: reserved bytes
- `tx_drop_state`: packet tansmission in non-forward port state
- `rx_bad_veswid`: received packet with invalid vesw id
- `rsvd6`: reserved bytes
- `rx_runt`: received ethernet packet with length \< 64 bytes
- `rx_oversize`: received ethernet packet with length > MTU size
- `rsvd7`: reserved bytes
- `rx_eth_down`: received packets when interface is down
- `rx_drop_state`: received packets in non-forwarding port state
- `rx_logic`: other receive errors
- `rsvd8`: reserved bytes
- `rsvd9`: reserved bytes

**Description**

All the above are counters of corresponding error conditions.

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

Trap message sent to EM by VNIC

**Definition**

```c
struct opa_veswport_trap {
    __be16 fabric_id;
    __be16 veswid;
    __be32 veswportnum;
    __be16 opaportnum;
    u8 veswportindex;
    u8 opcode;
    __be32 reserved;
};
```

**Members**

- `fabric_id`: 10 bit fabric id
- `veswid`: 12 bit virtual ethernet switch id
- `veswportnum`: logical port number on the Virtual switch
- `opaportnum`: physical port num (redundant on host)
- `veswportindex`: switch port index on opa port 0 based
- `opcode`: operation
- `reserved`: 32 bit for alignment

**Description**

The VNIC will send trap messages to the Ethernet manager to
inform it about changes to the VNIC config, behaviour etc.
This is the format of the trap payload.

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

single entry in the mac list

**Definition**

```c
struct opa_vnic_iface_mac_entry {
    u8 mac_addr[ETH_ALEN];
};
```

**Members**

- `mac_addr`: MAC address

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

Msg to set globally administered MAC

**Definition**

```c
struct opa_veswport_iface_macs {
    __be16 start_idx;
    __be16 num_macs_in_msg;
    __be16 tot_macs_in_lst;
    __be16 gen_count;
    struct opa_vnic_iface_mac_entry entry[];
};
```

**Members**

- `start_idx`: position of first entry (0 based)
- `num_macs_in_msg`: number of MACs in this message
- `tot_macs_in_lst`: The total number of MACs the agent has
- `gen_count`: gen_count to indicate change
- `entry`: The mac list entry

**Description**

Same attribute IDS and attribute modifiers as in locally administered
addresses used to set globally administered addresses

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

Generic VEMA MAD

**Definition**

```c
struct opa_vnic_vema_mad {
    struct ib_mad_hdr  mad_hdr;
    struct ib_rmpp_hdr rmpp_hdr;
    u8 reserved;
    u8 oui[3];
    u8 data[OPA_VNIC_EMA_DATA];
};
```

**Members**

- `mad_hdr`: Generic MAD header
- `rmpp_hdr`: RMPP header for vendor specific MADs
- `reserved`: reserved bytes
- `oui`: Unique org identifier
- `data`: MAD data

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

Generic Notice MAD

**Definition**

```c
struct opa_vnic_notice_attr {
    u8 gen_type;
    u8 oui_1;
    u8 oui_2;
    u8 oui_3;
    __be16 trap_num;
    __be16 toggle_count;
    __be32 issuer_lid;
    __be32 reserved;
    u8 issuer_gid[16];
    u8 raw_data[64];
};
```

**Members**

- `gen_type`: Generic/Specific bit and type of notice
- `oui_1`: Vendor ID byte 1
- `oui_2`: Vendor ID byte 2
- `oui_3`: Vendor ID byte 3
- `trap_num`: Trap number
- `toggle_count`: Notice toggle bit and count value
- `issuer_lid`: Trap issuer's lid
- `reserved`: reserved bytes
- `issuer_gid`: Issuer GID (only if Report method)
- `raw_data`: Trap message body

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

Generic VEMA MAD Trap

**Definition**

```c
struct opa_vnic_vema_mad_trap {
    struct ib_mad_hdr            mad_hdr;
    struct ib_rmpp_hdr           rmpp_hdr;
    u8 reserved;
    u8 oui[3];
    struct opa_vnic_notice_attr  notice;
};
```

**Members**

- `mad_hdr`: Generic MAD header
- `rmpp_hdr`: RMPP header for vendor specific MADs
- `reserved`: reserved bytes
- `oui`: Unique org identifier
- `notice`: Notice structure



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

```c
void opa_vnic_vema_report_event(struct opa_vnic_adapter *adapter, u8 event)
```

sent trap to report the specified event

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `u8 event`: event to be reported

**Description**

This function calls vema api to sent a trap for the given event.

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

```c
void opa_vnic_get_summary_counters(struct opa_vnic_adapter *adapter, struct opa_veswport_summary_counters *cntrs)
```

get summary counters

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_veswport_summary_counters *cntrs`: pointer to destination summary counters structure

**Description**

This function populates the summary counters that is maintained by the
given adapter to destination address provided.

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

```c
void opa_vnic_get_error_counters(struct opa_vnic_adapter *adapter, struct opa_veswport_error_counters *cntrs)
```

get error counters

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_veswport_error_counters *cntrs`: pointer to destination error counters structure

**Description**

This function populates the error counters that is maintained by the
given adapter to destination address provided.

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

```c
void opa_vnic_get_vesw_info(struct opa_vnic_adapter *adapter, struct opa_vesw_info *info)
```

- Get the vesw information

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_vesw_info *info`: pointer to destination vesw info structure

**Description**

This function copies the vesw info that is maintained by the
given adapter to destination address provided.

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

```c
void opa_vnic_set_vesw_info(struct opa_vnic_adapter *adapter, struct opa_vesw_info *info)
```

- Set the vesw information

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_vesw_info *info`: pointer to vesw info structure

**Description**

This function updates the vesw info that is maintained by the
given adapter with vesw info provided. Reserved fields are stored
and returned back to EM as is.

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

```c
void opa_vnic_get_per_veswport_info(struct opa_vnic_adapter *adapter, struct opa_per_veswport_info *info)
```

- Get the vesw per port information

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_per_veswport_info *info`: pointer to destination vport info structure

**Description**

This function copies the vesw per port info that is maintained by the
given adapter to destination address provided.
Note that the read only fields are not copied.

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

```c
void opa_vnic_set_per_veswport_info(struct opa_vnic_adapter *adapter, struct opa_per_veswport_info *info)
```

- Set vesw per port information

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_per_veswport_info *info`: pointer to vport info structure

**Description**

This function updates the vesw per port info that is maintained by the
given adapter with vesw per port info provided. Reserved fields are
stored and returned back to EM as is.

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

```c
void opa_vnic_query_mcast_macs(struct opa_vnic_adapter *adapter, struct opa_veswport_iface_macs *macs)
```

query multicast mac list

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_veswport_iface_macs *macs`: pointer mac list

**Description**

This function populates the provided mac list with the configured
multicast addresses in the adapter.

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

```c
void opa_vnic_query_ucast_macs(struct opa_vnic_adapter *adapter, struct opa_veswport_iface_macs *macs)
```

query unicast mac list

**Parameters**

- `struct opa_vnic_adapter *adapter`: vnic port adapter
- `struct opa_veswport_iface_macs *macs`: pointer mac list

**Description**

This function populates the provided mac list with the configured
unicast addresses in the adapter.



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

- VNIC VEMA port details

**Definition**

```c
struct opa_vnic_vema_port {
    struct opa_vnic_ctrl_port      *cport;
    struct ib_mad_agent            *mad_agent;
    struct opa_class_port_info      class_port_info;
    u64 tid;
    u8 port_num;
    struct xarray                   vports;
    struct ib_event_handler         event_handler;
    struct mutex                    lock;
};
```

**Members**

- `cport`: pointer to port
- `mad_agent`: pointer to mad agent for port
- `class_port_info`: Class port info information.
- `tid`: Transaction id
- `port_num`: OPA port number
- `vports`: vnic ports
- `event_handler`: ib event handler
- `lock`: adapter interface lock

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

```c
u8 vema_get_vport_num(struct opa_vnic_vema_mad *recvd_mad)
```

- Get the vnic from the mad

**Parameters**

- `struct opa_vnic_vema_mad *recvd_mad`: Received mad

**Return**

returns value of the vnic port number

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

```c
struct opa_vnic_adapter * vema_get_vport_adapter(struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_port *port)
```

- Get vnic port adapter from recvd mad

**Parameters**

- `struct opa_vnic_vema_mad *recvd_mad`: received mad
- `struct opa_vnic_vema_port *port`: ptr to port struct on which MAD was recvd

**Return**

vnic adapter

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

```c
bool vema_mac_tbl_req_ok(struct opa_veswport_mactable *mac_tbl)
```

- Check if mac request has correct values

**Parameters**

- `struct opa_veswport_mactable *mac_tbl`: mac table

**Description**

This function checks for the validity of the offset and number of
entries required.

**Return**

true if offset and num_entries are valid

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

```c
struct opa_vnic_adapter * vema_add_vport(struct opa_vnic_vema_port *port, u8 vport_num)
```

- Add a new vnic port

**Parameters**

- `struct opa_vnic_vema_port *port`: ptr to opa_vnic_vema_port struct
- `u8 vport_num`: vnic port number (to be added)

**Description**

Return a pointer to the vnic adapter structure

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

```c
void vema_get_class_port_info(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Get class info for port

**Parameters**

- `struct opa_vnic_vema_port *port`: Port on whic MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function copies the latest class port info value set for the
port and stores it for generating traps

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

```c
void vema_set_class_port_info(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Get class info for port

**Parameters**

- `struct opa_vnic_vema_port *port`: Port on whic MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function updates the port class info for the specific vnic
and sets up the response mad data

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

```c
void vema_get_veswport_info(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Get veswport info

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

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

```c
void vema_set_veswport_info(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Set veswport info

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function gets the port class infor for vnic

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

```c
void vema_get_mac_entries(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Get MAC entries in VNIC MAC table

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function gets the MAC entries that are programmed into
the VNIC MAC forwarding table. It checks for the validity of
the index into the MAC table and the number of entries that
are to be retrieved.

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

```c
void vema_set_mac_entries(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Set MAC entries in VNIC MAC table

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function sets the MAC entries in the VNIC forwarding table
It checks for the validity of the index and the number of forwarding
table entries to be programmed.

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

```c
void vema_set_delete_vesw(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Reset VESW info to POD values

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: pointer to the received mad
- `struct opa_vnic_vema_mad *rsp_mad`: pointer to respose mad

**Description**

This function clears all the fields of veswport info for the requested vesw
and sets them back to the power-on default values. It does not delete the
vesw.

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

```c
void vema_get_mac_list(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad, u16 attr_id)
```

- Get the unicast/multicast macs.

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad contains fields to set vnic parameters
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built
- `u16 attr_id`: Attribute ID indicating multicast or unicast mac list

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

```c
void vema_get_summary_counters(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Gets summary counters.

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad contains fields to set vnic parameters
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built

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

```c
void vema_get_error_counters(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Gets summary counters.

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad contains fields to set vnic parameters
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built

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

```c
void vema_get(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Process received get MAD

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built

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

```c
void vema_set(struct opa_vnic_vema_port *port, struct opa_vnic_vema_mad *recvd_mad, struct opa_vnic_vema_mad *rsp_mad)
```

- Process received set MAD

**Parameters**

- `struct opa_vnic_vema_port *port`: source port on which MAD was received
- `struct opa_vnic_vema_mad *recvd_mad`: Received mad contains fields to set vnic parameters
- `struct opa_vnic_vema_mad *rsp_mad`: Response mad to be built

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

```c
void vema_send(struct ib_mad_agent *mad_agent, struct ib_mad_send_wc *mad_wc)
```

- Send handler for VEMA MAD agent

**Parameters**

- `struct ib_mad_agent *mad_agent`: pointer to the mad agent
- `struct ib_mad_send_wc *mad_wc`: pointer to mad send work completion information

**Description**

Free all the data structures associated with the sent MAD

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

```c
void vema_recv(struct ib_mad_agent *mad_agent, struct ib_mad_send_buf *send_buf, struct ib_mad_recv_wc *mad_wc)
```

- Recv handler for VEMA MAD agent

**Parameters**

- `struct ib_mad_agent *mad_agent`: pointer to the mad agent
- `struct ib_mad_send_buf *send_buf`: Send buffer if found, else NULL
- `struct ib_mad_recv_wc *mad_wc`: pointer to mad send work completion information

**Description**

Handle only set and get methods and respond to other methods
as unsupported. Allocate response buffer and address handle
for the response MAD.

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

```c
struct opa_vnic_vema_port * vema_get_port(struct opa_vnic_ctrl_port *cport, u8 port_num)
```

- Gets the opa_vnic_vema_port

**Parameters**

- `struct opa_vnic_ctrl_port *cport`: pointer to control dev
- `u8 port_num`: Port number

**Description**

This function loops through the ports and returns
the opa_vnic_vema port structure that is associated
with the OPA port number

**Return**

ptr to requested opa_vnic_vema_port strucure
if success, NULL if not

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

```c
void opa_vnic_vema_send_trap(struct opa_vnic_adapter *adapter, struct __opa_veswport_trap *data, u32 lid)
```

- This function sends a trap to the EM

**Parameters**

- `struct opa_vnic_adapter *adapter`: pointer to vnic adapter
- `struct __opa_veswport_trap *data`: pointer to trap data filled by calling function
- `u32 lid`: issuers lid (encap_slid from vesw_port_info)

**Description**

This function is called from the VNIC driver to send a trap if there
is somethng the EM should be notified about. These events currently
are
1) UNICAST INTERFACE MACADDRESS changes
2) MULTICAST INTERFACE MACADDRESS changes
3) ETHERNET LINK STATUS changes
While allocating the send mad the remote site qpn used is 1
as this is the well known QP.

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

```c
void vema_unregister(struct opa_vnic_ctrl_port *cport)
```

- Unregisters agent

**Parameters**

- `struct opa_vnic_ctrl_port *cport`: pointer to control port

**Description**

This deletes the registration by VEMA for MADs

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

```c
int vema_register(struct opa_vnic_ctrl_port *cport)
```

- Registers agent

**Parameters**

- `struct opa_vnic_ctrl_port *cport`: pointer to control port

**Description**

This function registers the handlers for the VEMA MADs

**Return**

returns 0 on success. non zero otherwise

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

```c
void opa_vnic_ctrl_config_dev(struct opa_vnic_ctrl_port *cport, bool en)
```

- This function sends a trap to the EM by way of ib_modify_port to indicate support for ethernet on the fabric.

**Parameters**

- `struct opa_vnic_ctrl_port *cport`: pointer to control port
- `bool en`: enable or disable ethernet on fabric support

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

```c
int opa_vnic_vema_add_one(struct ib_device *device)
```

- Handle new ib device

**Parameters**

- `struct ib_device *device`: ib device pointer

**Description**

Allocate the vnic control port and initialize it.

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

```c
void opa_vnic_vema_rem_one(struct ib_device *device, void *client_data)
```

- Handle ib device removal

**Parameters**

- `struct ib_device *device`: ib device pointer
- `void *client_data`: ib client data

**Description**

Uninitialize and free the vnic control port.


<a id="rst-infiniband-scsi-rdma-protocol-target-support"></a>

### InfiniBand SCSI RDMA protocol target support


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

SCSI command state managed by SRPT

**Constants**

- `SRPT_STATE_NEW`: New command arrived and is being processed.
- `SRPT_STATE_NEED_DATA`: Processing a write or bidir command and waiting
  for data arrival.
- `SRPT_STATE_DATA_IN`: Data for the write or bidir command arrived and is
  being processed.
- `SRPT_STATE_CMD_RSP_SENT`: SRP_RSP for SRP_CMD has been sent.
- `SRPT_STATE_MGMT`: Processing a SCSI task management command.
- `SRPT_STATE_MGMT_RSP_SENT`: SRP_RSP for SRP_TSK_MGMT has been sent.
- `SRPT_STATE_DONE`: Command processing finished successfully, command
  processing has been aborted or command processing
  failed.

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

shared SRPT I/O context information

**Definition**

```c
struct srpt_ioctx {
    struct ib_cqe           cqe;
    void *buf;
    dma_addr_t dma;
    uint32_t offset;
    uint32_t index;
};
```

**Members**

- `cqe`: Completion queue element.
- `buf`: Pointer to the buffer.
- `dma`: DMA address of the buffer.
- `offset`: Offset of the first byte in **buf** and **dma** that is actually used.
- `index`: Index of the I/O context in its ioctx_ring array.

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

SRPT receive I/O context

**Definition**

```c
struct srpt_recv_ioctx {
    struct srpt_ioctx       ioctx;
    struct list_head        wait_list;
    int byte_len;
};
```

**Members**

- `ioctx`: See above.
- `wait_list`: Node for insertion in srpt_rdma_ch.cmd_wait_list.
- `byte_len`: Number of bytes in **ioctx.buf**.

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

SRPT send I/O context

**Definition**

```c
struct srpt_send_ioctx {
    struct srpt_ioctx       ioctx;
    struct srpt_rdma_ch     *ch;
    struct srpt_recv_ioctx  *recv_ioctx;
    struct srpt_rw_ctx      s_rw_ctx;
    struct srpt_rw_ctx      *rw_ctxs;
    struct scatterlist      imm_sg;
    struct ib_cqe           rdma_cqe;
    enum srpt_command_state state;
    struct se_cmd           cmd;
    u8 n_rdma;
    u8 n_rw_ctx;
    bool queue_status_only;
    u8 sense_data[TRANSPORT_SENSE_BUFFER];
};
```

**Members**

- `ioctx`: See above.
- `ch`: Channel pointer.
- `recv_ioctx`: Receive I/O context associated with this send I/O context.
  Only used for processing immediate data.
- `s_rw_ctx`:

  **rw_ctxs** points here if only a single rw_ctx is needed.
- `rw_ctxs`: RDMA read/write contexts.
- `imm_sg`: Scatterlist for immediate data.
- `rdma_cqe`: RDMA completion queue element.
- `state`: I/O context state.
- `cmd`: Target core command data structure.
- `n_rdma`: Number of work requests needed to transfer this ioctx.
- `n_rw_ctx`: Size of rw_ctxs array.
- `queue_status_only`: Send a SCSI status back to the initiator but no data.
- `sense_data`: Sense data to be sent to the initiator.

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

SRP channel state

**Constants**

- `CH_CONNECTING`: QP is in RTR state; waiting for RTU.
- `CH_LIVE`: QP is in RTS state.
- `CH_DISCONNECTING`: DREQ has been sent and waiting for DREP or DREQ has
  been received.
- `CH_DRAINING`: DREP has been received or waiting for DREP timed out
  and last work request has been queued.
- `CH_DISCONNECTED`: Last completion has been received.

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

RDMA channel

**Definition**

```c
struct srpt_rdma_ch {
    struct srpt_nexus       *nexus;
    struct ib_qp            *qp;
    union {
        struct {
            struct ib_cm_id         *cm_id;
        } ib_cm;
        struct {
            struct rdma_cm_id       *cm_id;
        } rdma_cm;
    };
    struct ib_cq            *cq;
    u32 cq_size;
    struct ib_cqe           zw_cqe;
    struct rcu_head         rcu;
    struct kref             kref;
    struct completion       *closed;
    int rq_size;
    u32 max_rsp_size;
    atomic_t sq_wr_avail;
    struct srpt_port        *sport;
    int max_ti_iu_len;
    atomic_t req_lim;
    atomic_t req_lim_delta;
    u16 imm_data_offset;
    spinlock_t spinlock;
    enum rdma_ch_state      state;
    struct kmem_cache       *rsp_buf_cache;
    struct srpt_send_ioctx  **ioctx_ring;
    struct kmem_cache       *req_buf_cache;
    struct srpt_recv_ioctx  **ioctx_recv_ring;
    struct list_head        list;
    struct list_head        cmd_wait_list;
    uint16_t pkey;
    bool using_rdma_cm;
    bool processing_wait_list;
    struct se_session       *sess;
    u8 sess_name[40];
    struct work_struct      release_work;
};
```

**Members**

- `nexus`: I_T nexus this channel is associated with.
- `qp`: IB queue pair used for communicating over this channel.
- `{unnamed_union}`: anonymous
- `ib_cm`: See below.
- `ib_cm.cm_id`: IB CM ID associated with the channel.
- `rdma_cm`: See below.
- `rdma_cm.cm_id`: RDMA CM ID associated with the channel.
- `cq`: IB completion queue for this channel.
- `cq_size`: Number of CQEs in **cq**.
- `zw_cqe`: Zero-length write CQE.
- `rcu`: RCU head.
- `kref`: kref for this channel.
- `closed`: Completion object that will be signaled as soon as a new
  channel object with the same identity can be created.
- `rq_size`: IB receive queue size.
- `max_rsp_size`: Maximum size of an RSP response message in bytes.
- `sq_wr_avail`: number of work requests available in the send queue.
- `sport`: pointer to the information of the HCA port used by this
  channel.
- `max_ti_iu_len`: maximum target-to-initiator information unit length.
- `req_lim`: request limit: maximum number of requests that may be sent
  by the initiator without having received a response.
- `req_lim_delta`: Number of credits not yet sent back to the initiator.
- `imm_data_offset`: Offset from start of SRP_CMD for immediate data.
- `spinlock`: Protects free_list and state.
- `state`: channel state. See also enum rdma_ch_state.
- `rsp_buf_cache`: kmem_cache for **ioctx_ring**.
- `ioctx_ring`: Send ring.
- `req_buf_cache`: kmem_cache for **ioctx_recv_ring**.
- `ioctx_recv_ring`: Receive I/O context ring.
- `list`: Node in srpt_nexus.ch_list.
- `cmd_wait_list`: List of SCSI commands that arrived before the RTU event. This
  list contains struct srpt_ioctx elements and is protected
  against concurrent modification by the cm_id spinlock.
- `pkey`: P_Key of the IB partition for this SRP channel.
- `using_rdma_cm`: Whether the RDMA/CM or IB/CM is used for this channel.
- `processing_wait_list`: Whether or not cmd_wait_list is being processed.
- `sess`: Session information associated with this SRP channel.
- `sess_name`: Session name.
- `release_work`: Allows scheduling of `srpt_release_channel()`.

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

I_T nexus

**Definition**

```c
struct srpt_nexus {
    struct rcu_head         rcu;
    struct list_head        entry;
    struct list_head        ch_list;
    u8 i_port_id[16];
    u8 t_port_id[16];
};
```

**Members**

- `rcu`: RCU head for this data structure.
- `entry`: srpt_port.nexus_list list node.
- `ch_list`: struct srpt_rdma_ch list. Protected by srpt_port.mutex.
- `i_port_id`: 128-bit initiator port identifier copied from SRP_LOGIN_REQ.
- `t_port_id`: 128-bit target port identifier copied from SRP_LOGIN_REQ.

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

attributes for SRPT port

**Definition**

```c
struct srpt_port_attrib {
    u32 srp_max_rdma_size;
    u32 srp_max_rsp_size;
    u32 srp_sq_size;
    bool use_srq;
};
```

**Members**

- `srp_max_rdma_size`: Maximum size of SRP RDMA transfers for new connections.
- `srp_max_rsp_size`: Maximum size of SRP response messages in bytes.
- `srp_sq_size`: Shared receive queue (SRQ) size.
- `use_srq`: Whether or not to use SRQ.

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

information about a single "target portal group"

**Definition**

```c
struct srpt_tpg {
    struct list_head        entry;
    struct srpt_port_id     *sport_id;
    struct se_portal_group  tpg;
};
```

**Members**

- `entry`: Entry in **sport_id->tpg_list**.
- `sport_id`: Port name this TPG is associated with.
- `tpg`: LIO TPG data structure.

**Description**

Zero or more target portal groups are associated with each port name
(srpt_port_id). With each TPG an ACL list is associated.

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

LIO RDMA port information

**Definition**

```c
struct srpt_port_id {
    struct mutex            mutex;
    struct list_head        tpg_list;
    struct se_wwn           wwn;
    char name[64];
};
```

**Members**

- `mutex`: Protects **tpg_list** changes.
- `tpg_list`: TPGs associated with the RDMA port name.
- `wwn`: WWN associated with the RDMA port name.
- `name`: ASCII representation of the port name.

**Description**

Multiple sysfs directories can be associated with a single RDMA port. This
data structure represents a single (port, name) pair.

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

SRPT RDMA port information

**Definition**

```c
struct srpt_port {
    struct srpt_device      *sdev;
    struct ib_mad_agent     *mad_agent;
    bool enabled;
    u8 port;
    u32 sm_lid;
    u32 lid;
    union ib_gid            gid;
    struct work_struct      work;
    char guid_name[64];
    struct srpt_port_id     *guid_id;
    char gid_name[64];
    struct srpt_port_id     *gid_id;
    struct srpt_port_attrib port_attrib;
    atomic_t refcount;
    struct completion       *freed_channels;
    struct mutex            mutex;
    struct list_head        nexus_list;
};
```

**Members**

- `sdev`: backpointer to the HCA information.
- `mad_agent`: per-port management datagram processing information.
- `enabled`: Whether or not this target port is enabled.
- `port`: one-based port number.
- `sm_lid`: cached value of the port's sm_lid.
- `lid`: cached value of the port's lid.
- `gid`: cached value of the port's gid.
- `work`: work structure for refreshing the aforementioned cached values.
- `guid_name`: port name in GUID format.
- `guid_id`: LIO target port information for the port name in GUID format.
- `gid_name`: port name in GID format.
- `gid_id`: LIO target port information for the port name in GID format.
- `port_attrib`: Port attributes that can be accessed through configfs.
- `refcount`: Number of objects associated with this port.
- `freed_channels`: Completion that will be signaled once **refcount** becomes 0.
- `mutex`: Protects nexus_list.
- `nexus_list`: Nexus list. See also srpt_nexus.entry.

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

information associated by SRPT with a single HCA

**Definition**

```c
struct srpt_device {
    struct kref             refcnt;
    struct ib_device        *device;
    struct ib_pd            *pd;
    u32 lkey;
    struct ib_srq           *srq;
    struct ib_cm_id         *cm_id;
    int srq_size;
    struct mutex            sdev_mutex;
    bool use_srq;
    struct kmem_cache       *req_buf_cache;
    struct srpt_recv_ioctx  **ioctx_ring;
    struct ib_event_handler event_handler;
    struct list_head        list;
    struct srpt_port        port[];
};
```

**Members**

- `refcnt`: Reference count for this device.
- `device`: Backpointer to the struct ib_device managed by the IB core.
- `pd`: IB protection domain.
- `lkey`: L_Key (local key) with write access to all local memory.
- `srq`: Per-HCA SRQ (shared receive queue).
- `cm_id`: Connection identifier.
- `srq_size`: SRQ size.
- `sdev_mutex`: Serializes use_srq changes.
- `use_srq`: Whether or not to use SRQ.
- `req_buf_cache`: kmem_cache for **ioctx_ring** buffers.
- `ioctx_ring`: Per-HCA SRQ.
- `event_handler`: Per-HCA asynchronous IB event handler.
- `list`: Node in srpt_dev_list.
- `port`: Information about the ports owned by this HCA.



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

```c
void srpt_event_handler(struct ib_event_handler *handler, struct ib_event *event)
```

asynchronous IB event callback function

**Parameters**

- `struct ib_event_handler *handler`: IB event handler registered by [`ib_register_event_handler()`](#c-ib_register_event_handler).
- `struct ib_event *event`: Description of the event that occurred.

**Description**

Callback function called by the InfiniBand core when an asynchronous IB
event occurs. This callback may occur in interrupt context. See also
section 11.5.2, Set Asynchronous Event Handler in the InfiniBand
Architecture Specification.

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

```c
void srpt_srq_event(struct ib_event *event, void *ctx)
```

SRQ event callback function

**Parameters**

- `struct ib_event *event`: Description of the event that occurred.
- `void *ctx`: Context pointer specified at SRQ creation time.

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

```c
void srpt_qp_event(struct ib_event *event, void *ptr)
```

QP event callback function

**Parameters**

- `struct ib_event *event`: Description of the event that occurred.
- `void *ptr`: SRPT RDMA channel.

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

```c
void srpt_set_ioc(u8 *c_list, u32 slot, u8 value)
```

initialize a IOUnitInfo structure

**Parameters**

- `u8 *c_list`: controller list.
- `u32 slot`: one-based slot number.
- `u8 value`: four-bit value.

**Description**

Copies the lowest four bits of value in element slot of the array of four
bit elements called c_list (controller list). The index slot is one-based.

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

```c
void srpt_get_class_port_info(struct ib_dm_mad *mad)
```

copy ClassPortInfo to a management datagram

**Parameters**

- `struct ib_dm_mad *mad`: Datagram that will be sent as response to DM_ATTR_CLASS_PORT_INFO.

**Description**

See also section 16.3.3.1 ClassPortInfo in the InfiniBand Architecture
Specification.

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

```c
void srpt_get_iou(struct ib_dm_mad *mad)
```

write IOUnitInfo to a management datagram

**Parameters**

- `struct ib_dm_mad *mad`: Datagram that will be sent as response to DM_ATTR_IOU_INFO.

**Description**

See also section 16.3.3.3 IOUnitInfo in the InfiniBand Architecture
Specification. See also section B.7, table B.6 in the SRP r16a document.

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

```c
void srpt_get_ioc(struct srpt_port *sport, u32 slot, struct ib_dm_mad *mad)
```

write IOControllerprofile to a management datagram

**Parameters**

- `struct srpt_port *sport`: HCA port through which the MAD has been received.
- `u32 slot`: Slot number specified in DM_ATTR_IOC_PROFILE query.
- `struct ib_dm_mad *mad`: Datagram that will be sent as response to DM_ATTR_IOC_PROFILE.

**Description**

See also section 16.3.3.4 IOControllerProfile in the InfiniBand
Architecture Specification. See also section B.7, table B.7 in the SRP
r16a document.

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

```c
void srpt_get_svc_entries(u64 ioc_guid, u16 slot, u8 hi, u8 lo, struct ib_dm_mad *mad)
```

write ServiceEntries to a management datagram

**Parameters**

- `u64 ioc_guid`: I/O controller GUID to use in reply.
- `u16 slot`: I/O controller number.
- `u8 hi`: End of the range of service entries to be specified in the reply.
- `u8 lo`: Start of the range of service entries to be specified in the reply..
- `struct ib_dm_mad *mad`: Datagram that will be sent as response to DM_ATTR_SVC_ENTRIES.

**Description**

See also section 16.3.3.5 ServiceEntries in the InfiniBand Architecture
Specification. See also section B.7, table B.8 in the SRP r16a document.

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

```c
void srpt_mgmt_method_get(struct srpt_port *sp, struct ib_mad *rq_mad, struct ib_dm_mad *rsp_mad)
```

process a received management datagram

**Parameters**

- `struct srpt_port *sp`: HCA port through which the MAD has been received.
- `struct ib_mad *rq_mad`: received MAD.
- `struct ib_dm_mad *rsp_mad`: response MAD.

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

```c
void srpt_mad_send_handler(struct ib_mad_agent *mad_agent, struct ib_mad_send_wc *mad_wc)
```

MAD send completion callback

**Parameters**

- `struct ib_mad_agent *mad_agent`: Return value of `ib_register_mad_agent()`.
- `struct ib_mad_send_wc *mad_wc`: Work completion reporting that the MAD has been sent.

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

```c
void srpt_mad_recv_handler(struct ib_mad_agent *mad_agent, struct ib_mad_send_buf *send_buf, struct ib_mad_recv_wc *mad_wc)
```

MAD reception callback function

**Parameters**

- `struct ib_mad_agent *mad_agent`: Return value of `ib_register_mad_agent()`.
- `struct ib_mad_send_buf *send_buf`: Not used.
- `struct ib_mad_recv_wc *mad_wc`: Work completion reporting that a MAD has been received.

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

```c
int srpt_refresh_port(struct srpt_port *sport)
```

configure a HCA port

**Parameters**

- `struct srpt_port *sport`: SRPT HCA port.

**Description**

Enable InfiniBand management datagram processing, update the cached sm_lid,
lid and gid values, and register a callback function for processing MADs
on the specified port.

**Note**

It is safe to call this function more than once for the same port.

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

```c
void srpt_unregister_mad_agent(struct srpt_device *sdev, int port_cnt)
```

unregister MAD callback functions

**Parameters**

- `struct srpt_device *sdev`: SRPT HCA pointer.
- `int port_cnt`: number of ports with registered MAD

**Note**

It is safe to call this function more than once for the same device.

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

```c
struct srpt_ioctx * srpt_alloc_ioctx(struct srpt_device *sdev, int ioctx_size, struct kmem_cache *buf_cache, enum dma_data_direction dir)
```

allocate a SRPT I/O context structure

**Parameters**

- `struct srpt_device *sdev`: SRPT HCA pointer.
- `int ioctx_size`: I/O context size.
- `struct kmem_cache *buf_cache`: I/O buffer cache.
- `enum dma_data_direction dir`: DMA data direction.

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

```c
void srpt_free_ioctx(struct srpt_device *sdev, struct srpt_ioctx *ioctx, struct kmem_cache *buf_cache, enum dma_data_direction dir)
```

free a SRPT I/O context structure

**Parameters**

- `struct srpt_device *sdev`: SRPT HCA pointer.
- `struct srpt_ioctx *ioctx`: I/O context pointer.
- `struct kmem_cache *buf_cache`: I/O buffer cache.
- `enum dma_data_direction dir`: DMA data direction.

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

```c
struct srpt_ioctx ** srpt_alloc_ioctx_ring(struct srpt_device *sdev, int ring_size, int ioctx_size, struct kmem_cache *buf_cache, int alignment_offset, enum dma_data_direction dir)
```

allocate a ring of SRPT I/O context structures

**Parameters**

- `struct srpt_device *sdev`: Device to allocate the I/O context ring for.
- `int ring_size`: Number of elements in the I/O context ring.
- `int ioctx_size`: I/O context size.
- `struct kmem_cache *buf_cache`: I/O buffer cache.
- `int alignment_offset`: Offset in each ring buffer at which the SRP information
  unit starts.
- `enum dma_data_direction dir`: DMA data direction.

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

```c
void srpt_free_ioctx_ring(struct srpt_ioctx **ioctx_ring, struct srpt_device *sdev, int ring_size, struct kmem_cache *buf_cache, enum dma_data_direction dir)
```

free the ring of SRPT I/O context structures

**Parameters**

- `struct srpt_ioctx **ioctx_ring`: I/O context ring to be freed.
- `struct srpt_device *sdev`: SRPT HCA pointer.
- `int ring_size`: Number of ring elements.
- `struct kmem_cache *buf_cache`: I/O buffer cache.
- `enum dma_data_direction dir`: DMA data direction.

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

```c
enum srpt_command_state srpt_set_cmd_state(struct srpt_send_ioctx *ioctx, enum srpt_command_state new)
```

set the state of a SCSI command

**Parameters**

- `struct srpt_send_ioctx *ioctx`: Send I/O context.
- `enum srpt_command_state new`: New I/O context state.

**Description**

Does not modify the state of aborted commands. Returns the previous command
state.

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

```c
bool srpt_test_and_set_cmd_state(struct srpt_send_ioctx *ioctx, enum srpt_command_state old, enum srpt_command_state new)
```

test and set the state of a command

**Parameters**

- `struct srpt_send_ioctx *ioctx`: Send I/O context.
- `enum srpt_command_state old`: Current I/O context state.
- `enum srpt_command_state new`: New I/O context state.

**Description**

Returns true if and only if the previous command state was equal to 'old'.

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

```c
int srpt_post_recv(struct srpt_device *sdev, struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *ioctx)
```

post an IB receive request

**Parameters**

- `struct srpt_device *sdev`: SRPT HCA pointer.
- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.
- `struct srpt_recv_ioctx *ioctx`: Receive I/O context pointer.

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

```c
int srpt_zerolength_write(struct srpt_rdma_ch *ch)
```

perform a zero-length RDMA write

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

**Description**

A quote from the InfiniBand specification: C9-88: For an HCA responder
using Reliable Connection service, for each zero-length RDMA READ or WRITE
request, the R_Key shall not be validated, even if the request includes
Immediate data.

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

```c
int srpt_get_desc_tbl(struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *ioctx, struct srp_cmd *srp_cmd, enum dma_data_direction *dir, struct scatterlist **sg, unsigned int *sg_cnt, u64 *data_len, u16 imm_data_offset)
```

parse the data descriptors of a SRP_CMD request

**Parameters**

- `struct srpt_recv_ioctx *recv_ioctx`: I/O context associated with the received command **srp_cmd**.
- `struct srpt_send_ioctx *ioctx`: I/O context that will be used for responding to the initiator.
- `struct srp_cmd *srp_cmd`: Pointer to the SRP_CMD request data.
- `enum dma_data_direction *dir`: Pointer to the variable to which the transfer direction will be
  written.
- `struct scatterlist **sg`: \[out\] scatterlist for the parsed SRP_CMD.
- `unsigned int *sg_cnt`: \[out\] length of **sg**.
- `u64 *data_len`: Pointer to the variable to which the total data length of all
  descriptors in the SRP_CMD request will be written.
- `u16 imm_data_offset`: \[in\] Offset in SRP_CMD requests at which immediate data
  starts.

**Description**

This function initializes ioctx->nrbuf and ioctx->r_bufs.

Returns -EINVAL when the SRP_CMD request contains inconsistent descriptors;
-ENOMEM when memory allocation fails and zero upon success.

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

```c
int srpt_init_ch_qp(struct srpt_rdma_ch *ch, struct ib_qp *qp)
```

initialize queue pair attributes

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.
- `struct ib_qp *qp`: Queue pair pointer.

**Description**

Initialized the attributes of queue pair 'qp' by allowing local write,
remote read and remote write. Also transitions 'qp' to state IB_QPS_INIT.

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

```c
int srpt_ch_qp_rtr(struct srpt_rdma_ch *ch, struct ib_qp *qp)
```

change the state of a channel to 'ready to receive' (RTR)

**Parameters**

- `struct srpt_rdma_ch *ch`: channel of the queue pair.
- `struct ib_qp *qp`: queue pair to change the state of.

**Description**

Returns zero upon success and a negative value upon failure.

**Note**

currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
If this structure ever becomes larger, it might be necessary to allocate
it dynamically instead of on the stack.

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

```c
int srpt_ch_qp_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp)
```

change the state of a channel to 'ready to send' (RTS)

**Parameters**

- `struct srpt_rdma_ch *ch`: channel of the queue pair.
- `struct ib_qp *qp`: queue pair to change the state of.

**Description**

Returns zero upon success and a negative value upon failure.

**Note**

currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
If this structure ever becomes larger, it might be necessary to allocate
it dynamically instead of on the stack.

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

```c
int srpt_ch_qp_err(struct srpt_rdma_ch *ch)
```

set the channel queue pair state to 'error'

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

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

```c
struct srpt_send_ioctx * srpt_get_send_ioctx(struct srpt_rdma_ch *ch)
```

obtain an I/O context for sending to the initiator

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

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

```c
int srpt_abort_cmd(struct srpt_send_ioctx *ioctx)
```

abort a SCSI command

**Parameters**

- `struct srpt_send_ioctx *ioctx`: I/O context associated with the SCSI command.

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

```c
void srpt_rdma_read_done(struct ib_cq *cq, struct ib_wc *wc)
```

RDMA read completion callback

**Parameters**

- `struct ib_cq *cq`: Completion queue.
- `struct ib_wc *wc`: Work completion.

**Description**

XXX: what is now target_execute_cmd used to be asynchronous, and unmapping
the data that has been transferred via IB RDMA had to be postponed until the
`check_stop_free()` callback.  None of this is necessary anymore and needs to
be cleaned up.

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

```c
int srpt_build_cmd_rsp(struct srpt_rdma_ch *ch, struct srpt_send_ioctx *ioctx, u64 tag, int status)
```

build a SRP_RSP response

**Parameters**

- `struct srpt_rdma_ch *ch`: RDMA channel through which the request has been received.
- `struct srpt_send_ioctx *ioctx`: I/O context associated with the SRP_CMD request. The response will
  be built in the buffer ioctx->buf points at and hence this function will
  overwrite the request data.
- `u64 tag`: tag of the request for which this response is being generated.
- `int status`: value for the STATUS field of the SRP_RSP information unit.

**Description**

Returns the size in bytes of the SRP_RSP response.

An SRP_RSP response contains a SCSI status or service response. See also
section 6.9 in the SRP r16a document for the format of an SRP_RSP
response. See also SPC-2 for more information about sense data.

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

```c
int srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch, struct srpt_send_ioctx *ioctx, u8 rsp_code, u64 tag)
```

build a task management response

**Parameters**

- `struct srpt_rdma_ch *ch`: RDMA channel through which the request has been received.
- `struct srpt_send_ioctx *ioctx`: I/O context in which the SRP_RSP response will be built.
- `u8 rsp_code`: RSP_CODE that will be stored in the response.
- `u64 tag`: Tag of the request for which this response is being generated.

**Description**

Returns the size in bytes of the SRP_RSP response.

An SRP_RSP response contains a SCSI status or service response. See also
section 6.9 in the SRP r16a document for the format of an SRP_RSP
response.

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

```c
void srpt_handle_cmd(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx)
```

process a SRP_CMD information unit

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.
- `struct srpt_recv_ioctx *recv_ioctx`: Receive I/O context.
- `struct srpt_send_ioctx *send_ioctx`: Send I/O context.

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

```c
void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx)
```

process a SRP_TSK_MGMT information unit

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.
- `struct srpt_recv_ioctx *recv_ioctx`: Receive I/O context.
- `struct srpt_send_ioctx *send_ioctx`: Send I/O context.

**Description**

Returns 0 if and only if the request will be processed by the target core.

For more information about SRP_TSK_MGMT information units, see also section
6.7 in the SRP r16a document.

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

```c
bool srpt_handle_new_iu(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx)
```

process a newly received information unit

**Parameters**

- `struct srpt_rdma_ch *ch`: RDMA channel through which the information unit has been received.
- `struct srpt_recv_ioctx *recv_ioctx`: Receive I/O context associated with the information unit.

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

```c
void srpt_send_done(struct ib_cq *cq, struct ib_wc *wc)
```

send completion callback

**Parameters**

- `struct ib_cq *cq`: Completion queue.
- `struct ib_wc *wc`: Work completion.

**Note**

Although this has not yet been observed during tests, at least in
theory it is possible that the [`srpt_get_send_ioctx()`](#c-srpt_get_send_ioctx) call invoked by
[`srpt_handle_new_iu()`](#c-srpt_handle_new_iu) fails. This is possible because the req_lim_delta
value in each response is set to one, and it is possible that this response
makes the initiator send a new request before the send completion for that
response has been processed. This could e.g. happen if the call to
`srpt_put_send_iotcx()` is delayed because of a higher priority interrupt or
if IB retransmission causes generation of the send completion to be
delayed. Incoming information units for which [`srpt_get_send_ioctx()`](#c-srpt_get_send_ioctx) fails
are queued on cmd_wait_list. The code below processes these delayed
requests one at a time.

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

```c
int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
```

create receive and send completion queues

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

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

```c
bool srpt_close_ch(struct srpt_rdma_ch *ch)
```

close a RDMA channel

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

**Description**

Make sure all resources associated with the channel will be deallocated at
an appropriate time.

Returns true if and only if the channel state has been modified into
CH_DRAINING.

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

```c
int srpt_cm_req_recv(struct srpt_device *const sdev, struct ib_cm_id *ib_cm_id, struct rdma_cm_id *rdma_cm_id, u8 port_num, __be16 pkey, const struct srp_login_req *req, const char *src_addr)
```

process the event IB_CM_REQ_RECEIVED

**Parameters**

- `struct srpt_device *const sdev`: HCA through which the login request was received.
- `struct ib_cm_id *ib_cm_id`: IB/CM connection identifier in case of IB/CM.
- `struct rdma_cm_id *rdma_cm_id`: RDMA/CM connection identifier in case of RDMA/CM.
- `u8 port_num`: Port through which the REQ message was received.
- `__be16 pkey`: P_Key of the incoming connection.
- `const struct srp_login_req *req`: SRP login request.
- `const char *src_addr`: GID (IB/CM) or IP address (RDMA/CM) of the port that submitted
  the login request.

**Description**

Ownership of the cm_id is transferred to the target session if this
function returns zero. Otherwise the caller remains the owner of cm_id.

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

```c
void srpt_cm_rtu_recv(struct srpt_rdma_ch *ch)
```

process an IB_CM_RTU_RECEIVED or USER_ESTABLISHED event

**Parameters**

- `struct srpt_rdma_ch *ch`: SRPT RDMA channel.

**Description**

An RTU (ready to use) message indicates that the connection has been
established and that the recipient may begin transmitting.

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

```c
int srpt_cm_handler(struct ib_cm_id *cm_id, const struct ib_cm_event *event)
```

IB connection manager callback function

**Parameters**

- `struct ib_cm_id *cm_id`: IB/CM connection identifier.
- `const struct ib_cm_event *event`: IB/CM event.

**Description**

A non-zero return value will cause the caller destroy the CM ID.

**Note**

[`srpt_cm_handler()`](#c-srpt_cm_handler) must only return a non-zero value when transferring
ownership of the cm_id to a channel by [`srpt_cm_req_recv()`](#c-srpt_cm_req_recv) failed. Returning
a non-zero value in any other case will trigger a race with the
`ib_destroy_cm_id()` call in `srpt_release_channel()`.

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

```c
void srpt_queue_response(struct se_cmd *cmd)
```

transmit the response to a SCSI command

**Parameters**

- `struct se_cmd *cmd`: SCSI target command.

**Description**

Callback function called by the TCM core. Must not block since it can be
invoked on the context of the IB completion handler.

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

```c
int srpt_release_sport(struct srpt_port *sport)
```

disable login and wait for associated channels

**Parameters**

- `struct srpt_port *sport`: SRPT HCA port.

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

```c
struct port_and_port_id srpt_lookup_port(const char *name)
```

Look up an RDMA port by name

**Parameters**

- `const char *name`: ASCII port name

**Description**

Increments the RDMA port reference count if an RDMA port pointer is returned.
The caller must drop that reference count by calling `srpt_port_put_ref()`.

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

```c
int srpt_add_one(struct ib_device *device)
```

InfiniBand device addition callback function

**Parameters**

- `struct ib_device *device`: Describes a HCA.

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

```c
void srpt_remove_one(struct ib_device *device, void *client_data)
```

InfiniBand device removal callback function

**Parameters**

- `struct ib_device *device`: Describes a HCA.
- `void *client_data`: The value passed as the third argument to [`ib_set_client_data()`](#c-ib_set_client_data).

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

```c
void srpt_close_session(struct se_session *se_sess)
```

forcibly close a session

**Parameters**

- `struct se_session *se_sess`: SCSI target session.

**Description**

Callback function invoked by the TCM core to clean up sessions associated
with a node ACL when the user invokes
rmdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id

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

```c
int srpt_parse_i_port_id(u8 i_port_id[16], const char *name)
```

parse an initiator port ID

**Parameters**

- `u8 i_port_id[16]`: Binary 128-bit port ID.
- `const char *name`: ASCII representation of a 128-bit initiator port ID.

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

```c
struct se_portal_group * srpt_make_tpg(struct se_wwn *wwn, const char *name)
```

configfs callback invoked for mkdir /sys/kernel/config/target/$driver/$port/$tpg

**Parameters**

- `struct se_wwn *wwn`: Corresponds to $driver/$port.
- `const char *name`: $tpg.

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

```c
void srpt_drop_tpg(struct se_portal_group *tpg)
```

configfs callback invoked for rmdir /sys/kernel/config/target/$driver/$port/$tpg

**Parameters**

- `struct se_portal_group *tpg`: Target portal group to deregister.

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

```c
struct se_wwn * srpt_make_tport(struct target_fabric_configfs *tf, struct config_group *group, const char *name)
```

configfs callback invoked for mkdir /sys/kernel/config/target/$driver/$port

**Parameters**

- `struct target_fabric_configfs *tf`: Not used.
- `struct config_group *group`: Not used.
- `const char *name`: $port.

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

```c
void srpt_drop_tport(struct se_wwn *wwn)
```

configfs callback invoked for rmdir /sys/kernel/config/target/$driver/$port

**Parameters**

- `struct se_wwn *wwn`: $port.

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

```c
int srpt_init_module(void)
```

kernel module initialization

**Parameters**

- `void`: no arguments

**Note**

Since [`ib_register_client()`](#c-ib_register_client) registers callback functions, and since at
least one of these callback functions ([`srpt_add_one()`](#c-srpt_add_one)) calls target core
functions, this driver must be registered with the target core before
[`ib_register_client()`](#c-ib_register_client) is called.


<a id="rst-iscsi-extensions-for-rdma-iser-target-support"></a>

### iSCSI Extensions for RDMA (iSER) target support


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

```c
void isert_conn_terminate(struct isert_conn *isert_conn)
```

Initiate connection termination

**Parameters**

- `struct isert_conn *isert_conn`: isert connection struct

**Notes**

In case the connection state is BOUND, move state
to TEMINATING and start teardown sequence (rdma_disconnect).
In case the connection state is UP, complete flush as well.

This routine must be called with mutex held. Thus it is
safe to call multiple times.

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

```c
void isert_put_unsol_pending_cmds(struct iscsit_conn *conn)
```

Drop commands waiting for unsolicitate dataout

**Parameters**

- `struct iscsit_conn *conn`: iscsi connection

**Description**

We might still have commands that are waiting for unsolicited
dataouts messages. We must put the extra reference on those
before blocking on the target_wait_for_session_cmds

---

# ISA Drivers

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> The following text is adapted from the commit message of the initial commit of the ISA bus driver authored by Rene Herman.

<a id="rst-isa-drivers"></a>

The following text is adapted from the commit message of the initial commit of the ISA bus driver authored by Rene Herman.

During the recent "isa drivers using platform devices" discussion it was pointed out that (ALSA) ISA drivers ran into the problem of not having the option to fail driver load (device registration rather) upon not finding their hardware due to a probe() error not being passed up through the driver model. In the course of that, I suggested a separate ISA bus might be best; Russell King agreed and suggested this bus could use the .match() method for the actual device discovery.

The attached does this. For this old non (generically) discoverable ISA hardware only the driver itself can do discovery so as a difference with the platform_bus, this isa_bus also distributes match() up to the driver.

As another difference: these devices only exist in the driver model due to the driver creating them because it might want to drive them, meaning that all device creation has been made internal as well.

The usage model this provides is nice, and has been acked from the ALSA side by Takashi Iwai and Jaroslav Kysela. The ALSA driver module_init's now (for oldisa-only drivers) become:



```text
static int __init alsa_card_foo_init(void)
{
        return isa_register_driver(&snd_foo_isa_driver, SNDRV_CARDS);
}

static void __exit alsa_card_foo_exit(void)
{
        isa_unregister_driver(&snd_foo_isa_driver);
}
```

Quite like the other bus models therefore. This removes a lot of duplicated init code from the ALSA ISA drivers.

The passed in isa_driver struct is the regular driver struct embedding a struct device_driver, the normal probe/remove/shutdown/suspend/resume callbacks, and as indicated that .match callback.

The "SNDRV_CARDS" you see being passed in is a "unsigned int ndev" parameter, indicating how many devices to create and call our methods with.

The platform_driver callbacks are called with a platform_device param; the isa_driver callbacks are being called with a `struct device *dev, unsigned int id` pair directly -- with the device creation completely internal to the bus it's much cleaner to not leak isa_dev's by passing them in at all. The id is the only thing we ever want other then the struct device anyways, and it makes for nicer code in the callbacks as well.

With this additional .match() callback ISA drivers have all options. If ALSA would want to keep the old non-load behaviour, it could stick all of the old .probe in .match, which would only keep them registered after everything was found to be present and accounted for. If it wanted the behaviour of always loading as it inadvertently did for a bit after the changeover to platform devices, it could just not provide a .match() and do everything in .probe() as before.

If it, as Takashi Iwai already suggested earlier as a way of following the model from saner buses more closely, wants to load when a later bind could conceivably succeed, it could use .match() for the prerequisites (such as checking the user wants the card enabled and that port/irq/dma values have been passed in) and .probe() for everything else. This is the nicest model.

To the code...

This exports only two functions; isa\_\{,un\}register_driver().

isa_register_driver() register's the struct device_driver, and then loops over the passed in ndev creating devices and registering them. This causes the bus match method to be called for them, which is:



```text
int isa_bus_match(struct device *dev, struct device_driver *driver)
{
        struct isa_driver *isa_driver = to_isa_driver(driver);

        if (dev->platform_data == isa_driver) {
                if (!isa_driver->match ||
                        isa_driver->match(dev, to_isa_dev(dev)->id))
                        return 1;
                dev->platform_data = NULL;
        }
        return 0;
}
```

The first thing this does is check if this device is in fact one of this driver's devices by seeing if the device's platform_data pointer is set to this driver. Platform devices compare strings, but we don't need to do that with everything being internal, so isa_register_driver() abuses dev-&gt;platform_data as a isa_driver pointer which we can then check here. I believe platform_data is available for this, but if rather not, moving the isa_driver pointer to the private struct isa_dev is ofcourse fine as well.

Then, if the driver did not provide a .match, it matches. If it did, the driver match() method is called to determine a match.

If it did **not** match, dev-&gt;platform_data is reset to indicate this to isa_register_driver which can then unregister the device again.

If during all this, there's any error, or no devices matched at all everything is backed out again and the error, or -ENODEV, is returned.

isa_unregister_driver() just unregisters the matched devices and the driver itself.

module_isa_driver is a helper macro for ISA drivers which do not do anything special in module init/exit. This eliminates a lot of boilerplate code. Each module may only use this macro once, and calling it replaces module_init and module_exit.

max_num_isa_dev is a macro to determine the maximum possible number of ISA devices which may be registered in the I/O port address space given the address extent of the ISA devices.

---

# libATA Developer's Guide

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> libATA is a library used inside the Linux kernel to support ATA host controllers and devices. libATA provides an ATA driver API, class transports for ATA and ATAPI devices, and SCSI<->ATA translation for ATA devices according to the T10…

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

**Author:** Jeff Garzik

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

## Introduction

libATA is a library used inside the Linux kernel to support ATA host controllers and devices. libATA provides an ATA driver API, class transports for ATA and ATAPI devices, and SCSI&lt;-&gt;ATA translation for ATA devices according to the T10 SAT specification.

This Guide documents the libATA driver API, library functions, library internals, and a couple sample ATA low-level drivers.

<a id="rst-libata-driver-api"></a>

## libata Driver API

`struct ata_port_operations <ata_port_operations>` is defined for every low-level libata hardware driver, and it controls how the low-level driver interfaces with the ATA and SCSI layers.

FIS-based drivers will hook into the system with `->qc_prep()` and `->qc_issue()` high-level hooks. Hardware which behaves in a manner similar to PCI IDE hardware may utilize several generic helpers, defining at a bare minimum the bus I/O addresses of the ATA shadow register blocks.

<a id="rst-struct-ata-port-operations-ata-port-operations"></a>

### `struct ata_port_operations <ata_port_operations>`

<a id="rst-post-identify-device-configuration"></a>

#### Post-IDENTIFY device configuration



```text
void (*dev_config) (struct ata_port *, struct ata_device *);
```

Called after IDENTIFY \[PACKET\] DEVICE is issued to each device found. Typically used to apply device-specific fixups prior to issue of SET FEATURES - XFER MODE, and prior to operation.

This entry may be specified as NULL in ata_port_operations.

<a id="rst-set-pio-dma-mode"></a>

#### Set PIO/DMA mode



```text
void (*set_piomode) (struct ata_port *, struct ata_device *);
void (*set_dmamode) (struct ata_port *, struct ata_device *);
void (*post_set_mode) (struct ata_port *);
unsigned int (*mode_filter) (struct ata_port *, struct ata_device *, unsigned int);
```

Hooks called prior to the issue of SET FEATURES - XFER MODE command. The optional `->mode_filter()` hook is called when libata has built a mask of the possible modes. This is passed to the `->mode_filter()` function which should return a mask of valid modes after filtering those unsuitable due to hardware limits. It is not valid to use this interface to add modes.

`dev->pio_mode` and `dev->dma_mode` are guaranteed to be valid when `->set_piomode()` and when `->set_dmamode()` is called. The timings for any other drive sharing the cable will also be valid at this point. That is the library records the decisions for the modes of each drive on a channel before it attempts to set any of them.

`->post_set_mode()` is called unconditionally, after the SET FEATURES - XFER MODE command completes successfully.

`->set_piomode()` is always called (if present), but `->set_dma_mode()` is only called if DMA is possible.

<a id="rst-taskfile-read-write"></a>

#### Taskfile read/write



```text
void (*sff_tf_load) (struct ata_port *ap, struct ata_taskfile *tf);
void (*sff_tf_read) (struct ata_port *ap, struct ata_taskfile *tf);
```

`->tf_load()` is called to load the given taskfile into hardware registers / DMA buffers. `->tf_read()` is called to read the hardware registers / DMA buffers, to obtain the current set of taskfile register values. Most drivers for taskfile-based hardware (PIO or MMIO) use `ata_sff_tf_load()` and `ata_sff_tf_read()` for these hooks.

<a id="rst-pio-data-read-write"></a>

#### PIO data read/write



```text
void (*sff_data_xfer) (struct ata_device *, unsigned char *, unsigned int, int);
```

All bmdma-style drivers must implement this hook. This is the low-level operation that actually copies the data bytes during a PIO data transfer. Typically the driver will choose one of `ata_sff_data_xfer()`, or `ata_sff_data_xfer32()`.

<a id="rst-ata-command-execute"></a>

#### ATA command execute



```text
void (*sff_exec_command)(struct ata_port *ap, struct ata_taskfile *tf);
```

causes an ATA command, previously loaded with `->tf_load()`, to be initiated in hardware. Most drivers for taskfile-based hardware use `ata_sff_exec_command()` for this hook.

<a id="rst-per-cmd-atapi-dma-capabilities-filter"></a>

#### Per-cmd ATAPI DMA capabilities filter



```text
int (*check_atapi_dma) (struct ata_queued_cmd *qc);
```

Allow low-level driver to filter ATA PACKET commands, returning a status indicating whether or not it is OK to use DMA for the supplied PACKET command.

This hook may be specified as NULL, in which case libata will assume that atapi dma can be supported.

<a id="rst-read-specific-ata-shadow-registers"></a>

#### Read specific ATA shadow registers



```text
u8   (*sff_check_status)(struct ata_port *ap);
u8   (*sff_check_altstatus)(struct ata_port *ap);
```

Reads the Status/AltStatus ATA shadow register from hardware. On some hardware, reading the Status register has the side effect of clearing the interrupt condition. Most drivers for taskfile-based hardware use `ata_sff_check_status()` for this hook.

<a id="rst-write-specific-ata-shadow-register"></a>

#### Write specific ATA shadow register



```text
void (*sff_set_devctl)(struct ata_port *ap, u8 ctl);
```

Write the device control ATA shadow register to the hardware. Most drivers don't need to define this.

<a id="rst-select-ata-device-on-bus"></a>

#### Select ATA device on bus



```text
void (*sff_dev_select)(struct ata_port *ap, unsigned int device);
```

Issues the low-level hardware command(s) that causes one of N hardware devices to be considered 'selected' (active and available for use) on the ATA bus. This generally has no meaning on FIS-based devices.

Most drivers for taskfile-based hardware use `ata_sff_dev_select()` for this hook.

<a id="rst-private-tuning-method"></a>

#### Private tuning method



```text
void (*set_mode) (struct ata_port *ap);
```

By default libata performs drive and controller tuning in accordance with the ATA timing rules and also applies blacklists and cable limits. Some controllers need special handling and have custom tuning rules, typically raid controllers that use ATA commands but do not actually do drive timing.

> **Warning**
>
> This hook should not be used to replace the standard controller tuning logic when a controller has quirks. Replacing the default tuning logic in that case would bypass handling for drive and bridge quirks that may be important to data reliability. If a controller needs to filter the mode selection it should use the mode_filter hook instead.

<a id="rst-control-pci-ide-bmdma-engine"></a>

#### Control PCI IDE BMDMA engine



```text
void (*bmdma_setup) (struct ata_queued_cmd *qc);
void (*bmdma_start) (struct ata_queued_cmd *qc);
void (*bmdma_stop) (struct ata_port *ap);
u8   (*bmdma_status) (struct ata_port *ap);
```

When setting up an IDE BMDMA transaction, these hooks arm (`->bmdma_setup`), fire (`->bmdma_start`), and halt (`->bmdma_stop`) the hardware's DMA engine. `->bmdma_status` is used to read the standard PCI IDE DMA Status register.

These hooks are typically either no-ops, or simply not implemented, in FIS-based drivers.

Most legacy IDE drivers use `ata_bmdma_setup()` for the `bmdma_setup()` hook. `ata_bmdma_setup()` will write the pointer to the PRD table to the IDE PRD Table Address register, enable DMA in the DMA Command register, and call `exec_command()` to begin the transfer.

Most legacy IDE drivers use `ata_bmdma_start()` for the `bmdma_start()` hook. `ata_bmdma_start()` will write the ATA_DMA_START flag to the DMA Command register.

Many legacy IDE drivers use `ata_bmdma_stop()` for the `bmdma_stop()` hook. `ata_bmdma_stop()` clears the ATA_DMA_START flag in the DMA command register.

Many legacy IDE drivers use `ata_bmdma_status()` as the `bmdma_status()` hook.

<a id="rst-high-level-taskfile-hooks"></a>

#### High-level taskfile hooks



```text
enum ata_completion_errors (*qc_prep) (struct ata_queued_cmd *qc);
int (*qc_issue) (struct ata_queued_cmd *qc);
```

Higher-level hooks, these two hooks can potentially supersede several of the above taskfile/DMA engine hooks. `->qc_prep` is called after the buffers have been DMA-mapped, and is typically used to populate the hardware's DMA scatter-gather table. Some drivers use the standard `ata_bmdma_qc_prep()` and `ata_bmdma_dumb_qc_prep()` helper functions, but more advanced drivers roll their own.

`->qc_issue` is used to make a command active, once the hardware and S/G tables have been prepared. IDE BMDMA drivers use the helper function `ata_sff_qc_issue()` for taskfile protocol-based dispatch. More advanced drivers implement their own `->qc_issue`.

`ata_sff_qc_issue()` calls `->sff_tf_load()`, `->bmdma_setup()`, and `->bmdma_start()` as necessary to initiate a transfer.

<a id="rst-exception-and-probe-handling-eh"></a>

#### Exception and probe handling (EH)



```text
void (*freeze) (struct ata_port *ap);
void (*thaw) (struct ata_port *ap);
```

`ata_port_freeze()` is called when HSM violations or some other condition disrupts normal operation of the port. A frozen port is not allowed to perform any operation until the port is thawed, which usually follows a successful reset.

The optional `->freeze()` callback can be used for freezing the port hardware-wise (e.g. mask interrupt and stop DMA engine). If a port cannot be frozen hardware-wise, the interrupt handler must ack and clear interrupts unconditionally while the port is frozen.

The optional `->thaw()` callback is called to perform the opposite of `->freeze()`: prepare the port for normal operation once again. Unmask interrupts, start DMA engine, etc.



```text
void (*error_handler) (struct ata_port *ap);
```

`->error_handler()` is a driver's hook into probe, hotplug, and recovery and other exceptional conditions. The primary responsibility of an implementation is to call `ata_std_error_handler()`.

`ata_std_error_handler()` will perform a standard error handling sequence to resurect failed devices, detach lost devices and add new devices (if any). This function will call the various reset operations for a port, as needed. These operations are as follows.

- The 'prereset' operation (which may be NULL) is called during an EH reset, before any other action is taken.

- The 'postreset' hook (which may be NULL) is called after the EH reset is performed. Based on existing conditions, severity of the problem, and hardware capabilities,

- Either the 'softreset' operation or the 'hardreset' operation will be called to perform the low-level EH reset. If both operations are defined, 'hardreset' is preferred and used. If both are not defined, no low-level reset is performed and EH assumes that an ATA class device is connected through the link.



```text
void (*post_internal_cmd) (struct ata_queued_cmd *qc);
```

Perform any hardware-specific actions necessary to finish processing after executing a probe-time or EH-time command via `ata_exec_internal()`.

<a id="rst-hardware-interrupt-handling"></a>

#### Hardware interrupt handling



```text
irqreturn_t (*irq_handler)(int, void *, struct pt_regs *);
void (*irq_clear) (struct ata_port *);
```

`->irq_handler` is the interrupt handling routine registered with the system, by libata. `->irq_clear` is called during probe just before the interrupt handler is registered, to be sure hardware is quiet.

The second argument, dev_instance, should be cast to a pointer to `struct ata_host_set <ata_host_set>`.

Most legacy IDE drivers use `ata_sff_interrupt()` for the irq_handler hook, which scans all ports in the host_set, determines which queued command was active (if any), and calls ata_sff_host_intr(ap,qc).

Most legacy IDE drivers use `ata_sff_irq_clear()` for the `irq_clear()` hook, which simply clears the interrupt and error flags in the DMA status register.

<a id="rst-sata-phy-read-write"></a>

#### SATA phy read/write



```text
int (*scr_read) (struct ata_port *ap, unsigned int sc_reg,
         u32 *val);
int (*scr_write) (struct ata_port *ap, unsigned int sc_reg,
                   u32 val);
```

Read and write standard SATA phy registers. sc_reg is one of SCR_STATUS, SCR_CONTROL, SCR_ERROR, or SCR_ACTIVE.

<a id="rst-init-and-shutdown"></a>

#### Init and shutdown



```text
int (*port_start) (struct ata_port *ap);
void (*port_stop) (struct ata_port *ap);
void (*host_stop) (struct ata_host_set *host_set);
```

`->port_start()` is called just after the data structures for each port are initialized. Typically this is used to alloc per-port DMA buffers / tables / rings, enable DMA engines, and similar tasks. Some drivers also use this entry point as a chance to allocate driver-private memory for `ap->private_data`.

Many drivers use `ata_port_start()` as this hook or call it from their own `port_start()` hooks. `ata_port_start()` allocates space for a legacy IDE PRD table and returns.

`->port_stop()` is called after `->host_stop()`. Its sole function is to release DMA/memory resources, now that they are no longer actively being used. Many drivers also free driver-private data from port at this time.

`->host_stop()` is called after all `->port_stop()` calls have completed. The hook must finalize hardware shutdown, release DMA and other resources, etc. This hook may be specified as NULL, in which case it is not called.

<a id="rst-error-handling"></a>

## Error handling

This chapter describes how errors are handled under libata. Readers are advised to read SCSI EH ([Documentation/scsi/scsi_eh.rst](/kernel/hardware/scsi/scsi-eh.md)) and ATA exceptions doc first.

<a id="rst-origins-of-commands"></a>

### Origins of commands

In libata, a command is represented with `struct ata_queued_cmd <ata_queued_cmd>` or qc. qc's are preallocated during port initialization and repetitively used for command executions. Currently only one qc is allocated per port but yet-to-be-merged NCQ branch allocates one for each tag and maps each qc to NCQ tag 1-to-1.

libata commands can originate from two sources - libata itself and SCSI midlayer. libata internal commands are used for initialization and error handling. All normal blk requests and commands for SCSI emulation are passed as SCSI commands through queuecommand callback of SCSI host template.

<a id="rst-how-commands-are-issued"></a>

### How commands are issued

- **Internal commands**

  Once allocated qc's taskfile is initialized for the command to be executed. qc currently has two mechanisms to notify completion. One is via `qc->complete_fn()` callback and the other is completion `qc->waiting`. `qc->complete_fn()` callback is the asynchronous path used by normal SCSI translated commands and `qc->waiting` is the synchronous (issuer sleeps in process context) path used by internal commands.

  Once initialization is complete, host_set lock is acquired and the qc is issued.

- **SCSI commands**

  All libata drivers use `ata_scsi_queuecmd()` as `hostt->queuecommand` callback. scmds can either be simulated or translated. No qc is involved in processing a simulated scmd. The result is computed right away and the scmd is completed.

  `qc->complete_fn()` callback is used for completion notification. ATA commands use `ata_scsi_qc_complete()` while ATAPI commands use `atapi_qc_complete()`. Both functions end up calling `qc->scsidone` to notify upper layer when the qc is finished. After translation is completed, the qc is issued with `ata_qc_issue()`.

  Note that SCSI midlayer invokes hostt-&gt;queuecommand while holding host_set lock, so all above occur while holding host_set lock.

<a id="rst-how-commands-are-processed"></a>

### How commands are processed

Depending on which protocol and which controller are used, commands are processed differently. For the purpose of discussion, a controller which uses taskfile interface and all standard callbacks is assumed.

Currently 6 ATA command protocols are used. They can be sorted into the following four categories according to how they are processed.

- **ATA NO DATA or DMA**

  ATA_PROT_NODATA and ATA_PROT_DMA fall into this category. These types of commands don't require any software intervention once issued. Device will raise interrupt on completion.

- **ATA PIO**

  ATA_PROT_PIO is in this category. libata currently implements PIO with polling. ATA_NIEN bit is set to turn off interrupt and pio_task on ata_wq performs polling and IO.

- **ATAPI NODATA or DMA**

  ATA_PROT_ATAPI_NODATA and ATA_PROT_ATAPI_DMA are in this category. packet_task is used to poll BSY bit after issuing PACKET command. Once BSY is turned off by the device, packet_task transfers CDB and hands off processing to interrupt handler.

- **ATAPI PIO**

  ATA_PROT_ATAPI is in this category. ATA_NIEN bit is set and, as in ATAPI NODATA or DMA, packet_task submits cdb. However, after submitting cdb, further processing (data transfer) is handed off to pio_task.

<a id="rst-how-commands-are-completed"></a>

### How commands are completed

Once issued, all qc's are either completed with `ata_qc_complete()` or time out. For commands which are handled by interrupts, `ata_host_intr()` invokes `ata_qc_complete()`, and, for PIO tasks, pio_task invokes `ata_qc_complete()`. In error cases, packet_task may also complete commands.

`ata_qc_complete()` does the following.

1. DMA memory is unmapped.

2. ATA_QCFLAG_ACTIVE is cleared from qc-&gt;flags.

3. `qc->complete_fn` callback is invoked. If the return value of the callback is not zero. Completion is short circuited and `ata_qc_complete()` returns.

4. `__ata_qc_complete()` is called, which does

   1. `qc->flags` is cleared to zero.

   2. `ap->active_tag` and `qc->tag` are poisoned.

   3. `qc->waiting` is cleared &amp; completed (in that order).

   4. qc is deallocated by clearing appropriate bit in `ap->qactive`.

So, it basically notifies upper layer and deallocates qc. One exception is short-circuit path in \#3 which is used by `atapi_qc_complete()`.

For all non-ATAPI commands, whether it fails or not, almost the same code path is taken and very little error handling takes place. A qc is completed with success status if it succeeded, with failed status otherwise.

However, failed ATAPI commands require more handling as REQUEST SENSE is needed to acquire sense data. If an ATAPI command fails, `ata_qc_complete()` is invoked with error status, which in turn invokes `atapi_qc_complete()` via `qc->complete_fn()` callback.

This makes `atapi_qc_complete()` set `scmd->result` to SAM_STAT_CHECK_CONDITION, complete the scmd and return 1. As the sense data is empty but `scmd->result` is CHECK CONDITION, SCSI midlayer will invoke EH for the scmd, and returning 1 makes `ata_qc_complete()` to return without deallocating the qc. This leads us to `ata_scsi_error()` with partially completed qc.

<a id="rst-ata-scsi-error"></a>

### `ata_scsi_error()`

`ata_scsi_error()` is the current `transportt->eh_strategy_handler()` for libata. As discussed above, this will be entered in two cases - timeout and ATAPI error completion. This function will check if a qc is active and has not failed yet. Such a qc will be marked with AC_ERR_TIMEOUT such that EH will know to handle it later. Then it calls low level libata driver's `error_handler()` callback.

When the `error_handler()` callback is invoked it stops BMDMA and completes the qc. Note that as we're currently in EH, we cannot call scsi_done. As described in SCSI EH doc, a recovered scmd should be either retried with `scsi_queue_insert()` or finished with `scsi_finish_command()`. Here, we override `qc->scsidone` with `scsi_finish_command()` and calls `ata_qc_complete()`.

If EH is invoked due to a failed ATAPI qc, the qc here is completed but not deallocated. The purpose of this half-completion is to use the qc as place holder to make EH code reach this place. This is a bit hackish, but it works.

Once control reaches here, the qc is deallocated by invoking `__ata_qc_complete()` explicitly. Then, internal qc for REQUEST SENSE is issued. Once sense data is acquired, scmd is finished by directly invoking `scsi_finish_command()` on the scmd. Note that as we already have completed and deallocated the qc which was associated with the scmd, we don't need to/cannot call `ata_qc_complete()` again.

<a id="rst-problems-with-the-current-eh"></a>

### Problems with the current EH

- Error representation is too crude. Currently any and all error conditions are represented with ATA STATUS and ERROR registers. Errors which aren't ATA device errors are treated as ATA device errors by setting ATA_ERR bit. Better error descriptor which can properly represent ATA and other errors/exceptions is needed.

- When handling timeouts, no action is taken to make device forget about the timed out command and ready for new commands.

- EH handling via `ata_scsi_error()` is not properly protected from usual command processing. On EH entrance, the device is not in quiescent state. Timed out commands may succeed or fail any time. pio_task and atapi_task may still be running.

- Too weak error recovery. Devices / controllers causing HSM mismatch errors and other errors quite often require reset to return to known state. Also, advanced error handling is necessary to support features like NCQ and hotplug.

- ATA errors are directly handled in the interrupt handler and PIO errors in pio_task. This is problematic for advanced error handling for the following reasons.

  First, advanced error handling often requires context and internal qc execution.

  Second, even a simple failure (say, CRC error) needs information gathering and could trigger complex error handling (say, resetting &amp; reconfiguring). Having multiple code paths to gather information, enter EH and trigger actions makes life painful.

  Third, scattered EH code makes implementing low level drivers difficult. Low level drivers override libata callbacks. If EH is scattered over several places, each affected callbacks should perform its part of error handling. This can be error prone and painful.

<a id="rst-libata-library"></a>

## libata Library


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

```c
struct ata_link * ata_link_next(struct ata_link *link, struct ata_port *ap, enum ata_link_iter_mode mode)
```

link iteration helper

**Parameters**

- `struct ata_link *link`: the previous link, NULL to start
- `struct ata_port *ap`: ATA port containing links to iterate
- `enum ata_link_iter_mode mode`: iteration mode, one of ATA_LITER_*

**Description**

LOCKING:
Host lock or EH context.

**Return**

Pointer to the next link.

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

```c
struct ata_device * ata_dev_next(struct ata_device *dev, struct ata_link *link, enum ata_dev_iter_mode mode)
```

device iteration helper

**Parameters**

- `struct ata_device *dev`: the previous device, NULL to start
- `struct ata_link *link`: ATA link containing devices to iterate
- `enum ata_dev_iter_mode mode`: iteration mode, one of ATA_DITER_*

**Description**

LOCKING:
Host lock or EH context.

**Return**

Pointer to the next device.

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

```c
int atapi_cmd_type(u8 opcode)
```

Determine ATAPI command type from SCSI opcode

**Parameters**

- `u8 opcode`: SCSI opcode

**Description**

Determine ATAPI command type from **opcode**.

LOCKING:
None.

**Return**

ATAPI_{READ|WRITE|READ_CD|PASS_THRU|MISC}

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

```c
unsigned int ata_pack_xfermask(unsigned int pio_mask, unsigned int mwdma_mask, unsigned int udma_mask)
```

Pack pio, mwdma and udma masks into xfer_mask

**Parameters**

- `unsigned int pio_mask`: pio_mask
- `unsigned int mwdma_mask`: mwdma_mask
- `unsigned int udma_mask`: udma_mask

**Description**

Pack **pio_mask**, **mwdma_mask** and **udma_mask** into a single
unsigned int xfer_mask.

LOCKING:
None.

**Return**

Packed xfer_mask.

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

```c
u8 ata_xfer_mask2mode(unsigned int xfer_mask)
```

Find matching XFER_* for the given xfer_mask

**Parameters**

- `unsigned int xfer_mask`: xfer_mask of interest

**Description**

Return matching XFER_* value for **xfer_mask**.  Only the highest
bit of **xfer_mask** is considered.

LOCKING:
None.

**Return**

Matching XFER_* value, 0xff if no match found.

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

```c
unsigned int ata_xfer_mode2mask(u8 xfer_mode)
```

Find matching xfer_mask for XFER_*

**Parameters**

- `u8 xfer_mode`: XFER_* of interest

**Description**

Return matching xfer_mask for **xfer_mode**.

LOCKING:
None.

**Return**

Matching xfer_mask, 0 if no match found.

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

```c
int ata_xfer_mode2shift(u8 xfer_mode)
```

Find matching xfer_shift for XFER_*

**Parameters**

- `u8 xfer_mode`: XFER_* of interest

**Description**

Return matching xfer_shift for **xfer_mode**.

LOCKING:
None.

**Return**

Matching xfer_shift, -1 if no match found.

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

```c
const char * ata_mode_string(unsigned int xfer_mask)
```

convert xfer_mask to string

**Parameters**

- `unsigned int xfer_mask`: mask of bits supported; only highest bit counts.

**Description**

Determine string which represents the highest speed
(highest bit in **modemask**).

LOCKING:
None.

**Return**

Constant C string representing highest speed listed in
**mode_mask**, or the constant C string "\<n/a>".

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

```c
unsigned int ata_dev_classify(const struct ata_taskfile *tf)
```

determine device type based on ATA-spec signature

**Parameters**

- `const struct ata_taskfile *tf`: ATA taskfile register set for device to be identified

**Description**

Determine from taskfile register contents whether a device is
ATA or ATAPI, as per "Signature and persistence" section
of ATA/PI spec (volume 1, sect 5.14).

LOCKING:
None.

**Return**

Device type, `ATA_DEV_ATA`, `ATA_DEV_ATAPI`, `ATA_DEV_PMP`,
`ATA_DEV_ZAC`, or `ATA_DEV_UNKNOWN` the event of failure.

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

```c
void ata_id_string(const u16 *id, unsigned char *s, unsigned int ofs, unsigned int len)
```

Convert IDENTIFY DEVICE page into string

**Parameters**

- `const u16 *id`: IDENTIFY DEVICE results we will examine
- `unsigned char *s`: string into which data is output
- `unsigned int ofs`: offset into identify device page
- `unsigned int len`: length of string to return. must be an even number.

**Description**

The strings in the IDENTIFY DEVICE page are broken up into
16-bit chunks.  Run through the string, and output each
8-bit chunk linearly, regardless of platform.

LOCKING:
caller.

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

```c
void ata_id_c_string(const u16 *id, unsigned char *s, unsigned int ofs, unsigned int len)
```

Convert IDENTIFY DEVICE page into C string

**Parameters**

- `const u16 *id`: IDENTIFY DEVICE results we will examine
- `unsigned char *s`: string into which data is output
- `unsigned int ofs`: offset into identify device page
- `unsigned int len`: length of string to return. must be an odd number.

**Description**

This function is identical to ata_id_string except that it
trims trailing spaces and terminates the resulting string with
null.  **len** must be actual maximum length (even number) + 1.

LOCKING:
caller.

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

```c
unsigned int ata_id_xfermask(const u16 *id)
```

Compute xfermask from the given IDENTIFY data

**Parameters**

- `const u16 *id`: IDENTIFY data to compute xfer mask from

**Description**

Compute the xfermask for this device. This is not as trivial
as it seems if we must consider early devices correctly.

FIXME: pre IDE drive timing (do we care ?).

LOCKING:
None.

**Return**

Computed xfermask

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

```c
unsigned int ata_pio_need_iordy(const struct ata_device *adev)
```

check if iordy needed

**Parameters**

- `const struct ata_device *adev`: ATA device

**Description**

Check if the current speed of the device requires IORDY. Used
by various controllers for chip configuration.

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

```c
unsigned int ata_do_dev_read_id(struct ata_device *dev, struct ata_taskfile *tf, __le16 *id)
```

default ID read method

**Parameters**

- `struct ata_device *dev`: device
- `struct ata_taskfile *tf`: proposed taskfile
- `__le16 *id`: data buffer

**Description**

Issue the identify taskfile and hand back the buffer containing
identify data. For some RAID controllers and for pre ATA devices
this function is wrapped or replaced by the driver

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

```c
int ata_cable_40wire(struct ata_port *ap)
```

return 40 wire cable type

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which want to hardwire 40 wire cable
detection.

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

```c
int ata_cable_80wire(struct ata_port *ap)
```

return 80 wire cable type

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which want to hardwire 80 wire cable
detection.

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

```c
int ata_cable_unknown(struct ata_port *ap)
```

return unknown PATA cable.

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which have no PATA cable detection.

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

```c
int ata_cable_ignore(struct ata_port *ap)
```

return ignored PATA cable.

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which don't use cable type to limit
transfer mode.

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

```c
int ata_cable_sata(struct ata_port *ap)
```

return SATA cable type

**Parameters**

- `struct ata_port *ap`: port

**Description**

Helper method for drivers which have SATA cables

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

```c
struct ata_device * ata_dev_pair(struct ata_device *adev)
```

return other device on cable

**Parameters**

- `struct ata_device *adev`: device

**Description**

Obtain the other device on the same cable, or if none is
present NULL is returned

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

```c
int ata_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
```

Program timings and issue SET FEATURES - XFER

**Parameters**

- `struct ata_link *link`: link on which timings will be programmed
- `struct ata_device **r_failed_dev`: out parameter for failed device

**Description**

Standard implementation of the function used to tune and set
ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
`ata_dev_set_mode()` fails, pointer to the failing device is
returned in **r_failed_dev**.

LOCKING:
PCI/etc. bus probe sem.

**Return**

0 on success, negative errno otherwise

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

```c
int ata_wait_after_reset(struct ata_link *link, unsigned long deadline, int (*check_ready)(struct ata_link *link))
```

wait for link to become ready after reset

**Parameters**

- `struct ata_link *link`: link to be waited on
- `unsigned long deadline`: deadline jiffies for the operation
- `int (*check_ready)(struct ata_link *link)`: callback to check link readiness

**Description**

Wait for **link** to become ready after reset.

LOCKING:
EH context.

**Return**

0 if **link** is ready before **deadline**; otherwise, -errno.

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

```c
int ata_std_prereset(struct ata_link *link, unsigned long deadline)
```

prepare for reset

**Parameters**

- `struct ata_link *link`: ATA link to be reset
- `unsigned long deadline`: deadline jiffies for the operation

**Description**

**link** is about to be reset.  Initialize it.  Failure from
prereset makes libata abort whole reset sequence and give up
that port, so prereset should be best-effort.  It does its
best to prepare for reset sequence but if things go wrong, it
should just whine, not fail.

LOCKING:
Kernel thread context (may sleep)

**Return**

Always 0.

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

```c
void ata_std_postreset(struct ata_link *link, unsigned int *classes)
```

standard postreset callback

**Parameters**

- `struct ata_link *link`: the target ata_link
- `unsigned int *classes`: classes of attached devices

**Description**

This function is invoked after a successful reset.  Note that
the device might have been reset more than once using
different reset methods before postreset is invoked.

LOCKING:
Kernel thread context (may sleep)

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

```c
unsigned int ata_dev_set_feature(struct ata_device *dev, u8 subcmd, u8 action)
```

Issue SET FEATURES

**Parameters**

- `struct ata_device *dev`: Device to which command will be sent
- `u8 subcmd`: The SET FEATURES subcommand to be sent
- `u8 action`: The sector count represents a subcommand specific action

**Description**

Issue SET FEATURES command to device **dev** on port **ap** with sector count

LOCKING:
PCI/etc. bus probe sem.

**Return**

0 on success, AC_ERR_* mask otherwise.

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

```c
int ata_std_qc_defer(struct ata_queued_cmd *qc)
```

Check whether a qc needs to be deferred

**Parameters**

- `struct ata_queued_cmd *qc`: ATA command in question

**Description**

Non-NCQ commands cannot run with any other command, NCQ or
not.  As upper layer only knows the queue depth, we are
responsible for maintaining exclusion.  This function checks
whether a new command **qc** can be issued.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

ATA_DEFER_* if deferring is needed, 0 otherwise.

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

```c
void ata_qc_complete(struct ata_queued_cmd *qc)
```

Complete an active ATA command

**Parameters**

- `struct ata_queued_cmd *qc`: Command to complete

**Description**

Indicate to the mid and upper layers that an ATA command has
completed, with either an ok or not-ok status.

Refrain from calling this function multiple times when
successfully completing multiple NCQ commands.
`ata_qc_complete_multiple()` should be used instead, which will
properly update IRQ expect state.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
u64 ata_qc_get_active(struct ata_port *ap)
```

get bitmask of active qcs

**Parameters**

- `struct ata_port *ap`: port in question

**Description**

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Bitmask of active qcs

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

```c
bool ata_link_online(struct ata_link *link)
```

test whether the given link is online

**Parameters**

- `struct ata_link *link`: ATA link to test

**Description**

Test whether **link** is online.  This is identical to
[`ata_phys_link_online()`](#c-ata_phys_link_online) when there's no slave link.  When
there's a slave link, this function should only be called on
the master link and will return true if any of M/S links is
online.

LOCKING:
None.

**Return**

True if the port online status is available and online.

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

```c
bool ata_link_offline(struct ata_link *link)
```

test whether the given link is offline

**Parameters**

- `struct ata_link *link`: ATA link to test

**Description**

Test whether **link** is offline.  This is identical to
[`ata_phys_link_offline()`](#c-ata_phys_link_offline) when there's no slave link.  When
there's a slave link, this function should only be called on
the master link and will return true if both M/S links are
offline.

LOCKING:
None.

**Return**

True if the port offline status is available and offline.

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

```c
void ata_host_suspend(struct ata_host *host, pm_message_t mesg)
```

suspend host

**Parameters**

- `struct ata_host *host`: host to suspend
- `pm_message_t mesg`: PM message

**Description**

Suspend **host**.  Actual operation is performed by port suspend.

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

```c
void ata_host_resume(struct ata_host *host)
```

resume host

**Parameters**

- `struct ata_host *host`: host to resume

**Description**

Resume **host**.  Actual operation is performed by port resume.

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

```c
struct ata_port * ata_port_alloc(struct ata_host *host)
```

allocate and initialize basic ATA port resources

**Parameters**

- `struct ata_host *host`: ATA host this allocated port belongs to

**Description**

Allocate and initialize basic ATA port resources.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

Allocate ATA port on success, NULL on failure.

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

```c
struct ata_host * ata_host_alloc(struct device *dev, int n_ports)
```

allocate and init basic ATA host resources

**Parameters**

- `struct device *dev`: generic device this host is associated with
- `int n_ports`: the number of ATA ports associated with this host

**Description**

Allocate and initialize basic ATA host resources.  LLD calls
this function to allocate a host, initializes it fully and
attaches it using [`ata_host_register()`](#c-ata_host_register).

LOCKING:
Inherited from calling layer (may sleep).

**Return**

Allocate ATA host on success, NULL on failure.

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

```c
struct ata_host * ata_host_alloc_pinfo(struct device *dev, const struct ata_port_info * const * ppi, int n_ports)
```

alloc host and init with port_info array

**Parameters**

- `struct device *dev`: generic device this host is associated with
- `const struct ata_port_info * const * ppi`: array of ATA port_info to initialize host with
- `int n_ports`: number of ATA ports attached to this host

**Description**

Allocate ATA host and initialize with info from **ppi**.  If NULL
terminated, **ppi** may contain fewer entries than **n_ports**.  The
last entry will be used for the remaining ports.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

Allocate ATA host on success, NULL on failure.

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

```c
int ata_host_start(struct ata_host *host)
```

start and freeze ports of an ATA host

**Parameters**

- `struct ata_host *host`: ATA host to start ports for

**Description**

Start and then freeze ports of **host**.  Started status is
recorded in host->flags, so this function can be called
multiple times.  Ports are guaranteed to get started only
once.  If host->ops is not initialized yet, it is set to the
first non-dummy port ops.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

0 if all ports are started successfully, -errno otherwise.

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

```c
void ata_host_init(struct ata_host *host, struct device *dev, struct ata_port_operations *ops)
```

Initialize a host struct for sas (ipr, libsas)

**Parameters**

- `struct ata_host *host`: host to initialize
- `struct device *dev`: device host is attached to
- `struct ata_port_operations *ops`: port_ops

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

```c
int ata_host_register(struct ata_host *host, const struct scsi_host_template *sht)
```

register initialized ATA host

**Parameters**

- `struct ata_host *host`: ATA host to register
- `const struct scsi_host_template *sht`: template for SCSI host

**Description**

Register initialized ATA host.  **host** is allocated using
[`ata_host_alloc()`](#c-ata_host_alloc) and fully initialized by LLD.  This function
starts ports, registers **host** with ATA and SCSI layers and
probe registered devices.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

0 on success, -errno otherwise.

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

```c
int ata_host_activate(struct ata_host *host, int irq, irq_handler_t irq_handler, unsigned long irq_flags, const struct scsi_host_template *sht)
```

start host, request IRQ and register it

**Parameters**

- `struct ata_host *host`: target ATA host
- `int irq`: IRQ to request
- `irq_handler_t irq_handler`: irq_handler used when requesting IRQ
- `unsigned long irq_flags`: irq_flags used when requesting IRQ
- `const struct scsi_host_template *sht`: scsi_host_template to use when registering the host

**Description**

After allocating an ATA host and initializing it, most libata
LLDs perform three steps to activate the host - start host,
request IRQ and register it.  This helper takes necessary
arguments and performs the three steps in one go.

An invalid IRQ skips the IRQ registration and expects the host to
have set polling mode on the port. In this case, **irq_handler**
should be NULL.

LOCKING:
Inherited from calling layer (may sleep).

**Return**

0 on success, -errno otherwise.

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

```c
void ata_host_detach(struct ata_host *host)
```

Detach all ports of an ATA host

**Parameters**

- `struct ata_host *host`: Host to detach

**Description**

Detach all ports of **host**.

LOCKING:
Kernel thread context (may sleep).

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

```c
void ata_pci_remove_one(struct pci_dev *pdev)
```

PCI layer callback for device removal

**Parameters**

- `struct pci_dev *pdev`: PCI device that was removed

**Description**

PCI layer indicates to libata via this hook that hot-unplug or
module unload event has occurred.  Detach all ports.  Resource
release is handled via devres.

LOCKING:
Inherited from PCI layer (may sleep).

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

```c
void ata_platform_remove_one(struct platform_device *pdev)
```

Platform layer callback for device removal

**Parameters**

- `struct platform_device *pdev`: Platform device that was removed

**Description**

Platform layer indicates to libata via this hook that hot-unplug or
module unload event has occurred.  Detach all ports.  Resource
release is handled via devres.

LOCKING:
Inherited from platform layer (may sleep).

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

```c
void ata_msleep(struct ata_port *ap, unsigned int msecs)
```

ATA EH owner aware msleep

**Parameters**

- `struct ata_port *ap`: ATA port to attribute the sleep to
- `unsigned int msecs`: duration to sleep in milliseconds

**Description**

Sleeps **msecs**.  If the current task is owner of **ap**'s EH, the
ownership is released before going to sleep and reacquired
after the sleep is complete.  IOW, other ports sharing the
**ap->host** will be allowed to own the EH while this task is
sleeping.

LOCKING:
Might sleep.

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

```c
u32 ata_wait_register(struct ata_port *ap, void __iomem *reg, u32 mask, u32 val, unsigned int interval, unsigned int timeout)
```

wait until register value changes

**Parameters**

- `struct ata_port *ap`: ATA port to wait register for, can be NULL
- `void __iomem *reg`: IO-mapped register
- `u32 mask`: Mask to apply to read register value
- `u32 val`: Wait condition
- `unsigned int interval`: polling interval in milliseconds
- `unsigned int timeout`: timeout in milliseconds

**Description**

Waiting for some bits of register to change is a common
operation for ATA controllers.  This function reads 32bit LE
IO-mapped register **reg** and tests for the following condition.

(**\*reg** & mask) != val

If the condition is met, it returns; otherwise, the process is
repeated after **interval_msec** until timeout.

LOCKING:
Kernel thread context (may sleep)

**Return**

The final register value.


<a id="rst-libata-core-internals"></a>

## libata Core Internals


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

```c
struct ata_link * ata_dev_phys_link(struct ata_device *dev)
```

find physical link for a device

**Parameters**

- `struct ata_device *dev`: ATA device to look up physical link for

**Description**

Look up physical link which **dev** is attached to.  Note that
this is different from **dev->link** only when **dev** is on slave
link.  For all other cases, it's the same as **dev->link**.

LOCKING:
Don't care.

**Return**

Pointer to the found physical link.

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

```c
void ata_force_cbl(struct ata_port *ap)
```

force cable type according to libata.force

**Parameters**

- `struct ata_port *ap`: ATA port of interest

**Description**

Force cable type according to libata.force and whine about it.
The last entry which has matching port number is used, so it
can be specified as part of device force parameters.  For
example, both "a:40c,1.00:udma4" and "1.00:40c,udma4" have the
same effect.

LOCKING:
EH context.

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

```c
void ata_force_pflags(struct ata_port *ap)
```

force port flags according to libata.force

**Parameters**

- `struct ata_port *ap`: ATA port of interest

**Description**

Force port flags according to libata.force and whine about it.

LOCKING:
EH context.

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

```c
void ata_force_link_limits(struct ata_link *link)
```

force link limits according to libata.force

**Parameters**

- `struct ata_link *link`: ATA link of interest

**Description**

Force link flags and SATA spd limit according to libata.force
and whine about it.  When only the port part is specified
(e.g. 1:), the limit applies to all links connected to both
the host link and all fan-out ports connected via PMP.  If the
device part is specified as 0 (e.g. 1.00:), it specifies the
first fan-out link not the host link.  Device number 15 always
points to the host link whether PMP is attached or not.  If the
controller has slave link, device number 16 points to it.

LOCKING:
EH context.

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

```c
void ata_force_xfermask(struct ata_device *dev)
```

force xfermask according to libata.force

**Parameters**

- `struct ata_device *dev`: ATA device of interest

**Description**

Force xfer_mask according to libata.force and whine about it.
For consistency with link selection, device number 15 selects
the first device connected to the host link.

LOCKING:
EH context.

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

```c
void ata_force_quirks(struct ata_device *dev)
```

force quirks according to libata.force

**Parameters**

- `struct ata_device *dev`: ATA device of interest

**Description**

Force quirks according to libata.force and whine about it.
For consistency with link selection, device number 15 selects
the first device connected to the host link.

LOCKING:
EH context.

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

```c
bool ata_set_rwcmd_protocol(struct ata_device *dev, struct ata_taskfile *tf)
```

set taskfile r/w command and protocol

**Parameters**

- `struct ata_device *dev`: target device for the taskfile
- `struct ata_taskfile *tf`: taskfile to examine and configure

**Description**

Examine the device configuration and tf->flags to determine
the proper read/write command and protocol to use for **tf**.

LOCKING:
caller.

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

```c
u64 ata_tf_read_block(const struct ata_taskfile *tf, struct ata_device *dev)
```

Read block address from ATA taskfile

**Parameters**

- `const struct ata_taskfile *tf`: ATA taskfile of interest
- `struct ata_device *dev`: ATA device **tf** belongs to

**Description**

LOCKING:
None.

Read block address from **tf**.  This function can handle all
three address formats - LBA, LBA48 and CHS.  tf->protocol and
flags select the address format to use.

**Return**

Block address read from **tf**.

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

```c
int ata_build_rw_tf(struct ata_queued_cmd *qc, u64 block, u32 n_block, unsigned int tf_flags, int cdl, int class)
```

Build ATA taskfile for given read/write request

**Parameters**

- `struct ata_queued_cmd *qc`: Metadata associated with the taskfile to build
- `u64 block`: Block address
- `u32 n_block`: Number of blocks
- `unsigned int tf_flags`: RW/FUA etc...
- `int cdl`: Command duration limit index
- `int class`: IO priority class

**Description**

LOCKING:
None.

Build ATA taskfile for the command **qc** for read/write request described
by **block**, **n_block**, **tf_flags** and **class**.

0 on success, -ERANGE if the request is too large for **dev**,
-EINVAL if the request is invalid.

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

```c
void ata_unpack_xfermask(unsigned int xfer_mask, unsigned int *pio_mask, unsigned int *mwdma_mask, unsigned int *udma_mask)
```

Unpack xfer_mask into pio, mwdma and udma masks

**Parameters**

- `unsigned int xfer_mask`: xfer_mask to unpack
- `unsigned int *pio_mask`: resulting pio_mask
- `unsigned int *mwdma_mask`: resulting mwdma_mask
- `unsigned int *udma_mask`: resulting udma_mask

**Description**

Unpack **xfer_mask** into **pio_mask**, **mwdma_mask** and **udma_mask**.
Any NULL destination masks will be ignored.

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

```c
int ata_read_native_max_address(struct ata_device *dev, u64 *max_sectors)
```

Read native max address

**Parameters**

- `struct ata_device *dev`: target device
- `u64 *max_sectors`: out parameter for the result native max address

**Description**

Perform an LBA48 or LBA28 native size query upon the device in
question.

**Return**

0 on success, -EACCES if command is aborted by the drive.
-EIO on other errors.

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

```c
int ata_set_max_sectors(struct ata_device *dev, u64 new_sectors)
```

Set max sectors

**Parameters**

- `struct ata_device *dev`: target device
- `u64 new_sectors`: new max sectors value to set for the device

**Description**

Set max sectors of **dev** to **new_sectors**.

**Return**

0 on success, -EACCES if command is aborted or denied (due to
previous non-volatile SET_MAX) by the drive.  -EIO on other
errors.

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

```c
int ata_hpa_resize(struct ata_device *dev)
```

Resize a device with an HPA set

**Parameters**

- `struct ata_device *dev`: Device to resize

**Description**

Read the size of an LBA28 or LBA48 disk with HPA features and resize
it if required to the full size of the media. The caller must check
the drive has the HPA feature set enabled.

**Return**

0 on success, -errno on failure.

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

```c
void ata_dump_id(struct ata_device *dev, const u16 *id)
```

IDENTIFY DEVICE info debugging output

**Parameters**

- `struct ata_device *dev`: device from which the information is fetched
- `const u16 *id`: IDENTIFY DEVICE page to dump

**Description**

Dump selected 16-bit words from the given IDENTIFY DEVICE
page.

LOCKING:
caller.

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

```c
unsigned int ata_exec_internal(struct ata_device *dev, struct ata_taskfile *tf, const u8 *cdb, enum dma_data_direction dma_dir, void *buf, unsigned int buflen, unsigned int timeout)
```

execute libata internal command

**Parameters**

- `struct ata_device *dev`: Device to which the command is sent
- `struct ata_taskfile *tf`: Taskfile registers for the command and the result
- `const u8 *cdb`: CDB for packet command
- `enum dma_data_direction dma_dir`: Data transfer direction of the command
- `void *buf`: Data buffer of the command
- `unsigned int buflen`: Length of data buffer
- `unsigned int timeout`: Timeout in msecs (0 for default)

**Description**

Executes libata internal command with timeout. **tf** contains
the command on entry and the result on return. Timeout and error
conditions are reported via the return value. No recovery action
is taken after a command times out. It is the caller's duty to
clean up after timeout.

LOCKING:
None.  Should be called with kernel context, might sleep.

**Return**

Zero on success, AC_ERR_* mask on failure

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

```c
u32 ata_pio_mask_no_iordy(const struct ata_device *adev)
```

Return the non IORDY mask

**Parameters**

- `const struct ata_device *adev`: ATA device

**Description**

Compute the highest mode possible if we are not using iordy. Return
-1 if no iordy mode is available.

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

```c
int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class, unsigned int flags, u16 *id)
```

Read ID data from the specified device

**Parameters**

- `struct ata_device *dev`: target device
- `unsigned int *p_class`: pointer to class of the target device (may be changed)
- `unsigned int flags`: ATA_READID_* flags
- `u16 *id`: buffer to read IDENTIFY data into

**Description**

Read ID data from the specified device.  ATA_CMD_ID_ATA is
performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
for pre-ATA4 drives.

FIXME: ATA_CMD_ID_ATA is optional for early drives and right
now we abort if we hit that case.

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, -errno otherwise.

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

```c
void ata_dev_power_set_standby(struct ata_device *dev)
```

Set a device power mode to standby

**Parameters**

- `struct ata_device *dev`: target device

**Description**

Issue a STANDBY IMMEDIATE command to set a device power mode to standby.
For an HDD device, this spins down the disks.

LOCKING:
Kernel thread context (may sleep).

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

```c
void ata_dev_power_set_active(struct ata_device *dev)
```

Set a device power mode to active

**Parameters**

- `struct ata_device *dev`: target device

**Description**

Issue a VERIFY command to enter to ensure that the device is in the
active power mode. For a spun-down HDD (standby or idle power mode),
the VERIFY command will complete after the disk spins up.

LOCKING:
Kernel thread context (may sleep).

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

```c
unsigned int ata_read_log_page(struct ata_device *dev, u8 log, u8 page, void *buf, unsigned int sectors)
```

read a specific log page

**Parameters**

- `struct ata_device *dev`: target device
- `u8 log`: log to read
- `u8 page`: page to read
- `void *buf`: buffer to store read page
- `unsigned int sectors`: number of sectors to read

**Description**

Read log page using READ_LOG_EXT command.

LOCKING:
Kernel thread context (may sleep).

**Return**

0 on success, AC_ERR_* mask otherwise.

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

```c
int ata_dev_configure(struct ata_device *dev)
```

Configure the specified ATA/ATAPI device

**Parameters**

- `struct ata_device *dev`: Target device to configure

**Description**

Configure **dev** according to **dev->id**.  Generic and low-level
driver specific fixups are also applied.

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, -errno otherwise

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

```c
void sata_print_link_status(struct ata_link *link)
```

Print SATA link status

**Parameters**

- `struct ata_link *link`: SATA link to printk link status about

**Description**

This function prints link speed and status of a SATA link.

LOCKING:
None.

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

```c
u8 ata_timing_cycle2mode(unsigned int xfer_shift, int cycle)
```

find xfer mode for the specified cycle duration

**Parameters**

- `unsigned int xfer_shift`: ATA_SHIFT_* value for transfer type to examine.
- `int cycle`: cycle duration in ns

**Description**

Return matching xfer mode for **cycle**.  The returned mode is of
the transfer type specified by **xfer_shift**.  If **cycle** is too
slow for **xfer_shift**, 0xff is returned.  If **cycle** is faster
than the fastest known mode, the fasted mode is returned.

LOCKING:
None.

**Return**

Matching xfer_mode, 0xff if no match found.

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

```c
int ata_down_xfermask_limit(struct ata_device *dev, unsigned int sel)
```

adjust dev xfer masks downward

**Parameters**

- `struct ata_device *dev`: Device to adjust xfer masks
- `unsigned int sel`: ATA_DNXFER_* selector

**Description**

Adjust xfer masks of **dev** downward.  Note that this function
does not apply the change.  Invoking [`ata_set_mode()`](#c-ata_set_mode) afterwards
will apply the limit.

LOCKING:
Inherited from caller.

**Return**

0 on success, negative errno on failure

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

```c
int ata_wait_ready(struct ata_link *link, unsigned long deadline, int (*check_ready)(struct ata_link *link))
```

wait for link to become ready

**Parameters**

- `struct ata_link *link`: link to be waited on
- `unsigned long deadline`: deadline jiffies for the operation
- `int (*check_ready)(struct ata_link *link)`: callback to check link readiness

**Description**

Wait for **link** to become ready.  **check_ready** should return
positive number if **link** is ready, 0 if it isn't, -ENODEV if
link doesn't seem to be occupied, other errno for other error
conditions.

Transient -ENODEV conditions are allowed for
ATA_TMOUT_FF_WAIT.

LOCKING:
EH context.

**Return**

0 if **link** is ready before **deadline**; otherwise, -errno.

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

```c
int ata_dev_same_device(struct ata_device *dev, unsigned int new_class, const u16 *new_id)
```

Determine whether new ID matches configured device

**Parameters**

- `struct ata_device *dev`: device to compare against
- `unsigned int new_class`: class of the new device
- `const u16 *new_id`: IDENTIFY page of the new device

**Description**

Compare **new_class** and **new_id** against **dev** and determine
whether **dev** is the device indicated by **new_class** and
**new_id**.

LOCKING:
None.

**Return**

1 if **dev** matches **new_class** and **new_id**, 0 otherwise.

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

```c
int ata_dev_reread_id(struct ata_device *dev, unsigned int readid_flags)
```

Re-read IDENTIFY data

**Parameters**

- `struct ata_device *dev`: target ATA device
- `unsigned int readid_flags`: read ID flags

**Description**

Re-read IDENTIFY page and make sure **dev** is still attached to
the port.

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, negative errno otherwise

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

```c
int ata_dev_revalidate(struct ata_device *dev, unsigned int new_class, unsigned int readid_flags)
```

Revalidate ATA device

**Parameters**

- `struct ata_device *dev`: device to revalidate
- `unsigned int new_class`: new class code
- `unsigned int readid_flags`: read ID flags

**Description**

Re-read IDENTIFY page, make sure **dev** is still attached to the
port and reconfigure it according to the new IDENTIFY page.

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, negative errno otherwise

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

```c
int ata_is_40wire(struct ata_device *dev)
```

check drive side detection

**Parameters**

- `struct ata_device *dev`: device

**Description**

Perform drive side detection decoding, allowing for device vendors
who can't follow the documentation.

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

```c
int cable_is_40wire(struct ata_port *ap)
```

40/80/SATA decider

**Parameters**

- `struct ata_port *ap`: port to consider

**Description**

This function encapsulates the policy for speed management
in one place. At the moment we don't cache the result but
there is a good case for setting ap->cbl to the result when
we are called with unknown cables (and figuring out if it
impacts hotplug at all).

Return 1 if the cable appears to be 40 wire.

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

```c
void ata_dev_xfermask(struct ata_device *dev)
```

Compute supported xfermask of the given device

**Parameters**

- `struct ata_device *dev`: Device to compute xfermask for

**Description**

Compute supported xfermask of **dev** and store it in
dev->*_mask.  This function is responsible for applying all
known limits including host controller limits, device quirks, etc...

LOCKING:
None.

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

```c
unsigned int ata_dev_set_xfermode(struct ata_device *dev)
```

Issue SET FEATURES - XFER MODE command

**Parameters**

- `struct ata_device *dev`: Device to which command will be sent

**Description**

Issue SET FEATURES - XFER MODE command to device **dev**
on port **ap**.

LOCKING:
PCI/etc. bus probe sem.

**Return**

0 on success, AC_ERR_* mask otherwise.

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

```c
unsigned int ata_dev_init_params(struct ata_device *dev, u16 heads, u16 sectors)
```

Issue INIT DEV PARAMS command

**Parameters**

- `struct ata_device *dev`: Device to which command will be sent
- `u16 heads`: Number of heads (taskfile parameter)
- `u16 sectors`: Number of sectors (taskfile parameter)

**Description**

LOCKING:
Kernel thread context (may sleep)

**Return**

0 on success, AC_ERR_* mask otherwise.

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

```c
int atapi_check_dma(struct ata_queued_cmd *qc)
```

Check whether ATAPI DMA can be supported

**Parameters**

- `struct ata_queued_cmd *qc`: Metadata associated with taskfile to check

**Description**

Allow low-level driver to filter ATA PACKET commands, returning
a status indicating whether or not it is OK to use DMA for the
supplied PACKET command.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

0 when ATAPI DMA can be used
nonzero otherwise

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

```c
void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg, unsigned int n_elem)
```

Associate command with scatter-gather table.

**Parameters**

- `struct ata_queued_cmd *qc`: Command to be associated
- `struct scatterlist *sg`: Scatter-gather table.
- `unsigned int n_elem`: Number of elements in s/g table.

**Description**

Initialize the data-related elements of queued_cmd **qc**
to point to a scatter-gather table **sg**, containing **n_elem**
elements.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_sg_clean(struct ata_queued_cmd *qc)
```

Unmap DMA memory associated with command

**Parameters**

- `struct ata_queued_cmd *qc`: Command containing DMA memory to be released

**Description**

Unmap all mapped DMA memory associated with this command.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
int ata_sg_setup(struct ata_queued_cmd *qc)
```

DMA-map the scatter-gather table associated with a command.

**Parameters**

- `struct ata_queued_cmd *qc`: Command with scatter-gather table to be mapped.

**Description**

DMA-map the scatter-gather table associated with queued_cmd **qc**.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, negative on error.

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

```c
void swap_buf_le16(u16 *buf, unsigned int buf_words)
```

swap halves of 16-bit words in place

**Parameters**

- `u16 *buf`: Buffer to swap
- `unsigned int buf_words`: Number of 16-bit words in buffer.

**Description**

Swap halves of 16-bit words if needed to convert from
little-endian byte order to native cpu byte order, or
vice-versa.

LOCKING:
Inherited from caller.

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

```c
void ata_qc_free(struct ata_queued_cmd *qc)
```

free unused ata_queued_cmd

**Parameters**

- `struct ata_queued_cmd *qc`: Command to complete

**Description**

Designed to free unused ata_queued_cmd object
in case something prevents using it.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_qc_issue(struct ata_queued_cmd *qc)
```

issue taskfile to device

**Parameters**

- `struct ata_queued_cmd *qc`: command to issue to device

**Description**

Prepare an ATA command to submission to device.
This includes mapping the data into a DMA-able
area, filling in the S/G table, and finally
writing the taskfile to hardware, starting the command.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
bool ata_phys_link_online(struct ata_link *link)
```

test whether the given link is online

**Parameters**

- `struct ata_link *link`: ATA link to test

**Description**

Test whether **link** is online.  Note that this function returns
0 if online status of **link** cannot be obtained, so
ata_link_online(link) != !ata_link_offline(link).

LOCKING:
None.

**Return**

True if the port online status is available and online.

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

```c
bool ata_phys_link_offline(struct ata_link *link)
```

test whether the given link is offline

**Parameters**

- `struct ata_link *link`: ATA link to test

**Description**

Test whether **link** is offline.  Note that this function
returns 0 if offline status of **link** cannot be obtained, so
ata_link_online(link) != !ata_link_offline(link).

LOCKING:
None.

**Return**

True if the port offline status is available and offline.

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

```c
void ata_dev_init(struct ata_device *dev)
```

Initialize an ata_device structure

**Parameters**

- `struct ata_device *dev`: Device structure to initialize

**Description**

Initialize **dev** in preparation for probing.

LOCKING:
Inherited from caller.

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

```c
void ata_link_init(struct ata_port *ap, struct ata_link *link, int pmp)
```

Initialize an ata_link structure

**Parameters**

- `struct ata_port *ap`: ATA port link is attached to
- `struct ata_link *link`: Link structure to initialize
- `int pmp`: Port multiplier port number

**Description**

Initialize **link**.

LOCKING:
Kernel thread context (may sleep)

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

```c
int sata_link_init_spd(struct ata_link *link)
```

Initialize link->sata_spd_limit

**Parameters**

- `struct ata_link *link`: Link to configure sata_spd_limit for

**Description**

Initialize `link->[hw_]sata_spd_limit` to the currently
configured value.

LOCKING:
Kernel thread context (may sleep).

**Return**

0 on success, -errno on failure.

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

```c
void ata_finalize_port_ops(struct ata_port_operations *ops)
```

finalize ata_port_operations

**Parameters**

- `struct ata_port_operations *ops`: ata_port_operations to finalize

**Description**

An ata_port_operations can inherit from another ops and that
ops can again inherit from another.  This can go on as many
times as necessary as long as there is no loop in the
inheritance chain.

Ops tables are finalized when the host is started.  NULL or
unspecified entries are inherited from the closet ancestor
which has the method and the entry is populated with it.
After finalization, the ops table directly points to all the
methods and ->inherits is no longer necessary and cleared.

Using ATA_OP_NULL, inheriting ops can force a method to NULL.

LOCKING:
None.

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

```c
void ata_dev_free_resources(struct ata_device *dev)
```

Free a device resources

**Parameters**

- `struct ata_device *dev`: Target ATA device

**Description**

Free resources allocated to support a device features.

LOCKING:
Kernel thread context (may sleep).

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

```c
void ata_port_detach(struct ata_port *ap)
```

Detach ATA port in preparation of device removal

**Parameters**

- `struct ata_port *ap`: ATA port to be detached

**Description**

Detach all ATA devices and the associated SCSI devices of **ap**;
then, remove the associated SCSI host.  **ap** is guaranteed to
be quiescent on return from this function.

LOCKING:
Kernel thread context (may sleep).



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

```c
void __ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
```

push error description without adding separator

**Parameters**

- `struct ata_eh_info *ehi`: target EHI
- `const char *fmt`: printf format string
- `...`: variable arguments

**Description**

Format string according to **fmt** and append it to **ehi->desc**.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
```

push error description with separator

**Parameters**

- `struct ata_eh_info *ehi`: target EHI
- `const char *fmt`: printf format string
- `...`: variable arguments

**Description**

Format string according to **fmt** and append it to **ehi->desc**.
If **ehi->desc** is not empty, ", " is added in-between.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_ehi_clear_desc(struct ata_eh_info *ehi)
```

clean error description

**Parameters**

- `struct ata_eh_info *ehi`: target EHI

**Description**

Clear **ehi->desc**.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_port_desc(struct ata_port *ap, const char *fmt, ...)
```

append port description

**Parameters**

- `struct ata_port *ap`: target ATA port
- `const char *fmt`: printf format string
- `...`: variable arguments

**Description**

Format string according to **fmt** and append it to port
description.  If port description is not empty, " " is added
in-between.  This function is to be used while initializing
ata_host.  The description is printed on host registration.

LOCKING:
None.

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

```c
void ata_port_pbar_desc(struct ata_port *ap, int bar, ssize_t offset, const char *name)
```

append PCI BAR description

**Parameters**

- `struct ata_port *ap`: target ATA port
- `int bar`: target PCI BAR
- `ssize_t offset`: offset into PCI BAR
- `const char *name`: name of the area

**Description**

If **offset** is negative, this function formats a string which
contains the name, address, size and type of the BAR and
appends it to the port description.  If **offset** is zero or
positive, only name and offsetted address is appended.

LOCKING:
None.

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

```c
unsigned int ata_internal_cmd_timeout(struct ata_device *dev, u8 cmd)
```

determine timeout for an internal command

**Parameters**

- `struct ata_device *dev`: target device
- `u8 cmd`: internal command to be issued

**Description**

Determine timeout for internal command **cmd** for **dev**.

LOCKING:
EH context.

**Return**

Determined timeout.

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

```c
void ata_internal_cmd_timed_out(struct ata_device *dev, u8 cmd)
```

notification for internal command timeout

**Parameters**

- `struct ata_device *dev`: target device
- `u8 cmd`: internal command which timed out

**Description**

Notify EH that internal command **cmd** for **dev** timed out.  This
function should be called only for commands whose timeouts are
determined using [`ata_internal_cmd_timeout()`](#c-ata_internal_cmd_timeout).

LOCKING:
EH context.

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

```c
void ata_eh_acquire(struct ata_port *ap)
```

acquire EH ownership

**Parameters**

- `struct ata_port *ap`: ATA port to acquire EH ownership for

**Description**

Acquire EH ownership for **ap**.  This is the basic exclusion
mechanism for ports sharing a host.  Only one port hanging off
the same host can claim the ownership of EH.

LOCKING:
EH context.

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

```c
void ata_eh_release(struct ata_port *ap)
```

release EH ownership

**Parameters**

- `struct ata_port *ap`: ATA port to release EH ownership for

**Description**

Release EH ownership for **ap** if the caller.  The caller must
have acquired EH ownership using [`ata_eh_acquire()`](#c-ata_eh_acquire) previously.

LOCKING:
EH context.

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

```c
void ata_scsi_error(struct Scsi_Host *host)
```

SCSI layer error handler callback

**Parameters**

- `struct Scsi_Host *host`: SCSI host on which error occurred

**Description**

Handles SCSI-layer-thrown error events.

LOCKING:
Inherited from SCSI layer (none, can sleep)

**Return**

Zero.

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

```c
void ata_scsi_cmd_error_handler(struct Scsi_Host *host, struct ata_port *ap, struct list_head *eh_work_q)
```

error callback for a list of commands

**Parameters**

- `struct Scsi_Host *host`: scsi host containing the port
- `struct ata_port *ap`: ATA port within the host
- `struct list_head *eh_work_q`: list of commands to process

**Description**

process the given list of commands and return those finished to the
ap->eh_done_q.  This function is the first part of the libata error
handler which processes a given list of failed commands.

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

```c
void ata_scsi_port_error_handler(struct Scsi_Host *host, struct ata_port *ap)
```

recover the port after the commands

**Parameters**

- `struct Scsi_Host *host`: SCSI host containing the port
- `struct ata_port *ap`: the ATA port

**Description**

Handle the recovery of the port **ap** after all the commands
have been recovered.

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

```c
void ata_port_wait_eh(struct ata_port *ap)
```

Wait for the currently pending EH to complete

**Parameters**

- `struct ata_port *ap`: Port to wait EH for

**Description**

Wait until the currently pending EH is complete.

LOCKING:
Kernel thread context (may sleep).

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

```c
void ata_eh_set_pending(struct ata_port *ap, bool fastdrain)
```

set ATA_PFLAG_EH_PENDING and activate fast drain

**Parameters**

- `struct ata_port *ap`: target ATA port
- `bool fastdrain`: activate fast drain

**Description**

Set ATA_PFLAG_EH_PENDING and activate fast drain if **fastdrain**
is non-zero and EH wasn't pending before.  Fast drain ensures
that EH kicks in in timely manner.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_qc_schedule_eh(struct ata_queued_cmd *qc)
```

schedule qc for error handling

**Parameters**

- `struct ata_queued_cmd *qc`: command to schedule error handling for

**Description**

Schedule error handling for **qc**.  EH will kick in as soon as
other commands are drained.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_std_sched_eh(struct ata_port *ap)
```

non-libsas ata_ports issue eh with this common routine

**Parameters**

- `struct ata_port *ap`: ATA port to schedule EH for

**Description**

LOCKING: inherited from ata_port_schedule_eh
spin_lock_irqsave(host lock)

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

```c
void ata_std_end_eh(struct ata_port *ap)
```

non-libsas ata_ports complete eh with this common routine

**Parameters**

- `struct ata_port *ap`: ATA port to end EH for

**Description**

In the libata object model there is a 1:1 mapping of ata_port to
shost, so host fields can be directly manipulated under ap->lock, in
the libsas case we need to hold a lock at the ha->level to coordinate
these events.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_port_schedule_eh(struct ata_port *ap)
```

schedule error handling without a qc

**Parameters**

- `struct ata_port *ap`: ATA port to schedule EH for

**Description**

Schedule error handling for **ap**.  EH will kick in as soon as
all commands are drained.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
int ata_link_abort(struct ata_link *link)
```

abort all qc's on the link

**Parameters**

- `struct ata_link *link`: ATA link to abort qc's for

**Description**

Abort all active qc's active on **link** and schedule EH.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Number of aborted qc's.

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

```c
int ata_port_abort(struct ata_port *ap)
```

abort all qc's on the port

**Parameters**

- `struct ata_port *ap`: ATA port to abort qc's for

**Description**

Abort all active qc's of **ap** and schedule EH.

LOCKING:
spin_lock_irqsave(host_set lock)

**Return**

Number of aborted qc's.

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

```c
void __ata_port_freeze(struct ata_port *ap)
```

freeze port

**Parameters**

- `struct ata_port *ap`: ATA port to freeze

**Description**

This function is called when HSM violation or some other
condition disrupts normal operation of the port.  Frozen port
is not allowed to perform any operation until the port is
thawed, which usually follows a successful reset.

ap->ops->`freeze()` callback can be used for freezing the port
hardware-wise (e.g. mask interrupt and stop DMA engine).  If a
port cannot be frozen hardware-wise, the interrupt handler
must ack and clear interrupts unconditionally while the port
is frozen.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
int ata_port_freeze(struct ata_port *ap)
```

abort & freeze port

**Parameters**

- `struct ata_port *ap`: ATA port to freeze

**Description**

Abort and freeze **ap**.  The freeze operation must be called
first, because some hardware requires special operations
before the taskfile registers are accessible.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Number of aborted commands.

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

```c
void ata_eh_freeze_port(struct ata_port *ap)
```

EH helper to freeze port

**Parameters**

- `struct ata_port *ap`: ATA port to freeze

**Description**

Freeze **ap**.

LOCKING:
None.

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

```c
void ata_eh_thaw_port(struct ata_port *ap)
```

EH helper to thaw port

**Parameters**

- `struct ata_port *ap`: ATA port to thaw

**Description**

Thaw frozen port **ap**.

LOCKING:
None.

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

```c
void ata_eh_qc_complete(struct ata_queued_cmd *qc)
```

Complete an active ATA command from EH

**Parameters**

- `struct ata_queued_cmd *qc`: Command to complete

**Description**

Indicate to the mid and upper layers that an ATA command has
completed.  To be used from EH.

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

```c
void ata_eh_qc_retry(struct ata_queued_cmd *qc)
```

Tell midlayer to retry an ATA command after EH

**Parameters**

- `struct ata_queued_cmd *qc`: Command to retry

**Description**

Indicate to the mid and upper layers that an ATA command
should be retried.  To be used from EH.

SCSI midlayer limits the number of retries to scmd->allowed.
scmd->allowed is incremented for commands which get retried
due to unrelated failures (qc->err_mask is zero).

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

```c
void ata_dev_disable(struct ata_device *dev)
```

disable ATA device

**Parameters**

- `struct ata_device *dev`: ATA device to disable

**Description**

Disable **dev**.

Locking:
EH context.

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

```c
void ata_eh_detach_dev(struct ata_device *dev)
```

detach ATA device

**Parameters**

- `struct ata_device *dev`: ATA device to detach

**Description**

Detach **dev**.

LOCKING:
None.

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

```c
void ata_eh_about_to_do(struct ata_link *link, struct ata_device *dev, unsigned int action)
```

about to perform eh_action

**Parameters**

- `struct ata_link *link`: target ATA link
- `struct ata_device *dev`: target ATA dev for per-dev action (can be NULL)
- `unsigned int action`: action about to be performed

**Description**

Called just before performing EH actions to clear related bits
in **link->eh_info** such that eh actions are not unnecessarily
repeated.

LOCKING:
None.

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

```c
void ata_eh_done(struct ata_link *link, struct ata_device *dev, unsigned int action)
```

EH action complete

**Parameters**

- `struct ata_link *link`: ATA link for which EH actions are complete
- `struct ata_device *dev`: target ATA dev for per-dev action (can be NULL)
- `unsigned int action`: action just completed

**Description**

Called right after performing EH actions to clear related bits
in **link->eh_context**.

LOCKING:
None.

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

```c
const char * ata_err_string(unsigned int err_mask)
```

convert err_mask to descriptive string

**Parameters**

- `unsigned int err_mask`: error mask to convert to string

**Description**

Convert **err_mask** to descriptive string.  Errors are
prioritized according to severity and only the most severe
error is reported.

LOCKING:
None.

**Return**

Descriptive string for **err_mask**

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

```c
unsigned int atapi_eh_tur(struct ata_device *dev, u8 *r_sense_key)
```

perform ATAPI TEST_UNIT_READY

**Parameters**

- `struct ata_device *dev`: target ATAPI device
- `u8 *r_sense_key`: out parameter for sense_key

**Description**

Perform ATAPI TEST_UNIT_READY.

LOCKING:
EH context (may sleep).

**Return**

0 on success, AC_ERR_* mask on failure.

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

```c
enum scsi_disposition ata_eh_decide_disposition(struct ata_queued_cmd *qc)
```

Disposition a qc based on sense data

**Parameters**

- `struct ata_queued_cmd *qc`: qc to examine

**Description**

For a regular SCSI command, the SCSI completion callback (`scsi_done()`)
will call `scsi_complete()`, which will call `scsi_decide_disposition()`,
which will call [`scsi_check_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_check_sense). `scsi_complete()` finally calls
`scsi_finish_command()`. This is fine for SCSI, since any eventual sense
data is usually returned in the completion itself (without invoking SCSI
EH). However, for a QC, we always need to fetch the sense data
explicitly using SCSI EH.

A command that is completed via SCSI EH will instead be completed using
[`scsi_eh_flush_done_q()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_eh_flush_done_q), which will call `scsi_finish_command()` directly
(without ever calling [`scsi_check_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_check_sense)).

For a command that went through SCSI EH, it is the responsibility of the
SCSI EH strategy handler to call `scsi_decide_disposition()`, see e.g. how
[`scsi_eh_get_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_eh_get_sense) calls `scsi_decide_disposition()` for SCSI LLDDs that
do not get the sense data as part of the completion.

Thus, for QC commands that went via SCSI EH, we need to call
[`scsi_check_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_check_sense) ourselves, similar to how [`scsi_eh_get_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_eh_get_sense) calls
`scsi_decide_disposition()`, which calls [`scsi_check_sense()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_check_sense), in order to
set the correct SCSI ML byte (if any).

LOCKING:
EH context.

**Return**

SUCCESS or FAILED or NEEDS_RETRY or ADD_TO_MLQUEUE

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

```c
bool ata_eh_request_sense(struct ata_queued_cmd *qc)
```

perform REQUEST_SENSE_DATA_EXT

**Parameters**

- `struct ata_queued_cmd *qc`: qc to perform REQUEST_SENSE_SENSE_DATA_EXT to

**Description**

Perform REQUEST_SENSE_DATA_EXT after the device reported CHECK
SENSE.  This function is an EH helper.

LOCKING:
Kernel thread context (may sleep).

**Return**

true if sense data could be fetched, false otherwise.

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

```c
unsigned int atapi_eh_request_sense(struct ata_device *dev, u8 *sense_buf, u8 dfl_sense_key)
```

perform ATAPI REQUEST_SENSE

**Parameters**

- `struct ata_device *dev`: device to perform REQUEST_SENSE to
- `u8 *sense_buf`: result sense data buffer (SCSI_SENSE_BUFFERSIZE bytes long)
- `u8 dfl_sense_key`: default sense key to use

**Description**

Perform ATAPI REQUEST_SENSE after the device reported CHECK
SENSE.  This function is EH helper.

LOCKING:
Kernel thread context (may sleep).

**Return**

0 on success, AC_ERR_* mask on failure

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

```c
void ata_eh_analyze_serror(struct ata_link *link)
```

analyze SError for a failed port

**Parameters**

- `struct ata_link *link`: ATA link to analyze SError for

**Description**

Analyze SError if available and further determine cause of
failure.

LOCKING:
None.

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

```c
unsigned int ata_eh_analyze_tf(struct ata_queued_cmd *qc)
```

analyze taskfile of a failed qc

**Parameters**

- `struct ata_queued_cmd *qc`: qc to analyze

**Description**

Analyze taskfile of **qc** and further determine cause of
failure.  This function also requests ATAPI sense data if
available.

LOCKING:
Kernel thread context (may sleep).

**Return**

Determined recovery action

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

```c
unsigned int ata_eh_speed_down_verdict(struct ata_device *dev)
```

Determine speed down verdict

**Parameters**

- `struct ata_device *dev`: Device of interest

**Description**

This function examines error ring of **dev** and determines
whether NCQ needs to be turned off, transfer speed should be
stepped down, or falling back to PIO is necessary.

ECAT_ATA_BUS    : ATA_BUS error for any command

- ECAT_TOUT_HSM   : TIMEOUT for any command or HSM violation for

  IO commands

ECAT_UNK_DEV    : Unknown DEV error for IO commands

- ECAT_DUBIOUS_*  : Identical to above three but occurred while

  data transfer hasn't been verified.

Verdicts are

NCQ_OFF         : Turn off NCQ.

- SPEED_DOWN      : Speed down transfer speed but don't fall back

  to PIO.

FALLBACK_TO_PIO : Fall back to PIO.

Even if multiple verdicts are returned, only one action is
taken per error.  An action triggered by non-DUBIOUS errors
clears ering, while one triggered by DUBIOUS_* errors doesn't.
This is to expedite speed down decisions right after device is
initially configured.

The following are speed down rules.  #1 and #2 deal with
DUBIOUS errors.

1. If more than one DUBIOUS_ATA_BUS or DUBIOUS_TOUT_HSM errors
   occurred during last 5 mins, SPEED_DOWN and FALLBACK_TO_PIO.

2. If more than one DUBIOUS_TOUT_HSM or DUBIOUS_UNK_DEV errors
   occurred during last 5 mins, NCQ_OFF.

3. If more than 8 ATA_BUS, TOUT_HSM or UNK_DEV errors
   occurred during last 5 mins, FALLBACK_TO_PIO

4. If more than 3 TOUT_HSM or UNK_DEV errors occurred
   during last 10 mins, NCQ_OFF.

5. If more than 3 ATA_BUS or TOUT_HSM errors, or more than 6
   UNK_DEV errors occurred during last 10 mins, SPEED_DOWN.

LOCKING:
Inherited from caller.

**Return**

OR of ATA_EH_SPDN_* flags.

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

```c
unsigned int ata_eh_speed_down(struct ata_device *dev, unsigned int eflags, unsigned int err_mask)
```

record error and speed down if necessary

**Parameters**

- `struct ata_device *dev`: Failed device
- `unsigned int eflags`: mask of ATA_EFLAG_* flags
- `unsigned int err_mask`: err_mask of the error

**Description**

Record error and examine error history to determine whether
adjusting transmission speed is necessary.  It also sets
transmission limits appropriately if such adjustment is
necessary.

LOCKING:
Kernel thread context (may sleep).

**Return**

Determined recovery action.

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

```c
int ata_eh_worth_retry(struct ata_queued_cmd *qc)
```

analyze error and decide whether to retry

**Parameters**

- `struct ata_queued_cmd *qc`: qc to possibly retry

**Description**

Look at the cause of the error and decide if a retry
might be useful or not.  We don't want to retry media errors
because the drive itself has probably already taken 10-30 seconds
doing its own internal retries before reporting the failure.

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

```c
bool ata_eh_quiet(struct ata_queued_cmd *qc)
```

check if we need to be quiet about a command error

**Parameters**

- `struct ata_queued_cmd *qc`: qc to check

**Description**

Look at the qc flags anbd its scsi command request flags to determine
if we need to be quiet about the command failure.

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

```c
int ata_eh_link_set_lpm(struct ata_link *link, enum ata_lpm_policy policy, struct ata_device **r_failed_dev)
```

configure SATA interface power management

**Parameters**

- `struct ata_link *link`: link to configure
- `enum ata_lpm_policy policy`: the link power management policy
- `struct ata_device **r_failed_dev`: out parameter for failed device

**Description**

Enable SATA Interface power management.  This will enable
Device Interface Power Management (DIPM) for min_power and
medium_power_with_dipm policies, and then call driver specific
callbacks for enabling Host Initiated Power management.

LOCKING:
EH context.

**Return**

0 on success, -errno on failure.

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

```c
void ata_eh_link_autopsy(struct ata_link *link)
```

analyze error and determine recovery action

**Parameters**

- `struct ata_link *link`: host link to perform autopsy on

**Description**

Analyze why **link** failed and determine which recovery actions
are needed.  This function also sets more detailed AC_ERR_*
values and fills sense data for ATAPI CHECK SENSE.

LOCKING:
Kernel thread context (may sleep).

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

```c
void ata_eh_autopsy(struct ata_port *ap)
```

analyze error and determine recovery action

**Parameters**

- `struct ata_port *ap`: host port to perform autopsy on

**Description**

Analyze all links of **ap** and determine why they failed and
which recovery actions are needed.

LOCKING:
Kernel thread context (may sleep).

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

```c
const char * ata_get_cmd_name(u8 command)
```

get name for ATA command

**Parameters**

- `u8 command`: ATA command code to get name for

**Description**

Return a textual name of the given command or "unknown"

LOCKING:
None

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

```c
void ata_eh_link_report(struct ata_link *link)
```

report error handling to user

**Parameters**

- `struct ata_link *link`: ATA link EH is going on

**Description**

Report EH to user.

LOCKING:
None.

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

```c
void ata_eh_report(struct ata_port *ap)
```

report error handling to user

**Parameters**

- `struct ata_port *ap`: ATA port to report EH about

**Description**

Report EH to user.

LOCKING:
None.

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

```c
int ata_eh_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
```

Program timings and issue SET FEATURES - XFER

**Parameters**

- `struct ata_link *link`: link on which timings will be programmed
- `struct ata_device **r_failed_dev`: out parameter for failed device

**Description**

Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
[`ata_eh_set_mode()`](#c-ata_eh_set_mode) fails, pointer to the failing device is
returned in **r_failed_dev**.

LOCKING:
PCI/etc. bus probe sem.

**Return**

0 on success, negative errno otherwise

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

```c
int atapi_eh_clear_ua(struct ata_device *dev)
```

Clear ATAPI UNIT ATTENTION after reset

**Parameters**

- `struct ata_device *dev`: ATAPI device to clear UA for

**Description**

Resets and other operations can make an ATAPI device raise
UNIT ATTENTION which causes the next operation to fail.  This
function clears UA.

LOCKING:
EH context (may sleep).

**Return**

0 on success, -errno on failure.

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

```c
int ata_eh_maybe_retry_flush(struct ata_device *dev)
```

Retry FLUSH if necessary

**Parameters**

- `struct ata_device *dev`: ATA device which may need FLUSH retry

**Description**

If **dev** failed FLUSH, it needs to be reported upper layer
immediately as it means that **dev** failed to remap and already
lost at least a sector and further FLUSH retrials won't make
any difference to the lost sector.  However, if FLUSH failed
for other reasons, for example transmission error, FLUSH needs
to be retried.

This function determines whether FLUSH failure retry is
necessary and performs it if so.

**Return**

0 if EH can continue, -errno if EH needs to be repeated.

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

```c
int ata_eh_recover(struct ata_port *ap, struct ata_reset_operations *reset_ops, struct ata_link **r_failed_link)
```

recover host port after error

**Parameters**

- `struct ata_port *ap`: host port to recover
- `struct ata_reset_operations *reset_ops`: The set of reset operations to use
- `struct ata_link **r_failed_link`: out parameter for failed link

**Description**

This is the alpha and omega, eum and yang, heart and soul of
libata exception handling.  On entry, actions required to
recover each link and hotplug requests are recorded in the
link's eh_context.  This function executes all the operations
with appropriate retrials and fallbacks to resurrect failed
devices, detach goners and greet newcomers.

LOCKING:
Kernel thread context (may sleep).

**Return**

0 on success, -errno on failure.

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

```c
void ata_eh_finish(struct ata_port *ap)
```

finish up EH

**Parameters**

- `struct ata_port *ap`: host port to finish EH for

**Description**

Recovery is complete.  Clean up EH states and retry or finish
failed qcs.

LOCKING:
None.

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

```c
void ata_std_error_handler(struct ata_port *ap)
```

standard error handler

**Parameters**

- `struct ata_port *ap`: host port to handle error for

**Description**

Perform standard error handling sequence.

LOCKING:
Kernel thread context (may sleep).

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

```c
void ata_eh_handle_port_suspend(struct ata_port *ap)
```

perform port suspend operation

**Parameters**

- `struct ata_port *ap`: port to suspend

**Description**

Suspend **ap**.

LOCKING:
Kernel thread context (may sleep).

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

```c
void ata_eh_handle_port_resume(struct ata_port *ap)
```

perform port resume operation

**Parameters**

- `struct ata_port *ap`: port to resume

**Description**

Resume **ap**.

LOCKING:
Kernel thread context (may sleep).


<a id="rst-libata-scsi-translation-emulation"></a>

## libata SCSI translation/emulation


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

```c
int ata_std_bios_param(struct scsi_device *sdev, struct gendisk *unused, sector_t capacity, int geom[])
```

generic bios head/sector/cylinder calculator used by sd.

**Parameters**

- `struct scsi_device *sdev`: SCSI device for which BIOS geometry is to be determined
- `struct gendisk *unused`: gendisk associated with **sdev**
- `sector_t capacity`: capacity of SCSI device
- `int geom[]`: location to which geometry will be output

**Description**

Generic bios head/sector/cylinder calculator
used by sd. Most BIOSes nowadays expect a XXX/255/16  (CHS)
mapping. Some situations may arise where the disk is not
bootable if this is not used.

LOCKING:
Defined by the SCSI layer.  We don't really care.

**Return**

Zero.

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

```c
void ata_scsi_unlock_native_capacity(struct scsi_device *sdev)
```

unlock native capacity

**Parameters**

- `struct scsi_device *sdev`: SCSI device to adjust device capacity for

**Description**

This function is called if a partition on **sdev** extends beyond
the end of the device.  It requests EH to unlock HPA.

LOCKING:
Defined by the SCSI layer.  Might sleep.

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

```c
bool ata_scsi_dma_need_drain(struct request *rq)
```

Check whether data transfer may overflow

**Parameters**

- `struct request *rq`: request to be checked

**Description**

ATAPI commands which transfer variable length data to host
might overflow due to application error or hardware bug.  This
function checks whether overflow should be drained and ignored
for **request**.

LOCKING:
None.

**Return**

1 if ; otherwise, 0.

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

```c
int ata_scsi_sdev_init(struct scsi_device *sdev)
```

Early setup of SCSI device

**Parameters**

- `struct scsi_device *sdev`: SCSI device to examine

**Description**

This is called from `scsi_alloc_sdev()` when the scsi device
associated with an ATA device is scanned on a port.

LOCKING:
Defined by SCSI layer.  We don't really care.

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

```c
int ata_scsi_sdev_configure(struct scsi_device *sdev, struct queue_limits *lim)
```

Set SCSI device attributes

**Parameters**

- `struct scsi_device *sdev`: SCSI device to examine
- `struct queue_limits *lim`: queue limits

**Description**

This is called before we actually start reading
and writing to the device, to configure certain
SCSI mid-layer behaviors.

LOCKING:
Defined by SCSI layer.  We don't really care.

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

```c
void ata_scsi_sdev_destroy(struct scsi_device *sdev)
```

SCSI device is about to be destroyed

**Parameters**

- `struct scsi_device *sdev`: SCSI device to be destroyed

**Description**

**sdev** is about to be destroyed for hot/warm unplugging.  If
this unplugging was initiated by libata as indicated by NULL
dev->sdev, this function doesn't have to do anything.
Otherwise, SCSI layer initiated warm-unplug is in progress.
Clear dev->sdev, schedule the device for ATA detach and invoke
EH.

LOCKING:
Defined by SCSI layer.  We don't really care.

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

```c
enum scsi_qc_status ata_scsi_queuecmd(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
```

Issue SCSI cdb to libata-managed device

**Parameters**

- `struct Scsi_Host *shost`: SCSI host of command to be sent
- `struct scsi_cmnd *cmd`: SCSI command to be sent

**Description**

In some cases, this function translates SCSI commands into
ATA taskfiles, and queues the taskfiles to be sent to
hardware.  In other cases, this function simulates a
SCSI device by evaluating and responding to certain
SCSI commands.  This creates the overall effect of
ATA and ATAPI devices appearing as SCSI devices.

LOCKING:
ATA host lock

**Return**

Return value from `__ata_scsi_queuecmd()` if **cmd** can be queued,
0 otherwise.



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

```c
void ata_scsi_set_passthru_sense_fields(struct ata_queued_cmd *qc)
```

Set ATA fields in sense buffer

**Parameters**

- `struct ata_queued_cmd *qc`: ATA PASS-THROUGH command.

**Description**

Populates "ATA Status Return sense data descriptor" / "Fixed format
sense data" with ATA taskfile fields.

LOCKING:
None.

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

```c
int ata_get_identity(struct ata_port *ap, struct scsi_device *sdev, void __user *arg)
```

Handler for HDIO_GET_IDENTITY ioctl

**Parameters**

- `struct ata_port *ap`: target port
- `struct scsi_device *sdev`: SCSI device to get identify data for
- `void __user *arg`: User buffer area for identify data

**Description**

LOCKING:
Defined by the SCSI layer.  We don't really care.

**Return**

Zero on success, negative errno on error.

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

```c
int ata_cmd_ioctl(struct scsi_device *scsidev, void __user *arg)
```

Handler for HDIO_DRIVE_CMD ioctl

**Parameters**

- `struct scsi_device *scsidev`: Device to which we are issuing command
- `void __user *arg`: User provided data for issuing command

**Description**

LOCKING:
Defined by the SCSI layer.  We don't really care.

**Return**

Zero on success, negative errno on error.

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

```c
int ata_task_ioctl(struct scsi_device *scsidev, void __user *arg)
```

Handler for HDIO_DRIVE_TASK ioctl

**Parameters**

- `struct scsi_device *scsidev`: Device to which we are issuing command
- `void __user *arg`: User provided data for issuing command

**Description**

LOCKING:
Defined by the SCSI layer.  We don't really care.

**Return**

Zero on success, negative errno on error.

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

```c
struct ata_queued_cmd * ata_scsi_qc_new(struct ata_device *dev, struct scsi_cmnd *cmd)
```

acquire new ata_queued_cmd reference

**Parameters**

- `struct ata_device *dev`: ATA device to which the new command is attached
- `struct scsi_cmnd *cmd`: SCSI command that originated this ATA command

**Description**

Obtain a reference to an unused ata_queued_cmd structure,
which is the basic libata structure representing a single
ATA command sent to the hardware.

If a command was available, fill in the SCSI-specific
portions of the structure with information on the
current command.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Command allocated, or `NULL` if none available.

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

```c
void ata_to_sense_error(u8 drv_stat, u8 drv_err, u8 *sk, u8 *asc, u8 *ascq)
```

convert ATA error to SCSI error

**Parameters**

- `u8 drv_stat`: value contained in ATA status register
- `u8 drv_err`: value contained in ATA error register
- `u8 *sk`: the sense key we'll fill out
- `u8 *asc`: the additional sense code we'll fill out
- `u8 *ascq`: the additional sense code qualifier we'll fill out

**Description**

Converts an ATA error into a SCSI error.  Fill out pointers to
SK, ASC, and ASCQ bytes for later use in fixed or descriptor
format sense blocks.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_gen_ata_sense(struct ata_queued_cmd *qc)
```

generate a SCSI fixed sense block

**Parameters**

- `struct ata_queued_cmd *qc`: Command that we are erroring out

**Description**

Generate sense block for a failed ATA command **qc**.

LOCKING:
None.

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

```c
unsigned int ata_scsi_start_stop_xlat(struct ata_queued_cmd *qc)
```

Translate SCSI START STOP UNIT command

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Sets up an ATA taskfile to issue STANDBY (to stop) or READ VERIFY
(to start). Perhaps these commands should be preceded by
CHECK POWER MODE to see what power mode the device is already in.
\[See SAT revision 5 at www.t10.org\]

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on error.

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

```c
unsigned int ata_scsi_flush_xlat(struct ata_queued_cmd *qc)
```

Translate SCSI SYNCHRONIZE CACHE command

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Sets up an ATA taskfile to issue FLUSH CACHE or
FLUSH CACHE EXT.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on error.

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

```c
void scsi_6_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
```

Get LBA and transfer length

**Parameters**

- `const u8 *cdb`: SCSI command to translate
- `u64 *plba`: the LBA
- `u32 *plen`: the transfer length

**Description**

Calculate LBA and transfer length for 6-byte commands.

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

```c
void scsi_10_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
```

Get LBA and transfer length

**Parameters**

- `const u8 *cdb`: SCSI command to translate
- `u64 *plba`: the LBA
- `u32 *plen`: the transfer length

**Description**

Calculate LBA and transfer length for 10-byte commands.

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

```c
void scsi_16_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
```

Get LBA and transfer length

**Parameters**

- `const u8 *cdb`: SCSI command to translate
- `u64 *plba`: the LBA
- `u32 *plen`: the transfer length

**Description**

Calculate LBA and transfer length for 16-byte commands.

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

```c
int scsi_dld(const u8 *cdb)
```

Get duration limit descriptor index

**Parameters**

- `const u8 *cdb`: SCSI command to translate

**Description**

Returns the dld bits indicating the index of a command duration limit
descriptor.

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

```c
unsigned int ata_scsi_verify_xlat(struct ata_queued_cmd *qc)
```

Translate SCSI VERIFY command into an ATA one

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Converts SCSI VERIFY command to an ATA READ VERIFY command.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on error.

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

```c
unsigned int ata_scsi_rw_xlat(struct ata_queued_cmd *qc)
```

Translate SCSI r/w command into an ATA one

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Converts any of six SCSI read/write commands into the
ATA counterpart, including starting sector (LBA),
sector count, and taking into account the device's LBA48
support.

Commands `READ_6`, `READ_10`, `READ_16`, `WRITE_6`, `WRITE_10`, and
`WRITE_16` are currently supported.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on error.

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

```c
int ata_scsi_translate(struct ata_device *dev, struct scsi_cmnd *cmd, ata_xlat_func_t xlat_func)
```

Translate then issue SCSI command to ATA device

**Parameters**

- `struct ata_device *dev`: ATA device to which the command is addressed
- `struct scsi_cmnd *cmd`: SCSI command to execute
- `ata_xlat_func_t xlat_func`: Actor which translates **cmd** to an ATA taskfile

**Description**

Our ->`queuecommand()` function has decided that the SCSI
command issued can be directly translated into an ATA
command, rather than handled internally.

This function sets up an ata_queued_cmd structure for the
SCSI command, and sends that ata_queued_cmd to the hardware.

The xlat_func argument (actor) returns 0 if ready to execute
ATA command, else 1 to finish translation. If 1 is returned
then cmd->result (and possibly cmd->sense_buffer) are assumed
to be set reflecting an error condition or clean (early)
termination.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

0 on success, SCSI_ML_QUEUE_DEVICE_BUSY or SCSI_MLQUEUE_HOST_BUSY if the
command needs to be deferred.

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

```c
void ata_scsi_rbuf_fill(struct ata_device *dev, struct scsi_cmnd *cmd, unsigned int (*actor)(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf))
```

wrapper for SCSI command simulators

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `unsigned int (*actor)(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)`: Callback hook for desired SCSI command simulator

**Description**

Takes care of the hard work of simulating a SCSI command...
Mapping the response buffer, calling the command's handler,
and handling the handler's return value.  This return value
indicates whether the handler wishes the SCSI command to be
completed successfully (0), or not (in which case cmd->result
and sense buffer are assumed to be set).

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_std(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate standard INQUIRY command

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Returns standard device identification data associated
with non-VPD INQUIRY command output.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_00(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page 0, list of pages

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Returns list of inquiry VPD pages available.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_80(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page 80, device serial number

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Returns ATA device serial number.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_83(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page 83, device identity

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

- Yields two logical unit device identification designators:
  - vendor specific ASCII containing the ATA serial number
  - SAT defined "t10 vendor id based" containing ASCII vendor
    name ("ATA     "), model and serial numbers.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_89(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page 89, ATA info

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Yields SAT-specified ATA VPD page.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_b0(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B0, Block Limits

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B0h (Block Limits).

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_b1(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B1, Block Device Characteristics

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B1h (Block Device Characteristics).

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_b2(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B2, Logical Block Provisioning

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B2h (Logical Block Provisioning).

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_b6(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B6, Zoned Block Device Characteristics

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B2h (Zoned Block Device Characteristics).

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inq_b9(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY VPD page B9, Concurrent Positioning Ranges

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Return data for the VPD page B9h (Concurrent Positioning Ranges).

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_inquiry(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate INQUIRY command

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Returns data associated with an INQUIRY command output.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void modecpy(u8 *dest, const u8 *src, int n, bool changeable)
```

Prepare response for MODE SENSE

**Parameters**

- `u8 *dest`: output buffer
- `const u8 *src`: data being copied
- `int n`: length of mode page
- `bool changeable`: whether changeable parameters are requested

**Description**

Generate a generic MODE SENSE page for either current or changeable
parameters.

LOCKING:
None.

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

```c
unsigned int ata_msense_caching(u16 *id, u8 *buf, bool changeable)
```

Simulate MODE SENSE caching info page

**Parameters**

- `u16 *id`: device IDENTIFY data
- `u8 *buf`: output buffer
- `bool changeable`: whether changeable parameters are requested

**Description**

Generate a caching info page, which conditionally indicates
write caching to the SCSI layer, depending on device
capabilities.

LOCKING:
None.

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

```c
unsigned int ata_msense_control(struct ata_device *dev, u8 *buf, u8 spg, bool changeable)
```

Simulate MODE SENSE control mode page

**Parameters**

- `struct ata_device *dev`: ATA device of interest
- `u8 *buf`: output buffer
- `u8 spg`: sub-page code
- `bool changeable`: whether changeable parameters are requested

**Description**

Generate a generic MODE SENSE control mode page.

LOCKING:
None.

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

```c
unsigned int ata_msense_rw_recovery(u8 *buf, bool changeable)
```

Simulate MODE SENSE r/w error recovery page

**Parameters**

- `u8 *buf`: output buffer
- `bool changeable`: whether changeable parameters are requested

**Description**

Generate a generic MODE SENSE r/w error recovery page.

LOCKING:
None.

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

```c
unsigned int ata_scsiop_mode_sense(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate MODE SENSE 6, 10 commands

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Simulate MODE SENSE commands. Assume this is invoked for direct
access devices (e.g. disks) only. There should be no block
descriptor for other device types.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsiop_read_cap(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate READ CAPACITY\[ 16\] commands

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Simulate READ CAPACITY commands.

LOCKING:
None.

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

```c
unsigned int ata_scsiop_report_luns(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate REPORT LUNS command

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Simulate REPORT LUNS command.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int atapi_xlat(struct ata_queued_cmd *qc)
```

Initialize PACKET taskfile

**Parameters**

- `struct ata_queued_cmd *qc`: command structure to be initialized

**Description**

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Zero on success, non-zero on failure.

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

```c
struct ata_device * ata_scsi_find_dev(struct ata_port *ap, const struct scsi_device *scsidev)
```

lookup ata_device from scsi_cmnd

**Parameters**

- `struct ata_port *ap`: ATA port to which the device is attached
- `const struct scsi_device *scsidev`: SCSI device from which we derive the ATA device

**Description**

Given various information provided in struct scsi_cmnd,
map that onto an ATA bus, and using that mapping
determine which ata_device is associated with the
SCSI command to be sent.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

Associated ATA device, or `NULL` if not found.

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

```c
unsigned int ata_scsi_pass_thru(struct ata_queued_cmd *qc)
```

convert ATA pass-thru CDB to taskfile

**Parameters**

- `struct ata_queued_cmd *qc`: command structure to be initialized

**Description**

Handles either 12, 16, or 32-byte versions of the CDB.

**Return**

Zero on success, non-zero on failure.

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

```c
size_t ata_format_dsm_trim_descr(struct scsi_cmnd *cmd, u32 trmax, u64 sector, u32 count)
```

SATL Write Same to DSM Trim

**Parameters**

- `struct scsi_cmnd *cmd`: SCSI command being translated
- `u32 trmax`: Maximum number of entries that will fit in sector_size bytes.
- `u64 sector`: Starting sector
- `u32 count`: Total Range of request in logical sectors

**Description**

Rewrite the WRITE SAME descriptor to be a DSM TRIM little-endian formatted
descriptor.

- Upto 64 entries of the format:
  63:48 Range Length
  47:0  LBA

  Range Length of 0 is ignored.
  LBA's should be sorted order and not overlap.

**NOTE**

this is the same format as ADD LBA(S) TO NV CACHE PINNED SET

**Return**

Number of bytes copied into sglist.

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

```c
unsigned int ata_scsi_write_same_xlat(struct ata_queued_cmd *qc)
```

SATL Write Same to ATA SCT Write Same

**Parameters**

- `struct ata_queued_cmd *qc`: Command to be translated

**Description**

Translate a SCSI WRITE SAME command to be either a DSM TRIM command or
an SCT Write Same command.
Based on WRITE SAME has the UNMAP flag:

- When set translate to DSM TRIM
- When clear translate to SCT Write Same

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

```c
unsigned int ata_scsiop_maint_in(struct ata_device *dev, struct scsi_cmnd *cmd, u8 *rbuf)
```

Simulate a subset of MAINTENANCE_IN

**Parameters**

- `struct ata_device *dev`: Target device.
- `struct scsi_cmnd *cmd`: SCSI command of interest.
- `u8 *rbuf`: Response buffer, to which simulated SCSI cmd output is sent.

**Description**

Yields a subset to satisfy [`scsi_report_opcode()`](/kernel/hardware/driver-api/buses/scsi.md#c-scsi_report_opcode)

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_scsi_report_zones_complete(struct ata_queued_cmd *qc)
```

convert ATA output

**Parameters**

- `struct ata_queued_cmd *qc`: command structure returning the data

**Description**

Convert T-13 little-endian field representation into
T-10 big-endian field representation.
What a mess.

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

```c
int ata_mselect_caching(struct ata_queued_cmd *qc, const u8 *buf, int len, u16 *fp)
```

Simulate MODE SELECT for caching info page

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile
- `const u8 *buf`: input buffer
- `int len`: number of valid bytes in the input buffer
- `u16 *fp`: out parameter for the failed field on error

**Description**

Prepare a taskfile to modify caching information for the device.

LOCKING:
None.

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

```c
int ata_mselect_control(struct ata_queued_cmd *qc, u8 spg, const u8 *buf, int len, u16 *fp)
```

Simulate MODE SELECT for control page

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile
- `u8 spg`: target sub-page of the control page
- `const u8 *buf`: input buffer
- `int len`: number of valid bytes in the input buffer
- `u16 *fp`: out parameter for the failed field on error

**Description**

Prepare a taskfile to modify caching information for the device.

LOCKING:
None.

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

```c
unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc)
```

Simulate MODE SELECT 6, 10 commands

**Parameters**

- `struct ata_queued_cmd *qc`: Storage for translated ATA taskfile

**Description**

Converts a MODE SELECT command to an ATA SET FEATURES taskfile.
Assume this is invoked for direct access devices (e.g. disks) only.
There should be no block descriptor for other device types.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
unsigned int ata_scsi_var_len_cdb_xlat(struct ata_queued_cmd *qc)
```

SATL variable length CDB to Handler

**Parameters**

- `struct ata_queued_cmd *qc`: Command to be translated

**Description**

Translate a SCSI variable length CDB to specified commands.
It checks a service action value in CDB to call corresponding handler.

**Return**

Zero on success, non-zero on failure

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

```c
ata_xlat_func_t ata_get_xlat_func(struct ata_device *dev, u8 cmd)
```

check if SCSI to ATA translation is possible

**Parameters**

- `struct ata_device *dev`: ATA device
- `u8 cmd`: SCSI command opcode to consider

**Description**

Look up the SCSI command given, and determine whether the
SCSI command is to be translated or simulated.

**Return**

Pointer to translation function if possible, `NULL` if not.

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

```c
void ata_scsi_simulate(struct ata_device *dev, struct scsi_cmnd *cmd)
```

simulate SCSI command on ATA device

**Parameters**

- `struct ata_device *dev`: the target device
- `struct scsi_cmnd *cmd`: SCSI command being sent to device.

**Description**

Interprets and directly executes a select list of SCSI commands
that can be handled internally.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
bool ata_scsi_offline_dev(struct ata_device *dev)
```

offline attached SCSI device

**Parameters**

- `struct ata_device *dev`: ATA device to offline attached SCSI device for

**Description**

This function is called from [`ata_eh_detach_dev()`](#c-ata_eh_detach_dev) and is responsible for
taking the SCSI device attached to **dev** offline.  This function is
called with host lock which protects dev->sdev against clearing.

LOCKING:
spin_lock_irqsave(host lock)

**Return**

true if attached SCSI device exists, false otherwise.

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

```c
void ata_scsi_remove_dev(struct ata_device *dev)
```

remove attached SCSI device

**Parameters**

- `struct ata_device *dev`: ATA device to remove attached SCSI device for

**Description**

This function is called from `ata_eh_scsi_hotplug()` and
responsible for removing the SCSI device attached to **dev**.

LOCKING:
Kernel thread context (may sleep).

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

```c
void ata_scsi_media_change_notify(struct ata_device *dev)
```

send media change event

**Parameters**

- `struct ata_device *dev`: Pointer to the disk device with media change event

**Description**

Tell the block layer to send a media change notification
event.

LOCKING:
spin_lock_irqsave(host lock)

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

```c
void ata_scsi_hotplug(struct work_struct *work)
```

SCSI part of hotplug

**Parameters**

- `struct work_struct *work`: Pointer to ATA port to perform SCSI hotplug on

**Description**

Perform SCSI part of hotplug.  It's executed from a separate
workqueue after EH completes.  This is necessary because SCSI
hot plugging requires working EH and hot unplugging is
synchronized with hot plugging with a mutex.

LOCKING:
Kernel thread context (may sleep).

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

```c
int ata_scsi_user_scan(struct Scsi_Host *shost, unsigned int channel, unsigned int id, u64 lun)
```

indication for user-initiated bus scan

**Parameters**

- `struct Scsi_Host *shost`: SCSI host to scan
- `unsigned int channel`: Channel to scan
- `unsigned int id`: ID to scan
- `u64 lun`: LUN to scan

**Description**

This function is called when user explicitly requests bus
scan.  Set probe pending flag and invoke EH.

LOCKING:
SCSI layer (we don't care)

**Return**

Zero.

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

```c
void ata_scsi_dev_rescan(struct work_struct *work)
```

initiate `scsi_rescan_device()`

**Parameters**

- `struct work_struct *work`: Pointer to ATA port to perform `scsi_rescan_device()`

**Description**

After ATA pass thru (SAT) commands are executed successfully,
libata need to propagate the changes to SCSI layer.

LOCKING:
Kernel thread context (may sleep).


<a id="rst-ata-errors-and-exceptions"></a>

## ATA errors and exceptions

This chapter tries to identify what error/exception conditions exist for ATA/ATAPI devices and describe how they should be handled in implementation-neutral way.

The term 'error' is used to describe conditions where either an explicit error condition is reported from device or a command has timed out.

The term 'exception' is either used to describe exceptional conditions which are not errors (say, power or hotplug events), or to describe both errors and non-error exceptional conditions. Where explicit distinction between error and exception is necessary, the term 'non-error exception' is used.

<a id="rst-exception-categories"></a>

### Exception categories

Exceptions are described primarily with respect to legacy taskfile + bus master IDE interface. If a controller provides other better mechanism for error reporting, mapping those into categories described below shouldn't be difficult.

In the following sections, two recovery actions - reset and reconfiguring transport - are mentioned. These are described further in [EH recovery actions](#rst-eh-recovery-actions).

<a id="rst-hsm-violation"></a>

#### HSM violation

This error is indicated when STATUS value doesn't match HSM requirement during issuing or execution any ATA/ATAPI command.

- ATA_STATUS doesn't contain \!BSY &amp;&amp; DRDY &amp;&amp; \!DRQ while trying to issue a command.

- \!BSY &amp;&amp; \!DRQ during PIO data transfer.

- DRQ on command completion.

- \!BSY &amp;&amp; ERR after CDB transfer starts but before the last byte of CDB is transferred. ATA/ATAPI standard states that "The device shall not terminate the PACKET command with an error before the last byte of the command packet has been written" in the error outputs description of PACKET command and the state diagram doesn't include such transitions.

In these cases, HSM is violated and not much information regarding the error can be acquired from STATUS or ERROR register. IOW, this error can be anything - driver bug, faulty device, controller and/or cable.

As HSM is violated, reset is necessary to restore known state. Reconfiguring transport for lower speed might be helpful too as transmission errors sometimes cause this kind of errors.

<a id="rst-ata-atapi-device-error-non-ncq-non-check-condition"></a>

#### ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)

These are errors detected and reported by ATA/ATAPI devices indicating device problems. For this type of errors, STATUS and ERROR register values are valid and describe error condition. Note that some of ATA bus errors are detected by ATA/ATAPI devices and reported using the same mechanism as device errors. Those cases are described later in this section.

For ATA commands, this type of errors are indicated by \!BSY &amp;&amp; ERR during command execution and on completion.

For ATAPI commands,

- \!BSY &amp;&amp; ERR &amp;&amp; ABRT right after issuing PACKET indicates that PACKET command is not supported and falls in this category.

- \!BSY &amp;&amp; ERR(==CHK) &amp;&amp; \!ABRT after the last byte of CDB is transferred indicates CHECK CONDITION and doesn't fall in this category.

- \!BSY &amp;&amp; ERR(==CHK) &amp;&amp; ABRT after the last byte of CDB is transferred \*probably\* indicates CHECK CONDITION and doesn't fall in this category.

Of errors detected as above, the following are not ATA/ATAPI device errors but ATA bus errors and should be handled according to [ATA bus error](#rst-ata-bus-error).

- **CRC error during data transfer**

  This is indicated by ICRC bit in the ERROR register and means that corruption occurred during data transfer. Up to ATA/ATAPI-7, the standard specifies that this bit is only applicable to UDMA transfers but ATA/ATAPI-8 draft revision 1f says that the bit may be applicable to multiword DMA and PIO.

- **ABRT error during data transfer or on completion**

  Up to ATA/ATAPI-7, the standard specifies that ABRT could be set on ICRC errors and on cases where a device is not able to complete a command. Combined with the fact that MWDMA and PIO transfer errors aren't allowed to use ICRC bit up to ATA/ATAPI-7, it seems to imply that ABRT bit alone could indicate transfer errors.

  However, ATA/ATAPI-8 draft revision 1f removes the part that ICRC errors can turn on ABRT. So, this is kind of gray area. Some heuristics are needed here.

ATA/ATAPI device errors can be further categorized as follows.

- **Media errors**

  This is indicated by UNC bit in the ERROR register. ATA devices reports UNC error only after certain number of retries cannot recover the data, so there's nothing much else to do other than notifying upper layer.

  READ and WRITE commands report CHS or LBA of the first failed sector but ATA/ATAPI standard specifies that the amount of transferred data on error completion is indeterminate, so we cannot assume that sectors preceding the failed sector have been transferred and thus cannot complete those sectors successfully as SCSI does.

- **Media changed / media change requested error**

  &lt;&lt;TODO: fill here&gt;&gt;

- **Address error**

  This is indicated by IDNF bit in the ERROR register. Report to upper layer.

- **Other errors**

  This can be invalid command or parameter indicated by ABRT ERROR bit or some other error condition. Note that ABRT bit can indicate a lot of things including ICRC and Address errors. Heuristics needed.

Depending on commands, not all STATUS/ERROR bits are applicable. These non-applicable bits are marked with "na" in the output descriptions but up to ATA/ATAPI-7 no definition of "na" can be found. However, ATA/ATAPI-8 draft revision 1f describes "N/A" as follows.

> - **3.2.3.3a N/A**
>
>   A keyword the indicates a field has no defined value in this standard and should not be checked by the host or device. N/A fields should be cleared to zero.

So, it seems reasonable to assume that "na" bits are cleared to zero by devices and thus need no explicit masking.

<a id="rst-atapi-device-check-condition"></a>

#### ATAPI device CHECK CONDITION

ATAPI device CHECK CONDITION error is indicated by set CHK bit (ERR bit) in the STATUS register after the last byte of CDB is transferred for a PACKET command. For this kind of errors, sense data should be acquired to gather information regarding the errors. REQUEST SENSE packet command should be used to acquire sense data.

Once sense data is acquired, this type of errors can be handled similarly to other SCSI errors. Note that sense data may indicate ATA bus error (e.g. Sense Key 04h HARDWARE ERROR &amp;&amp; ASC/ASCQ 47h/00h SCSI PARITY ERROR). In such cases, the error should be considered as an ATA bus error and handled according to [ATA bus error](#rst-ata-bus-error).

<a id="rst-ata-device-error-ncq"></a>

#### ATA device error (NCQ)

NCQ command error is indicated by cleared BSY and set ERR bit during NCQ command phase (one or more NCQ commands outstanding). Although STATUS and ERROR registers will contain valid values describing the error, READ LOG EXT is required to clear the error condition, determine which command has failed and acquire more information.

READ LOG EXT Log Page 10h reports which tag has failed and taskfile register values describing the error. With this information the failed command can be handled as a normal ATA command error as in [ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)](#rst-ata-atapi-device-error-non-ncq-non-check-condition) and all other in-flight commands must be retried. Note that this retry should not be counted - it's likely that commands retried this way would have completed normally if it were not for the failed command.

Note that ATA bus errors can be reported as ATA device NCQ errors. This should be handled as described in [ATA bus error](#rst-ata-bus-error).

If READ LOG EXT Log Page 10h fails or reports NQ, we're thoroughly screwed. This condition should be treated according to [HSM violation](#rst-hsm-violation).

<a id="rst-ata-bus-error"></a>

#### ATA bus error

ATA bus error means that data corruption occurred during transmission over ATA bus (SATA or PATA). This type of errors can be indicated by

- ICRC or ABRT error as described in [ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)](#rst-ata-atapi-device-error-non-ncq-non-check-condition).

- Controller-specific error completion with error information indicating transmission error.

- On some controllers, command timeout. In this case, there may be a mechanism to determine that the timeout is due to transmission error.

- Unknown/random errors, timeouts and all sorts of weirdities.

As described above, transmission errors can cause wide variety of symptoms ranging from device ICRC error to random device lockup, and, for many cases, there is no way to tell if an error condition is due to transmission error or not; therefore, it's necessary to employ some kind of heuristic when dealing with errors and timeouts. For example, encountering repetitive ABRT errors for known supported command is likely to indicate ATA bus error.

Once it's determined that ATA bus errors have possibly occurred, lowering ATA bus transmission speed is one of actions which may alleviate the problem. See [Reconfigure transport](#rst-reconfigure-transport) for more information.

<a id="rst-pci-bus-error"></a>

#### PCI bus error

Data corruption or other failures during transmission over PCI (or other system bus). For standard BMDMA, this is indicated by Error bit in the BMDMA Status register. This type of errors must be logged as it indicates something is very wrong with the system. Resetting host controller is recommended.

<a id="rst-late-completion"></a>

#### Late completion

This occurs when timeout occurs and the timeout handler finds out that the timed out command has completed successfully or with error. This is usually caused by lost interrupts. This type of errors must be logged. Resetting host controller is recommended.

<a id="rst-unknown-error-timeout"></a>

#### Unknown error (timeout)

This is when timeout occurs and the command is still processing or the host and device are in unknown state. When this occurs, HSM could be in any valid or invalid state. To bring the device to known state and make it forget about the timed out command, resetting is necessary. The timed out command may be retried.

Timeouts can also be caused by transmission errors. Refer to [ATA bus error](#rst-ata-bus-error) for more details.

<a id="rst-hotplug-and-power-management-exceptions"></a>

#### Hotplug and power management exceptions

&lt;&lt;TODO: fill here&gt;&gt;

<a id="rst-eh-recovery-actions"></a>

### EH recovery actions

This section discusses several important recovery actions.

<a id="rst-clearing-error-condition"></a>

#### Clearing error condition

Many controllers require its error registers to be cleared by error handler. Different controllers may have different requirements.

For SATA, it's strongly recommended to clear at least SError register during error handling.

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

#### Reset

During EH, resetting is necessary in the following cases.

- HSM is in unknown or invalid state

- HBA is in unknown or invalid state

- EH needs to make HBA/device forget about in-flight commands

- HBA/device behaves weirdly

Resetting during EH might be a good idea regardless of error condition to improve EH robustness. Whether to reset both or either one of HBA and device depends on situation but the following scheme is recommended.

- When it's known that HBA is in ready state but ATA/ATAPI device is in unknown state, reset only device.

- If HBA is in unknown state, reset both HBA and device.

HBA resetting is implementation specific. For a controller complying to taskfile/BMDMA PCI IDE, stopping active DMA transaction may be sufficient iff BMDMA state is the only HBA context. But even mostly taskfile/BMDMA PCI IDE complying controllers may have implementation specific requirements and mechanism to reset themselves. This must be addressed by specific drivers.

OTOH, ATA/ATAPI standard describes in detail ways to reset ATA/ATAPI devices.

- **PATA hardware reset**

  This is hardware initiated device reset signalled with asserted PATA RESET- signal. There is no standard way to initiate hardware reset from software although some hardware provides registers that allow driver to directly tweak the RESET- signal.

- **Software reset**

  This is achieved by turning CONTROL SRST bit on for at least 5us. Both PATA and SATA support it but, in case of SATA, this may require controller-specific support as the second Register FIS to clear SRST should be transmitted while BSY bit is still set. Note that on PATA, this resets both master and slave devices on a channel.

- **EXECUTE DEVICE DIAGNOSTIC command**

  Although ATA/ATAPI standard doesn't describe exactly, EDD implies some level of resetting, possibly similar level with software reset. Host-side EDD protocol can be handled with normal command processing and most SATA controllers should be able to handle EDD's just like other commands. As in software reset, EDD affects both devices on a PATA bus.

  Although EDD does reset devices, this doesn't suit error handling as EDD cannot be issued while BSY is set and it's unclear how it will act when device is in unknown/weird state.

- **ATAPI DEVICE RESET command**

  This is very similar to software reset except that reset can be restricted to the selected device without affecting the other device sharing the cable.

- **SATA phy reset**

  This is the preferred way of resetting a SATA device. In effect, it's identical to PATA hardware reset. Note that this can be done with the standard SCR Control register. As such, it's usually easier to implement than software reset.

One more thing to consider when resetting devices is that resetting clears certain configuration parameters and they need to be set to their previous or newly adjusted values after reset.

Parameters affected are.

- CHS set up with INITIALIZE DEVICE PARAMETERS (seldom used)

- Parameters set with SET FEATURES including transfer mode setting

- Block count set with SET MULTIPLE MODE

- Other parameters (SET MAX, MEDIA LOCK...)

ATA/ATAPI standard specifies that some parameters must be maintained across hardware or software reset, but doesn't strictly specify all of them. Always reconfiguring needed parameters after reset is required for robustness. Note that this also applies when resuming from deep sleep (power-off).

Also, ATA/ATAPI standard requires that IDENTIFY DEVICE / IDENTIFY PACKET DEVICE is issued after any configuration parameter is updated or a hardware reset and the result used for further operation. OS driver is required to implement revalidation mechanism to support this.

<a id="rst-reconfigure-transport"></a>

#### Reconfigure transport

For both PATA and SATA, a lot of corners are cut for cheap connectors, cables or controllers and it's quite common to see high transmission error rate. This can be mitigated by lowering transmission speed.

The following is a possible scheme Jeff Garzik suggested.

> If more than $N (3?) transmission errors happen in 15 minutes,
>
> - if SATA, decrease SATA PHY speed. if speed cannot be decreased,
>
> - decrease UDMA xfer speed. if at UDMA0, switch to PIO4,
>
> - decrease PIO xfer speed. if at PIO3, complain, but continue

<a id="rst-ata-piix-internals"></a>

## ata_piix Internals


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

```c
int ich_pata_cable_detect(struct ata_port *ap)
```

Probe host controller cable detect info

**Parameters**

- `struct ata_port *ap`: Port for which cable detect info is desired

**Description**

Read 80c cable indicator from ATA PCI device's PCI config
register.  This register is normally set by firmware (BIOS).

LOCKING:
None (inherited from caller).

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

```c
int piix_pata_prereset(struct ata_link *link, unsigned long deadline)
```

prereset for PATA host controller

**Parameters**

- `struct ata_link *link`: Target link
- `unsigned long deadline`: deadline jiffies for the operation

**Description**

LOCKING:
None (inherited from caller).

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

```c
void piix_set_piomode(struct ata_port *ap, struct ata_device *adev)
```

Initialize host controller PATA PIO timings

**Parameters**

- `struct ata_port *ap`: Port whose timings we are configuring
- `struct ata_device *adev`: Drive in question

**Description**

Set PIO mode for device, in host controller PCI config space.

LOCKING:
None (inherited from caller).

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

```c
void do_pata_set_dmamode(struct ata_port *ap, struct ata_device *adev, int isich)
```

Initialize host controller PATA PIO timings

**Parameters**

- `struct ata_port *ap`: Port whose timings we are configuring
- `struct ata_device *adev`: Drive in question
- `int isich`: set if the chip is an ICH device

**Description**

Set UDMA mode for device, in host controller PCI config space.

LOCKING:
None (inherited from caller).

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

```c
void piix_set_dmamode(struct ata_port *ap, struct ata_device *adev)
```

Initialize host controller PATA DMA timings

**Parameters**

- `struct ata_port *ap`: Port whose timings we are configuring
- `struct ata_device *adev`: um

**Description**

Set MW/UDMA mode for device, in host controller PCI config space.

LOCKING:
None (inherited from caller).

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

```c
void ich_set_dmamode(struct ata_port *ap, struct ata_device *adev)
```

Initialize host controller PATA DMA timings

**Parameters**

- `struct ata_port *ap`: Port whose timings we are configuring
- `struct ata_device *adev`: um

**Description**

Set MW/UDMA mode for device, in host controller PCI config space.

LOCKING:
None (inherited from caller).

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

```c
int piix_check_450nx_errata(struct pci_dev *ata_dev)
```

Check for problem 450NX setup

**Parameters**

- `struct pci_dev *ata_dev`: the PCI device to check

**Description**

Check for the present of 450NX errata #19 and errata #25. If
they are found return an error code so we can turn off DMA

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

```c
int piix_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
```

Register PIIX ATA PCI device with kernel services

**Parameters**

- `struct pci_dev *pdev`: PCI device to register
- `const struct pci_device_id *ent`: Entry in piix_pci_tbl matching with **pdev**

**Description**

Called from kernel PCI layer.  We probe for combined mode (sigh),
and then hand over control to libata, for it to do the rest.

LOCKING:
Inherited from PCI layer (may sleep).

**Return**

Zero on success, or -ERRNO value.


<a id="rst-sata-sil-internals"></a>

## sata_sil Internals


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

```c
int sil_set_mode(struct ata_link *link, struct ata_device **r_failed)
```

wrap set_mode functions

**Parameters**

- `struct ata_link *link`: link to set up
- `struct ata_device **r_failed`: returned device when we fail

**Description**

Wrap the libata method for device setup as after the setup we need
to inspect the results and do some configuration work

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

```c
void sil_dev_config(struct ata_device *dev)
```

Apply device/host-specific errata fixups

**Parameters**

- `struct ata_device *dev`: Device to be examined

**Description**

After the IDENTIFY \[PACKET\] DEVICE step is complete, and a
device is known to be present, this function is called.
We apply two errata fixups which are specific to Silicon Image,
a Seagate and a Maxtor fixup.

For certain Seagate devices, we must limit the maximum sectors
to under 8K.

For certain Maxtor devices, we must not program the drive
beyond udma5.

Both fixups are unfairly pessimistic.  As soon as I get more
information on these errata, I will create a more exhaustive
list, and apply the fixups to only the specific
devices/hosts/firmwares that need it.

20040111 - Seagate drives affected by the Mod15Write bug are quirked
The Maxtor quirk is in sil_quirks, but I'm keeping the original
pessimistic fix for the following reasons...
- There seems to be less info on it, only one device gleaned off the
Windows driver, maybe only one is affected.  More info would be greatly
appreciated.
- But then again UDMA5 is hardly anything to complain about


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

## Thanks

The bulk of the ATA knowledge comes thanks to long conversations with Andre Hedrick (www.linux-ide.org), and long hours pondering the ATA and SCSI specifications.

Thanks to Alan Cox for pointing out similarities between SATA and SCSI, and in general for motivation to hack on libata.

libata's device detection method, ata_pio_devchk, and in general all the early probing was based on extensive study of Hale Landis's probe/reset code in his ATADRVR driver (www.ata-atapi.com).

---

# MEN Chameleon Bus

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> This document describes the architecture and implementation of the MEN Chameleon Bus (called MCB throughout this document).

<a id="rst-men-chameleon-bus"></a>

<!-- Table of Contents
=================
1 Introduction
    1.1 Scope of this Document
    1.2 Limitations of the current implementation
2 Architecture
    2.1 MEN Chameleon Bus
    2.2 Carrier Devices
    2.3 Parser
3 Resource handling
    3.1 Memory Resources
    3.2 IRQs
4 Writing an MCB driver
    4.1 The driver structure
    4.2 Probing and attaching
    4.3 Initializing the driver
    4.4 Using DMA -->

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

## Introduction

This document describes the architecture and implementation of the MEN Chameleon Bus (called MCB throughout this document).

<a id="rst-scope-of-this-document"></a>

### Scope of this Document

This document is intended to be a short overview of the current implementation and does by no means describe the complete possibilities of MCB based devices.

<a id="rst-limitations-of-the-current-implementation"></a>

### Limitations of the current implementation

The current implementation is limited to PCI and PCIe based carrier devices that only use a single memory resource and share the PCI legacy IRQ.  Not implemented are:

- Multi-resource MCB devices like the VME Controller or M-Module carrier.

- MCB devices that need another MCB device, like SRAM for a DMA Controller's buffer descriptors or a video controller's video memory.

- A per-carrier IRQ domain for carrier devices that have one (or more) IRQs per MCB device like PCIe based carriers with MSI or MSI-X support.

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

## Architecture

MCB is divided into 3 functional blocks:

- The MEN Chameleon Bus itself,

- drivers for MCB Carrier Devices and

- the parser for the Chameleon table.

<a id="rst-men-chameleon-bus-1"></a>

### MEN Chameleon Bus

The MEN Chameleon Bus is an artificial bus system that attaches to a so called Chameleon FPGA device found on some hardware produced my MEN Mikro Elektronik GmbH. These devices are multi-function devices implemented in a single FPGA and usually attached via some sort of PCI or PCIe link. Each FPGA contains a header section describing the content of the FPGA. The header lists the device id, PCI BAR, offset from the beginning of the PCI BAR, size in the FPGA, interrupt number and some other properties currently not handled by the MCB implementation.

<a id="rst-carrier-devices"></a>

### Carrier Devices

A carrier device is just an abstraction for the real world physical bus the Chameleon FPGA is attached to. Some IP Core drivers may need to interact with properties of the carrier device (like querying the IRQ number of a PCI device). To provide abstraction from the real hardware bus, an MCB carrier device provides callback methods to translate the driver's MCB function calls to hardware related function calls. For example a carrier device may implement the get_irq() method which can be translated into a hardware bus query for the IRQ number the device should use.

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

### Parser

The parser reads the first 512 bytes of a Chameleon device and parses the Chameleon table. Currently the parser only supports the Chameleon v2 variant of the Chameleon table but can easily be adopted to support an older or possible future variant. While parsing the table's entries new MCB devices are allocated and their resources are assigned according to the resource assignment in the Chameleon table. After resource assignment is finished, the MCB devices are registered at the MCB and thus at the driver core of the Linux kernel.

<a id="rst-resource-handling"></a>

## Resource handling

The current implementation assigns exactly one memory and one IRQ resource per MCB device. But this is likely going to change in the future.

<a id="rst-memory-resources"></a>

### Memory Resources

Each MCB device has exactly one memory resource, which can be requested from the MCB bus. This memory resource is the physical address of the MCB device inside the carrier and is intended to be passed to ioremap() and friends. It is already requested from the kernel by calling request_mem_region().

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

### IRQs

Each MCB device has exactly one IRQ resource, which can be requested from the MCB bus. If a carrier device driver implements the -&gt;get_irq() callback method, the IRQ number assigned by the carrier device will be returned, otherwise the IRQ number inside the Chameleon table will be returned. This number is suitable to be passed to request_irq().

<a id="rst-writing-an-mcb-driver"></a>

## Writing an MCB driver

<a id="rst-the-driver-structure"></a>

### The driver structure

Each MCB driver has a structure to identify the device driver as well as device ids which identify the IP Core inside the FPGA. The driver structure also contains callback methods which get executed on driver probe and removal from the system:



```text
static const struct mcb_device_id foo_ids[] = {
        { .device = 0x123 },
        { }
};
MODULE_DEVICE_TABLE(mcb, foo_ids);

static struct mcb_driver foo_driver = {
driver = {
        .name = "foo-bar",
        .owner = THIS_MODULE,
},
        .probe = foo_probe,
        .remove = foo_remove,
        .id_table = foo_ids,
};
```

<a id="rst-probing-and-attaching"></a>

### Probing and attaching

When a driver is loaded and the MCB devices it services are found, the MCB core will call the driver's probe callback method. When the driver is removed from the system, the MCB core will call the driver's remove callback method:



```text
static init foo_probe(struct mcb_device *mdev, const struct mcb_device_id *id);
static void foo_remove(struct mcb_device *mdev);
```

<a id="rst-initializing-the-driver"></a>

### Initializing the driver

When the kernel is booted or your foo driver module is inserted, you have to perform driver initialization. Usually it is enough to register your driver module at the MCB core:



```text
static int __init foo_init(void)
{
        return mcb_register_driver(&foo_driver);
}
module_init(foo_init);

static void __exit foo_exit(void)
{
        mcb_unregister_driver(&foo_driver);
}
module_exit(foo_exit);
```

The module_mcb_driver() macro can be used to reduce the above code:



```text
module_mcb_driver(foo_driver);
```

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

### Using DMA

To make use of the kernel's DMA-API's function, you will need to use the carrier device's 'struct device'. Fortunately 'struct mcb_device' embeds a pointer (-&gt;dma_dev) to the carrier's device for DMA purposes:



```text
ret = dma_set_mask_and_coherent(&mdev->dma_dev, DMA_BIT_MASK(dma_bits));
if (rc)
        /* Handle errors */
```

---

# NTB Drivers

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> NTB (Non-Transparent Bridge) is a type of PCI-Express bridge chip that connects the separate memory systems of two or more computers to the same PCI-Express fabric. Existing NTB hardware supports a common feature set: doorbell registers…

<a id="rst-ntb-drivers"></a>

NTB (Non-Transparent Bridge) is a type of PCI-Express bridge chip that connects the separate memory systems of two or more computers to the same PCI-Express fabric. Existing NTB hardware supports a common feature set: doorbell registers and memory translation windows, as well as non common features like scratchpad and message registers. Scratchpad registers are read-and-writable registers that are accessible from either side of the device, so that peers can exchange a small amount of information at a fixed address. Message registers can be utilized for the same purpose. Additionally they are provided with special status bits to make sure the information isn't rewritten by another peer. Doorbell registers provide a way for peers to send interrupt events. Memory windows allow translated read and write access to the peer memory.

<a id="rst-ntb-core-driver-ntb"></a>

## NTB Core Driver (ntb)

The NTB core driver defines an api wrapping the common feature set, and allows clients interested in NTB features to discover NTB the devices supported by hardware drivers.  The term "client" is used here to mean an upper layer component making use of the NTB api.  The term "driver," or "hardware driver," is used here to mean a driver for a specific vendor and model of NTB hardware.

<a id="rst-ntb-client-drivers"></a>

## NTB Client Drivers

NTB client drivers should register with the NTB core driver.  After registering, the client probe and remove functions will be called appropriately as ntb hardware, or hardware drivers, are inserted and removed.  The registration uses the Linux Device framework, so it should feel familiar to anyone who has written a pci driver.

<a id="rst-ntb-typical-client-driver-implementation"></a>

### NTB Typical client driver implementation

Primary purpose of NTB is to share some piece of memory between at least two systems. So the NTB device features like Scratchpad/Message registers are mainly used to perform the proper memory window initialization. Typically there are two types of memory window interfaces supported by the NTB API: inbound translation configured on the local ntb port and outbound translation configured by the peer, on the peer ntb port. The first type is depicted on the next figure:



```text
Inbound translation:

Memory:              Local NTB Port:      Peer NTB Port:      Peer MMIO:
 ____________
| dma-mapped |-ntb_mw_set_trans(addr)  |
| memory     |        _v____________   |   ______________
| (addr)     |<======| MW xlat addr |<====| MW base addr |<== memory-mapped IO
|------------|       |--------------|  |  |--------------|
```

So typical scenario of the first type memory window initialization looks: 1) allocate a memory region, 2) put translated address to NTB config, 3) somehow notify a peer device of performed initialization, 4) peer device maps corresponding outbound memory window so to have access to the shared memory region.

The second type of interface, that implies the shared windows being initialized by a peer device, is depicted on the figure:



```text
Outbound translation:

Memory:        Local NTB Port:    Peer NTB Port:      Peer MMIO:
 ____________                      ______________
| dma-mapped |                |   | MW base addr |<== memory-mapped IO
| memory     |                |   |--------------|
| (addr)     |<===================| MW xlat addr |<-ntb_peer_mw_set_trans(addr)
|------------|                |   |--------------|
```

Typical scenario of the second type interface initialization would be: 1) allocate a memory region, 2) somehow deliver a translated address to a peer device, 3) peer puts the translated address to NTB config, 4) peer device maps outbound memory window so to have access to the shared memory region.

As one can see the described scenarios can be combined in one portable algorithm.

> - **Local device:**
>
>   1. Allocate memory for a shared window
>
>   2. Initialize memory window by translated address of the allocated region (it may fail if local memory window initialization is unsupported)
>
>   3. Send the translated address and memory window index to a peer device
>
> - **Peer device:**
>
>   1. Initialize memory window with retrieved address of the allocated by another device memory region (it may fail if peer memory window initialization is unsupported)
>
>   2. Map outbound memory window

In accordance with this scenario, the NTB Memory Window API can be used as follows:

> - **Local device:**
>
>   1. ntb_mw_count(pidx) - retrieve number of memory ranges, which can be allocated for memory windows between local device and peer device of port with specified index.
>
>   2. ntb_get_align(pidx, midx) - retrieve parameters restricting the shared memory region alignment and size. Then memory can be properly allocated.
>
>   3. Allocate physically contiguous memory region in compliance with restrictions retrieved in 2).
>
>   4. ntb_mw_set_trans(pidx, midx) - try to set translation address of the memory window with specified index for the defined peer device (it may fail if local translated address setting is not supported)
>
>   5. Send translated base address (usually together with memory window number) to the peer device using, for instance, scratchpad or message registers.
>
> - **Peer device:**
>
>   1. ntb_peer_mw_set_trans(pidx, midx) - try to set received from other device (related to pidx) translated address for specified memory window. It may fail if retrieved address, for instance, exceeds maximum possible address or isn't properly aligned.
>
>   2. ntb_peer_mw_get_addr(widx) - retrieve MMIO address to map the memory window so to have an access to the shared memory.

Also it is worth to note, that method ntb_mw_count(pidx) should return the same value as ntb_peer_mw_count() on the peer with port index - pidx.

<a id="rst-ntb-transport-client-ntb-transport-and-ntb-netdev-ntb-netdev"></a>

### NTB Transport Client (ntb_transport) and NTB Netdev (ntb_netdev)

The primary client for NTB is the Transport client, used in tandem with NTB Netdev.  These drivers function together to create a logical link to the peer, across the ntb, to exchange packets of network data.  The Transport client establishes a logical link to the peer, and creates queue pairs to exchange messages and data.  The NTB Netdev then creates an ethernet device using a Transport queue pair.  Network data is copied between socket buffers and the Transport queue pair buffer.  The Transport client may be used for other things besides Netdev, however no other applications have yet been written.

<a id="rst-ntb-ping-pong-test-client-ntb-pingpong"></a>

### NTB Ping Pong Test Client (ntb_pingpong)

The Ping Pong test client serves as a demonstration to exercise the doorbell and scratchpad registers of NTB hardware, and as an example simple NTB client. Ping Pong enables the link when started, waits for the NTB link to come up, and then proceeds to read and write the doorbell scratchpad registers of the NTB. The peers interrupt each other using a bit mask of doorbell bits, which is shifted by one in each round, to test the behavior of multiple doorbell bits and interrupt vectors.  The Ping Pong driver also reads the first local scratchpad, and writes the value plus one to the first peer scratchpad, each round before writing the peer doorbell register.

Module Parameters:

- - **unsafe - Some hardware has known issues with scratchpad and doorbell**

    registers.  By default, Ping Pong will not attempt to exercise such hardware.  You may override this behavior at your own risk by setting unsafe=1.

- - **delay_ms - Specify the delay between receiving a doorbell**

    interrupt event and setting the peer doorbell register for the next round.

- - **init_db - Specify the doorbell bits to start new series of rounds.  A new**

    series begins once all the doorbell bits have been shifted out of range.

- - **dyndbg - It is suggested to specify dyndbg=+p when loading this module, and**

    then to observe debugging output on the console.

<a id="rst-ntb-tool-test-client-ntb-tool"></a>

### NTB Tool Test Client (ntb_tool)

The Tool test client serves for debugging, primarily, ntb hardware and drivers. The Tool provides access through debugfs for reading, setting, and clearing the NTB doorbell, and reading and writing scratchpads.

The Tool does not currently have any module parameters.

Debugfs Files:

- - ***debugfs*/ntb_tool/*hw*/**

    A directory in debugfs will be created for each NTB device probed by the tool.  This directory is shortened to *hw* below.

- - ***hw*/db**

    This file is used to read, set, and clear the local doorbell.  Not all operations may be supported by all hardware.  To read the doorbell, read the file.  To set the doorbell, write `s` followed by the bits to set (eg: `echo 's 0x0101' > db`).  To clear the doorbell, write `c` followed by the bits to clear.

- - ***hw*/mask**

    This file is used to read, set, and clear the local doorbell mask. See *db* for details.

- - ***hw*/peer_db**

    This file is used to read, set, and clear the peer doorbell. See *db* for details.

- - ***hw*/peer_mask**

    This file is used to read, set, and clear the peer doorbell mask.  See *db* for details.

- - ***hw*/spad**

    This file is used to read and write local scratchpads.  To read the values of all scratchpads, read the file.  To write values, write a series of pairs of scratchpad number and value (eg: `echo '4 0x123 7 0xabc' > spad` \# to set scratchpads `4` and `7` to `0x123` and `0xabc`, respectively).

- - ***hw*/peer_spad**

    This file is used to read and write peer scratchpads.  See *spad* for details.

<a id="rst-ntb-msi-test-client-ntb-msi-test"></a>

### NTB MSI Test Client (ntb_msi_test)

The MSI test client serves to test and debug the MSI library which allows for passing MSI interrupts across NTB memory windows. The test client is interacted with through the debugfs filesystem:

- - ***debugfs*/ntb_msi_test/*hw*/**

    A directory in debugfs will be created for each NTB device probed by the msi test.  This directory is shortened to *hw* below.

- - ***hw*/port**

    This file describes the local port number

- - ***hw*/irq\*\_occurrences**

    One occurrences file exists for each interrupt and, when read, returns the number of times the interrupt has been triggered.

- - ***hw*/peer\*/port**

    This file describes the port number for each peer

- - ***hw*/peer\*/count**

    This file describes the number of interrupts that can be triggered on each peer

- - ***hw*/peer\*/trigger**

    Writing an interrupt number (any number less than the value specified in count) will trigger the interrupt on the specified peer. That peer's interrupt's occurrence file should be incremented.

<a id="rst-ntb-hardware-drivers"></a>

## NTB Hardware Drivers

NTB hardware drivers should register devices with the NTB core driver.  After registering, clients probe and remove functions will be called.

<a id="rst-ntb-intel-hardware-driver-ntb-hw-intel"></a>

### NTB Intel Hardware Driver (ntb_hw_intel)

The Intel hardware driver supports NTB on Xeon and Atom CPUs.

Module Parameters:

- - **b2b_mw_idx**

    If the peer ntb is to be accessed via a memory window, then use this memory window to access the peer ntb.  A value of zero or positive starts from the first mw idx, and a negative value starts from the last mw idx.  Both sides MUST set the same value here\!  The default value is `-1`.

- - **b2b_mw_share**

    If the peer ntb is to be accessed via a memory window, and if the memory window is large enough, still allow the client to use the second half of the memory window for address translation to the peer.

- - **xeon_b2b_usd_bar2_addr64**

    If using B2B topology on Xeon hardware, use this 64 bit address on the bus between the NTB devices for the window at BAR2, on the upstream side of the link.

- xeon_b2b_usd_bar4_addr64 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_usd_bar4_addr32 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_usd_bar5_addr32 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_dsd_bar2_addr64 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_dsd_bar4_addr64 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_dsd_bar4_addr32 - See *xeon_b2b_bar2_addr64*.

- xeon_b2b_dsd_bar5_addr32 - See *xeon_b2b_bar2_addr64*.

---

# PARPORT interface documentation

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> Described here are the following functions:

<a id="rst-parport-interface-documentation"></a>

**Time-stamp:** &lt;2000-02-24 13:30:20 twaugh&gt;

Described here are the following functions:

Global functions:



```text
parport_register_driver
parport_unregister_driver
parport_enumerate
parport_register_device
parport_unregister_device
parport_claim
parport_claim_or_block
parport_release
parport_yield
parport_yield_blocking
parport_wait_peripheral
parport_poll_peripheral
parport_wait_event
parport_negotiate
parport_read
parport_write
parport_open
parport_close
parport_device_id
parport_device_coords
parport_find_class
parport_find_device
parport_set_timeout
```

Port functions (can be overridden by low-level drivers):

> SPP:
>
>
>
> ```text
> port->ops->read_data
> port->ops->write_data
> port->ops->read_status
> port->ops->read_control
> port->ops->write_control
> port->ops->frob_control
> port->ops->enable_irq
> port->ops->disable_irq
> port->ops->data_forward
> port->ops->data_reverse
> ```
>
> EPP:
>
>
>
> ```text
> port->ops->epp_write_data
> port->ops->epp_read_data
> port->ops->epp_write_addr
> port->ops->epp_read_addr
> ```
>
> ECP:
>
>
>
> ```text
> port->ops->ecp_write_data
> port->ops->ecp_read_data
> port->ops->ecp_write_addr
> ```
>
> Other:
>
>
>
> ```text
> port->ops->nibble_read_data
> port->ops->byte_read_data
> port->ops->compat_write_data
> ```

The parport subsystem comprises `parport` (the core port-sharing code), and a variety of low-level drivers that actually do the port accesses.  Each low-level driver handles a particular style of port (PC, Amiga, and so on).

The parport interface to the device driver author can be broken down into global functions and port functions.

The global functions are mostly for communicating between the device driver and the parport subsystem: acquiring a list of available ports, claiming a port for exclusive use, and so on.  They also include `generic` functions for doing standard things that will work on any IEEE 1284-capable architecture.

The port functions are provided by the low-level drivers, although the core parport module provides generic `defaults` for some routines. The port functions can be split into three groups: SPP, EPP, and ECP.

SPP (Standard Parallel Port) functions modify so-called `SPP` registers: data, status, and control.  The hardware may not actually have registers exactly like that, but the PC does and this interface is modelled after common PC implementations.  Other low-level drivers may be able to emulate most of the functionality.

EPP (Enhanced Parallel Port) functions are provided for reading and writing in IEEE 1284 EPP mode, and ECP (Extended Capabilities Port) functions are used for IEEE 1284 ECP mode. (What about BECP? Does anyone care?)

Hardware assistance for EPP and/or ECP transfers may or may not be available, and if it is available it may or may not be used.  If hardware is not used, the transfer will be software-driven.  In order to cope with peripherals that only tenuously support IEEE 1284, a low-level driver specific function is provided, for altering 'fudge factors'.

<a id="rst-global-functions"></a>

## Global functions

<a id="rst-parport-register-driver-register-a-device-driver-with-parport"></a>

### parport_register_driver - register a device driver with parport

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

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_driver {
        const char *name;
        void (*attach) (struct parport *);
        void (*detach) (struct parport *);
        struct parport_driver *next;
};
int parport_register_driver (struct parport_driver *driver);
```

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

#### DESCRIPTION

In order to be notified about parallel ports when they are detected, parport_register_driver should be called.  Your driver will immediately be notified of all ports that have already been detected, and of each new port as low-level drivers are loaded.

A `struct parport_driver` contains the textual name of your driver, a pointer to a function to handle new ports, and a pointer to a function to handle ports going away due to a low-level driver unloading.  Ports will only be detached if they are not being used (i.e. there are no devices registered on them).

The visible parts of the `struct parport *` argument given to attach/detach are:



```text
struct parport
{
        struct parport *next; /* next parport in list */
        const char *name;     /* port's name */
        unsigned int modes;   /* bitfield of hardware modes */
        struct parport_device_info probe_info;
                        /* IEEE1284 info */
        int number;           /* parport index */
        struct parport_operations *ops;
        ...
};
```

There are other members of the structure, but they should not be touched.

The `modes` member summarises the capabilities of the underlying hardware.  It consists of flags which may be bitwise-ored together:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> PARPORT_MODE_PCSPP
>
> </td>
> <td>
>
>
> IBM PC registers are available, i.e. functions that act on data, control and status registers are probably writing directly to the hardware.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_TRISTATE
>
> </td>
> <td>
>
>
> The data drivers may be turned off. This allows the data lines to be used for reverse (peripheral to host) transfers.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_COMPAT
>
> </td>
> <td>
>
>
> The hardware can assist with compatibility-mode (printer) transfers, i.e. compat_write_block.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_EPP
>
> </td>
> <td>
>
>
> The hardware can assist with EPP transfers.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_ECP
>
> </td>
> <td>
>
>
> The hardware can assist with ECP transfers.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PARPORT_MODE_DMA
>
> </td>
> <td>
>
>
> The hardware can use DMA, so you might want to pass ISA DMA-able memory (i.e. memory allocated using the GFP_DMA flag with kmalloc) to the low-level driver in order to take advantage of it.
>
> </td>
> </tr>
> </tbody>
> </table>

There may be other flags in `modes` as well.

The contents of `modes` is advisory only.  For example, if the hardware is capable of DMA, and PARPORT_MODE_DMA is in `modes`, it doesn't necessarily mean that DMA will always be used when possible. Similarly, hardware that is capable of assisting ECP transfers won't necessarily be used.

<a id="rst-return-value"></a>

#### RETURN VALUE

Zero on success, otherwise an error code.

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

#### ERRORS

None. (Can it fail? Why return int?)

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

#### EXAMPLE



```text
static void lp_attach (struct parport *port)
{
        ...
        private = kmalloc (...);
        dev[count++] = parport_register_device (...);
        ...
}

static void lp_detach (struct parport *port)
{
        ...
}

static struct parport_driver lp_driver = {
        "lp",
        lp_attach,
        lp_detach,
        NULL /* always put NULL here */
};

int lp_init (void)
{
        ...
        if (parport_register_driver (&lp_driver)) {
                /* Failed; nothing we can do. */
                return -EIO;
        }
        ...
}
```

<a id="rst-see-also"></a>

#### SEE ALSO

parport_unregister_driver, parport_register_device, parport_enumerate

<a id="rst-parport-unregister-driver-tell-parport-to-forget-about-this-driver"></a>

### parport_unregister_driver - tell parport to forget about this driver

<a id="rst-synopsis-1"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_driver {
        const char *name;
        void (*attach) (struct parport *);
        void (*detach) (struct parport *);
        struct parport_driver *next;
};
void parport_unregister_driver (struct parport_driver *driver);
```

<a id="rst-description-1"></a>

#### DESCRIPTION

This tells parport not to notify the device driver of new ports or of ports going away.  Registered devices belonging to that driver are NOT unregistered: parport_unregister_device must be used for each one.

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

#### EXAMPLE



```text
void cleanup_module (void)
{
        ...
        /* Stop notifications. */
        parport_unregister_driver (&lp_driver);

        /* Unregister devices. */
        for (i = 0; i < NUM_DEVS; i++)
                parport_unregister_device (dev[i]);
        ...
}
```

<a id="rst-see-also-1"></a>

#### SEE ALSO

parport_register_driver, parport_enumerate

<a id="rst-parport-enumerate-retrieve-a-list-of-parallel-ports-deprecated"></a>

### parport_enumerate - retrieve a list of parallel ports (DEPRECATED)

<a id="rst-synopsis-2"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport *parport_enumerate (void);
```

<a id="rst-description-2"></a>

#### DESCRIPTION

Retrieve the first of a list of valid parallel ports for this machine. Successive parallel ports can be found using the `struct parport *next` element of the `struct parport *` that is returned.  If `next` is NULL, there are no more parallel ports in the list.  The number of ports in the list will not exceed PARPORT_MAX.

<a id="rst-return-value-1"></a>

#### RETURN VALUE

A `struct parport *` describing a valid parallel port for the machine, or NULL if there are none.

<a id="rst-errors-1"></a>

#### ERRORS

This function can return NULL to indicate that there are no parallel ports to use.

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

#### EXAMPLE



```text
int detect_device (void)
{
        struct parport *port;

        for (port = parport_enumerate ();
        port != NULL;
        port = port->next) {
                /* Try to detect a device on the port... */
                ...
        }
        }

        ...
}
```

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

#### NOTES

parport_enumerate is deprecated; parport_register_driver should be used instead.

<a id="rst-see-also-2"></a>

#### SEE ALSO

parport_register_driver, parport_unregister_driver

<a id="rst-parport-register-device-register-to-use-a-port"></a>

### parport_register_device - register to use a port

<a id="rst-synopsis-3"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

typedef int (*preempt_func) (void *handle);
typedef void (*wakeup_func) (void *handle);
typedef int (*irq_func) (int irq, void *handle, struct pt_regs *);

struct pardevice *parport_register_device(struct parport *port,
                                          const char *name,
                                          preempt_func preempt,
                                          wakeup_func wakeup,
                                          irq_func irq,
                                          int flags,
                                          void *handle);
```

<a id="rst-description-3"></a>

#### DESCRIPTION

Use this function to register your device driver on a parallel port (`port`).  Once you have done that, you will be able to use parport_claim and parport_release in order to use the port.

The (`name`) argument is the name of the device that appears in /proc filesystem. The string must be valid for the whole lifetime of the device (until parport_unregister_device is called).

This function will register three callbacks into your driver: `preempt`, `wakeup` and `irq`.  Each of these may be NULL in order to indicate that you do not want a callback.

When the `preempt` function is called, it is because another driver wishes to use the parallel port.  The `preempt` function should return non-zero if the parallel port cannot be released yet -- if zero is returned, the port is lost to another driver and the port must be re-claimed before use.

The `wakeup` function is called once another driver has released the port and no other driver has yet claimed it.  You can claim the parallel port from within the `wakeup` function (in which case the claim is guaranteed to succeed), or choose not to if you don't need it now.

If an interrupt occurs on the parallel port your driver has claimed, the `irq` function will be called. (Write something about shared interrupts here.)

The `handle` is a pointer to driver-specific data, and is passed to the callback functions.

`flags` may be a bitwise combination of the following flags:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Flag
>
> </th>
> <th>
>
>
> Meaning
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> PARPORT_DEV_EXCL
>
> </td>
> <td>
>
>
> The device cannot share the parallel port at all. Use this only when absolutely necessary.
>
> </td>
> </tr>
> </tbody>
> </table>

The typedefs are not actually defined -- they are only shown in order to make the function prototype more readable.

The visible parts of the returned `struct pardevice` are:



```text
struct pardevice {
        struct parport *port;   /* Associated port */
        void *private;          /* Device driver's 'handle' */
        ...
};
```

<a id="rst-return-value-2"></a>

#### RETURN VALUE

A `struct pardevice *`: a handle to the registered parallel port device that can be used for parport_claim, parport_release, etc.

<a id="rst-errors-2"></a>

#### ERRORS

A return value of NULL indicates that there was a problem registering a device on that port.

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

#### EXAMPLE



```text
static int preempt (void *handle)
{
        if (busy_right_now)
                return 1;

        must_reclaim_port = 1;
        return 0;
}

static void wakeup (void *handle)
{
        struct toaster *private = handle;
        struct pardevice *dev = private->dev;
        if (!dev) return; /* avoid races */

        if (want_port)
                parport_claim (dev);
}

static int toaster_detect (struct toaster *private, struct parport *port)
{
        private->dev = parport_register_device (port, "toaster", preempt,
                                                wakeup, NULL, 0,
                                                private);
        if (!private->dev)
                /* Couldn't register with parport. */
                return -EIO;

        must_reclaim_port = 0;
        busy_right_now = 1;
        parport_claim_or_block (private->dev);
        ...
        /* Don't need the port while the toaster warms up. */
        busy_right_now = 0;
        ...
        busy_right_now = 1;
        if (must_reclaim_port) {
                parport_claim_or_block (private->dev);
                must_reclaim_port = 0;
        }
        ...
}
```

<a id="rst-see-also-3"></a>

#### SEE ALSO

parport_unregister_device, parport_claim

<a id="rst-parport-unregister-device-finish-using-a-port"></a>

### parport_unregister_device - finish using a port

SYNPOPSIS



```text
#include <linux/parport.h>

void parport_unregister_device (struct pardevice *dev);
```

<a id="rst-description-4"></a>

#### DESCRIPTION

This function is the opposite of parport_register_device.  After using parport_unregister_device, `dev` is no longer a valid device handle.

You should not unregister a device that is currently claimed, although if you do it will be released automatically.

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

#### EXAMPLE



```text
...
kfree (dev->private); /* before we lose the pointer */
parport_unregister_device (dev);
...
```

<a id="rst-see-also-4"></a>

#### SEE ALSO

parport_unregister_driver

<a id="rst-parport-claim-parport-claim-or-block-claim-the-parallel-port-for-a-device"></a>

### parport_claim, parport_claim_or_block - claim the parallel port for a device

<a id="rst-synopsis-4"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_claim (struct pardevice *dev);
int parport_claim_or_block (struct pardevice *dev);
```

<a id="rst-description-5"></a>

#### DESCRIPTION

These functions attempt to gain control of the parallel port on which `dev` is registered.  `parport_claim` does not block, but `parport_claim_or_block` may do. (Put something here about blocking interruptibly or non-interruptibly.)

You should not try to claim a port that you have already claimed.

<a id="rst-return-value-3"></a>

#### RETURN VALUE

A return value of zero indicates that the port was successfully claimed, and the caller now has possession of the parallel port.

If `parport_claim_or_block` blocks before returning successfully, the return value is positive.

<a id="rst-errors-3"></a>

#### ERRORS


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


-EAGAIN

</td>
<td>


The port is unavailable at the moment, but another attempt to claim it may succeed.

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

<a id="rst-see-also-5"></a>

#### SEE ALSO

parport_release

<a id="rst-parport-release-release-the-parallel-port"></a>

### parport_release - release the parallel port

<a id="rst-synopsis-5"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

void parport_release (struct pardevice *dev);
```

<a id="rst-description-6"></a>

#### DESCRIPTION

Once a parallel port device has been claimed, it can be released using `parport_release`.  It cannot fail, but you should not release a device that you do not have possession of.

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

#### EXAMPLE



```text
static size_t write (struct pardevice *dev, const void *buf,
                size_t len)
{
        ...
        written = dev->port->ops->write_ecp_data (dev->port, buf,
                                                len);
        parport_release (dev);
        ...
}
```

<a id="rst-see-also-6"></a>

#### SEE ALSO

change_mode, parport_claim, parport_claim_or_block, parport_yield

<a id="rst-parport-yield-parport-yield-blocking-temporarily-release-a-parallel-port"></a>

### parport_yield, parport_yield_blocking - temporarily release a parallel port

<a id="rst-synopsis-6"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_yield (struct pardevice *dev)
int parport_yield_blocking (struct pardevice *dev);
```

<a id="rst-description-7"></a>

#### DESCRIPTION

When a driver has control of a parallel port, it may allow another driver to temporarily `borrow` it.  `parport_yield` does not block; `parport_yield_blocking` may do.

<a id="rst-return-value-4"></a>

#### RETURN VALUE

A return value of zero indicates that the caller still owns the port and the call did not block.

A positive return value from `parport_yield_blocking` indicates that the caller still owns the port and the call blocked.

A return value of -EAGAIN indicates that the caller no longer owns the port, and it must be re-claimed before use.

<a id="rst-errors-4"></a>

#### ERRORS


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


-EAGAIN

</td>
<td>


Ownership of the parallel port was given away.

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

<a id="rst-see-also-7"></a>

#### SEE ALSO

parport_release

<a id="rst-parport-wait-peripheral-wait-for-status-lines-up-to-35ms"></a>

### parport_wait_peripheral - wait for status lines, up to 35ms

<a id="rst-synopsis-7"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_wait_peripheral (struct parport *port,
                             unsigned char mask,
                             unsigned char val);
```

<a id="rst-description-8"></a>

#### DESCRIPTION

Wait for the status lines in mask to match the values in val.

<a id="rst-return-value-5"></a>

#### RETURN VALUE


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


-EINTR

</td>
<td>


a signal is pending

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


0

</td>
<td>


the status lines in mask have values in val

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


1

</td>
<td>


timed out while waiting (35ms elapsed)

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

<a id="rst-see-also-8"></a>

#### SEE ALSO

parport_poll_peripheral

<a id="rst-parport-poll-peripheral-wait-for-status-lines-in-usec"></a>

### parport_poll_peripheral - wait for status lines, in usec

<a id="rst-synopsis-8"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_poll_peripheral (struct parport *port,
                             unsigned char mask,
                             unsigned char val,
                             int usec);
```

<a id="rst-description-9"></a>

#### DESCRIPTION

Wait for the status lines in mask to match the values in val.

<a id="rst-return-value-6"></a>

#### RETURN VALUE


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


-EINTR

</td>
<td>


a signal is pending

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


0

</td>
<td>


the status lines in mask have values in val

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


1

</td>
<td>


timed out while waiting (usec microseconds have elapsed)

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

<a id="rst-see-also-9"></a>

#### SEE ALSO

parport_wait_peripheral

<a id="rst-parport-wait-event-wait-for-an-event-on-a-port"></a>

### parport_wait_event - wait for an event on a port

<a id="rst-synopsis-9"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_wait_event (struct parport *port, signed long timeout)
```

<a id="rst-description-10"></a>

#### DESCRIPTION

Wait for an event (e.g. interrupt) on a port.  The timeout is in jiffies.

<a id="rst-return-value-7"></a>

#### RETURN VALUE


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


0

</td>
<td>


success

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


&lt;0

</td>
<td>


error (exit as soon as possible)

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


&gt;0

</td>
<td>


timed out

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

<a id="rst-parport-negotiate-perform-ieee-1284-negotiation"></a>

### parport_negotiate - perform IEEE 1284 negotiation

<a id="rst-synopsis-10"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_negotiate (struct parport *, int mode);
```

<a id="rst-description-11"></a>

#### DESCRIPTION

Perform IEEE 1284 negotiation.

<a id="rst-return-value-8"></a>

#### RETURN VALUE


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


0

</td>
<td>


handshake OK; IEEE 1284 peripheral and mode available

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


-1

</td>
<td>


handshake failed; peripheral not compliant (or none present)

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


1

</td>
<td>


handshake OK; IEEE 1284 peripheral present but mode not available

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

<a id="rst-see-also-10"></a>

#### SEE ALSO

parport_read, parport_write

<a id="rst-parport-read-read-data-from-device"></a>

### parport_read - read data from device

<a id="rst-synopsis-11"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

ssize_t parport_read (struct parport *, void *buf, size_t len);
```

<a id="rst-description-12"></a>

#### DESCRIPTION

Read data from device in current IEEE 1284 transfer mode.  This only works for modes that support reverse data transfer.

<a id="rst-return-value-9"></a>

#### RETURN VALUE

If negative, an error code; otherwise the number of bytes transferred.

<a id="rst-see-also-11"></a>

#### SEE ALSO

parport_write, parport_negotiate

<a id="rst-parport-write-write-data-to-device"></a>

### parport_write - write data to device

<a id="rst-synopsis-12"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

ssize_t parport_write (struct parport *, const void *buf, size_t len);
```

<a id="rst-description-13"></a>

#### DESCRIPTION

Write data to device in current IEEE 1284 transfer mode.  This only works for modes that support forward data transfer.

<a id="rst-return-value-10"></a>

#### RETURN VALUE

If negative, an error code; otherwise the number of bytes transferred.

<a id="rst-see-also-12"></a>

#### SEE ALSO

parport_read, parport_negotiate

<a id="rst-parport-open-register-device-for-particular-device-number"></a>

### parport_open - register device for particular device number

<a id="rst-synopsis-13"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct pardevice *parport_open (int devnum, const char *name,
                                int (*pf) (void *),
                                void (*kf) (void *),
                                void (*irqf) (int, void *,
                                              struct pt_regs *),
                                int flags, void *handle);
```

<a id="rst-description-14"></a>

#### DESCRIPTION

This is like parport_register_device but takes a device number instead of a pointer to a struct parport.

<a id="rst-return-value-11"></a>

#### RETURN VALUE

See parport_register_device.  If no device is associated with devnum, NULL is returned.

<a id="rst-see-also-13"></a>

#### SEE ALSO

parport_register_device

<a id="rst-parport-close-unregister-device-for-particular-device-number"></a>

### parport_close - unregister device for particular device number

<a id="rst-synopsis-14"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

void parport_close (struct pardevice *dev);
```

<a id="rst-description-15"></a>

#### DESCRIPTION

This is the equivalent of parport_unregister_device for parport_open.

<a id="rst-see-also-14"></a>

#### SEE ALSO

parport_unregister_device, parport_open

<a id="rst-parport-device-id-obtain-ieee-1284-device-id"></a>

### parport_device_id - obtain IEEE 1284 Device ID

<a id="rst-synopsis-15"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

ssize_t parport_device_id (int devnum, char *buffer, size_t len);
```

<a id="rst-description-16"></a>

#### DESCRIPTION

Obtains the IEEE 1284 Device ID associated with a given device.

<a id="rst-return-value-12"></a>

#### RETURN VALUE

If negative, an error code; otherwise, the number of bytes of buffer that contain the device ID.  The format of the device ID is as follows:



```text
[length][ID]
```

The first two bytes indicate the inclusive length of the entire Device ID, and are in big-endian order.  The ID is a sequence of pairs of the form:



```text
key:value;
```

<a id="rst-notes-1"></a>

#### NOTES

Many devices have ill-formed IEEE 1284 Device IDs.

<a id="rst-see-also-15"></a>

#### SEE ALSO

parport_find_class, parport_find_device

<a id="rst-parport-device-coords-convert-device-number-to-device-coordinates"></a>

### parport_device_coords - convert device number to device coordinates

<a id="rst-synopsis-16"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_device_coords (int devnum, int *parport, int *mux,
                           int *daisy);
```

<a id="rst-description-17"></a>

#### DESCRIPTION

Convert between device number (zero-based) and device coordinates (port, multiplexor, daisy chain address).

<a id="rst-return-value-13"></a>

#### RETURN VALUE

Zero on success, in which case the coordinates are (`*parport`, `*mux`, `*daisy`).

<a id="rst-see-also-16"></a>

#### SEE ALSO

parport_open, parport_device_id

<a id="rst-parport-find-class-find-a-device-by-its-class"></a>

### parport_find_class - find a device by its class

<a id="rst-synopsis-17"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

typedef enum {
        PARPORT_CLASS_LEGACY = 0,       /* Non-IEEE1284 device */
        PARPORT_CLASS_PRINTER,
        PARPORT_CLASS_MODEM,
        PARPORT_CLASS_NET,
        PARPORT_CLASS_HDC,              /* Hard disk controller */
        PARPORT_CLASS_PCMCIA,
        PARPORT_CLASS_MEDIA,            /* Multimedia device */
        PARPORT_CLASS_FDC,              /* Floppy disk controller */
        PARPORT_CLASS_PORTS,
        PARPORT_CLASS_SCANNER,
        PARPORT_CLASS_DIGCAM,
        PARPORT_CLASS_OTHER,            /* Anything else */
        PARPORT_CLASS_UNSPEC,           /* No CLS field in ID */
        PARPORT_CLASS_SCSIADAPTER
} parport_device_class;

int parport_find_class (parport_device_class cls, int from);
```

<a id="rst-description-18"></a>

#### DESCRIPTION

Find a device by class.  The search starts from device number from+1.

<a id="rst-return-value-14"></a>

#### RETURN VALUE

The device number of the next device in that class, or -1 if no such device exists.

<a id="rst-notes-2"></a>

#### NOTES

Example usage:



```text
int devnum = -1;
while ((devnum = parport_find_class (PARPORT_CLASS_DIGCAM, devnum)) != -1) {
        struct pardevice *dev = parport_open (devnum, ...);
        ...
}
```

<a id="rst-see-also-17"></a>

#### SEE ALSO

parport_find_device, parport_open, parport_device_id

<a id="rst-parport-find-device-find-a-device-by-its-class"></a>

### parport_find_device - find a device by its class

<a id="rst-synopsis-18"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

int parport_find_device (const char *mfg, const char *mdl, int from);
```

<a id="rst-description-19"></a>

#### DESCRIPTION

Find a device by vendor and model.  The search starts from device number from+1.

<a id="rst-return-value-15"></a>

#### RETURN VALUE

The device number of the next device matching the specifications, or -1 if no such device exists.

<a id="rst-notes-3"></a>

#### NOTES

Example usage:



```text
int devnum = -1;
while ((devnum = parport_find_device ("IOMEGA", "ZIP+", devnum)) != -1) {
        struct pardevice *dev = parport_open (devnum, ...);
        ...
}
```

<a id="rst-see-also-18"></a>

#### SEE ALSO

parport_find_class, parport_open, parport_device_id

<a id="rst-parport-set-timeout-set-the-inactivity-timeout"></a>

### parport_set_timeout - set the inactivity timeout

<a id="rst-synopsis-19"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

long parport_set_timeout (struct pardevice *dev, long inactivity);
```

<a id="rst-description-20"></a>

#### DESCRIPTION

Set the inactivity timeout, in jiffies, for a registered device.  The previous timeout is returned.

<a id="rst-return-value-16"></a>

#### RETURN VALUE

The previous timeout, in jiffies.

<a id="rst-notes-4"></a>

#### NOTES

Some of the port-&gt;ops functions for a parport may take time, owing to delays at the peripheral.  After the peripheral has not responded for `inactivity` jiffies, a timeout will occur and the blocking function will return.

A timeout of 0 jiffies is a special case: the function must do as much as it can without blocking or leaving the hardware in an unknown state.  If port operations are performed from within an interrupt handler, for instance, a timeout of 0 jiffies should be used.

Once set for a registered device, the timeout will remain at the set value until set again.

<a id="rst-see-also-19"></a>

#### SEE ALSO

port-&gt;ops-&gt;xxx_read/write_yyy

<a id="rst-port-functions"></a>

## PORT FUNCTIONS

The functions in the port-&gt;ops structure (struct parport_operations) are provided by the low-level driver responsible for that port.

<a id="rst-port-ops-read-data-read-the-data-register"></a>

### port-&gt;ops-&gt;read_data - read the data register

<a id="rst-synopsis-20"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        unsigned char (*read_data) (struct parport *port);
        ...
};
```

<a id="rst-description-21"></a>

#### DESCRIPTION

If port-&gt;modes contains the PARPORT_MODE_TRISTATE flag and the PARPORT_CONTROL_DIRECTION bit in the control register is set, this returns the value on the data pins.  If port-&gt;modes contains the PARPORT_MODE_TRISTATE flag and the PARPORT_CONTROL_DIRECTION bit is not set, the return value \_may\_ be the last value written to the data register.  Otherwise the return value is undefined.

<a id="rst-see-also-20"></a>

#### SEE ALSO

write_data, read_status, write_control

<a id="rst-port-ops-write-data-write-the-data-register"></a>

### port-&gt;ops-&gt;write_data - write the data register

<a id="rst-synopsis-21"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*write_data) (struct parport *port, unsigned char d);
        ...
};
```

<a id="rst-description-22"></a>

#### DESCRIPTION

Writes to the data register.  May have side-effects (a STROBE pulse, for instance).

<a id="rst-see-also-21"></a>

#### SEE ALSO

read_data, read_status, write_control

<a id="rst-port-ops-read-status-read-the-status-register"></a>

### port-&gt;ops-&gt;read_status - read the status register

<a id="rst-synopsis-22"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        unsigned char (*read_status) (struct parport *port);
        ...
};
```

<a id="rst-description-23"></a>

#### DESCRIPTION

Reads from the status register.  This is a bitmask:

- PARPORT_STATUS_ERROR (printer fault, "nFault")

- PARPORT_STATUS_SELECT (on-line, "Select")

- PARPORT_STATUS_PAPEROUT (no paper, "PError")

- PARPORT_STATUS_ACK (handshake, "nAck")

- PARPORT_STATUS_BUSY (busy, "Busy")

There may be other bits set.

<a id="rst-see-also-22"></a>

#### SEE ALSO

read_data, write_data, write_control

<a id="rst-port-ops-read-control-read-the-control-register"></a>

### port-&gt;ops-&gt;read_control - read the control register

<a id="rst-synopsis-23"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        unsigned char (*read_control) (struct parport *port);
        ...
};
```

<a id="rst-description-24"></a>

#### DESCRIPTION

Returns the last value written to the control register (either from write_control or frob_control).  No port access is performed.

<a id="rst-see-also-23"></a>

#### SEE ALSO

read_data, write_data, read_status, write_control

<a id="rst-port-ops-write-control-write-the-control-register"></a>

### port-&gt;ops-&gt;write_control - write the control register

<a id="rst-synopsis-24"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*write_control) (struct parport *port, unsigned char s);
        ...
};
```

<a id="rst-description-25"></a>

#### DESCRIPTION

Writes to the control register. This is a bitmask:



```text
                          _______
- PARPORT_CONTROL_STROBE (nStrobe)
                          _______
- PARPORT_CONTROL_AUTOFD (nAutoFd)
                        _____
- PARPORT_CONTROL_INIT (nInit)
                          _________
- PARPORT_CONTROL_SELECT (nSelectIn)
```

<a id="rst-see-also-24"></a>

#### SEE ALSO

read_data, write_data, read_status, frob_control

<a id="rst-port-ops-frob-control-write-control-register-bits"></a>

### port-&gt;ops-&gt;frob_control - write control register bits

<a id="rst-synopsis-25"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        unsigned char (*frob_control) (struct parport *port,
                                unsigned char mask,
                                unsigned char val);
        ...
};
```

<a id="rst-description-26"></a>

#### DESCRIPTION

This is equivalent to reading from the control register, masking out the bits in mask, exclusive-or'ing with the bits in val, and writing the result to the control register.

As some ports don't allow reads from the control port, a software copy of its contents is maintained, so frob_control is in fact only one port access.

<a id="rst-see-also-25"></a>

#### SEE ALSO

read_data, write_data, read_status, write_control

<a id="rst-port-ops-enable-irq-enable-interrupt-generation"></a>

### port-&gt;ops-&gt;enable_irq - enable interrupt generation

<a id="rst-synopsis-26"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*enable_irq) (struct parport *port);
        ...
};
```

<a id="rst-description-27"></a>

#### DESCRIPTION

The parallel port hardware is instructed to generate interrupts at appropriate moments, although those moments are architecture-specific.  For the PC architecture, interrupts are commonly generated on the rising edge of nAck.

<a id="rst-see-also-26"></a>

#### SEE ALSO

disable_irq

<a id="rst-port-ops-disable-irq-disable-interrupt-generation"></a>

### port-&gt;ops-&gt;disable_irq - disable interrupt generation

<a id="rst-synopsis-27"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*disable_irq) (struct parport *port);
        ...
};
```

<a id="rst-description-28"></a>

#### DESCRIPTION

The parallel port hardware is instructed not to generate interrupts. The interrupt itself is not masked.

<a id="rst-see-also-27"></a>

#### SEE ALSO

enable_irq

<a id="rst-port-ops-data-forward-enable-data-drivers"></a>

### port-&gt;ops-&gt;data_forward - enable data drivers

<a id="rst-synopsis-28"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*data_forward) (struct parport *port);
        ...
};
```

<a id="rst-description-29"></a>

#### DESCRIPTION

Enables the data line drivers, for 8-bit host-to-peripheral communications.

<a id="rst-see-also-28"></a>

#### SEE ALSO

data_reverse

<a id="rst-port-ops-data-reverse-tristate-the-buffer"></a>

### port-&gt;ops-&gt;data_reverse - tristate the buffer

<a id="rst-synopsis-29"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        void (*data_reverse) (struct parport *port);
        ...
};
```

<a id="rst-description-30"></a>

#### DESCRIPTION

Places the data bus in a high impedance state, if port-&gt;modes has the PARPORT_MODE_TRISTATE bit set.

<a id="rst-see-also-29"></a>

#### SEE ALSO

data_forward

<a id="rst-port-ops-epp-write-data-write-epp-data"></a>

### port-&gt;ops-&gt;epp_write_data - write EPP data

<a id="rst-synopsis-30"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*epp_write_data) (struct parport *port, const void *buf,
                                size_t len, int flags);
        ...
};
```

<a id="rst-description-31"></a>

#### DESCRIPTION

Writes data in EPP mode, and returns the number of bytes written.

The `flags` parameter may be one or more of the following, bitwise-or'ed together:


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


PARPORT_EPP_FAST

</td>
<td>


Use fast transfers. Some chips provide 16-bit and 32-bit registers.  However, if a transfer times out, the return value may be unreliable.

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

<a id="rst-see-also-30"></a>

#### SEE ALSO

epp_read_data, epp_write_addr, epp_read_addr

<a id="rst-port-ops-epp-read-data-read-epp-data"></a>

### port-&gt;ops-&gt;epp_read_data - read EPP data

<a id="rst-synopsis-31"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*epp_read_data) (struct parport *port, void *buf,
                                size_t len, int flags);
        ...
};
```

<a id="rst-description-32"></a>

#### DESCRIPTION

Reads data in EPP mode, and returns the number of bytes read.

The `flags` parameter may be one or more of the following, bitwise-or'ed together:


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


PARPORT_EPP_FAST

</td>
<td>


Use fast transfers. Some chips provide 16-bit and 32-bit registers.  However, if a transfer times out, the return value may be unreliable.

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

<a id="rst-see-also-31"></a>

#### SEE ALSO

epp_write_data, epp_write_addr, epp_read_addr

<a id="rst-port-ops-epp-write-addr-write-epp-address"></a>

### port-&gt;ops-&gt;epp_write_addr - write EPP address

<a id="rst-synopsis-32"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*epp_write_addr) (struct parport *port,
                                const void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-33"></a>

#### DESCRIPTION

Writes EPP addresses (8 bits each), and returns the number written.

The `flags` parameter may be one or more of the following, bitwise-or'ed together:


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


PARPORT_EPP_FAST

</td>
<td>


Use fast transfers. Some chips provide 16-bit and 32-bit registers.  However, if a transfer times out, the return value may be unreliable.

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

(Does PARPORT_EPP_FAST make sense for this function?)

<a id="rst-see-also-32"></a>

#### SEE ALSO

epp_write_data, epp_read_data, epp_read_addr

<a id="rst-port-ops-epp-read-addr-read-epp-address"></a>

### port-&gt;ops-&gt;epp_read_addr - read EPP address

<a id="rst-synopsis-33"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*epp_read_addr) (struct parport *port, void *buf,
                                size_t len, int flags);
        ...
};
```

<a id="rst-description-34"></a>

#### DESCRIPTION

Reads EPP addresses (8 bits each), and returns the number read.

The `flags` parameter may be one or more of the following, bitwise-or'ed together:


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


PARPORT_EPP_FAST

</td>
<td>


Use fast transfers. Some chips provide 16-bit and 32-bit registers.  However, if a transfer times out, the return value may be unreliable.

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

(Does PARPORT_EPP_FAST make sense for this function?)

<a id="rst-see-also-33"></a>

#### SEE ALSO

epp_write_data, epp_read_data, epp_write_addr

<a id="rst-port-ops-ecp-write-data-write-a-block-of-ecp-data"></a>

### port-&gt;ops-&gt;ecp_write_data - write a block of ECP data

<a id="rst-synopsis-34"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*ecp_write_data) (struct parport *port,
                                const void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-35"></a>

#### DESCRIPTION

Writes a block of ECP data.  The `flags` parameter is ignored.

<a id="rst-return-value-17"></a>

#### RETURN VALUE

The number of bytes written.

<a id="rst-see-also-34"></a>

#### SEE ALSO

ecp_read_data, ecp_write_addr

<a id="rst-port-ops-ecp-read-data-read-a-block-of-ecp-data"></a>

### port-&gt;ops-&gt;ecp_read_data - read a block of ECP data

<a id="rst-synopsis-35"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*ecp_read_data) (struct parport *port,
                                void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-36"></a>

#### DESCRIPTION

Reads a block of ECP data.  The `flags` parameter is ignored.

<a id="rst-return-value-18"></a>

#### RETURN VALUE

The number of bytes read.  NB. There may be more unread data in a FIFO.  Is there a way of stunning the FIFO to prevent this?

<a id="rst-see-also-35"></a>

#### SEE ALSO

ecp_write_block, ecp_write_addr

<a id="rst-port-ops-ecp-write-addr-write-a-block-of-ecp-addresses"></a>

### port-&gt;ops-&gt;ecp_write_addr - write a block of ECP addresses

<a id="rst-synopsis-36"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*ecp_write_addr) (struct parport *port,
                                const void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-37"></a>

#### DESCRIPTION

Writes a block of ECP addresses.  The `flags` parameter is ignored.

<a id="rst-return-value-19"></a>

#### RETURN VALUE

The number of bytes written.

<a id="rst-notes-5"></a>

#### NOTES

This may use a FIFO, and if so shall not return until the FIFO is empty.

<a id="rst-see-also-36"></a>

#### SEE ALSO

ecp_read_data, ecp_write_data

<a id="rst-port-ops-nibble-read-data-read-a-block-of-data-in-nibble-mode"></a>

### port-&gt;ops-&gt;nibble_read_data - read a block of data in nibble mode

<a id="rst-synopsis-37"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*nibble_read_data) (struct parport *port,
                                void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-38"></a>

#### DESCRIPTION

Reads a block of data in nibble mode.  The `flags` parameter is ignored.

<a id="rst-return-value-20"></a>

#### RETURN VALUE

The number of whole bytes read.

<a id="rst-see-also-37"></a>

#### SEE ALSO

byte_read_data, compat_write_data

<a id="rst-port-ops-byte-read-data-read-a-block-of-data-in-byte-mode"></a>

### port-&gt;ops-&gt;byte_read_data - read a block of data in byte mode

<a id="rst-synopsis-38"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*byte_read_data) (struct parport *port,
                                void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-39"></a>

#### DESCRIPTION

Reads a block of data in byte mode.  The `flags` parameter is ignored.

<a id="rst-return-value-21"></a>

#### RETURN VALUE

The number of bytes read.

<a id="rst-see-also-38"></a>

#### SEE ALSO

nibble_read_data, compat_write_data

<a id="rst-port-ops-compat-write-data-write-a-block-of-data-in-compatibility-mode"></a>

### port-&gt;ops-&gt;compat_write_data - write a block of data in compatibility mode

<a id="rst-synopsis-39"></a>

#### SYNOPSIS



```text
#include <linux/parport.h>

struct parport_operations {
        ...
        size_t (*compat_write_data) (struct parport *port,
                                const void *buf, size_t len, int flags);
        ...
};
```

<a id="rst-description-40"></a>

#### DESCRIPTION

Writes a block of data in compatibility mode.  The `flags` parameter is ignored.

<a id="rst-return-value-22"></a>

#### RETURN VALUE

The number of bytes written.

<a id="rst-see-also-39"></a>

#### SEE ALSO

nibble_read_data, byte_read_data

---

# SCSI Interfaces Guide

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> Once upon a time, the Small Computer Systems Interface defined both a parallel I/O bus and a data protocol to connect a wide variety of peripherals (disk drives, tape drives, modems, printers, scanners, optical drives, test equipment, and…

<a id="rst-scsi-interfaces-guide"></a>

**Author:** James Bottomley

**Author:** Rob Landley

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

## Introduction

<a id="rst-protocol-vs-bus"></a>

### Protocol vs bus

Once upon a time, the Small Computer Systems Interface defined both a parallel I/O bus and a data protocol to connect a wide variety of peripherals (disk drives, tape drives, modems, printers, scanners, optical drives, test equipment, and medical devices) to a host computer.

Although the old parallel (fast/wide/ultra) SCSI bus has largely fallen out of use, the SCSI command set is more widely used than ever to communicate with devices over a number of different buses.

The [SCSI protocol](<https://www.t10.org/scsi-3.htm>) is a big-endian peer-to-peer packet based protocol. SCSI commands are 6, 10, 12, or 16 bytes long, often followed by an associated data payload.

SCSI commands can be transported over just about any kind of bus, and are the default protocol for storage devices attached to USB, SATA, SAS, Fibre Channel, FireWire, and ATAPI devices. SCSI packets are also commonly exchanged over Infiniband, TCP/IP ([iSCSI](<https://en.wikipedia.org/wiki/ISCSI>)), even [Parallel ports](<http://cyberelk.net/tim/parport/parscsi.html>).

<a id="rst-design-of-the-linux-scsi-subsystem"></a>

### Design of the Linux SCSI subsystem

The SCSI subsystem uses a three layer design, with upper, mid, and low layers. Every operation involving the SCSI subsystem (such as reading a sector from a disk) uses one driver at each of the 3 levels: one upper layer driver, one lower layer driver, and the SCSI midlayer.

The SCSI upper layer provides the interface between userspace and the kernel, in the form of block and char device nodes for I/O and ioctl(). The SCSI lower layer contains drivers for specific hardware devices.

In between is the SCSI mid-layer, analogous to a network routing layer such as the IPv4 stack. The SCSI mid-layer routes a packet based data protocol between the upper layer's /dev nodes and the corresponding devices in the lower layer. It manages command queues, provides error handling and power management functions, and responds to ioctl() requests.

<a id="rst-scsi-upper-layer"></a>

## SCSI upper layer

The upper layer supports the user-kernel interface by providing device nodes.

<a id="rst-sd-scsi-disk"></a>

### sd (SCSI Disk)

sd (sd_mod.o)

<a id="rst-sr-scsi-cd-rom"></a>

### sr (SCSI CD-ROM)

sr (sr_mod.o)

<a id="rst-st-scsi-tape"></a>

### st (SCSI Tape)

st (st.o)

<a id="rst-sg-scsi-generic"></a>

### sg (SCSI Generic)

sg (sg.o)

<a id="rst-ch-scsi-media-changer"></a>

### ch (SCSI Media Changer)

ch (ch.c)

<a id="rst-scsi-mid-layer"></a>

## SCSI mid layer

<a id="rst-scsi-midlayer-implementation"></a>

### SCSI midlayer implementation

<a id="rst-include-scsi-scsi-device-h"></a>

#### include/scsi/scsi_device.h


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

SCSI Vital Product Data

**Definition**

```c
struct scsi_vpd {
    struct rcu_head rcu;
    int len;
    unsigned char   data[];
};
```

**Members**

- `rcu`: For [`kfree_rcu()`](/kernel/internals/core-api/kernel-api.md#c-kfree_rcu).
- `len`: Length in bytes of **data**.
- `data`: VPD data as defined in various T10 SCSI standard documents.

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

```c
shost_for_each_device(sdev, shost)
```

iterate over all devices of a host

**Parameters**

- `sdev`: the `struct scsi_device` to use as a cursor
- `shost`: the `struct scsi_host` to iterate over

**Description**

Iterator that returns each device attached to **shost**.  This loop
takes a reference on each device and releases it at the end.  If
you break out of the loop, you must call scsi_device_put(sdev).

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

```c
__shost_for_each_device(sdev, shost)
```

iterate over all devices of a host (UNLOCKED)

**Parameters**

- `sdev`: the `struct scsi_device` to use as a cursor
- `shost`: the `struct scsi_host` to iterate over

**Description**

Iterator that returns each device attached to **shost**.  It does _not_
take a reference on the scsi_device, so the whole loop must be
protected by shost->host_lock.

**Note**

The only reason to use this is because you need to access the
device list in interrupt context.  Otherwise you really want to use
shost_for_each_device instead.

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

```c
bool scsi_device_is_pseudo_dev(struct scsi_device *sdev)
```

Whether a device is a pseudo SCSI device.

**Parameters**

- `struct scsi_device *sdev`: SCSI device to examine

**Description**

A pseudo SCSI device can be used to allocate SCSI commands but does not show
up in sysfs. Additionally, the logical unit information in **\*sdev** is made up.

This function tests the LUN number instead of comparing **sdev** with
**sdev->host->pseudo_sdev** because this function may be called before
**sdev->host->pseudo_sdev** has been initialized.

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

```c
int scsi_device_supports_vpd(struct scsi_device *sdev)
```

test if a device supports VPD pages

**Parameters**

- `struct scsi_device *sdev`: the `struct scsi_device` to test

**Description**

If the 'try_vpd_pages' flag is set it takes precedence.
Otherwise we will assume VPD pages are supported if the
SCSI level is at least SPC-3 and 'skip_vpd_pages' is not set.


<a id="rst-drivers-scsi-scsi-c"></a>

#### drivers/scsi/scsi.c

Main file for the SCSI midlayer.


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

```c
int scsi_change_queue_depth(struct scsi_device *sdev, int depth)
```

change a device's queue depth

**Parameters**

- `struct scsi_device *sdev`: SCSI Device in question
- `int depth`: number of commands allowed to be queued to the driver

**Description**

Sets the device queue depth and returns the new value.

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

```c
int scsi_track_queue_full(struct scsi_device *sdev, int depth)
```

track QUEUE_FULL events to adjust queue depth

**Parameters**

- `struct scsi_device *sdev`: SCSI Device in question
- `int depth`: Current number of outstanding SCSI commands on this device,
  not counting the one returned as QUEUE_FULL.

**Description**

- This function will track successive QUEUE_FULL events on a

  specific SCSI device to determine if and when there is a
  need to adjust the queue depth on the device.

Lock Status: None held on entry

**Return**

* 0 - No change needed
* >0 - Adjust queue depth to this new depth,
* -1 - Drop back to untagged operation using host->cmd_per_lun as the
  untagged command depth

**Notes**

- Low level drivers may call this at any time and we will do

  "The Right Thing."  We are interrupt context safe.

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

```c
int scsi_get_vpd_page(struct scsi_device *sdev, u8 page, unsigned char *buf, int buf_len)
```

Get Vital Product Data from a SCSI device

**Parameters**

- `struct scsi_device *sdev`: The device to ask
- `u8 page`: Which Vital Product Data to return
- `unsigned char *buf`: where to store the VPD
- `int buf_len`: number of bytes in the VPD buffer area

**Description**

SCSI devices may optionally supply Vital Product Data.  Each 'page'
of VPD is defined in the appropriate SCSI document (eg SPC, SBC).
If the device supports this VPD page, this routine fills **buf**
with the data from that page and return 0. If the VPD page is not
supported or its content cannot be retrieved, -EINVAL is returned.

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

```c
int scsi_report_opcode(struct scsi_device *sdev, unsigned char *buffer, unsigned int len, unsigned char opcode, unsigned short sa)
```

Find out if a given command is supported

**Parameters**

- `struct scsi_device *sdev`: scsi device to query
- `unsigned char *buffer`: scratch buffer (must be at least 20 bytes long)
- `unsigned int len`: length of buffer
- `unsigned char opcode`: opcode for the command to look up
- `unsigned short sa`: service action for the command to look up

**Description**

Uses the REPORT SUPPORTED OPERATION CODES to check support for the
command identified with **opcode** and **sa**. If the command does not
have a service action, **sa** must be 0. Returns -EINVAL if RSOC fails,
0 if the command is not supported and 1 if the device claims to
support the command.

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

```c
int scsi_device_get(struct scsi_device *sdev)
```

get an additional reference to a scsi_device

**Parameters**

- `struct scsi_device *sdev`: device to get a reference to

**Description**

Gets a reference to the scsi_device and increments the use count
of the underlying LLDD module.  You must hold host_lock of the
parent Scsi_Host or already have a reference when calling this.

This will fail if a device is deleted or cancelled, or when the LLD module
is in the process of being unloaded.

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

```c
void scsi_device_put(struct scsi_device *sdev)
```

release a reference to a scsi_device

**Parameters**

- `struct scsi_device *sdev`: device to release a reference on.

**Description**

Release a reference to the scsi_device and decrements the use
count of the underlying LLDD module.  The device is freed once the last
user vanishes.

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

```c
void starget_for_each_device(struct scsi_target *starget, void *data, void (*fn)(struct scsi_device *, void *))
```

helper to walk all devices of a target

**Parameters**

- `struct scsi_target *starget`: target whose devices we want to iterate over.
- `void *data`: Opaque passed to each function call.
- `void (*fn)(struct scsi_device *, void *)`: Function to call on each device

**Description**

This traverses over each device of **starget**.  The devices have
a reference that must be released by scsi_host_put when breaking
out of the loop.

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

```c
void __starget_for_each_device(struct scsi_target *starget, void *data, void (*fn)(struct scsi_device *, void *))
```

helper to walk all devices of a target (UNLOCKED)

**Parameters**

- `struct scsi_target *starget`: target whose devices we want to iterate over.
- `void *data`: parameter for callback **fn()**
- `void (*fn)(struct scsi_device *, void *)`: callback function that is invoked for each device

**Description**

This traverses over each device of **starget**.  It does _not_
take a reference on the scsi_device, so the whole loop must be
protected by shost->host_lock.

**Note**

The only reason why drivers would want to use this is because
they need to access the device list in irq context.  Otherwise you
really want to use starget_for_each_device instead.

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

```c
struct scsi_device * __scsi_device_lookup_by_target(struct scsi_target *starget, u64 lun)
```

find a device given the target (UNLOCKED)

**Parameters**

- `struct scsi_target *starget`: SCSI target pointer
- `u64 lun`: SCSI Logical Unit Number

**Description**

Looks up the scsi_device with the specified **lun** for a given
**starget**.  The returned scsi_device does not have an additional
reference.  You must hold the host's host_lock over this call and
any access to the returned scsi_device. A scsi_device in state
SDEV_DEL is skipped.

**Note**

The only reason why drivers should use this is because
they need to access the device list in irq context.  Otherwise you
really want to use scsi_device_lookup_by_target instead.

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

```c
struct scsi_device * scsi_device_lookup_by_target(struct scsi_target *starget, u64 lun)
```

find a device given the target

**Parameters**

- `struct scsi_target *starget`: SCSI target pointer
- `u64 lun`: SCSI Logical Unit Number

**Description**

Looks up the scsi_device with the specified **lun** for a given
**starget**.  The returned scsi_device has an additional reference that
needs to be released with scsi_device_put once you're done with it.

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

```c
struct scsi_device * __scsi_device_lookup(struct Scsi_Host *shost, uint channel, uint id, u64 lun)
```

find a device given the host (UNLOCKED)

**Parameters**

- `struct Scsi_Host *shost`: SCSI host pointer
- `uint channel`: SCSI channel (zero if only one channel)
- `uint id`: SCSI target number (physical unit number)
- `u64 lun`: SCSI Logical Unit Number

**Description**

Looks up the scsi_device with the specified **channel**, **id**, **lun**
for a given host. The returned scsi_device does not have an additional
reference.  You must hold the host's host_lock over this call and any access
to the returned scsi_device.

**Note**

The only reason why drivers would want to use this is because
they need to access the device list in irq context.  Otherwise you
really want to use scsi_device_lookup instead.

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

```c
struct scsi_device * scsi_device_lookup(struct Scsi_Host *shost, uint channel, uint id, u64 lun)
```

find a device given the host

**Parameters**

- `struct Scsi_Host *shost`: SCSI host pointer
- `uint channel`: SCSI channel (zero if only one channel)
- `uint id`: SCSI target number (physical unit number)
- `u64 lun`: SCSI Logical Unit Number

**Description**

Looks up the scsi_device with the specified **channel**, **id**, **lun**
for a given host.  The returned scsi_device has an additional reference that
needs to be released with scsi_device_put once you're done with it.


<a id="rst-drivers-scsi-scsicam-c"></a>

#### drivers/scsi/scsicam.c

[SCSI Common Access Method](<http://www.t10.org/ftp/t10/drafts/cam/cam-r12b.pdf>) support functions, for use with HDIO_GETGEO, etc.


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

```c
unsigned char * scsi_bios_ptable(struct gendisk *dev)
```

Read PC partition table out of first sector of device.

**Parameters**

- `struct gendisk *dev`: from this device

**Description**

- Reads the first sector from the device and returns `0x42` bytes

  starting at offset `0x1be`.

**Return**

partition table in kmalloc(GFP_KERNEL) memory, or NULL on error.

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

```c
bool scsi_partsize(struct gendisk *disk, sector_t capacity, int geom[3])
```

Parse cylinders/heads/sectors from PC partition table

**Parameters**

- `struct gendisk *disk`: gendisk of the disk to parse
- `sector_t capacity`: size of the disk in sectors
- `int geom[3]`: output in form of \[hds, cylinders, sectors\]

**Description**

Determine the BIOS mapping/geometry used to create the partition
table, storing the results in **geom**.

**Return**

`false` on failure, `true` on success.

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

```c
int scsicam_bios_param(struct gendisk *disk, sector_t capacity, int *ip)
```

Determine geometry of a disk in cylinders/heads/sectors.

**Parameters**

- `struct gendisk *disk`: which device
- `sector_t capacity`: size of the disk in sectors
- `int *ip`: return value: ip\[0\]=heads, ip\[1\]=sectors, ip\[2\]=cylinders

**Description**

- determine the BIOS mapping/geometry used for a drive in a

  SCSI-CAM system, storing the results in ip as required
  by the HDIO_GETGEO `ioctl()`.

**Return**

-1 on failure, 0 on success.


<a id="rst-drivers-scsi-scsi-error-c"></a>

#### drivers/scsi/scsi_error.c

Common SCSI error/timeout handling routines.


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

```c
void scsi_schedule_eh(struct Scsi_Host *shost)
```

schedule EH for SCSI host

**Parameters**

- `struct Scsi_Host *shost`: SCSI host to invoke error handling on.

**Description**

Schedule SCSI EH without scmd.

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

```c
int scsi_block_when_processing_errors(struct scsi_device *sdev)
```

Prevent cmds from being queued.

**Parameters**

- `struct scsi_device *sdev`: Device on which we are performing recovery.

**Description**

We block until the host is out of error recovery, and then check to
see whether the host or the device is offline.

- Return value:
  0 when dev was taken offline by error recovery. 1 OK to proceed.

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

```c
enum scsi_disposition scsi_check_sense(struct scsi_cmnd *scmd)
```

Examine scsi cmd sense

**Parameters**

- `struct scsi_cmnd *scmd`: Cmd to have sense checked.

**Description**

- Return value:
  SUCCESS or FAILED or NEEDS_RETRY or ADD_TO_MLQUEUE

**Notes**

When a deferred error is detected the current command has
not been executed and needs retrying.

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

```c
void scsi_eh_prep_cmnd(struct scsi_cmnd *scmd, struct scsi_eh_save *ses, unsigned char *cmnd, int cmnd_size, unsigned sense_bytes)
```

Save a scsi command info as part of error recovery

**Parameters**

- `struct scsi_cmnd *scmd`: SCSI command structure to hijack
- `struct scsi_eh_save *ses`: structure to save restore information
- `unsigned char *cmnd`: CDB to send. Can be NULL if no new cmnd is needed
- `int cmnd_size`: size in bytes of **cmnd** (must be \<= MAX_COMMAND_SIZE)
- `unsigned sense_bytes`: size of sense data to copy. or 0 (if != 0 **cmnd** is ignored)

**Description**

This function is used to save a scsi command information before re-execution
as part of the error recovery process.  If **sense_bytes** is 0 the command
sent must be one that does not transfer any data.  If **sense_bytes** != 0
**cmnd** is ignored and this functions sets up a REQUEST_SENSE command
and cmnd buffers to read **sense_bytes** into **scmd->sense_buffer**.

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

```c
void scsi_eh_restore_cmnd(struct scsi_cmnd* scmd, struct scsi_eh_save *ses)
```

Restore a scsi command info as part of error recovery

**Parameters**

- `struct scsi_cmnd* scmd`: SCSI command structure to restore
- `struct scsi_eh_save *ses`: saved information from a coresponding call to scsi_eh_prep_cmnd

**Description**

Undo any damage done by above [`scsi_eh_prep_cmnd()`](#c-scsi_eh_prep_cmnd).

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

```c
void scsi_eh_finish_cmd(struct scsi_cmnd *scmd, struct list_head *done_q)
```

Handle a cmd that eh is finished with.

**Parameters**

- `struct scsi_cmnd *scmd`: Original SCSI cmd that eh has finished.
- `struct list_head *done_q`: Queue for processed commands.

**Notes**

We don't want to use the normal command completion while we are are
still handling errors - it may cause other commands to be queued,
and that would disturb what we are doing.  Thus we really want to
keep a list of pending commands for final completion, and once we
are ready to leave error handling we handle completion for real.

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

```c
int scsi_eh_get_sense(struct list_head *work_q, struct list_head *done_q)
```

Get device sense data.

**Parameters**

- `struct list_head *work_q`: Queue of commands to process.
- `struct list_head *done_q`: Queue of processed commands.

**Description**

See if we need to request sense information.  if so, then get it
now, so we have a better idea of what to do.

**Notes**

This has the unfortunate side effect that if a shost adapter does
not automatically request sense information, we end up shutting
it down before we request it.

All drivers should request sense information internally these days,
so for now all I have to say is tough noogies if you end up in here.

- XXX: Long term this code should go away, but that needs an audit of

  all LLDDs first.

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

```c
void scsi_eh_ready_devs(struct Scsi_Host *shost, struct list_head *work_q, struct list_head *done_q)
```

check device ready state and recover if not.

**Parameters**

- `struct Scsi_Host *shost`: host to be recovered.
- `struct list_head *work_q`: `list_head` for pending commands.
- `struct list_head *done_q`: `list_head` for processed commands.

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

```c
void scsi_eh_flush_done_q(struct list_head *done_q)
```

finish processed commands or retry them.

**Parameters**

- `struct list_head *done_q`: list_head of processed commands.

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

```c
void scsi_report_bus_reset(struct Scsi_Host *shost, int channel)
```

report bus reset observed

**Parameters**

- `struct Scsi_Host *shost`: Host in question
- `int channel`: channel on which reset was observed.

**Description**

Utility function used by low-level drivers to report that
they have observed a bus reset on the bus being handled.

Lock status: Host lock must be held.

**Return**

Nothing

**Notes**

- This only needs to be called if the reset is one which

  originates from an unknown location.  Resets originated
  by the mid-level itself don't need to call this, but there
  should be no harm.

  The main purpose of this is to make sure that a CHECK_CONDITION
  is properly treated.

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

```c
void scsi_report_device_reset(struct Scsi_Host *shost, int channel, int target)
```

report device reset observed

**Parameters**

- `struct Scsi_Host *shost`: Host in question
- `int channel`: channel on which reset was observed
- `int target`: target on which reset was observed

**Description**

Utility function used by low-level drivers to report that
they have observed a device reset on the device being handled.

Lock status: Host lock must be held

**Return**

Nothing

**Notes**

- This only needs to be called if the reset is one which

  originates from an unknown location.  Resets originated
  by the mid-level itself don't need to call this, but there
  should be no harm.

  The main purpose of this is to make sure that a CHECK_CONDITION
  is properly treated.

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

```c
bool scsi_get_sense_info_fld(const u8 *sense_buffer, int sb_len, u64 *info_out)
```

get information field from sense data (either fixed or descriptor format)

**Parameters**

- `const u8 *sense_buffer`: byte array of sense data
- `int sb_len`: number of valid bytes in sense_buffer
- `u64 *info_out`: pointer to 64 integer where 8 or 4 byte information
  field will be placed if found.

**Description**

- Return value:
  true if information field found, false if not found.


<a id="rst-drivers-scsi-scsi-devinfo-c"></a>

#### drivers/scsi/scsi_devinfo.c

Manage scsi_dev_info_list, which tracks blacklisted and whitelisted devices.


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

```c
int scsi_dev_info_list_add_keyed(int compatible, char *vendor, char *model, char *strflags, blist_flags_t flags, enum scsi_devinfo_key key)
```

add one dev_info list entry.

**Parameters**

- `int compatible`: if true, null terminate short strings.  Otherwise space pad.
- `char *vendor`: vendor string
- `char *model`: model (product) string
- `char *strflags`: integer string
- `blist_flags_t flags`: if strflags NULL, use this flag value
- `enum scsi_devinfo_key key`: specify list to use

**Description**

Create and add one dev_info entry for **vendor**, **model**,
**strflags** or **flag** in list specified by **key**. If **compatible**,
add to the tail of the list, do not space pad, and set
devinfo->compatible. The scsi_static_device_list entries are
added with **compatible** 1 and **clfags** NULL.

**Return**

0 OK, -error on failure.

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

```c
blist_flags_t scsi_get_device_flags_keyed(struct scsi_device *sdev, const unsigned char *vendor, const unsigned char *model, enum scsi_devinfo_key key)
```

get device specific flags from the dynamic device list

**Parameters**

- `struct scsi_device *sdev`: `scsi_device` to get flags for
- `const unsigned char *vendor`: vendor name
- `const unsigned char *model`: model name
- `enum scsi_devinfo_key key`: list to look up

**Description**

Search the scsi_dev_info_list specified by **key** for an entry
matching **vendor** and **model**, if found, return the matching
flags value, else return the host or global default settings.
Called during scan time.

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

```c
int scsi_dev_info_add_list(enum scsi_devinfo_key key, const char *name)
```

add a new devinfo list

**Parameters**

- `enum scsi_devinfo_key key`: key of the list to add
- `const char *name`: Name of the list to add (for /proc/scsi/device_info)

**Description**

Adds the requested list, returns zero on success, -EEXIST if the
key is already registered to a list, or other error on failure.

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

```c
int scsi_dev_info_remove_list(enum scsi_devinfo_key key)
```

destroy an added devinfo list

**Parameters**

- `enum scsi_devinfo_key key`: key of the list to destroy

**Description**

Iterates over the entire list first, freeing all the values, then
frees the list itself.  Returns 0 on success or -EINVAL if the key
can't be found.


<a id="rst-drivers-scsi-scsi-ioctl-c"></a>

#### drivers/scsi/scsi_ioctl.c

Handle ioctl() calls for SCSI devices.


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

```c
int scsi_set_medium_removal(struct scsi_device *sdev, char state)
```

send command to allow or prevent medium removal

**Parameters**

- `struct scsi_device *sdev`: target scsi device
- `char state`: removal state to set (prevent or allow)

**Return**

* `0` if **sdev** is not removable or not lockable or successful.
* non-`0` is a SCSI result code if > 0 or kernel error code if \< 0.
* Sets **sdev->locked** to the new state on success.

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

```c
bool scsi_cmd_allowed(unsigned char *cmd, bool open_for_write)
```

Check if the given command is allowed.

**Parameters**

- `unsigned char *cmd`: SCSI command to check
- `bool open_for_write`: is the file / block device opened for writing?

**Description**

Only a subset of commands are allowed for unprivileged users. Commands used
to format the media, update the firmware, etc. are not permitted.

**Return**

`true` if the cmd is allowed, otherwise **false**.

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

```c
int scsi_ioctl(struct scsi_device *sdev, bool open_for_write, int cmd, void __user *arg)
```

Dispatch ioctl to scsi device

**Parameters**

- `struct scsi_device *sdev`: scsi device receiving ioctl
- `bool open_for_write`: is the file / block device opened for writing?
- `int cmd`: which ioctl is it
- `void __user *arg`: data associated with ioctl

**Description**

The [`scsi_ioctl()`](#c-scsi_ioctl) function differs from most ioctls in that it
does not take a major/minor number as the dev field.  Rather, it takes
a pointer to a `struct scsi_device`.

**Return**

varies depending on the **cmd**

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

```c
int scsi_ioctl_block_when_processing_errors(struct scsi_device *sdev, int cmd, bool ndelay)
```

prevent commands from being queued

**Parameters**

- `struct scsi_device *sdev`: target scsi device
- `int cmd`: which ioctl is it
- `bool ndelay`: no delay (non-blocking)

**Description**

We can process a reset even when a device isn't fully operable.

**Return**

`0` on success, \<0 error code.


<a id="rst-drivers-scsi-scsi-lib-c"></a>

#### drivers/scsi/scsi_lib.c

SCSI queuing library.


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

```c
void scsi_failures_reset_retries(struct scsi_failures *failures)
```

reset all failures to zero

**Parameters**

- `struct scsi_failures *failures`: `struct scsi_failures` with specific failure modes set

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

```c
int scsi_execute_cmd(struct scsi_device *sdev, const unsigned char *cmd, blk_opf_t opf, void *buffer, unsigned int bufflen, int timeout, int ml_retries, const struct scsi_exec_args *args)
```

insert request and wait for the result

**Parameters**

- `struct scsi_device *sdev`: scsi_device
- `const unsigned char *cmd`: scsi command
- `blk_opf_t opf`: block layer request cmd_flags
- `void *buffer`: data buffer
- `unsigned int bufflen`: len of buffer
- `int timeout`: request timeout in HZ
- `int ml_retries`: number of times SCSI midlayer will retry request
- `const struct scsi_exec_args *args`: Optional args. See struct definition for field descriptions

**Description**

Returns the scsi_cmnd result field if a command was executed, or a negative
Linux error code if we didn't get that far.

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

```c
blk_status_t scsi_alloc_sgtables(struct scsi_cmnd *cmd)
```

Allocate and initialize data and integrity scatterlists

**Parameters**

- `struct scsi_cmnd *cmd`: SCSI command data structure to initialize.

**Description**

Initializes **cmd->sdb** and also **cmd->prot_sdb** if data integrity is enabled
for **cmd**.

**Return**

* BLK_STS_OK       - on success
* BLK_STS_RESOURCE - if the failure is retryable
* BLK_STS_IOERR    - if the failure is fatal

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

```c
struct request * scsi_alloc_request(struct request_queue *q, blk_opf_t opf, blk_mq_req_flags_t flags)
```

allocate a block request and partially initialize its `scsi_cmnd`

**Parameters**

- `struct request_queue *q`: the device's request queue
- `blk_opf_t opf`: the request operation code
- `blk_mq_req_flags_t flags`: block layer allocation flags

**Return**

`struct request` pointer on success or `NULL` on failure

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

```c
struct scsi_cmnd * scsi_get_internal_cmd(struct scsi_device *sdev, enum dma_data_direction data_direction, blk_mq_req_flags_t flags)
```

Allocate an internal SCSI command.

**Parameters**

- `struct scsi_device *sdev`: SCSI device from which to allocate the command
- `enum dma_data_direction data_direction`: Data direction for the allocated command
- `blk_mq_req_flags_t flags`: request allocation flags, e.g. BLK_MQ_REQ_RESERVED or
  BLK_MQ_REQ_NOWAIT.

**Description**

Allocates a SCSI command for internal LLDD use.

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

```c
void scsi_put_internal_cmd(struct scsi_cmnd *scmd)
```

Free an internal SCSI command.

**Parameters**

- `struct scsi_cmnd *scmd`: SCSI command to be freed

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

```c
struct scsi_device * scsi_device_from_queue(struct request_queue *q)
```

return sdev associated with a request_queue

**Parameters**

- `struct request_queue *q`: The request queue to return the sdev from

**Description**

Return the sdev associated with a request queue or NULL if the
request_queue does not reference a SCSI device.

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

```c
void scsi_block_requests(struct Scsi_Host *shost)
```

Utility function used by low-level drivers to prevent further commands from being queued to the device.

**Parameters**

- `struct Scsi_Host *shost`: host in question

**Description**

There is no timer nor any other means by which the requests get unblocked
other than the low-level driver calling [`scsi_unblock_requests()`](#c-scsi_unblock_requests).

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

```c
void scsi_unblock_requests(struct Scsi_Host *shost)
```

Utility function used by low-level drivers to allow further commands to be queued to the device.

**Parameters**

- `struct Scsi_Host *shost`: host in question

**Description**

There is no timer nor any other means by which the requests get unblocked
other than the low-level driver calling [`scsi_unblock_requests()`](#c-scsi_unblock_requests). This is done
as an API function so that changes to the internals of the scsi mid-layer
won't require wholesale changes to drivers that use this feature.

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

```c
int scsi_mode_select(struct scsi_device *sdev, int pf, int sp, unsigned char *buffer, int len, int timeout, int retries, struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
```

issue a mode select

**Parameters**

- `struct scsi_device *sdev`: SCSI device to be queried
- `int pf`: Page format bit (1 == standard, 0 == vendor specific)
- `int sp`: Save page bit (0 == don't save, 1 == save)
- `unsigned char *buffer`: request buffer (may not be smaller than eight bytes)
- `int len`: length of request buffer.
- `int timeout`: command timeout
- `int retries`: number of retries before failing
- `struct scsi_mode_data *data`: returns a structure abstracting the mode header data
- `struct scsi_sense_hdr *sshdr`: place to put sense data (or NULL if no sense to be collected).
  must be SCSI_SENSE_BUFFERSIZE big.

**Description**

Returns zero if successful; negative error number or scsi
status on error

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

```c
int scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage, int subpage, unsigned char *buffer, int len, int timeout, int retries, struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
```

issue a mode sense, falling back from 10 to six bytes if necessary.

**Parameters**

- `struct scsi_device *sdev`: SCSI device to be queried
- `int dbd`: set to prevent mode sense from returning block descriptors
- `int modepage`: mode page being requested
- `int subpage`: sub-page of the mode page being requested
- `unsigned char *buffer`: request buffer (may not be smaller than eight bytes)
- `int len`: length of request buffer.
- `int timeout`: command timeout
- `int retries`: number of retries before failing
- `struct scsi_mode_data *data`: returns a structure abstracting the mode header data
- `struct scsi_sense_hdr *sshdr`: place to put sense data (or NULL if no sense to be collected).
  must be SCSI_SENSE_BUFFERSIZE big.

**Description**

Returns zero if successful, or a negative error number on failure

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

```c
int scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries, struct scsi_sense_hdr *sshdr)
```

test if unit is ready

**Parameters**

- `struct scsi_device *sdev`: scsi device to change the state of.
- `int timeout`: command timeout
- `int retries`: number of retries before failing
- `struct scsi_sense_hdr *sshdr`: outpout pointer for decoded sense information.

**Description**

Returns zero if successful or an error if TUR failed.  For
removable media, UNIT_ATTENTION sets ->changed flag.

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

```c
int scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
```

Take the given device through the device state model.

**Parameters**

- `struct scsi_device *sdev`: scsi device to change the state of.
- `enum scsi_device_state state`: state to change to.

**Description**

Returns zero if successful or an error if the requested
transition is illegal.

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

```c
void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
```

send asserted event to uevent thread

**Parameters**

- `struct scsi_device *sdev`: scsi_device event occurred on
- `struct scsi_event *evt`: event to send

**Description**

Assert scsi device event asynchronously.

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

```c
struct scsi_event * sdev_evt_alloc(enum scsi_device_event evt_type, gfp_t gfpflags)
```

allocate a new scsi event

**Parameters**

- `enum scsi_device_event evt_type`: type of event to allocate
- `gfp_t gfpflags`: GFP flags for allocation

**Description**

Allocates and returns a new scsi_event.

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

```c
void sdev_evt_send_simple(struct scsi_device *sdev, enum scsi_device_event evt_type, gfp_t gfpflags)
```

send asserted event to uevent thread

**Parameters**

- `struct scsi_device *sdev`: scsi_device event occurred on
- `enum scsi_device_event evt_type`: type of event to send
- `gfp_t gfpflags`: GFP flags for allocation

**Description**

Assert scsi device event asynchronously, given an event type.

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

```c
int scsi_device_quiesce(struct scsi_device *sdev)
```

Block all commands except power management.

**Parameters**

- `struct scsi_device *sdev`: scsi device to quiesce.

**Description**

This works by trying to transition to the SDEV_QUIESCE state
(which must be a legal transition).  When the device is in this
state, only power management requests will be accepted, all others will
be deferred.

Must be called with user context, may sleep.

Returns zero if successful or an error if not.

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

```c
void scsi_device_resume(struct scsi_device *sdev)
```

Restart user issued commands to a quiesced device.

**Parameters**

- `struct scsi_device *sdev`: scsi device to resume.

**Description**

Moves the device from quiesced back to running and restarts the
queues.

Must be called with user context, may sleep.

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

```c
int scsi_internal_device_block_nowait(struct scsi_device *sdev)
```

try to transition to the SDEV_BLOCK state

**Parameters**

- `struct scsi_device *sdev`: device to block

**Description**

Pause SCSI command processing on the specified device. Does not sleep.

Returns zero if successful or a negative error code upon failure.

**Notes**

This routine transitions the device to the SDEV_BLOCK state (which must be
a legal transition). When the device is in this state, command processing
is paused until the device leaves the SDEV_BLOCK state. See also
[`scsi_internal_device_unblock_nowait()`](#c-scsi_internal_device_unblock_nowait).

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

```c
int scsi_internal_device_unblock_nowait(struct scsi_device *sdev, enum scsi_device_state new_state)
```

resume a device after a block request

**Parameters**

- `struct scsi_device *sdev`: device to resume
- `enum scsi_device_state new_state`: state to set the device to after unblocking

**Description**

Restart the device queue for a previously suspended SCSI device. Does not
sleep.

Returns zero if successful or a negative error code upon failure.

**Notes**

This routine transitions the device to the SDEV_RUNNING state or to one of
the offline states (which must be a legal transition) allowing the midlayer
to goose the queue for this device.

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

```c
void scsi_block_targets(struct Scsi_Host *shost, struct device *dev)
```

transition all SCSI child devices to SDEV_BLOCK state

**Parameters**

- `struct Scsi_Host *shost`: the Scsi_Host to which this device belongs
- `struct device *dev`: a parent device of one or more scsi_target devices

**Description**

Iterate over all children of **dev**, which should be scsi_target devices,
and switch all subordinate scsi devices to SDEV_BLOCK state. Wait for
ongoing `scsi_queue_rq()` calls to finish. May sleep.

**Note**

**dev** must not itself be a scsi_target device.

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

```c
int scsi_host_block(struct Scsi_Host *shost)
```

Try to transition all logical units to the SDEV_BLOCK state

**Parameters**

- `struct Scsi_Host *shost`: device to block

**Description**

Pause SCSI command processing for all logical units associated with the SCSI
host and wait until pending `scsi_queue_rq()` calls have finished.

Returns zero if successful or a negative error code upon failure.

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

```c
void * scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count, size_t *offset, size_t *len)
```

find and atomically map an sg-elemnt

**Parameters**

- `struct scatterlist *sgl`: scatter-gather list
- `int sg_count`: number of segments in sg
- `size_t *offset`: offset in bytes into sg, on return offset into the mapped area
- `size_t *len`: bytes to map, on return number of bytes mapped

**Description**

Returns virtual address of the start of the mapped page

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

```c
void scsi_kunmap_atomic_sg(void *virt)
```

atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg

**Parameters**

- `void *virt`: virtual address to be unmapped

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

```c
int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len)
```

return a unique device identification

**Parameters**

- `struct scsi_device *sdev`: SCSI device
- `char *id`: buffer for the identification
- `size_t id_len`: length of the buffer

**Description**

Copies a unique device identification into **id** based
on the information in the VPD page 0x83 of the device.
The string will be formatted as a SCSI name string.

Returns the length of the identification or error on failure.
If the identifier is longer than the supplied buffer the actual
identifier length is returned and the buffer is not zero-padded.

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

```c
int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id)
```

return a target port group identifier

**Parameters**

- `struct scsi_device *sdev`: SCSI device
- `int *rel_id`: pointer to return relative target port in if not `NULL`

**Description**

Returns the Target Port Group identifier from the information
from VPD page 0x83 of the device.
Optionally sets **rel_id** to the relative target port on success.

**Return**

the identifier or error on failure.

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

```c
void scsi_build_sense(struct scsi_cmnd *scmd, int desc, u8 key, u8 asc, u8 ascq)
```

build sense data for a command

**Parameters**

- `struct scsi_cmnd *scmd`: scsi command for which the sense should be formatted
- `int desc`: Sense format (non-zero == descriptor format,
  0 == fixed format)
- `u8 key`: Sense key
- `u8 asc`: Additional sense code
- `u8 ascq`: Additional sense code qualifier


<a id="rst-drivers-scsi-scsi-lib-dma-c"></a>

#### drivers/scsi/scsi_lib_dma.c

SCSI library functions depending on DMA (map and unmap scatter-gather lists).


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

```c
int scsi_dma_map(struct scsi_cmnd *cmd)
```

perform DMA mapping against command's sg lists

**Parameters**

- `struct scsi_cmnd *cmd`: scsi command

**Description**

Returns the number of sg lists actually used, zero if the sg lists
is NULL, or -ENOMEM if the mapping failed.

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

```c
void scsi_dma_unmap(struct scsi_cmnd *cmd)
```

unmap command's sg lists mapped by scsi_dma_map

**Parameters**

- `struct scsi_cmnd *cmd`: scsi command


<a id="rst-drivers-scsi-scsi-proc-c"></a>

#### drivers/scsi/scsi_proc.c

The functions in this file provide an interface between the PROC file system and the SCSI device drivers It is mainly used for debugging, statistics and to pass information directly to the lowlevel driver. I.E. plumbing to manage /proc/scsi/\*


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

(host template, SCSI proc dir) association

**Definition**

```c
struct scsi_proc_entry {
    struct list_head        entry;
    const struct scsi_host_template *sht;
    struct proc_dir_entry   *proc_dir;
    unsigned int            present;
};
```

**Members**

- `entry`: entry in scsi_proc_list.
- `sht`: SCSI host template associated with the procfs directory.
- `proc_dir`: procfs directory associated with the SCSI host template.
- `present`: Number of SCSI hosts instantiated for **sht**.

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

```c
struct proc_dir_entry * scsi_template_proc_dir(const struct scsi_host_template *sht)
```

returns the procfs dir for a SCSI host template

**Parameters**

- `const struct scsi_host_template *sht`: SCSI host template pointer.

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

```c
int scsi_proc_hostdir_add(const struct scsi_host_template *sht)
```

Create directory in /proc for a scsi host

**Parameters**

- `const struct scsi_host_template *sht`: owner of this directory

**Description**

Sets sht->proc_dir to the new directory.

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

```c
void scsi_proc_hostdir_rm(const struct scsi_host_template *sht)
```

remove directory in /proc for a scsi host

**Parameters**

- `const struct scsi_host_template *sht`: owner of directory

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

```c
void scsi_proc_host_add(struct Scsi_Host *shost)
```

Add entry for this host to appropriate /proc dir

**Parameters**

- `struct Scsi_Host *shost`: host to add

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

```c
void scsi_proc_host_rm(struct Scsi_Host *shost)
```

remove this host's entry from /proc

**Parameters**

- `struct Scsi_Host *shost`: which host

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

```c
int proc_print_scsidevice(struct device *dev, void *data)
```

return data about this host

**Parameters**

- `struct device *dev`: A scsi device
- `void *data`: `struct seq_file` to output to.

**Description**

prints Host, Channel, Id, Lun, Vendor, Model, Rev, Type,
and revision.

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

```c
int scsi_add_single_device(uint host, uint channel, uint id, uint lun)
```

Respond to user request to probe for/add device

**Parameters**

- `uint host`: user-supplied decimal integer
- `uint channel`: user-supplied decimal integer
- `uint id`: user-supplied decimal integer
- `uint lun`: user-supplied decimal integer

**Description**

called by writing "scsi add-single-device" to /proc/scsi/scsi.

does [`scsi_host_lookup()`](#c-scsi_host_lookup) and either `user_scan()` if that transport
type supports it, or else `scsi_scan_host_selected()`

**Note**

this seems to be aimed exclusively at SCSI parallel busses.

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

```c
int scsi_remove_single_device(uint host, uint channel, uint id, uint lun)
```

Respond to user request to remove a device

**Parameters**

- `uint host`: user-supplied decimal integer
- `uint channel`: user-supplied decimal integer
- `uint id`: user-supplied decimal integer
- `uint lun`: user-supplied decimal integer

**Description**

called by writing "scsi remove-single-device" to
/proc/scsi/scsi.  Does a [`scsi_device_lookup()`](#c-scsi_device_lookup) and [`scsi_remove_device()`](#c-scsi_remove_device)

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

```c
ssize_t proc_scsi_write(struct file *file, const char __user *buf, size_t length, loff_t *ppos)
```

handle writes to /proc/scsi/scsi

**Parameters**

- `struct file *file`: not used
- `const char __user *buf`: buffer to write
- `size_t length`: length of buf, at most PAGE_SIZE
- `loff_t *ppos`: not used

**Description**

this provides a legacy mechanism to add or remove devices by
Host, Channel, ID, and Lun.  To use,
"echo 'scsi add-single-device 0 1 2 3' > /proc/scsi/scsi" or
"echo 'scsi remove-single-device 0 1 2 3' > /proc/scsi/scsi" with
"0 1 2 3" replaced by the Host, Channel, Id, and Lun.

**Note**

this seems to be aimed at parallel SCSI. Most modern busses (USB,
SATA, Firewire, Fibre Channel, etc) dynamically assign these values to
provide a unique identifier and nothing more.

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

```c
int proc_scsi_open(struct inode *inode, struct file *file)
```

glue function

**Parameters**

- `struct inode *inode`: not used
- `struct file *file`: passed to `single_open()`

**Description**

Associates proc_scsi_show with this file

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

```c
int scsi_init_procfs(void)
```

create scsi and scsi/scsi in procfs

**Parameters**

- `void`: no arguments

#### <a id="c-scsi_exit_procfs"></a>`scsi_exit_procfs()`

```c
void scsi_exit_procfs(void)
```

Remove scsi/scsi and scsi from procfs

**Parameters**

- `void`: no arguments


<a id="rst-drivers-scsi-scsi-netlink-c"></a>

#### drivers/scsi/scsi_netlink.c

Infrastructure to provide async events from transports to userspace via netlink, using a single NETLINK_SCSITRANSPORT protocol for all transports. See [the original patch submission](<https://lore.kernel.org/linux-scsi/1155070439.6275.5.camel@localhost.localdomain/>) for more details.


#### <a id="c-scsi_nl_rcv_msg"></a>`scsi_nl_rcv_msg()`

```c
void scsi_nl_rcv_msg(struct sk_buff *skb)
```

Receive message handler.

**Parameters**

- `struct sk_buff *skb`: socket receive buffer

**Description**

- Extracts message from a receive buffer.

  Validates message header and calls appropriate transport message handler

#### <a id="c-scsi_netlink_init"></a>`scsi_netlink_init()`

```c
void scsi_netlink_init(void)
```

Called by SCSI subsystem to initialize the SCSI transport netlink interface

**Parameters**

- `void`: no arguments

#### <a id="c-scsi_netlink_exit"></a>`scsi_netlink_exit()`

```c
void scsi_netlink_exit(void)
```

Called by SCSI subsystem to disable the SCSI transport netlink interface

**Parameters**

- `void`: no arguments


<a id="rst-drivers-scsi-scsi-scan-c"></a>

#### drivers/scsi/scsi_scan.c

Scan a host to determine which (if any) devices are attached. The general scanning/probing algorithm is as follows, exceptions are made to it depending on device specific flags, compilation options, and global variable (boot or module load time) settings. A specific LUN is scanned via an INQUIRY command; if the LUN has a device attached, a scsi_device is allocated and setup for it. For every id of every channel on the given host, start by scanning LUN 0. Skip hosts that don't respond at all to a scan of LUN 0. Otherwise, if LUN 0 has a device attached, allocate and setup a scsi_device for it. If target is SCSI-3 or up, issue a REPORT LUN, and scan all of the LUNs returned by the REPORT LUN; else, sequentially scan LUNs up until some maximum is reached, or a LUN is seen that cannot have a device attached to it.


#### <a id="c-scsi_sanitize_inquiry_string"></a>`scsi_sanitize_inquiry_string()`

```c
void scsi_sanitize_inquiry_string(unsigned char *s, int len)
```

remove non-graphical chars from an INQUIRY result string

**Parameters**

- `unsigned char *s`: INQUIRY result string to sanitize
- `int len`: length of the string

**Description**

The SCSI spec says that INQUIRY vendor, product, and revision
strings must consist entirely of graphic ASCII characters,
padded on the right with spaces.  Since not all devices obey
this rule, we will replace non-graphic or non-ASCII characters
with spaces.  Exception: a NUL character is interpreted as a
string terminator, so all the following characters are set to
spaces.

#### <a id="c-scsi_add_device"></a>`scsi_add_device()`

```c
int scsi_add_device(struct Scsi_Host *host, uint channel, uint target, u64 lun)
```

creates a new SCSI (LU) instance

**Parameters**

- `struct Scsi_Host *host`: the `Scsi_Host` instance where the device is located
- `uint channel`: target channel number (rarely other than `0`)
- `uint target`: target id number
- `u64 lun`: LUN of target device

**Description**

Probe for a specific LUN and add it if found.

**Notes**

This call is usually performed internally during a SCSI
bus scan when an HBA is added (i.e. [`scsi_scan_host()`](#c-scsi_scan_host)). So it
should only be called if the HBA becomes aware of a new SCSI
device (LU) after [`scsi_scan_host()`](#c-scsi_scan_host) has completed. If successful
this call can lead to `sdev_init()` and `sdev_configure()` callbacks
into the LLD.

**Return**

`0` on success or negative error code on failure

#### <a id="c-scsi_scan_target"></a>`scsi_scan_target()`

```c
void scsi_scan_target(struct device *parent, unsigned int channel, unsigned int id, u64 lun, enum scsi_scan_mode rescan)
```

scan a target id, possibly including all LUNs on the target.

**Parameters**

- `struct device *parent`: host to scan
- `unsigned int channel`: channel to scan
- `unsigned int id`: target id to scan
- `u64 lun`: Specific LUN to scan or SCAN_WILD_CARD
- `enum scsi_scan_mode rescan`: passed to LUN scanning routines; SCSI_SCAN_INITIAL for
  no rescan, SCSI_SCAN_RESCAN to rescan existing LUNs,
  and SCSI_SCAN_MANUAL to force scanning even if
  'scan=manual' is set.

**Description**

Scan the target id on **parent**, **channel**, and **id**. Scan at least LUN 0,
and possibly all LUNs on the target id.

First try a REPORT LUN scan, if that does not scan the target, do a
sequential scan of LUNs on the target id.

#### <a id="c-scsi_scan_host"></a>`scsi_scan_host()`

```c
void scsi_scan_host(struct Scsi_Host *shost)
```

scan the given adapter

**Parameters**

- `struct Scsi_Host *shost`: adapter to scan

**Notes**

Should be called after `scsi_add_host()`


<a id="rst-drivers-scsi-scsi-sysctl-c"></a>

#### drivers/scsi/scsi_sysctl.c

Set up the sysctl entry: "/dev/scsi/logging_level" (DEV_SCSI_LOGGING_LEVEL) which sets/returns scsi_logging_level.

<a id="rst-drivers-scsi-scsi-sysfs-c"></a>

#### drivers/scsi/scsi_sysfs.c

SCSI sysfs interface routines.


#### <a id="c-scsi_remove_device"></a>`scsi_remove_device()`

```c
void scsi_remove_device(struct scsi_device *sdev)
```

unregister a device from the scsi bus

**Parameters**

- `struct scsi_device *sdev`: scsi_device to unregister

#### <a id="c-scsi_remove_target"></a>`scsi_remove_target()`

```c
void scsi_remove_target(struct device *dev)
```

try to remove a target and all its devices

**Parameters**

- `struct device *dev`: generic starget or parent of generic stargets to be removed

**Note**

This is slightly racy.  It is possible that if the user
requests the addition of another device then the target won't be
removed.


<a id="rst-drivers-scsi-hosts-c"></a>

#### drivers/scsi/hosts.c

mid to lowlevel SCSI driver interface


#### <a id="c-scsi_remove_host"></a>`scsi_remove_host()`

```c
void scsi_remove_host(struct Scsi_Host *shost)
```

remove a scsi host

**Parameters**

- `struct Scsi_Host *shost`: a pointer to a scsi host to remove

#### <a id="c-scsi_add_host_with_dma"></a>`scsi_add_host_with_dma()`

```c
int scsi_add_host_with_dma(struct Scsi_Host *shost, struct device *dev, struct device *dma_dev)
```

add a scsi host with dma device

**Parameters**

- `struct Scsi_Host *shost`: scsi host pointer to add
- `struct device *dev`: a struct device of type scsi class
- `struct device *dma_dev`: dma device for the host

**Note**

You rarely need to worry about this unless you're in a
virtualised host environments, so use the simpler `scsi_add_host()`
function instead.

- Return value:
  0 on success / != 0 for error

#### <a id="c-scsi_host_alloc"></a>`scsi_host_alloc()`

```c
struct Scsi_Host * scsi_host_alloc(const struct scsi_host_template *sht, int privsize)
```

register a scsi host adapter instance.

**Parameters**

- `const struct scsi_host_template *sht`: pointer to scsi host template
- `int privsize`: extra bytes to allocate for driver

**Note**

Allocate a new Scsi_Host and perform basic initialization.
The host is not published to the scsi midlayer until scsi_add_host
is called.

- Return value:
  Pointer to a new Scsi_Host

#### <a id="c-scsi_host_lookup"></a>`scsi_host_lookup()`

```c
struct Scsi_Host * scsi_host_lookup(unsigned int hostnum)
```

get a reference to a Scsi_Host by host no

**Parameters**

- `unsigned int hostnum`: host number to locate

**Description**

- Return value:
  A pointer to located Scsi_Host or NULL.

  The caller must do a [`scsi_host_put()`](#c-scsi_host_put) to drop the reference
  that [`scsi_host_get()`](#c-scsi_host_get) took. The [`put_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-put_device) below dropped
  the reference from [`class_find_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-class_find_device).

#### <a id="c-scsi_host_get"></a>`scsi_host_get()`

```c
struct Scsi_Host * scsi_host_get(struct Scsi_Host *shost)
```

inc a Scsi_Host ref count

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host to inc.

#### <a id="c-scsi_host_busy"></a>`scsi_host_busy()`

```c
int scsi_host_busy(struct Scsi_Host *shost)
```

Return the count of in-flight commands

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host

#### <a id="c-scsi_host_put"></a>`scsi_host_put()`

```c
void scsi_host_put(struct Scsi_Host *shost)
```

dec a Scsi_Host ref count

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host to dec.

#### <a id="c-scsi_queue_work"></a>`scsi_queue_work()`

```c
int scsi_queue_work(struct Scsi_Host *shost, struct work_struct *work)
```

Queue work to the Scsi_Host workqueue.

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host.
- `struct work_struct *work`: Work to queue for execution.

**Description**

- Return value:
  1 - work queued for execution
  0 - work is already queued
  -EINVAL - work queue doesn't exist

#### <a id="c-scsi_flush_work"></a>`scsi_flush_work()`

```c
void scsi_flush_work(struct Scsi_Host *shost)
```

Flush a Scsi_Host's workqueue.

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host.

#### <a id="c-scsi_host_complete_all_commands"></a>`scsi_host_complete_all_commands()`

```c
void scsi_host_complete_all_commands(struct Scsi_Host *shost, enum scsi_host_status status)
```

Terminate all running commands

**Parameters**

- `struct Scsi_Host *shost`: Scsi Host on which commands should be terminated
- `enum scsi_host_status status`: Status to be set for the terminated commands

**Description**

There is no protection against modification of the number
of outstanding commands. It is the responsibility of the
caller to ensure that concurrent I/O submission and/or
completion is stopped when calling this function.

#### <a id="c-scsi_host_busy_iter"></a>`scsi_host_busy_iter()`

```c
void scsi_host_busy_iter(struct Scsi_Host *shost, bool (*fn)(struct scsi_cmnd *, void *), void *priv)
```

Iterate over all busy commands

**Parameters**

- `struct Scsi_Host *shost`: Pointer to Scsi_Host.
- `bool (*fn)(struct scsi_cmnd *, void *)`: Function to call on each busy command
- `void *priv`: Data pointer passed to **fn**

**Description**

If locking against concurrent command completions is required
ithas to be provided by the caller


<a id="rst-drivers-scsi-scsi-common-c"></a>

#### drivers/scsi/scsi_common.c

general support functions


#### <a id="c-scsi_device_type"></a>`scsi_device_type()`

```c
const char * scsi_device_type(unsigned type)
```

Return 17-char string indicating device type.

**Parameters**

- `unsigned type`: type number to look up

#### <a id="c-scsilun_to_int"></a>`scsilun_to_int()`

```c
u64 scsilun_to_int(struct scsi_lun *scsilun)
```

convert a scsi_lun to an int

**Parameters**

- `struct scsi_lun *scsilun`: struct scsi_lun to be converted.

**Description**

Convert **scsilun** from a struct scsi_lun to a four-byte host byte-ordered
integer, and return the result. The caller must check for
truncation before using this function.

**Notes**

For a description of the LUN format, post SCSI-3 see the SCSI
Architecture Model, for SCSI-3 see the SCSI Controller Commands.

Given a struct scsi_lun of: d2 04 0b 03 00 00 00 00, this function
returns the integer: 0x0b03d204

This encoding will return a standard integer LUN for LUNs smaller
than 256, which typically use a single level LUN structure with
addressing method 0.

#### <a id="c-int_to_scsilun"></a>`int_to_scsilun()`

```c
void int_to_scsilun(u64 lun, struct scsi_lun *scsilun)
```

reverts an int into a scsi_lun

**Parameters**

- `u64 lun`: integer to be reverted
- `struct scsi_lun *scsilun`: struct scsi_lun to be set.

**Description**

Reverts the functionality of the scsilun_to_int, which packed
an 8-byte lun value into an int. This routine unpacks the int
back into the lun value.

**Notes**

Given an integer : 0x0b03d204, this function returns a
struct scsi_lun of: d2 04 0b 03 00 00 00 00

#### <a id="c-scsi_normalize_sense"></a>`scsi_normalize_sense()`

```c
bool scsi_normalize_sense(const u8 *sense_buffer, int sb_len, struct scsi_sense_hdr *sshdr)
```

normalize main elements from either fixed or descriptor sense data format into a common format.

**Parameters**

- `const u8 *sense_buffer`: byte array containing sense data returned by device
- `int sb_len`: number of valid bytes in sense_buffer
- `struct scsi_sense_hdr *sshdr`: pointer to instance of structure that common
  elements are written to.

**Notes**

The "main elements" from sense data are: response_code, sense_key,
asc, ascq and additional_length (only for descriptor format).

Typically this function can be called after a device has
responded to a SCSI command with the CHECK_CONDITION status.

- Return value:
  true if valid sense data information found, else false;

#### <a id="c-scsi_sense_desc_find"></a>`scsi_sense_desc_find()`

```c
const u8 * scsi_sense_desc_find(const u8 * sense_buffer, int sb_len, int desc_type)
```

search for a given descriptor type in descriptor sense data format.

**Parameters**

- `const u8 * sense_buffer`: byte array of descriptor format sense data
- `int sb_len`: number of valid bytes in sense_buffer
- `int desc_type`: value of descriptor type to find
  (e.g. 0 -> information)

**Notes**

only valid when sense data is in descriptor format

- Return value:
  pointer to start of (first) descriptor if found else NULL

#### <a id="c-scsi_build_sense_buffer"></a>`scsi_build_sense_buffer()`

```c
void scsi_build_sense_buffer(int desc, u8 *buf, u8 key, u8 asc, u8 ascq)
```

build sense data in a buffer

**Parameters**

- `int desc`: Sense format (non-zero == descriptor format,
  0 == fixed format)
- `u8 *buf`: Where to build sense data
- `u8 key`: Sense key
- `u8 asc`: Additional sense code
- `u8 ascq`: Additional sense code qualifier

#### <a id="c-scsi_set_sense_information"></a>`scsi_set_sense_information()`

```c
int scsi_set_sense_information(u8 *buf, int buf_len, u64 info)
```

set the information field in a formatted sense data buffer

**Parameters**

- `u8 *buf`: Where to build sense data
- `int buf_len`: buffer length
- `u64 info`: 64-bit information value to be set

**Description**

- Return value:
  0 on success or -EINVAL for invalid sense buffer length

#### <a id="c-scsi_set_sense_field_pointer"></a>`scsi_set_sense_field_pointer()`

```c
int scsi_set_sense_field_pointer(u8 *buf, int buf_len, u16 fp, u8 bp, bool cd)
```

set the field pointer sense key specific information in a formatted sense data buffer

**Parameters**

- `u8 *buf`: Where to build sense data
- `int buf_len`: buffer length
- `u16 fp`: field pointer to be set
- `u8 bp`: bit pointer to be set
- `bool cd`: command/data bit

**Description**

- Return value:
  0 on success or -EINVAL for invalid sense buffer length


<a id="rst-transport-classes"></a>

### Transport classes

Transport classes are service libraries for drivers in the SCSI lower layer, which expose transport attributes in sysfs.

<a id="rst-fibre-channel-transport"></a>

#### Fibre Channel transport

The file drivers/scsi/scsi_transport_fc.c defines transport attributes for Fibre Channel.


#### <a id="c-fc_get_event_number"></a>`fc_get_event_number()`

```c
u32 fc_get_event_number(void)
```

Obtain the next sequential FC event number

**Parameters**

- `void`: no arguments

**Notes**

We could have inlined this, but it would have required fc_event_seq to
be exposed. For now, live with the subroutine call.
Atomic used to avoid lock/unlock...

#### <a id="c-fc_host_post_fc_event"></a>`fc_host_post_fc_event()`

```c
void fc_host_post_fc_event(struct Scsi_Host *shost, u32 event_number, enum fc_host_event_code event_code, u32 data_len, char *data_buf, u64 vendor_id)
```

routine to do the work of posting an event on an fc_host.

**Parameters**

- `struct Scsi_Host *shost`: host the event occurred on
- `u32 event_number`: fc event number obtained from `get_fc_event_number()`
- `enum fc_host_event_code event_code`: fc_host event being posted
- `u32 data_len`: amount, in bytes, of event data
- `char *data_buf`: pointer to event data
- `u64 vendor_id`: value for Vendor id

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_host_post_event"></a>`fc_host_post_event()`

```c
void fc_host_post_event(struct Scsi_Host *shost, u32 event_number, enum fc_host_event_code event_code, u32 event_data)
```

called to post an even on an fc_host.

**Parameters**

- `struct Scsi_Host *shost`: host the event occurred on
- `u32 event_number`: fc event number obtained from `get_fc_event_number()`
- `enum fc_host_event_code event_code`: fc_host event being posted
- `u32 event_data`: 32bits of data for the event being posted

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_host_post_vendor_event"></a>`fc_host_post_vendor_event()`

```c
void fc_host_post_vendor_event(struct Scsi_Host *shost, u32 event_number, u32 data_len, char * data_buf, u64 vendor_id)
```

called to post a vendor unique event on an fc_host

**Parameters**

- `struct Scsi_Host *shost`: host the event occurred on
- `u32 event_number`: fc event number obtained from `get_fc_event_number()`
- `u32 data_len`: amount, in bytes, of vendor unique data
- `char * data_buf`: pointer to vendor unique data
- `u64 vendor_id`: Vendor id

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_find_rport_by_wwpn"></a>`fc_find_rport_by_wwpn()`

```c
struct fc_rport * fc_find_rport_by_wwpn(struct Scsi_Host *shost, u64 wwpn)
```

find the fc_rport pointer for a given wwpn

**Parameters**

- `struct Scsi_Host *shost`: host the fc_rport is associated with
- `u64 wwpn`: wwpn of the fc_rport device

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_host_fpin_rcv"></a>`fc_host_fpin_rcv()`

```c
void fc_host_fpin_rcv(struct Scsi_Host *shost, u32 fpin_len, char *fpin_buf, u8 event_acknowledge)
```

routine to process a received FPIN.

**Parameters**

- `struct Scsi_Host *shost`: host the FPIN was received on
- `u32 fpin_len`: length of FPIN payload, in bytes
- `char *fpin_buf`: pointer to FPIN payload
- `u8 event_acknowledge`: 1, if LLDD handles this event.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_eh_timed_out"></a>`fc_eh_timed_out()`

```c
enum scsi_timeout_action fc_eh_timed_out(struct scsi_cmnd *scmd)
```

FC Transport I/O timeout intercept handler

**Parameters**

- `struct scsi_cmnd *scmd`: The SCSI command which timed out

**Description**

This routine protects against error handlers getting invoked while a
rport is in a blocked state, typically due to a temporarily loss of
connectivity. If the error handlers are allowed to proceed, requests
to abort i/o, reset the target, etc will likely fail as there is no way
to communicate with the device to perform the requested function. These
failures may result in the midlayer taking the device offline, requiring
manual intervention to restore operation.

This routine, called whenever an i/o times out, validates the state of
the underlying rport. If the rport is blocked, it returns
EH_RESET_TIMER, which will continue to reschedule the timeout.
Eventually, either the device will return, or devloss_tmo will fire,
and when the timeout then fires, it will be handled normally.
If the rport is not blocked, normal error handling continues.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_remove_host"></a>`fc_remove_host()`

```c
void fc_remove_host(struct Scsi_Host *shost)
```

called to terminate any fc_transport-related elements for a scsi host.

**Parameters**

- `struct Scsi_Host *shost`: Which `Scsi_Host`

**Description**

This routine is expected to be called immediately preceding the
a driver's call to [`scsi_remove_host()`](#c-scsi_remove_host).

- WARNING: A driver utilizing the fc_transport, which fails to call

  this routine prior to [`scsi_remove_host()`](#c-scsi_remove_host), will leave dangling
  objects in /sys/class/fc_remote_ports. Access to any of these
  objects can result in a system crash !!!

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_remote_port_add"></a>`fc_remote_port_add()`

```c
struct fc_rport * fc_remote_port_add(struct Scsi_Host *shost, int channel, struct fc_rport_identifiers *ids)
```

notify fc transport of the existence of a remote FC port.

**Parameters**

- `struct Scsi_Host *shost`: scsi host the remote port is connected to.
- `int channel`: Channel on shost port connected to.
- `struct fc_rport_identifiers *ids`: The world wide names, fc address, and FC4 port
  roles for the remote port.

**Description**

The LLDD calls this routine to notify the transport of the existence
of a remote port. The LLDD provides the unique identifiers (wwpn,wwn)
of the port, it's FC address (port_id), and the FC4 roles that are
active for the port.

For ports that are FCP targets (aka scsi targets), the FC transport
maintains consistent target id bindings on behalf of the LLDD.
A consistent target id binding is an assignment of a target id to
a remote port identifier, which persists while the scsi host is
attached. The remote port can disappear, then later reappear, and
it's target id assignment remains the same. This allows for shifts
in FC addressing (if binding by wwpn or wwnn) with no apparent
changes to the scsi subsystem which is based on scsi host number and
target id values.  Bindings are only valid during the attachment of
the scsi host. If the host detaches, then later re-attaches, target
id bindings may change.

This routine is responsible for returning a remote port structure.
The routine will search the list of remote ports it maintains
internally on behalf of consistent target id mappings. If found, the
remote port structure will be reused. Otherwise, a new remote port
structure will be allocated.

Whenever a remote port is allocated, a new fc_remote_port class
device is created.

Should not be called from interrupt context.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_remote_port_delete"></a>`fc_remote_port_delete()`

```c
void fc_remote_port_delete(struct fc_rport *rport)
```

notifies the fc transport that a remote port is no longer in existence.

**Parameters**

- `struct fc_rport *rport`: The remote port that no longer exists

**Description**

The LLDD calls this routine to notify the transport that a remote
port is no longer part of the topology. Note: Although a port
may no longer be part of the topology, it may persist in the remote
ports displayed by the fc_host. We do this under 2 conditions:

1) If the port was a scsi target, we delay its deletion by "blocking" it.
   This allows the port to temporarily disappear, then reappear without
   disrupting the SCSI device tree attached to it. During the "blocked"
   period the port will still exist.

2) If the port was a scsi target and disappears for longer than we
   expect, we'll delete the port and the tear down the SCSI device tree
   attached to it. However, we want to semi-persist the target id assigned
   to that port if it eventually does exist. The port structure will
   remain (although with minimal information) so that the target id
   bindings also remain.

If the remote port is not an FCP Target, it will be fully torn down
and deallocated, including the fc_remote_port class device.

If the remote port is an FCP Target, the port will be placed in a
temporary blocked state. From the LLDD's perspective, the rport no
longer exists. From the SCSI midlayer's perspective, the SCSI target
exists, but all sdevs on it are blocked from further I/O. The following
is then expected.

If the remote port does not return (signaled by a LLDD call to
[`fc_remote_port_add()`](#c-fc_remote_port_add)) within the dev_loss_tmo timeout, then the
scsi target is removed - killing all outstanding i/o and removing the
scsi devices attached to it. The port structure will be marked Not
Present and be partially cleared, leaving only enough information to
recognize the remote port relative to the scsi target id binding if
it later appears.  The port will remain as long as there is a valid
binding (e.g. until the user changes the binding type or unloads the
scsi host with the binding).

If the remote port returns within the dev_loss_tmo value (and matches
according to the target id binding type), the port structure will be
reused. If it is no longer a SCSI target, the target will be torn
down. If it continues to be a SCSI target, then the target will be
unblocked (allowing i/o to be resumed), and a scan will be activated
to ensure that all luns are detected.

Called from normal process context only - cannot be called from interrupt.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_remote_port_rolechg"></a>`fc_remote_port_rolechg()`

```c
void fc_remote_port_rolechg(struct fc_rport *rport, u32 roles)
```

notifies the fc transport that the roles on a remote may have changed.

**Parameters**

- `struct fc_rport *rport`: The remote port that changed.
- `u32 roles`: New roles for this port.

**Description**

The LLDD calls this routine to notify the transport that the
roles on a remote port may have changed. The largest effect of this is
if a port now becomes a FCP Target, it must be allocated a
scsi target id.  If the port is no longer a FCP target, any
scsi target id value assigned to it will persist in case the
role changes back to include FCP Target. No changes in the scsi
midlayer will be invoked if the role changes (in the expectation
that the role will be resumed. If it doesn't normal error processing
will take place).

Should not be called from interrupt context.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_block_rport"></a>`fc_block_rport()`

```c
int fc_block_rport(struct fc_rport *rport)
```

Block SCSI eh thread for blocked fc_rport.

**Parameters**

- `struct fc_rport *rport`: Remote port that scsi_eh is trying to recover.

**Description**

This routine can be called from a FC LLD scsi_eh callback. It
blocks the scsi_eh thread until the fc_rport leaves the
FC_PORTSTATE_BLOCKED, or the fast_io_fail_tmo fires. This is
necessary to avoid the scsi_eh failing recovery actions for blocked
rports which would lead to offlined SCSI devices.

**Return**

0 if the fc_rport left the state FC_PORTSTATE_BLOCKED.
FAST_IO_FAIL if the fast_io_fail_tmo fired, this should be
passed back to scsi_eh.

#### <a id="c-fc_block_scsi_eh"></a>`fc_block_scsi_eh()`

```c
int fc_block_scsi_eh(struct scsi_cmnd *cmnd)
```

Block SCSI eh thread for blocked fc_rport

**Parameters**

- `struct scsi_cmnd *cmnd`: SCSI command that scsi_eh is trying to recover

**Description**

This routine can be called from a FC LLD scsi_eh callback. It
blocks the scsi_eh thread until the fc_rport leaves the
FC_PORTSTATE_BLOCKED, or the fast_io_fail_tmo fires. This is
necessary to avoid the scsi_eh failing recovery actions for blocked
rports which would lead to offlined SCSI devices.

**Return**

0 if the fc_rport left the state FC_PORTSTATE_BLOCKED.
FAST_IO_FAIL if the fast_io_fail_tmo fired, this should be
passed back to scsi_eh.

#### <a id="c-fc_vport_create"></a>`fc_vport_create()`

```c
struct fc_vport * fc_vport_create(struct Scsi_Host *shost, int channel, struct fc_vport_identifiers *ids)
```

Admin App or LLDD requests creation of a vport

**Parameters**

- `struct Scsi_Host *shost`: scsi host the virtual port is connected to.
- `int channel`: channel on shost port connected to.
- `struct fc_vport_identifiers *ids`: The world wide names, FC4 port roles, etc for
  the virtual port.

**Notes**

This routine assumes no locks are held on entry.

#### <a id="c-fc_vport_terminate"></a>`fc_vport_terminate()`

```c
int fc_vport_terminate(struct fc_vport *vport)
```

Admin App or LLDD requests termination of a vport

**Parameters**

- `struct fc_vport *vport`: fc_vport to be terminated

**Description**

Calls the LLDD `vport_delete()` function, then deallocates and removes
the vport from the shost and object tree.

**Notes**

This routine assumes no locks are held on entry.


<a id="rst-iscsi-transport-class"></a>

#### iSCSI transport class

The file drivers/scsi/scsi_transport_iscsi.c defines transport attributes for the iSCSI class, which sends SCSI packets over TCP/IP connections.


#### <a id="c-iscsi_lookup_endpoint"></a>`iscsi_lookup_endpoint()`

```c
struct iscsi_endpoint * iscsi_lookup_endpoint(u64 handle)
```

get ep from handle

**Parameters**

- `u64 handle`: endpoint handle

**Description**

Caller must do a iscsi_put_endpoint.

#### <a id="c-iscsi_create_flashnode_sess"></a>`iscsi_create_flashnode_sess()`

```c
struct iscsi_bus_flash_session * iscsi_create_flashnode_sess(struct Scsi_Host *shost, int index, struct iscsi_transport *transport, int dd_size)
```

Add flashnode session entry in sysfs

**Parameters**

- `struct Scsi_Host *shost`: pointer to host data
- `int index`: index of flashnode to add in sysfs
- `struct iscsi_transport *transport`: pointer to transport data
- `int dd_size`: total size to allocate

**Description**

Adds a sysfs entry for the flashnode session attributes

**Return**

pointer to allocated flashnode sess on success
`NULL` on failure

#### <a id="c-iscsi_create_flashnode_conn"></a>`iscsi_create_flashnode_conn()`

```c
struct iscsi_bus_flash_conn * iscsi_create_flashnode_conn(struct Scsi_Host *shost, struct iscsi_bus_flash_session *fnode_sess, struct iscsi_transport *transport, int dd_size)
```

Add flashnode conn entry in sysfs

**Parameters**

- `struct Scsi_Host *shost`: pointer to host data
- `struct iscsi_bus_flash_session *fnode_sess`: pointer to the parent flashnode session entry
- `struct iscsi_transport *transport`: pointer to transport data
- `int dd_size`: total size to allocate

**Description**

Adds a sysfs entry for the flashnode connection attributes

**Return**

pointer to allocated flashnode conn on success
`NULL` on failure

#### <a id="c-iscsi_find_flashnode_sess"></a>`iscsi_find_flashnode_sess()`

```c
struct device * iscsi_find_flashnode_sess(struct Scsi_Host *shost, const void *data, device_match_t fn)
```

finds flashnode session entry

**Parameters**

- `struct Scsi_Host *shost`: pointer to host data
- `const void *data`: pointer to data containing value to use for comparison
- `device_match_t fn`: function pointer that does actual comparison

**Description**

Finds the flashnode session object comparing the data passed using logic
defined in passed function pointer

**Return**

pointer to found flashnode session device object on success
`NULL` on failure

#### <a id="c-iscsi_find_flashnode_conn"></a>`iscsi_find_flashnode_conn()`

```c
struct device * iscsi_find_flashnode_conn(struct iscsi_bus_flash_session *fnode_sess)
```

finds flashnode connection entry

**Parameters**

- `struct iscsi_bus_flash_session *fnode_sess`: pointer to parent flashnode session entry

**Description**

Finds the flashnode connection object comparing the data passed using logic
defined in passed function pointer

**Return**

pointer to found flashnode connection device object on success
`NULL` on failure

#### <a id="c-iscsi_destroy_flashnode_sess"></a>`iscsi_destroy_flashnode_sess()`

```c
void iscsi_destroy_flashnode_sess(struct iscsi_bus_flash_session *fnode_sess)
```

destroy flashnode session entry

**Parameters**

- `struct iscsi_bus_flash_session *fnode_sess`: pointer to flashnode session entry to be destroyed

**Description**

Deletes the flashnode session entry and all children flashnode connection
entries from sysfs

#### <a id="c-iscsi_destroy_all_flashnode"></a>`iscsi_destroy_all_flashnode()`

```c
void iscsi_destroy_all_flashnode(struct Scsi_Host *shost)
```

destroy all flashnode session entries

**Parameters**

- `struct Scsi_Host *shost`: pointer to host data

**Description**

Destroys all the flashnode session entries and all corresponding children
flashnode connection entries from sysfs

#### <a id="c-iscsi_block_scsi_eh"></a>`iscsi_block_scsi_eh()`

```c
int iscsi_block_scsi_eh(struct scsi_cmnd *cmd)
```

block scsi eh until session state has transistioned

**Parameters**

- `struct scsi_cmnd *cmd`: scsi cmd passed to scsi eh handler

**Description**

If the session is down this function will wait for the recovery
timer to fire or for the session to be logged back in. If the
recovery timer fires then FAST_IO_FAIL is returned. The caller
should pass this error value to the scsi eh.

#### <a id="c-iscsi_unblock_session"></a>`iscsi_unblock_session()`

```c
void iscsi_unblock_session(struct iscsi_cls_session *session)
```

set a session as logged in and start IO.

**Parameters**

- `struct iscsi_cls_session *session`: iscsi session

**Description**

Mark a session as ready to accept IO.

#### <a id="c-iscsi_force_destroy_session"></a>`iscsi_force_destroy_session()`

```c
void iscsi_force_destroy_session(struct iscsi_cls_session *session)
```

destroy a session from the kernel

**Parameters**

- `struct iscsi_cls_session *session`: session to destroy

**Description**

Force the destruction of a session from the kernel. This should only be
used when userspace is no longer running during system shutdown.

#### <a id="c-iscsi_alloc_conn"></a>`iscsi_alloc_conn()`

```c
struct iscsi_cls_conn * iscsi_alloc_conn(struct iscsi_cls_session *session, int dd_size, uint32_t cid)
```

alloc iscsi class connection

**Parameters**

- `struct iscsi_cls_session *session`: iscsi cls session
- `int dd_size`: private driver data size
- `uint32_t cid`: connection id

#### <a id="c-iscsi_add_conn"></a>`iscsi_add_conn()`

```c
int iscsi_add_conn(struct iscsi_cls_conn *conn)
```

add iscsi class connection

**Parameters**

- `struct iscsi_cls_conn *conn`: iscsi cls connection

**Description**

This will expose iscsi_cls_conn to sysfs so make sure the related
resources for sysfs attributes are initialized before calling this.

#### <a id="c-iscsi_remove_conn"></a>`iscsi_remove_conn()`

```c
void iscsi_remove_conn(struct iscsi_cls_conn *conn)
```

remove iscsi class connection from sysfs

**Parameters**

- `struct iscsi_cls_conn *conn`: iscsi cls connection

**Description**

Remove iscsi_cls_conn from sysfs, and wait for previous
read/write of iscsi_cls_conn's attributes in sysfs to finish.

#### <a id="c-iscsi_session_event"></a>`iscsi_session_event()`

```c
int iscsi_session_event(struct iscsi_cls_session *session, enum iscsi_uevent_e event)
```

send session destr. completion event

**Parameters**

- `struct iscsi_cls_session *session`: iscsi class session
- `enum iscsi_uevent_e event`: type of event


<a id="rst-serial-attached-scsi-sas-transport-class"></a>

#### Serial Attached SCSI (SAS) transport class

The file drivers/scsi/scsi_transport_sas.c defines transport attributes for Serial Attached SCSI, a variant of SATA aimed at large high-end systems.

The SAS transport class contains common code to deal with SAS HBAs, an approximated representation of SAS topologies in the driver model, and various sysfs attributes to expose these topologies and management interfaces to userspace.

In addition to the basic SCSI core objects this transport class introduces two additional intermediate objects: The SAS PHY as represented by struct sas_phy defines an "outgoing" PHY on a SAS HBA or Expander, and the SAS remote PHY represented by struct sas_rphy defines an "incoming" PHY on a SAS Expander or end device. Note that this is purely a software concept, the underlying hardware for a PHY and a remote PHY is the exactly the same.

There is no concept of a SAS port in this code, users can see what PHYs form a wide port based on the port_identifier attribute, which is the same for all PHYs in a port.


#### <a id="c-sas_remove_children"></a>`sas_remove_children()`

```c
void sas_remove_children(struct device *dev)
```

tear down a devices SAS data structures

**Parameters**

- `struct device *dev`: device belonging to the sas object

**Description**

Removes all SAS PHYs and remote PHYs for a given object

#### <a id="c-sas_remove_host"></a>`sas_remove_host()`

```c
void sas_remove_host(struct Scsi_Host *shost)
```

tear down a Scsi_Host's SAS data structures

**Parameters**

- `struct Scsi_Host *shost`: Scsi Host that is torn down

**Description**

Removes all SAS PHYs and remote PHYs for a given Scsi_Host and remove the
Scsi_Host as well.

**Note**

Do not call [`scsi_remove_host()`](#c-scsi_remove_host) on the Scsi_Host any more, as it is
already removed.

#### <a id="c-sas_get_address"></a>`sas_get_address()`

```c
u64 sas_get_address(struct scsi_device *sdev)
```

return the SAS address of the device

**Parameters**

- `struct scsi_device *sdev`: scsi device

**Description**

Returns the SAS address of the scsi device

#### <a id="c-sas_tlr_supported"></a>`sas_tlr_supported()`

```c
unsigned int sas_tlr_supported(struct scsi_device *sdev)
```

checking TLR bit in vpd 0x90

**Parameters**

- `struct scsi_device *sdev`: scsi device struct

**Description**

Check Transport Layer Retries are supported or not.
If vpd page 0x90 is present, TRL is supported.

#### <a id="c-sas_disable_tlr"></a>`sas_disable_tlr()`

```c
void sas_disable_tlr(struct scsi_device *sdev)
```

setting TLR flags

**Parameters**

- `struct scsi_device *sdev`: scsi device struct

**Description**

Seting tlr_enabled flag to 0.

#### <a id="c-sas_enable_tlr"></a>`sas_enable_tlr()`

```c
void sas_enable_tlr(struct scsi_device *sdev)
```

setting TLR flags

**Parameters**

- `struct scsi_device *sdev`: scsi device struct

**Description**

Seting tlr_enabled flag 1.

#### <a id="c-sas_ata_ncq_prio_supported"></a>`sas_ata_ncq_prio_supported()`

```c
bool sas_ata_ncq_prio_supported(struct scsi_device *sdev)
```

Check for ATA NCQ command priority support

**Parameters**

- `struct scsi_device *sdev`: SCSI device

**Description**

Check if an ATA device supports NCQ priority using VPD page 89h (ATA
Information). Since this VPD page is implemented only for ATA devices,
this function always returns false for SCSI devices.

#### <a id="c-sas_phy_alloc"></a>`sas_phy_alloc()`

```c
struct sas_phy * sas_phy_alloc(struct device *parent, int number)
```

allocates and initialize a SAS PHY structure

**Parameters**

- `struct device *parent`: Parent device
- `int number`: Phy index

**Description**

Allocates an SAS PHY structure.  It will be added in the device tree
below the device specified by **parent**, which has to be either a Scsi_Host
or sas_rphy.

**Return**

SAS PHY allocated or `NULL` if the allocation failed.

#### <a id="c-sas_phy_add"></a>`sas_phy_add()`

```c
int sas_phy_add(struct sas_phy *phy)
```

add a SAS PHY to the device hierarchy

**Parameters**

- `struct sas_phy *phy`: The PHY to be added

**Description**

Publishes a SAS PHY to the rest of the system.

#### <a id="c-sas_phy_free"></a>`sas_phy_free()`

```c
void sas_phy_free(struct sas_phy *phy)
```

free a SAS PHY

**Parameters**

- `struct sas_phy *phy`: SAS PHY to free

**Description**

Frees the specified SAS PHY.

**Note**

This function must only be called on a PHY that has not
successfully been added using [`sas_phy_add()`](#c-sas_phy_add).

#### <a id="c-sas_phy_delete"></a>`sas_phy_delete()`

```c
void sas_phy_delete(struct sas_phy *phy)
```

remove SAS PHY

**Parameters**

- `struct sas_phy *phy`: SAS PHY to remove

**Description**

Removes the specified SAS PHY.  If the SAS PHY has an
associated remote PHY it is removed before.

#### <a id="c-scsi_is_sas_phy"></a>`scsi_is_sas_phy()`

```c
int scsi_is_sas_phy(const struct device *dev)
```

check if a struct device represents a SAS PHY

**Parameters**

- `const struct device *dev`: device to check

**Return**

`1` if the device represents a SAS PHY, `0` else

#### <a id="c-sas_port_alloc"></a>`sas_port_alloc()`

```c
struct sas_port * sas_port_alloc(struct device *parent, int port_id)
```

allocate and initialize a SAS port structure

**Parameters**

- `struct device *parent`: parent device
- `int port_id`: port number

**Description**

Allocates a SAS port structure.  It will be added to the device tree
below the device specified by **parent** which must be either a Scsi_Host
or a sas_expander_device.

**Return**

`NULL` on error

#### <a id="c-sas_port_alloc_num"></a>`sas_port_alloc_num()`

```c
struct sas_port * sas_port_alloc_num(struct device *parent)
```

allocate and initialize a SAS port structure

**Parameters**

- `struct device *parent`: parent device

**Description**

Allocates a SAS port structure and a number to go with it.  This
interface is really for adapters where the port number has no
meansing, so the sas class should manage them.  It will be added to
the device tree below the device specified by **parent** which must be
either a Scsi_Host or a sas_expander_device.

**Return**

`NULL` on error

#### <a id="c-sas_port_add"></a>`sas_port_add()`

```c
int sas_port_add(struct sas_port *port)
```

add a SAS port to the device hierarchy

**Parameters**

- `struct sas_port *port`: port to be added

**Description**

publishes a port to the rest of the system

#### <a id="c-sas_port_free"></a>`sas_port_free()`

```c
void sas_port_free(struct sas_port *port)
```

free a SAS PORT

**Parameters**

- `struct sas_port *port`: SAS PORT to free

**Description**

Frees the specified SAS PORT.

**Note**

This function must only be called on a PORT that has not
successfully been added using [`sas_port_add()`](#c-sas_port_add).

#### <a id="c-sas_port_delete"></a>`sas_port_delete()`

```c
void sas_port_delete(struct sas_port *port)
```

remove SAS PORT

**Parameters**

- `struct sas_port *port`: SAS PORT to remove

**Description**

Removes the specified SAS PORT.  If the SAS PORT has an
associated phys, unlink them from the port as well.

#### <a id="c-scsi_is_sas_port"></a>`scsi_is_sas_port()`

```c
int scsi_is_sas_port(const struct device *dev)
```

check if a struct device represents a SAS port

**Parameters**

- `const struct device *dev`: device to check

**Return**

`1` if the device represents a SAS Port, `0` else

#### <a id="c-sas_port_get_phy"></a>`sas_port_get_phy()`

```c
struct sas_phy * sas_port_get_phy(struct sas_port *port)
```

try to take a reference on a port member

**Parameters**

- `struct sas_port *port`: port to check

#### <a id="c-sas_port_add_phy"></a>`sas_port_add_phy()`

```c
void sas_port_add_phy(struct sas_port *port, struct sas_phy *phy)
```

add another phy to a port to form a wide port

**Parameters**

- `struct sas_port *port`: port to add the phy to
- `struct sas_phy *phy`: phy to add

**Description**

When a port is initially created, it is empty (has no phys).  All
ports must have at least one phy to operated, and all wide ports
must have at least two.  The current code makes no difference
between ports and wide ports, but the only object that can be
connected to a remote device is a port, so ports must be formed on
all devices with phys if they're connected to anything.

#### <a id="c-sas_port_delete_phy"></a>`sas_port_delete_phy()`

```c
void sas_port_delete_phy(struct sas_port *port, struct sas_phy *phy)
```

remove a phy from a port or wide port

**Parameters**

- `struct sas_port *port`: port to remove the phy from
- `struct sas_phy *phy`: phy to remove

**Description**

This operation is used for tearing down ports again.  It must be
done to every port or wide port before calling sas_port_delete.

#### <a id="c-sas_end_device_alloc"></a>`sas_end_device_alloc()`

```c
struct sas_rphy * sas_end_device_alloc(struct sas_port *parent)
```

allocate an rphy for an end device

**Parameters**

- `struct sas_port *parent`: which port

**Description**

Allocates an SAS remote PHY structure, connected to **parent**.

**Return**

SAS PHY allocated or `NULL` if the allocation failed.

#### <a id="c-sas_expander_alloc"></a>`sas_expander_alloc()`

```c
struct sas_rphy * sas_expander_alloc(struct sas_port *parent, enum sas_device_type type)
```

allocate an rphy for an end device

**Parameters**

- `struct sas_port *parent`: which port
- `enum sas_device_type type`: SAS_EDGE_EXPANDER_DEVICE or SAS_FANOUT_EXPANDER_DEVICE

**Description**

Allocates an SAS remote PHY structure, connected to **parent**.

**Return**

SAS PHY allocated or `NULL` if the allocation failed.

#### <a id="c-sas_rphy_add"></a>`sas_rphy_add()`

```c
int sas_rphy_add(struct sas_rphy *rphy)
```

add a SAS remote PHY to the device hierarchy

**Parameters**

- `struct sas_rphy *rphy`: The remote PHY to be added

**Description**

Publishes a SAS remote PHY to the rest of the system.

#### <a id="c-sas_rphy_free"></a>`sas_rphy_free()`

```c
void sas_rphy_free(struct sas_rphy *rphy)
```

free a SAS remote PHY

**Parameters**

- `struct sas_rphy *rphy`: SAS remote PHY to free

**Description**

Frees the specified SAS remote PHY.

**Note**

This function must only be called on a remote
PHY that has not successfully been added using
[`sas_rphy_add()`](#c-sas_rphy_add) (or has been [`sas_rphy_remove()`](#c-sas_rphy_remove)'d)

#### <a id="c-sas_rphy_delete"></a>`sas_rphy_delete()`

```c
void sas_rphy_delete(struct sas_rphy *rphy)
```

remove and free SAS remote PHY

**Parameters**

- `struct sas_rphy *rphy`: SAS remote PHY to remove and free

**Description**

Removes the specified SAS remote PHY and frees it.

#### <a id="c-sas_rphy_unlink"></a>`sas_rphy_unlink()`

```c
void sas_rphy_unlink(struct sas_rphy *rphy)
```

unlink SAS remote PHY

**Parameters**

- `struct sas_rphy *rphy`: SAS remote phy to unlink from its parent port

**Description**

Removes port reference to an rphy

#### <a id="c-sas_rphy_remove"></a>`sas_rphy_remove()`

```c
void sas_rphy_remove(struct sas_rphy *rphy)
```

remove SAS remote PHY

**Parameters**

- `struct sas_rphy *rphy`: SAS remote phy to remove

**Description**

Removes the specified SAS remote PHY.

#### <a id="c-scsi_is_sas_rphy"></a>`scsi_is_sas_rphy()`

```c
int scsi_is_sas_rphy(const struct device *dev)
```

check if a struct device represents a SAS remote PHY

**Parameters**

- `const struct device *dev`: device to check

**Return**

`1` if the device represents a SAS remote PHY, `0` else

#### <a id="c-sas_attach_transport"></a>`sas_attach_transport()`

```c
struct scsi_transport_template * sas_attach_transport(struct sas_function_template *ft)
```

instantiate SAS transport template

**Parameters**

- `struct sas_function_template *ft`: SAS transport class function template

#### <a id="c-sas_release_transport"></a>`sas_release_transport()`

```c
void sas_release_transport(struct scsi_transport_template *t)
```

release SAS transport template instance

**Parameters**

- `struct scsi_transport_template *t`: transport template instance


<a id="rst-sata-transport-class"></a>

#### SATA transport class

The SATA transport is handled by libata, which has its own book of documentation in this directory.

<a id="rst-parallel-scsi-spi-transport-class"></a>

#### Parallel SCSI (SPI) transport class

The file drivers/scsi/scsi_transport_spi.c defines transport attributes for traditional (fast/wide/ultra) SCSI buses.


#### <a id="c-spi_dv_device"></a>`spi_dv_device()`

```c
void spi_dv_device(struct scsi_device *sdev)
```

Do Domain Validation on the device

**Parameters**

- `struct scsi_device *sdev`: scsi device to validate

**Description**

Performs the domain validation on the given device in the
current execution thread.  Since DV operations may sleep,
the current thread must have user context.  Also no SCSI
related locks that would deadlock I/O issued by the DV may
be held.

#### <a id="c-spi_schedule_dv_device"></a>`spi_schedule_dv_device()`

```c
void spi_schedule_dv_device(struct scsi_device *sdev)
```

schedule domain validation to occur on the device

**Parameters**

- `struct scsi_device *sdev`: The device to validate

**Description**

Identical to [`spi_dv_device()`](#c-spi_dv_device) above, except that the DV will be
scheduled to occur in a workqueue later.  All memory allocations
are atomic, so may be called from any context including those holding
SCSI locks.

#### <a id="c-spi_display_xfer_agreement"></a>`spi_display_xfer_agreement()`

```c
void spi_display_xfer_agreement(struct scsi_target *starget)
```

Print the current target transfer agreement

**Parameters**

- `struct scsi_target *starget`: The target for which to display the agreement

**Description**

Each SPI port is required to maintain a transfer agreement for each
other port on the bus.  This function prints a one-line summary of
the current agreement; more detailed information is available in sysfs.

#### <a id="c-spi_populate_tag_msg"></a>`spi_populate_tag_msg()`

```c
int spi_populate_tag_msg(unsigned char *msg, struct scsi_cmnd *cmd)
```

place a tag message in a buffer

**Parameters**

- `unsigned char *msg`: pointer to the area to place the tag
- `struct scsi_cmnd *cmd`: pointer to the scsi command for the tag

**Notes**

designed to create the correct type of tag message for the
particular request.  Returns the size of the tag message.
May return 0 if TCQ is disabled for this device.


<a id="rst-scsi-rdma-srp-transport-class"></a>

#### SCSI RDMA (SRP) transport class

The file drivers/scsi/scsi_transport_srp.c defines transport attributes for SCSI over Remote Direct Memory Access.


#### <a id="c-srp_tmo_valid"></a>`srp_tmo_valid()`

```c
int srp_tmo_valid(int reconnect_delay, int fast_io_fail_tmo, long dev_loss_tmo)
```

check timeout combination validity

**Parameters**

- `int reconnect_delay`: Reconnect delay in seconds.
- `int fast_io_fail_tmo`: Fast I/O fail timeout in seconds.
- `long dev_loss_tmo`: Device loss timeout in seconds.

**Description**

The combination of the timeout parameters must be such that SCSI commands
are finished in a reasonable time. Hence do not allow the fast I/O fail
timeout to exceed SCSI_DEVICE_BLOCK_MAX_TIMEOUT nor allow dev_loss_tmo to
exceed that limit if failing I/O fast has been disabled. Furthermore, these
parameters must be such that multipath can detect failed paths timely.
Hence do not allow all three parameters to be disabled simultaneously.

#### <a id="c-srp_start_tl_fail_timers"></a>`srp_start_tl_fail_timers()`

```c
void srp_start_tl_fail_timers(struct srp_rport *rport)
```

start the transport layer failure timers

**Parameters**

- `struct srp_rport *rport`: SRP target port.

**Description**

Start the transport layer fast I/O failure and device loss timers. Do not
modify a timer that was already started.

#### <a id="c-srp_reconnect_rport"></a>`srp_reconnect_rport()`

```c
int srp_reconnect_rport(struct srp_rport *rport)
```

reconnect to an SRP target port

**Parameters**

- `struct srp_rport *rport`: SRP target port.

**Description**

Blocks SCSI command queueing before invoking `reconnect()` such that
`queuecommand()` won't be invoked concurrently with `reconnect()` from outside
the SCSI EH. This is important since a `reconnect()` implementation may
reallocate resources needed by `queuecommand()`.

**Notes**

- This function neither waits until outstanding requests have finished nor
  tries to abort these. It is the responsibility of the `reconnect()`
  function to finish outstanding commands before reconnecting to the target
  port.
- It is the responsibility of the caller to ensure that the resources
  reallocated by the `reconnect()` function won't be used while this function
  is in progress. One possible strategy is to invoke this function from
  the context of the SCSI EH thread only. Another possible strategy is to
  lock the rport mutex inside each SCSI LLD callback that can be invoked by
  the SCSI EH (the scsi_host_template.eh_*() functions and also the
  scsi_host_template.`queuecommand()` function).

#### <a id="c-srp_timed_out"></a>`srp_timed_out()`

```c
enum scsi_timeout_action srp_timed_out(struct scsi_cmnd *scmd)
```

SRP transport intercept of the SCSI timeout EH

**Parameters**

- `struct scsi_cmnd *scmd`: SCSI command.

**Description**

If a timeout occurs while an rport is in the blocked state, ask the SCSI
EH to continue waiting (SCSI_EH_RESET_TIMER). Otherwise let the SCSI core
handle the timeout (SCSI_EH_NOT_HANDLED).

**Note**

This function is called from soft-IRQ context and with the request
queue lock held.

#### <a id="c-srp_rport_get"></a>`srp_rport_get()`

```c
void srp_rport_get(struct srp_rport *rport)
```

increment rport reference count

**Parameters**

- `struct srp_rport *rport`: SRP target port.

#### <a id="c-srp_rport_put"></a>`srp_rport_put()`

```c
void srp_rport_put(struct srp_rport *rport)
```

decrement rport reference count

**Parameters**

- `struct srp_rport *rport`: SRP target port.

#### <a id="c-srp_rport_add"></a>`srp_rport_add()`

```c
struct srp_rport * srp_rport_add(struct Scsi_Host *shost, struct srp_rport_identifiers *ids)
```

add a SRP remote port to the device hierarchy

**Parameters**

- `struct Scsi_Host *shost`: scsi host the remote port is connected to.
- `struct srp_rport_identifiers *ids`: The port id for the remote port.

**Description**

Publishes a port to the rest of the system.

#### <a id="c-srp_rport_del"></a>`srp_rport_del()`

```c
void srp_rport_del(struct srp_rport *rport)
```

remove a SRP remote port

**Parameters**

- `struct srp_rport *rport`: SRP remote port to remove

**Description**

Removes the specified SRP remote port.

#### <a id="c-srp_remove_host"></a>`srp_remove_host()`

```c
void srp_remove_host(struct Scsi_Host *shost)
```

tear down a Scsi_Host's SRP data structures

**Parameters**

- `struct Scsi_Host *shost`: Scsi Host that is torn down

**Description**

Removes all SRP remote ports for a given Scsi_Host.
Must be called just before scsi_remove_host for SRP HBAs.

#### <a id="c-srp_stop_rport_timers"></a>`srp_stop_rport_timers()`

```c
void srp_stop_rport_timers(struct srp_rport *rport)
```

stop the transport layer recovery timers

**Parameters**

- `struct srp_rport *rport`: SRP remote port for which to stop the timers.

**Description**

Must be called after [`srp_remove_host()`](#c-srp_remove_host) and [`scsi_remove_host()`](#c-scsi_remove_host). The caller
must hold a reference on the rport (rport->dev) and on the SCSI host
(rport->dev.parent).

#### <a id="c-srp_attach_transport"></a>`srp_attach_transport()`

```c
struct scsi_transport_template * srp_attach_transport(struct srp_function_template *ft)
```

instantiate SRP transport template

**Parameters**

- `struct srp_function_template *ft`: SRP transport class function template

#### <a id="c-srp_release_transport"></a>`srp_release_transport()`

```c
void srp_release_transport(struct scsi_transport_template *t)
```

release SRP transport template instance

**Parameters**

- `struct scsi_transport_template *t`: transport template instance


<a id="rst-scsi-lower-layer"></a>

## SCSI lower layer

<a id="rst-host-bus-adapter-transport-types"></a>

### Host Bus Adapter transport types

Many modern device controllers use the SCSI command set as a protocol to communicate with their devices through many different types of physical connections.

In SCSI language a bus capable of carrying SCSI commands is called a "transport", and a controller connecting to such a bus is called a "host bus adapter" (HBA).

<a id="rst-debug-transport"></a>

#### Debug transport

The file drivers/scsi/scsi_debug.c simulates a host adapter with a variable number of disks (or disk like devices) attached, sharing a common amount of RAM. Does a lot of checking to make sure that we are not getting blocks mixed up, and panics the kernel if anything out of the ordinary is seen.

To be more realistic, the simulated devices have the transport attributes of SAS disks.

For documentation see [http://sg.danny.cz/sg/scsi_debug.html](<http://sg.danny.cz/sg/scsi_debug.html>)

<a id="rst-todo"></a>

#### todo

Parallel (fast/wide/ultra) SCSI, USB, SATA, SAS, Fibre Channel, FireWire, ATAPI devices, Infiniband, Parallel ports, netlink...

---

# Linux kernel SLIMbus support

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> SLIMbus (Serial Low Power Interchip Media Bus) is a specification developed by MIPI (Mobile Industry Processor Interface) alliance. The bus uses master/slave configuration, and is a 2-wire multi-drop implementation (clock, and data).

<a id="rst-linux-kernel-slimbus-support"></a>

<a id="rst-overview"></a>

## Overview

<a id="rst-what-is-slimbus"></a>

## What is SLIMbus?

SLIMbus (Serial Low Power Interchip Media Bus) is a specification developed by MIPI (Mobile Industry Processor Interface) alliance. The bus uses master/slave configuration, and is a 2-wire multi-drop implementation (clock, and data).

Currently, SLIMbus is used to interface between application processors of SoCs (System-on-Chip) and peripheral components (typically codec). SLIMbus uses Time-Division-Multiplexing to accommodate multiple data channels, and a control channel.

The control channel is used for various control functions such as bus management, configuration and status updates. These messages can be unicast (e.g. reading/writing device specific values), or multicast (e.g. data channel reconfiguration sequence is a broadcast message announced to all devices)

A data channel is used for data-transfer between 2 SLIMbus devices. Data channel uses dedicated ports on the device.

<a id="rst-hardware-description"></a>

## Hardware description:

SLIMbus specification has different types of device classifications based on their capabilities. A manager device is responsible for enumeration, configuration, and dynamic channel allocation. Every bus has 1 active manager.

A generic device is a device providing application functionality (e.g. codec).

Framer device is responsible for clocking the bus, and transmitting frame-sync and framing information on the bus.

Each SLIMbus component has an interface device for monitoring physical layer.

Typically each SoC contains SLIMbus component having 1 manager, 1 framer device, 1 generic device (for data channel support), and 1 interface device. External peripheral SLIMbus component usually has 1 generic device (for functionality/data channel support), and an associated interface device. The generic device's registers are mapped as 'value elements' so that they can be written/read using SLIMbus control channel exchanging control/status type of information. In case there are multiple framer devices on the same bus, manager device is responsible to select the active-framer for clocking the bus.

Per specification, SLIMbus uses "clock gears" to do power management based on current frequency and bandwidth requirements. There are 10 clock gears and each gear changes the SLIMbus frequency to be twice its previous gear.

Each device has a 6-byte enumeration-address and the manager assigns every device with a 1-byte logical address after the devices report presence on the bus.

<a id="rst-software-description"></a>

## Software description:

There are 2 types of SLIMbus drivers:

slim_controller represents a 'controller' for SLIMbus. This driver should implement duties needed by the SoC (manager device, associated interface device for monitoring the layers and reporting errors, default framer device).

slim_device represents the 'generic device/component' for SLIMbus, and a slim_driver should implement driver for that slim_device.

<a id="rst-device-notifications-to-the-driver"></a>

## Device notifications to the driver:

Since SLIMbus devices have mechanisms for reporting their presence, the framework allows drivers to bind when corresponding devices report their presence on the bus. However, it is possible that the driver needs to be probed first so that it can enable corresponding SLIMbus device (e.g. power it up and/or take it out of reset). To support that behavior, the framework allows drivers to probe first as well  (e.g. using standard DeviceTree compatibility field). This creates the necessity for the driver to know when the device is functional (i.e. reported present). device_up callback is used for that reason when the device reports present and is assigned a logical address by the controller.

Similarly, SLIMbus devices 'report absent' when they go down. A 'device_down' callback notifies the driver when the device reports absent and its logical address assignment is invalidated by the controller.

Another notification "boot_device" is used to notify the slim_driver when controller resets the bus. This notification allows the driver to take necessary steps to boot the device so that it's functional after the bus has been reset.

<a id="rst-driver-and-controller-apis"></a>

## Driver and Controller APIs:


#### <a id="c-struct-slim_eaddr"></a>`struct slim_eaddr`

Enumeration address for a SLIMbus device

**Definition**

```c
struct slim_eaddr {
    u8 instance;
    u8 dev_index;
    u16 prod_code;
    u16 manf_id;
};
```

**Members**

- `instance`: Instance value
- `dev_index`: Device index
- `prod_code`: Product code
- `manf_id`: Manufacturer Id for the device

#### <a id="c-enum-slim_device_status"></a>`enum slim_device_status`

slim device status

**Constants**

- `SLIM_DEVICE_STATUS_DOWN`: Slim device is absent or not reported yet.
- `SLIM_DEVICE_STATUS_UP`: Slim device is announced on the bus.
- `SLIM_DEVICE_STATUS_RESERVED`: Reserved for future use.

#### <a id="c-struct-slim_device"></a>`struct slim_device`

Slim device handle.

**Definition**

```c
struct slim_device {
    struct device           dev;
    struct slim_eaddr       e_addr;
    struct slim_controller  *ctrl;
    enum slim_device_status status;
    u8 laddr;
    bool is_laddr_valid;
    struct list_head        stream_list;
    spinlock_t stream_list_lock;
};
```

**Members**

- `dev`: Driver model representation of the device.
- `e_addr`: Enumeration address of this device.
- `ctrl`: slim controller instance.
- `status`: slim device status
- `laddr`: 1-byte Logical address of this device.
- `is_laddr_valid`: indicates if the laddr is valid or not
- `stream_list`: List of streams on this device
- `stream_list_lock`: lock to protect the stream list

**Description**

This is the client/device handle returned when a SLIMbus
device is registered with a controller.
Pointer to this structure is used by client-driver as a handle.

#### <a id="c-struct-slim_driver"></a>`struct slim_driver`

SLIMbus 'generic device' (slave) device driver (similar to 'spi_device' on SPI)

**Definition**

```c
struct slim_driver {
    int (*probe)(struct slim_device *sl);
    void (*remove)(struct slim_device *sl);
    void (*shutdown)(struct slim_device *sl);
    int (*device_status)(struct slim_device *sl, enum slim_device_status s);
    struct device_driver            driver;
    const struct slim_device_id     *id_table;
};
```

**Members**

- `probe`: Binds this driver to a SLIMbus device.
- `remove`: Unbinds this driver from the SLIMbus device.
- `shutdown`: Standard shutdown callback used during powerdown/halt.
- `device_status`: This callback is called when
  - The device reports present and gets a laddr assigned
  - The device reports absent, or the bus goes down.
- `driver`: SLIMbus device drivers should initialize name and owner field of
  this structure
- `id_table`: List of SLIMbus devices supported by this driver

#### <a id="c-struct-slim_val_inf"></a>`struct slim_val_inf`

Slimbus value or information element

**Definition**

```c
struct slim_val_inf {
    u16 start_offset;
    u8 num_bytes;
    u8 *rbuf;
    const u8                *wbuf;
    struct completion      *comp;
};
```

**Members**

- `start_offset`: Specifies starting offset in information/value element map
- `num_bytes`: upto 16. This ensures that the message will fit the slicesize
  per SLIMbus spec
- `rbuf`: buffer to read the values
- `wbuf`: buffer to write
- `comp`: completion for asynchronous operations, valid only if TID is
  required for transaction, like REQUEST operations.
  Rest of the transactions are synchronous anyway.

#### <a id="c-struct-slim_stream_config"></a>`struct slim_stream_config`

SLIMbus stream configuration Configuring a stream is done at hw_params or prepare call from audio drivers where they have all the required information regarding rate, number of channels and so on. There is a 1:1 mapping of channel and ports.

**Definition**

```c
struct slim_stream_config {
    unsigned int rate;
    unsigned int bps;
    unsigned int ch_count;
    unsigned int *chs;
    unsigned long port_mask;
    int direction;
};
```

**Members**

- `rate`: data rate
- `bps`: bits per data sample
- `ch_count`: number of channels
- `chs`: pointer to list of channel numbers
- `port_mask`: port mask of ports to use for this stream
- `direction`: direction of the stream, SNDRV_PCM_STREAM_PLAYBACK
  or SNDRV_PCM_STREAM_CAPTURE.

#### <a id="c-module_slim_driver"></a>`module_slim_driver()`

```c
module_slim_driver(__slim_driver)
```

Helper macro for registering a SLIMbus driver

**Parameters**

- `__slim_driver`: slimbus_driver struct

**Description**

Helper macro for SLIMbus drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)



#### <a id="c-struct-slim_framer"></a>`struct slim_framer`

Represents SLIMbus framer. Every controller may have multiple framers. There is 1 active framer device responsible for clocking the bus. Manager is responsible for framer hand-over.

**Definition**

```c
struct slim_framer {
    struct device           dev;
    struct slim_eaddr       e_addr;
    int rootfreq;
    int superfreq;
};
```

**Members**

- `dev`: Driver model representation of the device.
- `e_addr`: Enumeration address of the framer.
- `rootfreq`: Root Frequency at which the framer can run. This is maximum
  frequency ('clock gear 10') at which the bus can operate.
- `superfreq`: Superframes per root frequency. Every frame is 6144 bits.

#### <a id="c-struct-slim_msg_txn"></a>`struct slim_msg_txn`

Message to be sent by the controller. This structure has packet header, payload and buffer to be filled (if any)

**Definition**

```c
struct slim_msg_txn {
    u8 rl;
    u8 mt;
    u8 mc;
    u8 dt;
    u16 ec;
    u8 tid;
    u8 la;
    struct slim_val_inf     *msg;
    struct completion      *comp;
};
```

**Members**

- `rl`: Header field. remaining length.
- `mt`: Header field. Message type.
- `mc`: Header field. LSB is message code for type mt.
- `dt`: Header field. Destination type.
- `ec`: Element code. Used for elemental access APIs.
- `tid`: Transaction ID. Used for messages expecting response.
  (relevant for message-codes involving read operation)
- `la`: Logical address of the device this message is going to.
  (Not used when destination type is broadcast.)
- `msg`: Elemental access message to be read/written
- `comp`: completion if read/write is synchronous, used internally
  for tid based transactions.

#### <a id="c-enum-slim_clk_state"></a>`enum slim_clk_state`

SLIMbus controller's clock state used internally for maintaining current clock state.

**Constants**

- `SLIM_CLK_ACTIVE`: SLIMbus clock is active
- `SLIM_CLK_ENTERING_PAUSE`: SLIMbus clock pause sequence is being sent on the
  bus. If this succeeds, state changes to SLIM_CLK_PAUSED. If the
  transition fails, state changes back to SLIM_CLK_ACTIVE
- `SLIM_CLK_PAUSED`: SLIMbus controller clock has paused.

#### <a id="c-struct-slim_sched"></a>`struct slim_sched`

Framework uses this structure internally for scheduling.

**Definition**

```c
struct slim_sched {
    enum slim_clk_state     clk_state;
    struct completion       pause_comp;
    struct mutex            m_reconf;
};
```

**Members**

- `clk_state`: Controller's clock state from enum slim_clk_state
- `pause_comp`: Signals completion of clock pause sequence. This is useful when
  client tries to call SLIMbus transaction when controller is entering
  clock pause.
- `m_reconf`: This mutex is held until current reconfiguration (data channel
  scheduling, message bandwidth reservation) is done. Message APIs can
  use the bus concurrently when this mutex is held since elemental access
  messages can be sent on the bus when reconfiguration is in progress.

#### <a id="c-enum-slim_port_direction"></a>`enum slim_port_direction`

SLIMbus port direction

**Constants**

- `SLIM_PORT_SINK`: SLIMbus port is a sink
- `SLIM_PORT_SOURCE`: SLIMbus port is a source

#### <a id="c-enum-slim_port_state"></a>`enum slim_port_state`

SLIMbus Port/Endpoint state machine according to SLIMbus Spec 2.0

**Constants**

- `SLIM_PORT_DISCONNECTED`: SLIMbus port is disconnected
  entered from Unconfigure/configured state after
  DISCONNECT_PORT or REMOVE_CHANNEL core command
- `SLIM_PORT_UNCONFIGURED`: SLIMbus port is in unconfigured state.
  entered from disconnect state after CONNECT_SOURCE/SINK core command
- `SLIM_PORT_CONFIGURED`: SLIMbus port is in configured state.
  entered from unconfigured state after DEFINE_CHANNEL, DEFINE_CONTENT
  and ACTIVATE_CHANNEL core commands. Ready for data transmission.

#### <a id="c-enum-slim_channel_state"></a>`enum slim_channel_state`

SLIMbus channel state machine used by core.

**Constants**

- `SLIM_CH_STATE_DISCONNECTED`: SLIMbus channel is disconnected
- `SLIM_CH_STATE_ALLOCATED`: SLIMbus channel is allocated
- `SLIM_CH_STATE_ASSOCIATED`: SLIMbus channel is associated with port
- `SLIM_CH_STATE_DEFINED`: SLIMbus channel parameters are defined
- `SLIM_CH_STATE_CONTENT_DEFINED`: SLIMbus channel content is defined
- `SLIM_CH_STATE_ACTIVE`: SLIMbus channel is active and ready for data
- `SLIM_CH_STATE_REMOVED`: SLIMbus channel is inactive and removed

#### <a id="c-enum-slim_ch_data_fmt"></a>`enum slim_ch_data_fmt`

SLIMbus channel data Type identifiers according to Table 60 of SLIMbus Spec 1.01.01

**Constants**

- `SLIM_CH_DATA_FMT_NOT_DEFINED`: Undefined
- `SLIM_CH_DATA_FMT_LPCM_AUDIO`: LPCM audio
- `SLIM_CH_DATA_FMT_IEC61937_COMP_AUDIO`: IEC61937 Compressed audio
- `SLIM_CH_DATA_FMT_PACKED_PDM_AUDIO`: Packed PDM audio

#### <a id="c-enum-slim_ch_aux_bit_fmt"></a>`enum slim_ch_aux_bit_fmt`

SLIMbus channel Aux Field format IDs according to Table 63 of SLIMbus Spec 2.0

**Constants**

- `SLIM_CH_AUX_FMT_NOT_APPLICABLE`: Undefined
- `SLIM_CH_AUX_FMT_ZCUV_TUNNEL_IEC60958`: ZCUV for tunneling IEC60958
- `SLIM_CH_AUX_FMT_USER_DEFINED`: User defined

#### <a id="c-struct-slim_channel"></a>`struct slim_channel`

SLIMbus channel, used for state machine

**Definition**

```c
struct slim_channel {
    int id;
    int prrate;
    int seg_dist;
    enum slim_ch_data_fmt data_fmt;
    enum slim_ch_aux_bit_fmt aux_fmt;
    enum slim_channel_state state;
};
```

**Members**

- `id`: ID of channel
- `prrate`: Presense rate of channel from Table 66 of SLIMbus 2.0 Specs
- `seg_dist`: segment distribution code from Table 20 of SLIMbus 2.0 Specs
- `data_fmt`: Data format of channel.
- `aux_fmt`: Aux format for this channel.
- `state`: channel state machine

#### <a id="c-struct-slim_port"></a>`struct slim_port`

SLIMbus port

**Definition**

```c
struct slim_port {
    int id;
    enum slim_port_direction direction;
    enum slim_port_state state;
    struct slim_channel ch;
};
```

**Members**

- `id`: Port id
- `direction`: Port direction, Source or Sink.
- `state`: state machine of port.
- `ch`: channel associated with this port.

#### <a id="c-enum-slim_transport_protocol"></a>`enum slim_transport_protocol`

SLIMbus Transport protocol list from Table 47 of SLIMbus 2.0 specs.

**Constants**

- `SLIM_PROTO_ISO`: Isochronous Protocol, no flow control as data rate match
  channel rate flow control embedded in the data.
- `SLIM_PROTO_PUSH`: Pushed Protocol, includes flow control, Used to carry
  data whose rate is equal to, or lower than the channel rate.
- `SLIM_PROTO_PULL`: Pulled Protocol, similar usage as pushed protocol
  but pull is a unicast.
- `SLIM_PROTO_LOCKED`: Locked Protocol
- `SLIM_PROTO_ASYNC_SMPLX`: Asynchronous Protocol-Simplex
- `SLIM_PROTO_ASYNC_HALF_DUP`: Asynchronous Protocol-Half-duplex
- `SLIM_PROTO_EXT_SMPLX`: Extended Asynchronous Protocol-Simplex
- `SLIM_PROTO_EXT_HALF_DUP`: Extended Asynchronous Protocol-Half-duplex

#### <a id="c-struct-slim_stream_runtime"></a>`struct slim_stream_runtime`

SLIMbus stream runtime instance

**Definition**

```c
struct slim_stream_runtime {
    const char *name;
    struct slim_device *dev;
    int direction;
    enum slim_transport_protocol prot;
    unsigned int rate;
    unsigned int bps;
    unsigned int ratem;
    int num_ports;
    struct slim_port *ports;
    struct list_head node;
};
```

**Members**

- `name`: Name of the stream
- `dev`: SLIM Device instance associated with this stream
- `direction`: direction of stream
- `prot`: Transport protocol used in this stream
- `rate`: Data rate of samples *
- `bps`: bits per sample
- `ratem`: rate multipler which is super frame rate/data rate
- `num_ports`: number of ports
- `ports`: pointer to instance of ports
- `node`: list head for stream associated with slim device.

#### <a id="c-struct-slim_controller"></a>`struct slim_controller`

Controls every instance of SLIMbus (similar to 'master' on SPI)

**Definition**

```c
struct slim_controller {
    struct device           *dev;
    unsigned int            id;
    char name[SLIMBUS_NAME_SIZE];
    int min_cg;
    int max_cg;
    int clkgear;
    struct ida              laddr_ida;
    struct slim_framer      *a_framer;
    struct mutex            lock;
    struct list_head        devices;
    struct idr              tid_idr;
    spinlock_t txn_lock;
    struct slim_sched       sched;
    int (*xfer_msg)(struct slim_controller *ctrl, struct slim_msg_txn *tx);
    int (*set_laddr)(struct slim_controller *ctrl, struct slim_eaddr *ea, u8 laddr);
    int (*get_laddr)(struct slim_controller *ctrl, struct slim_eaddr *ea, u8 *laddr);
    int (*enable_stream)(struct slim_stream_runtime *rt);
    int (*disable_stream)(struct slim_stream_runtime *rt);
    int (*wakeup)(struct slim_controller *ctrl);
};
```

**Members**

- `dev`: Device interface to this driver
- `id`: Board-specific number identifier for this controller/bus
- `name`: Name for this controller
- `min_cg`: Minimum clock gear supported by this controller (default value: 1)
- `max_cg`: Maximum clock gear supported by this controller (default value: 10)
- `clkgear`: Current clock gear in which this bus is running
- `laddr_ida`: logical address id allocator
- `a_framer`: Active framer which is clocking the bus managed by this controller
- `lock`: Mutex protecting controller data structures
- `devices`: Slim device list
- `tid_idr`: tid id allocator
- `txn_lock`: Lock to protect table of transactions
- `sched`: scheduler structure used by the controller
- `xfer_msg`: Transfer a message on this controller (this can be a broadcast
  control/status message like data channel setup, or a unicast message
  like value element read/write.
- `set_laddr`: Setup logical address at laddr for the slave with elemental
  address e_addr. Drivers implementing controller will be expected to
  send unicast message to this device with its logical address.
- `get_laddr`: It is possible that controller needs to set fixed logical
  address table and get_laddr can be used in that case so that controller
  can do this assignment. Use case is when the master is on the remote
  processor side, who is resposible for allocating laddr.
- `enable_stream`: This function pointer implements controller-specific procedure
  to enable a stream.
- `disable_stream`: This function pointer implements controller-specific procedure
  to disable stream.
- `wakeup`: This function pointer implements controller-specific procedure
  to wake it up from clock-pause. Framework will call this to bring
  the controller out of clock pause.

**Description**

'Manager device' is responsible for  device management, bandwidth
allocation, channel setup, and port associations per channel.
Device management means Logical address assignment/removal based on
enumeration (report-present, report-absent) of a device.
Bandwidth allocation is done dynamically by the manager based on active
channels on the bus, message-bandwidth requests made by SLIMbus devices.
Based on current bandwidth usage, manager chooses a frequency to run
the bus at (in steps of 'clock-gear', 1 through 10, each clock gear
representing twice the frequency than the previous gear).
Manager is also responsible for entering (and exiting) low-power-mode
(known as 'clock pause').
Manager can do handover of framer if there are multiple framers on the
bus and a certain usecase warrants using certain framer to avoid keeping
previous framer being powered-on.

Controller here performs duties of the manager device, and 'interface
device'. Interface device is responsible for monitoring the bus and
reporting information such as loss-of-synchronization, data
slot-collision.



#### <a id="c-slim_unregister_controller"></a>`slim_unregister_controller()`

```c
int slim_unregister_controller(struct slim_controller *ctrl)
```

Controller tear-down.

**Parameters**

- `struct slim_controller *ctrl`: Controller to tear-down.

#### <a id="c-slim_report_absent"></a>`slim_report_absent()`

```c
void slim_report_absent(struct slim_device *sbdev)
```

Controller calls this function when a device reports absent, OR when the device cannot be communicated with

**Parameters**

- `struct slim_device *sbdev`: Device that cannot be reached, or sent report absent

#### <a id="c-slim_get_device"></a>`slim_get_device()`

```c
struct slim_device * slim_get_device(struct slim_controller *ctrl, struct slim_eaddr *e_addr)
```

get handle to a device.

**Parameters**

- `struct slim_controller *ctrl`: Controller on which this device will be added/queried
- `struct slim_eaddr *e_addr`: Enumeration address of the device to be queried

**Description**

Takes a reference to the embedded struct device which needs to be dropped
after use.

**Return**

pointer to a device if it has already reported. Creates a new
device and returns pointer to it if the device has not yet enumerated.

#### <a id="c-of_slim_get_device"></a>`of_slim_get_device()`

```c
struct slim_device * of_slim_get_device(struct slim_controller *ctrl, struct device_node *np)
```

get handle to a device using dt node.

**Parameters**

- `struct slim_controller *ctrl`: Controller on which this device will be queried
- `struct device_node *np`: node pointer to device

**Description**

Takes a reference to the embedded struct device which needs to be dropped
after use.

**Return**

pointer to a device if it has been registered, otherwise NULL.

#### <a id="c-slim_device_report_present"></a>`slim_device_report_present()`

```c
int slim_device_report_present(struct slim_controller *ctrl, struct slim_eaddr *e_addr, u8 *laddr)
```

Report enumerated device.

**Parameters**

- `struct slim_controller *ctrl`: Controller with which device is enumerated.
- `struct slim_eaddr *e_addr`: Enumeration address of the device.
- `u8 *laddr`: Return logical address (if valid flag is false)

**Description**

Called by controller in response to REPORT_PRESENT. Framework will assign
a logical address to this enumeration address.
Function returns -EXFULL to indicate that all logical addresses are already
taken.

#### <a id="c-slim_get_logical_addr"></a>`slim_get_logical_addr()`

```c
int slim_get_logical_addr(struct slim_device *sbdev)
```

get/allocate logical address of a SLIMbus device.

**Parameters**

- `struct slim_device *sbdev`: client handle requesting the address.

**Return**

zero if a logical address is valid or a new logical address
has been assigned. error code in case of error.


<a id="rst-clock-pause"></a>

## Clock-pause:

SLIMbus mandates that a reconfiguration sequence (known as clock-pause) be broadcast to all active devices on the bus before the bus can enter low-power mode. Controller uses this sequence when it decides to enter low-power mode so that corresponding clocks and/or power-rails can be turned off to save power. Clock-pause is exited by waking up framer device (if controller driver initiates exiting low power mode), or by toggling the data line (if a slave device wants to initiate it).

<a id="rst-clock-pause-apis"></a>

### Clock-pause APIs:


#### <a id="c-slim_ctrl_clk_pause"></a>`slim_ctrl_clk_pause()`

```c
int slim_ctrl_clk_pause(struct slim_controller *ctrl, bool wakeup, u8 restart)
```

Called by slimbus controller to enter/exit 'clock pause'

**Parameters**

- `struct slim_controller *ctrl`: controller requesting bus to be paused or woken up
- `bool wakeup`: Wakeup this controller from clock pause.
- `u8 restart`: Restart time value per spec used for clock pause. This value
  isn't used when controller is to be woken up.

**Description**

Slimbus specification needs this sequence to turn-off clocks for the bus.
The sequence involves sending 3 broadcast messages (reconfiguration
sequence) to inform all devices on the bus.
To exit clock-pause, controller typically wakes up active framer device.
This API executes clock pause reconfiguration sequence if wakeup is false.
If wakeup is true, controller's wakeup is called.
For entering clock-pause, -EBUSY is returned if a message txn in pending.


<a id="rst-messaging"></a>

## Messaging:

The framework supports regmap and read/write apis to exchange control-information with a SLIMbus device. APIs can be synchronous or asynchronous. The header file &lt;linux/slimbus.h&gt; has more documentation about messaging APIs.

<a id="rst-messaging-apis"></a>

### Messaging APIs:


#### <a id="c-slim_msg_response"></a>`slim_msg_response()`

```c
void slim_msg_response(struct slim_controller *ctrl, u8 *reply, u8 tid, u8 len)
```

Deliver Message response received from a device to the framework.

**Parameters**

- `struct slim_controller *ctrl`: Controller handle
- `u8 *reply`: Reply received from the device
- `u8 tid`: Transaction ID received with which framework can associate reply.
- `u8 len`: Length of the reply

**Description**

Called by controller to inform framework about the response received.
This helps in making the API asynchronous, and controller-driver doesn't need
to manage 1 more table other than the one managed by framework mapping TID
with buffers

#### <a id="c-slim_alloc_txn_tid"></a>`slim_alloc_txn_tid()`

```c
int slim_alloc_txn_tid(struct slim_controller *ctrl, struct slim_msg_txn *txn)
```

Allocate a tid to txn

**Parameters**

- `struct slim_controller *ctrl`: Controller handle
- `struct slim_msg_txn *txn`: transaction to be allocated with tid.

**Return**

zero on success with valid txn->tid and error code on failures.

#### <a id="c-slim_free_txn_tid"></a>`slim_free_txn_tid()`

```c
void slim_free_txn_tid(struct slim_controller *ctrl, struct slim_msg_txn *txn)
```

Free tid of txn

**Parameters**

- `struct slim_controller *ctrl`: Controller handle
- `struct slim_msg_txn *txn`: transaction whose tid should be freed

#### <a id="c-slim_do_transfer"></a>`slim_do_transfer()`

```c
int slim_do_transfer(struct slim_controller *ctrl, struct slim_msg_txn *txn)
```

Process a SLIMbus-messaging transaction

**Parameters**

- `struct slim_controller *ctrl`: Controller handle
- `struct slim_msg_txn *txn`: Transaction to be sent over SLIMbus

**Description**

Called by controller to transmit messaging transactions not dealing with
Interface/Value elements. (e.g. transmitting a message to assign logical
address to a slave device

**Return**

-ETIMEDOUT: If transmission of this message timed out
(e.g. due to bus lines not being clocked or driven by controller)

#### <a id="c-slim_xfer_msg"></a>`slim_xfer_msg()`

```c
int slim_xfer_msg(struct slim_device *sbdev, struct slim_val_inf *msg, u8 mc)
```

Transfer a value info message on slim device

**Parameters**

- `struct slim_device *sbdev`: slim device to which this msg has to be transferred
- `struct slim_val_inf *msg`: value info message pointer
- `u8 mc`: message code of the message

**Description**

Called by drivers which want to transfer a vlaue or info elements.

**Return**

-ETIMEDOUT: If transmission of this message timed out

#### <a id="c-slim_read"></a>`slim_read()`

```c
int slim_read(struct slim_device *sdev, u32 addr, size_t count, u8 *val)
```

Read SLIMbus value element

**Parameters**

- `struct slim_device *sdev`: client handle.
- `u32 addr`: address of value element to read.
- `size_t count`: number of bytes to read. Maximum bytes allowed are 16.
- `u8 *val`: will return what the value element value was

**Return**

-EINVAL for Invalid parameters, -ETIMEDOUT If transmission of
this message timed out (e.g. due to bus lines not being clocked
or driven by controller)

#### <a id="c-slim_readb"></a>`slim_readb()`

```c
int slim_readb(struct slim_device *sdev, u32 addr)
```

Read byte from SLIMbus value element

**Parameters**

- `struct slim_device *sdev`: client handle.
- `u32 addr`: address in the value element to read.

**Return**

byte value of value element.

#### <a id="c-slim_write"></a>`slim_write()`

```c
int slim_write(struct slim_device *sdev, u32 addr, size_t count, u8 *val)
```

Write SLIMbus value element

**Parameters**

- `struct slim_device *sdev`: client handle.
- `u32 addr`: address in the value element to write.
- `size_t count`: number of bytes to write. Maximum bytes allowed are 16.
- `u8 *val`: value to write to value element

**Return**

-EINVAL for Invalid parameters, -ETIMEDOUT If transmission of
this message timed out (e.g. due to bus lines not being clocked
or driven by controller)

#### <a id="c-slim_writeb"></a>`slim_writeb()`

```c
int slim_writeb(struct slim_device *sdev, u32 addr, u8 value)
```

Write byte to SLIMbus value element

**Parameters**

- `struct slim_device *sdev`: client handle.
- `u32 addr`: address of value element to write.
- `u8 value`: value to write to value element

**Return**

-EINVAL for Invalid parameters, -ETIMEDOUT If transmission of
this message timed out (e.g. due to bus lines not being clocked
or driven by controller)


<a id="rst-streaming-apis"></a>

### Streaming APIs:


#### <a id="c-slim_stream_allocate"></a>`slim_stream_allocate()`

```c
struct slim_stream_runtime * slim_stream_allocate(struct slim_device *dev, const char *name)
```

Allocate a new SLIMbus Stream

**Parameters**

- `struct slim_device *dev`: Slim device to be associated with
- `const char *name`: name of the stream

**Description**

This is very first call for SLIMbus streaming, this API will allocate
a new SLIMbus stream and return a valid stream runtime pointer for client
to use it in subsequent stream apis. state of stream is set to ALLOCATED

**Return**

valid pointer on success and error code on failure.
From ASoC DPCM framework, this state is linked to `startup()` operation.

#### <a id="c-slim_stream_prepare"></a>`slim_stream_prepare()`

```c
int slim_stream_prepare(struct slim_stream_runtime *rt, struct slim_stream_config *cfg)
```

Prepare a SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *rt`: instance of slim stream runtime to configure
- `struct slim_stream_config *cfg`: new configuration for the stream

**Description**

This API will configure SLIMbus stream with config parameters from cfg.
return zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `hw_params()` operation.

#### <a id="c-slim_stream_enable"></a>`slim_stream_enable()`

```c
int slim_stream_enable(struct slim_stream_runtime *stream)
```

Enable a prepared SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *stream`: instance of slim stream runtime to enable

**Description**

This API will enable all the ports and channels associated with
SLIMbus stream

**Return**

zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `trigger()` start operation.

#### <a id="c-slim_stream_disable"></a>`slim_stream_disable()`

```c
int slim_stream_disable(struct slim_stream_runtime *stream)
```

Disable a SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *stream`: instance of slim stream runtime to disable

**Description**

This API will disable all the ports and channels associated with
SLIMbus stream

**Return**

zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `trigger()` pause operation.

#### <a id="c-slim_stream_unprepare"></a>`slim_stream_unprepare()`

```c
int slim_stream_unprepare(struct slim_stream_runtime *stream)
```

Un-prepare a SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *stream`: instance of slim stream runtime to unprepare

**Description**

This API will un allocate all the ports and channels associated with
SLIMbus stream

**Return**

zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `trigger()` stop operation.

#### <a id="c-slim_stream_free"></a>`slim_stream_free()`

```c
int slim_stream_free(struct slim_stream_runtime *stream)
```

Free a SLIMbus Stream

**Parameters**

- `struct slim_stream_runtime *stream`: instance of slim stream runtime to free

**Description**

This API will un allocate all the memory associated with
slim stream runtime, user is not allowed to make an dereference
to stream after this call.

**Return**

zero on success and error code on failure. From ASoC DPCM framework,
this state is linked to `shutdown()` operation.

---

# Serial Peripheral Interface (SPI)

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> SPI is the "Serial Peripheral Interface", widely used with embedded systems because it is a simple and efficient interface: basically a multiplexed shift register. Its three signal wires hold a clock (SCK, often in the range of 1-20 MHz),…

<a id="rst-serial-peripheral-interface-spi"></a>

SPI is the "Serial Peripheral Interface", widely used with embedded systems because it is a simple and efficient interface: basically a multiplexed shift register. Its three signal wires hold a clock (SCK, often in the range of 1-20 MHz), a "Master Out, Slave In" (MOSI) data line, and a "Master In, Slave Out" (MISO) data line. SPI is a full duplex protocol; for each bit shifted out the MOSI line (one per clock) another is shifted in on the MISO line. Those bits are assembled into words of various sizes on the way to and from system memory. An additional chipselect line is usually active-low (nCS); four signals are normally used for each peripheral, plus sometimes an interrupt.

The SPI bus facilities listed here provide a generalized interface to declare SPI buses and devices, manage them according to the standard Linux driver model, and perform input/output operations. At this time, only "master" side interfaces are supported, where Linux talks to SPI peripherals and does not implement such a peripheral itself. (Interfaces to support implementing SPI slaves would necessarily look different.)

The programming interface is structured around two kinds of driver, and two kinds of device. A "Controller Driver" abstracts the controller hardware, which may be as simple as a set of GPIO pins or as complex as a pair of FIFOs connected to dual DMA engines on the other side of the SPI shift register (maximizing throughput). Such drivers bridge between whatever bus they sit on (often the platform bus) and SPI, and expose the SPI side of their device as a `struct spi_controller <spi_controller>`. SPI devices are children of that master, represented as a `struct spi_device <spi_device>` and manufactured from `struct spi_board_info <spi_board_info>` descriptors which are usually provided by board-specific initialization code. A `struct spi_driver <spi_driver>` is called a "Protocol Driver", and is bound to a spi_device using normal driver model calls.

The I/O model is a set of queued messages. Protocol drivers submit one or more `struct spi_message <spi_message>` objects, which are processed and completed asynchronously. (There are synchronous wrappers, however.) Messages are built from one or more `struct spi_transfer <spi_transfer>` objects, each of which wraps a full duplex SPI transfer. A variety of protocol tweaking options are needed, because different chips adopt very different policies for how they use the bits transferred with SPI.


#### <a id="c-struct-spi_statistics"></a>`struct spi_statistics`

statistics for spi transfers

**Definition**

```c
struct spi_statistics {
        struct u64_stats_sync   syncp;
        u64_stats_t messages;
        u64_stats_t transfers;
        u64_stats_t errors;
        u64_stats_t timedout;
        u64_stats_t spi_sync;
        u64_stats_t spi_sync_immediate;
        u64_stats_t spi_async;
        u64_stats_t bytes;
        u64_stats_t bytes_rx;
        u64_stats_t bytes_tx;
    #define SPI_STATISTICS_HISTO_SIZE 17;
        u64_stats_t transfer_bytes_histo[SPI_STATISTICS_HISTO_SIZE];
        u64_stats_t transfers_split_maxsize;
};
```

**Members**

- `syncp`: seqcount to protect members in this struct for per-cpu update
  on 32-bit systems
- `messages`: number of spi-messages handled
- `transfers`: number of spi_transfers handled
- `errors`: number of errors during spi_transfer
- `timedout`: number of timeouts during spi_transfer
- `spi_sync`: number of times spi_sync is used
- `spi_sync_immediate`: number of times spi_sync is executed immediately
  in calling context without queuing and scheduling
- `spi_async`: number of times spi_async is used
- `bytes`: number of bytes transferred to/from device
- `bytes_rx`: number of bytes received from device
- `bytes_tx`: number of bytes sent to device
- `transfer_bytes_histo`: transfer bytes histogram
- `transfers_split_maxsize`: number of transfers that have been split because of
  maxsize limit

#### <a id="c-struct-spi_delay"></a>`struct spi_delay`

SPI delay information

**Definition**

```c
struct spi_delay {
    #define SPI_DELAY_UNIT_USECS    0;
    #define SPI_DELAY_UNIT_NSECS    1;
    #define SPI_DELAY_UNIT_SCK      2;
        u16 value;
        u8 unit;
};
```

**Members**

- `value`: Value for the delay
- `unit`: Unit for the delay

#### <a id="c-struct-spi_device"></a>`struct spi_device`

Controller side proxy for an SPI target device

**Definition**

```c
struct spi_device {
        struct device           dev;
        struct spi_controller   *controller;
        u32 max_speed_hz;
        u8 bits_per_word;
        bool rt;
    #define SPI_NO_TX               BIT(31);
    #define SPI_NO_RX               BIT(30);
    #define SPI_TPM_HW_FLOW         BIT(29);
    #define SPI_MODE_KERNEL_MASK    (~(BIT(29) - 1));
        u32 mode;
        int irq;
        void *controller_state;
        void *controller_data;
        char modalias[SPI_NAME_SIZE];
        struct spi_statistics __percpu  *pcpu_statistics;
        struct spi_delay        word_delay;
        struct spi_delay        cs_setup;
        struct spi_delay        cs_hold;
        struct spi_delay        cs_inactive;
        u8 chip_select[SPI_DEVICE_CS_CNT_MAX];
        u8 num_chipselect;
        u32 cs_index_mask : SPI_DEVICE_CS_CNT_MAX;
        struct gpio_desc        *cs_gpiod[SPI_DEVICE_CS_CNT_MAX];
        u8 tx_lane_map[SPI_DEVICE_DATA_LANE_CNT_MAX];
        u8 num_tx_lanes;
        u8 rx_lane_map[SPI_DEVICE_DATA_LANE_CNT_MAX];
        u8 num_rx_lanes;
};
```

**Members**

- `dev`: Driver model representation of the device.
- `controller`: SPI controller used with the device.
- `max_speed_hz`: Maximum clock rate to be used with this chip
  (on this board); may be changed by the device's driver.
  The spi_transfer.speed_hz can override this for each transfer.
- `bits_per_word`: Data transfers involve one or more words; word sizes
  like eight or 12 bits are common.  In-memory wordsizes are
  powers of two bytes (e.g. 20 bit samples use 32 bits).
  This may be changed by the device's driver, or left at the
  default (0) indicating protocol words are eight bit bytes.
  The spi_transfer.bits_per_word can override this for each transfer.
- `rt`: Make the pump thread real time priority.
- `mode`: The spi mode defines how data is clocked out and in.
  This may be changed by the device's driver.
  The "active low" default for chipselect mode can be overridden
  (by specifying SPI_CS_HIGH) as can the "MSB first" default for
  each word in a transfer (by specifying SPI_LSB_FIRST).
- `irq`: Negative, or the number passed to [`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq) to receive
  interrupts from this device.
- `controller_state`: Controller's runtime state
- `controller_data`: Board-specific definitions for controller, such as
  FIFO initialization parameters; from board_info.controller_data
- `modalias`: Name of the driver to use with this device, or an alias
  for that name.  This appears in the sysfs "modalias" attribute
  for driver coldplugging, and in uevents used for hotplugging
- `pcpu_statistics`: statistics for the spi_device
- `word_delay`: delay to be inserted between consecutive
  words of a transfer
- `cs_setup`: delay to be introduced by the controller after CS is asserted
- `cs_hold`: delay to be introduced by the controller before CS is deasserted
- `cs_inactive`: delay to be introduced by the controller after CS is
  deasserted. If **cs_change_delay** is used from **spi_transfer**, then the
  two delays will be added up.
- `chip_select`: Array of physical chipselect, spi->chipselect\[i\] gives
  the corresponding physical CS for logical CS i.
- `num_chipselect`: Number of physical chipselects used.
- `cs_index_mask`: Bit mask of the active chipselect(s) in the chipselect array
- `cs_gpiod`: Array of GPIO descriptors of the corresponding chipselect lines
  (optional, NULL when not using a GPIO line)
- `tx_lane_map`: Map of peripheral lanes (index) to controller lanes (value).
- `num_tx_lanes`: Number of transmit lanes wired up.
- `rx_lane_map`: Map of peripheral lanes (index) to controller lanes (value).
- `num_rx_lanes`: Number of receive lanes wired up.

**Description**

A **spi_device** is used to interchange data between an SPI target device
(usually a discrete chip) and CPU memory.

In **dev**, the platform_data is used to hold information about this
device that's meaningful to the device's protocol driver, but not
to its controller.  One example might be an identifier for a chip
variant with slightly different functionality; another might be
information about how this particular board wires the chip's pins.

#### <a id="c-struct-spi_driver"></a>`struct spi_driver`

Host side "protocol" driver

**Definition**

```c
struct spi_driver {
    const struct spi_device_id *id_table;
    int (*probe)(struct spi_device *spi);
    void (*remove)(struct spi_device *spi);
    void (*shutdown)(struct spi_device *spi);
    struct device_driver    driver;
};
```

**Members**

- `id_table`: List of SPI devices supported by this driver
- `probe`: Binds this driver to the SPI device.  Drivers can verify
  that the device is actually present, and may need to configure
  characteristics (such as bits_per_word) which weren't needed for
  the initial configuration done during system setup.
- `remove`: Unbinds this driver from the SPI device
- `shutdown`: Standard shutdown callback used during system state
  transitions such as powerdown/halt and kexec
- `driver`: SPI device drivers should initialize the name and owner
  field of this structure.

**Description**

This represents the kind of device driver that uses SPI messages to
interact with the hardware at the other end of a SPI link.  It's called
a "protocol" driver because it works through messages rather than talking
directly to SPI hardware (which is what the underlying SPI controller
driver does to pass those messages).  These protocols are defined in the
specification for the device(s) supported by the driver.

As a rule, those device protocols represent the lowest level interface
supported by a driver, and it will support upper level interfaces too.
Examples of such upper levels include frameworks like MTD, networking,
MMC, RTC, filesystem character device nodes, and hardware monitoring.

#### <a id="c-spi_unregister_driver"></a>`spi_unregister_driver()`

```c
void spi_unregister_driver(struct spi_driver *sdrv)
```

reverse effect of spi_register_driver

**Parameters**

- `struct spi_driver *sdrv`: the driver to unregister

**Context**

can sleep

#### <a id="c-module_spi_driver"></a>`module_spi_driver()`

```c
module_spi_driver(__spi_driver)
```

Helper macro for registering a SPI driver

**Parameters**

- `__spi_driver`: spi_driver struct

**Description**

Helper macro for SPI drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)

#### <a id="c-struct-spi_controller"></a>`struct spi_controller`

interface to SPI host or target controller

**Definition**

```c
struct spi_controller {
        struct device   dev;
        struct list_head list;
        s16 bus_num;
        u16 num_chipselect;
        u16 num_data_lanes;
        u16 dma_alignment;
        u32 mode_bits;
        u32 buswidth_override_bits;
        u32 bits_per_word_mask;
    #define SPI_BPW_MASK(bits) BIT((bits) - 1);
    #define SPI_BPW_RANGE_MASK(min, max) GENMASK((max) - 1, (min) - 1);
        u32 min_speed_hz;
        u32 max_speed_hz;
        u16 flags;
    #define SPI_CONTROLLER_HALF_DUPLEX      BIT(0);
    #define SPI_CONTROLLER_NO_RX            BIT(1);
    #define SPI_CONTROLLER_NO_TX            BIT(2);
    #define SPI_CONTROLLER_MUST_RX          BIT(3);
    #define SPI_CONTROLLER_MUST_TX          BIT(4);
    #define SPI_CONTROLLER_GPIO_SS          BIT(5);
    #define SPI_CONTROLLER_SUSPENDED        BIT(6);
    #define SPI_CONTROLLER_MULTI_CS         BIT(7);
        bool devm_allocated;
        union {
            bool slave;
            bool target;
        };
        size_t (*max_transfer_size)(struct spi_device *spi);
        size_t (*max_message_size)(struct spi_device *spi);
        struct mutex            io_mutex;
        struct mutex            add_lock;
        spinlock_t bus_lock_spinlock;
        struct mutex            bus_lock_mutex;
        bool bus_lock_flag;
        int (*setup)(struct spi_device *spi);
        int (*set_cs_timing)(struct spi_device *spi);
        int (*transfer)(struct spi_device *spi, struct spi_message *mesg);
        void (*cleanup)(struct spi_device *spi);
        bool (*can_dma)(struct spi_controller *ctlr, struct spi_device *spi, struct spi_transfer *xfer);
        struct device *dma_map_dev;
        struct device *cur_rx_dma_dev;
        struct device *cur_tx_dma_dev;
        bool queued;
        struct kthread_worker           *kworker;
        struct kthread_work             pump_messages;
        spinlock_t queue_lock;
        struct list_head                queue;
        struct spi_message              *cur_msg;
        struct completion               cur_msg_completion;
        bool cur_msg_incomplete;
        bool cur_msg_need_completion;
        bool busy;
        bool running;
        bool rt;
        bool auto_runtime_pm;
        bool fallback;
        bool last_cs_mode_high;
        s8 last_cs[SPI_DEVICE_CS_CNT_MAX];
        u32 last_cs_index_mask : SPI_DEVICE_CS_CNT_MAX;
        struct completion               xfer_completion;
        size_t max_dma_len;
        int (*optimize_message)(struct spi_message *msg);
        int (*unoptimize_message)(struct spi_message *msg);
        int (*prepare_transfer_hardware)(struct spi_controller *ctlr);
        int (*transfer_one_message)(struct spi_controller *ctlr, struct spi_message *mesg);
        int (*unprepare_transfer_hardware)(struct spi_controller *ctlr);
        int (*prepare_message)(struct spi_controller *ctlr, struct spi_message *message);
        int (*unprepare_message)(struct spi_controller *ctlr, struct spi_message *message);
        int (*target_abort)(struct spi_controller *ctlr);
        void (*set_cs)(struct spi_device *spi, bool enable);
        int (*transfer_one)(struct spi_controller *ctlr, struct spi_device *spi, struct spi_transfer *transfer);
        void (*handle_err)(struct spi_controller *ctlr, struct spi_message *message);
        const struct spi_controller_mem_ops *mem_ops;
        const struct spi_controller_mem_caps *mem_caps;
        bool dtr_caps;
        struct spi_offload *(*get_offload)(struct spi_device *spi, const struct spi_offload_config *config);
        void (*put_offload)(struct spi_offload *offload);
        struct gpio_desc        **cs_gpiods;
        bool use_gpio_descriptors;
        s8 unused_native_cs;
        s8 max_native_cs;
        struct spi_statistics __percpu  *pcpu_statistics;
        struct dma_chan         *dma_tx;
        struct dma_chan         *dma_rx;
        void *dummy_rx;
        void *dummy_tx;
        int (*fw_translate_cs)(struct spi_controller *ctlr, unsigned cs);
        bool ptp_sts_supported;
        unsigned long           irq_flags;
        bool queue_empty;
        bool must_async;
        bool defer_optimize_message;
};
```

**Members**

- `dev`: device interface to this driver
- `list`: link with the global spi_controller list
- `bus_num`: board-specific (and often SOC-specific) identifier for a
  given SPI controller.
- `num_chipselect`: chipselects are used to distinguish individual
  SPI targets, and are numbered from zero to num_chipselects.
  each target has a chipselect signal, but it's common that not
  every chipselect is connected to a target.
- `num_data_lanes`: Number of data lanes supported by this controller. Default is 1.
- `dma_alignment`: SPI controller constraint on DMA buffers alignment.
- `mode_bits`: flags understood by this controller driver
- `buswidth_override_bits`: flags to override for this controller driver
- `bits_per_word_mask`: A mask indicating which values of bits_per_word are
  supported by the driver. Bit n indicates that a bits_per_word n+1 is
  supported. If set, the SPI core will reject any transfer with an
  unsupported bits_per_word. If not set, this value is simply ignored,
  and it's up to the individual driver to perform any validation.
- `min_speed_hz`: Lowest supported transfer speed
- `max_speed_hz`: Highest supported transfer speed
- `flags`: other constraints relevant to this driver
- `devm_allocated`: whether the allocation of this struct is devres-managed
- `{unnamed_union}`: anonymous
- `slave`: indicates that this is an SPI slave controller
- `target`: indicates that this is an SPI target controller
- `max_transfer_size`: function that returns the max transfer size for
  a [`spi_device`](#c-struct-spi_device); may be `NULL`, so the default `SIZE_MAX` will be used.
- `max_message_size`: function that returns the max message size for
  a [`spi_device`](#c-struct-spi_device); may be `NULL`, so the default `SIZE_MAX` will be used.
- `io_mutex`: mutex for physical bus access
- `add_lock`: mutex to avoid adding devices to the same chipselect
- `bus_lock_spinlock`: spinlock for SPI bus locking
- `bus_lock_mutex`: mutex for exclusion of multiple callers
- `bus_lock_flag`: indicates that the SPI bus is locked for exclusive use
- `setup`: updates the device mode and clocking records used by a
  device's SPI controller; protocol code may call this.  This
  must fail if an unrecognized or unsupported mode is requested.
  It's always safe to call this unless transfers are pending on
  the device whose settings are being modified.
- `set_cs_timing`: optional hook for SPI devices to request SPI
  controller for configuring specific CS setup time, hold time and inactive
  delay in terms of clock counts
- `transfer`: adds a message to the controller's transfer queue.
- `cleanup`: frees controller-specific state
- `can_dma`: determine whether this controller supports DMA
- `dma_map_dev`: device which can be used for DMA mapping
- `cur_rx_dma_dev`: device which is currently used for RX DMA mapping
- `cur_tx_dma_dev`: device which is currently used for TX DMA mapping
- `queued`: whether this controller is providing an internal message queue
- `kworker`: pointer to thread struct for message pump
- `pump_messages`: work struct for scheduling work to the message pump
- `queue_lock`: spinlock to synchronise access to message queue
- `queue`: message queue
- `cur_msg`: the currently in-flight message
- `cur_msg_completion`: a completion for the current in-flight message
- `cur_msg_incomplete`: Flag used internally to opportunistically skip
  the **cur_msg_completion**. This flag is used to check if the driver has
  already called [`spi_finalize_current_message()`](#c-spi_finalize_current_message).
- `cur_msg_need_completion`: Flag used internally to opportunistically skip
  the **cur_msg_completion**. This flag is used to signal the context that
  is running [`spi_finalize_current_message()`](#c-spi_finalize_current_message) that it needs to `complete()`
- `busy`: message pump is busy
- `running`: message pump is running
- `rt`: whether this queue is set to run as a realtime task
- `auto_runtime_pm`: the core should ensure a runtime PM reference is held
  while the hardware is prepared, using the parent
  device for the spidev
- `fallback`: fallback to PIO if DMA transfer return failure with
  SPI_TRANS_FAIL_NO_START.
- `last_cs_mode_high`: was (mode & SPI_CS_HIGH) true on the last call to set_cs.
- `last_cs`: the last chip_select that is recorded by set_cs, -1 on non chip
  selected
- `last_cs_index_mask`: bit mask the last chip selects that were used
- `xfer_completion`: used by core `transfer_one_message()`
- `max_dma_len`: Maximum length of a DMA transfer for the device.
- `optimize_message`: optimize the message for reuse
- `unoptimize_message`: release resources allocated by optimize_message
- `prepare_transfer_hardware`: a message will soon arrive from the queue
  so the subsystem requests the driver to prepare the transfer hardware
  by issuing this call
- `transfer_one_message`: the subsystem calls the driver to transfer a single
  message while queuing transfers that arrive in the meantime. When the
  driver is finished with this message, it must call
  [`spi_finalize_current_message()`](#c-spi_finalize_current_message) so the subsystem can issue the next
  message
- `unprepare_transfer_hardware`: there are currently no more messages on the
  queue so the subsystem notifies the driver that it may relax the
  hardware by issuing this call
- `prepare_message`: set up the controller to transfer a single message,
  for example doing DMA mapping.  Called from threaded
  context.
- `unprepare_message`: undo any work done by `prepare_message()`.
- `target_abort`: abort the ongoing transfer request on an SPI target controller
- `set_cs`: set the logic level of the chip select line.  May be called
  from interrupt context.
- `transfer_one`: transfer a single spi_transfer.
- `handle_err`: the subsystem calls the driver to handle an error that occurs
  in the generic implementation of `transfer_one_message()`.
- `mem_ops`: optimized/dedicated operations for interactions with SPI memory.
  This field is optional and should only be implemented if the
  controller has native support for memory like operations.
- `mem_caps`: controller capabilities for the handling of memory operations.
- `dtr_caps`: true if controller has dtr(single/dual transfer rate) capability.
  QSPI based controller should fill this based on controller's capability.
- `get_offload`: callback for controllers with offload support to get matching
  offload instance. Implementations should return -ENODEV if no match is
  found.
- `put_offload`: release the offload instance acquired by **get_offload**.
- `cs_gpiods`: Array of GPIO descriptors to use as chip select lines; one per CS
  number. Any individual value may be NULL for CS lines that
  are not GPIOs (driven by the SPI controller itself).
- `use_gpio_descriptors`: Turns on the code in the SPI core to parse and grab
  GPIO descriptors. This will fill in **cs_gpiods** and SPI devices will have
  the cs_gpiod assigned if a GPIO line is found for the chipselect.
- `unused_native_cs`: When cs_gpiods is used, [`spi_register_controller()`](#c-spi_register_controller) will
  fill in this field with the first unused native CS, to be used by SPI
  controller drivers that need to drive a native CS when using GPIO CS.
- `max_native_cs`: When cs_gpiods is used, and this field is filled in,
  [`spi_register_controller()`](#c-spi_register_controller) will validate all native CS (including the
  unused native CS) against this value.
- `pcpu_statistics`: statistics for the spi_controller
- `dma_tx`: DMA transmit channel
- `dma_rx`: DMA receive channel
- `dummy_rx`: dummy receive buffer for full-duplex devices
- `dummy_tx`: dummy transmit buffer for full-duplex devices
- `fw_translate_cs`: If the boot firmware uses different numbering scheme
  what Linux expects, this optional hook can be used to translate
  between the two.
- `ptp_sts_supported`: If the driver sets this to true, it must provide a
  time snapshot in **spi_transfer->ptp_sts** as close as possible to the
  moment in time when **spi_transfer->ptp_sts_word_pre** and
  **spi_transfer->ptp_sts_word_post** were transmitted.
  If the driver does not set this, the SPI core takes the snapshot as
  close to the driver hand-over as possible.
- `irq_flags`: Interrupt enable state during PTP system timestamping
- `queue_empty`: signal green light for opportunistically skipping the queue
  for spi_sync transfers.
- `must_async`: disable all fast paths in the core
- `defer_optimize_message`: set to true if controller cannot pre-optimize messages
  and needs to defer the optimization step until the message is actually
  being transferred

**Description**

- return 0 if the transfer is finished,
- return 1 if the transfer is still in progress. When
  the driver is finished with this transfer it must
  call [`spi_finalize_current_transfer()`](#c-spi_finalize_current_transfer) so the subsystem
  can issue the next transfer. If the transfer fails, the
  driver must set the flag SPI_TRANS_FAIL_IO to
  spi_transfer->error first, before calling
  [`spi_finalize_current_transfer()`](#c-spi_finalize_current_transfer).

Each SPI controller can communicate with one or more **spi_device**
children.  These make a small bus, sharing MOSI, MISO and SCK signals
but not chip select signals.  Each device may be configured to use a
different clock rate, since those shared signals are ignored unless
the chip is selected.

The driver for an SPI controller manages access to those devices through
a queue of spi_message transactions, copying data between CPU memory and
an SPI target device.  For each such message it queues, it calls the
message's completion function when the transaction completes.

**Note**

- transfer_one and transfer_one_message are mutually

  exclusive; when both are set, the generic subsystem does
  not call your transfer_one callback.

#### <a id="c-struct-spi_res"></a>`struct spi_res`

SPI resource management structure

**Definition**

```c
struct spi_res {
    struct list_head        entry;
    spi_res_release_t release;
    unsigned long long      data[];
};
```

**Members**

- `entry`: list entry
- `release`: release code called prior to freeing this resource
- `data`: extra data allocated for the specific use-case

**Description**

This is based on ideas from devres, but focused on life-cycle
management during spi_message processing.

#### <a id="c-struct-spi_transfer"></a>`struct spi_transfer`

a read/write buffer pair

**Definition**

```c
struct spi_transfer {
        const void      *tx_buf;
        void *rx_buf;
        unsigned len;
    #define SPI_TRANS_FAIL_NO_START BIT(0);
    #define SPI_TRANS_FAIL_IO       BIT(1);
        u16 error;
        bool tx_sg_mapped;
        bool rx_sg_mapped;
        struct sg_table tx_sg;
        struct sg_table rx_sg;
        dma_addr_t tx_dma;
        dma_addr_t rx_dma;
        unsigned dummy_data:1;
        unsigned cs_off:1;
        unsigned cs_change:1;
        unsigned tx_nbits:4;
        unsigned rx_nbits:4;
    #define SPI_MULTI_LANE_MODE_SINGLE      0;
    #define SPI_MULTI_LANE_MODE_STRIPE      1;
    #define SPI_MULTI_LANE_MODE_MIRROR      2;
        unsigned multi_lane_mode: 2;
        unsigned timestamped:1;
        bool dtr_mode;
    #define SPI_NBITS_SINGLE        0x01;
    #define SPI_NBITS_DUAL          0x02;
    #define SPI_NBITS_QUAD          0x04;
    #define SPI_NBITS_OCTAL 0x08;
        u8 bits_per_word;
        struct spi_delay        delay;
        struct spi_delay        cs_change_delay;
        struct spi_delay        word_delay;
        u32 speed_hz;
        u32 effective_speed_hz;
        unsigned int    offload_flags;
        unsigned int    ptp_sts_word_pre;
        unsigned int    ptp_sts_word_post;
        struct ptp_system_timestamp *ptp_sts;
        struct list_head transfer_list;
};
```

**Members**

- `tx_buf`: data to be written (DMA-safe memory), or NULL
- `rx_buf`: data to be read (DMA-safe memory), or NULL
- `len`: size of rx and tx buffers (in bytes)
- `error`: Error status logged by SPI controller driver.
- `tx_sg_mapped`: If true, the **tx_sg** is mapped for DMA
- `rx_sg_mapped`: If true, the **rx_sg** is mapped for DMA
- `tx_sg`: Scatterlist for transmit, currently not for client use
- `rx_sg`: Scatterlist for receive, currently not for client use
- `tx_dma`: DMA address of tx_buf, currently not for client use
- `rx_dma`: DMA address of rx_buf, currently not for client use
- `dummy_data`: indicates transfer is dummy bytes transfer.
- `cs_off`: performs the transfer with chipselect off.
- `cs_change`: affects chipselect after this transfer completes
- `tx_nbits`: number of bits used for writing. If 0 the default
  (SPI_NBITS_SINGLE) is used.
- `rx_nbits`: number of bits used for reading. If 0 the default
  (SPI_NBITS_SINGLE) is used.
- `multi_lane_mode`: How to serialize data on multiple lanes. One of the
  SPI_MULTI_LANE_MODE_* values.
- `timestamped`: true if the transfer has been timestamped
- `dtr_mode`: true if supports double transfer rate.
- `bits_per_word`: select a bits_per_word other than the device default
  for this transfer. If 0 the default (from **spi_device**) is used.
- `delay`: delay to be introduced after this transfer before
  (optionally) changing the chipselect status, then starting
  the next transfer or completing this **spi_message**.
- `cs_change_delay`: delay between cs deassert and assert when
  **cs_change** is set and **spi_transfer** is not the last in **spi_message**
- `word_delay`: inter word delay to be introduced after each word size
  (set by bits_per_word) transmission.
- `speed_hz`: Select a speed other than the device default for this
  transfer. If 0 the default (from **spi_device**) is used.
- `effective_speed_hz`: the effective SCK-speed that was used to
  transfer this transfer. Set to 0 if the SPI bus driver does
  not support it.
- `offload_flags`: Flags that are only applicable to specialized SPI offload
  transfers. See `SPI_OFFLOAD_XFER_*` in spi-offload.h.
- `ptp_sts_word_pre`: The word (subject to bits_per_word semantics) offset
  within **tx_buf** for which the SPI device is requesting that the time
  snapshot for this transfer begins. Upon completing the SPI transfer,
  this value may have changed compared to what was requested, depending
  on the available snapshotting resolution (DMA transfer,
  **ptp_sts_supported** is false, etc).
- `ptp_sts_word_post`: See **ptp_sts_word_post**. The two can be equal (meaning
  that a single byte should be snapshotted).
  If the core takes care of the timestamp (if **ptp_sts_supported** is false
  for this controller), it will set **ptp_sts_word_pre** to 0, and
  **ptp_sts_word_post** to the length of the transfer. This is done
  purposefully (instead of setting to spi_transfer->len - 1) to denote
  that a transfer-level snapshot taken from within the driver may still
  be of higher quality.
- `ptp_sts`: Pointer to a memory location held by the SPI target device where a
  PTP system timestamp structure may lie. If drivers use PIO or their
  hardware has some sort of assist for retrieving exact transfer timing,
  they can (and should) assert **ptp_sts_supported** and populate this
  structure using the ptp_read_system_*ts helper functions.
  The timestamp must represent the time at which the SPI target device has
  processed the word, i.e. the "pre" timestamp should be taken before
  transmitting the "pre" word, and the "post" timestamp after receiving
  transmit confirmation from the controller for the "post" word.
- `transfer_list`: transfers are sequenced through **spi_message.transfers**

**Description**

SPI transfers always write the same number of bytes as they read.
Protocol drivers should always provide **rx_buf** and/or **tx_buf**.
In some cases, they may also want to provide DMA addresses for
the data being transferred; that may reduce overhead, when the
underlying driver uses DMA.

If the transmit buffer is NULL, zeroes will be shifted out
while filling **rx_buf**.  If the receive buffer is NULL, the data
shifted in will be discarded.  Only "len" bytes shift out (or in).
It's an error to try to shift out a partial word.  (For example, by
shifting out three bytes with word size of sixteen or twenty bits;
the former uses two bytes per word, the latter uses four bytes.)

In-memory data values are always in native CPU byte order, translated
from the wire byte order (big-endian except with SPI_LSB_FIRST).  So
for example when bits_per_word is sixteen, buffers are 2N bytes long
(**len** = 2N) and hold N sixteen bit words in CPU byte order.

When the word size of the SPI transfer is not a power-of-two multiple
of eight bits, those in-memory words include extra bits.  In-memory
words are always seen by protocol drivers as right-justified, so the
undefined (rx) or unused (tx) bits are always the most significant bits.

All SPI transfers start with the relevant chipselect active.  Normally
it stays selected until after the last transfer in a message.  Drivers
can affect the chipselect signal using cs_change.

(i) If the transfer isn't the last one in the message, this flag is
used to make the chipselect briefly go inactive in the middle of the
message.  Toggling chipselect in this way may be needed to terminate
a chip command, letting a single spi_message perform all of group of
chip transactions together.

(ii) When the transfer is the last one in the message, the chip may
stay selected until the next transfer.  On multi-device SPI busses
with nothing blocking messages going to other devices, this is just
a performance hint; starting a message to another device deselects
this one.  But in other cases, this can be used to ensure correctness.
Some devices need protocol transactions to be built from a series of
spi_message submissions, where the content of one message is determined
by the results of previous messages and where the whole transaction
ends when the chipselect goes inactive.

When SPI can transfer in 1x,2x or 4x. It can get this transfer information
from device through **tx_nbits** and **rx_nbits**. In Bi-direction, these
two should both be set. User can set transfer mode with SPI_NBITS_SINGLE(1x)
SPI_NBITS_DUAL(2x) and SPI_NBITS_QUAD(4x) to support these three transfer.

User may also set dtr_mode to true to use dual transfer mode if desired. if
not, default considered as single transfer mode.

The code that submits an spi_message (and its spi_transfers)
to the lower layers is responsible for managing its memory.
Zero-initialize every field you don't set up explicitly, to
insulate against future API updates.  After you submit a message
and its transfers, ignore them until its completion callback.

#### <a id="c-struct-spi_message"></a>`struct spi_message`

one multi-segment SPI transaction

**Definition**

```c
struct spi_message {
    struct list_head        transfers;
    struct spi_device       *spi;
    bool pre_optimized;
    bool optimized;
    bool prepared;
    int status;
    void (*complete)(void *context);
    void *context;
    unsigned frame_length;
    unsigned actual_length;
    struct list_head        queue;
    void *state;
    void *opt_state;
    struct spi_offload      *offload;
    struct list_head        resources;
};
```

**Members**

- `transfers`: list of transfer segments in this transaction
- `spi`: SPI device to which the transaction is queued
- `pre_optimized`: peripheral driver pre-optimized the message
- `optimized`: the message is in the optimized state
- `prepared`: spi_prepare_message was called for the this message
- `status`: zero for success, else negative errno
- `complete`: called to report transaction completions
- `context`: the argument to `complete()` when it's called
- `frame_length`: the total number of bytes in the message
- `actual_length`: the total number of bytes that were transferred in all
  successful segments
- `queue`: for use by whichever driver currently owns the message
- `state`: for use by whichever driver currently owns the message
- `opt_state`: for use by whichever driver currently owns the message
- `offload`: (optional) offload instance used by this message
- `resources`: for resource management when the SPI message is processed

**Description**

A **spi_message** is used to execute an atomic sequence of data transfers,
each represented by a struct spi_transfer.  The sequence is "atomic"
in the sense that no other spi_message may use that SPI bus until that
sequence completes.  On some systems, many such sequences can execute as
a single programmed DMA transfer.  On all systems, these messages are
queued, and might complete after transactions to other devices.  Messages
sent to a given spi_device are always executed in FIFO order.

The code that submits an spi_message (and its spi_transfers)
to the lower layers is responsible for managing its memory.
Zero-initialize every field you don't set up explicitly, to
insulate against future API updates.  After you submit a message
and its transfers, ignore them until its completion callback.

#### <a id="c-spi_message_init_with_transfers"></a>`spi_message_init_with_transfers()`

```c
void spi_message_init_with_transfers(struct spi_message *m, struct spi_transfer *xfers, unsigned int num_xfers)
```

Initialize spi_message and append transfers

**Parameters**

- `struct spi_message *m`: spi_message to be initialized
- `struct spi_transfer *xfers`: An array of SPI transfers
- `unsigned int num_xfers`: Number of items in the xfer array

**Description**

This function initializes the given spi_message and adds each spi_transfer in
the given array to the message.

#### <a id="c-spi_is_bpw_supported"></a>`spi_is_bpw_supported()`

```c
bool spi_is_bpw_supported(struct spi_device *spi, u32 bpw)
```

Check if bits per word is supported

**Parameters**

- `struct spi_device *spi`: SPI device
- `u32 bpw`: Bits per word

**Description**

This function checks to see if the SPI controller supports **bpw**.

**Return**

True if **bpw** is supported, false otherwise.

#### <a id="c-spi_bpw_to_bytes"></a>`spi_bpw_to_bytes()`

```c
u32 spi_bpw_to_bytes(u32 bpw)
```

Covert bits per word to bytes

**Parameters**

- `u32 bpw`: Bits per word

**Description**

This function converts the given **bpw** to bytes. The result is always
power-of-two, e.g.,

```text
===============    =================
Input (in bits)    Output (in bytes)
===============    =================
        5                   1
        9                   2
        21                  4
        37                  8
===============    =================
```

It will return 0 for the 0 input.

**Return**

Bytes for the given **bpw**.

#### <a id="c-spi_controller_xfer_timeout"></a>`spi_controller_xfer_timeout()`

```c
unsigned int spi_controller_xfer_timeout(struct spi_controller *ctlr, struct spi_transfer *xfer)
```

Compute a suitable timeout value

**Parameters**

- `struct spi_controller *ctlr`: SPI device
- `struct spi_transfer *xfer`: Transfer descriptor

**Description**

Compute a relevant timeout value for the given transfer. We derive the time
that it would take on a single data line and take twice this amount of time
with a minimum of 500ms to avoid false positives on loaded systems.

**Return**

Transfer timeout value in milliseconds.

#### <a id="c-struct-spi_replaced_transfers"></a>`struct spi_replaced_transfers`

structure describing the spi_transfer replacements that have occurred so that they can get reverted

**Definition**

```c
struct spi_replaced_transfers {
    spi_replaced_release_t release;
    void *extradata;
    struct list_head replaced_transfers;
    struct list_head *replaced_after;
    size_t inserted;
    struct spi_transfer inserted_transfers[];
};
```

**Members**

- `release`: some extra release code to get executed prior to
  releasing this structure
- `extradata`: pointer to some extra data if requested or NULL
- `replaced_transfers`: transfers that have been replaced and which need
  to get restored
- `replaced_after`: the transfer after which the **replaced_transfers**
  are to get re-inserted
- `inserted`: number of transfers inserted
- `inserted_transfers`: array of spi_transfers of array-size **inserted**,
  that have been replacing replaced_transfers

**Note**

that **extradata** will point to **inserted_transfers**\[**inserted**\]
if some extra allocation is requested, so alignment will be the same
as for spi_transfers.

#### <a id="c-spi_sync_transfer"></a>`spi_sync_transfer()`

```c
int spi_sync_transfer(struct spi_device *spi, struct spi_transfer *xfers, unsigned int num_xfers)
```

synchronous SPI data transfer

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `struct spi_transfer *xfers`: An array of spi_transfers
- `unsigned int num_xfers`: Number of items in the xfer array

**Context**

can sleep

**Description**

Does a synchronous SPI data transfer of the given spi_transfer array.

For more specific semantics see [`spi_sync()`](#c-spi_sync).

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_write"></a>`spi_write()`

```c
int spi_write(struct spi_device *spi, const void *buf, size_t len)
```

SPI synchronous write

**Parameters**

- `struct spi_device *spi`: device to which data will be written
- `const void *buf`: data buffer
- `size_t len`: data buffer size

**Context**

can sleep

**Description**

This function writes the buffer **buf**.
Callable only from contexts that can sleep.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_read"></a>`spi_read()`

```c
int spi_read(struct spi_device *spi, void *buf, size_t len)
```

SPI synchronous read

**Parameters**

- `struct spi_device *spi`: device from which data will be read
- `void *buf`: data buffer
- `size_t len`: data buffer size

**Context**

can sleep

**Description**

This function reads the buffer **buf**.
Callable only from contexts that can sleep.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_w8r8"></a>`spi_w8r8()`

```c
ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
```

SPI synchronous 8 bit write followed by 8 bit read

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `u8 cmd`: command to be written before data is read back

**Context**

can sleep

**Description**

Callable only from contexts that can sleep.

**Return**

the (unsigned) eight bit number returned by the
device, or else a negative error code.

#### <a id="c-spi_w8r16"></a>`spi_w8r16()`

```c
ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
```

SPI synchronous 8 bit write followed by 16 bit read

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `u8 cmd`: command to be written before data is read back

**Context**

can sleep

**Description**

The number is returned in wire-order, which is at least sometimes
big-endian.

Callable only from contexts that can sleep.

**Return**

the (unsigned) sixteen bit number returned by the
device, or else a negative error code.

#### <a id="c-spi_w8r16be"></a>`spi_w8r16be()`

```c
ssize_t spi_w8r16be(struct spi_device *spi, u8 cmd)
```

SPI synchronous 8 bit write followed by 16 bit big-endian read

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `u8 cmd`: command to be written before data is read back

**Context**

can sleep

**Description**

This function is similar to spi_w8r16, with the exception that it will
convert the read 16 bit data word from big-endian to native endianness.

Callable only from contexts that can sleep.

**Return**

the (unsigned) sixteen bit number returned by the device in CPU
endianness, or else a negative error code.

#### <a id="c-struct-spi_board_info"></a>`struct spi_board_info`

board-specific template for a SPI device

**Definition**

```c
struct spi_board_info {
    char modalias[SPI_NAME_SIZE];
    const void      *platform_data;
    const struct software_node *swnode;
    void *controller_data;
    int irq;
    u32 max_speed_hz;
    u16 bus_num;
    u16 chip_select;
    u32 mode;
};
```

**Members**

- `modalias`: Initializes spi_device.modalias; identifies the driver.
- `platform_data`: Initializes spi_device.platform_data; the particular
  data stored there is driver-specific.
- `swnode`: Software node for the device.
- `controller_data`: Initializes spi_device.controller_data; some
  controllers need hints about hardware setup, e.g. for DMA.
- `irq`: Initializes spi_device.irq; depends on how the board is wired.
- `max_speed_hz`: Initializes spi_device.max_speed_hz; based on limits
  from the chip datasheet and board-specific signal quality issues.
- `bus_num`: Identifies which spi_controller parents the spi_device; unused
  by [`spi_new_device()`](#c-spi_new_device), and otherwise depends on board wiring.
- `chip_select`: Initializes spi_device.chip_select; depends on how
  the board is wired.
- `mode`: Initializes spi_device.mode; based on the chip datasheet, board
  wiring (some devices support both 3WIRE and standard modes), and
  possibly presence of an inverter in the chipselect path.

**Description**

When adding new SPI devices to the device tree, these structures serve
as a partial device template.  They hold information which can't always
be determined by drivers.  Information that `probe()` can establish (such
as the default transfer wordsize) is not included here.

These structures are used in two places.  Their primary role is to
be stored in tables of board-specific device descriptors, which are
declared early in board initialization and then used (much later) to
populate a controller's device tree after the that controller's driver
initializes.  A secondary (and atypical) role is as a parameter to
[`spi_new_device()`](#c-spi_new_device) call, which happens after those controller drivers
are active in some dynamic board configuration models.



#### <a id="c-spi_register_board_info"></a>`spi_register_board_info()`

```c
int spi_register_board_info(struct spi_board_info const *info, unsigned n)
```

register SPI devices for a given board

**Parameters**

- `struct spi_board_info const *info`: array of chip descriptors
- `unsigned n`: how many descriptors are provided

**Context**

can sleep

**Description**

Board-specific early init code calls this (probably during arch_initcall)
with segments of the SPI device table.  Any device nodes are created later,
after the relevant parent SPI controller (bus_num) is defined.  We keep
this table of devices forever, so that reloading a controller driver will
not make Linux forget about these hard-wired devices.

Other code can also call this, e.g. a particular add-on board might provide
SPI devices through its expansion connector, so code initializing that board
would naturally declare its SPI devices.

The board info passed can safely be __initdata ... but be careful of
any embedded pointers (platform_data, etc), they're copied as-is.

**Return**

zero on success, else a negative error code.



#### <a id="c-__spi_register_driver"></a>`__spi_register_driver()`

```c
int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
```

register a SPI driver

**Parameters**

- `struct module *owner`: owner module of the driver to register
- `struct spi_driver *sdrv`: the driver to register

**Context**

can sleep

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_alloc_device"></a>`spi_alloc_device()`

```c
struct spi_device * spi_alloc_device(struct spi_controller *ctlr)
```

Allocate a new SPI device

**Parameters**

- `struct spi_controller *ctlr`: Controller to which device is connected

**Context**

can sleep

**Description**

Allows a driver to allocate and initialize a spi_device without
registering it immediately.  This allows a driver to directly
fill the spi_device with device parameters before calling
[`spi_add_device()`](#c-spi_add_device) on it.

Caller is responsible to call [`spi_add_device()`](#c-spi_add_device) on the returned
spi_device structure to add it to the SPI controller.  If the caller
needs to discard the spi_device without adding it, then it should
call `spi_dev_put()` on it.

**Return**

a pointer to the new device, or NULL.

#### <a id="c-spi_add_device"></a>`spi_add_device()`

```c
int spi_add_device(struct spi_device *spi)
```

Add spi_device allocated with spi_alloc_device

**Parameters**

- `struct spi_device *spi`: spi_device to register

**Description**

Companion function to spi_alloc_device.  Devices allocated with
spi_alloc_device can be added onto the SPI bus with this function.

**Return**

0 on success; negative errno on failure

#### <a id="c-spi_new_device"></a>`spi_new_device()`

```c
struct spi_device * spi_new_device(struct spi_controller *ctlr, struct spi_board_info *chip)
```

instantiate one new SPI device

**Parameters**

- `struct spi_controller *ctlr`: Controller to which device is connected
- `struct spi_board_info *chip`: Describes the SPI device

**Context**

can sleep

**Description**

On typical mainboards, this is purely internal; and it's not needed
after board init creates the hard-wired devices.  Some development
platforms may not be able to use spi_register_board_info though, and
this is exported so that for example a USB or parport based adapter
driver could add devices (which it would learn about out-of-band).

**Return**

the new device, or NULL.

#### <a id="c-spi_unregister_device"></a>`spi_unregister_device()`

```c
void spi_unregister_device(struct spi_device *spi)
```

unregister a single SPI device

**Parameters**

- `struct spi_device *spi`: spi_device to unregister

**Description**

Start making the passed SPI device vanish. Normally this would be handled
by [`spi_unregister_controller()`](#c-spi_unregister_controller).

#### <a id="c-spi_finalize_current_transfer"></a>`spi_finalize_current_transfer()`

```c
void spi_finalize_current_transfer(struct spi_controller *ctlr)
```

report completion of a transfer

**Parameters**

- `struct spi_controller *ctlr`: the controller reporting completion

**Description**

Called by SPI drivers using the core `transfer_one_message()`
implementation to notify it that the current interrupt driven
transfer has finished and the next one may be scheduled.

#### <a id="c-spi_take_timestamp_pre"></a>`spi_take_timestamp_pre()`

```c
void spi_take_timestamp_pre(struct spi_controller *ctlr, struct spi_transfer *xfer, size_t progress, bool irqs_off)
```

helper to collect the beginning of the TX timestamp

**Parameters**

- `struct spi_controller *ctlr`: Pointer to the spi_controller structure of the driver
- `struct spi_transfer *xfer`: Pointer to the transfer being timestamped
- `size_t progress`: How many words (not bytes) have been transferred so far
- `bool irqs_off`: If true, will disable IRQs and preemption for the duration of the
  transfer, for less jitter in time measurement. Only compatible
  with PIO drivers. If true, must follow up with
  spi_take_timestamp_post or otherwise system will crash.
  WARNING: for fully predictable results, the CPU frequency must
  also be under control (governor).

**Description**

This is a helper for drivers to collect the beginning of the TX timestamp
for the requested byte from the SPI transfer. The frequency with which this
function must be called (once per word, once for the whole transfer, once
per batch of words etc) is arbitrary as long as the **tx** buffer offset is
greater than or equal to the requested byte at the time of the call. The
timestamp is only taken once, at the first such call. It is assumed that
the driver advances its **tx** buffer pointer monotonically.

#### <a id="c-spi_take_timestamp_post"></a>`spi_take_timestamp_post()`

```c
void spi_take_timestamp_post(struct spi_controller *ctlr, struct spi_transfer *xfer, size_t progress, bool irqs_off)
```

helper to collect the end of the TX timestamp

**Parameters**

- `struct spi_controller *ctlr`: Pointer to the spi_controller structure of the driver
- `struct spi_transfer *xfer`: Pointer to the transfer being timestamped
- `size_t progress`: How many words (not bytes) have been transferred so far
- `bool irqs_off`: If true, will re-enable IRQs and preemption for the local CPU.

**Description**

This is a helper for drivers to collect the end of the TX timestamp for
the requested byte from the SPI transfer. Can be called with an arbitrary
frequency: only the first call where **tx** exceeds or is equal to the
requested word will be timestamped.

#### <a id="c-spi_get_next_queued_message"></a>`spi_get_next_queued_message()`

```c
struct spi_message * spi_get_next_queued_message(struct spi_controller *ctlr)
```

called by driver to check for queued messages

**Parameters**

- `struct spi_controller *ctlr`: the controller to check for queued messages

**Description**

If there are more messages in the queue, the next message is returned from
this call.

**Return**

the next message in the queue, else NULL if the queue is empty.

#### <a id="c-spi_finalize_current_message"></a>`spi_finalize_current_message()`

```c
void spi_finalize_current_message(struct spi_controller *ctlr)
```

the current message is complete

**Parameters**

- `struct spi_controller *ctlr`: the controller to return the message to

**Description**

Called by the driver to notify the core that the message in the front of the
queue is complete and can be removed from the queue.

#### <a id="c-spi_new_ancillary_device"></a>`spi_new_ancillary_device()`

```c
struct spi_device * spi_new_ancillary_device(struct spi_device *spi, u8 chip_select)
```

Register ancillary SPI device

**Parameters**

- `struct spi_device *spi`: Pointer to the main SPI device registering the ancillary device
- `u8 chip_select`: Chip Select of the ancillary device

**Description**

Register an ancillary SPI device; for example some chips have a chip-select
for normal device usage and another one for setup/firmware upload.

This may only be called from main SPI device's probe routine.

**Return**

0 on success; negative errno on failure

#### <a id="c-acpi_spi_count_resources"></a>`acpi_spi_count_resources()`

```c
int acpi_spi_count_resources(struct acpi_device *adev)
```

Count the number of SpiSerialBus resources

**Parameters**

- `struct acpi_device *adev`: ACPI device

**Return**

the number of SpiSerialBus resources in the ACPI-device's
resource-list; or a negative error code.

#### <a id="c-acpi_spi_device_alloc"></a>`acpi_spi_device_alloc()`

```c
struct spi_device * acpi_spi_device_alloc(struct spi_controller *ctlr, struct acpi_device *adev, int index)
```

Allocate a spi device, and fill it in with ACPI information

**Parameters**

- `struct spi_controller *ctlr`: controller to which the spi device belongs
- `struct acpi_device *adev`: ACPI Device for the spi device
- `int index`: Index of the spi resource inside the ACPI Node

**Description**

This should be used to allocate a new SPI device from and ACPI Device node.
The caller is responsible for calling spi_add_device to register the SPI device.

If ctlr is set to NULL, the Controller for the SPI device will be looked up
using the resource.
If index is set to -1, index is not used.

**Note**

If index is -1, ctlr must be set.

**Return**

a pointer to the new device, or ERR_PTR on error.

#### <a id="c-spi_target_abort"></a>`spi_target_abort()`

```c
int spi_target_abort(struct spi_device *spi)
```

abort the ongoing transfer request on an SPI target controller

**Parameters**

- `struct spi_device *spi`: device used for the current transfer

#### <a id="c-__spi_alloc_controller"></a>`__spi_alloc_controller()`

```c
struct spi_controller * __spi_alloc_controller(struct device *dev, unsigned int size, bool target)
```

allocate an SPI host or target controller

**Parameters**

- `struct device *dev`: the controller, possibly using the platform_bus
- `unsigned int size`: how much zeroed driver-private data to allocate; the pointer to this
  memory is in the driver_data field of the returned device, accessible
  with `spi_controller_get_devdata()`; the memory is cacheline aligned;
  drivers granting DMA access to portions of their private data need to
  round up **size** using ALIGN(size, `dma_get_cache_alignment()`).
- `bool target`: flag indicating whether to allocate an SPI host (false) or SPI target (true)
  controller

**Context**

can sleep

**Description**

This call is used only by SPI controller drivers, which are the
only ones directly touching chip registers.  It's how they allocate
an spi_controller structure, prior to calling [`spi_register_controller()`](#c-spi_register_controller).

This must be called from context that can sleep.

The caller is responsible for assigning the bus number and initializing the
controller's methods before calling [`spi_register_controller()`](#c-spi_register_controller); and (after
errors adding the device) calling `spi_controller_put()` to prevent a memory
leak.

**Return**

the SPI controller structure on success, else NULL.

#### <a id="c-__devm_spi_alloc_controller"></a>`__devm_spi_alloc_controller()`

```c
struct spi_controller * __devm_spi_alloc_controller(struct device *dev, unsigned int size, bool target)
```

resource-managed [`__spi_alloc_controller()`](#c-__spi_alloc_controller)

**Parameters**

- `struct device *dev`: physical device of SPI controller
- `unsigned int size`: how much zeroed driver-private data to allocate
- `bool target`: whether to allocate an SPI host (false) or SPI target (true) controller

**Context**

can sleep

**Description**

Allocate an SPI controller and automatically release a reference on it
when **dev** is unbound from its driver.  Drivers are thus relieved from
having to call `spi_controller_put()`.

The arguments to this function are identical to [`__spi_alloc_controller()`](#c-__spi_alloc_controller).

**Return**

the SPI controller structure on success, else NULL.

#### <a id="c-spi_register_controller"></a>`spi_register_controller()`

```c
int spi_register_controller(struct spi_controller *ctlr)
```

register SPI host or target controller

**Parameters**

- `struct spi_controller *ctlr`: initialized controller, originally from `spi_alloc_host()` or
  `spi_alloc_target()`

**Context**

can sleep

**Description**

SPI controllers connect to their drivers using some non-SPI bus,
such as the platform bus.  The final stage of `probe()` in that code
includes calling [`spi_register_controller()`](#c-spi_register_controller) to hook up to this SPI bus glue.

SPI controllers use board specific (often SOC specific) bus numbers,
and board-specific addressing for SPI devices combines those numbers
with chip select numbers.  Since SPI does not directly support dynamic
device identification, boards need configuration tables telling which
chip is at which address.

This must be called from context that can sleep.  It returns zero on
success, else a negative error code (dropping the controller's refcount).
After a successful return, the caller is responsible for calling
[`spi_unregister_controller()`](#c-spi_unregister_controller).

**Return**

zero on success, else a negative error code.

#### <a id="c-devm_spi_register_controller"></a>`devm_spi_register_controller()`

```c
int devm_spi_register_controller(struct device *dev, struct spi_controller *ctlr)
```

register managed SPI host or target controller

**Parameters**

- `struct device *dev`: device managing SPI controller
- `struct spi_controller *ctlr`: initialized controller, originally from `spi_alloc_host()` or
  `spi_alloc_target()`

**Context**

can sleep

**Description**

Register a SPI device as with [`spi_register_controller()`](#c-spi_register_controller) which will
automatically be unregistered and freed.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_unregister_controller"></a>`spi_unregister_controller()`

```c
void spi_unregister_controller(struct spi_controller *ctlr)
```

unregister SPI host or target controller

**Parameters**

- `struct spi_controller *ctlr`: the controller being unregistered

**Context**

can sleep

**Description**

This call is used only by SPI controller drivers, which are the
only ones directly touching chip registers.

This must be called from context that can sleep.

Note that this function also drops a reference to the controller.

#### <a id="c-spi_split_transfers_maxsize"></a>`spi_split_transfers_maxsize()`

```c
int spi_split_transfers_maxsize(struct spi_controller *ctlr, struct spi_message *msg, size_t maxsize)
```

split spi transfers into multiple transfers when an individual transfer exceeds a certain size

**Parameters**

- `struct spi_controller *ctlr`: the **spi_controller** for this transfer
- `struct spi_message *msg`: the **spi_message** to transform
- `size_t maxsize`: the maximum when to apply this

**Description**

This function allocates resources that are automatically freed during the
spi message unoptimize phase so this function should only be called from
optimize_message callbacks.

**Return**

status of transformation

#### <a id="c-spi_split_transfers_maxwords"></a>`spi_split_transfers_maxwords()`

```c
int spi_split_transfers_maxwords(struct spi_controller *ctlr, struct spi_message *msg, size_t maxwords)
```

split SPI transfers into multiple transfers when an individual transfer exceeds a certain number of SPI words

**Parameters**

- `struct spi_controller *ctlr`: the **spi_controller** for this transfer
- `struct spi_message *msg`: the **spi_message** to transform
- `size_t maxwords`: the number of words to limit each transfer to

**Description**

This function allocates resources that are automatically freed during the
spi message unoptimize phase so this function should only be called from
optimize_message callbacks.

**Return**

status of transformation

#### <a id="c-spi_setup"></a>`spi_setup()`

```c
int spi_setup(struct spi_device *spi)
```

setup SPI mode and clock rate

**Parameters**

- `struct spi_device *spi`: the device whose settings are being modified

**Context**

can sleep, and no requests are queued to the device

**Description**

SPI protocol drivers may need to update the transfer mode if the
device doesn't work with its default.  They may likewise need
to update clock rates or word sizes from initial values.  This function
changes those settings, and must be called from a context that can sleep.
Except for SPI_CS_HIGH, which takes effect immediately, the changes take
effect the next time the device is selected and data is transferred to
or from it.  When this function returns, the SPI device is deselected.

Note that this call will fail if the protocol driver specifies an option
that the underlying controller or its driver does not support.  For
example, not all hardware supports wire transfers using nine bit words,
LSB-first wire encoding, or active-high chipselects.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_optimize_message"></a>`spi_optimize_message()`

```c
int spi_optimize_message(struct spi_device *spi, struct spi_message *msg)
```

do any one-time validation and setup for a SPI message

**Parameters**

- `struct spi_device *spi`: the device that will be used for the message
- `struct spi_message *msg`: the message to optimize

**Description**

Peripheral drivers that reuse the same message repeatedly may call this to
perform as much message prep as possible once, rather than repeating it each
time a message transfer is performed to improve throughput and reduce CPU
usage.

Once a message has been optimized, it cannot be modified with the exception
of updating the contents of any xfer->tx_buf (the pointer can't be changed,
only the data in the memory it points to).

Calls to this function must be balanced with calls to [`spi_unoptimize_message()`](#c-spi_unoptimize_message)
to avoid leaking resources.

**Context**

can sleep

**Return**

zero on success, else a negative error code

#### <a id="c-spi_unoptimize_message"></a>`spi_unoptimize_message()`

```c
void spi_unoptimize_message(struct spi_message *msg)
```

releases any resources allocated by [`spi_optimize_message()`](#c-spi_optimize_message)

**Parameters**

- `struct spi_message *msg`: the message to unoptimize

**Description**

Calls to this function must be balanced with calls to [`spi_optimize_message()`](#c-spi_optimize_message).

**Context**

can sleep

#### <a id="c-devm_spi_optimize_message"></a>`devm_spi_optimize_message()`

```c
int devm_spi_optimize_message(struct device *dev, struct spi_device *spi, struct spi_message *msg)
```

managed version of [`spi_optimize_message()`](#c-spi_optimize_message)

**Parameters**

- `struct device *dev`: the device that manages **msg** (usually **spi->dev**)
- `struct spi_device *spi`: the device that will be used for the message
- `struct spi_message *msg`: the message to optimize

**Return**

zero on success, else a negative error code

**Description**

[`spi_unoptimize_message()`](#c-spi_unoptimize_message) will automatically be called when the device is
removed.

#### <a id="c-spi_async"></a>`spi_async()`

```c
int spi_async(struct spi_device *spi, struct spi_message *message)
```

asynchronous SPI transfer

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `struct spi_message *message`: describes the data transfers, including completion callback

**Context**

any (IRQs may be blocked, etc)

**Description**

This call may be used in_irq and other contexts which can't sleep,
as well as from task contexts which can sleep.

The completion callback is invoked in a context which can't sleep.
Before that invocation, the value of message->status is undefined.
When the callback is issued, message->status holds either zero (to
indicate complete success) or a negative error code.  After that
callback returns, the driver which issued the transfer request may
deallocate the associated memory; it's no longer in use by any SPI
core or controller driver code.

Note that although all messages to a spi_device are handled in
FIFO order, messages may go to different devices in other orders.
Some device might be higher priority, or have various "hard" access
time requirements, for example.

On detection of any fault during the transfer, processing of
the entire message is aborted, and the device is deselected.
Until returning from the associated message completion callback,
no other spi_message queued to that device will be processed.
(This rule applies equally to all the synchronous transfer calls,
which are wrappers around this core asynchronous primitive.)

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_sync"></a>`spi_sync()`

```c
int spi_sync(struct spi_device *spi, struct spi_message *message)
```

blocking/synchronous SPI data transfers

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `struct spi_message *message`: describes the data transfers

**Context**

can sleep

**Description**

This call may only be used from a context that may sleep.  The sleep
is non-interruptible, and has no timeout.  Low-overhead controller
drivers may DMA directly into and out of the message buffers.

Note that the SPI device's chip select is active during the message,
and then is normally disabled between messages.  Drivers for some
frequently-used devices may want to minimize costs of selecting a chip,
by leaving it selected in anticipation that the next message will go
to the same chip.  (That may increase power usage.)

Also, the caller is guaranteeing that the memory associated with the
message will not be freed before this call returns.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_sync_locked"></a>`spi_sync_locked()`

```c
int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
```

version of spi_sync with exclusive bus usage

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `struct spi_message *message`: describes the data transfers

**Context**

can sleep

**Description**

This call may only be used from a context that may sleep.  The sleep
is non-interruptible, and has no timeout.  Low-overhead controller
drivers may DMA directly into and out of the message buffers.

This call should be used by drivers that require exclusive access to the
SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
be released by a spi_bus_unlock call when the exclusive access is over.

**Return**

zero on success, else a negative error code.

#### <a id="c-spi_bus_lock"></a>`spi_bus_lock()`

```c
int spi_bus_lock(struct spi_controller *ctlr)
```

obtain a lock for exclusive SPI bus usage

**Parameters**

- `struct spi_controller *ctlr`: SPI bus controller that should be locked for exclusive bus access

**Context**

can sleep

**Description**

This call may only be used from a context that may sleep.  The sleep
is non-interruptible, and has no timeout.

This call should be used by drivers that require exclusive access to the
SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
exclusive access is over. Data transfer must be done by spi_sync_locked
and spi_async_locked calls when the SPI bus lock is held.

**Return**

always zero.

#### <a id="c-spi_bus_unlock"></a>`spi_bus_unlock()`

```c
int spi_bus_unlock(struct spi_controller *ctlr)
```

release the lock for exclusive SPI bus usage

**Parameters**

- `struct spi_controller *ctlr`: SPI bus controller that was locked for exclusive bus access

**Context**

can sleep

**Description**

This call may only be used from a context that may sleep.  The sleep
is non-interruptible, and has no timeout.

This call releases an SPI bus lock previously obtained by an spi_bus_lock
call.

**Return**

always zero.

#### <a id="c-spi_write_then_read"></a>`spi_write_then_read()`

```c
int spi_write_then_read(struct spi_device *spi, const void *txbuf, unsigned n_tx, void *rxbuf, unsigned n_rx)
```

SPI synchronous write followed by read

**Parameters**

- `struct spi_device *spi`: device with which data will be exchanged
- `const void *txbuf`: data to be written (need not be DMA-safe)
- `unsigned n_tx`: size of txbuf, in bytes
- `void *rxbuf`: buffer into which data will be read (need not be DMA-safe)
- `unsigned n_rx`: size of rxbuf, in bytes

**Context**

can sleep

**Description**

This performs a half duplex MicroWire style transaction with the
device, sending txbuf and then reading rxbuf.  The return value
is zero for success, else a negative errno status code.
This call may only be used from a context that may sleep.

Parameters to this routine are always copied using a small buffer.
Performance-sensitive or bulk transfer code should instead use
spi_{async,sync}() calls with DMA-safe buffers.

**Return**

zero on success, else a negative error code.

---

# Linux Switchtec Support

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> Microsemi's "Switchtec" line of PCI switch devices is already supported by the kernel with standard PCI switch drivers. However, the Switchtec device advertises a special management endpoint which enables some additional functionality.…

<a id="rst-linux-switchtec-support"></a>

Microsemi's "Switchtec" line of PCI switch devices is already supported by the kernel with standard PCI switch drivers. However, the Switchtec device advertises a special management endpoint which enables some additional functionality. This includes:

- Packet and Byte Counters

- Firmware Upgrades

- Event and Error logs

- Querying port link status

- Custom user firmware commands

The switchtec kernel module implements this functionality.

<a id="rst-interface"></a>

## Interface

The primary means of communicating with the Switchtec management firmware is through the Memory-mapped Remote Procedure Call (MRPC) interface. Commands are submitted to the interface with a 4-byte command identifier and up to 1KB of command specific data. The firmware will respond with a 4-byte return code and up to 1KB of command-specific data. The interface only processes a single command at a time.

<a id="rst-userspace-interface"></a>

## Userspace Interface

The MRPC interface will be exposed to userspace through a simple char device: /dev/switchtec\#, one for each management endpoint in the system.

The char device has the following semantics:

- A write must consist of at least 4 bytes and no more than 1028 bytes. The first 4 bytes will be interpreted as the Command ID and the remainder will be used as the input data. A write will send the command to the firmware to begin processing.

- Each write must be followed by exactly one read. Any double write will produce an error and any read that doesn't follow a write will produce an error.

- A read will block until the firmware completes the command and return the 4-byte Command Return Value plus up to 1024 bytes of output data. (The length will be specified by the size parameter of the read call -- reading less than 4 bytes will produce an error.)

- The poll call will also be supported for userspace applications that need to do other things while waiting for the command to complete.

The following IOCTLs are also supported by the device:

- SWITCHTEC_IOCTL_FLASH_INFO - Retrieve firmware length and number of partitions in the device.

- SWITCHTEC_IOCTL_FLASH_PART_INFO - Retrieve address and lengeth for any specified partition in flash.

- SWITCHTEC_IOCTL_EVENT_SUMMARY - Read a structure of bitmaps indicating all uncleared events.

- SWITCHTEC_IOCTL_EVENT_CTL - Get the current count, clear and set flags for any event. This ioctl takes in a switchtec_ioctl_event_ctl struct with the event_id, index and flags set (index being the partition or PFF number for non-global events). It returns whether the event has occurred, the number of times and any event specific data. The flags can be used to clear the count or enable and disable actions to happen when the event occurs. By using the SWITCHTEC_IOCTL_EVENT_FLAG_EN_POLL flag, you can set an event to trigger a poll command to return with POLLPRI. In this way, userspace can wait for events to occur.

- SWITCHTEC_IOCTL_PFF_TO_PORT and SWITCHTEC_IOCTL_PORT_TO_PFF convert between PCI Function Framework number (used by the event system) and Switchtec Logic Port ID and Partition number (which is more user friendly).

<a id="rst-non-transparent-bridge-ntb-driver"></a>

## Non-Transparent Bridge (NTB) Driver

An NTB hardware driver is provided for the Switchtec hardware in ntb_hw_switchtec. Currently, it only supports switches configured with exactly 2 NT partitions and zero or more non-NT partitions. It also requires the following configuration settings:

- Both NT partitions must be able to access each other's GAS spaces. Thus, the bits in the GAS Access Vector under Management Settings must be set to support this.

- Kernel configuration MUST include support for NTB (CONFIG_NTB needs to be set)

NT EP BAR 2 will be dynamically configured as a Direct Window, and the configuration file does not need to configure it explicitly.

Please refer to [Documentation/driver-api/ntb.rst](/kernel/hardware/driver-api/buses/ntb.md) in Linux source tree for an overall understanding of the Linux NTB stack. ntb_hw_switchtec works as an NTB Hardware Driver in this stack.

---

# target and iSCSI Interfaces Guide

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> TBD

<a id="rst-target-and-iscsi-interfaces-guide"></a>

<a id="rst-introduction-and-overview"></a>

## Introduction and Overview

TBD

<a id="rst-target-core-device-interfaces"></a>

## Target core device interfaces

This section is blank because no kerneldoc comments have been added to drivers/target/target_core_device.c.

<a id="rst-target-core-transport-interfaces"></a>

## Target core transport interfaces


#### <a id="c-transport_init_session"></a>`transport_init_session()`

```c
void transport_init_session(struct se_session *se_sess)
```

initialize a session object

**Parameters**

- `struct se_session *se_sess`: Session object pointer.

**Description**

The caller must have zero-initialized **se_sess** before calling this function.

#### <a id="c-transport_alloc_session"></a>`transport_alloc_session()`

```c
struct se_session * transport_alloc_session(enum target_prot_op sup_prot_ops)
```

allocate a session object and initialize it

**Parameters**

- `enum target_prot_op sup_prot_ops`: bitmask that defines which T10-PI modes are supported.

#### <a id="c-transport_alloc_session_tags"></a>`transport_alloc_session_tags()`

```c
int transport_alloc_session_tags(struct se_session *se_sess, unsigned int tag_num, unsigned int tag_size)
```

allocate target driver private data

**Parameters**

- `struct se_session *se_sess`: Session pointer.
- `unsigned int tag_num`: Maximum number of in-flight commands between initiator and target.
- `unsigned int tag_size`: Size in bytes of the private data a target driver associates with
  each command.

#### <a id="c-target_init_cmd"></a>`target_init_cmd()`

```c
int target_init_cmd(struct se_cmd *se_cmd, struct se_session *se_sess, unsigned char *sense, u64 unpacked_lun, u32 data_length, int task_attr, int data_dir, int flags)
```

initialize se_cmd

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to init
- `struct se_session *se_sess`: associated se_sess for endpoint
- `unsigned char *sense`: pointer to SCSI sense buffer
- `u64 unpacked_lun`: unpacked LUN to reference for struct se_lun
- `u32 data_length`: fabric expected data transfer length
- `int task_attr`: SAM task attribute
- `int data_dir`: DMA data direction
- `int flags`: flags for command submission from target_sc_flags_tables

**Description**

Task tags are supported if the caller has set **se_cmd->tag**.

If the fabric driver calls target_stop_session, then it must check the
return code and handle failures. This will never fail for other drivers,
and the return code can be ignored.

**Return**

- less than zero to signal active I/O shutdown failure.
- zero on success.

#### <a id="c-target_submit_prep"></a>`target_submit_prep()`

```c
int target_submit_prep(struct se_cmd *se_cmd, unsigned char *cdb, struct scatterlist *sgl, u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count, struct scatterlist *sgl_prot, u32 sgl_prot_count, gfp_t gfp)
```

prepare cmd for submission

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to prep
- `unsigned char *cdb`: pointer to SCSI CDB
- `struct scatterlist *sgl`: struct scatterlist memory for unidirectional mapping
- `u32 sgl_count`: scatterlist count for unidirectional mapping
- `struct scatterlist *sgl_bidi`: struct scatterlist memory for bidirectional READ mapping
- `u32 sgl_bidi_count`: scatterlist count for bidirectional READ mapping
- `struct scatterlist *sgl_prot`: struct scatterlist memory protection information
- `u32 sgl_prot_count`: scatterlist count for protection information
- `gfp_t gfp`: gfp allocation type

**Return**

- less than zero to signal failure.
- zero on success.

**Description**

If failure is returned, lio will the callers queue_status to complete
the cmd.

#### <a id="c-target_submit_cmd"></a>`target_submit_cmd()`

```c
void target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess, unsigned char *cdb, unsigned char *sense, u64 unpacked_lun, u32 data_length, int task_attr, int data_dir, int flags)
```

lookup unpacked lun and submit uninitialized se_cmd

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to submit
- `struct se_session *se_sess`: associated se_sess for endpoint
- `unsigned char *cdb`: pointer to SCSI CDB
- `unsigned char *sense`: pointer to SCSI sense buffer
- `u64 unpacked_lun`: unpacked LUN to reference for struct se_lun
- `u32 data_length`: fabric expected data transfer length
- `int task_attr`: SAM task attribute
- `int data_dir`: DMA data direction
- `int flags`: flags for command submission from target_sc_flags_tables

**Description**

Task tags are supported if the caller has set **se_cmd->tag**.

This may only be called from process context, and also currently
assumes internal allocation of fabric payload buffer by target-core.

It also assumes interal target core SGL memory allocation.

This function must only be used by drivers that do their own
sync during shutdown and does not use target_stop_session. If there
is a failure this function will call into the fabric driver's
queue_status with a CHECK_CONDITION.

#### <a id="c-target_submit"></a>`target_submit()`

```c
int target_submit(struct se_cmd *se_cmd)
```

perform final initialization and submit cmd to LIO core

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to submit

**Description**

target_submit_prep or something similar must have been called on the cmd,
and this must be called from process context.

#### <a id="c-target_submit_tmr"></a>`target_submit_tmr()`

```c
int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess, unsigned char *sense, u64 unpacked_lun, void *fabric_tmr_ptr, unsigned char tm_type, gfp_t gfp, u64 tag, int flags)
```

lookup unpacked lun and submit uninitialized se_cmd for TMR CDBs

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to submit
- `struct se_session *se_sess`: associated se_sess for endpoint
- `unsigned char *sense`: pointer to SCSI sense buffer
- `u64 unpacked_lun`: unpacked LUN to reference for struct se_lun
- `void *fabric_tmr_ptr`: fabric context for TMR req
- `unsigned char tm_type`: Type of TM request
- `gfp_t gfp`: gfp type for caller
- `u64 tag`: referenced task tag for TMR_ABORT_TASK
- `int flags`: submit cmd flags

**Description**

Callable from all contexts.

#### <a id="c-target_get_sess_cmd"></a>`target_get_sess_cmd()`

```c
int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref)
```

Verify the session is accepting cmds and take ref

**Parameters**

- `struct se_cmd *se_cmd`: command descriptor to add
- `bool ack_kref`: Signal that fabric will perform an ack [`target_put_sess_cmd()`](#c-target_put_sess_cmd)

#### <a id="c-target_put_sess_cmd"></a>`target_put_sess_cmd()`

```c
int target_put_sess_cmd(struct se_cmd *se_cmd)
```

decrease the command reference count

**Parameters**

- `struct se_cmd *se_cmd`: command to drop a reference from

**Description**

Returns 1 if and only if this [`target_put_sess_cmd()`](#c-target_put_sess_cmd) call caused the
refcount to drop to zero. Returns zero otherwise.

#### <a id="c-target_stop_cmd_counter"></a>`target_stop_cmd_counter()`

```c
void target_stop_cmd_counter(struct target_cmd_counter *cmd_cnt)
```

Stop new IO from being added to the counter.

**Parameters**

- `struct target_cmd_counter *cmd_cnt`: counter to stop

#### <a id="c-target_stop_session"></a>`target_stop_session()`

```c
void target_stop_session(struct se_session *se_sess)
```

Stop new IO from being queued on the session.

**Parameters**

- `struct se_session *se_sess`: session to stop

#### <a id="c-target_wait_for_cmds"></a>`target_wait_for_cmds()`

```c
void target_wait_for_cmds(struct target_cmd_counter *cmd_cnt)
```

Wait for outstanding cmds.

**Parameters**

- `struct target_cmd_counter *cmd_cnt`: counter to wait for active I/O for.

#### <a id="c-target_wait_for_sess_cmds"></a>`target_wait_for_sess_cmds()`

```c
void target_wait_for_sess_cmds(struct se_session *se_sess)
```

Wait for outstanding commands

**Parameters**

- `struct se_session *se_sess`: session to wait for active I/O

#### <a id="c-transport_wait_for_tasks"></a>`transport_wait_for_tasks()`

```c
bool transport_wait_for_tasks(struct se_cmd *cmd)
```

set CMD_T_STOP and wait for t_transport_stop_comp

**Parameters**

- `struct se_cmd *cmd`: command to wait on

#### <a id="c-target_send_busy"></a>`target_send_busy()`

```c
int target_send_busy(struct se_cmd *cmd)
```

Send SCSI BUSY status back to the initiator

**Parameters**

- `struct se_cmd *cmd`: SCSI command for which to send a BUSY reply.

**Note**

Only call this function if target_submit_cmd*() failed.


<a id="rst-target-supported-userspace-i-o"></a>

## Target-supported userspace I/O


**Userspace I/O**

Define a shared-memory interface for LIO to pass SCSI commands and
data to userspace for processing. This is to allow backends that
are too complex for in-kernel support to be possible.

It uses the UIO framework to do a lot of the device-creation and
introspection work for us.

See the .h file for how the ring is laid out. Note that while the
command ring is defined, the particulars of the data area are
not. Offset values in the command entry point to other locations
internal to the mmap-ed area. There is separate space outside the
command ring for data buffers. This leaves maximum flexibility for
moving buffer allocations, or even page flipping or other
allocation techniques, without altering the command ring layout.

SECURITY:
The user process must be assumed to be malicious. There's no way to
prevent it breaking the command ring protocol if it wants, but in
order to prevent other issues we must only ever read *data* from
the shared memory area, not offsets or sizes. This applies to
command ring entries as well as the mailbox. Extra code needed for
this may have a 'UAM' comment.



**Ring Design**

The mmaped area is divided into three parts:
1) The mailbox (struct tcmu_mailbox, below);
2) The command ring;
3) Everything beyond the command ring (data).

The mailbox tells userspace the offset of the command ring from the
start of the shared memory region, and how big the command ring is.

The kernel passes SCSI commands to userspace by putting a struct
tcmu_cmd_entry in the ring, updating mailbox->cmd_head, and poking
userspace via UIO's interrupt mechanism.

tcmu_cmd_entry contains a header. If the header type is PAD,
userspace should skip hdr->length bytes (mod cmdr_size) to find the
next cmd_entry.

Otherwise, the entry will contain offsets into the mmaped area that
contain the cdb and data buffers -- the latter accessible via the
iov array. iov addresses are also offsets into the shared area.

When userspace is completed handling the command, set
entry->rsp.scsi_status, fill in rsp.sense_buffer if appropriate,
and also set mailbox->cmd_tail equal to the old cmd_tail plus
hdr->length, mod cmdr_size. If cmd_tail doesn't equal cmd_head, it
should process the next packet the same way, and so on.


<a id="rst-iscsi-helper-functions"></a>

## iSCSI helper functions


#### <a id="c-iscsi_prep_data_out_pdu"></a>`iscsi_prep_data_out_pdu()`

```c
void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t, struct iscsi_data *hdr)
```

initialize Data-Out

**Parameters**

- `struct iscsi_task *task`: scsi command task
- `struct iscsi_r2t_info *r2t`: R2T info
- `struct iscsi_data *hdr`: iscsi data in pdu

**Notes**

Initialize Data-Out within this R2T sequence and finds
proper data_offset within this SCSI command.

This function is called with connection lock taken.

#### <a id="c-__iscsi_put_task"></a>`__iscsi_put_task()`

```c
void __iscsi_put_task(struct iscsi_task *task)
```

drop the refcount on a task

**Parameters**

- `struct iscsi_task *task`: iscsi_task to drop the refcount on

**Description**

The back_lock must be held when calling in case it frees the task.

#### <a id="c-iscsi_complete_scsi_task"></a>`iscsi_complete_scsi_task()`

```c
void iscsi_complete_scsi_task(struct iscsi_task *task, uint32_t exp_cmdsn, uint32_t max_cmdsn)
```

finish scsi task normally

**Parameters**

- `struct iscsi_task *task`: iscsi task for scsi cmd
- `uint32_t exp_cmdsn`: expected cmd sn in cpu format
- `uint32_t max_cmdsn`: max cmd sn in cpu format

**Description**

This is used when drivers do not need or cannot perform
lower level pdu processing.

Called with session back_lock

#### <a id="c-iscsi_itt_to_task"></a>`iscsi_itt_to_task()`

```c
struct iscsi_task * iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt)
```

look up task by itt

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection
- `itt_t itt`: itt

**Description**

This should be used for mgmt tasks like login and nops, or if
the LDD's itt space does not include the session age.

The session back_lock must be held.

#### <a id="c-__iscsi_complete_pdu"></a>`__iscsi_complete_pdu()`

```c
int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, int datalen)
```

complete pdu

**Parameters**

- `struct iscsi_conn *conn`: iscsi conn
- `struct iscsi_hdr *hdr`: iscsi header
- `char *data`: data buffer
- `int datalen`: len of data buffer

**Description**

Completes pdu processing by freeing any resources allocated at
queuecommand or send generic. session back_lock must be held and verify
itt must have been called.

#### <a id="c-iscsi_itt_to_ctask"></a>`iscsi_itt_to_ctask()`

```c
struct iscsi_task * iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt)
```

look up ctask by itt

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection
- `itt_t itt`: itt

**Description**

This should be used for cmd tasks.

The session back_lock must be held.

#### <a id="c-iscsi_requeue_task"></a>`iscsi_requeue_task()`

```c
void iscsi_requeue_task(struct iscsi_task *task)
```

requeue task to run from session workqueue

**Parameters**

- `struct iscsi_task *task`: task to requeue

**Description**

Callers must have taken a ref to the task that is going to be requeued.

#### <a id="c-iscsi_suspend_queue"></a>`iscsi_suspend_queue()`

```c
void iscsi_suspend_queue(struct iscsi_conn *conn)
```

suspend iscsi_queuecommand

**Parameters**

- `struct iscsi_conn *conn`: iscsi conn to stop queueing IO on

**Description**

This grabs the session frwd_lock to make sure no one is in
xmit_task/queuecommand, and then sets suspend to prevent
new commands from being queued. This only needs to be called
by offload drivers that need to sync a path like ep disconnect
with the iscsi_queuecommand/xmit_task. To start IO again libiscsi
will call iscsi_start_tx and iscsi_unblock_session when in FFP.

#### <a id="c-iscsi_suspend_tx"></a>`iscsi_suspend_tx()`

```c
void iscsi_suspend_tx(struct iscsi_conn *conn)
```

suspend iscsi_data_xmit

**Parameters**

- `struct iscsi_conn *conn`: iscsi conn to stop processing IO on.

**Description**

This function sets the suspend bit to prevent iscsi_data_xmit
from sending new IO, and if work is queued on the xmit thread
it will wait for it to be completed.

#### <a id="c-iscsi_suspend_rx"></a>`iscsi_suspend_rx()`

```c
void iscsi_suspend_rx(struct iscsi_conn *conn)
```

Prevent recvwork from running again.

**Parameters**

- `struct iscsi_conn *conn`: iscsi conn to stop.

#### <a id="c-iscsi_conn_unbind"></a>`iscsi_conn_unbind()`

```c
void iscsi_conn_unbind(struct iscsi_cls_conn *cls_conn, bool is_active)
```

prevent queueing to conn.

**Parameters**

- `struct iscsi_cls_conn *cls_conn`: iscsi conn ep is bound to.
- `bool is_active`: is the conn in use for boot or is this for EH/termination

**Description**

This must be called by drivers implementing the ep_disconnect callout.
It disables queueing to the connection from libiscsi in preparation for
an ep_disconnect call.

#### <a id="c-iscsi_eh_session_reset"></a>`iscsi_eh_session_reset()`

```c
int iscsi_eh_session_reset(struct scsi_cmnd *sc)
```

drop session and attempt relogin

**Parameters**

- `struct scsi_cmnd *sc`: scsi command

**Description**

This function will wait for a relogin, session termination from
userspace, or a recovery/replacement timeout.

#### <a id="c-iscsi_eh_recover_target"></a>`iscsi_eh_recover_target()`

```c
int iscsi_eh_recover_target(struct scsi_cmnd *sc)
```

reset target and possibly the session

**Parameters**

- `struct scsi_cmnd *sc`: scsi command

**Description**

This will attempt to send a warm target reset. If that fails,
we will escalate to ERL0 session recovery.

#### <a id="c-iscsi_host_add"></a>`iscsi_host_add()`

```c
int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev)
```

add host to system

**Parameters**

- `struct Scsi_Host *shost`: scsi host
- `struct device *pdev`: parent device

**Description**

This should be called by partial offload and software iscsi drivers
to add a host to the system.

#### <a id="c-iscsi_host_alloc"></a>`iscsi_host_alloc()`

```c
struct Scsi_Host * iscsi_host_alloc(const struct scsi_host_template *sht, int dd_data_size, bool xmit_can_sleep)
```

allocate a host and driver data

**Parameters**

- `const struct scsi_host_template *sht`: scsi host template
- `int dd_data_size`: driver host data size
- `bool xmit_can_sleep`: bool indicating if LLD will queue IO from a work queue

**Description**

This should be called by partial offload and software iscsi drivers.
To access the driver specific memory use the `iscsi_host_priv()` macro.

#### <a id="c-iscsi_host_remove"></a>`iscsi_host_remove()`

```c
void iscsi_host_remove(struct Scsi_Host *shost, bool is_shutdown)
```

remove host and sessions

**Parameters**

- `struct Scsi_Host *shost`: scsi host
- `bool is_shutdown`: true if called from a driver shutdown callout

**Description**

If there are any sessions left, this will initiate the removal and wait
for the completion.

#### <a id="c-iscsi_session_setup"></a>`iscsi_session_setup()`

```c
struct iscsi_cls_session * iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost, uint16_t cmds_max, int dd_size, int cmd_task_size, uint32_t initial_cmdsn, unsigned int id)
```

create iscsi cls session and host and session

**Parameters**

- `struct iscsi_transport *iscsit`: iscsi transport template
- `struct Scsi_Host *shost`: scsi host
- `uint16_t cmds_max`: session can queue
- `int dd_size`: private driver data size, added to session allocation size
- `int cmd_task_size`: LLD task private data size
- `uint32_t initial_cmdsn`: initial CmdSN
- `unsigned int id`: target ID to add to this session

**Description**

This can be used by software iscsi_transports that allocate
a session per scsi host.

Callers should set cmds_max to the largest total numer (mgmt + scsi) of
tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks
for nop handling and login/logout requests.

#### <a id="c-iscsi_session_free"></a>`iscsi_session_free()`

```c
void iscsi_session_free(struct iscsi_cls_session *cls_session)
```

Free iscsi session and it's resources

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi session

#### <a id="c-iscsi_session_teardown"></a>`iscsi_session_teardown()`

```c
void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
```

destroy session and cls_session

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi session

#### <a id="c-iscsi_conn_setup"></a>`iscsi_conn_setup()`

```c
struct iscsi_cls_conn * iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, uint32_t conn_idx)
```

create iscsi_cls_conn and iscsi_conn

**Parameters**

- `struct iscsi_cls_session *cls_session`: iscsi_cls_session
- `int dd_size`: private driver data size
- `uint32_t conn_idx`: cid

#### <a id="c-iscsi_conn_teardown"></a>`iscsi_conn_teardown()`

```c
void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
```

teardown iscsi connection

**Parameters**

- `struct iscsi_cls_conn *cls_conn`: iscsi class connection

**Description**

TODO: we may need to make this into a two step process
like scsi-mls remove + put host


<a id="rst-iscsi-boot-information"></a>

## iSCSI boot information


#### <a id="c-iscsi_boot_create_target"></a>`iscsi_boot_create_target()`

```c
struct iscsi_boot_kobj * iscsi_boot_create_target(struct iscsi_boot_kset *boot_kset, int index, void *data, ssize_t (*show) (void *data, int type, char *buf), umode_t (*is_visible) (void *data, int type), void (*release) (void *data))
```

create boot target sysfs dir

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset
- `int index`: the target id
- `void *data`: driver specific data for target
- `ssize_t (*show) (void *data, int type, char *buf)`: attr show function
- `umode_t (*is_visible) (void *data, int type)`: attr visibility function
- `void (*release) (void *data)`: release function

**Note**

The boot sysfs lib will free the data passed in for the caller
when all refs to the target kobject have been released.

#### <a id="c-iscsi_boot_create_initiator"></a>`iscsi_boot_create_initiator()`

```c
struct iscsi_boot_kobj * iscsi_boot_create_initiator(struct iscsi_boot_kset *boot_kset, int index, void *data, ssize_t (*show) (void *data, int type, char *buf), umode_t (*is_visible) (void *data, int type), void (*release) (void *data))
```

create boot initiator sysfs dir

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset
- `int index`: the initiator id
- `void *data`: driver specific data
- `ssize_t (*show) (void *data, int type, char *buf)`: attr show function
- `umode_t (*is_visible) (void *data, int type)`: attr visibility function
- `void (*release) (void *data)`: release function

**Note**

The boot sysfs lib will free the data passed in for the caller
when all refs to the initiator kobject have been released.

#### <a id="c-iscsi_boot_create_ethernet"></a>`iscsi_boot_create_ethernet()`

```c
struct iscsi_boot_kobj * iscsi_boot_create_ethernet(struct iscsi_boot_kset *boot_kset, int index, void *data, ssize_t (*show) (void *data, int type, char *buf), umode_t (*is_visible) (void *data, int type), void (*release) (void *data))
```

create boot ethernet sysfs dir

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset
- `int index`: the ethernet device id
- `void *data`: driver specific data
- `ssize_t (*show) (void *data, int type, char *buf)`: attr show function
- `umode_t (*is_visible) (void *data, int type)`: attr visibility function
- `void (*release) (void *data)`: release function

**Note**

The boot sysfs lib will free the data passed in for the caller
when all refs to the ethernet kobject have been released.

#### <a id="c-iscsi_boot_create_acpitbl"></a>`iscsi_boot_create_acpitbl()`

```c
struct iscsi_boot_kobj * iscsi_boot_create_acpitbl(struct iscsi_boot_kset *boot_kset, int index, void *data, ssize_t (*show)(void *data, int type, char *buf), umode_t (*is_visible)(void *data, int type), void (*release)(void *data))
```

create boot acpi table sysfs dir

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset
- `int index`: not used
- `void *data`: driver specific data
- `ssize_t (*show)(void *data, int type, char *buf)`: attr show function
- `umode_t (*is_visible)(void *data, int type)`: attr visibility function
- `void (*release)(void *data)`: release function

**Note**

The boot sysfs lib will free the data passed in for the caller
when all refs to the acpitbl kobject have been released.

#### <a id="c-iscsi_boot_create_kset"></a>`iscsi_boot_create_kset()`

```c
struct iscsi_boot_kset * iscsi_boot_create_kset(const char *set_name)
```

creates root sysfs tree

**Parameters**

- `const char *set_name`: name of root dir

#### <a id="c-iscsi_boot_create_host_kset"></a>`iscsi_boot_create_host_kset()`

```c
struct iscsi_boot_kset * iscsi_boot_create_host_kset(unsigned int hostno)
```

creates root sysfs tree for a scsi host

**Parameters**

- `unsigned int hostno`: host number of scsi host

#### <a id="c-iscsi_boot_destroy_kset"></a>`iscsi_boot_destroy_kset()`

```c
void iscsi_boot_destroy_kset(struct iscsi_boot_kset *boot_kset)
```

destroy kset and kobjects under it

**Parameters**

- `struct iscsi_boot_kset *boot_kset`: boot kset

**Description**

This will remove the kset and kobjects and attrs under it.


<a id="rst-iscsi-tcp-interfaces"></a>

## iSCSI TCP interfaces


#### <a id="c-iscsi_sw_tcp_recv"></a>`iscsi_sw_tcp_recv()`

```c
int iscsi_sw_tcp_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, unsigned int offset, size_t len)
```

TCP receive in sendfile fashion

**Parameters**

- `read_descriptor_t *rd_desc`: read descriptor
- `struct sk_buff *skb`: socket buffer
- `unsigned int offset`: offset in skb
- `size_t len`: skb->len - offset

#### <a id="c-iscsi_sw_sk_state_check"></a>`iscsi_sw_sk_state_check()`

```c
int iscsi_sw_sk_state_check(struct sock *sk)
```

check socket state

**Parameters**

- `struct sock *sk`: socket

**Description**

If the socket is in CLOSE or CLOSE_WAIT we should
not close the connection if there is still some
data pending.

Must be called with sk_callback_lock.

#### <a id="c-iscsi_sw_tcp_write_space"></a>`iscsi_sw_tcp_write_space()`

```c
void iscsi_sw_tcp_write_space(struct sock *sk)
```

Called when more output buffer space is available

**Parameters**

- `struct sock *sk`: socket space is available for

#### <a id="c-iscsi_sw_tcp_xmit_segment"></a>`iscsi_sw_tcp_xmit_segment()`

```c
int iscsi_sw_tcp_xmit_segment(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment)
```

transmit segment

**Parameters**

- `struct iscsi_tcp_conn *tcp_conn`: the iSCSI TCP connection
- `struct iscsi_segment *segment`: the buffer to transmnit

**Description**

This function transmits as much of the buffer as
the network layer will accept, and returns the number of
bytes transmitted.

If CRC hashing is enabled, the function will compute the
hash as it goes. When the entire segment has been transmitted,
it will retrieve the hash value and send it as well.

#### <a id="c-iscsi_sw_tcp_xmit"></a>`iscsi_sw_tcp_xmit()`

```c
int iscsi_sw_tcp_xmit(struct iscsi_conn *conn)
```

TCP transmit

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection

#### <a id="c-iscsi_sw_tcp_xmit_qlen"></a>`iscsi_sw_tcp_xmit_qlen()`

```c
int iscsi_sw_tcp_xmit_qlen(struct iscsi_conn *conn)
```

return the number of bytes queued for xmit

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection



#### <a id="c-iscsi_tcp_segment_done"></a>`iscsi_tcp_segment_done()`

```c
int iscsi_tcp_segment_done(struct iscsi_tcp_conn *tcp_conn, struct iscsi_segment *segment, int recv, unsigned copied)
```

check whether the segment is complete

**Parameters**

- `struct iscsi_tcp_conn *tcp_conn`: iscsi tcp connection
- `struct iscsi_segment *segment`: iscsi segment to check
- `int recv`: set to one of this is called from the recv path
- `unsigned copied`: number of bytes copied

**Description**

Check if we're done receiving this segment. If the receive
buffer is full but we expect more data, move on to the
next entry in the scatterlist.

If the amount of data we received isn't a multiple of 4,
we will transparently receive the pad bytes, too.

This function must be re-entrant.

#### <a id="c-iscsi_tcp_hdr_recv_prep"></a>`iscsi_tcp_hdr_recv_prep()`

```c
void iscsi_tcp_hdr_recv_prep(struct iscsi_tcp_conn *tcp_conn)
```

prep segment for hdr reception

**Parameters**

- `struct iscsi_tcp_conn *tcp_conn`: iscsi connection to prep for

**Description**

This function always passes NULL for the crcp argument, because when this
function is called we do not yet know the final size of the header and want
to delay the digest processing until we know that.

#### <a id="c-iscsi_tcp_cleanup_task"></a>`iscsi_tcp_cleanup_task()`

```c
void iscsi_tcp_cleanup_task(struct iscsi_task *task)
```

free tcp_task resources

**Parameters**

- `struct iscsi_task *task`: iscsi task

**Description**

must be called with session back_lock

#### <a id="c-iscsi_tcp_recv_segment_is_hdr"></a>`iscsi_tcp_recv_segment_is_hdr()`

```c
int iscsi_tcp_recv_segment_is_hdr(struct iscsi_tcp_conn *tcp_conn)
```

tests if we are reading in a header

**Parameters**

- `struct iscsi_tcp_conn *tcp_conn`: iscsi tcp conn

**Description**

returns non zero if we are currently processing or setup to process
a header.

#### <a id="c-iscsi_tcp_recv_skb"></a>`iscsi_tcp_recv_skb()`

```c
int iscsi_tcp_recv_skb(struct iscsi_conn *conn, struct sk_buff *skb, unsigned int offset, bool offloaded, int *status)
```

Process skb

**Parameters**

- `struct iscsi_conn *conn`: iscsi connection
- `struct sk_buff *skb`: network buffer with header and/or data segment
- `unsigned int offset`: offset in skb
- `bool offloaded`: bool indicating if transfer was offloaded
- `int *status`: iscsi TCP status result

**Description**

Will return status of transfer in **status**. And will return
number of bytes copied.

#### <a id="c-iscsi_tcp_task_init"></a>`iscsi_tcp_task_init()`

```c
int iscsi_tcp_task_init(struct iscsi_task *task)
```

Initialize iSCSI SCSI_READ or SCSI_WRITE commands

**Parameters**

- `struct iscsi_task *task`: scsi command task

#### <a id="c-iscsi_tcp_task_xmit"></a>`iscsi_tcp_task_xmit()`

```c
int iscsi_tcp_task_xmit(struct iscsi_task *task)
```

xmit normal PDU task

**Parameters**

- `struct iscsi_task *task`: iscsi command task

**Description**

We're expected to return 0 when everything was transmitted successfully,
-EAGAIN if there's still data in the queue, or != 0 for any other kind
of error.

---

# VME Device Drivers

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> As with other subsystems within the Linux kernel, VME device drivers register with the VME subsystem, typically called from the devices init routine. This is achieved via a call to vme_register_driver().

<a id="rst-vme-device-drivers"></a>

<a id="rst-driver-registration"></a>

## Driver registration

As with other subsystems within the Linux kernel, VME device drivers register with the VME subsystem, typically called from the devices init routine.  This is achieved via a call to `vme_register_driver()`.

A pointer to a structure of type `struct vme_driver <vme_driver>` must be provided to the registration function. Along with the maximum number of devices your driver is able to support.

At the minimum, the '.name', '.match' and '.probe' elements of `struct vme_driver <vme_driver>` should be correctly set. The '.name' element is a pointer to a string holding the device driver's name.

The '.match' function allows control over which VME devices should be registered with the driver. The match function should return 1 if a device should be probed and 0 otherwise. This example match function (from vme_user.c) limits the number of devices probed to one:



```c
#define USER_BUS_MAX    1
...
static int vme_user_match(struct vme_dev *vdev)
{
        if (vdev->id.num >= USER_BUS_MAX)
                return 0;
        return 1;
}
```

The '.probe' element should contain a pointer to the probe routine. The probe routine is passed a `struct vme_dev <vme_dev>` pointer as an argument.

Here, the 'num' field refers to the sequential device ID for this specific driver. The bridge number (or bus number) can be accessed using dev-&gt;bridge-&gt;num.

A function is also provided to unregister the driver from the VME core called `vme_unregister_driver()` and should usually be called from the device driver's exit routine.

<a id="rst-resource-management"></a>

## Resource management

Once a driver has registered with the VME core the provided match routine will be called the number of times specified during the registration. If a match succeeds, a non-zero value should be returned. A zero return value indicates failure. For all successful matches, the probe routine of the corresponding driver is called. The probe routine is passed a pointer to the devices device structure. This pointer should be saved, it will be required for requesting VME resources.

The driver can request ownership of one or more master windows (`vme_master_request()`), slave windows (`vme_slave_request()`) and/or dma channels (`vme_dma_request()`). Rather than allowing the device driver to request a specific window or DMA channel (which may be used by a different driver) the API allows a resource to be assigned based on the required attributes of the driver in question. For slave windows these attributes are split into the VME address spaces that need to be accessed in 'aspace' and VME bus cycle types required in 'cycle'. Master windows add a further set of attributes in 'width' specifying the required data transfer widths. These attributes are defined as bitmasks and as such any combination of the attributes can be requested for a single window, the core will assign a window that meets the requirements, returning a pointer of type vme_resource that should be used to identify the allocated resource when it is used. For DMA controllers, the request function requires the potential direction of any transfers to be provided in the route attributes. This is typically VME-to-MEM and/or MEM-to-VME, though some hardware can support VME-to-VME and MEM-to-MEM transfers as well as test pattern generation. If an unallocated window fitting the requirements can not be found a NULL pointer will be returned.

Functions are also provided to free window allocations once they are no longer required. These functions (`vme_master_free()`, `vme_slave_free()` and `vme_dma_free()`) should be passed the pointer to the resource provided during resource allocation.

<a id="rst-master-windows"></a>

## Master windows

Master windows provide access from the local processor\[s\] out onto the VME bus. The number of windows available and the available access modes is dependent on the underlying chipset. A window must be configured before it can be used.

<a id="rst-master-window-configuration"></a>

### Master window configuration

Once a master window has been assigned `vme_master_set()` can be used to configure it and `vme_master_get()` to retrieve the current settings. The address spaces, transfer widths and cycle types are the same as described under resource management, however some of the options are mutually exclusive. For example, only one address space may be specified.

<a id="rst-master-window-access"></a>

### Master window access

The function `vme_master_read()` can be used to read from and `vme_master_write()` used to write to configured master windows.

In addition to simple reads and writes, `vme_master_rmw()` is provided to do a read-modify-write transaction. Parts of a VME window can also be mapped into user space memory using `vme_master_mmap()`.

<a id="rst-slave-windows"></a>

## Slave windows

Slave windows provide devices on the VME bus access into mapped portions of the local memory. The number of windows available and the access modes that can be used is dependent on the underlying chipset. A window must be configured before it can be used.

<a id="rst-slave-window-configuration"></a>

### Slave window configuration

Once a slave window has been assigned `vme_slave_set()` can be used to configure it and `vme_slave_get()` to retrieve the current settings.

The address spaces, transfer widths and cycle types are the same as described under resource management, however some of the options are mutually exclusive. For example, only one address space may be specified.

<a id="rst-slave-window-buffer-allocation"></a>

### Slave window buffer allocation

Functions are provided to allow the user to allocate (`vme_alloc_consistent()`) and free (`vme_free_consistent()`) contiguous buffers which will be accessible by the VME bridge. These functions do not have to be used, other methods can be used to allocate a buffer, though care must be taken to ensure that they are contiguous and accessible by the VME bridge.

<a id="rst-slave-window-access"></a>

### Slave window access

Slave windows map local memory onto the VME bus, the standard methods for accessing memory should be used.

<a id="rst-dma-channels"></a>

## DMA channels

The VME DMA transfer provides the ability to run link-list DMA transfers. The API introduces the concept of DMA lists. Each DMA list is a link-list which can be passed to a DMA controller. Multiple lists can be created, extended, executed, reused and destroyed.

<a id="rst-list-management"></a>

### List Management

The function `vme_new_dma_list()` is provided to create and `vme_dma_list_free()` to destroy DMA lists. Execution of a list will not automatically destroy the list, thus enabling a list to be reused for repetitive tasks.

<a id="rst-list-population"></a>

### List Population

An item can be added to a list using `vme_dma_list_add()` (the source and destination attributes need to be created before calling this function, this is covered under "Transfer Attributes").

> [!NOTE]
>
> The detailed attributes of the transfers source and destination are not checked until an entry is added to a DMA list, the request for a DMA channel purely checks the directions in which the controller is expected to transfer data. As a result it is possible for this call to return an error, for example if the source or destination is in an unsupported VME address space.

<a id="rst-transfer-attributes"></a>

### Transfer Attributes

The attributes for the source and destination are handled separately from adding an item to a list. This is due to the diverse attributes required for each type of source and destination. There are functions to create attributes for PCI, VME and pattern sources and destinations (where appropriate):

> - PCI source or destination: `vme_dma_pci_attribute()`
>
> - VME source or destination: `vme_dma_vme_attribute()`
>
> - Pattern source: `vme_dma_pattern_attribute()`

The function `vme_dma_free_attribute()` should be used to free an attribute.

<a id="rst-list-execution"></a>

### List Execution

The function `vme_dma_list_exec()` queues a list for execution and will return once the list has been executed.

<a id="rst-interrupts"></a>

## Interrupts

The VME API provides functions to attach and detach callbacks to specific VME level and status ID combinations and for the generation of VME interrupts with specific VME level and status IDs.

<a id="rst-attaching-interrupt-handlers"></a>

### Attaching Interrupt Handlers

The function `vme_irq_request()` can be used to attach and `vme_irq_free()` to free a specific VME level and status ID combination. Any given combination can only be assigned a single callback function. A void pointer parameter is provided, the value of which is passed to the callback function, the use of this pointer is user undefined. The callback parameters are as follows. Care must be taken in writing a callback function, callback functions run in interrupt context:



```c
void callback(int level, int statid, void *priv);
```

<a id="rst-interrupt-generation"></a>

### Interrupt Generation

The function `vme_irq_generate()` can be used to generate a VME interrupt at a given VME level and VME status ID.

<a id="rst-location-monitors"></a>

## Location monitors

The VME API provides the following functionality to configure the location monitor.

<a id="rst-location-monitor-management"></a>

### Location Monitor Management

The function `vme_lm_request()` is provided to request the use of a block of location monitors and `vme_lm_free()` to free them after they are no longer required. Each block may provide a number of location monitors, monitoring adjacent locations. The function `vme_lm_count()` can be used to determine how many locations are provided.

<a id="rst-location-monitor-configuration"></a>

### Location Monitor Configuration

Once a bank of location monitors has been allocated, the function `vme_lm_set()` is provided to configure the location and mode of the location monitor. The function `vme_lm_get()` can be used to retrieve existing settings.

<a id="rst-location-monitor-use"></a>

### Location Monitor Use

The function `vme_lm_attach()` enables a callback to be attached and `vme_lm_detach()` allows on to be detached from each location monitor location. Each location monitor can monitor a number of adjacent locations. The callback function is declared as follows.



```c
void callback(void *data);
```

<a id="rst-slot-detection"></a>

## Slot Detection

The function `vme_slot_num()` returns the slot ID of the provided bridge.

<a id="rst-bus-detection"></a>

## Bus Detection

The function `vme_bus_num()` returns the bus ID of the provided bridge.

<a id="rst-vme-api"></a>

## VME API


#### <a id="c-struct-vme_dev"></a>`struct vme_dev`

Structure representing a VME device

**Definition**

```c
struct vme_dev {
    int num;
    struct vme_bridge *bridge;
    struct device dev;
    struct list_head drv_list;
    struct list_head bridge_list;
};
```

**Members**

- `num`: The device number
- `bridge`: Pointer to the bridge device this device is on
- `dev`: Internal device structure
- `drv_list`: List of devices (per driver)
- `bridge_list`: List of devices (per bridge)

#### <a id="c-struct-vme_driver"></a>`struct vme_driver`

Structure representing a VME driver

**Definition**

```c
struct vme_driver {
    const char *name;
    int (*match)(struct vme_dev *vdev);
    int (*probe)(struct vme_dev *vdev);
    void (*remove)(struct vme_dev *vdev);
    struct device_driver driver;
    struct list_head devices;
};
```

**Members**

- `name`: Driver name, should be unique among VME drivers and usually the same
  as the module name.
- `match`: Callback used to determine whether probe should be run.
- `probe`: Callback for device binding, called when new device is detected.
- `remove`: Callback, called on device removal.
- `driver`: Underlying generic device driver structure.
- `devices`: List of VME devices (struct vme_dev) associated with this driver.



#### <a id="c-vme_alloc_consistent"></a>`vme_alloc_consistent()`

```c
void * vme_alloc_consistent(struct vme_resource *resource, size_t size, dma_addr_t *dma)
```

Allocate contiguous memory.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME resource.
- `size_t size`: Size of allocation required.
- `dma_addr_t *dma`: Pointer to variable to store physical address of allocation.

**Description**

Allocate a contiguous block of memory for use by the driver. This is used to
create the buffers for the slave windows.

**Return**

Virtual address of allocation on success, NULL on failure.

#### <a id="c-vme_free_consistent"></a>`vme_free_consistent()`

```c
void vme_free_consistent(struct vme_resource *resource, size_t size, void *vaddr, dma_addr_t dma)
```

Free previously allocated memory.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME resource.
- `size_t size`: Size of allocation to free.
- `void *vaddr`: Virtual address of allocation.
- `dma_addr_t dma`: Physical address of allocation.

**Description**

Free previously allocated block of contiguous memory.

#### <a id="c-vme_get_size"></a>`vme_get_size()`

```c
size_t vme_get_size(struct vme_resource *resource)
```

Helper function returning size of a VME window

**Parameters**

- `struct vme_resource *resource`: Pointer to VME slave or master resource.

**Description**

Determine the size of the VME window provided. This is a helper
function, wrappering the call to vme_master_get or vme_slave_get
depending on the type of window resource handed to it.

**Return**

Size of the window on success, zero on failure.

#### <a id="c-vme_slave_request"></a>`vme_slave_request()`

```c
struct vme_resource * vme_slave_request(struct vme_dev *vdev, u32 address, u32 cycle)
```

Request a VME slave window resource.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `u32 address`: Required VME address space.
- `u32 cycle`: Required VME data transfer cycle type.

**Description**

Request use of a VME window resource capable of being set for the requested
address space and data transfer cycle.

**Return**

Pointer to VME resource on success, NULL on failure.

#### <a id="c-vme_slave_set"></a>`vme_slave_set()`

```c
int vme_slave_set(struct vme_resource *resource, int enabled, unsigned long long vme_base, unsigned long long size, dma_addr_t buf_base, u32 aspace, u32 cycle)
```

Set VME slave window configuration.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME slave resource.
- `int enabled`: State to which the window should be configured.
- `unsigned long long vme_base`: Base address for the window.
- `unsigned long long size`: Size of the VME window.
- `dma_addr_t buf_base`: Based address of buffer used to provide VME slave window storage.
- `u32 aspace`: VME address space for the VME window.
- `u32 cycle`: VME data transfer cycle type for the VME window.

**Description**

Set configuration for provided VME slave window.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device, if an invalid resource has been provided or invalid
attributes are provided. Hardware specific errors may also be
returned.

#### <a id="c-vme_slave_get"></a>`vme_slave_get()`

```c
int vme_slave_get(struct vme_resource *resource, int *enabled, unsigned long long *vme_base, unsigned long long *size, dma_addr_t *buf_base, u32 *aspace, u32 *cycle)
```

Retrieve VME slave window configuration.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME slave resource.
- `int *enabled`: Pointer to variable for storing state.
- `unsigned long long *vme_base`: Pointer to variable for storing window base address.
- `unsigned long long *size`: Pointer to variable for storing window size.
- `dma_addr_t *buf_base`: Pointer to variable for storing slave buffer base address.
- `u32 *aspace`: Pointer to variable for storing VME address space.
- `u32 *cycle`: Pointer to variable for storing VME data transfer cycle type.

**Description**

Return configuration for provided VME slave window.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device or if an invalid resource has been provided.

#### <a id="c-vme_slave_free"></a>`vme_slave_free()`

```c
void vme_slave_free(struct vme_resource *resource)
```

Free VME slave window

**Parameters**

- `struct vme_resource *resource`: Pointer to VME slave resource.

**Description**

Free the provided slave resource so that it may be reallocated.

#### <a id="c-vme_master_request"></a>`vme_master_request()`

```c
struct vme_resource * vme_master_request(struct vme_dev *vdev, u32 address, u32 cycle, u32 dwidth)
```

Request a VME master window resource.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `u32 address`: Required VME address space.
- `u32 cycle`: Required VME data transfer cycle type.
- `u32 dwidth`: Required VME data transfer width.

**Description**

Request use of a VME window resource capable of being set for the requested
address space, data transfer cycle and width.

**Return**

Pointer to VME resource on success, NULL on failure.

#### <a id="c-vme_master_set"></a>`vme_master_set()`

```c
int vme_master_set(struct vme_resource *resource, int enabled, unsigned long long vme_base, unsigned long long size, u32 aspace, u32 cycle, u32 dwidth)
```

Set VME master window configuration.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `int enabled`: State to which the window should be configured.
- `unsigned long long vme_base`: Base address for the window.
- `unsigned long long size`: Size of the VME window.
- `u32 aspace`: VME address space for the VME window.
- `u32 cycle`: VME data transfer cycle type for the VME window.
- `u32 dwidth`: VME data transfer width for the VME window.

**Description**

Set configuration for provided VME master window.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device, if an invalid resource has been provided or invalid
attributes are provided. Hardware specific errors may also be
returned.

#### <a id="c-vme_master_get"></a>`vme_master_get()`

```c
int vme_master_get(struct vme_resource *resource, int *enabled, unsigned long long *vme_base, unsigned long long *size, u32 *aspace, u32 *cycle, u32 *dwidth)
```

Retrieve VME master window configuration.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `int *enabled`: Pointer to variable for storing state.
- `unsigned long long *vme_base`: Pointer to variable for storing window base address.
- `unsigned long long *size`: Pointer to variable for storing window size.
- `u32 *aspace`: Pointer to variable for storing VME address space.
- `u32 *cycle`: Pointer to variable for storing VME data transfer cycle type.
- `u32 *dwidth`: Pointer to variable for storing VME data transfer width.

**Description**

Return configuration for provided VME master window.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device or if an invalid resource has been provided.

#### <a id="c-vme_master_read"></a>`vme_master_read()`

```c
ssize_t vme_master_read(struct vme_resource *resource, void *buf, size_t count, loff_t offset)
```

Read data from VME space into a buffer.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `void *buf`: Pointer to buffer where data should be transferred.
- `size_t count`: Number of bytes to transfer.
- `loff_t offset`: Offset into VME master window at which to start transfer.

**Description**

Perform read of count bytes of data from location on VME bus which maps into
the VME master window at offset to buf.

**Return**

Number of bytes read, -EINVAL if resource is not a VME master
resource or read operation is not supported. -EFAULT returned if
invalid offset is provided. Hardware specific errors may also be
returned.

#### <a id="c-vme_master_write"></a>`vme_master_write()`

```c
ssize_t vme_master_write(struct vme_resource *resource, void *buf, size_t count, loff_t offset)
```

Write data out to VME space from a buffer.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `void *buf`: Pointer to buffer holding data to transfer.
- `size_t count`: Number of bytes to transfer.
- `loff_t offset`: Offset into VME master window at which to start transfer.

**Description**

Perform write of count bytes of data from buf to location on VME bus which
maps into the VME master window at offset.

**Return**

Number of bytes written, -EINVAL if resource is not a VME master
resource or write operation is not supported. -EFAULT returned if
invalid offset is provided. Hardware specific errors may also be
returned.

#### <a id="c-vme_master_rmw"></a>`vme_master_rmw()`

```c
unsigned int vme_master_rmw(struct vme_resource *resource, unsigned int mask, unsigned int compare, unsigned int swap, loff_t offset)
```

Perform read-modify-write cycle.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `unsigned int mask`: Bits to be compared and swapped in operation.
- `unsigned int compare`: Bits to be compared with data read from offset.
- `unsigned int swap`: Bits to be swapped in data read from offset.
- `loff_t offset`: Offset into VME master window at which to perform operation.

**Description**

Perform read-modify-write cycle on provided location:
- Location on VME bus is read.
- Bits selected by mask are compared with compare.
- Where a selected bit matches that in compare and are selected in swap,
the bit is swapped.
- Result written back to location on VME bus.

**Return**

Bytes written on success, -EINVAL if resource is not a VME master
resource or RMW operation is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_master_mmap"></a>`vme_master_mmap()`

```c
int vme_master_mmap(struct vme_resource *resource, struct vm_area_struct *vma)
```

Mmap region of VME master window.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.
- `struct vm_area_struct *vma`: Pointer to definition of user mapping.

**Description**

Memory map a region of the VME master window into user space.

**Return**

Zero on success, -EINVAL if resource is not a VME master
resource or -EFAULT if map exceeds window size. Other generic mmap
errors may also be returned.

#### <a id="c-vme_master_free"></a>`vme_master_free()`

```c
void vme_master_free(struct vme_resource *resource)
```

Free VME master window

**Parameters**

- `struct vme_resource *resource`: Pointer to VME master resource.

**Description**

Free the provided master resource so that it may be reallocated.

#### <a id="c-vme_dma_request"></a>`vme_dma_request()`

```c
struct vme_resource * vme_dma_request(struct vme_dev *vdev, u32 route)
```

Request a DMA controller.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `u32 route`: Required src/destination combination.

**Description**

Request a VME DMA controller with capability to perform transfers between
requested source/destination combination.

**Return**

Pointer to VME DMA resource on success, NULL on failure.

#### <a id="c-vme_new_dma_list"></a>`vme_new_dma_list()`

```c
struct vme_dma_list * vme_new_dma_list(struct vme_resource *resource)
```

Create new VME DMA list.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME DMA resource.

**Description**

Create a new VME DMA list. It is the responsibility of the user to free
the list once it is no longer required with [`vme_dma_list_free()`](#c-vme_dma_list_free).

**Return**

Pointer to new VME DMA list, NULL on allocation failure or invalid
VME DMA resource.

#### <a id="c-vme_dma_pattern_attribute"></a>`vme_dma_pattern_attribute()`

```c
struct vme_dma_attr * vme_dma_pattern_attribute(u32 pattern, u32 type)
```

Create "Pattern" type VME DMA list attribute.

**Parameters**

- `u32 pattern`: Value to use used as pattern
- `u32 type`: Type of pattern to be written.

**Description**

Create VME DMA list attribute for pattern generation. It is the
responsibility of the user to free used attributes using
[`vme_dma_free_attribute()`](#c-vme_dma_free_attribute).

**Return**

Pointer to VME DMA attribute, NULL on failure.

#### <a id="c-vme_dma_pci_attribute"></a>`vme_dma_pci_attribute()`

```c
struct vme_dma_attr * vme_dma_pci_attribute(dma_addr_t address)
```

Create "PCI" type VME DMA list attribute.

**Parameters**

- `dma_addr_t address`: PCI base address for DMA transfer.

**Description**

Create VME DMA list attribute pointing to a location on PCI for DMA
transfers. It is the responsibility of the user to free used attributes
using [`vme_dma_free_attribute()`](#c-vme_dma_free_attribute).

**Return**

Pointer to VME DMA attribute, NULL on failure.

#### <a id="c-vme_dma_vme_attribute"></a>`vme_dma_vme_attribute()`

```c
struct vme_dma_attr * vme_dma_vme_attribute(unsigned long long address, u32 aspace, u32 cycle, u32 dwidth)
```

Create "VME" type VME DMA list attribute.

**Parameters**

- `unsigned long long address`: VME base address for DMA transfer.
- `u32 aspace`: VME address space to use for DMA transfer.
- `u32 cycle`: VME bus cycle to use for DMA transfer.
- `u32 dwidth`: VME data width to use for DMA transfer.

**Description**

Create VME DMA list attribute pointing to a location on the VME bus for DMA
transfers. It is the responsibility of the user to free used attributes
using [`vme_dma_free_attribute()`](#c-vme_dma_free_attribute).

**Return**

Pointer to VME DMA attribute, NULL on failure.

#### <a id="c-vme_dma_free_attribute"></a>`vme_dma_free_attribute()`

```c
void vme_dma_free_attribute(struct vme_dma_attr *attributes)
```

Free DMA list attribute.

**Parameters**

- `struct vme_dma_attr *attributes`: Pointer to DMA list attribute.

**Description**

Free VME DMA list attribute. VME DMA list attributes can be safely freed
once [`vme_dma_list_add()`](#c-vme_dma_list_add) has returned.

#### <a id="c-vme_dma_list_add"></a>`vme_dma_list_add()`

```c
int vme_dma_list_add(struct vme_dma_list *list, struct vme_dma_attr *src, struct vme_dma_attr *dest, size_t count)
```

Add entry to a VME DMA list.

**Parameters**

- `struct vme_dma_list *list`: Pointer to VME list.
- `struct vme_dma_attr *src`: Pointer to DMA list attribute to use as source.
- `struct vme_dma_attr *dest`: Pointer to DMA list attribute to use as destination.
- `size_t count`: Number of bytes to transfer.

**Description**

Add an entry to the provided VME DMA list. Entry requires pointers to source
and destination DMA attributes and a count.

Please note, the attributes supported as source and destinations for
transfers are hardware dependent.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device or if the link list has already been submitted for execution.
Hardware specific errors also possible.

#### <a id="c-vme_dma_list_exec"></a>`vme_dma_list_exec()`

```c
int vme_dma_list_exec(struct vme_dma_list *list)
```

Queue a VME DMA list for execution.

**Parameters**

- `struct vme_dma_list *list`: Pointer to VME list.

**Description**

Queue the provided VME DMA list for execution. The call will return once the
list has been executed.

**Return**

Zero on success, -EINVAL if operation is not supported on this
device. Hardware specific errors also possible.

#### <a id="c-vme_dma_list_free"></a>`vme_dma_list_free()`

```c
int vme_dma_list_free(struct vme_dma_list *list)
```

Free a VME DMA list.

**Parameters**

- `struct vme_dma_list *list`: Pointer to VME list.

**Description**

Free the provided DMA list and all its entries.

**Return**

Zero on success, -EINVAL on invalid VME resource, -EBUSY if resource
is still in use. Hardware specific errors also possible.

#### <a id="c-vme_dma_free"></a>`vme_dma_free()`

```c
int vme_dma_free(struct vme_resource *resource)
```

Free a VME DMA resource.

**Parameters**

- `struct vme_resource *resource`: Pointer to VME DMA resource.

**Description**

Free the provided DMA resource so that it may be reallocated.

**Return**

Zero on success, -EINVAL on invalid VME resource, -EBUSY if resource
is still active.

#### <a id="c-vme_irq_request"></a>`vme_irq_request()`

```c
int vme_irq_request(struct vme_dev *vdev, int level, int statid, void (*callback)(int level, int statid, void *priv_data), void *priv_data)
```

Request a specific VME interrupt.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `int level`: Interrupt priority being requested.
- `int statid`: Interrupt vector being requested.
- `void (*callback)(int level, int statid, void *priv_data)`: Pointer to callback function called when VME interrupt/vector
  received.
- `void *priv_data`: Generic pointer that will be passed to the callback function.

**Description**

Request callback to be attached as a handler for VME interrupts with provided
level and statid.

**Return**

Zero on success, -EINVAL on invalid vme device, level or if the
function is not supported, -EBUSY if the level/statid combination is
already in use. Hardware specific errors also possible.

#### <a id="c-vme_irq_free"></a>`vme_irq_free()`

```c
void vme_irq_free(struct vme_dev *vdev, int level, int statid)
```

Free a VME interrupt.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `int level`: Interrupt priority of interrupt being freed.
- `int statid`: Interrupt vector of interrupt being freed.

**Description**

Remove previously attached callback from VME interrupt priority/vector.

#### <a id="c-vme_irq_generate"></a>`vme_irq_generate()`

```c
int vme_irq_generate(struct vme_dev *vdev, int level, int statid)
```

Generate VME interrupt.

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.
- `int level`: Interrupt priority at which to assert the interrupt.
- `int statid`: Interrupt vector to associate with the interrupt.

**Description**

Generate a VME interrupt of the provided level and with the provided
statid.

**Return**

Zero on success, -EINVAL on invalid vme device, level or if the
function is not supported. Hardware specific errors also possible.

#### <a id="c-vme_lm_request"></a>`vme_lm_request()`

```c
struct vme_resource * vme_lm_request(struct vme_dev *vdev)
```

Request a VME location monitor

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.

**Description**

Allocate a location monitor resource to the driver. A location monitor
allows the driver to monitor accesses to a contiguous number of
addresses on the VME bus.

**Return**

Pointer to a VME resource on success or NULL on failure.

#### <a id="c-vme_lm_count"></a>`vme_lm_count()`

```c
int vme_lm_count(struct vme_resource *resource)
```

Determine number of VME Addresses monitored

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.

**Description**

The number of contiguous addresses monitored is hardware dependent.
Return the number of contiguous addresses monitored by the
location monitor.

**Return**

Count of addresses monitored or -EINVAL when provided with an
invalid location monitor resource.

#### <a id="c-vme_lm_set"></a>`vme_lm_set()`

```c
int vme_lm_set(struct vme_resource *resource, unsigned long long lm_base, u32 aspace, u32 cycle)
```

Configure location monitor

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.
- `unsigned long long lm_base`: Base address to monitor.
- `u32 aspace`: VME address space to monitor.
- `u32 cycle`: VME bus cycle type to monitor.

**Description**

Set the base address, address space and cycle type of accesses to be
monitored by the location monitor.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource or function is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_lm_get"></a>`vme_lm_get()`

```c
int vme_lm_get(struct vme_resource *resource, unsigned long long *lm_base, u32 *aspace, u32 *cycle)
```

Retrieve location monitor settings

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.
- `unsigned long long *lm_base`: Pointer used to output the base address monitored.
- `u32 *aspace`: Pointer used to output the address space monitored.
- `u32 *cycle`: Pointer used to output the VME bus cycle type monitored.

**Description**

Retrieve the base address, address space and cycle type of accesses to
be monitored by the location monitor.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource or function is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_lm_attach"></a>`vme_lm_attach()`

```c
int vme_lm_attach(struct vme_resource *resource, int monitor, void (*callback)(void *), void *data)
```

Provide callback for location monitor address

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.
- `int monitor`: Offset to which callback should be attached.
- `void (*callback)(void *)`: Pointer to callback function called when triggered.
- `void *data`: Generic pointer that will be passed to the callback function.

**Description**

Attach a callback to the specified offset into the location monitors
monitored addresses. A generic pointer is provided to allow data to be
passed to the callback when called.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource or function is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_lm_detach"></a>`vme_lm_detach()`

```c
int vme_lm_detach(struct vme_resource *resource, int monitor)
```

Remove callback for location monitor address

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.
- `int monitor`: Offset to which callback should be removed.

**Description**

Remove the callback associated with the specified offset into the
location monitors monitored addresses.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource or function is not supported. Hardware specific
errors may also be returned.

#### <a id="c-vme_lm_free"></a>`vme_lm_free()`

```c
void vme_lm_free(struct vme_resource *resource)
```

Free allocated VME location monitor

**Parameters**

- `struct vme_resource *resource`: Pointer to VME location monitor resource.

**Description**

Free allocation of a VME location monitor.

- WARNING: This function currently expects that any callbacks that have

  been attached to the location monitor have been removed.

**Return**

Zero on success, -EINVAL when provided with an invalid location
monitor resource.

#### <a id="c-vme_slot_num"></a>`vme_slot_num()`

```c
int vme_slot_num(struct vme_dev *vdev)
```

Retrieve slot ID

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.

**Description**

Retrieve the slot ID associated with the provided VME device.

**Return**

The slot ID on success, -EINVAL if VME bridge cannot be determined
or the function is not supported. Hardware specific errors may also
be returned.

#### <a id="c-vme_bus_num"></a>`vme_bus_num()`

```c
int vme_bus_num(struct vme_dev *vdev)
```

Retrieve bus number

**Parameters**

- `struct vme_dev *vdev`: Pointer to VME device struct vme_dev assigned to driver instance.

**Description**

Retrieve the bus enumeration associated with the provided VME device.

**Return**

The bus number on success, -EINVAL if VME bridge cannot be
determined.

#### <a id="c-vme_register_driver"></a>`vme_register_driver()`

```c
int vme_register_driver(struct vme_driver *drv, unsigned int ndevs)
```

Register a VME driver

**Parameters**

- `struct vme_driver *drv`: Pointer to VME driver structure to register.
- `unsigned int ndevs`: Maximum number of devices to allow to be enumerated.

**Description**

Register a VME device driver with the VME subsystem.

**Return**

Zero on success, error value on registration failure.

#### <a id="c-vme_unregister_driver"></a>`vme_unregister_driver()`

```c
void vme_unregister_driver(struct vme_driver *drv)
```

Unregister a VME driver

**Parameters**

- `struct vme_driver *drv`: Pointer to VME driver structure to unregister.

**Description**

Unregister a VME device driver from the VME subsystem.

---

# W1: Dallas' 1-wire bus

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> W1 kernel API functions.

<a id="rst-w1-dallas-1-wire-bus"></a>

**Author:** David Fries

<a id="rst-w1-api-internal-to-the-kernel"></a>

## W1 API internal to the kernel

<a id="rst-include-linux-w1-h"></a>

### include/linux/w1.h

W1 kernel API functions.


#### <a id="c-struct-w1_reg_num"></a>`struct w1_reg_num`

broken out slave device id

**Definition**

```c
struct w1_reg_num {
    #if defined(__LITTLE_ENDIAN_BITFIELD);
        __u64 family:8, id:48, crc:8;
    #elif defined(__BIG_ENDIAN_BITFIELD);
        __u64 crc:8, id:48, family:8;
    #else;
    #error "Please fix <asm/byteorder.h>";
    #endif;
};
```

**Members**

- `family`: identifies the type of device
- `id`: along with family is the unique device id
- `crc`: checksum of the other bytes
- `crc`: checksum of the other bytes
- `id`: along with family is the unique device id
- `family`: identifies the type of device

#### <a id="c-struct-w1_slave"></a>`struct w1_slave`

holds a single slave device on the bus

**Definition**

```c
struct w1_slave {
    struct module           *owner;
    unsigned char           name[W1_MAXNAMELEN];
    struct list_head        w1_slave_entry;
    struct w1_reg_num       reg_num;
    atomic_t refcnt;
    int ttl;
    unsigned long           flags;
    struct w1_master        *master;
    struct w1_family        *family;
    void *family_data;
    struct device           dev;
    struct device           *hwmon;
};
```

**Members**

- `owner`: Points to the one wire "wire" kernel module.
- `name`: Device id is ascii.
- `w1_slave_entry`: data for the linked list
- `reg_num`: the slave id in binary
- `refcnt`: reference count, delete when 0
- `ttl`: decrement per search this slave isn't found, deatch at 0
- `flags`: bit flags for W1_SLAVE_ACTIVE W1_SLAVE_DETACH
- `master`: bus which this slave is on
- `family`: module for device family type
- `family_data`: pointer for use by the family module
- `dev`: kernel device identifier
- `hwmon`: pointer to hwmon device

#### <a id="c-struct-w1_bus_master"></a>`struct w1_bus_master`

operations available on a bus master

**Definition**

```c
struct w1_bus_master {
    void *data;
    u8 (*read_bit)(void *);
    void (*write_bit)(void *, u8);
    u8 (*touch_bit)(void *, u8);
    u8 (*read_byte)(void *);
    void (*write_byte)(void *, u8);
    u8 (*read_block)(void *, u8 *, int);
    void (*write_block)(void *, const u8 *, int);
    u8 (*triplet)(void *, u8);
    u8 (*reset_bus)(void *);
    u8 (*set_pullup)(void *, int);
    void (*search)(void *, struct w1_master *, u8, w1_slave_found_callback);
    char *dev_id;
};
```

**Members**

- `data`: the first parameter in all the functions below
- `read_bit`: Sample the line level
  **return** the level read (0 or 1)
- `write_bit`: Sets the line level
- `touch_bit`: the lowest-level function for devices that really support the
  1-wire protocol.
  touch_bit(0) = write-0 cycle
  touch_bit(1) = write-1 / read cycle
  **return** the bit read (0 or 1)
- `read_byte`: Reads a byte. Same as 8 touch_bit(1) calls.
  **return** the byte read
- `write_byte`: Writes a byte. Same as 8 touch_bit(x) calls.
- `read_block`: Same as a series of `read_byte()` calls
  **return** the number of bytes read
- `write_block`: Same as a series of `write_byte()` calls
- `triplet`: Combines two reads and a smart write for ROM searches
  **return** bit0=Id bit1=comp_id bit2=dir_taken
- `reset_bus`: long write-0 with a read for the presence pulse detection
  **return** -1=Error, 0=Device present, 1=No device present
- `set_pullup`: Put out a strong pull-up pulse of the specified duration.
  **return** -1=Error, 0=completed
- `search`: Really nice hardware can handle the different types of ROM search
  w1_master* is passed to the slave found callback.
  u8 is search_type, W1_SEARCH or W1_ALARM_SEARCH
- `dev_id`: Optional device id string, which w1 slaves could use for
  creating names, which then give a connection to the w1 master

**Note**

read_bit and write_bit are very low level functions and should only
be used with hardware that doesn't really support 1-wire operations,
like a parallel/serial port.
Either define read_bit and write_bit OR define, at minimum, touch_bit and
reset_bus.

#### <a id="c-enum-w1_master_flags"></a>`enum w1_master_flags`

bitfields used in w1_master.flags

**Constants**

- `W1_ABORT_SEARCH`: abort searching early on shutdown
- `W1_WARN_MAX_COUNT`: limit warning when the maximum count is reached

#### <a id="c-struct-w1_master"></a>`struct w1_master`

one per bus master

**Definition**

```c
struct w1_master {
    struct list_head        w1_master_entry;
    struct module           *owner;
    unsigned char           name[W1_MAXNAMELEN];
    struct mutex            list_mutex;
    struct list_head        slist;
    struct list_head        async_list;
    int max_slave_count, slave_count;
    unsigned long           attempts;
    int slave_ttl;
    int initialized;
    u32 id;
    int search_count;
    u64 search_id;
    atomic_t refcnt;
    void *priv;
    int enable_pullup;
    int pullup_duration;
    long flags;
    struct task_struct      *thread;
    struct mutex            mutex;
    struct mutex            bus_mutex;
    struct device_driver    *driver;
    struct device           dev;
    struct w1_bus_master    *bus_master;
    u32 seq;
};
```

**Members**

- `w1_master_entry`: master linked list
- `owner`: module owner
- `name`: dynamically allocate bus name
- `list_mutex`: protect slist and async_list
- `slist`: linked list of slaves
- `async_list`: linked list of netlink commands to execute
- `max_slave_count`: maximum number of slaves to search for at a time
- `slave_count`: current number of slaves known
- `attempts`: number of searches ran
- `slave_ttl`: number of searches before a slave is timed out
- `initialized`: prevent init/removal race conditions
- `id`: w1 bus number
- `search_count`: number of automatic searches to run, -1 unlimited
- `search_id`: allows continuing a search
- `refcnt`: reference count
- `priv`: private data storage
- `enable_pullup`: allows a strong pullup
- `pullup_duration`: time for the next strong pullup
- `flags`: one of w1_master_flags
- `thread`: thread for bus search and netlink commands
- `mutex`: protect most of w1_master
- `bus_mutex`: pretect concurrent bus access
- `driver`: sysfs driver
- `dev`: sysfs device
- `bus_master`: io operations available
- `seq`: sequence number used for netlink broadcasts

#### <a id="c-struct-w1_family_ops"></a>`struct w1_family_ops`

operations for a family type

**Definition**

```c
struct w1_family_ops {
    int (*add_slave)(struct w1_slave *sl);
    void (*remove_slave)(struct w1_slave *sl);
    const struct attribute_group **groups;
    const struct hwmon_chip_info *chip_info;
};
```

**Members**

- `add_slave`: add_slave
- `remove_slave`: remove_slave
- `groups`: sysfs group
- `chip_info`: pointer to struct hwmon_chip_info

#### <a id="c-struct-w1_family"></a>`struct w1_family`

reference counted family structure.

**Definition**

```c
struct w1_family {
    struct list_head        family_entry;
    u8 fid;
    const struct w1_family_ops *fops;
    const struct of_device_id *of_match_table;
    atomic_t refcnt;
};
```

**Members**

- `family_entry`: family linked list
- `fid`: 8 bit family identifier
- `fops`: operations for this family
- `of_match_table`: open firmware match table
- `refcnt`: reference counter

#### <a id="c-module_w1_family"></a>`module_w1_family()`

```c
module_w1_family(__w1_family)
```

Helper macro for registering a 1-Wire families

**Parameters**

- `__w1_family`: w1_family struct

**Description**

Helper macro for 1-Wire families which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit)


<a id="rst-drivers-w1-w1-c"></a>

### drivers/w1/w1.c

W1 core functions.


#### <a id="c-w1_search"></a>`w1_search()`

```c
void w1_search(struct w1_master *dev, u8 search_type, w1_slave_found_callback cb)
```

Performs a ROM Search & registers any devices found.

**Parameters**

- `struct w1_master *dev`: The master device to search
- `u8 search_type`: W1_SEARCH to search all devices, or W1_ALARM_SEARCH
  to return only devices in the alarmed state
- `w1_slave_found_callback cb`: Function to call when a device is found

**Description**

The 1-wire search is a simple binary tree search.
For each bit of the address, we read two bits and write one bit.
The bit written will put to sleep all devies that don't match that bit.
When the two reads differ, the direction choice is obvious.
When both bits are 0, we must choose a path to take.
When we can scan all 64 bits without having to choose a path, we are done.

See "Application note 187 1-wire search algorithm" at www.maxim-ic.com

#### <a id="c-w1_process_callbacks"></a>`w1_process_callbacks()`

```c
int w1_process_callbacks(struct w1_master *dev)
```

execute each dev->async_list callback entry

**Parameters**

- `struct w1_master *dev`: w1_master device

**Description**

The w1 master list_mutex must be held.

**Return**

1 if there were commands to executed 0 otherwise


<a id="rst-drivers-w1-w1-family-c"></a>

### drivers/w1/w1_family.c

Allows registering device family operations.


#### <a id="c-w1_register_family"></a>`w1_register_family()`

```c
int w1_register_family(struct w1_family *newf)
```

register a device family driver

**Parameters**

- `struct w1_family *newf`: family to register

#### <a id="c-w1_unregister_family"></a>`w1_unregister_family()`

```c
void w1_unregister_family(struct w1_family *fent)
```

unregister a device family driver

**Parameters**

- `struct w1_family *fent`: family to unregister


<a id="rst-drivers-w1-w1-internal-h"></a>

### drivers/w1/w1_internal.h

W1 internal initialization for master devices.


#### <a id="c-struct-w1_async_cmd"></a>`struct w1_async_cmd`

execute callback from the w1_process kthread

**Definition**

```c
struct w1_async_cmd {
    struct list_head        async_entry;
    void (*cb)(struct w1_master *dev, struct w1_async_cmd *async_cmd);
};
```

**Members**

- `async_entry`: link entry
- `cb`: callback function, must list_del and destroy this list before
  returning

**Description**

When inserted into the w1_master async_list, w1_process will execute
the callback.  Embed this into the structure with the command details.


<a id="rst-drivers-w1-w1-int-c"></a>

### drivers/w1/w1_int.c

W1 internal initialization for master devices.


#### <a id="c-w1_add_master_device"></a>`w1_add_master_device()`

```c
int w1_add_master_device(struct w1_bus_master *master)
```

registers a new master device

**Parameters**

- `struct w1_bus_master *master`: master bus device to register

#### <a id="c-w1_remove_master_device"></a>`w1_remove_master_device()`

```c
void w1_remove_master_device(struct w1_bus_master *bm)
```

unregister a master device

**Parameters**

- `struct w1_bus_master *bm`: master bus device to remove


<a id="rst-drivers-w1-w1-netlink-h"></a>

### drivers/w1/w1_netlink.h

W1 external netlink API structures and commands.


#### <a id="c-enum-w1_cn_msg_flags"></a>`enum w1_cn_msg_flags`

bitfield flags for struct cn_msg.flags

**Constants**

- `W1_CN_BUNDLE`: Request bundling replies into fewer messagse.  Be prepared
  to handle multiple struct cn_msg, struct w1_netlink_msg, and
  struct w1_netlink_cmd in one packet.

#### <a id="c-enum-w1_netlink_message_types"></a>`enum w1_netlink_message_types`

message type

**Constants**

- `W1_SLAVE_ADD`: notification that a slave device was added
- `W1_SLAVE_REMOVE`: notification that a slave device was removed
- `W1_MASTER_ADD`: notification that a new bus master was added
- `W1_MASTER_REMOVE`: notification that a bus masterwas removed
- `W1_MASTER_CMD`: initiate operations on a specific master
- `W1_SLAVE_CMD`: sends reset, selects the slave, then does a read/write/touch
  operation
- `W1_LIST_MASTERS`: used to determine the bus master identifiers

#### <a id="c-struct-w1_netlink_msg"></a>`struct w1_netlink_msg`

holds w1 message type, id, and result

**Definition**

```c
struct w1_netlink_msg {
    __u8 type;
    __u8 status;
    __u16 len;
    union {
        __u8 id[8];
        struct w1_mst {
            __u32 id;
            __u32 res;
        } mst;
    } id;
    __u8 data[];
};
```

**Members**

- `type`: one of enum w1_netlink_message_types
- `status`: kernel feedback for success 0 or errno failure value
- `len`: length of data following w1_netlink_msg
- `id`: union holding bus master id (msg.id) and slave device id (id\[8\]).
- `id.id`: Slave ID (8 bytes)
- `id.mst`: bus master identification
- `id.mst.id`: bus master ID
- `id.mst.res`: bus master reserved
- `data`: start address of any following data

**Description**

The base message structure for w1 messages over netlink.
The netlink connector data sequence is, struct nlmsghdr, struct cn_msg,
then one or more struct w1_netlink_msg (each with optional data).

#### <a id="c-enum-w1_commands"></a>`enum w1_commands`

commands available for master or slave operations

**Constants**

- `W1_CMD_READ`: read len bytes
- `W1_CMD_WRITE`: write len bytes
- `W1_CMD_SEARCH`: initiate a standard search, returns only the slave
  devices found during that search
- `W1_CMD_ALARM_SEARCH`: search for devices that are currently alarming
- `W1_CMD_TOUCH`: Touches a series of bytes.
- `W1_CMD_RESET`: sends a bus reset on the given master
- `W1_CMD_SLAVE_ADD`: adds a slave to the given master,
  8 byte slave id at data\[0\]
- `W1_CMD_SLAVE_REMOVE`: removes a slave to the given master,
  8 byte slave id at data\[0\]
- `W1_CMD_LIST_SLAVES`: list of slaves registered on this master
- `W1_CMD_MAX`: number of available commands

#### <a id="c-struct-w1_netlink_cmd"></a>`struct w1_netlink_cmd`

holds the command and data

**Definition**

```c
struct w1_netlink_cmd {
    __u8 cmd;
    __u8 res;
    __u16 len;
    __u8 data[];
};
```

**Members**

- `cmd`: one of enum w1_commands
- `res`: reserved
- `len`: length of data following w1_netlink_cmd
- `data`: start address of any following data

**Description**

One or more struct w1_netlink_cmd is placed starting at w1_netlink_msg.data
each with optional data.


<a id="rst-drivers-w1-w1-io-c"></a>

### drivers/w1/w1_io.c

W1 input/output.


#### <a id="c-w1_touch_bit"></a>`w1_touch_bit()`

```c
u8 w1_touch_bit(struct w1_master *dev, int bit)
```

Generates a write-0 or write-1 cycle and samples the level.

**Parameters**

- `struct w1_master *dev`: the master device
- `int bit`: 0 - write a 0, 1 - write a 0 read the level

#### <a id="c-w1_write_8"></a>`w1_write_8()`

```c
void w1_write_8(struct w1_master *dev, u8 byte)
```

Writes 8 bits.

**Parameters**

- `struct w1_master *dev`: the master device
- `u8 byte`: the byte to write

#### <a id="c-w1_triplet"></a>`w1_triplet()`

```c
u8 w1_triplet(struct w1_master *dev, int bdir)
```

* Does a triplet - used for searching ROM addresses.

**Parameters**

- `struct w1_master *dev`: the master device
- `int bdir`: the bit to write if both id_bit and comp_bit are 0

**Description**

- Return bits:
  bit 0 = id_bit
  bit 1 = comp_bit
  bit 2 = dir_taken

If both bits 0 & 1 are set, the search should be restarted.

**Return**

bit fields - see above

#### <a id="c-w1_read_8"></a>`w1_read_8()`

```c
u8 w1_read_8(struct w1_master *dev)
```

Reads 8 bits.

**Parameters**

- `struct w1_master *dev`: the master device

**Return**

the byte read

#### <a id="c-w1_write_block"></a>`w1_write_block()`

```c
void w1_write_block(struct w1_master *dev, const u8 *buf, int len)
```

Writes a series of bytes.

**Parameters**

- `struct w1_master *dev`: the master device
- `const u8 *buf`: pointer to the data to write
- `int len`: the number of bytes to write

#### <a id="c-w1_touch_block"></a>`w1_touch_block()`

```c
void w1_touch_block(struct w1_master *dev, u8 *buf, int len)
```

Touches a series of bytes.

**Parameters**

- `struct w1_master *dev`: the master device
- `u8 *buf`: pointer to the data to write
- `int len`: the number of bytes to write

#### <a id="c-w1_read_block"></a>`w1_read_block()`

```c
u8 w1_read_block(struct w1_master *dev, u8 *buf, int len)
```

Reads a series of bytes.

**Parameters**

- `struct w1_master *dev`: the master device
- `u8 *buf`: pointer to the buffer to fill
- `int len`: the number of bytes to read

**Return**

the number of bytes read

#### <a id="c-w1_reset_bus"></a>`w1_reset_bus()`

```c
int w1_reset_bus(struct w1_master *dev)
```

Issues a reset bus sequence.

**Parameters**

- `struct w1_master *dev`: the master device

**Return**

0=Device present, 1=No device present or error

#### <a id="c-w1_reset_select_slave"></a>`w1_reset_select_slave()`

```c
int w1_reset_select_slave(struct w1_slave *sl)
```

reset and select a slave

**Parameters**

- `struct w1_slave *sl`: the slave to select

**Description**

Resets the bus and then selects the slave by sending either a skip rom
or a rom match.  A skip rom is issued if there is only one device
registered on the bus.
The w1 master lock must be held.

**Return**

0=success, anything else=error

#### <a id="c-w1_reset_resume_command"></a>`w1_reset_resume_command()`

```c
int w1_reset_resume_command(struct w1_master *dev)
```

resume instead of another match ROM

**Parameters**

- `struct w1_master *dev`: the master device

**Description**

When the workflow with a slave amongst many requires several
successive commands a reset between each, this function is similar
to doing a reset then a match ROM for the last matched ROM. The
advantage being that the matched ROM step is skipped in favor of the
resume command. The slave must support the command of course.

If the bus has only one slave, traditionnaly the match ROM is skipped
and a "SKIP ROM" is done for efficiency. On multi-slave busses, this
doesn't work of course, but the resume command is the next best thing.

The w1 master lock must be held.

#### <a id="c-w1_next_pullup"></a>`w1_next_pullup()`

```c
void w1_next_pullup(struct w1_master *dev, int delay)
```

register for a strong pullup

**Parameters**

- `struct w1_master *dev`: the master device
- `int delay`: time in milliseconds

**Description**

Put out a strong pull-up of the specified duration after the next write
operation.  Not all hardware supports strong pullups.  Hardware that
doesn't support strong pullups will sleep for the given time after the
write operation without a strong pullup.  This is a one shot request for
the next write, specifying zero will clear a previous request.
The w1 master lock must be held.

**Return**

0=success, anything else=error



#### <a id="c-w1_write_bit"></a>`w1_write_bit()`

```c
void w1_write_bit(struct w1_master *dev, int bit)
```

Generates a write-0 or write-1 cycle.

**Parameters**

- `struct w1_master *dev`: the master device
- `int bit`: bit to write

**Description**

Only call if dev->bus_master->touch_bit is NULL

#### <a id="c-w1_pre_write"></a>`w1_pre_write()`

```c
void w1_pre_write(struct w1_master *dev)
```

pre-write operations

**Parameters**

- `struct w1_master *dev`: the master device

**Description**

Pre-write operation, currently only supporting strong pullups.
Program the hardware for a strong pullup, if one has been requested and
the hardware supports it.

#### <a id="c-w1_post_write"></a>`w1_post_write()`

```c
void w1_post_write(struct w1_master *dev)
```

post-write options

**Parameters**

- `struct w1_master *dev`: the master device

**Description**

Post-write operation, currently only supporting strong pullups.
If a strong pullup was requested, clear it if the hardware supports
them, or execute the delay otherwise, in either case clear the request.

#### <a id="c-w1_read_bit"></a>`w1_read_bit()`

```c
u8 w1_read_bit(struct w1_master *dev)
```

Generates a write-1 cycle and samples the level.

**Parameters**

- `struct w1_master *dev`: the master device

**Description**

Only call if dev->bus_master->touch_bit is NULL

---

# Xillybus driver for generic FPGA interface

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> An FPGA (Field Programmable Gate Array) is a piece of logic hardware, which can be programmed to become virtually anything that is usually found as a dedicated chipset: For instance, a display adapter, network interface card, or even a…

<a id="rst-xillybus-driver-for-generic-fpga-interface"></a>

**Author:** Eli Billauer, Xillybus Ltd. ([http://xillybus.com](<http://xillybus.com>))

**Email:** [eli.billauer@gmail.com](<mailto:eli.billauer@gmail.com>) or as advertised on Xillybus' site.

<!-- Contents:

- Introduction
 -- Background
 -- Xillybus Overview

- Usage
 -- User interface
 -- Synchronization
 -- Seekable pipes

- Internals
 -- Source code organization
 -- Pipe attributes
 -- Host never reads from the FPGA
 -- Channels, pipes, and the message channel
 -- Data streaming
 -- Data granularity
 -- Probing
 -- Buffer allocation
 -- The "nonempty" message (supporting poll) -->

<a id="rst-introduction"></a>

## Introduction

<a id="rst-background"></a>

### Background

An FPGA (Field Programmable Gate Array) is a piece of logic hardware, which can be programmed to become virtually anything that is usually found as a dedicated chipset: For instance, a display adapter, network interface card, or even a processor with its peripherals. FPGAs are the LEGO of hardware: Based upon certain building blocks, you make your own toys the way you like them. It's usually pointless to reimplement something that is already available on the market as a chipset, so FPGAs are mostly used when some special functionality is needed, and the production volume is relatively low (hence not justifying the development of an ASIC).

The challenge with FPGAs is that everything is implemented at a very low level, even lower than assembly language. In order to allow FPGA designers to focus on their specific project, and not reinvent the wheel over and over again, pre-designed building blocks, IP cores, are often used. These are the FPGA parallels of library functions. IP cores may implement certain mathematical functions, a functional unit (e.g. a USB interface), an entire processor (e.g. ARM) or anything that might come handy. Think of them as a building block, with electrical wires dangling on the sides for connection to other blocks.

One of the daunting tasks in FPGA design is communicating with a fullblown operating system (actually, with the processor running it): Implementing the low-level bus protocol and the somewhat higher-level interface with the host (registers, interrupts, DMA etc.) is a project in itself. When the FPGA's function is a well-known one (e.g. a video adapter card, or a NIC), it can make sense to design the FPGA's interface logic specifically for the project. A special driver is then written to present the FPGA as a well-known interface to the kernel and/or user space. In that case, there is no reason to treat the FPGA differently than any device on the bus.

It's however common that the desired data communication doesn't fit any well- known peripheral function. Also, the effort of designing an elegant abstraction for the data exchange is often considered too big. In those cases, a quicker and possibly less elegant solution is sought: The driver is effectively written as a user space program, leaving the kernel space part with just elementary data transport. This still requires designing some interface logic for the FPGA, and write a simple ad-hoc driver for the kernel.

<a id="rst-xillybus-overview"></a>

### Xillybus Overview

Xillybus is an IP core and a Linux driver. Together, they form a kit for elementary data transport between an FPGA and the host, providing pipe-like data streams with a straightforward user interface. It's intended as a low- effort solution for mixed FPGA-host projects, for which it makes sense to have the project-specific part of the driver running in a user-space program.

Since the communication requirements may vary significantly from one FPGA project to another (the number of data pipes needed in each direction and their attributes), there isn't one specific chunk of logic being the Xillybus IP core. Rather, the IP core is configured and built based upon a specification given by its end user.

Xillybus presents independent data streams, which resemble pipes or TCP/IP communication to the user. At the host side, a character device file is used just like any pipe file. On the FPGA side, hardware FIFOs are used to stream the data. This is contrary to a common method of communicating through fixed- sized buffers (even though such buffers are used by Xillybus under the hood). There may be more than a hundred of these streams on a single IP core, but also no more than one, depending on the configuration.

In order to ease the deployment of the Xillybus IP core, it contains a simple data structure which completely defines the core's configuration. The Linux driver fetches this data structure during its initialization process, and sets up the DMA buffers and character devices accordingly. As a result, a single driver is used to work out of the box with any Xillybus IP core.

The data structure just mentioned should not be confused with PCI's configuration space or the Flattened Device Tree.

<a id="rst-usage"></a>

## Usage

<a id="rst-user-interface"></a>

### User interface

On the host, all interface with Xillybus is done through /dev/xillybus\_\* device files, which are generated automatically as the drivers loads. The names of these files depend on the IP core that is loaded in the FPGA (see Probing below). To communicate with the FPGA, open the device file that corresponds to the hardware FIFO you want to send data or receive data from, and use plain write() or read() calls, just like with a regular pipe. In particular, it makes perfect sense to go:



```text
$ cat mydata > /dev/xillybus_thisfifo

$ cat /dev/xillybus_thatfifo > hisdata
```

possibly pressing CTRL-C as some stage, even though the xillybus\_\* pipes have the capability to send an EOF (but may not use it).

The driver and hardware are designed to behave sensibly as pipes, including:

- Supporting non-blocking I/O (by setting O_NONBLOCK on open() ).

- Supporting poll() and select().

- Being bandwidth efficient under load (using DMA) but also handle small pieces of data sent across (like TCP/IP) by autoflushing.

A device file can be read only, write only or bidirectional. Bidirectional device files are treated like two independent pipes (except for sharing a "channel" structure in the implementation code).

<a id="rst-synchronization"></a>

### Synchronization

Xillybus pipes are configured (on the IP core) to be either synchronous or asynchronous. For a synchronous pipe, write() returns successfully only after some data has been submitted and acknowledged by the FPGA. This slows down bulk data transfers, and is nearly impossible for use with streams that require data at a constant rate: There is no data transmitted to the FPGA between write() calls, in particular when the process loses the CPU.

When a pipe is configured asynchronous, write() returns if there was enough room in the buffers to store any of the data in the buffers.

For FPGA to host pipes, asynchronous pipes allow data transfer from the FPGA as soon as the respective device file is opened, regardless of if the data has been requested by a read() call. On synchronous pipes, only the amount of data requested by a read() call is transmitted.

In summary, for synchronous pipes, data between the host and FPGA is transmitted only to satisfy the read() or write() call currently handled by the driver, and those calls wait for the transmission to complete before returning.

Note that the synchronization attribute has nothing to do with the possibility that read() or write() completes less bytes than requested. There is a separate configuration flag ("allowpartial") that determines whether such a partial completion is allowed.

<a id="rst-seekable-pipes"></a>

### Seekable pipes

A synchronous pipe can be configured to have the stream's position exposed to the user logic at the FPGA. Such a pipe is also seekable on the host API. With this feature, a memory or register interface can be attached on the FPGA side to the seekable stream. Reading or writing to a certain address in the attached memory is done by seeking to the desired address, and calling read() or write() as required.

<a id="rst-internals"></a>

## Internals

<a id="rst-source-code-organization"></a>

### Source code organization

The Xillybus driver consists of a core module, xillybus_core.c, and modules that depend on the specific bus interface (xillybus_of.c and xillybus_pcie.c).

The bus specific modules are those probed when a suitable device is found by the kernel. Since the DMA mapping and synchronization functions, which are bus dependent by their nature, are used by the core module, a xilly_endpoint_hardware structure is passed to the core module on initialization. This structure is populated with pointers to wrapper functions which execute the DMA-related operations on the bus.

<a id="rst-pipe-attributes"></a>

### Pipe attributes

Each pipe has a number of attributes which are set when the FPGA component (IP core) is built. They are fetched from the IDT (the data structure which defines the core's configuration, see Probing below) by xilly_setupchannels() in xillybus_core.c as follows:

- is_writebuf: The pipe's direction. A non-zero value means it's an FPGA to host pipe (the FPGA "writes").

- channelnum: The pipe's identification number in communication between the host and FPGA.

- format: The underlying data width. See Data Granularity below.

- allowpartial: A non-zero value means that a read() or write() (whichever applies) may return with less than the requested number of bytes. The common choice is a non-zero value, to match standard UNIX behavior.

- synchronous: A non-zero value means that the pipe is synchronous. See Synchronization above.

- bufsize: Each DMA buffer's size. Always a power of two.

- bufnum: The number of buffers allocated for this pipe. Always a power of two.

- exclusive_open: A non-zero value forces exclusive opening of the associated device file. If the device file is bidirectional, and already opened only in one direction, the opposite direction may be opened once.

- seekable: A non-zero value indicates that the pipe is seekable. See Seekable pipes above.

- supports_nonempty: A non-zero value (which is typical) indicates that the hardware will send the messages that are necessary to support select() and poll() for this pipe.

<a id="rst-host-never-reads-from-the-fpga"></a>

### Host never reads from the FPGA

Even though PCI Express is hotpluggable in general, a typical motherboard doesn't expect a card to go away all of the sudden. But since the PCIe card is based upon reprogrammable logic, a sudden disappearance from the bus is quite likely as a result of an accidental reprogramming of the FPGA while the host is up. In practice, nothing happens immediately in such a situation. But if the host attempts to read from an address that is mapped to the PCI Express device, that leads to an immediate freeze of the system on some motherboards, even though the PCIe standard requires a graceful recovery.

In order to avoid these freezes, the Xillybus driver refrains completely from reading from the device's register space. All communication from the FPGA to the host is done through DMA. In particular, the Interrupt Service Routine doesn't follow the common practice of checking a status register when it's invoked. Rather, the FPGA prepares a small buffer which contains short messages, which inform the host what the interrupt was about.

This mechanism is used on non-PCIe buses as well for the sake of uniformity.

<a id="rst-channels-pipes-and-the-message-channel"></a>

### Channels, pipes, and the message channel

Each of the (possibly bidirectional) pipes presented to the user is allocated a data channel between the FPGA and the host. The distinction between channels and pipes is necessary only because of channel 0, which is used for interrupt- related messages from the FPGA, and has no pipe attached to it.

<a id="rst-data-streaming"></a>

### Data streaming

Even though a non-segmented data stream is presented to the user at both sides, the implementation relies on a set of DMA buffers which is allocated for each channel. For the sake of illustration, let's take the FPGA to host direction: As data streams into the respective channel's interface in the FPGA, the Xillybus IP core writes it to one of the DMA buffers. When the buffer is full, the FPGA informs the host about that (appending a XILLYMSG_OPCODE_RELEASEBUF message channel 0 and sending an interrupt if necessary). The host responds by making the data available for reading through the character device. When all data has been read, the host writes on the FPGA's buffer control register, allowing the buffer's overwriting. Flow control mechanisms exist on both sides to prevent underflows and overflows.

This is not good enough for creating a TCP/IP-like stream: If the data flow stops momentarily before a DMA buffer is filled, the intuitive expectation is that the partial data in buffer will arrive anyhow, despite the buffer not being completed. This is implemented by adding a field in the XILLYMSG_OPCODE_RELEASEBUF message, through which the FPGA informs not just which buffer is submitted, but how much data it contains.

But the FPGA will submit a partially filled buffer only if directed to do so by the host. This situation occurs when the read() method has been blocking for XILLY_RX_TIMEOUT jiffies (currently 10 ms), after which the host commands the FPGA to submit a DMA buffer as soon as it can. This timeout mechanism balances between bus bandwidth efficiency (preventing a lot of partially filled buffers being sent) and a latency held fairly low for tails of data.

A similar setting is used in the host to FPGA direction. The handling of partial DMA buffers is somewhat different, though. The user can tell the driver to submit all data it has in the buffers to the FPGA, by issuing a write() with the byte count set to zero. This is similar to a flush request, but it doesn't block. There is also an autoflushing mechanism, which triggers an equivalent flush roughly XILLY_RX_TIMEOUT jiffies after the last write(). This allows the user to be oblivious about the underlying buffering mechanism and yet enjoy a stream-like interface.

Note that the issue of partial buffer flushing is irrelevant for pipes having the "synchronous" attribute nonzero, since synchronous pipes don't allow data to lay around in the DMA buffers between read() and write() anyhow.

<a id="rst-data-granularity"></a>

### Data granularity

The data arrives or is sent at the FPGA as 8, 16 or 32 bit wide words, as configured by the "format" attribute. Whenever possible, the driver attempts to hide this when the pipe is accessed differently from its natural alignment. For example, reading single bytes from a pipe with 32 bit granularity works with no issues. Writing single bytes to pipes with 16 or 32 bit granularity will also work, but the driver can't send partially completed words to the FPGA, so the transmission of up to one word may be held until it's fully occupied with user data.

This somewhat complicates the handling of host to FPGA streams, because when a buffer is flushed, it may contain up to 3 bytes don't form a word in the FPGA, and hence can't be sent. To prevent loss of data, these leftover bytes need to be moved to the next buffer. The parts in xillybus_core.c that mention "leftovers" in some way are related to this complication.

<a id="rst-probing"></a>

### Probing

As mentioned earlier, the number of pipes that are created when the driver loads and their attributes depend on the Xillybus IP core in the FPGA. During the driver's initialization, a blob containing configuration info, the Interface Description Table (IDT), is sent from the FPGA to the host. The bootstrap process is done in three phases:

1. Acquire the length of the IDT, so a buffer can be allocated for it. This is done by sending a quiesce command to the device, since the acknowledge for this command contains the IDT's buffer length.

2. Acquire the IDT itself.

3. Create the interfaces according to the IDT.

<a id="rst-buffer-allocation"></a>

### Buffer allocation

In order to simplify the logic that prevents illegal boundary crossings of PCIe packets, the following rule applies: If a buffer is smaller than 4kB, it must not cross a 4kB boundary. Otherwise, it must be 4kB aligned. The xilly_setupchannels() functions allocates these buffers by requesting whole pages from the kernel, and diving them into DMA buffers as necessary. Since all buffers' sizes are powers of two, it's possible to pack any set of such buffers, with a maximal waste of one page of memory.

All buffers are allocated when the driver is loaded. This is necessary, since large continuous physical memory segments are sometimes requested, which are more likely to be available when the system is freshly booted.

The allocation of buffer memory takes place in the same order they appear in the IDT. The driver relies on a rule that the pipes are sorted with decreasing buffer size in the IDT. If a requested buffer is larger or equal to a page, the necessary number of pages is requested from the kernel, and these are used for this buffer. If the requested buffer is smaller than a page, one single page is requested from the kernel, and that page is partially used. Or, if there already is a partially used page at hand, the buffer is packed into that page. It can be shown that all pages requested from the kernel (except possibly for the last) are 100% utilized this way.

<a id="rst-the-nonempty-message-supporting-poll"></a>

### The "nonempty" message (supporting poll)

In order to support the "poll" method (and hence select() ), there is a small catch regarding the FPGA to host direction: The FPGA may have filled a DMA buffer with some data, but not submitted that buffer. If the host waited for the buffer's submission by the FPGA, there would be a possibility that the FPGA side has sent data, but a select() call would still block, because the host has not received any notification about this. This is solved with XILLYMSG_OPCODE_NONEMPTY messages sent by the FPGA when a channel goes from completely empty to containing some data.

These messages are used only to support poll() and select(). The IP core can be configured not to send them for a slight reduction of bandwidth.

---

# Writing Device Drivers for Zorro Devices

_Peios Kernel / Hardware and drivers / Driver development / Bus programming reference_

> The Zorro bus is the bus used in the Amiga family of computers. Thanks to AutoConfig(tm), it's 100% Plug-and-Play.

<a id="rst-writing-device-drivers-for-zorro-devices"></a>

**Author:** Written by Geert Uytterhoeven &lt;[geert@linux-m68k.org](<mailto:geert@linux-m68k.org>)&gt;

**Last revised:** September 5, 2003

<a id="rst-introduction"></a>

## Introduction

The Zorro bus is the bus used in the Amiga family of computers. Thanks to AutoConfig(tm), it's 100% Plug-and-Play.

There are two types of Zorro buses, Zorro II and Zorro III:

> - The Zorro II address space is 24-bit and lies within the first 16 MB of the Amiga's address map.
>
> - Zorro III is a 32-bit extension of Zorro II, which is backwards compatible with Zorro II. The Zorro III address space lies outside the first 16 MB.

<a id="rst-probing-for-zorro-devices"></a>

## Probing for Zorro Devices

Zorro devices are found by calling `zorro_find_device()`, which returns a pointer to the `next` Zorro device with the specified Zorro ID. A probe loop for the board with Zorro ID `ZORRO_PROD_xxx` looks like:



```text
struct zorro_dev *z = NULL;

while ((z = zorro_find_device(ZORRO_PROD_xxx, z))) {
    if (!zorro_request_region(z->resource.start+MY_START, MY_SIZE,
                              "My explanation"))
    ...
}
```

`ZORRO_WILDCARD` acts as a wildcard and finds any Zorro device. If your driver supports different types of boards, you can use a construct like:



```text
struct zorro_dev *z = NULL;

while ((z = zorro_find_device(ZORRO_WILDCARD, z))) {
    if (z->id != ZORRO_PROD_xxx1 && z->id != ZORRO_PROD_xxx2 && ...)
        continue;
    if (!zorro_request_region(z->resource.start+MY_START, MY_SIZE,
                              "My explanation"))
    ...
}
```

<a id="rst-zorro-resources"></a>

## Zorro Resources

Before you can access a Zorro device's registers, you have to make sure it's not yet in use. This is done using the I/O memory space resource management functions:



```text
request_mem_region()
release_mem_region()
```

Shortcuts to claim the whole device's address space are provided as well:



```text
zorro_request_device
zorro_release_device
```

<a id="rst-accessing-the-zorro-address-space"></a>

## Accessing the Zorro Address Space

The address regions in the Zorro device resources are Zorro bus address regions. Due to the identity bus-physical address mapping on the Zorro bus, they are CPU physical addresses as well.

The treatment of these regions depends on the type of Zorro space:

> - Zorro II address space is always mapped and does not have to be mapped explicitly using z_ioremap().
>
>   Conversion from bus/physical Zorro II addresses to kernel virtual addresses and vice versa is done using:
>
>
>
>   ```text
>   virt_addr = ZTWO_VADDR(bus_addr);
>   bus_addr = ZTWO_PADDR(virt_addr);
>   ```
>
> - Zorro III address space must be mapped explicitly using z_ioremap() first before it can be accessed:
>
>
>
>   ```text
>   virt_addr = z_ioremap(bus_addr, size);
>   ...
>   z_iounmap(virt_addr);
>   ```

<a id="rst-references"></a>

## References

1. linux/include/linux/zorro.h

2. linux/include/uapi/linux/zorro.h

3. linux/include/uapi/linux/zorro_ids.h

4. linux/arch/m68k/include/asm/zorro.h

5. linux/drivers/zorro

6. /proc/bus/zorro
