xref: /freebsd/sys/dev/virtio/block/virtio_blk.c (revision cfc39718e9cc18943a6f8428c560b02c6f590b16)
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.
996 	 */
997 	if (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE) {
998 		error = bus_dmamap_load_bio(sc->vtblk_dmat, req->vbr_mapp,
999 		    req->vbr_bp, vtblk_request_execute_cb, req, flags);
1000 		if (error == EINPROGRESS) {
1001 			req->vbr_busdma_wait = 1;
1002 			sc->vtblk_flags |= VTBLK_FLAG_BUSDMA_WAIT;
1003 		}
1004 	} else {
1005 		vtblk_request_execute_cb(req, NULL, 0, 0);
1006 	}
1007 
1008 	return (error ? error : req->vbr_error);
1009 }
1010 
1011 static void
1012 vtblk_request_execute_cb(void * callback_arg, bus_dma_segment_t * segs,
1013     int nseg, int error)
1014 {
1015 	struct vtblk_request *req;
1016 	struct vtblk_softc *sc;
1017 	struct virtqueue *vq;
1018 	struct sglist *sg;
1019 	struct bio *bp;
1020 	int ordered, readable, writable, i;
1021 
1022 	req = (struct vtblk_request *)callback_arg;
1023 	sc = req->vbr_sc;
1024 	vq = sc->vtblk_vq;
1025 	sg = sc->vtblk_sglist;
1026 	bp = req->vbr_bp;
1027 	ordered = 0;
1028 	writable = 0;
1029 
1030 	/*
1031 	 * If we paused request queueing while we waited for busdma to call us
1032 	 * asynchronously, unpause it now; this request made it through so we
1033 	 * don't need to worry about others getting ahead of us.  (Note that we
1034 	 * hold the device mutex so nothing will happen until after we return
1035 	 * anyway.)
1036 	 */
1037 	if (req->vbr_busdma_wait)
1038 		sc->vtblk_flags &= ~VTBLK_FLAG_BUSDMA_WAIT;
1039 
1040 	/* Fail on errors from busdma. */
1041 	if (error)
1042 		goto out1;
1043 
1044 	/*
1045 	 * Some hosts (such as bhyve) do not implement the barrier feature,
1046 	 * so we emulate it in the driver by allowing the barrier request
1047 	 * to be the only one in flight.
1048 	 */
1049 	if ((sc->vtblk_flags & VTBLK_FLAG_BARRIER) == 0) {
1050 		if (sc->vtblk_req_ordered != NULL) {
1051 			error = EBUSY;
1052 			goto out;
1053 		}
1054 		if (bp->bio_flags & BIO_ORDERED) {
1055 			if (!virtqueue_empty(vq)) {
1056 				error = EBUSY;
1057 				goto out;
1058 			}
1059 			ordered = 1;
1060 			req->vbr_hdr.type &= vtblk_gtoh32(sc,
1061 				~VIRTIO_BLK_T_BARRIER);
1062 		}
1063 	}
1064 
1065 	sglist_reset(sg);
1066 	sglist_append(sg, &req->vbr_hdr, sizeof(struct virtio_blk_outhdr));
1067 
1068 	if (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE) {
1069 		/*
1070 		 * We cast bus_addr_t to vm_paddr_t here; this isn't valid on
1071 		 * all platforms, but we believe it works on all platforms
1072 		 * which are supported by virtio.
1073 		 */
1074 		for (i = 0; i < nseg; i++) {
1075 			error = sglist_append_phys(sg,
1076 			    (vm_paddr_t)segs[i].ds_addr, segs[i].ds_len);
1077 			if (error || sg->sg_nseg == sg->sg_maxseg) {
1078 				panic("%s: bio %p data buffer too big %d",
1079 				    __func__, bp, error);
1080 			}
1081 		}
1082 
1083 		/* BIO_READ means the host writes into our buffer. */
1084 		if (bp->bio_cmd == BIO_READ)
1085 			writable = sg->sg_nseg - 1;
1086 	} else if (bp->bio_cmd == BIO_DELETE) {
1087 		struct virtio_blk_discard_write_zeroes *discard;
1088 
1089 		discard = malloc(sizeof(*discard), M_DEVBUF, M_NOWAIT | M_ZERO);
1090 		if (discard == NULL) {
1091 			error = ENOMEM;
1092 			goto out;
1093 		}
1094 
1095 		bp->bio_driver1 = discard;
1096 		discard->sector = vtblk_gtoh64(sc, bp->bio_offset / VTBLK_BSIZE);
1097 		discard->num_sectors = vtblk_gtoh32(sc, bp->bio_bcount / VTBLK_BSIZE);
1098 		error = sglist_append(sg, discard, sizeof(*discard));
1099 		if (error || sg->sg_nseg == sg->sg_maxseg) {
1100 			panic("%s: bio %p data buffer too big %d",
1101 			    __func__, bp, error);
1102 		}
1103 	}
1104 
1105 	writable++;
1106 	sglist_append(sg, &req->vbr_ack, sizeof(uint8_t));
1107 	readable = sg->sg_nseg - writable;
1108 
1109 	switch (bp->bio_cmd) {
1110 	case BIO_READ:
1111 		bus_dmamap_sync(sc->vtblk_dmat, req->vbr_mapp,
1112 		    BUS_DMASYNC_PREREAD);
1113 		break;
1114 	case BIO_WRITE:
1115 		bus_dmamap_sync(sc->vtblk_dmat, req->vbr_mapp,
1116 		    BUS_DMASYNC_PREWRITE);
1117 		break;
1118 	}
1119 
1120 	error = virtqueue_enqueue(vq, req, sg, readable, writable);
1121 	if (error == 0 && ordered)
1122 		sc->vtblk_req_ordered = req;
1123 
1124 	/*
1125 	 * If we were called asynchronously, we need to notify the queue that
1126 	 * we've added a new request, since the notification from startio was
1127 	 * performed already.
1128 	 */
1129 	if (error == 0 && req->vbr_busdma_wait)
1130 		virtqueue_notify(vq);
1131 
1132 out:
1133 	if (error)
1134 		bus_dmamap_unload(sc->vtblk_dmat, req->vbr_mapp);
1135 out1:
1136 	if (error && req->vbr_requeue_on_error)
1137 		vtblk_request_requeue_ready(sc, req);
1138 	req->vbr_error = error;
1139 }
1140 
1141 static int
1142 vtblk_request_error(struct vtblk_request *req)
1143 {
1144 	int error;
1145 
1146 	switch (req->vbr_ack) {
1147 	case VIRTIO_BLK_S_OK:
1148 		error = 0;
1149 		break;
1150 	case VIRTIO_BLK_S_UNSUPP:
1151 		error = ENOTSUP;
1152 		break;
1153 	default:
1154 		error = EIO;
1155 		break;
1156 	}
1157 
1158 	return (error);
1159 }
1160 
1161 static void
1162 vtblk_queue_completed(struct vtblk_softc *sc, struct bio_queue *queue)
1163 {
1164 	struct vtblk_request *req;
1165 	struct bio *bp;
1166 
1167 	while ((req = virtqueue_dequeue(sc->vtblk_vq, NULL)) != NULL) {
1168 		if (sc->vtblk_req_ordered != NULL) {
1169 			MPASS(sc->vtblk_req_ordered == req);
1170 			sc->vtblk_req_ordered = NULL;
1171 		}
1172 
1173 		bp = req->vbr_bp;
1174 		switch (bp->bio_cmd) {
1175 		case BIO_READ:
1176 			bus_dmamap_sync(sc->vtblk_dmat, req->vbr_mapp,
1177 			    BUS_DMASYNC_POSTREAD);
1178 			bus_dmamap_unload(sc->vtblk_dmat, req->vbr_mapp);
1179 			break;
1180 		case BIO_WRITE:
1181 			bus_dmamap_sync(sc->vtblk_dmat, req->vbr_mapp,
1182 			    BUS_DMASYNC_POSTWRITE);
1183 			bus_dmamap_unload(sc->vtblk_dmat, req->vbr_mapp);
1184 			break;
1185 		}
1186 		bp->bio_error = vtblk_request_error(req);
1187 		TAILQ_INSERT_TAIL(queue, bp, bio_queue);
1188 
1189 		vtblk_request_enqueue(sc, req);
1190 	}
1191 }
1192 
1193 static void
1194 vtblk_done_completed(struct vtblk_softc *sc, struct bio_queue *queue)
1195 {
1196 	struct bio *bp, *tmp;
1197 
1198 	TAILQ_FOREACH_SAFE(bp, queue, bio_queue, tmp) {
1199 		if (bp->bio_error != 0)
1200 			disk_err(bp, "hard error", -1, 1);
1201 		vtblk_bio_done(sc, bp, bp->bio_error);
1202 	}
1203 }
1204 
1205 static void
1206 vtblk_drain_vq(struct vtblk_softc *sc)
1207 {
1208 	struct virtqueue *vq;
1209 	struct vtblk_request *req;
1210 	int last;
1211 
1212 	vq = sc->vtblk_vq;
1213 	last = 0;
1214 
1215 	while ((req = virtqueue_drain(vq, &last)) != NULL) {
1216 		vtblk_bio_done(sc, req->vbr_bp, ENXIO);
1217 		vtblk_request_enqueue(sc, req);
1218 	}
1219 
1220 	sc->vtblk_req_ordered = NULL;
1221 	KASSERT(virtqueue_empty(vq), ("virtqueue not empty"));
1222 }
1223 
1224 static void
1225 vtblk_drain(struct vtblk_softc *sc)
1226 {
1227 	struct bio_queue_head *bioq;
1228 	struct vtblk_request *req;
1229 	struct bio *bp;
1230 
1231 	bioq = &sc->vtblk_bioq;
1232 
1233 	if (sc->vtblk_vq != NULL) {
1234 		struct bio_queue queue;
1235 
1236 		TAILQ_INIT(&queue);
1237 		vtblk_queue_completed(sc, &queue);
1238 		vtblk_done_completed(sc, &queue);
1239 
1240 		vtblk_drain_vq(sc);
1241 	}
1242 
1243 	while ((req = vtblk_request_next_ready(sc)) != NULL) {
1244 		vtblk_bio_done(sc, req->vbr_bp, ENXIO);
1245 		vtblk_request_enqueue(sc, req);
1246 	}
1247 
1248 	while (bioq_first(bioq) != NULL) {
1249 		bp = bioq_takefirst(bioq);
1250 		vtblk_bio_done(sc, bp, ENXIO);
1251 	}
1252 
1253 	vtblk_request_free(sc);
1254 }
1255 
1256 static void
1257 vtblk_startio(struct vtblk_softc *sc)
1258 {
1259 	struct virtqueue *vq;
1260 	struct vtblk_request *req;
1261 	int enq;
1262 
1263 	VTBLK_LOCK_ASSERT(sc);
1264 	vq = sc->vtblk_vq;
1265 	enq = 0;
1266 
1267 	if (sc->vtblk_flags & (VTBLK_FLAG_SUSPEND | VTBLK_FLAG_BUSDMA_WAIT))
1268 		return;
1269 
1270 	while (!virtqueue_full(vq)) {
1271 		req = vtblk_request_next(sc);
1272 		if (req == NULL)
1273 			break;
1274 
1275 		req->vbr_requeue_on_error = 1;
1276 		if (vtblk_request_execute(req, BUS_DMA_WAITOK))
1277 			break;
1278 
1279 		enq++;
1280 	}
1281 
1282 	if (enq > 0)
1283 		virtqueue_notify(vq);
1284 }
1285 
1286 static void
1287 vtblk_bio_done(struct vtblk_softc *sc, struct bio *bp, int error)
1288 {
1289 
1290 	/* Because of GEOM direct dispatch, we cannot hold any locks. */
1291 	if (sc != NULL)
1292 		VTBLK_LOCK_ASSERT_NOTOWNED(sc);
1293 
1294 	if (error) {
1295 		bp->bio_resid = bp->bio_bcount;
1296 		bp->bio_error = error;
1297 		bp->bio_flags |= BIO_ERROR;
1298 	} else {
1299 		kmsan_mark_bio(bp, KMSAN_STATE_INITED);
1300 	}
1301 
1302 	if (bp->bio_driver1 != NULL) {
1303 		free(bp->bio_driver1, M_DEVBUF);
1304 		bp->bio_driver1 = NULL;
1305 	}
1306 
1307 	biodone(bp);
1308 }
1309 
1310 #define VTBLK_GET_CONFIG(_dev, _feature, _field, _cfg)			\
1311 	if (virtio_with_feature(_dev, _feature)) {			\
1312 		virtio_read_device_config(_dev,				\
1313 		    offsetof(struct virtio_blk_config, _field),		\
1314 		    &(_cfg)->_field, sizeof((_cfg)->_field));		\
1315 	}
1316 
1317 static void
1318 vtblk_read_config(struct vtblk_softc *sc, struct virtio_blk_config *blkcfg)
1319 {
1320 	device_t dev;
1321 
1322 	dev = sc->vtblk_dev;
1323 
1324 	bzero(blkcfg, sizeof(struct virtio_blk_config));
1325 
1326 	/* The capacity is always available. */
1327 	virtio_read_device_config(dev, offsetof(struct virtio_blk_config,
1328 	    capacity), &blkcfg->capacity, sizeof(blkcfg->capacity));
1329 
1330 	/* Read the configuration if the feature was negotiated. */
1331 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_SIZE_MAX, size_max, blkcfg);
1332 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_SEG_MAX, seg_max, blkcfg);
1333 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_GEOMETRY,
1334 	    geometry.cylinders, blkcfg);
1335 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_GEOMETRY,
1336 	    geometry.heads, blkcfg);
1337 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_GEOMETRY,
1338 	    geometry.sectors, blkcfg);
1339 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_BLK_SIZE, blk_size, blkcfg);
1340 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_TOPOLOGY,
1341 	    topology.physical_block_exp, blkcfg);
1342 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_TOPOLOGY,
1343 	    topology.alignment_offset, blkcfg);
1344 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_TOPOLOGY,
1345 	    topology.min_io_size, blkcfg);
1346 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_TOPOLOGY,
1347 	    topology.opt_io_size, blkcfg);
1348 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_CONFIG_WCE, wce, blkcfg);
1349 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_DISCARD, max_discard_sectors,
1350 	    blkcfg);
1351 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_DISCARD, max_discard_seg, blkcfg);
1352 	VTBLK_GET_CONFIG(dev, VIRTIO_BLK_F_DISCARD, discard_sector_alignment,
1353 	    blkcfg);
1354 }
1355 
1356 #undef VTBLK_GET_CONFIG
1357 
1358 static void
1359 vtblk_ident(struct vtblk_softc *sc)
1360 {
1361 	struct bio buf;
1362 	struct disk *dp;
1363 	struct vtblk_request *req;
1364 	int len, error;
1365 
1366 	dp = sc->vtblk_disk;
1367 	len = MIN(VIRTIO_BLK_ID_BYTES, DISK_IDENT_SIZE);
1368 
1369 	if (vtblk_tunable_int(sc, "no_ident", vtblk_no_ident) != 0)
1370 		return;
1371 
1372 	req = vtblk_request_dequeue(sc);
1373 	if (req == NULL)
1374 		return;
1375 
1376 	req->vbr_ack = -1;
1377 	req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_GET_ID);
1378 	req->vbr_hdr.ioprio = vtblk_gtoh32(sc, 1);
1379 	req->vbr_hdr.sector = 0;
1380 
1381 	req->vbr_bp = &buf;
1382 	g_reset_bio(&buf);
1383 
1384 	buf.bio_cmd = BIO_READ;
1385 	buf.bio_data = dp->d_ident;
1386 	buf.bio_bcount = len;
1387 
1388 	VTBLK_LOCK(sc);
1389 	error = vtblk_poll_request(sc, req);
1390 	VTBLK_UNLOCK(sc);
1391 
1392 	vtblk_request_enqueue(sc, req);
1393 
1394 	if (error) {
1395 		device_printf(sc->vtblk_dev,
1396 		    "error getting device identifier: %d\n", error);
1397 	}
1398 }
1399 
1400 static int
1401 vtblk_poll_request(struct vtblk_softc *sc, struct vtblk_request *req)
1402 {
1403 	struct virtqueue *vq;
1404 	int error;
1405 
1406 	vq = sc->vtblk_vq;
1407 
1408 	if (!virtqueue_empty(vq))
1409 		return (EBUSY);
1410 
1411 	error = vtblk_request_execute(req, BUS_DMA_NOWAIT);
1412 	if (error)
1413 		return (error);
1414 
1415 	virtqueue_notify(vq);
1416 	virtqueue_poll(vq, NULL);
1417 
1418 	error = vtblk_request_error(req);
1419 	if (error && bootverbose) {
1420 		device_printf(sc->vtblk_dev,
1421 		    "%s: IO error: %d\n", __func__, error);
1422 	}
1423 
1424 	return (error);
1425 }
1426 
1427 static int
1428 vtblk_quiesce(struct vtblk_softc *sc)
1429 {
1430 	int error;
1431 
1432 	VTBLK_LOCK_ASSERT(sc);
1433 	error = 0;
1434 
1435 	while (!virtqueue_empty(sc->vtblk_vq)) {
1436 		if (mtx_sleep(&sc->vtblk_vq, VTBLK_MTX(sc), PRIBIO, "vtblkq",
1437 		    VTBLK_QUIESCE_TIMEOUT) == EWOULDBLOCK) {
1438 			error = EBUSY;
1439 			break;
1440 		}
1441 	}
1442 
1443 	return (error);
1444 }
1445 
1446 static void
1447 vtblk_vq_intr(void *xsc)
1448 {
1449 	struct vtblk_softc *sc;
1450 	struct virtqueue *vq;
1451 	struct bio_queue queue;
1452 
1453 	sc = xsc;
1454 	vq = sc->vtblk_vq;
1455 	TAILQ_INIT(&queue);
1456 
1457 	VTBLK_LOCK(sc);
1458 
1459 again:
1460 	if (sc->vtblk_flags & VTBLK_FLAG_DETACH)
1461 		goto out;
1462 
1463 	vtblk_queue_completed(sc, &queue);
1464 	vtblk_startio(sc);
1465 
1466 	if (virtqueue_enable_intr(vq) != 0) {
1467 		virtqueue_disable_intr(vq);
1468 		goto again;
1469 	}
1470 
1471 	if (sc->vtblk_flags & VTBLK_FLAG_SUSPEND)
1472 		wakeup(&sc->vtblk_vq);
1473 
1474 out:
1475 	VTBLK_UNLOCK(sc);
1476 	vtblk_done_completed(sc, &queue);
1477 }
1478 
1479 static void
1480 vtblk_stop(struct vtblk_softc *sc)
1481 {
1482 
1483 	virtqueue_disable_intr(sc->vtblk_vq);
1484 	virtio_stop(sc->vtblk_dev);
1485 }
1486 
1487 static void
1488 vtblk_dump_quiesce(struct vtblk_softc *sc)
1489 {
1490 
1491 	/*
1492 	 * Spin here until all the requests in-flight at the time of the
1493 	 * dump are completed and queued. The queued requests will be
1494 	 * biodone'd once the dump is finished.
1495 	 */
1496 	while (!virtqueue_empty(sc->vtblk_vq))
1497 		vtblk_queue_completed(sc, &sc->vtblk_dump_queue);
1498 }
1499 
1500 static int
1501 vtblk_dump_write(struct vtblk_softc *sc, void *virtual, off_t offset,
1502     size_t length)
1503 {
1504 	struct bio buf;
1505 	struct vtblk_request *req;
1506 
1507 	req = &sc->vtblk_dump_request;
1508 	req->vbr_ack = -1;
1509 	req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_OUT);
1510 	req->vbr_hdr.ioprio = vtblk_gtoh32(sc, 1);
1511 	req->vbr_hdr.sector = vtblk_gtoh64(sc, offset / VTBLK_BSIZE);
1512 
1513 	req->vbr_bp = &buf;
1514 	g_reset_bio(&buf);
1515 
1516 	buf.bio_cmd = BIO_WRITE;
1517 	buf.bio_data = virtual;
1518 	buf.bio_bcount = length;
1519 
1520 	return (vtblk_poll_request(sc, req));
1521 }
1522 
1523 static int
1524 vtblk_dump_flush(struct vtblk_softc *sc)
1525 {
1526 	struct bio buf;
1527 	struct vtblk_request *req;
1528 
1529 	req = &sc->vtblk_dump_request;
1530 	req->vbr_ack = -1;
1531 	req->vbr_hdr.type = vtblk_gtoh32(sc, VIRTIO_BLK_T_FLUSH);
1532 	req->vbr_hdr.ioprio = vtblk_gtoh32(sc, 1);
1533 	req->vbr_hdr.sector = 0;
1534 
1535 	req->vbr_bp = &buf;
1536 	g_reset_bio(&buf);
1537 
1538 	buf.bio_cmd = BIO_FLUSH;
1539 
1540 	return (vtblk_poll_request(sc, req));
1541 }
1542 
1543 static void
1544 vtblk_dump_complete(struct vtblk_softc *sc)
1545 {
1546 
1547 	vtblk_dump_flush(sc);
1548 
1549 	VTBLK_UNLOCK(sc);
1550 	vtblk_done_completed(sc, &sc->vtblk_dump_queue);
1551 	VTBLK_LOCK(sc);
1552 }
1553 
1554 static void
1555 vtblk_set_write_cache(struct vtblk_softc *sc, int wc)
1556 {
1557 
1558 	/* Set either writeback (1) or writethrough (0) mode. */
1559 	virtio_write_dev_config_1(sc->vtblk_dev,
1560 	    offsetof(struct virtio_blk_config, wce), wc);
1561 }
1562 
1563 static int
1564 vtblk_write_cache_enabled(struct vtblk_softc *sc,
1565     struct virtio_blk_config *blkcfg)
1566 {
1567 	int wc;
1568 
1569 	if (sc->vtblk_flags & VTBLK_FLAG_WCE_CONFIG) {
1570 		wc = vtblk_tunable_int(sc, "writecache_mode",
1571 		    vtblk_writecache_mode);
1572 		if (wc >= 0 && wc < VTBLK_CACHE_MAX)
1573 			vtblk_set_write_cache(sc, wc);
1574 		else
1575 			wc = blkcfg->wce;
1576 	} else
1577 		wc = virtio_with_feature(sc->vtblk_dev, VIRTIO_BLK_F_FLUSH);
1578 
1579 	return (wc);
1580 }
1581 
1582 static int
1583 vtblk_write_cache_sysctl(SYSCTL_HANDLER_ARGS)
1584 {
1585 	struct vtblk_softc *sc;
1586 	int wc, error;
1587 
1588 	sc = oidp->oid_arg1;
1589 	wc = sc->vtblk_write_cache;
1590 
1591 	error = sysctl_handle_int(oidp, &wc, 0, req);
1592 	if (error || req->newptr == NULL)
1593 		return (error);
1594 	if ((sc->vtblk_flags & VTBLK_FLAG_WCE_CONFIG) == 0)
1595 		return (EPERM);
1596 	if (wc < 0 || wc >= VTBLK_CACHE_MAX)
1597 		return (EINVAL);
1598 
1599 	VTBLK_LOCK(sc);
1600 	sc->vtblk_write_cache = wc;
1601 	vtblk_set_write_cache(sc, sc->vtblk_write_cache);
1602 	VTBLK_UNLOCK(sc);
1603 
1604 	return (0);
1605 }
1606 
1607 static void
1608 vtblk_setup_sysctl(struct vtblk_softc *sc)
1609 {
1610 	device_t dev;
1611 	struct sysctl_ctx_list *ctx;
1612 	struct sysctl_oid *tree;
1613 	struct sysctl_oid_list *child;
1614 
1615 	dev = sc->vtblk_dev;
1616 	ctx = device_get_sysctl_ctx(dev);
1617 	tree = device_get_sysctl_tree(dev);
1618 	child = SYSCTL_CHILDREN(tree);
1619 
1620 	SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "writecache_mode",
1621 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
1622 	    vtblk_write_cache_sysctl, "I",
1623 	    "Write cache mode (writethrough (0) or writeback (1))");
1624 }
1625 
1626 static int
1627 vtblk_tunable_int(struct vtblk_softc *sc, const char *knob, int def)
1628 {
1629 	char path[64];
1630 
1631 	snprintf(path, sizeof(path),
1632 	    "hw.vtblk.%d.%s", device_get_unit(sc->vtblk_dev), knob);
1633 	TUNABLE_INT_FETCH(path, &def);
1634 
1635 	return (def);
1636 }
1637