xref: /illumos-gate/usr/src/uts/common/io/vioblk/vioblk.c (revision 5328fc53d11d7151861fa272e4fb0248b8f0e145)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
24  * Copyright (c) 2012, Alexey Zaytsev <alexey.zaytsev@gmail.com>
25  * Copyright 2019 Joyent Inc.
26  */
27 
28 /*
29  * VIRTIO BLOCK DRIVER
30  *
31  * This driver provides support for Virtio Block devices.  Each driver instance
32  * attaches to a single underlying block device.
33  *
34  * REQUEST CHAIN LAYOUT
35  *
36  * Every request chain sent to the I/O queue has the following structure.  Each
37  * box in the diagram represents a descriptor entry (i.e., a DMA cookie) within
38  * the chain:
39  *
40  *    +-0-----------------------------------------+
41  *    | struct virtio_blk_hdr                     |-----------------------\
42  *    |   (written by driver, read by device)     |                       |
43  *    +-1-----------------------------------------+                       |
44  *    | optional data payload                     |--\                    |
45  *    |   (written by driver for write requests,  |  |                    |
46  *    |    or by device for read requests)        |  |                    |
47  *    +-2-----------------------------------------+  |                    |
48  *    | ,~`           :                              |-cookies loaned     |
49  *    |/              :                        ,~`|  | from blkdev        |
50  *                    :                       /   |  |                    |
51  *    +-(N - 1)-----------------------------------+  |                    |
52  *    | ... end of data payload.                  |  |                    |
53  *    |                                           |  |                    |
54  *    |                                           |--/                    |
55  *    +-N-----------------------------------------+                       |
56  *    | status byte                               |                       |
57  *    |   (written by device, read by driver)     |--------------------\  |
58  *    +-------------------------------------------+                    |  |
59  *                                                                     |  |
60  * The memory for the header and status bytes (i.e., 0 and N above)    |  |
61  * is allocated as a single chunk by vioblk_alloc_reqs():              |  |
62  *                                                                     |  |
63  *    +-------------------------------------------+                    |  |
64  *    | struct virtio_blk_hdr                     |<----------------------/
65  *    +-------------------------------------------+                    |
66  *    | status byte                               |<-------------------/
67  *    +-------------------------------------------+
68  */
69 
70 #include <sys/modctl.h>
71 #include <sys/blkdev.h>
72 #include <sys/types.h>
73 #include <sys/errno.h>
74 #include <sys/param.h>
75 #include <sys/stropts.h>
76 #include <sys/stream.h>
77 #include <sys/strsubr.h>
78 #include <sys/kmem.h>
79 #include <sys/conf.h>
80 #include <sys/devops.h>
81 #include <sys/ksynch.h>
82 #include <sys/stat.h>
83 #include <sys/modctl.h>
84 #include <sys/debug.h>
85 #include <sys/pci.h>
86 #include <sys/containerof.h>
87 #include <sys/ctype.h>
88 #include <sys/sysmacros.h>
89 
90 #include "virtio.h"
91 #include "vioblk.h"
92 
93 
94 static void vioblk_get_id(vioblk_t *);
95 uint_t vioblk_int_handler(caddr_t, caddr_t);
96 static uint_t vioblk_poll(vioblk_t *);
97 static int vioblk_quiesce(dev_info_t *);
98 static int vioblk_attach(dev_info_t *, ddi_attach_cmd_t);
99 static int vioblk_detach(dev_info_t *, ddi_detach_cmd_t);
100 
101 
102 static struct dev_ops vioblk_dev_ops = {
103 	.devo_rev =			DEVO_REV,
104 	.devo_refcnt =			0,
105 
106 	.devo_attach =			vioblk_attach,
107 	.devo_detach =			vioblk_detach,
108 	.devo_quiesce =			vioblk_quiesce,
109 
110 	.devo_getinfo =			ddi_no_info,
111 	.devo_identify =		nulldev,
112 	.devo_probe =			nulldev,
113 	.devo_reset =			nodev,
114 	.devo_cb_ops =			NULL,
115 	.devo_bus_ops =			NULL,
116 	.devo_power =			NULL,
117 };
118 
119 static struct modldrv vioblk_modldrv = {
120 	.drv_modops =			&mod_driverops,
121 	.drv_linkinfo =			"VIRTIO block driver",
122 	.drv_dev_ops =			&vioblk_dev_ops
123 };
124 
125 static struct modlinkage vioblk_modlinkage = {
126 	.ml_rev =			MODREV_1,
127 	.ml_linkage =			{ &vioblk_modldrv, NULL }
128 };
129 
130 /*
131  * DMA attribute template for header and status blocks.  We also make a
132  * per-instance copy of this template with negotiated sizes from the device for
133  * blkdev.
134  */
135 static const ddi_dma_attr_t vioblk_dma_attr = {
136 	.dma_attr_version =		DMA_ATTR_V0,
137 	.dma_attr_addr_lo =		0x0000000000000000,
138 	.dma_attr_addr_hi =		0xFFFFFFFFFFFFFFFF,
139 	.dma_attr_count_max =		0x00000000FFFFFFFF,
140 	.dma_attr_align =		1,
141 	.dma_attr_burstsizes =		1,
142 	.dma_attr_minxfer =		1,
143 	.dma_attr_maxxfer =		0x00000000FFFFFFFF,
144 	.dma_attr_seg =			0x00000000FFFFFFFF,
145 	.dma_attr_sgllen =		1,
146 	.dma_attr_granular =		1,
147 	.dma_attr_flags =		0
148 };
149 
150 
151 static vioblk_req_t *
152 vioblk_req_alloc(vioblk_t *vib)
153 {
154 	vioblk_req_t *vbr;
155 
156 	VERIFY(MUTEX_HELD(&vib->vib_mutex));
157 
158 	if ((vbr = list_remove_head(&vib->vib_reqs)) == NULL) {
159 		return (NULL);
160 	}
161 	vib->vib_nreqs_alloc++;
162 
163 	VERIFY0(vbr->vbr_status);
164 	vbr->vbr_status |= VIOBLK_REQSTAT_ALLOCATED;
165 
166 	VERIFY3P(vbr->vbr_xfer, ==, NULL);
167 	VERIFY3S(vbr->vbr_error, ==, 0);
168 
169 	return (vbr);
170 }
171 
172 static void
173 vioblk_req_free(vioblk_t *vib, vioblk_req_t *vbr)
174 {
175 	VERIFY(MUTEX_HELD(&vib->vib_mutex));
176 
177 	/*
178 	 * Check that this request was allocated, then zero the status field to
179 	 * clear all status bits.
180 	 */
181 	VERIFY(vbr->vbr_status & VIOBLK_REQSTAT_ALLOCATED);
182 	vbr->vbr_status = 0;
183 
184 	vbr->vbr_xfer = NULL;
185 	vbr->vbr_error = 0;
186 	vbr->vbr_type = 0;
187 
188 	list_insert_head(&vib->vib_reqs, vbr);
189 
190 	VERIFY3U(vib->vib_nreqs_alloc, >, 0);
191 	vib->vib_nreqs_alloc--;
192 }
193 
194 static void
195 vioblk_complete(vioblk_t *vib, vioblk_req_t *vbr)
196 {
197 	VERIFY(MUTEX_HELD(&vib->vib_mutex));
198 
199 	VERIFY(!(vbr->vbr_status & VIOBLK_REQSTAT_COMPLETE));
200 	vbr->vbr_status |= VIOBLK_REQSTAT_COMPLETE;
201 
202 	if (vbr->vbr_type == VIRTIO_BLK_T_FLUSH) {
203 		vib->vib_stats->vbs_rw_cacheflush.value.ui64++;
204 	}
205 
206 	if (vbr->vbr_xfer != NULL) {
207 		/*
208 		 * This is a blkdev framework request.
209 		 */
210 		mutex_exit(&vib->vib_mutex);
211 		bd_xfer_done(vbr->vbr_xfer, vbr->vbr_error);
212 		mutex_enter(&vib->vib_mutex);
213 		vbr->vbr_xfer = NULL;
214 	}
215 }
216 
217 static virtio_chain_t *
218 vioblk_common_start(vioblk_t *vib, int type, uint64_t sector,
219     boolean_t polled)
220 {
221 	vioblk_req_t *vbr = NULL;
222 	virtio_chain_t *vic = NULL;
223 
224 	if ((vbr = vioblk_req_alloc(vib)) == NULL) {
225 		vib->vib_stats->vbs_rw_outofmemory.value.ui64++;
226 		return (NULL);
227 	}
228 	vbr->vbr_type = type;
229 
230 	if (polled) {
231 		/*
232 		 * Mark this command as polled so that we can wait on it
233 		 * ourselves.
234 		 */
235 		vbr->vbr_status |= VIOBLK_REQSTAT_POLLED;
236 	}
237 
238 	if ((vic = virtio_chain_alloc(vib->vib_vq, KM_NOSLEEP)) == NULL) {
239 		vib->vib_stats->vbs_rw_outofmemory.value.ui64++;
240 		goto fail;
241 	}
242 
243 	struct vioblk_req_hdr vbh;
244 	vbh.vbh_type = type;
245 	vbh.vbh_ioprio = 0;
246 	vbh.vbh_sector = (sector * vib->vib_blk_size) / DEV_BSIZE;
247 	bcopy(&vbh, virtio_dma_va(vbr->vbr_dma, 0), sizeof (vbh));
248 
249 	virtio_chain_data_set(vic, vbr);
250 
251 	/*
252 	 * Put the header in the first descriptor.  See the block comment at
253 	 * the top of the file for more details on the chain layout.
254 	 */
255 	if (virtio_chain_append(vic, virtio_dma_cookie_pa(vbr->vbr_dma, 0),
256 	    sizeof (struct vioblk_req_hdr), VIRTIO_DIR_DEVICE_READS) !=
257 	    DDI_SUCCESS) {
258 		goto fail;
259 	}
260 
261 	return (vic);
262 
263 fail:
264 	vbr->vbr_xfer = NULL;
265 	vioblk_req_free(vib, vbr);
266 	if (vic != NULL) {
267 		virtio_chain_free(vic);
268 	}
269 	return (NULL);
270 }
271 
272 static int
273 vioblk_common_submit(vioblk_t *vib, virtio_chain_t *vic)
274 {
275 	int r;
276 	vioblk_req_t *vbr = virtio_chain_data(vic);
277 
278 	VERIFY(MUTEX_HELD(&vib->vib_mutex));
279 
280 	/*
281 	 * The device will write the status byte into this last descriptor.
282 	 * See the block comment at the top of the file for more details on the
283 	 * chain layout.
284 	 */
285 	if (virtio_chain_append(vic, virtio_dma_cookie_pa(vbr->vbr_dma, 0) +
286 	    sizeof (struct vioblk_req_hdr), sizeof (uint8_t),
287 	    VIRTIO_DIR_DEVICE_WRITES) != DDI_SUCCESS) {
288 		r = ENOMEM;
289 		goto out;
290 	}
291 
292 	virtio_dma_sync(vbr->vbr_dma, DDI_DMA_SYNC_FORDEV);
293 	virtio_chain_submit(vic, B_TRUE);
294 
295 	if (!(vbr->vbr_status & VIOBLK_REQSTAT_POLLED)) {
296 		/*
297 		 * This is not a polled request.  Our request will be freed and
298 		 * the caller notified later in vioblk_poll().
299 		 */
300 		return (0);
301 	}
302 
303 	/*
304 	 * This is a polled request.  We need to block here and wait for the
305 	 * device to complete request processing.
306 	 */
307 	while (!(vbr->vbr_status & VIOBLK_REQSTAT_POLL_COMPLETE)) {
308 		if (ddi_in_panic()) {
309 			/*
310 			 * When panicking, interrupts are disabled.  We must
311 			 * poll the queue manually.
312 			 */
313 			drv_usecwait(10);
314 			(void) vioblk_poll(vib);
315 			continue;
316 		}
317 
318 		/*
319 		 * When not panicking, the device will interrupt on command
320 		 * completion and vioblk_poll() will be called to wake us up.
321 		 */
322 		cv_wait(&vib->vib_cv, &vib->vib_mutex);
323 	}
324 
325 	vioblk_complete(vib, vbr);
326 	r = vbr->vbr_error;
327 
328 out:
329 	vioblk_req_free(vib, vbr);
330 	virtio_chain_free(vic);
331 	return (r);
332 }
333 
334 static int
335 vioblk_internal(vioblk_t *vib, int type, virtio_dma_t *dma,
336     uint64_t sector, virtio_direction_t dir)
337 {
338 	virtio_chain_t *vic;
339 	vioblk_req_t *vbr;
340 	int r;
341 
342 	VERIFY(MUTEX_HELD(&vib->vib_mutex));
343 
344 	/*
345 	 * Allocate a polled request.
346 	 */
347 	if ((vic = vioblk_common_start(vib, type, sector, B_TRUE)) == NULL) {
348 		return (ENOMEM);
349 	}
350 	vbr = virtio_chain_data(vic);
351 
352 	/*
353 	 * If there is a request payload, it goes between the header and the
354 	 * status byte.  See the block comment at the top of the file for more
355 	 * detail on the chain layout.
356 	 */
357 	if (dma != NULL) {
358 		for (uint_t n = 0; n < virtio_dma_ncookies(dma); n++) {
359 			if (virtio_chain_append(vic,
360 			    virtio_dma_cookie_pa(dma, n),
361 			    virtio_dma_cookie_size(dma, n), dir) !=
362 			    DDI_SUCCESS) {
363 				r = ENOMEM;
364 				goto out;
365 			}
366 		}
367 	}
368 
369 	return (vioblk_common_submit(vib, vic));
370 
371 out:
372 	vioblk_req_free(vib, vbr);
373 	virtio_chain_free(vic);
374 	return (r);
375 }
376 
377 static int
378 vioblk_request(vioblk_t *vib, bd_xfer_t *xfer, int type)
379 {
380 	virtio_chain_t *vic = NULL;
381 	vioblk_req_t *vbr = NULL;
382 	uint_t total_cookies = 2;
383 	boolean_t polled = (xfer->x_flags & BD_XFER_POLL) != 0;
384 	int r;
385 
386 	VERIFY(MUTEX_HELD(&vib->vib_mutex));
387 
388 	/*
389 	 * Ensure that this request falls within the advertised size of the
390 	 * block device.  Be careful to avoid overflow.
391 	 */
392 	if (xfer->x_nblks > SIZE_MAX - xfer->x_blkno ||
393 	    (xfer->x_blkno + xfer->x_nblks) > vib->vib_nblks) {
394 		vib->vib_stats->vbs_rw_badoffset.value.ui64++;
395 		return (EINVAL);
396 	}
397 
398 	if ((vic = vioblk_common_start(vib, type, xfer->x_blkno, polled)) ==
399 	    NULL) {
400 		return (ENOMEM);
401 	}
402 	vbr = virtio_chain_data(vic);
403 	vbr->vbr_xfer = xfer;
404 
405 	/*
406 	 * If there is a request payload, it goes between the header and the
407 	 * status byte.  See the block comment at the top of the file for more
408 	 * detail on the chain layout.
409 	 */
410 	if ((type == VIRTIO_BLK_T_IN || type == VIRTIO_BLK_T_OUT) &&
411 	    xfer->x_nblks > 0) {
412 		virtio_direction_t dir = (type == VIRTIO_BLK_T_OUT) ?
413 		    VIRTIO_DIR_DEVICE_READS : VIRTIO_DIR_DEVICE_WRITES;
414 
415 		for (uint_t n = 0; n < xfer->x_ndmac; n++) {
416 			ddi_dma_cookie_t dmac;
417 
418 			if (n == 0) {
419 				/*
420 				 * The first cookie is in the blkdev request.
421 				 */
422 				dmac = xfer->x_dmac;
423 			} else {
424 				ddi_dma_nextcookie(xfer->x_dmah, &dmac);
425 			}
426 
427 			if (virtio_chain_append(vic, dmac.dmac_laddress,
428 			    dmac.dmac_size, dir) != DDI_SUCCESS) {
429 				r = ENOMEM;
430 				goto fail;
431 			}
432 		}
433 
434 		total_cookies += xfer->x_ndmac;
435 
436 	} else if (xfer->x_nblks > 0) {
437 		dev_err(vib->vib_dip, CE_PANIC,
438 		    "request of type %d had payload length of %lu blocks", type,
439 		    xfer->x_nblks);
440 	}
441 
442 	if (vib->vib_stats->vbs_rw_cookiesmax.value.ui32 < total_cookies) {
443 		vib->vib_stats->vbs_rw_cookiesmax.value.ui32 = total_cookies;
444 	}
445 
446 	return (vioblk_common_submit(vib, vic));
447 
448 fail:
449 	vbr->vbr_xfer = NULL;
450 	vioblk_req_free(vib, vbr);
451 	virtio_chain_free(vic);
452 	return (r);
453 }
454 
455 static int
456 vioblk_bd_read(void *arg, bd_xfer_t *xfer)
457 {
458 	vioblk_t *vib = arg;
459 	int r;
460 
461 	mutex_enter(&vib->vib_mutex);
462 	r = vioblk_request(vib, xfer, VIRTIO_BLK_T_IN);
463 	mutex_exit(&vib->vib_mutex);
464 
465 	return (r);
466 }
467 
468 static int
469 vioblk_bd_write(void *arg, bd_xfer_t *xfer)
470 {
471 	vioblk_t *vib = arg;
472 	int r;
473 
474 	mutex_enter(&vib->vib_mutex);
475 	r = vioblk_request(vib, xfer, VIRTIO_BLK_T_OUT);
476 	mutex_exit(&vib->vib_mutex);
477 
478 	return (r);
479 }
480 
481 static int
482 vioblk_bd_flush(void *arg, bd_xfer_t *xfer)
483 {
484 	vioblk_t *vib = arg;
485 	int r;
486 
487 	mutex_enter(&vib->vib_mutex);
488 	if (!virtio_feature_present(vib->vib_virtio, VIRTIO_BLK_F_FLUSH)) {
489 		/*
490 		 * We don't really expect to get here, because if we did not
491 		 * negotiate the flush feature we would not have installed this
492 		 * function in the blkdev ops vector.
493 		 */
494 		mutex_exit(&vib->vib_mutex);
495 		return (ENOTSUP);
496 	}
497 
498 	r = vioblk_request(vib, xfer, VIRTIO_BLK_T_FLUSH);
499 	mutex_exit(&vib->vib_mutex);
500 
501 	return (r);
502 }
503 
504 static void
505 vioblk_bd_driveinfo(void *arg, bd_drive_t *drive)
506 {
507 	vioblk_t *vib = arg;
508 
509 	drive->d_qsize = vib->vib_reqs_capacity;
510 	drive->d_removable = B_FALSE;
511 	drive->d_hotpluggable = B_TRUE;
512 	drive->d_target = 0;
513 	drive->d_lun = 0;
514 
515 	drive->d_vendor = "Virtio";
516 	drive->d_vendor_len = strlen(drive->d_vendor);
517 
518 	drive->d_product = "Block Device";
519 	drive->d_product_len = strlen(drive->d_product);
520 
521 	drive->d_serial = vib->vib_devid;
522 	drive->d_serial_len = strlen(drive->d_serial);
523 
524 	drive->d_revision = "0000";
525 	drive->d_revision_len = strlen(drive->d_revision);
526 }
527 
528 static int
529 vioblk_bd_mediainfo(void *arg, bd_media_t *media)
530 {
531 	vioblk_t *vib = (void *)arg;
532 
533 	/*
534 	 * The device protocol is specified in terms of 512 byte logical
535 	 * blocks, regardless of the recommended I/O size which might be
536 	 * larger.
537 	 */
538 	media->m_nblks = vib->vib_nblks;
539 	media->m_blksize = vib->vib_blk_size;
540 
541 	media->m_readonly = vib->vib_readonly;
542 	media->m_pblksize = vib->vib_pblk_size;
543 	return (0);
544 }
545 
546 static void
547 vioblk_get_id(vioblk_t *vib)
548 {
549 	virtio_dma_t *dma;
550 	int r;
551 
552 	if ((dma = virtio_dma_alloc(vib->vib_virtio, VIRTIO_BLK_ID_BYTES,
553 	    &vioblk_dma_attr, DDI_DMA_CONSISTENT | DDI_DMA_READ,
554 	    KM_SLEEP)) == NULL) {
555 		return;
556 	}
557 
558 	mutex_enter(&vib->vib_mutex);
559 	if ((r = vioblk_internal(vib, VIRTIO_BLK_T_GET_ID, dma, 0,
560 	    VIRTIO_DIR_DEVICE_WRITES)) == 0) {
561 		const char *b = virtio_dma_va(dma, 0);
562 		uint_t pos = 0;
563 
564 		/*
565 		 * Save the entire response for debugging purposes.
566 		 */
567 		bcopy(virtio_dma_va(dma, 0), vib->vib_rawid,
568 		    VIRTIO_BLK_ID_BYTES);
569 
570 		/*
571 		 * Process the returned ID.
572 		 */
573 		bzero(vib->vib_devid, sizeof (vib->vib_devid));
574 		for (uint_t n = 0; n < VIRTIO_BLK_ID_BYTES; n++) {
575 			if (isalnum(b[n]) || b[n] == '-' || b[n] == '_') {
576 				/*
577 				 * Accept a subset of printable ASCII
578 				 * characters.
579 				 */
580 				vib->vib_devid[pos++] = b[n];
581 			} else {
582 				/*
583 				 * Stop processing at the first sign of
584 				 * trouble.
585 				 */
586 				break;
587 			}
588 		}
589 
590 		vib->vib_devid_fetched = B_TRUE;
591 	}
592 	mutex_exit(&vib->vib_mutex);
593 
594 	virtio_dma_free(dma);
595 }
596 
597 static int
598 vioblk_bd_devid(void *arg, dev_info_t *dip, ddi_devid_t *devid)
599 {
600 	vioblk_t *vib = arg;
601 	size_t len;
602 
603 	if ((len = strlen(vib->vib_devid)) == 0) {
604 		/*
605 		 * The device has no ID.
606 		 */
607 		return (DDI_FAILURE);
608 	}
609 
610 	return (ddi_devid_init(dip, DEVID_ATA_SERIAL, len, vib->vib_devid,
611 	    devid));
612 }
613 
614 /*
615  * As the device completes processing of a request, it returns the chain for
616  * that request to our I/O queue.  This routine is called in two contexts:
617  *   - from the interrupt handler, in response to notification from the device
618  *   - synchronously in line with request processing when panicking
619  */
620 static uint_t
621 vioblk_poll(vioblk_t *vib)
622 {
623 	virtio_chain_t *vic;
624 	uint_t count = 0;
625 	boolean_t wakeup = B_FALSE;
626 
627 	VERIFY(MUTEX_HELD(&vib->vib_mutex));
628 
629 	while ((vic = virtio_queue_poll(vib->vib_vq)) != NULL) {
630 		vioblk_req_t *vbr = virtio_chain_data(vic);
631 		uint8_t status;
632 
633 		virtio_dma_sync(vbr->vbr_dma, DDI_DMA_SYNC_FORCPU);
634 
635 		bcopy(virtio_dma_va(vbr->vbr_dma,
636 		    sizeof (struct vioblk_req_hdr)), &status, sizeof (status));
637 
638 		switch (status) {
639 		case VIRTIO_BLK_S_OK:
640 			vbr->vbr_error = 0;
641 			break;
642 		case VIRTIO_BLK_S_IOERR:
643 			vbr->vbr_error = EIO;
644 			vib->vib_stats->vbs_io_errors.value.ui64++;
645 			break;
646 		case VIRTIO_BLK_S_UNSUPP:
647 			vbr->vbr_error = ENOTTY;
648 			vib->vib_stats->vbs_unsupp_errors.value.ui64++;
649 			break;
650 		default:
651 			vbr->vbr_error = ENXIO;
652 			vib->vib_stats->vbs_nxio_errors.value.ui64++;
653 			break;
654 		}
655 
656 		count++;
657 
658 		if (vbr->vbr_status & VIOBLK_REQSTAT_POLLED) {
659 			/*
660 			 * This request must not be freed as it is being held
661 			 * by a call to vioblk_common_submit().
662 			 */
663 			VERIFY(!(vbr->vbr_status &
664 			    VIOBLK_REQSTAT_POLL_COMPLETE));
665 			vbr->vbr_status |= VIOBLK_REQSTAT_POLL_COMPLETE;
666 			wakeup = B_TRUE;
667 			continue;
668 		}
669 
670 		vioblk_complete(vib, vbr);
671 
672 		vioblk_req_free(vib, vbr);
673 		virtio_chain_free(vic);
674 	}
675 
676 	if (wakeup) {
677 		/*
678 		 * Signal anybody waiting for polled command completion.
679 		 */
680 		cv_broadcast(&vib->vib_cv);
681 	}
682 
683 	return (count);
684 }
685 
686 uint_t
687 vioblk_int_handler(caddr_t arg0, caddr_t arg1)
688 {
689 	vioblk_t *vib = (vioblk_t *)arg0;
690 	uint_t count;
691 
692 	mutex_enter(&vib->vib_mutex);
693 	if ((count = vioblk_poll(vib)) >
694 	    vib->vib_stats->vbs_intr_queuemax.value.ui32) {
695 		vib->vib_stats->vbs_intr_queuemax.value.ui32 = count;
696 	}
697 
698 	vib->vib_stats->vbs_intr_total.value.ui64++;
699 	mutex_exit(&vib->vib_mutex);
700 
701 	return (DDI_INTR_CLAIMED);
702 }
703 
704 static void
705 vioblk_free_reqs(vioblk_t *vib)
706 {
707 	VERIFY3U(vib->vib_nreqs_alloc, ==, 0);
708 
709 	for (uint_t i = 0; i < vib->vib_reqs_capacity; i++) {
710 		struct vioblk_req *vbr = &vib->vib_reqs_mem[i];
711 
712 		VERIFY(list_link_active(&vbr->vbr_link));
713 		list_remove(&vib->vib_reqs, vbr);
714 
715 		VERIFY0(vbr->vbr_status);
716 
717 		if (vbr->vbr_dma != NULL) {
718 			virtio_dma_free(vbr->vbr_dma);
719 			vbr->vbr_dma = NULL;
720 		}
721 	}
722 	VERIFY(list_is_empty(&vib->vib_reqs));
723 
724 	if (vib->vib_reqs_mem != NULL) {
725 		kmem_free(vib->vib_reqs_mem,
726 		    sizeof (struct vioblk_req) * vib->vib_reqs_capacity);
727 		vib->vib_reqs_mem = NULL;
728 		vib->vib_reqs_capacity = 0;
729 	}
730 }
731 
732 static int
733 vioblk_alloc_reqs(vioblk_t *vib)
734 {
735 	vib->vib_reqs_capacity = MIN(virtio_queue_size(vib->vib_vq),
736 	    VIRTIO_BLK_REQ_BUFS);
737 	vib->vib_reqs_mem = kmem_zalloc(
738 	    sizeof (struct vioblk_req) * vib->vib_reqs_capacity, KM_SLEEP);
739 	vib->vib_nreqs_alloc = 0;
740 
741 	for (uint_t i = 0; i < vib->vib_reqs_capacity; i++) {
742 		list_insert_tail(&vib->vib_reqs, &vib->vib_reqs_mem[i]);
743 	}
744 
745 	for (vioblk_req_t *vbr = list_head(&vib->vib_reqs); vbr != NULL;
746 	    vbr = list_next(&vib->vib_reqs, vbr)) {
747 		if ((vbr->vbr_dma = virtio_dma_alloc(vib->vib_virtio,
748 		    sizeof (struct vioblk_req_hdr) + sizeof (uint8_t),
749 		    &vioblk_dma_attr, DDI_DMA_RDWR | DDI_DMA_CONSISTENT,
750 		    KM_SLEEP)) == NULL) {
751 			goto fail;
752 		}
753 	}
754 
755 	return (0);
756 
757 fail:
758 	vioblk_free_reqs(vib);
759 	return (ENOMEM);
760 }
761 
762 static int
763 vioblk_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
764 {
765 	int instance = ddi_get_instance(dip);
766 	vioblk_t *vib;
767 	virtio_t *vio;
768 	boolean_t did_mutex = B_FALSE;
769 
770 	if (cmd != DDI_ATTACH) {
771 		return (DDI_FAILURE);
772 	}
773 
774 	if ((vio = virtio_init(dip, VIRTIO_BLK_WANTED_FEATURES, B_TRUE)) ==
775 	    NULL) {
776 		dev_err(dip, CE_WARN, "failed to start Virtio init");
777 		return (DDI_FAILURE);
778 	}
779 
780 	vib = kmem_zalloc(sizeof (*vib), KM_SLEEP);
781 	vib->vib_dip = dip;
782 	vib->vib_virtio = vio;
783 	ddi_set_driver_private(dip, vib);
784 	list_create(&vib->vib_reqs, sizeof (vioblk_req_t),
785 	    offsetof(vioblk_req_t, vbr_link));
786 
787 	/*
788 	 * Determine how many scatter-gather entries we can use in a single
789 	 * request.
790 	 */
791 	vib->vib_seg_max = VIRTIO_BLK_DEFAULT_MAX_SEG;
792 	if (virtio_feature_present(vio, VIRTIO_BLK_F_SEG_MAX)) {
793 		vib->vib_seg_max = virtio_dev_get32(vio,
794 		    VIRTIO_BLK_CONFIG_SEG_MAX);
795 
796 		if (vib->vib_seg_max == 0 || vib->vib_seg_max == PCI_EINVAL32) {
797 			/*
798 			 * We need to be able to use at least one data segment,
799 			 * so we'll assume that this device is just poorly
800 			 * implemented and try for one.
801 			 */
802 			vib->vib_seg_max = 1;
803 		}
804 	}
805 
806 	/*
807 	 * When allocating the request queue, we include two additional
808 	 * descriptors (beyond those required for request data) to account for
809 	 * the header and the status byte.
810 	 */
811 	if ((vib->vib_vq = virtio_queue_alloc(vio, VIRTIO_BLK_VIRTQ_IO, "io",
812 	    vioblk_int_handler, vib, B_FALSE, vib->vib_seg_max + 2)) == NULL) {
813 		goto fail;
814 	}
815 
816 	if (virtio_init_complete(vio, 0) != DDI_SUCCESS) {
817 		dev_err(dip, CE_WARN, "failed to complete Virtio init");
818 		goto fail;
819 	}
820 
821 	cv_init(&vib->vib_cv, NULL, CV_DRIVER, NULL);
822 	mutex_init(&vib->vib_mutex, NULL, MUTEX_DRIVER, virtio_intr_pri(vio));
823 	did_mutex = B_TRUE;
824 
825 	if ((vib->vib_kstat = kstat_create("vioblk", instance,
826 	    "statistics", "controller", KSTAT_TYPE_NAMED,
827 	    sizeof (struct vioblk_stats) / sizeof (kstat_named_t),
828 	    KSTAT_FLAG_PERSISTENT)) == NULL) {
829 		dev_err(dip, CE_WARN, "kstat_create failed");
830 		goto fail;
831 	}
832 	vib->vib_stats = (vioblk_stats_t *)vib->vib_kstat->ks_data;
833 	kstat_named_init(&vib->vib_stats->vbs_rw_outofmemory,
834 	    "total_rw_outofmemory", KSTAT_DATA_UINT64);
835 	kstat_named_init(&vib->vib_stats->vbs_rw_badoffset,
836 	    "total_rw_badoffset", KSTAT_DATA_UINT64);
837 	kstat_named_init(&vib->vib_stats->vbs_intr_total,
838 	    "total_intr", KSTAT_DATA_UINT64);
839 	kstat_named_init(&vib->vib_stats->vbs_io_errors,
840 	    "total_io_errors", KSTAT_DATA_UINT64);
841 	kstat_named_init(&vib->vib_stats->vbs_unsupp_errors,
842 	    "total_unsupp_errors", KSTAT_DATA_UINT64);
843 	kstat_named_init(&vib->vib_stats->vbs_nxio_errors,
844 	    "total_nxio_errors", KSTAT_DATA_UINT64);
845 	kstat_named_init(&vib->vib_stats->vbs_rw_cacheflush,
846 	    "total_rw_cacheflush", KSTAT_DATA_UINT64);
847 	kstat_named_init(&vib->vib_stats->vbs_rw_cookiesmax,
848 	    "max_rw_cookies", KSTAT_DATA_UINT32);
849 	kstat_named_init(&vib->vib_stats->vbs_intr_queuemax,
850 	    "max_intr_queue", KSTAT_DATA_UINT32);
851 	kstat_install(vib->vib_kstat);
852 
853 	vib->vib_readonly = virtio_feature_present(vio, VIRTIO_BLK_F_RO);
854 	if ((vib->vib_nblks = virtio_dev_get64(vio,
855 	    VIRTIO_BLK_CONFIG_CAPACITY)) == UINT64_MAX) {
856 		dev_err(dip, CE_WARN, "invalid capacity");
857 		goto fail;
858 	}
859 
860 	/*
861 	 * Determine the optimal logical block size recommended by the device.
862 	 * This size is advisory; the protocol always deals in 512 byte blocks.
863 	 */
864 	vib->vib_blk_size = DEV_BSIZE;
865 	if (virtio_feature_present(vio, VIRTIO_BLK_F_BLK_SIZE)) {
866 		uint32_t v = virtio_dev_get32(vio, VIRTIO_BLK_CONFIG_BLK_SIZE);
867 
868 		if (v != 0 && v != PCI_EINVAL32) {
869 			vib->vib_blk_size = v;
870 		}
871 	}
872 
873 	/*
874 	 * Device capacity is always in 512-byte units, convert to
875 	 * native blocks.
876 	 */
877 	vib->vib_nblks = (vib->vib_nblks * DEV_BSIZE) / vib->vib_blk_size;
878 
879 	/*
880 	 * The device may also provide an advisory physical block size.
881 	 */
882 	vib->vib_pblk_size = vib->vib_blk_size;
883 	if (virtio_feature_present(vio, VIRTIO_BLK_F_TOPOLOGY)) {
884 		uint8_t v = virtio_dev_get8(vio, VIRTIO_BLK_CONFIG_TOPO_PBEXP);
885 
886 		if (v != PCI_EINVAL8) {
887 			vib->vib_pblk_size <<= v;
888 		}
889 	}
890 
891 	/*
892 	 * The maximum size for a cookie in a request.
893 	 */
894 	vib->vib_seg_size_max = VIRTIO_BLK_DEFAULT_MAX_SIZE;
895 	if (virtio_feature_present(vio, VIRTIO_BLK_F_SIZE_MAX)) {
896 		uint32_t v = virtio_dev_get32(vio, VIRTIO_BLK_CONFIG_SIZE_MAX);
897 
898 		if (v != 0 && v != PCI_EINVAL32) {
899 			vib->vib_seg_size_max = v;
900 		}
901 	}
902 
903 	/*
904 	 * Set up the DMA attributes for blkdev to use for request data.  The
905 	 * specification is not extremely clear about whether DMA-related
906 	 * parameters include or exclude the header and status descriptors.
907 	 * For now, we assume they cover only the request data and not the
908 	 * headers.
909 	 */
910 	vib->vib_bd_dma_attr = vioblk_dma_attr;
911 	vib->vib_bd_dma_attr.dma_attr_sgllen = vib->vib_seg_max;
912 	vib->vib_bd_dma_attr.dma_attr_count_max = vib->vib_seg_size_max;
913 	vib->vib_bd_dma_attr.dma_attr_maxxfer = vib->vib_seg_max *
914 	    vib->vib_seg_size_max;
915 
916 	if (vioblk_alloc_reqs(vib) != 0) {
917 		goto fail;
918 	}
919 
920 	/*
921 	 * The blkdev framework does not provide a way to specify that the
922 	 * device does not support write cache flushing, except by omitting the
923 	 * "o_sync_cache" member from the ops vector.  As "bd_alloc_handle()"
924 	 * makes a copy of the ops vector, we can safely assemble one on the
925 	 * stack based on negotiated features.
926 	 */
927 	bd_ops_t vioblk_bd_ops = {
928 		.o_version =		BD_OPS_VERSION_0,
929 		.o_drive_info =		vioblk_bd_driveinfo,
930 		.o_media_info =		vioblk_bd_mediainfo,
931 		.o_devid_init =		vioblk_bd_devid,
932 		.o_sync_cache =		vioblk_bd_flush,
933 		.o_read =		vioblk_bd_read,
934 		.o_write =		vioblk_bd_write,
935 	};
936 	if (!virtio_feature_present(vio, VIRTIO_BLK_F_FLUSH)) {
937 		vioblk_bd_ops.o_sync_cache = NULL;
938 	}
939 
940 	vib->vib_bd_h = bd_alloc_handle(vib, &vioblk_bd_ops,
941 	    &vib->vib_bd_dma_attr, KM_SLEEP);
942 
943 	/*
944 	 * Enable interrupts now so that we can request the device identity.
945 	 */
946 	if (virtio_interrupts_enable(vio) != DDI_SUCCESS) {
947 		goto fail;
948 	}
949 
950 	vioblk_get_id(vib);
951 
952 	if (bd_attach_handle(dip, vib->vib_bd_h) != DDI_SUCCESS) {
953 		dev_err(dip, CE_WARN, "Failed to attach blkdev");
954 		goto fail;
955 	}
956 
957 	return (DDI_SUCCESS);
958 
959 fail:
960 	if (vib->vib_bd_h != NULL) {
961 		(void) bd_detach_handle(vib->vib_bd_h);
962 		bd_free_handle(vib->vib_bd_h);
963 	}
964 	if (vio != NULL) {
965 		(void) virtio_fini(vio, B_TRUE);
966 	}
967 	if (did_mutex) {
968 		mutex_destroy(&vib->vib_mutex);
969 		cv_destroy(&vib->vib_cv);
970 	}
971 	if (vib->vib_kstat != NULL) {
972 		kstat_delete(vib->vib_kstat);
973 	}
974 	vioblk_free_reqs(vib);
975 	kmem_free(vib, sizeof (*vib));
976 	return (DDI_FAILURE);
977 }
978 
979 static int
980 vioblk_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
981 {
982 	vioblk_t *vib = ddi_get_driver_private(dip);
983 
984 	if (cmd != DDI_DETACH) {
985 		return (DDI_FAILURE);
986 	}
987 
988 	mutex_enter(&vib->vib_mutex);
989 	if (vib->vib_nreqs_alloc > 0) {
990 		/*
991 		 * Cannot detach while there are still outstanding requests.
992 		 */
993 		mutex_exit(&vib->vib_mutex);
994 		return (DDI_FAILURE);
995 	}
996 
997 	if (bd_detach_handle(vib->vib_bd_h) != DDI_SUCCESS) {
998 		mutex_exit(&vib->vib_mutex);
999 		return (DDI_FAILURE);
1000 	}
1001 
1002 	/*
1003 	 * Tear down the Virtio framework before freeing the rest of the
1004 	 * resources.  This will ensure the interrupt handlers are no longer
1005 	 * running.
1006 	 */
1007 	virtio_fini(vib->vib_virtio, B_FALSE);
1008 
1009 	vioblk_free_reqs(vib);
1010 	kstat_delete(vib->vib_kstat);
1011 
1012 	mutex_exit(&vib->vib_mutex);
1013 	mutex_destroy(&vib->vib_mutex);
1014 
1015 	kmem_free(vib, sizeof (*vib));
1016 
1017 	return (DDI_SUCCESS);
1018 }
1019 
1020 static int
1021 vioblk_quiesce(dev_info_t *dip)
1022 {
1023 	vioblk_t *vib;
1024 
1025 	if ((vib = ddi_get_driver_private(dip)) == NULL) {
1026 		return (DDI_FAILURE);
1027 	}
1028 
1029 	return (virtio_quiesce(vib->vib_virtio));
1030 }
1031 
1032 int
1033 _init(void)
1034 {
1035 	int rv;
1036 
1037 	bd_mod_init(&vioblk_dev_ops);
1038 
1039 	if ((rv = mod_install(&vioblk_modlinkage)) != 0) {
1040 		bd_mod_fini(&vioblk_dev_ops);
1041 	}
1042 
1043 	return (rv);
1044 }
1045 
1046 int
1047 _fini(void)
1048 {
1049 	int rv;
1050 
1051 	if ((rv = mod_remove(&vioblk_modlinkage)) == 0) {
1052 		bd_mod_fini(&vioblk_dev_ops);
1053 	}
1054 
1055 	return (rv);
1056 }
1057 
1058 int
1059 _info(struct modinfo *modinfop)
1060 {
1061 	return (mod_info(&vioblk_modlinkage, modinfop));
1062 }
1063