]> nv-tegra.nvidia Code Review - linux-2.6.git/blob - drivers/virtio/virtio_ring.c
virtio: rename virtqueue_add_buf_gfp to virtqueue_add_buf
[linux-2.6.git] / drivers / virtio / virtio_ring.c
1 /* Virtio ring implementation.
2  *
3  *  Copyright 2007 Rusty Russell IBM Corporation
4  *
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.
9  *
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.
14  *
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
18  */
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
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. */
28 #ifdef CONFIG_SMP
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)
38 #else
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()
45 #endif
46
47 #ifdef DEBUG
48 /* For development, we want to crash whenever the ring is screwed. */
49 #define BAD_RING(_vq, fmt, args...)                             \
50         do {                                                    \
51                 dev_err(&(_vq)->vq.vdev->dev,                   \
52                         "%s:"fmt, (_vq)->vq.name, ##args);      \
53                 BUG();                                          \
54         } while (0)
55 /* Caller is supposed to guarantee no reentry. */
56 #define START_USE(_vq)                                          \
57         do {                                                    \
58                 if ((_vq)->in_use)                              \
59                         panic("%s:in_use = %i\n",               \
60                               (_vq)->vq.name, (_vq)->in_use);   \
61                 (_vq)->in_use = __LINE__;                       \
62         } while (0)
63 #define END_USE(_vq) \
64         do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
65 #else
66 #define BAD_RING(_vq, fmt, args...)                             \
67         do {                                                    \
68                 dev_err(&_vq->vq.vdev->dev,                     \
69                         "%s:"fmt, (_vq)->vq.name, ##args);      \
70                 (_vq)->broken = true;                           \
71         } while (0)
72 #define START_USE(vq)
73 #define END_USE(vq)
74 #endif
75
76 struct vring_virtqueue
77 {
78         struct virtqueue vq;
79
80         /* Actual memory layout for this queue */
81         struct vring vring;
82
83         /* Can we use weak barriers? */
84         bool weak_barriers;
85
86         /* Other side has made a mess, don't try any more. */
87         bool broken;
88
89         /* Host supports indirect buffers */
90         bool indirect;
91
92         /* Host publishes avail event idx */
93         bool event;
94
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;
101
102         /* Last used index we've seen. */
103         u16 last_used_idx;
104
105         /* How to notify other side. FIXME: commonalize hcalls! */
106         void (*notify)(struct virtqueue *vq);
107
108 #ifdef DEBUG
109         /* They're supposed to lock for us. */
110         unsigned int in_use;
111 #endif
112
113         /* Tokens for callbacks. */
114         void *data[];
115 };
116
117 #define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
118
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[],
122                               unsigned int out,
123                               unsigned int in,
124                               gfp_t gfp)
125 {
126         struct vring_desc *desc;
127         unsigned head;
128         int i;
129
130         desc = kmalloc((out + in) * sizeof(struct vring_desc), gfp);
131         if (!desc)
132                 return -ENOMEM;
133
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;
139                 desc[i].next = i+1;
140                 sg++;
141         }
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;
146                 desc[i].next = i+1;
147                 sg++;
148         }
149
150         /* Last one doesn't continue. */
151         desc[i-1].flags &= ~VRING_DESC_F_NEXT;
152         desc[i-1].next = 0;
153
154         /* We're about to use a buffer */
155         vq->num_free--;
156
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);
162
163         /* Update free pointer */
164         vq->free_head = vq->vring.desc[head].next;
165
166         return head;
167 }
168
169 /**
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).
177  *
178  * Caller must ensure we don't call this with other virtqueue operations
179  * at the same time (except where noted).
180  *
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.
185  */
186 int virtqueue_add_buf(struct virtqueue *_vq,
187                       struct scatterlist sg[],
188                       unsigned int out,
189                       unsigned int in,
190                       void *data,
191                       gfp_t gfp)
192 {
193         struct vring_virtqueue *vq = to_vvq(_vq);
194         unsigned int i, avail, uninitialized_var(prev);
195         int head;
196
197         START_USE(vq);
198
199         BUG_ON(data == NULL);
200
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))
206                         goto add_head;
207         }
208
209         BUG_ON(out + in > vq->vring.num);
210         BUG_ON(out + in == 0);
211
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. */
218                 if (out)
219                         vq->notify(&vq->vq);
220                 END_USE(vq);
221                 return -ENOSPC;
222         }
223
224         /* We're about to use some buffers from the free list. */
225         vq->num_free -= out + in;
226
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;
232                 prev = i;
233                 sg++;
234         }
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;
239                 prev = i;
240                 sg++;
241         }
242         /* Last one doesn't continue. */
243         vq->vring.desc[prev].flags &= ~VRING_DESC_F_NEXT;
244
245         /* Update free pointer */
246         vq->free_head = i;
247
248 add_head:
249         /* Set token. */
250         vq->data[head] = data;
251
252         /* Put entry in available array (but don't update avail->idx until they
253          * do sync).  FIXME: avoid modulus here? */
254         avail = (vq->vring.avail->idx + vq->num_added++) % vq->vring.num;
255         vq->vring.avail->ring[avail] = head;
256
257         pr_debug("Added buffer head %i to %p\n", head, vq);
258         END_USE(vq);
259
260         return vq->num_free;
261 }
262 EXPORT_SYMBOL_GPL(virtqueue_add_buf);
263
264 /**
265  * virtqueue_kick - update after add_buf
266  * @vq: the struct virtqueue
267  *
268  * After one or more virtqueue_add_buf calls, invoke this to kick
269  * the other side.
270  *
271  * Caller must ensure we don't call this with other virtqueue
272  * operations at the same time (except where noted).
273  */
274 void virtqueue_kick(struct virtqueue *_vq)
275 {
276         struct vring_virtqueue *vq = to_vvq(_vq);
277         u16 new, old;
278         START_USE(vq);
279         /* Descriptors and available array need to be set before we expose the
280          * new available array entries. */
281         virtio_wmb(vq);
282
283         old = vq->vring.avail->idx;
284         new = vq->vring.avail->idx = old + vq->num_added;
285         vq->num_added = 0;
286
287         /* Need to update avail index before checking if we should notify */
288         virtio_mb(vq);
289
290         if (vq->event ?
291             vring_need_event(vring_avail_event(&vq->vring), new, old) :
292             !(vq->vring.used->flags & VRING_USED_F_NO_NOTIFY))
293                 /* Prod other side to tell it about changes. */
294                 vq->notify(&vq->vq);
295
296         END_USE(vq);
297 }
298 EXPORT_SYMBOL_GPL(virtqueue_kick);
299
300 static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
301 {
302         unsigned int i;
303
304         /* Clear data ptr. */
305         vq->data[head] = NULL;
306
307         /* Put back on free list: find end */
308         i = head;
309
310         /* Free the indirect table */
311         if (vq->vring.desc[i].flags & VRING_DESC_F_INDIRECT)
312                 kfree(phys_to_virt(vq->vring.desc[i].addr));
313
314         while (vq->vring.desc[i].flags & VRING_DESC_F_NEXT) {
315                 i = vq->vring.desc[i].next;
316                 vq->num_free++;
317         }
318
319         vq->vring.desc[i].next = vq->free_head;
320         vq->free_head = head;
321         /* Plus final descriptor */
322         vq->num_free++;
323 }
324
325 static inline bool more_used(const struct vring_virtqueue *vq)
326 {
327         return vq->last_used_idx != vq->vring.used->idx;
328 }
329
330 /**
331  * virtqueue_get_buf - get the next used buffer
332  * @vq: the struct virtqueue we're talking about.
333  * @len: the length written into the buffer
334  *
335  * If the driver wrote data into the buffer, @len will be set to the
336  * amount written.  This means you don't need to clear the buffer
337  * beforehand to ensure there's no data leakage in the case of short
338  * writes.
339  *
340  * Caller must ensure we don't call this with other virtqueue
341  * operations at the same time (except where noted).
342  *
343  * Returns NULL if there are no used buffers, or the "data" token
344  * handed to virtqueue_add_buf().
345  */
346 void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
347 {
348         struct vring_virtqueue *vq = to_vvq(_vq);
349         void *ret;
350         unsigned int i;
351
352         START_USE(vq);
353
354         if (unlikely(vq->broken)) {
355                 END_USE(vq);
356                 return NULL;
357         }
358
359         if (!more_used(vq)) {
360                 pr_debug("No more buffers in queue\n");
361                 END_USE(vq);
362                 return NULL;
363         }
364
365         /* Only get used array entries after they have been exposed by host. */
366         virtio_rmb(vq);
367
368         i = vq->vring.used->ring[vq->last_used_idx%vq->vring.num].id;
369         *len = vq->vring.used->ring[vq->last_used_idx%vq->vring.num].len;
370
371         if (unlikely(i >= vq->vring.num)) {
372                 BAD_RING(vq, "id %u out of range\n", i);
373                 return NULL;
374         }
375         if (unlikely(!vq->data[i])) {
376                 BAD_RING(vq, "id %u is not a head!\n", i);
377                 return NULL;
378         }
379
380         /* detach_buf clears data, so grab it now. */
381         ret = vq->data[i];
382         detach_buf(vq, i);
383         vq->last_used_idx++;
384         /* If we expect an interrupt for the next entry, tell host
385          * by writing event index and flush out the write before
386          * the read in the next get_buf call. */
387         if (!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) {
388                 vring_used_event(&vq->vring) = vq->last_used_idx;
389                 virtio_mb(vq);
390         }
391
392         END_USE(vq);
393         return ret;
394 }
395 EXPORT_SYMBOL_GPL(virtqueue_get_buf);
396
397 /**
398  * virtqueue_disable_cb - disable callbacks
399  * @vq: the struct virtqueue we're talking about.
400  *
401  * Note that this is not necessarily synchronous, hence unreliable and only
402  * useful as an optimization.
403  *
404  * Unlike other operations, this need not be serialized.
405  */
406 void virtqueue_disable_cb(struct virtqueue *_vq)
407 {
408         struct vring_virtqueue *vq = to_vvq(_vq);
409
410         vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
411 }
412 EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
413
414 /**
415  * virtqueue_enable_cb - restart callbacks after disable_cb.
416  * @vq: the struct virtqueue we're talking about.
417  *
418  * This re-enables callbacks; it returns "false" if there are pending
419  * buffers in the queue, to detect a possible race between the driver
420  * checking for more work, and enabling callbacks.
421  *
422  * Caller must ensure we don't call this with other virtqueue
423  * operations at the same time (except where noted).
424  */
425 bool virtqueue_enable_cb(struct virtqueue *_vq)
426 {
427         struct vring_virtqueue *vq = to_vvq(_vq);
428
429         START_USE(vq);
430
431         /* We optimistically turn back on interrupts, then check if there was
432          * more to do. */
433         /* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
434          * either clear the flags bit or point the event index at the next
435          * entry. Always do both to keep code simple. */
436         vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
437         vring_used_event(&vq->vring) = vq->last_used_idx;
438         virtio_mb(vq);
439         if (unlikely(more_used(vq))) {
440                 END_USE(vq);
441                 return false;
442         }
443
444         END_USE(vq);
445         return true;
446 }
447 EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
448
449 /**
450  * virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
451  * @vq: the struct virtqueue we're talking about.
452  *
453  * This re-enables callbacks but hints to the other side to delay
454  * interrupts until most of the available buffers have been processed;
455  * it returns "false" if there are many pending buffers in the queue,
456  * to detect a possible race between the driver checking for more work,
457  * and enabling callbacks.
458  *
459  * Caller must ensure we don't call this with other virtqueue
460  * operations at the same time (except where noted).
461  */
462 bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
463 {
464         struct vring_virtqueue *vq = to_vvq(_vq);
465         u16 bufs;
466
467         START_USE(vq);
468
469         /* We optimistically turn back on interrupts, then check if there was
470          * more to do. */
471         /* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
472          * either clear the flags bit or point the event index at the next
473          * entry. Always do both to keep code simple. */
474         vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
475         /* TODO: tune this threshold */
476         bufs = (u16)(vq->vring.avail->idx - vq->last_used_idx) * 3 / 4;
477         vring_used_event(&vq->vring) = vq->last_used_idx + bufs;
478         virtio_mb(vq);
479         if (unlikely((u16)(vq->vring.used->idx - vq->last_used_idx) > bufs)) {
480                 END_USE(vq);
481                 return false;
482         }
483
484         END_USE(vq);
485         return true;
486 }
487 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
488
489 /**
490  * virtqueue_detach_unused_buf - detach first unused buffer
491  * @vq: the struct virtqueue we're talking about.
492  *
493  * Returns NULL or the "data" token handed to virtqueue_add_buf().
494  * This is not valid on an active queue; it is useful only for device
495  * shutdown.
496  */
497 void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
498 {
499         struct vring_virtqueue *vq = to_vvq(_vq);
500         unsigned int i;
501         void *buf;
502
503         START_USE(vq);
504
505         for (i = 0; i < vq->vring.num; i++) {
506                 if (!vq->data[i])
507                         continue;
508                 /* detach_buf clears data, so grab it now. */
509                 buf = vq->data[i];
510                 detach_buf(vq, i);
511                 vq->vring.avail->idx--;
512                 END_USE(vq);
513                 return buf;
514         }
515         /* That should have freed everything. */
516         BUG_ON(vq->num_free != vq->vring.num);
517
518         END_USE(vq);
519         return NULL;
520 }
521 EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
522
523 irqreturn_t vring_interrupt(int irq, void *_vq)
524 {
525         struct vring_virtqueue *vq = to_vvq(_vq);
526
527         if (!more_used(vq)) {
528                 pr_debug("virtqueue interrupt with no work for %p\n", vq);
529                 return IRQ_NONE;
530         }
531
532         if (unlikely(vq->broken))
533                 return IRQ_HANDLED;
534
535         pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
536         if (vq->vq.callback)
537                 vq->vq.callback(&vq->vq);
538
539         return IRQ_HANDLED;
540 }
541 EXPORT_SYMBOL_GPL(vring_interrupt);
542
543 struct virtqueue *vring_new_virtqueue(unsigned int num,
544                                       unsigned int vring_align,
545                                       struct virtio_device *vdev,
546                                       bool weak_barriers,
547                                       void *pages,
548                                       void (*notify)(struct virtqueue *),
549                                       void (*callback)(struct virtqueue *),
550                                       const char *name)
551 {
552         struct vring_virtqueue *vq;
553         unsigned int i;
554
555         /* We assume num is a power of 2. */
556         if (num & (num - 1)) {
557                 dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
558                 return NULL;
559         }
560
561         vq = kmalloc(sizeof(*vq) + sizeof(void *)*num, GFP_KERNEL);
562         if (!vq)
563                 return NULL;
564
565         vring_init(&vq->vring, num, pages, vring_align);
566         vq->vq.callback = callback;
567         vq->vq.vdev = vdev;
568         vq->vq.name = name;
569         vq->notify = notify;
570         vq->weak_barriers = weak_barriers;
571         vq->broken = false;
572         vq->last_used_idx = 0;
573         vq->num_added = 0;
574         list_add_tail(&vq->vq.list, &vdev->vqs);
575 #ifdef DEBUG
576         vq->in_use = false;
577 #endif
578
579         vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
580         vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
581
582         /* No callback?  Tell other side not to bother us. */
583         if (!callback)
584                 vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
585
586         /* Put everything in free lists. */
587         vq->num_free = num;
588         vq->free_head = 0;
589         for (i = 0; i < num-1; i++) {
590                 vq->vring.desc[i].next = i+1;
591                 vq->data[i] = NULL;
592         }
593         vq->data[i] = NULL;
594
595         return &vq->vq;
596 }
597 EXPORT_SYMBOL_GPL(vring_new_virtqueue);
598
599 void vring_del_virtqueue(struct virtqueue *vq)
600 {
601         list_del(&vq->list);
602         kfree(to_vvq(vq));
603 }
604 EXPORT_SYMBOL_GPL(vring_del_virtqueue);
605
606 /* Manipulates transport-specific feature bits. */
607 void vring_transport_features(struct virtio_device *vdev)
608 {
609         unsigned int i;
610
611         for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
612                 switch (i) {
613                 case VIRTIO_RING_F_INDIRECT_DESC:
614                         break;
615                 case VIRTIO_RING_F_EVENT_IDX:
616                         break;
617                 default:
618                         /* We don't understand this bit. */
619                         clear_bit(i, vdev->features);
620                 }
621         }
622 }
623 EXPORT_SYMBOL_GPL(vring_transport_features);
624
625 /**
626  * virtqueue_get_vring_size - return the size of the virtqueue's vring
627  * @vq: the struct virtqueue containing the vring of interest.
628  *
629  * Returns the size of the vring.  This is mainly used for boasting to
630  * userspace.  Unlike other operations, this need not be serialized.
631  */
632 unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
633 {
634
635         struct vring_virtqueue *vq = to_vvq(_vq);
636
637         return vq->vring.num;
638 }
639 EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
640
641 MODULE_LICENSE("GPL");