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