1 /* Virtio ring implementation.
3 * Copyright 2007 Rusty Russell IBM Corporation
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 #include <linux/virtio.h>
20 #include <linux/virtio_ring.h>
21 #include <linux/virtio_config.h>
22 #include <linux/device.h>
23 #include <linux/slab.h>
24 #include <linux/module.h>
26 /* virtio guest is communicating with a virtual "device" that actually runs on
27 * a host processor. Memory barriers are used to control SMP effects. */
29 /* Where possible, use SMP barriers which are more lightweight than mandatory
30 * barriers, because mandatory barriers control MMIO effects on accesses
31 * through relaxed memory I/O windows (which virtio-pci does not use). */
32 #define virtio_mb(vq) \
33 do { if ((vq)->weak_barriers) smp_mb(); else mb(); } while(0)
34 #define virtio_rmb(vq) \
35 do { if ((vq)->weak_barriers) smp_rmb(); else rmb(); } while(0)
36 #define virtio_wmb(vq) \
37 do { if ((vq)->weak_barriers) smp_rmb(); else rmb(); } while(0)
39 /* We must force memory ordering even if guest is UP since host could be
40 * running on another CPU, but SMP barriers are defined to barrier() in that
41 * configuration. So fall back to mandatory barriers instead. */
42 #define virtio_mb(vq) mb()
43 #define virtio_rmb(vq) rmb()
44 #define virtio_wmb(vq) wmb()
48 /* For development, we want to crash whenever the ring is screwed. */
49 #define BAD_RING(_vq, fmt, args...) \
51 dev_err(&(_vq)->vq.vdev->dev, \
52 "%s:"fmt, (_vq)->vq.name, ##args); \
55 /* Caller is supposed to guarantee no reentry. */
56 #define START_USE(_vq) \
59 panic("%s:in_use = %i\n", \
60 (_vq)->vq.name, (_vq)->in_use); \
61 (_vq)->in_use = __LINE__; \
63 #define END_USE(_vq) \
64 do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
66 #define BAD_RING(_vq, fmt, args...) \
68 dev_err(&_vq->vq.vdev->dev, \
69 "%s:"fmt, (_vq)->vq.name, ##args); \
70 (_vq)->broken = true; \
76 struct vring_virtqueue
80 /* Actual memory layout for this queue */
83 /* Can we use weak barriers? */
86 /* Other side has made a mess, don't try any more. */
89 /* Host supports indirect buffers */
92 /* Host publishes avail event idx */
95 /* Number of free buffers */
96 unsigned int num_free;
97 /* Head of free buffer list. */
98 unsigned int free_head;
99 /* Number we've added since last sync. */
100 unsigned int num_added;
102 /* Last used index we've seen. */
105 /* How to notify other side. FIXME: commonalize hcalls! */
106 void (*notify)(struct virtqueue *vq);
109 /* They're supposed to lock for us. */
113 /* Tokens for callbacks. */
117 #define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
119 /* Set up an indirect table of descriptors and add it to the queue. */
120 static int vring_add_indirect(struct vring_virtqueue *vq,
121 struct scatterlist sg[],
126 struct vring_desc *desc;
130 desc = kmalloc((out + in) * sizeof(struct vring_desc), gfp);
134 /* Transfer entries from the sg list into the indirect page */
135 for (i = 0; i < out; i++) {
136 desc[i].flags = VRING_DESC_F_NEXT;
137 desc[i].addr = sg_phys(sg);
138 desc[i].len = sg->length;
142 for (; i < (out + in); i++) {
143 desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE;
144 desc[i].addr = sg_phys(sg);
145 desc[i].len = sg->length;
150 /* Last one doesn't continue. */
151 desc[i-1].flags &= ~VRING_DESC_F_NEXT;
154 /* We're about to use a buffer */
157 /* Use a single buffer which doesn't continue */
158 head = vq->free_head;
159 vq->vring.desc[head].flags = VRING_DESC_F_INDIRECT;
160 vq->vring.desc[head].addr = virt_to_phys(desc);
161 vq->vring.desc[head].len = i * sizeof(struct vring_desc);
163 /* Update free pointer */
164 vq->free_head = vq->vring.desc[head].next;
170 * virtqueue_add_buf - expose buffer to other end
171 * @vq: the struct virtqueue we're talking about.
172 * @sg: the description of the buffer(s).
173 * @out_num: the number of sg readable by other side
174 * @in_num: the number of sg which are writable (after readable ones)
175 * @data: the token identifying the buffer.
176 * @gfp: how to do memory allocations (if necessary).
178 * Caller must ensure we don't call this with other virtqueue operations
179 * at the same time (except where noted).
181 * Returns remaining capacity of queue or a negative error
182 * (ie. ENOSPC). Note that it only really makes sense to treat all
183 * positive return values as "available": indirect buffers mean that
184 * we can put an entire sg[] array inside a single queue entry.
186 int virtqueue_add_buf(struct virtqueue *_vq,
187 struct scatterlist sg[],
193 struct vring_virtqueue *vq = to_vvq(_vq);
194 unsigned int i, avail, uninitialized_var(prev);
199 BUG_ON(data == NULL);
201 /* If the host supports indirect descriptor tables, and we have multiple
202 * buffers, then go indirect. FIXME: tune this threshold */
203 if (vq->indirect && (out + in) > 1 && vq->num_free) {
204 head = vring_add_indirect(vq, sg, out, in, gfp);
205 if (likely(head >= 0))
209 BUG_ON(out + in > vq->vring.num);
210 BUG_ON(out + in == 0);
212 if (vq->num_free < out + in) {
213 pr_debug("Can't add buf len %i - avail = %i\n",
214 out + in, vq->num_free);
215 /* FIXME: for historical reasons, we force a notify here if
216 * there are outgoing parts to the buffer. Presumably the
217 * host should service the ring ASAP. */
224 /* We're about to use some buffers from the free list. */
225 vq->num_free -= out + in;
227 head = vq->free_head;
228 for (i = vq->free_head; out; i = vq->vring.desc[i].next, out--) {
229 vq->vring.desc[i].flags = VRING_DESC_F_NEXT;
230 vq->vring.desc[i].addr = sg_phys(sg);
231 vq->vring.desc[i].len = sg->length;
235 for (; in; i = vq->vring.desc[i].next, in--) {
236 vq->vring.desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE;
237 vq->vring.desc[i].addr = sg_phys(sg);
238 vq->vring.desc[i].len = sg->length;
242 /* Last one doesn't continue. */
243 vq->vring.desc[prev].flags &= ~VRING_DESC_F_NEXT;
245 /* Update free pointer */
250 vq->data[head] = data;
252 /* Put entry in available array (but don't update avail->idx until they
254 avail = (vq->vring.avail->idx & (vq->vring.num-1));
255 vq->vring.avail->ring[avail] = head;
257 /* Descriptors and available array need to be set before we expose the
258 * new available array entries. */
260 vq->vring.avail->idx++;
263 /* This is very unlikely, but theoretically possible. Kick
265 if (unlikely(vq->num_added == (1 << 16) - 1))
268 pr_debug("Added buffer head %i to %p\n", head, vq);
273 EXPORT_SYMBOL_GPL(virtqueue_add_buf);
276 * virtqueue_kick_prepare - first half of split virtqueue_kick call.
277 * @vq: the struct virtqueue
279 * Instead of virtqueue_kick(), you can do:
280 * if (virtqueue_kick_prepare(vq))
281 * virtqueue_notify(vq);
283 * This is sometimes useful because the virtqueue_kick_prepare() needs
284 * to be serialized, but the actual virtqueue_notify() call does not.
286 bool virtqueue_kick_prepare(struct virtqueue *_vq)
288 struct vring_virtqueue *vq = to_vvq(_vq);
293 /* Descriptors and available array need to be set before we expose the
294 * new available array entries. */
297 old = vq->vring.avail->idx - vq->num_added;
298 new = vq->vring.avail->idx;
302 needs_kick = vring_need_event(vring_avail_event(&vq->vring),
305 needs_kick = !(vq->vring.used->flags & VRING_USED_F_NO_NOTIFY);
310 EXPORT_SYMBOL_GPL(virtqueue_kick_prepare);
313 * virtqueue_notify - second half of split virtqueue_kick call.
314 * @vq: the struct virtqueue
316 * This does not need to be serialized.
318 void virtqueue_notify(struct virtqueue *_vq)
320 struct vring_virtqueue *vq = to_vvq(_vq);
322 /* Prod other side to tell it about changes. */
325 EXPORT_SYMBOL_GPL(virtqueue_notify);
328 * virtqueue_kick - update after add_buf
329 * @vq: the struct virtqueue
331 * After one or more virtqueue_add_buf calls, invoke this to kick
334 * Caller must ensure we don't call this with other virtqueue
335 * operations at the same time (except where noted).
337 void virtqueue_kick(struct virtqueue *vq)
339 if (virtqueue_kick_prepare(vq))
340 virtqueue_notify(vq);
342 EXPORT_SYMBOL_GPL(virtqueue_kick);
344 static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
348 /* Clear data ptr. */
349 vq->data[head] = NULL;
351 /* Put back on free list: find end */
354 /* Free the indirect table */
355 if (vq->vring.desc[i].flags & VRING_DESC_F_INDIRECT)
356 kfree(phys_to_virt(vq->vring.desc[i].addr));
358 while (vq->vring.desc[i].flags & VRING_DESC_F_NEXT) {
359 i = vq->vring.desc[i].next;
363 vq->vring.desc[i].next = vq->free_head;
364 vq->free_head = head;
365 /* Plus final descriptor */
369 static inline bool more_used(const struct vring_virtqueue *vq)
371 return vq->last_used_idx != vq->vring.used->idx;
375 * virtqueue_get_buf - get the next used buffer
376 * @vq: the struct virtqueue we're talking about.
377 * @len: the length written into the buffer
379 * If the driver wrote data into the buffer, @len will be set to the
380 * amount written. This means you don't need to clear the buffer
381 * beforehand to ensure there's no data leakage in the case of short
384 * Caller must ensure we don't call this with other virtqueue
385 * operations at the same time (except where noted).
387 * Returns NULL if there are no used buffers, or the "data" token
388 * handed to virtqueue_add_buf().
390 void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
392 struct vring_virtqueue *vq = to_vvq(_vq);
399 if (unlikely(vq->broken)) {
404 if (!more_used(vq)) {
405 pr_debug("No more buffers in queue\n");
410 /* Only get used array entries after they have been exposed by host. */
413 last_used = (vq->last_used_idx & (vq->vring.num - 1));
414 i = vq->vring.used->ring[last_used].id;
415 *len = vq->vring.used->ring[last_used].len;
417 if (unlikely(i >= vq->vring.num)) {
418 BAD_RING(vq, "id %u out of range\n", i);
421 if (unlikely(!vq->data[i])) {
422 BAD_RING(vq, "id %u is not a head!\n", i);
426 /* detach_buf clears data, so grab it now. */
430 /* If we expect an interrupt for the next entry, tell host
431 * by writing event index and flush out the write before
432 * the read in the next get_buf call. */
433 if (!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) {
434 vring_used_event(&vq->vring) = vq->last_used_idx;
441 EXPORT_SYMBOL_GPL(virtqueue_get_buf);
444 * virtqueue_disable_cb - disable callbacks
445 * @vq: the struct virtqueue we're talking about.
447 * Note that this is not necessarily synchronous, hence unreliable and only
448 * useful as an optimization.
450 * Unlike other operations, this need not be serialized.
452 void virtqueue_disable_cb(struct virtqueue *_vq)
454 struct vring_virtqueue *vq = to_vvq(_vq);
456 vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
458 EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
461 * virtqueue_enable_cb - restart callbacks after disable_cb.
462 * @vq: the struct virtqueue we're talking about.
464 * This re-enables callbacks; it returns "false" if there are pending
465 * buffers in the queue, to detect a possible race between the driver
466 * checking for more work, and enabling callbacks.
468 * Caller must ensure we don't call this with other virtqueue
469 * operations at the same time (except where noted).
471 bool virtqueue_enable_cb(struct virtqueue *_vq)
473 struct vring_virtqueue *vq = to_vvq(_vq);
477 /* We optimistically turn back on interrupts, then check if there was
479 /* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
480 * either clear the flags bit or point the event index at the next
481 * entry. Always do both to keep code simple. */
482 vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
483 vring_used_event(&vq->vring) = vq->last_used_idx;
485 if (unlikely(more_used(vq))) {
493 EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
496 * virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
497 * @vq: the struct virtqueue we're talking about.
499 * This re-enables callbacks but hints to the other side to delay
500 * interrupts until most of the available buffers have been processed;
501 * it returns "false" if there are many pending buffers in the queue,
502 * to detect a possible race between the driver checking for more work,
503 * and enabling callbacks.
505 * Caller must ensure we don't call this with other virtqueue
506 * operations at the same time (except where noted).
508 bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
510 struct vring_virtqueue *vq = to_vvq(_vq);
515 /* We optimistically turn back on interrupts, then check if there was
517 /* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
518 * either clear the flags bit or point the event index at the next
519 * entry. Always do both to keep code simple. */
520 vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
521 /* TODO: tune this threshold */
522 bufs = (u16)(vq->vring.avail->idx - vq->last_used_idx) * 3 / 4;
523 vring_used_event(&vq->vring) = vq->last_used_idx + bufs;
525 if (unlikely((u16)(vq->vring.used->idx - vq->last_used_idx) > bufs)) {
533 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
536 * virtqueue_detach_unused_buf - detach first unused buffer
537 * @vq: the struct virtqueue we're talking about.
539 * Returns NULL or the "data" token handed to virtqueue_add_buf().
540 * This is not valid on an active queue; it is useful only for device
543 void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
545 struct vring_virtqueue *vq = to_vvq(_vq);
551 for (i = 0; i < vq->vring.num; i++) {
554 /* detach_buf clears data, so grab it now. */
557 vq->vring.avail->idx--;
561 /* That should have freed everything. */
562 BUG_ON(vq->num_free != vq->vring.num);
567 EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
569 irqreturn_t vring_interrupt(int irq, void *_vq)
571 struct vring_virtqueue *vq = to_vvq(_vq);
573 if (!more_used(vq)) {
574 pr_debug("virtqueue interrupt with no work for %p\n", vq);
578 if (unlikely(vq->broken))
581 pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
583 vq->vq.callback(&vq->vq);
587 EXPORT_SYMBOL_GPL(vring_interrupt);
589 struct virtqueue *vring_new_virtqueue(unsigned int num,
590 unsigned int vring_align,
591 struct virtio_device *vdev,
594 void (*notify)(struct virtqueue *),
595 void (*callback)(struct virtqueue *),
598 struct vring_virtqueue *vq;
601 /* We assume num is a power of 2. */
602 if (num & (num - 1)) {
603 dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
607 vq = kmalloc(sizeof(*vq) + sizeof(void *)*num, GFP_KERNEL);
611 vring_init(&vq->vring, num, pages, vring_align);
612 vq->vq.callback = callback;
616 vq->weak_barriers = weak_barriers;
618 vq->last_used_idx = 0;
620 list_add_tail(&vq->vq.list, &vdev->vqs);
625 vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
626 vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
628 /* No callback? Tell other side not to bother us. */
630 vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
632 /* Put everything in free lists. */
635 for (i = 0; i < num-1; i++) {
636 vq->vring.desc[i].next = i+1;
643 EXPORT_SYMBOL_GPL(vring_new_virtqueue);
645 void vring_del_virtqueue(struct virtqueue *vq)
650 EXPORT_SYMBOL_GPL(vring_del_virtqueue);
652 /* Manipulates transport-specific feature bits. */
653 void vring_transport_features(struct virtio_device *vdev)
657 for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
659 case VIRTIO_RING_F_INDIRECT_DESC:
661 case VIRTIO_RING_F_EVENT_IDX:
664 /* We don't understand this bit. */
665 clear_bit(i, vdev->features);
669 EXPORT_SYMBOL_GPL(vring_transport_features);
672 * virtqueue_get_vring_size - return the size of the virtqueue's vring
673 * @vq: the struct virtqueue containing the vring of interest.
675 * Returns the size of the vring. This is mainly used for boasting to
676 * userspace. Unlike other operations, this need not be serialized.
678 unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
681 struct vring_virtqueue *vq = to_vvq(_vq);
683 return vq->vring.num;
685 EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
687 MODULE_LICENSE("GPL");