xref: /freebsd/sys/dev/virtio/block/virtio_blk.c (revision 54d2737e7fe48226c908dcccfbda2ca1c08e07fc)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011, Bryan Venteicher <bryanv@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /* Driver for VirtIO block devices. */
30 
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/bio.h>
35 #include <sys/malloc.h>
36 #include <sys/module.h>
37 #include <sys/msan.h>
38 #include <sys/sglist.h>
39 #include <sys/sysctl.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/queue.h>
43 
44 #include <geom/geom.h>
45 #include <geom/geom_disk.h>
46 
47 #include <machine/bus.h>
48 #include <machine/resource.h>
49 #include <sys/bus.h>
50 #include <sys/rman.h>
51 
52 #include <dev/virtio/virtio.h>
53 #include <dev/virtio/virtqueue.h>
54 #include <dev/virtio/block/virtio_blk.h>
55 
56 #include "virtio_if.h"
57 
58 struct vtblk_request {
59 	struct vtblk_softc		*vbr_sc;
60 	bus_dmamap_t			 vbr_mapp;
61 
62 	/* Fields after this point are zeroed for each request. */
63 	struct virtio_blk_outhdr	 vbr_hdr;
64 	struct bio			*vbr_bp;
65 	uint8_t				 vbr_ack;
66 	uint8_t				 vbr_requeue_on_error;
67 	uint8_t				 vbr_busdma_wait;
68 	int				 vbr_error;
69 	TAILQ_ENTRY(vtblk_request)	 vbr_link;
70 };
71 
72 enum vtblk_cache_mode {
73 	VTBLK_CACHE_WRITETHROUGH,
74 	VTBLK_CACHE_WRITEBACK,
75 	VTBLK_CACHE_MAX
76 };
77 
78 struct vtblk_softc {
79 	device_t		 vtblk_dev;
80 	struct mtx		 vtblk_mtx;
81 	uint64_t		 vtblk_features;
82 	uint32_t		 vtblk_flags;
83 #define VTBLK_FLAG_INDIRECT	0x0001
84 #define VTBLK_FLAG_DETACH	0x0002
85 #define VTBLK_FLAG_SUSPEND	0x0004
86 #define VTBLK_FLAG_BARRIER	0x0008
87 #define VTBLK_FLAG_WCE_CONFIG	0x0010
88 #define VTBLK_FLAG_BUSDMA_WAIT	0x0020
89 #define VTBLK_FLAG_BUSDMA_ALIGN	0x0040
90 
91 	struct virtqueue	*vtblk_vq;
92 	struct sglist		*vtblk_sglist;
93 	bus_dma_tag_t		 vtblk_dmat;
94 	struct disk		*vtblk_disk;
95 
96 	struct bio_queue_head	 vtblk_bioq;
97 	TAILQ_HEAD(, vtblk_request)
98 				 vtblk_req_free;
99 	TAILQ_HEAD(, vtblk_request)
100 				 vtblk_req_ready;
101 	struct vtblk_request	*vtblk_req_ordered;
102 
103 	int			 vtblk_max_nsegs;
104 	int			 vtblk_request_count;
105 	enum vtblk_cache_mode	 vtblk_write_cache;
106 
107 	struct bio_queue	 vtblk_dump_queue;
108 	struct vtblk_request	 vtblk_dump_request;
109 };
110 
111 static struct virtio_feature_desc vtblk_feature_desc[] = {
112 	{ VIRTIO_BLK_F_BARRIER,		"HostBarrier"	},
113 	{ VIRTIO_BLK_F_SIZE_MAX,	"MaxSegSize"	},
114 	{ VIRTIO_BLK_F_SEG_MAX,		"MaxNumSegs"	},
115 	{ VIRTIO_BLK_F_GEOMETRY,	"DiskGeometry"	},
116 	{ VIRTIO_BLK_F_RO,		"ReadOnly"	},
117 	{ VIRTIO_BLK_F_BLK_SIZE,	"BlockSize"	},
118 	{ VIRTIO_BLK_F_SCSI,		"SCSICmds"	},
119 	{ VIRTIO_BLK_F_FLUSH,		"FlushCmd"	},
120 	{ VIRTIO_BLK_F_TOPOLOGY,	"Topology"	},
121 	{ VIRTIO_BLK_F_CONFIG_WCE,	"ConfigWCE"	},
122 	{ VIRTIO_BLK_F_MQ,		"Multiqueue"	},
123 	{ VIRTIO_BLK_F_DISCARD,		"Discard"	},
124 	{ VIRTIO_BLK_F_WRITE_ZEROES,	"WriteZeros"	},
125 
126 	{ 0, NULL }
127 };
128 
129 static int	vtblk_modevent(module_t, int, void *);
130 
131 static int	vtblk_probe(device_t);
132 static int	vtblk_attach(device_t);
133 static int	vtblk_detach(device_t);
134 static int	vtblk_suspend(device_t);
135 static int	vtblk_resume(device_t);
136 static int	vtblk_shutdown(device_t);
137 static int	vtblk_attach_completed(device_t);
138 static int	vtblk_config_change(device_t);
139 
140 static int	vtblk_open(struct disk *);
141 static int	vtblk_close(struct disk *);
142 static int	vtblk_ioctl(struct disk *, u_long, void *, int,
143 		    struct thread *);
144 static int	vtblk_dump(void *, void *, off_t, size_t);
145 static void	vtblk_strategy(struct bio *);
146 
147 static int	vtblk_negotiate_features(struct vtblk_softc *);
148 static int	vtblk_setup_features(struct vtblk_softc *);
149 static int	vtblk_maximum_segments(struct vtblk_softc *,
150 		    struct virtio_blk_config *);
151 static int	vtblk_alloc_virtqueue(struct vtblk_softc *);
152 static void	vtblk_resize_disk(struct vtblk_softc *, uint64_t);
153 static void	vtblk_alloc_disk(struct vtblk_softc *,
154 		    struct virtio_blk_config *);
155 static void	vtblk_create_disk(struct vtblk_softc *);
156 
157 static int	vtblk_request_prealloc(struct vtblk_softc *);
158 static void	vtblk_request_free(struct vtblk_softc *);
159 static struct vtblk_request *
160 		vtblk_request_dequeue(struct vtblk_softc *);
161 static void	vtblk_request_enqueue(struct vtblk_softc *,
162 		    struct vtblk_request *);
163 static struct vtblk_request *
164 		vtblk_request_next_ready(struct vtblk_softc *);
165 static void	vtblk_request_requeue_ready(struct vtblk_softc *,
166 		    struct vtblk_request *);
167 static struct vtblk_request *
168 		vtblk_request_next(struct vtblk_softc *);
169 static struct vtblk_request *
170 		vtblk_request_bio(struct vtblk_softc *);
171 static int	vtblk_request_execute(struct vtblk_request *, int);
172 static void	vtblk_request_execute_cb(void *,
173 		    bus_dma_segment_t *, int, int);
174 static int	vtblk_request_error(struct vtblk_request *);
175 
176 static void	vtblk_queue_completed(struct vtblk_softc *,
177 		    struct bio_queue *);
178 static void	vtblk_done_completed(struct vtblk_softc *,
179 		    struct bio_queue *);
180 static void	vtblk_drain_vq(struct vtblk_softc *);
181 static void	vtblk_drain(struct vtblk_softc *);
182 
183 static void	vtblk_startio(struct vtblk_softc *);
184 static void	vtblk_bio_done(struct vtblk_softc *, struct bio *, int);
185 
186 static void	vtblk_read_config(struct vtblk_softc *,
187 		    struct virtio_blk_config *);
188 static void	vtblk_ident(struct vtblk_softc *);
189 static int	vtblk_poll_request(struct vtblk_softc *,
190 		    struct vtblk_request *);
191 static int	vtblk_quiesce(struct vtblk_softc *);
192 static void	vtblk_vq_intr(void *);
193 static void	vtblk_stop(struct vtblk_softc *);
194 
195 static void	vtblk_dump_quiesce(struct vtblk_softc *);
196 static int	vtblk_dump_write(struct vtblk_softc *, void *, off_t, size_t);
197 static int	vtblk_dump_flush(struct vtblk_softc *);
198 static void	vtblk_dump_complete(struct vtblk_softc *);
199 
200 static void	vtblk_set_write_cache(struct vtblk_softc *, int);
201 static int	vtblk_write_cache_enabled(struct vtblk_softc *sc,
202 		    struct virtio_blk_config *);
203 static int	vtblk_write_cache_sysctl(SYSCTL_HANDLER_ARGS);
204 
205 static void	vtblk_setup_sysctl(struct vtblk_softc *);
206 static int	vtblk_tunable_int(struct vtblk_softc *, const char *, int);
207 
208 #define vtblk_modern(_sc) (((_sc)->vtblk_features & VIRTIO_F_VERSION_1) != 0)
209 #define vtblk_htog16(_sc, _val)	virtio_htog16(vtblk_modern(_sc), _val)
210 #define vtblk_htog32(_sc, _val)	virtio_htog32(vtblk_modern(_sc), _val)
211 #define vtblk_htog64(_sc, _val)	virtio_htog64(vtblk_modern(_sc), _val)
212 #define vtblk_gtoh16(_sc, _val)	virtio_gtoh16(vtblk_modern(_sc), _val)
213 #define vtblk_gtoh32(_sc, _val)	virtio_gtoh32(vtblk_modern(_sc), _val)
214 #define vtblk_gtoh64(_sc, _val)	virtio_gtoh64(vtblk_modern(_sc), _val)
215 
216 /* Tunables. */
217 static int vtblk_no_ident = 0;
218 TUNABLE_INT("hw.vtblk.no_ident", &vtblk_no_ident);
219 static int vtblk_writecache_mode = -1;
220 TUNABLE_INT("hw.vtblk.writecache_mode", &vtblk_writecache_mode);
221 
222 #define VTBLK_COMMON_FEATURES \
223     (VIRTIO_BLK_F_SIZE_MAX		| \
224      VIRTIO_BLK_F_SEG_MAX		| \
225      VIRTIO_BLK_F_GEOMETRY		| \
226      VIRTIO_BLK_F_RO			| \
227      VIRTIO_BLK_F_BLK_SIZE		| \
228      VIRTIO_BLK_F_FLUSH			| \
229      VIRTIO_BLK_F_TOPOLOGY		| \
230      VIRTIO_BLK_F_CONFIG_WCE		| \
231      VIRTIO_BLK_F_DISCARD		| \
232      VIRTIO_RING_F_INDIRECT_DESC)
233 
234 #define VTBLK_MODERN_FEATURES	(VTBLK_COMMON_FEATURES)
235 #define VTBLK_LEGACY_FEATURES	(VIRTIO_BLK_F_BARRIER | VTBLK_COMMON_FEATURES)
236 
237 #define VTBLK_MTX(_sc)		&(_sc)->vtblk_mtx
238 #define VTBLK_LOCK_INIT(_sc, _name) \
239 				mtx_init(VTBLK_MTX((_sc)), (_name), \
240 				    "VirtIO Block Lock", MTX_DEF)
241 #define VTBLK_LOCK(_sc)		mtx_lock(VTBLK_MTX((_sc)))
242 #define VTBLK_UNLOCK(_sc)	mtx_unlock(VTBLK_MTX((_sc)))
243 #define VTBLK_LOCK_DESTROY(_sc)	mtx_destroy(VTBLK_MTX((_sc)))
244 #define VTBLK_LOCK_ASSERT(_sc)	mtx_assert(VTBLK_MTX((_sc)), MA_OWNED)
245 #define VTBLK_LOCK_ASSERT_NOTOWNED(_sc) \
246 				mtx_assert(VTBLK_MTX((_sc)), MA_NOTOWNED)
247 
248 #define VTBLK_DISK_NAME		"vtbd"
249 #define VTBLK_QUIESCE_TIMEOUT	(30 * hz)
250 #define VTBLK_BSIZE		512
251 
252 /*
253  * Each block request uses at least two segments - one for the header
254  * and one for the status.
255  */
256 #define VTBLK_MIN_SEGMENTS	2
257 
258 static device_method_t vtblk_methods[] = {
259 	/* Device methods. */
260 	DEVMETHOD(device_probe,		vtblk_probe),
261 	DEVMETHOD(device_attach,	vtblk_attach),
262 	DEVMETHOD(device_detach,	vtblk_detach),
263 	DEVMETHOD(device_suspend,	vtblk_suspend),
264 	DEVMETHOD(device_resume,	vtblk_resume),
265 	DEVMETHOD(device_shutdown,	vtblk_shutdown),
266 
267 	/* VirtIO methods. */
268 	DEVMETHOD(virtio_attach_completed, vtblk_attach_completed),
269 	DEVMETHOD(virtio_config_change,	vtblk_config_change),
270 
271 	DEVMETHOD_END
272 };
273 
274 static driver_t vtblk_driver = {
275 	"vtblk",
276 	vtblk_methods,
277 	sizeof(struct vtblk_softc)
278 };
279 
280 VIRTIO_DRIVER_MODULE(virtio_blk, vtblk_driver, vtblk_modevent, NULL);
281 MODULE_VERSION(virtio_blk, 1);
282 MODULE_DEPEND(virtio_blk, virtio, 1, 1, 1);
283 
284 VIRTIO_SIMPLE_PNPINFO(virtio_blk, VIRTIO_ID_BLOCK, "VirtIO Block Adapter");
285 
286 static int
287 vtblk_modevent(module_t mod, int type, void *unused)
288 {
289 	int error;
290 
291 	error = 0;
292 
293 	switch (type) {
294 	case MOD_LOAD:
295 	case MOD_QUIESCE:
296 	case MOD_UNLOAD:
297 	case MOD_SHUTDOWN:
298 		break;
299 	default:
300 		error = EOPNOTSUPP;
301 		break;
302 	}
303 
304 	return (error);
305 }
306 
307 static int
308 vtblk_probe(device_t dev)
309 {
310 	return (VIRTIO_SIMPLE_PROBE(dev, virtio_blk));
311 }
312 
313 static int
314 vtblk_attach(device_t dev)
315 {
316 	struct vtblk_softc *sc;
317 	struct virtio_blk_config blkcfg;
318 	int error;
319 
320 	sc = device_get_softc(dev);
321 	sc->vtblk_dev = dev;
322 	virtio_set_feature_desc(dev, vtblk_feature_desc);
323 
324 	VTBLK_LOCK_INIT(sc, device_get_nameunit(dev));
325 	bioq_init(&sc->vtblk_bioq);
326 	TAILQ_INIT(&sc->vtblk_dump_queue);
327 	TAILQ_INIT(&sc->vtblk_req_free);
328 	TAILQ_INIT(&sc->vtblk_req_ready);
329 
330 	vtblk_setup_sysctl(sc);
331 
332 	error = vtblk_setup_features(sc);
333 	if (error) {
334 		device_printf(dev, "cannot setup features\n");
335 		goto fail;
336 	}
337 
338 	vtblk_read_config(sc, &blkcfg);
339 
340 	/*
341 	 * With the current sglist(9) implementation, it is not easy
342 	 * for us to support a maximum segment size as adjacent
343 	 * segments are coalesced. For now, just make sure it's larger
344 	 * than the maximum supported transfer size.
345 	 */
346 	if (virtio_with_feature(dev, VIRTIO_BLK_F_SIZE_MAX)) {
347 		if (blkcfg.size_max < maxphys) {
348 			error = ENOTSUP;
349 			device_printf(dev, "host requires unsupported "
350 			    "maximum segment size feature\n");
351 			goto fail;
352 		}
353 	}
354 
355 	sc->vtblk_max_nsegs = vtblk_maximum_segments(sc, &blkcfg);
356 	if (sc->vtblk_max_nsegs <= VTBLK_MIN_SEGMENTS) {
357 		error = EINVAL;
358 		device_printf(dev, "fewer than minimum number of segments "
359 		    "allowed: %d\n", sc->vtblk_max_nsegs);
360 		goto fail;
361 	}
362 
363 	sc->vtblk_sglist = sglist_alloc(sc->vtblk_max_nsegs, M_NOWAIT);
364 	if (sc->vtblk_sglist == NULL) {
365 		error = ENOMEM;
366 		device_printf(dev, "cannot allocate sglist\n");
367 		goto fail;
368 	}
369 
370 	/*
371 	 * If vtblk_max_nsegs == VTBLK_MIN_SEGMENTS + 1, the device only
372 	 * supports a single data segment; in that case we need busdma to
373 	 * align to a page boundary so we can send a *contiguous* page size
374 	 * request to the host.
375 	 */
376 	if (sc->vtblk_max_nsegs == VTBLK_MIN_SEGMENTS + 1)
377 		sc->vtblk_flags |= VTBLK_FLAG_BUSDMA_ALIGN;
378 	error = bus_dma_tag_create(
379 	    bus_get_dma_tag(dev),			/* parent */
380 	    (sc->vtblk_flags & VTBLK_FLAG_BUSDMA_ALIGN) ? PAGE_SIZE : 1,
381 	    0,						/* boundary */
382 	    BUS_SPACE_MAXADDR,				/* lowaddr */
383 	    BUS_SPACE_MAXADDR,				/* highaddr */
384 	    NULL, NULL,					/* filter, filterarg */
385 	    maxphys,					/* max request size */
386 	    sc->vtblk_max_nsegs - VTBLK_MIN_SEGMENTS,	/* max # segments */
387 	    maxphys,					/* maxsegsize */
388 	    0,						/* flags */
389 	    busdma_lock_mutex,				/* lockfunc */
390 	    &sc->vtblk_mtx,				/* lockarg */
391 	    &sc->vtblk_dmat);
392 	if (error) {
393 		device_printf(dev, "cannot create bus dma tag\n");
394 		goto fail;
395 	}
396 
397 #ifdef __powerpc__
398 	/*
399 	 * Virtio uses physical addresses rather than bus addresses, so we
400 	 * need to ask busdma to skip the iommu physical->bus mapping.  At
401 	 * present, this is only a thing on the powerpc architectures.
402 	 */
403 	bus_dma_tag_set_iommu(sc->vtblk_dmat, NULL, NULL);
404 #endif
405 
406 	error = vtblk_alloc_virtqueue(sc);
407 	if (error) {
408 		device_printf(dev, "cannot allocate virtqueue\n");
409 		goto fail;
410 	}
411 
412 	error = vtblk_request_prealloc(sc);
413 	if (error) {
414 		device_printf(dev, "cannot preallocate requests\n");
415 		goto fail;
416 	}
417 
418 	vtblk_alloc_disk(sc, &blkcfg);
419 
420 	error = virtio_setup_intr(dev, INTR_TYPE_BIO | INTR_ENTROPY);
421 	if (error) {
422 		device_printf(dev, "cannot setup virtqueue interrupt\n");
423 		goto fail;
424 	}
425 
426 	virtqueue_enable_intr(sc->vtblk_vq);
427 
428 fail:
429 	if (error)
430 		vtblk_detach(dev);
431 
432 	return (error);
433 }
434 
435 static int
436 vtblk_detach(device_t dev)
437 {
438 	struct vtblk_softc *sc;
439 
440 	sc = device_get_softc(dev);
441 
442 	VTBLK_LOCK(sc);
443 	sc->vtblk_flags |= VTBLK_FLAG_DETACH;
444 	if (device_is_attached(dev))
445 		vtblk_stop(sc);
446 	VTBLK_UNLOCK(sc);
447 
448 	vtblk_drain(sc);
449 
450 	if (sc->vtblk_disk != NULL) {
451 		disk_destroy(sc->vtblk_disk);
452 		sc->vtblk_disk = NULL;
453 	}
454 
455 	if (sc->vtblk_dmat != NULL) {
456 		bus_dma_tag_destroy(sc->vtblk_dmat);
457 		sc->vtblk_dmat = NULL;
458 	}
459 
460 	if (sc->vtblk_sglist != NULL) {
461 		sglist_free(sc->vtblk_sglist);
462 		sc->vtblk_sglist = NULL;
463 	}
464 
465 	VTBLK_LOCK_DESTROY(sc);
466 
467 	return (0);
468 }
469 
470 static int
471 vtblk_suspend(device_t dev)
472 {
473 	struct vtblk_softc *sc;
474 	int error;
475 
476 	sc = device_get_softc(dev);
477 
478 	VTBLK_LOCK(sc);
479 	sc->vtblk_flags |= VTBLK_FLAG_SUSPEND;
480 	/* XXX BMV: virtio_stop(), etc needed here? */
481 	error = vtblk_quiesce(sc);
482 	if (error)
483 		sc->vtblk_flags &= ~VTBLK_FLAG_SUSPEND;
484 	VTBLK_UNLOCK(sc);
485 
486 	return (error);
487 }
488 
489 static int
490 vtblk_resume(device_t dev)
491 {
492 	struct vtblk_softc *sc;
493 
494 	sc = device_get_softc(dev);
495 
496 	VTBLK_LOCK(sc);
497 	/* XXX BMV: virtio_reinit(), etc needed here? */
498 	sc->vtblk_flags &= ~VTBLK_FLAG_SUSPEND;
499 	vtblk_startio(sc);
500 	VTBLK_UNLOCK(sc);
501 
502 	return (0);
503 }
504 
505 static int
506 vtblk_shutdown(device_t dev)
507 {
508 
509 	return (0);
510 }
511 
512 static int
513 vtblk_attach_completed(device_t dev)
514 {
515 	struct vtblk_softc *sc;
516 
517 	sc = device_get_softc(dev);
518 
519 	/*
520 	 * Create disk after attach as VIRTIO_BLK_T_GET_ID can only be
521 	 * processed after the device acknowledged
522 	 * VIRTIO_CONFIG_STATUS_DRIVER_OK.
523 	 */
524 	vtblk_create_disk(sc);
525 	return (0);
526 }
527 
528 static int
529 vtblk_config_change(device_t dev)
530 {
531 	struct vtblk_softc *sc;
532 	struct virtio_blk_config blkcfg;
533 	uint64_t capacity;
534 
535 	sc = device_get_softc(dev);
536 
537 	vtblk_read_config(sc, &blkcfg);
538 
539 	/* Capacity is always in 512-byte units. */
540 	capacity = blkcfg.capacity * VTBLK_BSIZE;
541 
542 	if (sc->vtblk_disk->d_mediasize != capacity)
543 		vtblk_resize_disk(sc, capacity);
544 
545 	return (0);
546 }
547 
548 static int
549 vtblk_open(struct disk *dp)
550 {
551 	struct vtblk_softc *sc;
552 
553 	if ((sc = dp->d_drv1) == NULL)
554 		return (ENXIO);
555 
556 	return (sc->vtblk_flags & VTBLK_FLAG_DETACH ? ENXIO : 0);
557 }
558 
559 static int
560 vtblk_close(struct disk *dp)
561 {
562 	struct vtblk_softc *sc;
563 
564 	if ((sc = dp->d_drv1) == NULL)
565 		return (ENXIO);
566 
567 	return (0);
568 }
569 
570 static int
571 vtblk_ioctl(struct disk *dp, u_long cmd, void *addr, int flag,
572     struct thread *td)
573 {
574 	struct vtblk_softc *sc;
575 
576 	if ((sc = dp->d_drv1) == NULL)
577 		return (ENXIO);
578 
579 	return (ENOTTY);
580 }
581 
582 static int
583 vtblk_dump(void *arg, void *virtual, off_t offset, size_t length)
584 {
585 	struct disk *dp;
586 	struct vtblk_softc *sc;
587 	int error;
588 
589 	dp = arg;
590 	error = 0;
591 
592 	if ((sc = dp->d_drv1) == NULL)
593 		return (ENXIO);
594 
595 	VTBLK_LOCK(sc);
596 
597 	vtblk_dump_quiesce(sc);
598 
599 	if (length > 0)
600 		error = vtblk_dump_write(sc, virtual, offset, length);
601 	if (error || (virtual == NULL && offset == 0))
602 		vtblk_dump_complete(sc);
603 
604 	VTBLK_UNLOCK(sc);
605 
606 	return (error);
607 }
608 
609 static void
610 vtblk_strategy(struct bio *bp)
611 {
612 	struct vtblk_softc *sc;
613 
614 	if ((sc = bp->bio_disk->d_drv1) == NULL) {
615 		vtblk_bio_done(NULL, bp, EINVAL);
616 		return;
617 	}
618 
619 	if ((bp->bio_cmd != BIO_READ) && (bp->bio_cmd != BIO_WRITE) &&
620 	    (bp->bio_cmd != BIO_FLUSH) && (bp->bio_cmd != BIO_DELETE)) {
621 		vtblk_bio_done(sc, bp, EOPNOTSUPP);
622 		return;
623 	}
624 
625 	VTBLK_LOCK(sc);
626 
627 	if (sc->vtblk_flags & VTBLK_FLAG_DETACH) {
628 		VTBLK_UNLOCK(sc);
629 		vtblk_bio_done(sc, bp, ENXIO);
630 		return;
631 	}
632 
633 	bioq_insert_tail(&sc->vtblk_bioq, bp);
634 	vtblk_startio(sc);
635 
636 	VTBLK_UNLOCK(sc);
637 }
638 
639 static int
640 vtblk_negotiate_features(struct vtblk_softc *sc)
641 {
642 	device_t dev;
643 	uint64_t features;
644 
645 	dev = sc->vtblk_dev;
646 	features = virtio_bus_is_modern(dev) ? VTBLK_MODERN_FEATURES :
647 	    VTBLK_LEGACY_FEATURES;
648 
649 	sc->vtblk_features = virtio_negotiate_features(dev, features);
650 	return (virtio_finalize_features(dev));
651 }
652 
653 static int
654 vtblk_setup_features(struct vtblk_softc *sc)
655 {
656 	device_t dev;
657 	int error;
658 
659 	dev = sc->vtblk_dev;
660 
661 	error = vtblk_negotiate_features(sc);
662 	if (error)
663 		return (error);
664 
665 	if (virtio_with_feature(dev, VIRTIO_RING_F_INDIRECT_DESC))
666 		sc->vtblk_flags |= VTBLK_FLAG_INDIRECT;
667 	if (virtio_with_feature(dev, VIRTIO_BLK_F_CONFIG_WCE))
668 		sc->vtblk_flags |= VTBLK_FLAG_WCE_CONFIG;
669 
670 	/* Legacy. */
671 	if (virtio_with_feature(dev, VIRTIO_BLK_F_BARRIER))
672 		sc->vtblk_flags |= VTBLK_FLAG_BARRIER;
673 
674 	return (0);
675 }
676 
677 static int
678 vtblk_maximum_segments(struct vtblk_softc *sc,
679     struct virtio_blk_config *blkcfg)
680 {
681 	device_t dev;
682 	int nsegs;
683 
684 	dev = sc->vtblk_dev;
685 	nsegs = VTBLK_MIN_SEGMENTS;
686 
687 	if (virtio_with_feature(dev, VIRTIO_BLK_F_SEG_MAX)) {
688 		nsegs += MIN(blkcfg->seg_max, maxphys / PAGE_SIZE + 1);
689 		if (sc->vtblk_flags & VTBLK_FLAG_INDIRECT)
690 			nsegs = MIN(nsegs, VIRTIO_MAX_INDIRECT);
691 	} else
692 		nsegs += 1;
693 
694 	return (nsegs);
695 }
696 
697 static int
698 vtblk_alloc_virtqueue(struct vtblk_softc *sc)
699 {
700 	device_t dev;
701 	struct vq_alloc_info vq_info;
702 
703 	dev = sc->vtblk_dev;
704 
705 	VQ_ALLOC_INFO_INIT(&vq_info, sc->vtblk_max_nsegs,
706 	    vtblk_vq_intr, sc, &sc->vtblk_vq,
707 	    "%s request", device_get_nameunit(dev));
708 
709 	return (virtio_alloc_virtqueues(dev, 1, &vq_info));
710 }
711 
712 static void
713 vtblk_resize_disk(struct vtblk_softc *sc, uint64_t new_capacity)
714 {
715 	device_t dev;
716 	struct disk *dp;
717 	int error;
718 
719 	dev = sc->vtblk_dev;
720 	dp = sc->vtblk_disk;
721 
722 	dp->d_mediasize = new_capacity;
723 	if (bootverbose) {
724 		device_printf(dev, "resized to %juMB (%ju %u byte sectors)\n",
725 		    (uintmax_t) dp->d_mediasize >> 20,
726 		    (uintmax_t) dp->d_mediasize / dp->d_sectorsize,
727 		    dp->d_sectorsize);
728 	}
729 
730 	error = disk_resize(dp, M_NOWAIT);
731 	if (error) {
732 		device_printf(dev,
733 		    "disk_resize(9) failed, error: %d\n", error);
734 	}
735 }
736 
737 static void
738 vtblk_alloc_disk(struct vtblk_softc *sc, struct virtio_blk_config *blkcfg)
739 {
740 	device_t dev;
741 	struct disk *dp;
742 
743 	dev = sc->vtblk_dev;
744 
745 	sc->vtblk_disk = dp = disk_alloc();
746 	dp->d_open = vtblk_open;
747 	dp->d_close = vtblk_close;
748 	dp->d_ioctl = vtblk_ioctl;
749 	dp->d_strategy = vtblk_strategy;
750 	dp->d_name = VTBLK_DISK_NAME;
751 	dp->d_unit = device_get_unit(dev);
752 	dp->d_drv1 = sc;
753 	dp->d_flags = DISKFLAG_UNMAPPED_BIO | DISKFLAG_DIRECT_COMPLETION;
754 	dp->d_hba_vendor = virtio_get_vendor(dev);
755 	dp->d_hba_device = virtio_get_device(dev);
756 	dp->d_hba_subvendor = virtio_get_subvendor(dev);
757 	dp->d_hba_subdevice = virtio_get_subdevice(dev);
758 	strlcpy(dp->d_attachment, device_get_nameunit(dev),
759 	    sizeof(dp->d_attachment));
760 
761 	if (virtio_with_feature(dev, VIRTIO_BLK_F_RO))
762 		dp->d_flags |= DISKFLAG_WRITE_PROTECT;
763 	else {
764 		if (virtio_with_feature(dev, VIRTIO_BLK_F_FLUSH))
765 			dp->d_flags |= DISKFLAG_CANFLUSHCACHE;
766 		dp->d_dump = vtblk_dump;
767 	}
768 
769 	/* Capacity is always in 512-byte units. */
770 	dp->d_mediasize = blkcfg->capacity * VTBLK_BSIZE;
771 
772 	if (virtio_with_feature(dev, VIRTIO_BLK_F_BLK_SIZE))
773 		dp->d_sectorsize = blkcfg->blk_size;
774 	else
775 		dp->d_sectorsize = VTBLK_BSIZE;
776 
777 	/*
778 	 * The VirtIO maximum I/O size is given in terms of segments.
779 	 * However, FreeBSD limits I/O size by logical buffer size, not
780 	 * by physically contiguous pages. Therefore, we have to assume
781 	 * no pages are contiguous. This may impose an artificially low
782 	 * maximum I/O size. But in practice, since QEMU advertises 128
783 	 * segments, this gives us a maximum IO size of 125 * PAGE_SIZE,
784 	 * which is typically greater than maxphys. Eventually we should
785 	 * just advertise maxphys and split buffers that are too big.
786 	 *
787 	 * If we're not asking busdma to align data to page boundaries, the
788 	 * maximum I/O size is reduced by PAGE_SIZE in order to accommodate
789 	 * unaligned I/Os.
790 	 */
791 	dp->d_maxsize = (sc->vtblk_max_nsegs - VTBLK_MIN_SEGMENTS) *
792 	    PAGE_SIZE;
793 	if ((sc->vtblk_flags & VTBLK_FLAG_BUSDMA_ALIGN) == 0)
794 		dp->d_maxsize -= PAGE_SIZE;
795 
796 	if (virtio_with_feature(dev, VIRTIO_BLK_F_GEOMETRY)) {
797 		dp->d_fwsectors = blkcfg->geometry.sectors;
798 		dp->d_fwheads = blkcfg->geometry.heads;
799 	}
800 
801 	if (virtio_with_feature(dev, VIRTIO_BLK_F_TOPOLOGY) &&
802 	    blkcfg->topology.physical_block_exp > 0) {
803 		dp->d_stripesize = dp->d_sectorsize *
804 		    (1 << blkcfg->topology.physical_block_exp);
805 		dp->d_stripeoffset = (dp->d_stripesize -
806 		    blkcfg->topology.alignment_offset * dp->d_sectorsize) %
807 		    dp->d_stripesize;
808 	}
809 
810 	if (virtio_with_feature(dev, VIRTIO_BLK_F_DISCARD)) {
811 		dp->d_flags |= DISKFLAG_CANDELETE;
812 		dp->d_delmaxsize = blkcfg->max_discard_sectors * VTBLK_BSIZE;
813 	}
814 
815 	if (vtblk_write_cache_enabled(sc, blkcfg) != 0)
816 		sc->vtblk_write_cache = VTBLK_CACHE_WRITEBACK;
817 	else
818 		sc->vtblk_write_cache = VTBLK_CACHE_WRITETHROUGH;
819 }
820 
821 static void
822 vtblk_create_disk(struct vtblk_softc *sc)
823 {
824 	struct disk *dp;
825 
826 	dp = sc->vtblk_disk;
827 
828 	vtblk_ident(sc);
829 
830 	device_printf(sc->vtblk_dev, "%juMB (%ju %u byte sectors)\n",
831 	    (uintmax_t) dp->d_mediasize >> 20,
832 	    (uintmax_t) dp->d_mediasize / dp->d_sectorsize,
833 	    dp->d_sectorsize);
834 
835 	disk_create(dp, DISK_VERSION);
836 }
837 
838 static int
839 vtblk_request_prealloc(struct vtblk_softc *sc)
840 {
841 	struct vtblk_request *req;
842 	int i, nreqs;
843 
844 	nreqs = virtqueue_size(sc->vtblk_vq);
845 
846 	/*
847 	 * Preallocate sufficient requests to keep the virtqueue full. Each
848 	 * request consumes VTBLK_MIN_SEGMENTS or more descriptors so reduce
849 	 * the number allocated when indirect descriptors are not available.
850 	 */
851 	if ((sc->vtblk_flags & VTBLK_FLAG_INDIRECT) == 0)
852 		nreqs /= VTBLK_MIN_SEGMENTS;
853 
854 	for (i = 0; i < nreqs; i++) {
855 		req = malloc(sizeof(struct vtblk_request), M_DEVBUF, M_NOWAIT);
856 		if (req == NULL)
857 			return (ENOMEM);
858 
859 		req->vbr_sc = sc;
860 		if (bus_dmamap_create(sc->vtblk_dmat, 0, &req->vbr_mapp)) {
861 			free(req, M_DEVBUF);
862 			return (ENOMEM);
863 		}
864 
865 		MPASS(sglist_count(&req->vbr_hdr, sizeof(req->vbr_hdr)) == 1);
866 		MPASS(sglist_count(&req->vbr_ack, sizeof(req->vbr_ack)) == 1);
867 
868 		sc->vtblk_request_count++;
869 		vtblk_request_enqueue(sc, req);
870 	}
871 
872 	return (0);
873 }
874 
875 static void
876 vtblk_request_free(struct vtblk_softc *sc)
877 {
878 	struct vtblk_request *req;
879 
880 	MPASS(TAILQ_EMPTY(&sc->vtblk_req_ready));
881 
882 	while ((req = vtblk_request_dequeue(sc)) != NULL) {
883 		sc->vtblk_request_count--;
884 		bus_dmamap_destroy(sc->vtblk_dmat, req->vbr_mapp);
885 		free(req, M_DEVBUF);
886 	}
887 
888 	KASSERT(sc->vtblk_request_count == 0,
889 	    ("%s: leaked %d requests", __func__, sc->vtblk_request_count));
890 }
891 
892 static struct vtblk_request *
893 vtblk_request_dequeue(struct vtblk_softc *sc)
894 {
895 	struct vtblk_request *req;
896 
897 	req = TAILQ_FIRST(&sc->vtblk_req_free);
898 	if (req != NULL) {
899 		TAILQ_REMOVE(&sc->vtblk_req_free, req, vbr_link);
900 		bzero(&req->vbr_hdr, sizeof(struct vtblk_request) -
901 		    offsetof(struct vtblk_request, vbr_hdr));
902 	}
903 
904 	return (req);
905 }
906 
907 static void
908 vtblk_request_enqueue(struct vtblk_softc *sc, struct vtblk_request *req)
909 {
910 
911 	TAILQ_INSERT_HEAD(&sc->vtblk_req_free, req, vbr_link);
912 }
913 
914 static struct vtblk_request *
915 vtblk_request_next_ready(struct vtblk_softc *sc)
916 {
917 	struct vtblk_request *req;
918 
919 	req = TAILQ_FIRST(&sc->vtblk_req_ready);
920 	if (req != NULL)
921 		TAILQ_REMOVE(&sc->vtblk_req_ready, req, vbr_link);
922 
923 	return (req);
924 }
925 
926 static void
927 vtblk_request_requeue_ready(struct vtblk_softc *sc, struct vtblk_request *req)
928 {
929 
930 	/* NOTE: Currently, there will be at most one request in the queue. */
931 	TAILQ_INSERT_HEAD(&sc->vtblk_req_ready, req, vbr_link);
932 }
933 
934 static struct vtblk_request *
935 vtblk_request_next(struct vtblk_softc *sc)
936 {
937 	struct vtblk_request *req;
938 
939 	req = vtblk_request_next_ready(sc);
940 	if (req != NULL)
941 		return (req);
942 
943 	return (vtblk_request_bio(sc));
944 }
945 
946 static struct vtblk_request *
947 vtblk_request_bio(struct vtblk_softc *sc)
948 {
949 	struct bio_queue_head *bioq;
950 	struct vtblk_request *req;
951 	struct bio *bp;
952 
953 	bioq = &sc->vtblk_bioq;
954 
955 	if (bioq_first(bioq) == NULL)
956 		return (NULL);
957 
958 	req = vtblk_request_dequeue(sc);
959 	if (req == NULL)
960 		return (NULL);
961 
962 	bp = bioq_takefirst(bioq);
963 	req->vbr_bp = bp;
964 	req->vbr_ack = -1;
965 	req->vbr_hdr.ioprio = vtblk_gtoh32(sc, 1);
966 
967 	switch (bp->bio_cmd) {
968 	case BIO_FLUSH:
969 		req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_FLUSH);
970 		req->vbr_hdr.sector = 0;
971 		break;
972 	case BIO_READ:
973 		req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_IN);
974 		req->vbr_hdr.sector = vtblk_gtoh64(sc, bp->bio_offset / VTBLK_BSIZE);
975 		break;
976 	case BIO_WRITE:
977 		req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_OUT);
978 		req->vbr_hdr.sector = vtblk_gtoh64(sc, bp->bio_offset / VTBLK_BSIZE);
979 		break;
980 	case BIO_DELETE:
981 		req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_DISCARD);
982 		req->vbr_hdr.sector = vtblk_gtoh64(sc, bp->bio_offset / VTBLK_BSIZE);
983 		break;
984 	default:
985 		panic("%s: bio with unhandled cmd: %d", __func__, bp->bio_cmd);
986 	}
987 
988 	if (bp->bio_flags & BIO_ORDERED)
989 		req->vbr_hdr.type |= vtblk_gtoh32(sc, VIRTIO_BLK_T_BARRIER);
990 
991 	return (req);
992 }
993 
994 static int
995 vtblk_request_execute(struct vtblk_request *req, int flags)
996 {
997 	struct vtblk_softc *sc = req->vbr_sc;
998 	struct bio *bp = req->vbr_bp;
999 	int error = 0;
1000 
1001 	/*
1002 	 * Call via bus_dmamap_load_bio or directly depending on whether we
1003 	 * have a buffer we need to map.  If we don't have a busdma map,
1004 	 * try to perform the I/O directly and hope that it works (this will
1005 	 * happen when dumping).
1006 	 */
1007 	if ((req->vbr_mapp != NULL) &&
1008 	    (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE)) {
1009 		error = bus_dmamap_load_bio(sc->vtblk_dmat, req->vbr_mapp,
1010 		    req->vbr_bp, vtblk_request_execute_cb, req, flags);
1011 		if (error == EINPROGRESS) {
1012 			req->vbr_busdma_wait = 1;
1013 			sc->vtblk_flags |= VTBLK_FLAG_BUSDMA_WAIT;
1014 		}
1015 	} else {
1016 		vtblk_request_execute_cb(req, NULL, 0, 0);
1017 	}
1018 
1019 	return (error ? error : req->vbr_error);
1020 }
1021 
1022 static void
1023 vtblk_request_execute_cb(void * callback_arg, bus_dma_segment_t * segs,
1024     int nseg, int error)
1025 {
1026 	struct vtblk_request *req;
1027 	struct vtblk_softc *sc;
1028 	struct virtqueue *vq;
1029 	struct sglist *sg;
1030 	struct bio *bp;
1031 	int ordered, readable, writable, i;
1032 
1033 	req = (struct vtblk_request *)callback_arg;
1034 	sc = req->vbr_sc;
1035 	vq = sc->vtblk_vq;
1036 	sg = sc->vtblk_sglist;
1037 	bp = req->vbr_bp;
1038 	ordered = 0;
1039 	writable = 0;
1040 
1041 	/*
1042 	 * If we paused request queueing while we waited for busdma to call us
1043 	 * asynchronously, unpause it now; this request made it through so we
1044 	 * don't need to worry about others getting ahead of us.  (Note that we
1045 	 * hold the device mutex so nothing will happen until after we return
1046 	 * anyway.)
1047 	 */
1048 	if (req->vbr_busdma_wait)
1049 		sc->vtblk_flags &= ~VTBLK_FLAG_BUSDMA_WAIT;
1050 
1051 	/* Fail on errors from busdma. */
1052 	if (error)
1053 		goto out1;
1054 
1055 	/*
1056 	 * Some hosts (such as bhyve) do not implement the barrier feature,
1057 	 * so we emulate it in the driver by allowing the barrier request
1058 	 * to be the only one in flight.
1059 	 */
1060 	if ((sc->vtblk_flags & VTBLK_FLAG_BARRIER) == 0) {
1061 		if (sc->vtblk_req_ordered != NULL) {
1062 			error = EBUSY;
1063 			goto out;
1064 		}
1065 		if (bp->bio_flags & BIO_ORDERED) {
1066 			if (!virtqueue_empty(vq)) {
1067 				error = EBUSY;
1068 				goto out;
1069 			}
1070 			ordered = 1;
1071 			req->vbr_hdr.type &= vtblk_gtoh32(sc,
1072 				~VIRTIO_BLK_T_BARRIER);
1073 		}
1074 	}
1075 
1076 	sglist_reset(sg);
1077 	sglist_append(sg, &req->vbr_hdr, sizeof(struct virtio_blk_outhdr));
1078 
1079 	if (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE) {
1080 		/*
1081 		 * We cast bus_addr_t to vm_paddr_t here; since we skip the
1082 		 * iommu mapping (see vtblk_attach) this should be safe.
1083 		 */
1084 		for (i = 0; i < nseg; i++) {
1085 			error = sglist_append_phys(sg,
1086 			    (vm_paddr_t)segs[i].ds_addr, segs[i].ds_len);
1087 			if (error || sg->sg_nseg == sg->sg_maxseg) {
1088 				panic("%s: bio %p data buffer too big %d",
1089 				    __func__, bp, error);
1090 			}
1091 		}
1092 
1093 		/* Special handling for dump, which bypasses busdma. */
1094 		if (req->vbr_mapp == NULL) {
1095 			error = sglist_append_bio(sg, bp);
1096 			if (error || sg->sg_nseg == sg->sg_maxseg) {
1097 				panic("%s: bio %p data buffer too big %d",
1098 				    __func__, bp, error);
1099 			}
1100 		}
1101 
1102 		/* BIO_READ means the host writes into our buffer. */
1103 		if (bp->bio_cmd == BIO_READ)
1104 			writable = sg->sg_nseg - 1;
1105 	} else if (bp->bio_cmd == BIO_DELETE) {
1106 		struct virtio_blk_discard_write_zeroes *discard;
1107 
1108 		discard = malloc(sizeof(*discard), M_DEVBUF, M_NOWAIT | M_ZERO);
1109 		if (discard == NULL) {
1110 			error = ENOMEM;
1111 			goto out;
1112 		}
1113 
1114 		bp->bio_driver1 = discard;
1115 		discard->sector = vtblk_gtoh64(sc, bp->bio_offset / VTBLK_BSIZE);
1116 		discard->num_sectors = vtblk_gtoh32(sc, bp->bio_bcount / VTBLK_BSIZE);
1117 		error = sglist_append(sg, discard, sizeof(*discard));
1118 		if (error || sg->sg_nseg == sg->sg_maxseg) {
1119 			panic("%s: bio %p data buffer too big %d",
1120 			    __func__, bp, error);
1121 		}
1122 	}
1123 
1124 	writable++;
1125 	sglist_append(sg, &req->vbr_ack, sizeof(uint8_t));
1126 	readable = sg->sg_nseg - writable;
1127 
1128 	if (req->vbr_mapp != NULL) {
1129 		switch (bp->bio_cmd) {
1130 		case BIO_READ:
1131 			bus_dmamap_sync(sc->vtblk_dmat, req->vbr_mapp,
1132 			    BUS_DMASYNC_PREREAD);
1133 			break;
1134 		case BIO_WRITE:
1135 			bus_dmamap_sync(sc->vtblk_dmat, req->vbr_mapp,
1136 			    BUS_DMASYNC_PREWRITE);
1137 			break;
1138 		}
1139 	}
1140 
1141 	error = virtqueue_enqueue(vq, req, sg, readable, writable);
1142 	if (error == 0 && ordered)
1143 		sc->vtblk_req_ordered = req;
1144 
1145 	/*
1146 	 * If we were called asynchronously, we need to notify the queue that
1147 	 * we've added a new request, since the notification from startio was
1148 	 * performed already.
1149 	 */
1150 	if (error == 0 && req->vbr_busdma_wait)
1151 		virtqueue_notify(vq);
1152 
1153 out:
1154 	if (error && (req->vbr_mapp != NULL))
1155 		bus_dmamap_unload(sc->vtblk_dmat, req->vbr_mapp);
1156 out1:
1157 	if (error && req->vbr_requeue_on_error)
1158 		vtblk_request_requeue_ready(sc, req);
1159 	req->vbr_error = error;
1160 }
1161 
1162 static int
1163 vtblk_request_error(struct vtblk_request *req)
1164 {
1165 	int error;
1166 
1167 	switch (req->vbr_ack) {
1168 	case VIRTIO_BLK_S_OK:
1169 		error = 0;
1170 		break;
1171 	case VIRTIO_BLK_S_UNSUPP:
1172 		error = ENOTSUP;
1173 		break;
1174 	default:
1175 		error = EIO;
1176 		break;
1177 	}
1178 
1179 	return (error);
1180 }
1181 
1182 static struct bio *
1183 vtblk_queue_complete_one(struct vtblk_softc *sc, struct vtblk_request *req)
1184 {
1185 	struct bio *bp;
1186 
1187 	if (sc->vtblk_req_ordered != NULL) {
1188 		MPASS(sc->vtblk_req_ordered == req);
1189 		sc->vtblk_req_ordered = NULL;
1190 	}
1191 
1192 	bp = req->vbr_bp;
1193 	if (req->vbr_mapp != NULL) {
1194 		switch (bp->bio_cmd) {
1195 		case BIO_READ:
1196 			bus_dmamap_sync(sc->vtblk_dmat, req->vbr_mapp,
1197 			    BUS_DMASYNC_POSTREAD);
1198 			bus_dmamap_unload(sc->vtblk_dmat, req->vbr_mapp);
1199 			break;
1200 		case BIO_WRITE:
1201 			bus_dmamap_sync(sc->vtblk_dmat, req->vbr_mapp,
1202 			    BUS_DMASYNC_POSTWRITE);
1203 			bus_dmamap_unload(sc->vtblk_dmat, req->vbr_mapp);
1204 			break;
1205 		}
1206 	}
1207 	bp->bio_error = vtblk_request_error(req);
1208 	return (bp);
1209 }
1210 
1211 static void
1212 vtblk_queue_completed(struct vtblk_softc *sc, struct bio_queue *queue)
1213 {
1214 	struct vtblk_request *req;
1215 	struct bio *bp;
1216 
1217 	while ((req = virtqueue_dequeue(sc->vtblk_vq, NULL)) != NULL) {
1218 		bp = vtblk_queue_complete_one(sc, req);
1219 
1220 		TAILQ_INSERT_TAIL(queue, bp, bio_queue);
1221 		vtblk_request_enqueue(sc, req);
1222 	}
1223 }
1224 
1225 static void
1226 vtblk_done_completed(struct vtblk_softc *sc, struct bio_queue *queue)
1227 {
1228 	struct bio *bp, *tmp;
1229 
1230 	TAILQ_FOREACH_SAFE(bp, queue, bio_queue, tmp) {
1231 		if (bp->bio_error != 0)
1232 			disk_err(bp, "hard error", -1, 1);
1233 		vtblk_bio_done(sc, bp, bp->bio_error);
1234 	}
1235 }
1236 
1237 static void
1238 vtblk_drain_vq(struct vtblk_softc *sc)
1239 {
1240 	struct virtqueue *vq;
1241 	struct vtblk_request *req;
1242 	int last;
1243 
1244 	vq = sc->vtblk_vq;
1245 	last = 0;
1246 
1247 	while ((req = virtqueue_drain(vq, &last)) != NULL) {
1248 		vtblk_bio_done(sc, req->vbr_bp, ENXIO);
1249 		vtblk_request_enqueue(sc, req);
1250 	}
1251 
1252 	sc->vtblk_req_ordered = NULL;
1253 	KASSERT(virtqueue_empty(vq), ("virtqueue not empty"));
1254 }
1255 
1256 static void
1257 vtblk_drain(struct vtblk_softc *sc)
1258 {
1259 	struct bio_queue_head *bioq;
1260 	struct vtblk_request *req;
1261 	struct bio *bp;
1262 
1263 	bioq = &sc->vtblk_bioq;
1264 
1265 	if (sc->vtblk_vq != NULL) {
1266 		struct bio_queue queue;
1267 
1268 		TAILQ_INIT(&queue);
1269 		vtblk_queue_completed(sc, &queue);
1270 		vtblk_done_completed(sc, &queue);
1271 
1272 		vtblk_drain_vq(sc);
1273 	}
1274 
1275 	while ((req = vtblk_request_next_ready(sc)) != NULL) {
1276 		vtblk_bio_done(sc, req->vbr_bp, ENXIO);
1277 		vtblk_request_enqueue(sc, req);
1278 	}
1279 
1280 	while (bioq_first(bioq) != NULL) {
1281 		bp = bioq_takefirst(bioq);
1282 		vtblk_bio_done(sc, bp, ENXIO);
1283 	}
1284 
1285 	vtblk_request_free(sc);
1286 }
1287 
1288 static void
1289 vtblk_startio(struct vtblk_softc *sc)
1290 {
1291 	struct virtqueue *vq;
1292 	struct vtblk_request *req;
1293 	int enq;
1294 
1295 	VTBLK_LOCK_ASSERT(sc);
1296 	vq = sc->vtblk_vq;
1297 	enq = 0;
1298 
1299 	if (sc->vtblk_flags & (VTBLK_FLAG_SUSPEND | VTBLK_FLAG_BUSDMA_WAIT))
1300 		return;
1301 
1302 	while (!virtqueue_full(vq)) {
1303 		req = vtblk_request_next(sc);
1304 		if (req == NULL)
1305 			break;
1306 
1307 		req->vbr_requeue_on_error = 1;
1308 		if (vtblk_request_execute(req, BUS_DMA_WAITOK))
1309 			break;
1310 
1311 		enq++;
1312 	}
1313 
1314 	if (enq > 0)
1315 		virtqueue_notify(vq);
1316 }
1317 
1318 static void
1319 vtblk_bio_done(struct vtblk_softc *sc, struct bio *bp, int error)
1320 {
1321 
1322 	/* Because of GEOM direct dispatch, we cannot hold any locks. */
1323 	if (sc != NULL)
1324 		VTBLK_LOCK_ASSERT_NOTOWNED(sc);
1325 
1326 	if (error) {
1327 		bp->bio_resid = bp->bio_bcount;
1328 		bp->bio_error = error;
1329 		bp->bio_flags |= BIO_ERROR;
1330 	} else {
1331 		kmsan_mark_bio(bp, KMSAN_STATE_INITED);
1332 	}
1333 
1334 	if (bp->bio_driver1 != NULL) {
1335 		free(bp->bio_driver1, M_DEVBUF);
1336 		bp->bio_driver1 = NULL;
1337 	}
1338 
1339 	biodone(bp);
1340 }
1341 
1342 #define VTBLK_GET_CONFIG(_dev, _feature, _field, _cfg)			\
1343 	if (virtio_with_feature(_dev, _feature)) {			\
1344 		virtio_read_device_config(_dev,				\
1345 		    offsetof(struct virtio_blk_config, _field),		\
1346 		    &(_cfg)->_field, sizeof((_cfg)->_field));		\
1347 	}
1348 
1349 static void
1350 vtblk_read_config(struct vtblk_softc *sc, struct virtio_blk_config *blkcfg)
1351 {
1352 	device_t dev;
1353 
1354 	dev = sc->vtblk_dev;
1355 
1356 	bzero(blkcfg, sizeof(struct virtio_blk_config));
1357 
1358 	/* The capacity is always available. */
1359 	virtio_read_device_config(dev, offsetof(struct virtio_blk_config,
1360 	    capacity), &blkcfg->capacity, sizeof(blkcfg->capacity));
1361 
1362 	/* Read the configuration if the feature was negotiated. */
1363 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_SIZE_MAX, size_max, blkcfg);
1364 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_SEG_MAX, seg_max, blkcfg);
1365 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_GEOMETRY,
1366 	    geometry.cylinders, blkcfg);
1367 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_GEOMETRY,
1368 	    geometry.heads, blkcfg);
1369 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_GEOMETRY,
1370 	    geometry.sectors, blkcfg);
1371 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_BLK_SIZE, blk_size, blkcfg);
1372 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_TOPOLOGY,
1373 	    topology.physical_block_exp, blkcfg);
1374 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_TOPOLOGY,
1375 	    topology.alignment_offset, blkcfg);
1376 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_TOPOLOGY,
1377 	    topology.min_io_size, blkcfg);
1378 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_TOPOLOGY,
1379 	    topology.opt_io_size, blkcfg);
1380 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_CONFIG_WCE, wce, blkcfg);
1381 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_DISCARD, max_discard_sectors,
1382 	    blkcfg);
1383 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_DISCARD, max_discard_seg, blkcfg);
1384 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_DISCARD, discard_sector_alignment,
1385 	    blkcfg);
1386 }
1387 
1388 #undef VTBLK_GET_CONFIG
1389 
1390 static void
1391 vtblk_ident(struct vtblk_softc *sc)
1392 {
1393 	struct bio buf;
1394 	struct disk *dp;
1395 	struct vtblk_request *req;
1396 	int len, error;
1397 
1398 	dp = sc->vtblk_disk;
1399 	len = MIN(VIRTIO_BLK_ID_BYTES, DISK_IDENT_SIZE);
1400 
1401 	if (vtblk_tunable_int(sc, "no_ident", vtblk_no_ident) != 0)
1402 		return;
1403 
1404 	req = vtblk_request_dequeue(sc);
1405 	if (req == NULL)
1406 		return;
1407 
1408 	req->vbr_ack = -1;
1409 	req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_GET_ID);
1410 	req->vbr_hdr.ioprio = vtblk_gtoh32(sc, 1);
1411 	req->vbr_hdr.sector = 0;
1412 
1413 	req->vbr_bp = &buf;
1414 	g_reset_bio(&buf);
1415 
1416 	buf.bio_cmd = BIO_READ;
1417 	buf.bio_data = dp->d_ident;
1418 	buf.bio_bcount = len;
1419 
1420 	VTBLK_LOCK(sc);
1421 	error = vtblk_poll_request(sc, req);
1422 	VTBLK_UNLOCK(sc);
1423 
1424 	if (error) {
1425 		device_printf(sc->vtblk_dev,
1426 		    "error getting device identifier: %d\n", error);
1427 	}
1428 }
1429 
1430 static int
1431 vtblk_poll_request(struct vtblk_softc *sc, struct vtblk_request *req)
1432 {
1433 	struct vtblk_request *req1 __diagused;
1434 	struct virtqueue *vq;
1435 	struct bio *bp;
1436 	int error;
1437 
1438 	vq = sc->vtblk_vq;
1439 
1440 	if (!virtqueue_empty(vq))
1441 		return (EBUSY);
1442 
1443 	error = vtblk_request_execute(req, BUS_DMA_NOWAIT);
1444 	if (error)
1445 		return (error);
1446 
1447 	virtqueue_notify(vq);
1448 	req1 = virtqueue_poll(vq, NULL);
1449 	KASSERT(req == req1,
1450 	    ("%s: polling completed %p not %p", __func__, req1, req));
1451 
1452 	bp = vtblk_queue_complete_one(sc, req);
1453 	error = bp->bio_error;
1454 	if (error && bootverbose) {
1455 		device_printf(sc->vtblk_dev,
1456 		    "%s: IO error: %d\n", __func__, error);
1457 	}
1458 	if (req != &sc->vtblk_dump_request)
1459 		vtblk_request_enqueue(sc, req);
1460 
1461 	return (error);
1462 }
1463 
1464 static int
1465 vtblk_quiesce(struct vtblk_softc *sc)
1466 {
1467 	int error;
1468 
1469 	VTBLK_LOCK_ASSERT(sc);
1470 	error = 0;
1471 
1472 	while (!virtqueue_empty(sc->vtblk_vq)) {
1473 		if (mtx_sleep(&sc->vtblk_vq, VTBLK_MTX(sc), PRIBIO, "vtblkq",
1474 		    VTBLK_QUIESCE_TIMEOUT) == EWOULDBLOCK) {
1475 			error = EBUSY;
1476 			break;
1477 		}
1478 	}
1479 
1480 	return (error);
1481 }
1482 
1483 static void
1484 vtblk_vq_intr(void *xsc)
1485 {
1486 	struct vtblk_softc *sc;
1487 	struct virtqueue *vq;
1488 	struct bio_queue queue;
1489 
1490 	sc = xsc;
1491 	vq = sc->vtblk_vq;
1492 	TAILQ_INIT(&queue);
1493 
1494 	VTBLK_LOCK(sc);
1495 
1496 again:
1497 	if (sc->vtblk_flags & VTBLK_FLAG_DETACH)
1498 		goto out;
1499 
1500 	vtblk_queue_completed(sc, &queue);
1501 	vtblk_startio(sc);
1502 
1503 	if (virtqueue_enable_intr(vq) != 0) {
1504 		virtqueue_disable_intr(vq);
1505 		goto again;
1506 	}
1507 
1508 	if (sc->vtblk_flags & VTBLK_FLAG_SUSPEND)
1509 		wakeup(&sc->vtblk_vq);
1510 
1511 out:
1512 	VTBLK_UNLOCK(sc);
1513 	vtblk_done_completed(sc, &queue);
1514 }
1515 
1516 static void
1517 vtblk_stop(struct vtblk_softc *sc)
1518 {
1519 
1520 	virtqueue_disable_intr(sc->vtblk_vq);
1521 	virtio_stop(sc->vtblk_dev);
1522 }
1523 
1524 static void
1525 vtblk_dump_quiesce(struct vtblk_softc *sc)
1526 {
1527 
1528 	/*
1529 	 * Spin here until all the requests in-flight at the time of the
1530 	 * dump are completed and queued. The queued requests will be
1531 	 * biodone'd once the dump is finished.
1532 	 */
1533 	while (!virtqueue_empty(sc->vtblk_vq))
1534 		vtblk_queue_completed(sc, &sc->vtblk_dump_queue);
1535 }
1536 
1537 static int
1538 vtblk_dump_write(struct vtblk_softc *sc, void *virtual, off_t offset,
1539     size_t length)
1540 {
1541 	struct bio buf;
1542 	struct vtblk_request *req;
1543 
1544 	req = &sc->vtblk_dump_request;
1545 	req->vbr_sc = sc;
1546 	req->vbr_ack = -1;
1547 	req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_OUT);
1548 	req->vbr_hdr.ioprio = vtblk_gtoh32(sc, 1);
1549 	req->vbr_hdr.sector = vtblk_gtoh64(sc, offset / VTBLK_BSIZE);
1550 
1551 	req->vbr_bp = &buf;
1552 	g_reset_bio(&buf);
1553 
1554 	buf.bio_cmd = BIO_WRITE;
1555 	buf.bio_data = virtual;
1556 	buf.bio_bcount = length;
1557 
1558 	return (vtblk_poll_request(sc, req));
1559 }
1560 
1561 static int
1562 vtblk_dump_flush(struct vtblk_softc *sc)
1563 {
1564 	struct bio buf;
1565 	struct vtblk_request *req;
1566 
1567 	req = &sc->vtblk_dump_request;
1568 	req->vbr_sc = sc;
1569 	req->vbr_ack = -1;
1570 	req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_FLUSH);
1571 	req->vbr_hdr.ioprio = vtblk_gtoh32(sc, 1);
1572 	req->vbr_hdr.sector = 0;
1573 
1574 	req->vbr_bp = &buf;
1575 	g_reset_bio(&buf);
1576 
1577 	buf.bio_cmd = BIO_FLUSH;
1578 
1579 	return (vtblk_poll_request(sc, req));
1580 }
1581 
1582 static void
1583 vtblk_dump_complete(struct vtblk_softc *sc)
1584 {
1585 
1586 	vtblk_dump_flush(sc);
1587 
1588 	VTBLK_UNLOCK(sc);
1589 	vtblk_done_completed(sc, &sc->vtblk_dump_queue);
1590 	VTBLK_LOCK(sc);
1591 }
1592 
1593 static void
1594 vtblk_set_write_cache(struct vtblk_softc *sc, int wc)
1595 {
1596 
1597 	/* Set either writeback (1) or writethrough (0) mode. */
1598 	virtio_write_dev_config_1(sc->vtblk_dev,
1599 	    offsetof(struct virtio_blk_config, wce), wc);
1600 }
1601 
1602 static int
1603 vtblk_write_cache_enabled(struct vtblk_softc *sc,
1604     struct virtio_blk_config *blkcfg)
1605 {
1606 	int wc;
1607 
1608 	if (sc->vtblk_flags & VTBLK_FLAG_WCE_CONFIG) {
1609 		wc = vtblk_tunable_int(sc, "writecache_mode",
1610 		    vtblk_writecache_mode);
1611 		if (wc >= 0 && wc < VTBLK_CACHE_MAX)
1612 			vtblk_set_write_cache(sc, wc);
1613 		else
1614 			wc = blkcfg->wce;
1615 	} else
1616 		wc = virtio_with_feature(sc->vtblk_dev, VIRTIO_BLK_F_FLUSH);
1617 
1618 	return (wc);
1619 }
1620 
1621 static int
1622 vtblk_write_cache_sysctl(SYSCTL_HANDLER_ARGS)
1623 {
1624 	struct vtblk_softc *sc;
1625 	int wc, error;
1626 
1627 	sc = oidp->oid_arg1;
1628 	wc = sc->vtblk_write_cache;
1629 
1630 	error = sysctl_handle_int(oidp, &wc, 0, req);
1631 	if (error || req->newptr == NULL)
1632 		return (error);
1633 	if ((sc->vtblk_flags & VTBLK_FLAG_WCE_CONFIG) == 0)
1634 		return (EPERM);
1635 	if (wc < 0 || wc >= VTBLK_CACHE_MAX)
1636 		return (EINVAL);
1637 
1638 	VTBLK_LOCK(sc);
1639 	sc->vtblk_write_cache = wc;
1640 	vtblk_set_write_cache(sc, sc->vtblk_write_cache);
1641 	VTBLK_UNLOCK(sc);
1642 
1643 	return (0);
1644 }
1645 
1646 static void
1647 vtblk_setup_sysctl(struct vtblk_softc *sc)
1648 {
1649 	device_t dev;
1650 	struct sysctl_ctx_list *ctx;
1651 	struct sysctl_oid *tree;
1652 	struct sysctl_oid_list *child;
1653 
1654 	dev = sc->vtblk_dev;
1655 	ctx = device_get_sysctl_ctx(dev);
1656 	tree = device_get_sysctl_tree(dev);
1657 	child = SYSCTL_CHILDREN(tree);
1658 
1659 	SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "writecache_mode",
1660 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
1661 	    vtblk_write_cache_sysctl, "I",
1662 	    "Write cache mode (writethrough (0) or writeback (1))");
1663 }
1664 
1665 static int
1666 vtblk_tunable_int(struct vtblk_softc *sc, const char *knob, int def)
1667 {
1668 	char path[64];
1669 
1670 	snprintf(path, sizeof(path),
1671 	    "hw.vtblk.%d.%s", device_get_unit(sc->vtblk_dev), knob);
1672 	TUNABLE_INT_FETCH(path, &def);
1673 
1674 	return (def);
1675 }
1676