• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Virtio ring implementation.
2  *
3  *  Copyright 2007 Rusty Russell IBM Corporation
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  */
19 #include <linux/virtio.h>
20 #include <linux/virtio_ring.h>
21 #include <linux/virtio_config.h>
22 #include <linux/device.h>
23 #include <linux/slab.h>
24 #include <linux/module.h>
25 #include <linux/hrtimer.h>
26 #include <linux/kmemleak.h>
27 #include <linux/dma-mapping.h>
28 #include <xen/xen.h>
29 
30 #ifdef DEBUG
31 /* For development, we want to crash whenever the ring is screwed. */
32 #define BAD_RING(_vq, fmt, args...)				\
33 	do {							\
34 		dev_err(&(_vq)->vq.vdev->dev,			\
35 			"%s:"fmt, (_vq)->vq.name, ##args);	\
36 		BUG();						\
37 	} while (0)
38 /* Caller is supposed to guarantee no reentry. */
39 #define START_USE(_vq)						\
40 	do {							\
41 		if ((_vq)->in_use)				\
42 			panic("%s:in_use = %i\n",		\
43 			      (_vq)->vq.name, (_vq)->in_use);	\
44 		(_vq)->in_use = __LINE__;			\
45 	} while (0)
46 #define END_USE(_vq) \
47 	do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
48 #else
49 #define BAD_RING(_vq, fmt, args...)				\
50 	do {							\
51 		dev_err(&_vq->vq.vdev->dev,			\
52 			"%s:"fmt, (_vq)->vq.name, ##args);	\
53 		(_vq)->broken = true;				\
54 	} while (0)
55 #define START_USE(vq)
56 #define END_USE(vq)
57 #endif
58 
59 struct vring_desc_state {
60 	void *data;			/* Data for callback. */
61 	struct vring_desc *indir_desc;	/* Indirect descriptor, if any. */
62 };
63 
64 struct vring_virtqueue {
65 	struct virtqueue vq;
66 
67 	/* Actual memory layout for this queue */
68 	struct vring vring;
69 
70 	/* Can we use weak barriers? */
71 	bool weak_barriers;
72 
73 	/* Other side has made a mess, don't try any more. */
74 	bool broken;
75 
76 	/* Host supports indirect buffers */
77 	bool indirect;
78 
79 	/* Host publishes avail event idx */
80 	bool event;
81 
82 	/* Head of free buffer list. */
83 	unsigned int free_head;
84 	/* Number we've added since last sync. */
85 	unsigned int num_added;
86 
87 	/* Last used index we've seen. */
88 	u16 last_used_idx;
89 
90 	/* Last written value to avail->flags */
91 	u16 avail_flags_shadow;
92 
93 	/* Last written value to avail->idx in guest byte order */
94 	u16 avail_idx_shadow;
95 
96 	/* How to notify other side. FIXME: commonalize hcalls! */
97 	bool (*notify)(struct virtqueue *vq);
98 
99 #ifdef DEBUG
100 	/* They're supposed to lock for us. */
101 	unsigned int in_use;
102 
103 	/* Figure out if their kicks are too delayed. */
104 	bool last_add_time_valid;
105 	ktime_t last_add_time;
106 #endif
107 
108 	/* Per-descriptor state. */
109 	struct vring_desc_state desc_state[];
110 };
111 
112 #define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
113 
114 /*
115  * Modern virtio devices have feature bits to specify whether they need a
116  * quirk and bypass the IOMMU. If not there, just use the DMA API.
117  *
118  * If there, the interaction between virtio and DMA API is messy.
119  *
120  * On most systems with virtio, physical addresses match bus addresses,
121  * and it doesn't particularly matter whether we use the DMA API.
122  *
123  * On some systems, including Xen and any system with a physical device
124  * that speaks virtio behind a physical IOMMU, we must use the DMA API
125  * for virtio DMA to work at all.
126  *
127  * On other systems, including SPARC and PPC64, virtio-pci devices are
128  * enumerated as though they are behind an IOMMU, but the virtio host
129  * ignores the IOMMU, so we must either pretend that the IOMMU isn't
130  * there or somehow map everything as the identity.
131  *
132  * For the time being, we preserve historic behavior and bypass the DMA
133  * API.
134  *
135  * TODO: install a per-device DMA ops structure that does the right thing
136  * taking into account all the above quirks, and use the DMA API
137  * unconditionally on data path.
138  */
139 
vring_use_dma_api(struct virtio_device * vdev)140 static bool vring_use_dma_api(struct virtio_device *vdev)
141 {
142 	if (!virtio_has_iommu_quirk(vdev))
143 		return true;
144 
145 	/* Otherwise, we are left to guess. */
146 	/*
147 	 * In theory, it's possible to have a buggy QEMU-supposed
148 	 * emulated Q35 IOMMU and Xen enabled at the same time.  On
149 	 * such a configuration, virtio has never worked and will
150 	 * not work without an even larger kludge.  Instead, enable
151 	 * the DMA API if we're a Xen guest, which at least allows
152 	 * all of the sensible Xen configurations to work correctly.
153 	 */
154 	if (xen_domain())
155 		return true;
156 
157 	return false;
158 }
159 
160 /*
161  * The DMA ops on various arches are rather gnarly right now, and
162  * making all of the arch DMA ops work on the vring device itself
163  * is a mess.  For now, we use the parent device for DMA ops.
164  */
vring_dma_dev(const struct vring_virtqueue * vq)165 struct device *vring_dma_dev(const struct vring_virtqueue *vq)
166 {
167 	return vq->vq.vdev->dev.parent;
168 }
169 
170 /* Map one sg entry. */
vring_map_one_sg(const struct vring_virtqueue * vq,struct scatterlist * sg,enum dma_data_direction direction)171 static dma_addr_t vring_map_one_sg(const struct vring_virtqueue *vq,
172 				   struct scatterlist *sg,
173 				   enum dma_data_direction direction)
174 {
175 	if (!vring_use_dma_api(vq->vq.vdev))
176 		return (dma_addr_t)sg_phys(sg);
177 
178 	/*
179 	 * We can't use dma_map_sg, because we don't use scatterlists in
180 	 * the way it expects (we don't guarantee that the scatterlist
181 	 * will exist for the lifetime of the mapping).
182 	 */
183 	return dma_map_page(vring_dma_dev(vq),
184 			    sg_page(sg), sg->offset, sg->length,
185 			    direction);
186 }
187 
vring_map_single(const struct vring_virtqueue * vq,void * cpu_addr,size_t size,enum dma_data_direction direction)188 static dma_addr_t vring_map_single(const struct vring_virtqueue *vq,
189 				   void *cpu_addr, size_t size,
190 				   enum dma_data_direction direction)
191 {
192 	if (!vring_use_dma_api(vq->vq.vdev))
193 		return (dma_addr_t)virt_to_phys(cpu_addr);
194 
195 	return dma_map_single(vring_dma_dev(vq),
196 			      cpu_addr, size, direction);
197 }
198 
vring_unmap_one(const struct vring_virtqueue * vq,struct vring_desc * desc)199 static void vring_unmap_one(const struct vring_virtqueue *vq,
200 			    struct vring_desc *desc)
201 {
202 	u16 flags;
203 
204 	if (!vring_use_dma_api(vq->vq.vdev))
205 		return;
206 
207 	flags = virtio16_to_cpu(vq->vq.vdev, desc->flags);
208 
209 	if (flags & VRING_DESC_F_INDIRECT) {
210 		dma_unmap_single(vring_dma_dev(vq),
211 				 virtio64_to_cpu(vq->vq.vdev, desc->addr),
212 				 virtio32_to_cpu(vq->vq.vdev, desc->len),
213 				 (flags & VRING_DESC_F_WRITE) ?
214 				 DMA_FROM_DEVICE : DMA_TO_DEVICE);
215 	} else {
216 		dma_unmap_page(vring_dma_dev(vq),
217 			       virtio64_to_cpu(vq->vq.vdev, desc->addr),
218 			       virtio32_to_cpu(vq->vq.vdev, desc->len),
219 			       (flags & VRING_DESC_F_WRITE) ?
220 			       DMA_FROM_DEVICE : DMA_TO_DEVICE);
221 	}
222 }
223 
vring_mapping_error(const struct vring_virtqueue * vq,dma_addr_t addr)224 static int vring_mapping_error(const struct vring_virtqueue *vq,
225 			       dma_addr_t addr)
226 {
227 	if (!vring_use_dma_api(vq->vq.vdev))
228 		return 0;
229 
230 	return dma_mapping_error(vring_dma_dev(vq), addr);
231 }
232 
alloc_indirect(struct virtqueue * _vq,unsigned int total_sg,gfp_t gfp)233 static struct vring_desc *alloc_indirect(struct virtqueue *_vq,
234 					 unsigned int total_sg, gfp_t gfp)
235 {
236 	struct vring_desc *desc;
237 	unsigned int i;
238 
239 	/*
240 	 * We require lowmem mappings for the descriptors because
241 	 * otherwise virt_to_phys will give us bogus addresses in the
242 	 * virtqueue.
243 	 */
244 	gfp &= ~__GFP_HIGHMEM;
245 
246 	desc = kmalloc(total_sg * sizeof(struct vring_desc), gfp);
247 	if (!desc)
248 		return NULL;
249 
250 	for (i = 0; i < total_sg; i++)
251 		desc[i].next = cpu_to_virtio16(_vq->vdev, i + 1);
252 	return desc;
253 }
254 
virtqueue_add(struct virtqueue * _vq,struct scatterlist * sgs[],unsigned int total_sg,unsigned int out_sgs,unsigned int in_sgs,void * data,gfp_t gfp)255 static inline int virtqueue_add(struct virtqueue *_vq,
256 				struct scatterlist *sgs[],
257 				unsigned int total_sg,
258 				unsigned int out_sgs,
259 				unsigned int in_sgs,
260 				void *data,
261 				gfp_t gfp)
262 {
263 	struct vring_virtqueue *vq = to_vvq(_vq);
264 	struct scatterlist *sg;
265 	struct vring_desc *desc;
266 	unsigned int i, n, avail, descs_used, uninitialized_var(prev), err_idx;
267 	int head;
268 	bool indirect;
269 
270 	START_USE(vq);
271 
272 	BUG_ON(data == NULL);
273 
274 	if (unlikely(vq->broken)) {
275 		END_USE(vq);
276 		return -EIO;
277 	}
278 
279 #ifdef DEBUG
280 	{
281 		ktime_t now = ktime_get();
282 
283 		/* No kick or get, with .1 second between?  Warn. */
284 		if (vq->last_add_time_valid)
285 			WARN_ON(ktime_to_ms(ktime_sub(now, vq->last_add_time))
286 					    > 100);
287 		vq->last_add_time = now;
288 		vq->last_add_time_valid = true;
289 	}
290 #endif
291 
292 	BUG_ON(total_sg > vq->vring.num);
293 	BUG_ON(total_sg == 0);
294 
295 	head = vq->free_head;
296 
297 	/* If the host supports indirect descriptor tables, and we have multiple
298 	 * buffers, then go indirect. FIXME: tune this threshold */
299 	if (vq->indirect && total_sg > 1 && vq->vq.num_free)
300 		desc = alloc_indirect(_vq, total_sg, gfp);
301 	else
302 		desc = NULL;
303 
304 	if (desc) {
305 		/* Use a single buffer which doesn't continue */
306 		indirect = true;
307 		/* Set up rest to use this indirect table. */
308 		i = 0;
309 		descs_used = 1;
310 	} else {
311 		indirect = false;
312 		desc = vq->vring.desc;
313 		i = head;
314 		descs_used = total_sg;
315 	}
316 
317 	if (vq->vq.num_free < descs_used) {
318 		pr_debug("Can't add buf len %i - avail = %i\n",
319 			 descs_used, vq->vq.num_free);
320 		/* FIXME: for historical reasons, we force a notify here if
321 		 * there are outgoing parts to the buffer.  Presumably the
322 		 * host should service the ring ASAP. */
323 		if (out_sgs)
324 			vq->notify(&vq->vq);
325 		if (indirect)
326 			kfree(desc);
327 		END_USE(vq);
328 		return -ENOSPC;
329 	}
330 
331 	for (n = 0; n < out_sgs; n++) {
332 		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
333 			dma_addr_t addr = vring_map_one_sg(vq, sg, DMA_TO_DEVICE);
334 			if (vring_mapping_error(vq, addr))
335 				goto unmap_release;
336 
337 			desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT);
338 			desc[i].addr = cpu_to_virtio64(_vq->vdev, addr);
339 			desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
340 			prev = i;
341 			i = virtio16_to_cpu(_vq->vdev, desc[i].next);
342 		}
343 	}
344 	for (; n < (out_sgs + in_sgs); n++) {
345 		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
346 			dma_addr_t addr = vring_map_one_sg(vq, sg, DMA_FROM_DEVICE);
347 			if (vring_mapping_error(vq, addr))
348 				goto unmap_release;
349 
350 			desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT | VRING_DESC_F_WRITE);
351 			desc[i].addr = cpu_to_virtio64(_vq->vdev, addr);
352 			desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
353 			prev = i;
354 			i = virtio16_to_cpu(_vq->vdev, desc[i].next);
355 		}
356 	}
357 	/* Last one doesn't continue. */
358 	desc[prev].flags &= cpu_to_virtio16(_vq->vdev, ~VRING_DESC_F_NEXT);
359 
360 	if (indirect) {
361 		/* Now that the indirect table is filled in, map it. */
362 		dma_addr_t addr = vring_map_single(
363 			vq, desc, total_sg * sizeof(struct vring_desc),
364 			DMA_TO_DEVICE);
365 		if (vring_mapping_error(vq, addr))
366 			goto unmap_release;
367 
368 		vq->vring.desc[head].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_INDIRECT);
369 		vq->vring.desc[head].addr = cpu_to_virtio64(_vq->vdev, addr);
370 
371 		vq->vring.desc[head].len = cpu_to_virtio32(_vq->vdev, total_sg * sizeof(struct vring_desc));
372 	}
373 
374 	/* We're using some buffers from the free list. */
375 	vq->vq.num_free -= descs_used;
376 
377 	/* Update free pointer */
378 	if (indirect)
379 		vq->free_head = virtio16_to_cpu(_vq->vdev, vq->vring.desc[head].next);
380 	else
381 		vq->free_head = i;
382 
383 	/* Store token and indirect buffer state. */
384 	vq->desc_state[head].data = data;
385 	if (indirect)
386 		vq->desc_state[head].indir_desc = desc;
387 
388 	/* Put entry in available array (but don't update avail->idx until they
389 	 * do sync). */
390 	avail = vq->avail_idx_shadow & (vq->vring.num - 1);
391 	vq->vring.avail->ring[avail] = cpu_to_virtio16(_vq->vdev, head);
392 
393 	/* Descriptors and available array need to be set before we expose the
394 	 * new available array entries. */
395 	virtio_wmb(vq->weak_barriers);
396 	vq->avail_idx_shadow++;
397 	vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
398 	vq->num_added++;
399 
400 	pr_debug("Added buffer head %i to %p\n", head, vq);
401 	END_USE(vq);
402 
403 	/* This is very unlikely, but theoretically possible.  Kick
404 	 * just in case. */
405 	if (unlikely(vq->num_added == (1 << 16) - 1))
406 		virtqueue_kick(_vq);
407 
408 	return 0;
409 
410 unmap_release:
411 	err_idx = i;
412 	i = head;
413 
414 	for (n = 0; n < total_sg; n++) {
415 		if (i == err_idx)
416 			break;
417 		vring_unmap_one(vq, &desc[i]);
418 		i = vq->vring.desc[i].next;
419 	}
420 
421 	vq->vq.num_free += total_sg;
422 
423 	if (indirect)
424 		kfree(desc);
425 
426 	return -EIO;
427 }
428 
429 /**
430  * virtqueue_add_sgs - expose buffers to other end
431  * @vq: the struct virtqueue we're talking about.
432  * @sgs: array of terminated scatterlists.
433  * @out_num: the number of scatterlists readable by other side
434  * @in_num: the number of scatterlists which are writable (after readable ones)
435  * @data: the token identifying the buffer.
436  * @gfp: how to do memory allocations (if necessary).
437  *
438  * Caller must ensure we don't call this with other virtqueue operations
439  * at the same time (except where noted).
440  *
441  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
442  */
virtqueue_add_sgs(struct virtqueue * _vq,struct scatterlist * sgs[],unsigned int out_sgs,unsigned int in_sgs,void * data,gfp_t gfp)443 int virtqueue_add_sgs(struct virtqueue *_vq,
444 		      struct scatterlist *sgs[],
445 		      unsigned int out_sgs,
446 		      unsigned int in_sgs,
447 		      void *data,
448 		      gfp_t gfp)
449 {
450 	unsigned int i, total_sg = 0;
451 
452 	/* Count them first. */
453 	for (i = 0; i < out_sgs + in_sgs; i++) {
454 		struct scatterlist *sg;
455 		for (sg = sgs[i]; sg; sg = sg_next(sg))
456 			total_sg++;
457 	}
458 	return virtqueue_add(_vq, sgs, total_sg, out_sgs, in_sgs, data, gfp);
459 }
460 EXPORT_SYMBOL_GPL(virtqueue_add_sgs);
461 
462 /**
463  * virtqueue_add_outbuf - expose output buffers to other end
464  * @vq: the struct virtqueue we're talking about.
465  * @sg: scatterlist (must be well-formed and terminated!)
466  * @num: the number of entries in @sg readable by other side
467  * @data: the token identifying the buffer.
468  * @gfp: how to do memory allocations (if necessary).
469  *
470  * Caller must ensure we don't call this with other virtqueue operations
471  * at the same time (except where noted).
472  *
473  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
474  */
virtqueue_add_outbuf(struct virtqueue * vq,struct scatterlist * sg,unsigned int num,void * data,gfp_t gfp)475 int virtqueue_add_outbuf(struct virtqueue *vq,
476 			 struct scatterlist *sg, unsigned int num,
477 			 void *data,
478 			 gfp_t gfp)
479 {
480 	return virtqueue_add(vq, &sg, num, 1, 0, data, gfp);
481 }
482 EXPORT_SYMBOL_GPL(virtqueue_add_outbuf);
483 
484 /**
485  * virtqueue_add_inbuf - expose input buffers to other end
486  * @vq: the struct virtqueue we're talking about.
487  * @sg: scatterlist (must be well-formed and terminated!)
488  * @num: the number of entries in @sg writable by other side
489  * @data: the token identifying the buffer.
490  * @gfp: how to do memory allocations (if necessary).
491  *
492  * Caller must ensure we don't call this with other virtqueue operations
493  * at the same time (except where noted).
494  *
495  * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
496  */
virtqueue_add_inbuf(struct virtqueue * vq,struct scatterlist * sg,unsigned int num,void * data,gfp_t gfp)497 int virtqueue_add_inbuf(struct virtqueue *vq,
498 			struct scatterlist *sg, unsigned int num,
499 			void *data,
500 			gfp_t gfp)
501 {
502 	return virtqueue_add(vq, &sg, num, 0, 1, data, gfp);
503 }
504 EXPORT_SYMBOL_GPL(virtqueue_add_inbuf);
505 
506 /**
507  * virtqueue_kick_prepare - first half of split virtqueue_kick call.
508  * @vq: the struct virtqueue
509  *
510  * Instead of virtqueue_kick(), you can do:
511  *	if (virtqueue_kick_prepare(vq))
512  *		virtqueue_notify(vq);
513  *
514  * This is sometimes useful because the virtqueue_kick_prepare() needs
515  * to be serialized, but the actual virtqueue_notify() call does not.
516  */
virtqueue_kick_prepare(struct virtqueue * _vq)517 bool virtqueue_kick_prepare(struct virtqueue *_vq)
518 {
519 	struct vring_virtqueue *vq = to_vvq(_vq);
520 	u16 new, old;
521 	bool needs_kick;
522 
523 	START_USE(vq);
524 	/* We need to expose available array entries before checking avail
525 	 * event. */
526 	virtio_mb(vq->weak_barriers);
527 
528 	old = vq->avail_idx_shadow - vq->num_added;
529 	new = vq->avail_idx_shadow;
530 	vq->num_added = 0;
531 
532 #ifdef DEBUG
533 	if (vq->last_add_time_valid) {
534 		WARN_ON(ktime_to_ms(ktime_sub(ktime_get(),
535 					      vq->last_add_time)) > 100);
536 	}
537 	vq->last_add_time_valid = false;
538 #endif
539 
540 	if (vq->event) {
541 		needs_kick = vring_need_event(virtio16_to_cpu(_vq->vdev, vring_avail_event(&vq->vring)),
542 					      new, old);
543 	} else {
544 		needs_kick = !(vq->vring.used->flags & cpu_to_virtio16(_vq->vdev, VRING_USED_F_NO_NOTIFY));
545 	}
546 	END_USE(vq);
547 	return needs_kick;
548 }
549 EXPORT_SYMBOL_GPL(virtqueue_kick_prepare);
550 
551 /**
552  * virtqueue_notify - second half of split virtqueue_kick call.
553  * @vq: the struct virtqueue
554  *
555  * This does not need to be serialized.
556  *
557  * Returns false if host notify failed or queue is broken, otherwise true.
558  */
virtqueue_notify(struct virtqueue * _vq)559 bool virtqueue_notify(struct virtqueue *_vq)
560 {
561 	struct vring_virtqueue *vq = to_vvq(_vq);
562 
563 	if (unlikely(vq->broken))
564 		return false;
565 
566 	/* Prod other side to tell it about changes. */
567 	if (!vq->notify(_vq)) {
568 		vq->broken = true;
569 		return false;
570 	}
571 	return true;
572 }
573 EXPORT_SYMBOL_GPL(virtqueue_notify);
574 
575 /**
576  * virtqueue_kick - update after add_buf
577  * @vq: the struct virtqueue
578  *
579  * After one or more virtqueue_add_* calls, invoke this to kick
580  * the other side.
581  *
582  * Caller must ensure we don't call this with other virtqueue
583  * operations at the same time (except where noted).
584  *
585  * Returns false if kick failed, otherwise true.
586  */
virtqueue_kick(struct virtqueue * vq)587 bool virtqueue_kick(struct virtqueue *vq)
588 {
589 	if (virtqueue_kick_prepare(vq))
590 		return virtqueue_notify(vq);
591 	return true;
592 }
593 EXPORT_SYMBOL_GPL(virtqueue_kick);
594 
detach_buf(struct vring_virtqueue * vq,unsigned int head)595 static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
596 {
597 	unsigned int i, j;
598 	u16 nextflag = cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_NEXT);
599 
600 	/* Clear data ptr. */
601 	vq->desc_state[head].data = NULL;
602 
603 	/* Put back on free list: unmap first-level descriptors and find end */
604 	i = head;
605 
606 	while (vq->vring.desc[i].flags & nextflag) {
607 		vring_unmap_one(vq, &vq->vring.desc[i]);
608 		i = virtio16_to_cpu(vq->vq.vdev, vq->vring.desc[i].next);
609 		vq->vq.num_free++;
610 	}
611 
612 	vring_unmap_one(vq, &vq->vring.desc[i]);
613 	vq->vring.desc[i].next = cpu_to_virtio16(vq->vq.vdev, vq->free_head);
614 	vq->free_head = head;
615 
616 	/* Plus final descriptor */
617 	vq->vq.num_free++;
618 
619 	/* Free the indirect table, if any, now that it's unmapped. */
620 	if (vq->desc_state[head].indir_desc) {
621 		struct vring_desc *indir_desc = vq->desc_state[head].indir_desc;
622 		u32 len = virtio32_to_cpu(vq->vq.vdev, vq->vring.desc[head].len);
623 
624 		BUG_ON(!(vq->vring.desc[head].flags &
625 			 cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_INDIRECT)));
626 		BUG_ON(len == 0 || len % sizeof(struct vring_desc));
627 
628 		for (j = 0; j < len / sizeof(struct vring_desc); j++)
629 			vring_unmap_one(vq, &indir_desc[j]);
630 
631 		kfree(vq->desc_state[head].indir_desc);
632 		vq->desc_state[head].indir_desc = NULL;
633 	}
634 }
635 
more_used(const struct vring_virtqueue * vq)636 static inline bool more_used(const struct vring_virtqueue *vq)
637 {
638 	return vq->last_used_idx != virtio16_to_cpu(vq->vq.vdev, vq->vring.used->idx);
639 }
640 
641 /**
642  * virtqueue_get_buf - get the next used buffer
643  * @vq: the struct virtqueue we're talking about.
644  * @len: the length written into the buffer
645  *
646  * If the driver wrote data into the buffer, @len will be set to the
647  * amount written.  This means you don't need to clear the buffer
648  * beforehand to ensure there's no data leakage in the case of short
649  * writes.
650  *
651  * Caller must ensure we don't call this with other virtqueue
652  * operations at the same time (except where noted).
653  *
654  * Returns NULL if there are no used buffers, or the "data" token
655  * handed to virtqueue_add_*().
656  */
virtqueue_get_buf(struct virtqueue * _vq,unsigned int * len)657 void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
658 {
659 	struct vring_virtqueue *vq = to_vvq(_vq);
660 	void *ret;
661 	unsigned int i;
662 	u16 last_used;
663 
664 	START_USE(vq);
665 
666 	if (unlikely(vq->broken)) {
667 		END_USE(vq);
668 		return NULL;
669 	}
670 
671 	if (!more_used(vq)) {
672 		pr_debug("No more buffers in queue\n");
673 		END_USE(vq);
674 		return NULL;
675 	}
676 
677 	/* Only get used array entries after they have been exposed by host. */
678 	virtio_rmb(vq->weak_barriers);
679 
680 	last_used = (vq->last_used_idx & (vq->vring.num - 1));
681 	i = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].id);
682 	*len = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].len);
683 
684 	if (unlikely(i >= vq->vring.num)) {
685 		BAD_RING(vq, "id %u out of range\n", i);
686 		return NULL;
687 	}
688 	if (unlikely(!vq->desc_state[i].data)) {
689 		BAD_RING(vq, "id %u is not a head!\n", i);
690 		return NULL;
691 	}
692 
693 	/* detach_buf clears data, so grab it now. */
694 	ret = vq->desc_state[i].data;
695 	detach_buf(vq, i);
696 	vq->last_used_idx++;
697 	/* If we expect an interrupt for the next entry, tell host
698 	 * by writing event index and flush out the write before
699 	 * the read in the next get_buf call. */
700 	if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT)) {
701 		vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, vq->last_used_idx);
702 		virtio_mb(vq->weak_barriers);
703 	}
704 
705 #ifdef DEBUG
706 	vq->last_add_time_valid = false;
707 #endif
708 
709 	END_USE(vq);
710 	return ret;
711 }
712 EXPORT_SYMBOL_GPL(virtqueue_get_buf);
713 
714 /**
715  * virtqueue_disable_cb - disable callbacks
716  * @vq: the struct virtqueue we're talking about.
717  *
718  * Note that this is not necessarily synchronous, hence unreliable and only
719  * useful as an optimization.
720  *
721  * Unlike other operations, this need not be serialized.
722  */
virtqueue_disable_cb(struct virtqueue * _vq)723 void virtqueue_disable_cb(struct virtqueue *_vq)
724 {
725 	struct vring_virtqueue *vq = to_vvq(_vq);
726 
727 	if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT)) {
728 		vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
729 		if (!vq->event)
730 			vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
731 	}
732 
733 }
734 EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
735 
736 /**
737  * virtqueue_enable_cb_prepare - restart callbacks after disable_cb
738  * @vq: the struct virtqueue we're talking about.
739  *
740  * This re-enables callbacks; it returns current queue state
741  * in an opaque unsigned value. This value should be later tested by
742  * virtqueue_poll, to detect a possible race between the driver checking for
743  * more work, and enabling callbacks.
744  *
745  * Caller must ensure we don't call this with other virtqueue
746  * operations at the same time (except where noted).
747  */
virtqueue_enable_cb_prepare(struct virtqueue * _vq)748 unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
749 {
750 	struct vring_virtqueue *vq = to_vvq(_vq);
751 	u16 last_used_idx;
752 
753 	START_USE(vq);
754 
755 	/* We optimistically turn back on interrupts, then check if there was
756 	 * more to do. */
757 	/* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
758 	 * either clear the flags bit or point the event index at the next
759 	 * entry. Always do both to keep code simple. */
760 	if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
761 		vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
762 		if (!vq->event)
763 			vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
764 	}
765 	vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, last_used_idx = vq->last_used_idx);
766 	END_USE(vq);
767 	return last_used_idx;
768 }
769 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);
770 
771 /**
772  * virtqueue_poll - query pending used buffers
773  * @vq: the struct virtqueue we're talking about.
774  * @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
775  *
776  * Returns "true" if there are pending used buffers in the queue.
777  *
778  * This does not need to be serialized.
779  */
virtqueue_poll(struct virtqueue * _vq,unsigned last_used_idx)780 bool virtqueue_poll(struct virtqueue *_vq, unsigned last_used_idx)
781 {
782 	struct vring_virtqueue *vq = to_vvq(_vq);
783 
784 	if (unlikely(vq->broken))
785 		return false;
786 
787 	virtio_mb(vq->weak_barriers);
788 	return (u16)last_used_idx != virtio16_to_cpu(_vq->vdev, vq->vring.used->idx);
789 }
790 EXPORT_SYMBOL_GPL(virtqueue_poll);
791 
792 /**
793  * virtqueue_enable_cb - restart callbacks after disable_cb.
794  * @vq: the struct virtqueue we're talking about.
795  *
796  * This re-enables callbacks; it returns "false" if there are pending
797  * buffers in the queue, to detect a possible race between the driver
798  * checking for more work, and enabling callbacks.
799  *
800  * Caller must ensure we don't call this with other virtqueue
801  * operations at the same time (except where noted).
802  */
virtqueue_enable_cb(struct virtqueue * _vq)803 bool virtqueue_enable_cb(struct virtqueue *_vq)
804 {
805 	unsigned last_used_idx = virtqueue_enable_cb_prepare(_vq);
806 	return !virtqueue_poll(_vq, last_used_idx);
807 }
808 EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
809 
810 /**
811  * virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
812  * @vq: the struct virtqueue we're talking about.
813  *
814  * This re-enables callbacks but hints to the other side to delay
815  * interrupts until most of the available buffers have been processed;
816  * it returns "false" if there are many pending buffers in the queue,
817  * to detect a possible race between the driver checking for more work,
818  * and enabling callbacks.
819  *
820  * Caller must ensure we don't call this with other virtqueue
821  * operations at the same time (except where noted).
822  */
virtqueue_enable_cb_delayed(struct virtqueue * _vq)823 bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
824 {
825 	struct vring_virtqueue *vq = to_vvq(_vq);
826 	u16 bufs;
827 
828 	START_USE(vq);
829 
830 	/* We optimistically turn back on interrupts, then check if there was
831 	 * more to do. */
832 	/* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
833 	 * either clear the flags bit or point the event index at the next
834 	 * entry. Always update the event index to keep code simple. */
835 	if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
836 		vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
837 		if (!vq->event)
838 			vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
839 	}
840 	/* TODO: tune this threshold */
841 	bufs = (u16)(vq->avail_idx_shadow - vq->last_used_idx) * 3 / 4;
842 	vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, vq->last_used_idx + bufs);
843 	virtio_mb(vq->weak_barriers);
844 	if (unlikely((u16)(virtio16_to_cpu(_vq->vdev, vq->vring.used->idx) - vq->last_used_idx) > bufs)) {
845 		END_USE(vq);
846 		return false;
847 	}
848 
849 	END_USE(vq);
850 	return true;
851 }
852 EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
853 
854 /**
855  * virtqueue_detach_unused_buf - detach first unused buffer
856  * @vq: the struct virtqueue we're talking about.
857  *
858  * Returns NULL or the "data" token handed to virtqueue_add_*().
859  * This is not valid on an active queue; it is useful only for device
860  * shutdown.
861  */
virtqueue_detach_unused_buf(struct virtqueue * _vq)862 void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
863 {
864 	struct vring_virtqueue *vq = to_vvq(_vq);
865 	unsigned int i;
866 	void *buf;
867 
868 	START_USE(vq);
869 
870 	for (i = 0; i < vq->vring.num; i++) {
871 		if (!vq->desc_state[i].data)
872 			continue;
873 		/* detach_buf clears data, so grab it now. */
874 		buf = vq->desc_state[i].data;
875 		detach_buf(vq, i);
876 		vq->avail_idx_shadow--;
877 		vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
878 		END_USE(vq);
879 		return buf;
880 	}
881 	/* That should have freed everything. */
882 	BUG_ON(vq->vq.num_free != vq->vring.num);
883 
884 	END_USE(vq);
885 	return NULL;
886 }
887 EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
888 
vring_interrupt(int irq,void * _vq)889 irqreturn_t vring_interrupt(int irq, void *_vq)
890 {
891 	struct vring_virtqueue *vq = to_vvq(_vq);
892 
893 	if (!more_used(vq)) {
894 		pr_debug("virtqueue interrupt with no work for %p\n", vq);
895 		return IRQ_NONE;
896 	}
897 
898 	if (unlikely(vq->broken))
899 		return IRQ_HANDLED;
900 
901 	pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
902 	if (vq->vq.callback)
903 		vq->vq.callback(&vq->vq);
904 
905 	return IRQ_HANDLED;
906 }
907 EXPORT_SYMBOL_GPL(vring_interrupt);
908 
vring_new_virtqueue(unsigned int index,unsigned int num,unsigned int vring_align,struct virtio_device * vdev,bool weak_barriers,void * pages,bool (* notify)(struct virtqueue *),void (* callback)(struct virtqueue *),const char * name)909 struct virtqueue *vring_new_virtqueue(unsigned int index,
910 				      unsigned int num,
911 				      unsigned int vring_align,
912 				      struct virtio_device *vdev,
913 				      bool weak_barriers,
914 				      void *pages,
915 				      bool (*notify)(struct virtqueue *),
916 				      void (*callback)(struct virtqueue *),
917 				      const char *name)
918 {
919 	struct vring_virtqueue *vq;
920 	unsigned int i;
921 
922 	/* We assume num is a power of 2. */
923 	if (num & (num - 1)) {
924 		dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
925 		return NULL;
926 	}
927 
928 	vq = kmalloc(sizeof(*vq) + num * sizeof(struct vring_desc_state),
929 		     GFP_KERNEL);
930 	if (!vq)
931 		return NULL;
932 
933 	vring_init(&vq->vring, num, pages, vring_align);
934 	vq->vq.callback = callback;
935 	vq->vq.vdev = vdev;
936 	vq->vq.name = name;
937 	vq->vq.num_free = num;
938 	vq->vq.index = index;
939 	vq->notify = notify;
940 	vq->weak_barriers = weak_barriers;
941 	vq->broken = false;
942 	vq->last_used_idx = 0;
943 	vq->avail_flags_shadow = 0;
944 	vq->avail_idx_shadow = 0;
945 	vq->num_added = 0;
946 	list_add_tail(&vq->vq.list, &vdev->vqs);
947 #ifdef DEBUG
948 	vq->in_use = false;
949 	vq->last_add_time_valid = false;
950 #endif
951 
952 	vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
953 	vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
954 
955 	/* No callback?  Tell other side not to bother us. */
956 	if (!callback) {
957 		vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
958 		if (!vq->event)
959 			vq->vring.avail->flags = cpu_to_virtio16(vdev, vq->avail_flags_shadow);
960 	}
961 
962 	/* Put everything in free lists. */
963 	vq->free_head = 0;
964 	for (i = 0; i < num-1; i++)
965 		vq->vring.desc[i].next = cpu_to_virtio16(vdev, i + 1);
966 	memset(vq->desc_state, 0, num * sizeof(struct vring_desc_state));
967 
968 	return &vq->vq;
969 }
970 EXPORT_SYMBOL_GPL(vring_new_virtqueue);
971 
vring_del_virtqueue(struct virtqueue * vq)972 void vring_del_virtqueue(struct virtqueue *vq)
973 {
974 	list_del(&vq->list);
975 	kfree(to_vvq(vq));
976 }
977 EXPORT_SYMBOL_GPL(vring_del_virtqueue);
978 
979 /* Manipulates transport-specific feature bits. */
vring_transport_features(struct virtio_device * vdev)980 void vring_transport_features(struct virtio_device *vdev)
981 {
982 	unsigned int i;
983 
984 	for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
985 		switch (i) {
986 		case VIRTIO_RING_F_INDIRECT_DESC:
987 			break;
988 		case VIRTIO_RING_F_EVENT_IDX:
989 			break;
990 		case VIRTIO_F_VERSION_1:
991 			break;
992 		case VIRTIO_F_IOMMU_PLATFORM:
993 			break;
994 		default:
995 			/* We don't understand this bit. */
996 			__virtio_clear_bit(vdev, i);
997 		}
998 	}
999 }
1000 EXPORT_SYMBOL_GPL(vring_transport_features);
1001 
1002 /**
1003  * virtqueue_get_vring_size - return the size of the virtqueue's vring
1004  * @vq: the struct virtqueue containing the vring of interest.
1005  *
1006  * Returns the size of the vring.  This is mainly used for boasting to
1007  * userspace.  Unlike other operations, this need not be serialized.
1008  */
virtqueue_get_vring_size(struct virtqueue * _vq)1009 unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
1010 {
1011 
1012 	struct vring_virtqueue *vq = to_vvq(_vq);
1013 
1014 	return vq->vring.num;
1015 }
1016 EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
1017 
virtqueue_is_broken(struct virtqueue * _vq)1018 bool virtqueue_is_broken(struct virtqueue *_vq)
1019 {
1020 	struct vring_virtqueue *vq = to_vvq(_vq);
1021 
1022 	return READ_ONCE(vq->broken);
1023 }
1024 EXPORT_SYMBOL_GPL(virtqueue_is_broken);
1025 
1026 /*
1027  * This should prevent the device from being used, allowing drivers to
1028  * recover.  You may need to grab appropriate locks to flush.
1029  */
virtio_break_device(struct virtio_device * dev)1030 void virtio_break_device(struct virtio_device *dev)
1031 {
1032 	struct virtqueue *_vq;
1033 
1034 	list_for_each_entry(_vq, &dev->vqs, list) {
1035 		struct vring_virtqueue *vq = to_vvq(_vq);
1036 
1037 		/* Pairs with READ_ONCE() in virtqueue_is_broken(). */
1038 		WRITE_ONCE(vq->broken, true);
1039 	}
1040 }
1041 EXPORT_SYMBOL_GPL(virtio_break_device);
1042 
virtqueue_get_avail(struct virtqueue * _vq)1043 void *virtqueue_get_avail(struct virtqueue *_vq)
1044 {
1045 	struct vring_virtqueue *vq = to_vvq(_vq);
1046 
1047 	return vq->vring.avail;
1048 }
1049 EXPORT_SYMBOL_GPL(virtqueue_get_avail);
1050 
virtqueue_get_used(struct virtqueue * _vq)1051 void *virtqueue_get_used(struct virtqueue *_vq)
1052 {
1053 	struct vring_virtqueue *vq = to_vvq(_vq);
1054 
1055 	return vq->vring.used;
1056 }
1057 EXPORT_SYMBOL_GPL(virtqueue_get_used);
1058 
1059 MODULE_LICENSE("GPL");
1060