# Virtio

---

# Virtio

_Peios Kernel / Hardware and drivers / Driver development / Virtio_

> Reference for Virtio.

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

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

- [Virtio on Linux](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/virtio/virtio.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Writing Virtio Drivers](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/driver-api/virtio/writing_virtio_drivers.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

---

# Virtio on Linux

_Peios Kernel / Hardware and drivers / Driver development / Virtio_

> Virtio is an open standard that defines a protocol for communication between drivers and devices of different types, see Chapter 5 ("Device Types") of the virtio spec ([1]). Originally developed as a standard for paravirtualized devices…

<a id="rst-virtio-on-linux"></a>
<a id="rst-virtio"></a>

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

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

## Introduction

Virtio is an open standard that defines a protocol for communication between drivers and devices of different types, see Chapter 5 ("Device Types") of the virtio spec ([\[1\]](<#rst-target-1>)). Originally developed as a standard for paravirtualized devices implemented by a hypervisor, it can be used to interface any compliant device (real or emulated) with a driver.

For illustrative purposes, this document will focus on the common case of a Linux kernel running in a virtual machine and using paravirtualized devices provided by the hypervisor, which exposes them as virtio devices via standard mechanisms such as PCI.

<a id="rst-device-driver-communication-virtqueues"></a>

## Device - Driver communication: virtqueues

Although the virtio devices are really an abstraction layer in the hypervisor, they're exposed to the guest as if they are physical devices using a specific transport method -- PCI, MMIO or CCW -- that is orthogonal to the device itself. The virtio spec defines these transport methods in detail, including device discovery, capabilities and interrupt handling.

The communication between the driver in the guest OS and the device in the hypervisor is done through shared memory (that's what makes virtio devices so efficient) using specialized data structures called virtqueues, which are actually ring buffers <a id="rst-footnote-reference-1"></a>[1](#rst-f1) of buffer descriptors similar to the ones used in a network device:


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

Virtio ring descriptors, 16 bytes long. These can chain together via **next**.

**Definition**

```c
struct vring_desc {
    __virtio64 addr;
    __virtio32 len;
    __virtio16 flags;
    __virtio16 next;
};
```

**Members**

- `addr`: buffer address (guest-physical)
- `len`: buffer length
- `flags`: descriptor flags
- `next`: index of the next descriptor in the chain,
  if the VRING_DESC_F_NEXT flag is set. We chain unused
  descriptors via this, too.


All the buffers the descriptors point to are allocated by the guest and used by the host either for reading or for writing but not for both.

Refer to Chapter 2.5 ("Virtqueues") of the virtio spec ([\[1\]](<#rst-target-1>)) for the reference definitions of virtqueues and "Virtqueues and virtio ring: How the data travels" blog post ([\[2\]](<#rst-target-2>)) for an illustrated overview of how the host device and the guest driver communicate.

The `vring_virtqueue` struct models a virtqueue, including the ring buffers and management data. Embedded in this struct is the `virtqueue` struct, which is the data structure that's ultimately used by virtio drivers:


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

a queue to register buffers for sending or receiving.

**Definition**

```c
struct virtqueue {
    struct list_head list;
    void (*callback)(struct virtqueue *vq);
    const char *name;
    struct virtio_device *vdev;
    unsigned int index;
    unsigned int num_free;
    unsigned int num_max;
    bool reset;
    void *priv;
};
```

**Members**

- `list`: the chain of virtqueues for this device
- `callback`: the function to call when buffers are consumed (can be NULL).
- `name`: the name of this virtqueue (mainly for debugging)
- `vdev`: the virtio device this queue was created for.
- `index`: the zero-based ordinal number for this queue.
- `num_free`: number of elements we expect to be able to fit.
- `num_max`: the maximum number of elements supported by the device.
- `reset`: vq is in reset state or not.
- `priv`: a pointer for the virtqueue implementation to use.

**Description**

A note on **num_free**: with indirect buffers, each buffer needs one
element in the queue, otherwise a buffer will need one element per
sg element.


The callback function pointed by this struct is triggered when the device has consumed the buffers provided by the driver. More specifically, the trigger will be an interrupt issued by the hypervisor (see vring\_interrupt()). Interrupt request handlers are registered for a virtqueue during the virtqueue setup process (transport-specific).


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

```c
irqreturn_t vring_interrupt(int irq, void *_vq)
```

notify a virtqueue on an interrupt

**Parameters**

- `int irq`: the IRQ number (ignored)
- `void *_vq`: the struct virtqueue to notify

**Description**

Calls the callback function of **_vq** to process the virtqueue
notification.


<a id="rst-device-discovery-and-probing"></a>

## Device discovery and probing

In the kernel, the virtio core contains the virtio bus driver and transport-specific drivers like `virtio-pci` and `virtio-mmio`. Then there are individual virtio drivers for specific device types that are registered to the virtio bus driver.

How a virtio device is found and configured by the kernel depends on how the hypervisor defines it. Taking the [QEMU virtio-console](<https://gitlab.com/qemu-project/qemu/-/blob/master/hw/char/virtio-console.c>) device as an example. When using PCI as a transport method, the device will present itself on the PCI bus with vendor 0x1af4 (Red Hat, Inc.) and device id 0x1003 (virtio console), as defined in the spec, so the kernel will detect it as it would do with any other PCI device.

During the PCI enumeration process, if a device is found to match the virtio-pci driver (according to the virtio-pci device table, any PCI device with vendor id = 0x1af4):



```text
/* Qumranet donated their vendor ID for devices 0x1000 thru 0x10FF. */
static const struct pci_device_id virtio_pci_id_table[] = {
        { PCI_DEVICE(PCI_VENDOR_ID_REDHAT_QUMRANET, PCI_ANY_ID) },
        { 0 }
};
```

then the virtio-pci driver is probed and, if the probing goes well, the device is registered to the virtio bus:



```text
static int virtio_pci_probe(struct pci_dev *pci_dev,
                            const struct pci_device_id *id)
{
        ...

        if (force_legacy) {
                rc = virtio_pci_legacy_probe(vp_dev);
                /* Also try modern mode if we can't map BAR0 (no IO space). */
                if (rc == -ENODEV || rc == -ENOMEM)
                        rc = virtio_pci_modern_probe(vp_dev);
                if (rc)
                        goto err_probe;
        } else {
                rc = virtio_pci_modern_probe(vp_dev);
                if (rc == -ENODEV)
                        rc = virtio_pci_legacy_probe(vp_dev);
                if (rc)
                        goto err_probe;
        }

        ...

        rc = register_virtio_device(&vp_dev->vdev);
```

When the device is registered to the virtio bus the kernel will look for a driver in the bus that can handle the device and call that driver's `probe` method.

At this point, the virtqueues will be allocated and configured by calling the appropriate `virtio_find` helper function, such as virtio\_find\_single\_vq() or virtio\_find\_vqs(), which will end up calling a transport-specific `find_vqs` method.

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

## References

<a id="rst-target-1"></a>\[1\] Virtio Spec v1.2: [https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html](<https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html>)

<!-- Check for later versions of the spec as well. -->

<a id="rst-target-2"></a>\[2\] Virtqueues and virtio ring: How the data travels [https://www.redhat.com/en/blog/virtqueues-and-virtio-ring-how-data-travels](<https://www.redhat.com/en/blog/virtqueues-and-virtio-ring-how-data-travels>)

**Footnotes**

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



**[1]** that's why they may be also referred to as virtrings.

---

# Writing Virtio Drivers

_Peios Kernel / Hardware and drivers / Driver development / Virtio_

> This document serves as a basic guideline for driver programmers that need to hack a new virtio driver or understand the essentials of the existing ones. See Virtio on Linux <virtio> for a general overview of virtio.

<a id="rst-writing-virtio-drivers-1"></a>
<a id="rst-writing-virtio-drivers"></a>

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

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

## Introduction

This document serves as a basic guideline for driver programmers that need to hack a new virtio driver or understand the essentials of the existing ones. See [Virtio on Linux](</kernel/hardware/driver-api/virtio/virtio.md#rst-virtio>) for a general overview of virtio.

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

## Driver boilerplate

As a bare minimum, a virtio driver needs to register in the virtio bus and configure the virtqueues for the device according to its spec, the configuration of the virtqueues in the driver side must match the virtqueue definitions in the device. A basic driver skeleton could look like this:



```text
#include <linux/virtio.h>
#include <linux/virtio_ids.h>
#include <linux/virtio_config.h>
#include <linux/module.h>

/* device private data (one per device) */
struct virtio_dummy_dev {
        struct virtqueue *vq;
};

static void virtio_dummy_recv_cb(struct virtqueue *vq)
{
        struct virtio_dummy_dev *dev = vq->vdev->priv;
        char *buf;
        unsigned int len;

        while ((buf = virtqueue_get_buf(dev->vq, &len)) != NULL) {
                /* process the received data */
        }
}

static int virtio_dummy_probe(struct virtio_device *vdev)
{
        struct virtio_dummy_dev *dev = NULL;

        /* initialize device data */
        dev = kzalloc(sizeof(struct virtio_dummy_dev), GFP_KERNEL);
        if (!dev)
                return -ENOMEM;

        /* the device has a single virtqueue */
        dev->vq = virtio_find_single_vq(vdev, virtio_dummy_recv_cb, "input");
        if (IS_ERR(dev->vq)) {
                kfree(dev);
                return PTR_ERR(dev->vq);

        }
        vdev->priv = dev;

        /* from this point on, the device can notify and get callbacks */
        virtio_device_ready(vdev);

        return 0;
}

static void virtio_dummy_remove(struct virtio_device *vdev)
{
        struct virtio_dummy_dev *dev = vdev->priv;

        /*
         * disable vq interrupts: equivalent to
         * vdev->config->reset(vdev)
         */
        virtio_reset_device(vdev);

        /* detach unused buffers */
        while ((buf = virtqueue_detach_unused_buf(dev->vq)) != NULL) {
                kfree(buf);
        }

        /* remove virtqueues */
        vdev->config->del_vqs(vdev);

        kfree(dev);
}

static const struct virtio_device_id id_table[] = {
        { VIRTIO_ID_DUMMY, VIRTIO_DEV_ANY_ID },
        { 0 },
};

static struct virtio_driver virtio_dummy_driver = {
        .driver.name =  KBUILD_MODNAME,
        .id_table =     id_table,
        .probe =        virtio_dummy_probe,
        .remove =       virtio_dummy_remove,
};

module_virtio_driver(virtio_dummy_driver);
MODULE_DEVICE_TABLE(virtio, id_table);
MODULE_DESCRIPTION("Dummy virtio driver");
MODULE_LICENSE("GPL");
```

The device id `VIRTIO_ID_DUMMY` here is a placeholder, virtio drivers should be added only for devices that are defined in the spec, see include/uapi/linux/virtio\_ids.h. Device ids need to be at least reserved in the virtio spec before being added to that file.

If your driver doesn't have to do anything special in its `init` and `exit` methods, you can use the module\_virtio\_driver() helper to reduce the amount of boilerplate code.

The `probe` method does the minimum driver setup in this case (memory allocation for the device data) and initializes the virtqueue. virtio\_device\_ready() is used to enable the virtqueue and to notify the device that the driver is ready to manage the device ("DRIVER\_OK"). The virtqueues are anyway enabled automatically by the core after `probe` returns.


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

```c
void virtio_device_ready(struct virtio_device *dev)
```

enable vq use in probe function

**Parameters**

- `struct virtio_device *dev`: the virtio device

**Description**

Driver must call this to use vqs in the probe function.

**Note**

vqs are enabled automatically after probe returns.


In any case, the virtqueues need to be enabled before adding buffers to them.

<a id="rst-sending-and-receiving-data"></a>

## Sending and receiving data

The virtio\_dummy\_recv\_cb() callback in the code above will be triggered when the device notifies the driver after it finishes processing a descriptor or descriptor chain, either for reading or writing. However, that's only the second half of the virtio device-driver communication process, as the communication is always started by the driver regardless of the direction of the data transfer.

To configure a buffer transfer from the driver to the device, first you have to add the buffers -- packed as `scatterlists` -- to the appropriate virtqueue using any of the virtqueue\_add\_inbuf(), virtqueue\_add\_outbuf() or virtqueue\_add\_sgs(), depending on whether you need to add one input `scatterlist` (for the device to fill in), one output `scatterlist` (for the device to consume) or multiple `scatterlists`, respectively. Then, once the virtqueue is set up, a call to virtqueue\_kick() sends a notification that will be serviced by the hypervisor that implements the device:



```text
struct scatterlist sg[1];
sg_init_one(sg, buffer, BUFLEN);
virtqueue_add_inbuf(dev->vq, sg, 1, buffer, GFP_ATOMIC);
virtqueue_kick(dev->vq);
```


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

```c
int virtqueue_add_inbuf(struct virtqueue *vq, struct scatterlist *sg, unsigned int num, void *data, gfp_t gfp)
```

expose input buffers to other end

**Parameters**

- `struct virtqueue *vq`: the struct virtqueue we're talking about.
- `struct scatterlist *sg`: scatterlist (must be well-formed and terminated!)
- `unsigned int num`: the number of entries in **sg** writable by other side
- `void *data`: the token identifying the buffer.
- `gfp_t gfp`: how to do memory allocations (if necessary).

**Description**

Caller must ensure we don't call this with other virtqueue operations
at the same time (except where noted).

Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).



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

```c
int virtqueue_add_outbuf(struct virtqueue *vq, struct scatterlist *sg, unsigned int num, void *data, gfp_t gfp)
```

expose output buffers to other end

**Parameters**

- `struct virtqueue *vq`: the struct virtqueue we're talking about.
- `struct scatterlist *sg`: scatterlist (must be well-formed and terminated!)
- `unsigned int num`: the number of entries in **sg** readable by other side
- `void *data`: the token identifying the buffer.
- `gfp_t gfp`: how to do memory allocations (if necessary).

**Description**

Caller must ensure we don't call this with other virtqueue operations
at the same time (except where noted).

Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).



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

```c
int virtqueue_add_sgs(struct virtqueue *_vq, struct scatterlist *sgs[], unsigned int out_sgs, unsigned int in_sgs, void *data, gfp_t gfp)
```

expose buffers to other end

**Parameters**

- `struct virtqueue *_vq`: the struct virtqueue we're talking about.
- `struct scatterlist *sgs[]`: array of terminated scatterlists.
- `unsigned int out_sgs`: the number of scatterlists readable by other side
- `unsigned int in_sgs`: the number of scatterlists which are writable (after readable ones)
- `void *data`: the token identifying the buffer.
- `gfp_t gfp`: how to do memory allocations (if necessary).

**Description**

Caller must ensure we don't call this with other virtqueue operations
at the same time (except where noted).

Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).

NB: ENOSPC is a special code that is only returned on an attempt to add a
buffer to a full VQ. It indicates that some buffers are outstanding and that
the operation can be retried after some buffers have been used.


Then, after the device has read or written the buffers prepared by the driver and notifies it back, the driver can call virtqueue\_get\_buf() to read the data produced by the device (if the virtqueue was set up with input buffers) or simply to reclaim the buffers if they were already consumed by the device:


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

```c
void * virtqueue_get_buf_ctx(struct virtqueue *_vq, unsigned int *len, void **ctx)
```

get the next used buffer

**Parameters**

- `struct virtqueue *_vq`: the struct virtqueue we're talking about.
- `unsigned int *len`: the length written into the buffer
- `void **ctx`: extra context for the token

**Description**

If the device wrote data into the buffer, **len** will be set to the
amount written.  This means you don't need to clear the buffer
beforehand to ensure there's no data leakage in the case of short
writes.

Caller must ensure we don't call this with other virtqueue
operations at the same time (except where noted).

Returns NULL if there are no used buffers, or the "data" token
handed to virtqueue_add_*().


The virtqueue callbacks can be disabled and re-enabled using the virtqueue\_disable\_cb() and the family of virtqueue\_enable\_cb() functions respectively. See drivers/virtio/virtio\_ring.c for more details:


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

```c
void virtqueue_disable_cb(struct virtqueue *_vq)
```

disable callbacks

**Parameters**

- `struct virtqueue *_vq`: the struct virtqueue we're talking about.

**Description**

Note that this is not necessarily synchronous, hence unreliable and only
useful as an optimization.

Unlike other operations, this need not be serialized.



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

```c
bool virtqueue_enable_cb(struct virtqueue *_vq)
```

restart callbacks after disable_cb.

**Parameters**

- `struct virtqueue *_vq`: the struct virtqueue we're talking about.

**Description**

This re-enables callbacks; it returns "false" if there are pending
buffers in the queue, to detect a possible race between the driver
checking for more work, and enabling callbacks.

Caller must ensure we don't call this with other virtqueue
operations at the same time (except where noted).


But note that some spurious callbacks can still be triggered under certain scenarios. The way to disable callbacks reliably is to reset the device or the virtqueue (virtio\_reset\_device()).

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

## References

<a id="rst-target-1"></a>\[1\] Virtio Spec v1.2: [https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html](<https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html>)

Check for later versions of the spec as well.
