xref: /linux/drivers/virtio/virtio_ring.c (revision 2449b912a6d200ec09c25dc597ec42d22d2eea56)
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 enum vq_layout {
71 	VQ_LAYOUT_SPLIT = 0,
72 	VQ_LAYOUT_PACKED,
73 	VQ_LAYOUT_SPLIT_IN_ORDER,
74 	VQ_LAYOUT_PACKED_IN_ORDER,
75 };
76 
77 struct vring_desc_state_split {
78 	void *data;			/* Data for callback. */
79 
80 	/* Indirect desc table and extra table, if any. These two will be
81 	 * allocated together. So we won't stress more to the memory allocator.
82 	 */
83 	struct vring_desc *indir_desc;
84 	u32 total_in_len;
85 };
86 
87 struct vring_desc_state_packed {
88 	void *data;			/* Data for callback. */
89 
90 	/* Indirect desc table and extra table, if any. These two will be
91 	 * allocated together. So we won't stress more to the memory allocator.
92 	 */
93 	struct vring_packed_desc *indir_desc;
94 	u16 num;			/* Descriptor list length. */
95 	u16 last;			/* The last desc state in a list. */
96 	u32 total_in_len;		/* In length for the skipped buffer. */
97 };
98 
99 struct vring_desc_extra {
100 	dma_addr_t addr;		/* Descriptor DMA addr. */
101 	u32 len;			/* Descriptor length. */
102 	u16 flags;			/* Descriptor flags. */
103 	u16 next;			/* The next desc state in a list. */
104 };
105 
106 struct vring_virtqueue_split {
107 	/* Actual memory layout for this queue. */
108 	struct vring vring;
109 
110 	/* Last written value to avail->flags */
111 	u16 avail_flags_shadow;
112 
113 	/*
114 	 * Last written value to avail->idx in
115 	 * guest byte order.
116 	 */
117 	u16 avail_idx_shadow;
118 
119 	/* Per-descriptor state. */
120 	struct vring_desc_state_split *desc_state;
121 	struct vring_desc_extra *desc_extra;
122 
123 	/* DMA address and size information */
124 	dma_addr_t queue_dma_addr;
125 	size_t queue_size_in_bytes;
126 
127 	/*
128 	 * The parameters for creating vrings are reserved for creating new
129 	 * vring.
130 	 */
131 	u32 vring_align;
132 	bool may_reduce_num;
133 };
134 
135 struct vring_virtqueue_packed {
136 	/* Actual memory layout for this queue. */
137 	struct {
138 		unsigned int num;
139 		struct vring_packed_desc *desc;
140 		struct vring_packed_desc_event *driver;
141 		struct vring_packed_desc_event *device;
142 	} vring;
143 
144 	/* Driver ring wrap counter. */
145 	bool avail_wrap_counter;
146 
147 	/* Avail used flags. */
148 	u16 avail_used_flags;
149 
150 	/* Index of the next avail descriptor. */
151 	u16 next_avail_idx;
152 
153 	/*
154 	 * Last written value to driver->flags in
155 	 * guest byte order.
156 	 */
157 	u16 event_flags_shadow;
158 
159 	/* Per-descriptor state. */
160 	struct vring_desc_state_packed *desc_state;
161 	struct vring_desc_extra *desc_extra;
162 
163 	/* DMA address and size information */
164 	dma_addr_t ring_dma_addr;
165 	dma_addr_t driver_event_dma_addr;
166 	dma_addr_t device_event_dma_addr;
167 	size_t ring_size_in_bytes;
168 	size_t event_size_in_bytes;
169 };
170 
171 struct vring_virtqueue;
172 
173 struct virtqueue_ops {
174 	int (*add)(struct vring_virtqueue *vq, struct scatterlist *sgs[],
175 		   unsigned int total_sg, unsigned int out_sgs,
176 		   unsigned int in_sgs,	void *data,
177 		   void *ctx, bool premapped, gfp_t gfp,
178 		   unsigned long attr);
179 	void *(*get)(struct vring_virtqueue *vq, unsigned int *len, void **ctx);
180 	bool (*kick_prepare)(struct vring_virtqueue *vq);
181 	void (*disable_cb)(struct vring_virtqueue *vq);
182 	bool (*enable_cb_delayed)(struct vring_virtqueue *vq);
183 	unsigned int (*enable_cb_prepare)(struct vring_virtqueue *vq);
184 	bool (*poll)(const struct vring_virtqueue *vq,
185 		     unsigned int last_used_idx);
186 	void *(*detach_unused_buf)(struct vring_virtqueue *vq);
187 	bool (*more_used)(const struct vring_virtqueue *vq);
188 	int (*resize)(struct vring_virtqueue *vq, u32 num);
189 	void (*reset)(struct vring_virtqueue *vq);
190 };
191 
192 struct vring_virtqueue {
193 	struct virtqueue vq;
194 
195 	/* Is DMA API used? */
196 	bool use_map_api;
197 
198 	/* Can we use weak barriers? */
199 	bool weak_barriers;
200 
201 	/* Other side has made a mess, don't try any more. */
202 	bool broken;
203 
204 	/* Host supports indirect buffers */
205 	bool indirect;
206 
207 	/* Host publishes avail event idx */
208 	bool event;
209 
210 	enum vq_layout layout;
211 
212 	/*
213 	 * Without IN_ORDER it's the head of free buffer list. With
214 	 * IN_ORDER and SPLIT, it's the next available buffer
215 	 * index. With IN_ORDER and PACKED, it's unused.
216 	 */
217 	unsigned int free_head;
218 
219 	/*
220 	 * With IN_ORDER, once we see an in-order batch, this stores
221 	 * this last entry, and until we return the last buffer.
222 	 * After this, id is set to UINT_MAX to mark it invalid.
223 	 * Unused without IN_ORDER.
224 	 */
225 	struct used_entry {
226 		u32 id;
227 		u32 len;
228 	} batch_last;
229 
230 	/* Number we've added since last sync. */
231 	unsigned int num_added;
232 
233 	/* Last used index  we've seen.
234 	 * for split ring, it just contains last used index
235 	 * for packed ring:
236 	 * bits up to VRING_PACKED_EVENT_F_WRAP_CTR include the last used index.
237 	 * bits from VRING_PACKED_EVENT_F_WRAP_CTR include the used wrap counter.
238 	 */
239 	u16 last_used_idx;
240 
241 	/* With IN_ORDER and SPLIT, last descriptor id we used to
242 	 * detach buffer.
243 	 */
244 	u16 last_used;
245 
246 	/* Hint for event idx: already triggered no need to disable. */
247 	bool event_triggered;
248 
249 	union {
250 		/* Available for split ring */
251 		struct vring_virtqueue_split split;
252 
253 		/* Available for packed ring */
254 		struct vring_virtqueue_packed packed;
255 	};
256 
257 	/* How to notify other side. FIXME: commonalize hcalls! */
258 	bool (*notify)(struct virtqueue *vq);
259 
260 	/* DMA, allocation, and size information */
261 	bool we_own_ring;
262 
263 	union virtio_map map;
264 
265 #ifdef DEBUG
266 	/* They're supposed to lock for us. */
267 	unsigned int in_use;
268 
269 	/* Figure out if their kicks are too delayed. */
270 	bool last_add_time_valid;
271 	ktime_t last_add_time;
272 #endif
273 };
274 
275 /*
276  * Accessors for device-writable fields in virtio rings.
277  * These fields are concurrently written by the device and read by the driver.
278  * Use READ_ONCE() to prevent compiler optimizations, document the
279  * intentional data race and prevent KCSAN warnings.
280  */
281 static inline u16 vring_read_split_used_idx(const struct vring_virtqueue *vq)
282 {
283 	return virtio16_to_cpu(vq->vq.vdev,
284 			       READ_ONCE(vq->split.vring.used->idx));
285 }
286 
287 static inline u32 vring_read_split_used_id(const struct vring_virtqueue *vq,
288 					   u16 idx)
289 {
290 	return virtio32_to_cpu(vq->vq.vdev,
291 			       READ_ONCE(vq->split.vring.used->ring[idx].id));
292 }
293 
294 static inline u32 vring_read_split_used_len(const struct vring_virtqueue *vq, u16 idx)
295 {
296 	return virtio32_to_cpu(vq->vq.vdev,
297 			       READ_ONCE(vq->split.vring.used->ring[idx].len));
298 }
299 
300 static inline u16 vring_read_split_avail_event(const struct vring_virtqueue *vq)
301 {
302 	return virtio16_to_cpu(vq->vq.vdev,
303 			       READ_ONCE(vring_avail_event(&vq->split.vring)));
304 }
305 
306 static inline u16 vring_read_packed_desc_flags(const struct vring_virtqueue *vq,
307 					       u16 idx)
308 {
309 	return le16_to_cpu(READ_ONCE(vq->packed.vring.desc[idx].flags));
310 }
311 
312 static inline u16 vring_read_packed_desc_id(const struct vring_virtqueue *vq,
313 				            u16 idx)
314 {
315 	return le16_to_cpu(READ_ONCE(vq->packed.vring.desc[idx].id));
316 }
317 
318 static inline u32 vring_read_packed_desc_len(const struct vring_virtqueue *vq,
319 				             u16 idx)
320 {
321 	return le32_to_cpu(READ_ONCE(vq->packed.vring.desc[idx].len));
322 }
323 
324 static struct vring_desc_extra *vring_alloc_desc_extra(unsigned int num);
325 static void vring_free(struct virtqueue *_vq);
326 
327 /*
328  * Helpers.
329  */
330 
331 #define to_vvq(_vq) container_of_const(_vq, struct vring_virtqueue, vq)
332 
333 
334 static inline bool virtqueue_is_packed(const struct vring_virtqueue *vq)
335 {
336 	return vq->layout == VQ_LAYOUT_PACKED ||
337 	       vq->layout == VQ_LAYOUT_PACKED_IN_ORDER;
338 }
339 
340 static inline bool virtqueue_is_in_order(const struct vring_virtqueue *vq)
341 {
342 	return vq->layout == VQ_LAYOUT_SPLIT_IN_ORDER ||
343 	       vq->layout == VQ_LAYOUT_PACKED_IN_ORDER;
344 }
345 
346 static bool virtqueue_use_indirect(const struct vring_virtqueue *vq,
347 				   unsigned int total_sg)
348 {
349 	/*
350 	 * If the host supports indirect descriptor tables, and we have multiple
351 	 * buffers, then go indirect. FIXME: tune this threshold
352 	 */
353 	return (vq->indirect && total_sg > 1 && vq->vq.num_free);
354 }
355 
356 /*
357  * Modern virtio devices have feature bits to specify whether they need a
358  * quirk and bypass the IOMMU. If not there, just use the DMA API.
359  *
360  * If there, the interaction between virtio and DMA API is messy.
361  *
362  * On most systems with virtio, physical addresses match bus addresses,
363  * and it doesn't particularly matter whether we use the DMA API.
364  *
365  * On some systems, including Xen and any system with a physical device
366  * that speaks virtio behind a physical IOMMU, we must use the DMA API
367  * for virtio DMA to work at all.
368  *
369  * On other systems, including SPARC and PPC64, virtio-pci devices are
370  * enumerated as though they are behind an IOMMU, but the virtio host
371  * ignores the IOMMU, so we must either pretend that the IOMMU isn't
372  * there or somehow map everything as the identity.
373  *
374  * For the time being, we preserve historic behavior and bypass the DMA
375  * API.
376  *
377  * TODO: install a per-device DMA ops structure that does the right thing
378  * taking into account all the above quirks, and use the DMA API
379  * unconditionally on data path.
380  */
381 
382 static bool vring_use_map_api(const struct virtio_device *vdev)
383 {
384 	if (!virtio_has_dma_quirk(vdev))
385 		return true;
386 
387 	/* Otherwise, we are left to guess. */
388 	/*
389 	 * In theory, it's possible to have a buggy QEMU-supposed
390 	 * emulated Q35 IOMMU and Xen enabled at the same time.  On
391 	 * such a configuration, virtio has never worked and will
392 	 * not work without an even larger kludge.  Instead, enable
393 	 * the DMA API if we're a Xen guest, which at least allows
394 	 * all of the sensible Xen configurations to work correctly.
395 	 */
396 	if (xen_domain())
397 		return true;
398 
399 	return false;
400 }
401 
402 static bool vring_need_unmap_buffer(const struct vring_virtqueue *vring,
403 				    const struct vring_desc_extra *extra)
404 {
405 	return vring->use_map_api && (extra->addr != DMA_MAPPING_ERROR);
406 }
407 
408 size_t virtio_max_dma_size(const struct virtio_device *vdev)
409 {
410 	size_t max_segment_size = SIZE_MAX;
411 
412 	if (vring_use_map_api(vdev)) {
413 		if (vdev->map) {
414 			max_segment_size =
415 				vdev->map->max_mapping_size(vdev->vmap);
416 		} else
417 			max_segment_size =
418 				dma_max_mapping_size(vdev->dev.parent);
419 	}
420 
421 	return max_segment_size;
422 }
423 EXPORT_SYMBOL_GPL(virtio_max_dma_size);
424 
425 static void *vring_alloc_queue(struct virtio_device *vdev, size_t size,
426 			       dma_addr_t *map_handle, gfp_t flag,
427 			       union virtio_map map)
428 {
429 	if (vring_use_map_api(vdev)) {
430 		return virtqueue_map_alloc_coherent(vdev, map, size,
431 						    map_handle, flag);
432 	} else {
433 		void *queue = alloc_pages_exact(PAGE_ALIGN(size), flag);
434 
435 		if (queue) {
436 			phys_addr_t phys_addr = virt_to_phys(queue);
437 			*map_handle = (dma_addr_t)phys_addr;
438 
439 			/*
440 			 * Sanity check: make sure we dind't truncate
441 			 * the address.  The only arches I can find that
442 			 * have 64-bit phys_addr_t but 32-bit dma_addr_t
443 			 * are certain non-highmem MIPS and x86
444 			 * configurations, but these configurations
445 			 * should never allocate physical pages above 32
446 			 * bits, so this is fine.  Just in case, throw a
447 			 * warning and abort if we end up with an
448 			 * unrepresentable address.
449 			 */
450 			if (WARN_ON_ONCE(*map_handle != phys_addr)) {
451 				free_pages_exact(queue, PAGE_ALIGN(size));
452 				return NULL;
453 			}
454 		}
455 		return queue;
456 	}
457 }
458 
459 static void vring_free_queue(struct virtio_device *vdev, size_t size,
460 			     void *queue, dma_addr_t map_handle,
461 			     union virtio_map map)
462 {
463 	if (vring_use_map_api(vdev))
464 		virtqueue_map_free_coherent(vdev, map, size,
465 					    queue, map_handle);
466 	else
467 		free_pages_exact(queue, PAGE_ALIGN(size));
468 }
469 
470 /*
471  * The DMA ops on various arches are rather gnarly right now, and
472  * making all of the arch DMA ops work on the vring device itself
473  * is a mess.
474  */
475 static struct device *vring_dma_dev(const struct vring_virtqueue *vq)
476 {
477 	return vq->map.dma_dev;
478 }
479 
480 static int vring_mapping_error(const struct vring_virtqueue *vq,
481 			       dma_addr_t addr)
482 {
483 	struct virtio_device *vdev = vq->vq.vdev;
484 
485 	if (!vq->use_map_api)
486 		return 0;
487 
488 	if (vdev->map)
489 		return vdev->map->mapping_error(vq->map, addr);
490 	else
491 		return dma_mapping_error(vring_dma_dev(vq), addr);
492 }
493 
494 /* Map one sg entry. */
495 static int vring_map_one_sg(const struct vring_virtqueue *vq, struct scatterlist *sg,
496 			    enum dma_data_direction direction, dma_addr_t *addr,
497 			    u32 *len, bool premapped, unsigned long attr)
498 {
499 	if (premapped) {
500 		*addr = sg_dma_address(sg);
501 		*len = sg_dma_len(sg);
502 		return 0;
503 	}
504 
505 	*len = sg->length;
506 
507 	if (!vq->use_map_api) {
508 		/*
509 		 * If DMA is not used, KMSAN doesn't know that the scatterlist
510 		 * is initialized by the hardware. Explicitly check/unpoison it
511 		 * depending on the direction.
512 		 */
513 		kmsan_handle_dma(sg_phys(sg), sg->length, direction);
514 		*addr = (dma_addr_t)sg_phys(sg);
515 		return 0;
516 	}
517 
518 	/*
519 	 * We can't use dma_map_sg, because we don't use scatterlists in
520 	 * the way it expects (we don't guarantee that the scatterlist
521 	 * will exist for the lifetime of the mapping).
522 	 */
523 	*addr = virtqueue_map_page_attrs(&vq->vq, sg_page(sg),
524 					 sg->offset, sg->length,
525 					 direction, attr);
526 
527 	if (vring_mapping_error(vq, *addr))
528 		return -ENOMEM;
529 
530 	return 0;
531 }
532 
533 static dma_addr_t vring_map_single(const struct vring_virtqueue *vq,
534 				   void *cpu_addr, size_t size,
535 				   enum dma_data_direction direction)
536 {
537 	if (!vq->use_map_api)
538 		return (dma_addr_t)virt_to_phys(cpu_addr);
539 
540 	return virtqueue_map_single_attrs(&vq->vq, cpu_addr,
541 					  size, direction, 0);
542 }
543 
544 static void virtqueue_init(struct vring_virtqueue *vq, u32 num)
545 {
546 	vq->vq.num_free = num;
547 
548 	if (virtqueue_is_packed(vq))
549 		vq->last_used_idx = 0 | (1 << VRING_PACKED_EVENT_F_WRAP_CTR);
550 	else
551 		vq->last_used_idx = 0;
552 
553 	vq->last_used = 0;
554 
555 	vq->event_triggered = false;
556 	vq->num_added = 0;
557 
558 #ifdef DEBUG
559 	vq->in_use = false;
560 	vq->last_add_time_valid = false;
561 #endif
562 
563 	if (virtqueue_is_in_order(vq)) {
564 		vq->free_head = 0;
565 		vq->batch_last.id = UINT_MAX;
566 	}
567 }
568 
569 
570 /*
571  * Split ring specific functions - *_split().
572  */
573 
574 static unsigned int vring_unmap_one_split(const struct vring_virtqueue *vq,
575 					  struct vring_desc_extra *extra)
576 {
577 	u16 flags;
578 
579 	flags = extra->flags;
580 
581 	if (flags & VRING_DESC_F_INDIRECT) {
582 		if (!vq->use_map_api)
583 			goto out;
584 	} else if (!vring_need_unmap_buffer(vq, extra))
585 		goto out;
586 
587 	virtqueue_unmap_page_attrs(&vq->vq,
588 				   extra->addr,
589 				   extra->len,
590 				   (flags & VRING_DESC_F_WRITE) ?
591 				   DMA_FROM_DEVICE : DMA_TO_DEVICE,
592 				   0);
593 
594 out:
595 	return extra->next;
596 }
597 
598 static struct vring_desc *alloc_indirect_split(struct vring_virtqueue *vq,
599 					       unsigned int total_sg,
600 					       gfp_t gfp)
601 {
602 	struct vring_desc_extra *extra;
603 	struct vring_desc *desc;
604 	unsigned int i, size;
605 
606 	/*
607 	 * We require lowmem mappings for the descriptors because
608 	 * otherwise virt_to_phys will give us bogus addresses in the
609 	 * virtqueue.
610 	 */
611 	gfp &= ~__GFP_HIGHMEM;
612 
613 	size = sizeof(*desc) * total_sg + sizeof(*extra) * total_sg;
614 
615 	desc = kmalloc(size, gfp);
616 	if (!desc)
617 		return NULL;
618 
619 	extra = (struct vring_desc_extra *)&desc[total_sg];
620 
621 	for (i = 0; i < total_sg; i++)
622 		extra[i].next = i + 1;
623 
624 	return desc;
625 }
626 
627 static inline unsigned int virtqueue_add_desc_split(struct vring_virtqueue *vq,
628 						    struct vring_desc *desc,
629 						    struct vring_desc_extra *extra,
630 						    unsigned int i,
631 						    dma_addr_t addr,
632 						    unsigned int len,
633 						    u16 flags, bool premapped)
634 {
635 	struct virtio_device *vdev = vq->vq.vdev;
636 	u16 next;
637 
638 	desc[i].flags = cpu_to_virtio16(vdev, flags);
639 	desc[i].addr = cpu_to_virtio64(vdev, addr);
640 	desc[i].len = cpu_to_virtio32(vdev, len);
641 
642 	extra[i].addr = premapped ? DMA_MAPPING_ERROR : addr;
643 	extra[i].len = len;
644 	extra[i].flags = flags;
645 
646 	next = extra[i].next;
647 
648 	desc[i].next = cpu_to_virtio16(vdev, next);
649 
650 	return next;
651 }
652 
653 static inline int virtqueue_add_split(struct vring_virtqueue *vq,
654 				      struct scatterlist *sgs[],
655 				      unsigned int total_sg,
656 				      unsigned int out_sgs,
657 				      unsigned int in_sgs,
658 				      void *data,
659 				      void *ctx,
660 				      bool premapped,
661 				      gfp_t gfp,
662 				      unsigned long attr)
663 {
664 	struct vring_desc_extra *extra;
665 	struct scatterlist *sg;
666 	struct vring_desc *desc;
667 	unsigned int i, n, avail, descs_used, err_idx, sg_count = 0;
668 	/* Total length for in-order */
669 	unsigned int total_in_len = 0;
670 	int head;
671 	bool indirect;
672 
673 	START_USE(vq);
674 
675 	BUG_ON(data == NULL);
676 	BUG_ON(ctx && vq->indirect);
677 
678 	if (unlikely(vq->broken)) {
679 		END_USE(vq);
680 		return -EIO;
681 	}
682 
683 	LAST_ADD_TIME_UPDATE(vq);
684 
685 	BUG_ON(total_sg == 0);
686 
687 	head = vq->free_head;
688 
689 	if (virtqueue_use_indirect(vq, total_sg))
690 		desc = alloc_indirect_split(vq, total_sg, gfp);
691 	else {
692 		desc = NULL;
693 		WARN_ON_ONCE(total_sg > vq->split.vring.num && !vq->indirect);
694 	}
695 
696 	if (desc) {
697 		/* Use a single buffer which doesn't continue */
698 		indirect = true;
699 		/* Set up rest to use this indirect table. */
700 		i = 0;
701 		descs_used = 1;
702 		extra = (struct vring_desc_extra *)&desc[total_sg];
703 	} else {
704 		indirect = false;
705 		desc = vq->split.vring.desc;
706 		extra = vq->split.desc_extra;
707 		i = head;
708 		descs_used = total_sg;
709 	}
710 
711 	if (unlikely(vq->vq.num_free < descs_used)) {
712 		pr_debug("Can't add buf len %i - avail = %i\n",
713 			 descs_used, vq->vq.num_free);
714 		/* FIXME: for historical reasons, we force a notify here if
715 		 * there are outgoing parts to the buffer.  Presumably the
716 		 * host should service the ring ASAP. */
717 		if (out_sgs)
718 			vq->notify(&vq->vq);
719 		if (indirect)
720 			kfree(desc);
721 		END_USE(vq);
722 		return -ENOSPC;
723 	}
724 
725 	for (n = 0; n < out_sgs; n++) {
726 		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
727 			dma_addr_t addr;
728 			u32 len;
729 			u16 flags = 0;
730 
731 			if (++sg_count != total_sg)
732 				flags |= VRING_DESC_F_NEXT;
733 
734 			if (vring_map_one_sg(vq, sg, DMA_TO_DEVICE, &addr, &len,
735 					     premapped, attr))
736 				goto unmap_release;
737 
738 			/* Note that we trust indirect descriptor
739 			 * table since it use stream DMA mapping.
740 			 */
741 			i = virtqueue_add_desc_split(vq, desc, extra, i, addr,
742 						     len, flags, premapped);
743 		}
744 	}
745 	for (; n < (out_sgs + in_sgs); n++) {
746 		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
747 			dma_addr_t addr;
748 			u32 len;
749 			u16 flags = VRING_DESC_F_WRITE;
750 
751 			if (++sg_count != total_sg)
752 				flags |= VRING_DESC_F_NEXT;
753 
754 			if (vring_map_one_sg(vq, sg, DMA_FROM_DEVICE, &addr, &len,
755 					     premapped, attr))
756 				goto unmap_release;
757 
758 			/* Note that we trust indirect descriptor
759 			 * table since it use stream DMA mapping.
760 			 */
761 			i = virtqueue_add_desc_split(vq, desc, extra, i, addr,
762 						     len, flags, premapped);
763 			total_in_len += len;
764 		}
765 	}
766 
767 	if (indirect) {
768 		/* Now that the indirect table is filled in, map it. */
769 		dma_addr_t addr = vring_map_single(
770 			vq, desc, total_sg * sizeof(struct vring_desc),
771 			DMA_TO_DEVICE);
772 		if (vring_mapping_error(vq, addr))
773 			goto unmap_release;
774 
775 		virtqueue_add_desc_split(vq, vq->split.vring.desc,
776 					 vq->split.desc_extra,
777 					 head, addr,
778 					 total_sg * sizeof(struct vring_desc),
779 					 VRING_DESC_F_INDIRECT, false);
780 	}
781 
782 	/* We're using some buffers from the free list. */
783 	vq->vq.num_free -= descs_used;
784 
785 	/* Update free pointer */
786 	if (virtqueue_is_in_order(vq)) {
787 		vq->free_head += descs_used;
788 		if (vq->free_head >= vq->split.vring.num)
789 			vq->free_head -= vq->split.vring.num;
790 		vq->split.desc_state[head].total_in_len = total_in_len;
791 	} else if (indirect)
792 		vq->free_head = vq->split.desc_extra[head].next;
793 	else
794 		vq->free_head = i;
795 
796 	/* Store token and indirect buffer state. */
797 	vq->split.desc_state[head].data = data;
798 	if (indirect)
799 		vq->split.desc_state[head].indir_desc = desc;
800 	else
801 		vq->split.desc_state[head].indir_desc = ctx;
802 
803 	/* Put entry in available array (but don't update avail->idx until they
804 	 * do sync). */
805 	avail = vq->split.avail_idx_shadow & (vq->split.vring.num - 1);
806 	vq->split.vring.avail->ring[avail] = cpu_to_virtio16(vq->vq.vdev, head);
807 
808 	/* Descriptors and available array need to be set before we expose the
809 	 * new available array entries. */
810 	virtio_wmb(vq->weak_barriers);
811 	vq->split.avail_idx_shadow++;
812 	vq->split.vring.avail->idx = cpu_to_virtio16(vq->vq.vdev,
813 						vq->split.avail_idx_shadow);
814 	vq->num_added++;
815 
816 	pr_debug("Added buffer head %i to %p\n", head, vq);
817 	END_USE(vq);
818 
819 	/* This is very unlikely, but theoretically possible.  Kick
820 	 * just in case. */
821 	if (unlikely(vq->num_added == (1 << 16) - 1))
822 		virtqueue_kick(&vq->vq);
823 
824 	return 0;
825 
826 unmap_release:
827 	err_idx = i;
828 
829 	if (indirect)
830 		i = 0;
831 	else
832 		i = head;
833 
834 	for (n = 0; n < total_sg; n++) {
835 		if (i == err_idx)
836 			break;
837 
838 		i = vring_unmap_one_split(vq, &extra[i]);
839 	}
840 
841 	if (indirect)
842 		kfree(desc);
843 
844 	END_USE(vq);
845 	return -ENOMEM;
846 }
847 
848 static bool virtqueue_kick_prepare_split(struct vring_virtqueue *vq)
849 {
850 	u16 new, old;
851 	bool needs_kick;
852 
853 	START_USE(vq);
854 	/* We need to expose available array entries before checking avail
855 	 * event. */
856 	virtio_mb(vq->weak_barriers);
857 
858 	old = vq->split.avail_idx_shadow - vq->num_added;
859 	new = vq->split.avail_idx_shadow;
860 	vq->num_added = 0;
861 
862 	LAST_ADD_TIME_CHECK(vq);
863 	LAST_ADD_TIME_INVALID(vq);
864 
865 	if (vq->event) {
866 		needs_kick = vring_need_event(vring_read_split_avail_event(vq),
867 					      new, old);
868 	} else {
869 		needs_kick = !(vq->split.vring.used->flags &
870 					cpu_to_virtio16(vq->vq.vdev,
871 						VRING_USED_F_NO_NOTIFY));
872 	}
873 	END_USE(vq);
874 	return needs_kick;
875 }
876 
877 static void detach_indirect_split(struct vring_virtqueue *vq,
878 				  unsigned int head)
879 {
880 	struct vring_desc_extra *extra = vq->split.desc_extra;
881 	struct vring_desc *indir_desc = vq->split.desc_state[head].indir_desc;
882 	unsigned int j;
883 	u32 len, num;
884 
885 	/* Free the indirect table, if any, now that it's unmapped. */
886 	if (!indir_desc)
887 		return;
888 	len = vq->split.desc_extra[head].len;
889 
890 	BUG_ON(!(vq->split.desc_extra[head].flags &
891 			VRING_DESC_F_INDIRECT));
892 	BUG_ON(len == 0 || len % sizeof(struct vring_desc));
893 
894 	num = len / sizeof(struct vring_desc);
895 
896 	extra = (struct vring_desc_extra *)&indir_desc[num];
897 
898 	if (vq->use_map_api) {
899 		for (j = 0; j < num; j++)
900 			vring_unmap_one_split(vq, &extra[j]);
901 	}
902 
903 	kfree(indir_desc);
904 	vq->split.desc_state[head].indir_desc = NULL;
905 }
906 
907 static unsigned detach_buf_split_in_order(struct vring_virtqueue *vq,
908 					  unsigned int head,
909 					  void **ctx)
910 {
911 	struct vring_desc_extra *extra;
912 	unsigned int i;
913 
914 	/* Clear data ptr. */
915 	vq->split.desc_state[head].data = NULL;
916 
917 	extra = vq->split.desc_extra;
918 
919 	/* Put back on free list: unmap first-level descriptors and find end */
920 	i = head;
921 
922 	while (extra[i].flags & VRING_DESC_F_NEXT) {
923 		i = vring_unmap_one_split(vq, &extra[i]);
924 		vq->vq.num_free++;
925 	}
926 
927 	vring_unmap_one_split(vq, &extra[i]);
928 
929 	/* Plus final descriptor */
930 	vq->vq.num_free++;
931 
932 	if (vq->indirect)
933 		detach_indirect_split(vq, head);
934 	else if (ctx)
935 		*ctx = vq->split.desc_state[head].indir_desc;
936 
937 	return i;
938 }
939 
940 static void detach_buf_split(struct vring_virtqueue *vq, unsigned int head,
941 			     void **ctx)
942 {
943 	unsigned int i = detach_buf_split_in_order(vq, head, ctx);
944 
945 	vq->split.desc_extra[i].next = vq->free_head;
946 	vq->free_head = head;
947 }
948 
949 static bool virtqueue_poll_split(const struct vring_virtqueue *vq,
950 				 unsigned int last_used_idx)
951 {
952 	return (u16)last_used_idx != vring_read_split_used_idx(vq);
953 }
954 
955 static bool more_used_split(const struct vring_virtqueue *vq)
956 {
957 	return virtqueue_poll_split(vq, vq->last_used_idx);
958 }
959 
960 static bool more_used_split_in_order(const struct vring_virtqueue *vq)
961 {
962 	if (vq->batch_last.id != UINT_MAX)
963 		return true;
964 
965 	return virtqueue_poll_split(vq, vq->last_used_idx);
966 }
967 
968 static void *virtqueue_get_buf_ctx_split(struct vring_virtqueue *vq,
969 					 unsigned int *len,
970 					 void **ctx)
971 {
972 	void *ret;
973 	unsigned int i;
974 	u16 last_used;
975 
976 	START_USE(vq);
977 
978 	if (unlikely(vq->broken)) {
979 		END_USE(vq);
980 		return NULL;
981 	}
982 
983 	if (!more_used_split(vq)) {
984 		pr_debug("No more buffers in queue\n");
985 		END_USE(vq);
986 		return NULL;
987 	}
988 
989 	/* Only get used array entries after they have been exposed by host. */
990 	virtio_rmb(vq->weak_barriers);
991 
992 	last_used = (vq->last_used_idx & (vq->split.vring.num - 1));
993 	i = vring_read_split_used_id(vq, last_used);
994 	*len = vring_read_split_used_len(vq, last_used);
995 
996 	if (unlikely(i >= vq->split.vring.num)) {
997 		BAD_RING(vq, "id %u out of range\n", i);
998 		return NULL;
999 	}
1000 	if (unlikely(!vq->split.desc_state[i].data)) {
1001 		BAD_RING(vq, "id %u is not a head!\n", i);
1002 		return NULL;
1003 	}
1004 
1005 	/* detach_buf_split clears data, so grab it now. */
1006 	ret = vq->split.desc_state[i].data;
1007 	detach_buf_split(vq, i, ctx);
1008 	vq->last_used_idx++;
1009 	/* If we expect an interrupt for the next entry, tell host
1010 	 * by writing event index and flush out the write before
1011 	 * the read in the next get_buf call. */
1012 	if (!(vq->split.avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT))
1013 		virtio_store_mb(vq->weak_barriers,
1014 				&vring_used_event(&vq->split.vring),
1015 				cpu_to_virtio16(vq->vq.vdev, vq->last_used_idx));
1016 
1017 	LAST_ADD_TIME_INVALID(vq);
1018 
1019 	END_USE(vq);
1020 	return ret;
1021 }
1022 
1023 static void *virtqueue_get_buf_ctx_split_in_order(struct vring_virtqueue *vq,
1024 						  unsigned int *len,
1025 						  void **ctx)
1026 {
1027 	void *ret;
1028 	unsigned int num = vq->split.vring.num;
1029 	unsigned int num_free = vq->vq.num_free;
1030 	u16 last_used, last_used_idx;
1031 
1032 	START_USE(vq);
1033 
1034 	if (unlikely(vq->broken)) {
1035 		END_USE(vq);
1036 		return NULL;
1037 	}
1038 
1039 	last_used = vq->last_used & (num - 1);
1040 	last_used_idx = vq->last_used_idx & (num - 1);
1041 
1042 	if (vq->batch_last.id == UINT_MAX) {
1043 		if (!more_used_split_in_order(vq)) {
1044 			pr_debug("No more buffers in queue\n");
1045 			END_USE(vq);
1046 			return NULL;
1047 		}
1048 
1049 		/*
1050 		 * Only get used array entries after they have been
1051 		 * exposed by host.
1052 		 */
1053 		virtio_rmb(vq->weak_barriers);
1054 
1055 		vq->batch_last.id = vring_read_split_used_id(vq, last_used_idx);
1056 		vq->batch_last.len = vring_read_split_used_len(vq, last_used_idx);
1057 	}
1058 
1059 	if (vq->batch_last.id == last_used) {
1060 		vq->batch_last.id = UINT_MAX;
1061 		*len = vq->batch_last.len;
1062 	} else {
1063 		*len = vq->split.desc_state[last_used].total_in_len;
1064 	}
1065 
1066 	if (unlikely(!vq->split.desc_state[last_used].data)) {
1067 		BAD_RING(vq, "id %u is not a head!\n", last_used);
1068 		return NULL;
1069 	}
1070 
1071 	/* detach_buf_split clears data, so grab it now. */
1072 	ret = vq->split.desc_state[last_used].data;
1073 	detach_buf_split_in_order(vq, last_used, ctx);
1074 
1075 	vq->last_used_idx++;
1076 	vq->last_used += (vq->vq.num_free - num_free);
1077 	/* If we expect an interrupt for the next entry, tell host
1078 	 * by writing event index and flush out the write before
1079 	 * the read in the next get_buf call. */
1080 	if (!(vq->split.avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT))
1081 		virtio_store_mb(vq->weak_barriers,
1082 				&vring_used_event(&vq->split.vring),
1083 				cpu_to_virtio16(vq->vq.vdev, vq->last_used_idx));
1084 
1085 	LAST_ADD_TIME_INVALID(vq);
1086 
1087 	END_USE(vq);
1088 	return ret;
1089 }
1090 
1091 static void virtqueue_disable_cb_split(struct vring_virtqueue *vq)
1092 {
1093 	if (!(vq->split.avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT)) {
1094 		vq->split.avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
1095 
1096 		/*
1097 		 * If device triggered an event already it won't trigger one again:
1098 		 * no need to disable.
1099 		 */
1100 		if (vq->event_triggered)
1101 			return;
1102 
1103 		if (vq->event)
1104 			/* TODO: this is a hack. Figure out a cleaner value to write. */
1105 			vring_used_event(&vq->split.vring) = 0x0;
1106 		else
1107 			vq->split.vring.avail->flags =
1108 				cpu_to_virtio16(vq->vq.vdev,
1109 						vq->split.avail_flags_shadow);
1110 	}
1111 }
1112 
1113 static unsigned int virtqueue_enable_cb_prepare_split(struct vring_virtqueue *vq)
1114 {
1115 	u16 last_used_idx;
1116 
1117 	START_USE(vq);
1118 
1119 	/* We optimistically turn back on interrupts, then check if there was
1120 	 * more to do. */
1121 	/* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
1122 	 * either clear the flags bit or point the event index at the next
1123 	 * entry. Always do both to keep code simple. */
1124 	if (vq->split.avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
1125 		vq->split.avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
1126 		if (!vq->event)
1127 			vq->split.vring.avail->flags =
1128 				cpu_to_virtio16(vq->vq.vdev,
1129 						vq->split.avail_flags_shadow);
1130 	}
1131 	vring_used_event(&vq->split.vring) = cpu_to_virtio16(vq->vq.vdev,
1132 			last_used_idx = vq->last_used_idx);
1133 	END_USE(vq);
1134 	return last_used_idx;
1135 }
1136 
1137 static bool virtqueue_enable_cb_delayed_split(struct vring_virtqueue *vq)
1138 {
1139 	u16 bufs;
1140 
1141 	START_USE(vq);
1142 
1143 	/* We optimistically turn back on interrupts, then check if there was
1144 	 * more to do. */
1145 	/* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
1146 	 * either clear the flags bit or point the event index at the next
1147 	 * entry. Always update the event index to keep code simple. */
1148 	if (vq->split.avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
1149 		vq->split.avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
1150 		if (!vq->event)
1151 			vq->split.vring.avail->flags =
1152 				cpu_to_virtio16(vq->vq.vdev,
1153 						vq->split.avail_flags_shadow);
1154 	}
1155 	/* TODO: tune this threshold */
1156 	bufs = (u16)(vq->split.avail_idx_shadow - vq->last_used_idx) * 3 / 4;
1157 
1158 	virtio_store_mb(vq->weak_barriers,
1159 			&vring_used_event(&vq->split.vring),
1160 			cpu_to_virtio16(vq->vq.vdev, vq->last_used_idx + bufs));
1161 
1162 	if (unlikely((u16)(vring_read_split_used_idx(vq)
1163 					- vq->last_used_idx) > bufs)) {
1164 		END_USE(vq);
1165 		return false;
1166 	}
1167 
1168 	END_USE(vq);
1169 	return true;
1170 }
1171 
1172 static void *virtqueue_detach_unused_buf_split(struct vring_virtqueue *vq)
1173 {
1174 	unsigned int i;
1175 	void *buf;
1176 
1177 	START_USE(vq);
1178 
1179 	for (i = 0; i < vq->split.vring.num; i++) {
1180 		if (!vq->split.desc_state[i].data)
1181 			continue;
1182 		/* detach_buf_split clears data, so grab it now. */
1183 		buf = vq->split.desc_state[i].data;
1184 		if (virtqueue_is_in_order(vq))
1185 			detach_buf_split_in_order(vq, i, NULL);
1186 		else
1187 			detach_buf_split(vq, i, NULL);
1188 		vq->split.avail_idx_shadow--;
1189 		vq->split.vring.avail->idx = cpu_to_virtio16(vq->vq.vdev,
1190 				vq->split.avail_idx_shadow);
1191 		END_USE(vq);
1192 		return buf;
1193 	}
1194 	/* That should have freed everything. */
1195 	BUG_ON(vq->vq.num_free != vq->split.vring.num);
1196 
1197 	END_USE(vq);
1198 	return NULL;
1199 }
1200 
1201 static void virtqueue_vring_init_split(struct vring_virtqueue_split *vring_split,
1202 				       struct vring_virtqueue *vq)
1203 {
1204 	struct virtio_device *vdev;
1205 
1206 	vdev = vq->vq.vdev;
1207 
1208 	vring_split->avail_flags_shadow = 0;
1209 	vring_split->avail_idx_shadow = 0;
1210 
1211 	/* No callback?  Tell other side not to bother us. */
1212 	if (!vq->vq.callback) {
1213 		vring_split->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
1214 		if (!vq->event)
1215 			vring_split->vring.avail->flags = cpu_to_virtio16(vdev,
1216 					vring_split->avail_flags_shadow);
1217 	}
1218 }
1219 
1220 static void virtqueue_reset_split(struct vring_virtqueue *vq)
1221 {
1222 	int num;
1223 
1224 	num = vq->split.vring.num;
1225 
1226 	vq->split.vring.avail->flags = 0;
1227 	vq->split.vring.avail->idx = 0;
1228 
1229 	/* reset avail event */
1230 	vq->split.vring.avail->ring[num] = 0;
1231 
1232 	vq->split.vring.used->flags = 0;
1233 	vq->split.vring.used->idx = 0;
1234 
1235 	/* reset used event */
1236 	*(__virtio16 *)&(vq->split.vring.used->ring[num]) = 0;
1237 
1238 	virtqueue_init(vq, num);
1239 
1240 	virtqueue_vring_init_split(&vq->split, vq);
1241 }
1242 
1243 static void virtqueue_vring_attach_split(struct vring_virtqueue *vq,
1244 					 struct vring_virtqueue_split *vring_split)
1245 {
1246 	vq->split = *vring_split;
1247 
1248 	/* Put everything in free lists. */
1249 	vq->free_head = 0;
1250 	vq->batch_last.id = UINT_MAX;
1251 }
1252 
1253 static int vring_alloc_state_extra_split(struct vring_virtqueue_split *vring_split)
1254 {
1255 	struct vring_desc_state_split *state;
1256 	struct vring_desc_extra *extra;
1257 	u32 num = vring_split->vring.num;
1258 
1259 	state = kmalloc_objs(struct vring_desc_state_split, num);
1260 	if (!state)
1261 		goto err_state;
1262 
1263 	extra = vring_alloc_desc_extra(num);
1264 	if (!extra)
1265 		goto err_extra;
1266 
1267 	memset(state, 0, num * sizeof(struct vring_desc_state_split));
1268 
1269 	vring_split->desc_state = state;
1270 	vring_split->desc_extra = extra;
1271 	return 0;
1272 
1273 err_extra:
1274 	kfree(state);
1275 err_state:
1276 	return -ENOMEM;
1277 }
1278 
1279 static void vring_free_split(struct vring_virtqueue_split *vring_split,
1280 			     struct virtio_device *vdev,
1281 			     union virtio_map map)
1282 {
1283 	vring_free_queue(vdev, vring_split->queue_size_in_bytes,
1284 			 vring_split->vring.desc,
1285 			 vring_split->queue_dma_addr,
1286 			 map);
1287 
1288 	kfree(vring_split->desc_state);
1289 	kfree(vring_split->desc_extra);
1290 }
1291 
1292 static int vring_alloc_queue_split(struct vring_virtqueue_split *vring_split,
1293 				   struct virtio_device *vdev,
1294 				   u32 num,
1295 				   unsigned int vring_align,
1296 				   bool may_reduce_num,
1297 				   union virtio_map map)
1298 {
1299 	void *queue = NULL;
1300 	dma_addr_t dma_addr;
1301 
1302 	/* We assume num is a power of 2. */
1303 	if (!is_power_of_2(num)) {
1304 		dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
1305 		return -EINVAL;
1306 	}
1307 
1308 	/* TODO: allocate each queue chunk individually */
1309 	for (; num && vring_size(num, vring_align) > PAGE_SIZE; num /= 2) {
1310 		queue = vring_alloc_queue(vdev, vring_size(num, vring_align),
1311 					  &dma_addr,
1312 					  GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
1313 					  map);
1314 		if (queue)
1315 			break;
1316 		if (!may_reduce_num)
1317 			return -ENOMEM;
1318 	}
1319 
1320 	if (!num)
1321 		return -ENOMEM;
1322 
1323 	if (!queue) {
1324 		/* Try to get a single page. You are my only hope! */
1325 		queue = vring_alloc_queue(vdev, vring_size(num, vring_align),
1326 					  &dma_addr, GFP_KERNEL | __GFP_ZERO,
1327 					  map);
1328 	}
1329 	if (!queue)
1330 		return -ENOMEM;
1331 
1332 	vring_init(&vring_split->vring, num, queue, vring_align);
1333 
1334 	vring_split->queue_dma_addr = dma_addr;
1335 	vring_split->queue_size_in_bytes = vring_size(num, vring_align);
1336 
1337 	vring_split->vring_align = vring_align;
1338 	vring_split->may_reduce_num = may_reduce_num;
1339 
1340 	return 0;
1341 }
1342 
1343 static const struct virtqueue_ops split_ops;
1344 
1345 static struct virtqueue *__vring_new_virtqueue_split(unsigned int index,
1346 					       struct vring_virtqueue_split *vring_split,
1347 					       struct virtio_device *vdev,
1348 					       bool weak_barriers,
1349 					       bool context,
1350 					       bool (*notify)(struct virtqueue *),
1351 					       void (*callback)(struct virtqueue *),
1352 					       const char *name,
1353 					       union virtio_map map)
1354 {
1355 	struct vring_virtqueue *vq;
1356 	int err;
1357 
1358 	vq = kmalloc_obj(*vq);
1359 	if (!vq)
1360 		return NULL;
1361 
1362 	vq->vq.callback = callback;
1363 	vq->vq.vdev = vdev;
1364 	vq->vq.name = name;
1365 	vq->vq.index = index;
1366 	vq->vq.reset = false;
1367 	vq->we_own_ring = false;
1368 	vq->notify = notify;
1369 	vq->weak_barriers = weak_barriers;
1370 #ifdef CONFIG_VIRTIO_HARDEN_NOTIFICATION
1371 	vq->broken = true;
1372 #else
1373 	vq->broken = false;
1374 #endif
1375 	vq->map = map;
1376 	vq->use_map_api = vring_use_map_api(vdev);
1377 
1378 	vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC) &&
1379 		!context;
1380 	vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
1381 	vq->layout = virtio_has_feature(vdev, VIRTIO_F_IN_ORDER) ?
1382 		     VQ_LAYOUT_SPLIT_IN_ORDER : VQ_LAYOUT_SPLIT;
1383 
1384 	if (virtio_has_feature(vdev, VIRTIO_F_ORDER_PLATFORM))
1385 		vq->weak_barriers = false;
1386 
1387 	err = vring_alloc_state_extra_split(vring_split);
1388 	if (err) {
1389 		kfree(vq);
1390 		return NULL;
1391 	}
1392 
1393 	virtqueue_vring_init_split(vring_split, vq);
1394 
1395 	virtqueue_init(vq, vring_split->vring.num);
1396 	virtqueue_vring_attach_split(vq, vring_split);
1397 
1398 	spin_lock(&vdev->vqs_list_lock);
1399 	list_add_tail(&vq->vq.list, &vdev->vqs);
1400 	spin_unlock(&vdev->vqs_list_lock);
1401 	return &vq->vq;
1402 }
1403 
1404 static struct virtqueue *vring_create_virtqueue_split(
1405 	unsigned int index,
1406 	unsigned int num,
1407 	unsigned int vring_align,
1408 	struct virtio_device *vdev,
1409 	bool weak_barriers,
1410 	bool may_reduce_num,
1411 	bool context,
1412 	bool (*notify)(struct virtqueue *),
1413 	void (*callback)(struct virtqueue *),
1414 	const char *name,
1415 	union virtio_map map)
1416 {
1417 	struct vring_virtqueue_split vring_split = {};
1418 	struct virtqueue *vq;
1419 	int err;
1420 
1421 	err = vring_alloc_queue_split(&vring_split, vdev, num, vring_align,
1422 				      may_reduce_num, map);
1423 	if (err)
1424 		return ERR_PTR(err);
1425 
1426 	vq = __vring_new_virtqueue_split(index, &vring_split, vdev, weak_barriers,
1427 				   context, notify, callback, name, map);
1428 	if (!vq) {
1429 		vring_free_split(&vring_split, vdev, map);
1430 		return ERR_PTR(-ENOMEM);
1431 	}
1432 
1433 	to_vvq(vq)->we_own_ring = true;
1434 
1435 	return vq;
1436 }
1437 
1438 static int virtqueue_resize_split(struct vring_virtqueue *vq, u32 num)
1439 {
1440 	struct vring_virtqueue_split vring_split = {};
1441 	struct virtio_device *vdev = vq->vq.vdev;
1442 	int err;
1443 
1444 	err = vring_alloc_queue_split(&vring_split, vdev, num,
1445 				      vq->split.vring_align,
1446 				      vq->split.may_reduce_num,
1447 				      vq->map);
1448 	if (err)
1449 		goto err;
1450 
1451 	err = vring_alloc_state_extra_split(&vring_split);
1452 	if (err)
1453 		goto err_state_extra;
1454 
1455 	vring_free(&vq->vq);
1456 
1457 	virtqueue_vring_init_split(&vring_split, vq);
1458 
1459 	virtqueue_init(vq, vring_split.vring.num);
1460 	virtqueue_vring_attach_split(vq, &vring_split);
1461 
1462 	return 0;
1463 
1464 err_state_extra:
1465 	vring_free_split(&vring_split, vdev, vq->map);
1466 err:
1467 	virtqueue_reset_split(vq);
1468 	return -ENOMEM;
1469 }
1470 
1471 
1472 /*
1473  * Packed ring specific functions - *_packed().
1474  */
1475 static bool packed_used_wrap_counter(u16 last_used_idx)
1476 {
1477 	return !!(last_used_idx & (1 << VRING_PACKED_EVENT_F_WRAP_CTR));
1478 }
1479 
1480 static u16 packed_last_used(u16 last_used_idx)
1481 {
1482 	return last_used_idx & ~(-(1 << VRING_PACKED_EVENT_F_WRAP_CTR));
1483 }
1484 
1485 static void vring_unmap_extra_packed(const struct vring_virtqueue *vq,
1486 				     const struct vring_desc_extra *extra)
1487 {
1488 	u16 flags;
1489 
1490 	flags = extra->flags;
1491 
1492 	if (flags & VRING_DESC_F_INDIRECT) {
1493 		if (!vq->use_map_api)
1494 			return;
1495 	} else if (!vring_need_unmap_buffer(vq, extra))
1496 		return;
1497 
1498 	virtqueue_unmap_page_attrs(&vq->vq,
1499 				   extra->addr, extra->len,
1500 				   (flags & VRING_DESC_F_WRITE) ?
1501 				   DMA_FROM_DEVICE : DMA_TO_DEVICE,
1502 				   0);
1503 }
1504 
1505 static struct vring_packed_desc *alloc_indirect_packed(unsigned int total_sg,
1506 						       gfp_t gfp)
1507 {
1508 	struct vring_desc_extra *extra;
1509 	struct vring_packed_desc *desc;
1510 	int i, size;
1511 
1512 	/*
1513 	 * We require lowmem mappings for the descriptors because
1514 	 * otherwise virt_to_phys will give us bogus addresses in the
1515 	 * virtqueue.
1516 	 */
1517 	gfp &= ~__GFP_HIGHMEM;
1518 
1519 	size = (sizeof(*desc) + sizeof(*extra)) * total_sg;
1520 
1521 	desc = kmalloc(size, gfp);
1522 	if (!desc)
1523 		return NULL;
1524 
1525 	extra = (struct vring_desc_extra *)&desc[total_sg];
1526 
1527 	for (i = 0; i < total_sg; i++)
1528 		extra[i].next = i + 1;
1529 
1530 	return desc;
1531 }
1532 
1533 static int virtqueue_add_indirect_packed(struct vring_virtqueue *vq,
1534 					 struct scatterlist *sgs[],
1535 					 unsigned int total_sg,
1536 					 unsigned int out_sgs,
1537 					 unsigned int in_sgs,
1538 					 void *data,
1539 					 bool premapped,
1540 					 gfp_t gfp,
1541 					 u16 id,
1542 					 unsigned long attr)
1543 {
1544 	struct vring_desc_extra *extra;
1545 	struct vring_packed_desc *desc;
1546 	struct scatterlist *sg;
1547 	unsigned int i, n, err_idx, len, total_in_len = 0;
1548 	u16 head;
1549 	dma_addr_t addr;
1550 
1551 	head = vq->packed.next_avail_idx;
1552 	desc = alloc_indirect_packed(total_sg, gfp);
1553 	if (!desc)
1554 		return -ENOMEM;
1555 
1556 	extra = (struct vring_desc_extra *)&desc[total_sg];
1557 
1558 	if (unlikely(vq->vq.num_free < 1)) {
1559 		pr_debug("Can't add buf len 1 - avail = 0\n");
1560 		kfree(desc);
1561 		END_USE(vq);
1562 		return -ENOSPC;
1563 	}
1564 
1565 	i = 0;
1566 
1567 	for (n = 0; n < out_sgs + in_sgs; n++) {
1568 		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
1569 			if (vring_map_one_sg(vq, sg, n < out_sgs ?
1570 					     DMA_TO_DEVICE : DMA_FROM_DEVICE,
1571 					     &addr, &len, premapped, attr))
1572 				goto unmap_release;
1573 
1574 			desc[i].flags = cpu_to_le16(n < out_sgs ?
1575 						0 : VRING_DESC_F_WRITE);
1576 			desc[i].addr = cpu_to_le64(addr);
1577 			desc[i].len = cpu_to_le32(len);
1578 			/* The id field is unused in indirect descriptors but
1579 			 * must be initialized to prevent leaking kernel heap
1580 			 * memory to the device through the DMA-mapped table.
1581 			 */
1582 			desc[i].id = 0;
1583 
1584 			if (unlikely(vq->use_map_api)) {
1585 				extra[i].addr = premapped ? DMA_MAPPING_ERROR : addr;
1586 				extra[i].len = len;
1587 				extra[i].flags = n < out_sgs ?  0 : VRING_DESC_F_WRITE;
1588 			}
1589 
1590 			if (n >= out_sgs)
1591 				total_in_len += len;
1592 			i++;
1593 		}
1594 	}
1595 
1596 	/* Now that the indirect table is filled in, map it. */
1597 	addr = vring_map_single(vq, desc,
1598 			total_sg * sizeof(struct vring_packed_desc),
1599 			DMA_TO_DEVICE);
1600 	if (vring_mapping_error(vq, addr))
1601 		goto unmap_release;
1602 
1603 	vq->packed.vring.desc[head].addr = cpu_to_le64(addr);
1604 	vq->packed.vring.desc[head].len = cpu_to_le32(total_sg *
1605 				sizeof(struct vring_packed_desc));
1606 	vq->packed.vring.desc[head].id = cpu_to_le16(id);
1607 
1608 	if (vq->use_map_api) {
1609 		vq->packed.desc_extra[id].addr = addr;
1610 		vq->packed.desc_extra[id].len = total_sg *
1611 				sizeof(struct vring_packed_desc);
1612 		vq->packed.desc_extra[id].flags = VRING_DESC_F_INDIRECT |
1613 						  vq->packed.avail_used_flags;
1614 	}
1615 
1616 	/*
1617 	 * A driver MUST NOT make the first descriptor in the list
1618 	 * available before all subsequent descriptors comprising
1619 	 * the list are made available.
1620 	 */
1621 	virtio_wmb(vq->weak_barriers);
1622 	vq->packed.vring.desc[head].flags = cpu_to_le16(VRING_DESC_F_INDIRECT |
1623 						vq->packed.avail_used_flags);
1624 
1625 	/* We're using some buffers from the free list. */
1626 	vq->vq.num_free -= 1;
1627 
1628 	/* Update free pointer */
1629 	n = head + 1;
1630 	if (n >= vq->packed.vring.num) {
1631 		n = 0;
1632 		vq->packed.avail_wrap_counter ^= 1;
1633 		vq->packed.avail_used_flags ^=
1634 				1 << VRING_PACKED_DESC_F_AVAIL |
1635 				1 << VRING_PACKED_DESC_F_USED;
1636 	}
1637 	vq->packed.next_avail_idx = n;
1638 	if (!virtqueue_is_in_order(vq))
1639 		vq->free_head = vq->packed.desc_extra[id].next;
1640 
1641 	/* Store token and indirect buffer state. */
1642 	vq->packed.desc_state[id].num = 1;
1643 	vq->packed.desc_state[id].data = data;
1644 	vq->packed.desc_state[id].indir_desc = desc;
1645 	vq->packed.desc_state[id].last = id;
1646 	vq->packed.desc_state[id].total_in_len = total_in_len;
1647 
1648 	vq->num_added += 1;
1649 
1650 	pr_debug("Added buffer head %i to %p\n", head, vq);
1651 	END_USE(vq);
1652 
1653 	return 0;
1654 
1655 unmap_release:
1656 	err_idx = i;
1657 
1658 	for (i = 0; i < err_idx; i++)
1659 		vring_unmap_extra_packed(vq, &extra[i]);
1660 
1661 	kfree(desc);
1662 
1663 	END_USE(vq);
1664 	return -ENOMEM;
1665 }
1666 
1667 static inline int virtqueue_add_packed(struct vring_virtqueue *vq,
1668 				       struct scatterlist *sgs[],
1669 				       unsigned int total_sg,
1670 				       unsigned int out_sgs,
1671 				       unsigned int in_sgs,
1672 				       void *data,
1673 				       void *ctx,
1674 				       bool premapped,
1675 				       gfp_t gfp,
1676 				       unsigned long attr)
1677 {
1678 	struct vring_packed_desc *desc;
1679 	struct scatterlist *sg;
1680 	unsigned int i, n, c, descs_used, err_idx, len;
1681 	__le16 head_flags, flags;
1682 	u16 head, id, prev, curr, avail_used_flags, unpub_flags;
1683 	int err;
1684 
1685 	START_USE(vq);
1686 
1687 	BUG_ON(data == NULL);
1688 	BUG_ON(ctx && vq->indirect);
1689 
1690 	if (unlikely(vq->broken)) {
1691 		END_USE(vq);
1692 		return -EIO;
1693 	}
1694 
1695 	LAST_ADD_TIME_UPDATE(vq);
1696 
1697 	BUG_ON(total_sg == 0);
1698 
1699 	if (virtqueue_use_indirect(vq, total_sg)) {
1700 		id = vq->free_head;
1701 		BUG_ON(id == vq->packed.vring.num);
1702 		err = virtqueue_add_indirect_packed(vq, sgs, total_sg, out_sgs,
1703 						    in_sgs, data, premapped, gfp,
1704 						    id, attr);
1705 		if (err != -ENOMEM) {
1706 			END_USE(vq);
1707 			return err;
1708 		}
1709 
1710 		/* fall back on direct */
1711 	}
1712 
1713 	head = vq->packed.next_avail_idx;
1714 	avail_used_flags = vq->packed.avail_used_flags;
1715 
1716 	WARN_ON_ONCE(total_sg > vq->packed.vring.num && !vq->indirect);
1717 
1718 	desc = vq->packed.vring.desc;
1719 	i = head;
1720 	descs_used = total_sg;
1721 
1722 	if (unlikely(vq->vq.num_free < descs_used)) {
1723 		pr_debug("Can't add buf len %i - avail = %i\n",
1724 			 descs_used, vq->vq.num_free);
1725 		END_USE(vq);
1726 		return -ENOSPC;
1727 	}
1728 
1729 	id = vq->free_head;
1730 	BUG_ON(id == vq->packed.vring.num);
1731 
1732 	curr = id;
1733 	c = 0;
1734 	for (n = 0; n < out_sgs + in_sgs; n++) {
1735 		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
1736 			dma_addr_t addr;
1737 
1738 			if (vring_map_one_sg(vq, sg, n < out_sgs ?
1739 					     DMA_TO_DEVICE : DMA_FROM_DEVICE,
1740 					     &addr, &len, premapped, attr))
1741 				goto unmap_release;
1742 
1743 			flags = cpu_to_le16(vq->packed.avail_used_flags |
1744 				    (++c == total_sg ? 0 : VRING_DESC_F_NEXT) |
1745 				    (n < out_sgs ? 0 : VRING_DESC_F_WRITE));
1746 			if (i == head)
1747 				head_flags = flags;
1748 			else
1749 				desc[i].flags = flags;
1750 
1751 			desc[i].addr = cpu_to_le64(addr);
1752 			desc[i].len = cpu_to_le32(len);
1753 			desc[i].id = cpu_to_le16(id);
1754 
1755 			if (unlikely(vq->use_map_api)) {
1756 				vq->packed.desc_extra[curr].addr = premapped ?
1757 					DMA_MAPPING_ERROR : addr;
1758 				vq->packed.desc_extra[curr].len = len;
1759 				vq->packed.desc_extra[curr].flags =
1760 					le16_to_cpu(flags);
1761 			}
1762 			prev = curr;
1763 			curr = vq->packed.desc_extra[curr].next;
1764 
1765 			if ((unlikely(++i >= vq->packed.vring.num))) {
1766 				i = 0;
1767 				vq->packed.avail_used_flags ^=
1768 					1 << VRING_PACKED_DESC_F_AVAIL |
1769 					1 << VRING_PACKED_DESC_F_USED;
1770 			}
1771 		}
1772 	}
1773 
1774 	if (i <= head)
1775 		vq->packed.avail_wrap_counter ^= 1;
1776 
1777 	/* We're using some buffers from the free list. */
1778 	vq->vq.num_free -= descs_used;
1779 
1780 	/* Update free pointer */
1781 	vq->packed.next_avail_idx = i;
1782 	vq->free_head = curr;
1783 
1784 	/* Store token. */
1785 	vq->packed.desc_state[id].num = descs_used;
1786 	vq->packed.desc_state[id].data = data;
1787 	vq->packed.desc_state[id].indir_desc = ctx;
1788 	vq->packed.desc_state[id].last = prev;
1789 
1790 	/*
1791 	 * A driver MUST NOT make the first descriptor in the list
1792 	 * available before all subsequent descriptors comprising
1793 	 * the list are made available.
1794 	 */
1795 	virtio_wmb(vq->weak_barriers);
1796 	vq->packed.vring.desc[head].flags = head_flags;
1797 	vq->num_added += descs_used;
1798 
1799 	pr_debug("Added buffer head %i to %p\n", head, vq);
1800 	END_USE(vq);
1801 
1802 	return 0;
1803 
1804 unmap_release:
1805 	err_idx = i;
1806 	i = head;
1807 	curr = vq->free_head;
1808 
1809 	vq->packed.avail_used_flags = avail_used_flags;
1810 	unpub_flags = avail_used_flags ^ (1 << VRING_PACKED_DESC_F_AVAIL |
1811 					  1 << VRING_PACKED_DESC_F_USED);
1812 
1813 	for (n = 0; n < total_sg; n++) {
1814 		if (i == err_idx)
1815 			break;
1816 		/*
1817 		 * The mapping loop made every descriptor but the head
1818 		 * available. Stamp the previous wrap counter's AVAIL and USED
1819 		 * bits on those, so that a later and shorter chain at this head
1820 		 * does not leave one of them available beyond its own last
1821 		 * descriptor. Marking them used instead would hand
1822 		 * is_used_desc_packed() a completion we never made.
1823 		 */
1824 		if (i != head)
1825 			desc[i].flags = cpu_to_le16(unpub_flags);
1826 		vring_unmap_extra_packed(vq, &vq->packed.desc_extra[curr]);
1827 		curr = vq->packed.desc_extra[curr].next;
1828 		i++;
1829 		if (i >= vq->packed.vring.num) {
1830 			i = 0;
1831 			unpub_flags ^= 1 << VRING_PACKED_DESC_F_AVAIL |
1832 				       1 << VRING_PACKED_DESC_F_USED;
1833 		}
1834 	}
1835 
1836 	END_USE(vq);
1837 	return -EIO;
1838 }
1839 
1840 static inline int virtqueue_add_packed_in_order(struct vring_virtqueue *vq,
1841 						struct scatterlist *sgs[],
1842 						unsigned int total_sg,
1843 						unsigned int out_sgs,
1844 						unsigned int in_sgs,
1845 						void *data,
1846 						void *ctx,
1847 						bool premapped,
1848 						gfp_t gfp,
1849 						unsigned long attr)
1850 {
1851 	struct vring_packed_desc *desc;
1852 	struct scatterlist *sg;
1853 	unsigned int i, n, sg_count, err_idx, total_in_len = 0;
1854 	__le16 head_flags, flags;
1855 	u16 head, avail_used_flags, unpub_flags;
1856 	bool avail_wrap_counter;
1857 	int err;
1858 
1859 	START_USE(vq);
1860 
1861 	BUG_ON(data == NULL);
1862 	BUG_ON(ctx && vq->indirect);
1863 
1864 	if (unlikely(vq->broken)) {
1865 		END_USE(vq);
1866 		return -EIO;
1867 	}
1868 
1869 	LAST_ADD_TIME_UPDATE(vq);
1870 
1871 	BUG_ON(total_sg == 0);
1872 
1873 	if (virtqueue_use_indirect(vq, total_sg)) {
1874 		err = virtqueue_add_indirect_packed(vq, sgs, total_sg, out_sgs,
1875 						    in_sgs, data, premapped, gfp,
1876 						    vq->packed.next_avail_idx,
1877 						    attr);
1878 		if (err != -ENOMEM) {
1879 			END_USE(vq);
1880 			return err;
1881 		}
1882 
1883 		/* fall back on direct */
1884 	}
1885 
1886 	head = vq->packed.next_avail_idx;
1887 	avail_used_flags = vq->packed.avail_used_flags;
1888 	avail_wrap_counter = vq->packed.avail_wrap_counter;
1889 
1890 	WARN_ON_ONCE(total_sg > vq->packed.vring.num && !vq->indirect);
1891 
1892 	desc = vq->packed.vring.desc;
1893 	i = head;
1894 
1895 	if (unlikely(vq->vq.num_free < total_sg)) {
1896 		pr_debug("Can't add buf len %i - avail = %i\n",
1897 			 total_sg, vq->vq.num_free);
1898 		END_USE(vq);
1899 		return -ENOSPC;
1900 	}
1901 
1902 	sg_count = 0;
1903 	for (n = 0; n < out_sgs + in_sgs; n++) {
1904 		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
1905 			dma_addr_t addr;
1906 			u32 len;
1907 
1908 			flags = 0;
1909 			if (++sg_count != total_sg)
1910 				flags |= cpu_to_le16(VRING_DESC_F_NEXT);
1911 			if (n >= out_sgs)
1912 				flags |= cpu_to_le16(VRING_DESC_F_WRITE);
1913 
1914 			if (vring_map_one_sg(vq, sg, n < out_sgs ?
1915 					     DMA_TO_DEVICE : DMA_FROM_DEVICE,
1916 					     &addr, &len, premapped, attr))
1917 				goto unmap_release;
1918 
1919 			flags |= cpu_to_le16(vq->packed.avail_used_flags);
1920 
1921 			if (i == head)
1922 				head_flags = flags;
1923 			else
1924 				desc[i].flags = flags;
1925 
1926 			desc[i].addr = cpu_to_le64(addr);
1927 			desc[i].len = cpu_to_le32(len);
1928 			desc[i].id = cpu_to_le16(head);
1929 
1930 			if (unlikely(vq->use_map_api)) {
1931 				vq->packed.desc_extra[i].addr = premapped ?
1932 				      DMA_MAPPING_ERROR : addr;
1933 				vq->packed.desc_extra[i].len = len;
1934 				vq->packed.desc_extra[i].flags =
1935 					le16_to_cpu(flags);
1936 			}
1937 
1938 			if ((unlikely(++i >= vq->packed.vring.num))) {
1939 				i = 0;
1940 				vq->packed.avail_used_flags ^=
1941 					1 << VRING_PACKED_DESC_F_AVAIL |
1942 					1 << VRING_PACKED_DESC_F_USED;
1943 				vq->packed.avail_wrap_counter ^= 1;
1944 			}
1945 
1946 			if (n >= out_sgs)
1947 				total_in_len += len;
1948 		}
1949 	}
1950 
1951 	/* We're using some buffers from the free list. */
1952 	vq->vq.num_free -= total_sg;
1953 
1954 	/* Update free pointer */
1955 	vq->packed.next_avail_idx = i;
1956 
1957 	/* Store token. */
1958 	vq->packed.desc_state[head].num = total_sg;
1959 	vq->packed.desc_state[head].data = data;
1960 	vq->packed.desc_state[head].indir_desc = ctx;
1961 	vq->packed.desc_state[head].total_in_len = total_in_len;
1962 
1963 	/*
1964 	 * A driver MUST NOT make the first descriptor in the list
1965 	 * available before all subsequent descriptors comprising
1966 	 * the list are made available.
1967 	 */
1968 	virtio_wmb(vq->weak_barriers);
1969 	vq->packed.vring.desc[head].flags = head_flags;
1970 	vq->num_added += total_sg;
1971 
1972 	pr_debug("Added buffer head %i to %p\n", head, vq);
1973 	END_USE(vq);
1974 
1975 	return 0;
1976 
1977 unmap_release:
1978 	err_idx = i;
1979 	i = head;
1980 	vq->packed.avail_used_flags = avail_used_flags;
1981 	vq->packed.avail_wrap_counter = avail_wrap_counter;
1982 	unpub_flags = avail_used_flags ^ (1 << VRING_PACKED_DESC_F_AVAIL |
1983 					  1 << VRING_PACKED_DESC_F_USED);
1984 
1985 	for (n = 0; n < total_sg; n++) {
1986 		if (i == err_idx)
1987 			break;
1988 		/*
1989 		 * The mapping loop made every descriptor but the head
1990 		 * available. Stamp the previous wrap counter's AVAIL and USED
1991 		 * bits on those, so that a later and shorter chain at this head
1992 		 * does not leave one of them available beyond its own last
1993 		 * descriptor. Marking them used instead would hand
1994 		 * is_used_desc_packed() a completion we never made.
1995 		 */
1996 		if (i != head)
1997 			desc[i].flags = cpu_to_le16(unpub_flags);
1998 		vring_unmap_extra_packed(vq, &vq->packed.desc_extra[i]);
1999 		i++;
2000 		if (i >= vq->packed.vring.num) {
2001 			i = 0;
2002 			unpub_flags ^= 1 << VRING_PACKED_DESC_F_AVAIL |
2003 				       1 << VRING_PACKED_DESC_F_USED;
2004 		}
2005 	}
2006 
2007 	END_USE(vq);
2008 	return -EIO;
2009 }
2010 
2011 static bool virtqueue_kick_prepare_packed(struct vring_virtqueue *vq)
2012 {
2013 	u16 new, old, off_wrap, flags, wrap_counter, event_idx;
2014 	bool needs_kick;
2015 	union {
2016 		struct {
2017 			__le16 off_wrap;
2018 			__le16 flags;
2019 		};
2020 		u32 u32;
2021 	} snapshot;
2022 
2023 	START_USE(vq);
2024 
2025 	/*
2026 	 * We need to expose the new flags value before checking notification
2027 	 * suppressions.
2028 	 */
2029 	virtio_mb(vq->weak_barriers);
2030 
2031 	old = vq->packed.next_avail_idx - vq->num_added;
2032 	new = vq->packed.next_avail_idx;
2033 	vq->num_added = 0;
2034 
2035 	snapshot.u32 = *(u32 *)vq->packed.vring.device;
2036 	flags = le16_to_cpu(snapshot.flags);
2037 
2038 	LAST_ADD_TIME_CHECK(vq);
2039 	LAST_ADD_TIME_INVALID(vq);
2040 
2041 	if (flags != VRING_PACKED_EVENT_FLAG_DESC) {
2042 		needs_kick = (flags != VRING_PACKED_EVENT_FLAG_DISABLE);
2043 		goto out;
2044 	}
2045 
2046 	off_wrap = le16_to_cpu(snapshot.off_wrap);
2047 
2048 	wrap_counter = off_wrap >> VRING_PACKED_EVENT_F_WRAP_CTR;
2049 	event_idx = off_wrap & ~(1 << VRING_PACKED_EVENT_F_WRAP_CTR);
2050 	if (wrap_counter != vq->packed.avail_wrap_counter)
2051 		event_idx -= vq->packed.vring.num;
2052 
2053 	needs_kick = vring_need_event(event_idx, new, old);
2054 out:
2055 	END_USE(vq);
2056 	return needs_kick;
2057 }
2058 
2059 static void detach_buf_packed_in_order(struct vring_virtqueue *vq,
2060 				       unsigned int id, void **ctx)
2061 {
2062 	struct vring_desc_state_packed *state = NULL;
2063 	struct vring_packed_desc *desc;
2064 	unsigned int i, curr;
2065 
2066 	state = &vq->packed.desc_state[id];
2067 
2068 	/* Clear data ptr. */
2069 	state->data = NULL;
2070 
2071 	vq->vq.num_free += state->num;
2072 
2073 	if (unlikely(vq->use_map_api)) {
2074 		curr = id;
2075 		for (i = 0; i < state->num; i++) {
2076 			vring_unmap_extra_packed(vq,
2077 						 &vq->packed.desc_extra[curr]);
2078 			curr = vq->packed.desc_extra[curr].next;
2079 		}
2080 	}
2081 
2082 	if (vq->indirect) {
2083 		struct vring_desc_extra *extra;
2084 		u32 len, num;
2085 
2086 		/* Free the indirect table, if any, now that it's unmapped. */
2087 		desc = state->indir_desc;
2088 		if (!desc)
2089 			return;
2090 
2091 		if (vq->use_map_api) {
2092 			len = vq->packed.desc_extra[id].len;
2093 			num = len / sizeof(struct vring_packed_desc);
2094 
2095 			extra = (struct vring_desc_extra *)&desc[num];
2096 
2097 			for (i = 0; i < num; i++)
2098 				vring_unmap_extra_packed(vq, &extra[i]);
2099 		}
2100 		kfree(desc);
2101 		state->indir_desc = NULL;
2102 	} else if (ctx) {
2103 		*ctx = state->indir_desc;
2104 	}
2105 }
2106 
2107 static void detach_buf_packed(struct vring_virtqueue *vq,
2108 			      unsigned int id, void **ctx)
2109 {
2110 	struct vring_desc_state_packed *state = &vq->packed.desc_state[id];
2111 
2112 	vq->packed.desc_extra[state->last].next = vq->free_head;
2113 	vq->free_head = id;
2114 
2115 	detach_buf_packed_in_order(vq, id, ctx);
2116 }
2117 
2118 static inline bool is_used_desc_packed(const struct vring_virtqueue *vq,
2119 				       u16 idx, bool used_wrap_counter)
2120 {
2121 	u16 flags;
2122 	bool avail, used;
2123 
2124 	flags = vring_read_packed_desc_flags(vq, idx);
2125 	avail = !!(flags & (1 << VRING_PACKED_DESC_F_AVAIL));
2126 	used = !!(flags & (1 << VRING_PACKED_DESC_F_USED));
2127 
2128 	return avail == used && used == used_wrap_counter;
2129 }
2130 
2131 static bool virtqueue_poll_packed(const struct vring_virtqueue *vq,
2132 				  unsigned int off_wrap)
2133 {
2134 	bool wrap_counter;
2135 	u16 used_idx;
2136 
2137 	wrap_counter = off_wrap >> VRING_PACKED_EVENT_F_WRAP_CTR;
2138 	used_idx = off_wrap & ~(1 << VRING_PACKED_EVENT_F_WRAP_CTR);
2139 
2140 	return is_used_desc_packed(vq, used_idx, wrap_counter);
2141 }
2142 
2143 static bool more_used_packed(const struct vring_virtqueue *vq)
2144 {
2145 	return virtqueue_poll_packed(vq, READ_ONCE(vq->last_used_idx));
2146 }
2147 
2148 static void update_last_used_idx_packed(struct vring_virtqueue *vq,
2149 					u16 id, u16 last_used,
2150 					u16 used_wrap_counter)
2151 {
2152 	last_used += vq->packed.desc_state[id].num;
2153 	if (unlikely(last_used >= vq->packed.vring.num)) {
2154 		last_used -= vq->packed.vring.num;
2155 		used_wrap_counter ^= 1;
2156 	}
2157 
2158 	last_used = (last_used | (used_wrap_counter << VRING_PACKED_EVENT_F_WRAP_CTR));
2159 	WRITE_ONCE(vq->last_used_idx, last_used);
2160 
2161 	/*
2162 	 * If we expect an interrupt for the next entry, tell host
2163 	 * by writing event index and flush out the write before
2164 	 * the read in the next get_buf call.
2165 	 */
2166 	if (vq->packed.event_flags_shadow == VRING_PACKED_EVENT_FLAG_DESC)
2167 		virtio_store_mb(vq->weak_barriers,
2168 				&vq->packed.vring.driver->off_wrap,
2169 				cpu_to_le16(vq->last_used_idx));
2170 }
2171 
2172 static bool more_used_packed_in_order(const struct vring_virtqueue *vq)
2173 {
2174 	if (vq->batch_last.id != UINT_MAX)
2175 		return true;
2176 
2177 	return virtqueue_poll_packed(vq, READ_ONCE(vq->last_used_idx));
2178 }
2179 
2180 static void *virtqueue_get_buf_ctx_packed_in_order(struct vring_virtqueue *vq,
2181 						   unsigned int *len,
2182 						   void **ctx)
2183 {
2184 	unsigned int num = vq->packed.vring.num;
2185 	u16 last_used, last_used_idx;
2186 	bool used_wrap_counter;
2187 	void *ret;
2188 
2189 	START_USE(vq);
2190 
2191 	if (unlikely(vq->broken)) {
2192 		END_USE(vq);
2193 		return NULL;
2194 	}
2195 
2196 	last_used_idx = vq->last_used_idx;
2197 	used_wrap_counter = packed_used_wrap_counter(last_used_idx);
2198 	last_used = packed_last_used(last_used_idx);
2199 
2200 	if (vq->batch_last.id == UINT_MAX) {
2201 		if (!more_used_packed_in_order(vq)) {
2202 			pr_debug("No more buffers in queue\n");
2203 			END_USE(vq);
2204 			return NULL;
2205 		}
2206 		/* Only get used elements after they have been exposed by host. */
2207 		virtio_rmb(vq->weak_barriers);
2208 		vq->batch_last.id =
2209 			le16_to_cpu(vq->packed.vring.desc[last_used].id);
2210 		vq->batch_last.len =
2211 			le32_to_cpu(vq->packed.vring.desc[last_used].len);
2212 	}
2213 
2214 	if (vq->batch_last.id == last_used) {
2215 		vq->batch_last.id = UINT_MAX;
2216 		*len = vq->batch_last.len;
2217 	} else {
2218 		*len = vq->packed.desc_state[last_used].total_in_len;
2219 	}
2220 
2221 	if (unlikely(last_used >= num)) {
2222 		BAD_RING(vq, "id %u out of range\n", last_used);
2223 		return NULL;
2224 	}
2225 	if (unlikely(!vq->packed.desc_state[last_used].data)) {
2226 		BAD_RING(vq, "id %u is not a head!\n", last_used);
2227 		return NULL;
2228 	}
2229 
2230 	/* detach_buf_packed clears data, so grab it now. */
2231 	ret = vq->packed.desc_state[last_used].data;
2232 	detach_buf_packed_in_order(vq, last_used, ctx);
2233 
2234 	update_last_used_idx_packed(vq, last_used, last_used,
2235 				    used_wrap_counter);
2236 
2237 	LAST_ADD_TIME_INVALID(vq);
2238 
2239 	END_USE(vq);
2240 	return ret;
2241 }
2242 
2243 static void *virtqueue_get_buf_ctx_packed(struct vring_virtqueue *vq,
2244 					  unsigned int *len,
2245 					  void **ctx)
2246 {
2247 	unsigned int num = vq->packed.vring.num;
2248 	u16 last_used, id, last_used_idx;
2249 	bool used_wrap_counter;
2250 	void *ret;
2251 
2252 	START_USE(vq);
2253 
2254 	if (unlikely(vq->broken)) {
2255 		END_USE(vq);
2256 		return NULL;
2257 	}
2258 
2259 	if (!more_used_packed(vq)) {
2260 		pr_debug("No more buffers in queue\n");
2261 		END_USE(vq);
2262 		return NULL;
2263 	}
2264 
2265 	/* Only get used elements after they have been exposed by host. */
2266 	virtio_rmb(vq->weak_barriers);
2267 
2268 	last_used_idx = READ_ONCE(vq->last_used_idx);
2269 	used_wrap_counter = packed_used_wrap_counter(last_used_idx);
2270 	last_used = packed_last_used(last_used_idx);
2271 	id = vring_read_packed_desc_id(vq, last_used);
2272 	*len = vring_read_packed_desc_len(vq, last_used);
2273 
2274 	if (unlikely(id >= num)) {
2275 		BAD_RING(vq, "id %u out of range\n", id);
2276 		return NULL;
2277 	}
2278 	if (unlikely(!vq->packed.desc_state[id].data)) {
2279 		BAD_RING(vq, "id %u is not a head!\n", id);
2280 		return NULL;
2281 	}
2282 
2283 	/* detach_buf_packed clears data, so grab it now. */
2284 	ret = vq->packed.desc_state[id].data;
2285 	detach_buf_packed(vq, id, ctx);
2286 
2287 	update_last_used_idx_packed(vq, id, last_used, used_wrap_counter);
2288 
2289 	LAST_ADD_TIME_INVALID(vq);
2290 
2291 	END_USE(vq);
2292 	return ret;
2293 }
2294 
2295 static void virtqueue_disable_cb_packed(struct vring_virtqueue *vq)
2296 {
2297 	if (vq->packed.event_flags_shadow != VRING_PACKED_EVENT_FLAG_DISABLE) {
2298 		vq->packed.event_flags_shadow = VRING_PACKED_EVENT_FLAG_DISABLE;
2299 
2300 		/*
2301 		 * If device triggered an event already it won't trigger one again:
2302 		 * no need to disable.
2303 		 */
2304 		if (vq->event_triggered)
2305 			return;
2306 
2307 		vq->packed.vring.driver->flags =
2308 			cpu_to_le16(vq->packed.event_flags_shadow);
2309 	}
2310 }
2311 
2312 static unsigned int virtqueue_enable_cb_prepare_packed(struct vring_virtqueue *vq)
2313 {
2314 	START_USE(vq);
2315 
2316 	/*
2317 	 * We optimistically turn back on interrupts, then check if there was
2318 	 * more to do.
2319 	 */
2320 
2321 	if (vq->event) {
2322 		vq->packed.vring.driver->off_wrap =
2323 			cpu_to_le16(vq->last_used_idx);
2324 		/*
2325 		 * We need to update event offset and event wrap
2326 		 * counter first before updating event flags.
2327 		 */
2328 		virtio_wmb(vq->weak_barriers);
2329 	}
2330 
2331 	if (vq->packed.event_flags_shadow == VRING_PACKED_EVENT_FLAG_DISABLE) {
2332 		vq->packed.event_flags_shadow = vq->event ?
2333 				VRING_PACKED_EVENT_FLAG_DESC :
2334 				VRING_PACKED_EVENT_FLAG_ENABLE;
2335 		vq->packed.vring.driver->flags =
2336 				cpu_to_le16(vq->packed.event_flags_shadow);
2337 	}
2338 
2339 	END_USE(vq);
2340 	return vq->last_used_idx;
2341 }
2342 
2343 static bool virtqueue_enable_cb_delayed_packed(struct vring_virtqueue *vq)
2344 {
2345 	u16 used_idx, wrap_counter, last_used_idx;
2346 	u16 bufs;
2347 
2348 	START_USE(vq);
2349 
2350 	/*
2351 	 * We optimistically turn back on interrupts, then check if there was
2352 	 * more to do.
2353 	 */
2354 
2355 	if (vq->event) {
2356 		/* TODO: tune this threshold */
2357 		bufs = (vq->packed.vring.num - vq->vq.num_free) * 3 / 4;
2358 		last_used_idx = READ_ONCE(vq->last_used_idx);
2359 		wrap_counter = packed_used_wrap_counter(last_used_idx);
2360 
2361 		used_idx = packed_last_used(last_used_idx) + bufs;
2362 		if (used_idx >= vq->packed.vring.num) {
2363 			used_idx -= vq->packed.vring.num;
2364 			wrap_counter ^= 1;
2365 		}
2366 
2367 		vq->packed.vring.driver->off_wrap = cpu_to_le16(used_idx |
2368 			(wrap_counter << VRING_PACKED_EVENT_F_WRAP_CTR));
2369 
2370 		/*
2371 		 * We need to update event offset and event wrap
2372 		 * counter first before updating event flags.
2373 		 */
2374 		virtio_wmb(vq->weak_barriers);
2375 	}
2376 
2377 	if (vq->packed.event_flags_shadow == VRING_PACKED_EVENT_FLAG_DISABLE) {
2378 		vq->packed.event_flags_shadow = vq->event ?
2379 				VRING_PACKED_EVENT_FLAG_DESC :
2380 				VRING_PACKED_EVENT_FLAG_ENABLE;
2381 		vq->packed.vring.driver->flags =
2382 				cpu_to_le16(vq->packed.event_flags_shadow);
2383 	}
2384 
2385 	/*
2386 	 * We need to update event suppression structure first
2387 	 * before re-checking for more used buffers.
2388 	 */
2389 	virtio_mb(vq->weak_barriers);
2390 
2391 	last_used_idx = READ_ONCE(vq->last_used_idx);
2392 	wrap_counter = packed_used_wrap_counter(last_used_idx);
2393 	used_idx = packed_last_used(last_used_idx);
2394 	if (is_used_desc_packed(vq, used_idx, wrap_counter)) {
2395 		END_USE(vq);
2396 		return false;
2397 	}
2398 
2399 	END_USE(vq);
2400 	return true;
2401 }
2402 
2403 static void *virtqueue_detach_unused_buf_packed(struct vring_virtqueue *vq)
2404 {
2405 	unsigned int i;
2406 	void *buf;
2407 
2408 	START_USE(vq);
2409 
2410 	for (i = 0; i < vq->packed.vring.num; i++) {
2411 		if (!vq->packed.desc_state[i].data)
2412 			continue;
2413 		/* detach_buf clears data, so grab it now. */
2414 		buf = vq->packed.desc_state[i].data;
2415 		if (virtqueue_is_in_order(vq))
2416 			detach_buf_packed_in_order(vq, i, NULL);
2417 		else
2418 			detach_buf_packed(vq, i, NULL);
2419 		END_USE(vq);
2420 		return buf;
2421 	}
2422 	/* That should have freed everything. */
2423 	BUG_ON(vq->vq.num_free != vq->packed.vring.num);
2424 
2425 	END_USE(vq);
2426 	return NULL;
2427 }
2428 
2429 static struct vring_desc_extra *vring_alloc_desc_extra(unsigned int num)
2430 {
2431 	struct vring_desc_extra *desc_extra;
2432 	unsigned int i;
2433 
2434 	desc_extra = kmalloc_objs(struct vring_desc_extra, num);
2435 	if (!desc_extra)
2436 		return NULL;
2437 
2438 	memset(desc_extra, 0, num * sizeof(struct vring_desc_extra));
2439 
2440 	for (i = 0; i < num - 1; i++)
2441 		desc_extra[i].next = i + 1;
2442 
2443 	desc_extra[num - 1].next = 0;
2444 
2445 	return desc_extra;
2446 }
2447 
2448 static void vring_free_packed(struct vring_virtqueue_packed *vring_packed,
2449 			      struct virtio_device *vdev,
2450 			      union virtio_map map)
2451 {
2452 	if (vring_packed->vring.desc)
2453 		vring_free_queue(vdev, vring_packed->ring_size_in_bytes,
2454 				 vring_packed->vring.desc,
2455 				 vring_packed->ring_dma_addr,
2456 				 map);
2457 
2458 	if (vring_packed->vring.driver)
2459 		vring_free_queue(vdev, vring_packed->event_size_in_bytes,
2460 				 vring_packed->vring.driver,
2461 				 vring_packed->driver_event_dma_addr,
2462 				 map);
2463 
2464 	if (vring_packed->vring.device)
2465 		vring_free_queue(vdev, vring_packed->event_size_in_bytes,
2466 				 vring_packed->vring.device,
2467 				 vring_packed->device_event_dma_addr,
2468 				 map);
2469 
2470 	kfree(vring_packed->desc_state);
2471 	kfree(vring_packed->desc_extra);
2472 }
2473 
2474 static int vring_alloc_queue_packed(struct vring_virtqueue_packed *vring_packed,
2475 				    struct virtio_device *vdev,
2476 				    u32 num, union virtio_map map)
2477 {
2478 	struct vring_packed_desc *ring;
2479 	struct vring_packed_desc_event *driver, *device;
2480 	dma_addr_t ring_dma_addr, driver_event_dma_addr, device_event_dma_addr;
2481 	size_t ring_size_in_bytes, event_size_in_bytes;
2482 
2483 	ring_size_in_bytes = num * sizeof(struct vring_packed_desc);
2484 
2485 	ring = vring_alloc_queue(vdev, ring_size_in_bytes,
2486 				 &ring_dma_addr,
2487 				 GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
2488 				 map);
2489 	if (!ring)
2490 		goto err;
2491 
2492 	vring_packed->vring.desc         = ring;
2493 	vring_packed->ring_dma_addr      = ring_dma_addr;
2494 	vring_packed->ring_size_in_bytes = ring_size_in_bytes;
2495 
2496 	event_size_in_bytes = sizeof(struct vring_packed_desc_event);
2497 
2498 	driver = vring_alloc_queue(vdev, event_size_in_bytes,
2499 				   &driver_event_dma_addr,
2500 				   GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
2501 				   map);
2502 	if (!driver)
2503 		goto err;
2504 
2505 	vring_packed->vring.driver          = driver;
2506 	vring_packed->event_size_in_bytes   = event_size_in_bytes;
2507 	vring_packed->driver_event_dma_addr = driver_event_dma_addr;
2508 
2509 	device = vring_alloc_queue(vdev, event_size_in_bytes,
2510 				   &device_event_dma_addr,
2511 				   GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
2512 				   map);
2513 	if (!device)
2514 		goto err;
2515 
2516 	vring_packed->vring.device          = device;
2517 	vring_packed->device_event_dma_addr = device_event_dma_addr;
2518 
2519 	vring_packed->vring.num = num;
2520 
2521 	return 0;
2522 
2523 err:
2524 	vring_free_packed(vring_packed, vdev, map);
2525 	return -ENOMEM;
2526 }
2527 
2528 static int vring_alloc_state_extra_packed(struct vring_virtqueue_packed *vring_packed)
2529 {
2530 	struct vring_desc_state_packed *state;
2531 	struct vring_desc_extra *extra;
2532 	u32 num = vring_packed->vring.num;
2533 
2534 	state = kmalloc_objs(struct vring_desc_state_packed, num);
2535 	if (!state)
2536 		goto err_desc_state;
2537 
2538 	memset(state, 0, num * sizeof(struct vring_desc_state_packed));
2539 
2540 	extra = vring_alloc_desc_extra(num);
2541 	if (!extra)
2542 		goto err_desc_extra;
2543 
2544 	vring_packed->desc_state = state;
2545 	vring_packed->desc_extra = extra;
2546 
2547 	return 0;
2548 
2549 err_desc_extra:
2550 	kfree(state);
2551 err_desc_state:
2552 	return -ENOMEM;
2553 }
2554 
2555 static void virtqueue_vring_init_packed(struct vring_virtqueue_packed *vring_packed,
2556 					bool callback)
2557 {
2558 	vring_packed->next_avail_idx = 0;
2559 	vring_packed->avail_wrap_counter = 1;
2560 	vring_packed->event_flags_shadow = 0;
2561 	vring_packed->avail_used_flags = 1 << VRING_PACKED_DESC_F_AVAIL;
2562 
2563 	/* No callback?  Tell other side not to bother us. */
2564 	if (!callback) {
2565 		vring_packed->event_flags_shadow = VRING_PACKED_EVENT_FLAG_DISABLE;
2566 		vring_packed->vring.driver->flags =
2567 			cpu_to_le16(vring_packed->event_flags_shadow);
2568 	}
2569 }
2570 
2571 static void virtqueue_vring_attach_packed(struct vring_virtqueue *vq,
2572 					  struct vring_virtqueue_packed *vring_packed)
2573 {
2574 	vq->packed = *vring_packed;
2575 
2576 	if (virtqueue_is_in_order(vq)) {
2577 		vq->batch_last.id = UINT_MAX;
2578 	} else {
2579 		/*
2580 		 * Put everything in free lists. Note that
2581 		 * next_avail_idx is sufficient with IN_ORDER so
2582 		 * free_head is unused.
2583 		 */
2584 		vq->free_head = 0;
2585 	}
2586 }
2587 static void virtqueue_reset_packed(struct vring_virtqueue *vq)
2588 {
2589 	memset(vq->packed.vring.device, 0, vq->packed.event_size_in_bytes);
2590 	memset(vq->packed.vring.driver, 0, vq->packed.event_size_in_bytes);
2591 
2592 	/* we need to reset the desc.flags. For more, see is_used_desc_packed() */
2593 	memset(vq->packed.vring.desc, 0, vq->packed.ring_size_in_bytes);
2594 	virtqueue_init(vq, vq->packed.vring.num);
2595 	virtqueue_vring_init_packed(&vq->packed, !!vq->vq.callback);
2596 }
2597 
2598 static const struct virtqueue_ops packed_ops;
2599 
2600 static struct virtqueue *__vring_new_virtqueue_packed(unsigned int index,
2601 					       struct vring_virtqueue_packed *vring_packed,
2602 					       struct virtio_device *vdev,
2603 					       bool weak_barriers,
2604 					       bool context,
2605 					       bool (*notify)(struct virtqueue *),
2606 					       void (*callback)(struct virtqueue *),
2607 					       const char *name,
2608 					       union virtio_map map)
2609 {
2610 	struct vring_virtqueue *vq;
2611 	int err;
2612 
2613 	vq = kmalloc_obj(*vq);
2614 	if (!vq)
2615 		return NULL;
2616 
2617 	vq->vq.callback = callback;
2618 	vq->vq.vdev = vdev;
2619 	vq->vq.name = name;
2620 	vq->vq.index = index;
2621 	vq->vq.reset = false;
2622 	vq->we_own_ring = false;
2623 	vq->notify = notify;
2624 	vq->weak_barriers = weak_barriers;
2625 #ifdef CONFIG_VIRTIO_HARDEN_NOTIFICATION
2626 	vq->broken = true;
2627 #else
2628 	vq->broken = false;
2629 #endif
2630 	vq->map = map;
2631 	vq->use_map_api = vring_use_map_api(vdev);
2632 
2633 	vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC) &&
2634 		!context;
2635 	vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
2636 	vq->layout = virtio_has_feature(vdev, VIRTIO_F_IN_ORDER) ?
2637 		     VQ_LAYOUT_PACKED_IN_ORDER : VQ_LAYOUT_PACKED;
2638 
2639 	if (virtio_has_feature(vdev, VIRTIO_F_ORDER_PLATFORM))
2640 		vq->weak_barriers = false;
2641 
2642 	err = vring_alloc_state_extra_packed(vring_packed);
2643 	if (err) {
2644 		kfree(vq);
2645 		return NULL;
2646 	}
2647 
2648 	virtqueue_vring_init_packed(vring_packed, !!callback);
2649 
2650 	virtqueue_init(vq, vring_packed->vring.num);
2651 	virtqueue_vring_attach_packed(vq, vring_packed);
2652 
2653 	spin_lock(&vdev->vqs_list_lock);
2654 	list_add_tail(&vq->vq.list, &vdev->vqs);
2655 	spin_unlock(&vdev->vqs_list_lock);
2656 	return &vq->vq;
2657 }
2658 
2659 static struct virtqueue *vring_create_virtqueue_packed(
2660 	unsigned int index,
2661 	unsigned int num,
2662 	unsigned int vring_align,
2663 	struct virtio_device *vdev,
2664 	bool weak_barriers,
2665 	bool may_reduce_num,
2666 	bool context,
2667 	bool (*notify)(struct virtqueue *),
2668 	void (*callback)(struct virtqueue *),
2669 	const char *name,
2670 	union virtio_map map)
2671 {
2672 	struct vring_virtqueue_packed vring_packed = {};
2673 	struct virtqueue *vq;
2674 	int err;
2675 
2676 	err = vring_alloc_queue_packed(&vring_packed, vdev, num, map);
2677 	if (err)
2678 		return ERR_PTR(err);
2679 
2680 	vq = __vring_new_virtqueue_packed(index, &vring_packed, vdev, weak_barriers,
2681 					context, notify, callback, name, map);
2682 	if (!vq) {
2683 		vring_free_packed(&vring_packed, vdev, map);
2684 		return ERR_PTR(-ENOMEM);
2685 	}
2686 
2687 	to_vvq(vq)->we_own_ring = true;
2688 
2689 	return vq;
2690 }
2691 
2692 static int virtqueue_resize_packed(struct vring_virtqueue *vq, u32 num)
2693 {
2694 	struct vring_virtqueue_packed vring_packed = {};
2695 	struct virtio_device *vdev = vq->vq.vdev;
2696 	int err;
2697 
2698 	if (vring_alloc_queue_packed(&vring_packed, vdev, num, vq->map))
2699 		goto err_ring;
2700 
2701 	err = vring_alloc_state_extra_packed(&vring_packed);
2702 	if (err)
2703 		goto err_state_extra;
2704 
2705 	vring_free(&vq->vq);
2706 
2707 	virtqueue_vring_init_packed(&vring_packed, !!vq->vq.callback);
2708 
2709 	virtqueue_init(vq, vring_packed.vring.num);
2710 	virtqueue_vring_attach_packed(vq, &vring_packed);
2711 
2712 	return 0;
2713 
2714 err_state_extra:
2715 	vring_free_packed(&vring_packed, vdev, vq->map);
2716 err_ring:
2717 	virtqueue_reset_packed(vq);
2718 	return -ENOMEM;
2719 }
2720 
2721 static const struct virtqueue_ops split_ops = {
2722 	.add = virtqueue_add_split,
2723 	.get = virtqueue_get_buf_ctx_split,
2724 	.kick_prepare = virtqueue_kick_prepare_split,
2725 	.disable_cb = virtqueue_disable_cb_split,
2726 	.enable_cb_delayed = virtqueue_enable_cb_delayed_split,
2727 	.enable_cb_prepare = virtqueue_enable_cb_prepare_split,
2728 	.poll = virtqueue_poll_split,
2729 	.detach_unused_buf = virtqueue_detach_unused_buf_split,
2730 	.more_used = more_used_split,
2731 	.resize = virtqueue_resize_split,
2732 	.reset = virtqueue_reset_split,
2733 };
2734 
2735 static const struct virtqueue_ops packed_ops = {
2736 	.add = virtqueue_add_packed,
2737 	.get = virtqueue_get_buf_ctx_packed,
2738 	.kick_prepare = virtqueue_kick_prepare_packed,
2739 	.disable_cb = virtqueue_disable_cb_packed,
2740 	.enable_cb_delayed = virtqueue_enable_cb_delayed_packed,
2741 	.enable_cb_prepare = virtqueue_enable_cb_prepare_packed,
2742 	.poll = virtqueue_poll_packed,
2743 	.detach_unused_buf = virtqueue_detach_unused_buf_packed,
2744 	.more_used = more_used_packed,
2745 	.resize = virtqueue_resize_packed,
2746 	.reset = virtqueue_reset_packed,
2747 };
2748 
2749 static const struct virtqueue_ops split_in_order_ops = {
2750 	.add = virtqueue_add_split,
2751 	.get = virtqueue_get_buf_ctx_split_in_order,
2752 	.kick_prepare = virtqueue_kick_prepare_split,
2753 	.disable_cb = virtqueue_disable_cb_split,
2754 	.enable_cb_delayed = virtqueue_enable_cb_delayed_split,
2755 	.enable_cb_prepare = virtqueue_enable_cb_prepare_split,
2756 	.poll = virtqueue_poll_split,
2757 	.detach_unused_buf = virtqueue_detach_unused_buf_split,
2758 	.more_used = more_used_split_in_order,
2759 	.resize = virtqueue_resize_split,
2760 	.reset = virtqueue_reset_split,
2761 };
2762 
2763 static const struct virtqueue_ops packed_in_order_ops = {
2764 	.add = virtqueue_add_packed_in_order,
2765 	.get = virtqueue_get_buf_ctx_packed_in_order,
2766 	.kick_prepare = virtqueue_kick_prepare_packed,
2767 	.disable_cb = virtqueue_disable_cb_packed,
2768 	.enable_cb_delayed = virtqueue_enable_cb_delayed_packed,
2769 	.enable_cb_prepare = virtqueue_enable_cb_prepare_packed,
2770 	.poll = virtqueue_poll_packed,
2771 	.detach_unused_buf = virtqueue_detach_unused_buf_packed,
2772 	.more_used = more_used_packed_in_order,
2773 	.resize = virtqueue_resize_packed,
2774 	.reset = virtqueue_reset_packed,
2775 };
2776 
2777 static int virtqueue_disable_and_recycle(struct virtqueue *_vq,
2778 					 void (*recycle)(struct virtqueue *vq, void *buf))
2779 {
2780 	struct vring_virtqueue *vq = to_vvq(_vq);
2781 	struct virtio_device *vdev = vq->vq.vdev;
2782 	void *buf;
2783 	int err;
2784 
2785 	if (!vq->we_own_ring)
2786 		return -EPERM;
2787 
2788 	if (!vdev->config->disable_vq_and_reset)
2789 		return -ENOENT;
2790 
2791 	if (!vdev->config->enable_vq_after_reset)
2792 		return -ENOENT;
2793 
2794 	err = vdev->config->disable_vq_and_reset(_vq);
2795 	if (err)
2796 		return err;
2797 
2798 	while ((buf = virtqueue_detach_unused_buf(_vq)) != NULL)
2799 		recycle(_vq, buf);
2800 
2801 	return 0;
2802 }
2803 
2804 static int virtqueue_enable_after_reset(struct virtqueue *_vq)
2805 {
2806 	struct vring_virtqueue *vq = to_vvq(_vq);
2807 	struct virtio_device *vdev = vq->vq.vdev;
2808 
2809 	if (vdev->config->enable_vq_after_reset(_vq))
2810 		return -EBUSY;
2811 
2812 	return 0;
2813 }
2814 
2815 /*
2816  * Generic functions and exported symbols.
2817  */
2818 
2819 #define VIRTQUEUE_CALL(vq, op, ...)					\
2820 	({								\
2821 	typeof(vq) __VIRTQUEUE_CALL_vq = (vq);				\
2822 	typeof(split_ops.op(__VIRTQUEUE_CALL_vq, ##__VA_ARGS__)) ret;	\
2823 									\
2824 	switch (__VIRTQUEUE_CALL_vq->layout) {				\
2825 	case VQ_LAYOUT_SPLIT:						\
2826 		ret = split_ops.op(__VIRTQUEUE_CALL_vq, ##__VA_ARGS__);	\
2827 		break;							\
2828 	case VQ_LAYOUT_PACKED:						\
2829 		ret = packed_ops.op(__VIRTQUEUE_CALL_vq, ##__VA_ARGS__);\
2830 		break;							\
2831 	case VQ_LAYOUT_SPLIT_IN_ORDER:					\
2832 		ret = split_in_order_ops.op(vq, ##__VA_ARGS__);		\
2833 		break;							\
2834 	case VQ_LAYOUT_PACKED_IN_ORDER:					\
2835 		ret = packed_in_order_ops.op(vq, ##__VA_ARGS__);	\
2836 		break;							\
2837 	default:							\
2838 		BUG();							\
2839 		break;							\
2840 	}								\
2841 	ret;								\
2842 })
2843 
2844 #define VOID_VIRTQUEUE_CALL(vq, op, ...)				\
2845 	({								\
2846 	typeof(vq) __VIRTQUEUE_CALL_vq = (vq);				\
2847 									\
2848 	switch (__VIRTQUEUE_CALL_vq->layout) {				\
2849 	case VQ_LAYOUT_SPLIT:						\
2850 		split_ops.op(__VIRTQUEUE_CALL_vq, ##__VA_ARGS__);	\
2851 		break;							\
2852 	case VQ_LAYOUT_PACKED:						\
2853 		packed_ops.op(__VIRTQUEUE_CALL_vq, ##__VA_ARGS__);	\
2854 		break;							\
2855 	case VQ_LAYOUT_SPLIT_IN_ORDER:					\
2856 		split_in_order_ops.op(vq, ##__VA_ARGS__);		\
2857 		break;							\
2858 	case VQ_LAYOUT_PACKED_IN_ORDER:					\
2859 		packed_in_order_ops.op(vq, ##__VA_ARGS__);		\
2860 		break;							\
2861 	default:							\
2862 		BUG();							\
2863 		break;							\
2864 	}								\
2865 })
2866 
2867 static inline int virtqueue_add(struct virtqueue *_vq,
2868 				struct scatterlist *sgs[],
2869 				unsigned int total_sg,
2870 				unsigned int out_sgs,
2871 				unsigned int in_sgs,
2872 				void *data,
2873 				void *ctx,
2874 				bool premapped,
2875 				gfp_t gfp,
2876 				unsigned long attr)
2877 {
2878 	struct vring_virtqueue *vq = to_vvq(_vq);
2879 
2880 	return VIRTQUEUE_CALL(vq, add, sgs, total_sg,
2881 			      out_sgs, in_sgs, data,
2882 			      ctx, premapped, gfp, attr);
2883 }
2884 
2885 /**
2886  * virtqueue_add_sgs - expose buffers to other end
2887  * @_vq: the struct virtqueue we're talking about.
2888  * @sgs: array of terminated scatterlists.
2889  * @out_sgs: the number of scatterlists readable by other side
2890  * @in_sgs: the number of scatterlists which are writable (after readable ones)
2891  * @data: the token identifying the buffer.
2892  * @gfp: how to do memory allocations (if necessary).
2893  *
2894  * Caller must ensure we don't call this with other virtqueue operations
2895  * at the same time (except where noted).
2896  *
2897  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
2898  *
2899  * NB: ENOSPC is a special code that is only returned on an attempt to add a
2900  * buffer to a full VQ. It indicates that some buffers are outstanding and that
2901  * the operation can be retried after some buffers have been used.
2902  */
2903 int virtqueue_add_sgs(struct virtqueue *_vq,
2904 		      struct scatterlist *sgs[],
2905 		      unsigned int out_sgs,
2906 		      unsigned int in_sgs,
2907 		      void *data,
2908 		      gfp_t gfp)
2909 {
2910 	unsigned int i, total_sg = 0;
2911 
2912 	/* Count them first. */
2913 	for (i = 0; i < out_sgs + in_sgs; i++) {
2914 		struct scatterlist *sg;
2915 
2916 		for (sg = sgs[i]; sg; sg = sg_next(sg))
2917 			total_sg++;
2918 	}
2919 	return virtqueue_add(_vq, sgs, total_sg, out_sgs, in_sgs,
2920 			     data, NULL, false, gfp, 0);
2921 }
2922 EXPORT_SYMBOL_GPL(virtqueue_add_sgs);
2923 
2924 /**
2925  * virtqueue_add_outbuf - expose output buffers to other end
2926  * @vq: the struct virtqueue we're talking about.
2927  * @sg: scatterlist (must be well-formed and terminated!)
2928  * @num: the number of entries in @sg readable by other side
2929  * @data: the token identifying the buffer.
2930  * @gfp: how to do memory allocations (if necessary).
2931  *
2932  * Caller must ensure we don't call this with other virtqueue operations
2933  * at the same time (except where noted).
2934  *
2935  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
2936  */
2937 int virtqueue_add_outbuf(struct virtqueue *vq,
2938 			 struct scatterlist *sg, unsigned int num,
2939 			 void *data,
2940 			 gfp_t gfp)
2941 {
2942 	return virtqueue_add(vq, &sg, num, 1, 0, data, NULL, false, gfp, 0);
2943 }
2944 EXPORT_SYMBOL_GPL(virtqueue_add_outbuf);
2945 
2946 /**
2947  * virtqueue_add_outbuf_premapped - expose output buffers to other end
2948  * @vq: the struct virtqueue we're talking about.
2949  * @sg: scatterlist (must be well-formed and terminated!)
2950  * @num: the number of entries in @sg readable by other side
2951  * @data: the token identifying the buffer.
2952  * @gfp: how to do memory allocations (if necessary).
2953  *
2954  * Caller must ensure we don't call this with other virtqueue operations
2955  * at the same time (except where noted).
2956  *
2957  * Return:
2958  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
2959  */
2960 int virtqueue_add_outbuf_premapped(struct virtqueue *vq,
2961 				   struct scatterlist *sg, unsigned int num,
2962 				   void *data,
2963 				   gfp_t gfp)
2964 {
2965 	return virtqueue_add(vq, &sg, num, 1, 0, data, NULL, true, gfp, 0);
2966 }
2967 EXPORT_SYMBOL_GPL(virtqueue_add_outbuf_premapped);
2968 
2969 /**
2970  * virtqueue_add_inbuf - expose input buffers to other end
2971  * @vq: the struct virtqueue we're talking about.
2972  * @sg: scatterlist (must be well-formed and terminated!)
2973  * @num: the number of entries in @sg writable by other side
2974  * @data: the token identifying the buffer.
2975  * @gfp: how to do memory allocations (if necessary).
2976  *
2977  * Caller must ensure we don't call this with other virtqueue operations
2978  * at the same time (except where noted).
2979  *
2980  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
2981  */
2982 int virtqueue_add_inbuf(struct virtqueue *vq,
2983 			struct scatterlist *sg, unsigned int num,
2984 			void *data,
2985 			gfp_t gfp)
2986 {
2987 	return virtqueue_add(vq, &sg, num, 0, 1, data, NULL, false, gfp, 0);
2988 }
2989 EXPORT_SYMBOL_GPL(virtqueue_add_inbuf);
2990 
2991 /**
2992  * virtqueue_add_inbuf_cache_clean - expose input buffers with cache clean
2993  * @vq: the struct virtqueue we're talking about.
2994  * @sg: scatterlist (must be well-formed and terminated!)
2995  * @num: the number of entries in @sg writable by other side
2996  * @data: the token identifying the buffer.
2997  * @gfp: how to do memory allocations (if necessary).
2998  *
2999  * Same as virtqueue_add_inbuf but passes DMA_ATTR_DEBUGGING_IGNORE_CACHELINES
3000  * to indicate that the CPU will not dirty any cacheline overlapping this buffer
3001  * while it is available, and to suppress overlapping cacheline warnings in DMA
3002  * debug builds.
3003  *
3004  * Caller must ensure we don't call this with other virtqueue operations
3005  * at the same time (except where noted).
3006  *
3007  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
3008  */
3009 int virtqueue_add_inbuf_cache_clean(struct virtqueue *vq,
3010 				    struct scatterlist *sg, unsigned int num,
3011 				    void *data,
3012 				    gfp_t gfp)
3013 {
3014 	return virtqueue_add(vq, &sg, num, 0, 1, data, NULL, false, gfp,
3015 			     DMA_ATTR_DEBUGGING_IGNORE_CACHELINES);
3016 }
3017 EXPORT_SYMBOL_GPL(virtqueue_add_inbuf_cache_clean);
3018 
3019 /**
3020  * virtqueue_add_inbuf_ctx - expose input buffers to other end
3021  * @vq: the struct virtqueue we're talking about.
3022  * @sg: scatterlist (must be well-formed and terminated!)
3023  * @num: the number of entries in @sg writable by other side
3024  * @data: the token identifying the buffer.
3025  * @ctx: extra context for the token
3026  * @gfp: how to do memory allocations (if necessary).
3027  *
3028  * Caller must ensure we don't call this with other virtqueue operations
3029  * at the same time (except where noted).
3030  *
3031  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
3032  */
3033 int virtqueue_add_inbuf_ctx(struct virtqueue *vq,
3034 			struct scatterlist *sg, unsigned int num,
3035 			void *data,
3036 			void *ctx,
3037 			gfp_t gfp)
3038 {
3039 	return virtqueue_add(vq, &sg, num, 0, 1, data, ctx, false, gfp, 0);
3040 }
3041 EXPORT_SYMBOL_GPL(virtqueue_add_inbuf_ctx);
3042 
3043 /**
3044  * virtqueue_add_inbuf_premapped - expose input buffers to other end
3045  * @vq: the struct virtqueue we're talking about.
3046  * @sg: scatterlist (must be well-formed and terminated!)
3047  * @num: the number of entries in @sg writable by other side
3048  * @data: the token identifying the buffer.
3049  * @ctx: extra context for the token
3050  * @gfp: how to do memory allocations (if necessary).
3051  *
3052  * Caller must ensure we don't call this with other virtqueue operations
3053  * at the same time (except where noted).
3054  *
3055  * Return:
3056  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
3057  */
3058 int virtqueue_add_inbuf_premapped(struct virtqueue *vq,
3059 				  struct scatterlist *sg, unsigned int num,
3060 				  void *data,
3061 				  void *ctx,
3062 				  gfp_t gfp)
3063 {
3064 	return virtqueue_add(vq, &sg, num, 0, 1, data, ctx, true, gfp, 0);
3065 }
3066 EXPORT_SYMBOL_GPL(virtqueue_add_inbuf_premapped);
3067 
3068 /**
3069  * virtqueue_dma_dev - get the dma dev
3070  * @_vq: the struct virtqueue we're talking about.
3071  *
3072  * Returns the dma dev. That can been used for dma api.
3073  */
3074 struct device *virtqueue_dma_dev(struct virtqueue *_vq)
3075 {
3076 	struct vring_virtqueue *vq = to_vvq(_vq);
3077 
3078 	if (vq->use_map_api && !_vq->vdev->map)
3079 		return vq->map.dma_dev;
3080 	else
3081 		return NULL;
3082 }
3083 EXPORT_SYMBOL_GPL(virtqueue_dma_dev);
3084 
3085 /**
3086  * virtqueue_kick_prepare - first half of split virtqueue_kick call.
3087  * @_vq: the struct virtqueue
3088  *
3089  * Instead of virtqueue_kick(), you can do:
3090  *	if (virtqueue_kick_prepare(vq))
3091  *		virtqueue_notify(vq);
3092  *
3093  * This is sometimes useful because the virtqueue_kick_prepare() needs
3094  * to be serialized, but the actual virtqueue_notify() call does not.
3095  */
3096 bool virtqueue_kick_prepare(struct virtqueue *_vq)
3097 {
3098 	struct vring_virtqueue *vq = to_vvq(_vq);
3099 
3100 	return VIRTQUEUE_CALL(vq, kick_prepare);
3101 }
3102 EXPORT_SYMBOL_GPL(virtqueue_kick_prepare);
3103 
3104 /**
3105  * virtqueue_notify - second half of split virtqueue_kick call.
3106  * @_vq: the struct virtqueue
3107  *
3108  * This does not need to be serialized.
3109  *
3110  * Returns false if host notify failed or queue is broken, otherwise true.
3111  */
3112 bool virtqueue_notify(struct virtqueue *_vq)
3113 {
3114 	struct vring_virtqueue *vq = to_vvq(_vq);
3115 
3116 	if (unlikely(vq->broken))
3117 		return false;
3118 
3119 	/* Prod other side to tell it about changes. */
3120 	if (!vq->notify(_vq)) {
3121 		vq->broken = true;
3122 		return false;
3123 	}
3124 	return true;
3125 }
3126 EXPORT_SYMBOL_GPL(virtqueue_notify);
3127 
3128 /**
3129  * virtqueue_kick - update after add_buf
3130  * @vq: the struct virtqueue
3131  *
3132  * After one or more virtqueue_add_* calls, invoke this to kick
3133  * the other side.
3134  *
3135  * Caller must ensure we don't call this with other virtqueue
3136  * operations at the same time (except where noted).
3137  *
3138  * Returns false if kick failed, otherwise true.
3139  */
3140 bool virtqueue_kick(struct virtqueue *vq)
3141 {
3142 	if (virtqueue_kick_prepare(vq))
3143 		return virtqueue_notify(vq);
3144 	return true;
3145 }
3146 EXPORT_SYMBOL_GPL(virtqueue_kick);
3147 
3148 /**
3149  * virtqueue_get_buf_ctx - get the next used buffer
3150  * @_vq: the struct virtqueue we're talking about.
3151  * @len: the length written into the buffer
3152  * @ctx: extra context for the token
3153  *
3154  * If the device wrote data into the buffer, @len will be set to the
3155  * amount written.  This means you don't need to clear the buffer
3156  * beforehand to ensure there's no data leakage in the case of short
3157  * writes.
3158  *
3159  * Caller must ensure we don't call this with other virtqueue
3160  * operations at the same time (except where noted).
3161  *
3162  * Returns NULL if there are no used buffers, or the "data" token
3163  * handed to virtqueue_add_*().
3164  */
3165 void *virtqueue_get_buf_ctx(struct virtqueue *_vq, unsigned int *len,
3166 			    void **ctx)
3167 {
3168 	struct vring_virtqueue *vq = to_vvq(_vq);
3169 
3170 	return VIRTQUEUE_CALL(vq, get, len, ctx);
3171 }
3172 EXPORT_SYMBOL_GPL(virtqueue_get_buf_ctx);
3173 
3174 void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
3175 {
3176 	return virtqueue_get_buf_ctx(_vq, len, NULL);
3177 }
3178 EXPORT_SYMBOL_GPL(virtqueue_get_buf);
3179 /**
3180  * virtqueue_disable_cb - disable callbacks
3181  * @_vq: the struct virtqueue we're talking about.
3182  *
3183  * Note that this is not necessarily synchronous, hence unreliable and only
3184  * useful as an optimization.
3185  *
3186  * Unlike other operations, this need not be serialized.
3187  */
3188 void virtqueue_disable_cb(struct virtqueue *_vq)
3189 {
3190 	struct vring_virtqueue *vq = to_vvq(_vq);
3191 
3192 	VOID_VIRTQUEUE_CALL(vq, disable_cb);
3193 }
3194 EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
3195 
3196 /**
3197  * virtqueue_enable_cb_prepare - restart callbacks after disable_cb
3198  * @_vq: the struct virtqueue we're talking about.
3199  *
3200  * This re-enables callbacks; it returns current queue state
3201  * in an opaque unsigned value. This value should be later tested by
3202  * virtqueue_poll, to detect a possible race between the driver checking for
3203  * more work, and enabling callbacks.
3204  *
3205  * Caller must ensure we don't call this with other virtqueue
3206  * operations at the same time (except where noted).
3207  */
3208 unsigned int virtqueue_enable_cb_prepare(struct virtqueue *_vq)
3209 {
3210 	struct vring_virtqueue *vq = to_vvq(_vq);
3211 
3212 	if (vq->event_triggered)
3213 		vq->event_triggered = false;
3214 
3215 	return VIRTQUEUE_CALL(vq, enable_cb_prepare);
3216 }
3217 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);
3218 
3219 /**
3220  * virtqueue_poll - query pending used buffers
3221  * @_vq: the struct virtqueue we're talking about.
3222  * @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
3223  *
3224  * Returns "true" if there are pending used buffers in the queue.
3225  *
3226  * This does not need to be serialized.
3227  */
3228 bool virtqueue_poll(struct virtqueue *_vq, unsigned int last_used_idx)
3229 {
3230 	struct vring_virtqueue *vq = to_vvq(_vq);
3231 
3232 	if (unlikely(vq->broken))
3233 		return false;
3234 
3235 	virtio_mb(vq->weak_barriers);
3236 
3237 	return VIRTQUEUE_CALL(vq, poll, last_used_idx);
3238 }
3239 EXPORT_SYMBOL_GPL(virtqueue_poll);
3240 
3241 /**
3242  * virtqueue_enable_cb - restart callbacks after disable_cb.
3243  * @_vq: the struct virtqueue we're talking about.
3244  *
3245  * This re-enables callbacks; it returns "false" if there are pending
3246  * buffers in the queue, to detect a possible race between the driver
3247  * checking for more work, and enabling callbacks.
3248  *
3249  * Caller must ensure we don't call this with other virtqueue
3250  * operations at the same time (except where noted).
3251  */
3252 bool virtqueue_enable_cb(struct virtqueue *_vq)
3253 {
3254 	unsigned int last_used_idx = virtqueue_enable_cb_prepare(_vq);
3255 
3256 	return !virtqueue_poll(_vq, last_used_idx);
3257 }
3258 EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
3259 
3260 /**
3261  * virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
3262  * @_vq: the struct virtqueue we're talking about.
3263  *
3264  * This re-enables callbacks but hints to the other side to delay
3265  * interrupts until most of the available buffers have been processed;
3266  * it returns "false" if there are many pending buffers in the queue,
3267  * to detect a possible race between the driver checking for more work,
3268  * and enabling callbacks.
3269  *
3270  * Caller must ensure we don't call this with other virtqueue
3271  * operations at the same time (except where noted).
3272  */
3273 bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
3274 {
3275 	struct vring_virtqueue *vq = to_vvq(_vq);
3276 
3277 	/*
3278 	 * When the device is broken there is no point in polling used->idx,
3279 	 * the backend will never update it. Return true to let callers
3280 	 * exit their cleanup loops instead of spinning forever.
3281 	 */
3282 	if (unlikely(vq->broken))
3283 		return true;
3284 
3285 	if (vq->event_triggered)
3286 		data_race(vq->event_triggered = false);
3287 
3288 	return VIRTQUEUE_CALL(vq, enable_cb_delayed);
3289 }
3290 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
3291 
3292 /**
3293  * virtqueue_detach_unused_buf - detach first unused buffer
3294  * @_vq: the struct virtqueue we're talking about.
3295  *
3296  * Returns NULL or the "data" token handed to virtqueue_add_*().
3297  * This is not valid on an active queue; it is useful for device
3298  * shutdown or the reset queue.
3299  */
3300 void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
3301 {
3302 	struct vring_virtqueue *vq = to_vvq(_vq);
3303 
3304 	return VIRTQUEUE_CALL(vq, detach_unused_buf);
3305 }
3306 EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
3307 
3308 static inline bool more_used(const struct vring_virtqueue *vq)
3309 {
3310 	return VIRTQUEUE_CALL(vq, more_used);
3311 }
3312 
3313 /**
3314  * vring_interrupt - notify a virtqueue on an interrupt
3315  * @irq: the IRQ number (ignored)
3316  * @_vq: the struct virtqueue to notify
3317  *
3318  * Calls the callback function of @_vq to process the virtqueue
3319  * notification.
3320  */
3321 irqreturn_t vring_interrupt(int irq, void *_vq)
3322 {
3323 	struct vring_virtqueue *vq = to_vvq(_vq);
3324 
3325 	if (!more_used(vq)) {
3326 		pr_debug("virtqueue interrupt with no work for %p\n", vq);
3327 		return IRQ_NONE;
3328 	}
3329 
3330 	if (unlikely(vq->broken)) {
3331 #ifdef CONFIG_VIRTIO_HARDEN_NOTIFICATION
3332 		dev_warn_once(&vq->vq.vdev->dev,
3333 			      "virtio vring IRQ raised before DRIVER_OK");
3334 		return IRQ_NONE;
3335 #else
3336 		return IRQ_HANDLED;
3337 #endif
3338 	}
3339 
3340 	/* Just a hint for performance: so it's ok that this can be racy! */
3341 	if (vq->event)
3342 		data_race(vq->event_triggered = true);
3343 
3344 	pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
3345 	if (vq->vq.callback)
3346 		vq->vq.callback(&vq->vq);
3347 
3348 	return IRQ_HANDLED;
3349 }
3350 EXPORT_SYMBOL_GPL(vring_interrupt);
3351 
3352 struct virtqueue *vring_create_virtqueue(
3353 	unsigned int index,
3354 	unsigned int num,
3355 	unsigned int vring_align,
3356 	struct virtio_device *vdev,
3357 	bool weak_barriers,
3358 	bool may_reduce_num,
3359 	bool context,
3360 	bool (*notify)(struct virtqueue *),
3361 	void (*callback)(struct virtqueue *),
3362 	const char *name)
3363 {
3364 	union virtio_map map = {.dma_dev = vdev->dev.parent};
3365 
3366 	if (virtio_has_feature(vdev, VIRTIO_F_RING_PACKED))
3367 		return vring_create_virtqueue_packed(index, num, vring_align,
3368 				vdev, weak_barriers, may_reduce_num,
3369 				context, notify, callback, name, map);
3370 
3371 	return vring_create_virtqueue_split(index, num, vring_align,
3372 			vdev, weak_barriers, may_reduce_num,
3373 			context, notify, callback, name, map);
3374 }
3375 EXPORT_SYMBOL_GPL(vring_create_virtqueue);
3376 
3377 struct virtqueue *vring_create_virtqueue_map(
3378 	unsigned int index,
3379 	unsigned int num,
3380 	unsigned int vring_align,
3381 	struct virtio_device *vdev,
3382 	bool weak_barriers,
3383 	bool may_reduce_num,
3384 	bool context,
3385 	bool (*notify)(struct virtqueue *),
3386 	void (*callback)(struct virtqueue *),
3387 	const char *name,
3388 	union virtio_map map)
3389 {
3390 
3391 	if (virtio_has_feature(vdev, VIRTIO_F_RING_PACKED))
3392 		return vring_create_virtqueue_packed(index, num, vring_align,
3393 				vdev, weak_barriers, may_reduce_num,
3394 				context, notify, callback, name, map);
3395 
3396 	return vring_create_virtqueue_split(index, num, vring_align,
3397 			vdev, weak_barriers, may_reduce_num,
3398 			context, notify, callback, name, map);
3399 }
3400 EXPORT_SYMBOL_GPL(vring_create_virtqueue_map);
3401 
3402 /**
3403  * virtqueue_resize - resize the vring of vq
3404  * @_vq: the struct virtqueue we're talking about.
3405  * @num: new ring num
3406  * @recycle: callback to recycle unused buffers
3407  * @recycle_done: callback to be invoked when recycle for all unused buffers done
3408  *
3409  * When it is really necessary to create a new vring, it will set the current vq
3410  * into the reset state. Then call the passed callback to recycle the buffer
3411  * that is no longer used. Only after the new vring is successfully created, the
3412  * old vring will be released.
3413  *
3414  * Caller must ensure we don't call this with other virtqueue operations
3415  * at the same time (except where noted).
3416  *
3417  * Returns zero or a negative error.
3418  * 0: success.
3419  * -ENOMEM: Failed to allocate a new ring, fall back to the original ring size.
3420  *  vq can still work normally
3421  * -EBUSY: Failed to sync with device, vq may not work properly
3422  * -ENOENT: Transport or device not supported
3423  * -E2BIG/-EINVAL: num error
3424  * -EPERM: Operation not permitted
3425  *
3426  */
3427 int virtqueue_resize(struct virtqueue *_vq, u32 num,
3428 		     void (*recycle)(struct virtqueue *vq, void *buf),
3429 		     void (*recycle_done)(struct virtqueue *vq))
3430 {
3431 	struct vring_virtqueue *vq = to_vvq(_vq);
3432 	int err, err_reset;
3433 
3434 	if (num > vq->vq.num_max)
3435 		return -E2BIG;
3436 
3437 	if (!num)
3438 		return -EINVAL;
3439 
3440 	if (virtqueue_get_vring_size(_vq) == num)
3441 		return 0;
3442 
3443 	err = virtqueue_disable_and_recycle(_vq, recycle);
3444 	if (err)
3445 		return err;
3446 	if (recycle_done)
3447 		recycle_done(_vq);
3448 
3449 	err = VIRTQUEUE_CALL(vq, resize, num);
3450 
3451 	err_reset = virtqueue_enable_after_reset(_vq);
3452 	if (err_reset)
3453 		return err_reset;
3454 
3455 	return err;
3456 }
3457 EXPORT_SYMBOL_GPL(virtqueue_resize);
3458 
3459 /**
3460  * virtqueue_reset - detach and recycle all unused buffers
3461  * @_vq: the struct virtqueue we're talking about.
3462  * @recycle: callback to recycle unused buffers
3463  * @recycle_done: callback to be invoked when recycle for all unused buffers done
3464  *
3465  * Caller must ensure we don't call this with other virtqueue operations
3466  * at the same time (except where noted).
3467  *
3468  * Returns zero or a negative error.
3469  * 0: success.
3470  * -EBUSY: Failed to sync with device, vq may not work properly
3471  * -ENOENT: Transport or device not supported
3472  * -EPERM: Operation not permitted
3473  */
3474 int virtqueue_reset(struct virtqueue *_vq,
3475 		    void (*recycle)(struct virtqueue *vq, void *buf),
3476 		    void (*recycle_done)(struct virtqueue *vq))
3477 {
3478 	struct vring_virtqueue *vq = to_vvq(_vq);
3479 	int err;
3480 
3481 	err = virtqueue_disable_and_recycle(_vq, recycle);
3482 	if (err)
3483 		return err;
3484 	if (recycle_done)
3485 		recycle_done(_vq);
3486 
3487 	VOID_VIRTQUEUE_CALL(vq, reset);
3488 
3489 	return virtqueue_enable_after_reset(_vq);
3490 }
3491 EXPORT_SYMBOL_GPL(virtqueue_reset);
3492 
3493 struct virtqueue *vring_new_virtqueue(unsigned int index,
3494 				      unsigned int num,
3495 				      unsigned int vring_align,
3496 				      struct virtio_device *vdev,
3497 				      bool weak_barriers,
3498 				      bool context,
3499 				      void *pages,
3500 				      bool (*notify)(struct virtqueue *vq),
3501 				      void (*callback)(struct virtqueue *vq),
3502 				      const char *name)
3503 {
3504 	struct vring_virtqueue_split vring_split = {};
3505 	union virtio_map map = {.dma_dev = vdev->dev.parent};
3506 
3507 	if (virtio_has_feature(vdev, VIRTIO_F_RING_PACKED)) {
3508 		struct vring_virtqueue_packed vring_packed = {};
3509 
3510 		vring_packed.vring.num = num;
3511 		vring_packed.vring.desc = pages;
3512 		return __vring_new_virtqueue_packed(index, &vring_packed,
3513 						    vdev, weak_barriers,
3514 						    context, notify, callback,
3515 						    name, map);
3516 	}
3517 
3518 	/* The split ring indexes its rings with num - 1 as a mask. */
3519 	if (!is_power_of_2(num)) {
3520 		dev_err(&vdev->dev,
3521 			"Bad virtqueue length %u (not a power of two)\n", num);
3522 		return NULL;
3523 	}
3524 
3525 	vring_init(&vring_split.vring, num, pages, vring_align);
3526 	return __vring_new_virtqueue_split(index, &vring_split, vdev, weak_barriers,
3527 				     context, notify, callback, name,
3528 				     map);
3529 }
3530 EXPORT_SYMBOL_GPL(vring_new_virtqueue);
3531 
3532 static void vring_free(struct virtqueue *_vq)
3533 {
3534 	struct vring_virtqueue *vq = to_vvq(_vq);
3535 
3536 	if (vq->we_own_ring) {
3537 		if (virtqueue_is_packed(vq)) {
3538 			vring_free_queue(vq->vq.vdev,
3539 					 vq->packed.ring_size_in_bytes,
3540 					 vq->packed.vring.desc,
3541 					 vq->packed.ring_dma_addr,
3542 					 vq->map);
3543 
3544 			vring_free_queue(vq->vq.vdev,
3545 					 vq->packed.event_size_in_bytes,
3546 					 vq->packed.vring.driver,
3547 					 vq->packed.driver_event_dma_addr,
3548 					 vq->map);
3549 
3550 			vring_free_queue(vq->vq.vdev,
3551 					 vq->packed.event_size_in_bytes,
3552 					 vq->packed.vring.device,
3553 					 vq->packed.device_event_dma_addr,
3554 					 vq->map);
3555 
3556 			kfree(vq->packed.desc_state);
3557 			kfree(vq->packed.desc_extra);
3558 		} else {
3559 			vring_free_queue(vq->vq.vdev,
3560 					 vq->split.queue_size_in_bytes,
3561 					 vq->split.vring.desc,
3562 					 vq->split.queue_dma_addr,
3563 					 vq->map);
3564 		}
3565 	}
3566 	if (!virtqueue_is_packed(vq)) {
3567 		kfree(vq->split.desc_state);
3568 		kfree(vq->split.desc_extra);
3569 	}
3570 }
3571 
3572 void vring_del_virtqueue(struct virtqueue *_vq)
3573 {
3574 	struct vring_virtqueue *vq = to_vvq(_vq);
3575 
3576 	spin_lock(&vq->vq.vdev->vqs_list_lock);
3577 	list_del(&_vq->list);
3578 	spin_unlock(&vq->vq.vdev->vqs_list_lock);
3579 
3580 	vring_free(_vq);
3581 
3582 	kfree(vq);
3583 }
3584 EXPORT_SYMBOL_GPL(vring_del_virtqueue);
3585 
3586 u32 vring_notification_data(struct virtqueue *_vq)
3587 {
3588 	struct vring_virtqueue *vq = to_vvq(_vq);
3589 	u16 next;
3590 
3591 	if (virtqueue_is_packed(vq))
3592 		next = (vq->packed.next_avail_idx &
3593 				~(-(1 << VRING_PACKED_EVENT_F_WRAP_CTR))) |
3594 			vq->packed.avail_wrap_counter <<
3595 				VRING_PACKED_EVENT_F_WRAP_CTR;
3596 	else
3597 		next = vq->split.avail_idx_shadow;
3598 
3599 	return next << 16 | _vq->index;
3600 }
3601 EXPORT_SYMBOL_GPL(vring_notification_data);
3602 
3603 /* Manipulates transport-specific feature bits. */
3604 void vring_transport_features(struct virtio_device *vdev)
3605 {
3606 	unsigned int i;
3607 
3608 	for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
3609 		switch (i) {
3610 		case VIRTIO_RING_F_INDIRECT_DESC:
3611 			break;
3612 		case VIRTIO_RING_F_EVENT_IDX:
3613 			break;
3614 		case VIRTIO_F_VERSION_1:
3615 			break;
3616 		case VIRTIO_F_ACCESS_PLATFORM:
3617 			break;
3618 		case VIRTIO_F_RING_PACKED:
3619 			break;
3620 		case VIRTIO_F_ORDER_PLATFORM:
3621 			break;
3622 		case VIRTIO_F_NOTIFICATION_DATA:
3623 			break;
3624 		case VIRTIO_F_IN_ORDER:
3625 			break;
3626 		default:
3627 			/* We don't understand this bit. */
3628 			__virtio_clear_bit(vdev, i);
3629 		}
3630 	}
3631 }
3632 EXPORT_SYMBOL_GPL(vring_transport_features);
3633 
3634 /**
3635  * virtqueue_get_vring_size - return the size of the virtqueue's vring
3636  * @_vq: the struct virtqueue containing the vring of interest.
3637  *
3638  * Returns the size of the vring.  This is mainly used for boasting to
3639  * userspace.  Unlike other operations, this need not be serialized.
3640  */
3641 unsigned int virtqueue_get_vring_size(const struct virtqueue *_vq)
3642 {
3643 
3644 	const struct vring_virtqueue *vq = to_vvq(_vq);
3645 
3646 	return virtqueue_is_packed(vq) ? vq->packed.vring.num :
3647 				      vq->split.vring.num;
3648 }
3649 EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
3650 
3651 /*
3652  * This function should only be called by the core, not directly by the driver.
3653  */
3654 void __virtqueue_break(struct virtqueue *_vq)
3655 {
3656 	struct vring_virtqueue *vq = to_vvq(_vq);
3657 
3658 	/* Pairs with READ_ONCE() in virtqueue_is_broken(). */
3659 	WRITE_ONCE(vq->broken, true);
3660 }
3661 EXPORT_SYMBOL_GPL(__virtqueue_break);
3662 
3663 /*
3664  * This function should only be called by the core, not directly by the driver.
3665  */
3666 void __virtqueue_unbreak(struct virtqueue *_vq)
3667 {
3668 	struct vring_virtqueue *vq = to_vvq(_vq);
3669 
3670 	/* Pairs with READ_ONCE() in virtqueue_is_broken(). */
3671 	WRITE_ONCE(vq->broken, false);
3672 }
3673 EXPORT_SYMBOL_GPL(__virtqueue_unbreak);
3674 
3675 bool virtqueue_is_broken(const struct virtqueue *_vq)
3676 {
3677 	const struct vring_virtqueue *vq = to_vvq(_vq);
3678 
3679 	return READ_ONCE(vq->broken);
3680 }
3681 EXPORT_SYMBOL_GPL(virtqueue_is_broken);
3682 
3683 /*
3684  * This should prevent the device from being used, allowing drivers to
3685  * recover.  You may need to grab appropriate locks to flush.
3686  */
3687 void virtio_break_device(struct virtio_device *dev)
3688 {
3689 	struct virtqueue *_vq;
3690 
3691 	spin_lock(&dev->vqs_list_lock);
3692 	list_for_each_entry(_vq, &dev->vqs, list) {
3693 		struct vring_virtqueue *vq = to_vvq(_vq);
3694 
3695 		/* Pairs with READ_ONCE() in virtqueue_is_broken(). */
3696 		WRITE_ONCE(vq->broken, true);
3697 	}
3698 	spin_unlock(&dev->vqs_list_lock);
3699 }
3700 EXPORT_SYMBOL_GPL(virtio_break_device);
3701 
3702 /*
3703  * This should allow the device to be used by the driver. You may
3704  * need to grab appropriate locks to flush the write to
3705  * vq->broken. This should only be used in some specific case e.g
3706  * (probing and restoring). This function should only be called by the
3707  * core, not directly by the driver.
3708  */
3709 void __virtio_unbreak_device(struct virtio_device *dev)
3710 {
3711 	struct virtqueue *_vq;
3712 
3713 	spin_lock(&dev->vqs_list_lock);
3714 	list_for_each_entry(_vq, &dev->vqs, list) {
3715 		struct vring_virtqueue *vq = to_vvq(_vq);
3716 
3717 		/* Pairs with READ_ONCE() in virtqueue_is_broken(). */
3718 		WRITE_ONCE(vq->broken, false);
3719 	}
3720 	spin_unlock(&dev->vqs_list_lock);
3721 }
3722 EXPORT_SYMBOL_GPL(__virtio_unbreak_device);
3723 
3724 dma_addr_t virtqueue_get_desc_addr(const struct virtqueue *_vq)
3725 {
3726 	const struct vring_virtqueue *vq = to_vvq(_vq);
3727 
3728 	BUG_ON(!vq->we_own_ring);
3729 
3730 	if (virtqueue_is_packed(vq))
3731 		return vq->packed.ring_dma_addr;
3732 
3733 	return vq->split.queue_dma_addr;
3734 }
3735 EXPORT_SYMBOL_GPL(virtqueue_get_desc_addr);
3736 
3737 dma_addr_t virtqueue_get_avail_addr(const struct virtqueue *_vq)
3738 {
3739 	const struct vring_virtqueue *vq = to_vvq(_vq);
3740 
3741 	BUG_ON(!vq->we_own_ring);
3742 
3743 	if (virtqueue_is_packed(vq))
3744 		return vq->packed.driver_event_dma_addr;
3745 
3746 	return vq->split.queue_dma_addr +
3747 		((char *)vq->split.vring.avail - (char *)vq->split.vring.desc);
3748 }
3749 EXPORT_SYMBOL_GPL(virtqueue_get_avail_addr);
3750 
3751 dma_addr_t virtqueue_get_used_addr(const struct virtqueue *_vq)
3752 {
3753 	const struct vring_virtqueue *vq = to_vvq(_vq);
3754 
3755 	BUG_ON(!vq->we_own_ring);
3756 
3757 	if (virtqueue_is_packed(vq))
3758 		return vq->packed.device_event_dma_addr;
3759 
3760 	return vq->split.queue_dma_addr +
3761 		((char *)vq->split.vring.used - (char *)vq->split.vring.desc);
3762 }
3763 EXPORT_SYMBOL_GPL(virtqueue_get_used_addr);
3764 
3765 /* Only available for split ring */
3766 const struct vring *virtqueue_get_vring(const struct virtqueue *vq)
3767 {
3768 	return &to_vvq(vq)->split.vring;
3769 }
3770 EXPORT_SYMBOL_GPL(virtqueue_get_vring);
3771 
3772 /**
3773  * virtqueue_map_alloc_coherent - alloc coherent mapping
3774  * @vdev: the virtio device we are talking to
3775  * @map: metadata for performing mapping
3776  * @size: the size of the buffer
3777  * @map_handle: the pointer to the mapped address
3778  * @gfp: allocation flag (GFP_XXX)
3779  *
3780  * return virtual address or NULL on error
3781  */
3782 void *virtqueue_map_alloc_coherent(struct virtio_device *vdev,
3783 				   union virtio_map map,
3784 				   size_t size, dma_addr_t *map_handle,
3785 				   gfp_t gfp)
3786 {
3787 	if (vdev->map)
3788 		return vdev->map->alloc(map, size,
3789 					map_handle, gfp);
3790 	else
3791 		return dma_alloc_coherent(map.dma_dev, size,
3792 					  map_handle, gfp);
3793 }
3794 EXPORT_SYMBOL_GPL(virtqueue_map_alloc_coherent);
3795 
3796 /**
3797  * virtqueue_map_free_coherent - free coherent mapping
3798  * @vdev: the virtio device we are talking to
3799  * @map: metadata for performing mapping
3800  * @size: the size of the buffer
3801  * @vaddr: the virtual address that needs to be freed
3802  * @map_handle: the mapped address that needs to be freed
3803  *
3804  */
3805 void virtqueue_map_free_coherent(struct virtio_device *vdev,
3806 				 union virtio_map map, size_t size, void *vaddr,
3807 				 dma_addr_t map_handle)
3808 {
3809 	if (vdev->map)
3810 		vdev->map->free(map, size, vaddr,
3811 				map_handle, 0);
3812 	else
3813 		dma_free_coherent(map.dma_dev, size, vaddr, map_handle);
3814 }
3815 EXPORT_SYMBOL_GPL(virtqueue_map_free_coherent);
3816 
3817 /**
3818  * virtqueue_map_page_attrs - map a page to the device
3819  * @_vq: the virtqueue we are talking to
3820  * @page: the page that will be mapped by the device
3821  * @offset: the offset in the page for a buffer
3822  * @size: the buffer size
3823  * @dir: mapping direction
3824  * @attrs: mapping attributes
3825  *
3826  * Returns mapped address. Caller should check that by virtqueue_map_mapping_error().
3827  */
3828 dma_addr_t virtqueue_map_page_attrs(const struct virtqueue *_vq,
3829 				    struct page *page,
3830 				    unsigned long offset,
3831 				    size_t size,
3832 				    enum dma_data_direction dir,
3833 				    unsigned long attrs)
3834 {
3835 	const struct vring_virtqueue *vq = to_vvq(_vq);
3836 	struct virtio_device *vdev = _vq->vdev;
3837 
3838 	if (vdev->map)
3839 		return vdev->map->map_page(vq->map,
3840 					   page, offset, size,
3841 					   dir, attrs);
3842 
3843 	return dma_map_page_attrs(vring_dma_dev(vq),
3844 				  page, offset, size,
3845 				  dir, attrs);
3846 }
3847 EXPORT_SYMBOL_GPL(virtqueue_map_page_attrs);
3848 
3849 /**
3850  * virtqueue_unmap_page_attrs - map a page to the device
3851  * @_vq: the virtqueue we are talking to
3852  * @map_handle: the mapped address
3853  * @size: the buffer size
3854  * @dir: mapping direction
3855  * @attrs: unmapping attributes
3856  */
3857 void virtqueue_unmap_page_attrs(const struct virtqueue *_vq,
3858 				dma_addr_t map_handle,
3859 				size_t size, enum dma_data_direction dir,
3860 				unsigned long attrs)
3861 {
3862 	const struct vring_virtqueue *vq = to_vvq(_vq);
3863 	struct virtio_device *vdev = _vq->vdev;
3864 
3865 	if (vdev->map)
3866 		vdev->map->unmap_page(vq->map,
3867 				      map_handle, size, dir, attrs);
3868 	else
3869 		dma_unmap_page_attrs(vring_dma_dev(vq), map_handle,
3870 				     size, dir, attrs);
3871 }
3872 EXPORT_SYMBOL_GPL(virtqueue_unmap_page_attrs);
3873 
3874 /**
3875  * virtqueue_map_single_attrs - map DMA for _vq
3876  * @_vq: the struct virtqueue we're talking about.
3877  * @ptr: the pointer of the buffer to do dma
3878  * @size: the size of the buffer to do dma
3879  * @dir: DMA direction
3880  * @attrs: DMA Attrs
3881  *
3882  * The caller calls this to do dma mapping in advance. The DMA address can be
3883  * passed to this _vq when it is in pre-mapped mode.
3884  *
3885  * return mapped address. Caller should check that by virtqueue_map_mapping_error().
3886  */
3887 dma_addr_t virtqueue_map_single_attrs(const struct virtqueue *_vq, void *ptr,
3888 				      size_t size,
3889 				      enum dma_data_direction dir,
3890 				      unsigned long attrs)
3891 {
3892 	const struct vring_virtqueue *vq = to_vvq(_vq);
3893 
3894 	if (!vq->use_map_api) {
3895 		kmsan_handle_dma(virt_to_phys(ptr), size, dir);
3896 		return (dma_addr_t)virt_to_phys(ptr);
3897 	}
3898 
3899 	/* DMA must never operate on areas that might be remapped. */
3900 	if (dev_WARN_ONCE(&_vq->vdev->dev, is_vmalloc_addr(ptr),
3901 			  "rejecting DMA map of vmalloc memory\n"))
3902 		return DMA_MAPPING_ERROR;
3903 
3904 	return virtqueue_map_page_attrs(&vq->vq, virt_to_page(ptr),
3905 					offset_in_page(ptr), size, dir, attrs);
3906 }
3907 EXPORT_SYMBOL_GPL(virtqueue_map_single_attrs);
3908 
3909 /**
3910  * virtqueue_unmap_single_attrs - unmap map for _vq
3911  * @_vq: the struct virtqueue we're talking about.
3912  * @addr: the dma address to unmap
3913  * @size: the size of the buffer
3914  * @dir: DMA direction
3915  * @attrs: DMA Attrs
3916  *
3917  * Unmap the address that is mapped by the virtqueue_map_* APIs.
3918  *
3919  */
3920 void virtqueue_unmap_single_attrs(const struct virtqueue *_vq,
3921 				  dma_addr_t addr,
3922 				  size_t size, enum dma_data_direction dir,
3923 				  unsigned long attrs)
3924 {
3925 	const struct vring_virtqueue *vq = to_vvq(_vq);
3926 
3927 	if (!vq->use_map_api)
3928 		return;
3929 
3930 	virtqueue_unmap_page_attrs(_vq, addr, size, dir, attrs);
3931 }
3932 EXPORT_SYMBOL_GPL(virtqueue_unmap_single_attrs);
3933 
3934 /**
3935  * virtqueue_map_mapping_error - check dma address
3936  * @_vq: the struct virtqueue we're talking about.
3937  * @addr: DMA address
3938  *
3939  * Returns 0 means dma valid. Other means invalid dma address.
3940  */
3941 int virtqueue_map_mapping_error(const struct virtqueue *_vq, dma_addr_t addr)
3942 {
3943 	const struct vring_virtqueue *vq = to_vvq(_vq);
3944 
3945 	return vring_mapping_error(vq, addr);
3946 }
3947 EXPORT_SYMBOL_GPL(virtqueue_map_mapping_error);
3948 
3949 /**
3950  * virtqueue_map_need_sync - check a dma address needs sync
3951  * @_vq: the struct virtqueue we're talking about.
3952  * @addr: DMA address
3953  *
3954  * Check if the dma address mapped by the virtqueue_map_* APIs needs to be
3955  * synchronized
3956  *
3957  * return bool
3958  */
3959 bool virtqueue_map_need_sync(const struct virtqueue *_vq, dma_addr_t addr)
3960 {
3961 	const struct vring_virtqueue *vq = to_vvq(_vq);
3962 	struct virtio_device *vdev = _vq->vdev;
3963 
3964 	if (!vq->use_map_api)
3965 		return false;
3966 
3967 	if (vdev->map)
3968 		return vdev->map->need_sync(vq->map, addr);
3969 	else
3970 		return dma_need_sync(vring_dma_dev(vq), addr);
3971 }
3972 EXPORT_SYMBOL_GPL(virtqueue_map_need_sync);
3973 
3974 /**
3975  * virtqueue_map_sync_single_range_for_cpu - map sync for cpu
3976  * @_vq: the struct virtqueue we're talking about.
3977  * @addr: DMA address
3978  * @offset: DMA address offset
3979  * @size: buf size for sync
3980  * @dir: DMA direction
3981  *
3982  * Before calling this function, use virtqueue_map_need_sync() to confirm that
3983  * the DMA address really needs to be synchronized
3984  *
3985  */
3986 void virtqueue_map_sync_single_range_for_cpu(const struct virtqueue *_vq,
3987 					     dma_addr_t addr,
3988 					     unsigned long offset, size_t size,
3989 					     enum dma_data_direction dir)
3990 {
3991 	const struct vring_virtqueue *vq = to_vvq(_vq);
3992 	struct virtio_device *vdev = _vq->vdev;
3993 
3994 	if (!vq->use_map_api)
3995 		return;
3996 
3997 	if (vdev->map)
3998 		vdev->map->sync_single_for_cpu(vq->map,
3999 					       addr + offset, size, dir);
4000 	else
4001 		dma_sync_single_range_for_cpu(vring_dma_dev(vq),
4002 					      addr, offset, size, dir);
4003 }
4004 EXPORT_SYMBOL_GPL(virtqueue_map_sync_single_range_for_cpu);
4005 
4006 /**
4007  * virtqueue_map_sync_single_range_for_device - map sync for device
4008  * @_vq: the struct virtqueue we're talking about.
4009  * @addr: DMA address
4010  * @offset: DMA address offset
4011  * @size: buf size for sync
4012  * @dir: DMA direction
4013  *
4014  * Before calling this function, use virtqueue_map_need_sync() to confirm that
4015  * the DMA address really needs to be synchronized
4016  */
4017 void virtqueue_map_sync_single_range_for_device(const struct virtqueue *_vq,
4018 						dma_addr_t addr,
4019 						unsigned long offset, size_t size,
4020 						enum dma_data_direction dir)
4021 {
4022 	const struct vring_virtqueue *vq = to_vvq(_vq);
4023 	struct virtio_device *vdev = _vq->vdev;
4024 
4025 	if (!vq->use_map_api)
4026 		return;
4027 
4028 	if (vdev->map)
4029 		vdev->map->sync_single_for_device(vq->map,
4030 						  addr + offset,
4031 						  size, dir);
4032 	else
4033 		dma_sync_single_range_for_device(vring_dma_dev(vq), addr,
4034 						 offset, size, dir);
4035 }
4036 EXPORT_SYMBOL_GPL(virtqueue_map_sync_single_range_for_device);
4037 
4038 MODULE_DESCRIPTION("Virtio ring implementation");
4039 MODULE_LICENSE("GPL");
4040