GNU Linux-libre 4.4.284-gnu1
[releases.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 #include <linux/hrtimer.h>
26 #include <linux/kmemleak.h>
27
28 #ifdef DEBUG
29 /* For development, we want to crash whenever the ring is screwed. */
30 #define BAD_RING(_vq, fmt, args...)                             \
31         do {                                                    \
32                 dev_err(&(_vq)->vq.vdev->dev,                   \
33                         "%s:"fmt, (_vq)->vq.name, ##args);      \
34                 BUG();                                          \
35         } while (0)
36 /* Caller is supposed to guarantee no reentry. */
37 #define START_USE(_vq)                                          \
38         do {                                                    \
39                 if ((_vq)->in_use)                              \
40                         panic("%s:in_use = %i\n",               \
41                               (_vq)->vq.name, (_vq)->in_use);   \
42                 (_vq)->in_use = __LINE__;                       \
43         } while (0)
44 #define END_USE(_vq) \
45         do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
46 #else
47 #define BAD_RING(_vq, fmt, args...)                             \
48         do {                                                    \
49                 dev_err(&_vq->vq.vdev->dev,                     \
50                         "%s:"fmt, (_vq)->vq.name, ##args);      \
51                 (_vq)->broken = true;                           \
52         } while (0)
53 #define START_USE(vq)
54 #define END_USE(vq)
55 #endif
56
57 struct vring_virtqueue {
58         struct virtqueue vq;
59
60         /* Actual memory layout for this queue */
61         struct vring vring;
62
63         /* Can we use weak barriers? */
64         bool weak_barriers;
65
66         /* Other side has made a mess, don't try any more. */
67         bool broken;
68
69         /* Host supports indirect buffers */
70         bool indirect;
71
72         /* Host publishes avail event idx */
73         bool event;
74
75         /* Head of free buffer list. */
76         unsigned int free_head;
77         /* Number we've added since last sync. */
78         unsigned int num_added;
79
80         /* Last used index we've seen. */
81         u16 last_used_idx;
82
83         /* Last written value to avail->flags */
84         u16 avail_flags_shadow;
85
86         /* Last written value to avail->idx in guest byte order */
87         u16 avail_idx_shadow;
88
89         /* How to notify other side. FIXME: commonalize hcalls! */
90         bool (*notify)(struct virtqueue *vq);
91
92 #ifdef DEBUG
93         /* They're supposed to lock for us. */
94         unsigned int in_use;
95
96         /* Figure out if their kicks are too delayed. */
97         bool last_add_time_valid;
98         ktime_t last_add_time;
99 #endif
100
101         /* Tokens for callbacks. */
102         void *data[];
103 };
104
105 #define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
106
107 static struct vring_desc *alloc_indirect(struct virtqueue *_vq,
108                                          unsigned int total_sg, gfp_t gfp)
109 {
110         struct vring_desc *desc;
111         unsigned int i;
112
113         /*
114          * We require lowmem mappings for the descriptors because
115          * otherwise virt_to_phys will give us bogus addresses in the
116          * virtqueue.
117          */
118         gfp &= ~__GFP_HIGHMEM;
119
120         desc = kmalloc(total_sg * sizeof(struct vring_desc), gfp);
121         if (!desc)
122                 return NULL;
123
124         for (i = 0; i < total_sg; i++)
125                 desc[i].next = cpu_to_virtio16(_vq->vdev, i + 1);
126         return desc;
127 }
128
129 static inline int virtqueue_add(struct virtqueue *_vq,
130                                 struct scatterlist *sgs[],
131                                 unsigned int total_sg,
132                                 unsigned int out_sgs,
133                                 unsigned int in_sgs,
134                                 void *data,
135                                 gfp_t gfp)
136 {
137         struct vring_virtqueue *vq = to_vvq(_vq);
138         struct scatterlist *sg;
139         struct vring_desc *desc;
140         unsigned int i, n, avail, descs_used, uninitialized_var(prev);
141         int head;
142         bool indirect;
143
144         START_USE(vq);
145
146         BUG_ON(data == NULL);
147
148         if (unlikely(vq->broken)) {
149                 END_USE(vq);
150                 return -EIO;
151         }
152
153 #ifdef DEBUG
154         {
155                 ktime_t now = ktime_get();
156
157                 /* No kick or get, with .1 second between?  Warn. */
158                 if (vq->last_add_time_valid)
159                         WARN_ON(ktime_to_ms(ktime_sub(now, vq->last_add_time))
160                                             > 100);
161                 vq->last_add_time = now;
162                 vq->last_add_time_valid = true;
163         }
164 #endif
165
166         BUG_ON(total_sg > vq->vring.num);
167         BUG_ON(total_sg == 0);
168
169         head = vq->free_head;
170
171         /* If the host supports indirect descriptor tables, and we have multiple
172          * buffers, then go indirect. FIXME: tune this threshold */
173         if (vq->indirect && total_sg > 1 && vq->vq.num_free)
174                 desc = alloc_indirect(_vq, total_sg, gfp);
175         else
176                 desc = NULL;
177
178         if (desc) {
179                 /* Use a single buffer which doesn't continue */
180                 vq->vring.desc[head].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_INDIRECT);
181                 vq->vring.desc[head].addr = cpu_to_virtio64(_vq->vdev, virt_to_phys(desc));
182                 /* avoid kmemleak false positive (hidden by virt_to_phys) */
183                 kmemleak_ignore(desc);
184                 vq->vring.desc[head].len = cpu_to_virtio32(_vq->vdev, total_sg * sizeof(struct vring_desc));
185
186                 /* Set up rest to use this indirect table. */
187                 i = 0;
188                 descs_used = 1;
189                 indirect = true;
190         } else {
191                 desc = vq->vring.desc;
192                 i = head;
193                 descs_used = total_sg;
194                 indirect = false;
195         }
196
197         if (vq->vq.num_free < descs_used) {
198                 pr_debug("Can't add buf len %i - avail = %i\n",
199                          descs_used, vq->vq.num_free);
200                 /* FIXME: for historical reasons, we force a notify here if
201                  * there are outgoing parts to the buffer.  Presumably the
202                  * host should service the ring ASAP. */
203                 if (out_sgs)
204                         vq->notify(&vq->vq);
205                 if (indirect)
206                         kfree(desc);
207                 END_USE(vq);
208                 return -ENOSPC;
209         }
210
211         /* We're about to use some buffers from the free list. */
212         vq->vq.num_free -= descs_used;
213
214         for (n = 0; n < out_sgs; n++) {
215                 for (sg = sgs[n]; sg; sg = sg_next(sg)) {
216                         desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT);
217                         desc[i].addr = cpu_to_virtio64(_vq->vdev, sg_phys(sg));
218                         desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
219                         prev = i;
220                         i = virtio16_to_cpu(_vq->vdev, desc[i].next);
221                 }
222         }
223         for (; n < (out_sgs + in_sgs); n++) {
224                 for (sg = sgs[n]; sg; sg = sg_next(sg)) {
225                         desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT | VRING_DESC_F_WRITE);
226                         desc[i].addr = cpu_to_virtio64(_vq->vdev, sg_phys(sg));
227                         desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
228                         prev = i;
229                         i = virtio16_to_cpu(_vq->vdev, desc[i].next);
230                 }
231         }
232         /* Last one doesn't continue. */
233         desc[prev].flags &= cpu_to_virtio16(_vq->vdev, ~VRING_DESC_F_NEXT);
234
235         /* Update free pointer */
236         if (indirect)
237                 vq->free_head = virtio16_to_cpu(_vq->vdev, vq->vring.desc[head].next);
238         else
239                 vq->free_head = i;
240
241         /* Set token. */
242         vq->data[head] = data;
243
244         /* Put entry in available array (but don't update avail->idx until they
245          * do sync). */
246         avail = vq->avail_idx_shadow & (vq->vring.num - 1);
247         vq->vring.avail->ring[avail] = cpu_to_virtio16(_vq->vdev, head);
248
249         /* Descriptors and available array need to be set before we expose the
250          * new available array entries. */
251         virtio_wmb(vq->weak_barriers);
252         vq->avail_idx_shadow++;
253         vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
254         vq->num_added++;
255
256         pr_debug("Added buffer head %i to %p\n", head, vq);
257         END_USE(vq);
258
259         /* This is very unlikely, but theoretically possible.  Kick
260          * just in case. */
261         if (unlikely(vq->num_added == (1 << 16) - 1))
262                 virtqueue_kick(_vq);
263
264         return 0;
265 }
266
267 /**
268  * virtqueue_add_sgs - expose buffers to other end
269  * @vq: the struct virtqueue we're talking about.
270  * @sgs: array of terminated scatterlists.
271  * @out_num: the number of scatterlists readable by other side
272  * @in_num: the number of scatterlists which are writable (after readable ones)
273  * @data: the token identifying the buffer.
274  * @gfp: how to do memory allocations (if necessary).
275  *
276  * Caller must ensure we don't call this with other virtqueue operations
277  * at the same time (except where noted).
278  *
279  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
280  */
281 int virtqueue_add_sgs(struct virtqueue *_vq,
282                       struct scatterlist *sgs[],
283                       unsigned int out_sgs,
284                       unsigned int in_sgs,
285                       void *data,
286                       gfp_t gfp)
287 {
288         unsigned int i, total_sg = 0;
289
290         /* Count them first. */
291         for (i = 0; i < out_sgs + in_sgs; i++) {
292                 struct scatterlist *sg;
293                 for (sg = sgs[i]; sg; sg = sg_next(sg))
294                         total_sg++;
295         }
296         return virtqueue_add(_vq, sgs, total_sg, out_sgs, in_sgs, data, gfp);
297 }
298 EXPORT_SYMBOL_GPL(virtqueue_add_sgs);
299
300 /**
301  * virtqueue_add_outbuf - expose output buffers to other end
302  * @vq: the struct virtqueue we're talking about.
303  * @sg: scatterlist (must be well-formed and terminated!)
304  * @num: the number of entries in @sg readable by other side
305  * @data: the token identifying the buffer.
306  * @gfp: how to do memory allocations (if necessary).
307  *
308  * Caller must ensure we don't call this with other virtqueue operations
309  * at the same time (except where noted).
310  *
311  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
312  */
313 int virtqueue_add_outbuf(struct virtqueue *vq,
314                          struct scatterlist *sg, unsigned int num,
315                          void *data,
316                          gfp_t gfp)
317 {
318         return virtqueue_add(vq, &sg, num, 1, 0, data, gfp);
319 }
320 EXPORT_SYMBOL_GPL(virtqueue_add_outbuf);
321
322 /**
323  * virtqueue_add_inbuf - expose input buffers to other end
324  * @vq: the struct virtqueue we're talking about.
325  * @sg: scatterlist (must be well-formed and terminated!)
326  * @num: the number of entries in @sg writable by other side
327  * @data: the token identifying the buffer.
328  * @gfp: how to do memory allocations (if necessary).
329  *
330  * Caller must ensure we don't call this with other virtqueue operations
331  * at the same time (except where noted).
332  *
333  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
334  */
335 int virtqueue_add_inbuf(struct virtqueue *vq,
336                         struct scatterlist *sg, unsigned int num,
337                         void *data,
338                         gfp_t gfp)
339 {
340         return virtqueue_add(vq, &sg, num, 0, 1, data, gfp);
341 }
342 EXPORT_SYMBOL_GPL(virtqueue_add_inbuf);
343
344 /**
345  * virtqueue_kick_prepare - first half of split virtqueue_kick call.
346  * @vq: the struct virtqueue
347  *
348  * Instead of virtqueue_kick(), you can do:
349  *      if (virtqueue_kick_prepare(vq))
350  *              virtqueue_notify(vq);
351  *
352  * This is sometimes useful because the virtqueue_kick_prepare() needs
353  * to be serialized, but the actual virtqueue_notify() call does not.
354  */
355 bool virtqueue_kick_prepare(struct virtqueue *_vq)
356 {
357         struct vring_virtqueue *vq = to_vvq(_vq);
358         u16 new, old;
359         bool needs_kick;
360
361         START_USE(vq);
362         /* We need to expose available array entries before checking avail
363          * event. */
364         virtio_mb(vq->weak_barriers);
365
366         old = vq->avail_idx_shadow - vq->num_added;
367         new = vq->avail_idx_shadow;
368         vq->num_added = 0;
369
370 #ifdef DEBUG
371         if (vq->last_add_time_valid) {
372                 WARN_ON(ktime_to_ms(ktime_sub(ktime_get(),
373                                               vq->last_add_time)) > 100);
374         }
375         vq->last_add_time_valid = false;
376 #endif
377
378         if (vq->event) {
379                 needs_kick = vring_need_event(virtio16_to_cpu(_vq->vdev, vring_avail_event(&vq->vring)),
380                                               new, old);
381         } else {
382                 needs_kick = !(vq->vring.used->flags & cpu_to_virtio16(_vq->vdev, VRING_USED_F_NO_NOTIFY));
383         }
384         END_USE(vq);
385         return needs_kick;
386 }
387 EXPORT_SYMBOL_GPL(virtqueue_kick_prepare);
388
389 /**
390  * virtqueue_notify - second half of split virtqueue_kick call.
391  * @vq: the struct virtqueue
392  *
393  * This does not need to be serialized.
394  *
395  * Returns false if host notify failed or queue is broken, otherwise true.
396  */
397 bool virtqueue_notify(struct virtqueue *_vq)
398 {
399         struct vring_virtqueue *vq = to_vvq(_vq);
400
401         if (unlikely(vq->broken))
402                 return false;
403
404         /* Prod other side to tell it about changes. */
405         if (!vq->notify(_vq)) {
406                 vq->broken = true;
407                 return false;
408         }
409         return true;
410 }
411 EXPORT_SYMBOL_GPL(virtqueue_notify);
412
413 /**
414  * virtqueue_kick - update after add_buf
415  * @vq: the struct virtqueue
416  *
417  * After one or more virtqueue_add_* calls, invoke this to kick
418  * the other side.
419  *
420  * Caller must ensure we don't call this with other virtqueue
421  * operations at the same time (except where noted).
422  *
423  * Returns false if kick failed, otherwise true.
424  */
425 bool virtqueue_kick(struct virtqueue *vq)
426 {
427         if (virtqueue_kick_prepare(vq))
428                 return virtqueue_notify(vq);
429         return true;
430 }
431 EXPORT_SYMBOL_GPL(virtqueue_kick);
432
433 static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
434 {
435         unsigned int i;
436
437         /* Clear data ptr. */
438         vq->data[head] = NULL;
439
440         /* Put back on free list: find end */
441         i = head;
442
443         /* Free the indirect table */
444         if (vq->vring.desc[i].flags & cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_INDIRECT))
445                 kfree(phys_to_virt(virtio64_to_cpu(vq->vq.vdev, vq->vring.desc[i].addr)));
446
447         while (vq->vring.desc[i].flags & cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_NEXT)) {
448                 i = virtio16_to_cpu(vq->vq.vdev, vq->vring.desc[i].next);
449                 vq->vq.num_free++;
450         }
451
452         vq->vring.desc[i].next = cpu_to_virtio16(vq->vq.vdev, vq->free_head);
453         vq->free_head = head;
454         /* Plus final descriptor */
455         vq->vq.num_free++;
456 }
457
458 static inline bool more_used(const struct vring_virtqueue *vq)
459 {
460         return vq->last_used_idx != virtio16_to_cpu(vq->vq.vdev, vq->vring.used->idx);
461 }
462
463 /**
464  * virtqueue_get_buf - get the next used buffer
465  * @vq: the struct virtqueue we're talking about.
466  * @len: the length written into the buffer
467  *
468  * If the driver wrote data into the buffer, @len will be set to the
469  * amount written.  This means you don't need to clear the buffer
470  * beforehand to ensure there's no data leakage in the case of short
471  * writes.
472  *
473  * Caller must ensure we don't call this with other virtqueue
474  * operations at the same time (except where noted).
475  *
476  * Returns NULL if there are no used buffers, or the "data" token
477  * handed to virtqueue_add_*().
478  */
479 void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
480 {
481         struct vring_virtqueue *vq = to_vvq(_vq);
482         void *ret;
483         unsigned int i;
484         u16 last_used;
485
486         START_USE(vq);
487
488         if (unlikely(vq->broken)) {
489                 END_USE(vq);
490                 return NULL;
491         }
492
493         if (!more_used(vq)) {
494                 pr_debug("No more buffers in queue\n");
495                 END_USE(vq);
496                 return NULL;
497         }
498
499         /* Only get used array entries after they have been exposed by host. */
500         virtio_rmb(vq->weak_barriers);
501
502         last_used = (vq->last_used_idx & (vq->vring.num - 1));
503         i = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].id);
504         *len = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].len);
505
506         if (unlikely(i >= vq->vring.num)) {
507                 BAD_RING(vq, "id %u out of range\n", i);
508                 return NULL;
509         }
510         if (unlikely(!vq->data[i])) {
511                 BAD_RING(vq, "id %u is not a head!\n", i);
512                 return NULL;
513         }
514
515         /* detach_buf clears data, so grab it now. */
516         ret = vq->data[i];
517         detach_buf(vq, i);
518         vq->last_used_idx++;
519         /* If we expect an interrupt for the next entry, tell host
520          * by writing event index and flush out the write before
521          * the read in the next get_buf call. */
522         if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT)) {
523                 vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, vq->last_used_idx);
524                 virtio_mb(vq->weak_barriers);
525         }
526
527 #ifdef DEBUG
528         vq->last_add_time_valid = false;
529 #endif
530
531         END_USE(vq);
532         return ret;
533 }
534 EXPORT_SYMBOL_GPL(virtqueue_get_buf);
535
536 /**
537  * virtqueue_disable_cb - disable callbacks
538  * @vq: the struct virtqueue we're talking about.
539  *
540  * Note that this is not necessarily synchronous, hence unreliable and only
541  * useful as an optimization.
542  *
543  * Unlike other operations, this need not be serialized.
544  */
545 void virtqueue_disable_cb(struct virtqueue *_vq)
546 {
547         struct vring_virtqueue *vq = to_vvq(_vq);
548
549         if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT)) {
550                 vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
551                 if (!vq->event)
552                         vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
553         }
554
555 }
556 EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
557
558 /**
559  * virtqueue_enable_cb_prepare - restart callbacks after disable_cb
560  * @vq: the struct virtqueue we're talking about.
561  *
562  * This re-enables callbacks; it returns current queue state
563  * in an opaque unsigned value. This value should be later tested by
564  * virtqueue_poll, to detect a possible race between the driver checking for
565  * more work, and enabling callbacks.
566  *
567  * Caller must ensure we don't call this with other virtqueue
568  * operations at the same time (except where noted).
569  */
570 unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
571 {
572         struct vring_virtqueue *vq = to_vvq(_vq);
573         u16 last_used_idx;
574
575         START_USE(vq);
576
577         /* We optimistically turn back on interrupts, then check if there was
578          * more to do. */
579         /* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
580          * either clear the flags bit or point the event index at the next
581          * entry. Always do both to keep code simple. */
582         if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
583                 vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
584                 if (!vq->event)
585                         vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
586         }
587         vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, last_used_idx = vq->last_used_idx);
588         END_USE(vq);
589         return last_used_idx;
590 }
591 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);
592
593 /**
594  * virtqueue_poll - query pending used buffers
595  * @vq: the struct virtqueue we're talking about.
596  * @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
597  *
598  * Returns "true" if there are pending used buffers in the queue.
599  *
600  * This does not need to be serialized.
601  */
602 bool virtqueue_poll(struct virtqueue *_vq, unsigned last_used_idx)
603 {
604         struct vring_virtqueue *vq = to_vvq(_vq);
605
606         if (unlikely(vq->broken))
607                 return false;
608
609         virtio_mb(vq->weak_barriers);
610         return (u16)last_used_idx != virtio16_to_cpu(_vq->vdev, vq->vring.used->idx);
611 }
612 EXPORT_SYMBOL_GPL(virtqueue_poll);
613
614 /**
615  * virtqueue_enable_cb - restart callbacks after disable_cb.
616  * @vq: the struct virtqueue we're talking about.
617  *
618  * This re-enables callbacks; it returns "false" if there are pending
619  * buffers in the queue, to detect a possible race between the driver
620  * checking for more work, and enabling callbacks.
621  *
622  * Caller must ensure we don't call this with other virtqueue
623  * operations at the same time (except where noted).
624  */
625 bool virtqueue_enable_cb(struct virtqueue *_vq)
626 {
627         unsigned last_used_idx = virtqueue_enable_cb_prepare(_vq);
628         return !virtqueue_poll(_vq, last_used_idx);
629 }
630 EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
631
632 /**
633  * virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
634  * @vq: the struct virtqueue we're talking about.
635  *
636  * This re-enables callbacks but hints to the other side to delay
637  * interrupts until most of the available buffers have been processed;
638  * it returns "false" if there are many pending buffers in the queue,
639  * to detect a possible race between the driver checking for more work,
640  * and enabling callbacks.
641  *
642  * Caller must ensure we don't call this with other virtqueue
643  * operations at the same time (except where noted).
644  */
645 bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
646 {
647         struct vring_virtqueue *vq = to_vvq(_vq);
648         u16 bufs;
649
650         START_USE(vq);
651
652         /* We optimistically turn back on interrupts, then check if there was
653          * more to do. */
654         /* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
655          * either clear the flags bit or point the event index at the next
656          * entry. Always update the event index to keep code simple. */
657         if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
658                 vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
659                 if (!vq->event)
660                         vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
661         }
662         /* TODO: tune this threshold */
663         bufs = (u16)(vq->avail_idx_shadow - vq->last_used_idx) * 3 / 4;
664         vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, vq->last_used_idx + bufs);
665         virtio_mb(vq->weak_barriers);
666         if (unlikely((u16)(virtio16_to_cpu(_vq->vdev, vq->vring.used->idx) - vq->last_used_idx) > bufs)) {
667                 END_USE(vq);
668                 return false;
669         }
670
671         END_USE(vq);
672         return true;
673 }
674 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
675
676 /**
677  * virtqueue_detach_unused_buf - detach first unused buffer
678  * @vq: the struct virtqueue we're talking about.
679  *
680  * Returns NULL or the "data" token handed to virtqueue_add_*().
681  * This is not valid on an active queue; it is useful only for device
682  * shutdown.
683  */
684 void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
685 {
686         struct vring_virtqueue *vq = to_vvq(_vq);
687         unsigned int i;
688         void *buf;
689
690         START_USE(vq);
691
692         for (i = 0; i < vq->vring.num; i++) {
693                 if (!vq->data[i])
694                         continue;
695                 /* detach_buf clears data, so grab it now. */
696                 buf = vq->data[i];
697                 detach_buf(vq, i);
698                 vq->avail_idx_shadow--;
699                 vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
700                 END_USE(vq);
701                 return buf;
702         }
703         /* That should have freed everything. */
704         BUG_ON(vq->vq.num_free != vq->vring.num);
705
706         END_USE(vq);
707         return NULL;
708 }
709 EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
710
711 irqreturn_t vring_interrupt(int irq, void *_vq)
712 {
713         struct vring_virtqueue *vq = to_vvq(_vq);
714
715         if (!more_used(vq)) {
716                 pr_debug("virtqueue interrupt with no work for %p\n", vq);
717                 return IRQ_NONE;
718         }
719
720         if (unlikely(vq->broken))
721                 return IRQ_HANDLED;
722
723         pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
724         if (vq->vq.callback)
725                 vq->vq.callback(&vq->vq);
726
727         return IRQ_HANDLED;
728 }
729 EXPORT_SYMBOL_GPL(vring_interrupt);
730
731 struct virtqueue *vring_new_virtqueue(unsigned int index,
732                                       unsigned int num,
733                                       unsigned int vring_align,
734                                       struct virtio_device *vdev,
735                                       bool weak_barriers,
736                                       void *pages,
737                                       bool (*notify)(struct virtqueue *),
738                                       void (*callback)(struct virtqueue *),
739                                       const char *name)
740 {
741         struct vring_virtqueue *vq;
742         unsigned int i;
743
744         /* We assume num is a power of 2. */
745         if (num & (num - 1)) {
746                 dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
747                 return NULL;
748         }
749
750         vq = kmalloc(sizeof(*vq) + sizeof(void *)*num, GFP_KERNEL);
751         if (!vq)
752                 return NULL;
753
754         vring_init(&vq->vring, num, pages, vring_align);
755         vq->vq.callback = callback;
756         vq->vq.vdev = vdev;
757         vq->vq.name = name;
758         vq->vq.num_free = num;
759         vq->vq.index = index;
760         vq->notify = notify;
761         vq->weak_barriers = weak_barriers;
762         vq->broken = false;
763         vq->last_used_idx = 0;
764         vq->avail_flags_shadow = 0;
765         vq->avail_idx_shadow = 0;
766         vq->num_added = 0;
767         list_add_tail(&vq->vq.list, &vdev->vqs);
768 #ifdef DEBUG
769         vq->in_use = false;
770         vq->last_add_time_valid = false;
771 #endif
772
773         vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
774         vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
775
776         /* No callback?  Tell other side not to bother us. */
777         if (!callback) {
778                 vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
779                 if (!vq->event)
780                         vq->vring.avail->flags = cpu_to_virtio16(vdev, vq->avail_flags_shadow);
781         }
782
783         /* Put everything in free lists. */
784         vq->free_head = 0;
785         for (i = 0; i < num-1; i++) {
786                 vq->vring.desc[i].next = cpu_to_virtio16(vdev, i + 1);
787                 vq->data[i] = NULL;
788         }
789         vq->data[i] = NULL;
790
791         return &vq->vq;
792 }
793 EXPORT_SYMBOL_GPL(vring_new_virtqueue);
794
795 void vring_del_virtqueue(struct virtqueue *vq)
796 {
797         list_del(&vq->list);
798         kfree(to_vvq(vq));
799 }
800 EXPORT_SYMBOL_GPL(vring_del_virtqueue);
801
802 /* Manipulates transport-specific feature bits. */
803 void vring_transport_features(struct virtio_device *vdev)
804 {
805         unsigned int i;
806
807         for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
808                 switch (i) {
809                 case VIRTIO_RING_F_INDIRECT_DESC:
810                         break;
811                 case VIRTIO_RING_F_EVENT_IDX:
812                         break;
813                 case VIRTIO_F_VERSION_1:
814                         break;
815                 default:
816                         /* We don't understand this bit. */
817                         __virtio_clear_bit(vdev, i);
818                 }
819         }
820 }
821 EXPORT_SYMBOL_GPL(vring_transport_features);
822
823 /**
824  * virtqueue_get_vring_size - return the size of the virtqueue's vring
825  * @vq: the struct virtqueue containing the vring of interest.
826  *
827  * Returns the size of the vring.  This is mainly used for boasting to
828  * userspace.  Unlike other operations, this need not be serialized.
829  */
830 unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
831 {
832
833         struct vring_virtqueue *vq = to_vvq(_vq);
834
835         return vq->vring.num;
836 }
837 EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
838
839 bool virtqueue_is_broken(struct virtqueue *_vq)
840 {
841         struct vring_virtqueue *vq = to_vvq(_vq);
842
843         return READ_ONCE(vq->broken);
844 }
845 EXPORT_SYMBOL_GPL(virtqueue_is_broken);
846
847 /*
848  * This should prevent the device from being used, allowing drivers to
849  * recover.  You may need to grab appropriate locks to flush.
850  */
851 void virtio_break_device(struct virtio_device *dev)
852 {
853         struct virtqueue *_vq;
854
855         list_for_each_entry(_vq, &dev->vqs, list) {
856                 struct vring_virtqueue *vq = to_vvq(_vq);
857
858                 /* Pairs with READ_ONCE() in virtqueue_is_broken(). */
859                 WRITE_ONCE(vq->broken, true);
860         }
861 }
862 EXPORT_SYMBOL_GPL(virtio_break_device);
863
864 void *virtqueue_get_avail(struct virtqueue *_vq)
865 {
866         struct vring_virtqueue *vq = to_vvq(_vq);
867
868         return vq->vring.avail;
869 }
870 EXPORT_SYMBOL_GPL(virtqueue_get_avail);
871
872 void *virtqueue_get_used(struct virtqueue *_vq)
873 {
874         struct vring_virtqueue *vq = to_vvq(_vq);
875
876         return vq->vring.used;
877 }
878 EXPORT_SYMBOL_GPL(virtqueue_get_used);
879
880 MODULE_LICENSE("GPL");