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>
25 #include <linux/hrtimer.h>
26 #include <linux/kmemleak.h>
29 /* For development, we want to crash whenever the ring is screwed. */
30 #define BAD_RING(_vq, fmt, args...) \
32 dev_err(&(_vq)->vq.vdev->dev, \
33 "%s:"fmt, (_vq)->vq.name, ##args); \
36 /* Caller is supposed to guarantee no reentry. */
37 #define START_USE(_vq) \
40 panic("%s:in_use = %i\n", \
41 (_vq)->vq.name, (_vq)->in_use); \
42 (_vq)->in_use = __LINE__; \
44 #define END_USE(_vq) \
45 do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
47 #define BAD_RING(_vq, fmt, args...) \
49 dev_err(&_vq->vq.vdev->dev, \
50 "%s:"fmt, (_vq)->vq.name, ##args); \
51 (_vq)->broken = true; \
57 struct vring_virtqueue
61 /* Actual memory layout for this queue */
64 /* Can we use weak barriers? */
67 /* Other side has made a mess, don't try any more. */
70 /* Host supports indirect buffers */
73 /* Host publishes avail event idx */
76 /* Head of free buffer list. */
77 unsigned int free_head;
78 /* Number we've added since last sync. */
79 unsigned int num_added;
81 /* Last used index we've seen. */
84 /* How to notify other side. FIXME: commonalize hcalls! */
85 bool (*notify)(struct virtqueue *vq);
88 /* They're supposed to lock for us. */
91 /* Figure out if their kicks are too delayed. */
92 bool last_add_time_valid;
93 ktime_t last_add_time;
96 /* Tokens for callbacks. */
100 #define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
102 static inline struct scatterlist *sg_next_chained(struct scatterlist *sg,
108 static inline struct scatterlist *sg_next_arr(struct scatterlist *sg,
116 /* Set up an indirect table of descriptors and add it to the queue. */
117 static inline int vring_add_indirect(struct vring_virtqueue *vq,
118 struct scatterlist *sgs[],
119 struct scatterlist *(*next)
120 (struct scatterlist *, unsigned int *),
121 unsigned int total_sg,
122 unsigned int total_out,
123 unsigned int total_in,
124 unsigned int out_sgs,
128 struct vring_desc *desc;
130 struct scatterlist *sg;
134 * We require lowmem mappings for the descriptors because
135 * otherwise virt_to_phys will give us bogus addresses in the
138 gfp &= ~(__GFP_HIGHMEM | __GFP_HIGH);
140 desc = kmalloc(total_sg * sizeof(struct vring_desc), gfp);
144 /* Transfer entries from the sg lists into the indirect page */
146 for (n = 0; n < out_sgs; n++) {
147 for (sg = sgs[n]; sg; sg = next(sg, &total_out)) {
148 desc[i].flags = VRING_DESC_F_NEXT;
149 desc[i].addr = sg_phys(sg);
150 desc[i].len = sg->length;
155 for (; n < (out_sgs + in_sgs); n++) {
156 for (sg = sgs[n]; sg; sg = next(sg, &total_in)) {
157 desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE;
158 desc[i].addr = sg_phys(sg);
159 desc[i].len = sg->length;
164 BUG_ON(i != total_sg);
166 /* Last one doesn't continue. */
167 desc[i-1].flags &= ~VRING_DESC_F_NEXT;
170 /* We're about to use a buffer */
173 /* Use a single buffer which doesn't continue */
174 head = vq->free_head;
175 vq->vring.desc[head].flags = VRING_DESC_F_INDIRECT;
176 vq->vring.desc[head].addr = virt_to_phys(desc);
177 /* kmemleak gives a false positive, as it's hidden by virt_to_phys */
178 kmemleak_ignore(desc);
179 vq->vring.desc[head].len = i * sizeof(struct vring_desc);
181 /* Update free pointer */
182 vq->free_head = vq->vring.desc[head].next;
187 static inline int virtqueue_add(struct virtqueue *_vq,
188 struct scatterlist *sgs[],
189 struct scatterlist *(*next)
190 (struct scatterlist *, unsigned int *),
191 unsigned int total_out,
192 unsigned int total_in,
193 unsigned int out_sgs,
198 struct vring_virtqueue *vq = to_vvq(_vq);
199 struct scatterlist *sg;
200 unsigned int i, n, avail, uninitialized_var(prev), total_sg;
205 BUG_ON(data == NULL);
207 if (unlikely(vq->broken)) {
214 ktime_t now = ktime_get();
216 /* No kick or get, with .1 second between? Warn. */
217 if (vq->last_add_time_valid)
218 WARN_ON(ktime_to_ms(ktime_sub(now, vq->last_add_time))
220 vq->last_add_time = now;
221 vq->last_add_time_valid = true;
225 total_sg = total_in + total_out;
227 /* If the host supports indirect descriptor tables, and we have multiple
228 * buffers, then go indirect. FIXME: tune this threshold */
229 if (vq->indirect && total_sg > 1 && vq->vq.num_free) {
230 head = vring_add_indirect(vq, sgs, next, total_sg, total_out,
232 out_sgs, in_sgs, gfp);
233 if (likely(head >= 0))
237 BUG_ON(total_sg > vq->vring.num);
238 BUG_ON(total_sg == 0);
240 if (vq->vq.num_free < total_sg) {
241 pr_debug("Can't add buf len %i - avail = %i\n",
242 total_sg, vq->vq.num_free);
243 /* FIXME: for historical reasons, we force a notify here if
244 * there are outgoing parts to the buffer. Presumably the
245 * host should service the ring ASAP. */
252 /* We're about to use some buffers from the free list. */
253 vq->vq.num_free -= total_sg;
255 head = i = vq->free_head;
256 for (n = 0; n < out_sgs; n++) {
257 for (sg = sgs[n]; sg; sg = next(sg, &total_out)) {
258 vq->vring.desc[i].flags = VRING_DESC_F_NEXT;
259 vq->vring.desc[i].addr = sg_phys(sg);
260 vq->vring.desc[i].len = sg->length;
262 i = vq->vring.desc[i].next;
265 for (; n < (out_sgs + in_sgs); n++) {
266 for (sg = sgs[n]; sg; sg = next(sg, &total_in)) {
267 vq->vring.desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE;
268 vq->vring.desc[i].addr = sg_phys(sg);
269 vq->vring.desc[i].len = sg->length;
271 i = vq->vring.desc[i].next;
274 /* Last one doesn't continue. */
275 vq->vring.desc[prev].flags &= ~VRING_DESC_F_NEXT;
277 /* Update free pointer */
282 vq->data[head] = data;
284 /* Put entry in available array (but don't update avail->idx until they
286 avail = (vq->vring.avail->idx & (vq->vring.num-1));
287 vq->vring.avail->ring[avail] = head;
289 /* Descriptors and available array need to be set before we expose the
290 * new available array entries. */
291 virtio_wmb(vq->weak_barriers);
292 vq->vring.avail->idx++;
295 /* This is very unlikely, but theoretically possible. Kick
297 if (unlikely(vq->num_added == (1 << 16) - 1))
300 pr_debug("Added buffer head %i to %p\n", head, vq);
307 * virtqueue_add_sgs - expose buffers to other end
308 * @vq: the struct virtqueue we're talking about.
309 * @sgs: array of terminated scatterlists.
310 * @out_num: the number of scatterlists readable by other side
311 * @in_num: the number of scatterlists which are writable (after readable ones)
312 * @data: the token identifying the buffer.
313 * @gfp: how to do memory allocations (if necessary).
315 * Caller must ensure we don't call this with other virtqueue operations
316 * at the same time (except where noted).
318 * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
320 int virtqueue_add_sgs(struct virtqueue *_vq,
321 struct scatterlist *sgs[],
322 unsigned int out_sgs,
327 unsigned int i, total_out, total_in;
329 /* Count them first. */
330 for (i = total_out = total_in = 0; i < out_sgs; i++) {
331 struct scatterlist *sg;
332 for (sg = sgs[i]; sg; sg = sg_next(sg))
335 for (; i < out_sgs + in_sgs; i++) {
336 struct scatterlist *sg;
337 for (sg = sgs[i]; sg; sg = sg_next(sg))
340 return virtqueue_add(_vq, sgs, sg_next_chained,
341 total_out, total_in, out_sgs, in_sgs, data, gfp);
343 EXPORT_SYMBOL_GPL(virtqueue_add_sgs);
346 * virtqueue_add_outbuf - expose output buffers to other end
347 * @vq: the struct virtqueue we're talking about.
348 * @sgs: array of scatterlists (need not be terminated!)
349 * @num: the number of scatterlists readable by other side
350 * @data: the token identifying the buffer.
351 * @gfp: how to do memory allocations (if necessary).
353 * Caller must ensure we don't call this with other virtqueue operations
354 * at the same time (except where noted).
356 * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
358 int virtqueue_add_outbuf(struct virtqueue *vq,
359 struct scatterlist sg[], unsigned int num,
363 return virtqueue_add(vq, &sg, sg_next_arr, num, 0, 1, 0, data, gfp);
365 EXPORT_SYMBOL_GPL(virtqueue_add_outbuf);
368 * virtqueue_add_inbuf - expose input buffers to other end
369 * @vq: the struct virtqueue we're talking about.
370 * @sgs: array of scatterlists (need not be terminated!)
371 * @num: the number of scatterlists writable by other side
372 * @data: the token identifying the buffer.
373 * @gfp: how to do memory allocations (if necessary).
375 * Caller must ensure we don't call this with other virtqueue operations
376 * at the same time (except where noted).
378 * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
380 int virtqueue_add_inbuf(struct virtqueue *vq,
381 struct scatterlist sg[], unsigned int num,
385 return virtqueue_add(vq, &sg, sg_next_arr, 0, num, 0, 1, data, gfp);
387 EXPORT_SYMBOL_GPL(virtqueue_add_inbuf);
390 * virtqueue_kick_prepare - first half of split virtqueue_kick call.
391 * @vq: the struct virtqueue
393 * Instead of virtqueue_kick(), you can do:
394 * if (virtqueue_kick_prepare(vq))
395 * virtqueue_notify(vq);
397 * This is sometimes useful because the virtqueue_kick_prepare() needs
398 * to be serialized, but the actual virtqueue_notify() call does not.
400 bool virtqueue_kick_prepare(struct virtqueue *_vq)
402 struct vring_virtqueue *vq = to_vvq(_vq);
407 /* We need to expose available array entries before checking avail
409 virtio_mb(vq->weak_barriers);
411 old = vq->vring.avail->idx - vq->num_added;
412 new = vq->vring.avail->idx;
416 if (vq->last_add_time_valid) {
417 WARN_ON(ktime_to_ms(ktime_sub(ktime_get(),
418 vq->last_add_time)) > 100);
420 vq->last_add_time_valid = false;
424 needs_kick = vring_need_event(vring_avail_event(&vq->vring),
427 needs_kick = !(vq->vring.used->flags & VRING_USED_F_NO_NOTIFY);
432 EXPORT_SYMBOL_GPL(virtqueue_kick_prepare);
435 * virtqueue_notify - second half of split virtqueue_kick call.
436 * @vq: the struct virtqueue
438 * This does not need to be serialized.
440 * Returns false if host notify failed or queue is broken, otherwise true.
442 bool virtqueue_notify(struct virtqueue *_vq)
444 struct vring_virtqueue *vq = to_vvq(_vq);
446 if (unlikely(vq->broken))
449 /* Prod other side to tell it about changes. */
450 if (!vq->notify(_vq)) {
456 EXPORT_SYMBOL_GPL(virtqueue_notify);
459 * virtqueue_kick - update after add_buf
460 * @vq: the struct virtqueue
462 * After one or more virtqueue_add_* calls, invoke this to kick
465 * Caller must ensure we don't call this with other virtqueue
466 * operations at the same time (except where noted).
468 * Returns false if kick failed, otherwise true.
470 bool virtqueue_kick(struct virtqueue *vq)
472 if (virtqueue_kick_prepare(vq))
473 return virtqueue_notify(vq);
476 EXPORT_SYMBOL_GPL(virtqueue_kick);
478 static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
482 /* Clear data ptr. */
483 vq->data[head] = NULL;
485 /* Put back on free list: find end */
488 /* Free the indirect table */
489 if (vq->vring.desc[i].flags & VRING_DESC_F_INDIRECT)
490 kfree(phys_to_virt(vq->vring.desc[i].addr));
492 while (vq->vring.desc[i].flags & VRING_DESC_F_NEXT) {
493 i = vq->vring.desc[i].next;
497 vq->vring.desc[i].next = vq->free_head;
498 vq->free_head = head;
499 /* Plus final descriptor */
503 static inline bool more_used(const struct vring_virtqueue *vq)
505 return vq->last_used_idx != vq->vring.used->idx;
509 * virtqueue_get_buf - get the next used buffer
510 * @vq: the struct virtqueue we're talking about.
511 * @len: the length written into the buffer
513 * If the driver wrote data into the buffer, @len will be set to the
514 * amount written. This means you don't need to clear the buffer
515 * beforehand to ensure there's no data leakage in the case of short
518 * Caller must ensure we don't call this with other virtqueue
519 * operations at the same time (except where noted).
521 * Returns NULL if there are no used buffers, or the "data" token
522 * handed to virtqueue_add_*().
524 void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
526 struct vring_virtqueue *vq = to_vvq(_vq);
533 if (unlikely(vq->broken)) {
538 if (!more_used(vq)) {
539 pr_debug("No more buffers in queue\n");
544 /* Only get used array entries after they have been exposed by host. */
545 virtio_rmb(vq->weak_barriers);
547 last_used = (vq->last_used_idx & (vq->vring.num - 1));
548 i = vq->vring.used->ring[last_used].id;
549 *len = vq->vring.used->ring[last_used].len;
551 if (unlikely(i >= vq->vring.num)) {
552 BAD_RING(vq, "id %u out of range\n", i);
555 if (unlikely(!vq->data[i])) {
556 BAD_RING(vq, "id %u is not a head!\n", i);
560 /* detach_buf clears data, so grab it now. */
564 /* If we expect an interrupt for the next entry, tell host
565 * by writing event index and flush out the write before
566 * the read in the next get_buf call. */
567 if (!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) {
568 vring_used_event(&vq->vring) = vq->last_used_idx;
569 virtio_mb(vq->weak_barriers);
573 vq->last_add_time_valid = false;
579 EXPORT_SYMBOL_GPL(virtqueue_get_buf);
582 * virtqueue_disable_cb - disable callbacks
583 * @vq: the struct virtqueue we're talking about.
585 * Note that this is not necessarily synchronous, hence unreliable and only
586 * useful as an optimization.
588 * Unlike other operations, this need not be serialized.
590 void virtqueue_disable_cb(struct virtqueue *_vq)
592 struct vring_virtqueue *vq = to_vvq(_vq);
594 vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
596 EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
599 * virtqueue_enable_cb_prepare - restart callbacks after disable_cb
600 * @vq: the struct virtqueue we're talking about.
602 * This re-enables callbacks; it returns current queue state
603 * in an opaque unsigned value. This value should be later tested by
604 * virtqueue_poll, to detect a possible race between the driver checking for
605 * more work, and enabling callbacks.
607 * Caller must ensure we don't call this with other virtqueue
608 * operations at the same time (except where noted).
610 unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
612 struct vring_virtqueue *vq = to_vvq(_vq);
617 /* We optimistically turn back on interrupts, then check if there was
619 /* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
620 * either clear the flags bit or point the event index at the next
621 * entry. Always do both to keep code simple. */
622 vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
623 vring_used_event(&vq->vring) = last_used_idx = vq->last_used_idx;
625 return last_used_idx;
627 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);
630 * virtqueue_poll - query pending used buffers
631 * @vq: the struct virtqueue we're talking about.
632 * @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
634 * Returns "true" if there are pending used buffers in the queue.
636 * This does not need to be serialized.
638 bool virtqueue_poll(struct virtqueue *_vq, unsigned last_used_idx)
640 struct vring_virtqueue *vq = to_vvq(_vq);
642 virtio_mb(vq->weak_barriers);
643 return (u16)last_used_idx != vq->vring.used->idx;
645 EXPORT_SYMBOL_GPL(virtqueue_poll);
648 * virtqueue_enable_cb - restart callbacks after disable_cb.
649 * @vq: the struct virtqueue we're talking about.
651 * This re-enables callbacks; it returns "false" if there are pending
652 * buffers in the queue, to detect a possible race between the driver
653 * checking for more work, and enabling callbacks.
655 * Caller must ensure we don't call this with other virtqueue
656 * operations at the same time (except where noted).
658 bool virtqueue_enable_cb(struct virtqueue *_vq)
660 unsigned last_used_idx = virtqueue_enable_cb_prepare(_vq);
661 return !virtqueue_poll(_vq, last_used_idx);
663 EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
666 * virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
667 * @vq: the struct virtqueue we're talking about.
669 * This re-enables callbacks but hints to the other side to delay
670 * interrupts until most of the available buffers have been processed;
671 * it returns "false" if there are many pending buffers in the queue,
672 * to detect a possible race between the driver checking for more work,
673 * and enabling callbacks.
675 * Caller must ensure we don't call this with other virtqueue
676 * operations at the same time (except where noted).
678 bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
680 struct vring_virtqueue *vq = to_vvq(_vq);
685 /* We optimistically turn back on interrupts, then check if there was
687 /* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
688 * either clear the flags bit or point the event index at the next
689 * entry. Always do both to keep code simple. */
690 vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
691 /* TODO: tune this threshold */
692 bufs = (u16)(vq->vring.avail->idx - vq->last_used_idx) * 3 / 4;
693 vring_used_event(&vq->vring) = vq->last_used_idx + bufs;
694 virtio_mb(vq->weak_barriers);
695 if (unlikely((u16)(vq->vring.used->idx - vq->last_used_idx) > bufs)) {
703 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
706 * virtqueue_detach_unused_buf - detach first unused buffer
707 * @vq: the struct virtqueue we're talking about.
709 * Returns NULL or the "data" token handed to virtqueue_add_*().
710 * This is not valid on an active queue; it is useful only for device
713 void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
715 struct vring_virtqueue *vq = to_vvq(_vq);
721 for (i = 0; i < vq->vring.num; i++) {
724 /* detach_buf clears data, so grab it now. */
727 vq->vring.avail->idx--;
731 /* That should have freed everything. */
732 BUG_ON(vq->vq.num_free != vq->vring.num);
737 EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
739 irqreturn_t vring_interrupt(int irq, void *_vq)
741 struct vring_virtqueue *vq = to_vvq(_vq);
743 if (!more_used(vq)) {
744 pr_debug("virtqueue interrupt with no work for %p\n", vq);
748 if (unlikely(vq->broken))
751 pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
753 vq->vq.callback(&vq->vq);
757 EXPORT_SYMBOL_GPL(vring_interrupt);
759 struct virtqueue *vring_new_virtqueue(unsigned int index,
761 unsigned int vring_align,
762 struct virtio_device *vdev,
765 bool (*notify)(struct virtqueue *),
766 void (*callback)(struct virtqueue *),
769 struct vring_virtqueue *vq;
772 /* We assume num is a power of 2. */
773 if (num & (num - 1)) {
774 dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
778 vq = kmalloc(sizeof(*vq) + sizeof(void *)*num, GFP_KERNEL);
782 vring_init(&vq->vring, num, pages, vring_align);
783 vq->vq.callback = callback;
786 vq->vq.num_free = num;
787 vq->vq.index = index;
789 vq->weak_barriers = weak_barriers;
791 vq->last_used_idx = 0;
793 list_add_tail(&vq->vq.list, &vdev->vqs);
796 vq->last_add_time_valid = false;
799 vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
800 vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
802 /* No callback? Tell other side not to bother us. */
804 vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
806 /* Put everything in free lists. */
808 for (i = 0; i < num-1; i++) {
809 vq->vring.desc[i].next = i+1;
816 EXPORT_SYMBOL_GPL(vring_new_virtqueue);
818 void vring_del_virtqueue(struct virtqueue *vq)
823 EXPORT_SYMBOL_GPL(vring_del_virtqueue);
825 /* Manipulates transport-specific feature bits. */
826 void vring_transport_features(struct virtio_device *vdev)
830 for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
832 case VIRTIO_RING_F_INDIRECT_DESC:
834 case VIRTIO_RING_F_EVENT_IDX:
837 /* We don't understand this bit. */
838 clear_bit(i, vdev->features);
842 EXPORT_SYMBOL_GPL(vring_transport_features);
845 * virtqueue_get_vring_size - return the size of the virtqueue's vring
846 * @vq: the struct virtqueue containing the vring of interest.
848 * Returns the size of the vring. This is mainly used for boasting to
849 * userspace. Unlike other operations, this need not be serialized.
851 unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
854 struct vring_virtqueue *vq = to_vvq(_vq);
856 return vq->vring.num;
858 EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
860 bool virtqueue_is_broken(struct virtqueue *_vq)
862 struct vring_virtqueue *vq = to_vvq(_vq);
866 EXPORT_SYMBOL_GPL(virtqueue_is_broken);
868 MODULE_LICENSE("GPL");