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