virtio_ring.c 24.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* Virtio ring implementation.
 *
 *  Copyright 2007 Rusty Russell IBM Corporation
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
#include <linux/virtio.h>
#include <linux/virtio_ring.h>
21
#include <linux/virtio_config.h>
22
#include <linux/device.h>
23
#include <linux/slab.h>
24
#include <linux/module.h>
25
#include <linux/hrtimer.h>
26
#include <linux/kmemleak.h>
27 28 29

#ifdef DEBUG
/* For development, we want to crash whenever the ring is screwed. */
30 31 32 33 34 35
#define BAD_RING(_vq, fmt, args...)				\
	do {							\
		dev_err(&(_vq)->vq.vdev->dev,			\
			"%s:"fmt, (_vq)->vq.name, ##args);	\
		BUG();						\
	} while (0)
36 37 38 39
/* Caller is supposed to guarantee no reentry. */
#define START_USE(_vq)						\
	do {							\
		if ((_vq)->in_use)				\
40 41
			panic("%s:in_use = %i\n",		\
			      (_vq)->vq.name, (_vq)->in_use);	\
42
		(_vq)->in_use = __LINE__;			\
43
	} while (0)
44
#define END_USE(_vq) \
45
	do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
46
#else
47 48 49 50 51 52
#define BAD_RING(_vq, fmt, args...)				\
	do {							\
		dev_err(&_vq->vq.vdev->dev,			\
			"%s:"fmt, (_vq)->vq.name, ##args);	\
		(_vq)->broken = true;				\
	} while (0)
53 54 55 56
#define START_USE(vq)
#define END_USE(vq)
#endif

57
struct vring_virtqueue {
58 59 60 61 62
	struct virtqueue vq;

	/* Actual memory layout for this queue */
	struct vring vring;

63 64 65
	/* Can we use weak barriers? */
	bool weak_barriers;

66 67 68
	/* Other side has made a mess, don't try any more. */
	bool broken;

69 70 71
	/* Host supports indirect buffers */
	bool indirect;

72 73 74
	/* Host publishes avail event idx */
	bool event;

75 76 77 78 79 80
	/* Head of free buffer list. */
	unsigned int free_head;
	/* Number we've added since last sync. */
	unsigned int num_added;

	/* Last used index we've seen. */
A
Anthony Liguori 已提交
81
	u16 last_used_idx;
82

83 84 85 86 87 88
	/* Last written value to avail->flags */
	u16 avail_flags_shadow;

	/* Last written value to avail->idx in guest byte order */
	u16 avail_idx_shadow;

89
	/* How to notify other side. FIXME: commonalize hcalls! */
90
	bool (*notify)(struct virtqueue *vq);
91 92 93 94

#ifdef DEBUG
	/* They're supposed to lock for us. */
	unsigned int in_use;
95 96 97 98

	/* Figure out if their kicks are too delayed. */
	bool last_add_time_valid;
	ktime_t last_add_time;
99 100 101 102 103 104 105 106
#endif

	/* Tokens for callbacks. */
	void *data[];
};

#define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
/*
 * The interaction between virtio and a possible IOMMU is a mess.
 *
 * On most systems with virtio, physical addresses match bus addresses,
 * and it doesn't particularly matter whether we use the DMA API.
 *
 * On some systems, including Xen and any system with a physical device
 * that speaks virtio behind a physical IOMMU, we must use the DMA API
 * for virtio DMA to work at all.
 *
 * On other systems, including SPARC and PPC64, virtio-pci devices are
 * enumerated as though they are behind an IOMMU, but the virtio host
 * ignores the IOMMU, so we must either pretend that the IOMMU isn't
 * there or somehow map everything as the identity.
 *
 * For the time being, we preserve historic behavior and bypass the DMA
 * API.
 */

static bool vring_use_dma_api(struct virtio_device *vdev)
{
	return false;
}

131 132
static struct vring_desc *alloc_indirect(struct virtqueue *_vq,
					 unsigned int total_sg, gfp_t gfp)
133 134
{
	struct vring_desc *desc;
135
	unsigned int i;
136

137 138 139 140 141
	/*
	 * We require lowmem mappings for the descriptors because
	 * otherwise virt_to_phys will give us bogus addresses in the
	 * virtqueue.
	 */
142
	gfp &= ~__GFP_HIGHMEM;
143

144
	desc = kmalloc(total_sg * sizeof(struct vring_desc), gfp);
145
	if (!desc)
146
		return NULL;
147

148
	for (i = 0; i < total_sg; i++)
149
		desc[i].next = cpu_to_virtio16(_vq->vdev, i + 1);
150
	return desc;
151 152
}

153 154
static inline int virtqueue_add(struct virtqueue *_vq,
				struct scatterlist *sgs[],
155
				unsigned int total_sg,
156 157 158 159
				unsigned int out_sgs,
				unsigned int in_sgs,
				void *data,
				gfp_t gfp)
160 161
{
	struct vring_virtqueue *vq = to_vvq(_vq);
162
	struct scatterlist *sg;
163 164
	struct vring_desc *desc;
	unsigned int i, n, avail, descs_used, uninitialized_var(prev);
M
Michael S. Tsirkin 已提交
165
	int head;
166
	bool indirect;
167

168 169
	START_USE(vq);

170
	BUG_ON(data == NULL);
171

172 173 174 175 176
	if (unlikely(vq->broken)) {
		END_USE(vq);
		return -EIO;
	}

177 178 179 180 181 182 183 184 185 186 187 188 189
#ifdef DEBUG
	{
		ktime_t now = ktime_get();

		/* No kick or get, with .1 second between?  Warn. */
		if (vq->last_add_time_valid)
			WARN_ON(ktime_to_ms(ktime_sub(now, vq->last_add_time))
					    > 100);
		vq->last_add_time = now;
		vq->last_add_time_valid = true;
	}
#endif

190 191 192 193 194
	BUG_ON(total_sg > vq->vring.num);
	BUG_ON(total_sg == 0);

	head = vq->free_head;

195 196
	/* If the host supports indirect descriptor tables, and we have multiple
	 * buffers, then go indirect. FIXME: tune this threshold */
197
	if (vq->indirect && total_sg > 1 && vq->vq.num_free)
198
		desc = alloc_indirect(_vq, total_sg, gfp);
199 200 201 202 203
	else
		desc = NULL;

	if (desc) {
		/* Use a single buffer which doesn't continue */
204 205
		vq->vring.desc[head].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_INDIRECT);
		vq->vring.desc[head].addr = cpu_to_virtio64(_vq->vdev, virt_to_phys(desc));
206 207
		/* avoid kmemleak false positive (hidden by virt_to_phys) */
		kmemleak_ignore(desc);
208
		vq->vring.desc[head].len = cpu_to_virtio32(_vq->vdev, total_sg * sizeof(struct vring_desc));
209 210 211 212 213 214 215 216 217 218

		/* Set up rest to use this indirect table. */
		i = 0;
		descs_used = 1;
		indirect = true;
	} else {
		desc = vq->vring.desc;
		i = head;
		descs_used = total_sg;
		indirect = false;
219 220
	}

221
	if (vq->vq.num_free < descs_used) {
222
		pr_debug("Can't add buf len %i - avail = %i\n",
223
			 descs_used, vq->vq.num_free);
224 225 226
		/* FIXME: for historical reasons, we force a notify here if
		 * there are outgoing parts to the buffer.  Presumably the
		 * host should service the ring ASAP. */
227
		if (out_sgs)
228
			vq->notify(&vq->vq);
229 230 231 232 233
		END_USE(vq);
		return -ENOSPC;
	}

	/* We're about to use some buffers from the free list. */
234
	vq->vq.num_free -= descs_used;
235 236

	for (n = 0; n < out_sgs; n++) {
237
		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
238 239 240
			desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT);
			desc[i].addr = cpu_to_virtio64(_vq->vdev, sg_phys(sg));
			desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
241
			prev = i;
242
			i = virtio16_to_cpu(_vq->vdev, desc[i].next);
243
		}
244
	}
245
	for (; n < (out_sgs + in_sgs); n++) {
246
		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
247 248 249
			desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT | VRING_DESC_F_WRITE);
			desc[i].addr = cpu_to_virtio64(_vq->vdev, sg_phys(sg));
			desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
250
			prev = i;
251
			i = virtio16_to_cpu(_vq->vdev, desc[i].next);
252
		}
253 254
	}
	/* Last one doesn't continue. */
255
	desc[prev].flags &= cpu_to_virtio16(_vq->vdev, ~VRING_DESC_F_NEXT);
256 257

	/* Update free pointer */
258
	if (indirect)
259
		vq->free_head = virtio16_to_cpu(_vq->vdev, vq->vring.desc[head].next);
260 261
	else
		vq->free_head = i;
262 263 264 265 266

	/* Set token. */
	vq->data[head] = data;

	/* Put entry in available array (but don't update avail->idx until they
R
Rusty Russell 已提交
267
	 * do sync). */
268
	avail = vq->avail_idx_shadow & (vq->vring.num - 1);
269
	vq->vring.avail->ring[avail] = cpu_to_virtio16(_vq->vdev, head);
270

271 272
	/* Descriptors and available array need to be set before we expose the
	 * new available array entries. */
273
	virtio_wmb(vq->weak_barriers);
274 275
	vq->avail_idx_shadow++;
	vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
276 277
	vq->num_added++;

278 279 280
	pr_debug("Added buffer head %i to %p\n", head, vq);
	END_USE(vq);

281 282 283 284 285
	/* This is very unlikely, but theoretically possible.  Kick
	 * just in case. */
	if (unlikely(vq->num_added == (1 << 16) - 1))
		virtqueue_kick(_vq);

286
	return 0;
287
}
288 289 290 291 292 293 294 295 296 297 298 299 300

/**
 * virtqueue_add_sgs - expose buffers to other end
 * @vq: the struct virtqueue we're talking about.
 * @sgs: array of terminated scatterlists.
 * @out_num: the number of scatterlists readable by other side
 * @in_num: the number of scatterlists which are writable (after readable ones)
 * @data: the token identifying the buffer.
 * @gfp: how to do memory allocations (if necessary).
 *
 * Caller must ensure we don't call this with other virtqueue operations
 * at the same time (except where noted).
 *
301
 * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
302 303 304 305 306 307 308 309
 */
int virtqueue_add_sgs(struct virtqueue *_vq,
		      struct scatterlist *sgs[],
		      unsigned int out_sgs,
		      unsigned int in_sgs,
		      void *data,
		      gfp_t gfp)
{
310
	unsigned int i, total_sg = 0;
311 312

	/* Count them first. */
313
	for (i = 0; i < out_sgs + in_sgs; i++) {
314 315
		struct scatterlist *sg;
		for (sg = sgs[i]; sg; sg = sg_next(sg))
316
			total_sg++;
317
	}
318
	return virtqueue_add(_vq, sgs, total_sg, out_sgs, in_sgs, data, gfp);
319 320 321
}
EXPORT_SYMBOL_GPL(virtqueue_add_sgs);

322 323 324
/**
 * virtqueue_add_outbuf - expose output buffers to other end
 * @vq: the struct virtqueue we're talking about.
325 326
 * @sg: scatterlist (must be well-formed and terminated!)
 * @num: the number of entries in @sg readable by other side
327 328 329 330 331 332
 * @data: the token identifying the buffer.
 * @gfp: how to do memory allocations (if necessary).
 *
 * Caller must ensure we don't call this with other virtqueue operations
 * at the same time (except where noted).
 *
333
 * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
334 335
 */
int virtqueue_add_outbuf(struct virtqueue *vq,
336
			 struct scatterlist *sg, unsigned int num,
337 338 339
			 void *data,
			 gfp_t gfp)
{
340
	return virtqueue_add(vq, &sg, num, 1, 0, data, gfp);
341 342 343 344 345 346
}
EXPORT_SYMBOL_GPL(virtqueue_add_outbuf);

/**
 * virtqueue_add_inbuf - expose input buffers to other end
 * @vq: the struct virtqueue we're talking about.
347 348
 * @sg: scatterlist (must be well-formed and terminated!)
 * @num: the number of entries in @sg writable by other side
349 350 351 352 353 354
 * @data: the token identifying the buffer.
 * @gfp: how to do memory allocations (if necessary).
 *
 * Caller must ensure we don't call this with other virtqueue operations
 * at the same time (except where noted).
 *
355
 * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
356 357
 */
int virtqueue_add_inbuf(struct virtqueue *vq,
358
			struct scatterlist *sg, unsigned int num,
359 360 361
			void *data,
			gfp_t gfp)
{
362
	return virtqueue_add(vq, &sg, num, 0, 1, data, gfp);
363 364 365
}
EXPORT_SYMBOL_GPL(virtqueue_add_inbuf);

366
/**
367
 * virtqueue_kick_prepare - first half of split virtqueue_kick call.
368 369
 * @vq: the struct virtqueue
 *
370 371 372
 * Instead of virtqueue_kick(), you can do:
 *	if (virtqueue_kick_prepare(vq))
 *		virtqueue_notify(vq);
373
 *
374 375
 * This is sometimes useful because the virtqueue_kick_prepare() needs
 * to be serialized, but the actual virtqueue_notify() call does not.
376
 */
377
bool virtqueue_kick_prepare(struct virtqueue *_vq)
378 379
{
	struct vring_virtqueue *vq = to_vvq(_vq);
380
	u16 new, old;
381 382
	bool needs_kick;

383
	START_USE(vq);
384 385
	/* We need to expose available array entries before checking avail
	 * event. */
386
	virtio_mb(vq->weak_barriers);
387

388 389
	old = vq->avail_idx_shadow - vq->num_added;
	new = vq->avail_idx_shadow;
390 391
	vq->num_added = 0;

392 393 394 395 396 397 398 399
#ifdef DEBUG
	if (vq->last_add_time_valid) {
		WARN_ON(ktime_to_ms(ktime_sub(ktime_get(),
					      vq->last_add_time)) > 100);
	}
	vq->last_add_time_valid = false;
#endif

400
	if (vq->event) {
401
		needs_kick = vring_need_event(virtio16_to_cpu(_vq->vdev, vring_avail_event(&vq->vring)),
402 403
					      new, old);
	} else {
404
		needs_kick = !(vq->vring.used->flags & cpu_to_virtio16(_vq->vdev, VRING_USED_F_NO_NOTIFY));
405
	}
406
	END_USE(vq);
407 408 409 410 411 412 413 414 415
	return needs_kick;
}
EXPORT_SYMBOL_GPL(virtqueue_kick_prepare);

/**
 * virtqueue_notify - second half of split virtqueue_kick call.
 * @vq: the struct virtqueue
 *
 * This does not need to be serialized.
416 417
 *
 * Returns false if host notify failed or queue is broken, otherwise true.
418
 */
419
bool virtqueue_notify(struct virtqueue *_vq)
420 421 422
{
	struct vring_virtqueue *vq = to_vvq(_vq);

423 424 425
	if (unlikely(vq->broken))
		return false;

426
	/* Prod other side to tell it about changes. */
427
	if (!vq->notify(_vq)) {
428 429 430 431
		vq->broken = true;
		return false;
	}
	return true;
432 433 434 435 436 437 438
}
EXPORT_SYMBOL_GPL(virtqueue_notify);

/**
 * virtqueue_kick - update after add_buf
 * @vq: the struct virtqueue
 *
439
 * After one or more virtqueue_add_* calls, invoke this to kick
440 441 442 443
 * the other side.
 *
 * Caller must ensure we don't call this with other virtqueue
 * operations at the same time (except where noted).
444 445
 *
 * Returns false if kick failed, otherwise true.
446
 */
447
bool virtqueue_kick(struct virtqueue *vq)
448 449
{
	if (virtqueue_kick_prepare(vq))
450 451
		return virtqueue_notify(vq);
	return true;
452
}
453
EXPORT_SYMBOL_GPL(virtqueue_kick);
454 455 456 457 458 459 460 461 462 463

static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
{
	unsigned int i;

	/* Clear data ptr. */
	vq->data[head] = NULL;

	/* Put back on free list: find end */
	i = head;
464 465

	/* Free the indirect table */
466 467
	if (vq->vring.desc[i].flags & cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_INDIRECT))
		kfree(phys_to_virt(virtio64_to_cpu(vq->vq.vdev, vq->vring.desc[i].addr)));
468

469 470
	while (vq->vring.desc[i].flags & cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_NEXT)) {
		i = virtio16_to_cpu(vq->vq.vdev, vq->vring.desc[i].next);
471
		vq->vq.num_free++;
472 473
	}

474
	vq->vring.desc[i].next = cpu_to_virtio16(vq->vq.vdev, vq->free_head);
475 476
	vq->free_head = head;
	/* Plus final descriptor */
477
	vq->vq.num_free++;
478 479 480 481
}

static inline bool more_used(const struct vring_virtqueue *vq)
{
482
	return vq->last_used_idx != virtio16_to_cpu(vq->vq.vdev, vq->vring.used->idx);
483 484
}

485 486 487 488 489 490 491 492 493 494 495 496 497 498
/**
 * virtqueue_get_buf - get the next used buffer
 * @vq: the struct virtqueue we're talking about.
 * @len: the length written into the buffer
 *
 * If the driver wrote data into the buffer, @len will be set to the
 * amount written.  This means you don't need to clear the buffer
 * beforehand to ensure there's no data leakage in the case of short
 * writes.
 *
 * Caller must ensure we don't call this with other virtqueue
 * operations at the same time (except where noted).
 *
 * Returns NULL if there are no used buffers, or the "data" token
499
 * handed to virtqueue_add_*().
500
 */
501
void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
502 503 504 505
{
	struct vring_virtqueue *vq = to_vvq(_vq);
	void *ret;
	unsigned int i;
R
Rusty Russell 已提交
506
	u16 last_used;
507 508 509

	START_USE(vq);

510 511 512 513 514
	if (unlikely(vq->broken)) {
		END_USE(vq);
		return NULL;
	}

515 516 517 518 519 520
	if (!more_used(vq)) {
		pr_debug("No more buffers in queue\n");
		END_USE(vq);
		return NULL;
	}

521
	/* Only get used array entries after they have been exposed by host. */
522
	virtio_rmb(vq->weak_barriers);
523

R
Rusty Russell 已提交
524
	last_used = (vq->last_used_idx & (vq->vring.num - 1));
525 526
	i = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].id);
	*len = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].len);
527 528 529 530 531 532 533 534 535 536 537 538 539 540

	if (unlikely(i >= vq->vring.num)) {
		BAD_RING(vq, "id %u out of range\n", i);
		return NULL;
	}
	if (unlikely(!vq->data[i])) {
		BAD_RING(vq, "id %u is not a head!\n", i);
		return NULL;
	}

	/* detach_buf clears data, so grab it now. */
	ret = vq->data[i];
	detach_buf(vq, i);
	vq->last_used_idx++;
541 542 543
	/* If we expect an interrupt for the next entry, tell host
	 * by writing event index and flush out the write before
	 * the read in the next get_buf call. */
544 545 546 547
	if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT))
		virtio_store_mb(vq->weak_barriers,
				&vring_used_event(&vq->vring),
				cpu_to_virtio16(_vq->vdev, vq->last_used_idx));
548

549 550 551 552
#ifdef DEBUG
	vq->last_add_time_valid = false;
#endif

553 554 555
	END_USE(vq);
	return ret;
}
556
EXPORT_SYMBOL_GPL(virtqueue_get_buf);
557

558 559 560 561 562 563 564 565 566
/**
 * virtqueue_disable_cb - disable callbacks
 * @vq: the struct virtqueue we're talking about.
 *
 * Note that this is not necessarily synchronous, hence unreliable and only
 * useful as an optimization.
 *
 * Unlike other operations, this need not be serialized.
 */
567
void virtqueue_disable_cb(struct virtqueue *_vq)
568 569 570
{
	struct vring_virtqueue *vq = to_vvq(_vq);

571 572 573 574 575
	if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT)) {
		vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
		vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
	}

576
}
577
EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
578

579
/**
580
 * virtqueue_enable_cb_prepare - restart callbacks after disable_cb
581 582
 * @vq: the struct virtqueue we're talking about.
 *
583 584 585 586
 * This re-enables callbacks; it returns current queue state
 * in an opaque unsigned value. This value should be later tested by
 * virtqueue_poll, to detect a possible race between the driver checking for
 * more work, and enabling callbacks.
587 588 589 590
 *
 * Caller must ensure we don't call this with other virtqueue
 * operations at the same time (except where noted).
 */
591
unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
592 593
{
	struct vring_virtqueue *vq = to_vvq(_vq);
594
	u16 last_used_idx;
595 596 597 598 599

	START_USE(vq);

	/* We optimistically turn back on interrupts, then check if there was
	 * more to do. */
600 601 602
	/* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
	 * either clear the flags bit or point the event index at the next
	 * entry. Always do both to keep code simple. */
603 604 605 606
	if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
		vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
		vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
	}
607
	vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, last_used_idx = vq->last_used_idx);
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
	END_USE(vq);
	return last_used_idx;
}
EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);

/**
 * virtqueue_poll - query pending used buffers
 * @vq: the struct virtqueue we're talking about.
 * @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
 *
 * Returns "true" if there are pending used buffers in the queue.
 *
 * This does not need to be serialized.
 */
bool virtqueue_poll(struct virtqueue *_vq, unsigned last_used_idx)
{
	struct vring_virtqueue *vq = to_vvq(_vq);

626
	virtio_mb(vq->weak_barriers);
627
	return (u16)last_used_idx != virtio16_to_cpu(_vq->vdev, vq->vring.used->idx);
628 629
}
EXPORT_SYMBOL_GPL(virtqueue_poll);
630

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
/**
 * virtqueue_enable_cb - restart callbacks after disable_cb.
 * @vq: the struct virtqueue we're talking about.
 *
 * This re-enables callbacks; it returns "false" if there are pending
 * buffers in the queue, to detect a possible race between the driver
 * checking for more work, and enabling callbacks.
 *
 * Caller must ensure we don't call this with other virtqueue
 * operations at the same time (except where noted).
 */
bool virtqueue_enable_cb(struct virtqueue *_vq)
{
	unsigned last_used_idx = virtqueue_enable_cb_prepare(_vq);
	return !virtqueue_poll(_vq, last_used_idx);
646
}
647
EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
648

649 650 651 652 653 654 655 656 657 658 659 660 661
/**
 * virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
 * @vq: the struct virtqueue we're talking about.
 *
 * This re-enables callbacks but hints to the other side to delay
 * interrupts until most of the available buffers have been processed;
 * it returns "false" if there are many pending buffers in the queue,
 * to detect a possible race between the driver checking for more work,
 * and enabling callbacks.
 *
 * Caller must ensure we don't call this with other virtqueue
 * operations at the same time (except where noted).
 */
662 663 664 665 666 667 668 669 670 671 672 673
bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
{
	struct vring_virtqueue *vq = to_vvq(_vq);
	u16 bufs;

	START_USE(vq);

	/* We optimistically turn back on interrupts, then check if there was
	 * more to do. */
	/* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
	 * either clear the flags bit or point the event index at the next
	 * entry. Always do both to keep code simple. */
674 675 676 677
	if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
		vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
		vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
	}
678
	/* TODO: tune this threshold */
679
	bufs = (u16)(vq->avail_idx_shadow - vq->last_used_idx) * 3 / 4;
680 681 682 683 684

	virtio_store_mb(vq->weak_barriers,
			&vring_used_event(&vq->vring),
			cpu_to_virtio16(_vq->vdev, vq->last_used_idx + bufs));

685
	if (unlikely((u16)(virtio16_to_cpu(_vq->vdev, vq->vring.used->idx) - vq->last_used_idx) > bufs)) {
686 687 688 689 690 691 692 693 694
		END_USE(vq);
		return false;
	}

	END_USE(vq);
	return true;
}
EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);

695 696 697 698
/**
 * virtqueue_detach_unused_buf - detach first unused buffer
 * @vq: the struct virtqueue we're talking about.
 *
699
 * Returns NULL or the "data" token handed to virtqueue_add_*().
700 701 702
 * This is not valid on an active queue; it is useful only for device
 * shutdown.
 */
703
void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
704 705 706 707 708 709 710 711 712 713 714 715 716
{
	struct vring_virtqueue *vq = to_vvq(_vq);
	unsigned int i;
	void *buf;

	START_USE(vq);

	for (i = 0; i < vq->vring.num; i++) {
		if (!vq->data[i])
			continue;
		/* detach_buf clears data, so grab it now. */
		buf = vq->data[i];
		detach_buf(vq, i);
717 718
		vq->avail_idx_shadow--;
		vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
719 720 721 722
		END_USE(vq);
		return buf;
	}
	/* That should have freed everything. */
723
	BUG_ON(vq->vq.num_free != vq->vring.num);
724 725 726 727

	END_USE(vq);
	return NULL;
}
728
EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
729

730 731 732 733 734 735 736 737 738 739 740 741 742
irqreturn_t vring_interrupt(int irq, void *_vq)
{
	struct vring_virtqueue *vq = to_vvq(_vq);

	if (!more_used(vq)) {
		pr_debug("virtqueue interrupt with no work for %p\n", vq);
		return IRQ_NONE;
	}

	if (unlikely(vq->broken))
		return IRQ_HANDLED;

	pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
743 744
	if (vq->vq.callback)
		vq->vq.callback(&vq->vq);
745 746 747

	return IRQ_HANDLED;
}
748
EXPORT_SYMBOL_GPL(vring_interrupt);
749

750 751
struct virtqueue *vring_new_virtqueue(unsigned int index,
				      unsigned int num,
752
				      unsigned int vring_align,
753
				      struct virtio_device *vdev,
754
				      bool weak_barriers,
755
				      void *pages,
756
				      bool (*notify)(struct virtqueue *),
757 758
				      void (*callback)(struct virtqueue *),
				      const char *name)
759 760 761 762
{
	struct vring_virtqueue *vq;
	unsigned int i;

763 764 765 766 767 768
	/* We assume num is a power of 2. */
	if (num & (num - 1)) {
		dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
		return NULL;
	}

769 770 771 772
	vq = kmalloc(sizeof(*vq) + sizeof(void *)*num, GFP_KERNEL);
	if (!vq)
		return NULL;

773
	vring_init(&vq->vring, num, pages, vring_align);
774 775
	vq->vq.callback = callback;
	vq->vq.vdev = vdev;
776
	vq->vq.name = name;
777 778
	vq->vq.num_free = num;
	vq->vq.index = index;
779
	vq->notify = notify;
780
	vq->weak_barriers = weak_barriers;
781 782
	vq->broken = false;
	vq->last_used_idx = 0;
783 784
	vq->avail_flags_shadow = 0;
	vq->avail_idx_shadow = 0;
785
	vq->num_added = 0;
786
	list_add_tail(&vq->vq.list, &vdev->vqs);
787 788
#ifdef DEBUG
	vq->in_use = false;
789
	vq->last_add_time_valid = false;
790 791
#endif

792
	vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
793
	vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
794

795
	/* No callback?  Tell other side not to bother us. */
796 797 798 799
	if (!callback) {
		vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
		vq->vring.avail->flags = cpu_to_virtio16(vdev, vq->avail_flags_shadow);
	}
800 801 802

	/* Put everything in free lists. */
	vq->free_head = 0;
803
	for (i = 0; i < num-1; i++) {
804
		vq->vring.desc[i].next = cpu_to_virtio16(vdev, i + 1);
805 806 807
		vq->data[i] = NULL;
	}
	vq->data[i] = NULL;
808 809 810

	return &vq->vq;
}
811
EXPORT_SYMBOL_GPL(vring_new_virtqueue);
812 813 814

void vring_del_virtqueue(struct virtqueue *vq)
{
815
	list_del(&vq->list);
816 817
	kfree(to_vvq(vq));
}
818
EXPORT_SYMBOL_GPL(vring_del_virtqueue);
819

820 821 822 823 824 825 826
/* Manipulates transport-specific feature bits. */
void vring_transport_features(struct virtio_device *vdev)
{
	unsigned int i;

	for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
		switch (i) {
827 828
		case VIRTIO_RING_F_INDIRECT_DESC:
			break;
829 830
		case VIRTIO_RING_F_EVENT_IDX:
			break;
831 832
		case VIRTIO_F_VERSION_1:
			break;
833 834
		default:
			/* We don't understand this bit. */
835
			__virtio_clear_bit(vdev, i);
836 837 838 839 840
		}
	}
}
EXPORT_SYMBOL_GPL(vring_transport_features);

841 842 843 844 845 846 847
/**
 * virtqueue_get_vring_size - return the size of the virtqueue's vring
 * @vq: the struct virtqueue containing the vring of interest.
 *
 * Returns the size of the vring.  This is mainly used for boasting to
 * userspace.  Unlike other operations, this need not be serialized.
 */
R
Rick Jones 已提交
848 849 850 851 852 853 854 855 856
unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
{

	struct vring_virtqueue *vq = to_vvq(_vq);

	return vq->vring.num;
}
EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);

857 858 859 860 861 862 863 864
bool virtqueue_is_broken(struct virtqueue *_vq)
{
	struct vring_virtqueue *vq = to_vvq(_vq);

	return vq->broken;
}
EXPORT_SYMBOL_GPL(virtqueue_is_broken);

865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
/*
 * This should prevent the device from being used, allowing drivers to
 * recover.  You may need to grab appropriate locks to flush.
 */
void virtio_break_device(struct virtio_device *dev)
{
	struct virtqueue *_vq;

	list_for_each_entry(_vq, &dev->vqs, list) {
		struct vring_virtqueue *vq = to_vvq(_vq);
		vq->broken = true;
	}
}
EXPORT_SYMBOL_GPL(virtio_break_device);

880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
void *virtqueue_get_avail(struct virtqueue *_vq)
{
	struct vring_virtqueue *vq = to_vvq(_vq);

	return vq->vring.avail;
}
EXPORT_SYMBOL_GPL(virtqueue_get_avail);

void *virtqueue_get_used(struct virtqueue *_vq)
{
	struct vring_virtqueue *vq = to_vvq(_vq);

	return vq->vring.used;
}
EXPORT_SYMBOL_GPL(virtqueue_get_used);

896
MODULE_LICENSE("GPL");