virtio_pci: defer kfree until release callback
[pandora-kernel.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 does not use). */
32 #define virtio_mb() smp_mb()
33 #define virtio_rmb() smp_rmb()
34 #define virtio_wmb() smp_wmb()
35 #else
36 /* We must force memory ordering even if guest is UP since host could be
37  * running on another CPU, but SMP barriers are defined to barrier() in that
38  * configuration. So fall back to mandatory barriers instead. */
39 #define virtio_mb() mb()
40 #define virtio_rmb() rmb()
41 #define virtio_wmb() wmb()
42 #endif
43
44 #ifdef DEBUG
45 /* For development, we want to crash whenever the ring is screwed. */
46 #define BAD_RING(_vq, fmt, args...)                             \
47         do {                                                    \
48                 dev_err(&(_vq)->vq.vdev->dev,                   \
49                         "%s:"fmt, (_vq)->vq.name, ##args);      \
50                 BUG();                                          \
51         } while (0)
52 /* Caller is supposed to guarantee no reentry. */
53 #define START_USE(_vq)                                          \
54         do {                                                    \
55                 if ((_vq)->in_use)                              \
56                         panic("%s:in_use = %i\n",               \
57                               (_vq)->vq.name, (_vq)->in_use);   \
58                 (_vq)->in_use = __LINE__;                       \
59         } while (0)
60 #define END_USE(_vq) \
61         do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
62 #else
63 #define BAD_RING(_vq, fmt, args...)                             \
64         do {                                                    \
65                 dev_err(&_vq->vq.vdev->dev,                     \
66                         "%s:"fmt, (_vq)->vq.name, ##args);      \
67                 (_vq)->broken = true;                           \
68         } while (0)
69 #define START_USE(vq)
70 #define END_USE(vq)
71 #endif
72
73 struct vring_virtqueue
74 {
75         struct virtqueue vq;
76
77         /* Actual memory layout for this queue */
78         struct vring vring;
79
80         /* Other side has made a mess, don't try any more. */
81         bool broken;
82
83         /* Host supports indirect buffers */
84         bool indirect;
85
86         /* Host publishes avail event idx */
87         bool event;
88
89         /* Number of free buffers */
90         unsigned int num_free;
91         /* Head of free buffer list. */
92         unsigned int free_head;
93         /* Number we've added since last sync. */
94         unsigned int num_added;
95
96         /* Last used index we've seen. */
97         u16 last_used_idx;
98
99         /* How to notify other side. FIXME: commonalize hcalls! */
100         void (*notify)(struct virtqueue *vq);
101
102 #ifdef DEBUG
103         /* They're supposed to lock for us. */
104         unsigned int in_use;
105 #endif
106
107         /* Tokens for callbacks. */
108         void *data[];
109 };
110
111 #define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
112
113 /* Set up an indirect table of descriptors and add it to the queue. */
114 static int vring_add_indirect(struct vring_virtqueue *vq,
115                               struct scatterlist sg[],
116                               unsigned int out,
117                               unsigned int in,
118                               gfp_t gfp)
119 {
120         struct vring_desc *desc;
121         unsigned head;
122         int i;
123
124         /*
125          * We require lowmem mappings for the descriptors because
126          * otherwise virt_to_phys will give us bogus addresses in the
127          * virtqueue.
128          */
129         gfp &= ~(__GFP_HIGHMEM | __GFP_HIGH);
130
131         desc = kmalloc((out + in) * sizeof(struct vring_desc), gfp);
132         if (!desc)
133                 return -ENOMEM;
134
135         /* Transfer entries from the sg list into the indirect page */
136         for (i = 0; i < out; i++) {
137                 desc[i].flags = VRING_DESC_F_NEXT;
138                 desc[i].addr = sg_phys(sg);
139                 desc[i].len = sg->length;
140                 desc[i].next = i+1;
141                 sg++;
142         }
143         for (; i < (out + in); i++) {
144                 desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE;
145                 desc[i].addr = sg_phys(sg);
146                 desc[i].len = sg->length;
147                 desc[i].next = i+1;
148                 sg++;
149         }
150
151         /* Last one doesn't continue. */
152         desc[i-1].flags &= ~VRING_DESC_F_NEXT;
153         desc[i-1].next = 0;
154
155         /* We're about to use a buffer */
156         vq->num_free--;
157
158         /* Use a single buffer which doesn't continue */
159         head = vq->free_head;
160         vq->vring.desc[head].flags = VRING_DESC_F_INDIRECT;
161         vq->vring.desc[head].addr = virt_to_phys(desc);
162         vq->vring.desc[head].len = i * sizeof(struct vring_desc);
163
164         /* Update free pointer */
165         vq->free_head = vq->vring.desc[head].next;
166
167         return head;
168 }
169
170 int virtqueue_add_buf_gfp(struct virtqueue *_vq,
171                           struct scatterlist sg[],
172                           unsigned int out,
173                           unsigned int in,
174                           void *data,
175                           gfp_t gfp)
176 {
177         struct vring_virtqueue *vq = to_vvq(_vq);
178         unsigned int i, avail, uninitialized_var(prev);
179         int head;
180
181         START_USE(vq);
182
183         BUG_ON(data == NULL);
184
185         /* If the host supports indirect descriptor tables, and we have multiple
186          * buffers, then go indirect. FIXME: tune this threshold */
187         if (vq->indirect && (out + in) > 1 && vq->num_free) {
188                 head = vring_add_indirect(vq, sg, out, in, gfp);
189                 if (likely(head >= 0))
190                         goto add_head;
191         }
192
193         BUG_ON(out + in > vq->vring.num);
194         BUG_ON(out + in == 0);
195
196         if (vq->num_free < out + in) {
197                 pr_debug("Can't add buf len %i - avail = %i\n",
198                          out + in, vq->num_free);
199                 /* FIXME: for historical reasons, we force a notify here if
200                  * there are outgoing parts to the buffer.  Presumably the
201                  * host should service the ring ASAP. */
202                 if (out)
203                         vq->notify(&vq->vq);
204                 END_USE(vq);
205                 return -ENOSPC;
206         }
207
208         /* We're about to use some buffers from the free list. */
209         vq->num_free -= out + in;
210
211         head = vq->free_head;
212         for (i = vq->free_head; out; i = vq->vring.desc[i].next, out--) {
213                 vq->vring.desc[i].flags = VRING_DESC_F_NEXT;
214                 vq->vring.desc[i].addr = sg_phys(sg);
215                 vq->vring.desc[i].len = sg->length;
216                 prev = i;
217                 sg++;
218         }
219         for (; in; i = vq->vring.desc[i].next, in--) {
220                 vq->vring.desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE;
221                 vq->vring.desc[i].addr = sg_phys(sg);
222                 vq->vring.desc[i].len = sg->length;
223                 prev = i;
224                 sg++;
225         }
226         /* Last one doesn't continue. */
227         vq->vring.desc[prev].flags &= ~VRING_DESC_F_NEXT;
228
229         /* Update free pointer */
230         vq->free_head = i;
231
232 add_head:
233         /* Set token. */
234         vq->data[head] = data;
235
236         /* Put entry in available array (but don't update avail->idx until they
237          * do sync).  FIXME: avoid modulus here? */
238         avail = (vq->vring.avail->idx + vq->num_added++) % vq->vring.num;
239         vq->vring.avail->ring[avail] = head;
240
241         pr_debug("Added buffer head %i to %p\n", head, vq);
242         END_USE(vq);
243
244         return vq->num_free;
245 }
246 EXPORT_SYMBOL_GPL(virtqueue_add_buf_gfp);
247
248 void virtqueue_kick(struct virtqueue *_vq)
249 {
250         struct vring_virtqueue *vq = to_vvq(_vq);
251         u16 new, old;
252         START_USE(vq);
253         /* Descriptors and available array need to be set before we expose the
254          * new available array entries. */
255         virtio_wmb();
256
257         old = vq->vring.avail->idx;
258         new = vq->vring.avail->idx = old + vq->num_added;
259         vq->num_added = 0;
260
261         /* Need to update avail index before checking if we should notify */
262         virtio_mb();
263
264         if (vq->event ?
265             vring_need_event(vring_avail_event(&vq->vring), new, old) :
266             !(vq->vring.used->flags & VRING_USED_F_NO_NOTIFY))
267                 /* Prod other side to tell it about changes. */
268                 vq->notify(&vq->vq);
269
270         END_USE(vq);
271 }
272 EXPORT_SYMBOL_GPL(virtqueue_kick);
273
274 static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
275 {
276         unsigned int i;
277
278         /* Clear data ptr. */
279         vq->data[head] = NULL;
280
281         /* Put back on free list: find end */
282         i = head;
283
284         /* Free the indirect table */
285         if (vq->vring.desc[i].flags & VRING_DESC_F_INDIRECT)
286                 kfree(phys_to_virt(vq->vring.desc[i].addr));
287
288         while (vq->vring.desc[i].flags & VRING_DESC_F_NEXT) {
289                 i = vq->vring.desc[i].next;
290                 vq->num_free++;
291         }
292
293         vq->vring.desc[i].next = vq->free_head;
294         vq->free_head = head;
295         /* Plus final descriptor */
296         vq->num_free++;
297 }
298
299 static inline bool more_used(const struct vring_virtqueue *vq)
300 {
301         return vq->last_used_idx != vq->vring.used->idx;
302 }
303
304 void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
305 {
306         struct vring_virtqueue *vq = to_vvq(_vq);
307         void *ret;
308         unsigned int i;
309
310         START_USE(vq);
311
312         if (unlikely(vq->broken)) {
313                 END_USE(vq);
314                 return NULL;
315         }
316
317         if (!more_used(vq)) {
318                 pr_debug("No more buffers in queue\n");
319                 END_USE(vq);
320                 return NULL;
321         }
322
323         /* Only get used array entries after they have been exposed by host. */
324         virtio_rmb();
325
326         i = vq->vring.used->ring[vq->last_used_idx%vq->vring.num].id;
327         *len = vq->vring.used->ring[vq->last_used_idx%vq->vring.num].len;
328
329         if (unlikely(i >= vq->vring.num)) {
330                 BAD_RING(vq, "id %u out of range\n", i);
331                 return NULL;
332         }
333         if (unlikely(!vq->data[i])) {
334                 BAD_RING(vq, "id %u is not a head!\n", i);
335                 return NULL;
336         }
337
338         /* detach_buf clears data, so grab it now. */
339         ret = vq->data[i];
340         detach_buf(vq, i);
341         vq->last_used_idx++;
342         /* If we expect an interrupt for the next entry, tell host
343          * by writing event index and flush out the write before
344          * the read in the next get_buf call. */
345         if (!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) {
346                 vring_used_event(&vq->vring) = vq->last_used_idx;
347                 virtio_mb();
348         }
349
350         END_USE(vq);
351         return ret;
352 }
353 EXPORT_SYMBOL_GPL(virtqueue_get_buf);
354
355 void virtqueue_disable_cb(struct virtqueue *_vq)
356 {
357         struct vring_virtqueue *vq = to_vvq(_vq);
358
359         vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
360 }
361 EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
362
363 /**
364  * virtqueue_enable_cb_prepare - restart callbacks after disable_cb
365  * @vq: the struct virtqueue we're talking about.
366  *
367  * This re-enables callbacks; it returns current queue state
368  * in an opaque unsigned value. This value should be later tested by
369  * virtqueue_poll, to detect a possible race between the driver checking for
370  * more work, and enabling callbacks.
371  *
372  * Caller must ensure we don't call this with other virtqueue
373  * operations at the same time (except where noted).
374  */
375 unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
376 {
377         struct vring_virtqueue *vq = to_vvq(_vq);
378         u16 last_used_idx;
379
380         START_USE(vq);
381
382         /* We optimistically turn back on interrupts, then check if there was
383          * more to do. */
384         /* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
385          * either clear the flags bit or point the event index at the next
386          * entry. Always do both to keep code simple. */
387         vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
388         vring_used_event(&vq->vring) = last_used_idx = vq->last_used_idx;
389         END_USE(vq);
390         return last_used_idx;
391 }
392 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);
393
394 /**
395  * virtqueue_poll - query pending used buffers
396  * @vq: the struct virtqueue we're talking about.
397  * @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
398  *
399  * Returns "true" if there are pending used buffers in the queue.
400  *
401  * This does not need to be serialized.
402  */
403 bool virtqueue_poll(struct virtqueue *_vq, unsigned last_used_idx)
404 {
405         struct vring_virtqueue *vq = to_vvq(_vq);
406
407         virtio_mb();
408         return (u16)last_used_idx != vq->vring.used->idx;
409 }
410 EXPORT_SYMBOL_GPL(virtqueue_poll);
411
412 /**
413  * virtqueue_enable_cb - restart callbacks after disable_cb.
414  * @vq: the struct virtqueue we're talking about.
415  *
416  * This re-enables callbacks; it returns "false" if there are pending
417  * buffers in the queue, to detect a possible race between the driver
418  * checking for more work, and enabling callbacks.
419  *
420  * Caller must ensure we don't call this with other virtqueue
421  * operations at the same time (except where noted).
422  */
423 bool virtqueue_enable_cb(struct virtqueue *_vq)
424 {
425         unsigned last_used_idx = virtqueue_enable_cb_prepare(_vq);
426         return !virtqueue_poll(_vq, last_used_idx);
427 }
428 EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
429
430 bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
431 {
432         struct vring_virtqueue *vq = to_vvq(_vq);
433         u16 bufs;
434
435         START_USE(vq);
436
437         /* We optimistically turn back on interrupts, then check if there was
438          * more to do. */
439         /* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
440          * either clear the flags bit or point the event index at the next
441          * entry. Always do both to keep code simple. */
442         vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
443         /* TODO: tune this threshold */
444         bufs = (u16)(vq->vring.avail->idx - vq->last_used_idx) * 3 / 4;
445         vring_used_event(&vq->vring) = vq->last_used_idx + bufs;
446         virtio_mb();
447         if (unlikely((u16)(vq->vring.used->idx - vq->last_used_idx) > bufs)) {
448                 END_USE(vq);
449                 return false;
450         }
451
452         END_USE(vq);
453         return true;
454 }
455 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
456
457 void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
458 {
459         struct vring_virtqueue *vq = to_vvq(_vq);
460         unsigned int i;
461         void *buf;
462
463         START_USE(vq);
464
465         for (i = 0; i < vq->vring.num; i++) {
466                 if (!vq->data[i])
467                         continue;
468                 /* detach_buf clears data, so grab it now. */
469                 buf = vq->data[i];
470                 detach_buf(vq, i);
471                 vq->vring.avail->idx--;
472                 END_USE(vq);
473                 return buf;
474         }
475         /* That should have freed everything. */
476         BUG_ON(vq->num_free != vq->vring.num);
477
478         END_USE(vq);
479         return NULL;
480 }
481 EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
482
483 irqreturn_t vring_interrupt(int irq, void *_vq)
484 {
485         struct vring_virtqueue *vq = to_vvq(_vq);
486
487         if (!more_used(vq)) {
488                 pr_debug("virtqueue interrupt with no work for %p\n", vq);
489                 return IRQ_NONE;
490         }
491
492         if (unlikely(vq->broken))
493                 return IRQ_HANDLED;
494
495         pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
496         if (vq->vq.callback)
497                 vq->vq.callback(&vq->vq);
498
499         return IRQ_HANDLED;
500 }
501 EXPORT_SYMBOL_GPL(vring_interrupt);
502
503 struct virtqueue *vring_new_virtqueue(unsigned int num,
504                                       unsigned int vring_align,
505                                       struct virtio_device *vdev,
506                                       void *pages,
507                                       void (*notify)(struct virtqueue *),
508                                       void (*callback)(struct virtqueue *),
509                                       const char *name)
510 {
511         struct vring_virtqueue *vq;
512         unsigned int i;
513
514         /* We assume num is a power of 2. */
515         if (num & (num - 1)) {
516                 dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
517                 return NULL;
518         }
519
520         vq = kmalloc(sizeof(*vq) + sizeof(void *)*num, GFP_KERNEL);
521         if (!vq)
522                 return NULL;
523
524         vring_init(&vq->vring, num, pages, vring_align);
525         vq->vq.callback = callback;
526         vq->vq.vdev = vdev;
527         vq->vq.name = name;
528         vq->notify = notify;
529         vq->broken = false;
530         vq->last_used_idx = 0;
531         vq->num_added = 0;
532         list_add_tail(&vq->vq.list, &vdev->vqs);
533 #ifdef DEBUG
534         vq->in_use = false;
535 #endif
536
537         vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
538         vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
539
540         /* No callback?  Tell other side not to bother us. */
541         if (!callback)
542                 vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
543
544         /* Put everything in free lists. */
545         vq->num_free = num;
546         vq->free_head = 0;
547         for (i = 0; i < num-1; i++) {
548                 vq->vring.desc[i].next = i+1;
549                 vq->data[i] = NULL;
550         }
551         vq->data[i] = NULL;
552
553         return &vq->vq;
554 }
555 EXPORT_SYMBOL_GPL(vring_new_virtqueue);
556
557 void vring_del_virtqueue(struct virtqueue *vq)
558 {
559         list_del(&vq->list);
560         kfree(to_vvq(vq));
561 }
562 EXPORT_SYMBOL_GPL(vring_del_virtqueue);
563
564 /* Manipulates transport-specific feature bits. */
565 void vring_transport_features(struct virtio_device *vdev)
566 {
567         unsigned int i;
568
569         for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
570                 switch (i) {
571                 case VIRTIO_RING_F_INDIRECT_DESC:
572                         break;
573                 case VIRTIO_RING_F_EVENT_IDX:
574                         break;
575                 default:
576                         /* We don't understand this bit. */
577                         clear_bit(i, vdev->features);
578                 }
579         }
580 }
581 EXPORT_SYMBOL_GPL(vring_transport_features);
582
583 /* return the size of the vring within the virtqueue */
584 unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
585 {
586
587         struct vring_virtqueue *vq = to_vvq(_vq);
588
589         return vq->vring.num;
590 }
591 EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
592
593 MODULE_LICENSE("GPL");