xref: /openbsd-src/sys/dev/pv/virtio.c (revision 4b70baf6e17fc8b27fc1f7fa7929335753fa94c3)
1 /*	$OpenBSD: virtio.c,v 1.18 2019/04/17 21:44:32 sf Exp $	*/
2 /*	$NetBSD: virtio.c,v 1.3 2011/11/02 23:05:52 njoly Exp $	*/
3 
4 /*
5  * Copyright (c) 2012 Stefan Fritsch, Alexander Fiveg.
6  * Copyright (c) 2010 Minoura Makoto.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/device.h>
34 #include <sys/mutex.h>
35 #include <sys/atomic.h>
36 #include <sys/malloc.h>
37 
38 #include <dev/pv/virtioreg.h>
39 #include <dev/pv/virtiovar.h>
40 
41 #if VIRTIO_DEBUG
42 #define VIRTIO_ASSERT(x)	KASSERT(x)
43 #else
44 #define VIRTIO_ASSERT(x)
45 #endif
46 
47 void		 virtio_init_vq(struct virtio_softc *,
48 				struct virtqueue *);
49 void		 vq_free_entry(struct virtqueue *, struct vq_entry *);
50 struct vq_entry	*vq_alloc_entry(struct virtqueue *);
51 
52 struct cfdriver virtio_cd = {
53 	NULL, "virtio", DV_DULL
54 };
55 
56 static const char * const virtio_device_name[] = {
57 	"Unknown (0)",		/* 0 */
58 	"Network",		/* 1 */
59 	"Block",		/* 2 */
60 	"Console",		/* 3 */
61 	"Entropy",		/* 4 */
62 	"Memory Balloon",	/* 5 */
63 	"IO Memory",		/* 6 */
64 	"Rpmsg",		/* 7 */
65 	"SCSI host",		/* 8 */
66 	"9P Transport",		/* 9 */
67 	"mac80211 wlan"		/* 10 */
68 };
69 #define NDEVNAMES	(sizeof(virtio_device_name)/sizeof(char*))
70 
71 const char *
72 virtio_device_string(int id)
73 {
74 	return id < NDEVNAMES ? virtio_device_name[id] : "Unknown";
75 }
76 
77 #if VIRTIO_DEBUG
78 static const struct virtio_feature_name transport_feature_names[] = {
79 	{ VIRTIO_F_NOTIFY_ON_EMPTY,	"NotifyOnEmpty"},
80 	{ VIRTIO_F_RING_INDIRECT_DESC,	"RingIndirectDesc"},
81 	{ VIRTIO_F_RING_EVENT_IDX,	"RingEventIdx"},
82 	{ VIRTIO_F_BAD_FEATURE,		"BadFeature"},
83 	{ VIRTIO_F_VERSION_1,		"Version1"},
84 	{ 0,				NULL}
85 };
86 
87 void
88 virtio_log_features(uint64_t host, uint64_t neg,
89     const struct virtio_feature_name *guest_feature_names)
90 {
91 	const struct virtio_feature_name *namep;
92 	int i;
93 	char c;
94 	uint32_t bit;
95 
96 	for (i = 0; i < 64; i++) {
97 		if (i == 30) {
98 			/*
99 			 * VIRTIO_F_BAD_FEATURE is only used for
100 			 * checking correct negotiation
101 			 */
102 			continue;
103 		}
104 		bit = 1 << i;
105 		if ((host&bit) == 0)
106 			continue;
107 		namep = (i < 24 || i > 37) ? guest_feature_names :
108 		    transport_feature_names;
109 		while (namep->bit && namep->bit != bit)
110 			namep++;
111 		c = (neg&bit) ? '+' : '-';
112 		if (namep->name)
113 			printf(" %c%s", c, namep->name);
114 		else
115 			printf(" %cUnknown(%d)", c, i);
116 	}
117 }
118 #endif
119 
120 /*
121  * Reset the device.
122  */
123 /*
124  * To reset the device to a known state, do following:
125  *	virtio_reset(sc);	     // this will stop the device activity
126  *	<dequeue finished requests>; // virtio_dequeue() still can be called
127  *	<revoke pending requests in the vqs if any>;
128  *	virtio_reinit_start(sc);     // dequeue prohibitted
129  *	newfeatures = virtio_negotiate_features(sc, requestedfeatures);
130  *	<some other initialization>;
131  *	virtio_reinit_end(sc);	     // device activated; enqueue allowed
132  * Once attached, feature negotiation can only be allowed after virtio_reset.
133  */
134 void
135 virtio_reset(struct virtio_softc *sc)
136 {
137 	virtio_device_reset(sc);
138 }
139 
140 void
141 virtio_reinit_start(struct virtio_softc *sc)
142 {
143 	int i;
144 
145 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_ACK);
146 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_DRIVER);
147 	for (i = 0; i < sc->sc_nvqs; i++) {
148 		int n;
149 		struct virtqueue *vq = &sc->sc_vqs[i];
150 		n = virtio_read_queue_size(sc, vq->vq_index);
151 		if (n == 0)	/* vq disappeared */
152 			continue;
153 		if (n != vq->vq_num) {
154 			panic("%s: virtqueue size changed, vq index %d\n",
155 			    sc->sc_dev.dv_xname, vq->vq_index);
156 		}
157 		virtio_init_vq(sc, vq);
158 		virtio_setup_queue(sc, vq, vq->vq_dmamap->dm_segs[0].ds_addr);
159 	}
160 }
161 
162 void
163 virtio_reinit_end(struct virtio_softc *sc)
164 {
165 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_DRIVER_OK);
166 }
167 
168 /*
169  * dmamap sync operations for a virtqueue.
170  */
171 static inline void
172 vq_sync_descs(struct virtio_softc *sc, struct virtqueue *vq, int ops)
173 {
174 	/* availoffset == sizeof(vring_desc)*vq_num */
175 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap, 0, vq->vq_availoffset,
176 	    ops);
177 }
178 
179 static inline void
180 vq_sync_aring(struct virtio_softc *sc, struct virtqueue *vq, int ops)
181 {
182 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap, vq->vq_availoffset,
183 	    offsetof(struct vring_avail, ring) + vq->vq_num * sizeof(uint16_t),
184 	    ops);
185 }
186 
187 static inline void
188 vq_sync_uring(struct virtio_softc *sc, struct virtqueue *vq, int ops)
189 {
190 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap, vq->vq_usedoffset,
191 	    offsetof(struct vring_used, ring) + vq->vq_num *
192 	    sizeof(struct vring_used_elem), ops);
193 }
194 
195 static inline void
196 vq_sync_indirect(struct virtio_softc *sc, struct virtqueue *vq, int slot,
197     int ops)
198 {
199 	int offset = vq->vq_indirectoffset +
200 	    sizeof(struct vring_desc) * vq->vq_maxnsegs * slot;
201 
202 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap, offset,
203 	    sizeof(struct vring_desc) * vq->vq_maxnsegs, ops);
204 }
205 
206 /*
207  * Scan vq, bus_dmamap_sync for the vqs (not for the payload),
208  * and calls (*vq_done)() if some entries are consumed.
209  * For use in transport specific irq handlers.
210  */
211 int
212 virtio_check_vqs(struct virtio_softc *sc)
213 {
214 	struct virtqueue *vq;
215 	int i, r = 0;
216 
217 	/* going backwards is better for if_vio */
218 	for (i = sc->sc_nvqs - 1; i >= 0; i--) {
219 		vq = &sc->sc_vqs[i];
220 		if (vq->vq_queued) {
221 			vq->vq_queued = 0;
222 			vq_sync_aring(sc, vq, BUS_DMASYNC_POSTWRITE);
223 		}
224 		vq_sync_uring(sc, vq, BUS_DMASYNC_POSTREAD);
225 		if (vq->vq_used_idx != vq->vq_used->idx) {
226 			if (vq->vq_done)
227 				r |= (vq->vq_done)(vq);
228 		}
229 	}
230 
231 	return r;
232 }
233 
234 /*
235  * Initialize vq structure.
236  */
237 void
238 virtio_init_vq(struct virtio_softc *sc, struct virtqueue *vq)
239 {
240 	int i, j;
241 	int vq_size = vq->vq_num;
242 
243 	memset(vq->vq_vaddr, 0, vq->vq_bytesize);
244 
245 	/* build the indirect descriptor chain */
246 	if (vq->vq_indirect != NULL) {
247 		struct vring_desc *vd;
248 
249 		for (i = 0; i < vq_size; i++) {
250 			vd = vq->vq_indirect;
251 			vd += vq->vq_maxnsegs * i;
252 			for (j = 0; j < vq->vq_maxnsegs-1; j++)
253 				vd[j].next = j + 1;
254 		}
255 	}
256 
257 	/* free slot management */
258 	SLIST_INIT(&vq->vq_freelist);
259 	/*
260 	 * virtio_enqueue_trim needs monotonely raising entries, therefore
261 	 * initialize in reverse order
262 	 */
263 	for (i = vq_size - 1; i >= 0; i--) {
264 		SLIST_INSERT_HEAD(&vq->vq_freelist, &vq->vq_entries[i],
265 		    qe_list);
266 		vq->vq_entries[i].qe_index = i;
267 	}
268 
269 	/* enqueue/dequeue status */
270 	vq->vq_avail_idx = 0;
271 	vq->vq_used_idx = 0;
272 	vq_sync_aring(sc, vq, BUS_DMASYNC_PREWRITE);
273 	vq_sync_uring(sc, vq, BUS_DMASYNC_PREREAD);
274 	vq->vq_queued = 1;
275 }
276 
277 /*
278  * Allocate/free a vq.
279  *
280  * maxnsegs denotes how much space should be allocated for indirect
281  * descriptors. maxnsegs == 1 can be used to disable use indirect
282  * descriptors for this queue.
283  */
284 int
285 virtio_alloc_vq(struct virtio_softc *sc, struct virtqueue *vq, int index,
286     int maxsegsize, int maxnsegs, const char *name)
287 {
288 	int vq_size, allocsize1, allocsize2, allocsize3, allocsize = 0;
289 	int rsegs, r, hdrlen;
290 #define VIRTQUEUE_ALIGN(n)	(((n)+(VIRTIO_PAGE_SIZE-1))&	\
291 				 ~(VIRTIO_PAGE_SIZE-1))
292 
293 	memset(vq, 0, sizeof(*vq));
294 
295 	vq_size = virtio_read_queue_size(sc, index);
296 	if (vq_size == 0) {
297 		printf("virtqueue not exist, index %d for %s\n", index, name);
298 		goto err;
299 	}
300 	if (((vq_size - 1) & vq_size) != 0)
301 		panic("vq_size not power of two: %d", vq_size);
302 
303 	hdrlen = (sc->sc_features & VIRTIO_F_RING_EVENT_IDX) ? 3 : 2;
304 
305 	/* allocsize1: descriptor table + avail ring + pad */
306 	allocsize1 = VIRTQUEUE_ALIGN(sizeof(struct vring_desc) * vq_size
307 	    + sizeof(uint16_t) * (hdrlen + vq_size));
308 	/* allocsize2: used ring + pad */
309 	allocsize2 = VIRTQUEUE_ALIGN(sizeof(uint16_t) * hdrlen
310 	    + sizeof(struct vring_used_elem) * vq_size);
311 	/* allocsize3: indirect table */
312 	if (sc->sc_indirect && maxnsegs > 1)
313 		allocsize3 = sizeof(struct vring_desc) * maxnsegs * vq_size;
314 	else
315 		allocsize3 = 0;
316 	allocsize = allocsize1 + allocsize2 + allocsize3;
317 
318 	/* alloc and map the memory */
319 	r = bus_dmamem_alloc(sc->sc_dmat, allocsize, VIRTIO_PAGE_SIZE, 0,
320 	    &vq->vq_segs[0], 1, &rsegs, BUS_DMA_NOWAIT);
321 	if (r != 0) {
322 		printf("virtqueue %d for %s allocation failed, error %d\n",
323 		       index, name, r);
324 		goto err;
325 	}
326 	r = bus_dmamem_map(sc->sc_dmat, &vq->vq_segs[0], 1, allocsize,
327 	    (caddr_t*)&vq->vq_vaddr, BUS_DMA_NOWAIT);
328 	if (r != 0) {
329 		printf("virtqueue %d for %s map failed, error %d\n", index,
330 		    name, r);
331 		goto err;
332 	}
333 	r = bus_dmamap_create(sc->sc_dmat, allocsize, 1, allocsize, 0,
334 	    BUS_DMA_NOWAIT, &vq->vq_dmamap);
335 	if (r != 0) {
336 		printf("virtqueue %d for %s dmamap creation failed, "
337 		    "error %d\n", index, name, r);
338 		goto err;
339 	}
340 	r = bus_dmamap_load(sc->sc_dmat, vq->vq_dmamap, vq->vq_vaddr,
341 	    allocsize, NULL, BUS_DMA_NOWAIT);
342 	if (r != 0) {
343 		printf("virtqueue %d for %s dmamap load failed, error %d\n",
344 		    index, name, r);
345 		goto err;
346 	}
347 
348 	/* remember addresses and offsets for later use */
349 	vq->vq_owner = sc;
350 	vq->vq_num = vq_size;
351 	vq->vq_mask = vq_size - 1;
352 	vq->vq_index = index;
353 	vq->vq_desc = vq->vq_vaddr;
354 	vq->vq_availoffset = sizeof(struct vring_desc)*vq_size;
355 	vq->vq_avail = (struct vring_avail*)(((char*)vq->vq_desc) +
356 	    vq->vq_availoffset);
357 	vq->vq_usedoffset = allocsize1;
358 	vq->vq_used = (struct vring_used*)(((char*)vq->vq_desc) +
359 	    vq->vq_usedoffset);
360 	if (allocsize3 > 0) {
361 		vq->vq_indirectoffset = allocsize1 + allocsize2;
362 		vq->vq_indirect = (void*)(((char*)vq->vq_desc)
363 		    + vq->vq_indirectoffset);
364 	}
365 	vq->vq_bytesize = allocsize;
366 	vq->vq_maxnsegs = maxnsegs;
367 
368 	/* free slot management */
369 	vq->vq_entries = mallocarray(vq_size, sizeof(struct vq_entry),
370 	    M_DEVBUF, M_NOWAIT | M_ZERO);
371 	if (vq->vq_entries == NULL) {
372 		r = ENOMEM;
373 		goto err;
374 	}
375 
376 	virtio_init_vq(sc, vq);
377 	virtio_setup_queue(sc, vq, vq->vq_dmamap->dm_segs[0].ds_addr);
378 
379 #if VIRTIO_DEBUG
380 	printf("\nallocated %u byte for virtqueue %d for %s, size %d\n",
381 	    allocsize, index, name, vq_size);
382 	if (allocsize3 > 0)
383 		printf("using %d byte (%d entries) indirect descriptors\n",
384 		    allocsize3, maxnsegs * vq_size);
385 #endif
386 	return 0;
387 
388 err:
389 	if (vq->vq_dmamap)
390 		bus_dmamap_destroy(sc->sc_dmat, vq->vq_dmamap);
391 	if (vq->vq_vaddr)
392 		bus_dmamem_unmap(sc->sc_dmat, vq->vq_vaddr, allocsize);
393 	if (vq->vq_segs[0].ds_addr)
394 		bus_dmamem_free(sc->sc_dmat, &vq->vq_segs[0], 1);
395 	memset(vq, 0, sizeof(*vq));
396 
397 	return -1;
398 }
399 
400 int
401 virtio_free_vq(struct virtio_softc *sc, struct virtqueue *vq)
402 {
403 	struct vq_entry *qe;
404 	int i = 0;
405 
406 	/* device must be already deactivated */
407 	/* confirm the vq is empty */
408 	SLIST_FOREACH(qe, &vq->vq_freelist, qe_list) {
409 		i++;
410 	}
411 	if (i != vq->vq_num) {
412 		printf("%s: freeing non-empty vq, index %d\n",
413 		    sc->sc_dev.dv_xname, vq->vq_index);
414 		return EBUSY;
415 	}
416 
417 	/* tell device that there's no virtqueue any longer */
418 	virtio_setup_queue(sc, vq, 0);
419 
420 	free(vq->vq_entries, M_DEVBUF, 0);
421 	bus_dmamap_unload(sc->sc_dmat, vq->vq_dmamap);
422 	bus_dmamap_destroy(sc->sc_dmat, vq->vq_dmamap);
423 	bus_dmamem_unmap(sc->sc_dmat, vq->vq_vaddr, vq->vq_bytesize);
424 	bus_dmamem_free(sc->sc_dmat, &vq->vq_segs[0], 1);
425 	memset(vq, 0, sizeof(*vq));
426 
427 	return 0;
428 }
429 
430 /*
431  * Free descriptor management.
432  */
433 struct vq_entry *
434 vq_alloc_entry(struct virtqueue *vq)
435 {
436 	struct vq_entry *qe;
437 
438 	if (SLIST_EMPTY(&vq->vq_freelist))
439 		return NULL;
440 	qe = SLIST_FIRST(&vq->vq_freelist);
441 	SLIST_REMOVE_HEAD(&vq->vq_freelist, qe_list);
442 
443 	return qe;
444 }
445 
446 void
447 vq_free_entry(struct virtqueue *vq, struct vq_entry *qe)
448 {
449 	SLIST_INSERT_HEAD(&vq->vq_freelist, qe, qe_list);
450 }
451 
452 /*
453  * Enqueue several dmamaps as a single request.
454  */
455 /*
456  * Typical usage:
457  *  <queue size> number of followings are stored in arrays
458  *  - command blocks (in dmamem) should be pre-allocated and mapped
459  *  - dmamaps for command blocks should be pre-allocated and loaded
460  *  - dmamaps for payload should be pre-allocated
461  *	r = virtio_enqueue_prep(sc, vq, &slot);		// allocate a slot
462  *	if (r)		// currently 0 or EAGAIN
463  *	  return r;
464  *	r = bus_dmamap_load(dmat, dmamap_payload[slot], data, count, ..);
465  *	if (r) {
466  *	  virtio_enqueue_abort(sc, vq, slot);
467  *	  bus_dmamap_unload(dmat, dmamap_payload[slot]);
468  *	  return r;
469  *	}
470  *	r = virtio_enqueue_reserve(sc, vq, slot,
471  *				   dmamap_payload[slot]->dm_nsegs+1);
472  *							// ^ +1 for command
473  *	if (r) {	// currently 0 or EAGAIN
474  *	  bus_dmamap_unload(dmat, dmamap_payload[slot]);
475  *	  return r;					// do not call abort()
476  *	}
477  *	<setup and prepare commands>
478  *	bus_dmamap_sync(dmat, dmamap_cmd[slot],... BUS_DMASYNC_PREWRITE);
479  *	bus_dmamap_sync(dmat, dmamap_payload[slot],...);
480  *	virtio_enqueue(sc, vq, slot, dmamap_cmd[slot], 0);
481  *	virtio_enqueue(sc, vq, slot, dmamap_payload[slot], iswrite);
482  *	virtio_enqueue_commit(sc, vq, slot, 1);
483  *
484  * Alternative usage with statically allocated slots:
485  *	<during initialization>
486  *	// while not out of slots, do
487  *	virtio_enqueue_prep(sc, vq, &slot);		// allocate a slot
488  *	virtio_enqueue_reserve(sc, vq, slot, max_segs);	// reserve all slots
489  *						that may ever be needed
490  *
491  *	<when enqueing a request>
492  *	// Don't call virtio_enqueue_prep()
493  *	bus_dmamap_load(dmat, dmamap_payload[slot], data, count, ..);
494  *	bus_dmamap_sync(dmat, dmamap_cmd[slot],... BUS_DMASYNC_PREWRITE);
495  *	bus_dmamap_sync(dmat, dmamap_payload[slot],...);
496  *	virtio_enqueue_trim(sc, vq, slot, num_segs_needed);
497  *	virtio_enqueue(sc, vq, slot, dmamap_cmd[slot], 0);
498  *	virtio_enqueue(sc, vq, slot, dmamap_payload[slot], iswrite);
499  *	virtio_enqueue_commit(sc, vq, slot, 1);
500  *
501  *	<when dequeuing>
502  *	// don't call virtio_dequeue_commit()
503  */
504 
505 /*
506  * enqueue_prep: allocate a slot number
507  */
508 int
509 virtio_enqueue_prep(struct virtqueue *vq, int *slotp)
510 {
511 	struct vq_entry *qe1;
512 
513 	VIRTIO_ASSERT(slotp != NULL);
514 
515 	qe1 = vq_alloc_entry(vq);
516 	if (qe1 == NULL)
517 		return EAGAIN;
518 	/* next slot is not allocated yet */
519 	qe1->qe_next = -1;
520 	*slotp = qe1->qe_index;
521 
522 	return 0;
523 }
524 
525 /*
526  * enqueue_reserve: allocate remaining slots and build the descriptor chain.
527  * Calls virtio_enqueue_abort() on failure.
528  */
529 int
530 virtio_enqueue_reserve(struct virtqueue *vq, int slot, int nsegs)
531 {
532 	struct vq_entry *qe1 = &vq->vq_entries[slot];
533 
534 	VIRTIO_ASSERT(qe1->qe_next == -1);
535 	VIRTIO_ASSERT(1 <= nsegs && nsegs <= vq->vq_num);
536 
537 	if (vq->vq_indirect != NULL && nsegs > 1 && nsegs <= vq->vq_maxnsegs) {
538 		struct vring_desc *vd;
539 		int i;
540 
541 		qe1->qe_indirect = 1;
542 
543 		vd = &vq->vq_desc[qe1->qe_index];
544 		vd->addr = vq->vq_dmamap->dm_segs[0].ds_addr +
545 		    vq->vq_indirectoffset;
546 		vd->addr += sizeof(struct vring_desc) * vq->vq_maxnsegs *
547 		    qe1->qe_index;
548 		vd->len = sizeof(struct vring_desc) * nsegs;
549 		vd->flags = VRING_DESC_F_INDIRECT;
550 
551 		vd = vq->vq_indirect;
552 		vd += vq->vq_maxnsegs * qe1->qe_index;
553 		qe1->qe_desc_base = vd;
554 
555 		for (i = 0; i < nsegs-1; i++)
556 			vd[i].flags = VRING_DESC_F_NEXT;
557 		vd[i].flags = 0;
558 		qe1->qe_next = 0;
559 
560 		return 0;
561 	} else {
562 		struct vring_desc *vd;
563 		struct vq_entry *qe;
564 		int i, s;
565 
566 		qe1->qe_indirect = 0;
567 
568 		vd = &vq->vq_desc[0];
569 		qe1->qe_desc_base = vd;
570 		qe1->qe_next = qe1->qe_index;
571 		s = slot;
572 		for (i = 0; i < nsegs - 1; i++) {
573 			qe = vq_alloc_entry(vq);
574 			if (qe == NULL) {
575 				vd[s].flags = 0;
576 				virtio_enqueue_abort(vq, slot);
577 				return EAGAIN;
578 			}
579 			vd[s].flags = VRING_DESC_F_NEXT;
580 			vd[s].next = qe->qe_index;
581 			s = qe->qe_index;
582 		}
583 		vd[s].flags = 0;
584 
585 		return 0;
586 	}
587 }
588 
589 /*
590  * enqueue: enqueue a single dmamap.
591  */
592 int
593 virtio_enqueue(struct virtqueue *vq, int slot, bus_dmamap_t dmamap, int write)
594 {
595 	struct vq_entry *qe1 = &vq->vq_entries[slot];
596 	struct vring_desc *vd = qe1->qe_desc_base;
597 	int i;
598 	int s = qe1->qe_next;
599 
600 	VIRTIO_ASSERT(s >= 0);
601 	VIRTIO_ASSERT(dmamap->dm_nsegs > 0);
602 	if (dmamap->dm_nsegs > vq->vq_maxnsegs) {
603 #if VIRTIO_DEBUG
604 		for (i = 0; i < dmamap->dm_nsegs; i++) {
605 			printf(" %d (%d): %p %lx \n", i, write,
606 			    (void *)dmamap->dm_segs[i].ds_addr,
607 			    dmamap->dm_segs[i].ds_len);
608 		}
609 #endif
610 		panic("dmamap->dm_nseg %d > vq->vq_maxnsegs %d\n",
611 		    dmamap->dm_nsegs, vq->vq_maxnsegs);
612 	}
613 
614 	for (i = 0; i < dmamap->dm_nsegs; i++) {
615 		vd[s].addr = dmamap->dm_segs[i].ds_addr;
616 		vd[s].len = dmamap->dm_segs[i].ds_len;
617 		if (!write)
618 			vd[s].flags |= VRING_DESC_F_WRITE;
619 		s = vd[s].next;
620 	}
621 	qe1->qe_next = s;
622 
623 	return 0;
624 }
625 
626 int
627 virtio_enqueue_p(struct virtqueue *vq, int slot, bus_dmamap_t dmamap,
628     bus_addr_t start, bus_size_t len, int write)
629 {
630 	struct vq_entry *qe1 = &vq->vq_entries[slot];
631 	struct vring_desc *vd = qe1->qe_desc_base;
632 	int s = qe1->qe_next;
633 
634 	VIRTIO_ASSERT(s >= 0);
635 	/* XXX todo: handle more segments */
636 	VIRTIO_ASSERT(dmamap->dm_nsegs == 1);
637 	VIRTIO_ASSERT((dmamap->dm_segs[0].ds_len > start) &&
638 	    (dmamap->dm_segs[0].ds_len >= start + len));
639 
640 	vd[s].addr = dmamap->dm_segs[0].ds_addr + start;
641 	vd[s].len = len;
642 	if (!write)
643 		vd[s].flags |= VRING_DESC_F_WRITE;
644 	qe1->qe_next = vd[s].next;
645 
646 	return 0;
647 }
648 
649 static void
650 publish_avail_idx(struct virtio_softc *sc, struct virtqueue *vq)
651 {
652 	vq_sync_aring(sc, vq, BUS_DMASYNC_PREWRITE);
653 
654 	virtio_membar_producer();
655 	vq->vq_avail->idx = vq->vq_avail_idx;
656 	vq_sync_aring(sc, vq, BUS_DMASYNC_POSTWRITE);
657 	vq->vq_queued = 1;
658 }
659 
660 /*
661  * enqueue_commit: add it to the aring.
662  */
663 void
664 virtio_enqueue_commit(struct virtio_softc *sc, struct virtqueue *vq, int slot,
665     int notifynow)
666 {
667 	struct vq_entry *qe1;
668 
669 	if (slot < 0)
670 		goto notify;
671 	vq_sync_descs(sc, vq, BUS_DMASYNC_PREWRITE);
672 	qe1 = &vq->vq_entries[slot];
673 	if (qe1->qe_indirect)
674 		vq_sync_indirect(sc, vq, slot, BUS_DMASYNC_PREWRITE);
675 	vq->vq_avail->ring[(vq->vq_avail_idx++) & vq->vq_mask] = slot;
676 
677 notify:
678 	if (notifynow) {
679 		if (vq->vq_owner->sc_features & VIRTIO_F_RING_EVENT_IDX) {
680 			uint16_t o = vq->vq_avail->idx;
681 			uint16_t n = vq->vq_avail_idx;
682 			uint16_t t;
683 			publish_avail_idx(sc, vq);
684 
685 			virtio_membar_sync();
686 			t = VQ_AVAIL_EVENT(vq) + 1;
687 			if ((uint16_t)(n - t) < (uint16_t)(n - o))
688 				sc->sc_ops->kick(sc, vq->vq_index);
689 		} else {
690 			publish_avail_idx(sc, vq);
691 
692 			virtio_membar_sync();
693 			if (!(vq->vq_used->flags & VRING_USED_F_NO_NOTIFY))
694 				sc->sc_ops->kick(sc, vq->vq_index);
695 		}
696 	}
697 }
698 
699 /*
700  * enqueue_abort: rollback.
701  */
702 int
703 virtio_enqueue_abort(struct virtqueue *vq, int slot)
704 {
705 	struct vq_entry *qe = &vq->vq_entries[slot];
706 	struct vring_desc *vd;
707 	int s;
708 
709 	if (qe->qe_next < 0) {
710 		vq_free_entry(vq, qe);
711 		return 0;
712 	}
713 
714 	s = slot;
715 	vd = &vq->vq_desc[0];
716 	while (vd[s].flags & VRING_DESC_F_NEXT) {
717 		s = vd[s].next;
718 		vq_free_entry(vq, qe);
719 		qe = &vq->vq_entries[s];
720 	}
721 	vq_free_entry(vq, qe);
722 	return 0;
723 }
724 
725 /*
726  * enqueue_trim: adjust buffer size to given # of segments, a.k.a.
727  * descriptors.
728  */
729 void
730 virtio_enqueue_trim(struct virtqueue *vq, int slot, int nsegs)
731 {
732 	struct vq_entry *qe1 = &vq->vq_entries[slot];
733 	struct vring_desc *vd = &vq->vq_desc[0];
734 	int i;
735 
736 	if ((vd[slot].flags & VRING_DESC_F_INDIRECT) == 0) {
737 		qe1->qe_next = qe1->qe_index;
738 		/*
739 		 * N.B.: the vq_entries are ASSUMED to be a contiguous
740 		 *       block with slot being the index to the first one.
741 		 */
742 	} else {
743 		qe1->qe_next = 0;
744 		vd = &vq->vq_desc[qe1->qe_index];
745 		vd->len = sizeof(struct vring_desc) * nsegs;
746 		vd = qe1->qe_desc_base;
747 		slot = 0;
748 	}
749 
750 	for (i = 0; i < nsegs -1 ; i++) {
751 		vd[slot].flags = VRING_DESC_F_NEXT;
752 		slot++;
753 	}
754 	vd[slot].flags = 0;
755 }
756 
757 /*
758  * Dequeue a request.
759  */
760 /*
761  * dequeue: dequeue a request from uring; dmamap_sync for uring is
762  *	    already done in the interrupt handler.
763  */
764 int
765 virtio_dequeue(struct virtio_softc *sc, struct virtqueue *vq,
766     int *slotp, int *lenp)
767 {
768 	uint16_t slot, usedidx;
769 	struct vq_entry *qe;
770 
771 	if (vq->vq_used_idx == vq->vq_used->idx)
772 		return ENOENT;
773 	usedidx = vq->vq_used_idx++;
774 	usedidx &= vq->vq_mask;
775 
776 	virtio_membar_consumer();
777 	slot = vq->vq_used->ring[usedidx].id;
778 	qe = &vq->vq_entries[slot];
779 
780 	if (qe->qe_indirect)
781 		vq_sync_indirect(sc, vq, slot, BUS_DMASYNC_POSTWRITE);
782 
783 	if (slotp)
784 		*slotp = slot;
785 	if (lenp)
786 		*lenp = vq->vq_used->ring[usedidx].len;
787 
788 	return 0;
789 }
790 
791 /*
792  * dequeue_commit: complete dequeue; the slot is recycled for future use.
793  *                 if you forget to call this the slot will be leaked.
794  *
795  *                 Don't call this if you use statically allocated slots
796  *                 and virtio_dequeue_trim().
797  */
798 int
799 virtio_dequeue_commit(struct virtqueue *vq, int slot)
800 {
801 	struct vq_entry *qe = &vq->vq_entries[slot];
802 	struct vring_desc *vd = &vq->vq_desc[0];
803 	int s = slot;
804 
805 	while (vd[s].flags & VRING_DESC_F_NEXT) {
806 		s = vd[s].next;
807 		vq_free_entry(vq, qe);
808 		qe = &vq->vq_entries[s];
809 	}
810 	vq_free_entry(vq, qe);
811 
812 	return 0;
813 }
814 
815 /*
816  * Increase the event index in order to delay interrupts.
817  * Returns 0 on success; returns 1 if the used ring has already advanced
818  * too far, and the caller must process the queue again (otherewise, no
819  * more interrupts will happen).
820  */
821 int
822 virtio_postpone_intr(struct virtqueue *vq, uint16_t nslots)
823 {
824 	uint16_t	idx;
825 
826 	idx = vq->vq_used_idx + nslots;
827 
828 	/* set the new event index: avail_ring->used_event = idx */
829 	VQ_USED_EVENT(vq) = idx;
830 	virtio_membar_sync();
831 
832 	vq_sync_aring(vq->vq_owner, vq, BUS_DMASYNC_PREWRITE);
833 	vq->vq_queued++;
834 
835 	if (nslots < virtio_nused(vq))
836 		return 1;
837 
838 	return 0;
839 }
840 
841 /*
842  * Postpone interrupt until 3/4 of the available descriptors have been
843  * consumed.
844  */
845 int
846 virtio_postpone_intr_smart(struct virtqueue *vq)
847 {
848 	uint16_t	nslots;
849 
850 	nslots = (uint16_t)(vq->vq_avail->idx - vq->vq_used_idx) * 3 / 4;
851 
852 	return virtio_postpone_intr(vq, nslots);
853 }
854 
855 /*
856  * Postpone interrupt until all of the available descriptors have been
857  * consumed.
858  */
859 int
860 virtio_postpone_intr_far(struct virtqueue *vq)
861 {
862 	uint16_t	nslots;
863 
864 	nslots = (uint16_t)(vq->vq_avail->idx - vq->vq_used_idx);
865 
866 	return virtio_postpone_intr(vq, nslots);
867 }
868 
869 
870 /*
871  * Start/stop vq interrupt.  No guarantee.
872  */
873 void
874 virtio_stop_vq_intr(struct virtio_softc *sc, struct virtqueue *vq)
875 {
876 	if ((sc->sc_features & VIRTIO_F_RING_EVENT_IDX)) {
877 		/*
878 		 * No way to disable the interrupt completely with
879 		 * RingEventIdx. Instead advance used_event by half
880 		 * the possible value. This won't happen soon and
881 		 * is far enough in the past to not trigger a spurios
882 		 * interrupt.
883 		 */
884 		VQ_USED_EVENT(vq) = vq->vq_used_idx + 0x8000;
885 	} else {
886 		vq->vq_avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
887 	}
888 	vq_sync_aring(sc, vq, BUS_DMASYNC_PREWRITE);
889 	vq->vq_queued++;
890 }
891 
892 int
893 virtio_start_vq_intr(struct virtio_softc *sc, struct virtqueue *vq)
894 {
895 	/*
896 	 * If event index feature is negotiated, enabling
897 	 * interrupts is done through setting the latest
898 	 * consumed index in the used_event field
899 	 */
900 	if (sc->sc_features & VIRTIO_F_RING_EVENT_IDX)
901 		VQ_USED_EVENT(vq) = vq->vq_used_idx;
902 	else
903 		vq->vq_avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
904 
905 	virtio_membar_sync();
906 
907 	vq_sync_aring(sc, vq, BUS_DMASYNC_PREWRITE);
908 	vq->vq_queued++;
909 
910 	if (vq->vq_used_idx != vq->vq_used->idx)
911 		return 1;
912 
913 	return 0;
914 }
915 
916 /*
917  * Returns a number of slots in the used ring available to
918  * be supplied to the avail ring.
919  */
920 int
921 virtio_nused(struct virtqueue *vq)
922 {
923 	uint16_t	n;
924 
925 	n = (uint16_t)(vq->vq_used->idx - vq->vq_used_idx);
926 	VIRTIO_ASSERT(n <= vq->vq_num);
927 
928 	return n;
929 }
930 
931 #if VIRTIO_DEBUG
932 void
933 virtio_vq_dump(struct virtqueue *vq)
934 {
935 	/* Common fields */
936 	printf(" + vq num: %d\n", vq->vq_num);
937 	printf(" + vq mask: 0x%X\n", vq->vq_mask);
938 	printf(" + vq index: %d\n", vq->vq_index);
939 	printf(" + vq used idx: %d\n", vq->vq_used_idx);
940 	printf(" + vq avail idx: %d\n", vq->vq_avail_idx);
941 	printf(" + vq queued: %d\n",vq->vq_queued);
942 	/* Avail ring fields */
943 	printf(" + avail flags: 0x%X\n", vq->vq_avail->flags);
944 	printf(" + avail idx: %d\n", vq->vq_avail->idx);
945 	printf(" + avail event: %d\n", VQ_AVAIL_EVENT(vq));
946 	/* Used ring fields */
947 	printf(" + used flags: 0x%X\n",vq->vq_used->flags);
948 	printf(" + used idx: %d\n",vq->vq_used->idx);
949 	printf(" + used event: %d\n", VQ_USED_EVENT(vq));
950 	printf(" +++++++++++++++++++++++++++\n");
951 }
952 #endif
953