xref: /illumos-gate/usr/src/uts/common/io/blkdev/blkdev.c (revision d17be682a2c70b4505d43c830bbd2603da11918d)
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  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2012 Garrett D'Amore <garrett@damore.org>.  All rights reserved.
24  * Copyright 2012 Alexey Zaytsev <alexey.zaytsev@gmail.com> All rights reserved.
25  * Copyright 2017 The MathWorks, Inc.  All rights reserved.
26  * Copyright 2020 Joyent, Inc.
27  * Copyright 2022 OmniOS Community Edition (OmniOSce) Association.
28  * Copyright 2022 Tintri by DDN, Inc. All rights reserved.
29  * Copyright 2023 Oxide Computer Company
30  */
31 
32 #include <sys/types.h>
33 #include <sys/ksynch.h>
34 #include <sys/kmem.h>
35 #include <sys/file.h>
36 #include <sys/errno.h>
37 #include <sys/open.h>
38 #include <sys/buf.h>
39 #include <sys/uio.h>
40 #include <sys/aio_req.h>
41 #include <sys/cred.h>
42 #include <sys/modctl.h>
43 #include <sys/cmlb.h>
44 #include <sys/conf.h>
45 #include <sys/devops.h>
46 #include <sys/list.h>
47 #include <sys/sysmacros.h>
48 #include <sys/dkio.h>
49 #include <sys/dkioc_free_util.h>
50 #include <sys/vtoc.h>
51 #include <sys/scsi/scsi.h>	/* for DTYPE_DIRECT */
52 #include <sys/kstat.h>
53 #include <sys/fs/dv_node.h>
54 #include <sys/ddi.h>
55 #include <sys/sunddi.h>
56 #include <sys/note.h>
57 #include <sys/blkdev.h>
58 #include <sys/scsi/impl/inquiry.h>
59 #include <sys/taskq.h>
60 #include <sys/taskq_impl.h>
61 #include <sys/disp.h>
62 #include <sys/sysevent/eventdefs.h>
63 #include <sys/sysevent/dev.h>
64 
65 /*
66  * blkdev is a driver which provides a lot of the common functionality
67  * a block device driver may need and helps by removing code which
68  * is frequently duplicated in block device drivers.
69  *
70  * Within this driver all the struct cb_ops functions required for a
71  * block device driver are written with appropriate call back functions
72  * to be provided by the parent driver.
73  *
74  * To use blkdev, a driver needs to:
75  *	1. Create a bd_ops_t structure which has the call back operations
76  *	   blkdev will use.
77  *	2. Create a handle by calling bd_alloc_handle(). One of the
78  *	   arguments to this function is the bd_ops_t.
79  *	3. Call bd_attach_handle(). This will instantiate a blkdev device
80  *	   as a child device node of the calling driver.
81  *
82  * A parent driver is not restricted to just allocating and attaching a
83  * single instance, it may attach as many as it wishes. For each handle
84  * attached, appropriate entries in /dev/[r]dsk are created.
85  *
86  * The bd_ops_t routines that a parent of blkdev need to provide are:
87  *
88  * o_drive_info: Provide information to blkdev such as how many I/O queues
89  *		 to create and the size of those queues. Also some device
90  *		 specifics such as EUI, vendor, product, model, serial
91  *		 number ....
92  *
93  * o_media_info: Provide information about the media. Eg size and block size.
94  *
95  * o_devid_init: Creates and initializes the device id. Typically calls
96  *		 ddi_devid_init().
97  *
98  * o_sync_cache: Issues a device appropriate command to flush any write
99  *		 caches.
100  *
101  * o_read:	 Read data as described by bd_xfer_t argument.
102  *
103  * o_write:	 Write data as described by bd_xfer_t argument.
104  *
105  * o_free_space: Free the space described by bd_xfer_t argument (optional).
106  *
107  * Queues
108  * ------
109  * Part of the drive_info data is a queue count. blkdev will create
110  * "queue count" number of waitq/runq pairs. Each waitq/runq pair
111  * operates independently. As an I/O is scheduled up to the parent
112  * driver via o_read or o_write its queue number is given. If the
113  * parent driver supports multiple hardware queues it can then select
114  * where to submit the I/O request.
115  *
116  * Currently blkdev uses a simplistic round-robin queue selection method.
117  * It has the advantage that it is lockless. In the future it will be
118  * worthwhile reviewing this strategy for something which prioritizes queues
119  * depending on how busy they are.
120  *
121  * Each waitq/runq pair is protected by its mutex (q_iomutex). Incoming
122  * I/O requests are initially added to the waitq. They are taken off the
123  * waitq, added to the runq and submitted, providing the runq is less
124  * than the qsize as specified in the drive_info. As an I/O request
125  * completes, the parent driver is required to call bd_xfer_done(), which
126  * will remove the I/O request from the runq and pass I/O completion
127  * status up the stack.
128  *
129  * Locks
130  * -----
131  * There are 5 instance global locks d_ocmutex, d_ksmutex, d_errmutex,
132  * d_statemutex and d_dle_mutex. As well a q_iomutex per waitq/runq pair.
133  *
134  * Lock Hierarchy
135  * --------------
136  * The only two locks which may be held simultaneously are q_iomutex and
137  * d_ksmutex. In all cases q_iomutex must be acquired before d_ksmutex.
138  */
139 
140 #define	BD_MAXPART	64
141 #define	BDINST(dev)	(getminor(dev) / BD_MAXPART)
142 #define	BDPART(dev)	(getminor(dev) % BD_MAXPART)
143 
144 typedef struct bd bd_t;
145 typedef struct bd_xfer_impl bd_xfer_impl_t;
146 typedef struct bd_queue bd_queue_t;
147 
148 typedef enum {
149 	BD_DLE_PENDING	= 1 << 0,
150 	BD_DLE_RUNNING	= 1 << 1
151 } bd_dle_state_t;
152 
153 struct bd {
154 	void		*d_private;
155 	dev_info_t	*d_dip;
156 	kmutex_t	d_ocmutex;	/* open/close */
157 	kmutex_t	d_ksmutex;	/* kstat */
158 	kmutex_t	d_errmutex;
159 	kmutex_t	d_statemutex;
160 	kcondvar_t	d_statecv;
161 	enum dkio_state	d_state;
162 	cmlb_handle_t	d_cmlbh;
163 	unsigned	d_open_lyr[BD_MAXPART];	/* open count */
164 	uint64_t	d_open_excl;	/* bit mask indexed by partition */
165 	uint64_t	d_open_reg[OTYPCNT];		/* bit mask */
166 	uint64_t	d_io_counter;
167 
168 	uint32_t	d_qcount;
169 	uint32_t	d_qactive;
170 	uint32_t	d_maxxfer;
171 	uint32_t	d_blkshift;
172 	uint32_t	d_pblkshift;
173 	uint64_t	d_numblks;
174 	ddi_devid_t	d_devid;
175 
176 	uint64_t	d_max_free_seg;
177 	uint64_t	d_max_free_blks;
178 	uint64_t	d_max_free_seg_blks;
179 	uint64_t	d_free_align;
180 
181 	kmem_cache_t	*d_cache;
182 	bd_queue_t	*d_queues;
183 	kstat_t		*d_ksp;
184 	kstat_io_t	*d_kiop;
185 	kstat_t		*d_errstats;
186 	struct bd_errstats *d_kerr;
187 
188 	boolean_t	d_rdonly;
189 	boolean_t	d_ssd;
190 	boolean_t	d_removable;
191 	boolean_t	d_hotpluggable;
192 	boolean_t	d_use_dma;
193 
194 	ddi_dma_attr_t	d_dma;
195 	bd_ops_t	d_ops;
196 	bd_handle_t	d_handle;
197 
198 	kmutex_t	d_dle_mutex;
199 	taskq_ent_t	d_dle_ent;
200 	bd_dle_state_t	d_dle_state;
201 };
202 
203 struct bd_handle {
204 	bd_ops_t	h_ops;
205 	ddi_dma_attr_t	*h_dma;
206 	dev_info_t	*h_parent;
207 	dev_info_t	*h_child;
208 	void		*h_private;
209 	bd_t		*h_bd;
210 	char		*h_name;
211 	char		h_addr[50];	/* enough for w%0.32x,%X */
212 };
213 
214 struct bd_xfer_impl {
215 	bd_xfer_t	i_public;
216 	list_node_t	i_linkage;
217 	bd_t		*i_bd;
218 	buf_t		*i_bp;
219 	bd_queue_t	*i_bq;
220 	uint_t		i_num_win;
221 	uint_t		i_cur_win;
222 	off_t		i_offset;
223 	int		(*i_func)(void *, bd_xfer_t *);
224 	uint32_t	i_blkshift;
225 	size_t		i_len;
226 	size_t		i_resid;
227 };
228 
229 struct bd_queue {
230 	kmutex_t	q_iomutex;
231 	uint32_t	q_qsize;
232 	uint32_t	q_qactive;
233 	list_t		q_runq;
234 	list_t		q_waitq;
235 };
236 
237 #define	i_dmah		i_public.x_dmah
238 #define	i_dmac		i_public.x_dmac
239 #define	i_ndmac		i_public.x_ndmac
240 #define	i_kaddr		i_public.x_kaddr
241 #define	i_nblks		i_public.x_nblks
242 #define	i_blkno		i_public.x_blkno
243 #define	i_flags		i_public.x_flags
244 #define	i_qnum		i_public.x_qnum
245 #define	i_dfl		i_public.x_dfl
246 
247 #define	CAN_FREESPACE(bd) \
248 	(((bd)->d_ops.o_free_space == NULL) ? B_FALSE : B_TRUE)
249 
250 /*
251  * Private prototypes.
252  */
253 
254 static void bd_prop_update_inqstring(dev_info_t *, char *, char *, size_t);
255 static void bd_create_inquiry_props(dev_info_t *, bd_drive_t *);
256 static void bd_create_errstats(bd_t *, int, bd_drive_t *);
257 static void bd_destroy_errstats(bd_t *);
258 static void bd_errstats_setstr(kstat_named_t *, char *, size_t, char *);
259 static void bd_init_errstats(bd_t *, bd_drive_t *);
260 static void bd_fini_errstats(bd_t *);
261 
262 static int bd_getinfo(dev_info_t *, ddi_info_cmd_t, void *, void **);
263 static int bd_attach(dev_info_t *, ddi_attach_cmd_t);
264 static int bd_detach(dev_info_t *, ddi_detach_cmd_t);
265 
266 static int bd_open(dev_t *, int, int, cred_t *);
267 static int bd_close(dev_t, int, int, cred_t *);
268 static int bd_strategy(struct buf *);
269 static int bd_ioctl(dev_t, int, intptr_t, int, cred_t *, int *);
270 static int bd_dump(dev_t, caddr_t, daddr_t, int);
271 static int bd_read(dev_t, struct uio *, cred_t *);
272 static int bd_write(dev_t, struct uio *, cred_t *);
273 static int bd_aread(dev_t, struct aio_req *, cred_t *);
274 static int bd_awrite(dev_t, struct aio_req *, cred_t *);
275 static int bd_prop_op(dev_t, dev_info_t *, ddi_prop_op_t, int, char *,
276     caddr_t, int *);
277 
278 static int bd_tg_rdwr(dev_info_t *, uchar_t, void *, diskaddr_t, size_t,
279     void *);
280 static int bd_tg_getinfo(dev_info_t *, int, void *, void *);
281 static int bd_xfer_ctor(void *, void *, int);
282 static void bd_xfer_dtor(void *, void *);
283 static void bd_sched(bd_t *, bd_queue_t *);
284 static void bd_submit(bd_t *, bd_xfer_impl_t *);
285 static void bd_runq_exit(bd_xfer_impl_t *, int);
286 static void bd_update_state(bd_t *);
287 static int bd_check_state(bd_t *, enum dkio_state *);
288 static int bd_flush_write_cache(bd_t *, struct dk_callback *);
289 static int bd_check_uio(dev_t, struct uio *);
290 static int bd_free_space(dev_t, bd_t *, dkioc_free_list_t *);
291 
292 struct cmlb_tg_ops bd_tg_ops = {
293 	TG_DK_OPS_VERSION_1,
294 	bd_tg_rdwr,
295 	bd_tg_getinfo,
296 };
297 
298 static struct cb_ops bd_cb_ops = {
299 	bd_open,		/* open */
300 	bd_close,		/* close */
301 	bd_strategy,		/* strategy */
302 	nodev,			/* print */
303 	bd_dump,		/* dump */
304 	bd_read,		/* read */
305 	bd_write,		/* write */
306 	bd_ioctl,		/* ioctl */
307 	nodev,			/* devmap */
308 	nodev,			/* mmap */
309 	nodev,			/* segmap */
310 	nochpoll,		/* poll */
311 	bd_prop_op,		/* cb_prop_op */
312 	0,			/* streamtab  */
313 	D_64BIT | D_MP,		/* Driver comaptibility flag */
314 	CB_REV,			/* cb_rev */
315 	bd_aread,		/* async read */
316 	bd_awrite		/* async write */
317 };
318 
319 struct dev_ops bd_dev_ops = {
320 	DEVO_REV,		/* devo_rev, */
321 	0,			/* refcnt  */
322 	bd_getinfo,		/* getinfo */
323 	nulldev,		/* identify */
324 	nulldev,		/* probe */
325 	bd_attach,		/* attach */
326 	bd_detach,		/* detach */
327 	nodev,			/* reset */
328 	&bd_cb_ops,		/* driver operations */
329 	NULL,			/* bus operations */
330 	NULL,			/* power */
331 	ddi_quiesce_not_needed,	/* quiesce */
332 };
333 
334 static struct modldrv modldrv = {
335 	&mod_driverops,
336 	"Generic Block Device",
337 	&bd_dev_ops,
338 };
339 
340 static struct modlinkage modlinkage = {
341 	MODREV_1, { &modldrv, NULL }
342 };
343 
344 static void *bd_state;
345 static krwlock_t bd_lock;
346 static taskq_t *bd_taskq;
347 
348 int
349 _init(void)
350 {
351 	char taskq_name[TASKQ_NAMELEN];
352 	const char *name;
353 	int rv;
354 
355 	rv = ddi_soft_state_init(&bd_state, sizeof (struct bd), 2);
356 	if (rv != DDI_SUCCESS)
357 		return (rv);
358 
359 	name = mod_modname(&modlinkage);
360 	(void) snprintf(taskq_name, sizeof (taskq_name), "%s_taskq", name);
361 	bd_taskq = taskq_create(taskq_name, 1, minclsyspri, 0, 0, 0);
362 	if (bd_taskq == NULL) {
363 		cmn_err(CE_WARN, "%s: unable to create %s", name, taskq_name);
364 		ddi_soft_state_fini(&bd_state);
365 		return (DDI_FAILURE);
366 	}
367 
368 	rw_init(&bd_lock, NULL, RW_DRIVER, NULL);
369 
370 	rv = mod_install(&modlinkage);
371 	if (rv != DDI_SUCCESS) {
372 		rw_destroy(&bd_lock);
373 		taskq_destroy(bd_taskq);
374 		ddi_soft_state_fini(&bd_state);
375 	}
376 	return (rv);
377 }
378 
379 int
380 _fini(void)
381 {
382 	int	rv;
383 
384 	rv = mod_remove(&modlinkage);
385 	if (rv == DDI_SUCCESS) {
386 		rw_destroy(&bd_lock);
387 		taskq_destroy(bd_taskq);
388 		ddi_soft_state_fini(&bd_state);
389 	}
390 	return (rv);
391 }
392 
393 int
394 _info(struct modinfo *modinfop)
395 {
396 	return (mod_info(&modlinkage, modinfop));
397 }
398 
399 static int
400 bd_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg, void **resultp)
401 {
402 	bd_t	*bd;
403 	minor_t	inst;
404 
405 	_NOTE(ARGUNUSED(dip));
406 
407 	inst = BDINST((dev_t)arg);
408 
409 	switch (cmd) {
410 	case DDI_INFO_DEVT2DEVINFO:
411 		bd = ddi_get_soft_state(bd_state, inst);
412 		if (bd == NULL) {
413 			return (DDI_FAILURE);
414 		}
415 		*resultp = (void *)bd->d_dip;
416 		break;
417 
418 	case DDI_INFO_DEVT2INSTANCE:
419 		*resultp = (void *)(intptr_t)inst;
420 		break;
421 
422 	default:
423 		return (DDI_FAILURE);
424 	}
425 	return (DDI_SUCCESS);
426 }
427 
428 static void
429 bd_prop_update_inqstring(dev_info_t *dip, char *name, char *data, size_t len)
430 {
431 	int	ilen;
432 	char	*data_string;
433 
434 	ilen = scsi_ascii_inquiry_len(data, len);
435 	ASSERT3U(ilen, <=, len);
436 	if (ilen <= 0)
437 		return;
438 	/* ensure null termination */
439 	data_string = kmem_zalloc(ilen + 1, KM_SLEEP);
440 	bcopy(data, data_string, ilen);
441 	(void) ndi_prop_update_string(DDI_DEV_T_NONE, dip, name, data_string);
442 	kmem_free(data_string, ilen + 1);
443 }
444 
445 static void
446 bd_create_inquiry_props(dev_info_t *dip, bd_drive_t *drive)
447 {
448 	if (drive->d_vendor_len > 0)
449 		bd_prop_update_inqstring(dip, INQUIRY_VENDOR_ID,
450 		    drive->d_vendor, drive->d_vendor_len);
451 
452 	if (drive->d_product_len > 0)
453 		bd_prop_update_inqstring(dip, INQUIRY_PRODUCT_ID,
454 		    drive->d_product, drive->d_product_len);
455 
456 	if (drive->d_serial_len > 0)
457 		bd_prop_update_inqstring(dip, INQUIRY_SERIAL_NO,
458 		    drive->d_serial, drive->d_serial_len);
459 
460 	if (drive->d_revision_len > 0)
461 		bd_prop_update_inqstring(dip, INQUIRY_REVISION_ID,
462 		    drive->d_revision, drive->d_revision_len);
463 }
464 
465 static void
466 bd_create_errstats(bd_t *bd, int inst, bd_drive_t *drive)
467 {
468 	char	ks_module[KSTAT_STRLEN];
469 	char	ks_name[KSTAT_STRLEN];
470 	int	ndata = sizeof (struct bd_errstats) / sizeof (kstat_named_t);
471 
472 	if (bd->d_errstats != NULL)
473 		return;
474 
475 	(void) snprintf(ks_module, sizeof (ks_module), "%serr",
476 	    ddi_driver_name(bd->d_dip));
477 	(void) snprintf(ks_name, sizeof (ks_name), "%s%d,err",
478 	    ddi_driver_name(bd->d_dip), inst);
479 
480 	bd->d_errstats = kstat_create(ks_module, inst, ks_name, "device_error",
481 	    KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
482 
483 	mutex_init(&bd->d_errmutex, NULL, MUTEX_DRIVER, NULL);
484 	if (bd->d_errstats == NULL) {
485 		/*
486 		 * Even if we cannot create the kstat, we create a
487 		 * scratch kstat.  The reason for this is to ensure
488 		 * that we can update the kstat all of the time,
489 		 * without adding an extra branch instruction.
490 		 */
491 		bd->d_kerr = kmem_zalloc(sizeof (struct bd_errstats),
492 		    KM_SLEEP);
493 	} else {
494 		bd->d_errstats->ks_lock = &bd->d_errmutex;
495 		bd->d_kerr = (struct bd_errstats *)bd->d_errstats->ks_data;
496 	}
497 
498 	kstat_named_init(&bd->d_kerr->bd_softerrs,	"Soft Errors",
499 	    KSTAT_DATA_UINT32);
500 	kstat_named_init(&bd->d_kerr->bd_harderrs,	"Hard Errors",
501 	    KSTAT_DATA_UINT32);
502 	kstat_named_init(&bd->d_kerr->bd_transerrs,	"Transport Errors",
503 	    KSTAT_DATA_UINT32);
504 
505 	if (drive->d_model_len > 0) {
506 		kstat_named_init(&bd->d_kerr->bd_model,	"Model",
507 		    KSTAT_DATA_STRING);
508 	} else {
509 		kstat_named_init(&bd->d_kerr->bd_vid,	"Vendor",
510 		    KSTAT_DATA_STRING);
511 		kstat_named_init(&bd->d_kerr->bd_pid,	"Product",
512 		    KSTAT_DATA_STRING);
513 	}
514 
515 	kstat_named_init(&bd->d_kerr->bd_revision,	"Revision",
516 	    KSTAT_DATA_STRING);
517 	kstat_named_init(&bd->d_kerr->bd_serial,	"Serial No",
518 	    KSTAT_DATA_STRING);
519 	kstat_named_init(&bd->d_kerr->bd_capacity,	"Size",
520 	    KSTAT_DATA_ULONGLONG);
521 	kstat_named_init(&bd->d_kerr->bd_rq_media_err,	"Media Error",
522 	    KSTAT_DATA_UINT32);
523 	kstat_named_init(&bd->d_kerr->bd_rq_ntrdy_err,	"Device Not Ready",
524 	    KSTAT_DATA_UINT32);
525 	kstat_named_init(&bd->d_kerr->bd_rq_nodev_err,	"No Device",
526 	    KSTAT_DATA_UINT32);
527 	kstat_named_init(&bd->d_kerr->bd_rq_recov_err,	"Recoverable",
528 	    KSTAT_DATA_UINT32);
529 	kstat_named_init(&bd->d_kerr->bd_rq_illrq_err,	"Illegal Request",
530 	    KSTAT_DATA_UINT32);
531 	kstat_named_init(&bd->d_kerr->bd_rq_pfa_err,
532 	    "Predictive Failure Analysis", KSTAT_DATA_UINT32);
533 
534 	bd->d_errstats->ks_private = bd;
535 
536 	kstat_install(bd->d_errstats);
537 	bd_init_errstats(bd, drive);
538 }
539 
540 static void
541 bd_destroy_errstats(bd_t *bd)
542 {
543 	if (bd->d_errstats != NULL) {
544 		bd_fini_errstats(bd);
545 		kstat_delete(bd->d_errstats);
546 		bd->d_errstats = NULL;
547 	} else {
548 		kmem_free(bd->d_kerr, sizeof (struct bd_errstats));
549 		bd->d_kerr = NULL;
550 		mutex_destroy(&bd->d_errmutex);
551 	}
552 }
553 
554 static void
555 bd_errstats_setstr(kstat_named_t *k, char *str, size_t len, char *alt)
556 {
557 	char	*tmp;
558 	size_t	km_len;
559 
560 	if (KSTAT_NAMED_STR_PTR(k) == NULL) {
561 		if (len > 0)
562 			km_len = strnlen(str, len);
563 		else if (alt != NULL)
564 			km_len = strlen(alt);
565 		else
566 			return;
567 
568 		tmp = kmem_alloc(km_len + 1, KM_SLEEP);
569 		bcopy(len > 0 ? str : alt, tmp, km_len);
570 		tmp[km_len] = '\0';
571 
572 		kstat_named_setstr(k, tmp);
573 	}
574 }
575 
576 static void
577 bd_errstats_clrstr(kstat_named_t *k)
578 {
579 	if (KSTAT_NAMED_STR_PTR(k) == NULL)
580 		return;
581 
582 	kmem_free(KSTAT_NAMED_STR_PTR(k), KSTAT_NAMED_STR_BUFLEN(k));
583 	kstat_named_setstr(k, NULL);
584 }
585 
586 static void
587 bd_init_errstats(bd_t *bd, bd_drive_t *drive)
588 {
589 	struct bd_errstats	*est = bd->d_kerr;
590 
591 	mutex_enter(&bd->d_errmutex);
592 
593 	if (drive->d_model_len > 0 &&
594 	    KSTAT_NAMED_STR_PTR(&est->bd_model) == NULL) {
595 		bd_errstats_setstr(&est->bd_model, drive->d_model,
596 		    drive->d_model_len, NULL);
597 	} else {
598 		bd_errstats_setstr(&est->bd_vid, drive->d_vendor,
599 		    drive->d_vendor_len, "Unknown ");
600 		bd_errstats_setstr(&est->bd_pid, drive->d_product,
601 		    drive->d_product_len, "Unknown         ");
602 	}
603 
604 	bd_errstats_setstr(&est->bd_revision, drive->d_revision,
605 	    drive->d_revision_len, "0001");
606 	bd_errstats_setstr(&est->bd_serial, drive->d_serial,
607 	    drive->d_serial_len, "0               ");
608 
609 	mutex_exit(&bd->d_errmutex);
610 }
611 
612 static void
613 bd_fini_errstats(bd_t *bd)
614 {
615 	struct bd_errstats	*est = bd->d_kerr;
616 
617 	mutex_enter(&bd->d_errmutex);
618 
619 	bd_errstats_clrstr(&est->bd_model);
620 	bd_errstats_clrstr(&est->bd_vid);
621 	bd_errstats_clrstr(&est->bd_pid);
622 	bd_errstats_clrstr(&est->bd_revision);
623 	bd_errstats_clrstr(&est->bd_serial);
624 
625 	mutex_exit(&bd->d_errmutex);
626 }
627 
628 static void
629 bd_queues_free(bd_t *bd)
630 {
631 	uint32_t i;
632 
633 	for (i = 0; i < bd->d_qcount; i++) {
634 		bd_queue_t *bq = &bd->d_queues[i];
635 
636 		mutex_destroy(&bq->q_iomutex);
637 		list_destroy(&bq->q_waitq);
638 		list_destroy(&bq->q_runq);
639 	}
640 
641 	kmem_free(bd->d_queues, sizeof (*bd->d_queues) * bd->d_qcount);
642 }
643 
644 static int
645 bd_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
646 {
647 	int		inst;
648 	bd_handle_t	hdl;
649 	bd_t		*bd;
650 	bd_drive_t	drive;
651 	uint32_t	i;
652 	int		rv;
653 	char		name[16];
654 	char		kcache[32];
655 	char		*node_type;
656 
657 	switch (cmd) {
658 	case DDI_ATTACH:
659 		break;
660 	case DDI_RESUME:
661 		/* We don't do anything native for suspend/resume */
662 		return (DDI_SUCCESS);
663 	default:
664 		return (DDI_FAILURE);
665 	}
666 
667 	inst = ddi_get_instance(dip);
668 	hdl = ddi_get_parent_data(dip);
669 
670 	(void) snprintf(name, sizeof (name), "%s%d",
671 	    ddi_driver_name(dip), ddi_get_instance(dip));
672 	(void) snprintf(kcache, sizeof (kcache), "%s_xfer", name);
673 
674 	if (hdl == NULL) {
675 		cmn_err(CE_WARN, "%s: missing parent data!", name);
676 		return (DDI_FAILURE);
677 	}
678 
679 	if (ddi_soft_state_zalloc(bd_state, inst) != DDI_SUCCESS) {
680 		cmn_err(CE_WARN, "%s: unable to zalloc soft state!", name);
681 		return (DDI_FAILURE);
682 	}
683 	bd = ddi_get_soft_state(bd_state, inst);
684 
685 	if (hdl->h_dma) {
686 		bd->d_dma = *(hdl->h_dma);
687 		bd->d_dma.dma_attr_granular =
688 		    max(DEV_BSIZE, bd->d_dma.dma_attr_granular);
689 		bd->d_use_dma = B_TRUE;
690 
691 		if (bd->d_maxxfer &&
692 		    (bd->d_maxxfer != bd->d_dma.dma_attr_maxxfer)) {
693 			cmn_err(CE_WARN,
694 			    "%s: inconsistent maximum transfer size!",
695 			    name);
696 			/* We force it */
697 			bd->d_maxxfer = bd->d_dma.dma_attr_maxxfer;
698 		} else {
699 			bd->d_maxxfer = bd->d_dma.dma_attr_maxxfer;
700 		}
701 	} else {
702 		bd->d_use_dma = B_FALSE;
703 		if (bd->d_maxxfer == 0) {
704 			bd->d_maxxfer = 1024 * 1024;
705 		}
706 	}
707 	bd->d_ops = hdl->h_ops;
708 	bd->d_private = hdl->h_private;
709 	bd->d_blkshift = DEV_BSHIFT;	/* 512 bytes, to start */
710 
711 	if (bd->d_maxxfer % DEV_BSIZE) {
712 		cmn_err(CE_WARN, "%s: maximum transfer misaligned!", name);
713 		bd->d_maxxfer &= ~(DEV_BSIZE - 1);
714 	}
715 	if (bd->d_maxxfer < DEV_BSIZE) {
716 		cmn_err(CE_WARN, "%s: maximum transfer size too small!", name);
717 		ddi_soft_state_free(bd_state, inst);
718 		return (DDI_FAILURE);
719 	}
720 
721 	bd->d_dip = dip;
722 	bd->d_handle = hdl;
723 	ddi_set_driver_private(dip, bd);
724 
725 	mutex_init(&bd->d_ksmutex, NULL, MUTEX_DRIVER, NULL);
726 	mutex_init(&bd->d_ocmutex, NULL, MUTEX_DRIVER, NULL);
727 	mutex_init(&bd->d_statemutex, NULL, MUTEX_DRIVER, NULL);
728 	cv_init(&bd->d_statecv, NULL, CV_DRIVER, NULL);
729 	mutex_init(&bd->d_dle_mutex, NULL, MUTEX_DRIVER, NULL);
730 	bd->d_dle_state = 0;
731 
732 	bd->d_cache = kmem_cache_create(kcache, sizeof (bd_xfer_impl_t), 8,
733 	    bd_xfer_ctor, bd_xfer_dtor, NULL, bd, NULL, 0);
734 
735 	bd->d_ksp = kstat_create(ddi_driver_name(dip), inst, NULL, "disk",
736 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
737 	if (bd->d_ksp != NULL) {
738 		bd->d_ksp->ks_lock = &bd->d_ksmutex;
739 		kstat_install(bd->d_ksp);
740 		bd->d_kiop = bd->d_ksp->ks_data;
741 	} else {
742 		/*
743 		 * Even if we cannot create the kstat, we create a
744 		 * scratch kstat.  The reason for this is to ensure
745 		 * that we can update the kstat all of the time,
746 		 * without adding an extra branch instruction.
747 		 */
748 		bd->d_kiop = kmem_zalloc(sizeof (kstat_io_t), KM_SLEEP);
749 	}
750 
751 	cmlb_alloc_handle(&bd->d_cmlbh);
752 
753 	bd->d_state = DKIO_NONE;
754 
755 	bzero(&drive, sizeof (drive));
756 	/*
757 	 * Default to one queue, and no restrictions on free space requests
758 	 * (if driver provides method) parent driver can override.
759 	 */
760 	drive.d_qcount = 1;
761 	drive.d_free_align = 1;
762 	bd->d_ops.o_drive_info(bd->d_private, &drive);
763 
764 	/*
765 	 * Several checks to make sure o_drive_info() didn't return bad
766 	 * values:
767 	 *
768 	 * There must be at least one queue
769 	 */
770 	if (drive.d_qcount == 0)
771 		goto fail_drive_info;
772 
773 	/* FREE/UNMAP/TRIM alignment needs to be at least 1 block */
774 	if (drive.d_free_align == 0)
775 		goto fail_drive_info;
776 
777 	/*
778 	 * If d_max_free_blks is not unlimited (not 0), then we cannot allow
779 	 * an unlimited segment size. It is however permissible to not impose
780 	 * a limit on the total number of blocks freed while limiting the
781 	 * amount allowed in an individual segment.
782 	 */
783 	if ((drive.d_max_free_blks > 0 && drive.d_max_free_seg_blks == 0))
784 		goto fail_drive_info;
785 
786 	/*
787 	 * If a limit is set on d_max_free_blks (by the above check, we know
788 	 * if there's a limit on d_max_free_blks, d_max_free_seg_blks cannot
789 	 * be unlimited), it cannot be smaller than the limit on an individual
790 	 * segment.
791 	 */
792 	if ((drive.d_max_free_blks > 0 &&
793 	    drive.d_max_free_seg_blks > drive.d_max_free_blks)) {
794 		goto fail_drive_info;
795 	}
796 
797 	bd->d_qcount = drive.d_qcount;
798 	bd->d_removable = drive.d_removable;
799 	bd->d_hotpluggable = drive.d_hotpluggable;
800 
801 	if (drive.d_maxxfer && drive.d_maxxfer < bd->d_maxxfer)
802 		bd->d_maxxfer = drive.d_maxxfer;
803 
804 	bd->d_free_align = drive.d_free_align;
805 	bd->d_max_free_seg = drive.d_max_free_seg;
806 	bd->d_max_free_blks = drive.d_max_free_blks;
807 	bd->d_max_free_seg_blks = drive.d_max_free_seg_blks;
808 
809 	bd_create_inquiry_props(dip, &drive);
810 	bd_create_errstats(bd, inst, &drive);
811 	bd_update_state(bd);
812 
813 	bd->d_queues = kmem_alloc(sizeof (*bd->d_queues) * bd->d_qcount,
814 	    KM_SLEEP);
815 	for (i = 0; i < bd->d_qcount; i++) {
816 		bd_queue_t *bq = &bd->d_queues[i];
817 
818 		bq->q_qsize = drive.d_qsize;
819 		bq->q_qactive = 0;
820 		mutex_init(&bq->q_iomutex, NULL, MUTEX_DRIVER, NULL);
821 
822 		list_create(&bq->q_waitq, sizeof (bd_xfer_impl_t),
823 		    offsetof(struct bd_xfer_impl, i_linkage));
824 		list_create(&bq->q_runq, sizeof (bd_xfer_impl_t),
825 		    offsetof(struct bd_xfer_impl, i_linkage));
826 	}
827 
828 	if (*(uint64_t *)drive.d_eui64 != 0 ||
829 	    *(uint64_t *)drive.d_guid != 0 ||
830 	    *((uint64_t *)drive.d_guid + 1) != 0)
831 		node_type = DDI_NT_BLOCK_BLKDEV;
832 	else if (drive.d_lun >= 0)
833 		node_type = DDI_NT_BLOCK_CHAN;
834 	else
835 		node_type = DDI_NT_BLOCK;
836 
837 	rv = cmlb_attach(dip, &bd_tg_ops, DTYPE_DIRECT,
838 	    bd->d_removable, bd->d_hotpluggable, node_type,
839 	    CMLB_FAKE_LABEL_ONE_PARTITION, bd->d_cmlbh, 0);
840 	if (rv != 0) {
841 		goto fail_cmlb_attach;
842 	}
843 
844 	if (bd->d_ops.o_devid_init != NULL) {
845 		rv = bd->d_ops.o_devid_init(bd->d_private, dip, &bd->d_devid);
846 		if (rv == DDI_SUCCESS) {
847 			if (ddi_devid_register(dip, bd->d_devid) !=
848 			    DDI_SUCCESS) {
849 				cmn_err(CE_WARN,
850 				    "%s: unable to register devid", name);
851 			}
852 		}
853 	}
854 
855 	/*
856 	 * Add a zero-length attribute to tell the world we support
857 	 * kernel ioctls (for layered drivers).  Also set up properties
858 	 * used by HAL to identify removable media.
859 	 */
860 	(void) ddi_prop_create(DDI_DEV_T_NONE, dip, DDI_PROP_CANSLEEP,
861 	    DDI_KERNEL_IOCTL, NULL, 0);
862 	if (bd->d_removable) {
863 		(void) ddi_prop_create(DDI_DEV_T_NONE, dip, DDI_PROP_CANSLEEP,
864 		    "removable-media", NULL, 0);
865 	}
866 	if (bd->d_hotpluggable) {
867 		(void) ddi_prop_create(DDI_DEV_T_NONE, dip, DDI_PROP_CANSLEEP,
868 		    "hotpluggable", NULL, 0);
869 	}
870 
871 	hdl->h_bd = bd;
872 	ddi_report_dev(dip);
873 
874 	return (DDI_SUCCESS);
875 
876 fail_cmlb_attach:
877 	bd_queues_free(bd);
878 	bd_destroy_errstats(bd);
879 
880 fail_drive_info:
881 	cmlb_free_handle(&bd->d_cmlbh);
882 
883 	if (bd->d_ksp != NULL) {
884 		kstat_delete(bd->d_ksp);
885 		bd->d_ksp = NULL;
886 	} else {
887 		kmem_free(bd->d_kiop, sizeof (kstat_io_t));
888 	}
889 
890 	kmem_cache_destroy(bd->d_cache);
891 	cv_destroy(&bd->d_statecv);
892 	mutex_destroy(&bd->d_statemutex);
893 	mutex_destroy(&bd->d_ocmutex);
894 	mutex_destroy(&bd->d_ksmutex);
895 	mutex_destroy(&bd->d_dle_mutex);
896 	ddi_soft_state_free(bd_state, inst);
897 	return (DDI_FAILURE);
898 }
899 
900 static int
901 bd_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
902 {
903 	bd_handle_t	hdl;
904 	bd_t		*bd;
905 
906 	bd = ddi_get_driver_private(dip);
907 	hdl = ddi_get_parent_data(dip);
908 
909 	switch (cmd) {
910 	case DDI_DETACH:
911 		break;
912 	case DDI_SUSPEND:
913 		/* We don't suspend, but our parent does */
914 		return (DDI_SUCCESS);
915 	default:
916 		return (DDI_FAILURE);
917 	}
918 
919 	hdl->h_bd = NULL;
920 
921 	if (bd->d_ksp != NULL) {
922 		kstat_delete(bd->d_ksp);
923 		bd->d_ksp = NULL;
924 	} else {
925 		kmem_free(bd->d_kiop, sizeof (kstat_io_t));
926 	}
927 
928 	bd_destroy_errstats(bd);
929 	cmlb_detach(bd->d_cmlbh, 0);
930 	cmlb_free_handle(&bd->d_cmlbh);
931 	if (bd->d_devid)
932 		ddi_devid_free(bd->d_devid);
933 	kmem_cache_destroy(bd->d_cache);
934 	mutex_destroy(&bd->d_ksmutex);
935 	mutex_destroy(&bd->d_ocmutex);
936 	mutex_destroy(&bd->d_statemutex);
937 	cv_destroy(&bd->d_statecv);
938 	mutex_destroy(&bd->d_dle_mutex);
939 	bd_queues_free(bd);
940 	ddi_soft_state_free(bd_state, ddi_get_instance(dip));
941 	return (DDI_SUCCESS);
942 }
943 
944 static int
945 bd_xfer_ctor(void *buf, void *arg, int kmflag)
946 {
947 	bd_xfer_impl_t	*xi;
948 	bd_t		*bd = arg;
949 	int		(*dcb)(caddr_t);
950 
951 	if (kmflag == KM_PUSHPAGE || kmflag == KM_SLEEP) {
952 		dcb = DDI_DMA_SLEEP;
953 	} else {
954 		dcb = DDI_DMA_DONTWAIT;
955 	}
956 
957 	xi = buf;
958 	bzero(xi, sizeof (*xi));
959 	xi->i_bd = bd;
960 
961 	if (bd->d_use_dma) {
962 		if (ddi_dma_alloc_handle(bd->d_dip, &bd->d_dma, dcb, NULL,
963 		    &xi->i_dmah) != DDI_SUCCESS) {
964 			return (-1);
965 		}
966 	}
967 
968 	return (0);
969 }
970 
971 static void
972 bd_xfer_dtor(void *buf, void *arg)
973 {
974 	bd_xfer_impl_t	*xi = buf;
975 
976 	_NOTE(ARGUNUSED(arg));
977 
978 	if (xi->i_dmah)
979 		ddi_dma_free_handle(&xi->i_dmah);
980 	xi->i_dmah = NULL;
981 }
982 
983 static bd_xfer_impl_t *
984 bd_xfer_alloc(bd_t *bd, struct buf *bp, int (*func)(void *, bd_xfer_t *),
985     int kmflag)
986 {
987 	bd_xfer_impl_t		*xi;
988 	int			rv = 0;
989 	int			status;
990 	unsigned		dir;
991 	int			(*cb)(caddr_t);
992 	size_t			len;
993 	uint32_t		shift;
994 
995 	if (kmflag == KM_SLEEP) {
996 		cb = DDI_DMA_SLEEP;
997 	} else {
998 		cb = DDI_DMA_DONTWAIT;
999 	}
1000 
1001 	xi = kmem_cache_alloc(bd->d_cache, kmflag);
1002 	if (xi == NULL) {
1003 		bioerror(bp, ENOMEM);
1004 		return (NULL);
1005 	}
1006 
1007 	ASSERT(bp);
1008 
1009 	xi->i_bp = bp;
1010 	xi->i_func = func;
1011 	xi->i_blkno = bp->b_lblkno >> (bd->d_blkshift - DEV_BSHIFT);
1012 
1013 	if (bp->b_bcount == 0) {
1014 		xi->i_len = 0;
1015 		xi->i_nblks = 0;
1016 		xi->i_kaddr = NULL;
1017 		xi->i_resid = 0;
1018 		xi->i_num_win = 0;
1019 		goto done;
1020 	}
1021 
1022 	if (bp->b_flags & B_READ) {
1023 		dir = DDI_DMA_READ;
1024 		xi->i_func = bd->d_ops.o_read;
1025 	} else {
1026 		dir = DDI_DMA_WRITE;
1027 		xi->i_func = bd->d_ops.o_write;
1028 	}
1029 
1030 	shift = bd->d_blkshift;
1031 	xi->i_blkshift = shift;
1032 
1033 	if (!bd->d_use_dma) {
1034 		bp_mapin(bp);
1035 		rv = 0;
1036 		xi->i_offset = 0;
1037 		xi->i_num_win =
1038 		    (bp->b_bcount + (bd->d_maxxfer - 1)) / bd->d_maxxfer;
1039 		xi->i_cur_win = 0;
1040 		xi->i_len = min(bp->b_bcount, bd->d_maxxfer);
1041 		xi->i_nblks = xi->i_len >> shift;
1042 		xi->i_kaddr = bp->b_un.b_addr;
1043 		xi->i_resid = bp->b_bcount;
1044 	} else {
1045 
1046 		/*
1047 		 * We have to use consistent DMA if the address is misaligned.
1048 		 */
1049 		if (((bp->b_flags & (B_PAGEIO | B_REMAPPED)) != B_PAGEIO) &&
1050 		    ((uintptr_t)bp->b_un.b_addr & 0x7)) {
1051 			dir |= DDI_DMA_CONSISTENT | DDI_DMA_PARTIAL;
1052 		} else {
1053 			dir |= DDI_DMA_STREAMING | DDI_DMA_PARTIAL;
1054 		}
1055 
1056 		status = ddi_dma_buf_bind_handle(xi->i_dmah, bp, dir, cb,
1057 		    NULL, &xi->i_dmac, &xi->i_ndmac);
1058 		switch (status) {
1059 		case DDI_DMA_MAPPED:
1060 			xi->i_num_win = 1;
1061 			xi->i_cur_win = 0;
1062 			xi->i_offset = 0;
1063 			xi->i_len = bp->b_bcount;
1064 			xi->i_nblks = xi->i_len >> shift;
1065 			xi->i_resid = bp->b_bcount;
1066 			rv = 0;
1067 			break;
1068 		case DDI_DMA_PARTIAL_MAP:
1069 			xi->i_cur_win = 0;
1070 
1071 			if ((ddi_dma_numwin(xi->i_dmah, &xi->i_num_win) !=
1072 			    DDI_SUCCESS) ||
1073 			    (ddi_dma_getwin(xi->i_dmah, 0, &xi->i_offset,
1074 			    &len, &xi->i_dmac, &xi->i_ndmac) !=
1075 			    DDI_SUCCESS) ||
1076 			    (P2PHASE(len, (1U << shift)) != 0)) {
1077 				(void) ddi_dma_unbind_handle(xi->i_dmah);
1078 				rv = EFAULT;
1079 				goto done;
1080 			}
1081 			xi->i_len = len;
1082 			xi->i_nblks = xi->i_len >> shift;
1083 			xi->i_resid = bp->b_bcount;
1084 			rv = 0;
1085 			break;
1086 		case DDI_DMA_NORESOURCES:
1087 			rv = EAGAIN;
1088 			goto done;
1089 		case DDI_DMA_TOOBIG:
1090 			rv = EINVAL;
1091 			goto done;
1092 		case DDI_DMA_NOMAPPING:
1093 		case DDI_DMA_INUSE:
1094 		default:
1095 			rv = EFAULT;
1096 			goto done;
1097 		}
1098 	}
1099 
1100 done:
1101 	if (rv != 0) {
1102 		kmem_cache_free(bd->d_cache, xi);
1103 		bioerror(bp, rv);
1104 		return (NULL);
1105 	}
1106 
1107 	return (xi);
1108 }
1109 
1110 static void
1111 bd_xfer_free(bd_xfer_impl_t *xi)
1112 {
1113 	if (xi->i_dmah) {
1114 		(void) ddi_dma_unbind_handle(xi->i_dmah);
1115 	}
1116 	if (xi->i_dfl != NULL) {
1117 		dfl_free((dkioc_free_list_t *)xi->i_dfl);
1118 		xi->i_dfl = NULL;
1119 	}
1120 	kmem_cache_free(xi->i_bd->d_cache, xi);
1121 }
1122 
1123 static int
1124 bd_open(dev_t *devp, int flag, int otyp, cred_t *credp)
1125 {
1126 	dev_t		dev = *devp;
1127 	bd_t		*bd;
1128 	minor_t		part;
1129 	minor_t		inst;
1130 	uint64_t	mask;
1131 	boolean_t	ndelay;
1132 	int		rv;
1133 	diskaddr_t	nblks;
1134 	diskaddr_t	lba;
1135 
1136 	_NOTE(ARGUNUSED(credp));
1137 
1138 	part = BDPART(dev);
1139 	inst = BDINST(dev);
1140 
1141 	if (otyp >= OTYPCNT)
1142 		return (EINVAL);
1143 
1144 	ndelay = (flag & (FNDELAY | FNONBLOCK)) ? B_TRUE : B_FALSE;
1145 
1146 	/*
1147 	 * Block any DR events from changing the set of registered
1148 	 * devices while we function.
1149 	 */
1150 	rw_enter(&bd_lock, RW_READER);
1151 	if ((bd = ddi_get_soft_state(bd_state, inst)) == NULL) {
1152 		rw_exit(&bd_lock);
1153 		return (ENXIO);
1154 	}
1155 
1156 	mutex_enter(&bd->d_ocmutex);
1157 
1158 	ASSERT(part < 64);
1159 	mask = (1U << part);
1160 
1161 	bd_update_state(bd);
1162 
1163 	if (cmlb_validate(bd->d_cmlbh, 0, 0) != 0) {
1164 
1165 		/* non-blocking opens are allowed to succeed */
1166 		if (!ndelay) {
1167 			rv = ENXIO;
1168 			goto done;
1169 		}
1170 	} else if (cmlb_partinfo(bd->d_cmlbh, part, &nblks, &lba,
1171 	    NULL, NULL, 0) == 0) {
1172 
1173 		/*
1174 		 * We read the partinfo, verify valid ranges.  If the
1175 		 * partition is invalid, and we aren't blocking or
1176 		 * doing a raw access, then fail. (Non-blocking and
1177 		 * raw accesses can still succeed to allow a disk with
1178 		 * bad partition data to opened by format and fdisk.)
1179 		 */
1180 		if ((!nblks) && ((!ndelay) || (otyp != OTYP_CHR))) {
1181 			rv = ENXIO;
1182 			goto done;
1183 		}
1184 	} else if (!ndelay) {
1185 		/*
1186 		 * cmlb_partinfo failed -- invalid partition or no
1187 		 * disk label.
1188 		 */
1189 		rv = ENXIO;
1190 		goto done;
1191 	}
1192 
1193 	if ((flag & FWRITE) && bd->d_rdonly) {
1194 		rv = EROFS;
1195 		goto done;
1196 	}
1197 
1198 	if ((bd->d_open_excl) & (mask)) {
1199 		rv = EBUSY;
1200 		goto done;
1201 	}
1202 	if (flag & FEXCL) {
1203 		if (bd->d_open_lyr[part]) {
1204 			rv = EBUSY;
1205 			goto done;
1206 		}
1207 		for (int i = 0; i < OTYP_LYR; i++) {
1208 			if (bd->d_open_reg[i] & mask) {
1209 				rv = EBUSY;
1210 				goto done;
1211 			}
1212 		}
1213 	}
1214 
1215 	if (otyp == OTYP_LYR) {
1216 		bd->d_open_lyr[part]++;
1217 	} else {
1218 		bd->d_open_reg[otyp] |= mask;
1219 	}
1220 	if (flag & FEXCL) {
1221 		bd->d_open_excl |= mask;
1222 	}
1223 
1224 	rv = 0;
1225 done:
1226 	mutex_exit(&bd->d_ocmutex);
1227 	rw_exit(&bd_lock);
1228 
1229 	return (rv);
1230 }
1231 
1232 static int
1233 bd_close(dev_t dev, int flag, int otyp, cred_t *credp)
1234 {
1235 	bd_t		*bd;
1236 	minor_t		inst;
1237 	minor_t		part;
1238 	uint64_t	mask;
1239 	boolean_t	last = B_TRUE;
1240 
1241 	_NOTE(ARGUNUSED(flag));
1242 	_NOTE(ARGUNUSED(credp));
1243 
1244 	part = BDPART(dev);
1245 	inst = BDINST(dev);
1246 
1247 	ASSERT(part < 64);
1248 	mask = (1U << part);
1249 
1250 	rw_enter(&bd_lock, RW_READER);
1251 
1252 	if ((bd = ddi_get_soft_state(bd_state, inst)) == NULL) {
1253 		rw_exit(&bd_lock);
1254 		return (ENXIO);
1255 	}
1256 
1257 	mutex_enter(&bd->d_ocmutex);
1258 	if (bd->d_open_excl & mask) {
1259 		bd->d_open_excl &= ~mask;
1260 	}
1261 	if (otyp == OTYP_LYR) {
1262 		bd->d_open_lyr[part]--;
1263 	} else {
1264 		bd->d_open_reg[otyp] &= ~mask;
1265 	}
1266 	for (int i = 0; i < 64; i++) {
1267 		if (bd->d_open_lyr[part]) {
1268 			last = B_FALSE;
1269 		}
1270 	}
1271 	for (int i = 0; last && (i < OTYP_LYR); i++) {
1272 		if (bd->d_open_reg[i]) {
1273 			last = B_FALSE;
1274 		}
1275 	}
1276 	mutex_exit(&bd->d_ocmutex);
1277 
1278 	if (last) {
1279 		cmlb_invalidate(bd->d_cmlbh, 0);
1280 	}
1281 	rw_exit(&bd_lock);
1282 
1283 	return (0);
1284 }
1285 
1286 static int
1287 bd_dump(dev_t dev, caddr_t caddr, daddr_t blkno, int nblk)
1288 {
1289 	minor_t		inst;
1290 	minor_t		part;
1291 	diskaddr_t	pstart;
1292 	diskaddr_t	psize;
1293 	bd_t		*bd;
1294 	bd_xfer_impl_t	*xi;
1295 	buf_t		*bp;
1296 	int		rv;
1297 	uint32_t	shift;
1298 	daddr_t		d_blkno;
1299 	int	d_nblk;
1300 
1301 	rw_enter(&bd_lock, RW_READER);
1302 
1303 	part = BDPART(dev);
1304 	inst = BDINST(dev);
1305 
1306 	if ((bd = ddi_get_soft_state(bd_state, inst)) == NULL) {
1307 		rw_exit(&bd_lock);
1308 		return (ENXIO);
1309 	}
1310 	shift = bd->d_blkshift;
1311 	d_blkno = blkno >> (shift - DEV_BSHIFT);
1312 	d_nblk = nblk >> (shift - DEV_BSHIFT);
1313 	/*
1314 	 * do cmlb, but do it synchronously unless we already have the
1315 	 * partition (which we probably should.)
1316 	 */
1317 	if (cmlb_partinfo(bd->d_cmlbh, part, &psize, &pstart, NULL, NULL,
1318 	    (void *)1)) {
1319 		rw_exit(&bd_lock);
1320 		return (ENXIO);
1321 	}
1322 
1323 	if ((d_blkno + d_nblk) > psize) {
1324 		rw_exit(&bd_lock);
1325 		return (EINVAL);
1326 	}
1327 	bp = getrbuf(KM_NOSLEEP);
1328 	if (bp == NULL) {
1329 		rw_exit(&bd_lock);
1330 		return (ENOMEM);
1331 	}
1332 
1333 	bp->b_bcount = nblk << DEV_BSHIFT;
1334 	bp->b_resid = bp->b_bcount;
1335 	bp->b_lblkno = blkno;
1336 	bp->b_un.b_addr = caddr;
1337 
1338 	xi = bd_xfer_alloc(bd, bp,  bd->d_ops.o_write, KM_NOSLEEP);
1339 	if (xi == NULL) {
1340 		rw_exit(&bd_lock);
1341 		freerbuf(bp);
1342 		return (ENOMEM);
1343 	}
1344 	xi->i_blkno = d_blkno + pstart;
1345 	xi->i_flags = BD_XFER_POLL;
1346 	bd_submit(bd, xi);
1347 	rw_exit(&bd_lock);
1348 
1349 	/*
1350 	 * Generally, we should have run this entirely synchronously
1351 	 * at this point and the biowait call should be a no-op.  If
1352 	 * it didn't happen this way, it's a bug in the underlying
1353 	 * driver not honoring BD_XFER_POLL.
1354 	 */
1355 	(void) biowait(bp);
1356 	rv = geterror(bp);
1357 	freerbuf(bp);
1358 	return (rv);
1359 }
1360 
1361 void
1362 bd_minphys(struct buf *bp)
1363 {
1364 	minor_t inst;
1365 	bd_t	*bd;
1366 	inst = BDINST(bp->b_edev);
1367 
1368 	bd = ddi_get_soft_state(bd_state, inst);
1369 
1370 	/*
1371 	 * In a non-debug kernel, bd_strategy will catch !bd as
1372 	 * well, and will fail nicely.
1373 	 */
1374 	ASSERT(bd);
1375 
1376 	if (bp->b_bcount > bd->d_maxxfer)
1377 		bp->b_bcount = bd->d_maxxfer;
1378 }
1379 
1380 static int
1381 bd_check_uio(dev_t dev, struct uio *uio)
1382 {
1383 	bd_t		*bd;
1384 	uint32_t	shift;
1385 
1386 	if ((bd = ddi_get_soft_state(bd_state, BDINST(dev))) == NULL) {
1387 		return (ENXIO);
1388 	}
1389 
1390 	shift = bd->d_blkshift;
1391 	if ((P2PHASE(uio->uio_loffset, (1U << shift)) != 0) ||
1392 	    (P2PHASE(uio->uio_iov->iov_len, (1U << shift)) != 0)) {
1393 		return (EINVAL);
1394 	}
1395 
1396 	return (0);
1397 }
1398 
1399 static int
1400 bd_read(dev_t dev, struct uio *uio, cred_t *credp)
1401 {
1402 	_NOTE(ARGUNUSED(credp));
1403 	int	ret = bd_check_uio(dev, uio);
1404 	if (ret != 0) {
1405 		return (ret);
1406 	}
1407 	return (physio(bd_strategy, NULL, dev, B_READ, bd_minphys, uio));
1408 }
1409 
1410 static int
1411 bd_write(dev_t dev, struct uio *uio, cred_t *credp)
1412 {
1413 	_NOTE(ARGUNUSED(credp));
1414 	int	ret = bd_check_uio(dev, uio);
1415 	if (ret != 0) {
1416 		return (ret);
1417 	}
1418 	return (physio(bd_strategy, NULL, dev, B_WRITE, bd_minphys, uio));
1419 }
1420 
1421 static int
1422 bd_aread(dev_t dev, struct aio_req *aio, cred_t *credp)
1423 {
1424 	_NOTE(ARGUNUSED(credp));
1425 	int	ret = bd_check_uio(dev, aio->aio_uio);
1426 	if (ret != 0) {
1427 		return (ret);
1428 	}
1429 	return (aphysio(bd_strategy, anocancel, dev, B_READ, bd_minphys, aio));
1430 }
1431 
1432 static int
1433 bd_awrite(dev_t dev, struct aio_req *aio, cred_t *credp)
1434 {
1435 	_NOTE(ARGUNUSED(credp));
1436 	int	ret = bd_check_uio(dev, aio->aio_uio);
1437 	if (ret != 0) {
1438 		return (ret);
1439 	}
1440 	return (aphysio(bd_strategy, anocancel, dev, B_WRITE, bd_minphys, aio));
1441 }
1442 
1443 static int
1444 bd_strategy(struct buf *bp)
1445 {
1446 	minor_t		inst;
1447 	minor_t		part;
1448 	bd_t		*bd;
1449 	diskaddr_t	p_lba;
1450 	diskaddr_t	p_nblks;
1451 	diskaddr_t	b_nblks;
1452 	bd_xfer_impl_t	*xi;
1453 	uint32_t	shift;
1454 	int		(*func)(void *, bd_xfer_t *);
1455 	diskaddr_t	lblkno;
1456 
1457 	part = BDPART(bp->b_edev);
1458 	inst = BDINST(bp->b_edev);
1459 
1460 	ASSERT(bp);
1461 
1462 	bp->b_resid = bp->b_bcount;
1463 
1464 	if ((bd = ddi_get_soft_state(bd_state, inst)) == NULL) {
1465 		bioerror(bp, ENXIO);
1466 		biodone(bp);
1467 		return (0);
1468 	}
1469 
1470 	if (cmlb_partinfo(bd->d_cmlbh, part, &p_nblks, &p_lba,
1471 	    NULL, NULL, 0)) {
1472 		bioerror(bp, ENXIO);
1473 		biodone(bp);
1474 		return (0);
1475 	}
1476 
1477 	shift = bd->d_blkshift;
1478 	lblkno = bp->b_lblkno >> (shift - DEV_BSHIFT);
1479 	if ((P2PHASE(bp->b_lblkno, (1U << (shift - DEV_BSHIFT))) != 0) ||
1480 	    (P2PHASE(bp->b_bcount, (1U << shift)) != 0) ||
1481 	    (lblkno > p_nblks)) {
1482 		bioerror(bp, EINVAL);
1483 		biodone(bp);
1484 		return (0);
1485 	}
1486 	b_nblks = bp->b_bcount >> shift;
1487 	if ((lblkno == p_nblks) || (bp->b_bcount == 0)) {
1488 		biodone(bp);
1489 		return (0);
1490 	}
1491 
1492 	if ((b_nblks + lblkno) > p_nblks) {
1493 		bp->b_resid = ((lblkno + b_nblks - p_nblks) << shift);
1494 		bp->b_bcount -= bp->b_resid;
1495 	} else {
1496 		bp->b_resid = 0;
1497 	}
1498 	func = (bp->b_flags & B_READ) ? bd->d_ops.o_read : bd->d_ops.o_write;
1499 
1500 	xi = bd_xfer_alloc(bd, bp, func, KM_NOSLEEP);
1501 	if (xi == NULL) {
1502 		xi = bd_xfer_alloc(bd, bp, func, KM_PUSHPAGE);
1503 	}
1504 	if (xi == NULL) {
1505 		/* bd_request_alloc will have done bioerror */
1506 		biodone(bp);
1507 		return (0);
1508 	}
1509 	xi->i_blkno = lblkno + p_lba;
1510 
1511 	bd_submit(bd, xi);
1512 
1513 	return (0);
1514 }
1515 
1516 static int
1517 bd_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *credp, int *rvalp)
1518 {
1519 	minor_t		inst;
1520 	uint16_t	part;
1521 	bd_t		*bd;
1522 	void		*ptr = (void *)arg;
1523 	int		rv;
1524 
1525 	part = BDPART(dev);
1526 	inst = BDINST(dev);
1527 
1528 	if ((bd = ddi_get_soft_state(bd_state, inst)) == NULL) {
1529 		return (ENXIO);
1530 	}
1531 
1532 	rv = cmlb_ioctl(bd->d_cmlbh, dev, cmd, arg, flag, credp, rvalp, 0);
1533 	if (rv != ENOTTY)
1534 		return (rv);
1535 
1536 	if (rvalp != NULL) {
1537 		/* the return value of the ioctl is 0 by default */
1538 		*rvalp = 0;
1539 	}
1540 
1541 	switch (cmd) {
1542 	case DKIOCGMEDIAINFO: {
1543 		struct dk_minfo minfo;
1544 
1545 		/* make sure our state information is current */
1546 		bd_update_state(bd);
1547 		bzero(&minfo, sizeof (minfo));
1548 		minfo.dki_media_type = DK_FIXED_DISK;
1549 		minfo.dki_lbsize = (1U << bd->d_blkshift);
1550 		minfo.dki_capacity = bd->d_numblks;
1551 		if (ddi_copyout(&minfo, ptr, sizeof (minfo), flag)) {
1552 			return (EFAULT);
1553 		}
1554 		return (0);
1555 	}
1556 	case DKIOCGMEDIAINFOEXT: {
1557 		struct dk_minfo_ext miext;
1558 		size_t len;
1559 
1560 		/* make sure our state information is current */
1561 		bd_update_state(bd);
1562 		bzero(&miext, sizeof (miext));
1563 		miext.dki_media_type = DK_FIXED_DISK;
1564 		miext.dki_lbsize = (1U << bd->d_blkshift);
1565 		miext.dki_pbsize = (1U << bd->d_pblkshift);
1566 		miext.dki_capacity = bd->d_numblks;
1567 
1568 		switch (ddi_model_convert_from(flag & FMODELS)) {
1569 		case DDI_MODEL_ILP32:
1570 			len = sizeof (struct dk_minfo_ext32);
1571 			break;
1572 		default:
1573 			len = sizeof (struct dk_minfo_ext);
1574 			break;
1575 		}
1576 
1577 		if (ddi_copyout(&miext, ptr, len, flag)) {
1578 			return (EFAULT);
1579 		}
1580 		return (0);
1581 	}
1582 	case DKIOCINFO: {
1583 		struct dk_cinfo cinfo;
1584 		bzero(&cinfo, sizeof (cinfo));
1585 		cinfo.dki_ctype = DKC_BLKDEV;
1586 		cinfo.dki_cnum = ddi_get_instance(ddi_get_parent(bd->d_dip));
1587 		(void) snprintf(cinfo.dki_cname, sizeof (cinfo.dki_cname),
1588 		    "%s", ddi_driver_name(ddi_get_parent(bd->d_dip)));
1589 		(void) snprintf(cinfo.dki_dname, sizeof (cinfo.dki_dname),
1590 		    "%s", ddi_driver_name(bd->d_dip));
1591 		cinfo.dki_unit = inst;
1592 		cinfo.dki_flags = DKI_FMTVOL;
1593 		cinfo.dki_partition = part;
1594 		cinfo.dki_maxtransfer = bd->d_maxxfer / DEV_BSIZE;
1595 		cinfo.dki_addr = 0;
1596 		cinfo.dki_slave = 0;
1597 		cinfo.dki_space = 0;
1598 		cinfo.dki_prio = 0;
1599 		cinfo.dki_vec = 0;
1600 		if (ddi_copyout(&cinfo, ptr, sizeof (cinfo), flag)) {
1601 			return (EFAULT);
1602 		}
1603 		return (0);
1604 	}
1605 	case DKIOCREMOVABLE: {
1606 		int i;
1607 		i = bd->d_removable ? 1 : 0;
1608 		if (ddi_copyout(&i, ptr, sizeof (i), flag)) {
1609 			return (EFAULT);
1610 		}
1611 		return (0);
1612 	}
1613 	case DKIOCHOTPLUGGABLE: {
1614 		int i;
1615 		i = bd->d_hotpluggable ? 1 : 0;
1616 		if (ddi_copyout(&i, ptr, sizeof (i), flag)) {
1617 			return (EFAULT);
1618 		}
1619 		return (0);
1620 	}
1621 	case DKIOCREADONLY: {
1622 		int i;
1623 		i = bd->d_rdonly ? 1 : 0;
1624 		if (ddi_copyout(&i, ptr, sizeof (i), flag)) {
1625 			return (EFAULT);
1626 		}
1627 		return (0);
1628 	}
1629 	case DKIOCSOLIDSTATE: {
1630 		int i;
1631 		i = bd->d_ssd ? 1 : 0;
1632 		if (ddi_copyout(&i, ptr, sizeof (i), flag)) {
1633 			return (EFAULT);
1634 		}
1635 		return (0);
1636 	}
1637 	case DKIOCSTATE: {
1638 		enum dkio_state	state;
1639 		if (ddi_copyin(ptr, &state, sizeof (state), flag)) {
1640 			return (EFAULT);
1641 		}
1642 		if ((rv = bd_check_state(bd, &state)) != 0) {
1643 			return (rv);
1644 		}
1645 		if (ddi_copyout(&state, ptr, sizeof (state), flag)) {
1646 			return (EFAULT);
1647 		}
1648 		return (0);
1649 	}
1650 	case DKIOCFLUSHWRITECACHE: {
1651 		struct dk_callback *dkc = NULL;
1652 
1653 		if (flag & FKIOCTL)
1654 			dkc = (void *)arg;
1655 
1656 		rv = bd_flush_write_cache(bd, dkc);
1657 		return (rv);
1658 	}
1659 	case DKIOCFREE: {
1660 		dkioc_free_list_t *dfl = NULL;
1661 
1662 		/*
1663 		 * Check free space support early to avoid copyin/allocation
1664 		 * when unnecessary.
1665 		 */
1666 		if (!CAN_FREESPACE(bd))
1667 			return (ENOTSUP);
1668 
1669 		rv = dfl_copyin(ptr, &dfl, flag, KM_SLEEP);
1670 		if (rv != 0)
1671 			return (rv);
1672 
1673 		/*
1674 		 * bd_free_space() consumes 'dfl'. bd_free_space() will
1675 		 * call dfl_iter() which will normally try to pass dfl through
1676 		 * to bd_free_space_cb() which attaches dfl to the bd_xfer_t
1677 		 * that is then queued for the underlying driver. Once the
1678 		 * driver processes the request, the bd_xfer_t instance is
1679 		 * disposed of, including any attached dkioc_free_list_t.
1680 		 *
1681 		 * If dfl cannot be processed by the underlying driver due to
1682 		 * size or alignment requirements of the driver, dfl_iter()
1683 		 * will replace dfl with one or more new dkioc_free_list_t
1684 		 * instances with the correct alignment and sizes for the driver
1685 		 * (and free the original dkioc_free_list_t).
1686 		 */
1687 		rv = bd_free_space(dev, bd, dfl);
1688 		return (rv);
1689 	}
1690 
1691 	case DKIOC_CANFREE: {
1692 		boolean_t supported = CAN_FREESPACE(bd);
1693 
1694 		if (ddi_copyout(&supported, (void *)arg, sizeof (supported),
1695 		    flag) != 0) {
1696 			return (EFAULT);
1697 		}
1698 
1699 		return (0);
1700 	}
1701 
1702 	default:
1703 		break;
1704 
1705 	}
1706 	return (ENOTTY);
1707 }
1708 
1709 static int
1710 bd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
1711     char *name, caddr_t valuep, int *lengthp)
1712 {
1713 	bd_t	*bd;
1714 
1715 	bd = ddi_get_soft_state(bd_state, ddi_get_instance(dip));
1716 	if (bd == NULL)
1717 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
1718 		    name, valuep, lengthp));
1719 
1720 	return (cmlb_prop_op(bd->d_cmlbh, dev, dip, prop_op, mod_flags, name,
1721 	    valuep, lengthp, BDPART(dev), 0));
1722 }
1723 
1724 
1725 static int
1726 bd_tg_rdwr(dev_info_t *dip, uchar_t cmd, void *bufaddr, diskaddr_t start,
1727     size_t length, void *tg_cookie)
1728 {
1729 	bd_t		*bd;
1730 	buf_t		*bp;
1731 	bd_xfer_impl_t	*xi;
1732 	int		rv;
1733 	int		(*func)(void *, bd_xfer_t *);
1734 	int		kmflag;
1735 
1736 	/*
1737 	 * If we are running in polled mode (such as during dump(9e)
1738 	 * execution), then we cannot sleep for kernel allocations.
1739 	 */
1740 	kmflag = tg_cookie ? KM_NOSLEEP : KM_SLEEP;
1741 
1742 	bd = ddi_get_soft_state(bd_state, ddi_get_instance(dip));
1743 
1744 	if (P2PHASE(length, (1U << bd->d_blkshift)) != 0) {
1745 		/* We can only transfer whole blocks at a time! */
1746 		return (EINVAL);
1747 	}
1748 
1749 	if ((bp = getrbuf(kmflag)) == NULL) {
1750 		return (ENOMEM);
1751 	}
1752 
1753 	switch (cmd) {
1754 	case TG_READ:
1755 		bp->b_flags = B_READ;
1756 		func = bd->d_ops.o_read;
1757 		break;
1758 	case TG_WRITE:
1759 		bp->b_flags = B_WRITE;
1760 		func = bd->d_ops.o_write;
1761 		break;
1762 	default:
1763 		freerbuf(bp);
1764 		return (EINVAL);
1765 	}
1766 
1767 	bp->b_un.b_addr = bufaddr;
1768 	bp->b_bcount = length;
1769 	xi = bd_xfer_alloc(bd, bp, func, kmflag);
1770 	if (xi == NULL) {
1771 		rv = geterror(bp);
1772 		freerbuf(bp);
1773 		return (rv);
1774 	}
1775 	xi->i_flags = tg_cookie ? BD_XFER_POLL : 0;
1776 	xi->i_blkno = start;
1777 	bd_submit(bd, xi);
1778 	(void) biowait(bp);
1779 	rv = geterror(bp);
1780 	freerbuf(bp);
1781 
1782 	return (rv);
1783 }
1784 
1785 static int
1786 bd_tg_getinfo(dev_info_t *dip, int cmd, void *arg, void *tg_cookie)
1787 {
1788 	bd_t		*bd;
1789 
1790 	_NOTE(ARGUNUSED(tg_cookie));
1791 	bd = ddi_get_soft_state(bd_state, ddi_get_instance(dip));
1792 
1793 	switch (cmd) {
1794 	case TG_GETPHYGEOM:
1795 	case TG_GETVIRTGEOM:
1796 		/*
1797 		 * We don't have any "geometry" as such, let cmlb
1798 		 * fabricate something.
1799 		 */
1800 		return (ENOTTY);
1801 
1802 	case TG_GETCAPACITY:
1803 		bd_update_state(bd);
1804 		*(diskaddr_t *)arg = bd->d_numblks;
1805 		return (0);
1806 
1807 	case TG_GETBLOCKSIZE:
1808 		*(uint32_t *)arg = (1U << bd->d_blkshift);
1809 		return (0);
1810 
1811 	case TG_GETATTR:
1812 		/*
1813 		 * It turns out that cmlb really doesn't do much for
1814 		 * non-writable media, but lets make the information
1815 		 * available for it in case it does more in the
1816 		 * future.  (The value is currently used for
1817 		 * triggering special behavior for CD-ROMs.)
1818 		 */
1819 		bd_update_state(bd);
1820 		((tg_attribute_t *)arg)->media_is_writable =
1821 		    bd->d_rdonly ? B_FALSE : B_TRUE;
1822 		((tg_attribute_t *)arg)->media_is_solid_state = bd->d_ssd;
1823 		((tg_attribute_t *)arg)->media_is_rotational = B_FALSE;
1824 		return (0);
1825 
1826 	default:
1827 		return (EINVAL);
1828 	}
1829 }
1830 
1831 
1832 static void
1833 bd_sched(bd_t *bd, bd_queue_t *bq)
1834 {
1835 	bd_xfer_impl_t	*xi;
1836 	struct buf	*bp;
1837 	int		rv;
1838 
1839 	mutex_enter(&bq->q_iomutex);
1840 
1841 	while ((bq->q_qactive < bq->q_qsize) &&
1842 	    ((xi = list_remove_head(&bq->q_waitq)) != NULL)) {
1843 		mutex_enter(&bd->d_ksmutex);
1844 		kstat_waitq_to_runq(bd->d_kiop);
1845 		mutex_exit(&bd->d_ksmutex);
1846 
1847 		bq->q_qactive++;
1848 		list_insert_tail(&bq->q_runq, xi);
1849 
1850 		/*
1851 		 * Submit the job to the driver.  We drop the I/O mutex
1852 		 * so that we can deal with the case where the driver
1853 		 * completion routine calls back into us synchronously.
1854 		 */
1855 
1856 		mutex_exit(&bq->q_iomutex);
1857 
1858 		rv = xi->i_func(bd->d_private, &xi->i_public);
1859 		if (rv != 0) {
1860 			bp = xi->i_bp;
1861 			bioerror(bp, rv);
1862 			biodone(bp);
1863 
1864 			atomic_inc_32(&bd->d_kerr->bd_transerrs.value.ui32);
1865 
1866 			mutex_enter(&bq->q_iomutex);
1867 
1868 			mutex_enter(&bd->d_ksmutex);
1869 			kstat_runq_exit(bd->d_kiop);
1870 			mutex_exit(&bd->d_ksmutex);
1871 
1872 			bq->q_qactive--;
1873 			list_remove(&bq->q_runq, xi);
1874 			bd_xfer_free(xi);
1875 		} else {
1876 			mutex_enter(&bq->q_iomutex);
1877 		}
1878 	}
1879 
1880 	mutex_exit(&bq->q_iomutex);
1881 }
1882 
1883 static void
1884 bd_submit(bd_t *bd, bd_xfer_impl_t *xi)
1885 {
1886 	uint64_t	nv = atomic_inc_64_nv(&bd->d_io_counter);
1887 	unsigned	q = nv % bd->d_qcount;
1888 	bd_queue_t	*bq = &bd->d_queues[q];
1889 
1890 	xi->i_bq = bq;
1891 	xi->i_qnum = q;
1892 
1893 	mutex_enter(&bq->q_iomutex);
1894 
1895 	list_insert_tail(&bq->q_waitq, xi);
1896 
1897 	mutex_enter(&bd->d_ksmutex);
1898 	kstat_waitq_enter(bd->d_kiop);
1899 	mutex_exit(&bd->d_ksmutex);
1900 
1901 	mutex_exit(&bq->q_iomutex);
1902 
1903 	bd_sched(bd, bq);
1904 }
1905 
1906 static void
1907 bd_runq_exit(bd_xfer_impl_t *xi, int err)
1908 {
1909 	bd_t		*bd = xi->i_bd;
1910 	buf_t		*bp = xi->i_bp;
1911 	bd_queue_t	*bq = xi->i_bq;
1912 
1913 	mutex_enter(&bq->q_iomutex);
1914 	bq->q_qactive--;
1915 
1916 	mutex_enter(&bd->d_ksmutex);
1917 	kstat_runq_exit(bd->d_kiop);
1918 	mutex_exit(&bd->d_ksmutex);
1919 
1920 	list_remove(&bq->q_runq, xi);
1921 	mutex_exit(&bq->q_iomutex);
1922 
1923 	if (err == 0) {
1924 		if (bp->b_flags & B_READ) {
1925 			atomic_inc_uint(&bd->d_kiop->reads);
1926 			atomic_add_64((uint64_t *)&bd->d_kiop->nread,
1927 			    bp->b_bcount - xi->i_resid);
1928 		} else {
1929 			atomic_inc_uint(&bd->d_kiop->writes);
1930 			atomic_add_64((uint64_t *)&bd->d_kiop->nwritten,
1931 			    bp->b_bcount - xi->i_resid);
1932 		}
1933 	}
1934 	bd_sched(bd, bq);
1935 }
1936 
1937 static void
1938 bd_dle_sysevent_task(void *arg)
1939 {
1940 	nvlist_t *attr = NULL;
1941 	char *path = NULL;
1942 	bd_t *bd = arg;
1943 	dev_info_t *dip = bd->d_dip;
1944 	size_t n;
1945 
1946 	mutex_enter(&bd->d_dle_mutex);
1947 	bd->d_dle_state &= ~BD_DLE_PENDING;
1948 	bd->d_dle_state |= BD_DLE_RUNNING;
1949 	mutex_exit(&bd->d_dle_mutex);
1950 
1951 	dev_err(dip, CE_NOTE, "!dynamic LUN expansion");
1952 
1953 	if (nvlist_alloc(&attr, NV_UNIQUE_NAME_TYPE, KM_SLEEP) != 0) {
1954 		mutex_enter(&bd->d_dle_mutex);
1955 		bd->d_dle_state &= ~(BD_DLE_RUNNING|BD_DLE_PENDING);
1956 		mutex_exit(&bd->d_dle_mutex);
1957 		return;
1958 	}
1959 
1960 	path = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1961 
1962 	n = snprintf(path, MAXPATHLEN, "/devices");
1963 	(void) ddi_pathname(dip, path + n);
1964 	n = strlen(path);
1965 	n += snprintf(path + n, MAXPATHLEN - n, ":x");
1966 
1967 	for (;;) {
1968 		/*
1969 		 * On receipt of this event, the ZFS sysevent module will scan
1970 		 * active zpools for child vdevs matching this physical path.
1971 		 * In order to catch both whole disk pools and those with an
1972 		 * EFI boot partition, generate separate sysevents for minor
1973 		 * node 'a' and 'b'.
1974 		 */
1975 		for (char c = 'a'; c < 'c'; c++) {
1976 			path[n - 1] = c;
1977 
1978 			if (nvlist_add_string(attr, DEV_PHYS_PATH, path) != 0)
1979 				break;
1980 
1981 			(void) ddi_log_sysevent(dip, DDI_VENDOR_SUNW,
1982 			    EC_DEV_STATUS, ESC_DEV_DLE, attr, NULL, DDI_SLEEP);
1983 		}
1984 
1985 		mutex_enter(&bd->d_dle_mutex);
1986 		if ((bd->d_dle_state & BD_DLE_PENDING) == 0) {
1987 			bd->d_dle_state &= ~BD_DLE_RUNNING;
1988 			mutex_exit(&bd->d_dle_mutex);
1989 			break;
1990 		}
1991 		bd->d_dle_state &= ~BD_DLE_PENDING;
1992 		mutex_exit(&bd->d_dle_mutex);
1993 	}
1994 
1995 	nvlist_free(attr);
1996 	kmem_free(path, MAXPATHLEN);
1997 }
1998 
1999 static void
2000 bd_update_state(bd_t *bd)
2001 {
2002 	enum	dkio_state	state = DKIO_INSERTED;
2003 	boolean_t		docmlb = B_FALSE;
2004 	bd_media_t		media;
2005 
2006 	bzero(&media, sizeof (media));
2007 
2008 	mutex_enter(&bd->d_statemutex);
2009 	if (bd->d_ops.o_media_info(bd->d_private, &media) != 0) {
2010 		bd->d_numblks = 0;
2011 		state = DKIO_EJECTED;
2012 		goto done;
2013 	}
2014 
2015 	if ((media.m_blksize < 512) ||
2016 	    (!ISP2(media.m_blksize)) ||
2017 	    (P2PHASE(bd->d_maxxfer, media.m_blksize))) {
2018 		dev_err(bd->d_dip, CE_WARN, "Invalid media block size (%d)",
2019 		    media.m_blksize);
2020 		/*
2021 		 * We can't use the media, treat it as not present.
2022 		 */
2023 		state = DKIO_EJECTED;
2024 		bd->d_numblks = 0;
2025 		goto done;
2026 	}
2027 
2028 	if (((1U << bd->d_blkshift) != media.m_blksize) ||
2029 	    (bd->d_numblks != media.m_nblks)) {
2030 		/* Device size changed */
2031 		docmlb = B_TRUE;
2032 	}
2033 
2034 	bd->d_blkshift = ddi_ffs(media.m_blksize) - 1;
2035 	bd->d_pblkshift = bd->d_blkshift;
2036 	bd->d_numblks = media.m_nblks;
2037 	bd->d_rdonly = media.m_readonly;
2038 	bd->d_ssd = media.m_solidstate;
2039 
2040 	/*
2041 	 * Only use the supplied physical block size if it is non-zero,
2042 	 * greater or equal to the block size, and a power of 2. Ignore it
2043 	 * if not, it's just informational and we can still use the media.
2044 	 */
2045 	if ((media.m_pblksize != 0) &&
2046 	    (media.m_pblksize >= media.m_blksize) &&
2047 	    (ISP2(media.m_pblksize)))
2048 		bd->d_pblkshift = ddi_ffs(media.m_pblksize) - 1;
2049 
2050 done:
2051 	if (state != bd->d_state) {
2052 		bd->d_state = state;
2053 		cv_broadcast(&bd->d_statecv);
2054 		docmlb = B_TRUE;
2055 	}
2056 	mutex_exit(&bd->d_statemutex);
2057 
2058 	bd->d_kerr->bd_capacity.value.ui64 = bd->d_numblks << bd->d_blkshift;
2059 
2060 	if (docmlb) {
2061 		if (state == DKIO_INSERTED) {
2062 			(void) cmlb_validate(bd->d_cmlbh, 0, 0);
2063 
2064 			mutex_enter(&bd->d_dle_mutex);
2065 			/*
2066 			 * If there is already an event pending, there's
2067 			 * nothing to do; we coalesce multiple events.
2068 			 */
2069 			if ((bd->d_dle_state & BD_DLE_PENDING) == 0) {
2070 				if ((bd->d_dle_state & BD_DLE_RUNNING) == 0) {
2071 					taskq_dispatch_ent(bd_taskq,
2072 					    bd_dle_sysevent_task, bd, 0,
2073 					    &bd->d_dle_ent);
2074 				}
2075 				bd->d_dle_state |= BD_DLE_PENDING;
2076 			}
2077 			mutex_exit(&bd->d_dle_mutex);
2078 		} else {
2079 			cmlb_invalidate(bd->d_cmlbh, 0);
2080 		}
2081 	}
2082 }
2083 
2084 static int
2085 bd_check_state(bd_t *bd, enum dkio_state *state)
2086 {
2087 	clock_t		when;
2088 
2089 	for (;;) {
2090 
2091 		bd_update_state(bd);
2092 
2093 		mutex_enter(&bd->d_statemutex);
2094 
2095 		if (bd->d_state != *state) {
2096 			*state = bd->d_state;
2097 			mutex_exit(&bd->d_statemutex);
2098 			break;
2099 		}
2100 
2101 		when = drv_usectohz(1000000);
2102 		if (cv_reltimedwait_sig(&bd->d_statecv, &bd->d_statemutex,
2103 		    when, TR_CLOCK_TICK) == 0) {
2104 			mutex_exit(&bd->d_statemutex);
2105 			return (EINTR);
2106 		}
2107 
2108 		mutex_exit(&bd->d_statemutex);
2109 	}
2110 
2111 	return (0);
2112 }
2113 
2114 static int
2115 bd_flush_write_cache_done(struct buf *bp)
2116 {
2117 	struct dk_callback *dc = (void *)bp->b_private;
2118 
2119 	(*dc->dkc_callback)(dc->dkc_cookie, geterror(bp));
2120 	kmem_free(dc, sizeof (*dc));
2121 	freerbuf(bp);
2122 	return (0);
2123 }
2124 
2125 static int
2126 bd_flush_write_cache(bd_t *bd, struct dk_callback *dkc)
2127 {
2128 	buf_t			*bp;
2129 	struct dk_callback	*dc;
2130 	bd_xfer_impl_t		*xi;
2131 	int			rv;
2132 
2133 	if (bd->d_ops.o_sync_cache == NULL) {
2134 		return (ENOTSUP);
2135 	}
2136 	if ((bp = getrbuf(KM_SLEEP)) == NULL) {
2137 		return (ENOMEM);
2138 	}
2139 	bp->b_resid = 0;
2140 	bp->b_bcount = 0;
2141 
2142 	xi = bd_xfer_alloc(bd, bp, bd->d_ops.o_sync_cache, KM_SLEEP);
2143 	if (xi == NULL) {
2144 		rv = geterror(bp);
2145 		freerbuf(bp);
2146 		return (rv);
2147 	}
2148 
2149 	/* Make an asynchronous flush, but only if there is a callback */
2150 	if (dkc != NULL && dkc->dkc_callback != NULL) {
2151 		/* Make a private copy of the callback structure */
2152 		dc = kmem_alloc(sizeof (*dc), KM_SLEEP);
2153 		*dc = *dkc;
2154 		bp->b_private = dc;
2155 		bp->b_iodone = bd_flush_write_cache_done;
2156 
2157 		bd_submit(bd, xi);
2158 		return (0);
2159 	}
2160 
2161 	/* In case there is no callback, perform a synchronous flush */
2162 	bd_submit(bd, xi);
2163 	(void) biowait(bp);
2164 	rv = geterror(bp);
2165 	freerbuf(bp);
2166 
2167 	return (rv);
2168 }
2169 
2170 static int
2171 bd_free_space_done(struct buf *bp)
2172 {
2173 	freerbuf(bp);
2174 	return (0);
2175 }
2176 
2177 static int
2178 bd_free_space_cb(dkioc_free_list_t *dfl, void *arg, int kmflag)
2179 {
2180 	bd_t		*bd = arg;
2181 	buf_t		*bp = NULL;
2182 	bd_xfer_impl_t	*xi = NULL;
2183 	boolean_t	sync = DFL_ISSYNC(dfl) ?  B_TRUE : B_FALSE;
2184 	int		rv = 0;
2185 
2186 	bp = getrbuf(KM_SLEEP);
2187 	bp->b_resid = 0;
2188 	bp->b_bcount = 0;
2189 	bp->b_lblkno = 0;
2190 
2191 	xi = bd_xfer_alloc(bd, bp, bd->d_ops.o_free_space, kmflag);
2192 	xi->i_dfl = dfl;
2193 
2194 	if (!sync) {
2195 		bp->b_iodone = bd_free_space_done;
2196 		bd_submit(bd, xi);
2197 		return (0);
2198 	}
2199 
2200 	xi->i_flags |= BD_XFER_POLL;
2201 	bd_submit(bd, xi);
2202 
2203 	(void) biowait(bp);
2204 	rv = geterror(bp);
2205 	freerbuf(bp);
2206 
2207 	return (rv);
2208 }
2209 
2210 static int
2211 bd_free_space(dev_t dev, bd_t *bd, dkioc_free_list_t *dfl)
2212 {
2213 	diskaddr_t p_len, p_offset;
2214 	uint64_t offset_bytes, len_bytes;
2215 	minor_t part = BDPART(dev);
2216 	const uint_t bshift = bd->d_blkshift;
2217 	dkioc_free_info_t dfi = {
2218 		.dfi_bshift = bshift,
2219 		.dfi_align = bd->d_free_align << bshift,
2220 		.dfi_max_bytes = bd->d_max_free_blks << bshift,
2221 		.dfi_max_ext = bd->d_max_free_seg,
2222 		.dfi_max_ext_bytes = bd->d_max_free_seg_blks << bshift,
2223 	};
2224 
2225 	if (cmlb_partinfo(bd->d_cmlbh, part, &p_len, &p_offset, NULL,
2226 	    NULL, 0) != 0) {
2227 		dfl_free(dfl);
2228 		return (ENXIO);
2229 	}
2230 
2231 	/*
2232 	 * bd_ioctl created our own copy of dfl, so we can modify as
2233 	 * necessary
2234 	 */
2235 	offset_bytes = (uint64_t)p_offset << bshift;
2236 	len_bytes = (uint64_t)p_len << bshift;
2237 
2238 	dfl->dfl_offset += offset_bytes;
2239 	if (dfl->dfl_offset < offset_bytes) {
2240 		dfl_free(dfl);
2241 		return (EOVERFLOW);
2242 	}
2243 
2244 	return (dfl_iter(dfl, &dfi, offset_bytes + len_bytes, bd_free_space_cb,
2245 	    bd, KM_SLEEP));
2246 }
2247 
2248 /*
2249  * Nexus support.
2250  */
2251 int
2252 bd_bus_ctl(dev_info_t *dip, dev_info_t *rdip, ddi_ctl_enum_t ctlop,
2253     void *arg, void *result)
2254 {
2255 	bd_handle_t	hdl;
2256 
2257 	switch (ctlop) {
2258 	case DDI_CTLOPS_REPORTDEV:
2259 		cmn_err(CE_CONT, "?Block device: %s@%s, %s%d\n",
2260 		    ddi_node_name(rdip), ddi_get_name_addr(rdip),
2261 		    ddi_driver_name(rdip), ddi_get_instance(rdip));
2262 		return (DDI_SUCCESS);
2263 
2264 	case DDI_CTLOPS_INITCHILD:
2265 		hdl = ddi_get_parent_data((dev_info_t *)arg);
2266 		if (hdl == NULL) {
2267 			return (DDI_NOT_WELL_FORMED);
2268 		}
2269 		ddi_set_name_addr((dev_info_t *)arg, hdl->h_addr);
2270 		return (DDI_SUCCESS);
2271 
2272 	case DDI_CTLOPS_UNINITCHILD:
2273 		ddi_set_name_addr((dev_info_t *)arg, NULL);
2274 		ndi_prop_remove_all((dev_info_t *)arg);
2275 		return (DDI_SUCCESS);
2276 
2277 	default:
2278 		return (ddi_ctlops(dip, rdip, ctlop, arg, result));
2279 	}
2280 }
2281 
2282 /*
2283  * Functions for device drivers.
2284  */
2285 bd_handle_t
2286 bd_alloc_handle(void *private, bd_ops_t *ops, ddi_dma_attr_t *dma, int kmflag)
2287 {
2288 	bd_handle_t	hdl;
2289 
2290 	switch (ops->o_version) {
2291 	case BD_OPS_VERSION_0:
2292 	case BD_OPS_VERSION_1:
2293 	case BD_OPS_VERSION_2:
2294 		break;
2295 
2296 	default:
2297 		/* Unsupported version */
2298 		return (NULL);
2299 	}
2300 
2301 	hdl = kmem_zalloc(sizeof (*hdl), kmflag);
2302 	if (hdl == NULL) {
2303 		return (NULL);
2304 	}
2305 
2306 	switch (ops->o_version) {
2307 	case BD_OPS_VERSION_2:
2308 		hdl->h_ops.o_free_space = ops->o_free_space;
2309 		/*FALLTHRU*/
2310 	case BD_OPS_VERSION_1:
2311 	case BD_OPS_VERSION_0:
2312 		hdl->h_ops.o_drive_info = ops->o_drive_info;
2313 		hdl->h_ops.o_media_info = ops->o_media_info;
2314 		hdl->h_ops.o_devid_init = ops->o_devid_init;
2315 		hdl->h_ops.o_sync_cache = ops->o_sync_cache;
2316 		hdl->h_ops.o_read = ops->o_read;
2317 		hdl->h_ops.o_write = ops->o_write;
2318 		break;
2319 	}
2320 
2321 	hdl->h_dma = dma;
2322 	hdl->h_private = private;
2323 
2324 	return (hdl);
2325 }
2326 
2327 void
2328 bd_free_handle(bd_handle_t hdl)
2329 {
2330 	kmem_free(hdl, sizeof (*hdl));
2331 }
2332 
2333 int
2334 bd_attach_handle(dev_info_t *dip, bd_handle_t hdl)
2335 {
2336 	bd_drive_t	drive = { 0 };
2337 	dev_info_t	*child;
2338 	size_t		len;
2339 
2340 	/*
2341 	 * It's not an error if bd_attach_handle() is called on a handle that
2342 	 * already is attached. We just ignore the request to attach and return.
2343 	 * This way drivers using blkdev don't have to keep track about blkdev
2344 	 * state, they can just call this function to make sure it attached.
2345 	 */
2346 	if (hdl->h_child != NULL) {
2347 		return (DDI_SUCCESS);
2348 	}
2349 
2350 	/* if drivers don't override this, make it assume none */
2351 	drive.d_lun = -1;
2352 	hdl->h_ops.o_drive_info(hdl->h_private, &drive);
2353 
2354 	hdl->h_parent = dip;
2355 	hdl->h_name = "blkdev";
2356 
2357 	/*
2358 	 * Prefer the GUID over the EUI64.
2359 	 */
2360 	if (*(uint64_t *)drive.d_guid != 0 ||
2361 	    *((uint64_t *)drive.d_guid + 1) != 0) {
2362 		len = snprintf(hdl->h_addr, sizeof (hdl->h_addr),
2363 		    "w%02X%02X%02X%02X%02X%02X%02X%02X"
2364 		    "%02X%02X%02X%02X%02X%02X%02X%02X",
2365 		    drive.d_guid[0], drive.d_guid[1], drive.d_guid[2],
2366 		    drive.d_guid[3], drive.d_guid[4], drive.d_guid[5],
2367 		    drive.d_guid[6], drive.d_guid[7], drive.d_guid[8],
2368 		    drive.d_guid[9], drive.d_guid[10], drive.d_guid[11],
2369 		    drive.d_guid[12], drive.d_guid[13], drive.d_guid[14],
2370 		    drive.d_guid[15]);
2371 	} else if (*(uint64_t *)drive.d_eui64 != 0) {
2372 		len = snprintf(hdl->h_addr, sizeof (hdl->h_addr),
2373 		    "w%02X%02X%02X%02X%02X%02X%02X%02X",
2374 		    drive.d_eui64[0], drive.d_eui64[1],
2375 		    drive.d_eui64[2], drive.d_eui64[3],
2376 		    drive.d_eui64[4], drive.d_eui64[5],
2377 		    drive.d_eui64[6], drive.d_eui64[7]);
2378 	} else {
2379 		len = snprintf(hdl->h_addr, sizeof (hdl->h_addr),
2380 		    "%X", drive.d_target);
2381 	}
2382 
2383 	VERIFY(len <= sizeof (hdl->h_addr));
2384 
2385 	if (drive.d_lun >= 0) {
2386 		(void) snprintf(hdl->h_addr + len, sizeof (hdl->h_addr) - len,
2387 		    ",%X", drive.d_lun);
2388 	}
2389 
2390 	if (ndi_devi_alloc(dip, hdl->h_name, (pnode_t)DEVI_SID_NODEID,
2391 	    &child) != NDI_SUCCESS) {
2392 		cmn_err(CE_WARN, "%s%d: unable to allocate node %s@%s",
2393 		    ddi_driver_name(dip), ddi_get_instance(dip),
2394 		    "blkdev", hdl->h_addr);
2395 		return (DDI_FAILURE);
2396 	}
2397 
2398 	ddi_set_parent_data(child, hdl);
2399 	hdl->h_child = child;
2400 
2401 	if (ndi_devi_online(child, 0) != NDI_SUCCESS) {
2402 		cmn_err(CE_WARN, "%s%d: failed bringing node %s@%s online",
2403 		    ddi_driver_name(dip), ddi_get_instance(dip),
2404 		    hdl->h_name, hdl->h_addr);
2405 		(void) ndi_devi_free(child);
2406 		hdl->h_child = NULL;
2407 		return (DDI_FAILURE);
2408 	}
2409 
2410 	return (DDI_SUCCESS);
2411 }
2412 
2413 int
2414 bd_detach_handle(bd_handle_t hdl)
2415 {
2416 	int	rv;
2417 	char	*devnm;
2418 
2419 	/*
2420 	 * It's not an error if bd_detach_handle() is called on a handle that
2421 	 * already is detached. We just ignore the request to detach and return.
2422 	 * This way drivers using blkdev don't have to keep track about blkdev
2423 	 * state, they can just call this function to make sure it detached.
2424 	 */
2425 	if (hdl->h_child == NULL) {
2426 		return (DDI_SUCCESS);
2427 	}
2428 	ndi_devi_enter(hdl->h_parent);
2429 	if (i_ddi_node_state(hdl->h_child) < DS_INITIALIZED) {
2430 		rv = ddi_remove_child(hdl->h_child, 0);
2431 	} else {
2432 		devnm = kmem_alloc(MAXNAMELEN + 1, KM_SLEEP);
2433 		(void) ddi_deviname(hdl->h_child, devnm);
2434 		(void) devfs_clean(hdl->h_parent, devnm + 1, DV_CLEAN_FORCE);
2435 		rv = ndi_devi_unconfig_one(hdl->h_parent, devnm + 1, NULL,
2436 		    NDI_DEVI_REMOVE | NDI_UNCONFIG);
2437 		kmem_free(devnm, MAXNAMELEN + 1);
2438 	}
2439 	if (rv == 0) {
2440 		hdl->h_child = NULL;
2441 	}
2442 
2443 	ndi_devi_exit(hdl->h_parent);
2444 	return (rv == NDI_SUCCESS ? DDI_SUCCESS : DDI_FAILURE);
2445 }
2446 
2447 void
2448 bd_xfer_done(bd_xfer_t *xfer, int err)
2449 {
2450 	bd_xfer_impl_t	*xi = (void *)xfer;
2451 	buf_t		*bp = xi->i_bp;
2452 	int		rv = DDI_SUCCESS;
2453 	bd_t		*bd = xi->i_bd;
2454 	size_t		len;
2455 
2456 	if (err != 0) {
2457 		bd_runq_exit(xi, err);
2458 		atomic_inc_32(&bd->d_kerr->bd_harderrs.value.ui32);
2459 
2460 		bp->b_resid += xi->i_resid;
2461 		bd_xfer_free(xi);
2462 		bioerror(bp, err);
2463 		biodone(bp);
2464 		return;
2465 	}
2466 
2467 	xi->i_cur_win++;
2468 	xi->i_resid -= xi->i_len;
2469 
2470 	if (xi->i_resid == 0) {
2471 		/* Job completed succcessfully! */
2472 		bd_runq_exit(xi, 0);
2473 
2474 		bd_xfer_free(xi);
2475 		biodone(bp);
2476 		return;
2477 	}
2478 
2479 	xi->i_blkno += xi->i_nblks;
2480 
2481 	if (bd->d_use_dma) {
2482 		/* More transfer still pending... advance to next DMA window. */
2483 		rv = ddi_dma_getwin(xi->i_dmah, xi->i_cur_win,
2484 		    &xi->i_offset, &len, &xi->i_dmac, &xi->i_ndmac);
2485 	} else {
2486 		/* Advance memory window. */
2487 		xi->i_kaddr += xi->i_len;
2488 		xi->i_offset += xi->i_len;
2489 		len = min(bp->b_bcount - xi->i_offset, bd->d_maxxfer);
2490 	}
2491 
2492 
2493 	if ((rv != DDI_SUCCESS) ||
2494 	    (P2PHASE(len, (1U << xi->i_blkshift)) != 0)) {
2495 		bd_runq_exit(xi, EFAULT);
2496 
2497 		bp->b_resid += xi->i_resid;
2498 		bd_xfer_free(xi);
2499 		bioerror(bp, EFAULT);
2500 		biodone(bp);
2501 		return;
2502 	}
2503 	xi->i_len = len;
2504 	xi->i_nblks = len >> xi->i_blkshift;
2505 
2506 	/* Submit next window to hardware. */
2507 	rv = xi->i_func(bd->d_private, &xi->i_public);
2508 	if (rv != 0) {
2509 		bd_runq_exit(xi, rv);
2510 
2511 		atomic_inc_32(&bd->d_kerr->bd_transerrs.value.ui32);
2512 
2513 		bp->b_resid += xi->i_resid;
2514 		bd_xfer_free(xi);
2515 		bioerror(bp, rv);
2516 		biodone(bp);
2517 	}
2518 }
2519 
2520 void
2521 bd_error(bd_xfer_t *xfer, int error)
2522 {
2523 	bd_xfer_impl_t	*xi = (void *)xfer;
2524 	bd_t		*bd = xi->i_bd;
2525 
2526 	switch (error) {
2527 	case BD_ERR_MEDIA:
2528 		atomic_inc_32(&bd->d_kerr->bd_rq_media_err.value.ui32);
2529 		break;
2530 	case BD_ERR_NTRDY:
2531 		atomic_inc_32(&bd->d_kerr->bd_rq_ntrdy_err.value.ui32);
2532 		break;
2533 	case BD_ERR_NODEV:
2534 		atomic_inc_32(&bd->d_kerr->bd_rq_nodev_err.value.ui32);
2535 		break;
2536 	case BD_ERR_RECOV:
2537 		atomic_inc_32(&bd->d_kerr->bd_rq_recov_err.value.ui32);
2538 		break;
2539 	case BD_ERR_ILLRQ:
2540 		atomic_inc_32(&bd->d_kerr->bd_rq_illrq_err.value.ui32);
2541 		break;
2542 	case BD_ERR_PFA:
2543 		atomic_inc_32(&bd->d_kerr->bd_rq_pfa_err.value.ui32);
2544 		break;
2545 	default:
2546 		cmn_err(CE_PANIC, "bd_error: unknown error type %d", error);
2547 		break;
2548 	}
2549 }
2550 
2551 void
2552 bd_state_change(bd_handle_t hdl)
2553 {
2554 	bd_t		*bd;
2555 
2556 	if ((bd = hdl->h_bd) != NULL) {
2557 		bd_update_state(bd);
2558 	}
2559 }
2560 
2561 void
2562 bd_mod_init(struct dev_ops *devops)
2563 {
2564 	static struct bus_ops bd_bus_ops = {
2565 		BUSO_REV,		/* busops_rev */
2566 		nullbusmap,		/* bus_map */
2567 		NULL,			/* bus_get_intrspec (OBSOLETE) */
2568 		NULL,			/* bus_add_intrspec (OBSOLETE) */
2569 		NULL,			/* bus_remove_intrspec (OBSOLETE) */
2570 		i_ddi_map_fault,	/* bus_map_fault */
2571 		NULL,			/* bus_dma_map (OBSOLETE) */
2572 		ddi_dma_allochdl,	/* bus_dma_allochdl */
2573 		ddi_dma_freehdl,	/* bus_dma_freehdl */
2574 		ddi_dma_bindhdl,	/* bus_dma_bindhdl */
2575 		ddi_dma_unbindhdl,	/* bus_dma_unbindhdl */
2576 		ddi_dma_flush,		/* bus_dma_flush */
2577 		ddi_dma_win,		/* bus_dma_win */
2578 		ddi_dma_mctl,		/* bus_dma_ctl */
2579 		bd_bus_ctl,		/* bus_ctl */
2580 		ddi_bus_prop_op,	/* bus_prop_op */
2581 		NULL,			/* bus_get_eventcookie */
2582 		NULL,			/* bus_add_eventcall */
2583 		NULL,			/* bus_remove_eventcall */
2584 		NULL,			/* bus_post_event */
2585 		NULL,			/* bus_intr_ctl (OBSOLETE) */
2586 		NULL,			/* bus_config */
2587 		NULL,			/* bus_unconfig */
2588 		NULL,			/* bus_fm_init */
2589 		NULL,			/* bus_fm_fini */
2590 		NULL,			/* bus_fm_access_enter */
2591 		NULL,			/* bus_fm_access_exit */
2592 		NULL,			/* bus_power */
2593 		NULL,			/* bus_intr_op */
2594 	};
2595 
2596 	devops->devo_bus_ops = &bd_bus_ops;
2597 
2598 	/*
2599 	 * NB: The device driver is free to supply its own
2600 	 * character entry device support.
2601 	 */
2602 }
2603 
2604 void
2605 bd_mod_fini(struct dev_ops *devops)
2606 {
2607 	devops->devo_bus_ops = NULL;
2608 }
2609