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