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