Home | History | Annotate | Line # | Download | only in pci
      1 /*	$NetBSD: virtio.c,v 1.85 2026/05/22 14:36:37 riastradh Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2020 The NetBSD Foundation, Inc.
      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/cdefs.h>
     31 __KERNEL_RCSID(0, "$NetBSD: virtio.c,v 1.85 2026/05/22 14:36:37 riastradh Exp $");
     32 
     33 #include <sys/param.h>
     34 #include <sys/systm.h>
     35 #include <sys/kernel.h>
     36 #include <sys/atomic.h>
     37 #include <sys/bus.h>
     38 #include <sys/device.h>
     39 #include <sys/kmem.h>
     40 #include <sys/module.h>
     41 #include <sys/paravirt_membar.h>
     42 
     43 #define VIRTIO_PRIVATE
     44 
     45 #include <dev/pci/virtioreg.h> /* XXX: move to non-pci */
     46 #include <dev/pci/virtiovar.h> /* XXX: move to non-pci */
     47 
     48 #define MINSEG_INDIRECT		2 /* use indirect if nsegs >= this value */
     49 
     50 /*
     51  * The maximum descriptor size is 2^15. Use that value as the end of
     52  * descriptor chain terminator since it will never be a valid index
     53  * in the descriptor table.
     54  */
     55 #define VRING_DESC_CHAIN_END		32768
     56 
     57 /* incomplete list */
     58 static const char *virtio_device_name[] = {
     59 	"unknown (0)",			/*  0 */
     60 	"network",			/*  1 */
     61 	"block",			/*  2 */
     62 	"console",			/*  3 */
     63 	"entropy",			/*  4 */
     64 	"memory balloon",		/*  5 */
     65 	"I/O memory",			/*  6 */
     66 	"remote processor messaging",	/*  7 */
     67 	"SCSI",				/*  8 */
     68 	"9P transport",			/*  9 */
     69 	NULL,				/* 10 */
     70 	NULL,				/* 11 */
     71 	NULL,				/* 12 */
     72 	NULL,				/* 13 */
     73 	NULL,				/* 14 */
     74 	NULL,				/* 15 */
     75 	"GPU",				/* 16 */
     76 };
     77 #define NDEVNAMES	__arraycount(virtio_device_name)
     78 
     79 static void	virtio_reset_vq(struct virtio_softc *,
     80 		    struct virtqueue *);
     81 
     82 void
     83 virtio_set_status(struct virtio_softc *sc, int status)
     84 {
     85 	sc->sc_ops->set_status(sc, status);
     86 }
     87 
     88 /*
     89  * Reset the device.
     90  */
     91 /*
     92  * To reset the device to a known state, do following:
     93  *	virtio_reset(sc);	     // this will stop the device activity
     94  *	<dequeue finished requests>; // virtio_dequeue() still can be called
     95  *	<revoke pending requests in the vqs if any>;
     96  *	virtio_reinit_start(sc);     // dequeue prohibited
     97  *	newfeatures = virtio_negotiate_features(sc, requestedfeatures);
     98  *	<some other initialization>;
     99  *	virtio_reinit_end(sc);	     // device activated; enqueue allowed
    100  * Once attached, feature negotiation can only be allowed after virtio_reset.
    101  */
    102 void
    103 virtio_reset(struct virtio_softc *sc)
    104 {
    105 	virtio_device_reset(sc);
    106 }
    107 
    108 int
    109 virtio_reinit_start(struct virtio_softc *sc)
    110 {
    111 	int i, r;
    112 
    113 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_ACK);
    114 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_DRIVER);
    115 	for (i = 0; i < sc->sc_nvqs; i++) {
    116 		int n;
    117 		struct virtqueue *vq = &sc->sc_vqs[i];
    118 		n = sc->sc_ops->read_queue_size(sc, vq->vq_index);
    119 		if (n == 0)	/* vq disappeared */
    120 			continue;
    121 		if (n != vq->vq_num) {
    122 			panic("%s: virtqueue size changed, vq index %d\n",
    123 			    device_xname(sc->sc_dev),
    124 			    vq->vq_index);
    125 		}
    126 		virtio_reset_vq(sc, vq);
    127 		sc->sc_ops->setup_queue(sc, vq->vq_index,
    128 		    vq->vq_dmamap->dm_segs[0].ds_addr);
    129 	}
    130 
    131 	r = sc->sc_ops->setup_interrupts(sc, 1);
    132 	if (r != 0)
    133 		goto fail;
    134 
    135 	return 0;
    136 
    137 fail:
    138 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_FAILED);
    139 
    140 	return 1;
    141 }
    142 
    143 void
    144 virtio_reinit_end(struct virtio_softc *sc)
    145 {
    146 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_DRIVER_OK);
    147 }
    148 
    149 /*
    150  * Feature negotiation.
    151  */
    152 void
    153 virtio_negotiate_features(struct virtio_softc *sc, uint64_t guest_features)
    154 {
    155 	if (!(device_cfdata(sc->sc_dev)->cf_flags & 1) &&
    156 	    !(device_cfdata(sc->sc_child)->cf_flags & 1)) /* XXX */
    157 		guest_features |= VIRTIO_F_RING_INDIRECT_DESC;
    158 	sc->sc_ops->neg_features(sc, guest_features);
    159 	if (sc->sc_active_features & VIRTIO_F_RING_INDIRECT_DESC)
    160 		sc->sc_indirect = true;
    161 	else
    162 		sc->sc_indirect = false;
    163 }
    164 
    165 
    166 /*
    167  * Device configuration registers readers/writers
    168  */
    169 #if 0
    170 #define DPRINTFR(n, fmt, val, index, num) \
    171 	printf("\n%s (", n); \
    172 	for (int i = 0; i < num; i++) \
    173 		printf("%02x ", bus_space_read_1(sc->sc_devcfg_iot, sc->sc_devcfg_ioh, index+i)); \
    174 	printf(") -> "); printf(fmt, val); printf("\n");
    175 #define DPRINTFR2(n, fmt, val_s, val_n) \
    176 	printf("%s ", n); \
    177 	printf("\n        stream "); printf(fmt, val_s); printf(" norm "); printf(fmt, val_n); printf("\n");
    178 #else
    179 #define DPRINTFR(n, fmt, val, index, num)
    180 #define DPRINTFR2(n, fmt, val_s, val_n)
    181 #endif
    182 
    183 
    184 uint8_t
    185 virtio_read_device_config_1(struct virtio_softc *sc, int index)
    186 {
    187 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    188 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    189 	uint8_t val;
    190 
    191 	val = bus_space_read_1(iot, ioh, index);
    192 
    193 	DPRINTFR("read_1", "%02x", val, index, 1);
    194 	return val;
    195 }
    196 
    197 uint16_t
    198 virtio_read_device_config_2(struct virtio_softc *sc, int index)
    199 {
    200 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    201 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    202 	uint16_t val;
    203 
    204 	val = bus_space_read_2(iot, ioh, index);
    205 	if (BYTE_ORDER != sc->sc_bus_endian)
    206 		val = bswap16(val);
    207 
    208 	DPRINTFR("read_2", "%04x", val, index, 2);
    209 	DPRINTFR2("read_2", "%04x",
    210 	    bus_space_read_stream_2(sc->sc_devcfg_iot, sc->sc_devcfg_ioh,
    211 		index),
    212 	    bus_space_read_2(sc->sc_devcfg_iot, sc->sc_devcfg_ioh, index));
    213 	return val;
    214 }
    215 
    216 uint32_t
    217 virtio_read_device_config_4(struct virtio_softc *sc, int index)
    218 {
    219 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    220 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    221 	uint32_t val;
    222 
    223 	val = bus_space_read_4(iot, ioh, index);
    224 	if (BYTE_ORDER != sc->sc_bus_endian)
    225 		val = bswap32(val);
    226 
    227 	DPRINTFR("read_4", "%08x", val, index, 4);
    228 	DPRINTFR2("read_4", "%08x",
    229 	    bus_space_read_stream_4(sc->sc_devcfg_iot, sc->sc_devcfg_ioh,
    230 		index),
    231 	    bus_space_read_4(sc->sc_devcfg_iot, sc->sc_devcfg_ioh, index));
    232 	return val;
    233 }
    234 
    235 /*
    236  * The Virtio spec explicitly tells that reading and writing 8 bytes are not
    237  * considered atomic and no triggers may be connected to reading or writing
    238  * it. We access it using two 32 reads. See virtio spec 4.1.3.1.
    239  */
    240 uint64_t
    241 virtio_read_device_config_8(struct virtio_softc *sc, int index)
    242 {
    243 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    244 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    245 	union {
    246 		uint64_t u64;
    247 		uint32_t l[2];
    248 	} v;
    249 	uint64_t val;
    250 
    251 	v.l[0] = bus_space_read_4(iot, ioh, index);
    252 	v.l[1] = bus_space_read_4(iot, ioh, index + 4);
    253 	if (sc->sc_bus_endian != sc->sc_struct_endian) {
    254 		v.l[0] = bswap32(v.l[0]);
    255 		v.l[1] = bswap32(v.l[1]);
    256 	}
    257 	val = v.u64;
    258 
    259 	if (BYTE_ORDER != sc->sc_struct_endian)
    260 		val = bswap64(val);
    261 
    262 	DPRINTFR("read_8", "%08"PRIx64, val, index, 8);
    263 	DPRINTFR2("read_8 low ", "%08x",
    264 	    bus_space_read_stream_4(sc->sc_devcfg_iot, sc->sc_devcfg_ioh,
    265 		index),
    266 	    bus_space_read_4(sc->sc_devcfg_iot, sc->sc_devcfg_ioh, index));
    267 	DPRINTFR2("read_8 high ", "%08x",
    268 	    bus_space_read_stream_4(sc->sc_devcfg_iot, sc->sc_devcfg_ioh,
    269 		index + 4),
    270 	    bus_space_read_4(sc->sc_devcfg_iot, sc->sc_devcfg_ioh, index + 4));
    271 	return val;
    272 }
    273 
    274 /*
    275  * In the older virtio spec, device config registers are host endian. On newer
    276  * they are little endian. Some newer devices however explicitly specify their
    277  * register to always be little endian. These functions cater for these.
    278  */
    279 uint16_t
    280 virtio_read_device_config_le_2(struct virtio_softc *sc, int index)
    281 {
    282 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    283 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    284 	uint16_t val;
    285 
    286 	val = bus_space_read_2(iot, ioh, index);
    287 #if !defined(__aarch64__) && !defined(__arm__)
    288 	/*
    289 	 * For big-endian aarch64/armv7, bus endian is always LSB, but
    290 	 * byte-order is automatically swapped by bus_space(9) (see also
    291 	 * comments in virtio_pci.c). Therefore, no need to swap here.
    292 	 */
    293 	if (sc->sc_bus_endian != LITTLE_ENDIAN)
    294 		val = bswap16(val);
    295 #endif
    296 
    297 	DPRINTFR("read_le_2", "%04x", val, index, 2);
    298 	DPRINTFR2("read_le_2", "%04x",
    299 	    bus_space_read_stream_2(sc->sc_devcfg_iot, sc->sc_devcfg_ioh, 0),
    300 	    bus_space_read_2(sc->sc_devcfg_iot, sc->sc_devcfg_ioh, 0));
    301 	return val;
    302 }
    303 
    304 uint32_t
    305 virtio_read_device_config_le_4(struct virtio_softc *sc, int index)
    306 {
    307 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    308 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    309 	uint32_t val;
    310 
    311 	val = bus_space_read_4(iot, ioh, index);
    312 #if !defined(__aarch64__) && !defined(__arm__)
    313 	/* See virtio_read_device_config_le_2() above. */
    314 	if (sc->sc_bus_endian != LITTLE_ENDIAN)
    315 		val = bswap32(val);
    316 #endif
    317 
    318 	DPRINTFR("read_le_4", "%08x", val, index, 4);
    319 	DPRINTFR2("read_le_4", "%08x",
    320 	    bus_space_read_stream_4(sc->sc_devcfg_iot, sc->sc_devcfg_ioh, 0),
    321 	    bus_space_read_4(sc->sc_devcfg_iot, sc->sc_devcfg_ioh, 0));
    322 	return val;
    323 }
    324 
    325 void
    326 virtio_write_device_config_1(struct virtio_softc *sc, int index, uint8_t value)
    327 {
    328 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    329 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    330 
    331 	bus_space_write_1(iot, ioh, index, value);
    332 }
    333 
    334 void
    335 virtio_write_device_config_2(struct virtio_softc *sc, int index,
    336     uint16_t value)
    337 {
    338 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    339 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    340 
    341 	if (BYTE_ORDER != sc->sc_bus_endian)
    342 		value = bswap16(value);
    343 	bus_space_write_2(iot, ioh, index, value);
    344 }
    345 
    346 void
    347 virtio_write_device_config_4(struct virtio_softc *sc, int index,
    348     uint32_t value)
    349 {
    350 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    351 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    352 
    353 	if (BYTE_ORDER != sc->sc_bus_endian)
    354 		value = bswap32(value);
    355 	bus_space_write_4(iot, ioh, index, value);
    356 }
    357 
    358 /*
    359  * The Virtio spec explicitly tells that reading and writing 8 bytes are not
    360  * considered atomic and no triggers may be connected to reading or writing
    361  * it. We access it using two 32 bit writes. For good measure it is stated to
    362  * always write lsb first just in case of a hypervisor bug. See See virtio
    363  * spec 4.1.3.1.
    364  */
    365 void
    366 virtio_write_device_config_8(struct virtio_softc *sc, int index,
    367     uint64_t value)
    368 {
    369 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    370 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    371 	union {
    372 		uint64_t u64;
    373 		uint32_t l[2];
    374 	} v;
    375 
    376 	if (BYTE_ORDER != sc->sc_struct_endian)
    377 		value = bswap64(value);
    378 
    379 	v.u64 = value;
    380 	if (sc->sc_bus_endian != sc->sc_struct_endian) {
    381 		v.l[0] = bswap32(v.l[0]);
    382 		v.l[1] = bswap32(v.l[1]);
    383 	}
    384 
    385 	if (sc->sc_struct_endian == LITTLE_ENDIAN) {
    386 		bus_space_write_4(iot, ioh, index,     v.l[0]);
    387 		bus_space_write_4(iot, ioh, index + 4, v.l[1]);
    388 	} else {
    389 		bus_space_write_4(iot, ioh, index + 4, v.l[1]);
    390 		bus_space_write_4(iot, ioh, index,     v.l[0]);
    391 	}
    392 }
    393 
    394 /*
    395  * In the older virtio spec, device config registers are host endian. On newer
    396  * they are little endian. Some newer devices however explicitly specify their
    397  * register to always be little endian. These functions cater for these.
    398  */
    399 void
    400 virtio_write_device_config_le_2(struct virtio_softc *sc, int index,
    401     uint16_t value)
    402 {
    403 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    404 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    405 
    406 	if (sc->sc_bus_endian != LITTLE_ENDIAN)
    407 		value = bswap16(value);
    408 	bus_space_write_2(iot, ioh, index, value);
    409 }
    410 
    411 void
    412 virtio_write_device_config_le_4(struct virtio_softc *sc, int index,
    413     uint32_t value)
    414 {
    415 	bus_space_tag_t	   iot = sc->sc_devcfg_iot;
    416 	bus_space_handle_t ioh = sc->sc_devcfg_ioh;
    417 
    418 	if (sc->sc_bus_endian != LITTLE_ENDIAN)
    419 		value = bswap32(value);
    420 	bus_space_write_4(iot, ioh, index, value);
    421 }
    422 
    423 
    424 /*
    425  * data structures endian helpers
    426  */
    427 uint16_t
    428 virtio_rw16(struct virtio_softc *sc, uint16_t val)
    429 {
    430 	KASSERT(sc);
    431 	return BYTE_ORDER != sc->sc_struct_endian ? bswap16(val) : val;
    432 }
    433 
    434 uint32_t
    435 virtio_rw32(struct virtio_softc *sc, uint32_t val)
    436 {
    437 	KASSERT(sc);
    438 	return BYTE_ORDER != sc->sc_struct_endian ? bswap32(val) : val;
    439 }
    440 
    441 uint64_t
    442 virtio_rw64(struct virtio_softc *sc, uint64_t val)
    443 {
    444 	KASSERT(sc);
    445 	return BYTE_ORDER != sc->sc_struct_endian ? bswap64(val) : val;
    446 }
    447 
    448 
    449 /*
    450  * Interrupt handler.
    451  */
    452 static void
    453 virtio_soft_intr(void *arg)
    454 {
    455 	struct virtio_softc *sc = arg;
    456 
    457 	KASSERT(sc->sc_intrhand != NULL);
    458 
    459 	(*sc->sc_intrhand)(sc);
    460 }
    461 
    462 /* set to vq->vq_intrhand in virtio_init_vq_vqdone() */
    463 static int
    464 virtio_vq_done(void *xvq)
    465 {
    466 	struct virtqueue *vq = xvq;
    467 
    468 	return vq->vq_done(vq);
    469 }
    470 
    471 static int
    472 virtio_vq_intr(struct virtio_softc *sc)
    473 {
    474 	struct virtqueue *vq;
    475 	int i, r = 0;
    476 
    477 	for (i = 0; i < sc->sc_nvqs; i++) {
    478 		vq = &sc->sc_vqs[i];
    479 		if (virtio_vq_is_enqueued(sc, vq) == 1) {
    480 			r |= (*vq->vq_intrhand)(vq->vq_intrhand_arg);
    481 		}
    482 	}
    483 
    484 	return r;
    485 }
    486 
    487 /*
    488  * dmamap sync operations for a virtqueue.
    489  */
    490 static inline void
    491 vq_sync_descs(struct virtio_softc *sc, struct virtqueue *vq, int ops)
    492 {
    493 
    494 	/* availoffset == sizeof(vring_desc) * vq_num */
    495 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap, 0, vq->vq_availoffset,
    496 	    ops);
    497 }
    498 
    499 static inline void
    500 vq_sync_aring_all(struct virtio_softc *sc, struct virtqueue *vq, int ops)
    501 {
    502 	uint16_t hdrlen = offsetof(struct vring_avail, ring);
    503 	size_t payloadlen = vq->vq_num * sizeof(uint16_t);
    504 	size_t usedlen = 0;
    505 
    506 	if (sc->sc_active_features & VIRTIO_F_RING_EVENT_IDX)
    507 		usedlen = sizeof(uint16_t);
    508 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap,
    509 	    vq->vq_availoffset, hdrlen + payloadlen + usedlen, ops);
    510 }
    511 
    512 static inline void
    513 vq_sync_aring_header(struct virtio_softc *sc, struct virtqueue *vq, int ops)
    514 {
    515 	uint16_t hdrlen = offsetof(struct vring_avail, ring);
    516 
    517 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap,
    518 	    vq->vq_availoffset, hdrlen, ops);
    519 }
    520 
    521 static inline void
    522 vq_sync_aring_payload(struct virtio_softc *sc, struct virtqueue *vq, int ops)
    523 {
    524 	uint16_t hdrlen = offsetof(struct vring_avail, ring);
    525 	size_t payloadlen = vq->vq_num * sizeof(uint16_t);
    526 
    527 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap,
    528 	    vq->vq_availoffset + hdrlen, payloadlen, ops);
    529 }
    530 
    531 static inline void
    532 vq_sync_aring_used(struct virtio_softc *sc, struct virtqueue *vq, int ops)
    533 {
    534 	uint16_t hdrlen = offsetof(struct vring_avail, ring);
    535 	size_t payloadlen = vq->vq_num * sizeof(uint16_t);
    536 	size_t usedlen = sizeof(uint16_t);
    537 
    538 	if ((sc->sc_active_features & VIRTIO_F_RING_EVENT_IDX) == 0)
    539 		return;
    540 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap,
    541 	    vq->vq_availoffset + hdrlen + payloadlen, usedlen, ops);
    542 }
    543 
    544 static inline void
    545 vq_sync_uring_all(struct virtio_softc *sc, struct virtqueue *vq, int ops)
    546 {
    547 	uint16_t hdrlen = offsetof(struct vring_used, ring);
    548 	size_t payloadlen = vq->vq_num * sizeof(struct vring_used_elem);
    549 	size_t availlen = 0;
    550 
    551 	if (sc->sc_active_features & VIRTIO_F_RING_EVENT_IDX)
    552 		availlen = sizeof(uint16_t);
    553 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap,
    554 	    vq->vq_usedoffset, hdrlen + payloadlen + availlen, ops);
    555 }
    556 
    557 static inline void
    558 vq_sync_uring_header(struct virtio_softc *sc, struct virtqueue *vq, int ops)
    559 {
    560 	uint16_t hdrlen = offsetof(struct vring_used, ring);
    561 
    562 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap,
    563 	    vq->vq_usedoffset, hdrlen, ops);
    564 }
    565 
    566 static inline void
    567 vq_sync_uring_payload(struct virtio_softc *sc, struct virtqueue *vq, int ops)
    568 {
    569 	uint16_t hdrlen = offsetof(struct vring_used, ring);
    570 	size_t payloadlen = vq->vq_num * sizeof(struct vring_used_elem);
    571 
    572 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap,
    573 	    vq->vq_usedoffset + hdrlen, payloadlen, ops);
    574 }
    575 
    576 static inline void
    577 vq_sync_uring_avail(struct virtio_softc *sc, struct virtqueue *vq, int ops)
    578 {
    579 	uint16_t hdrlen = offsetof(struct vring_used, ring);
    580 	size_t payloadlen = vq->vq_num * sizeof(struct vring_used_elem);
    581 	size_t availlen = sizeof(uint16_t);
    582 
    583 	if ((sc->sc_active_features & VIRTIO_F_RING_EVENT_IDX) == 0)
    584 		return;
    585 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap,
    586 	    vq->vq_usedoffset + hdrlen + payloadlen, availlen, ops);
    587 }
    588 
    589 static inline void
    590 vq_sync_indirect(struct virtio_softc *sc, struct virtqueue *vq, int slot,
    591     int ops)
    592 {
    593 	int offset = vq->vq_indirectoffset +
    594 	    sizeof(struct vring_desc) * vq->vq_maxnsegs * slot;
    595 
    596 	bus_dmamap_sync(sc->sc_dmat, vq->vq_dmamap,
    597 	    offset, sizeof(struct vring_desc) * vq->vq_maxnsegs, ops);
    598 }
    599 
    600 bool
    601 virtio_vq_is_enqueued(struct virtio_softc *sc, struct virtqueue *vq)
    602 {
    603 
    604 	if (vq->vq_queued) {
    605 		vq->vq_queued = 0;
    606 		vq_sync_aring_all(sc, vq, BUS_DMASYNC_POSTWRITE);
    607 	}
    608 
    609 	vq_sync_uring_header(sc, vq, BUS_DMASYNC_POSTREAD);
    610 	if (vq->vq_used_idx == virtio_rw16(sc, vq->vq_used->idx)) {
    611 		vq_sync_uring_header(sc, vq, BUS_DMASYNC_PREREAD);
    612 		return 0;
    613 	}
    614 	vq_sync_uring_payload(sc, vq, BUS_DMASYNC_POSTREAD);
    615 	return 1;
    616 }
    617 
    618 /*
    619  * Increase the event index in order to delay interrupts.
    620  */
    621 int
    622 virtio_postpone_intr(struct virtio_softc *sc, struct virtqueue *vq,
    623     uint16_t nslots)
    624 {
    625 	uint16_t	idx, nused;
    626 
    627 	idx = vq->vq_used_idx + nslots;
    628 
    629 	/* set the new event index: avail_ring->used_event = idx */
    630 	*vq->vq_used_event = virtio_rw16(sc, idx);
    631 	vq_sync_aring_used(vq->vq_owner, vq, BUS_DMASYNC_PREWRITE);
    632 	vq->vq_queued++;
    633 
    634 	vq_sync_uring_header(sc, vq, BUS_DMASYNC_POSTREAD);
    635 	nused = (uint16_t)
    636 	    (virtio_rw16(sc, vq->vq_used->idx) - vq->vq_used_idx);
    637 	vq_sync_uring_header(sc, vq, BUS_DMASYNC_PREREAD);
    638 	KASSERT(nused <= vq->vq_num);
    639 
    640 	return nslots < nused;
    641 }
    642 
    643 /*
    644  * Postpone interrupt until 3/4 of the available descriptors have been
    645  * consumed.
    646  */
    647 int
    648 virtio_postpone_intr_smart(struct virtio_softc *sc, struct virtqueue *vq)
    649 {
    650 	uint16_t	nslots;
    651 
    652 	nslots = (uint16_t)
    653 	    (virtio_rw16(sc, vq->vq_avail->idx) - vq->vq_used_idx) * 3 / 4;
    654 
    655 	return virtio_postpone_intr(sc, vq, nslots);
    656 }
    657 
    658 /*
    659  * Postpone interrupt until all of the available descriptors have been
    660  * consumed.
    661  */
    662 int
    663 virtio_postpone_intr_far(struct virtio_softc *sc, struct virtqueue *vq)
    664 {
    665 	uint16_t	nslots;
    666 
    667 	nslots = (uint16_t)
    668 	    (virtio_rw16(sc, vq->vq_avail->idx) - vq->vq_used_idx);
    669 
    670 	return virtio_postpone_intr(sc, vq, nslots);
    671 }
    672 
    673 /*
    674  * Start/stop vq interrupt.  No guarantee.
    675  */
    676 void
    677 virtio_stop_vq_intr(struct virtio_softc *sc, struct virtqueue *vq)
    678 {
    679 
    680 	if (sc->sc_active_features & VIRTIO_F_RING_EVENT_IDX) {
    681 		/*
    682 		 * No way to disable the interrupt completely with
    683 		 * RingEventIdx. Instead advance used_event by half the
    684 		 * possible value. This won't happen soon and is far enough in
    685 		 * the past to not trigger a spurious interrupt.
    686 		 */
    687 		*vq->vq_used_event = virtio_rw16(sc, vq->vq_used_idx + 0x8000);
    688 		vq_sync_aring_used(sc, vq, BUS_DMASYNC_PREWRITE);
    689 	} else {
    690 		vq->vq_avail->flags |=
    691 		    virtio_rw16(sc, VRING_AVAIL_F_NO_INTERRUPT);
    692 		vq_sync_aring_header(sc, vq, BUS_DMASYNC_PREWRITE);
    693 	}
    694 	vq->vq_queued++;
    695 }
    696 
    697 int
    698 virtio_start_vq_intr(struct virtio_softc *sc, struct virtqueue *vq)
    699 {
    700 
    701 	if (sc->sc_active_features & VIRTIO_F_RING_EVENT_IDX) {
    702 		/*
    703 		 * If event index feature is negotiated, enabling interrupts
    704 		 * is done through setting the latest consumed index in the
    705 		 * used_event field
    706 		 */
    707 		*vq->vq_used_event = virtio_rw16(sc, vq->vq_used_idx);
    708 		vq_sync_aring_used(sc, vq, BUS_DMASYNC_PREWRITE);
    709 	} else {
    710 		vq->vq_avail->flags &=
    711 		    ~virtio_rw16(sc, VRING_AVAIL_F_NO_INTERRUPT);
    712 		vq_sync_aring_header(sc, vq, BUS_DMASYNC_PREWRITE);
    713 	}
    714 	vq->vq_queued++;
    715 
    716 	/*
    717 	 * Ensure we announce to the host side that we are accepting
    718 	 * interrupts _before_ we check whether any pending events had
    719 	 * come over the queue while we weren't accepting interrupts.
    720 	 */
    721 	paravirt_membar_sync();
    722 
    723 	vq_sync_uring_header(sc, vq, BUS_DMASYNC_POSTREAD);
    724 	if (vq->vq_used_idx == virtio_rw16(sc, vq->vq_used->idx)) {
    725 		vq_sync_uring_header(sc, vq, BUS_DMASYNC_PREREAD);
    726 		return 0;
    727 	}
    728 	vq_sync_uring_payload(sc, vq, BUS_DMASYNC_POSTREAD);
    729 	return 1;
    730 }
    731 
    732 /*
    733  * Initialize vq structure.
    734  */
    735 /*
    736  * Reset virtqueue parameters
    737  */
    738 static void
    739 virtio_reset_vq(struct virtio_softc *sc, struct virtqueue *vq)
    740 {
    741 	struct vring_desc *vds;
    742 	int i, j;
    743 	int vq_size = vq->vq_num;
    744 
    745 	memset(vq->vq_vaddr, 0, vq->vq_bytesize);
    746 
    747 	/* build the descriptor chain for free slot management */
    748 	vds = vq->vq_desc;
    749 	for (i = 0; i < vq_size - 1; i++) {
    750 		vds[i].next = virtio_rw16(sc, i + 1);
    751 	}
    752 	vds[i].next = virtio_rw16(sc, VRING_DESC_CHAIN_END);
    753 	vq->vq_free_idx = 0;
    754 
    755 	/* build the indirect descriptor chain */
    756 	if (vq->vq_indirect != NULL) {
    757 		struct vring_desc *vd;
    758 
    759 		for (i = 0; i < vq_size; i++) {
    760 			vd = vq->vq_indirect;
    761 			vd += vq->vq_maxnsegs * i;
    762 			for (j = 0; j < vq->vq_maxnsegs - 1; j++) {
    763 				vd[j].next = virtio_rw16(sc, j + 1);
    764 			}
    765 		}
    766 	}
    767 
    768 	/* enqueue/dequeue status */
    769 	vq->vq_avail_idx = 0;
    770 	vq->vq_used_idx = 0;
    771 	vq->vq_queued = 0;
    772 	vq_sync_uring_all(sc, vq, BUS_DMASYNC_PREREAD);
    773 	vq->vq_queued++;
    774 }
    775 
    776 /* Initialize vq */
    777 void
    778 virtio_init_vq_vqdone(struct virtio_softc *sc, struct virtqueue *vq,
    779     int index, int (*vq_done)(struct virtqueue *))
    780 {
    781 
    782 	virtio_init_vq(sc, vq, index, virtio_vq_done, vq);
    783 	vq->vq_done = vq_done;
    784 }
    785 
    786 void
    787 virtio_init_vq(struct virtio_softc *sc, struct virtqueue *vq, int index,
    788    int (*func)(void *), void *arg)
    789 {
    790 
    791 	memset(vq, 0, sizeof(*vq));
    792 
    793 	vq->vq_owner = sc;
    794 	vq->vq_num = sc->sc_ops->read_queue_size(sc, index);
    795 	vq->vq_index = index;
    796 	vq->vq_intrhand = func;
    797 	vq->vq_intrhand_arg = arg;
    798 }
    799 
    800 /*
    801  * Allocate/free a vq.
    802  */
    803 int
    804 virtio_alloc_vq(struct virtio_softc *sc, struct virtqueue *vq,
    805     int maxsegsize, int maxnsegs, const char *name)
    806 {
    807 	bus_size_t size_desc, size_avail, size_used, size_indirect;
    808 	bus_size_t allocsize = 0, size_desc_avail;
    809 	int rsegs, r, hdrlen;
    810 	unsigned int vq_num;
    811 #define VIRTQUEUE_ALIGN(n)	roundup(n, VIRTIO_PAGE_SIZE)
    812 
    813 	vq_num = vq->vq_num;
    814 
    815 	if (vq_num == 0) {
    816 		aprint_error_dev(sc->sc_dev,
    817 		    "virtqueue not exist, index %d for %s\n",
    818 		    vq->vq_index, name);
    819 		goto err;
    820 	}
    821 
    822 	hdrlen = sc->sc_active_features & VIRTIO_F_RING_EVENT_IDX ? 3 : 2;
    823 
    824 	size_desc = sizeof(vq->vq_desc[0]) * vq_num;
    825 	size_avail = sizeof(uint16_t) * hdrlen
    826 	    + sizeof(vq->vq_avail[0].ring[0]) * vq_num;
    827 	size_used = sizeof(uint16_t) *hdrlen
    828 	    + sizeof(vq->vq_used[0].ring[0]) * vq_num;
    829 	size_indirect = (sc->sc_indirect && maxnsegs >= MINSEG_INDIRECT) ?
    830 	    sizeof(struct vring_desc) * maxnsegs * vq_num : 0;
    831 
    832 	size_desc_avail = VIRTQUEUE_ALIGN(size_desc + size_avail);
    833 	size_used = VIRTQUEUE_ALIGN(size_used);
    834 
    835 	allocsize = size_desc_avail + size_used + size_indirect;
    836 
    837 	/* alloc and map the memory */
    838 	r = bus_dmamem_alloc(sc->sc_dmat, allocsize, VIRTIO_PAGE_SIZE, 0,
    839 	    &vq->vq_segs[0], 1, &rsegs, BUS_DMA_WAITOK);
    840 	if (r != 0) {
    841 		aprint_error_dev(sc->sc_dev,
    842 		    "virtqueue %d for %s allocation failed, "
    843 		    "error code %d\n", vq->vq_index, name, r);
    844 		goto err;
    845 	}
    846 
    847 	r = bus_dmamem_map(sc->sc_dmat, &vq->vq_segs[0], rsegs, allocsize,
    848 	    &vq->vq_vaddr, BUS_DMA_WAITOK);
    849 	if (r != 0) {
    850 		aprint_error_dev(sc->sc_dev,
    851 		    "virtqueue %d for %s map failed, "
    852 		    "error code %d\n", vq->vq_index, name, r);
    853 		goto err;
    854 	}
    855 
    856 	r = bus_dmamap_create(sc->sc_dmat, allocsize, 1, allocsize, 0,
    857 	    BUS_DMA_WAITOK, &vq->vq_dmamap);
    858 	if (r != 0) {
    859 		aprint_error_dev(sc->sc_dev,
    860 		    "virtqueue %d for %s dmamap creation failed, "
    861 		    "error code %d\n", vq->vq_index, name, r);
    862 		goto err;
    863 	}
    864 
    865 	r = bus_dmamap_load(sc->sc_dmat, vq->vq_dmamap,
    866 	    vq->vq_vaddr, allocsize, NULL, BUS_DMA_WAITOK);
    867 	if (r != 0) {
    868 		aprint_error_dev(sc->sc_dev,
    869 		    "virtqueue %d for %s dmamap load failed, "
    870 		    "error code %d\n", vq->vq_index, name, r);
    871 		goto err;
    872 	}
    873 
    874 	vq->vq_bytesize = allocsize;
    875 	vq->vq_maxsegsize = maxsegsize;
    876 	vq->vq_maxnsegs = maxnsegs;
    877 
    878 #define VIRTIO_PTR(base, offset)	(void *)((intptr_t)(base) + (offset))
    879 	/* initialize vring pointers */
    880 	vq->vq_desc = VIRTIO_PTR(vq->vq_vaddr, 0);
    881 	vq->vq_availoffset = size_desc;
    882 	vq->vq_avail = VIRTIO_PTR(vq->vq_vaddr, vq->vq_availoffset);
    883 	vq->vq_used_event = VIRTIO_PTR(vq->vq_avail,
    884 	    offsetof(struct vring_avail, ring[vq_num]));
    885 	vq->vq_usedoffset = size_desc_avail;
    886 	vq->vq_used = VIRTIO_PTR(vq->vq_vaddr, vq->vq_usedoffset);
    887 	vq->vq_avail_event = VIRTIO_PTR(vq->vq_used,
    888 	    offsetof(struct vring_used, ring[vq_num]));
    889 
    890 	if (size_indirect > 0) {
    891 		vq->vq_indirectoffset = size_desc_avail + size_used;
    892 		vq->vq_indirect = VIRTIO_PTR(vq->vq_vaddr,
    893 		    vq->vq_indirectoffset);
    894 	}
    895 #undef VIRTIO_PTR
    896 
    897 	vq->vq_descx = kmem_zalloc(sizeof(vq->vq_descx[0]) * vq_num,
    898 	    KM_SLEEP);
    899 
    900 	mutex_init(&vq->vq_freedesc_lock, MUTEX_SPIN, sc->sc_ipl);
    901 	mutex_init(&vq->vq_aring_lock, MUTEX_SPIN, sc->sc_ipl);
    902 	mutex_init(&vq->vq_uring_lock, MUTEX_SPIN, sc->sc_ipl);
    903 
    904 	virtio_reset_vq(sc, vq);
    905 
    906 	aprint_verbose_dev(sc->sc_dev,
    907 	    "allocated %" PRIuBUSSIZE " byte for virtqueue %d for %s, "
    908 	    "size %d\n", allocsize, vq->vq_index, name, vq_num);
    909 	if (size_indirect > 0)
    910 		aprint_verbose_dev(sc->sc_dev,
    911 		    "using %" PRIuBUSSIZE " byte (%d entries) indirect "
    912 		    "descriptors\n", size_indirect, maxnsegs * vq_num);
    913 
    914 	return 0;
    915 
    916 err:
    917 	sc->sc_ops->setup_queue(sc, vq->vq_index, 0);
    918 	if (vq->vq_dmamap)
    919 		bus_dmamap_destroy(sc->sc_dmat, vq->vq_dmamap);
    920 	if (vq->vq_vaddr)
    921 		bus_dmamem_unmap(sc->sc_dmat, vq->vq_vaddr, allocsize);
    922 	if (vq->vq_segs[0].ds_addr)
    923 		bus_dmamem_free(sc->sc_dmat, &vq->vq_segs[0], 1);
    924 	memset(vq, 0, sizeof(*vq));
    925 
    926 	return -1;
    927 }
    928 
    929 int
    930 virtio_free_vq(struct virtio_softc *sc, struct virtqueue *vq)
    931 {
    932 	uint16_t s;
    933 	size_t i;
    934 
    935 	if (vq->vq_vaddr == NULL)
    936 		return 0;
    937 
    938 	/* device must be already deactivated */
    939 	/* confirm the vq is empty */
    940 	s = vq->vq_free_idx;
    941 	i = 0;
    942 	while (s != virtio_rw16(sc, VRING_DESC_CHAIN_END)) {
    943 		s = vq->vq_desc[s].next;
    944 		i++;
    945 	}
    946 	if (i != vq->vq_num) {
    947 		printf("%s: freeing non-empty vq, index %d\n",
    948 		    device_xname(sc->sc_dev), vq->vq_index);
    949 		return EBUSY;
    950 	}
    951 
    952 	/* tell device that there's no virtqueue any longer */
    953 	sc->sc_ops->setup_queue(sc, vq->vq_index, 0);
    954 
    955 	vq_sync_aring_all(sc, vq, BUS_DMASYNC_POSTWRITE);
    956 
    957 	kmem_free(vq->vq_descx, sizeof(vq->vq_descx[0]) * vq->vq_num);
    958 	bus_dmamap_unload(sc->sc_dmat, vq->vq_dmamap);
    959 	bus_dmamap_destroy(sc->sc_dmat, vq->vq_dmamap);
    960 	bus_dmamem_unmap(sc->sc_dmat, vq->vq_vaddr, vq->vq_bytesize);
    961 	bus_dmamem_free(sc->sc_dmat, &vq->vq_segs[0], 1);
    962 	mutex_destroy(&vq->vq_freedesc_lock);
    963 	mutex_destroy(&vq->vq_uring_lock);
    964 	mutex_destroy(&vq->vq_aring_lock);
    965 	memset(vq, 0, sizeof(*vq));
    966 
    967 	return 0;
    968 }
    969 
    970 /*
    971  * Free descriptor management.
    972  */
    973 static int
    974 vq_alloc_slot_locked(struct virtio_softc *sc, struct virtqueue *vq,
    975     size_t nslots)
    976 {
    977 	struct vring_desc *vd;
    978 	uint16_t head, tail;
    979 	size_t i;
    980 
    981 	KASSERT(mutex_owned(&vq->vq_freedesc_lock));
    982 
    983 	head = tail = virtio_rw16(sc, vq->vq_free_idx);
    984 	for (i = 0; i < nslots - 1; i++) {
    985 		if (tail == VRING_DESC_CHAIN_END)
    986 			return VRING_DESC_CHAIN_END;
    987 
    988 		vd = &vq->vq_desc[tail];
    989 		vd->flags = virtio_rw16(sc, VRING_DESC_F_NEXT);
    990 		tail = virtio_rw16(sc, vd->next);
    991 	}
    992 
    993 	if (tail == VRING_DESC_CHAIN_END)
    994 		return VRING_DESC_CHAIN_END;
    995 
    996 	vd = &vq->vq_desc[tail];
    997 	vd->flags = virtio_rw16(sc, 0);
    998 	vq->vq_free_idx = vd->next;
    999 
   1000 	return head;
   1001 }
   1002 static uint16_t
   1003 vq_alloc_slot(struct virtio_softc *sc, struct virtqueue *vq, size_t nslots)
   1004 {
   1005 	uint16_t rv;
   1006 
   1007 	mutex_enter(&vq->vq_freedesc_lock);
   1008 	rv = vq_alloc_slot_locked(sc, vq, nslots);
   1009 	mutex_exit(&vq->vq_freedesc_lock);
   1010 
   1011 	return rv;
   1012 }
   1013 
   1014 static void
   1015 vq_free_slot(struct virtio_softc *sc, struct virtqueue *vq, uint16_t slot)
   1016 {
   1017 	struct vring_desc *vd;
   1018 	uint16_t s;
   1019 
   1020 	mutex_enter(&vq->vq_freedesc_lock);
   1021 	vd = &vq->vq_desc[slot];
   1022 	while ((vd->flags & virtio_rw16(sc, VRING_DESC_F_NEXT)) != 0) {
   1023 		s = virtio_rw16(sc, vd->next);
   1024 		vd = &vq->vq_desc[s];
   1025 	}
   1026 	vd->next = vq->vq_free_idx;
   1027 	vq->vq_free_idx = virtio_rw16(sc, slot);
   1028 	mutex_exit(&vq->vq_freedesc_lock);
   1029 }
   1030 
   1031 /*
   1032  * Enqueue several dmamaps as a single request.
   1033  */
   1034 /*
   1035  * Typical usage:
   1036  *  <queue size> number of followings are stored in arrays
   1037  *  - command blocks (in dmamem) should be pre-allocated and mapped
   1038  *  - dmamaps for command blocks should be pre-allocated and loaded
   1039  *  - dmamaps for payload should be pre-allocated
   1040  *      r = virtio_enqueue_prep(sc, vq, &slot);		// allocate a slot
   1041  *	if (r)		// currently 0 or EAGAIN
   1042  *		return r;
   1043  *	r = bus_dmamap_load(dmat, dmamap_payload[slot], data, count, ..);
   1044  *	if (r) {
   1045  *		virtio_enqueue_abort(sc, vq, slot);
   1046  *		return r;
   1047  *	}
   1048  *	r = virtio_enqueue_reserve(sc, vq, slot,
   1049  *	    dmamap_payload[slot]->dm_nsegs + 1);
   1050  *							// ^ +1 for command
   1051  *	if (r) {	// currently 0 or EAGAIN
   1052  *		bus_dmamap_unload(dmat, dmamap_payload[slot]);
   1053  *		return r;				// do not call abort()
   1054  *	}
   1055  *	<setup and prepare commands>
   1056  *	bus_dmamap_sync(dmat, dmamap_cmd[slot],... BUS_DMASYNC_PREWRITE);
   1057  *	bus_dmamap_sync(dmat, dmamap_payload[slot],...);
   1058  *	virtio_enqueue(sc, vq, slot, dmamap_cmd[slot], false);
   1059  *	virtio_enqueue(sc, vq, slot, dmamap_payload[slot], iswrite);
   1060  *	virtio_enqueue_commit(sc, vq, slot, true);
   1061  */
   1062 
   1063 /*
   1064  * enqueue_prep: allocate a slot number
   1065  */
   1066 int
   1067 virtio_enqueue_prep(struct virtio_softc *sc, struct virtqueue *vq, int *slotp)
   1068 {
   1069 	uint16_t slot;
   1070 
   1071 	KASSERT(sc->sc_child_state == VIRTIO_CHILD_ATTACH_FINISHED);
   1072 	KASSERT(slotp != NULL);
   1073 
   1074 	slot = vq_alloc_slot(sc, vq, 1);
   1075 	if (slot == VRING_DESC_CHAIN_END)
   1076 		return EAGAIN;
   1077 
   1078 	*slotp = slot;
   1079 
   1080 	return 0;
   1081 }
   1082 
   1083 /*
   1084  * enqueue_reserve: allocate remaining slots and build the descriptor chain.
   1085  */
   1086 int
   1087 virtio_enqueue_reserve(struct virtio_softc *sc, struct virtqueue *vq,
   1088     int slot, int nsegs)
   1089 {
   1090 	struct vring_desc *vd;
   1091 	struct vring_desc_extra *vdx;
   1092 	int i;
   1093 
   1094 	KASSERT(1 <= nsegs);
   1095 	KASSERT(nsegs <= vq->vq_num);
   1096 
   1097 	vdx = &vq->vq_descx[slot];
   1098 	vd = &vq->vq_desc[slot];
   1099 
   1100 	KASSERT((vd->flags & virtio_rw16(sc, VRING_DESC_F_NEXT)) == 0);
   1101 
   1102 	if ((vq->vq_indirect != NULL) &&
   1103 	    (nsegs >= MINSEG_INDIRECT) &&
   1104 	    (nsegs <= vq->vq_maxnsegs))
   1105 		vdx->use_indirect = true;
   1106 	else
   1107 		vdx->use_indirect = false;
   1108 
   1109 	if (vdx->use_indirect) {
   1110 		uint64_t addr;
   1111 
   1112 		addr = vq->vq_dmamap->dm_segs[0].ds_addr
   1113 		    + vq->vq_indirectoffset;
   1114 		addr += sizeof(struct vring_desc)
   1115 		    * vq->vq_maxnsegs * slot;
   1116 
   1117 		vd->addr  = virtio_rw64(sc, addr);
   1118 		vd->len   = virtio_rw32(sc, sizeof(struct vring_desc) * nsegs);
   1119 		vd->flags = virtio_rw16(sc, VRING_DESC_F_INDIRECT);
   1120 
   1121 		vd = &vq->vq_indirect[vq->vq_maxnsegs * slot];
   1122 		vdx->desc_base = vd;
   1123 		vdx->desc_free_idx = 0;
   1124 
   1125 		for (i = 0; i < nsegs - 1; i++) {
   1126 			vd[i].flags = virtio_rw16(sc, VRING_DESC_F_NEXT);
   1127 		}
   1128 		vd[i].flags  = virtio_rw16(sc, 0);
   1129 	} else {
   1130 		if (nsegs > 1) {
   1131 			uint16_t s;
   1132 
   1133 			s = vq_alloc_slot(sc, vq, nsegs - 1);
   1134 			if (s == VRING_DESC_CHAIN_END) {
   1135 				vq_free_slot(sc, vq, slot);
   1136 				return EAGAIN;
   1137 			}
   1138 			vd->next = virtio_rw16(sc, s);
   1139 			vd->flags = virtio_rw16(sc, VRING_DESC_F_NEXT);
   1140 		}
   1141 
   1142 		vdx->desc_base = &vq->vq_desc[0];
   1143 		vdx->desc_free_idx = slot;
   1144 	}
   1145 
   1146 	return 0;
   1147 }
   1148 
   1149 /*
   1150  * enqueue: enqueue a single dmamap.
   1151  */
   1152 int
   1153 virtio_enqueue(struct virtio_softc *sc, struct virtqueue *vq, int slot,
   1154     bus_dmamap_t dmamap, bool write)
   1155 {
   1156 	struct vring_desc *vds;
   1157 	struct vring_desc_extra *vdx;
   1158 	uint16_t s;
   1159 	int i;
   1160 
   1161 	KASSERT(dmamap->dm_nsegs > 0);
   1162 
   1163 	vdx = &vq->vq_descx[slot];
   1164 	vds = vdx->desc_base;
   1165 	s = vdx->desc_free_idx;
   1166 
   1167 	KASSERT(vds != NULL);
   1168 
   1169 	for (i = 0; i < dmamap->dm_nsegs; i++) {
   1170 		KASSERT(s != VRING_DESC_CHAIN_END);
   1171 
   1172 		vds[s].addr = virtio_rw64(sc, dmamap->dm_segs[i].ds_addr);
   1173 		vds[s].len  = virtio_rw32(sc, dmamap->dm_segs[i].ds_len);
   1174 		if (!write)
   1175 			vds[s].flags |= virtio_rw16(sc, VRING_DESC_F_WRITE);
   1176 
   1177 		if ((vds[s].flags & virtio_rw16(sc, VRING_DESC_F_NEXT)) == 0) {
   1178 			s = VRING_DESC_CHAIN_END;
   1179 		} else {
   1180 			s = virtio_rw16(sc, vds[s].next);
   1181 		}
   1182 	}
   1183 
   1184 	vdx->desc_free_idx = s;
   1185 
   1186 	return 0;
   1187 }
   1188 
   1189 int
   1190 virtio_enqueue_p(struct virtio_softc *sc, struct virtqueue *vq, int slot,
   1191     bus_dmamap_t dmamap, bus_addr_t start, bus_size_t len,
   1192     bool write)
   1193 {
   1194 	struct vring_desc_extra *vdx;
   1195 	struct vring_desc *vds;
   1196 	uint16_t s;
   1197 
   1198 	vdx = &vq->vq_descx[slot];
   1199 	vds = vdx->desc_base;
   1200 	s = vdx->desc_free_idx;
   1201 
   1202 	KASSERT(s != VRING_DESC_CHAIN_END);
   1203 	KASSERT(vds != NULL);
   1204 	KASSERT(dmamap->dm_nsegs == 1); /* XXX */
   1205 	KASSERT(dmamap->dm_segs[0].ds_len > start);
   1206 	KASSERT(dmamap->dm_segs[0].ds_len >= start + len);
   1207 
   1208 	vds[s].addr = virtio_rw64(sc, dmamap->dm_segs[0].ds_addr + start);
   1209 	vds[s].len  = virtio_rw32(sc, len);
   1210 	if (!write)
   1211 		vds[s].flags |= virtio_rw16(sc, VRING_DESC_F_WRITE);
   1212 
   1213 	if ((vds[s].flags & virtio_rw16(sc, VRING_DESC_F_NEXT)) == 0) {
   1214 		s = VRING_DESC_CHAIN_END;
   1215 	} else {
   1216 		s = virtio_rw16(sc, vds[s].next);
   1217 	}
   1218 
   1219 	vdx->desc_free_idx = s;
   1220 
   1221 	return 0;
   1222 }
   1223 
   1224 /*
   1225  * enqueue_commit: add it to the aring.
   1226  */
   1227 int
   1228 virtio_enqueue_commit(struct virtio_softc *sc, struct virtqueue *vq, int slot,
   1229     bool notifynow)
   1230 {
   1231 
   1232 	if (slot < 0) {
   1233 		mutex_enter(&vq->vq_aring_lock);
   1234 		goto notify;
   1235 	}
   1236 
   1237 	vq_sync_descs(sc, vq, BUS_DMASYNC_PREWRITE);
   1238 	if (vq->vq_descx[slot].use_indirect)
   1239 		vq_sync_indirect(sc, vq, slot, BUS_DMASYNC_PREWRITE);
   1240 
   1241 	mutex_enter(&vq->vq_aring_lock);
   1242 	vq->vq_avail->ring[(vq->vq_avail_idx++) % vq->vq_num] =
   1243 	    virtio_rw16(sc, slot);
   1244 
   1245 notify:
   1246 	if (notifynow) {
   1247 		uint16_t o, n, t;
   1248 		uint16_t flags;
   1249 
   1250 		o = virtio_rw16(sc, vq->vq_avail->idx) - 1;
   1251 		n = vq->vq_avail_idx;
   1252 
   1253 		/*
   1254 		 * Prepare for `device->CPU' (host->guest) transfer
   1255 		 * into the buffer.  This must happen before we commit
   1256 		 * the vq->vq_avail->idx update to ensure we're not
   1257 		 * still using the buffer in case program-prior loads
   1258 		 * or stores in it get delayed past the store to
   1259 		 * vq->vq_avail->idx.
   1260 		 */
   1261 		vq_sync_uring_all(sc, vq, BUS_DMASYNC_PREREAD);
   1262 
   1263 		/* ensure payload is published, then avail idx */
   1264 		vq_sync_aring_payload(sc, vq, BUS_DMASYNC_PREWRITE);
   1265 		vq->vq_avail->idx = virtio_rw16(sc, vq->vq_avail_idx);
   1266 		vq_sync_aring_header(sc, vq, BUS_DMASYNC_PREWRITE);
   1267 		vq->vq_queued++;
   1268 
   1269 		/*
   1270 		 * Ensure we publish the avail idx _before_ we check whether
   1271 		 * the host needs to notified.
   1272 		 */
   1273 		paravirt_membar_sync();
   1274 
   1275 		if (sc->sc_active_features & VIRTIO_F_RING_EVENT_IDX) {
   1276 			vq_sync_uring_avail(sc, vq, BUS_DMASYNC_POSTREAD);
   1277 			t = virtio_rw16(sc, *vq->vq_avail_event) + 1;
   1278 			vq_sync_uring_avail(sc, vq, BUS_DMASYNC_PREREAD);
   1279 			if ((uint16_t) (n - t) < (uint16_t) (n - o))
   1280 				sc->sc_ops->kick(sc, vq->vq_index);
   1281 		} else {
   1282 			vq_sync_uring_header(sc, vq, BUS_DMASYNC_POSTREAD);
   1283 			flags = virtio_rw16(sc, vq->vq_used->flags);
   1284 			vq_sync_uring_header(sc, vq, BUS_DMASYNC_PREREAD);
   1285 			if (!(flags & VRING_USED_F_NO_NOTIFY))
   1286 				sc->sc_ops->kick(sc, vq->vq_index);
   1287 		}
   1288 	}
   1289 	mutex_exit(&vq->vq_aring_lock);
   1290 
   1291 	return 0;
   1292 }
   1293 
   1294 /*
   1295  * enqueue_abort: rollback.
   1296  */
   1297 int
   1298 virtio_enqueue_abort(struct virtio_softc *sc, struct virtqueue *vq, int slot)
   1299 {
   1300 	struct vring_desc_extra *vdx;
   1301 
   1302 	vdx = &vq->vq_descx[slot];
   1303 	vdx->desc_free_idx = VRING_DESC_CHAIN_END;
   1304 	vdx->desc_base = NULL;
   1305 
   1306 	vq_free_slot(sc, vq, slot);
   1307 
   1308 	return 0;
   1309 }
   1310 
   1311 /*
   1312  * Dequeue a request.
   1313  */
   1314 /*
   1315  * dequeue: dequeue a request from uring; dmamap_sync for uring is
   1316  *	    already done in the interrupt handler.
   1317  */
   1318 int
   1319 virtio_dequeue(struct virtio_softc *sc, struct virtqueue *vq,
   1320     int *slotp, int *lenp)
   1321 {
   1322 	uint16_t slot, usedidx;
   1323 
   1324 	if (vq->vq_used_idx == virtio_rw16(sc, vq->vq_used->idx))
   1325 		return ENOENT;
   1326 	mutex_enter(&vq->vq_uring_lock);
   1327 	usedidx = vq->vq_used_idx++;
   1328 	mutex_exit(&vq->vq_uring_lock);
   1329 	usedidx %= vq->vq_num;
   1330 	slot = virtio_rw32(sc, vq->vq_used->ring[usedidx].id);
   1331 
   1332 	if (vq->vq_descx[slot].use_indirect)
   1333 		vq_sync_indirect(sc, vq, slot, BUS_DMASYNC_POSTWRITE);
   1334 
   1335 	if (slotp)
   1336 		*slotp = slot;
   1337 	if (lenp)
   1338 		*lenp = virtio_rw32(sc, vq->vq_used->ring[usedidx].len);
   1339 
   1340 	return 0;
   1341 }
   1342 
   1343 /*
   1344  * dequeue_commit: complete dequeue; the slot is recycled for future use.
   1345  *                 if you forget to call this the slot will be leaked.
   1346  */
   1347 int
   1348 virtio_dequeue_commit(struct virtio_softc *sc, struct virtqueue *vq, int slot)
   1349 {
   1350 	struct vring_desc_extra *vdx;
   1351 
   1352 	vdx = &vq->vq_descx[slot];
   1353 	vdx->desc_base = NULL;
   1354 	vdx->desc_free_idx = VRING_DESC_CHAIN_END;
   1355 
   1356 	vq_free_slot(sc, vq, slot);
   1357 
   1358 	return 0;
   1359 }
   1360 
   1361 /*
   1362  * Attach a child, fill all the members.
   1363  */
   1364 void
   1365 virtio_child_attach_start(struct virtio_softc *sc, device_t child, int ipl,
   1366     uint64_t req_features, const char *feat_bits)
   1367 {
   1368 	char buf[1024];
   1369 
   1370 	KASSERT(sc->sc_child == NULL);
   1371 	KASSERT(sc->sc_child_state == VIRTIO_NO_CHILD);
   1372 
   1373 	sc->sc_child = child;
   1374 	sc->sc_ipl = ipl;
   1375 
   1376 	virtio_negotiate_features(sc, req_features);
   1377 	snprintb(buf, sizeof(buf), feat_bits, sc->sc_active_features);
   1378 	aprint_normal(": features: %s\n", buf);
   1379 	aprint_naive("\n");
   1380 }
   1381 
   1382 int
   1383 virtio_child_attach_finish(struct virtio_softc *sc,
   1384     struct virtqueue *vqs, size_t nvqs,
   1385     virtio_callback config_change,
   1386     int req_flags)
   1387 {
   1388 	size_t i;
   1389 	int r;
   1390 
   1391 #ifdef DIAGNOSTIC
   1392 	KASSERT(nvqs > 0);
   1393 #define VIRTIO_ASSERT_FLAGS	(VIRTIO_F_INTR_SOFTINT | VIRTIO_F_INTR_PERVQ)
   1394 	KASSERT((req_flags & VIRTIO_ASSERT_FLAGS) != VIRTIO_ASSERT_FLAGS);
   1395 #undef VIRTIO_ASSERT_FLAGS
   1396 
   1397 	for (i = 0; i < nvqs; i++){
   1398 		KASSERT(vqs[i].vq_index == i);
   1399 		KASSERT(vqs[i].vq_intrhand != NULL);
   1400 		KASSERT(vqs[i].vq_done == NULL ||
   1401 		    vqs[i].vq_intrhand == virtio_vq_done);
   1402 	}
   1403 #endif
   1404 
   1405 
   1406 	sc->sc_vqs = vqs;
   1407 	sc->sc_nvqs = nvqs;
   1408 	sc->sc_config_change = config_change;
   1409 	sc->sc_intrhand = virtio_vq_intr;
   1410 	sc->sc_flags = req_flags;
   1411 
   1412 	/* set the vq address */
   1413 	for (i = 0; i < nvqs; i++) {
   1414 		sc->sc_ops->setup_queue(sc, vqs[i].vq_index,
   1415 		    vqs[i].vq_dmamap->dm_segs[0].ds_addr);
   1416 	}
   1417 
   1418 	r = sc->sc_ops->alloc_interrupts(sc);
   1419 	if (r != 0) {
   1420 		aprint_error_dev(sc->sc_dev,
   1421 		    "failed to allocate interrupts\n");
   1422 		goto fail;
   1423 	}
   1424 
   1425 	r = sc->sc_ops->setup_interrupts(sc, 0);
   1426 	if (r != 0) {
   1427 		aprint_error_dev(sc->sc_dev, "failed to setup interrupts\n");
   1428 		goto fail;
   1429 	}
   1430 
   1431 	KASSERT(sc->sc_soft_ih == NULL);
   1432 	if (sc->sc_flags & VIRTIO_F_INTR_SOFTINT) {
   1433 		u_int flags = SOFTINT_NET;
   1434 		if (sc->sc_flags & VIRTIO_F_INTR_MPSAFE)
   1435 			flags |= SOFTINT_MPSAFE;
   1436 
   1437 		sc->sc_soft_ih = softint_establish(flags, virtio_soft_intr,
   1438 		    sc);
   1439 		if (sc->sc_soft_ih == NULL) {
   1440 			sc->sc_ops->free_interrupts(sc);
   1441 			aprint_error_dev(sc->sc_dev,
   1442 			    "failed to establish soft interrupt\n");
   1443 			goto fail;
   1444 		}
   1445 	}
   1446 
   1447 	sc->sc_child_state = VIRTIO_CHILD_ATTACH_FINISHED;
   1448 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_DRIVER_OK);
   1449 	return 0;
   1450 
   1451 fail:
   1452 	if (sc->sc_soft_ih) {
   1453 		softint_disestablish(sc->sc_soft_ih);
   1454 		sc->sc_soft_ih = NULL;
   1455 	}
   1456 
   1457 	sc->sc_ops->free_interrupts(sc);
   1458 
   1459 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_FAILED);
   1460 	return 1;
   1461 }
   1462 
   1463 void
   1464 virtio_child_detach(struct virtio_softc *sc)
   1465 {
   1466 
   1467 	/* already detached */
   1468 	if (sc->sc_child == NULL)
   1469 		return;
   1470 
   1471 
   1472 	virtio_device_reset(sc);
   1473 
   1474 	sc->sc_ops->free_interrupts(sc);
   1475 
   1476 	if (sc->sc_soft_ih) {
   1477 		softint_disestablish(sc->sc_soft_ih);
   1478 		sc->sc_soft_ih = NULL;
   1479 	}
   1480 
   1481 	sc->sc_vqs = NULL;
   1482 	sc->sc_child = NULL;
   1483 }
   1484 
   1485 void
   1486 virtio_child_attach_failed(struct virtio_softc *sc)
   1487 {
   1488 	virtio_child_detach(sc);
   1489 
   1490 	virtio_set_status(sc, VIRTIO_CONFIG_DEVICE_STATUS_FAILED);
   1491 
   1492 	sc->sc_child_state = VIRTIO_CHILD_ATTACH_FAILED;
   1493 }
   1494 
   1495 bus_dma_tag_t
   1496 virtio_dmat(struct virtio_softc *sc)
   1497 {
   1498 	return sc->sc_dmat;
   1499 }
   1500 
   1501 device_t
   1502 virtio_child(struct virtio_softc *sc)
   1503 {
   1504 	return sc->sc_child;
   1505 }
   1506 
   1507 int
   1508 virtio_intrhand(struct virtio_softc *sc)
   1509 {
   1510 	return (*sc->sc_intrhand)(sc);
   1511 }
   1512 
   1513 uint64_t
   1514 virtio_features(struct virtio_softc *sc)
   1515 {
   1516 	return sc->sc_active_features;
   1517 }
   1518 
   1519 bool
   1520 virtio_version_1(struct virtio_softc *sc)
   1521 {
   1522 	return sc->sc_version_1;
   1523 }
   1524 
   1525 int
   1526 virtio_attach_failed(struct virtio_softc *sc)
   1527 {
   1528 	device_t self = sc->sc_dev;
   1529 
   1530 	/* no error if its not connected, but its failed */
   1531 	if (sc->sc_childdevid == 0)
   1532 		return 1;
   1533 
   1534 	if (sc->sc_child == NULL) {
   1535 		switch (sc->sc_child_state) {
   1536 		case VIRTIO_CHILD_ATTACH_FAILED:
   1537 			aprint_error_dev(self,
   1538 			    "virtio configuration failed\n");
   1539 			break;
   1540 		case VIRTIO_NO_CHILD:
   1541 			aprint_error_dev(self,
   1542 			    "no matching child driver; not configured\n");
   1543 			break;
   1544 		default:
   1545 			/* sanity check */
   1546 			aprint_error_dev(self,
   1547 			    "virtio internal error, "
   1548 			    "child driver is not configured\n");
   1549 			break;
   1550 		}
   1551 
   1552 		return 1;
   1553 	}
   1554 
   1555 	/* sanity check */
   1556 	if (sc->sc_child_state != VIRTIO_CHILD_ATTACH_FINISHED) {
   1557 		aprint_error_dev(self, "virtio internal error, child driver "
   1558 		    "signaled OK but didn't initialize interrupts\n");
   1559 		return 1;
   1560 	}
   1561 
   1562 	return 0;
   1563 }
   1564 
   1565 void
   1566 virtio_print_device_type(device_t self, int id, int revision)
   1567 {
   1568 	aprint_normal_dev(self, "%s device (id %d, rev. 0x%02x)\n",
   1569 	    (id < NDEVNAMES ? virtio_device_name[id] : "Unknown"),
   1570 	    id,
   1571 	    revision);
   1572 }
   1573 
   1574 
   1575 MODULE(MODULE_CLASS_DRIVER, virtio, NULL);
   1576 
   1577 #ifdef _MODULE
   1578 #include "ioconf.c"
   1579 #endif
   1580 
   1581 static int
   1582 virtio_modcmd(modcmd_t cmd, void *opaque)
   1583 {
   1584 	int error = 0;
   1585 
   1586 #ifdef _MODULE
   1587 	switch (cmd) {
   1588 	case MODULE_CMD_INIT:
   1589 		error = config_init_component(cfdriver_ioconf_virtio,
   1590 		    cfattach_ioconf_virtio, cfdata_ioconf_virtio);
   1591 		break;
   1592 	case MODULE_CMD_FINI:
   1593 		error = config_fini_component(cfdriver_ioconf_virtio,
   1594 		    cfattach_ioconf_virtio, cfdata_ioconf_virtio);
   1595 		break;
   1596 	default:
   1597 		error = ENOTTY;
   1598 		break;
   1599 	}
   1600 #endif
   1601 
   1602 	return error;
   1603 }
   1604