virtio_ring.c 23.1 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 57 58 59 60 61 62 63
#define START_USE(vq)
#define END_USE(vq)
#endif

struct vring_virtqueue
{
	struct virtqueue vq;

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

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

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

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

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

76 77 78 79 80 81
	/* 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 已提交
82
	u16 last_used_idx;
83 84

	/* How to notify other side. FIXME: commonalize hcalls! */
85
	bool (*notify)(struct virtqueue *vq);
86 87 88 89

#ifdef DEBUG
	/* They're supposed to lock for us. */
	unsigned int in_use;
90 91 92 93

	/* Figure out if their kicks are too delayed. */
	bool last_add_time_valid;
	ktime_t last_add_time;
94 95 96 97 98 99 100 101
#endif

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

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

102 103
static struct vring_desc *alloc_indirect(struct virtqueue *_vq,
					 unsigned int total_sg, gfp_t gfp)
104 105
{
	struct vring_desc *desc;
106
	unsigned int i;
107

108 109 110 111 112 113 114
	/*
	 * We require lowmem mappings for the descriptors because
	 * otherwise virt_to_phys will give us bogus addresses in the
	 * virtqueue.
	 */
	gfp &= ~(__GFP_HIGHMEM | __GFP_HIGH);

115
	desc = kmalloc(total_sg * sizeof(struct vring_desc), gfp);
116
	if (!desc)
117
		return NULL;
118

119
	for (i = 0; i < total_sg; i++)
120
		desc[i].next = cpu_to_virtio16(_vq->vdev, i + 1);
121
	return desc;
122 123
}

124 125
static inline int virtqueue_add(struct virtqueue *_vq,
				struct scatterlist *sgs[],
126
				unsigned int total_sg,
127 128 129 130
				unsigned int out_sgs,
				unsigned int in_sgs,
				void *data,
				gfp_t gfp)
131 132
{
	struct vring_virtqueue *vq = to_vvq(_vq);
133
	struct scatterlist *sg;
134 135
	struct vring_desc *desc;
	unsigned int i, n, avail, descs_used, uninitialized_var(prev);
M
Michael S. Tsirkin 已提交
136
	int head;
137
	bool indirect;
138

139 140
	START_USE(vq);

141
	BUG_ON(data == NULL);
142

143 144 145 146 147
	if (unlikely(vq->broken)) {
		END_USE(vq);
		return -EIO;
	}

148 149 150 151 152 153 154 155 156 157 158 159 160
#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

161 162 163 164 165
	BUG_ON(total_sg > vq->vring.num);
	BUG_ON(total_sg == 0);

	head = vq->free_head;

166 167
	/* If the host supports indirect descriptor tables, and we have multiple
	 * buffers, then go indirect. FIXME: tune this threshold */
168
	if (vq->indirect && total_sg > 1 && vq->vq.num_free)
169
		desc = alloc_indirect(_vq, total_sg, gfp);
170 171 172 173 174
	else
		desc = NULL;

	if (desc) {
		/* Use a single buffer which doesn't continue */
175 176
		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));
177 178
		/* avoid kmemleak false positive (hidden by virt_to_phys) */
		kmemleak_ignore(desc);
179
		vq->vring.desc[head].len = cpu_to_virtio32(_vq->vdev, total_sg * sizeof(struct vring_desc));
180 181 182 183 184 185 186 187 188 189

		/* 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;
190 191
	}

192
	if (vq->vq.num_free < descs_used) {
193
		pr_debug("Can't add buf len %i - avail = %i\n",
194
			 descs_used, vq->vq.num_free);
195 196 197
		/* 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. */
198
		if (out_sgs)
199
			vq->notify(&vq->vq);
200 201 202 203 204
		END_USE(vq);
		return -ENOSPC;
	}

	/* We're about to use some buffers from the free list. */
205
	vq->vq.num_free -= descs_used;
206 207

	for (n = 0; n < out_sgs; n++) {
208
		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
209 210 211
			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);
212
			prev = i;
213
			i = virtio16_to_cpu(_vq->vdev, desc[i].next);
214
		}
215
	}
216
	for (; n < (out_sgs + in_sgs); n++) {
217
		for (sg = sgs[n]; sg; sg = sg_next(sg)) {
218 219 220
			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);
221
			prev = i;
222
			i = virtio16_to_cpu(_vq->vdev, desc[i].next);
223
		}
224 225
	}
	/* Last one doesn't continue. */
226
	desc[prev].flags &= cpu_to_virtio16(_vq->vdev, ~VRING_DESC_F_NEXT);
227 228

	/* Update free pointer */
229
	if (indirect)
230
		vq->free_head = virtio16_to_cpu(_vq->vdev, vq->vring.desc[head].next);
231 232
	else
		vq->free_head = i;
233 234 235 236 237

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

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

242 243
	/* Descriptors and available array need to be set before we expose the
	 * new available array entries. */
244
	virtio_wmb(vq->weak_barriers);
245
	vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, virtio16_to_cpu(_vq->vdev, vq->vring.avail->idx) + 1);
246 247 248 249 250 251 252
	vq->num_added++;

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

253 254
	pr_debug("Added buffer head %i to %p\n", head, vq);
	END_USE(vq);
255

256
	return 0;
257
}
258 259 260 261 262 263 264 265 266 267 268 269 270

/**
 * 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).
 *
271
 * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
272 273 274 275 276 277 278 279
 */
int virtqueue_add_sgs(struct virtqueue *_vq,
		      struct scatterlist *sgs[],
		      unsigned int out_sgs,
		      unsigned int in_sgs,
		      void *data,
		      gfp_t gfp)
{
280
	unsigned int i, total_sg = 0;
281 282

	/* Count them first. */
283
	for (i = 0; i < out_sgs + in_sgs; i++) {
284 285
		struct scatterlist *sg;
		for (sg = sgs[i]; sg; sg = sg_next(sg))
286
			total_sg++;
287
	}
288
	return virtqueue_add(_vq, sgs, total_sg, out_sgs, in_sgs, data, gfp);
289 290 291
}
EXPORT_SYMBOL_GPL(virtqueue_add_sgs);

292 293 294
/**
 * virtqueue_add_outbuf - expose output buffers to other end
 * @vq: the struct virtqueue we're talking about.
295 296
 * @sg: scatterlist (must be well-formed and terminated!)
 * @num: the number of entries in @sg readable by other side
297 298 299 300 301 302
 * @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).
 *
303
 * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
304 305
 */
int virtqueue_add_outbuf(struct virtqueue *vq,
306
			 struct scatterlist *sg, unsigned int num,
307 308 309
			 void *data,
			 gfp_t gfp)
{
310
	return virtqueue_add(vq, &sg, num, 1, 0, data, gfp);
311 312 313 314 315 316
}
EXPORT_SYMBOL_GPL(virtqueue_add_outbuf);

/**
 * virtqueue_add_inbuf - expose input buffers to other end
 * @vq: the struct virtqueue we're talking about.
317 318
 * @sg: scatterlist (must be well-formed and terminated!)
 * @num: the number of entries in @sg writable by other side
319 320 321 322 323 324
 * @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).
 *
325
 * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
326 327
 */
int virtqueue_add_inbuf(struct virtqueue *vq,
328
			struct scatterlist *sg, unsigned int num,
329 330 331
			void *data,
			gfp_t gfp)
{
332
	return virtqueue_add(vq, &sg, num, 0, 1, data, gfp);
333 334 335
}
EXPORT_SYMBOL_GPL(virtqueue_add_inbuf);

336
/**
337
 * virtqueue_kick_prepare - first half of split virtqueue_kick call.
338 339
 * @vq: the struct virtqueue
 *
340 341 342
 * Instead of virtqueue_kick(), you can do:
 *	if (virtqueue_kick_prepare(vq))
 *		virtqueue_notify(vq);
343
 *
344 345
 * This is sometimes useful because the virtqueue_kick_prepare() needs
 * to be serialized, but the actual virtqueue_notify() call does not.
346
 */
347
bool virtqueue_kick_prepare(struct virtqueue *_vq)
348 349
{
	struct vring_virtqueue *vq = to_vvq(_vq);
350
	u16 new, old;
351 352
	bool needs_kick;

353
	START_USE(vq);
354 355
	/* We need to expose available array entries before checking avail
	 * event. */
356
	virtio_mb(vq->weak_barriers);
357

358 359
	old = virtio16_to_cpu(_vq->vdev, vq->vring.avail->idx) - vq->num_added;
	new = virtio16_to_cpu(_vq->vdev, vq->vring.avail->idx);
360 361
	vq->num_added = 0;

362 363 364 365 366 367 368 369
#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

370
	if (vq->event) {
371
		needs_kick = vring_need_event(virtio16_to_cpu(_vq->vdev, vring_avail_event(&vq->vring)),
372 373
					      new, old);
	} else {
374
		needs_kick = !(vq->vring.used->flags & cpu_to_virtio16(_vq->vdev, VRING_USED_F_NO_NOTIFY));
375
	}
376
	END_USE(vq);
377 378 379 380 381 382 383 384 385
	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.
386 387
 *
 * Returns false if host notify failed or queue is broken, otherwise true.
388
 */
389
bool virtqueue_notify(struct virtqueue *_vq)
390 391 392
{
	struct vring_virtqueue *vq = to_vvq(_vq);

393 394 395
	if (unlikely(vq->broken))
		return false;

396
	/* Prod other side to tell it about changes. */
397
	if (!vq->notify(_vq)) {
398 399 400 401
		vq->broken = true;
		return false;
	}
	return true;
402 403 404 405 406 407 408
}
EXPORT_SYMBOL_GPL(virtqueue_notify);

/**
 * virtqueue_kick - update after add_buf
 * @vq: the struct virtqueue
 *
409
 * After one or more virtqueue_add_* calls, invoke this to kick
410 411 412 413
 * the other side.
 *
 * Caller must ensure we don't call this with other virtqueue
 * operations at the same time (except where noted).
414 415
 *
 * Returns false if kick failed, otherwise true.
416
 */
417
bool virtqueue_kick(struct virtqueue *vq)
418 419
{
	if (virtqueue_kick_prepare(vq))
420 421
		return virtqueue_notify(vq);
	return true;
422
}
423
EXPORT_SYMBOL_GPL(virtqueue_kick);
424 425 426 427 428 429 430 431 432 433

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;
434 435

	/* Free the indirect table */
436 437
	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)));
438

439 440
	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);
441
		vq->vq.num_free++;
442 443
	}

444
	vq->vring.desc[i].next = cpu_to_virtio16(vq->vq.vdev, vq->free_head);
445 446
	vq->free_head = head;
	/* Plus final descriptor */
447
	vq->vq.num_free++;
448 449 450 451
}

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

455 456 457 458 459 460 461 462 463 464 465 466 467 468
/**
 * 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
469
 * handed to virtqueue_add_*().
470
 */
471
void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
472 473 474 475
{
	struct vring_virtqueue *vq = to_vvq(_vq);
	void *ret;
	unsigned int i;
R
Rusty Russell 已提交
476
	u16 last_used;
477 478 479

	START_USE(vq);

480 481 482 483 484
	if (unlikely(vq->broken)) {
		END_USE(vq);
		return NULL;
	}

485 486 487 488 489 490
	if (!more_used(vq)) {
		pr_debug("No more buffers in queue\n");
		END_USE(vq);
		return NULL;
	}

491
	/* Only get used array entries after they have been exposed by host. */
492
	virtio_rmb(vq->weak_barriers);
493

R
Rusty Russell 已提交
494
	last_used = (vq->last_used_idx & (vq->vring.num - 1));
495 496
	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);
497 498 499 500 501 502 503 504 505 506 507 508 509 510

	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++;
511 512 513
	/* 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. */
514 515
	if (!(vq->vring.avail->flags & cpu_to_virtio16(_vq->vdev, VRING_AVAIL_F_NO_INTERRUPT))) {
		vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, vq->last_used_idx);
516
		virtio_mb(vq->weak_barriers);
517 518
	}

519 520 521 522
#ifdef DEBUG
	vq->last_add_time_valid = false;
#endif

523 524 525
	END_USE(vq);
	return ret;
}
526
EXPORT_SYMBOL_GPL(virtqueue_get_buf);
527

528 529 530 531 532 533 534 535 536
/**
 * 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.
 */
537
void virtqueue_disable_cb(struct virtqueue *_vq)
538 539 540
{
	struct vring_virtqueue *vq = to_vvq(_vq);

541
	vq->vring.avail->flags |= cpu_to_virtio16(_vq->vdev, VRING_AVAIL_F_NO_INTERRUPT);
542
}
543
EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
544

545
/**
546
 * virtqueue_enable_cb_prepare - restart callbacks after disable_cb
547 548
 * @vq: the struct virtqueue we're talking about.
 *
549 550 551 552
 * 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.
553 554 555 556
 *
 * Caller must ensure we don't call this with other virtqueue
 * operations at the same time (except where noted).
 */
557
unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
558 559
{
	struct vring_virtqueue *vq = to_vvq(_vq);
560
	u16 last_used_idx;
561 562 563 564 565

	START_USE(vq);

	/* We optimistically turn back on interrupts, then check if there was
	 * more to do. */
566 567 568
	/* 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. */
569 570
	vq->vring.avail->flags &= cpu_to_virtio16(_vq->vdev, ~VRING_AVAIL_F_NO_INTERRUPT);
	vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, last_used_idx = vq->last_used_idx);
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
	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);

589
	virtio_mb(vq->weak_barriers);
590
	return (u16)last_used_idx != virtio16_to_cpu(_vq->vdev, vq->vring.used->idx);
591 592
}
EXPORT_SYMBOL_GPL(virtqueue_poll);
593

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
/**
 * 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);
609
}
610
EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
611

612 613 614 615 616 617 618 619 620 621 622 623 624
/**
 * 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).
 */
625 626 627 628 629 630 631 632 633 634 635 636
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. */
637
	vq->vring.avail->flags &= cpu_to_virtio16(_vq->vdev, ~VRING_AVAIL_F_NO_INTERRUPT);
638
	/* TODO: tune this threshold */
639 640
	bufs = (u16)(virtio16_to_cpu(_vq->vdev, vq->vring.avail->idx) - vq->last_used_idx) * 3 / 4;
	vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, vq->last_used_idx + bufs);
641
	virtio_mb(vq->weak_barriers);
642
	if (unlikely((u16)(virtio16_to_cpu(_vq->vdev, vq->vring.used->idx) - vq->last_used_idx) > bufs)) {
643 644 645 646 647 648 649 650 651
		END_USE(vq);
		return false;
	}

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

652 653 654 655
/**
 * virtqueue_detach_unused_buf - detach first unused buffer
 * @vq: the struct virtqueue we're talking about.
 *
656
 * Returns NULL or the "data" token handed to virtqueue_add_*().
657 658 659
 * This is not valid on an active queue; it is useful only for device
 * shutdown.
 */
660
void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
661 662 663 664 665 666 667 668 669 670 671 672 673
{
	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);
674
		vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, virtio16_to_cpu(_vq->vdev, vq->vring.avail->idx) - 1);
675 676 677 678
		END_USE(vq);
		return buf;
	}
	/* That should have freed everything. */
679
	BUG_ON(vq->vq.num_free != vq->vring.num);
680 681 682 683

	END_USE(vq);
	return NULL;
}
684
EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
685

686 687 688 689 690 691 692 693 694 695 696 697 698
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);
699 700
	if (vq->vq.callback)
		vq->vq.callback(&vq->vq);
701 702 703

	return IRQ_HANDLED;
}
704
EXPORT_SYMBOL_GPL(vring_interrupt);
705

706 707
struct virtqueue *vring_new_virtqueue(unsigned int index,
				      unsigned int num,
708
				      unsigned int vring_align,
709
				      struct virtio_device *vdev,
710
				      bool weak_barriers,
711
				      void *pages,
712
				      bool (*notify)(struct virtqueue *),
713 714
				      void (*callback)(struct virtqueue *),
				      const char *name)
715 716 717 718
{
	struct vring_virtqueue *vq;
	unsigned int i;

719 720 721 722 723 724
	/* We assume num is a power of 2. */
	if (num & (num - 1)) {
		dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
		return NULL;
	}

725 726 727 728
	vq = kmalloc(sizeof(*vq) + sizeof(void *)*num, GFP_KERNEL);
	if (!vq)
		return NULL;

729
	vring_init(&vq->vring, num, pages, vring_align);
730 731
	vq->vq.callback = callback;
	vq->vq.vdev = vdev;
732
	vq->vq.name = name;
733 734
	vq->vq.num_free = num;
	vq->vq.index = index;
735
	vq->notify = notify;
736
	vq->weak_barriers = weak_barriers;
737 738 739
	vq->broken = false;
	vq->last_used_idx = 0;
	vq->num_added = 0;
740
	list_add_tail(&vq->vq.list, &vdev->vqs);
741 742
#ifdef DEBUG
	vq->in_use = false;
743
	vq->last_add_time_valid = false;
744 745
#endif

746
	vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
747
	vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
748

749 750
	/* No callback?  Tell other side not to bother us. */
	if (!callback)
751
		vq->vring.avail->flags |= cpu_to_virtio16(vdev, VRING_AVAIL_F_NO_INTERRUPT);
752 753 754

	/* Put everything in free lists. */
	vq->free_head = 0;
755
	for (i = 0; i < num-1; i++) {
756
		vq->vring.desc[i].next = cpu_to_virtio16(vdev, i + 1);
757 758 759
		vq->data[i] = NULL;
	}
	vq->data[i] = NULL;
760 761 762

	return &vq->vq;
}
763
EXPORT_SYMBOL_GPL(vring_new_virtqueue);
764 765 766

void vring_del_virtqueue(struct virtqueue *vq)
{
767
	list_del(&vq->list);
768 769
	kfree(to_vvq(vq));
}
770
EXPORT_SYMBOL_GPL(vring_del_virtqueue);
771

772 773 774 775 776 777 778
/* 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) {
779 780
		case VIRTIO_RING_F_INDIRECT_DESC:
			break;
781 782
		case VIRTIO_RING_F_EVENT_IDX:
			break;
783 784
		default:
			/* We don't understand this bit. */
785
			__virtio_clear_bit(vdev, i);
786 787 788 789 790
		}
	}
}
EXPORT_SYMBOL_GPL(vring_transport_features);

791 792 793 794 795 796 797
/**
 * 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 已提交
798 799 800 801 802 803 804 805 806
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);

807 808 809 810 811 812 813 814
bool virtqueue_is_broken(struct virtqueue *_vq)
{
	struct vring_virtqueue *vq = to_vvq(_vq);

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

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
/*
 * 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);

830
MODULE_LICENSE("GPL");