virtio-ring: factor out desc_extra allocation
[linux-2.6-microblaze.git] / drivers / virtio / virtio_ring.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Virtio ring implementation.
3  *
4  *  Copyright 2007 Rusty Russell IBM Corporation
5  */
6 #include <linux/virtio.h>
7 #include <linux/virtio_ring.h>
8 #include <linux/virtio_config.h>
9 #include <linux/device.h>
10 #include <linux/slab.h>
11 #include <linux/module.h>
12 #include <linux/hrtimer.h>
13 #include <linux/dma-mapping.h>
14 #include <xen/xen.h>
15
16 #ifdef DEBUG
17 /* For development, we want to crash whenever the ring is screwed. */
18 #define BAD_RING(_vq, fmt, args...)                             \
19         do {                                                    \
20                 dev_err(&(_vq)->vq.vdev->dev,                   \
21                         "%s:"fmt, (_vq)->vq.name, ##args);      \
22                 BUG();                                          \
23         } while (0)
24 /* Caller is supposed to guarantee no reentry. */
25 #define START_USE(_vq)                                          \
26         do {                                                    \
27                 if ((_vq)->in_use)                              \
28                         panic("%s:in_use = %i\n",               \
29                               (_vq)->vq.name, (_vq)->in_use);   \
30                 (_vq)->in_use = __LINE__;                       \
31         } while (0)
32 #define END_USE(_vq) \
33         do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
34 #define LAST_ADD_TIME_UPDATE(_vq)                               \
35         do {                                                    \
36                 ktime_t now = ktime_get();                      \
37                                                                 \
38                 /* No kick or get, with .1 second between?  Warn. */ \
39                 if ((_vq)->last_add_time_valid)                 \
40                         WARN_ON(ktime_to_ms(ktime_sub(now,      \
41                                 (_vq)->last_add_time)) > 100);  \
42                 (_vq)->last_add_time = now;                     \
43                 (_vq)->last_add_time_valid = true;              \
44         } while (0)
45 #define LAST_ADD_TIME_CHECK(_vq)                                \
46         do {                                                    \
47                 if ((_vq)->last_add_time_valid) {               \
48                         WARN_ON(ktime_to_ms(ktime_sub(ktime_get(), \
49                                       (_vq)->last_add_time)) > 100); \
50                 }                                               \
51         } while (0)
52 #define LAST_ADD_TIME_INVALID(_vq)                              \
53         ((_vq)->last_add_time_valid = false)
54 #else
55 #define BAD_RING(_vq, fmt, args...)                             \
56         do {                                                    \
57                 dev_err(&_vq->vq.vdev->dev,                     \
58                         "%s:"fmt, (_vq)->vq.name, ##args);      \
59                 (_vq)->broken = true;                           \
60         } while (0)
61 #define START_USE(vq)
62 #define END_USE(vq)
63 #define LAST_ADD_TIME_UPDATE(vq)
64 #define LAST_ADD_TIME_CHECK(vq)
65 #define LAST_ADD_TIME_INVALID(vq)
66 #endif
67
68 struct vring_desc_state_split {
69         void *data;                     /* Data for callback. */
70         struct vring_desc *indir_desc;  /* Indirect descriptor, if any. */
71 };
72
73 struct vring_desc_state_packed {
74         void *data;                     /* Data for callback. */
75         struct vring_packed_desc *indir_desc; /* Indirect descriptor, if any. */
76         u16 num;                        /* Descriptor list length. */
77         u16 last;                       /* The last desc state in a list. */
78 };
79
80 struct vring_desc_extra {
81         dma_addr_t addr;                /* Buffer DMA addr. */
82         u32 len;                        /* Buffer length. */
83         u16 flags;                      /* Descriptor flags. */
84         u16 next;                       /* The next desc state in a list. */
85 };
86
87 struct vring_virtqueue {
88         struct virtqueue vq;
89
90         /* Is this a packed ring? */
91         bool packed_ring;
92
93         /* Is DMA API used? */
94         bool use_dma_api;
95
96         /* Can we use weak barriers? */
97         bool weak_barriers;
98
99         /* Other side has made a mess, don't try any more. */
100         bool broken;
101
102         /* Host supports indirect buffers */
103         bool indirect;
104
105         /* Host publishes avail event idx */
106         bool event;
107
108         /* Head of free buffer list. */
109         unsigned int free_head;
110         /* Number we've added since last sync. */
111         unsigned int num_added;
112
113         /* Last used index we've seen. */
114         u16 last_used_idx;
115
116         /* Hint for event idx: already triggered no need to disable. */
117         bool event_triggered;
118
119         union {
120                 /* Available for split ring */
121                 struct {
122                         /* Actual memory layout for this queue. */
123                         struct vring vring;
124
125                         /* Last written value to avail->flags */
126                         u16 avail_flags_shadow;
127
128                         /*
129                          * Last written value to avail->idx in
130                          * guest byte order.
131                          */
132                         u16 avail_idx_shadow;
133
134                         /* Per-descriptor state. */
135                         struct vring_desc_state_split *desc_state;
136
137                         /* DMA address and size information */
138                         dma_addr_t queue_dma_addr;
139                         size_t queue_size_in_bytes;
140                 } split;
141
142                 /* Available for packed ring */
143                 struct {
144                         /* Actual memory layout for this queue. */
145                         struct {
146                                 unsigned int num;
147                                 struct vring_packed_desc *desc;
148                                 struct vring_packed_desc_event *driver;
149                                 struct vring_packed_desc_event *device;
150                         } vring;
151
152                         /* Driver ring wrap counter. */
153                         bool avail_wrap_counter;
154
155                         /* Device ring wrap counter. */
156                         bool used_wrap_counter;
157
158                         /* Avail used flags. */
159                         u16 avail_used_flags;
160
161                         /* Index of the next avail descriptor. */
162                         u16 next_avail_idx;
163
164                         /*
165                          * Last written value to driver->flags in
166                          * guest byte order.
167                          */
168                         u16 event_flags_shadow;
169
170                         /* Per-descriptor state. */
171                         struct vring_desc_state_packed *desc_state;
172                         struct vring_desc_extra *desc_extra;
173
174                         /* DMA address and size information */
175                         dma_addr_t ring_dma_addr;
176                         dma_addr_t driver_event_dma_addr;
177                         dma_addr_t device_event_dma_addr;
178                         size_t ring_size_in_bytes;
179                         size_t event_size_in_bytes;
180                 } packed;
181         };
182
183         /* How to notify other side. FIXME: commonalize hcalls! */
184         bool (*notify)(struct virtqueue *vq);
185
186         /* DMA, allocation, and size information */
187         bool we_own_ring;
188
189 #ifdef DEBUG
190         /* They're supposed to lock for us. */
191         unsigned int in_use;
192
193         /* Figure out if their kicks are too delayed. */
194         bool last_add_time_valid;
195         ktime_t last_add_time;
196 #endif
197 };
198
199
200 /*
201  * Helpers.
202  */
203
204 #define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
205
206 static inline bool virtqueue_use_indirect(struct virtqueue *_vq,
207                                           unsigned int total_sg)
208 {
209         struct vring_virtqueue *vq = to_vvq(_vq);
210
211         /*
212          * If the host supports indirect descriptor tables, and we have multiple
213          * buffers, then go indirect. FIXME: tune this threshold
214          */
215         return (vq->indirect && total_sg > 1 && vq->vq.num_free);
216 }
217
218 /*
219  * Modern virtio devices have feature bits to specify whether they need a
220  * quirk and bypass the IOMMU. If not there, just use the DMA API.
221  *
222  * If there, the interaction between virtio and DMA API is messy.
223  *
224  * On most systems with virtio, physical addresses match bus addresses,
225  * and it doesn't particularly matter whether we use the DMA API.
226  *
227  * On some systems, including Xen and any system with a physical device
228  * that speaks virtio behind a physical IOMMU, we must use the DMA API
229  * for virtio DMA to work at all.
230  *
231  * On other systems, including SPARC and PPC64, virtio-pci devices are
232  * enumerated as though they are behind an IOMMU, but the virtio host
233  * ignores the IOMMU, so we must either pretend that the IOMMU isn't
234  * there or somehow map everything as the identity.
235  *
236  * For the time being, we preserve historic behavior and bypass the DMA
237  * API.
238  *
239  * TODO: install a per-device DMA ops structure that does the right thing
240  * taking into account all the above quirks, and use the DMA API
241  * unconditionally on data path.
242  */
243
244 static bool vring_use_dma_api(struct virtio_device *vdev)
245 {
246         if (!virtio_has_dma_quirk(vdev))
247                 return true;
248
249         /* Otherwise, we are left to guess. */
250         /*
251          * In theory, it's possible to have a buggy QEMU-supposed
252          * emulated Q35 IOMMU and Xen enabled at the same time.  On
253          * such a configuration, virtio has never worked and will
254          * not work without an even larger kludge.  Instead, enable
255          * the DMA API if we're a Xen guest, which at least allows
256          * all of the sensible Xen configurations to work correctly.
257          */
258         if (xen_domain())
259                 return true;
260
261         return false;
262 }
263
264 size_t virtio_max_dma_size(struct virtio_device *vdev)
265 {
266         size_t max_segment_size = SIZE_MAX;
267
268         if (vring_use_dma_api(vdev))
269                 max_segment_size = dma_max_mapping_size(&vdev->dev);
270
271         return max_segment_size;
272 }
273 EXPORT_SYMBOL_GPL(virtio_max_dma_size);
274
275 static void *vring_alloc_queue(struct virtio_device *vdev, size_t size,
276                               dma_addr_t *dma_handle, gfp_t flag)
277 {
278         if (vring_use_dma_api(vdev)) {
279                 return dma_alloc_coherent(vdev->dev.parent, size,
280                                           dma_handle, flag);
281         } else {
282                 void *queue = alloc_pages_exact(PAGE_ALIGN(size), flag);
283
284                 if (queue) {
285                         phys_addr_t phys_addr = virt_to_phys(queue);
286                         *dma_handle = (dma_addr_t)phys_addr;
287
288                         /*
289                          * Sanity check: make sure we dind't truncate
290                          * the address.  The only arches I can find that
291                          * have 64-bit phys_addr_t but 32-bit dma_addr_t
292                          * are certain non-highmem MIPS and x86
293                          * configurations, but these configurations
294                          * should never allocate physical pages above 32
295                          * bits, so this is fine.  Just in case, throw a
296                          * warning and abort if we end up with an
297                          * unrepresentable address.
298                          */
299                         if (WARN_ON_ONCE(*dma_handle != phys_addr)) {
300                                 free_pages_exact(queue, PAGE_ALIGN(size));
301                                 return NULL;
302                         }
303                 }
304                 return queue;
305         }
306 }
307
308 static void vring_free_queue(struct virtio_device *vdev, size_t size,
309                              void *queue, dma_addr_t dma_handle)
310 {
311         if (vring_use_dma_api(vdev))
312                 dma_free_coherent(vdev->dev.parent, size, queue, dma_handle);
313         else
314                 free_pages_exact(queue, PAGE_ALIGN(size));
315 }
316
317 /*
318  * The DMA ops on various arches are rather gnarly right now, and
319  * making all of the arch DMA ops work on the vring device itself
320  * is a mess.  For now, we use the parent device for DMA ops.
321  */
322 static inline struct device *vring_dma_dev(const struct vring_virtqueue *vq)
323 {
324         return vq->vq.vdev->dev.parent;
325 }
326
327 /* Map one sg entry. */
328 static dma_addr_t vring_map_one_sg(const struct vring_virtqueue *vq,
329                                    struct scatterlist *sg,
330                                    enum dma_data_direction direction)
331 {
332         if (!vq->use_dma_api)
333                 return (dma_addr_t)sg_phys(sg);
334
335         /*
336          * We can't use dma_map_sg, because we don't use scatterlists in
337          * the way it expects (we don't guarantee that the scatterlist
338          * will exist for the lifetime of the mapping).
339          */
340         return dma_map_page(vring_dma_dev(vq),
341                             sg_page(sg), sg->offset, sg->length,
342                             direction);
343 }
344
345 static dma_addr_t vring_map_single(const struct vring_virtqueue *vq,
346                                    void *cpu_addr, size_t size,
347                                    enum dma_data_direction direction)
348 {
349         if (!vq->use_dma_api)
350                 return (dma_addr_t)virt_to_phys(cpu_addr);
351
352         return dma_map_single(vring_dma_dev(vq),
353                               cpu_addr, size, direction);
354 }
355
356 static int vring_mapping_error(const struct vring_virtqueue *vq,
357                                dma_addr_t addr)
358 {
359         if (!vq->use_dma_api)
360                 return 0;
361
362         return dma_mapping_error(vring_dma_dev(vq), addr);
363 }
364
365
366 /*
367  * Split ring specific functions - *_split().
368  */
369
370 static void vring_unmap_one_split(const struct vring_virtqueue *vq,
371                                   struct vring_desc *desc)
372 {
373         u16 flags;
374
375         if (!vq->use_dma_api)
376                 return;
377
378         flags = virtio16_to_cpu(vq->vq.vdev, desc->flags);
379
380         if (flags & VRING_DESC_F_INDIRECT) {
381                 dma_unmap_single(vring_dma_dev(vq),
382                                  virtio64_to_cpu(vq->vq.vdev, desc->addr),
383                                  virtio32_to_cpu(vq->vq.vdev, desc->len),
384                                  (flags & VRING_DESC_F_WRITE) ?
385                                  DMA_FROM_DEVICE : DMA_TO_DEVICE);
386         } else {
387                 dma_unmap_page(vring_dma_dev(vq),
388                                virtio64_to_cpu(vq->vq.vdev, desc->addr),
389                                virtio32_to_cpu(vq->vq.vdev, desc->len),
390                                (flags & VRING_DESC_F_WRITE) ?
391                                DMA_FROM_DEVICE : DMA_TO_DEVICE);
392         }
393 }
394
395 static struct vring_desc *alloc_indirect_split(struct virtqueue *_vq,
396                                                unsigned int total_sg,
397                                                gfp_t gfp)
398 {
399         struct vring_desc *desc;
400         unsigned int i;
401
402         /*
403          * We require lowmem mappings for the descriptors because
404          * otherwise virt_to_phys will give us bogus addresses in the
405          * virtqueue.
406          */
407         gfp &= ~__GFP_HIGHMEM;
408
409         desc = kmalloc_array(total_sg, sizeof(struct vring_desc), gfp);
410         if (!desc)
411                 return NULL;
412
413         for (i = 0; i < total_sg; i++)
414                 desc[i].next = cpu_to_virtio16(_vq->vdev, i + 1);
415         return desc;
416 }
417
418 static inline int virtqueue_add_split(struct virtqueue *_vq,
419                                       struct scatterlist *sgs[],
420                                       unsigned int total_sg,
421                                       unsigned int out_sgs,
422                                       unsigned int in_sgs,
423                                       void *data,
424                                       void *ctx,
425                                       gfp_t gfp)
426 {
427         struct vring_virtqueue *vq = to_vvq(_vq);
428         struct scatterlist *sg;
429         struct vring_desc *desc;
430         unsigned int i, n, avail, descs_used, prev, err_idx;
431         int head;
432         bool indirect;
433
434         START_USE(vq);
435
436         BUG_ON(data == NULL);
437         BUG_ON(ctx && vq->indirect);
438
439         if (unlikely(vq->broken)) {
440                 END_USE(vq);
441                 return -EIO;
442         }
443
444         LAST_ADD_TIME_UPDATE(vq);
445
446         BUG_ON(total_sg == 0);
447
448         head = vq->free_head;
449
450         if (virtqueue_use_indirect(_vq, total_sg))
451                 desc = alloc_indirect_split(_vq, total_sg, gfp);
452         else {
453                 desc = NULL;
454                 WARN_ON_ONCE(total_sg > vq->split.vring.num && !vq->indirect);
455         }
456
457         if (desc) {
458                 /* Use a single buffer which doesn't continue */
459                 indirect = true;
460                 /* Set up rest to use this indirect table. */
461                 i = 0;
462                 descs_used = 1;
463         } else {
464                 indirect = false;
465                 desc = vq->split.vring.desc;
466                 i = head;
467                 descs_used = total_sg;
468         }
469
470         if (vq->vq.num_free < descs_used) {
471                 pr_debug("Can't add buf len %i - avail = %i\n",
472                          descs_used, vq->vq.num_free);
473                 /* FIXME: for historical reasons, we force a notify here if
474                  * there are outgoing parts to the buffer.  Presumably the
475                  * host should service the ring ASAP. */
476                 if (out_sgs)
477                         vq->notify(&vq->vq);
478                 if (indirect)
479                         kfree(desc);
480                 END_USE(vq);
481                 return -ENOSPC;
482         }
483
484         for (n = 0; n < out_sgs; n++) {
485                 for (sg = sgs[n]; sg; sg = sg_next(sg)) {
486                         dma_addr_t addr = vring_map_one_sg(vq, sg, DMA_TO_DEVICE);
487                         if (vring_mapping_error(vq, addr))
488                                 goto unmap_release;
489
490                         desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT);
491                         desc[i].addr = cpu_to_virtio64(_vq->vdev, addr);
492                         desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
493                         prev = i;
494                         i = virtio16_to_cpu(_vq->vdev, desc[i].next);
495                 }
496         }
497         for (; n < (out_sgs + in_sgs); n++) {
498                 for (sg = sgs[n]; sg; sg = sg_next(sg)) {
499                         dma_addr_t addr = vring_map_one_sg(vq, sg, DMA_FROM_DEVICE);
500                         if (vring_mapping_error(vq, addr))
501                                 goto unmap_release;
502
503                         desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT | VRING_DESC_F_WRITE);
504                         desc[i].addr = cpu_to_virtio64(_vq->vdev, addr);
505                         desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
506                         prev = i;
507                         i = virtio16_to_cpu(_vq->vdev, desc[i].next);
508                 }
509         }
510         /* Last one doesn't continue. */
511         desc[prev].flags &= cpu_to_virtio16(_vq->vdev, ~VRING_DESC_F_NEXT);
512
513         if (indirect) {
514                 /* Now that the indirect table is filled in, map it. */
515                 dma_addr_t addr = vring_map_single(
516                         vq, desc, total_sg * sizeof(struct vring_desc),
517                         DMA_TO_DEVICE);
518                 if (vring_mapping_error(vq, addr))
519                         goto unmap_release;
520
521                 vq->split.vring.desc[head].flags = cpu_to_virtio16(_vq->vdev,
522                                 VRING_DESC_F_INDIRECT);
523                 vq->split.vring.desc[head].addr = cpu_to_virtio64(_vq->vdev,
524                                 addr);
525
526                 vq->split.vring.desc[head].len = cpu_to_virtio32(_vq->vdev,
527                                 total_sg * sizeof(struct vring_desc));
528         }
529
530         /* We're using some buffers from the free list. */
531         vq->vq.num_free -= descs_used;
532
533         /* Update free pointer */
534         if (indirect)
535                 vq->free_head = virtio16_to_cpu(_vq->vdev,
536                                         vq->split.vring.desc[head].next);
537         else
538                 vq->free_head = i;
539
540         /* Store token and indirect buffer state. */
541         vq->split.desc_state[head].data = data;
542         if (indirect)
543                 vq->split.desc_state[head].indir_desc = desc;
544         else
545                 vq->split.desc_state[head].indir_desc = ctx;
546
547         /* Put entry in available array (but don't update avail->idx until they
548          * do sync). */
549         avail = vq->split.avail_idx_shadow & (vq->split.vring.num - 1);
550         vq->split.vring.avail->ring[avail] = cpu_to_virtio16(_vq->vdev, head);
551
552         /* Descriptors and available array need to be set before we expose the
553          * new available array entries. */
554         virtio_wmb(vq->weak_barriers);
555         vq->split.avail_idx_shadow++;
556         vq->split.vring.avail->idx = cpu_to_virtio16(_vq->vdev,
557                                                 vq->split.avail_idx_shadow);
558         vq->num_added++;
559
560         pr_debug("Added buffer head %i to %p\n", head, vq);
561         END_USE(vq);
562
563         /* This is very unlikely, but theoretically possible.  Kick
564          * just in case. */
565         if (unlikely(vq->num_added == (1 << 16) - 1))
566                 virtqueue_kick(_vq);
567
568         return 0;
569
570 unmap_release:
571         err_idx = i;
572
573         if (indirect)
574                 i = 0;
575         else
576                 i = head;
577
578         for (n = 0; n < total_sg; n++) {
579                 if (i == err_idx)
580                         break;
581                 vring_unmap_one_split(vq, &desc[i]);
582                 i = virtio16_to_cpu(_vq->vdev, desc[i].next);
583         }
584
585         if (indirect)
586                 kfree(desc);
587
588         END_USE(vq);
589         return -ENOMEM;
590 }
591
592 static bool virtqueue_kick_prepare_split(struct virtqueue *_vq)
593 {
594         struct vring_virtqueue *vq = to_vvq(_vq);
595         u16 new, old;
596         bool needs_kick;
597
598         START_USE(vq);
599         /* We need to expose available array entries before checking avail
600          * event. */
601         virtio_mb(vq->weak_barriers);
602
603         old = vq->split.avail_idx_shadow - vq->num_added;
604         new = vq->split.avail_idx_shadow;
605         vq->num_added = 0;
606
607         LAST_ADD_TIME_CHECK(vq);
608         LAST_ADD_TIME_INVALID(vq);
609
610         if (vq->event) {
611                 needs_kick = vring_need_event(virtio16_to_cpu(_vq->vdev,
612                                         vring_avail_event(&vq->split.vring)),
613                                               new, old);
614         } else {
615                 needs_kick = !(vq->split.vring.used->flags &
616                                         cpu_to_virtio16(_vq->vdev,
617                                                 VRING_USED_F_NO_NOTIFY));
618         }
619         END_USE(vq);
620         return needs_kick;
621 }
622
623 static void detach_buf_split(struct vring_virtqueue *vq, unsigned int head,
624                              void **ctx)
625 {
626         unsigned int i, j;
627         __virtio16 nextflag = cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_NEXT);
628
629         /* Clear data ptr. */
630         vq->split.desc_state[head].data = NULL;
631
632         /* Put back on free list: unmap first-level descriptors and find end */
633         i = head;
634
635         while (vq->split.vring.desc[i].flags & nextflag) {
636                 vring_unmap_one_split(vq, &vq->split.vring.desc[i]);
637                 i = virtio16_to_cpu(vq->vq.vdev, vq->split.vring.desc[i].next);
638                 vq->vq.num_free++;
639         }
640
641         vring_unmap_one_split(vq, &vq->split.vring.desc[i]);
642         vq->split.vring.desc[i].next = cpu_to_virtio16(vq->vq.vdev,
643                                                 vq->free_head);
644         vq->free_head = head;
645
646         /* Plus final descriptor */
647         vq->vq.num_free++;
648
649         if (vq->indirect) {
650                 struct vring_desc *indir_desc =
651                                 vq->split.desc_state[head].indir_desc;
652                 u32 len;
653
654                 /* Free the indirect table, if any, now that it's unmapped. */
655                 if (!indir_desc)
656                         return;
657
658                 len = virtio32_to_cpu(vq->vq.vdev,
659                                 vq->split.vring.desc[head].len);
660
661                 BUG_ON(!(vq->split.vring.desc[head].flags &
662                          cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_INDIRECT)));
663                 BUG_ON(len == 0 || len % sizeof(struct vring_desc));
664
665                 for (j = 0; j < len / sizeof(struct vring_desc); j++)
666                         vring_unmap_one_split(vq, &indir_desc[j]);
667
668                 kfree(indir_desc);
669                 vq->split.desc_state[head].indir_desc = NULL;
670         } else if (ctx) {
671                 *ctx = vq->split.desc_state[head].indir_desc;
672         }
673 }
674
675 static inline bool more_used_split(const struct vring_virtqueue *vq)
676 {
677         return vq->last_used_idx != virtio16_to_cpu(vq->vq.vdev,
678                         vq->split.vring.used->idx);
679 }
680
681 static void *virtqueue_get_buf_ctx_split(struct virtqueue *_vq,
682                                          unsigned int *len,
683                                          void **ctx)
684 {
685         struct vring_virtqueue *vq = to_vvq(_vq);
686         void *ret;
687         unsigned int i;
688         u16 last_used;
689
690         START_USE(vq);
691
692         if (unlikely(vq->broken)) {
693                 END_USE(vq);
694                 return NULL;
695         }
696
697         if (!more_used_split(vq)) {
698                 pr_debug("No more buffers in queue\n");
699                 END_USE(vq);
700                 return NULL;
701         }
702
703         /* Only get used array entries after they have been exposed by host. */
704         virtio_rmb(vq->weak_barriers);
705
706         last_used = (vq->last_used_idx & (vq->split.vring.num - 1));
707         i = virtio32_to_cpu(_vq->vdev,
708                         vq->split.vring.used->ring[last_used].id);
709         *len = virtio32_to_cpu(_vq->vdev,
710                         vq->split.vring.used->ring[last_used].len);
711
712         if (unlikely(i >= vq->split.vring.num)) {
713                 BAD_RING(vq, "id %u out of range\n", i);
714                 return NULL;
715         }
716         if (unlikely(!vq->split.desc_state[i].data)) {
717                 BAD_RING(vq, "id %u is not a head!\n", i);
718                 return NULL;
719         }
720
721         /* detach_buf_split clears data, so grab it now. */
722         ret = vq->split.desc_state[i].data;
723         detach_buf_split(vq, i, ctx);
724         vq->last_used_idx++;
725         /* If we expect an interrupt for the next entry, tell host
726          * by writing event index and flush out the write before
727          * the read in the next get_buf call. */
728         if (!(vq->split.avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT))
729                 virtio_store_mb(vq->weak_barriers,
730                                 &vring_used_event(&vq->split.vring),
731                                 cpu_to_virtio16(_vq->vdev, vq->last_used_idx));
732
733         LAST_ADD_TIME_INVALID(vq);
734
735         END_USE(vq);
736         return ret;
737 }
738
739 static void virtqueue_disable_cb_split(struct virtqueue *_vq)
740 {
741         struct vring_virtqueue *vq = to_vvq(_vq);
742
743         if (!(vq->split.avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT)) {
744                 vq->split.avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
745                 if (vq->event)
746                         /* TODO: this is a hack. Figure out a cleaner value to write. */
747                         vring_used_event(&vq->split.vring) = 0x0;
748                 else
749                         vq->split.vring.avail->flags =
750                                 cpu_to_virtio16(_vq->vdev,
751                                                 vq->split.avail_flags_shadow);
752         }
753 }
754
755 static unsigned virtqueue_enable_cb_prepare_split(struct virtqueue *_vq)
756 {
757         struct vring_virtqueue *vq = to_vvq(_vq);
758         u16 last_used_idx;
759
760         START_USE(vq);
761
762         /* We optimistically turn back on interrupts, then check if there was
763          * more to do. */
764         /* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
765          * either clear the flags bit or point the event index at the next
766          * entry. Always do both to keep code simple. */
767         if (vq->split.avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
768                 vq->split.avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
769                 if (!vq->event)
770                         vq->split.vring.avail->flags =
771                                 cpu_to_virtio16(_vq->vdev,
772                                                 vq->split.avail_flags_shadow);
773         }
774         vring_used_event(&vq->split.vring) = cpu_to_virtio16(_vq->vdev,
775                         last_used_idx = vq->last_used_idx);
776         END_USE(vq);
777         return last_used_idx;
778 }
779
780 static bool virtqueue_poll_split(struct virtqueue *_vq, unsigned last_used_idx)
781 {
782         struct vring_virtqueue *vq = to_vvq(_vq);
783
784         return (u16)last_used_idx != virtio16_to_cpu(_vq->vdev,
785                         vq->split.vring.used->idx);
786 }
787
788 static bool virtqueue_enable_cb_delayed_split(struct virtqueue *_vq)
789 {
790         struct vring_virtqueue *vq = to_vvq(_vq);
791         u16 bufs;
792
793         START_USE(vq);
794
795         /* We optimistically turn back on interrupts, then check if there was
796          * more to do. */
797         /* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
798          * either clear the flags bit or point the event index at the next
799          * entry. Always update the event index to keep code simple. */
800         if (vq->split.avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
801                 vq->split.avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
802                 if (!vq->event)
803                         vq->split.vring.avail->flags =
804                                 cpu_to_virtio16(_vq->vdev,
805                                                 vq->split.avail_flags_shadow);
806         }
807         /* TODO: tune this threshold */
808         bufs = (u16)(vq->split.avail_idx_shadow - vq->last_used_idx) * 3 / 4;
809
810         virtio_store_mb(vq->weak_barriers,
811                         &vring_used_event(&vq->split.vring),
812                         cpu_to_virtio16(_vq->vdev, vq->last_used_idx + bufs));
813
814         if (unlikely((u16)(virtio16_to_cpu(_vq->vdev, vq->split.vring.used->idx)
815                                         - vq->last_used_idx) > bufs)) {
816                 END_USE(vq);
817                 return false;
818         }
819
820         END_USE(vq);
821         return true;
822 }
823
824 static void *virtqueue_detach_unused_buf_split(struct virtqueue *_vq)
825 {
826         struct vring_virtqueue *vq = to_vvq(_vq);
827         unsigned int i;
828         void *buf;
829
830         START_USE(vq);
831
832         for (i = 0; i < vq->split.vring.num; i++) {
833                 if (!vq->split.desc_state[i].data)
834                         continue;
835                 /* detach_buf_split clears data, so grab it now. */
836                 buf = vq->split.desc_state[i].data;
837                 detach_buf_split(vq, i, NULL);
838                 vq->split.avail_idx_shadow--;
839                 vq->split.vring.avail->idx = cpu_to_virtio16(_vq->vdev,
840                                 vq->split.avail_idx_shadow);
841                 END_USE(vq);
842                 return buf;
843         }
844         /* That should have freed everything. */
845         BUG_ON(vq->vq.num_free != vq->split.vring.num);
846
847         END_USE(vq);
848         return NULL;
849 }
850
851 static struct virtqueue *vring_create_virtqueue_split(
852         unsigned int index,
853         unsigned int num,
854         unsigned int vring_align,
855         struct virtio_device *vdev,
856         bool weak_barriers,
857         bool may_reduce_num,
858         bool context,
859         bool (*notify)(struct virtqueue *),
860         void (*callback)(struct virtqueue *),
861         const char *name)
862 {
863         struct virtqueue *vq;
864         void *queue = NULL;
865         dma_addr_t dma_addr;
866         size_t queue_size_in_bytes;
867         struct vring vring;
868
869         /* We assume num is a power of 2. */
870         if (num & (num - 1)) {
871                 dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
872                 return NULL;
873         }
874
875         /* TODO: allocate each queue chunk individually */
876         for (; num && vring_size(num, vring_align) > PAGE_SIZE; num /= 2) {
877                 queue = vring_alloc_queue(vdev, vring_size(num, vring_align),
878                                           &dma_addr,
879                                           GFP_KERNEL|__GFP_NOWARN|__GFP_ZERO);
880                 if (queue)
881                         break;
882                 if (!may_reduce_num)
883                         return NULL;
884         }
885
886         if (!num)
887                 return NULL;
888
889         if (!queue) {
890                 /* Try to get a single page. You are my only hope! */
891                 queue = vring_alloc_queue(vdev, vring_size(num, vring_align),
892                                           &dma_addr, GFP_KERNEL|__GFP_ZERO);
893         }
894         if (!queue)
895                 return NULL;
896
897         queue_size_in_bytes = vring_size(num, vring_align);
898         vring_init(&vring, num, queue, vring_align);
899
900         vq = __vring_new_virtqueue(index, vring, vdev, weak_barriers, context,
901                                    notify, callback, name);
902         if (!vq) {
903                 vring_free_queue(vdev, queue_size_in_bytes, queue,
904                                  dma_addr);
905                 return NULL;
906         }
907
908         to_vvq(vq)->split.queue_dma_addr = dma_addr;
909         to_vvq(vq)->split.queue_size_in_bytes = queue_size_in_bytes;
910         to_vvq(vq)->we_own_ring = true;
911
912         return vq;
913 }
914
915
916 /*
917  * Packed ring specific functions - *_packed().
918  */
919
920 static void vring_unmap_state_packed(const struct vring_virtqueue *vq,
921                                      struct vring_desc_extra *state)
922 {
923         u16 flags;
924
925         if (!vq->use_dma_api)
926                 return;
927
928         flags = state->flags;
929
930         if (flags & VRING_DESC_F_INDIRECT) {
931                 dma_unmap_single(vring_dma_dev(vq),
932                                  state->addr, state->len,
933                                  (flags & VRING_DESC_F_WRITE) ?
934                                  DMA_FROM_DEVICE : DMA_TO_DEVICE);
935         } else {
936                 dma_unmap_page(vring_dma_dev(vq),
937                                state->addr, state->len,
938                                (flags & VRING_DESC_F_WRITE) ?
939                                DMA_FROM_DEVICE : DMA_TO_DEVICE);
940         }
941 }
942
943 static void vring_unmap_desc_packed(const struct vring_virtqueue *vq,
944                                    struct vring_packed_desc *desc)
945 {
946         u16 flags;
947
948         if (!vq->use_dma_api)
949                 return;
950
951         flags = le16_to_cpu(desc->flags);
952
953         if (flags & VRING_DESC_F_INDIRECT) {
954                 dma_unmap_single(vring_dma_dev(vq),
955                                  le64_to_cpu(desc->addr),
956                                  le32_to_cpu(desc->len),
957                                  (flags & VRING_DESC_F_WRITE) ?
958                                  DMA_FROM_DEVICE : DMA_TO_DEVICE);
959         } else {
960                 dma_unmap_page(vring_dma_dev(vq),
961                                le64_to_cpu(desc->addr),
962                                le32_to_cpu(desc->len),
963                                (flags & VRING_DESC_F_WRITE) ?
964                                DMA_FROM_DEVICE : DMA_TO_DEVICE);
965         }
966 }
967
968 static struct vring_packed_desc *alloc_indirect_packed(unsigned int total_sg,
969                                                        gfp_t gfp)
970 {
971         struct vring_packed_desc *desc;
972
973         /*
974          * We require lowmem mappings for the descriptors because
975          * otherwise virt_to_phys will give us bogus addresses in the
976          * virtqueue.
977          */
978         gfp &= ~__GFP_HIGHMEM;
979
980         desc = kmalloc_array(total_sg, sizeof(struct vring_packed_desc), gfp);
981
982         return desc;
983 }
984
985 static int virtqueue_add_indirect_packed(struct vring_virtqueue *vq,
986                                        struct scatterlist *sgs[],
987                                        unsigned int total_sg,
988                                        unsigned int out_sgs,
989                                        unsigned int in_sgs,
990                                        void *data,
991                                        gfp_t gfp)
992 {
993         struct vring_packed_desc *desc;
994         struct scatterlist *sg;
995         unsigned int i, n, err_idx;
996         u16 head, id;
997         dma_addr_t addr;
998
999         head = vq->packed.next_avail_idx;
1000         desc = alloc_indirect_packed(total_sg, gfp);
1001
1002         if (unlikely(vq->vq.num_free < 1)) {
1003                 pr_debug("Can't add buf len 1 - avail = 0\n");
1004                 kfree(desc);
1005                 END_USE(vq);
1006                 return -ENOSPC;
1007         }
1008
1009         i = 0;
1010         id = vq->free_head;
1011         BUG_ON(id == vq->packed.vring.num);
1012
1013         for (n = 0; n < out_sgs + in_sgs; n++) {
1014                 for (sg = sgs[n]; sg; sg = sg_next(sg)) {
1015                         addr = vring_map_one_sg(vq, sg, n < out_sgs ?
1016                                         DMA_TO_DEVICE : DMA_FROM_DEVICE);
1017                         if (vring_mapping_error(vq, addr))
1018                                 goto unmap_release;
1019
1020                         desc[i].flags = cpu_to_le16(n < out_sgs ?
1021                                                 0 : VRING_DESC_F_WRITE);
1022                         desc[i].addr = cpu_to_le64(addr);
1023                         desc[i].len = cpu_to_le32(sg->length);
1024                         i++;
1025                 }
1026         }
1027
1028         /* Now that the indirect table is filled in, map it. */
1029         addr = vring_map_single(vq, desc,
1030                         total_sg * sizeof(struct vring_packed_desc),
1031                         DMA_TO_DEVICE);
1032         if (vring_mapping_error(vq, addr))
1033                 goto unmap_release;
1034
1035         vq->packed.vring.desc[head].addr = cpu_to_le64(addr);
1036         vq->packed.vring.desc[head].len = cpu_to_le32(total_sg *
1037                                 sizeof(struct vring_packed_desc));
1038         vq->packed.vring.desc[head].id = cpu_to_le16(id);
1039
1040         if (vq->use_dma_api) {
1041                 vq->packed.desc_extra[id].addr = addr;
1042                 vq->packed.desc_extra[id].len = total_sg *
1043                                 sizeof(struct vring_packed_desc);
1044                 vq->packed.desc_extra[id].flags = VRING_DESC_F_INDIRECT |
1045                                                   vq->packed.avail_used_flags;
1046         }
1047
1048         /*
1049          * A driver MUST NOT make the first descriptor in the list
1050          * available before all subsequent descriptors comprising
1051          * the list are made available.
1052          */
1053         virtio_wmb(vq->weak_barriers);
1054         vq->packed.vring.desc[head].flags = cpu_to_le16(VRING_DESC_F_INDIRECT |
1055                                                 vq->packed.avail_used_flags);
1056
1057         /* We're using some buffers from the free list. */
1058         vq->vq.num_free -= 1;
1059
1060         /* Update free pointer */
1061         n = head + 1;
1062         if (n >= vq->packed.vring.num) {
1063                 n = 0;
1064                 vq->packed.avail_wrap_counter ^= 1;
1065                 vq->packed.avail_used_flags ^=
1066                                 1 << VRING_PACKED_DESC_F_AVAIL |
1067                                 1 << VRING_PACKED_DESC_F_USED;
1068         }
1069         vq->packed.next_avail_idx = n;
1070         vq->free_head = vq->packed.desc_extra[id].next;
1071
1072         /* Store token and indirect buffer state. */
1073         vq->packed.desc_state[id].num = 1;
1074         vq->packed.desc_state[id].data = data;
1075         vq->packed.desc_state[id].indir_desc = desc;
1076         vq->packed.desc_state[id].last = id;
1077
1078         vq->num_added += 1;
1079
1080         pr_debug("Added buffer head %i to %p\n", head, vq);
1081         END_USE(vq);
1082
1083         return 0;
1084
1085 unmap_release:
1086         err_idx = i;
1087
1088         for (i = 0; i < err_idx; i++)
1089                 vring_unmap_desc_packed(vq, &desc[i]);
1090
1091         kfree(desc);
1092
1093         END_USE(vq);
1094         return -ENOMEM;
1095 }
1096
1097 static inline int virtqueue_add_packed(struct virtqueue *_vq,
1098                                        struct scatterlist *sgs[],
1099                                        unsigned int total_sg,
1100                                        unsigned int out_sgs,
1101                                        unsigned int in_sgs,
1102                                        void *data,
1103                                        void *ctx,
1104                                        gfp_t gfp)
1105 {
1106         struct vring_virtqueue *vq = to_vvq(_vq);
1107         struct vring_packed_desc *desc;
1108         struct scatterlist *sg;
1109         unsigned int i, n, c, descs_used, err_idx;
1110         __le16 head_flags, flags;
1111         u16 head, id, prev, curr, avail_used_flags;
1112
1113         START_USE(vq);
1114
1115         BUG_ON(data == NULL);
1116         BUG_ON(ctx && vq->indirect);
1117
1118         if (unlikely(vq->broken)) {
1119                 END_USE(vq);
1120                 return -EIO;
1121         }
1122
1123         LAST_ADD_TIME_UPDATE(vq);
1124
1125         BUG_ON(total_sg == 0);
1126
1127         if (virtqueue_use_indirect(_vq, total_sg))
1128                 return virtqueue_add_indirect_packed(vq, sgs, total_sg,
1129                                 out_sgs, in_sgs, data, gfp);
1130
1131         head = vq->packed.next_avail_idx;
1132         avail_used_flags = vq->packed.avail_used_flags;
1133
1134         WARN_ON_ONCE(total_sg > vq->packed.vring.num && !vq->indirect);
1135
1136         desc = vq->packed.vring.desc;
1137         i = head;
1138         descs_used = total_sg;
1139
1140         if (unlikely(vq->vq.num_free < descs_used)) {
1141                 pr_debug("Can't add buf len %i - avail = %i\n",
1142                          descs_used, vq->vq.num_free);
1143                 END_USE(vq);
1144                 return -ENOSPC;
1145         }
1146
1147         id = vq->free_head;
1148         BUG_ON(id == vq->packed.vring.num);
1149
1150         curr = id;
1151         c = 0;
1152         for (n = 0; n < out_sgs + in_sgs; n++) {
1153                 for (sg = sgs[n]; sg; sg = sg_next(sg)) {
1154                         dma_addr_t addr = vring_map_one_sg(vq, sg, n < out_sgs ?
1155                                         DMA_TO_DEVICE : DMA_FROM_DEVICE);
1156                         if (vring_mapping_error(vq, addr))
1157                                 goto unmap_release;
1158
1159                         flags = cpu_to_le16(vq->packed.avail_used_flags |
1160                                     (++c == total_sg ? 0 : VRING_DESC_F_NEXT) |
1161                                     (n < out_sgs ? 0 : VRING_DESC_F_WRITE));
1162                         if (i == head)
1163                                 head_flags = flags;
1164                         else
1165                                 desc[i].flags = flags;
1166
1167                         desc[i].addr = cpu_to_le64(addr);
1168                         desc[i].len = cpu_to_le32(sg->length);
1169                         desc[i].id = cpu_to_le16(id);
1170
1171                         if (unlikely(vq->use_dma_api)) {
1172                                 vq->packed.desc_extra[curr].addr = addr;
1173                                 vq->packed.desc_extra[curr].len = sg->length;
1174                                 vq->packed.desc_extra[curr].flags =
1175                                         le16_to_cpu(flags);
1176                         }
1177                         prev = curr;
1178                         curr = vq->packed.desc_extra[curr].next;
1179
1180                         if ((unlikely(++i >= vq->packed.vring.num))) {
1181                                 i = 0;
1182                                 vq->packed.avail_used_flags ^=
1183                                         1 << VRING_PACKED_DESC_F_AVAIL |
1184                                         1 << VRING_PACKED_DESC_F_USED;
1185                         }
1186                 }
1187         }
1188
1189         if (i < head)
1190                 vq->packed.avail_wrap_counter ^= 1;
1191
1192         /* We're using some buffers from the free list. */
1193         vq->vq.num_free -= descs_used;
1194
1195         /* Update free pointer */
1196         vq->packed.next_avail_idx = i;
1197         vq->free_head = curr;
1198
1199         /* Store token. */
1200         vq->packed.desc_state[id].num = descs_used;
1201         vq->packed.desc_state[id].data = data;
1202         vq->packed.desc_state[id].indir_desc = ctx;
1203         vq->packed.desc_state[id].last = prev;
1204
1205         /*
1206          * A driver MUST NOT make the first descriptor in the list
1207          * available before all subsequent descriptors comprising
1208          * the list are made available.
1209          */
1210         virtio_wmb(vq->weak_barriers);
1211         vq->packed.vring.desc[head].flags = head_flags;
1212         vq->num_added += descs_used;
1213
1214         pr_debug("Added buffer head %i to %p\n", head, vq);
1215         END_USE(vq);
1216
1217         return 0;
1218
1219 unmap_release:
1220         err_idx = i;
1221         i = head;
1222
1223         vq->packed.avail_used_flags = avail_used_flags;
1224
1225         for (n = 0; n < total_sg; n++) {
1226                 if (i == err_idx)
1227                         break;
1228                 vring_unmap_desc_packed(vq, &desc[i]);
1229                 i++;
1230                 if (i >= vq->packed.vring.num)
1231                         i = 0;
1232         }
1233
1234         END_USE(vq);
1235         return -EIO;
1236 }
1237
1238 static bool virtqueue_kick_prepare_packed(struct virtqueue *_vq)
1239 {
1240         struct vring_virtqueue *vq = to_vvq(_vq);
1241         u16 new, old, off_wrap, flags, wrap_counter, event_idx;
1242         bool needs_kick;
1243         union {
1244                 struct {
1245                         __le16 off_wrap;
1246                         __le16 flags;
1247                 };
1248                 u32 u32;
1249         } snapshot;
1250
1251         START_USE(vq);
1252
1253         /*
1254          * We need to expose the new flags value before checking notification
1255          * suppressions.
1256          */
1257         virtio_mb(vq->weak_barriers);
1258
1259         old = vq->packed.next_avail_idx - vq->num_added;
1260         new = vq->packed.next_avail_idx;
1261         vq->num_added = 0;
1262
1263         snapshot.u32 = *(u32 *)vq->packed.vring.device;
1264         flags = le16_to_cpu(snapshot.flags);
1265
1266         LAST_ADD_TIME_CHECK(vq);
1267         LAST_ADD_TIME_INVALID(vq);
1268
1269         if (flags != VRING_PACKED_EVENT_FLAG_DESC) {
1270                 needs_kick = (flags != VRING_PACKED_EVENT_FLAG_DISABLE);
1271                 goto out;
1272         }
1273
1274         off_wrap = le16_to_cpu(snapshot.off_wrap);
1275
1276         wrap_counter = off_wrap >> VRING_PACKED_EVENT_F_WRAP_CTR;
1277         event_idx = off_wrap & ~(1 << VRING_PACKED_EVENT_F_WRAP_CTR);
1278         if (wrap_counter != vq->packed.avail_wrap_counter)
1279                 event_idx -= vq->packed.vring.num;
1280
1281         needs_kick = vring_need_event(event_idx, new, old);
1282 out:
1283         END_USE(vq);
1284         return needs_kick;
1285 }
1286
1287 static void detach_buf_packed(struct vring_virtqueue *vq,
1288                               unsigned int id, void **ctx)
1289 {
1290         struct vring_desc_state_packed *state = NULL;
1291         struct vring_packed_desc *desc;
1292         unsigned int i, curr;
1293
1294         state = &vq->packed.desc_state[id];
1295
1296         /* Clear data ptr. */
1297         state->data = NULL;
1298
1299         vq->packed.desc_extra[state->last].next = vq->free_head;
1300         vq->free_head = id;
1301         vq->vq.num_free += state->num;
1302
1303         if (unlikely(vq->use_dma_api)) {
1304                 curr = id;
1305                 for (i = 0; i < state->num; i++) {
1306                         vring_unmap_state_packed(vq,
1307                                 &vq->packed.desc_extra[curr]);
1308                         curr = vq->packed.desc_extra[curr].next;
1309                 }
1310         }
1311
1312         if (vq->indirect) {
1313                 u32 len;
1314
1315                 /* Free the indirect table, if any, now that it's unmapped. */
1316                 desc = state->indir_desc;
1317                 if (!desc)
1318                         return;
1319
1320                 if (vq->use_dma_api) {
1321                         len = vq->packed.desc_extra[id].len;
1322                         for (i = 0; i < len / sizeof(struct vring_packed_desc);
1323                                         i++)
1324                                 vring_unmap_desc_packed(vq, &desc[i]);
1325                 }
1326                 kfree(desc);
1327                 state->indir_desc = NULL;
1328         } else if (ctx) {
1329                 *ctx = state->indir_desc;
1330         }
1331 }
1332
1333 static inline bool is_used_desc_packed(const struct vring_virtqueue *vq,
1334                                        u16 idx, bool used_wrap_counter)
1335 {
1336         bool avail, used;
1337         u16 flags;
1338
1339         flags = le16_to_cpu(vq->packed.vring.desc[idx].flags);
1340         avail = !!(flags & (1 << VRING_PACKED_DESC_F_AVAIL));
1341         used = !!(flags & (1 << VRING_PACKED_DESC_F_USED));
1342
1343         return avail == used && used == used_wrap_counter;
1344 }
1345
1346 static inline bool more_used_packed(const struct vring_virtqueue *vq)
1347 {
1348         return is_used_desc_packed(vq, vq->last_used_idx,
1349                         vq->packed.used_wrap_counter);
1350 }
1351
1352 static void *virtqueue_get_buf_ctx_packed(struct virtqueue *_vq,
1353                                           unsigned int *len,
1354                                           void **ctx)
1355 {
1356         struct vring_virtqueue *vq = to_vvq(_vq);
1357         u16 last_used, id;
1358         void *ret;
1359
1360         START_USE(vq);
1361
1362         if (unlikely(vq->broken)) {
1363                 END_USE(vq);
1364                 return NULL;
1365         }
1366
1367         if (!more_used_packed(vq)) {
1368                 pr_debug("No more buffers in queue\n");
1369                 END_USE(vq);
1370                 return NULL;
1371         }
1372
1373         /* Only get used elements after they have been exposed by host. */
1374         virtio_rmb(vq->weak_barriers);
1375
1376         last_used = vq->last_used_idx;
1377         id = le16_to_cpu(vq->packed.vring.desc[last_used].id);
1378         *len = le32_to_cpu(vq->packed.vring.desc[last_used].len);
1379
1380         if (unlikely(id >= vq->packed.vring.num)) {
1381                 BAD_RING(vq, "id %u out of range\n", id);
1382                 return NULL;
1383         }
1384         if (unlikely(!vq->packed.desc_state[id].data)) {
1385                 BAD_RING(vq, "id %u is not a head!\n", id);
1386                 return NULL;
1387         }
1388
1389         /* detach_buf_packed clears data, so grab it now. */
1390         ret = vq->packed.desc_state[id].data;
1391         detach_buf_packed(vq, id, ctx);
1392
1393         vq->last_used_idx += vq->packed.desc_state[id].num;
1394         if (unlikely(vq->last_used_idx >= vq->packed.vring.num)) {
1395                 vq->last_used_idx -= vq->packed.vring.num;
1396                 vq->packed.used_wrap_counter ^= 1;
1397         }
1398
1399         /*
1400          * If we expect an interrupt for the next entry, tell host
1401          * by writing event index and flush out the write before
1402          * the read in the next get_buf call.
1403          */
1404         if (vq->packed.event_flags_shadow == VRING_PACKED_EVENT_FLAG_DESC)
1405                 virtio_store_mb(vq->weak_barriers,
1406                                 &vq->packed.vring.driver->off_wrap,
1407                                 cpu_to_le16(vq->last_used_idx |
1408                                         (vq->packed.used_wrap_counter <<
1409                                          VRING_PACKED_EVENT_F_WRAP_CTR)));
1410
1411         LAST_ADD_TIME_INVALID(vq);
1412
1413         END_USE(vq);
1414         return ret;
1415 }
1416
1417 static void virtqueue_disable_cb_packed(struct virtqueue *_vq)
1418 {
1419         struct vring_virtqueue *vq = to_vvq(_vq);
1420
1421         if (vq->packed.event_flags_shadow != VRING_PACKED_EVENT_FLAG_DISABLE) {
1422                 vq->packed.event_flags_shadow = VRING_PACKED_EVENT_FLAG_DISABLE;
1423                 vq->packed.vring.driver->flags =
1424                         cpu_to_le16(vq->packed.event_flags_shadow);
1425         }
1426 }
1427
1428 static unsigned virtqueue_enable_cb_prepare_packed(struct virtqueue *_vq)
1429 {
1430         struct vring_virtqueue *vq = to_vvq(_vq);
1431
1432         START_USE(vq);
1433
1434         /*
1435          * We optimistically turn back on interrupts, then check if there was
1436          * more to do.
1437          */
1438
1439         if (vq->event) {
1440                 vq->packed.vring.driver->off_wrap =
1441                         cpu_to_le16(vq->last_used_idx |
1442                                 (vq->packed.used_wrap_counter <<
1443                                  VRING_PACKED_EVENT_F_WRAP_CTR));
1444                 /*
1445                  * We need to update event offset and event wrap
1446                  * counter first before updating event flags.
1447                  */
1448                 virtio_wmb(vq->weak_barriers);
1449         }
1450
1451         if (vq->packed.event_flags_shadow == VRING_PACKED_EVENT_FLAG_DISABLE) {
1452                 vq->packed.event_flags_shadow = vq->event ?
1453                                 VRING_PACKED_EVENT_FLAG_DESC :
1454                                 VRING_PACKED_EVENT_FLAG_ENABLE;
1455                 vq->packed.vring.driver->flags =
1456                                 cpu_to_le16(vq->packed.event_flags_shadow);
1457         }
1458
1459         END_USE(vq);
1460         return vq->last_used_idx | ((u16)vq->packed.used_wrap_counter <<
1461                         VRING_PACKED_EVENT_F_WRAP_CTR);
1462 }
1463
1464 static bool virtqueue_poll_packed(struct virtqueue *_vq, u16 off_wrap)
1465 {
1466         struct vring_virtqueue *vq = to_vvq(_vq);
1467         bool wrap_counter;
1468         u16 used_idx;
1469
1470         wrap_counter = off_wrap >> VRING_PACKED_EVENT_F_WRAP_CTR;
1471         used_idx = off_wrap & ~(1 << VRING_PACKED_EVENT_F_WRAP_CTR);
1472
1473         return is_used_desc_packed(vq, used_idx, wrap_counter);
1474 }
1475
1476 static bool virtqueue_enable_cb_delayed_packed(struct virtqueue *_vq)
1477 {
1478         struct vring_virtqueue *vq = to_vvq(_vq);
1479         u16 used_idx, wrap_counter;
1480         u16 bufs;
1481
1482         START_USE(vq);
1483
1484         /*
1485          * We optimistically turn back on interrupts, then check if there was
1486          * more to do.
1487          */
1488
1489         if (vq->event) {
1490                 /* TODO: tune this threshold */
1491                 bufs = (vq->packed.vring.num - vq->vq.num_free) * 3 / 4;
1492                 wrap_counter = vq->packed.used_wrap_counter;
1493
1494                 used_idx = vq->last_used_idx + bufs;
1495                 if (used_idx >= vq->packed.vring.num) {
1496                         used_idx -= vq->packed.vring.num;
1497                         wrap_counter ^= 1;
1498                 }
1499
1500                 vq->packed.vring.driver->off_wrap = cpu_to_le16(used_idx |
1501                         (wrap_counter << VRING_PACKED_EVENT_F_WRAP_CTR));
1502
1503                 /*
1504                  * We need to update event offset and event wrap
1505                  * counter first before updating event flags.
1506                  */
1507                 virtio_wmb(vq->weak_barriers);
1508         }
1509
1510         if (vq->packed.event_flags_shadow == VRING_PACKED_EVENT_FLAG_DISABLE) {
1511                 vq->packed.event_flags_shadow = vq->event ?
1512                                 VRING_PACKED_EVENT_FLAG_DESC :
1513                                 VRING_PACKED_EVENT_FLAG_ENABLE;
1514                 vq->packed.vring.driver->flags =
1515                                 cpu_to_le16(vq->packed.event_flags_shadow);
1516         }
1517
1518         /*
1519          * We need to update event suppression structure first
1520          * before re-checking for more used buffers.
1521          */
1522         virtio_mb(vq->weak_barriers);
1523
1524         if (is_used_desc_packed(vq,
1525                                 vq->last_used_idx,
1526                                 vq->packed.used_wrap_counter)) {
1527                 END_USE(vq);
1528                 return false;
1529         }
1530
1531         END_USE(vq);
1532         return true;
1533 }
1534
1535 static void *virtqueue_detach_unused_buf_packed(struct virtqueue *_vq)
1536 {
1537         struct vring_virtqueue *vq = to_vvq(_vq);
1538         unsigned int i;
1539         void *buf;
1540
1541         START_USE(vq);
1542
1543         for (i = 0; i < vq->packed.vring.num; i++) {
1544                 if (!vq->packed.desc_state[i].data)
1545                         continue;
1546                 /* detach_buf clears data, so grab it now. */
1547                 buf = vq->packed.desc_state[i].data;
1548                 detach_buf_packed(vq, i, NULL);
1549                 END_USE(vq);
1550                 return buf;
1551         }
1552         /* That should have freed everything. */
1553         BUG_ON(vq->vq.num_free != vq->packed.vring.num);
1554
1555         END_USE(vq);
1556         return NULL;
1557 }
1558
1559 static struct vring_desc_extra *vring_alloc_desc_extra(struct vring_virtqueue *vq,
1560                                                        unsigned int num)
1561 {
1562         struct vring_desc_extra *desc_extra;
1563         unsigned int i;
1564
1565         desc_extra = kmalloc_array(num, sizeof(struct vring_desc_extra),
1566                                    GFP_KERNEL);
1567         if (!desc_extra)
1568                 return NULL;
1569
1570         memset(desc_extra, 0, num * sizeof(struct vring_desc_extra));
1571
1572         for (i = 0; i < num - 1; i++)
1573                 desc_extra[i].next = i + 1;
1574
1575         return desc_extra;
1576 }
1577
1578 static struct virtqueue *vring_create_virtqueue_packed(
1579         unsigned int index,
1580         unsigned int num,
1581         unsigned int vring_align,
1582         struct virtio_device *vdev,
1583         bool weak_barriers,
1584         bool may_reduce_num,
1585         bool context,
1586         bool (*notify)(struct virtqueue *),
1587         void (*callback)(struct virtqueue *),
1588         const char *name)
1589 {
1590         struct vring_virtqueue *vq;
1591         struct vring_packed_desc *ring;
1592         struct vring_packed_desc_event *driver, *device;
1593         dma_addr_t ring_dma_addr, driver_event_dma_addr, device_event_dma_addr;
1594         size_t ring_size_in_bytes, event_size_in_bytes;
1595
1596         ring_size_in_bytes = num * sizeof(struct vring_packed_desc);
1597
1598         ring = vring_alloc_queue(vdev, ring_size_in_bytes,
1599                                  &ring_dma_addr,
1600                                  GFP_KERNEL|__GFP_NOWARN|__GFP_ZERO);
1601         if (!ring)
1602                 goto err_ring;
1603
1604         event_size_in_bytes = sizeof(struct vring_packed_desc_event);
1605
1606         driver = vring_alloc_queue(vdev, event_size_in_bytes,
1607                                    &driver_event_dma_addr,
1608                                    GFP_KERNEL|__GFP_NOWARN|__GFP_ZERO);
1609         if (!driver)
1610                 goto err_driver;
1611
1612         device = vring_alloc_queue(vdev, event_size_in_bytes,
1613                                    &device_event_dma_addr,
1614                                    GFP_KERNEL|__GFP_NOWARN|__GFP_ZERO);
1615         if (!device)
1616                 goto err_device;
1617
1618         vq = kmalloc(sizeof(*vq), GFP_KERNEL);
1619         if (!vq)
1620                 goto err_vq;
1621
1622         vq->vq.callback = callback;
1623         vq->vq.vdev = vdev;
1624         vq->vq.name = name;
1625         vq->vq.num_free = num;
1626         vq->vq.index = index;
1627         vq->we_own_ring = true;
1628         vq->notify = notify;
1629         vq->weak_barriers = weak_barriers;
1630         vq->broken = false;
1631         vq->last_used_idx = 0;
1632         vq->event_triggered = false;
1633         vq->num_added = 0;
1634         vq->packed_ring = true;
1635         vq->use_dma_api = vring_use_dma_api(vdev);
1636 #ifdef DEBUG
1637         vq->in_use = false;
1638         vq->last_add_time_valid = false;
1639 #endif
1640
1641         vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC) &&
1642                 !context;
1643         vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
1644
1645         if (virtio_has_feature(vdev, VIRTIO_F_ORDER_PLATFORM))
1646                 vq->weak_barriers = false;
1647
1648         vq->packed.ring_dma_addr = ring_dma_addr;
1649         vq->packed.driver_event_dma_addr = driver_event_dma_addr;
1650         vq->packed.device_event_dma_addr = device_event_dma_addr;
1651
1652         vq->packed.ring_size_in_bytes = ring_size_in_bytes;
1653         vq->packed.event_size_in_bytes = event_size_in_bytes;
1654
1655         vq->packed.vring.num = num;
1656         vq->packed.vring.desc = ring;
1657         vq->packed.vring.driver = driver;
1658         vq->packed.vring.device = device;
1659
1660         vq->packed.next_avail_idx = 0;
1661         vq->packed.avail_wrap_counter = 1;
1662         vq->packed.used_wrap_counter = 1;
1663         vq->packed.event_flags_shadow = 0;
1664         vq->packed.avail_used_flags = 1 << VRING_PACKED_DESC_F_AVAIL;
1665
1666         vq->packed.desc_state = kmalloc_array(num,
1667                         sizeof(struct vring_desc_state_packed),
1668                         GFP_KERNEL);
1669         if (!vq->packed.desc_state)
1670                 goto err_desc_state;
1671
1672         memset(vq->packed.desc_state, 0,
1673                 num * sizeof(struct vring_desc_state_packed));
1674
1675         /* Put everything in free lists. */
1676         vq->free_head = 0;
1677
1678         vq->packed.desc_extra = vring_alloc_desc_extra(vq, num);
1679         if (!vq->packed.desc_extra)
1680                 goto err_desc_extra;
1681
1682         /* No callback?  Tell other side not to bother us. */
1683         if (!callback) {
1684                 vq->packed.event_flags_shadow = VRING_PACKED_EVENT_FLAG_DISABLE;
1685                 vq->packed.vring.driver->flags =
1686                         cpu_to_le16(vq->packed.event_flags_shadow);
1687         }
1688
1689         list_add_tail(&vq->vq.list, &vdev->vqs);
1690         return &vq->vq;
1691
1692 err_desc_extra:
1693         kfree(vq->packed.desc_state);
1694 err_desc_state:
1695         kfree(vq);
1696 err_vq:
1697         vring_free_queue(vdev, event_size_in_bytes, device, device_event_dma_addr);
1698 err_device:
1699         vring_free_queue(vdev, event_size_in_bytes, driver, driver_event_dma_addr);
1700 err_driver:
1701         vring_free_queue(vdev, ring_size_in_bytes, ring, ring_dma_addr);
1702 err_ring:
1703         return NULL;
1704 }
1705
1706
1707 /*
1708  * Generic functions and exported symbols.
1709  */
1710
1711 static inline int virtqueue_add(struct virtqueue *_vq,
1712                                 struct scatterlist *sgs[],
1713                                 unsigned int total_sg,
1714                                 unsigned int out_sgs,
1715                                 unsigned int in_sgs,
1716                                 void *data,
1717                                 void *ctx,
1718                                 gfp_t gfp)
1719 {
1720         struct vring_virtqueue *vq = to_vvq(_vq);
1721
1722         return vq->packed_ring ? virtqueue_add_packed(_vq, sgs, total_sg,
1723                                         out_sgs, in_sgs, data, ctx, gfp) :
1724                                  virtqueue_add_split(_vq, sgs, total_sg,
1725                                         out_sgs, in_sgs, data, ctx, gfp);
1726 }
1727
1728 /**
1729  * virtqueue_add_sgs - expose buffers to other end
1730  * @_vq: the struct virtqueue we're talking about.
1731  * @sgs: array of terminated scatterlists.
1732  * @out_sgs: the number of scatterlists readable by other side
1733  * @in_sgs: the number of scatterlists which are writable (after readable ones)
1734  * @data: the token identifying the buffer.
1735  * @gfp: how to do memory allocations (if necessary).
1736  *
1737  * Caller must ensure we don't call this with other virtqueue operations
1738  * at the same time (except where noted).
1739  *
1740  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
1741  */
1742 int virtqueue_add_sgs(struct virtqueue *_vq,
1743                       struct scatterlist *sgs[],
1744                       unsigned int out_sgs,
1745                       unsigned int in_sgs,
1746                       void *data,
1747                       gfp_t gfp)
1748 {
1749         unsigned int i, total_sg = 0;
1750
1751         /* Count them first. */
1752         for (i = 0; i < out_sgs + in_sgs; i++) {
1753                 struct scatterlist *sg;
1754
1755                 for (sg = sgs[i]; sg; sg = sg_next(sg))
1756                         total_sg++;
1757         }
1758         return virtqueue_add(_vq, sgs, total_sg, out_sgs, in_sgs,
1759                              data, NULL, gfp);
1760 }
1761 EXPORT_SYMBOL_GPL(virtqueue_add_sgs);
1762
1763 /**
1764  * virtqueue_add_outbuf - expose output buffers to other end
1765  * @vq: the struct virtqueue we're talking about.
1766  * @sg: scatterlist (must be well-formed and terminated!)
1767  * @num: the number of entries in @sg readable by other side
1768  * @data: the token identifying the buffer.
1769  * @gfp: how to do memory allocations (if necessary).
1770  *
1771  * Caller must ensure we don't call this with other virtqueue operations
1772  * at the same time (except where noted).
1773  *
1774  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
1775  */
1776 int virtqueue_add_outbuf(struct virtqueue *vq,
1777                          struct scatterlist *sg, unsigned int num,
1778                          void *data,
1779                          gfp_t gfp)
1780 {
1781         return virtqueue_add(vq, &sg, num, 1, 0, data, NULL, gfp);
1782 }
1783 EXPORT_SYMBOL_GPL(virtqueue_add_outbuf);
1784
1785 /**
1786  * virtqueue_add_inbuf - expose input buffers to other end
1787  * @vq: the struct virtqueue we're talking about.
1788  * @sg: scatterlist (must be well-formed and terminated!)
1789  * @num: the number of entries in @sg writable by other side
1790  * @data: the token identifying the buffer.
1791  * @gfp: how to do memory allocations (if necessary).
1792  *
1793  * Caller must ensure we don't call this with other virtqueue operations
1794  * at the same time (except where noted).
1795  *
1796  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
1797  */
1798 int virtqueue_add_inbuf(struct virtqueue *vq,
1799                         struct scatterlist *sg, unsigned int num,
1800                         void *data,
1801                         gfp_t gfp)
1802 {
1803         return virtqueue_add(vq, &sg, num, 0, 1, data, NULL, gfp);
1804 }
1805 EXPORT_SYMBOL_GPL(virtqueue_add_inbuf);
1806
1807 /**
1808  * virtqueue_add_inbuf_ctx - expose input buffers to other end
1809  * @vq: the struct virtqueue we're talking about.
1810  * @sg: scatterlist (must be well-formed and terminated!)
1811  * @num: the number of entries in @sg writable by other side
1812  * @data: the token identifying the buffer.
1813  * @ctx: extra context for the token
1814  * @gfp: how to do memory allocations (if necessary).
1815  *
1816  * Caller must ensure we don't call this with other virtqueue operations
1817  * at the same time (except where noted).
1818  *
1819  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
1820  */
1821 int virtqueue_add_inbuf_ctx(struct virtqueue *vq,
1822                         struct scatterlist *sg, unsigned int num,
1823                         void *data,
1824                         void *ctx,
1825                         gfp_t gfp)
1826 {
1827         return virtqueue_add(vq, &sg, num, 0, 1, data, ctx, gfp);
1828 }
1829 EXPORT_SYMBOL_GPL(virtqueue_add_inbuf_ctx);
1830
1831 /**
1832  * virtqueue_kick_prepare - first half of split virtqueue_kick call.
1833  * @_vq: the struct virtqueue
1834  *
1835  * Instead of virtqueue_kick(), you can do:
1836  *      if (virtqueue_kick_prepare(vq))
1837  *              virtqueue_notify(vq);
1838  *
1839  * This is sometimes useful because the virtqueue_kick_prepare() needs
1840  * to be serialized, but the actual virtqueue_notify() call does not.
1841  */
1842 bool virtqueue_kick_prepare(struct virtqueue *_vq)
1843 {
1844         struct vring_virtqueue *vq = to_vvq(_vq);
1845
1846         return vq->packed_ring ? virtqueue_kick_prepare_packed(_vq) :
1847                                  virtqueue_kick_prepare_split(_vq);
1848 }
1849 EXPORT_SYMBOL_GPL(virtqueue_kick_prepare);
1850
1851 /**
1852  * virtqueue_notify - second half of split virtqueue_kick call.
1853  * @_vq: the struct virtqueue
1854  *
1855  * This does not need to be serialized.
1856  *
1857  * Returns false if host notify failed or queue is broken, otherwise true.
1858  */
1859 bool virtqueue_notify(struct virtqueue *_vq)
1860 {
1861         struct vring_virtqueue *vq = to_vvq(_vq);
1862
1863         if (unlikely(vq->broken))
1864                 return false;
1865
1866         /* Prod other side to tell it about changes. */
1867         if (!vq->notify(_vq)) {
1868                 vq->broken = true;
1869                 return false;
1870         }
1871         return true;
1872 }
1873 EXPORT_SYMBOL_GPL(virtqueue_notify);
1874
1875 /**
1876  * virtqueue_kick - update after add_buf
1877  * @vq: the struct virtqueue
1878  *
1879  * After one or more virtqueue_add_* calls, invoke this to kick
1880  * the other side.
1881  *
1882  * Caller must ensure we don't call this with other virtqueue
1883  * operations at the same time (except where noted).
1884  *
1885  * Returns false if kick failed, otherwise true.
1886  */
1887 bool virtqueue_kick(struct virtqueue *vq)
1888 {
1889         if (virtqueue_kick_prepare(vq))
1890                 return virtqueue_notify(vq);
1891         return true;
1892 }
1893 EXPORT_SYMBOL_GPL(virtqueue_kick);
1894
1895 /**
1896  * virtqueue_get_buf_ctx - get the next used buffer
1897  * @_vq: the struct virtqueue we're talking about.
1898  * @len: the length written into the buffer
1899  * @ctx: extra context for the token
1900  *
1901  * If the device wrote data into the buffer, @len will be set to the
1902  * amount written.  This means you don't need to clear the buffer
1903  * beforehand to ensure there's no data leakage in the case of short
1904  * writes.
1905  *
1906  * Caller must ensure we don't call this with other virtqueue
1907  * operations at the same time (except where noted).
1908  *
1909  * Returns NULL if there are no used buffers, or the "data" token
1910  * handed to virtqueue_add_*().
1911  */
1912 void *virtqueue_get_buf_ctx(struct virtqueue *_vq, unsigned int *len,
1913                             void **ctx)
1914 {
1915         struct vring_virtqueue *vq = to_vvq(_vq);
1916
1917         return vq->packed_ring ? virtqueue_get_buf_ctx_packed(_vq, len, ctx) :
1918                                  virtqueue_get_buf_ctx_split(_vq, len, ctx);
1919 }
1920 EXPORT_SYMBOL_GPL(virtqueue_get_buf_ctx);
1921
1922 void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
1923 {
1924         return virtqueue_get_buf_ctx(_vq, len, NULL);
1925 }
1926 EXPORT_SYMBOL_GPL(virtqueue_get_buf);
1927 /**
1928  * virtqueue_disable_cb - disable callbacks
1929  * @_vq: the struct virtqueue we're talking about.
1930  *
1931  * Note that this is not necessarily synchronous, hence unreliable and only
1932  * useful as an optimization.
1933  *
1934  * Unlike other operations, this need not be serialized.
1935  */
1936 void virtqueue_disable_cb(struct virtqueue *_vq)
1937 {
1938         struct vring_virtqueue *vq = to_vvq(_vq);
1939
1940         /* If device triggered an event already it won't trigger one again:
1941          * no need to disable.
1942          */
1943         if (vq->event_triggered)
1944                 return;
1945
1946         if (vq->packed_ring)
1947                 virtqueue_disable_cb_packed(_vq);
1948         else
1949                 virtqueue_disable_cb_split(_vq);
1950 }
1951 EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
1952
1953 /**
1954  * virtqueue_enable_cb_prepare - restart callbacks after disable_cb
1955  * @_vq: the struct virtqueue we're talking about.
1956  *
1957  * This re-enables callbacks; it returns current queue state
1958  * in an opaque unsigned value. This value should be later tested by
1959  * virtqueue_poll, to detect a possible race between the driver checking for
1960  * more work, and enabling callbacks.
1961  *
1962  * Caller must ensure we don't call this with other virtqueue
1963  * operations at the same time (except where noted).
1964  */
1965 unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
1966 {
1967         struct vring_virtqueue *vq = to_vvq(_vq);
1968
1969         if (vq->event_triggered)
1970                 vq->event_triggered = false;
1971
1972         return vq->packed_ring ? virtqueue_enable_cb_prepare_packed(_vq) :
1973                                  virtqueue_enable_cb_prepare_split(_vq);
1974 }
1975 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);
1976
1977 /**
1978  * virtqueue_poll - query pending used buffers
1979  * @_vq: the struct virtqueue we're talking about.
1980  * @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
1981  *
1982  * Returns "true" if there are pending used buffers in the queue.
1983  *
1984  * This does not need to be serialized.
1985  */
1986 bool virtqueue_poll(struct virtqueue *_vq, unsigned last_used_idx)
1987 {
1988         struct vring_virtqueue *vq = to_vvq(_vq);
1989
1990         if (unlikely(vq->broken))
1991                 return false;
1992
1993         virtio_mb(vq->weak_barriers);
1994         return vq->packed_ring ? virtqueue_poll_packed(_vq, last_used_idx) :
1995                                  virtqueue_poll_split(_vq, last_used_idx);
1996 }
1997 EXPORT_SYMBOL_GPL(virtqueue_poll);
1998
1999 /**
2000  * virtqueue_enable_cb - restart callbacks after disable_cb.
2001  * @_vq: the struct virtqueue we're talking about.
2002  *
2003  * This re-enables callbacks; it returns "false" if there are pending
2004  * buffers in the queue, to detect a possible race between the driver
2005  * checking for more work, and enabling callbacks.
2006  *
2007  * Caller must ensure we don't call this with other virtqueue
2008  * operations at the same time (except where noted).
2009  */
2010 bool virtqueue_enable_cb(struct virtqueue *_vq)
2011 {
2012         unsigned last_used_idx = virtqueue_enable_cb_prepare(_vq);
2013
2014         return !virtqueue_poll(_vq, last_used_idx);
2015 }
2016 EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
2017
2018 /**
2019  * virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
2020  * @_vq: the struct virtqueue we're talking about.
2021  *
2022  * This re-enables callbacks but hints to the other side to delay
2023  * interrupts until most of the available buffers have been processed;
2024  * it returns "false" if there are many pending buffers in the queue,
2025  * to detect a possible race between the driver checking for more work,
2026  * and enabling callbacks.
2027  *
2028  * Caller must ensure we don't call this with other virtqueue
2029  * operations at the same time (except where noted).
2030  */
2031 bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
2032 {
2033         struct vring_virtqueue *vq = to_vvq(_vq);
2034
2035         if (vq->event_triggered)
2036                 vq->event_triggered = false;
2037
2038         return vq->packed_ring ? virtqueue_enable_cb_delayed_packed(_vq) :
2039                                  virtqueue_enable_cb_delayed_split(_vq);
2040 }
2041 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
2042
2043 /**
2044  * virtqueue_detach_unused_buf - detach first unused buffer
2045  * @_vq: the struct virtqueue we're talking about.
2046  *
2047  * Returns NULL or the "data" token handed to virtqueue_add_*().
2048  * This is not valid on an active queue; it is useful only for device
2049  * shutdown.
2050  */
2051 void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
2052 {
2053         struct vring_virtqueue *vq = to_vvq(_vq);
2054
2055         return vq->packed_ring ? virtqueue_detach_unused_buf_packed(_vq) :
2056                                  virtqueue_detach_unused_buf_split(_vq);
2057 }
2058 EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
2059
2060 static inline bool more_used(const struct vring_virtqueue *vq)
2061 {
2062         return vq->packed_ring ? more_used_packed(vq) : more_used_split(vq);
2063 }
2064
2065 irqreturn_t vring_interrupt(int irq, void *_vq)
2066 {
2067         struct vring_virtqueue *vq = to_vvq(_vq);
2068
2069         if (!more_used(vq)) {
2070                 pr_debug("virtqueue interrupt with no work for %p\n", vq);
2071                 return IRQ_NONE;
2072         }
2073
2074         if (unlikely(vq->broken))
2075                 return IRQ_HANDLED;
2076
2077         /* Just a hint for performance: so it's ok that this can be racy! */
2078         if (vq->event)
2079                 vq->event_triggered = true;
2080
2081         pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
2082         if (vq->vq.callback)
2083                 vq->vq.callback(&vq->vq);
2084
2085         return IRQ_HANDLED;
2086 }
2087 EXPORT_SYMBOL_GPL(vring_interrupt);
2088
2089 /* Only available for split ring */
2090 struct virtqueue *__vring_new_virtqueue(unsigned int index,
2091                                         struct vring vring,
2092                                         struct virtio_device *vdev,
2093                                         bool weak_barriers,
2094                                         bool context,
2095                                         bool (*notify)(struct virtqueue *),
2096                                         void (*callback)(struct virtqueue *),
2097                                         const char *name)
2098 {
2099         unsigned int i;
2100         struct vring_virtqueue *vq;
2101
2102         if (virtio_has_feature(vdev, VIRTIO_F_RING_PACKED))
2103                 return NULL;
2104
2105         vq = kmalloc(sizeof(*vq), GFP_KERNEL);
2106         if (!vq)
2107                 return NULL;
2108
2109         vq->packed_ring = false;
2110         vq->vq.callback = callback;
2111         vq->vq.vdev = vdev;
2112         vq->vq.name = name;
2113         vq->vq.num_free = vring.num;
2114         vq->vq.index = index;
2115         vq->we_own_ring = false;
2116         vq->notify = notify;
2117         vq->weak_barriers = weak_barriers;
2118         vq->broken = false;
2119         vq->last_used_idx = 0;
2120         vq->event_triggered = false;
2121         vq->num_added = 0;
2122         vq->use_dma_api = vring_use_dma_api(vdev);
2123 #ifdef DEBUG
2124         vq->in_use = false;
2125         vq->last_add_time_valid = false;
2126 #endif
2127
2128         vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC) &&
2129                 !context;
2130         vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
2131
2132         if (virtio_has_feature(vdev, VIRTIO_F_ORDER_PLATFORM))
2133                 vq->weak_barriers = false;
2134
2135         vq->split.queue_dma_addr = 0;
2136         vq->split.queue_size_in_bytes = 0;
2137
2138         vq->split.vring = vring;
2139         vq->split.avail_flags_shadow = 0;
2140         vq->split.avail_idx_shadow = 0;
2141
2142         /* No callback?  Tell other side not to bother us. */
2143         if (!callback) {
2144                 vq->split.avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
2145                 if (!vq->event)
2146                         vq->split.vring.avail->flags = cpu_to_virtio16(vdev,
2147                                         vq->split.avail_flags_shadow);
2148         }
2149
2150         vq->split.desc_state = kmalloc_array(vring.num,
2151                         sizeof(struct vring_desc_state_split), GFP_KERNEL);
2152         if (!vq->split.desc_state) {
2153                 kfree(vq);
2154                 return NULL;
2155         }
2156
2157         /* Put everything in free lists. */
2158         vq->free_head = 0;
2159         for (i = 0; i < vring.num-1; i++)
2160                 vq->split.vring.desc[i].next = cpu_to_virtio16(vdev, i + 1);
2161         memset(vq->split.desc_state, 0, vring.num *
2162                         sizeof(struct vring_desc_state_split));
2163
2164         list_add_tail(&vq->vq.list, &vdev->vqs);
2165         return &vq->vq;
2166 }
2167 EXPORT_SYMBOL_GPL(__vring_new_virtqueue);
2168
2169 struct virtqueue *vring_create_virtqueue(
2170         unsigned int index,
2171         unsigned int num,
2172         unsigned int vring_align,
2173         struct virtio_device *vdev,
2174         bool weak_barriers,
2175         bool may_reduce_num,
2176         bool context,
2177         bool (*notify)(struct virtqueue *),
2178         void (*callback)(struct virtqueue *),
2179         const char *name)
2180 {
2181
2182         if (virtio_has_feature(vdev, VIRTIO_F_RING_PACKED))
2183                 return vring_create_virtqueue_packed(index, num, vring_align,
2184                                 vdev, weak_barriers, may_reduce_num,
2185                                 context, notify, callback, name);
2186
2187         return vring_create_virtqueue_split(index, num, vring_align,
2188                         vdev, weak_barriers, may_reduce_num,
2189                         context, notify, callback, name);
2190 }
2191 EXPORT_SYMBOL_GPL(vring_create_virtqueue);
2192
2193 /* Only available for split ring */
2194 struct virtqueue *vring_new_virtqueue(unsigned int index,
2195                                       unsigned int num,
2196                                       unsigned int vring_align,
2197                                       struct virtio_device *vdev,
2198                                       bool weak_barriers,
2199                                       bool context,
2200                                       void *pages,
2201                                       bool (*notify)(struct virtqueue *vq),
2202                                       void (*callback)(struct virtqueue *vq),
2203                                       const char *name)
2204 {
2205         struct vring vring;
2206
2207         if (virtio_has_feature(vdev, VIRTIO_F_RING_PACKED))
2208                 return NULL;
2209
2210         vring_init(&vring, num, pages, vring_align);
2211         return __vring_new_virtqueue(index, vring, vdev, weak_barriers, context,
2212                                      notify, callback, name);
2213 }
2214 EXPORT_SYMBOL_GPL(vring_new_virtqueue);
2215
2216 void vring_del_virtqueue(struct virtqueue *_vq)
2217 {
2218         struct vring_virtqueue *vq = to_vvq(_vq);
2219
2220         if (vq->we_own_ring) {
2221                 if (vq->packed_ring) {
2222                         vring_free_queue(vq->vq.vdev,
2223                                          vq->packed.ring_size_in_bytes,
2224                                          vq->packed.vring.desc,
2225                                          vq->packed.ring_dma_addr);
2226
2227                         vring_free_queue(vq->vq.vdev,
2228                                          vq->packed.event_size_in_bytes,
2229                                          vq->packed.vring.driver,
2230                                          vq->packed.driver_event_dma_addr);
2231
2232                         vring_free_queue(vq->vq.vdev,
2233                                          vq->packed.event_size_in_bytes,
2234                                          vq->packed.vring.device,
2235                                          vq->packed.device_event_dma_addr);
2236
2237                         kfree(vq->packed.desc_state);
2238                         kfree(vq->packed.desc_extra);
2239                 } else {
2240                         vring_free_queue(vq->vq.vdev,
2241                                          vq->split.queue_size_in_bytes,
2242                                          vq->split.vring.desc,
2243                                          vq->split.queue_dma_addr);
2244                 }
2245         }
2246         if (!vq->packed_ring)
2247                 kfree(vq->split.desc_state);
2248         list_del(&_vq->list);
2249         kfree(vq);
2250 }
2251 EXPORT_SYMBOL_GPL(vring_del_virtqueue);
2252
2253 /* Manipulates transport-specific feature bits. */
2254 void vring_transport_features(struct virtio_device *vdev)
2255 {
2256         unsigned int i;
2257
2258         for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
2259                 switch (i) {
2260                 case VIRTIO_RING_F_INDIRECT_DESC:
2261                         break;
2262                 case VIRTIO_RING_F_EVENT_IDX:
2263                         break;
2264                 case VIRTIO_F_VERSION_1:
2265                         break;
2266                 case VIRTIO_F_ACCESS_PLATFORM:
2267                         break;
2268                 case VIRTIO_F_RING_PACKED:
2269                         break;
2270                 case VIRTIO_F_ORDER_PLATFORM:
2271                         break;
2272                 default:
2273                         /* We don't understand this bit. */
2274                         __virtio_clear_bit(vdev, i);
2275                 }
2276         }
2277 }
2278 EXPORT_SYMBOL_GPL(vring_transport_features);
2279
2280 /**
2281  * virtqueue_get_vring_size - return the size of the virtqueue's vring
2282  * @_vq: the struct virtqueue containing the vring of interest.
2283  *
2284  * Returns the size of the vring.  This is mainly used for boasting to
2285  * userspace.  Unlike other operations, this need not be serialized.
2286  */
2287 unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
2288 {
2289
2290         struct vring_virtqueue *vq = to_vvq(_vq);
2291
2292         return vq->packed_ring ? vq->packed.vring.num : vq->split.vring.num;
2293 }
2294 EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
2295
2296 bool virtqueue_is_broken(struct virtqueue *_vq)
2297 {
2298         struct vring_virtqueue *vq = to_vvq(_vq);
2299
2300         return vq->broken;
2301 }
2302 EXPORT_SYMBOL_GPL(virtqueue_is_broken);
2303
2304 /*
2305  * This should prevent the device from being used, allowing drivers to
2306  * recover.  You may need to grab appropriate locks to flush.
2307  */
2308 void virtio_break_device(struct virtio_device *dev)
2309 {
2310         struct virtqueue *_vq;
2311
2312         list_for_each_entry(_vq, &dev->vqs, list) {
2313                 struct vring_virtqueue *vq = to_vvq(_vq);
2314                 vq->broken = true;
2315         }
2316 }
2317 EXPORT_SYMBOL_GPL(virtio_break_device);
2318
2319 dma_addr_t virtqueue_get_desc_addr(struct virtqueue *_vq)
2320 {
2321         struct vring_virtqueue *vq = to_vvq(_vq);
2322
2323         BUG_ON(!vq->we_own_ring);
2324
2325         if (vq->packed_ring)
2326                 return vq->packed.ring_dma_addr;
2327
2328         return vq->split.queue_dma_addr;
2329 }
2330 EXPORT_SYMBOL_GPL(virtqueue_get_desc_addr);
2331
2332 dma_addr_t virtqueue_get_avail_addr(struct virtqueue *_vq)
2333 {
2334         struct vring_virtqueue *vq = to_vvq(_vq);
2335
2336         BUG_ON(!vq->we_own_ring);
2337
2338         if (vq->packed_ring)
2339                 return vq->packed.driver_event_dma_addr;
2340
2341         return vq->split.queue_dma_addr +
2342                 ((char *)vq->split.vring.avail - (char *)vq->split.vring.desc);
2343 }
2344 EXPORT_SYMBOL_GPL(virtqueue_get_avail_addr);
2345
2346 dma_addr_t virtqueue_get_used_addr(struct virtqueue *_vq)
2347 {
2348         struct vring_virtqueue *vq = to_vvq(_vq);
2349
2350         BUG_ON(!vq->we_own_ring);
2351
2352         if (vq->packed_ring)
2353                 return vq->packed.device_event_dma_addr;
2354
2355         return vq->split.queue_dma_addr +
2356                 ((char *)vq->split.vring.used - (char *)vq->split.vring.desc);
2357 }
2358 EXPORT_SYMBOL_GPL(virtqueue_get_used_addr);
2359
2360 /* Only available for split ring */
2361 const struct vring *virtqueue_get_vring(struct virtqueue *vq)
2362 {
2363         return &to_vvq(vq)->split.vring;
2364 }
2365 EXPORT_SYMBOL_GPL(virtqueue_get_vring);
2366
2367 MODULE_LICENSE("GPL");