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