xref: /titanic_52/usr/src/uts/sun4v/io/vds.c (revision d92a527c473246e5c750ae6c33ecd2f242a5bf1f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * Virtual disk server
29  */
30 
31 
32 #include <sys/types.h>
33 #include <sys/conf.h>
34 #include <sys/crc32.h>
35 #include <sys/ddi.h>
36 #include <sys/dkio.h>
37 #include <sys/file.h>
38 #include <sys/fs/hsfs_isospec.h>
39 #include <sys/mdeg.h>
40 #include <sys/mhd.h>
41 #include <sys/modhash.h>
42 #include <sys/note.h>
43 #include <sys/pathname.h>
44 #include <sys/sdt.h>
45 #include <sys/sunddi.h>
46 #include <sys/sunldi.h>
47 #include <sys/sysmacros.h>
48 #include <sys/vio_common.h>
49 #include <sys/vio_util.h>
50 #include <sys/vdsk_mailbox.h>
51 #include <sys/vdsk_common.h>
52 #include <sys/vtoc.h>
53 #include <sys/vfs.h>
54 #include <sys/stat.h>
55 #include <sys/scsi/impl/uscsi.h>
56 #include <sys/ontrap.h>
57 #include <vm/seg_map.h>
58 
59 #define	ONE_MEGABYTE	(1ULL << 20)
60 #define	ONE_GIGABYTE	(1ULL << 30)
61 #define	ONE_TERABYTE	(1ULL << 40)
62 
63 /* Virtual disk server initialization flags */
64 #define	VDS_LDI			0x01
65 #define	VDS_MDEG		0x02
66 
67 /* Virtual disk server tunable parameters */
68 #define	VDS_RETRIES		5
69 #define	VDS_LDC_DELAY		1000 /* 1 msecs */
70 #define	VDS_DEV_DELAY		10000000 /* 10 secs */
71 #define	VDS_NCHAINS		32
72 
73 /* Identification parameters for MD, synthetic dkio(7i) structures, etc. */
74 #define	VDS_NAME		"virtual-disk-server"
75 
76 #define	VD_NAME			"vd"
77 #define	VD_VOLUME_NAME		"vdisk"
78 #define	VD_ASCIILABEL		"Virtual Disk"
79 
80 #define	VD_CHANNEL_ENDPOINT	"channel-endpoint"
81 #define	VD_ID_PROP		"id"
82 #define	VD_BLOCK_DEVICE_PROP	"vds-block-device"
83 #define	VD_BLOCK_DEVICE_OPTS	"vds-block-device-opts"
84 #define	VD_REG_PROP		"reg"
85 
86 /* Virtual disk initialization flags */
87 #define	VD_DISK_READY		0x01
88 #define	VD_LOCKING		0x02
89 #define	VD_LDC			0x04
90 #define	VD_DRING		0x08
91 #define	VD_SID			0x10
92 #define	VD_SEQ_NUM		0x20
93 #define	VD_SETUP_ERROR		0x40
94 
95 /* Number of backup labels */
96 #define	VD_DSKIMG_NUM_BACKUP	5
97 
98 /* Timeout for SCSI I/O */
99 #define	VD_SCSI_RDWR_TIMEOUT	30	/* 30 secs */
100 
101 /*
102  * Default number of threads for the I/O queue. In many cases, we will not
103  * receive more than 8 I/O requests at the same time. However there are
104  * cases (for example during the OS installation) where we can have a lot
105  * more (up to the limit of the DRing size).
106  */
107 #define	VD_IOQ_NTHREADS		8
108 
109 /* Maximum number of logical partitions */
110 #define	VD_MAXPART	(NDKMAP + 1)
111 
112 /*
113  * By Solaris convention, slice/partition 2 represents the entire disk;
114  * unfortunately, this convention does not appear to be codified.
115  */
116 #define	VD_ENTIRE_DISK_SLICE	2
117 
118 /* Logical block address for EFI */
119 #define	VD_EFI_LBA_GPT		1	/* LBA of the GPT */
120 #define	VD_EFI_LBA_GPE		2	/* LBA of the GPE */
121 
122 /*
123  * Flags defining the behavior for flushing asynchronous writes used to
124  * performed some write I/O requests.
125  *
126  * The VD_AWFLUSH_IMMEDIATE enables immediate flushing of asynchronous
127  * writes. This ensures that data are committed to the backend when the I/O
128  * request reply is sent to the guest domain so this prevents any data to
129  * be lost in case a service domain unexpectedly crashes.
130  *
131  * The flag VD_AWFLUSH_DEFER indicates that flushing is deferred to another
132  * thread while the request is immediatly marked as completed. In that case,
133  * a guest domain can a receive a reply that its write request is completed
134  * while data haven't been flushed to disk yet.
135  *
136  * Flags VD_AWFLUSH_IMMEDIATE and VD_AWFLUSH_DEFER are mutually exclusive.
137  */
138 #define	VD_AWFLUSH_IMMEDIATE	0x01	/* immediate flushing */
139 #define	VD_AWFLUSH_DEFER	0x02	/* defer flushing */
140 #define	VD_AWFLUSH_GROUP	0x04	/* group requests before flushing */
141 
142 /* Driver types */
143 typedef enum vd_driver {
144 	VD_DRIVER_UNKNOWN = 0,	/* driver type unknown  */
145 	VD_DRIVER_DISK,		/* disk driver */
146 	VD_DRIVER_VOLUME	/* volume driver */
147 } vd_driver_t;
148 
149 #define	VD_DRIVER_NAME_LEN	64
150 
151 #define	VDS_NUM_DRIVERS	(sizeof (vds_driver_types) / sizeof (vd_driver_type_t))
152 
153 typedef struct vd_driver_type {
154 	char name[VD_DRIVER_NAME_LEN];	/* driver name */
155 	vd_driver_t type;		/* driver type (disk or volume) */
156 } vd_driver_type_t;
157 
158 /*
159  * There is no reliable way to determine if a device is representing a disk
160  * or a volume, especially with pseudo devices. So we maintain a list of well
161  * known drivers and the type of device they represent (either a disk or a
162  * volume).
163  *
164  * The list can be extended by adding a "driver-type-list" entry in vds.conf
165  * with the following syntax:
166  *
167  * 	driver-type-list="<driver>:<type>", ... ,"<driver>:<type>";
168  *
169  * Where:
170  *	<driver> is the name of a driver (limited to 64 characters)
171  *	<type> is either the string "disk" or "volume"
172  *
173  * Invalid entries in "driver-type-list" will be ignored.
174  *
175  * For example, the following line in vds.conf:
176  *
177  * 	driver-type-list="foo:disk","bar:volume";
178  *
179  * defines that "foo" is a disk driver, and driver "bar" is a volume driver.
180  *
181  * When a list is defined in vds.conf, it is checked before the built-in list
182  * (vds_driver_types[]) so that any definition from this list can be overriden
183  * using vds.conf.
184  */
185 vd_driver_type_t vds_driver_types[] = {
186 	{ "dad",	VD_DRIVER_DISK },	/* Solaris */
187 	{ "did",	VD_DRIVER_DISK },	/* Sun Cluster */
188 	{ "emcp",	VD_DRIVER_DISK },	/* EMC Powerpath */
189 	{ "lofi",	VD_DRIVER_VOLUME },	/* Solaris */
190 	{ "md",		VD_DRIVER_VOLUME },	/* Solaris - SVM */
191 	{ "sd",		VD_DRIVER_DISK },	/* Solaris */
192 	{ "ssd",	VD_DRIVER_DISK },	/* Solaris */
193 	{ "vdc",	VD_DRIVER_DISK },	/* Solaris */
194 	{ "vxdmp",	VD_DRIVER_DISK },	/* Veritas */
195 	{ "vxio",	VD_DRIVER_VOLUME },	/* Veritas - VxVM */
196 	{ "zfs",	VD_DRIVER_VOLUME }	/* Solaris */
197 };
198 
199 /* Return a cpp token as a string */
200 #define	STRINGIZE(token)	#token
201 
202 /*
203  * Print a message prefixed with the current function name to the message log
204  * (and optionally to the console for verbose boots); these macros use cpp's
205  * concatenation of string literals and C99 variable-length-argument-list
206  * macros
207  */
208 #define	PRN(...)	_PRN("?%s():  "__VA_ARGS__, "")
209 #define	_PRN(format, ...)					\
210 	cmn_err(CE_CONT, format"%s", __func__, __VA_ARGS__)
211 
212 /* Return a pointer to the "i"th vdisk dring element */
213 #define	VD_DRING_ELEM(i)	((vd_dring_entry_t *)(void *)	\
214 	    (vd->dring + (i)*vd->descriptor_size))
215 
216 /* Return the virtual disk client's type as a string (for use in messages) */
217 #define	VD_CLIENT(vd)							\
218 	(((vd)->xfer_mode == VIO_DESC_MODE) ? "in-band client" :	\
219 	    (((vd)->xfer_mode == VIO_DRING_MODE_V1_0) ? "dring client" :    \
220 		(((vd)->xfer_mode == 0) ? "null client" :		\
221 		    "unsupported client")))
222 
223 /* Read disk label from a disk image */
224 #define	VD_DSKIMG_LABEL_READ(vd, labelp) \
225 	vd_dskimg_rw(vd, VD_SLICE_NONE, VD_OP_BREAD, (caddr_t)labelp, \
226 	    0, sizeof (struct dk_label))
227 
228 /* Write disk label to a disk image */
229 #define	VD_DSKIMG_LABEL_WRITE(vd, labelp)	\
230 	vd_dskimg_rw(vd, VD_SLICE_NONE, VD_OP_BWRITE, (caddr_t)labelp, \
231 	    0, sizeof (struct dk_label))
232 
233 /* Identify if a backend is a disk image */
234 #define	VD_DSKIMG(vd)	((vd)->vdisk_type == VD_DISK_TYPE_DISK &&	\
235 	((vd)->file || (vd)->volume))
236 
237 /* Next index in a write queue */
238 #define	VD_WRITE_INDEX_NEXT(vd, id)		\
239 	((((id) + 1) >= vd->dring_len)? 0 : (id) + 1)
240 
241 /* Message for disk access rights reset failure */
242 #define	VD_RESET_ACCESS_FAILURE_MSG \
243 	"Fail to reset disk access rights for disk %s"
244 
245 /*
246  * Specification of an MD node passed to the MDEG to filter any
247  * 'vport' nodes that do not belong to the specified node. This
248  * template is copied for each vds instance and filled in with
249  * the appropriate 'cfg-handle' value before being passed to the MDEG.
250  */
251 static mdeg_prop_spec_t	vds_prop_template[] = {
252 	{ MDET_PROP_STR,	"name",		VDS_NAME },
253 	{ MDET_PROP_VAL,	"cfg-handle",	NULL },
254 	{ MDET_LIST_END,	NULL, 		NULL }
255 };
256 
257 #define	VDS_SET_MDEG_PROP_INST(specp, val) (specp)[1].ps_val = (val);
258 
259 /*
260  * Matching criteria passed to the MDEG to register interest
261  * in changes to 'virtual-device-port' nodes identified by their
262  * 'id' property.
263  */
264 static md_prop_match_t	vd_prop_match[] = {
265 	{ MDET_PROP_VAL,	VD_ID_PROP },
266 	{ MDET_LIST_END,	NULL }
267 };
268 
269 static mdeg_node_match_t vd_match = {"virtual-device-port",
270 				    vd_prop_match};
271 
272 /*
273  * Options for the VD_BLOCK_DEVICE_OPTS property.
274  */
275 #define	VD_OPT_RDONLY		0x1	/* read-only  */
276 #define	VD_OPT_SLICE		0x2	/* single slice */
277 #define	VD_OPT_EXCLUSIVE	0x4	/* exclusive access */
278 
279 #define	VD_OPTION_NLEN	128
280 
281 typedef struct vd_option {
282 	char vdo_name[VD_OPTION_NLEN];
283 	uint64_t vdo_value;
284 } vd_option_t;
285 
286 vd_option_t vd_bdev_options[] = {
287 	{ "ro",		VD_OPT_RDONLY },
288 	{ "slice", 	VD_OPT_SLICE },
289 	{ "excl",	VD_OPT_EXCLUSIVE }
290 };
291 
292 /* Debugging macros */
293 #ifdef DEBUG
294 
295 static int	vd_msglevel = 0;
296 
297 #define	PR0 if (vd_msglevel > 0)	PRN
298 #define	PR1 if (vd_msglevel > 1)	PRN
299 #define	PR2 if (vd_msglevel > 2)	PRN
300 
301 #define	VD_DUMP_DRING_ELEM(elem)					\
302 	PR0("dst:%x op:%x st:%u nb:%lx addr:%lx ncook:%u\n",		\
303 	    elem->hdr.dstate,						\
304 	    elem->payload.operation,					\
305 	    elem->payload.status,					\
306 	    elem->payload.nbytes,					\
307 	    elem->payload.addr,						\
308 	    elem->payload.ncookies);
309 
310 char *
311 vd_decode_state(int state)
312 {
313 	char *str;
314 
315 #define	CASE_STATE(_s)	case _s: str = #_s; break;
316 
317 	switch (state) {
318 	CASE_STATE(VD_STATE_INIT)
319 	CASE_STATE(VD_STATE_VER)
320 	CASE_STATE(VD_STATE_ATTR)
321 	CASE_STATE(VD_STATE_DRING)
322 	CASE_STATE(VD_STATE_RDX)
323 	CASE_STATE(VD_STATE_DATA)
324 	default: str = "unknown"; break;
325 	}
326 
327 #undef CASE_STATE
328 
329 	return (str);
330 }
331 
332 void
333 vd_decode_tag(vio_msg_t *msg)
334 {
335 	char *tstr, *sstr, *estr;
336 
337 #define	CASE_TYPE(_s)	case _s: tstr = #_s; break;
338 
339 	switch (msg->tag.vio_msgtype) {
340 	CASE_TYPE(VIO_TYPE_CTRL)
341 	CASE_TYPE(VIO_TYPE_DATA)
342 	CASE_TYPE(VIO_TYPE_ERR)
343 	default: tstr = "unknown"; break;
344 	}
345 
346 #undef CASE_TYPE
347 
348 #define	CASE_SUBTYPE(_s) case _s: sstr = #_s; break;
349 
350 	switch (msg->tag.vio_subtype) {
351 	CASE_SUBTYPE(VIO_SUBTYPE_INFO)
352 	CASE_SUBTYPE(VIO_SUBTYPE_ACK)
353 	CASE_SUBTYPE(VIO_SUBTYPE_NACK)
354 	default: sstr = "unknown"; break;
355 	}
356 
357 #undef CASE_SUBTYPE
358 
359 #define	CASE_ENV(_s)	case _s: estr = #_s; break;
360 
361 	switch (msg->tag.vio_subtype_env) {
362 	CASE_ENV(VIO_VER_INFO)
363 	CASE_ENV(VIO_ATTR_INFO)
364 	CASE_ENV(VIO_DRING_REG)
365 	CASE_ENV(VIO_DRING_UNREG)
366 	CASE_ENV(VIO_RDX)
367 	CASE_ENV(VIO_PKT_DATA)
368 	CASE_ENV(VIO_DESC_DATA)
369 	CASE_ENV(VIO_DRING_DATA)
370 	default: estr = "unknown"; break;
371 	}
372 
373 #undef CASE_ENV
374 
375 	PR1("(%x/%x/%x) message : (%s/%s/%s)",
376 	    msg->tag.vio_msgtype, msg->tag.vio_subtype,
377 	    msg->tag.vio_subtype_env, tstr, sstr, estr);
378 }
379 
380 #else	/* !DEBUG */
381 
382 #define	PR0(...)
383 #define	PR1(...)
384 #define	PR2(...)
385 
386 #define	VD_DUMP_DRING_ELEM(elem)
387 
388 #define	vd_decode_state(_s)	(NULL)
389 #define	vd_decode_tag(_s)	(NULL)
390 
391 #endif	/* DEBUG */
392 
393 
394 /*
395  * Soft state structure for a vds instance
396  */
397 typedef struct vds {
398 	uint_t		initialized;	/* driver inst initialization flags */
399 	dev_info_t	*dip;		/* driver inst devinfo pointer */
400 	ldi_ident_t	ldi_ident;	/* driver's identifier for LDI */
401 	mod_hash_t	*vd_table;	/* table of virtual disks served */
402 	mdeg_node_spec_t *ispecp;	/* mdeg node specification */
403 	mdeg_handle_t	mdeg;		/* handle for MDEG operations  */
404 	vd_driver_type_t *driver_types;	/* extra driver types (from vds.conf) */
405 	int 		num_drivers;	/* num of extra driver types */
406 } vds_t;
407 
408 /*
409  * Types of descriptor-processing tasks
410  */
411 typedef enum vd_task_type {
412 	VD_NONFINAL_RANGE_TASK,	/* task for intermediate descriptor in range */
413 	VD_FINAL_RANGE_TASK,	/* task for last in a range of descriptors */
414 } vd_task_type_t;
415 
416 /*
417  * Structure describing the task for processing a descriptor
418  */
419 typedef struct vd_task {
420 	struct vd		*vd;		/* vd instance task is for */
421 	vd_task_type_t		type;		/* type of descriptor task */
422 	int			index;		/* dring elem index for task */
423 	vio_msg_t		*msg;		/* VIO message task is for */
424 	size_t			msglen;		/* length of message content */
425 	vd_dring_payload_t	*request;	/* request task will perform */
426 	struct buf		buf;		/* buf(9s) for I/O request */
427 	ldc_mem_handle_t	mhdl;		/* task memory handle */
428 	int			status;		/* status of processing task */
429 	int	(*completef)(struct vd_task *task); /* completion func ptr */
430 	uint32_t		write_index;	/* index in the write_queue */
431 } vd_task_t;
432 
433 /*
434  * Soft state structure for a virtual disk instance
435  */
436 typedef struct vd {
437 	uint64_t		id;		/* vdisk id */
438 	uint_t			initialized;	/* vdisk initialization flags */
439 	uint64_t		operations;	/* bitmask of VD_OPs exported */
440 	vio_ver_t		version;	/* ver negotiated with client */
441 	vds_t			*vds;		/* server for this vdisk */
442 	ddi_taskq_t		*startq;	/* queue for I/O start tasks */
443 	ddi_taskq_t		*completionq;	/* queue for completion tasks */
444 	ddi_taskq_t		*ioq;		/* queue for I/O */
445 	uint32_t		write_index;	/* next write index */
446 	buf_t			**write_queue;	/* queue for async writes */
447 	ldi_handle_t		ldi_handle[V_NUMPAR];	/* LDI slice handles */
448 	char			device_path[MAXPATHLEN + 1]; /* vdisk device */
449 	dev_t			dev[V_NUMPAR];	/* dev numbers for slices */
450 	int			open_flags;	/* open flags */
451 	uint_t			nslices;	/* number of slices we export */
452 	size_t			vdisk_size;	/* number of blocks in vdisk */
453 	size_t			vdisk_block_size; /* size of each vdisk block */
454 	vd_disk_type_t		vdisk_type;	/* slice or entire disk */
455 	vd_disk_label_t		vdisk_label;	/* EFI or VTOC label */
456 	vd_media_t		vdisk_media;	/* media type of backing dev. */
457 	boolean_t		is_atapi_dev;	/* Is this an IDE CD-ROM dev? */
458 	ushort_t		max_xfer_sz;	/* max xfer size in DEV_BSIZE */
459 	size_t			block_size;	/* blk size of actual device */
460 	boolean_t		volume;		/* is vDisk backed by volume */
461 	boolean_t		zvol;		/* is vDisk backed by a zvol */
462 	boolean_t		file;		/* is vDisk backed by a file? */
463 	boolean_t		scsi;		/* is vDisk backed by scsi? */
464 	vnode_t			*file_vnode;	/* file vnode */
465 	size_t			dskimg_size;	/* size of disk image */
466 	ddi_devid_t		dskimg_devid;	/* devid for disk image */
467 	int			efi_reserved;	/* EFI reserved slice */
468 	caddr_t			flabel;		/* fake label for slice type */
469 	uint_t			flabel_size;	/* fake label size */
470 	uint_t			flabel_limit;	/* limit of the fake label */
471 	struct dk_geom		dk_geom;	/* synthetic for slice type */
472 	struct extvtoc		vtoc;		/* synthetic for slice type */
473 	vd_slice_t		slices[VD_MAXPART]; /* logical partitions */
474 	boolean_t		ownership;	/* disk ownership status */
475 	ldc_status_t		ldc_state;	/* LDC connection state */
476 	ldc_handle_t		ldc_handle;	/* handle for LDC comm */
477 	size_t			max_msglen;	/* largest LDC message len */
478 	vd_state_t		state;		/* client handshake state */
479 	uint8_t			xfer_mode;	/* transfer mode with client */
480 	uint32_t		sid;		/* client's session ID */
481 	uint64_t		seq_num;	/* message sequence number */
482 	uint64_t		dring_ident;	/* identifier of dring */
483 	ldc_dring_handle_t	dring_handle;	/* handle for dring ops */
484 	uint32_t		descriptor_size;	/* num bytes in desc */
485 	uint32_t		dring_len;	/* number of dring elements */
486 	uint8_t			dring_mtype;	/* dring mem map type */
487 	caddr_t			dring;		/* address of dring */
488 	caddr_t			vio_msgp;	/* vio msg staging buffer */
489 	vd_task_t		inband_task;	/* task for inband descriptor */
490 	vd_task_t		*dring_task;	/* tasks dring elements */
491 
492 	kmutex_t		lock;		/* protects variables below */
493 	boolean_t		enabled;	/* is vdisk enabled? */
494 	boolean_t		reset_state;	/* reset connection state? */
495 	boolean_t		reset_ldc;	/* reset LDC channel? */
496 } vd_t;
497 
498 /*
499  * Macros to manipulate the fake label (flabel) for single slice disks.
500  *
501  * If we fake a VTOC label then the fake label consists of only one block
502  * containing the VTOC label (struct dk_label).
503  *
504  * If we fake an EFI label then the fake label consists of a blank block
505  * followed by a GPT (efi_gpt_t) and a GPE (efi_gpe_t).
506  *
507  */
508 #define	VD_LABEL_VTOC_SIZE					\
509 	P2ROUNDUP(sizeof (struct dk_label), DEV_BSIZE)
510 
511 #define	VD_LABEL_EFI_SIZE					\
512 	P2ROUNDUP(DEV_BSIZE + sizeof (efi_gpt_t) + 		\
513 	    sizeof (efi_gpe_t) * VD_MAXPART, DEV_BSIZE)
514 
515 #define	VD_LABEL_VTOC(vd)	\
516 		((struct dk_label *)(void *)((vd)->flabel))
517 
518 #define	VD_LABEL_EFI_GPT(vd)	\
519 		((efi_gpt_t *)(void *)((vd)->flabel + DEV_BSIZE))
520 #define	VD_LABEL_EFI_GPE(vd)	\
521 		((efi_gpe_t *)(void *)((vd)->flabel + DEV_BSIZE + \
522 		sizeof (efi_gpt_t)))
523 
524 
525 typedef struct vds_operation {
526 	char	*namep;
527 	uint8_t	operation;
528 	int	(*start)(vd_task_t *task);
529 	int	(*complete)(vd_task_t *task);
530 } vds_operation_t;
531 
532 typedef struct vd_ioctl {
533 	uint8_t		operation;		/* vdisk operation */
534 	const char	*operation_name;	/* vdisk operation name */
535 	size_t		nbytes;			/* size of operation buffer */
536 	int		cmd;			/* corresponding ioctl cmd */
537 	const char	*cmd_name;		/* ioctl cmd name */
538 	void		*arg;			/* ioctl cmd argument */
539 	/* convert input vd_buf to output ioctl_arg */
540 	int		(*copyin)(void *vd_buf, size_t, void *ioctl_arg);
541 	/* convert input ioctl_arg to output vd_buf */
542 	void		(*copyout)(void *ioctl_arg, void *vd_buf);
543 	/* write is true if the operation writes any data to the backend */
544 	boolean_t	write;
545 } vd_ioctl_t;
546 
547 /* Define trivial copyin/copyout conversion function flag */
548 #define	VD_IDENTITY_IN	((int (*)(void *, size_t, void *))-1)
549 #define	VD_IDENTITY_OUT	((void (*)(void *, void *))-1)
550 
551 
552 static int	vds_ldc_retries = VDS_RETRIES;
553 static int	vds_ldc_delay = VDS_LDC_DELAY;
554 static int	vds_dev_retries = VDS_RETRIES;
555 static int	vds_dev_delay = VDS_DEV_DELAY;
556 static void	*vds_state;
557 
558 static short	vd_scsi_rdwr_timeout = VD_SCSI_RDWR_TIMEOUT;
559 static int	vd_scsi_debug = USCSI_SILENT;
560 
561 /*
562  * Number of threads in the taskq handling vdisk I/O. This can be set up to
563  * the size of the DRing which is the maximum number of I/O we can receive
564  * in parallel. Note that using a high number of threads can improve performance
565  * but this is going to consume a lot of resources if there are many vdisks.
566  */
567 static int	vd_ioq_nthreads = VD_IOQ_NTHREADS;
568 
569 /*
570  * Tunable to define the behavior for flushing asynchronous writes used to
571  * performed some write I/O requests. The default behavior is to group as
572  * much asynchronous writes as possible and to flush them immediatly.
573  *
574  * If the tunable is set to 0 then explicit flushing is disabled. In that
575  * case, data will be flushed by traditional mechanism (like fsflush) but
576  * this might not happen immediatly.
577  *
578  */
579 static int	vd_awflush = VD_AWFLUSH_IMMEDIATE | VD_AWFLUSH_GROUP;
580 
581 /*
582  * Tunable to define the behavior of the service domain if the vdisk server
583  * fails to reset disk exclusive access when a LDC channel is reset. When a
584  * LDC channel is reset the vdisk server will try to reset disk exclusive
585  * access by releasing any SCSI-2 reservation or resetting the disk. If these
586  * actions fail then the default behavior (vd_reset_access_failure = 0) is to
587  * print a warning message. This default behavior can be changed by setting
588  * the vd_reset_access_failure variable to A_REBOOT (= 0x1) and that will
589  * cause the service domain to reboot, or A_DUMP (= 0x5) and that will cause
590  * the service domain to panic. In both cases, the reset of the service domain
591  * should trigger a reset SCSI buses and hopefully clear any SCSI-2 reservation.
592  */
593 static int 	vd_reset_access_failure = 0;
594 
595 /*
596  * Tunable for backward compatibility. When this variable is set to B_TRUE,
597  * all disk volumes (ZFS, SVM, VxvM volumes) will be exported as single
598  * slice disks whether or not they have the "slice" option set. This is
599  * to provide a simple backward compatibility mechanism when upgrading
600  * the vds driver and using a domain configuration created before the
601  * "slice" option was available.
602  */
603 static boolean_t vd_volume_force_slice = B_FALSE;
604 
605 /*
606  * The label of disk images created with some earlier versions of the virtual
607  * disk software is not entirely correct and have an incorrect v_sanity field
608  * (usually 0) instead of VTOC_SANE. This creates a compatibility problem with
609  * these images because we are now validating that the disk label (and the
610  * sanity) is correct when a disk image is opened.
611  *
612  * This tunable is set to false to not validate the sanity field and ensure
613  * compatibility. If the tunable is set to true, we will do a strict checking
614  * of the sanity but this can create compatibility problems with old disk
615  * images.
616  */
617 static boolean_t vd_dskimg_validate_sanity = B_FALSE;
618 
619 /*
620  * Enables the use of LDC_DIRECT_MAP when mapping in imported descriptor rings.
621  */
622 static boolean_t vd_direct_mapped_drings = B_TRUE;
623 
624 /*
625  * When a backend is exported as a single-slice disk then we entirely fake
626  * its disk label. So it can be exported either with a VTOC label or with
627  * an EFI label. If vd_slice_label is set to VD_DISK_LABEL_VTOC then all
628  * single-slice disks will be exported with a VTOC label; and if it is set
629  * to VD_DISK_LABEL_EFI then all single-slice disks will be exported with
630  * an EFI label.
631  *
632  * If vd_slice_label is set to VD_DISK_LABEL_UNK and the backend is a disk
633  * or volume device then it will be exported with the same type of label as
634  * defined on the device. Otherwise if the backend is a file then it will
635  * exported with the disk label type set in the vd_file_slice_label variable.
636  *
637  * Note that if the backend size is greater than 1TB then it will always be
638  * exported with an EFI label no matter what the setting is.
639  */
640 static vd_disk_label_t vd_slice_label = VD_DISK_LABEL_UNK;
641 
642 static vd_disk_label_t vd_file_slice_label = VD_DISK_LABEL_VTOC;
643 
644 /*
645  * Tunable for backward compatibility. If this variable is set to B_TRUE then
646  * single-slice disks are exported as disks with only one slice instead of
647  * faking a complete disk partitioning.
648  */
649 static boolean_t vd_slice_single_slice = B_FALSE;
650 
651 /*
652  * Supported protocol version pairs, from highest (newest) to lowest (oldest)
653  *
654  * Each supported major version should appear only once, paired with (and only
655  * with) its highest supported minor version number (as the protocol requires
656  * supporting all lower minor version numbers as well)
657  */
658 static const vio_ver_t	vds_version[] = {{1, 1}};
659 static const size_t	vds_num_versions =
660     sizeof (vds_version)/sizeof (vds_version[0]);
661 
662 static void vd_free_dring_task(vd_t *vdp);
663 static int vd_setup_vd(vd_t *vd);
664 static int vd_setup_single_slice_disk(vd_t *vd);
665 static int vd_setup_slice_image(vd_t *vd);
666 static int vd_setup_disk_image(vd_t *vd);
667 static int vd_backend_check_size(vd_t *vd);
668 static boolean_t vd_enabled(vd_t *vd);
669 static ushort_t vd_lbl2cksum(struct dk_label *label);
670 static int vd_dskimg_validate_geometry(vd_t *vd);
671 static boolean_t vd_dskimg_is_iso_image(vd_t *vd);
672 static void vd_set_exported_operations(vd_t *vd);
673 static void vd_reset_access(vd_t *vd);
674 static int vd_backend_ioctl(vd_t *vd, int cmd, caddr_t arg);
675 static int vds_efi_alloc_and_read(vd_t *, efi_gpt_t **, efi_gpe_t **);
676 static void vds_efi_free(vd_t *, efi_gpt_t *, efi_gpe_t *);
677 static void vds_driver_types_free(vds_t *vds);
678 static void vd_vtocgeom_to_label(struct extvtoc *vtoc, struct dk_geom *geom,
679     struct dk_label *label);
680 static void vd_label_to_vtocgeom(struct dk_label *label, struct extvtoc *vtoc,
681     struct dk_geom *geom);
682 static boolean_t vd_slice_geom_isvalid(vd_t *vd, struct dk_geom *geom);
683 static boolean_t vd_slice_vtoc_isvalid(vd_t *vd, struct extvtoc *vtoc);
684 
685 extern int is_pseudo_device(dev_info_t *);
686 
687 /*
688  * Function:
689  *	vd_get_readable_size
690  *
691  * Description:
692  * 	Convert a given size in bytes to a human readable format in
693  * 	kilobytes, megabytes, gigabytes or terabytes.
694  *
695  * Parameters:
696  *	full_size	- the size to convert in bytes.
697  *	size		- the converted size.
698  *	unit		- the unit of the converted size: 'K' (kilobyte),
699  *			  'M' (Megabyte), 'G' (Gigabyte), 'T' (Terabyte).
700  *
701  * Return Code:
702  *	none
703  */
704 static void
705 vd_get_readable_size(size_t full_size, size_t *size, char *unit)
706 {
707 	if (full_size < (1ULL << 20)) {
708 		*size = full_size >> 10;
709 		*unit = 'K'; /* Kilobyte */
710 	} else if (full_size < (1ULL << 30)) {
711 		*size = full_size >> 20;
712 		*unit = 'M'; /* Megabyte */
713 	} else if (full_size < (1ULL << 40)) {
714 		*size = full_size >> 30;
715 		*unit = 'G'; /* Gigabyte */
716 	} else {
717 		*size = full_size >> 40;
718 		*unit = 'T'; /* Terabyte */
719 	}
720 }
721 
722 /*
723  * Function:
724  *	vd_dskimg_io_params
725  *
726  * Description:
727  * 	Convert virtual disk I/O parameters (slice, block, length) to
728  *	(offset, length) relative to the disk image and according to
729  *	the virtual disk partitioning.
730  *
731  * Parameters:
732  *	vd		- disk on which the operation is performed.
733  *	slice		- slice to which is the I/O parameters apply.
734  *			  VD_SLICE_NONE indicates that parameters are
735  *			  are relative to the entire virtual disk.
736  *	blkp		- pointer to the starting block relative to the
737  *			  slice; return the starting block relative to
738  *			  the disk image.
739  *	lenp		- pointer to the number of bytes requested; return
740  *			  the number of bytes that can effectively be used.
741  *
742  * Return Code:
743  *	0		- I/O parameters have been successfully converted;
744  *			  blkp and lenp point to the converted values.
745  *	ENODATA		- no data are available for the given I/O parameters;
746  *			  This occurs if the starting block is past the limit
747  *			  of the slice.
748  *	EINVAL		- I/O parameters are invalid.
749  */
750 static int
751 vd_dskimg_io_params(vd_t *vd, int slice, size_t *blkp, size_t *lenp)
752 {
753 	size_t blk = *blkp;
754 	size_t len = *lenp;
755 	size_t offset, maxlen;
756 
757 	ASSERT(vd->file || VD_DSKIMG(vd));
758 	ASSERT(len > 0);
759 
760 	/*
761 	 * If a file is exported as a slice then we don't care about the vtoc.
762 	 * In that case, the vtoc is a fake mainly to make newfs happy and we
763 	 * handle any I/O as a raw disk access so that we can have access to the
764 	 * entire backend.
765 	 */
766 	if (vd->vdisk_type == VD_DISK_TYPE_SLICE || slice == VD_SLICE_NONE) {
767 		/* raw disk access */
768 		offset = blk * DEV_BSIZE;
769 		if (offset >= vd->dskimg_size) {
770 			/* offset past the end of the disk */
771 			PR0("offset (0x%lx) >= size (0x%lx)",
772 			    offset, vd->dskimg_size);
773 			return (ENODATA);
774 		}
775 		maxlen = vd->dskimg_size - offset;
776 	} else {
777 		ASSERT(slice >= 0 && slice < V_NUMPAR);
778 
779 		/*
780 		 * v1.0 vDisk clients depended on the server not verifying
781 		 * the label of a unformatted disk.  This "feature" is
782 		 * maintained for backward compatibility but all versions
783 		 * from v1.1 onwards must do the right thing.
784 		 */
785 		if (vd->vdisk_label == VD_DISK_LABEL_UNK &&
786 		    vio_ver_is_supported(vd->version, 1, 1)) {
787 			(void) vd_dskimg_validate_geometry(vd);
788 			if (vd->vdisk_label == VD_DISK_LABEL_UNK) {
789 				PR0("Unknown disk label, can't do I/O "
790 				    "from slice %d", slice);
791 				return (EINVAL);
792 			}
793 		}
794 
795 		if (vd->vdisk_label == VD_DISK_LABEL_VTOC) {
796 			ASSERT(vd->vtoc.v_sectorsz == DEV_BSIZE);
797 		} else {
798 			ASSERT(vd->vdisk_label == VD_DISK_LABEL_EFI);
799 			ASSERT(vd->vdisk_block_size == DEV_BSIZE);
800 		}
801 
802 		if (blk >= vd->slices[slice].nblocks) {
803 			/* address past the end of the slice */
804 			PR0("req_addr (0x%lx) >= psize (0x%lx)",
805 			    blk, vd->slices[slice].nblocks);
806 			return (ENODATA);
807 		}
808 
809 		offset = (vd->slices[slice].start + blk) * DEV_BSIZE;
810 		maxlen = (vd->slices[slice].nblocks - blk) * DEV_BSIZE;
811 	}
812 
813 	/*
814 	 * If the requested size is greater than the size
815 	 * of the partition, truncate the read/write.
816 	 */
817 	if (len > maxlen) {
818 		PR0("I/O size truncated to %lu bytes from %lu bytes",
819 		    maxlen, len);
820 		len = maxlen;
821 	}
822 
823 	/*
824 	 * We have to ensure that we are reading/writing into the mmap
825 	 * range. If we have a partial disk image (e.g. an image of
826 	 * s0 instead s2) the system can try to access slices that
827 	 * are not included into the disk image.
828 	 */
829 	if ((offset + len) > vd->dskimg_size) {
830 		PR0("offset + nbytes (0x%lx + 0x%lx) > "
831 		    "dskimg_size (0x%lx)", offset, len, vd->dskimg_size);
832 		return (EINVAL);
833 	}
834 
835 	*blkp = offset / DEV_BSIZE;
836 	*lenp = len;
837 
838 	return (0);
839 }
840 
841 /*
842  * Function:
843  *	vd_dskimg_rw
844  *
845  * Description:
846  * 	Read or write to a disk image. It handles the case where the disk
847  *	image is a file or a volume exported as a full disk or a file
848  *	exported as single-slice disk. Read or write to volumes exported as
849  *	single slice disks are done by directly using the ldi interface.
850  *
851  * Parameters:
852  *	vd		- disk on which the operation is performed.
853  *	slice		- slice on which the operation is performed,
854  *			  VD_SLICE_NONE indicates that the operation
855  *			  is done using an absolute disk offset.
856  *	operation	- operation to execute: read (VD_OP_BREAD) or
857  *			  write (VD_OP_BWRITE).
858  *	data		- buffer where data are read to or written from.
859  *	blk		- starting block for the operation.
860  *	len		- number of bytes to read or write.
861  *
862  * Return Code:
863  *	n >= 0		- success, n indicates the number of bytes read
864  *			  or written.
865  *	-1		- error.
866  */
867 static ssize_t
868 vd_dskimg_rw(vd_t *vd, int slice, int operation, caddr_t data, size_t offset,
869     size_t len)
870 {
871 	ssize_t resid;
872 	struct buf buf;
873 	int status;
874 
875 	ASSERT(vd->file || VD_DSKIMG(vd));
876 	ASSERT(len > 0);
877 
878 	if ((status = vd_dskimg_io_params(vd, slice, &offset, &len)) != 0)
879 		return ((status == ENODATA)? 0: -1);
880 
881 	if (vd->volume) {
882 
883 		bioinit(&buf);
884 		buf.b_flags	= B_BUSY |
885 		    ((operation == VD_OP_BREAD)? B_READ : B_WRITE);
886 		buf.b_bcount	= len;
887 		buf.b_lblkno	= offset;
888 		buf.b_edev 	= vd->dev[0];
889 		buf.b_un.b_addr = data;
890 
891 		/*
892 		 * We use ldi_strategy() and not ldi_read()/ldi_write() because
893 		 * the read/write functions of the underlying driver may try to
894 		 * lock pages of the data buffer, and this requires the data
895 		 * buffer to be kmem_alloc'ed (and not allocated on the stack).
896 		 *
897 		 * Also using ldi_strategy() ensures that writes are immediatly
898 		 * commited and not cached as this may be the case with
899 		 * ldi_write() (for example with a ZFS volume).
900 		 */
901 		if (ldi_strategy(vd->ldi_handle[0], &buf) != 0) {
902 			biofini(&buf);
903 			return (-1);
904 		}
905 
906 		if (biowait(&buf) != 0) {
907 			biofini(&buf);
908 			return (-1);
909 		}
910 
911 		resid = buf.b_resid;
912 		biofini(&buf);
913 
914 		ASSERT(resid <= len);
915 		return (len - resid);
916 	}
917 
918 	ASSERT(vd->file);
919 
920 	status = vn_rdwr((operation == VD_OP_BREAD)? UIO_READ : UIO_WRITE,
921 	    vd->file_vnode, data, len, offset * DEV_BSIZE, UIO_SYSSPACE, FSYNC,
922 	    RLIM64_INFINITY, kcred, &resid);
923 
924 	if (status != 0)
925 		return (-1);
926 
927 	return (len);
928 }
929 
930 /*
931  * Function:
932  *	vd_build_default_label
933  *
934  * Description:
935  *	Return a default label for a given disk size. This is used when the disk
936  *	does not have a valid VTOC so that the user can get a valid default
937  *	configuration. The default label has all slice sizes set to 0 (except
938  *	slice 2 which is the entire disk) to force the user to write a valid
939  *	label onto the disk image.
940  *
941  * Parameters:
942  *	disk_size	- the disk size in bytes
943  *	label		- the returned default label.
944  *
945  * Return Code:
946  *	none.
947  */
948 static void
949 vd_build_default_label(size_t disk_size, struct dk_label *label)
950 {
951 	size_t size;
952 	char unit;
953 
954 	bzero(label, sizeof (struct dk_label));
955 
956 	/*
957 	 * Ideally we would like the cylinder size (nsect * nhead) to be the
958 	 * same whatever the disk size is. That way the VTOC label could be
959 	 * easily updated in case the disk size is increased (keeping the
960 	 * same cylinder size allows to preserve the existing partitioning
961 	 * when updating the VTOC label). But it is not possible to have
962 	 * a fixed cylinder size and to cover all disk size.
963 	 *
964 	 * So we define different cylinder sizes depending on the disk size.
965 	 * The cylinder size is chosen so that we don't have too few cylinders
966 	 * for a small disk image, or so many on a big disk image that you
967 	 * waste space for backup superblocks or cylinder group structures.
968 	 * Also we must have a resonable number of cylinders and sectors so
969 	 * that newfs can run using default values.
970 	 *
971 	 *	+-----------+--------+---------+--------+
972 	 *	| disk_size |  < 2MB | 2MB-4GB | >= 8GB |
973 	 *	+-----------+--------+---------+--------+
974 	 *	| nhead	    |	 1   |	   1   |    96  |
975 	 *	| nsect	    |  200   |   600   |   768  |
976 	 *	+-----------+--------+---------+--------+
977 	 *
978 	 * Other parameters are computed from these values:
979 	 *
980 	 * 	pcyl = disk_size / (nhead * nsect * 512)
981 	 * 	acyl = (pcyl > 2)? 2 : 0
982 	 * 	ncyl = pcyl - acyl
983 	 *
984 	 * The maximum number of cylinder is 65535 so this allows to define a
985 	 * geometry for a disk size up to 65535 * 96 * 768 * 512 = 2.24 TB
986 	 * which is more than enough to cover the maximum size allowed by the
987 	 * extended VTOC format (2TB).
988 	 */
989 
990 	if (disk_size >= 8 * ONE_GIGABYTE) {
991 
992 		label->dkl_nhead = 96;
993 		label->dkl_nsect = 768;
994 
995 	} else if (disk_size >= 2 * ONE_MEGABYTE) {
996 
997 		label->dkl_nhead = 1;
998 		label->dkl_nsect = 600;
999 
1000 	} else {
1001 
1002 		label->dkl_nhead = 1;
1003 		label->dkl_nsect = 200;
1004 	}
1005 
1006 	label->dkl_pcyl = disk_size /
1007 	    (label->dkl_nsect * label->dkl_nhead * DEV_BSIZE);
1008 
1009 	if (label->dkl_pcyl == 0)
1010 		label->dkl_pcyl = 1;
1011 
1012 	label->dkl_acyl = 0;
1013 
1014 	if (label->dkl_pcyl > 2)
1015 		label->dkl_acyl = 2;
1016 
1017 	label->dkl_ncyl = label->dkl_pcyl - label->dkl_acyl;
1018 	label->dkl_write_reinstruct = 0;
1019 	label->dkl_read_reinstruct = 0;
1020 	label->dkl_rpm = 7200;
1021 	label->dkl_apc = 0;
1022 	label->dkl_intrlv = 0;
1023 
1024 	PR0("requested disk size: %ld bytes\n", disk_size);
1025 	PR0("setup: ncyl=%d nhead=%d nsec=%d\n", label->dkl_pcyl,
1026 	    label->dkl_nhead, label->dkl_nsect);
1027 	PR0("provided disk size: %ld bytes\n", (uint64_t)
1028 	    (label->dkl_pcyl * label->dkl_nhead *
1029 	    label->dkl_nsect * DEV_BSIZE));
1030 
1031 	vd_get_readable_size(disk_size, &size, &unit);
1032 
1033 	/*
1034 	 * We must have a correct label name otherwise format(1m) will
1035 	 * not recognized the disk as labeled.
1036 	 */
1037 	(void) snprintf(label->dkl_asciilabel, LEN_DKL_ASCII,
1038 	    "SUN-DiskImage-%ld%cB cyl %d alt %d hd %d sec %d",
1039 	    size, unit,
1040 	    label->dkl_ncyl, label->dkl_acyl, label->dkl_nhead,
1041 	    label->dkl_nsect);
1042 
1043 	/* default VTOC */
1044 	label->dkl_vtoc.v_version = V_EXTVERSION;
1045 	label->dkl_vtoc.v_nparts = V_NUMPAR;
1046 	label->dkl_vtoc.v_sanity = VTOC_SANE;
1047 	label->dkl_vtoc.v_part[VD_ENTIRE_DISK_SLICE].p_tag = V_BACKUP;
1048 	label->dkl_map[VD_ENTIRE_DISK_SLICE].dkl_cylno = 0;
1049 	label->dkl_map[VD_ENTIRE_DISK_SLICE].dkl_nblk = label->dkl_ncyl *
1050 	    label->dkl_nhead * label->dkl_nsect;
1051 	label->dkl_magic = DKL_MAGIC;
1052 	label->dkl_cksum = vd_lbl2cksum(label);
1053 }
1054 
1055 /*
1056  * Function:
1057  *	vd_dskimg_set_vtoc
1058  *
1059  * Description:
1060  *	Set the vtoc of a disk image by writing the label and backup
1061  *	labels into the disk image backend.
1062  *
1063  * Parameters:
1064  *	vd		- disk on which the operation is performed.
1065  *	label		- the data to be written.
1066  *
1067  * Return Code:
1068  *	0		- success.
1069  *	n > 0		- error, n indicates the errno code.
1070  */
1071 static int
1072 vd_dskimg_set_vtoc(vd_t *vd, struct dk_label *label)
1073 {
1074 	size_t blk, sec, cyl, head, cnt;
1075 
1076 	ASSERT(VD_DSKIMG(vd));
1077 
1078 	if (VD_DSKIMG_LABEL_WRITE(vd, label) < 0) {
1079 		PR0("fail to write disk label");
1080 		return (EIO);
1081 	}
1082 
1083 	/*
1084 	 * Backup labels are on the last alternate cylinder's
1085 	 * first five odd sectors.
1086 	 */
1087 	if (label->dkl_acyl == 0) {
1088 		PR0("no alternate cylinder, can not store backup labels");
1089 		return (0);
1090 	}
1091 
1092 	cyl = label->dkl_ncyl  + label->dkl_acyl - 1;
1093 	head = label->dkl_nhead - 1;
1094 
1095 	blk = (cyl * ((label->dkl_nhead * label->dkl_nsect) - label->dkl_apc)) +
1096 	    (head * label->dkl_nsect);
1097 
1098 	/*
1099 	 * Write the backup labels. Make sure we don't try to write past
1100 	 * the last cylinder.
1101 	 */
1102 	sec = 1;
1103 
1104 	for (cnt = 0; cnt < VD_DSKIMG_NUM_BACKUP; cnt++) {
1105 
1106 		if (sec >= label->dkl_nsect) {
1107 			PR0("not enough sector to store all backup labels");
1108 			return (0);
1109 		}
1110 
1111 		if (vd_dskimg_rw(vd, VD_SLICE_NONE, VD_OP_BWRITE,
1112 		    (caddr_t)label, blk + sec, sizeof (struct dk_label)) < 0) {
1113 			PR0("error writing backup label at block %lu\n",
1114 			    blk + sec);
1115 			return (EIO);
1116 		}
1117 
1118 		PR1("wrote backup label at block %lu\n", blk + sec);
1119 
1120 		sec += 2;
1121 	}
1122 
1123 	return (0);
1124 }
1125 
1126 /*
1127  * Function:
1128  *	vd_dskimg_get_devid_block
1129  *
1130  * Description:
1131  *	Return the block number where the device id is stored.
1132  *
1133  * Parameters:
1134  *	vd		- disk on which the operation is performed.
1135  *	blkp		- pointer to the block number
1136  *
1137  * Return Code:
1138  *	0		- success
1139  *	ENOSPC		- disk has no space to store a device id
1140  */
1141 static int
1142 vd_dskimg_get_devid_block(vd_t *vd, size_t *blkp)
1143 {
1144 	diskaddr_t spc, head, cyl;
1145 
1146 	ASSERT(VD_DSKIMG(vd));
1147 
1148 	if (vd->vdisk_label == VD_DISK_LABEL_UNK) {
1149 		/*
1150 		 * If no label is defined we don't know where to find
1151 		 * a device id.
1152 		 */
1153 		return (ENOSPC);
1154 	}
1155 
1156 	if (vd->vdisk_label == VD_DISK_LABEL_EFI) {
1157 		/*
1158 		 * For an EFI disk, the devid is at the beginning of
1159 		 * the reserved slice
1160 		 */
1161 		if (vd->efi_reserved == -1) {
1162 			PR0("EFI disk has no reserved slice");
1163 			return (ENOSPC);
1164 		}
1165 
1166 		*blkp = vd->slices[vd->efi_reserved].start;
1167 		return (0);
1168 	}
1169 
1170 	ASSERT(vd->vdisk_label == VD_DISK_LABEL_VTOC);
1171 
1172 	/* this geometry doesn't allow us to have a devid */
1173 	if (vd->dk_geom.dkg_acyl < 2) {
1174 		PR0("not enough alternate cylinder available for devid "
1175 		    "(acyl=%u)", vd->dk_geom.dkg_acyl);
1176 		return (ENOSPC);
1177 	}
1178 
1179 	/* the devid is in on the track next to the last cylinder */
1180 	cyl = vd->dk_geom.dkg_ncyl + vd->dk_geom.dkg_acyl - 2;
1181 	spc = vd->dk_geom.dkg_nhead * vd->dk_geom.dkg_nsect;
1182 	head = vd->dk_geom.dkg_nhead - 1;
1183 
1184 	*blkp = (cyl * (spc - vd->dk_geom.dkg_apc)) +
1185 	    (head * vd->dk_geom.dkg_nsect) + 1;
1186 
1187 	return (0);
1188 }
1189 
1190 /*
1191  * Return the checksum of a disk block containing an on-disk devid.
1192  */
1193 static uint_t
1194 vd_dkdevid2cksum(struct dk_devid *dkdevid)
1195 {
1196 	uint_t chksum, *ip;
1197 	int i;
1198 
1199 	chksum = 0;
1200 	ip = (void *)dkdevid;
1201 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int)); i++)
1202 		chksum ^= ip[i];
1203 
1204 	return (chksum);
1205 }
1206 
1207 /*
1208  * Function:
1209  *	vd_dskimg_read_devid
1210  *
1211  * Description:
1212  *	Read the device id stored on a disk image.
1213  *
1214  * Parameters:
1215  *	vd		- disk on which the operation is performed.
1216  *	devid		- the return address of the device ID.
1217  *
1218  * Return Code:
1219  *	0		- success
1220  *	EIO		- I/O error while trying to access the disk image
1221  *	EINVAL		- no valid device id was found
1222  *	ENOSPC		- disk has no space to store a device id
1223  */
1224 static int
1225 vd_dskimg_read_devid(vd_t *vd, ddi_devid_t *devid)
1226 {
1227 	struct dk_devid *dkdevid;
1228 	size_t blk;
1229 	uint_t chksum;
1230 	int status, sz;
1231 
1232 	if ((status = vd_dskimg_get_devid_block(vd, &blk)) != 0)
1233 		return (status);
1234 
1235 	dkdevid = kmem_zalloc(DEV_BSIZE, KM_SLEEP);
1236 
1237 	/* get the devid */
1238 	if ((vd_dskimg_rw(vd, VD_SLICE_NONE, VD_OP_BREAD, (caddr_t)dkdevid, blk,
1239 	    DEV_BSIZE)) < 0) {
1240 		PR0("error reading devid block at %lu", blk);
1241 		status = EIO;
1242 		goto done;
1243 	}
1244 
1245 	/* validate the revision */
1246 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
1247 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
1248 		PR0("invalid devid found at block %lu (bad revision)", blk);
1249 		status = EINVAL;
1250 		goto done;
1251 	}
1252 
1253 	/* compute checksum */
1254 	chksum = vd_dkdevid2cksum(dkdevid);
1255 
1256 	/* compare the checksums */
1257 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
1258 		PR0("invalid devid found at block %lu (bad checksum)", blk);
1259 		status = EINVAL;
1260 		goto done;
1261 	}
1262 
1263 	/* validate the device id */
1264 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
1265 		PR0("invalid devid found at block %lu", blk);
1266 		status = EINVAL;
1267 		goto done;
1268 	}
1269 
1270 	PR1("devid read at block %lu", blk);
1271 
1272 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
1273 	*devid = kmem_alloc(sz, KM_SLEEP);
1274 	bcopy(&dkdevid->dkd_devid, *devid, sz);
1275 
1276 done:
1277 	kmem_free(dkdevid, DEV_BSIZE);
1278 	return (status);
1279 
1280 }
1281 
1282 /*
1283  * Function:
1284  *	vd_dskimg_write_devid
1285  *
1286  * Description:
1287  *	Write a device id into disk image.
1288  *
1289  * Parameters:
1290  *	vd		- disk on which the operation is performed.
1291  *	devid		- the device ID to store.
1292  *
1293  * Return Code:
1294  *	0		- success
1295  *	EIO		- I/O error while trying to access the disk image
1296  *	ENOSPC		- disk has no space to store a device id
1297  */
1298 static int
1299 vd_dskimg_write_devid(vd_t *vd, ddi_devid_t devid)
1300 {
1301 	struct dk_devid *dkdevid;
1302 	uint_t chksum;
1303 	size_t blk;
1304 	int status;
1305 
1306 	if (devid == NULL) {
1307 		/* nothing to write */
1308 		return (0);
1309 	}
1310 
1311 	if ((status = vd_dskimg_get_devid_block(vd, &blk)) != 0)
1312 		return (status);
1313 
1314 	dkdevid = kmem_zalloc(DEV_BSIZE, KM_SLEEP);
1315 
1316 	/* set revision */
1317 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
1318 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
1319 
1320 	/* copy devid */
1321 	bcopy(devid, &dkdevid->dkd_devid, ddi_devid_sizeof(devid));
1322 
1323 	/* compute checksum */
1324 	chksum = vd_dkdevid2cksum(dkdevid);
1325 
1326 	/* set checksum */
1327 	DKD_FORMCHKSUM(chksum, dkdevid);
1328 
1329 	/* store the devid */
1330 	if ((status = vd_dskimg_rw(vd, VD_SLICE_NONE, VD_OP_BWRITE,
1331 	    (caddr_t)dkdevid, blk, DEV_BSIZE)) < 0) {
1332 		PR0("Error writing devid block at %lu", blk);
1333 		status = EIO;
1334 	} else {
1335 		PR1("devid written at block %lu", blk);
1336 		status = 0;
1337 	}
1338 
1339 	kmem_free(dkdevid, DEV_BSIZE);
1340 	return (status);
1341 }
1342 
1343 /*
1344  * Function:
1345  *	vd_do_scsi_rdwr
1346  *
1347  * Description:
1348  * 	Read or write to a SCSI disk using an absolute disk offset.
1349  *
1350  * Parameters:
1351  *	vd		- disk on which the operation is performed.
1352  *	operation	- operation to execute: read (VD_OP_BREAD) or
1353  *			  write (VD_OP_BWRITE).
1354  *	data		- buffer where data are read to or written from.
1355  *	blk		- starting block for the operation.
1356  *	len		- number of bytes to read or write.
1357  *
1358  * Return Code:
1359  *	0		- success
1360  *	n != 0		- error.
1361  */
1362 static int
1363 vd_do_scsi_rdwr(vd_t *vd, int operation, caddr_t data, size_t blk, size_t len)
1364 {
1365 	struct uscsi_cmd ucmd;
1366 	union scsi_cdb cdb;
1367 	int nsectors, nblk;
1368 	int max_sectors;
1369 	int status, rval;
1370 
1371 	ASSERT(!vd->file);
1372 	ASSERT(!vd->volume);
1373 	ASSERT(vd->vdisk_block_size > 0);
1374 
1375 	max_sectors = vd->max_xfer_sz;
1376 	nblk = (len / vd->vdisk_block_size);
1377 
1378 	if (len % vd->vdisk_block_size != 0)
1379 		return (EINVAL);
1380 
1381 	/*
1382 	 * Build and execute the uscsi ioctl.  We build a group0, group1
1383 	 * or group4 command as necessary, since some targets
1384 	 * do not support group1 commands.
1385 	 */
1386 	while (nblk) {
1387 
1388 		bzero(&ucmd, sizeof (ucmd));
1389 		bzero(&cdb, sizeof (cdb));
1390 
1391 		nsectors = (max_sectors < nblk) ? max_sectors : nblk;
1392 
1393 		/*
1394 		 * Some of the optical drives on sun4v machines are ATAPI
1395 		 * devices which use Group 1 Read/Write commands so we need
1396 		 * to explicitly check a flag which is set when a domain
1397 		 * is bound.
1398 		 */
1399 		if (blk < (2 << 20) && nsectors <= 0xff && !vd->is_atapi_dev) {
1400 			FORMG0ADDR(&cdb, blk);
1401 			FORMG0COUNT(&cdb, (uchar_t)nsectors);
1402 			ucmd.uscsi_cdblen = CDB_GROUP0;
1403 		} else if (blk > 0xffffffff) {
1404 			FORMG4LONGADDR(&cdb, blk);
1405 			FORMG4COUNT(&cdb, nsectors);
1406 			ucmd.uscsi_cdblen = CDB_GROUP4;
1407 			cdb.scc_cmd |= SCMD_GROUP4;
1408 		} else {
1409 			FORMG1ADDR(&cdb, blk);
1410 			FORMG1COUNT(&cdb, nsectors);
1411 			ucmd.uscsi_cdblen = CDB_GROUP1;
1412 			cdb.scc_cmd |= SCMD_GROUP1;
1413 		}
1414 		ucmd.uscsi_cdb = (caddr_t)&cdb;
1415 		ucmd.uscsi_bufaddr = data;
1416 		ucmd.uscsi_buflen = nsectors * vd->block_size;
1417 		ucmd.uscsi_timeout = vd_scsi_rdwr_timeout;
1418 		/*
1419 		 * Set flags so that the command is isolated from normal
1420 		 * commands and no error message is printed.
1421 		 */
1422 		ucmd.uscsi_flags = USCSI_ISOLATE | USCSI_SILENT;
1423 
1424 		if (operation == VD_OP_BREAD) {
1425 			cdb.scc_cmd |= SCMD_READ;
1426 			ucmd.uscsi_flags |= USCSI_READ;
1427 		} else {
1428 			cdb.scc_cmd |= SCMD_WRITE;
1429 		}
1430 
1431 		status = ldi_ioctl(vd->ldi_handle[VD_ENTIRE_DISK_SLICE],
1432 		    USCSICMD, (intptr_t)&ucmd, (vd->open_flags | FKIOCTL),
1433 		    kcred, &rval);
1434 
1435 		if (status == 0)
1436 			status = ucmd.uscsi_status;
1437 
1438 		if (status != 0)
1439 			break;
1440 
1441 		/*
1442 		 * Check if partial DMA breakup is required. If so, reduce
1443 		 * the request size by half and retry the last request.
1444 		 */
1445 		if (ucmd.uscsi_resid == ucmd.uscsi_buflen) {
1446 			max_sectors >>= 1;
1447 			if (max_sectors <= 0) {
1448 				status = EIO;
1449 				break;
1450 			}
1451 			continue;
1452 		}
1453 
1454 		if (ucmd.uscsi_resid != 0) {
1455 			status = EIO;
1456 			break;
1457 		}
1458 
1459 		blk += nsectors;
1460 		nblk -= nsectors;
1461 		data += nsectors * vd->vdisk_block_size; /* SECSIZE */
1462 	}
1463 
1464 	return (status);
1465 }
1466 
1467 /*
1468  * Function:
1469  *	vd_scsi_rdwr
1470  *
1471  * Description:
1472  * 	Wrapper function to read or write to a SCSI disk using an absolute
1473  *	disk offset. It checks the blocksize of the underlying device and,
1474  *	if necessary, adjusts the buffers accordingly before calling
1475  *	vd_do_scsi_rdwr() to do the actual read or write.
1476  *
1477  * Parameters:
1478  *	vd		- disk on which the operation is performed.
1479  *	operation	- operation to execute: read (VD_OP_BREAD) or
1480  *			  write (VD_OP_BWRITE).
1481  *	data		- buffer where data are read to or written from.
1482  *	blk		- starting block for the operation.
1483  *	len		- number of bytes to read or write.
1484  *
1485  * Return Code:
1486  *	0		- success
1487  *	n != 0		- error.
1488  */
1489 static int
1490 vd_scsi_rdwr(vd_t *vd, int operation, caddr_t data, size_t vblk, size_t vlen)
1491 {
1492 	int	rv;
1493 
1494 	size_t	pblk;	/* physical device block number of data on device */
1495 	size_t	delta;	/* relative offset between pblk and vblk */
1496 	size_t	pnblk;	/* number of physical blocks to be read from device */
1497 	size_t	plen;	/* length of data to be read from physical device */
1498 	char	*buf;	/* buffer area to fit physical device's block size */
1499 
1500 	if (vd->block_size == 0) {
1501 		/*
1502 		 * The block size was not available during the attach,
1503 		 * try to update it now.
1504 		 */
1505 		if (vd_backend_check_size(vd) != 0)
1506 			return (EIO);
1507 	}
1508 
1509 	/*
1510 	 * If the vdisk block size and the block size of the underlying device
1511 	 * match we can skip straight to vd_do_scsi_rdwr(), otherwise we need
1512 	 * to create a buffer large enough to handle the device's block size
1513 	 * and adjust the block to be read from and the amount of data to
1514 	 * read to correspond with the device's block size.
1515 	 */
1516 	if (vd->vdisk_block_size == vd->block_size)
1517 		return (vd_do_scsi_rdwr(vd, operation, data, vblk, vlen));
1518 
1519 	if (vd->vdisk_block_size > vd->block_size)
1520 		return (EINVAL);
1521 
1522 	/*
1523 	 * Writing of physical block sizes larger than the virtual block size
1524 	 * is not supported. This would be added if/when support for guests
1525 	 * writing to DVDs is implemented.
1526 	 */
1527 	if (operation == VD_OP_BWRITE)
1528 		return (ENOTSUP);
1529 
1530 	/* BEGIN CSTYLED */
1531 	/*
1532 	 * Below is a diagram showing the relationship between the physical
1533 	 * and virtual blocks. If the virtual blocks marked by 'X' below are
1534 	 * requested, then the physical blocks denoted by 'Y' are read.
1535 	 *
1536 	 *           vblk
1537 	 *             |      vlen
1538 	 *             |<--------------->|
1539 	 *             v                 v
1540 	 *  --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-   virtual disk:
1541 	 *    |  |  |  |XX|XX|XX|XX|XX|XX|  |  |  |  |  |  } block size is
1542 	 *  --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-  vd->vdisk_block_size
1543 	 *          :  :                 :  :
1544 	 *         >:==:< delta          :  :
1545 	 *          :  :                 :  :
1546 	 *  --+-----+-----+-----+-----+-----+-----+-----+--   physical disk:
1547 	 *    |     |YY:YY|YYYYY|YYYYY|YY:YY|     |     |   } block size is
1548 	 *  --+-----+-----+-----+-----+-----+-----+-----+--   vd->block_size
1549 	 *          ^                       ^
1550 	 *          |<--------------------->|
1551 	 *          |         plen
1552 	 *         pblk
1553 	 */
1554 	/* END CSTYLED */
1555 	pblk = (vblk * vd->vdisk_block_size) / vd->block_size;
1556 	delta = (vblk * vd->vdisk_block_size) - (pblk * vd->block_size);
1557 	pnblk = ((delta + vlen - 1) / vd->block_size) + 1;
1558 	plen = pnblk * vd->block_size;
1559 
1560 	PR2("vblk %lx:pblk %lx: vlen %ld:plen %ld", vblk, pblk, vlen, plen);
1561 
1562 	buf = kmem_zalloc(sizeof (caddr_t) * plen, KM_SLEEP);
1563 	rv = vd_do_scsi_rdwr(vd, operation, (caddr_t)buf, pblk, plen);
1564 	bcopy(buf + delta, data, vlen);
1565 
1566 	kmem_free(buf, sizeof (caddr_t) * plen);
1567 
1568 	return (rv);
1569 }
1570 
1571 /*
1572  * Function:
1573  *	vd_slice_flabel_read
1574  *
1575  * Description:
1576  *	This function simulates a read operation from the fake label of
1577  *	a single-slice disk.
1578  *
1579  * Parameters:
1580  *	vd		- single-slice disk to read from
1581  *	data		- buffer where data should be read to
1582  *	offset		- offset in byte where the read should start
1583  *	length		- number of bytes to read
1584  *
1585  * Return Code:
1586  *	n >= 0		- success, n indicates the number of bytes read
1587  *	-1		- error
1588  */
1589 static ssize_t
1590 vd_slice_flabel_read(vd_t *vd, caddr_t data, size_t offset, size_t length)
1591 {
1592 	size_t n = 0;
1593 	uint_t limit = vd->flabel_limit * DEV_BSIZE;
1594 
1595 	ASSERT(vd->vdisk_type == VD_DISK_TYPE_SLICE);
1596 	ASSERT(vd->flabel != NULL);
1597 
1598 	/* if offset is past the fake label limit there's nothing to read */
1599 	if (offset >= limit)
1600 		return (0);
1601 
1602 	/* data with offset 0 to flabel_size are read from flabel */
1603 	if (offset < vd->flabel_size) {
1604 
1605 		if (offset + length <= vd->flabel_size) {
1606 			bcopy(vd->flabel + offset, data, length);
1607 			return (length);
1608 		}
1609 
1610 		n = vd->flabel_size - offset;
1611 		bcopy(vd->flabel + offset, data, n);
1612 		data += n;
1613 	}
1614 
1615 	/* data with offset from flabel_size to flabel_limit are all zeros */
1616 	if (offset + length <= limit) {
1617 		bzero(data, length - n);
1618 		return (length);
1619 	}
1620 
1621 	bzero(data, limit - offset - n);
1622 	return (limit - offset);
1623 }
1624 
1625 /*
1626  * Function:
1627  *	vd_slice_flabel_write
1628  *
1629  * Description:
1630  *	This function simulates a write operation to the fake label of
1631  *	a single-slice disk. Write operations are actually faked and return
1632  *	success although the label is never changed. This is mostly to
1633  *	simulate a successful label update.
1634  *
1635  * Parameters:
1636  *	vd		- single-slice disk to write to
1637  *	data		- buffer where data should be written from
1638  *	offset		- offset in byte where the write should start
1639  *	length		- number of bytes to written
1640  *
1641  * Return Code:
1642  *	n >= 0		- success, n indicates the number of bytes written
1643  *	-1		- error
1644  */
1645 static ssize_t
1646 vd_slice_flabel_write(vd_t *vd, caddr_t data, size_t offset, size_t length)
1647 {
1648 	uint_t limit = vd->flabel_limit * DEV_BSIZE;
1649 	struct dk_label *label;
1650 	struct dk_geom geom;
1651 	struct extvtoc vtoc;
1652 
1653 	ASSERT(vd->vdisk_type == VD_DISK_TYPE_SLICE);
1654 	ASSERT(vd->flabel != NULL);
1655 
1656 	if (offset >= limit)
1657 		return (0);
1658 
1659 	/*
1660 	 * If this is a request to overwrite the VTOC disk label, check that
1661 	 * the new label is similar to the previous one and return that the
1662 	 * write was successful, but note that nothing is actually overwritten.
1663 	 */
1664 	if (vd->vdisk_label == VD_DISK_LABEL_VTOC &&
1665 	    offset == 0 && length == DEV_BSIZE) {
1666 		label = (void *)data;
1667 
1668 		/* check that this is a valid label */
1669 		if (label->dkl_magic != DKL_MAGIC ||
1670 		    label->dkl_cksum != vd_lbl2cksum(label))
1671 			return (-1);
1672 
1673 		/* check the vtoc and geometry */
1674 		vd_label_to_vtocgeom(label, &vtoc, &geom);
1675 		if (vd_slice_geom_isvalid(vd, &geom) &&
1676 		    vd_slice_vtoc_isvalid(vd, &vtoc))
1677 			return (length);
1678 	}
1679 
1680 	/* fail any other write */
1681 	return (-1);
1682 }
1683 
1684 /*
1685  * Function:
1686  *	vd_slice_fake_rdwr
1687  *
1688  * Description:
1689  *	This function simulates a raw read or write operation to a single-slice
1690  *	disk. It only handles the faked part of the operation i.e. I/Os to
1691  *	blocks which have no mapping with the vdisk backend (I/Os to the
1692  *	beginning and to the end of the vdisk).
1693  *
1694  *	The function returns 0 is the operation	is completed and it has been
1695  *	entirely handled as a fake read or write. In that case, lengthp points
1696  *	to the number of bytes not read or written. Values returned by datap
1697  *	and blkp are undefined.
1698  *
1699  *	If the fake operation has succeeded but the read or write is not
1700  *	complete (i.e. the read/write operation extends beyond the blocks
1701  *	we fake) then the function returns EAGAIN and datap, blkp and lengthp
1702  *	pointers points to the parameters for completing the operation.
1703  *
1704  *	In case of an error, for example if the slice is empty or parameters
1705  *	are invalid, then the function returns a non-zero value different
1706  *	from EAGAIN. In that case, the returned values of datap, blkp and
1707  *	lengthp are undefined.
1708  *
1709  * Parameters:
1710  *	vd		- single-slice disk on which the operation is performed
1711  *	slice		- slice on which the operation is performed,
1712  *			  VD_SLICE_NONE indicates that the operation
1713  *			  is done using an absolute disk offset.
1714  *	operation	- operation to execute: read (VD_OP_BREAD) or
1715  *			  write (VD_OP_BWRITE).
1716  *	datap		- pointer to the buffer where data are read to
1717  *			  or written from. Return the pointer where remaining
1718  *			  data have to be read to or written from.
1719  *	blkp		- pointer to the starting block for the operation.
1720  *			  Return the starting block relative to the vdisk
1721  *			  backend for the remaining operation.
1722  *	lengthp		- pointer to the number of bytes to read or write.
1723  *			  This should be a multiple of DEV_BSIZE. Return the
1724  *			  remaining number of bytes to read or write.
1725  *
1726  * Return Code:
1727  *	0		- read/write operation is completed
1728  *	EAGAIN		- read/write operation is not completed
1729  *	other values	- error
1730  */
1731 static int
1732 vd_slice_fake_rdwr(vd_t *vd, int slice, int operation, caddr_t *datap,
1733     size_t *blkp, size_t *lengthp)
1734 {
1735 	struct dk_label *label;
1736 	caddr_t data;
1737 	size_t blk, length, csize;
1738 	size_t ablk, asize, aoff, alen;
1739 	ssize_t n;
1740 	int sec, status;
1741 
1742 	ASSERT(vd->vdisk_type == VD_DISK_TYPE_SLICE);
1743 	ASSERT(slice != 0);
1744 
1745 	data = *datap;
1746 	blk = *blkp;
1747 	length = *lengthp;
1748 
1749 	/*
1750 	 * If this is not a raw I/O or an I/O from a full disk slice then
1751 	 * this is an I/O to/from an empty slice.
1752 	 */
1753 	if (slice != VD_SLICE_NONE &&
1754 	    (slice != VD_ENTIRE_DISK_SLICE ||
1755 	    vd->vdisk_label != VD_DISK_LABEL_VTOC) &&
1756 	    (slice != VD_EFI_WD_SLICE ||
1757 	    vd->vdisk_label != VD_DISK_LABEL_EFI)) {
1758 		return (EIO);
1759 	}
1760 
1761 	if (length % DEV_BSIZE != 0)
1762 		return (EINVAL);
1763 
1764 	/* handle any I/O with the fake label */
1765 	if (operation == VD_OP_BWRITE)
1766 		n = vd_slice_flabel_write(vd, data, blk * DEV_BSIZE, length);
1767 	else
1768 		n = vd_slice_flabel_read(vd, data, blk * DEV_BSIZE, length);
1769 
1770 	if (n == -1)
1771 		return (EINVAL);
1772 
1773 	ASSERT(n % DEV_BSIZE == 0);
1774 
1775 	/* adjust I/O arguments */
1776 	data += n;
1777 	blk += n / DEV_BSIZE;
1778 	length -= n;
1779 
1780 	/* check if there's something else to process */
1781 	if (length == 0) {
1782 		status = 0;
1783 		goto done;
1784 	}
1785 
1786 	if (vd->vdisk_label == VD_DISK_LABEL_VTOC &&
1787 	    slice == VD_ENTIRE_DISK_SLICE) {
1788 		status = EAGAIN;
1789 		goto done;
1790 	}
1791 
1792 	if (vd->vdisk_label == VD_DISK_LABEL_EFI) {
1793 		asize = EFI_MIN_RESV_SIZE + 33;
1794 		ablk = vd->vdisk_size - asize;
1795 	} else {
1796 		ASSERT(vd->vdisk_label == VD_DISK_LABEL_VTOC);
1797 		ASSERT(vd->dk_geom.dkg_apc == 0);
1798 
1799 		csize = vd->dk_geom.dkg_nhead * vd->dk_geom.dkg_nsect;
1800 		ablk = vd->dk_geom.dkg_ncyl * csize;
1801 		asize = vd->dk_geom.dkg_acyl * csize;
1802 	}
1803 
1804 	alen = length / DEV_BSIZE;
1805 	aoff = blk;
1806 
1807 	/* if we have reached the last block then the I/O is completed */
1808 	if (aoff == ablk + asize) {
1809 		status = 0;
1810 		goto done;
1811 	}
1812 
1813 	/* if we are past the last block then return an error */
1814 	if (aoff > ablk + asize)
1815 		return (EIO);
1816 
1817 	/* check if there is any I/O to end of the disk */
1818 	if (aoff + alen < ablk) {
1819 		status = EAGAIN;
1820 		goto done;
1821 	}
1822 
1823 	/* we don't allow any write to the end of the disk */
1824 	if (operation == VD_OP_BWRITE)
1825 		return (EIO);
1826 
1827 	if (aoff < ablk) {
1828 		alen -= (ablk - aoff);
1829 		aoff = ablk;
1830 	}
1831 
1832 	if (aoff + alen > ablk + asize) {
1833 		alen = ablk + asize - aoff;
1834 	}
1835 
1836 	alen *= DEV_BSIZE;
1837 
1838 	if (operation == VD_OP_BREAD) {
1839 		bzero(data + (aoff - blk) * DEV_BSIZE, alen);
1840 
1841 		if (vd->vdisk_label == VD_DISK_LABEL_VTOC) {
1842 			/* check if we read backup labels */
1843 			label = VD_LABEL_VTOC(vd);
1844 			ablk += (label->dkl_acyl - 1) * csize +
1845 			    (label->dkl_nhead - 1) * label->dkl_nsect;
1846 
1847 			for (sec = 1; (sec < 5 * 2 + 1); sec += 2) {
1848 
1849 				if (ablk + sec >= blk &&
1850 				    ablk + sec < blk + (length / DEV_BSIZE)) {
1851 					bcopy(label, data +
1852 					    (ablk + sec - blk) * DEV_BSIZE,
1853 					    sizeof (struct dk_label));
1854 				}
1855 			}
1856 		}
1857 	}
1858 
1859 	length -= alen;
1860 
1861 	status = (length == 0)? 0: EAGAIN;
1862 
1863 done:
1864 	ASSERT(length == 0 || blk >= vd->flabel_limit);
1865 
1866 	/*
1867 	 * Return the parameters for the remaining I/O. The starting block is
1868 	 * adjusted so that it is relative to the vdisk backend.
1869 	 */
1870 	*datap = data;
1871 	*blkp = blk - vd->flabel_limit;
1872 	*lengthp = length;
1873 
1874 	return (status);
1875 }
1876 
1877 static int
1878 vd_flush_write(vd_t *vd)
1879 {
1880 	int status, rval;
1881 
1882 	if (vd->file) {
1883 		status = VOP_FSYNC(vd->file_vnode, FSYNC, kcred, NULL);
1884 	} else {
1885 		status = ldi_ioctl(vd->ldi_handle[0], DKIOCFLUSHWRITECACHE,
1886 		    NULL, vd->open_flags | FKIOCTL, kcred, &rval);
1887 	}
1888 
1889 	return (status);
1890 }
1891 
1892 static void
1893 vd_bio_task(void *arg)
1894 {
1895 	struct buf *buf = (struct buf *)arg;
1896 	vd_task_t *task = (vd_task_t *)buf->b_private;
1897 	vd_t *vd = task->vd;
1898 	ssize_t resid;
1899 	int status;
1900 
1901 	if (vd->zvol) {
1902 
1903 		status = ldi_strategy(vd->ldi_handle[0], buf);
1904 
1905 	} else {
1906 
1907 		ASSERT(vd->file);
1908 
1909 		status = vn_rdwr((buf->b_flags & B_READ)? UIO_READ : UIO_WRITE,
1910 		    vd->file_vnode, buf->b_un.b_addr, buf->b_bcount,
1911 		    buf->b_lblkno * DEV_BSIZE, UIO_SYSSPACE, 0,
1912 		    RLIM64_INFINITY, kcred, &resid);
1913 
1914 		if (status == 0) {
1915 			buf->b_resid = resid;
1916 			biodone(buf);
1917 			return;
1918 		}
1919 	}
1920 
1921 	if (status != 0) {
1922 		bioerror(buf, status);
1923 		biodone(buf);
1924 	}
1925 }
1926 
1927 /*
1928  * We define our own biodone function so that buffers used for
1929  * asynchronous writes are not released when biodone() is called.
1930  */
1931 static int
1932 vd_biodone(struct buf *bp)
1933 {
1934 	ASSERT((bp->b_flags & B_DONE) == 0);
1935 	ASSERT(SEMA_HELD(&bp->b_sem));
1936 
1937 	bp->b_flags |= B_DONE;
1938 	sema_v(&bp->b_io);
1939 
1940 	return (0);
1941 }
1942 
1943 /*
1944  * Return Values
1945  *	EINPROGRESS	- operation was successfully started
1946  *	EIO		- encountered LDC (aka. task error)
1947  *	0		- operation completed successfully
1948  *
1949  * Side Effect
1950  *     sets request->status = <disk operation status>
1951  */
1952 static int
1953 vd_start_bio(vd_task_t *task)
1954 {
1955 	int			rv, status = 0;
1956 	vd_t			*vd		= task->vd;
1957 	vd_dring_payload_t	*request	= task->request;
1958 	struct buf		*buf		= &task->buf;
1959 	uint8_t			mtype;
1960 	int 			slice;
1961 	char			*bufaddr = 0;
1962 	size_t			buflen;
1963 	size_t			offset, length, nbytes;
1964 
1965 	ASSERT(vd != NULL);
1966 	ASSERT(request != NULL);
1967 
1968 	slice = request->slice;
1969 
1970 	ASSERT(slice == VD_SLICE_NONE || slice < vd->nslices);
1971 	ASSERT((request->operation == VD_OP_BREAD) ||
1972 	    (request->operation == VD_OP_BWRITE));
1973 
1974 	if (request->nbytes == 0) {
1975 		/* no service for trivial requests */
1976 		request->status = EINVAL;
1977 		return (0);
1978 	}
1979 
1980 	PR1("%s %lu bytes at block %lu",
1981 	    (request->operation == VD_OP_BREAD) ? "Read" : "Write",
1982 	    request->nbytes, request->addr);
1983 
1984 	/*
1985 	 * We have to check the open flags because the functions processing
1986 	 * the read/write request will not do it.
1987 	 */
1988 	if (request->operation == VD_OP_BWRITE && !(vd->open_flags & FWRITE)) {
1989 		PR0("write fails because backend is opened read-only");
1990 		request->nbytes = 0;
1991 		request->status = EROFS;
1992 		return (0);
1993 	}
1994 
1995 	mtype = (&vd->inband_task == task) ? LDC_SHADOW_MAP : LDC_DIRECT_MAP;
1996 
1997 	/* Map memory exported by client */
1998 	status = ldc_mem_map(task->mhdl, request->cookie, request->ncookies,
1999 	    mtype, (request->operation == VD_OP_BREAD) ? LDC_MEM_W : LDC_MEM_R,
2000 	    &bufaddr, NULL);
2001 	if (status != 0) {
2002 		PR0("ldc_mem_map() returned err %d ", status);
2003 		return (EIO);
2004 	}
2005 
2006 	/*
2007 	 * The buffer size has to be 8-byte aligned, so the client should have
2008 	 * sent a buffer which size is roundup to the next 8-byte aligned value.
2009 	 */
2010 	buflen = P2ROUNDUP(request->nbytes, 8);
2011 
2012 	status = ldc_mem_acquire(task->mhdl, 0, buflen);
2013 	if (status != 0) {
2014 		(void) ldc_mem_unmap(task->mhdl);
2015 		PR0("ldc_mem_acquire() returned err %d ", status);
2016 		return (EIO);
2017 	}
2018 
2019 	offset = request->addr;
2020 	nbytes = request->nbytes;
2021 	length = nbytes;
2022 
2023 	/* default number of byte returned by the I/O */
2024 	request->nbytes = 0;
2025 
2026 	if (vd->vdisk_type == VD_DISK_TYPE_SLICE) {
2027 
2028 		if (slice != 0) {
2029 			/* handle any fake I/O */
2030 			rv = vd_slice_fake_rdwr(vd, slice, request->operation,
2031 			    &bufaddr, &offset, &length);
2032 
2033 			/* record the number of bytes from the fake I/O */
2034 			request->nbytes = nbytes - length;
2035 
2036 			if (rv == 0) {
2037 				request->status = 0;
2038 				goto io_done;
2039 			}
2040 
2041 			if (rv != EAGAIN) {
2042 				request->nbytes = 0;
2043 				request->status = EIO;
2044 				goto io_done;
2045 			}
2046 
2047 			/*
2048 			 * If we return with EAGAIN then this means that there
2049 			 * are still data to read or write.
2050 			 */
2051 			ASSERT(length != 0);
2052 
2053 			/*
2054 			 * We need to continue the I/O from the slice backend to
2055 			 * complete the request. The variables bufaddr, offset
2056 			 * and length have been adjusted to have the right
2057 			 * information to do the remaining I/O from the backend.
2058 			 * The backend is entirely mapped to slice 0 so we just
2059 			 * have to complete the I/O from that slice.
2060 			 */
2061 			slice = 0;
2062 		}
2063 
2064 	} else if (vd->volume || vd->file) {
2065 
2066 		rv = vd_dskimg_io_params(vd, slice, &offset, &length);
2067 		if (rv != 0) {
2068 			request->status = (rv == ENODATA)? 0: EIO;
2069 			goto io_done;
2070 		}
2071 		slice = 0;
2072 
2073 	} else if (slice == VD_SLICE_NONE) {
2074 
2075 		/*
2076 		 * This is not a disk image so it is a real disk. We
2077 		 * assume that the underlying device driver supports
2078 		 * USCSICMD ioctls. This is the case of all SCSI devices
2079 		 * (sd, ssd...).
2080 		 *
2081 		 * In the future if we have non-SCSI disks we would need
2082 		 * to invoke the appropriate function to do I/O using an
2083 		 * absolute disk offset (for example using DIOCTL_RWCMD
2084 		 * for IDE disks).
2085 		 */
2086 		rv = vd_scsi_rdwr(vd, request->operation, bufaddr, offset,
2087 		    length);
2088 		if (rv != 0) {
2089 			request->status = EIO;
2090 		} else {
2091 			request->nbytes = length;
2092 			request->status = 0;
2093 		}
2094 		goto io_done;
2095 	}
2096 
2097 	/* Start the block I/O */
2098 	bioinit(buf);
2099 	buf->b_flags	= B_BUSY;
2100 	buf->b_bcount	= length;
2101 	buf->b_lblkno	= offset;
2102 	buf->b_bufsize	= buflen;
2103 	buf->b_edev 	= vd->dev[slice];
2104 	buf->b_un.b_addr = bufaddr;
2105 	buf->b_iodone	= vd_biodone;
2106 
2107 	if (vd->file || vd->zvol) {
2108 		/*
2109 		 * I/O to a file are dispatched to an I/O queue, so that several
2110 		 * I/Os can be processed in parallel. We also do that for ZFS
2111 		 * volumes because the ZFS volume strategy() function will only
2112 		 * return after the I/O is completed (instead of just starting
2113 		 * the I/O).
2114 		 */
2115 
2116 		if (request->operation == VD_OP_BREAD) {
2117 			buf->b_flags |= B_READ;
2118 		} else {
2119 			/*
2120 			 * For ZFS volumes and files, we do an asynchronous
2121 			 * write and we will wait for the completion of the
2122 			 * write in vd_complete_bio() by flushing the volume
2123 			 * or file.
2124 			 *
2125 			 * This done for performance reasons, so that we can
2126 			 * group together several write requests into a single
2127 			 * flush operation.
2128 			 */
2129 			buf->b_flags |= B_WRITE | B_ASYNC;
2130 
2131 			/*
2132 			 * We keep track of the write so that we can group
2133 			 * requests when flushing. The write queue has the
2134 			 * same number of slots as the dring so this prevents
2135 			 * the write queue from wrapping and overwriting
2136 			 * existing entries: if the write queue gets full
2137 			 * then that means that the dring is full so we stop
2138 			 * receiving new requests until an existing request
2139 			 * is processed, removed from the write queue and
2140 			 * then from the dring.
2141 			 */
2142 			task->write_index = vd->write_index;
2143 			vd->write_queue[task->write_index] = buf;
2144 			vd->write_index =
2145 			    VD_WRITE_INDEX_NEXT(vd, vd->write_index);
2146 		}
2147 
2148 		buf->b_private = task;
2149 
2150 		ASSERT(vd->ioq != NULL);
2151 
2152 		request->status = 0;
2153 		(void) ddi_taskq_dispatch(task->vd->ioq, vd_bio_task, buf,
2154 		    DDI_SLEEP);
2155 
2156 	} else {
2157 
2158 		if (request->operation == VD_OP_BREAD) {
2159 			buf->b_flags |= B_READ;
2160 		} else {
2161 			buf->b_flags |= B_WRITE;
2162 		}
2163 
2164 		request->status = ldi_strategy(vd->ldi_handle[slice], buf);
2165 	}
2166 
2167 	/*
2168 	 * This is to indicate to the caller that the request
2169 	 * needs to be finished by vd_complete_bio() by calling
2170 	 * biowait() there and waiting for that to return before
2171 	 * triggering the notification of the vDisk client.
2172 	 *
2173 	 * This is necessary when writing to real disks as
2174 	 * otherwise calls to ldi_strategy() would be serialized
2175 	 * behind the calls to biowait() and performance would
2176 	 * suffer.
2177 	 */
2178 	if (request->status == 0)
2179 		return (EINPROGRESS);
2180 
2181 	biofini(buf);
2182 
2183 io_done:
2184 	/* Clean up after error or completion */
2185 	rv = ldc_mem_release(task->mhdl, 0, buflen);
2186 	if (rv) {
2187 		PR0("ldc_mem_release() returned err %d ", rv);
2188 		status = EIO;
2189 	}
2190 	rv = ldc_mem_unmap(task->mhdl);
2191 	if (rv) {
2192 		PR0("ldc_mem_unmap() returned err %d ", rv);
2193 		status = EIO;
2194 	}
2195 
2196 	return (status);
2197 }
2198 
2199 /*
2200  * This function should only be called from vd_notify to ensure that requests
2201  * are responded to in the order that they are received.
2202  */
2203 static int
2204 send_msg(ldc_handle_t ldc_handle, void *msg, size_t msglen)
2205 {
2206 	int	status;
2207 	size_t	nbytes;
2208 
2209 	do {
2210 		nbytes = msglen;
2211 		status = ldc_write(ldc_handle, msg, &nbytes);
2212 		if (status != EWOULDBLOCK)
2213 			break;
2214 		drv_usecwait(vds_ldc_delay);
2215 	} while (status == EWOULDBLOCK);
2216 
2217 	if (status != 0) {
2218 		if (status != ECONNRESET)
2219 			PR0("ldc_write() returned errno %d", status);
2220 		return (status);
2221 	} else if (nbytes != msglen) {
2222 		PR0("ldc_write() performed only partial write");
2223 		return (EIO);
2224 	}
2225 
2226 	PR1("SENT %lu bytes", msglen);
2227 	return (0);
2228 }
2229 
2230 static void
2231 vd_need_reset(vd_t *vd, boolean_t reset_ldc)
2232 {
2233 	mutex_enter(&vd->lock);
2234 	vd->reset_state	= B_TRUE;
2235 	vd->reset_ldc	= reset_ldc;
2236 	mutex_exit(&vd->lock);
2237 }
2238 
2239 /*
2240  * Reset the state of the connection with a client, if needed; reset the LDC
2241  * transport as well, if needed.  This function should only be called from the
2242  * "vd_recv_msg", as it waits for tasks - otherwise a deadlock can occur.
2243  */
2244 static void
2245 vd_reset_if_needed(vd_t *vd)
2246 {
2247 	int	status = 0;
2248 
2249 	mutex_enter(&vd->lock);
2250 	if (!vd->reset_state) {
2251 		ASSERT(!vd->reset_ldc);
2252 		mutex_exit(&vd->lock);
2253 		return;
2254 	}
2255 	mutex_exit(&vd->lock);
2256 
2257 	PR0("Resetting connection state with %s", VD_CLIENT(vd));
2258 
2259 	/*
2260 	 * Let any asynchronous I/O complete before possibly pulling the rug
2261 	 * out from under it; defer checking vd->reset_ldc, as one of the
2262 	 * asynchronous tasks might set it
2263 	 */
2264 	if (vd->ioq != NULL)
2265 		ddi_taskq_wait(vd->ioq);
2266 	ddi_taskq_wait(vd->completionq);
2267 
2268 	status = vd_flush_write(vd);
2269 	if (status) {
2270 		PR0("flushwrite returned error %d", status);
2271 	}
2272 
2273 	if ((vd->initialized & VD_DRING) &&
2274 	    ((status = ldc_mem_dring_unmap(vd->dring_handle)) != 0))
2275 		PR0("ldc_mem_dring_unmap() returned errno %d", status);
2276 
2277 	vd_free_dring_task(vd);
2278 
2279 	/* Free the staging buffer for msgs */
2280 	if (vd->vio_msgp != NULL) {
2281 		kmem_free(vd->vio_msgp, vd->max_msglen);
2282 		vd->vio_msgp = NULL;
2283 	}
2284 
2285 	/* Free the inband message buffer */
2286 	if (vd->inband_task.msg != NULL) {
2287 		kmem_free(vd->inband_task.msg, vd->max_msglen);
2288 		vd->inband_task.msg = NULL;
2289 	}
2290 
2291 	mutex_enter(&vd->lock);
2292 
2293 	if (vd->reset_ldc)
2294 		PR0("taking down LDC channel");
2295 	if (vd->reset_ldc && ((status = ldc_down(vd->ldc_handle)) != 0))
2296 		PR0("ldc_down() returned errno %d", status);
2297 
2298 	/* Reset exclusive access rights */
2299 	vd_reset_access(vd);
2300 
2301 	vd->initialized	&= ~(VD_SID | VD_SEQ_NUM | VD_DRING);
2302 	vd->state	= VD_STATE_INIT;
2303 	vd->max_msglen	= sizeof (vio_msg_t);	/* baseline vio message size */
2304 
2305 	/* Allocate the staging buffer */
2306 	vd->vio_msgp = kmem_alloc(vd->max_msglen, KM_SLEEP);
2307 
2308 	PR0("calling ldc_up\n");
2309 	(void) ldc_up(vd->ldc_handle);
2310 
2311 	vd->reset_state	= B_FALSE;
2312 	vd->reset_ldc	= B_FALSE;
2313 
2314 	mutex_exit(&vd->lock);
2315 }
2316 
2317 static void vd_recv_msg(void *arg);
2318 
2319 static void
2320 vd_mark_in_reset(vd_t *vd)
2321 {
2322 	int status;
2323 
2324 	PR0("vd_mark_in_reset: marking vd in reset\n");
2325 
2326 	vd_need_reset(vd, B_FALSE);
2327 	status = ddi_taskq_dispatch(vd->startq, vd_recv_msg, vd, DDI_SLEEP);
2328 	if (status == DDI_FAILURE) {
2329 		PR0("cannot schedule task to recv msg\n");
2330 		vd_need_reset(vd, B_TRUE);
2331 		return;
2332 	}
2333 }
2334 
2335 static int
2336 vd_mark_elem_done(vd_t *vd, int idx, int elem_status, int elem_nbytes)
2337 {
2338 	boolean_t		accepted;
2339 	int			status;
2340 	on_trap_data_t		otd;
2341 	vd_dring_entry_t	*elem = VD_DRING_ELEM(idx);
2342 
2343 	if (vd->reset_state)
2344 		return (0);
2345 
2346 	/* Acquire the element */
2347 	if ((status = VIO_DRING_ACQUIRE(&otd, vd->dring_mtype,
2348 	    vd->dring_handle, idx, idx)) != 0) {
2349 		if (status == ECONNRESET) {
2350 			vd_mark_in_reset(vd);
2351 			return (0);
2352 		} else {
2353 			return (status);
2354 		}
2355 	}
2356 
2357 	/* Set the element's status and mark it done */
2358 	accepted = (elem->hdr.dstate == VIO_DESC_ACCEPTED);
2359 	if (accepted) {
2360 		elem->payload.nbytes	= elem_nbytes;
2361 		elem->payload.status	= elem_status;
2362 		elem->hdr.dstate	= VIO_DESC_DONE;
2363 	} else {
2364 		/* Perhaps client timed out waiting for I/O... */
2365 		PR0("element %u no longer \"accepted\"", idx);
2366 		VD_DUMP_DRING_ELEM(elem);
2367 	}
2368 	/* Release the element */
2369 	if ((status = VIO_DRING_RELEASE(vd->dring_mtype,
2370 	    vd->dring_handle, idx, idx)) != 0) {
2371 		if (status == ECONNRESET) {
2372 			vd_mark_in_reset(vd);
2373 			return (0);
2374 		} else {
2375 			PR0("VIO_DRING_RELEASE() returned errno %d",
2376 			    status);
2377 			return (status);
2378 		}
2379 	}
2380 
2381 	return (accepted ? 0 : EINVAL);
2382 }
2383 
2384 /*
2385  * Return Values
2386  *	0	- operation completed successfully
2387  *	EIO	- encountered LDC / task error
2388  *
2389  * Side Effect
2390  *	sets request->status = <disk operation status>
2391  */
2392 static int
2393 vd_complete_bio(vd_task_t *task)
2394 {
2395 	int			status		= 0;
2396 	int			rv		= 0;
2397 	vd_t			*vd		= task->vd;
2398 	vd_dring_payload_t	*request	= task->request;
2399 	struct buf		*buf		= &task->buf;
2400 	int			wid, nwrites;
2401 
2402 
2403 	ASSERT(vd != NULL);
2404 	ASSERT(request != NULL);
2405 	ASSERT(task->msg != NULL);
2406 	ASSERT(task->msglen >= sizeof (*task->msg));
2407 
2408 	if (buf->b_flags & B_DONE) {
2409 		/*
2410 		 * If the I/O is already done then we don't call biowait()
2411 		 * because biowait() might already have been called when
2412 		 * flushing a previous asynchronous write. So we just
2413 		 * retrieve the status of the request.
2414 		 */
2415 		request->status = geterror(buf);
2416 	} else {
2417 		/*
2418 		 * Wait for the I/O. For synchronous I/O, biowait() will return
2419 		 * when the I/O has completed. For asynchronous write, it will
2420 		 * return the write has been submitted to the backend, but it
2421 		 * may not have been committed.
2422 		 */
2423 		request->status = biowait(buf);
2424 	}
2425 
2426 	if (buf->b_flags & B_ASYNC) {
2427 		/*
2428 		 * Asynchronous writes are used when writing to a file or a
2429 		 * ZFS volume. In that case the bio notification indicates
2430 		 * that the write has started. We have to flush the backend
2431 		 * to ensure that the write has been committed before marking
2432 		 * the request as completed.
2433 		 */
2434 		ASSERT(task->request->operation == VD_OP_BWRITE);
2435 
2436 		wid = task->write_index;
2437 
2438 		/* check if write has been already flushed */
2439 		if (vd->write_queue[wid] != NULL) {
2440 
2441 			vd->write_queue[wid] = NULL;
2442 			wid = VD_WRITE_INDEX_NEXT(vd, wid);
2443 
2444 			/*
2445 			 * Because flushing is time consuming, it is worth
2446 			 * waiting for any other writes so that they can be
2447 			 * included in this single flush request.
2448 			 */
2449 			if (vd_awflush & VD_AWFLUSH_GROUP) {
2450 				nwrites = 1;
2451 				while (vd->write_queue[wid] != NULL) {
2452 					(void) biowait(vd->write_queue[wid]);
2453 					vd->write_queue[wid] = NULL;
2454 					wid = VD_WRITE_INDEX_NEXT(vd, wid);
2455 					nwrites++;
2456 				}
2457 				DTRACE_PROBE2(flushgrp, vd_task_t *, task,
2458 				    int, nwrites);
2459 			}
2460 
2461 			if (vd_awflush & VD_AWFLUSH_IMMEDIATE) {
2462 				request->status = vd_flush_write(vd);
2463 			} else if (vd_awflush & VD_AWFLUSH_DEFER) {
2464 				(void) taskq_dispatch(system_taskq,
2465 				    (void (*)(void *))vd_flush_write, vd,
2466 				    DDI_SLEEP);
2467 				request->status = 0;
2468 			}
2469 		}
2470 	}
2471 
2472 	/* Update the number of bytes read/written */
2473 	request->nbytes += buf->b_bcount - buf->b_resid;
2474 
2475 	/* Release the buffer */
2476 	if (!vd->reset_state)
2477 		status = ldc_mem_release(task->mhdl, 0, buf->b_bufsize);
2478 	if (status) {
2479 		PR0("ldc_mem_release() returned errno %d copying to "
2480 		    "client", status);
2481 		if (status == ECONNRESET) {
2482 			vd_mark_in_reset(vd);
2483 		}
2484 		rv = EIO;
2485 	}
2486 
2487 	/* Unmap the memory, even if in reset */
2488 	status = ldc_mem_unmap(task->mhdl);
2489 	if (status) {
2490 		PR0("ldc_mem_unmap() returned errno %d copying to client",
2491 		    status);
2492 		if (status == ECONNRESET) {
2493 			vd_mark_in_reset(vd);
2494 		}
2495 		rv = EIO;
2496 	}
2497 
2498 	biofini(buf);
2499 
2500 	return (rv);
2501 }
2502 
2503 /*
2504  * Description:
2505  *	This function is called by the two functions called by a taskq
2506  *	[ vd_complete_notify() and vd_serial_notify()) ] to send the
2507  *	message to the client.
2508  *
2509  * Parameters:
2510  *	arg 	- opaque pointer to structure containing task to be completed
2511  *
2512  * Return Values
2513  *	None
2514  */
2515 static void
2516 vd_notify(vd_task_t *task)
2517 {
2518 	int	status;
2519 
2520 	ASSERT(task != NULL);
2521 	ASSERT(task->vd != NULL);
2522 
2523 	/*
2524 	 * Send the "ack" or "nack" back to the client; if sending the message
2525 	 * via LDC fails, arrange to reset both the connection state and LDC
2526 	 * itself
2527 	 */
2528 	PR2("Sending %s",
2529 	    (task->msg->tag.vio_subtype == VIO_SUBTYPE_ACK) ? "ACK" : "NACK");
2530 
2531 	status = send_msg(task->vd->ldc_handle, task->msg, task->msglen);
2532 	switch (status) {
2533 	case 0:
2534 		break;
2535 	case ECONNRESET:
2536 		vd_mark_in_reset(task->vd);
2537 		break;
2538 	default:
2539 		PR0("initiating full reset");
2540 		vd_need_reset(task->vd, B_TRUE);
2541 		break;
2542 	}
2543 
2544 	DTRACE_PROBE1(task__end, vd_task_t *, task);
2545 }
2546 
2547 /*
2548  * Description:
2549  *	Mark the Dring entry as Done and (if necessary) send an ACK/NACK to
2550  *	the vDisk client
2551  *
2552  * Parameters:
2553  *	task 		- structure containing the request sent from client
2554  *
2555  * Return Values
2556  *	None
2557  */
2558 static void
2559 vd_complete_notify(vd_task_t *task)
2560 {
2561 	int			status		= 0;
2562 	vd_t			*vd		= task->vd;
2563 	vd_dring_payload_t	*request	= task->request;
2564 
2565 	/* Update the dring element for a dring client */
2566 	if (!vd->reset_state && (vd->xfer_mode == VIO_DRING_MODE_V1_0)) {
2567 		status = vd_mark_elem_done(vd, task->index,
2568 		    request->status, request->nbytes);
2569 		if (status == ECONNRESET)
2570 			vd_mark_in_reset(vd);
2571 		else if (status == EACCES)
2572 			vd_need_reset(vd, B_TRUE);
2573 	}
2574 
2575 	/*
2576 	 * If a transport error occurred while marking the element done or
2577 	 * previously while executing the task, arrange to "nack" the message
2578 	 * when the final task in the descriptor element range completes
2579 	 */
2580 	if ((status != 0) || (task->status != 0))
2581 		task->msg->tag.vio_subtype = VIO_SUBTYPE_NACK;
2582 
2583 	/*
2584 	 * Only the final task for a range of elements will respond to and
2585 	 * free the message
2586 	 */
2587 	if (task->type == VD_NONFINAL_RANGE_TASK) {
2588 		return;
2589 	}
2590 
2591 	/*
2592 	 * We should only send an ACK/NACK here if we are not currently in
2593 	 * reset as, depending on how we reset, the dring may have been
2594 	 * blown away and we don't want to ACK/NACK a message that isn't
2595 	 * there.
2596 	 */
2597 	if (!vd->reset_state)
2598 		vd_notify(task);
2599 }
2600 
2601 /*
2602  * Description:
2603  *	This is the basic completion function called to handle inband data
2604  *	requests and handshake messages. All it needs to do is trigger a
2605  *	message to the client that the request is completed.
2606  *
2607  * Parameters:
2608  *	arg 	- opaque pointer to structure containing task to be completed
2609  *
2610  * Return Values
2611  *	None
2612  */
2613 static void
2614 vd_serial_notify(void *arg)
2615 {
2616 	vd_task_t		*task = (vd_task_t *)arg;
2617 
2618 	ASSERT(task != NULL);
2619 	vd_notify(task);
2620 }
2621 
2622 /* ARGSUSED */
2623 static int
2624 vd_geom2dk_geom(void *vd_buf, size_t vd_buf_len, void *ioctl_arg)
2625 {
2626 	VD_GEOM2DK_GEOM((vd_geom_t *)vd_buf, (struct dk_geom *)ioctl_arg);
2627 	return (0);
2628 }
2629 
2630 /* ARGSUSED */
2631 static int
2632 vd_vtoc2vtoc(void *vd_buf, size_t vd_buf_len, void *ioctl_arg)
2633 {
2634 	VD_VTOC2VTOC((vd_vtoc_t *)vd_buf, (struct extvtoc *)ioctl_arg);
2635 	return (0);
2636 }
2637 
2638 static void
2639 dk_geom2vd_geom(void *ioctl_arg, void *vd_buf)
2640 {
2641 	DK_GEOM2VD_GEOM((struct dk_geom *)ioctl_arg, (vd_geom_t *)vd_buf);
2642 }
2643 
2644 static void
2645 vtoc2vd_vtoc(void *ioctl_arg, void *vd_buf)
2646 {
2647 	VTOC2VD_VTOC((struct extvtoc *)ioctl_arg, (vd_vtoc_t *)vd_buf);
2648 }
2649 
2650 static int
2651 vd_get_efi_in(void *vd_buf, size_t vd_buf_len, void *ioctl_arg)
2652 {
2653 	vd_efi_t *vd_efi = (vd_efi_t *)vd_buf;
2654 	dk_efi_t *dk_efi = (dk_efi_t *)ioctl_arg;
2655 	size_t data_len;
2656 
2657 	data_len = vd_buf_len - (sizeof (vd_efi_t) - sizeof (uint64_t));
2658 	if (vd_efi->length > data_len)
2659 		return (EINVAL);
2660 
2661 	dk_efi->dki_lba = vd_efi->lba;
2662 	dk_efi->dki_length = vd_efi->length;
2663 	dk_efi->dki_data = kmem_zalloc(vd_efi->length, KM_SLEEP);
2664 	return (0);
2665 }
2666 
2667 static void
2668 vd_get_efi_out(void *ioctl_arg, void *vd_buf)
2669 {
2670 	int len;
2671 	vd_efi_t *vd_efi = (vd_efi_t *)vd_buf;
2672 	dk_efi_t *dk_efi = (dk_efi_t *)ioctl_arg;
2673 
2674 	len = vd_efi->length;
2675 	DK_EFI2VD_EFI(dk_efi, vd_efi);
2676 	kmem_free(dk_efi->dki_data, len);
2677 }
2678 
2679 static int
2680 vd_set_efi_in(void *vd_buf, size_t vd_buf_len, void *ioctl_arg)
2681 {
2682 	vd_efi_t *vd_efi = (vd_efi_t *)vd_buf;
2683 	dk_efi_t *dk_efi = (dk_efi_t *)ioctl_arg;
2684 	size_t data_len;
2685 
2686 	data_len = vd_buf_len - (sizeof (vd_efi_t) - sizeof (uint64_t));
2687 	if (vd_efi->length > data_len)
2688 		return (EINVAL);
2689 
2690 	dk_efi->dki_data = kmem_alloc(vd_efi->length, KM_SLEEP);
2691 	VD_EFI2DK_EFI(vd_efi, dk_efi);
2692 	return (0);
2693 }
2694 
2695 static void
2696 vd_set_efi_out(void *ioctl_arg, void *vd_buf)
2697 {
2698 	vd_efi_t *vd_efi = (vd_efi_t *)vd_buf;
2699 	dk_efi_t *dk_efi = (dk_efi_t *)ioctl_arg;
2700 
2701 	kmem_free(dk_efi->dki_data, vd_efi->length);
2702 }
2703 
2704 static int
2705 vd_scsicmd_in(void *vd_buf, size_t vd_buf_len, void *ioctl_arg)
2706 {
2707 	size_t vd_scsi_len;
2708 	vd_scsi_t *vd_scsi = (vd_scsi_t *)vd_buf;
2709 	struct uscsi_cmd *uscsi = (struct uscsi_cmd *)ioctl_arg;
2710 
2711 	/* check buffer size */
2712 	vd_scsi_len = VD_SCSI_SIZE;
2713 	vd_scsi_len += P2ROUNDUP(vd_scsi->cdb_len, sizeof (uint64_t));
2714 	vd_scsi_len += P2ROUNDUP(vd_scsi->sense_len, sizeof (uint64_t));
2715 	vd_scsi_len += P2ROUNDUP(vd_scsi->datain_len, sizeof (uint64_t));
2716 	vd_scsi_len += P2ROUNDUP(vd_scsi->dataout_len, sizeof (uint64_t));
2717 
2718 	ASSERT(vd_scsi_len % sizeof (uint64_t) == 0);
2719 
2720 	if (vd_buf_len < vd_scsi_len)
2721 		return (EINVAL);
2722 
2723 	/* set flags */
2724 	uscsi->uscsi_flags = vd_scsi_debug;
2725 
2726 	if (vd_scsi->options & VD_SCSI_OPT_NORETRY) {
2727 		uscsi->uscsi_flags |= USCSI_ISOLATE;
2728 		uscsi->uscsi_flags |= USCSI_DIAGNOSE;
2729 	}
2730 
2731 	/* task attribute */
2732 	switch (vd_scsi->task_attribute) {
2733 	case VD_SCSI_TASK_ACA:
2734 		uscsi->uscsi_flags |= USCSI_HEAD;
2735 		break;
2736 	case VD_SCSI_TASK_HQUEUE:
2737 		uscsi->uscsi_flags |= USCSI_HTAG;
2738 		break;
2739 	case VD_SCSI_TASK_ORDERED:
2740 		uscsi->uscsi_flags |= USCSI_OTAG;
2741 		break;
2742 	default:
2743 		uscsi->uscsi_flags |= USCSI_NOTAG;
2744 		break;
2745 	}
2746 
2747 	/* timeout */
2748 	uscsi->uscsi_timeout = vd_scsi->timeout;
2749 
2750 	/* cdb data */
2751 	uscsi->uscsi_cdb = (caddr_t)VD_SCSI_DATA_CDB(vd_scsi);
2752 	uscsi->uscsi_cdblen = vd_scsi->cdb_len;
2753 
2754 	/* sense buffer */
2755 	if (vd_scsi->sense_len != 0) {
2756 		uscsi->uscsi_flags |= USCSI_RQENABLE;
2757 		uscsi->uscsi_rqbuf = (caddr_t)VD_SCSI_DATA_SENSE(vd_scsi);
2758 		uscsi->uscsi_rqlen = vd_scsi->sense_len;
2759 	}
2760 
2761 	if (vd_scsi->datain_len != 0 && vd_scsi->dataout_len != 0) {
2762 		/* uscsi does not support read/write request */
2763 		return (EINVAL);
2764 	}
2765 
2766 	/* request data-in */
2767 	if (vd_scsi->datain_len != 0) {
2768 		uscsi->uscsi_flags |= USCSI_READ;
2769 		uscsi->uscsi_buflen = vd_scsi->datain_len;
2770 		uscsi->uscsi_bufaddr = (char *)VD_SCSI_DATA_IN(vd_scsi);
2771 	}
2772 
2773 	/* request data-out */
2774 	if (vd_scsi->dataout_len != 0) {
2775 		uscsi->uscsi_buflen = vd_scsi->dataout_len;
2776 		uscsi->uscsi_bufaddr = (char *)VD_SCSI_DATA_OUT(vd_scsi);
2777 	}
2778 
2779 	return (0);
2780 }
2781 
2782 static void
2783 vd_scsicmd_out(void *ioctl_arg, void *vd_buf)
2784 {
2785 	vd_scsi_t *vd_scsi = (vd_scsi_t *)vd_buf;
2786 	struct uscsi_cmd *uscsi = (struct uscsi_cmd *)ioctl_arg;
2787 
2788 	/* output fields */
2789 	vd_scsi->cmd_status = uscsi->uscsi_status;
2790 
2791 	/* sense data */
2792 	if ((uscsi->uscsi_flags & USCSI_RQENABLE) &&
2793 	    (uscsi->uscsi_status == STATUS_CHECK ||
2794 	    uscsi->uscsi_status == STATUS_TERMINATED)) {
2795 		vd_scsi->sense_status = uscsi->uscsi_rqstatus;
2796 		if (uscsi->uscsi_rqstatus == STATUS_GOOD)
2797 			vd_scsi->sense_len -= uscsi->uscsi_rqresid;
2798 		else
2799 			vd_scsi->sense_len = 0;
2800 	} else {
2801 		vd_scsi->sense_len = 0;
2802 	}
2803 
2804 	if (uscsi->uscsi_status != STATUS_GOOD) {
2805 		vd_scsi->dataout_len = 0;
2806 		vd_scsi->datain_len = 0;
2807 		return;
2808 	}
2809 
2810 	if (uscsi->uscsi_flags & USCSI_READ) {
2811 		/* request data (read) */
2812 		vd_scsi->datain_len -= uscsi->uscsi_resid;
2813 		vd_scsi->dataout_len = 0;
2814 	} else {
2815 		/* request data (write) */
2816 		vd_scsi->datain_len = 0;
2817 		vd_scsi->dataout_len -= uscsi->uscsi_resid;
2818 	}
2819 }
2820 
2821 static ushort_t
2822 vd_lbl2cksum(struct dk_label *label)
2823 {
2824 	int	count;
2825 	ushort_t sum, *sp;
2826 
2827 	count =	(sizeof (struct dk_label)) / (sizeof (short)) - 1;
2828 	sp = (ushort_t *)label;
2829 	sum = 0;
2830 	while (count--) {
2831 		sum ^= *sp++;
2832 	}
2833 
2834 	return (sum);
2835 }
2836 
2837 /*
2838  * Copy information from a vtoc and dk_geom structures to a dk_label structure.
2839  */
2840 static void
2841 vd_vtocgeom_to_label(struct extvtoc *vtoc, struct dk_geom *geom,
2842     struct dk_label *label)
2843 {
2844 	int i;
2845 
2846 	ASSERT(vtoc->v_nparts == V_NUMPAR);
2847 	ASSERT(vtoc->v_sanity == VTOC_SANE);
2848 
2849 	bzero(label, sizeof (struct dk_label));
2850 
2851 	label->dkl_ncyl = geom->dkg_ncyl;
2852 	label->dkl_acyl = geom->dkg_acyl;
2853 	label->dkl_pcyl = geom->dkg_pcyl;
2854 	label->dkl_nhead = geom->dkg_nhead;
2855 	label->dkl_nsect = geom->dkg_nsect;
2856 	label->dkl_intrlv = geom->dkg_intrlv;
2857 	label->dkl_apc = geom->dkg_apc;
2858 	label->dkl_rpm = geom->dkg_rpm;
2859 	label->dkl_write_reinstruct = geom->dkg_write_reinstruct;
2860 	label->dkl_read_reinstruct = geom->dkg_read_reinstruct;
2861 
2862 	label->dkl_vtoc.v_nparts = V_NUMPAR;
2863 	label->dkl_vtoc.v_sanity = VTOC_SANE;
2864 	label->dkl_vtoc.v_version = vtoc->v_version;
2865 	for (i = 0; i < V_NUMPAR; i++) {
2866 		label->dkl_vtoc.v_timestamp[i] = vtoc->timestamp[i];
2867 		label->dkl_vtoc.v_part[i].p_tag = vtoc->v_part[i].p_tag;
2868 		label->dkl_vtoc.v_part[i].p_flag = vtoc->v_part[i].p_flag;
2869 		label->dkl_map[i].dkl_cylno = vtoc->v_part[i].p_start /
2870 		    (label->dkl_nhead * label->dkl_nsect);
2871 		label->dkl_map[i].dkl_nblk = vtoc->v_part[i].p_size;
2872 	}
2873 
2874 	/*
2875 	 * The bootinfo array can not be copied with bcopy() because
2876 	 * elements are of type long in vtoc (so 64-bit) and of type
2877 	 * int in dk_vtoc (so 32-bit).
2878 	 */
2879 	label->dkl_vtoc.v_bootinfo[0] = vtoc->v_bootinfo[0];
2880 	label->dkl_vtoc.v_bootinfo[1] = vtoc->v_bootinfo[1];
2881 	label->dkl_vtoc.v_bootinfo[2] = vtoc->v_bootinfo[2];
2882 	bcopy(vtoc->v_asciilabel, label->dkl_asciilabel, LEN_DKL_ASCII);
2883 	bcopy(vtoc->v_volume, label->dkl_vtoc.v_volume, LEN_DKL_VVOL);
2884 
2885 	/* re-compute checksum */
2886 	label->dkl_magic = DKL_MAGIC;
2887 	label->dkl_cksum = vd_lbl2cksum(label);
2888 }
2889 
2890 /*
2891  * Copy information from a dk_label structure to a vtoc and dk_geom structures.
2892  */
2893 static void
2894 vd_label_to_vtocgeom(struct dk_label *label, struct extvtoc *vtoc,
2895     struct dk_geom *geom)
2896 {
2897 	int i;
2898 
2899 	bzero(vtoc, sizeof (struct vtoc));
2900 	bzero(geom, sizeof (struct dk_geom));
2901 
2902 	geom->dkg_ncyl = label->dkl_ncyl;
2903 	geom->dkg_acyl = label->dkl_acyl;
2904 	geom->dkg_nhead = label->dkl_nhead;
2905 	geom->dkg_nsect = label->dkl_nsect;
2906 	geom->dkg_intrlv = label->dkl_intrlv;
2907 	geom->dkg_apc = label->dkl_apc;
2908 	geom->dkg_rpm = label->dkl_rpm;
2909 	geom->dkg_pcyl = label->dkl_pcyl;
2910 	geom->dkg_write_reinstruct = label->dkl_write_reinstruct;
2911 	geom->dkg_read_reinstruct = label->dkl_read_reinstruct;
2912 
2913 	vtoc->v_sanity = label->dkl_vtoc.v_sanity;
2914 	vtoc->v_version = label->dkl_vtoc.v_version;
2915 	vtoc->v_sectorsz = DEV_BSIZE;
2916 	vtoc->v_nparts = label->dkl_vtoc.v_nparts;
2917 
2918 	for (i = 0; i < vtoc->v_nparts; i++) {
2919 		vtoc->v_part[i].p_tag = label->dkl_vtoc.v_part[i].p_tag;
2920 		vtoc->v_part[i].p_flag = label->dkl_vtoc.v_part[i].p_flag;
2921 		vtoc->v_part[i].p_start = label->dkl_map[i].dkl_cylno *
2922 		    (label->dkl_nhead * label->dkl_nsect);
2923 		vtoc->v_part[i].p_size = label->dkl_map[i].dkl_nblk;
2924 		vtoc->timestamp[i] = label->dkl_vtoc.v_timestamp[i];
2925 	}
2926 
2927 	/*
2928 	 * The bootinfo array can not be copied with bcopy() because
2929 	 * elements are of type long in vtoc (so 64-bit) and of type
2930 	 * int in dk_vtoc (so 32-bit).
2931 	 */
2932 	vtoc->v_bootinfo[0] = label->dkl_vtoc.v_bootinfo[0];
2933 	vtoc->v_bootinfo[1] = label->dkl_vtoc.v_bootinfo[1];
2934 	vtoc->v_bootinfo[2] = label->dkl_vtoc.v_bootinfo[2];
2935 	bcopy(label->dkl_asciilabel, vtoc->v_asciilabel, LEN_DKL_ASCII);
2936 	bcopy(label->dkl_vtoc.v_volume, vtoc->v_volume, LEN_DKL_VVOL);
2937 }
2938 
2939 /*
2940  * Check if a geometry is valid for a single-slice disk. A geometry is
2941  * considered valid if the main attributes of the geometry match with the
2942  * attributes of the fake geometry we have created.
2943  */
2944 static boolean_t
2945 vd_slice_geom_isvalid(vd_t *vd, struct dk_geom *geom)
2946 {
2947 	ASSERT(vd->vdisk_type == VD_DISK_TYPE_SLICE);
2948 	ASSERT(vd->vdisk_label == VD_DISK_LABEL_VTOC);
2949 
2950 	if (geom->dkg_ncyl != vd->dk_geom.dkg_ncyl ||
2951 	    geom->dkg_acyl != vd->dk_geom.dkg_acyl ||
2952 	    geom->dkg_nsect != vd->dk_geom.dkg_nsect ||
2953 	    geom->dkg_pcyl != vd->dk_geom.dkg_pcyl)
2954 		return (B_FALSE);
2955 
2956 	return (B_TRUE);
2957 }
2958 
2959 /*
2960  * Check if a vtoc is valid for a single-slice disk. A vtoc is considered
2961  * valid if the main attributes of the vtoc match with the attributes of the
2962  * fake vtoc we have created.
2963  */
2964 static boolean_t
2965 vd_slice_vtoc_isvalid(vd_t *vd, struct extvtoc *vtoc)
2966 {
2967 	size_t csize;
2968 	int i;
2969 
2970 	ASSERT(vd->vdisk_type == VD_DISK_TYPE_SLICE);
2971 	ASSERT(vd->vdisk_label == VD_DISK_LABEL_VTOC);
2972 
2973 	if (vtoc->v_sanity != vd->vtoc.v_sanity ||
2974 	    vtoc->v_version != vd->vtoc.v_version ||
2975 	    vtoc->v_nparts != vd->vtoc.v_nparts ||
2976 	    strcmp(vtoc->v_volume, vd->vtoc.v_volume) != 0 ||
2977 	    strcmp(vtoc->v_asciilabel, vd->vtoc.v_asciilabel) != 0)
2978 		return (B_FALSE);
2979 
2980 	/* slice 2 should be unchanged */
2981 	if (vtoc->v_part[VD_ENTIRE_DISK_SLICE].p_start !=
2982 	    vd->vtoc.v_part[VD_ENTIRE_DISK_SLICE].p_start ||
2983 	    vtoc->v_part[VD_ENTIRE_DISK_SLICE].p_size !=
2984 	    vd->vtoc.v_part[VD_ENTIRE_DISK_SLICE].p_size)
2985 		return (B_FALSE);
2986 
2987 	/*
2988 	 * Slice 0 should be mostly unchanged and cover most of the disk.
2989 	 * However we allow some flexibility wrt to the start and the size
2990 	 * of this slice mainly because we can't exactly know how it will
2991 	 * be defined by the OS installer.
2992 	 *
2993 	 * We allow slice 0 to be defined as starting on any of the first
2994 	 * 4 cylinders.
2995 	 */
2996 	csize = vd->dk_geom.dkg_nhead * vd->dk_geom.dkg_nsect;
2997 
2998 	if (vtoc->v_part[0].p_start > 4 * csize ||
2999 	    vtoc->v_part[0].p_size > vtoc->v_part[VD_ENTIRE_DISK_SLICE].p_size)
3000 			return (B_FALSE);
3001 
3002 	if (vd->vtoc.v_part[0].p_size >= 4 * csize &&
3003 	    vtoc->v_part[0].p_size < vd->vtoc.v_part[0].p_size - 4 *csize)
3004 			return (B_FALSE);
3005 
3006 	/* any other slice should have a size of 0 */
3007 	for (i = 1; i < vtoc->v_nparts; i++) {
3008 		if (i != VD_ENTIRE_DISK_SLICE &&
3009 		    vtoc->v_part[i].p_size != 0)
3010 			return (B_FALSE);
3011 	}
3012 
3013 	return (B_TRUE);
3014 }
3015 
3016 /*
3017  * Handle ioctls to a disk slice.
3018  *
3019  * Return Values
3020  *	0	- Indicates that there are no errors in disk operations
3021  *	ENOTSUP	- Unknown disk label type or unsupported DKIO ioctl
3022  *	EINVAL	- Not enough room to copy the EFI label
3023  *
3024  */
3025 static int
3026 vd_do_slice_ioctl(vd_t *vd, int cmd, void *ioctl_arg)
3027 {
3028 	dk_efi_t *dk_ioc;
3029 	struct extvtoc *vtoc;
3030 	struct dk_geom *geom;
3031 	size_t len, lba;
3032 
3033 	ASSERT(vd->vdisk_type == VD_DISK_TYPE_SLICE);
3034 
3035 	if (cmd == DKIOCFLUSHWRITECACHE)
3036 		return (vd_flush_write(vd));
3037 
3038 	switch (vd->vdisk_label) {
3039 
3040 	/* ioctls for a single slice disk with a VTOC label */
3041 	case VD_DISK_LABEL_VTOC:
3042 
3043 		switch (cmd) {
3044 
3045 		case DKIOCGGEOM:
3046 			ASSERT(ioctl_arg != NULL);
3047 			bcopy(&vd->dk_geom, ioctl_arg, sizeof (vd->dk_geom));
3048 			return (0);
3049 
3050 		case DKIOCGEXTVTOC:
3051 			ASSERT(ioctl_arg != NULL);
3052 			bcopy(&vd->vtoc, ioctl_arg, sizeof (vd->vtoc));
3053 			return (0);
3054 
3055 		case DKIOCSGEOM:
3056 			ASSERT(ioctl_arg != NULL);
3057 			if (vd_slice_single_slice)
3058 				return (ENOTSUP);
3059 
3060 			/* fake success only if new geometry is valid */
3061 			geom = (struct dk_geom *)ioctl_arg;
3062 			if (!vd_slice_geom_isvalid(vd, geom))
3063 				return (EINVAL);
3064 
3065 			return (0);
3066 
3067 		case DKIOCSEXTVTOC:
3068 			ASSERT(ioctl_arg != NULL);
3069 			if (vd_slice_single_slice)
3070 				return (ENOTSUP);
3071 
3072 			/* fake sucess only if the new vtoc is valid */
3073 			vtoc = (struct extvtoc *)ioctl_arg;
3074 			if (!vd_slice_vtoc_isvalid(vd, vtoc))
3075 				return (EINVAL);
3076 
3077 			return (0);
3078 
3079 		default:
3080 			return (ENOTSUP);
3081 		}
3082 
3083 	/* ioctls for a single slice disk with an EFI label */
3084 	case VD_DISK_LABEL_EFI:
3085 
3086 		if (cmd != DKIOCGETEFI && cmd != DKIOCSETEFI)
3087 			return (ENOTSUP);
3088 
3089 		ASSERT(ioctl_arg != NULL);
3090 		dk_ioc = (dk_efi_t *)ioctl_arg;
3091 
3092 		len = dk_ioc->dki_length;
3093 		lba = dk_ioc->dki_lba;
3094 
3095 		if ((lba != VD_EFI_LBA_GPT && lba != VD_EFI_LBA_GPE) ||
3096 		    (lba == VD_EFI_LBA_GPT && len < sizeof (efi_gpt_t)) ||
3097 		    (lba == VD_EFI_LBA_GPE && len < sizeof (efi_gpe_t)))
3098 			return (EINVAL);
3099 
3100 		switch (cmd) {
3101 		case DKIOCGETEFI:
3102 			len = vd_slice_flabel_read(vd,
3103 			    (caddr_t)dk_ioc->dki_data, lba * DEV_BSIZE, len);
3104 
3105 			ASSERT(len > 0);
3106 
3107 			return (0);
3108 
3109 		case DKIOCSETEFI:
3110 			if (vd_slice_single_slice)
3111 				return (ENOTSUP);
3112 
3113 			/* we currently don't support writing EFI */
3114 			return (EIO);
3115 		}
3116 
3117 	default:
3118 		/* Unknown disk label type */
3119 		return (ENOTSUP);
3120 	}
3121 }
3122 
3123 static int
3124 vds_efi_alloc_and_read(vd_t *vd, efi_gpt_t **gpt, efi_gpe_t **gpe)
3125 {
3126 	vd_efi_dev_t edev;
3127 	int status;
3128 
3129 	VD_EFI_DEV_SET(edev, vd, (vd_efi_ioctl_func)vd_backend_ioctl);
3130 
3131 	status = vd_efi_alloc_and_read(&edev, gpt, gpe);
3132 
3133 	return (status);
3134 }
3135 
3136 static void
3137 vds_efi_free(vd_t *vd, efi_gpt_t *gpt, efi_gpe_t *gpe)
3138 {
3139 	vd_efi_dev_t edev;
3140 
3141 	VD_EFI_DEV_SET(edev, vd, (vd_efi_ioctl_func)vd_backend_ioctl);
3142 
3143 	vd_efi_free(&edev, gpt, gpe);
3144 }
3145 
3146 static int
3147 vd_dskimg_validate_efi(vd_t *vd)
3148 {
3149 	efi_gpt_t *gpt;
3150 	efi_gpe_t *gpe;
3151 	int i, nparts, status;
3152 	struct uuid efi_reserved = EFI_RESERVED;
3153 
3154 	if ((status = vds_efi_alloc_and_read(vd, &gpt, &gpe)) != 0)
3155 		return (status);
3156 
3157 	bzero(&vd->vtoc, sizeof (struct extvtoc));
3158 	bzero(&vd->dk_geom, sizeof (struct dk_geom));
3159 	bzero(vd->slices, sizeof (vd_slice_t) * VD_MAXPART);
3160 
3161 	vd->efi_reserved = -1;
3162 
3163 	nparts = gpt->efi_gpt_NumberOfPartitionEntries;
3164 
3165 	for (i = 0; i < nparts && i < VD_MAXPART; i++) {
3166 
3167 		if (gpe[i].efi_gpe_StartingLBA == 0 ||
3168 		    gpe[i].efi_gpe_EndingLBA == 0) {
3169 			continue;
3170 		}
3171 
3172 		vd->slices[i].start = gpe[i].efi_gpe_StartingLBA;
3173 		vd->slices[i].nblocks = gpe[i].efi_gpe_EndingLBA -
3174 		    gpe[i].efi_gpe_StartingLBA + 1;
3175 
3176 		if (bcmp(&gpe[i].efi_gpe_PartitionTypeGUID, &efi_reserved,
3177 		    sizeof (struct uuid)) == 0)
3178 			vd->efi_reserved = i;
3179 
3180 	}
3181 
3182 	ASSERT(vd->vdisk_size != 0);
3183 	vd->slices[VD_EFI_WD_SLICE].start = 0;
3184 	vd->slices[VD_EFI_WD_SLICE].nblocks = vd->vdisk_size;
3185 
3186 	vds_efi_free(vd, gpt, gpe);
3187 
3188 	return (status);
3189 }
3190 
3191 /*
3192  * Function:
3193  *	vd_dskimg_validate_geometry
3194  *
3195  * Description:
3196  *	Read the label and validate the geometry of a disk image. The driver
3197  *	label, vtoc and geometry information are updated according to the
3198  *	label read from the disk image.
3199  *
3200  *	If no valid label is found, the label is set to unknown and the
3201  *	function returns EINVAL, but a default vtoc and geometry are provided
3202  *	to the driver. If an EFI label is found, ENOTSUP is returned.
3203  *
3204  * Parameters:
3205  *	vd	- disk on which the operation is performed.
3206  *
3207  * Return Code:
3208  *	0	- success.
3209  *	EIO	- error reading the label from the disk image.
3210  *	EINVAL	- unknown disk label.
3211  *	ENOTSUP	- geometry not applicable (EFI label).
3212  */
3213 static int
3214 vd_dskimg_validate_geometry(vd_t *vd)
3215 {
3216 	struct dk_label label;
3217 	struct dk_geom *geom = &vd->dk_geom;
3218 	struct extvtoc *vtoc = &vd->vtoc;
3219 	int i;
3220 	int status = 0;
3221 
3222 	ASSERT(VD_DSKIMG(vd));
3223 
3224 	if (VD_DSKIMG_LABEL_READ(vd, &label) < 0)
3225 		return (EIO);
3226 
3227 	if (label.dkl_magic != DKL_MAGIC ||
3228 	    label.dkl_cksum != vd_lbl2cksum(&label) ||
3229 	    (vd_dskimg_validate_sanity &&
3230 	    label.dkl_vtoc.v_sanity != VTOC_SANE) ||
3231 	    label.dkl_vtoc.v_nparts != V_NUMPAR) {
3232 
3233 		if (vd_dskimg_validate_efi(vd) == 0) {
3234 			vd->vdisk_label = VD_DISK_LABEL_EFI;
3235 			return (ENOTSUP);
3236 		}
3237 
3238 		vd->vdisk_label = VD_DISK_LABEL_UNK;
3239 		vd_build_default_label(vd->dskimg_size, &label);
3240 		status = EINVAL;
3241 	} else {
3242 		vd->vdisk_label = VD_DISK_LABEL_VTOC;
3243 	}
3244 
3245 	/* Update the driver geometry and vtoc */
3246 	vd_label_to_vtocgeom(&label, vtoc, geom);
3247 
3248 	/* Update logical partitions */
3249 	bzero(vd->slices, sizeof (vd_slice_t) * VD_MAXPART);
3250 	if (vd->vdisk_label != VD_DISK_LABEL_UNK) {
3251 		for (i = 0; i < vtoc->v_nparts; i++) {
3252 			vd->slices[i].start = vtoc->v_part[i].p_start;
3253 			vd->slices[i].nblocks = vtoc->v_part[i].p_size;
3254 		}
3255 	}
3256 
3257 	return (status);
3258 }
3259 
3260 /*
3261  * Handle ioctls to a disk image.
3262  *
3263  * Return Values
3264  *	0	- Indicates that there are no errors
3265  *	!= 0	- Disk operation returned an error
3266  */
3267 static int
3268 vd_do_dskimg_ioctl(vd_t *vd, int cmd, void *ioctl_arg)
3269 {
3270 	struct dk_label label;
3271 	struct dk_geom *geom;
3272 	struct extvtoc *vtoc;
3273 	dk_efi_t *efi;
3274 	int rc;
3275 
3276 	ASSERT(VD_DSKIMG(vd));
3277 
3278 	switch (cmd) {
3279 
3280 	case DKIOCGGEOM:
3281 		ASSERT(ioctl_arg != NULL);
3282 		geom = (struct dk_geom *)ioctl_arg;
3283 
3284 		rc = vd_dskimg_validate_geometry(vd);
3285 		if (rc != 0 && rc != EINVAL)
3286 			return (rc);
3287 		bcopy(&vd->dk_geom, geom, sizeof (struct dk_geom));
3288 		return (0);
3289 
3290 	case DKIOCGEXTVTOC:
3291 		ASSERT(ioctl_arg != NULL);
3292 		vtoc = (struct extvtoc *)ioctl_arg;
3293 
3294 		rc = vd_dskimg_validate_geometry(vd);
3295 		if (rc != 0 && rc != EINVAL)
3296 			return (rc);
3297 		bcopy(&vd->vtoc, vtoc, sizeof (struct extvtoc));
3298 		return (0);
3299 
3300 	case DKIOCSGEOM:
3301 		ASSERT(ioctl_arg != NULL);
3302 		geom = (struct dk_geom *)ioctl_arg;
3303 
3304 		if (geom->dkg_nhead == 0 || geom->dkg_nsect == 0)
3305 			return (EINVAL);
3306 
3307 		/*
3308 		 * The current device geometry is not updated, just the driver
3309 		 * "notion" of it. The device geometry will be effectively
3310 		 * updated when a label is written to the device during a next
3311 		 * DKIOCSEXTVTOC.
3312 		 */
3313 		bcopy(ioctl_arg, &vd->dk_geom, sizeof (vd->dk_geom));
3314 		return (0);
3315 
3316 	case DKIOCSEXTVTOC:
3317 		ASSERT(ioctl_arg != NULL);
3318 		ASSERT(vd->dk_geom.dkg_nhead != 0 &&
3319 		    vd->dk_geom.dkg_nsect != 0);
3320 		vtoc = (struct extvtoc *)ioctl_arg;
3321 
3322 		if (vtoc->v_sanity != VTOC_SANE ||
3323 		    vtoc->v_sectorsz != DEV_BSIZE ||
3324 		    vtoc->v_nparts != V_NUMPAR)
3325 			return (EINVAL);
3326 
3327 		vd_vtocgeom_to_label(vtoc, &vd->dk_geom, &label);
3328 
3329 		/* write label to the disk image */
3330 		if ((rc = vd_dskimg_set_vtoc(vd, &label)) != 0)
3331 			return (rc);
3332 
3333 		break;
3334 
3335 	case DKIOCFLUSHWRITECACHE:
3336 		return (vd_flush_write(vd));
3337 
3338 	case DKIOCGETEFI:
3339 		ASSERT(ioctl_arg != NULL);
3340 		efi = (dk_efi_t *)ioctl_arg;
3341 
3342 		if (vd_dskimg_rw(vd, VD_SLICE_NONE, VD_OP_BREAD,
3343 		    (caddr_t)efi->dki_data, efi->dki_lba, efi->dki_length) < 0)
3344 			return (EIO);
3345 
3346 		return (0);
3347 
3348 	case DKIOCSETEFI:
3349 		ASSERT(ioctl_arg != NULL);
3350 		efi = (dk_efi_t *)ioctl_arg;
3351 
3352 		if (vd_dskimg_rw(vd, VD_SLICE_NONE, VD_OP_BWRITE,
3353 		    (caddr_t)efi->dki_data, efi->dki_lba, efi->dki_length) < 0)
3354 			return (EIO);
3355 
3356 		break;
3357 
3358 
3359 	default:
3360 		return (ENOTSUP);
3361 	}
3362 
3363 	ASSERT(cmd == DKIOCSEXTVTOC || cmd == DKIOCSETEFI);
3364 
3365 	/* label has changed, revalidate the geometry */
3366 	(void) vd_dskimg_validate_geometry(vd);
3367 
3368 	/*
3369 	 * The disk geometry may have changed, so we need to write
3370 	 * the devid (if there is one) so that it is stored at the
3371 	 * right location.
3372 	 */
3373 	if (vd_dskimg_write_devid(vd, vd->dskimg_devid) != 0) {
3374 		PR0("Fail to write devid");
3375 	}
3376 
3377 	return (0);
3378 }
3379 
3380 static int
3381 vd_backend_ioctl(vd_t *vd, int cmd, caddr_t arg)
3382 {
3383 	int rval = 0, status;
3384 	struct vtoc vtoc;
3385 
3386 	/*
3387 	 * Call the appropriate function to execute the ioctl depending
3388 	 * on the type of vdisk.
3389 	 */
3390 	if (vd->vdisk_type == VD_DISK_TYPE_SLICE) {
3391 
3392 		/* slice, file or volume exported as a single slice disk */
3393 		status = vd_do_slice_ioctl(vd, cmd, arg);
3394 
3395 	} else if (VD_DSKIMG(vd)) {
3396 
3397 		/* file or volume exported as a full disk */
3398 		status = vd_do_dskimg_ioctl(vd, cmd, arg);
3399 
3400 	} else {
3401 
3402 		/* disk device exported as a full disk */
3403 		status = ldi_ioctl(vd->ldi_handle[0], cmd, (intptr_t)arg,
3404 		    vd->open_flags | FKIOCTL, kcred, &rval);
3405 
3406 		/*
3407 		 * By default VTOC ioctls are done using ioctls for the
3408 		 * extended VTOC. Some drivers (in particular non-Sun drivers)
3409 		 * may not support these ioctls. In that case, we fallback to
3410 		 * the regular VTOC ioctls.
3411 		 */
3412 		if (status == ENOTTY) {
3413 			switch (cmd) {
3414 
3415 			case DKIOCGEXTVTOC:
3416 				cmd = DKIOCGVTOC;
3417 				status = ldi_ioctl(vd->ldi_handle[0], cmd,
3418 				    (intptr_t)&vtoc, vd->open_flags | FKIOCTL,
3419 				    kcred, &rval);
3420 				vtoctoextvtoc(vtoc,
3421 				    (*(struct extvtoc *)(void *)arg));
3422 				break;
3423 
3424 			case DKIOCSEXTVTOC:
3425 				cmd = DKIOCSVTOC;
3426 				extvtoctovtoc((*(struct extvtoc *)(void *)arg),
3427 				    vtoc);
3428 				status = ldi_ioctl(vd->ldi_handle[0], cmd,
3429 				    (intptr_t)&vtoc, vd->open_flags | FKIOCTL,
3430 				    kcred, &rval);
3431 				break;
3432 			}
3433 		}
3434 	}
3435 
3436 #ifdef DEBUG
3437 	if (rval != 0) {
3438 		PR0("ioctl %x set rval = %d, which is not being returned"
3439 		    " to caller", cmd, rval);
3440 	}
3441 #endif /* DEBUG */
3442 
3443 	return (status);
3444 }
3445 
3446 /*
3447  * Description:
3448  *	This is the function that processes the ioctl requests (farming it
3449  *	out to functions that handle slices, files or whole disks)
3450  *
3451  * Return Values
3452  *     0		- ioctl operation completed successfully
3453  *     != 0		- The LDC error value encountered
3454  *			  (propagated back up the call stack as a task error)
3455  *
3456  * Side Effect
3457  *     sets request->status to the return value of the ioctl function.
3458  */
3459 static int
3460 vd_do_ioctl(vd_t *vd, vd_dring_payload_t *request, void* buf, vd_ioctl_t *ioctl)
3461 {
3462 	int	status = 0;
3463 	size_t	nbytes = request->nbytes;	/* modifiable copy */
3464 
3465 
3466 	ASSERT(request->slice < vd->nslices);
3467 	PR0("Performing %s", ioctl->operation_name);
3468 
3469 	/* Get data from client and convert, if necessary */
3470 	if (ioctl->copyin != NULL)  {
3471 		ASSERT(nbytes != 0 && buf != NULL);
3472 		PR1("Getting \"arg\" data from client");
3473 		if ((status = ldc_mem_copy(vd->ldc_handle, buf, 0, &nbytes,
3474 		    request->cookie, request->ncookies,
3475 		    LDC_COPY_IN)) != 0) {
3476 			PR0("ldc_mem_copy() returned errno %d "
3477 			    "copying from client", status);
3478 			return (status);
3479 		}
3480 
3481 		/* Convert client's data, if necessary */
3482 		if (ioctl->copyin == VD_IDENTITY_IN) {
3483 			/* use client buffer */
3484 			ioctl->arg = buf;
3485 		} else {
3486 			/* convert client vdisk operation data to ioctl data */
3487 			status = (ioctl->copyin)(buf, nbytes,
3488 			    (void *)ioctl->arg);
3489 			if (status != 0) {
3490 				request->status = status;
3491 				return (0);
3492 			}
3493 		}
3494 	}
3495 
3496 	if (ioctl->operation == VD_OP_SCSICMD) {
3497 		struct uscsi_cmd *uscsi = (struct uscsi_cmd *)ioctl->arg;
3498 
3499 		/* check write permission */
3500 		if (!(vd->open_flags & FWRITE) &&
3501 		    !(uscsi->uscsi_flags & USCSI_READ)) {
3502 			PR0("uscsi fails because backend is opened read-only");
3503 			request->status = EROFS;
3504 			return (0);
3505 		}
3506 	}
3507 
3508 	/*
3509 	 * Send the ioctl to the disk backend.
3510 	 */
3511 	request->status = vd_backend_ioctl(vd, ioctl->cmd, ioctl->arg);
3512 
3513 	if (request->status != 0) {
3514 		PR0("ioctl(%s) = errno %d", ioctl->cmd_name, request->status);
3515 		if (ioctl->operation == VD_OP_SCSICMD &&
3516 		    ((struct uscsi_cmd *)ioctl->arg)->uscsi_status != 0)
3517 			/*
3518 			 * USCSICMD has reported an error and the uscsi_status
3519 			 * field is not zero. This means that the SCSI command
3520 			 * has completed but it has an error. So we should
3521 			 * mark the VD operation has succesfully completed
3522 			 * and clients can check the SCSI status field for
3523 			 * SCSI errors.
3524 			 */
3525 			request->status = 0;
3526 		else
3527 			return (0);
3528 	}
3529 
3530 	/* Convert data and send to client, if necessary */
3531 	if (ioctl->copyout != NULL)  {
3532 		ASSERT(nbytes != 0 && buf != NULL);
3533 		PR1("Sending \"arg\" data to client");
3534 
3535 		/* Convert ioctl data to vdisk operation data, if necessary */
3536 		if (ioctl->copyout != VD_IDENTITY_OUT)
3537 			(ioctl->copyout)((void *)ioctl->arg, buf);
3538 
3539 		if ((status = ldc_mem_copy(vd->ldc_handle, buf, 0, &nbytes,
3540 		    request->cookie, request->ncookies,
3541 		    LDC_COPY_OUT)) != 0) {
3542 			PR0("ldc_mem_copy() returned errno %d "
3543 			    "copying to client", status);
3544 			return (status);
3545 		}
3546 	}
3547 
3548 	return (status);
3549 }
3550 
3551 #define	RNDSIZE(expr) P2ROUNDUP(sizeof (expr), sizeof (uint64_t))
3552 
3553 /*
3554  * Description:
3555  *	This generic function is called by the task queue to complete
3556  *	the processing of the tasks. The specific completion function
3557  *	is passed in as a field in the task pointer.
3558  *
3559  * Parameters:
3560  *	arg 	- opaque pointer to structure containing task to be completed
3561  *
3562  * Return Values
3563  *	None
3564  */
3565 static void
3566 vd_complete(void *arg)
3567 {
3568 	vd_task_t	*task = (vd_task_t *)arg;
3569 
3570 	ASSERT(task != NULL);
3571 	ASSERT(task->status == EINPROGRESS);
3572 	ASSERT(task->completef != NULL);
3573 
3574 	task->status = task->completef(task);
3575 	if (task->status)
3576 		PR0("%s: Error %d completing task", __func__, task->status);
3577 
3578 	/* Now notify the vDisk client */
3579 	vd_complete_notify(task);
3580 }
3581 
3582 static int
3583 vd_ioctl(vd_task_t *task)
3584 {
3585 	int			i, status;
3586 	void			*buf = NULL;
3587 	struct dk_geom		dk_geom = {0};
3588 	struct extvtoc		vtoc = {0};
3589 	struct dk_efi		dk_efi = {0};
3590 	struct uscsi_cmd	uscsi = {0};
3591 	vd_t			*vd		= task->vd;
3592 	vd_dring_payload_t	*request	= task->request;
3593 	vd_ioctl_t		ioctl[] = {
3594 		/* Command (no-copy) operations */
3595 		{VD_OP_FLUSH, STRINGIZE(VD_OP_FLUSH), 0,
3596 		    DKIOCFLUSHWRITECACHE, STRINGIZE(DKIOCFLUSHWRITECACHE),
3597 		    NULL, NULL, NULL, B_TRUE},
3598 
3599 		/* "Get" (copy-out) operations */
3600 		{VD_OP_GET_WCE, STRINGIZE(VD_OP_GET_WCE), RNDSIZE(int),
3601 		    DKIOCGETWCE, STRINGIZE(DKIOCGETWCE),
3602 		    NULL, VD_IDENTITY_IN, VD_IDENTITY_OUT, B_FALSE},
3603 		{VD_OP_GET_DISKGEOM, STRINGIZE(VD_OP_GET_DISKGEOM),
3604 		    RNDSIZE(vd_geom_t),
3605 		    DKIOCGGEOM, STRINGIZE(DKIOCGGEOM),
3606 		    &dk_geom, NULL, dk_geom2vd_geom, B_FALSE},
3607 		{VD_OP_GET_VTOC, STRINGIZE(VD_OP_GET_VTOC), RNDSIZE(vd_vtoc_t),
3608 		    DKIOCGEXTVTOC, STRINGIZE(DKIOCGEXTVTOC),
3609 		    &vtoc, NULL, vtoc2vd_vtoc, B_FALSE},
3610 		{VD_OP_GET_EFI, STRINGIZE(VD_OP_GET_EFI), RNDSIZE(vd_efi_t),
3611 		    DKIOCGETEFI, STRINGIZE(DKIOCGETEFI),
3612 		    &dk_efi, vd_get_efi_in, vd_get_efi_out, B_FALSE},
3613 
3614 		/* "Set" (copy-in) operations */
3615 		{VD_OP_SET_WCE, STRINGIZE(VD_OP_SET_WCE), RNDSIZE(int),
3616 		    DKIOCSETWCE, STRINGIZE(DKIOCSETWCE),
3617 		    NULL, VD_IDENTITY_IN, VD_IDENTITY_OUT, B_TRUE},
3618 		{VD_OP_SET_DISKGEOM, STRINGIZE(VD_OP_SET_DISKGEOM),
3619 		    RNDSIZE(vd_geom_t),
3620 		    DKIOCSGEOM, STRINGIZE(DKIOCSGEOM),
3621 		    &dk_geom, vd_geom2dk_geom, NULL, B_TRUE},
3622 		{VD_OP_SET_VTOC, STRINGIZE(VD_OP_SET_VTOC), RNDSIZE(vd_vtoc_t),
3623 		    DKIOCSEXTVTOC, STRINGIZE(DKIOCSEXTVTOC),
3624 		    &vtoc, vd_vtoc2vtoc, NULL, B_TRUE},
3625 		{VD_OP_SET_EFI, STRINGIZE(VD_OP_SET_EFI), RNDSIZE(vd_efi_t),
3626 		    DKIOCSETEFI, STRINGIZE(DKIOCSETEFI),
3627 		    &dk_efi, vd_set_efi_in, vd_set_efi_out, B_TRUE},
3628 
3629 		{VD_OP_SCSICMD, STRINGIZE(VD_OP_SCSICMD), RNDSIZE(vd_scsi_t),
3630 		    USCSICMD, STRINGIZE(USCSICMD),
3631 		    &uscsi, vd_scsicmd_in, vd_scsicmd_out, B_FALSE},
3632 	};
3633 	size_t		nioctls = (sizeof (ioctl))/(sizeof (ioctl[0]));
3634 
3635 
3636 	ASSERT(vd != NULL);
3637 	ASSERT(request != NULL);
3638 	ASSERT(request->slice < vd->nslices);
3639 
3640 	/*
3641 	 * Determine ioctl corresponding to caller's "operation" and
3642 	 * validate caller's "nbytes"
3643 	 */
3644 	for (i = 0; i < nioctls; i++) {
3645 		if (request->operation == ioctl[i].operation) {
3646 			/* LDC memory operations require 8-byte multiples */
3647 			ASSERT(ioctl[i].nbytes % sizeof (uint64_t) == 0);
3648 
3649 			if (request->operation == VD_OP_GET_EFI ||
3650 			    request->operation == VD_OP_SET_EFI ||
3651 			    request->operation == VD_OP_SCSICMD) {
3652 				if (request->nbytes >= ioctl[i].nbytes)
3653 					break;
3654 				PR0("%s:  Expected at least nbytes = %lu, "
3655 				    "got %lu", ioctl[i].operation_name,
3656 				    ioctl[i].nbytes, request->nbytes);
3657 				return (EINVAL);
3658 			}
3659 
3660 			if (request->nbytes != ioctl[i].nbytes) {
3661 				PR0("%s:  Expected nbytes = %lu, got %lu",
3662 				    ioctl[i].operation_name, ioctl[i].nbytes,
3663 				    request->nbytes);
3664 				return (EINVAL);
3665 			}
3666 
3667 			break;
3668 		}
3669 	}
3670 	ASSERT(i < nioctls);	/* because "operation" already validated */
3671 
3672 	if (!(vd->open_flags & FWRITE) && ioctl[i].write) {
3673 		PR0("%s fails because backend is opened read-only",
3674 		    ioctl[i].operation_name);
3675 		request->status = EROFS;
3676 		return (0);
3677 	}
3678 
3679 	if (request->nbytes)
3680 		buf = kmem_zalloc(request->nbytes, KM_SLEEP);
3681 	status = vd_do_ioctl(vd, request, buf, &ioctl[i]);
3682 	if (request->nbytes)
3683 		kmem_free(buf, request->nbytes);
3684 
3685 	return (status);
3686 }
3687 
3688 static int
3689 vd_get_devid(vd_task_t *task)
3690 {
3691 	vd_t *vd = task->vd;
3692 	vd_dring_payload_t *request = task->request;
3693 	vd_devid_t *vd_devid;
3694 	impl_devid_t *devid;
3695 	int status, bufid_len, devid_len, len, sz;
3696 	int bufbytes;
3697 
3698 	PR1("Get Device ID, nbytes=%ld", request->nbytes);
3699 
3700 	if (vd->vdisk_type == VD_DISK_TYPE_SLICE) {
3701 		/*
3702 		 * We don't support devid for single-slice disks because we
3703 		 * have no space to store a fabricated devid and for physical
3704 		 * disk slices, we can't use the devid of the disk otherwise
3705 		 * exporting multiple slices from the same disk will produce
3706 		 * the same devids.
3707 		 */
3708 		PR2("No Device ID for slices");
3709 		request->status = ENOTSUP;
3710 		return (0);
3711 	}
3712 
3713 	if (VD_DSKIMG(vd)) {
3714 		if (vd->dskimg_devid == NULL) {
3715 			PR2("No Device ID");
3716 			request->status = ENOENT;
3717 			return (0);
3718 		} else {
3719 			sz = ddi_devid_sizeof(vd->dskimg_devid);
3720 			devid = kmem_alloc(sz, KM_SLEEP);
3721 			bcopy(vd->dskimg_devid, devid, sz);
3722 		}
3723 	} else {
3724 		if (ddi_lyr_get_devid(vd->dev[request->slice],
3725 		    (ddi_devid_t *)&devid) != DDI_SUCCESS) {
3726 			PR2("No Device ID");
3727 			request->status = ENOENT;
3728 			return (0);
3729 		}
3730 	}
3731 
3732 	bufid_len = request->nbytes - sizeof (vd_devid_t) + 1;
3733 	devid_len = DEVID_GETLEN(devid);
3734 
3735 	/*
3736 	 * Save the buffer size here for use in deallocation.
3737 	 * The actual number of bytes copied is returned in
3738 	 * the 'nbytes' field of the request structure.
3739 	 */
3740 	bufbytes = request->nbytes;
3741 
3742 	vd_devid = kmem_zalloc(bufbytes, KM_SLEEP);
3743 	vd_devid->length = devid_len;
3744 	vd_devid->type = DEVID_GETTYPE(devid);
3745 
3746 	len = (devid_len > bufid_len)? bufid_len : devid_len;
3747 
3748 	bcopy(devid->did_id, vd_devid->id, len);
3749 
3750 	request->status = 0;
3751 
3752 	/* LDC memory operations require 8-byte multiples */
3753 	ASSERT(request->nbytes % sizeof (uint64_t) == 0);
3754 
3755 	if ((status = ldc_mem_copy(vd->ldc_handle, (caddr_t)vd_devid, 0,
3756 	    &request->nbytes, request->cookie, request->ncookies,
3757 	    LDC_COPY_OUT)) != 0) {
3758 		PR0("ldc_mem_copy() returned errno %d copying to client",
3759 		    status);
3760 	}
3761 	PR1("post mem_copy: nbytes=%ld", request->nbytes);
3762 
3763 	kmem_free(vd_devid, bufbytes);
3764 	ddi_devid_free((ddi_devid_t)devid);
3765 
3766 	return (status);
3767 }
3768 
3769 static int
3770 vd_scsi_reset(vd_t *vd)
3771 {
3772 	int rval, status;
3773 	struct uscsi_cmd uscsi = { 0 };
3774 
3775 	uscsi.uscsi_flags = vd_scsi_debug | USCSI_RESET;
3776 	uscsi.uscsi_timeout = vd_scsi_rdwr_timeout;
3777 
3778 	status = ldi_ioctl(vd->ldi_handle[0], USCSICMD, (intptr_t)&uscsi,
3779 	    (vd->open_flags | FKIOCTL), kcred, &rval);
3780 
3781 	return (status);
3782 }
3783 
3784 static int
3785 vd_reset(vd_task_t *task)
3786 {
3787 	vd_t *vd = task->vd;
3788 	vd_dring_payload_t *request = task->request;
3789 
3790 	ASSERT(request->operation == VD_OP_RESET);
3791 	ASSERT(vd->scsi);
3792 
3793 	PR0("Performing VD_OP_RESET");
3794 
3795 	if (request->nbytes != 0) {
3796 		PR0("VD_OP_RESET:  Expected nbytes = 0, got %lu",
3797 		    request->nbytes);
3798 		return (EINVAL);
3799 	}
3800 
3801 	request->status = vd_scsi_reset(vd);
3802 
3803 	return (0);
3804 }
3805 
3806 static int
3807 vd_get_capacity(vd_task_t *task)
3808 {
3809 	int rv;
3810 	size_t nbytes;
3811 	vd_t *vd = task->vd;
3812 	vd_dring_payload_t *request = task->request;
3813 	vd_capacity_t vd_cap = { 0 };
3814 
3815 	ASSERT(request->operation == VD_OP_GET_CAPACITY);
3816 
3817 	PR0("Performing VD_OP_GET_CAPACITY");
3818 
3819 	nbytes = request->nbytes;
3820 
3821 	if (nbytes != RNDSIZE(vd_capacity_t)) {
3822 		PR0("VD_OP_GET_CAPACITY:  Expected nbytes = %lu, got %lu",
3823 		    RNDSIZE(vd_capacity_t), nbytes);
3824 		return (EINVAL);
3825 	}
3826 
3827 	/*
3828 	 * Check the backend size in case it has changed. If the check fails
3829 	 * then we will return the last known size.
3830 	 */
3831 
3832 	(void) vd_backend_check_size(vd);
3833 	ASSERT(vd->vdisk_size != 0);
3834 
3835 	request->status = 0;
3836 
3837 	vd_cap.vdisk_block_size = vd->vdisk_block_size;
3838 	vd_cap.vdisk_size = vd->vdisk_size;
3839 
3840 	if ((rv = ldc_mem_copy(vd->ldc_handle, (char *)&vd_cap, 0, &nbytes,
3841 	    request->cookie, request->ncookies, LDC_COPY_OUT)) != 0) {
3842 		PR0("ldc_mem_copy() returned errno %d copying to client", rv);
3843 		return (rv);
3844 	}
3845 
3846 	return (0);
3847 }
3848 
3849 static int
3850 vd_get_access(vd_task_t *task)
3851 {
3852 	uint64_t access;
3853 	int rv, rval = 0;
3854 	size_t nbytes;
3855 	vd_t *vd = task->vd;
3856 	vd_dring_payload_t *request = task->request;
3857 
3858 	ASSERT(request->operation == VD_OP_GET_ACCESS);
3859 	ASSERT(vd->scsi);
3860 
3861 	PR0("Performing VD_OP_GET_ACCESS");
3862 
3863 	nbytes = request->nbytes;
3864 
3865 	if (nbytes != sizeof (uint64_t)) {
3866 		PR0("VD_OP_GET_ACCESS:  Expected nbytes = %lu, got %lu",
3867 		    sizeof (uint64_t), nbytes);
3868 		return (EINVAL);
3869 	}
3870 
3871 	request->status = ldi_ioctl(vd->ldi_handle[request->slice], MHIOCSTATUS,
3872 	    NULL, (vd->open_flags | FKIOCTL), kcred, &rval);
3873 
3874 	if (request->status != 0)
3875 		return (0);
3876 
3877 	access = (rval == 0)? VD_ACCESS_ALLOWED : VD_ACCESS_DENIED;
3878 
3879 	if ((rv = ldc_mem_copy(vd->ldc_handle, (char *)&access, 0, &nbytes,
3880 	    request->cookie, request->ncookies, LDC_COPY_OUT)) != 0) {
3881 		PR0("ldc_mem_copy() returned errno %d copying to client", rv);
3882 		return (rv);
3883 	}
3884 
3885 	return (0);
3886 }
3887 
3888 static int
3889 vd_set_access(vd_task_t *task)
3890 {
3891 	uint64_t flags;
3892 	int rv, rval;
3893 	size_t nbytes;
3894 	vd_t *vd = task->vd;
3895 	vd_dring_payload_t *request = task->request;
3896 
3897 	ASSERT(request->operation == VD_OP_SET_ACCESS);
3898 	ASSERT(vd->scsi);
3899 
3900 	nbytes = request->nbytes;
3901 
3902 	if (nbytes != sizeof (uint64_t)) {
3903 		PR0("VD_OP_SET_ACCESS:  Expected nbytes = %lu, got %lu",
3904 		    sizeof (uint64_t), nbytes);
3905 		return (EINVAL);
3906 	}
3907 
3908 	if ((rv = ldc_mem_copy(vd->ldc_handle, (char *)&flags, 0, &nbytes,
3909 	    request->cookie, request->ncookies, LDC_COPY_IN)) != 0) {
3910 		PR0("ldc_mem_copy() returned errno %d copying from client", rv);
3911 		return (rv);
3912 	}
3913 
3914 	if (flags == VD_ACCESS_SET_CLEAR) {
3915 		PR0("Performing VD_OP_SET_ACCESS (CLEAR)");
3916 		request->status = ldi_ioctl(vd->ldi_handle[request->slice],
3917 		    MHIOCRELEASE, NULL, (vd->open_flags | FKIOCTL), kcred,
3918 		    &rval);
3919 		if (request->status == 0)
3920 			vd->ownership = B_FALSE;
3921 		return (0);
3922 	}
3923 
3924 	/*
3925 	 * As per the VIO spec, the PREEMPT and PRESERVE flags are only valid
3926 	 * when the EXCLUSIVE flag is set.
3927 	 */
3928 	if (!(flags & VD_ACCESS_SET_EXCLUSIVE)) {
3929 		PR0("Invalid VD_OP_SET_ACCESS flags: 0x%lx", flags);
3930 		request->status = EINVAL;
3931 		return (0);
3932 	}
3933 
3934 	switch (flags & (VD_ACCESS_SET_PREEMPT | VD_ACCESS_SET_PRESERVE)) {
3935 
3936 	case VD_ACCESS_SET_PREEMPT | VD_ACCESS_SET_PRESERVE:
3937 		/*
3938 		 * Flags EXCLUSIVE and PREEMPT and PRESERVE. We have to
3939 		 * acquire exclusive access rights, preserve them and we
3940 		 * can use preemption. So we can use the MHIOCTKNOWN ioctl.
3941 		 */
3942 		PR0("Performing VD_OP_SET_ACCESS (EXCLUSIVE|PREEMPT|PRESERVE)");
3943 		request->status = ldi_ioctl(vd->ldi_handle[request->slice],
3944 		    MHIOCTKOWN, NULL, (vd->open_flags | FKIOCTL), kcred, &rval);
3945 		break;
3946 
3947 	case VD_ACCESS_SET_PRESERVE:
3948 		/*
3949 		 * Flags EXCLUSIVE and PRESERVE. We have to acquire exclusive
3950 		 * access rights and preserve them, but not preempt any other
3951 		 * host. So we need to use the MHIOCTKOWN ioctl to enable the
3952 		 * "preserve" feature but we can not called it directly
3953 		 * because it uses preemption. So before that, we use the
3954 		 * MHIOCQRESERVE ioctl to ensure we can get exclusive rights
3955 		 * without preempting anyone.
3956 		 */
3957 		PR0("Performing VD_OP_SET_ACCESS (EXCLUSIVE|PRESERVE)");
3958 		request->status = ldi_ioctl(vd->ldi_handle[request->slice],
3959 		    MHIOCQRESERVE, NULL, (vd->open_flags | FKIOCTL), kcred,
3960 		    &rval);
3961 		if (request->status != 0)
3962 			break;
3963 		request->status = ldi_ioctl(vd->ldi_handle[request->slice],
3964 		    MHIOCTKOWN, NULL, (vd->open_flags | FKIOCTL), kcred, &rval);
3965 		break;
3966 
3967 	case VD_ACCESS_SET_PREEMPT:
3968 		/*
3969 		 * Flags EXCLUSIVE and PREEMPT. We have to acquire exclusive
3970 		 * access rights and we can use preemption. So we try to do
3971 		 * a SCSI reservation, if it fails we reset the disk to clear
3972 		 * any reservation and we try to reserve again.
3973 		 */
3974 		PR0("Performing VD_OP_SET_ACCESS (EXCLUSIVE|PREEMPT)");
3975 		request->status = ldi_ioctl(vd->ldi_handle[request->slice],
3976 		    MHIOCQRESERVE, NULL, (vd->open_flags | FKIOCTL), kcred,
3977 		    &rval);
3978 		if (request->status == 0)
3979 			break;
3980 
3981 		/* reset the disk */
3982 		(void) vd_scsi_reset(vd);
3983 
3984 		/* try again even if the reset has failed */
3985 		request->status = ldi_ioctl(vd->ldi_handle[request->slice],
3986 		    MHIOCQRESERVE, NULL, (vd->open_flags | FKIOCTL), kcred,
3987 		    &rval);
3988 		break;
3989 
3990 	case 0:
3991 		/* Flag EXCLUSIVE only. Just issue a SCSI reservation */
3992 		PR0("Performing VD_OP_SET_ACCESS (EXCLUSIVE)");
3993 		request->status = ldi_ioctl(vd->ldi_handle[request->slice],
3994 		    MHIOCQRESERVE, NULL, (vd->open_flags | FKIOCTL), kcred,
3995 		    &rval);
3996 		break;
3997 	}
3998 
3999 	if (request->status == 0)
4000 		vd->ownership = B_TRUE;
4001 	else
4002 		PR0("VD_OP_SET_ACCESS: error %d", request->status);
4003 
4004 	return (0);
4005 }
4006 
4007 static void
4008 vd_reset_access(vd_t *vd)
4009 {
4010 	int status, rval;
4011 
4012 	if (vd->file || vd->volume || !vd->ownership)
4013 		return;
4014 
4015 	PR0("Releasing disk ownership");
4016 	status = ldi_ioctl(vd->ldi_handle[0], MHIOCRELEASE, NULL,
4017 	    (vd->open_flags | FKIOCTL), kcred, &rval);
4018 
4019 	/*
4020 	 * An EACCES failure means that there is a reservation conflict,
4021 	 * so we are not the owner of the disk anymore.
4022 	 */
4023 	if (status == 0 || status == EACCES) {
4024 		vd->ownership = B_FALSE;
4025 		return;
4026 	}
4027 
4028 	PR0("Fail to release ownership, error %d", status);
4029 
4030 	/*
4031 	 * We have failed to release the ownership, try to reset the disk
4032 	 * to release reservations.
4033 	 */
4034 	PR0("Resetting disk");
4035 	status = vd_scsi_reset(vd);
4036 
4037 	if (status != 0)
4038 		PR0("Fail to reset disk, error %d", status);
4039 
4040 	/* whatever the result of the reset is, we try the release again */
4041 	status = ldi_ioctl(vd->ldi_handle[0], MHIOCRELEASE, NULL,
4042 	    (vd->open_flags | FKIOCTL), kcred, &rval);
4043 
4044 	if (status == 0 || status == EACCES) {
4045 		vd->ownership = B_FALSE;
4046 		return;
4047 	}
4048 
4049 	PR0("Fail to release ownership, error %d", status);
4050 
4051 	/*
4052 	 * At this point we have done our best to try to reset the
4053 	 * access rights to the disk and we don't know if we still
4054 	 * own a reservation and if any mechanism to preserve the
4055 	 * ownership is still in place. The ultimate solution would
4056 	 * be to reset the system but this is usually not what we
4057 	 * want to happen.
4058 	 */
4059 
4060 	if (vd_reset_access_failure == A_REBOOT) {
4061 		cmn_err(CE_WARN, VD_RESET_ACCESS_FAILURE_MSG
4062 		    ", rebooting the system", vd->device_path);
4063 		(void) uadmin(A_SHUTDOWN, AD_BOOT, NULL);
4064 	} else if (vd_reset_access_failure == A_DUMP) {
4065 		panic(VD_RESET_ACCESS_FAILURE_MSG, vd->device_path);
4066 	}
4067 
4068 	cmn_err(CE_WARN, VD_RESET_ACCESS_FAILURE_MSG, vd->device_path);
4069 }
4070 
4071 /*
4072  * Define the supported operations once the functions for performing them have
4073  * been defined
4074  */
4075 static const vds_operation_t	vds_operation[] = {
4076 #define	X(_s)	#_s, _s
4077 	{X(VD_OP_BREAD),	vd_start_bio,	vd_complete_bio},
4078 	{X(VD_OP_BWRITE),	vd_start_bio,	vd_complete_bio},
4079 	{X(VD_OP_FLUSH),	vd_ioctl,	NULL},
4080 	{X(VD_OP_GET_WCE),	vd_ioctl,	NULL},
4081 	{X(VD_OP_SET_WCE),	vd_ioctl,	NULL},
4082 	{X(VD_OP_GET_VTOC),	vd_ioctl,	NULL},
4083 	{X(VD_OP_SET_VTOC),	vd_ioctl,	NULL},
4084 	{X(VD_OP_GET_DISKGEOM),	vd_ioctl,	NULL},
4085 	{X(VD_OP_SET_DISKGEOM),	vd_ioctl,	NULL},
4086 	{X(VD_OP_GET_EFI),	vd_ioctl,	NULL},
4087 	{X(VD_OP_SET_EFI),	vd_ioctl,	NULL},
4088 	{X(VD_OP_GET_DEVID),	vd_get_devid,	NULL},
4089 	{X(VD_OP_SCSICMD),	vd_ioctl,	NULL},
4090 	{X(VD_OP_RESET),	vd_reset,	NULL},
4091 	{X(VD_OP_GET_CAPACITY),	vd_get_capacity, NULL},
4092 	{X(VD_OP_SET_ACCESS),	vd_set_access,	NULL},
4093 	{X(VD_OP_GET_ACCESS),	vd_get_access,	NULL},
4094 #undef	X
4095 };
4096 
4097 static const size_t	vds_noperations =
4098 	(sizeof (vds_operation))/(sizeof (vds_operation[0]));
4099 
4100 /*
4101  * Process a task specifying a client I/O request
4102  *
4103  * Parameters:
4104  *	task 		- structure containing the request sent from client
4105  *
4106  * Return Value
4107  *	0	- success
4108  *	ENOTSUP	- Unknown/Unsupported VD_OP_XXX operation
4109  *	EINVAL	- Invalid disk slice
4110  *	!= 0	- some other non-zero return value from start function
4111  */
4112 static int
4113 vd_do_process_task(vd_task_t *task)
4114 {
4115 	int			i;
4116 	vd_t			*vd		= task->vd;
4117 	vd_dring_payload_t	*request	= task->request;
4118 
4119 	ASSERT(vd != NULL);
4120 	ASSERT(request != NULL);
4121 
4122 	/* Find the requested operation */
4123 	for (i = 0; i < vds_noperations; i++) {
4124 		if (request->operation == vds_operation[i].operation) {
4125 			/* all operations should have a start func */
4126 			ASSERT(vds_operation[i].start != NULL);
4127 
4128 			task->completef = vds_operation[i].complete;
4129 			break;
4130 		}
4131 	}
4132 
4133 	/*
4134 	 * We need to check that the requested operation is permitted
4135 	 * for the particular client that sent it or that the loop above
4136 	 * did not complete without finding the operation type (indicating
4137 	 * that the requested operation is unknown/unimplemented)
4138 	 */
4139 	if ((VD_OP_SUPPORTED(vd->operations, request->operation) == B_FALSE) ||
4140 	    (i == vds_noperations)) {
4141 		PR0("Unsupported operation %u", request->operation);
4142 		request->status = ENOTSUP;
4143 		return (0);
4144 	}
4145 
4146 	/* Range-check slice */
4147 	if (request->slice >= vd->nslices &&
4148 	    ((vd->vdisk_type != VD_DISK_TYPE_DISK && vd_slice_single_slice) ||
4149 	    request->slice != VD_SLICE_NONE)) {
4150 		PR0("Invalid \"slice\" %u (max %u) for virtual disk",
4151 		    request->slice, (vd->nslices - 1));
4152 		request->status = EINVAL;
4153 		return (0);
4154 	}
4155 
4156 	/*
4157 	 * Call the function pointer that starts the operation.
4158 	 */
4159 	return (vds_operation[i].start(task));
4160 }
4161 
4162 /*
4163  * Description:
4164  *	This function is called by both the in-band and descriptor ring
4165  *	message processing functions paths to actually execute the task
4166  *	requested by the vDisk client. It in turn calls its worker
4167  *	function, vd_do_process_task(), to carry our the request.
4168  *
4169  *	Any transport errors (e.g. LDC errors, vDisk protocol errors) are
4170  *	saved in the 'status' field of the task and are propagated back
4171  *	up the call stack to trigger a NACK
4172  *
4173  *	Any request errors (e.g. ENOTTY from an ioctl) are saved in
4174  *	the 'status' field of the request and result in an ACK being sent
4175  *	by the completion handler.
4176  *
4177  * Parameters:
4178  *	task 		- structure containing the request sent from client
4179  *
4180  * Return Value
4181  *	0		- successful synchronous request.
4182  *	!= 0		- transport error (e.g. LDC errors, vDisk protocol)
4183  *	EINPROGRESS	- task will be finished in a completion handler
4184  */
4185 static int
4186 vd_process_task(vd_task_t *task)
4187 {
4188 	vd_t	*vd = task->vd;
4189 	int	status;
4190 
4191 	DTRACE_PROBE1(task__start, vd_task_t *, task);
4192 
4193 	task->status =  vd_do_process_task(task);
4194 
4195 	/*
4196 	 * If the task processing function returned EINPROGRESS indicating
4197 	 * that the task needs completing then schedule a taskq entry to
4198 	 * finish it now.
4199 	 *
4200 	 * Otherwise the task processing function returned either zero
4201 	 * indicating that the task was finished in the start function (and we
4202 	 * don't need to wait in a completion function) or the start function
4203 	 * returned an error - in both cases all that needs to happen is the
4204 	 * notification to the vDisk client higher up the call stack.
4205 	 * If the task was using a Descriptor Ring, we need to mark it as done
4206 	 * at this stage.
4207 	 */
4208 	if (task->status == EINPROGRESS) {
4209 		/* Queue a task to complete the operation */
4210 		(void) ddi_taskq_dispatch(vd->completionq, vd_complete,
4211 		    task, DDI_SLEEP);
4212 		return (EINPROGRESS);
4213 	}
4214 
4215 	if (!vd->reset_state && (vd->xfer_mode == VIO_DRING_MODE_V1_0)) {
4216 		/* Update the dring element if it's a dring client */
4217 		status = vd_mark_elem_done(vd, task->index,
4218 		    task->request->status, task->request->nbytes);
4219 		if (status == ECONNRESET)
4220 			vd_mark_in_reset(vd);
4221 		else if (status == EACCES)
4222 			vd_need_reset(vd, B_TRUE);
4223 	}
4224 
4225 	return (task->status);
4226 }
4227 
4228 /*
4229  * Return true if the "type", "subtype", and "env" fields of the "tag" first
4230  * argument match the corresponding remaining arguments; otherwise, return false
4231  */
4232 boolean_t
4233 vd_msgtype(vio_msg_tag_t *tag, int type, int subtype, int env)
4234 {
4235 	return ((tag->vio_msgtype == type) &&
4236 	    (tag->vio_subtype == subtype) &&
4237 	    (tag->vio_subtype_env == env)) ? B_TRUE : B_FALSE;
4238 }
4239 
4240 /*
4241  * Check whether the major/minor version specified in "ver_msg" is supported
4242  * by this server.
4243  */
4244 static boolean_t
4245 vds_supported_version(vio_ver_msg_t *ver_msg)
4246 {
4247 	for (int i = 0; i < vds_num_versions; i++) {
4248 		ASSERT(vds_version[i].major > 0);
4249 		ASSERT((i == 0) ||
4250 		    (vds_version[i].major < vds_version[i-1].major));
4251 
4252 		/*
4253 		 * If the major versions match, adjust the minor version, if
4254 		 * necessary, down to the highest value supported by this
4255 		 * server and return true so this message will get "ack"ed;
4256 		 * the client should also support all minor versions lower
4257 		 * than the value it sent
4258 		 */
4259 		if (ver_msg->ver_major == vds_version[i].major) {
4260 			if (ver_msg->ver_minor > vds_version[i].minor) {
4261 				PR0("Adjusting minor version from %u to %u",
4262 				    ver_msg->ver_minor, vds_version[i].minor);
4263 				ver_msg->ver_minor = vds_version[i].minor;
4264 			}
4265 			return (B_TRUE);
4266 		}
4267 
4268 		/*
4269 		 * If the message contains a higher major version number, set
4270 		 * the message's major/minor versions to the current values
4271 		 * and return false, so this message will get "nack"ed with
4272 		 * these values, and the client will potentially try again
4273 		 * with the same or a lower version
4274 		 */
4275 		if (ver_msg->ver_major > vds_version[i].major) {
4276 			ver_msg->ver_major = vds_version[i].major;
4277 			ver_msg->ver_minor = vds_version[i].minor;
4278 			return (B_FALSE);
4279 		}
4280 
4281 		/*
4282 		 * Otherwise, the message's major version is less than the
4283 		 * current major version, so continue the loop to the next
4284 		 * (lower) supported version
4285 		 */
4286 	}
4287 
4288 	/*
4289 	 * No common version was found; "ground" the version pair in the
4290 	 * message to terminate negotiation
4291 	 */
4292 	ver_msg->ver_major = 0;
4293 	ver_msg->ver_minor = 0;
4294 	return (B_FALSE);
4295 }
4296 
4297 /*
4298  * Process a version message from a client.  vds expects to receive version
4299  * messages from clients seeking service, but never issues version messages
4300  * itself; therefore, vds can ACK or NACK client version messages, but does
4301  * not expect to receive version-message ACKs or NACKs (and will treat such
4302  * messages as invalid).
4303  */
4304 static int
4305 vd_process_ver_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
4306 {
4307 	vio_ver_msg_t	*ver_msg = (vio_ver_msg_t *)msg;
4308 
4309 
4310 	ASSERT(msglen >= sizeof (msg->tag));
4311 
4312 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO,
4313 	    VIO_VER_INFO)) {
4314 		return (ENOMSG);	/* not a version message */
4315 	}
4316 
4317 	if (msglen != sizeof (*ver_msg)) {
4318 		PR0("Expected %lu-byte version message; "
4319 		    "received %lu bytes", sizeof (*ver_msg), msglen);
4320 		return (EBADMSG);
4321 	}
4322 
4323 	if (ver_msg->dev_class != VDEV_DISK) {
4324 		PR0("Expected device class %u (disk); received %u",
4325 		    VDEV_DISK, ver_msg->dev_class);
4326 		return (EBADMSG);
4327 	}
4328 
4329 	/*
4330 	 * We're talking to the expected kind of client; set our device class
4331 	 * for "ack/nack" back to the client
4332 	 */
4333 	ver_msg->dev_class = VDEV_DISK_SERVER;
4334 
4335 	/*
4336 	 * Check whether the (valid) version message specifies a version
4337 	 * supported by this server.  If the version is not supported, return
4338 	 * EBADMSG so the message will get "nack"ed; vds_supported_version()
4339 	 * will have updated the message with a supported version for the
4340 	 * client to consider
4341 	 */
4342 	if (!vds_supported_version(ver_msg))
4343 		return (EBADMSG);
4344 
4345 
4346 	/*
4347 	 * A version has been agreed upon; use the client's SID for
4348 	 * communication on this channel now
4349 	 */
4350 	ASSERT(!(vd->initialized & VD_SID));
4351 	vd->sid = ver_msg->tag.vio_sid;
4352 	vd->initialized |= VD_SID;
4353 
4354 	/*
4355 	 * Store the negotiated major and minor version values in the "vd" data
4356 	 * structure so that we can check if certain operations are supported
4357 	 * by the client.
4358 	 */
4359 	vd->version.major = ver_msg->ver_major;
4360 	vd->version.minor = ver_msg->ver_minor;
4361 
4362 	PR0("Using major version %u, minor version %u",
4363 	    ver_msg->ver_major, ver_msg->ver_minor);
4364 	return (0);
4365 }
4366 
4367 static void
4368 vd_set_exported_operations(vd_t *vd)
4369 {
4370 	vd->operations = 0;	/* clear field */
4371 
4372 	/*
4373 	 * We need to check from the highest version supported to the
4374 	 * lowest because versions with a higher minor number implicitly
4375 	 * support versions with a lower minor number.
4376 	 */
4377 	if (vio_ver_is_supported(vd->version, 1, 1)) {
4378 		ASSERT(vd->open_flags & FREAD);
4379 		vd->operations |= VD_OP_MASK_READ | (1 << VD_OP_GET_CAPACITY);
4380 
4381 		if (vd->open_flags & FWRITE)
4382 			vd->operations |= VD_OP_MASK_WRITE;
4383 
4384 		if (vd->scsi)
4385 			vd->operations |= VD_OP_MASK_SCSI;
4386 
4387 		if (VD_DSKIMG(vd) && vd_dskimg_is_iso_image(vd)) {
4388 			/*
4389 			 * can't write to ISO images, make sure that write
4390 			 * support is not set in case administrator did not
4391 			 * use "options=ro" when doing an ldm add-vdsdev
4392 			 */
4393 			vd->operations &= ~VD_OP_MASK_WRITE;
4394 		}
4395 	} else if (vio_ver_is_supported(vd->version, 1, 0)) {
4396 		vd->operations = VD_OP_MASK_READ | VD_OP_MASK_WRITE;
4397 	}
4398 
4399 	/* we should have already agreed on a version */
4400 	ASSERT(vd->operations != 0);
4401 }
4402 
4403 static int
4404 vd_process_attr_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
4405 {
4406 	vd_attr_msg_t	*attr_msg = (vd_attr_msg_t *)msg;
4407 	int		status, retry = 0;
4408 
4409 
4410 	ASSERT(msglen >= sizeof (msg->tag));
4411 
4412 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO,
4413 	    VIO_ATTR_INFO)) {
4414 		PR0("Message is not an attribute message");
4415 		return (ENOMSG);
4416 	}
4417 
4418 	if (msglen != sizeof (*attr_msg)) {
4419 		PR0("Expected %lu-byte attribute message; "
4420 		    "received %lu bytes", sizeof (*attr_msg), msglen);
4421 		return (EBADMSG);
4422 	}
4423 
4424 	if (attr_msg->max_xfer_sz == 0) {
4425 		PR0("Received maximum transfer size of 0 from client");
4426 		return (EBADMSG);
4427 	}
4428 
4429 	if ((attr_msg->xfer_mode != VIO_DESC_MODE) &&
4430 	    (attr_msg->xfer_mode != VIO_DRING_MODE_V1_0)) {
4431 		PR0("Client requested unsupported transfer mode");
4432 		return (EBADMSG);
4433 	}
4434 
4435 	/*
4436 	 * check if the underlying disk is ready, if not try accessing
4437 	 * the device again. Open the vdisk device and extract info
4438 	 * about it, as this is needed to respond to the attr info msg
4439 	 */
4440 	if ((vd->initialized & VD_DISK_READY) == 0) {
4441 		PR0("Retry setting up disk (%s)", vd->device_path);
4442 		do {
4443 			status = vd_setup_vd(vd);
4444 			if (status != EAGAIN || ++retry > vds_dev_retries)
4445 				break;
4446 
4447 			/* incremental delay */
4448 			delay(drv_usectohz(vds_dev_delay));
4449 
4450 			/* if vdisk is no longer enabled - return error */
4451 			if (!vd_enabled(vd))
4452 				return (ENXIO);
4453 
4454 		} while (status == EAGAIN);
4455 
4456 		if (status)
4457 			return (ENXIO);
4458 
4459 		vd->initialized |= VD_DISK_READY;
4460 		ASSERT(vd->nslices > 0 && vd->nslices <= V_NUMPAR);
4461 		PR0("vdisk_type = %s, volume = %s, file = %s, nslices = %u",
4462 		    ((vd->vdisk_type == VD_DISK_TYPE_DISK) ? "disk" : "slice"),
4463 		    (vd->volume ? "yes" : "no"),
4464 		    (vd->file ? "yes" : "no"),
4465 		    vd->nslices);
4466 	}
4467 
4468 	/* Success:  valid message and transfer mode */
4469 	vd->xfer_mode = attr_msg->xfer_mode;
4470 
4471 	if (vd->xfer_mode == VIO_DESC_MODE) {
4472 
4473 		/*
4474 		 * The vd_dring_inband_msg_t contains one cookie; need room
4475 		 * for up to n-1 more cookies, where "n" is the number of full
4476 		 * pages plus possibly one partial page required to cover
4477 		 * "max_xfer_sz".  Add room for one more cookie if
4478 		 * "max_xfer_sz" isn't an integral multiple of the page size.
4479 		 * Must first get the maximum transfer size in bytes.
4480 		 */
4481 		size_t	max_xfer_bytes = attr_msg->vdisk_block_size ?
4482 		    attr_msg->vdisk_block_size*attr_msg->max_xfer_sz :
4483 		    attr_msg->max_xfer_sz;
4484 		size_t	max_inband_msglen =
4485 		    sizeof (vd_dring_inband_msg_t) +
4486 		    ((max_xfer_bytes/PAGESIZE +
4487 		    ((max_xfer_bytes % PAGESIZE) ? 1 : 0))*
4488 		    (sizeof (ldc_mem_cookie_t)));
4489 
4490 		/*
4491 		 * Set the maximum expected message length to
4492 		 * accommodate in-band-descriptor messages with all
4493 		 * their cookies
4494 		 */
4495 		vd->max_msglen = MAX(vd->max_msglen, max_inband_msglen);
4496 
4497 		/*
4498 		 * Initialize the data structure for processing in-band I/O
4499 		 * request descriptors
4500 		 */
4501 		vd->inband_task.vd	= vd;
4502 		vd->inband_task.msg	= kmem_alloc(vd->max_msglen, KM_SLEEP);
4503 		vd->inband_task.index	= 0;
4504 		vd->inband_task.type	= VD_FINAL_RANGE_TASK;	/* range == 1 */
4505 	}
4506 
4507 	/* Return the device's block size and max transfer size to the client */
4508 	attr_msg->vdisk_block_size	= vd->vdisk_block_size;
4509 	attr_msg->max_xfer_sz		= vd->max_xfer_sz;
4510 
4511 	attr_msg->vdisk_size = vd->vdisk_size;
4512 	attr_msg->vdisk_type = (vd_slice_single_slice)? vd->vdisk_type :
4513 	    VD_DISK_TYPE_DISK;
4514 	attr_msg->vdisk_media = vd->vdisk_media;
4515 
4516 	/* Discover and save the list of supported VD_OP_XXX operations */
4517 	vd_set_exported_operations(vd);
4518 	attr_msg->operations = vd->operations;
4519 
4520 	PR0("%s", VD_CLIENT(vd));
4521 
4522 	ASSERT(vd->dring_task == NULL);
4523 
4524 	return (0);
4525 }
4526 
4527 static int
4528 vd_process_dring_reg_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
4529 {
4530 	int			status;
4531 	size_t			expected;
4532 	ldc_mem_info_t		dring_minfo;
4533 	uint8_t			mtype;
4534 	vio_dring_reg_msg_t	*reg_msg = (vio_dring_reg_msg_t *)msg;
4535 
4536 
4537 	ASSERT(msglen >= sizeof (msg->tag));
4538 
4539 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO,
4540 	    VIO_DRING_REG)) {
4541 		PR0("Message is not a register-dring message");
4542 		return (ENOMSG);
4543 	}
4544 
4545 	if (msglen < sizeof (*reg_msg)) {
4546 		PR0("Expected at least %lu-byte register-dring message; "
4547 		    "received %lu bytes", sizeof (*reg_msg), msglen);
4548 		return (EBADMSG);
4549 	}
4550 
4551 	expected = sizeof (*reg_msg) +
4552 	    (reg_msg->ncookies - 1)*(sizeof (reg_msg->cookie[0]));
4553 	if (msglen != expected) {
4554 		PR0("Expected %lu-byte register-dring message; "
4555 		    "received %lu bytes", expected, msglen);
4556 		return (EBADMSG);
4557 	}
4558 
4559 	if (vd->initialized & VD_DRING) {
4560 		PR0("A dring was previously registered; only support one");
4561 		return (EBADMSG);
4562 	}
4563 
4564 	if (reg_msg->num_descriptors > INT32_MAX) {
4565 		PR0("reg_msg->num_descriptors = %u; must be <= %u (%s)",
4566 		    reg_msg->ncookies, INT32_MAX, STRINGIZE(INT32_MAX));
4567 		return (EBADMSG);
4568 	}
4569 
4570 	if (reg_msg->ncookies != 1) {
4571 		/*
4572 		 * In addition to fixing the assertion in the success case
4573 		 * below, supporting drings which require more than one
4574 		 * "cookie" requires increasing the value of vd->max_msglen
4575 		 * somewhere in the code path prior to receiving the message
4576 		 * which results in calling this function.  Note that without
4577 		 * making this change, the larger message size required to
4578 		 * accommodate multiple cookies cannot be successfully
4579 		 * received, so this function will not even get called.
4580 		 * Gracefully accommodating more dring cookies might
4581 		 * reasonably demand exchanging an additional attribute or
4582 		 * making a minor protocol adjustment
4583 		 */
4584 		PR0("reg_msg->ncookies = %u != 1", reg_msg->ncookies);
4585 		return (EBADMSG);
4586 	}
4587 
4588 	if (vd_direct_mapped_drings)
4589 		mtype = LDC_DIRECT_MAP;
4590 	else
4591 		mtype = LDC_SHADOW_MAP;
4592 
4593 	status = ldc_mem_dring_map(vd->ldc_handle, reg_msg->cookie,
4594 	    reg_msg->ncookies, reg_msg->num_descriptors,
4595 	    reg_msg->descriptor_size, mtype, &vd->dring_handle);
4596 	if (status != 0) {
4597 		PR0("ldc_mem_dring_map() returned errno %d", status);
4598 		return (status);
4599 	}
4600 
4601 	/*
4602 	 * To remove the need for this assertion, must call
4603 	 * ldc_mem_dring_nextcookie() successfully ncookies-1 times after a
4604 	 * successful call to ldc_mem_dring_map()
4605 	 */
4606 	ASSERT(reg_msg->ncookies == 1);
4607 
4608 	if ((status =
4609 	    ldc_mem_dring_info(vd->dring_handle, &dring_minfo)) != 0) {
4610 		PR0("ldc_mem_dring_info() returned errno %d", status);
4611 		if ((status = ldc_mem_dring_unmap(vd->dring_handle)) != 0)
4612 			PR0("ldc_mem_dring_unmap() returned errno %d", status);
4613 		return (status);
4614 	}
4615 
4616 	if (dring_minfo.vaddr == NULL) {
4617 		PR0("Descriptor ring virtual address is NULL");
4618 		return (ENXIO);
4619 	}
4620 
4621 
4622 	/* Initialize for valid message and mapped dring */
4623 	vd->initialized |= VD_DRING;
4624 	vd->dring_ident = 1;	/* "There Can Be Only One" */
4625 	vd->dring = dring_minfo.vaddr;
4626 	vd->descriptor_size = reg_msg->descriptor_size;
4627 	vd->dring_len = reg_msg->num_descriptors;
4628 	vd->dring_mtype = dring_minfo.mtype;
4629 	reg_msg->dring_ident = vd->dring_ident;
4630 	PR1("descriptor size = %u, dring length = %u",
4631 	    vd->descriptor_size, vd->dring_len);
4632 
4633 	/*
4634 	 * Allocate and initialize a "shadow" array of data structures for
4635 	 * tasks to process I/O requests in dring elements
4636 	 */
4637 	vd->dring_task =
4638 	    kmem_zalloc((sizeof (*vd->dring_task)) * vd->dring_len, KM_SLEEP);
4639 	for (int i = 0; i < vd->dring_len; i++) {
4640 		vd->dring_task[i].vd		= vd;
4641 		vd->dring_task[i].index		= i;
4642 
4643 		status = ldc_mem_alloc_handle(vd->ldc_handle,
4644 		    &(vd->dring_task[i].mhdl));
4645 		if (status) {
4646 			PR0("ldc_mem_alloc_handle() returned err %d ", status);
4647 			return (ENXIO);
4648 		}
4649 
4650 		/*
4651 		 * The descriptor payload varies in length. Calculate its
4652 		 * size by subtracting the header size from the total
4653 		 * descriptor size.
4654 		 */
4655 		vd->dring_task[i].request = kmem_zalloc((vd->descriptor_size -
4656 		    sizeof (vio_dring_entry_hdr_t)), KM_SLEEP);
4657 		vd->dring_task[i].msg = kmem_alloc(vd->max_msglen, KM_SLEEP);
4658 	}
4659 
4660 	if (vd->file || vd->zvol) {
4661 		vd->write_queue =
4662 		    kmem_zalloc(sizeof (buf_t *) * vd->dring_len, KM_SLEEP);
4663 	}
4664 
4665 	return (0);
4666 }
4667 
4668 static int
4669 vd_process_dring_unreg_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
4670 {
4671 	vio_dring_unreg_msg_t	*unreg_msg = (vio_dring_unreg_msg_t *)msg;
4672 
4673 
4674 	ASSERT(msglen >= sizeof (msg->tag));
4675 
4676 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO,
4677 	    VIO_DRING_UNREG)) {
4678 		PR0("Message is not an unregister-dring message");
4679 		return (ENOMSG);
4680 	}
4681 
4682 	if (msglen != sizeof (*unreg_msg)) {
4683 		PR0("Expected %lu-byte unregister-dring message; "
4684 		    "received %lu bytes", sizeof (*unreg_msg), msglen);
4685 		return (EBADMSG);
4686 	}
4687 
4688 	if (unreg_msg->dring_ident != vd->dring_ident) {
4689 		PR0("Expected dring ident %lu; received %lu",
4690 		    vd->dring_ident, unreg_msg->dring_ident);
4691 		return (EBADMSG);
4692 	}
4693 
4694 	return (0);
4695 }
4696 
4697 static int
4698 process_rdx_msg(vio_msg_t *msg, size_t msglen)
4699 {
4700 	ASSERT(msglen >= sizeof (msg->tag));
4701 
4702 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO, VIO_RDX)) {
4703 		PR0("Message is not an RDX message");
4704 		return (ENOMSG);
4705 	}
4706 
4707 	if (msglen != sizeof (vio_rdx_msg_t)) {
4708 		PR0("Expected %lu-byte RDX message; received %lu bytes",
4709 		    sizeof (vio_rdx_msg_t), msglen);
4710 		return (EBADMSG);
4711 	}
4712 
4713 	PR0("Valid RDX message");
4714 	return (0);
4715 }
4716 
4717 static int
4718 vd_check_seq_num(vd_t *vd, uint64_t seq_num)
4719 {
4720 	if ((vd->initialized & VD_SEQ_NUM) && (seq_num != vd->seq_num + 1)) {
4721 		PR0("Received seq_num %lu; expected %lu",
4722 		    seq_num, (vd->seq_num + 1));
4723 		PR0("initiating soft reset");
4724 		vd_need_reset(vd, B_FALSE);
4725 		return (1);
4726 	}
4727 
4728 	vd->seq_num = seq_num;
4729 	vd->initialized |= VD_SEQ_NUM;	/* superfluous after first time... */
4730 	return (0);
4731 }
4732 
4733 /*
4734  * Return the expected size of an inband-descriptor message with all the
4735  * cookies it claims to include
4736  */
4737 static size_t
4738 expected_inband_size(vd_dring_inband_msg_t *msg)
4739 {
4740 	return ((sizeof (*msg)) +
4741 	    (msg->payload.ncookies - 1)*(sizeof (msg->payload.cookie[0])));
4742 }
4743 
4744 /*
4745  * Process an in-band descriptor message:  used with clients like OBP, with
4746  * which vds exchanges descriptors within VIO message payloads, rather than
4747  * operating on them within a descriptor ring
4748  */
4749 static int
4750 vd_process_desc_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
4751 {
4752 	size_t			expected;
4753 	vd_dring_inband_msg_t	*desc_msg = (vd_dring_inband_msg_t *)msg;
4754 
4755 
4756 	ASSERT(msglen >= sizeof (msg->tag));
4757 
4758 	if (!vd_msgtype(&msg->tag, VIO_TYPE_DATA, VIO_SUBTYPE_INFO,
4759 	    VIO_DESC_DATA)) {
4760 		PR1("Message is not an in-band-descriptor message");
4761 		return (ENOMSG);
4762 	}
4763 
4764 	if (msglen < sizeof (*desc_msg)) {
4765 		PR0("Expected at least %lu-byte descriptor message; "
4766 		    "received %lu bytes", sizeof (*desc_msg), msglen);
4767 		return (EBADMSG);
4768 	}
4769 
4770 	if (msglen != (expected = expected_inband_size(desc_msg))) {
4771 		PR0("Expected %lu-byte descriptor message; "
4772 		    "received %lu bytes", expected, msglen);
4773 		return (EBADMSG);
4774 	}
4775 
4776 	if (vd_check_seq_num(vd, desc_msg->hdr.seq_num) != 0)
4777 		return (EBADMSG);
4778 
4779 	/*
4780 	 * Valid message:  Set up the in-band descriptor task and process the
4781 	 * request.  Arrange to acknowledge the client's message, unless an
4782 	 * error processing the descriptor task results in setting
4783 	 * VIO_SUBTYPE_NACK
4784 	 */
4785 	PR1("Valid in-band-descriptor message");
4786 	msg->tag.vio_subtype = VIO_SUBTYPE_ACK;
4787 
4788 	ASSERT(vd->inband_task.msg != NULL);
4789 
4790 	bcopy(msg, vd->inband_task.msg, msglen);
4791 	vd->inband_task.msglen	= msglen;
4792 
4793 	/*
4794 	 * The task request is now the payload of the message
4795 	 * that was just copied into the body of the task.
4796 	 */
4797 	desc_msg = (vd_dring_inband_msg_t *)vd->inband_task.msg;
4798 	vd->inband_task.request	= &desc_msg->payload;
4799 
4800 	return (vd_process_task(&vd->inband_task));
4801 }
4802 
4803 static int
4804 vd_process_element(vd_t *vd, vd_task_type_t type, uint32_t idx,
4805     vio_msg_t *msg, size_t msglen)
4806 {
4807 	int			status;
4808 	boolean_t		ready;
4809 	on_trap_data_t		otd;
4810 	vd_dring_entry_t	*elem = VD_DRING_ELEM(idx);
4811 
4812 	/* Accept the updated dring element */
4813 	if ((status = VIO_DRING_ACQUIRE(&otd, vd->dring_mtype,
4814 	    vd->dring_handle, idx, idx)) != 0) {
4815 		return (status);
4816 	}
4817 	ready = (elem->hdr.dstate == VIO_DESC_READY);
4818 	if (ready) {
4819 		elem->hdr.dstate = VIO_DESC_ACCEPTED;
4820 		bcopy(&elem->payload, vd->dring_task[idx].request,
4821 		    (vd->descriptor_size - sizeof (vio_dring_entry_hdr_t)));
4822 	} else {
4823 		PR0("descriptor %u not ready", idx);
4824 		VD_DUMP_DRING_ELEM(elem);
4825 	}
4826 	if ((status = VIO_DRING_RELEASE(vd->dring_mtype,
4827 	    vd->dring_handle, idx, idx)) != 0) {
4828 		PR0("VIO_DRING_RELEASE() returned errno %d", status);
4829 		return (status);
4830 	}
4831 	if (!ready)
4832 		return (EBUSY);
4833 
4834 
4835 	/* Initialize a task and process the accepted element */
4836 	PR1("Processing dring element %u", idx);
4837 	vd->dring_task[idx].type	= type;
4838 
4839 	/* duplicate msg buf for cookies etc. */
4840 	bcopy(msg, vd->dring_task[idx].msg, msglen);
4841 
4842 	vd->dring_task[idx].msglen	= msglen;
4843 	return (vd_process_task(&vd->dring_task[idx]));
4844 }
4845 
4846 static int
4847 vd_process_element_range(vd_t *vd, int start, int end,
4848     vio_msg_t *msg, size_t msglen)
4849 {
4850 	int		i, n, nelem, status = 0;
4851 	boolean_t	inprogress = B_FALSE;
4852 	vd_task_type_t	type;
4853 
4854 
4855 	ASSERT(start >= 0);
4856 	ASSERT(end >= 0);
4857 
4858 	/*
4859 	 * Arrange to acknowledge the client's message, unless an error
4860 	 * processing one of the dring elements results in setting
4861 	 * VIO_SUBTYPE_NACK
4862 	 */
4863 	msg->tag.vio_subtype = VIO_SUBTYPE_ACK;
4864 
4865 	/*
4866 	 * Process the dring elements in the range
4867 	 */
4868 	nelem = ((end < start) ? end + vd->dring_len : end) - start + 1;
4869 	for (i = start, n = nelem; n > 0; i = (i + 1) % vd->dring_len, n--) {
4870 		((vio_dring_msg_t *)msg)->end_idx = i;
4871 		type = (n == 1) ? VD_FINAL_RANGE_TASK : VD_NONFINAL_RANGE_TASK;
4872 		status = vd_process_element(vd, type, i, msg, msglen);
4873 		if (status == EINPROGRESS)
4874 			inprogress = B_TRUE;
4875 		else if (status != 0)
4876 			break;
4877 	}
4878 
4879 	/*
4880 	 * If some, but not all, operations of a multi-element range are in
4881 	 * progress, wait for other operations to complete before returning
4882 	 * (which will result in "ack" or "nack" of the message).  Note that
4883 	 * all outstanding operations will need to complete, not just the ones
4884 	 * corresponding to the current range of dring elements; howevever, as
4885 	 * this situation is an error case, performance is less critical.
4886 	 */
4887 	if ((nelem > 1) && (status != EINPROGRESS) && inprogress) {
4888 		if (vd->ioq != NULL)
4889 			ddi_taskq_wait(vd->ioq);
4890 		ddi_taskq_wait(vd->completionq);
4891 	}
4892 
4893 	return (status);
4894 }
4895 
4896 static int
4897 vd_process_dring_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
4898 {
4899 	vio_dring_msg_t	*dring_msg = (vio_dring_msg_t *)msg;
4900 
4901 
4902 	ASSERT(msglen >= sizeof (msg->tag));
4903 
4904 	if (!vd_msgtype(&msg->tag, VIO_TYPE_DATA, VIO_SUBTYPE_INFO,
4905 	    VIO_DRING_DATA)) {
4906 		PR1("Message is not a dring-data message");
4907 		return (ENOMSG);
4908 	}
4909 
4910 	if (msglen != sizeof (*dring_msg)) {
4911 		PR0("Expected %lu-byte dring message; received %lu bytes",
4912 		    sizeof (*dring_msg), msglen);
4913 		return (EBADMSG);
4914 	}
4915 
4916 	if (vd_check_seq_num(vd, dring_msg->seq_num) != 0)
4917 		return (EBADMSG);
4918 
4919 	if (dring_msg->dring_ident != vd->dring_ident) {
4920 		PR0("Expected dring ident %lu; received ident %lu",
4921 		    vd->dring_ident, dring_msg->dring_ident);
4922 		return (EBADMSG);
4923 	}
4924 
4925 	if (dring_msg->start_idx >= vd->dring_len) {
4926 		PR0("\"start_idx\" = %u; must be less than %u",
4927 		    dring_msg->start_idx, vd->dring_len);
4928 		return (EBADMSG);
4929 	}
4930 
4931 	if ((dring_msg->end_idx < 0) ||
4932 	    (dring_msg->end_idx >= vd->dring_len)) {
4933 		PR0("\"end_idx\" = %u; must be >= 0 and less than %u",
4934 		    dring_msg->end_idx, vd->dring_len);
4935 		return (EBADMSG);
4936 	}
4937 
4938 	/* Valid message; process range of updated dring elements */
4939 	PR1("Processing descriptor range, start = %u, end = %u",
4940 	    dring_msg->start_idx, dring_msg->end_idx);
4941 	return (vd_process_element_range(vd, dring_msg->start_idx,
4942 	    dring_msg->end_idx, msg, msglen));
4943 }
4944 
4945 static int
4946 recv_msg(ldc_handle_t ldc_handle, void *msg, size_t *nbytes)
4947 {
4948 	int	retry, status;
4949 	size_t	size = *nbytes;
4950 
4951 
4952 	for (retry = 0, status = ETIMEDOUT;
4953 	    retry < vds_ldc_retries && status == ETIMEDOUT;
4954 	    retry++) {
4955 		PR1("ldc_read() attempt %d", (retry + 1));
4956 		*nbytes = size;
4957 		status = ldc_read(ldc_handle, msg, nbytes);
4958 	}
4959 
4960 	if (status) {
4961 		PR0("ldc_read() returned errno %d", status);
4962 		if (status != ECONNRESET)
4963 			return (ENOMSG);
4964 		return (status);
4965 	} else if (*nbytes == 0) {
4966 		PR1("ldc_read() returned 0 and no message read");
4967 		return (ENOMSG);
4968 	}
4969 
4970 	PR1("RCVD %lu-byte message", *nbytes);
4971 	return (0);
4972 }
4973 
4974 static int
4975 vd_do_process_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
4976 {
4977 	int		status;
4978 
4979 
4980 	PR1("Processing (%x/%x/%x) message", msg->tag.vio_msgtype,
4981 	    msg->tag.vio_subtype, msg->tag.vio_subtype_env);
4982 #ifdef	DEBUG
4983 	vd_decode_tag(msg);
4984 #endif
4985 
4986 	/*
4987 	 * Validate session ID up front, since it applies to all messages
4988 	 * once set
4989 	 */
4990 	if ((msg->tag.vio_sid != vd->sid) && (vd->initialized & VD_SID)) {
4991 		PR0("Expected SID %u, received %u", vd->sid,
4992 		    msg->tag.vio_sid);
4993 		return (EBADMSG);
4994 	}
4995 
4996 	PR1("\tWhile in state %d (%s)", vd->state, vd_decode_state(vd->state));
4997 
4998 	/*
4999 	 * Process the received message based on connection state
5000 	 */
5001 	switch (vd->state) {
5002 	case VD_STATE_INIT:	/* expect version message */
5003 		if ((status = vd_process_ver_msg(vd, msg, msglen)) != 0)
5004 			return (status);
5005 
5006 		/* Version negotiated, move to that state */
5007 		vd->state = VD_STATE_VER;
5008 		return (0);
5009 
5010 	case VD_STATE_VER:	/* expect attribute message */
5011 		if ((status = vd_process_attr_msg(vd, msg, msglen)) != 0)
5012 			return (status);
5013 
5014 		/* Attributes exchanged, move to that state */
5015 		vd->state = VD_STATE_ATTR;
5016 		return (0);
5017 
5018 	case VD_STATE_ATTR:
5019 		switch (vd->xfer_mode) {
5020 		case VIO_DESC_MODE:	/* expect RDX message */
5021 			if ((status = process_rdx_msg(msg, msglen)) != 0)
5022 				return (status);
5023 
5024 			/* Ready to receive in-band descriptors */
5025 			vd->state = VD_STATE_DATA;
5026 			return (0);
5027 
5028 		case VIO_DRING_MODE_V1_0:  /* expect register-dring message */
5029 			if ((status =
5030 			    vd_process_dring_reg_msg(vd, msg, msglen)) != 0)
5031 				return (status);
5032 
5033 			/* One dring negotiated, move to that state */
5034 			vd->state = VD_STATE_DRING;
5035 			return (0);
5036 
5037 		default:
5038 			ASSERT("Unsupported transfer mode");
5039 			PR0("Unsupported transfer mode");
5040 			return (ENOTSUP);
5041 		}
5042 
5043 	case VD_STATE_DRING:	/* expect RDX, register-dring, or unreg-dring */
5044 		if ((status = process_rdx_msg(msg, msglen)) == 0) {
5045 			/* Ready to receive data */
5046 			vd->state = VD_STATE_DATA;
5047 			return (0);
5048 		} else if (status != ENOMSG) {
5049 			return (status);
5050 		}
5051 
5052 
5053 		/*
5054 		 * If another register-dring message is received, stay in
5055 		 * dring state in case the client sends RDX; although the
5056 		 * protocol allows multiple drings, this server does not
5057 		 * support using more than one
5058 		 */
5059 		if ((status =
5060 		    vd_process_dring_reg_msg(vd, msg, msglen)) != ENOMSG)
5061 			return (status);
5062 
5063 		/*
5064 		 * Acknowledge an unregister-dring message, but reset the
5065 		 * connection anyway:  Although the protocol allows
5066 		 * unregistering drings, this server cannot serve a vdisk
5067 		 * without its only dring
5068 		 */
5069 		status = vd_process_dring_unreg_msg(vd, msg, msglen);
5070 		return ((status == 0) ? ENOTSUP : status);
5071 
5072 	case VD_STATE_DATA:
5073 		switch (vd->xfer_mode) {
5074 		case VIO_DESC_MODE:	/* expect in-band-descriptor message */
5075 			return (vd_process_desc_msg(vd, msg, msglen));
5076 
5077 		case VIO_DRING_MODE_V1_0: /* expect dring-data or unreg-dring */
5078 			/*
5079 			 * Typically expect dring-data messages, so handle
5080 			 * them first
5081 			 */
5082 			if ((status = vd_process_dring_msg(vd, msg,
5083 			    msglen)) != ENOMSG)
5084 				return (status);
5085 
5086 			/*
5087 			 * Acknowledge an unregister-dring message, but reset
5088 			 * the connection anyway:  Although the protocol
5089 			 * allows unregistering drings, this server cannot
5090 			 * serve a vdisk without its only dring
5091 			 */
5092 			status = vd_process_dring_unreg_msg(vd, msg, msglen);
5093 			return ((status == 0) ? ENOTSUP : status);
5094 
5095 		default:
5096 			ASSERT("Unsupported transfer mode");
5097 			PR0("Unsupported transfer mode");
5098 			return (ENOTSUP);
5099 		}
5100 
5101 	default:
5102 		ASSERT("Invalid client connection state");
5103 		PR0("Invalid client connection state");
5104 		return (ENOTSUP);
5105 	}
5106 }
5107 
5108 static int
5109 vd_process_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
5110 {
5111 	int		status;
5112 	boolean_t	reset_ldc = B_FALSE;
5113 	vd_task_t	task;
5114 
5115 	/*
5116 	 * Check that the message is at least big enough for a "tag", so that
5117 	 * message processing can proceed based on tag-specified message type
5118 	 */
5119 	if (msglen < sizeof (vio_msg_tag_t)) {
5120 		PR0("Received short (%lu-byte) message", msglen);
5121 		/* Can't "nack" short message, so drop the big hammer */
5122 		PR0("initiating full reset");
5123 		vd_need_reset(vd, B_TRUE);
5124 		return (EBADMSG);
5125 	}
5126 
5127 	/*
5128 	 * Process the message
5129 	 */
5130 	switch (status = vd_do_process_msg(vd, msg, msglen)) {
5131 	case 0:
5132 		/* "ack" valid, successfully-processed messages */
5133 		msg->tag.vio_subtype = VIO_SUBTYPE_ACK;
5134 		break;
5135 
5136 	case EINPROGRESS:
5137 		/* The completion handler will "ack" or "nack" the message */
5138 		return (EINPROGRESS);
5139 	case ENOMSG:
5140 		PR0("Received unexpected message");
5141 		_NOTE(FALLTHROUGH);
5142 	case EBADMSG:
5143 	case ENOTSUP:
5144 		/* "transport" error will cause NACK of invalid messages */
5145 		msg->tag.vio_subtype = VIO_SUBTYPE_NACK;
5146 		break;
5147 
5148 	default:
5149 		/* "transport" error will cause NACK of invalid messages */
5150 		msg->tag.vio_subtype = VIO_SUBTYPE_NACK;
5151 		/* An LDC error probably occurred, so try resetting it */
5152 		reset_ldc = B_TRUE;
5153 		break;
5154 	}
5155 
5156 	PR1("\tResulting in state %d (%s)", vd->state,
5157 	    vd_decode_state(vd->state));
5158 
5159 	/* populate the task so we can dispatch it on the taskq */
5160 	task.vd = vd;
5161 	task.msg = msg;
5162 	task.msglen = msglen;
5163 
5164 	/*
5165 	 * Queue a task to send the notification that the operation completed.
5166 	 * We need to ensure that requests are responded to in the correct
5167 	 * order and since the taskq is processed serially this ordering
5168 	 * is maintained.
5169 	 */
5170 	(void) ddi_taskq_dispatch(vd->completionq, vd_serial_notify,
5171 	    &task, DDI_SLEEP);
5172 
5173 	/*
5174 	 * To ensure handshake negotiations do not happen out of order, such
5175 	 * requests that come through this path should not be done in parallel
5176 	 * so we need to wait here until the response is sent to the client.
5177 	 */
5178 	ddi_taskq_wait(vd->completionq);
5179 
5180 	/* Arrange to reset the connection for nack'ed or failed messages */
5181 	if ((status != 0) || reset_ldc) {
5182 		PR0("initiating %s reset",
5183 		    (reset_ldc) ? "full" : "soft");
5184 		vd_need_reset(vd, reset_ldc);
5185 	}
5186 
5187 	return (status);
5188 }
5189 
5190 static boolean_t
5191 vd_enabled(vd_t *vd)
5192 {
5193 	boolean_t	enabled;
5194 
5195 	mutex_enter(&vd->lock);
5196 	enabled = vd->enabled;
5197 	mutex_exit(&vd->lock);
5198 	return (enabled);
5199 }
5200 
5201 static void
5202 vd_recv_msg(void *arg)
5203 {
5204 	vd_t	*vd = (vd_t *)arg;
5205 	int	rv = 0, status = 0;
5206 
5207 	ASSERT(vd != NULL);
5208 
5209 	PR2("New task to receive incoming message(s)");
5210 
5211 
5212 	while (vd_enabled(vd) && status == 0) {
5213 		size_t		msglen, msgsize;
5214 		ldc_status_t	lstatus;
5215 
5216 		/*
5217 		 * Receive and process a message
5218 		 */
5219 		vd_reset_if_needed(vd);	/* can change vd->max_msglen */
5220 
5221 		/*
5222 		 * check if channel is UP - else break out of loop
5223 		 */
5224 		status = ldc_status(vd->ldc_handle, &lstatus);
5225 		if (lstatus != LDC_UP) {
5226 			PR0("channel not up (status=%d), exiting recv loop\n",
5227 			    lstatus);
5228 			break;
5229 		}
5230 
5231 		ASSERT(vd->max_msglen != 0);
5232 
5233 		msgsize = vd->max_msglen; /* stable copy for alloc/free */
5234 		msglen	= msgsize;	  /* actual len after recv_msg() */
5235 
5236 		status = recv_msg(vd->ldc_handle, vd->vio_msgp, &msglen);
5237 		switch (status) {
5238 		case 0:
5239 			rv = vd_process_msg(vd, (void *)vd->vio_msgp, msglen);
5240 			/* check if max_msglen changed */
5241 			if (msgsize != vd->max_msglen) {
5242 				PR0("max_msglen changed 0x%lx to 0x%lx bytes\n",
5243 				    msgsize, vd->max_msglen);
5244 				kmem_free(vd->vio_msgp, msgsize);
5245 				vd->vio_msgp =
5246 				    kmem_alloc(vd->max_msglen, KM_SLEEP);
5247 			}
5248 			if (rv == EINPROGRESS)
5249 				continue;
5250 			break;
5251 
5252 		case ENOMSG:
5253 			break;
5254 
5255 		case ECONNRESET:
5256 			PR0("initiating soft reset (ECONNRESET)\n");
5257 			vd_need_reset(vd, B_FALSE);
5258 			status = 0;
5259 			break;
5260 
5261 		default:
5262 			/* Probably an LDC failure; arrange to reset it */
5263 			PR0("initiating full reset (status=0x%x)", status);
5264 			vd_need_reset(vd, B_TRUE);
5265 			break;
5266 		}
5267 	}
5268 
5269 	PR2("Task finished");
5270 }
5271 
5272 static uint_t
5273 vd_handle_ldc_events(uint64_t event, caddr_t arg)
5274 {
5275 	vd_t	*vd = (vd_t *)(void *)arg;
5276 	int	status;
5277 
5278 	ASSERT(vd != NULL);
5279 
5280 	if (!vd_enabled(vd))
5281 		return (LDC_SUCCESS);
5282 
5283 	if (event & LDC_EVT_DOWN) {
5284 		PR0("LDC_EVT_DOWN: LDC channel went down");
5285 
5286 		vd_need_reset(vd, B_TRUE);
5287 		status = ddi_taskq_dispatch(vd->startq, vd_recv_msg, vd,
5288 		    DDI_SLEEP);
5289 		if (status == DDI_FAILURE) {
5290 			PR0("cannot schedule task to recv msg\n");
5291 			vd_need_reset(vd, B_TRUE);
5292 		}
5293 	}
5294 
5295 	if (event & LDC_EVT_RESET) {
5296 		PR0("LDC_EVT_RESET: LDC channel was reset");
5297 
5298 		if (vd->state != VD_STATE_INIT) {
5299 			PR0("scheduling full reset");
5300 			vd_need_reset(vd, B_FALSE);
5301 			status = ddi_taskq_dispatch(vd->startq, vd_recv_msg,
5302 			    vd, DDI_SLEEP);
5303 			if (status == DDI_FAILURE) {
5304 				PR0("cannot schedule task to recv msg\n");
5305 				vd_need_reset(vd, B_TRUE);
5306 			}
5307 
5308 		} else {
5309 			PR0("channel already reset, ignoring...\n");
5310 			PR0("doing ldc up...\n");
5311 			(void) ldc_up(vd->ldc_handle);
5312 		}
5313 
5314 		return (LDC_SUCCESS);
5315 	}
5316 
5317 	if (event & LDC_EVT_UP) {
5318 		PR0("EVT_UP: LDC is up\nResetting client connection state");
5319 		PR0("initiating soft reset");
5320 		vd_need_reset(vd, B_FALSE);
5321 		status = ddi_taskq_dispatch(vd->startq, vd_recv_msg,
5322 		    vd, DDI_SLEEP);
5323 		if (status == DDI_FAILURE) {
5324 			PR0("cannot schedule task to recv msg\n");
5325 			vd_need_reset(vd, B_TRUE);
5326 			return (LDC_SUCCESS);
5327 		}
5328 	}
5329 
5330 	if (event & LDC_EVT_READ) {
5331 		int	status;
5332 
5333 		PR1("New data available");
5334 		/* Queue a task to receive the new data */
5335 		status = ddi_taskq_dispatch(vd->startq, vd_recv_msg, vd,
5336 		    DDI_SLEEP);
5337 
5338 		if (status == DDI_FAILURE) {
5339 			PR0("cannot schedule task to recv msg\n");
5340 			vd_need_reset(vd, B_TRUE);
5341 		}
5342 	}
5343 
5344 	return (LDC_SUCCESS);
5345 }
5346 
5347 static uint_t
5348 vds_check_for_vd(mod_hash_key_t key, mod_hash_val_t *val, void *arg)
5349 {
5350 	_NOTE(ARGUNUSED(key, val))
5351 	(*((uint_t *)arg))++;
5352 	return (MH_WALK_TERMINATE);
5353 }
5354 
5355 
5356 static int
5357 vds_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
5358 {
5359 	uint_t	vd_present = 0;
5360 	minor_t	instance;
5361 	vds_t	*vds;
5362 
5363 
5364 	switch (cmd) {
5365 	case DDI_DETACH:
5366 		/* the real work happens below */
5367 		break;
5368 	case DDI_SUSPEND:
5369 		PR0("No action required for DDI_SUSPEND");
5370 		return (DDI_SUCCESS);
5371 	default:
5372 		PR0("Unrecognized \"cmd\"");
5373 		return (DDI_FAILURE);
5374 	}
5375 
5376 	ASSERT(cmd == DDI_DETACH);
5377 	instance = ddi_get_instance(dip);
5378 	if ((vds = ddi_get_soft_state(vds_state, instance)) == NULL) {
5379 		PR0("Could not get state for instance %u", instance);
5380 		ddi_soft_state_free(vds_state, instance);
5381 		return (DDI_FAILURE);
5382 	}
5383 
5384 	/* Do no detach when serving any vdisks */
5385 	mod_hash_walk(vds->vd_table, vds_check_for_vd, &vd_present);
5386 	if (vd_present) {
5387 		PR0("Not detaching because serving vdisks");
5388 		return (DDI_FAILURE);
5389 	}
5390 
5391 	PR0("Detaching");
5392 	if (vds->initialized & VDS_MDEG) {
5393 		(void) mdeg_unregister(vds->mdeg);
5394 		kmem_free(vds->ispecp->specp, sizeof (vds_prop_template));
5395 		kmem_free(vds->ispecp, sizeof (mdeg_node_spec_t));
5396 		vds->ispecp = NULL;
5397 		vds->mdeg = NULL;
5398 	}
5399 
5400 	vds_driver_types_free(vds);
5401 
5402 	if (vds->initialized & VDS_LDI)
5403 		(void) ldi_ident_release(vds->ldi_ident);
5404 	mod_hash_destroy_hash(vds->vd_table);
5405 	ddi_soft_state_free(vds_state, instance);
5406 	return (DDI_SUCCESS);
5407 }
5408 
5409 /*
5410  * Description:
5411  *	This function checks to see if the disk image being used as a
5412  *	virtual disk is an ISO image. An ISO image is a special case
5413  *	which can be booted/installed from like a CD/DVD.
5414  *
5415  * Parameters:
5416  *	vd		- disk on which the operation is performed.
5417  *
5418  * Return Code:
5419  *	B_TRUE		- The disk image is an ISO 9660 compliant image
5420  *	B_FALSE		- just a regular disk image
5421  */
5422 static boolean_t
5423 vd_dskimg_is_iso_image(vd_t *vd)
5424 {
5425 	char	iso_buf[ISO_SECTOR_SIZE];
5426 	int	i, rv;
5427 	uint_t	sec;
5428 
5429 	ASSERT(VD_DSKIMG(vd));
5430 
5431 	/*
5432 	 * If we have already discovered and saved this info we can
5433 	 * short-circuit the check and avoid reading the disk image.
5434 	 */
5435 	if (vd->vdisk_media == VD_MEDIA_DVD || vd->vdisk_media == VD_MEDIA_CD)
5436 		return (B_TRUE);
5437 
5438 	/*
5439 	 * We wish to read the sector that should contain the 2nd ISO volume
5440 	 * descriptor. The second field in this descriptor is called the
5441 	 * Standard Identifier and is set to CD001 for a CD-ROM compliant
5442 	 * to the ISO 9660 standard.
5443 	 */
5444 	sec = (ISO_VOLDESC_SEC * ISO_SECTOR_SIZE) / vd->vdisk_block_size;
5445 	rv = vd_dskimg_rw(vd, VD_SLICE_NONE, VD_OP_BREAD, (caddr_t)iso_buf,
5446 	    sec, ISO_SECTOR_SIZE);
5447 
5448 	if (rv < 0)
5449 		return (B_FALSE);
5450 
5451 	for (i = 0; i < ISO_ID_STRLEN; i++) {
5452 		if (ISO_STD_ID(iso_buf)[i] != ISO_ID_STRING[i])
5453 			return (B_FALSE);
5454 	}
5455 
5456 	return (B_TRUE);
5457 }
5458 
5459 /*
5460  * Description:
5461  *	This function checks to see if the virtual device is an ATAPI
5462  *	device. ATAPI devices use Group 1 Read/Write commands, so
5463  *	any USCSI calls vds makes need to take this into account.
5464  *
5465  * Parameters:
5466  *	vd		- disk on which the operation is performed.
5467  *
5468  * Return Code:
5469  *	B_TRUE		- The virtual disk is backed by an ATAPI device
5470  *	B_FALSE		- not an ATAPI device (presumably SCSI)
5471  */
5472 static boolean_t
5473 vd_is_atapi_device(vd_t *vd)
5474 {
5475 	boolean_t	is_atapi = B_FALSE;
5476 	char		*variantp;
5477 	int		rv;
5478 
5479 	ASSERT(vd->ldi_handle[0] != NULL);
5480 	ASSERT(!vd->file);
5481 
5482 	rv = ldi_prop_lookup_string(vd->ldi_handle[0],
5483 	    (LDI_DEV_T_ANY | DDI_PROP_DONTPASS), "variant", &variantp);
5484 	if (rv == DDI_PROP_SUCCESS) {
5485 		PR0("'variant' property exists for %s", vd->device_path);
5486 		if (strcmp(variantp, "atapi") == 0)
5487 			is_atapi = B_TRUE;
5488 		ddi_prop_free(variantp);
5489 	}
5490 
5491 	rv = ldi_prop_exists(vd->ldi_handle[0], LDI_DEV_T_ANY, "atapi");
5492 	if (rv) {
5493 		PR0("'atapi' property exists for %s", vd->device_path);
5494 		is_atapi = B_TRUE;
5495 	}
5496 
5497 	return (is_atapi);
5498 }
5499 
5500 static int
5501 vd_setup_full_disk(vd_t *vd)
5502 {
5503 	int		status;
5504 	major_t		major = getmajor(vd->dev[0]);
5505 	minor_t		minor = getminor(vd->dev[0]) - VD_ENTIRE_DISK_SLICE;
5506 
5507 	ASSERT(vd->vdisk_type == VD_DISK_TYPE_DISK);
5508 
5509 	vd->vdisk_block_size = DEV_BSIZE;
5510 
5511 	/* set the disk size, block size and the media type of the disk */
5512 	status = vd_backend_check_size(vd);
5513 
5514 	if (status != 0) {
5515 		if (!vd->scsi) {
5516 			/* unexpected failure */
5517 			PRN("ldi_ioctl(DKIOCGMEDIAINFO) returned errno %d",
5518 			    status);
5519 			return (status);
5520 		}
5521 
5522 		/*
5523 		 * The function can fail for SCSI disks which are present but
5524 		 * reserved by another system. In that case, we don't know the
5525 		 * size of the disk and the block size.
5526 		 */
5527 		vd->vdisk_size = VD_SIZE_UNKNOWN;
5528 		vd->block_size = 0;
5529 		vd->vdisk_media = VD_MEDIA_FIXED;
5530 	}
5531 
5532 	/* Move dev number and LDI handle to entire-disk-slice array elements */
5533 	vd->dev[VD_ENTIRE_DISK_SLICE]		= vd->dev[0];
5534 	vd->dev[0]				= 0;
5535 	vd->ldi_handle[VD_ENTIRE_DISK_SLICE]	= vd->ldi_handle[0];
5536 	vd->ldi_handle[0]			= NULL;
5537 
5538 	/* Initialize device numbers for remaining slices and open them */
5539 	for (int slice = 0; slice < vd->nslices; slice++) {
5540 		/*
5541 		 * Skip the entire-disk slice, as it's already open and its
5542 		 * device known
5543 		 */
5544 		if (slice == VD_ENTIRE_DISK_SLICE)
5545 			continue;
5546 		ASSERT(vd->dev[slice] == 0);
5547 		ASSERT(vd->ldi_handle[slice] == NULL);
5548 
5549 		/*
5550 		 * Construct the device number for the current slice
5551 		 */
5552 		vd->dev[slice] = makedevice(major, (minor + slice));
5553 
5554 		/*
5555 		 * Open all slices of the disk to serve them to the client.
5556 		 * Slices are opened exclusively to prevent other threads or
5557 		 * processes in the service domain from performing I/O to
5558 		 * slices being accessed by a client.  Failure to open a slice
5559 		 * results in vds not serving this disk, as the client could
5560 		 * attempt (and should be able) to access any slice immediately.
5561 		 * Any slices successfully opened before a failure will get
5562 		 * closed by vds_destroy_vd() as a result of the error returned
5563 		 * by this function.
5564 		 *
5565 		 * We need to do the open with FNDELAY so that opening an empty
5566 		 * slice does not fail.
5567 		 */
5568 		PR0("Opening device major %u, minor %u = slice %u",
5569 		    major, minor, slice);
5570 
5571 		/*
5572 		 * Try to open the device. This can fail for example if we are
5573 		 * opening an empty slice. So in case of a failure, we try the
5574 		 * open again but this time with the FNDELAY flag.
5575 		 */
5576 		status = ldi_open_by_dev(&vd->dev[slice], OTYP_BLK,
5577 		    vd->open_flags, kcred, &vd->ldi_handle[slice],
5578 		    vd->vds->ldi_ident);
5579 
5580 		if (status != 0) {
5581 			status = ldi_open_by_dev(&vd->dev[slice], OTYP_BLK,
5582 			    vd->open_flags | FNDELAY, kcred,
5583 			    &vd->ldi_handle[slice], vd->vds->ldi_ident);
5584 		}
5585 
5586 		if (status != 0) {
5587 			PRN("ldi_open_by_dev() returned errno %d "
5588 			    "for slice %u", status, slice);
5589 			/* vds_destroy_vd() will close any open slices */
5590 			vd->ldi_handle[slice] = NULL;
5591 			return (status);
5592 		}
5593 	}
5594 
5595 	return (0);
5596 }
5597 
5598 /*
5599  * When a slice or a volume is exported as a single-slice disk, we want
5600  * the disk backend (i.e. the slice or volume) to be entirely mapped as
5601  * a slice without the addition of any metadata.
5602  *
5603  * So when exporting the disk as a VTOC disk, we fake a disk with the following
5604  * layout:
5605  *                flabel +--- flabel_limit
5606  *                 <->   V
5607  *                 0 1   C                          D  E
5608  *                 +-+---+--------------------------+--+
5609  *  virtual disk:  |L|XXX|           slice 0        |AA|
5610  *                 +-+---+--------------------------+--+
5611  *                  ^    :                          :
5612  *                  |    :                          :
5613  *      VTOC LABEL--+    :                          :
5614  *                       +--------------------------+
5615  *  disk backend:        |     slice/volume/file    |
5616  *                       +--------------------------+
5617  *                       0                          N
5618  *
5619  * N is the number of blocks in the slice/volume/file.
5620  *
5621  * We simulate a disk with N+M blocks, where M is the number of blocks
5622  * simluated at the beginning and at the end of the disk (blocks 0-C
5623  * and D-E).
5624  *
5625  * The first blocks (0 to C-1) are emulated and can not be changed. Blocks C
5626  * to D defines slice 0 and are mapped to the backend. Finally we emulate 2
5627  * alternate cylinders at the end of the disk (blocks D-E). In summary we have:
5628  *
5629  * - block 0 (L) returns a fake VTOC label
5630  * - blocks 1 to C-1 (X) are unused and return 0
5631  * - blocks C to D-1 are mapped to the exported slice or volume
5632  * - blocks D and E (A) are blocks defining alternate cylinders (2 cylinders)
5633  *
5634  * Note: because we define a fake disk geometry, it is possible that the length
5635  * of the backend is not a multiple of the size of cylinder, in that case the
5636  * very end of the backend will not map to any block of the virtual disk.
5637  */
5638 static int
5639 vd_setup_partition_vtoc(vd_t *vd)
5640 {
5641 	char *device_path = vd->device_path;
5642 	char unit;
5643 	size_t size, csize;
5644 
5645 	/* Initialize dk_geom structure for single-slice device */
5646 	if (vd->dk_geom.dkg_nsect == 0) {
5647 		PRN("%s geometry claims 0 sectors per track", device_path);
5648 		return (EIO);
5649 	}
5650 	if (vd->dk_geom.dkg_nhead == 0) {
5651 		PRN("%s geometry claims 0 heads", device_path);
5652 		return (EIO);
5653 	}
5654 
5655 	/* size of a cylinder in block */
5656 	csize = vd->dk_geom.dkg_nhead * vd->dk_geom.dkg_nsect;
5657 
5658 	/*
5659 	 * Add extra cylinders: we emulate the first cylinder (which contains
5660 	 * the disk label).
5661 	 */
5662 	vd->dk_geom.dkg_ncyl = vd->vdisk_size / csize + 1;
5663 
5664 	/* we emulate 2 alternate cylinders */
5665 	vd->dk_geom.dkg_acyl = 2;
5666 	vd->dk_geom.dkg_pcyl = vd->dk_geom.dkg_ncyl + vd->dk_geom.dkg_acyl;
5667 
5668 
5669 	/* Initialize vtoc structure for single-slice device */
5670 	bzero(vd->vtoc.v_part, sizeof (vd->vtoc.v_part));
5671 	vd->vtoc.v_part[0].p_tag = V_UNASSIGNED;
5672 	vd->vtoc.v_part[0].p_flag = 0;
5673 	/*
5674 	 * Partition 0 starts on cylinder 1 and its size has to be
5675 	 * a multiple of a number of cylinder.
5676 	 */
5677 	vd->vtoc.v_part[0].p_start = csize; /* start on cylinder 1 */
5678 	vd->vtoc.v_part[0].p_size = (vd->vdisk_size / csize) * csize;
5679 
5680 	if (vd_slice_single_slice) {
5681 		vd->vtoc.v_nparts = 1;
5682 		bcopy(VD_ASCIILABEL, vd->vtoc.v_asciilabel,
5683 		    MIN(sizeof (VD_ASCIILABEL),
5684 		    sizeof (vd->vtoc.v_asciilabel)));
5685 		bcopy(VD_VOLUME_NAME, vd->vtoc.v_volume,
5686 		    MIN(sizeof (VD_VOLUME_NAME), sizeof (vd->vtoc.v_volume)));
5687 	} else {
5688 		/* adjust the number of slices */
5689 		vd->nslices = V_NUMPAR;
5690 		vd->vtoc.v_nparts = V_NUMPAR;
5691 
5692 		/* define slice 2 representing the entire disk */
5693 		vd->vtoc.v_part[VD_ENTIRE_DISK_SLICE].p_tag = V_BACKUP;
5694 		vd->vtoc.v_part[VD_ENTIRE_DISK_SLICE].p_flag = 0;
5695 		vd->vtoc.v_part[VD_ENTIRE_DISK_SLICE].p_start = 0;
5696 		vd->vtoc.v_part[VD_ENTIRE_DISK_SLICE].p_size =
5697 		    vd->dk_geom.dkg_ncyl * csize;
5698 
5699 		vd_get_readable_size(vd->vdisk_size * vd->vdisk_block_size,
5700 		    &size, &unit);
5701 
5702 		/*
5703 		 * Set some attributes of the geometry to what format(1m) uses
5704 		 * so that writing a default label using format(1m) does not
5705 		 * produce any error.
5706 		 */
5707 		vd->dk_geom.dkg_bcyl = 0;
5708 		vd->dk_geom.dkg_intrlv = 1;
5709 		vd->dk_geom.dkg_write_reinstruct = 0;
5710 		vd->dk_geom.dkg_read_reinstruct = 0;
5711 
5712 		/*
5713 		 * We must have a correct label name otherwise format(1m) will
5714 		 * not recognized the disk as labeled.
5715 		 */
5716 		(void) snprintf(vd->vtoc.v_asciilabel, LEN_DKL_ASCII,
5717 		    "SUN-DiskSlice-%ld%cB cyl %d alt %d hd %d sec %d",
5718 		    size, unit,
5719 		    vd->dk_geom.dkg_ncyl, vd->dk_geom.dkg_acyl,
5720 		    vd->dk_geom.dkg_nhead, vd->dk_geom.dkg_nsect);
5721 		bzero(vd->vtoc.v_volume, sizeof (vd->vtoc.v_volume));
5722 
5723 		/* create a fake label from the vtoc and geometry */
5724 		vd->flabel_limit = (uint_t)csize;
5725 		vd->flabel_size = VD_LABEL_VTOC_SIZE;
5726 		vd->flabel = kmem_zalloc(vd->flabel_size, KM_SLEEP);
5727 		vd_vtocgeom_to_label(&vd->vtoc, &vd->dk_geom,
5728 		    VD_LABEL_VTOC(vd));
5729 	}
5730 
5731 	/* adjust the vdisk_size, we emulate 3 cylinders */
5732 	vd->vdisk_size += csize * 3;
5733 
5734 	return (0);
5735 }
5736 
5737 /*
5738  * When a slice, volume or file is exported as a single-slice disk, we want
5739  * the disk backend (i.e. the slice, volume or file) to be entirely mapped
5740  * as a slice without the addition of any metadata.
5741  *
5742  * So when exporting the disk as an EFI disk, we fake a disk with the following
5743  * layout:
5744  *
5745  *                  flabel        +--- flabel_limit
5746  *                 <------>       v
5747  *                 0 1 2  L      34                        34+N      P
5748  *                 +-+-+--+-------+--------------------------+-------+
5749  *  virtual disk:  |X|T|EE|XXXXXXX|           slice 0        |RRRRRRR|
5750  *                 +-+-+--+-------+--------------------------+-------+
5751  *                    ^ ^         :                          :
5752  *                    | |         :                          :
5753  *                GPT-+ +-GPE     :                          :
5754  *                                +--------------------------+
5755  *  disk backend:                 |     slice/volume/file    |
5756  *                                +--------------------------+
5757  *                                0                          N
5758  *
5759  * N is the number of blocks in the slice/volume/file.
5760  *
5761  * We simulate a disk with N+M blocks, where M is the number of blocks
5762  * simluated at the beginning and at the end of the disk (blocks 0-34
5763  * and 34+N-P).
5764  *
5765  * The first 34 blocks (0 to 33) are emulated and can not be changed. Blocks 34
5766  * to 34+N defines slice 0 and are mapped to the exported backend, and we
5767  * emulate some blocks at the end of the disk (blocks 34+N to P) as a the EFI
5768  * reserved partition.
5769  *
5770  * - block 0 (X) is unused and return 0
5771  * - block 1 (T) returns a fake EFI GPT (via DKIOCGETEFI)
5772  * - blocks 2 to L-1 (E) defines a fake EFI GPE (via DKIOCGETEFI)
5773  * - blocks L to 33 (X) are unused and return 0
5774  * - blocks 34 to 34+N are mapped to the exported slice, volume or file
5775  * - blocks 34+N+1 to P define a fake reserved partition and backup label, it
5776  *   returns 0
5777  *
5778  * Note: if the backend size is not a multiple of the vdisk block size
5779  * (DEV_BSIZE = 512 byte) then the very end of the backend will not map to
5780  * any block of the virtual disk.
5781  */
5782 static int
5783 vd_setup_partition_efi(vd_t *vd)
5784 {
5785 	efi_gpt_t *gpt;
5786 	efi_gpe_t *gpe;
5787 	struct uuid uuid = EFI_USR;
5788 	struct uuid efi_reserved = EFI_RESERVED;
5789 	uint32_t crc;
5790 	uint64_t s0_start, s0_end;
5791 
5792 	vd->flabel_limit = 34;
5793 	vd->flabel_size = VD_LABEL_EFI_SIZE;
5794 	vd->flabel = kmem_zalloc(vd->flabel_size, KM_SLEEP);
5795 	gpt = VD_LABEL_EFI_GPT(vd);
5796 	gpe = VD_LABEL_EFI_GPE(vd);
5797 
5798 	/* adjust the vdisk_size, we emulate the first 34 blocks */
5799 	vd->vdisk_size += 34;
5800 	s0_start = 34;
5801 	s0_end = vd->vdisk_size - 1;
5802 
5803 	gpt->efi_gpt_Signature = LE_64(EFI_SIGNATURE);
5804 	gpt->efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
5805 	gpt->efi_gpt_HeaderSize = LE_32(sizeof (efi_gpt_t));
5806 	gpt->efi_gpt_FirstUsableLBA = LE_64(34ULL);
5807 	gpt->efi_gpt_PartitionEntryLBA = LE_64(2ULL);
5808 	gpt->efi_gpt_SizeOfPartitionEntry = LE_32(sizeof (efi_gpe_t));
5809 
5810 	UUID_LE_CONVERT(gpe[0].efi_gpe_PartitionTypeGUID, uuid);
5811 	gpe[0].efi_gpe_StartingLBA = LE_64(s0_start);
5812 	gpe[0].efi_gpe_EndingLBA = LE_64(s0_end);
5813 
5814 	if (vd_slice_single_slice) {
5815 		gpt->efi_gpt_NumberOfPartitionEntries = LE_32(1);
5816 	} else {
5817 		/* adjust the number of slices */
5818 		gpt->efi_gpt_NumberOfPartitionEntries = LE_32(VD_MAXPART);
5819 		vd->nslices = V_NUMPAR;
5820 
5821 		/* define a fake reserved partition */
5822 		UUID_LE_CONVERT(gpe[VD_MAXPART - 1].efi_gpe_PartitionTypeGUID,
5823 		    efi_reserved);
5824 		gpe[VD_MAXPART - 1].efi_gpe_StartingLBA =
5825 		    LE_64(s0_end + 1);
5826 		gpe[VD_MAXPART - 1].efi_gpe_EndingLBA =
5827 		    LE_64(s0_end + EFI_MIN_RESV_SIZE);
5828 
5829 		/* adjust the vdisk_size to include the reserved slice */
5830 		vd->vdisk_size += EFI_MIN_RESV_SIZE;
5831 	}
5832 
5833 	gpt->efi_gpt_LastUsableLBA = LE_64(vd->vdisk_size - 1);
5834 
5835 	/* adjust the vdisk size for the backup GPT and GPE */
5836 	vd->vdisk_size += 33;
5837 
5838 	CRC32(crc, gpe, sizeof (efi_gpe_t) * VD_MAXPART, -1U, crc32_table);
5839 	gpt->efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
5840 
5841 	CRC32(crc, gpt, sizeof (efi_gpt_t), -1U, crc32_table);
5842 	gpt->efi_gpt_HeaderCRC32 = LE_32(~crc);
5843 
5844 	return (0);
5845 }
5846 
5847 /*
5848  * Setup for a virtual disk whose backend is a file (exported as a single slice
5849  * or as a full disk). In that case, the backend is accessed using the vnode
5850  * interface.
5851  */
5852 static int
5853 vd_setup_backend_vnode(vd_t *vd)
5854 {
5855 	int 		rval, status;
5856 	vattr_t		vattr;
5857 	dev_t		dev;
5858 	char		*file_path = vd->device_path;
5859 	ldi_handle_t	lhandle;
5860 	struct dk_cinfo	dk_cinfo;
5861 
5862 	ASSERT(!vd->volume);
5863 
5864 	if ((status = vn_open(file_path, UIO_SYSSPACE, vd->open_flags | FOFFMAX,
5865 	    0, &vd->file_vnode, 0, 0)) != 0) {
5866 		PRN("vn_open(%s) = errno %d", file_path, status);
5867 		return (status);
5868 	}
5869 
5870 	/*
5871 	 * We set vd->file now so that vds_destroy_vd will take care of
5872 	 * closing the file and releasing the vnode in case of an error.
5873 	 */
5874 	vd->file = B_TRUE;
5875 
5876 	vattr.va_mask = AT_SIZE;
5877 	if ((status = VOP_GETATTR(vd->file_vnode, &vattr, 0, kcred, NULL))
5878 	    != 0) {
5879 		PRN("VOP_GETATTR(%s) = errno %d", file_path, status);
5880 		return (EIO);
5881 	}
5882 
5883 	vd->dskimg_size = vattr.va_size;
5884 
5885 	if (vd->file_vnode->v_flag & VNOMAP) {
5886 		PRN("File %s cannot be mapped", file_path);
5887 		return (EIO);
5888 	}
5889 
5890 	vd->max_xfer_sz = maxphys / DEV_BSIZE; /* default transfer size */
5891 
5892 	/*
5893 	 * Get max_xfer_sz from the device where the file is.
5894 	 */
5895 	dev = vd->file_vnode->v_vfsp->vfs_dev;
5896 	PR0("underlying device of %s = (%d, %d)\n", file_path,
5897 	    getmajor(dev), getminor(dev));
5898 
5899 	status = ldi_open_by_dev(&dev, OTYP_BLK, FREAD, kcred, &lhandle,
5900 	    vd->vds->ldi_ident);
5901 
5902 	if (status != 0) {
5903 		PR0("ldi_open() returned errno %d for underlying device",
5904 		    status);
5905 	} else {
5906 		if ((status = ldi_ioctl(lhandle, DKIOCINFO,
5907 		    (intptr_t)&dk_cinfo, (vd->open_flags | FKIOCTL), kcred,
5908 		    &rval)) != 0) {
5909 			PR0("ldi_ioctl(DKIOCINFO) returned errno %d for "
5910 			    "underlying device", status);
5911 		} else {
5912 			/*
5913 			 * Store the device's max transfer size for
5914 			 * return to the client
5915 			 */
5916 			vd->max_xfer_sz = dk_cinfo.dki_maxtransfer;
5917 		}
5918 
5919 		PR0("close the underlying device");
5920 		(void) ldi_close(lhandle, FREAD, kcred);
5921 	}
5922 
5923 	PR0("using file %s on device (%d, %d), max_xfer = %u blks",
5924 	    file_path, getmajor(dev), getminor(dev), vd->max_xfer_sz);
5925 
5926 	if (vd->vdisk_type == VD_DISK_TYPE_SLICE)
5927 		status = vd_setup_slice_image(vd);
5928 	else
5929 		status = vd_setup_disk_image(vd);
5930 
5931 	return (status);
5932 }
5933 
5934 static int
5935 vd_setup_slice_image(vd_t *vd)
5936 {
5937 	struct dk_label label;
5938 	int status;
5939 
5940 	/* sector size = block size = DEV_BSIZE */
5941 	vd->block_size = DEV_BSIZE;
5942 	vd->vdisk_block_size = DEV_BSIZE;
5943 	vd->vdisk_size = vd->dskimg_size / DEV_BSIZE;
5944 	vd->vdisk_media = VD_MEDIA_FIXED;
5945 	vd->vdisk_label = (vd_slice_label == VD_DISK_LABEL_UNK)?
5946 	    vd_file_slice_label : vd_slice_label;
5947 
5948 	if (vd->vdisk_label == VD_DISK_LABEL_EFI ||
5949 	    vd->dskimg_size >= 2 * ONE_TERABYTE) {
5950 		status = vd_setup_partition_efi(vd);
5951 	} else {
5952 		/*
5953 		 * We build a default label to get a geometry for
5954 		 * the vdisk. Then the partition setup function will
5955 		 * adjust the vtoc so that it defines a single-slice
5956 		 * disk.
5957 		 */
5958 		vd_build_default_label(vd->dskimg_size, &label);
5959 		vd_label_to_vtocgeom(&label, &vd->vtoc, &vd->dk_geom);
5960 		status = vd_setup_partition_vtoc(vd);
5961 	}
5962 
5963 	return (status);
5964 }
5965 
5966 static int
5967 vd_setup_disk_image(vd_t *vd)
5968 {
5969 	int status;
5970 	char *backend_path = vd->device_path;
5971 
5972 	/* size should be at least sizeof(dk_label) */
5973 	if (vd->dskimg_size < sizeof (struct dk_label)) {
5974 		PRN("Size of file has to be at least %ld bytes",
5975 		    sizeof (struct dk_label));
5976 		return (EIO);
5977 	}
5978 
5979 	/* sector size = block size = DEV_BSIZE */
5980 	vd->block_size = DEV_BSIZE;
5981 	vd->vdisk_block_size = DEV_BSIZE;
5982 	vd->vdisk_size = vd->dskimg_size / DEV_BSIZE;
5983 
5984 	/*
5985 	 * Find and validate the geometry of a disk image.
5986 	 */
5987 	status = vd_dskimg_validate_geometry(vd);
5988 	if (status != 0 && status != EINVAL && status != ENOTSUP) {
5989 		PRN("Failed to read label from %s", backend_path);
5990 		return (EIO);
5991 	}
5992 
5993 	if (vd_dskimg_is_iso_image(vd)) {
5994 		/*
5995 		 * Indicate whether to call this a CD or DVD from the size
5996 		 * of the ISO image (images for both drive types are stored
5997 		 * in the ISO-9600 format). CDs can store up to just under 1Gb
5998 		 */
5999 		if ((vd->vdisk_size * vd->vdisk_block_size) > ONE_GIGABYTE)
6000 			vd->vdisk_media = VD_MEDIA_DVD;
6001 		else
6002 			vd->vdisk_media = VD_MEDIA_CD;
6003 	} else {
6004 		vd->vdisk_media = VD_MEDIA_FIXED;
6005 	}
6006 
6007 	/* Setup devid for the disk image */
6008 
6009 	if (vd->vdisk_label != VD_DISK_LABEL_UNK) {
6010 
6011 		status = vd_dskimg_read_devid(vd, &vd->dskimg_devid);
6012 
6013 		if (status == 0) {
6014 			/* a valid devid was found */
6015 			return (0);
6016 		}
6017 
6018 		if (status != EINVAL) {
6019 			/*
6020 			 * There was an error while trying to read the devid.
6021 			 * So this disk image may have a devid but we are
6022 			 * unable to read it.
6023 			 */
6024 			PR0("can not read devid for %s", backend_path);
6025 			vd->dskimg_devid = NULL;
6026 			return (0);
6027 		}
6028 	}
6029 
6030 	/*
6031 	 * No valid device id was found so we create one. Note that a failure
6032 	 * to create a device id is not fatal and does not prevent the disk
6033 	 * image from being attached.
6034 	 */
6035 	PR1("creating devid for %s", backend_path);
6036 
6037 	if (ddi_devid_init(vd->vds->dip, DEVID_FAB, NULL, 0,
6038 	    &vd->dskimg_devid) != DDI_SUCCESS) {
6039 		PR0("fail to create devid for %s", backend_path);
6040 		vd->dskimg_devid = NULL;
6041 		return (0);
6042 	}
6043 
6044 	/*
6045 	 * Write devid to the disk image. The devid is stored into the disk
6046 	 * image if we have a valid label; otherwise the devid will be stored
6047 	 * when the user writes a valid label.
6048 	 */
6049 	if (vd->vdisk_label != VD_DISK_LABEL_UNK) {
6050 		if (vd_dskimg_write_devid(vd, vd->dskimg_devid) != 0) {
6051 			PR0("fail to write devid for %s", backend_path);
6052 			ddi_devid_free(vd->dskimg_devid);
6053 			vd->dskimg_devid = NULL;
6054 		}
6055 	}
6056 
6057 	return (0);
6058 }
6059 
6060 
6061 /*
6062  * Description:
6063  *	Open a device using its device path (supplied by ldm(1m))
6064  *
6065  * Parameters:
6066  *	vd 	- pointer to structure containing the vDisk info
6067  *	flags	- open flags
6068  *
6069  * Return Value
6070  *	0	- success
6071  *	!= 0	- some other non-zero return value from ldi(9F) functions
6072  */
6073 static int
6074 vd_open_using_ldi_by_name(vd_t *vd, int flags)
6075 {
6076 	int		status;
6077 	char		*device_path = vd->device_path;
6078 
6079 	/* Attempt to open device */
6080 	status = ldi_open_by_name(device_path, flags, kcred,
6081 	    &vd->ldi_handle[0], vd->vds->ldi_ident);
6082 
6083 	/*
6084 	 * The open can fail for example if we are opening an empty slice.
6085 	 * In case of a failure, we try the open again but this time with
6086 	 * the FNDELAY flag.
6087 	 */
6088 	if (status != 0)
6089 		status = ldi_open_by_name(device_path, flags | FNDELAY,
6090 		    kcred, &vd->ldi_handle[0], vd->vds->ldi_ident);
6091 
6092 	if (status != 0) {
6093 		PR0("ldi_open_by_name(%s) = errno %d", device_path, status);
6094 		vd->ldi_handle[0] = NULL;
6095 		return (status);
6096 	}
6097 
6098 	return (0);
6099 }
6100 
6101 /*
6102  * Setup for a virtual disk which backend is a device (a physical disk,
6103  * slice or volume device) exported as a full disk or as a slice. In these
6104  * cases, the backend is accessed using the LDI interface.
6105  */
6106 static int
6107 vd_setup_backend_ldi(vd_t *vd)
6108 {
6109 	int		rval, status;
6110 	struct dk_cinfo	dk_cinfo;
6111 	char		*device_path = vd->device_path;
6112 
6113 	/* device has been opened by vd_identify_dev() */
6114 	ASSERT(vd->ldi_handle[0] != NULL);
6115 	ASSERT(vd->dev[0] != NULL);
6116 
6117 	vd->file = B_FALSE;
6118 
6119 	/* Verify backing device supports dk_cinfo */
6120 	if ((status = ldi_ioctl(vd->ldi_handle[0], DKIOCINFO,
6121 	    (intptr_t)&dk_cinfo, (vd->open_flags | FKIOCTL), kcred,
6122 	    &rval)) != 0) {
6123 		PRN("ldi_ioctl(DKIOCINFO) returned errno %d for %s",
6124 		    status, device_path);
6125 		return (status);
6126 	}
6127 	if (dk_cinfo.dki_partition >= V_NUMPAR) {
6128 		PRN("slice %u >= maximum slice %u for %s",
6129 		    dk_cinfo.dki_partition, V_NUMPAR, device_path);
6130 		return (EIO);
6131 	}
6132 
6133 	/*
6134 	 * The device has been opened read-only by vd_identify_dev(), re-open
6135 	 * it read-write if the write flag is set and we don't have an optical
6136 	 * device such as a CD-ROM, which, for now, we do not permit writes to
6137 	 * and thus should not export write operations to the client.
6138 	 *
6139 	 * Future: if/when we implement support for guest domains writing to
6140 	 * optical devices we will need to do further checking of the media type
6141 	 * to distinguish between read-only and writable discs.
6142 	 */
6143 	if (dk_cinfo.dki_ctype == DKC_CDROM) {
6144 
6145 		vd->open_flags &= ~FWRITE;
6146 
6147 	} else if (vd->open_flags & FWRITE) {
6148 
6149 		(void) ldi_close(vd->ldi_handle[0], vd->open_flags & ~FWRITE,
6150 		    kcred);
6151 		status = vd_open_using_ldi_by_name(vd, vd->open_flags);
6152 		if (status != 0) {
6153 			PR0("Failed to open (%s) = errno %d",
6154 			    device_path, status);
6155 			return (status);
6156 		}
6157 	}
6158 
6159 	/* Store the device's max transfer size for return to the client */
6160 	vd->max_xfer_sz = dk_cinfo.dki_maxtransfer;
6161 
6162 	/*
6163 	 * We need to work out if it's an ATAPI (IDE CD-ROM) or SCSI device so
6164 	 * that we can use the correct CDB group when sending USCSI commands.
6165 	 */
6166 	vd->is_atapi_dev = vd_is_atapi_device(vd);
6167 
6168 	/*
6169 	 * Export a full disk.
6170 	 *
6171 	 * The exported device can be either a volume, a disk or a CD/DVD
6172 	 * device.  We export a device as a full disk if we have an entire
6173 	 * disk slice (slice 2) and if this slice is exported as a full disk
6174 	 * and not as a single slice disk. A CD or DVD device is exported
6175 	 * as a full disk (even if it isn't s2). A volume is exported as a
6176 	 * full disk as long as the "slice" option is not specified.
6177 	 */
6178 	if (vd->vdisk_type == VD_DISK_TYPE_DISK) {
6179 
6180 		if (vd->volume) {
6181 			/* get size of backing device */
6182 			if (ldi_get_size(vd->ldi_handle[0], &vd->dskimg_size) !=
6183 			    DDI_SUCCESS) {
6184 				PRN("ldi_get_size() failed for %s",
6185 				    device_path);
6186 				return (EIO);
6187 			}
6188 
6189 			/* setup disk image */
6190 			return (vd_setup_disk_image(vd));
6191 		}
6192 
6193 		if (dk_cinfo.dki_partition == VD_ENTIRE_DISK_SLICE ||
6194 		    dk_cinfo.dki_ctype == DKC_CDROM) {
6195 			ASSERT(!vd->volume);
6196 			if (dk_cinfo.dki_ctype == DKC_SCSI_CCS)
6197 				vd->scsi = B_TRUE;
6198 			return (vd_setup_full_disk(vd));
6199 		}
6200 	}
6201 
6202 	/*
6203 	 * Export a single slice disk.
6204 	 *
6205 	 * The exported device can be either a volume device or a disk slice. If
6206 	 * it is a disk slice different from slice 2 then it is always exported
6207 	 * as a single slice disk even if the "slice" option is not specified.
6208 	 * If it is disk slice 2 or a volume device then it is exported as a
6209 	 * single slice disk only if the "slice" option is specified.
6210 	 */
6211 	return (vd_setup_single_slice_disk(vd));
6212 }
6213 
6214 static int
6215 vd_setup_single_slice_disk(vd_t *vd)
6216 {
6217 	int status, rval;
6218 	struct dk_label label;
6219 	char *device_path = vd->device_path;
6220 	struct vtoc vtoc;
6221 
6222 	/* Get size of backing device */
6223 	if (ldi_get_size(vd->ldi_handle[0], &vd->vdisk_size) != DDI_SUCCESS) {
6224 		PRN("ldi_get_size() failed for %s", device_path);
6225 		return (EIO);
6226 	}
6227 	vd->vdisk_size = lbtodb(vd->vdisk_size);	/* convert to blocks */
6228 	vd->block_size = DEV_BSIZE;
6229 	vd->vdisk_block_size = DEV_BSIZE;
6230 	vd->vdisk_media = VD_MEDIA_FIXED;
6231 
6232 	if (vd->volume) {
6233 		ASSERT(vd->vdisk_type == VD_DISK_TYPE_SLICE);
6234 	}
6235 
6236 	/*
6237 	 * We export the slice as a single slice disk even if the "slice"
6238 	 * option was not specified.
6239 	 */
6240 	vd->vdisk_type  = VD_DISK_TYPE_SLICE;
6241 	vd->nslices	= 1;
6242 
6243 	/*
6244 	 * When exporting a slice or a device as a single slice disk, we don't
6245 	 * care about any partitioning exposed by the backend. The goal is just
6246 	 * to export the backend as a flat storage. We provide a fake partition
6247 	 * table (either a VTOC or EFI), which presents only one slice, to
6248 	 * accommodate tools expecting a disk label. The selection of the label
6249 	 * type (VTOC or EFI) depends on the value of the vd_slice_label
6250 	 * variable.
6251 	 */
6252 	if (vd_slice_label == VD_DISK_LABEL_EFI ||
6253 	    vd->vdisk_size >= ONE_TERABYTE / DEV_BSIZE) {
6254 		vd->vdisk_label = VD_DISK_LABEL_EFI;
6255 	} else {
6256 		status = ldi_ioctl(vd->ldi_handle[0], DKIOCGEXTVTOC,
6257 		    (intptr_t)&vd->vtoc, (vd->open_flags | FKIOCTL),
6258 		    kcred, &rval);
6259 
6260 		if (status == ENOTTY) {
6261 			/* try with the non-extended vtoc ioctl */
6262 			status = ldi_ioctl(vd->ldi_handle[0], DKIOCGVTOC,
6263 			    (intptr_t)&vtoc, (vd->open_flags | FKIOCTL),
6264 			    kcred, &rval);
6265 			vtoctoextvtoc(vtoc, vd->vtoc);
6266 		}
6267 
6268 		if (status == 0) {
6269 			status = ldi_ioctl(vd->ldi_handle[0], DKIOCGGEOM,
6270 			    (intptr_t)&vd->dk_geom, (vd->open_flags | FKIOCTL),
6271 			    kcred, &rval);
6272 
6273 			if (status != 0) {
6274 				PRN("ldi_ioctl(DKIOCGEOM) returned errno %d "
6275 				    "for %s", status, device_path);
6276 				return (status);
6277 			}
6278 			vd->vdisk_label = VD_DISK_LABEL_VTOC;
6279 
6280 		} else if (vd_slice_label == VD_DISK_LABEL_VTOC) {
6281 
6282 			vd->vdisk_label = VD_DISK_LABEL_VTOC;
6283 			vd_build_default_label(vd->vdisk_size * DEV_BSIZE,
6284 			    &label);
6285 			vd_label_to_vtocgeom(&label, &vd->vtoc, &vd->dk_geom);
6286 
6287 		} else {
6288 			vd->vdisk_label = VD_DISK_LABEL_EFI;
6289 		}
6290 	}
6291 
6292 	if (vd->vdisk_label == VD_DISK_LABEL_VTOC) {
6293 		/* export with a fake VTOC label */
6294 		status = vd_setup_partition_vtoc(vd);
6295 
6296 	} else {
6297 		/* export with a fake EFI label */
6298 		status = vd_setup_partition_efi(vd);
6299 	}
6300 
6301 	return (status);
6302 }
6303 
6304 static int
6305 vd_backend_check_size(vd_t *vd)
6306 {
6307 	size_t backend_size, old_size, new_size;
6308 	struct dk_minfo minfo;
6309 	vattr_t vattr;
6310 	int rval, rv;
6311 
6312 	if (vd->file) {
6313 
6314 		/* file (slice or full disk) */
6315 		vattr.va_mask = AT_SIZE;
6316 		rv = VOP_GETATTR(vd->file_vnode, &vattr, 0, kcred, NULL);
6317 		if (rv != 0) {
6318 			PR0("VOP_GETATTR(%s) = errno %d", vd->device_path, rv);
6319 			return (rv);
6320 		}
6321 		backend_size = vattr.va_size;
6322 
6323 	} else if (vd->volume || vd->vdisk_type == VD_DISK_TYPE_SLICE) {
6324 
6325 		/* physical slice or volume (slice or full disk) */
6326 		rv = ldi_get_size(vd->ldi_handle[0], &backend_size);
6327 		if (rv != DDI_SUCCESS) {
6328 			PR0("ldi_get_size() failed for %s", vd->device_path);
6329 			return (EIO);
6330 		}
6331 
6332 	} else {
6333 
6334 		/* physical disk */
6335 		ASSERT(vd->vdisk_type == VD_DISK_TYPE_DISK);
6336 		rv = ldi_ioctl(vd->ldi_handle[0], DKIOCGMEDIAINFO,
6337 		    (intptr_t)&minfo, (vd->open_flags | FKIOCTL),
6338 		    kcred, &rval);
6339 		if (rv != 0) {
6340 			PR0("DKIOCGMEDIAINFO failed for %s (err=%d)",
6341 			    vd->device_path, rv);
6342 			return (rv);
6343 		}
6344 		backend_size = minfo.dki_capacity * minfo.dki_lbsize;
6345 	}
6346 
6347 	old_size = vd->vdisk_size;
6348 	new_size = backend_size / DEV_BSIZE;
6349 
6350 	/* check if size has changed */
6351 	if (old_size != VD_SIZE_UNKNOWN && old_size == new_size)
6352 		return (0);
6353 
6354 	vd->vdisk_size = new_size;
6355 
6356 	if (vd->file || vd->volume)
6357 		vd->dskimg_size = backend_size;
6358 
6359 	/*
6360 	 * If we are exporting a single-slice disk and the size of the backend
6361 	 * has changed then we regenerate the partition setup so that the
6362 	 * partitioning matches with the new disk backend size.
6363 	 */
6364 
6365 	if (vd->vdisk_type == VD_DISK_TYPE_SLICE) {
6366 		/* slice or file or device exported as a slice */
6367 		if (vd->vdisk_label == VD_DISK_LABEL_VTOC) {
6368 			rv = vd_setup_partition_vtoc(vd);
6369 			if (rv != 0) {
6370 				PR0("vd_setup_partition_vtoc() failed for %s "
6371 				    "(err = %d)", vd->device_path, rv);
6372 				return (rv);
6373 			}
6374 		} else {
6375 			rv = vd_setup_partition_efi(vd);
6376 			if (rv != 0) {
6377 				PR0("vd_setup_partition_efi() failed for %s "
6378 				    "(err = %d)", vd->device_path, rv);
6379 				return (rv);
6380 			}
6381 		}
6382 
6383 	} else if (!vd->file && !vd->volume) {
6384 		/* physical disk */
6385 		ASSERT(vd->vdisk_type == VD_DISK_TYPE_DISK);
6386 		vd->block_size = minfo.dki_lbsize;
6387 		vd->vdisk_media =
6388 		    DK_MEDIATYPE2VD_MEDIATYPE(minfo.dki_media_type);
6389 	}
6390 
6391 	return (0);
6392 }
6393 
6394 /*
6395  * Description:
6396  *	Open a device using its device path and identify if this is
6397  *	a disk device or a volume device.
6398  *
6399  * Parameters:
6400  *	vd 	- pointer to structure containing the vDisk info
6401  *	dtype	- return the driver type of the device
6402  *
6403  * Return Value
6404  *	0	- success
6405  *	!= 0	- some other non-zero return value from ldi(9F) functions
6406  */
6407 static int
6408 vd_identify_dev(vd_t *vd, int *dtype)
6409 {
6410 	int status, i;
6411 	char *device_path = vd->device_path;
6412 	char *drv_name;
6413 	int drv_type;
6414 	vds_t *vds = vd->vds;
6415 
6416 	status = vd_open_using_ldi_by_name(vd, vd->open_flags & ~FWRITE);
6417 	if (status != 0) {
6418 		PR0("Failed to open (%s) = errno %d", device_path, status);
6419 		return (status);
6420 	}
6421 
6422 	/* Get device number of backing device */
6423 	if ((status = ldi_get_dev(vd->ldi_handle[0], &vd->dev[0])) != 0) {
6424 		PRN("ldi_get_dev() returned errno %d for %s",
6425 		    status, device_path);
6426 		return (status);
6427 	}
6428 
6429 	/*
6430 	 * We start by looking if the driver is in the list from vds.conf
6431 	 * so that we can override the built-in list using vds.conf.
6432 	 */
6433 	drv_name = ddi_major_to_name(getmajor(vd->dev[0]));
6434 	drv_type = VD_DRIVER_UNKNOWN;
6435 
6436 	/* check vds.conf list */
6437 	for (i = 0; i < vds->num_drivers; i++) {
6438 		if (vds->driver_types[i].type == VD_DRIVER_UNKNOWN) {
6439 			/* ignore invalid entries */
6440 			continue;
6441 		}
6442 		if (strcmp(drv_name, vds->driver_types[i].name) == 0) {
6443 			drv_type = vds->driver_types[i].type;
6444 			goto done;
6445 		}
6446 	}
6447 
6448 	/* check built-in list */
6449 	for (i = 0; i < VDS_NUM_DRIVERS; i++) {
6450 		if (strcmp(drv_name, vds_driver_types[i].name) == 0) {
6451 			drv_type = vds_driver_types[i].type;
6452 			goto done;
6453 		}
6454 	}
6455 
6456 done:
6457 	PR0("driver %s identified as %s", drv_name,
6458 	    (drv_type == VD_DRIVER_DISK)? "DISK" :
6459 	    (drv_type == VD_DRIVER_VOLUME)? "VOLUME" : "UNKNOWN");
6460 
6461 	if (strcmp(drv_name, "zfs") == 0)
6462 		vd->zvol = B_TRUE;
6463 
6464 	*dtype = drv_type;
6465 
6466 	return (0);
6467 }
6468 
6469 static int
6470 vd_setup_vd(vd_t *vd)
6471 {
6472 	int		status, drv_type, pseudo;
6473 	dev_info_t	*dip;
6474 	vnode_t 	*vnp;
6475 	char		*path = vd->device_path;
6476 	char		tq_name[TASKQ_NAMELEN];
6477 
6478 	/* make sure the vdisk backend is valid */
6479 	if ((status = lookupname(path, UIO_SYSSPACE,
6480 	    FOLLOW, NULLVPP, &vnp)) != 0) {
6481 		PR0("Cannot lookup %s errno %d", path, status);
6482 		goto done;
6483 	}
6484 
6485 	switch (vnp->v_type) {
6486 	case VREG:
6487 		/*
6488 		 * Backend is a file so it is exported as a full disk or as a
6489 		 * single slice disk using the vnode interface.
6490 		 */
6491 		VN_RELE(vnp);
6492 		vd->volume = B_FALSE;
6493 		status = vd_setup_backend_vnode(vd);
6494 		break;
6495 
6496 	case VBLK:
6497 	case VCHR:
6498 		/*
6499 		 * Backend is a device. In that case, it is exported using the
6500 		 * LDI interface, and it is exported either as a single-slice
6501 		 * disk or as a full disk depending on the "slice" option and
6502 		 * on the type of device.
6503 		 *
6504 		 * - A volume device is exported as a single-slice disk if the
6505 		 *   "slice" is specified, otherwise it is exported as a full
6506 		 *   disk.
6507 		 *
6508 		 * - A disk slice (different from slice 2) is always exported
6509 		 *   as a single slice disk using the LDI interface.
6510 		 *
6511 		 * - The slice 2 of a disk is exported as a single slice disk
6512 		 *   if the "slice" option is specified, otherwise the entire
6513 		 *   disk will be exported.
6514 		 *
6515 		 * - The slice of a CD or DVD is exported as single slice disk
6516 		 *   if the "slice" option is specified, otherwise the entire
6517 		 *   disk will be exported.
6518 		 */
6519 
6520 		/* check if this is a pseudo device */
6521 		if ((dip = ddi_hold_devi_by_instance(getmajor(vnp->v_rdev),
6522 		    dev_to_instance(vnp->v_rdev), 0))  == NULL) {
6523 			PRN("%s is no longer accessible", path);
6524 			VN_RELE(vnp);
6525 			status = EIO;
6526 			break;
6527 		}
6528 		pseudo = is_pseudo_device(dip);
6529 		ddi_release_devi(dip);
6530 		VN_RELE(vnp);
6531 
6532 		if (vd_identify_dev(vd, &drv_type) != 0) {
6533 			PRN("%s identification failed", path);
6534 			status = EIO;
6535 			break;
6536 		}
6537 
6538 		/*
6539 		 * If the driver hasn't been identified then we consider that
6540 		 * pseudo devices are volumes and other devices are disks.
6541 		 */
6542 		if (drv_type == VD_DRIVER_VOLUME ||
6543 		    (drv_type == VD_DRIVER_UNKNOWN && pseudo)) {
6544 			vd->volume = B_TRUE;
6545 		}
6546 
6547 		/*
6548 		 * If this is a volume device then its usage depends if the
6549 		 * "slice" option is set or not. If the "slice" option is set
6550 		 * then the volume device will be exported as a single slice,
6551 		 * otherwise it will be exported as a full disk.
6552 		 *
6553 		 * For backward compatibility, if vd_volume_force_slice is set
6554 		 * then we always export volume devices as slices.
6555 		 */
6556 		if (vd->volume && vd_volume_force_slice) {
6557 			vd->vdisk_type = VD_DISK_TYPE_SLICE;
6558 			vd->nslices = 1;
6559 		}
6560 
6561 		status = vd_setup_backend_ldi(vd);
6562 		break;
6563 
6564 	default:
6565 		PRN("Unsupported vdisk backend %s", path);
6566 		VN_RELE(vnp);
6567 		status = EBADF;
6568 	}
6569 
6570 done:
6571 	if (status != 0) {
6572 		/*
6573 		 * If the error is retryable print an error message only
6574 		 * during the first try.
6575 		 */
6576 		if (status == ENXIO || status == ENODEV ||
6577 		    status == ENOENT || status == EROFS) {
6578 			if (!(vd->initialized & VD_SETUP_ERROR)) {
6579 				PRN("%s is currently inaccessible (error %d)",
6580 				    path, status);
6581 			}
6582 			status = EAGAIN;
6583 		} else {
6584 			PRN("%s can not be exported as a virtual disk "
6585 			    "(error %d)", path, status);
6586 		}
6587 		vd->initialized |= VD_SETUP_ERROR;
6588 
6589 	} else if (vd->initialized & VD_SETUP_ERROR) {
6590 		/* print a message only if we previously had an error */
6591 		PRN("%s is now online", path);
6592 		vd->initialized &= ~VD_SETUP_ERROR;
6593 	}
6594 
6595 	/*
6596 	 * For file or ZFS volume we also need an I/O queue.
6597 	 *
6598 	 * The I/O task queue is initialized here and not in vds_do_init_vd()
6599 	 * (as the start and completion queues) because vd_setup_vd() will be
6600 	 * call again if the backend is not available, and we need to know if
6601 	 * the backend is a ZFS volume or a file.
6602 	 */
6603 	if ((vd->file || vd->zvol) && vd->ioq == NULL) {
6604 		(void) snprintf(tq_name, sizeof (tq_name), "vd_ioq%lu", vd->id);
6605 
6606 		if ((vd->ioq = ddi_taskq_create(vd->vds->dip, tq_name,
6607 		    vd_ioq_nthreads, TASKQ_DEFAULTPRI, 0)) == NULL) {
6608 			PRN("Could not create io task queue");
6609 			return (EIO);
6610 		}
6611 	}
6612 
6613 	return (status);
6614 }
6615 
6616 static int
6617 vds_do_init_vd(vds_t *vds, uint64_t id, char *device_path, uint64_t options,
6618     uint64_t ldc_id, vd_t **vdp)
6619 {
6620 	char			tq_name[TASKQ_NAMELEN];
6621 	int			status;
6622 	ddi_iblock_cookie_t	iblock = NULL;
6623 	ldc_attr_t		ldc_attr;
6624 	vd_t			*vd;
6625 
6626 
6627 	ASSERT(vds != NULL);
6628 	ASSERT(device_path != NULL);
6629 	ASSERT(vdp != NULL);
6630 	PR0("Adding vdisk for %s", device_path);
6631 
6632 	if ((vd = kmem_zalloc(sizeof (*vd), KM_NOSLEEP)) == NULL) {
6633 		PRN("No memory for virtual disk");
6634 		return (EAGAIN);
6635 	}
6636 	*vdp = vd;	/* assign here so vds_destroy_vd() can cleanup later */
6637 	vd->id = id;
6638 	vd->vds = vds;
6639 	(void) strncpy(vd->device_path, device_path, MAXPATHLEN);
6640 
6641 	/* Setup open flags */
6642 	vd->open_flags = FREAD;
6643 
6644 	if (!(options & VD_OPT_RDONLY))
6645 		vd->open_flags |= FWRITE;
6646 
6647 	if (options & VD_OPT_EXCLUSIVE)
6648 		vd->open_flags |= FEXCL;
6649 
6650 	/* Setup disk type */
6651 	if (options & VD_OPT_SLICE) {
6652 		vd->vdisk_type = VD_DISK_TYPE_SLICE;
6653 		vd->nslices = 1;
6654 	} else {
6655 		vd->vdisk_type = VD_DISK_TYPE_DISK;
6656 		vd->nslices = V_NUMPAR;
6657 	}
6658 
6659 	/* default disk label */
6660 	vd->vdisk_label = VD_DISK_LABEL_UNK;
6661 
6662 	/* Open vdisk and initialize parameters */
6663 	if ((status = vd_setup_vd(vd)) == 0) {
6664 		vd->initialized |= VD_DISK_READY;
6665 
6666 		ASSERT(vd->nslices > 0 && vd->nslices <= V_NUMPAR);
6667 		PR0("vdisk_type = %s, volume = %s, file = %s, nslices = %u",
6668 		    ((vd->vdisk_type == VD_DISK_TYPE_DISK) ? "disk" : "slice"),
6669 		    (vd->volume ? "yes" : "no"), (vd->file ? "yes" : "no"),
6670 		    vd->nslices);
6671 	} else {
6672 		if (status != EAGAIN)
6673 			return (status);
6674 	}
6675 
6676 	/* Initialize locking */
6677 	if (ddi_get_soft_iblock_cookie(vds->dip, DDI_SOFTINT_MED,
6678 	    &iblock) != DDI_SUCCESS) {
6679 		PRN("Could not get iblock cookie.");
6680 		return (EIO);
6681 	}
6682 
6683 	mutex_init(&vd->lock, NULL, MUTEX_DRIVER, iblock);
6684 	vd->initialized |= VD_LOCKING;
6685 
6686 
6687 	/* Create start and completion task queues for the vdisk */
6688 	(void) snprintf(tq_name, sizeof (tq_name), "vd_startq%lu", id);
6689 	PR1("tq_name = %s", tq_name);
6690 	if ((vd->startq = ddi_taskq_create(vds->dip, tq_name, 1,
6691 	    TASKQ_DEFAULTPRI, 0)) == NULL) {
6692 		PRN("Could not create task queue");
6693 		return (EIO);
6694 	}
6695 	(void) snprintf(tq_name, sizeof (tq_name), "vd_completionq%lu", id);
6696 	PR1("tq_name = %s", tq_name);
6697 	if ((vd->completionq = ddi_taskq_create(vds->dip, tq_name, 1,
6698 	    TASKQ_DEFAULTPRI, 0)) == NULL) {
6699 		PRN("Could not create task queue");
6700 		return (EIO);
6701 	}
6702 
6703 	/* Allocate the staging buffer */
6704 	vd->max_msglen = sizeof (vio_msg_t);	/* baseline vio message size */
6705 	vd->vio_msgp = kmem_alloc(vd->max_msglen, KM_SLEEP);
6706 
6707 	vd->enabled = 1;	/* before callback can dispatch to startq */
6708 
6709 
6710 	/* Bring up LDC */
6711 	ldc_attr.devclass	= LDC_DEV_BLK_SVC;
6712 	ldc_attr.instance	= ddi_get_instance(vds->dip);
6713 	ldc_attr.mode		= LDC_MODE_UNRELIABLE;
6714 	ldc_attr.mtu		= VD_LDC_MTU;
6715 	if ((status = ldc_init(ldc_id, &ldc_attr, &vd->ldc_handle)) != 0) {
6716 		PRN("Could not initialize LDC channel %lx, "
6717 		    "init failed with error %d", ldc_id, status);
6718 		return (status);
6719 	}
6720 	vd->initialized |= VD_LDC;
6721 
6722 	if ((status = ldc_reg_callback(vd->ldc_handle, vd_handle_ldc_events,
6723 	    (caddr_t)vd)) != 0) {
6724 		PRN("Could not initialize LDC channel %lu,"
6725 		    "reg_callback failed with error %d", ldc_id, status);
6726 		return (status);
6727 	}
6728 
6729 	if ((status = ldc_open(vd->ldc_handle)) != 0) {
6730 		PRN("Could not initialize LDC channel %lu,"
6731 		    "open failed with error %d", ldc_id, status);
6732 		return (status);
6733 	}
6734 
6735 	if ((status = ldc_up(vd->ldc_handle)) != 0) {
6736 		PR0("ldc_up() returned errno %d", status);
6737 	}
6738 
6739 	/* Allocate the inband task memory handle */
6740 	status = ldc_mem_alloc_handle(vd->ldc_handle, &(vd->inband_task.mhdl));
6741 	if (status) {
6742 		PRN("Could not initialize LDC channel %lu,"
6743 		    "alloc_handle failed with error %d", ldc_id, status);
6744 		return (ENXIO);
6745 	}
6746 
6747 	/* Add the successfully-initialized vdisk to the server's table */
6748 	if (mod_hash_insert(vds->vd_table, (mod_hash_key_t)id, vd) != 0) {
6749 		PRN("Error adding vdisk ID %lu to table", id);
6750 		return (EIO);
6751 	}
6752 
6753 	/* store initial state */
6754 	vd->state = VD_STATE_INIT;
6755 
6756 	return (0);
6757 }
6758 
6759 static void
6760 vd_free_dring_task(vd_t *vdp)
6761 {
6762 	if (vdp->dring_task != NULL) {
6763 		ASSERT(vdp->dring_len != 0);
6764 		/* Free all dring_task memory handles */
6765 		for (int i = 0; i < vdp->dring_len; i++) {
6766 			(void) ldc_mem_free_handle(vdp->dring_task[i].mhdl);
6767 			kmem_free(vdp->dring_task[i].request,
6768 			    (vdp->descriptor_size -
6769 			    sizeof (vio_dring_entry_hdr_t)));
6770 			vdp->dring_task[i].request = NULL;
6771 			kmem_free(vdp->dring_task[i].msg, vdp->max_msglen);
6772 			vdp->dring_task[i].msg = NULL;
6773 		}
6774 		kmem_free(vdp->dring_task,
6775 		    (sizeof (*vdp->dring_task)) * vdp->dring_len);
6776 		vdp->dring_task = NULL;
6777 	}
6778 
6779 	if (vdp->write_queue != NULL) {
6780 		kmem_free(vdp->write_queue, sizeof (buf_t *) * vdp->dring_len);
6781 		vdp->write_queue = NULL;
6782 	}
6783 }
6784 
6785 /*
6786  * Destroy the state associated with a virtual disk
6787  */
6788 static void
6789 vds_destroy_vd(void *arg)
6790 {
6791 	vd_t	*vd = (vd_t *)arg;
6792 	int	retry = 0, rv;
6793 
6794 	if (vd == NULL)
6795 		return;
6796 
6797 	PR0("Destroying vdisk state");
6798 
6799 	/* Disable queuing requests for the vdisk */
6800 	if (vd->initialized & VD_LOCKING) {
6801 		mutex_enter(&vd->lock);
6802 		vd->enabled = 0;
6803 		mutex_exit(&vd->lock);
6804 	}
6805 
6806 	/* Drain and destroy start queue (*before* destroying ioq) */
6807 	if (vd->startq != NULL)
6808 		ddi_taskq_destroy(vd->startq);	/* waits for queued tasks */
6809 
6810 	/* Drain and destroy the I/O queue (*before* destroying completionq) */
6811 	if (vd->ioq != NULL)
6812 		ddi_taskq_destroy(vd->ioq);
6813 
6814 	/* Drain and destroy completion queue (*before* shutting down LDC) */
6815 	if (vd->completionq != NULL)
6816 		ddi_taskq_destroy(vd->completionq);	/* waits for tasks */
6817 
6818 	vd_free_dring_task(vd);
6819 
6820 	/* Free the inband task memory handle */
6821 	(void) ldc_mem_free_handle(vd->inband_task.mhdl);
6822 
6823 	/* Shut down LDC */
6824 	if (vd->initialized & VD_LDC) {
6825 		/* unmap the dring */
6826 		if (vd->initialized & VD_DRING)
6827 			(void) ldc_mem_dring_unmap(vd->dring_handle);
6828 
6829 		/* close LDC channel - retry on EAGAIN */
6830 		while ((rv = ldc_close(vd->ldc_handle)) == EAGAIN) {
6831 			if (++retry > vds_ldc_retries) {
6832 				PR0("Timed out closing channel");
6833 				break;
6834 			}
6835 			drv_usecwait(vds_ldc_delay);
6836 		}
6837 		if (rv == 0) {
6838 			(void) ldc_unreg_callback(vd->ldc_handle);
6839 			(void) ldc_fini(vd->ldc_handle);
6840 		} else {
6841 			/*
6842 			 * Closing the LDC channel has failed. Ideally we should
6843 			 * fail here but there is no Zeus level infrastructure
6844 			 * to handle this. The MD has already been changed and
6845 			 * we have to do the close. So we try to do as much
6846 			 * clean up as we can.
6847 			 */
6848 			(void) ldc_set_cb_mode(vd->ldc_handle, LDC_CB_DISABLE);
6849 			while (ldc_unreg_callback(vd->ldc_handle) == EAGAIN)
6850 				drv_usecwait(vds_ldc_delay);
6851 		}
6852 	}
6853 
6854 	/* Free the staging buffer for msgs */
6855 	if (vd->vio_msgp != NULL) {
6856 		kmem_free(vd->vio_msgp, vd->max_msglen);
6857 		vd->vio_msgp = NULL;
6858 	}
6859 
6860 	/* Free the inband message buffer */
6861 	if (vd->inband_task.msg != NULL) {
6862 		kmem_free(vd->inband_task.msg, vd->max_msglen);
6863 		vd->inband_task.msg = NULL;
6864 	}
6865 
6866 	if (vd->file) {
6867 		/* Close file */
6868 		(void) VOP_CLOSE(vd->file_vnode, vd->open_flags, 1,
6869 		    0, kcred, NULL);
6870 		VN_RELE(vd->file_vnode);
6871 	} else {
6872 		/* Close any open backing-device slices */
6873 		for (uint_t slice = 0; slice < V_NUMPAR; slice++) {
6874 			if (vd->ldi_handle[slice] != NULL) {
6875 				PR0("Closing slice %u", slice);
6876 				(void) ldi_close(vd->ldi_handle[slice],
6877 				    vd->open_flags, kcred);
6878 			}
6879 		}
6880 	}
6881 
6882 	/* Free disk image devid */
6883 	if (vd->dskimg_devid != NULL)
6884 		ddi_devid_free(vd->dskimg_devid);
6885 
6886 	/* Free any fake label */
6887 	if (vd->flabel) {
6888 		kmem_free(vd->flabel, vd->flabel_size);
6889 		vd->flabel = NULL;
6890 		vd->flabel_size = 0;
6891 	}
6892 
6893 	/* Free lock */
6894 	if (vd->initialized & VD_LOCKING)
6895 		mutex_destroy(&vd->lock);
6896 
6897 	/* Finally, free the vdisk structure itself */
6898 	kmem_free(vd, sizeof (*vd));
6899 }
6900 
6901 static int
6902 vds_init_vd(vds_t *vds, uint64_t id, char *device_path, uint64_t options,
6903     uint64_t ldc_id)
6904 {
6905 	int	status;
6906 	vd_t	*vd = NULL;
6907 
6908 
6909 	if ((status = vds_do_init_vd(vds, id, device_path, options,
6910 	    ldc_id, &vd)) != 0)
6911 		vds_destroy_vd(vd);
6912 
6913 	return (status);
6914 }
6915 
6916 static int
6917 vds_do_get_ldc_id(md_t *md, mde_cookie_t vd_node, mde_cookie_t *channel,
6918     uint64_t *ldc_id)
6919 {
6920 	int	num_channels;
6921 
6922 
6923 	/* Look for channel endpoint child(ren) of the vdisk MD node */
6924 	if ((num_channels = md_scan_dag(md, vd_node,
6925 	    md_find_name(md, VD_CHANNEL_ENDPOINT),
6926 	    md_find_name(md, "fwd"), channel)) <= 0) {
6927 		PRN("No \"%s\" found for virtual disk", VD_CHANNEL_ENDPOINT);
6928 		return (-1);
6929 	}
6930 
6931 	/* Get the "id" value for the first channel endpoint node */
6932 	if (md_get_prop_val(md, channel[0], VD_ID_PROP, ldc_id) != 0) {
6933 		PRN("No \"%s\" property found for \"%s\" of vdisk",
6934 		    VD_ID_PROP, VD_CHANNEL_ENDPOINT);
6935 		return (-1);
6936 	}
6937 
6938 	if (num_channels > 1) {
6939 		PRN("Using ID of first of multiple channels for this vdisk");
6940 	}
6941 
6942 	return (0);
6943 }
6944 
6945 static int
6946 vds_get_ldc_id(md_t *md, mde_cookie_t vd_node, uint64_t *ldc_id)
6947 {
6948 	int		num_nodes, status;
6949 	size_t		size;
6950 	mde_cookie_t	*channel;
6951 
6952 
6953 	if ((num_nodes = md_node_count(md)) <= 0) {
6954 		PRN("Invalid node count in Machine Description subtree");
6955 		return (-1);
6956 	}
6957 	size = num_nodes*(sizeof (*channel));
6958 	channel = kmem_zalloc(size, KM_SLEEP);
6959 	status = vds_do_get_ldc_id(md, vd_node, channel, ldc_id);
6960 	kmem_free(channel, size);
6961 
6962 	return (status);
6963 }
6964 
6965 /*
6966  * Function:
6967  *	vds_get_options
6968  *
6969  * Description:
6970  * 	Parse the options of a vds node. Options are defined as an array
6971  *	of strings in the vds-block-device-opts property of the vds node
6972  *	in the machine description. Options are returned as a bitmask. The
6973  *	mapping between the bitmask options and the options strings from the
6974  *	machine description is defined in the vd_bdev_options[] array.
6975  *
6976  *	The vds-block-device-opts property is optional. If a vds has no such
6977  *	property then no option is defined.
6978  *
6979  * Parameters:
6980  *	md		- machine description.
6981  *	vd_node		- vds node in the machine description for which
6982  *			  options have to be parsed.
6983  *	options		- the returned options.
6984  *
6985  * Return Code:
6986  *	none.
6987  */
6988 static void
6989 vds_get_options(md_t *md, mde_cookie_t vd_node, uint64_t *options)
6990 {
6991 	char	*optstr, *opt;
6992 	int	len, n, i;
6993 
6994 	*options = 0;
6995 
6996 	if (md_get_prop_data(md, vd_node, VD_BLOCK_DEVICE_OPTS,
6997 	    (uint8_t **)&optstr, &len) != 0) {
6998 		PR0("No options found");
6999 		return;
7000 	}
7001 
7002 	/* parse options */
7003 	opt = optstr;
7004 	n = sizeof (vd_bdev_options) / sizeof (vd_option_t);
7005 
7006 	while (opt < optstr + len) {
7007 		for (i = 0; i < n; i++) {
7008 			if (strncmp(vd_bdev_options[i].vdo_name,
7009 			    opt, VD_OPTION_NLEN) == 0) {
7010 				*options |= vd_bdev_options[i].vdo_value;
7011 				break;
7012 			}
7013 		}
7014 
7015 		if (i < n) {
7016 			PR0("option: %s", opt);
7017 		} else {
7018 			PRN("option %s is unknown or unsupported", opt);
7019 		}
7020 
7021 		opt += strlen(opt) + 1;
7022 	}
7023 }
7024 
7025 static void
7026 vds_driver_types_free(vds_t *vds)
7027 {
7028 	if (vds->driver_types != NULL) {
7029 		kmem_free(vds->driver_types, sizeof (vd_driver_type_t) *
7030 		    vds->num_drivers);
7031 		vds->driver_types = NULL;
7032 		vds->num_drivers = 0;
7033 	}
7034 }
7035 
7036 /*
7037  * Update the driver type list with information from vds.conf.
7038  */
7039 static void
7040 vds_driver_types_update(vds_t *vds)
7041 {
7042 	char **list, *s;
7043 	uint_t i, num, count = 0, len;
7044 
7045 	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, vds->dip,
7046 	    DDI_PROP_DONTPASS, "driver-type-list", &list, &num) !=
7047 	    DDI_PROP_SUCCESS)
7048 		return;
7049 
7050 	/*
7051 	 * We create a driver_types list with as many as entries as there
7052 	 * is in the driver-type-list from vds.conf. However only valid
7053 	 * entries will be populated (i.e. entries from driver-type-list
7054 	 * with a valid syntax). Invalid entries will be left blank so
7055 	 * they will have no driver name and the driver type will be
7056 	 * VD_DRIVER_UNKNOWN (= 0).
7057 	 */
7058 	vds->num_drivers = num;
7059 	vds->driver_types = kmem_zalloc(sizeof (vd_driver_type_t) * num,
7060 	    KM_SLEEP);
7061 
7062 	for (i = 0; i < num; i++) {
7063 
7064 		s = strchr(list[i], ':');
7065 
7066 		if (s == NULL) {
7067 			PRN("vds.conf: driver-type-list, entry %d (%s): "
7068 			    "a colon is expected in the entry",
7069 			    i, list[i]);
7070 			continue;
7071 		}
7072 
7073 		len = (uintptr_t)s - (uintptr_t)list[i];
7074 
7075 		if (len == 0) {
7076 			PRN("vds.conf: driver-type-list, entry %d (%s): "
7077 			    "the driver name is empty",
7078 			    i, list[i]);
7079 			continue;
7080 		}
7081 
7082 		if (len >= VD_DRIVER_NAME_LEN) {
7083 			PRN("vds.conf: driver-type-list, entry %d (%s): "
7084 			    "the driver name is too long",
7085 			    i, list[i]);
7086 			continue;
7087 		}
7088 
7089 		if (strcmp(s + 1, "disk") == 0) {
7090 
7091 			vds->driver_types[i].type = VD_DRIVER_DISK;
7092 
7093 		} else if (strcmp(s + 1, "volume") == 0) {
7094 
7095 			vds->driver_types[i].type = VD_DRIVER_VOLUME;
7096 
7097 		} else {
7098 			PRN("vds.conf: driver-type-list, entry %d (%s): "
7099 			    "the driver type is invalid",
7100 			    i, list[i]);
7101 			continue;
7102 		}
7103 
7104 		(void) strncpy(vds->driver_types[i].name, list[i], len);
7105 
7106 		PR0("driver-type-list, entry %d (%s) added",
7107 		    i, list[i]);
7108 
7109 		count++;
7110 	}
7111 
7112 	ddi_prop_free(list);
7113 
7114 	if (count == 0) {
7115 		/* nothing was added, clean up */
7116 		vds_driver_types_free(vds);
7117 	}
7118 }
7119 
7120 static void
7121 vds_add_vd(vds_t *vds, md_t *md, mde_cookie_t vd_node)
7122 {
7123 	char		*device_path = NULL;
7124 	uint64_t	id = 0, ldc_id = 0, options = 0;
7125 
7126 	if (md_get_prop_val(md, vd_node, VD_ID_PROP, &id) != 0) {
7127 		PRN("Error getting vdisk \"%s\"", VD_ID_PROP);
7128 		return;
7129 	}
7130 	PR0("Adding vdisk ID %lu", id);
7131 	if (md_get_prop_str(md, vd_node, VD_BLOCK_DEVICE_PROP,
7132 	    &device_path) != 0) {
7133 		PRN("Error getting vdisk \"%s\"", VD_BLOCK_DEVICE_PROP);
7134 		return;
7135 	}
7136 
7137 	vds_get_options(md, vd_node, &options);
7138 
7139 	if (vds_get_ldc_id(md, vd_node, &ldc_id) != 0) {
7140 		PRN("Error getting LDC ID for vdisk %lu", id);
7141 		return;
7142 	}
7143 
7144 	if (vds_init_vd(vds, id, device_path, options, ldc_id) != 0) {
7145 		PRN("Failed to add vdisk ID %lu", id);
7146 		if (mod_hash_destroy(vds->vd_table, (mod_hash_key_t)id) != 0)
7147 			PRN("No vDisk entry found for vdisk ID %lu", id);
7148 		return;
7149 	}
7150 }
7151 
7152 static void
7153 vds_remove_vd(vds_t *vds, md_t *md, mde_cookie_t vd_node)
7154 {
7155 	uint64_t	id = 0;
7156 
7157 
7158 	if (md_get_prop_val(md, vd_node, VD_ID_PROP, &id) != 0) {
7159 		PRN("Unable to get \"%s\" property from vdisk's MD node",
7160 		    VD_ID_PROP);
7161 		return;
7162 	}
7163 	PR0("Removing vdisk ID %lu", id);
7164 	if (mod_hash_destroy(vds->vd_table, (mod_hash_key_t)id) != 0)
7165 		PRN("No vdisk entry found for vdisk ID %lu", id);
7166 }
7167 
7168 static void
7169 vds_change_vd(vds_t *vds, md_t *prev_md, mde_cookie_t prev_vd_node,
7170     md_t *curr_md, mde_cookie_t curr_vd_node)
7171 {
7172 	char		*curr_dev, *prev_dev;
7173 	uint64_t	curr_id = 0, curr_ldc_id = 0, curr_options = 0;
7174 	uint64_t	prev_id = 0, prev_ldc_id = 0, prev_options = 0;
7175 	size_t		len;
7176 
7177 
7178 	/* Validate that vdisk ID has not changed */
7179 	if (md_get_prop_val(prev_md, prev_vd_node, VD_ID_PROP, &prev_id) != 0) {
7180 		PRN("Error getting previous vdisk \"%s\" property",
7181 		    VD_ID_PROP);
7182 		return;
7183 	}
7184 	if (md_get_prop_val(curr_md, curr_vd_node, VD_ID_PROP, &curr_id) != 0) {
7185 		PRN("Error getting current vdisk \"%s\" property", VD_ID_PROP);
7186 		return;
7187 	}
7188 	if (curr_id != prev_id) {
7189 		PRN("Not changing vdisk:  ID changed from %lu to %lu",
7190 		    prev_id, curr_id);
7191 		return;
7192 	}
7193 
7194 	/* Validate that LDC ID has not changed */
7195 	if (vds_get_ldc_id(prev_md, prev_vd_node, &prev_ldc_id) != 0) {
7196 		PRN("Error getting LDC ID for vdisk %lu", prev_id);
7197 		return;
7198 	}
7199 
7200 	if (vds_get_ldc_id(curr_md, curr_vd_node, &curr_ldc_id) != 0) {
7201 		PRN("Error getting LDC ID for vdisk %lu", curr_id);
7202 		return;
7203 	}
7204 	if (curr_ldc_id != prev_ldc_id) {
7205 		_NOTE(NOTREACHED);	/* lint is confused */
7206 		PRN("Not changing vdisk:  "
7207 		    "LDC ID changed from %lu to %lu", prev_ldc_id, curr_ldc_id);
7208 		return;
7209 	}
7210 
7211 	/* Determine whether device path has changed */
7212 	if (md_get_prop_str(prev_md, prev_vd_node, VD_BLOCK_DEVICE_PROP,
7213 	    &prev_dev) != 0) {
7214 		PRN("Error getting previous vdisk \"%s\"",
7215 		    VD_BLOCK_DEVICE_PROP);
7216 		return;
7217 	}
7218 	if (md_get_prop_str(curr_md, curr_vd_node, VD_BLOCK_DEVICE_PROP,
7219 	    &curr_dev) != 0) {
7220 		PRN("Error getting current vdisk \"%s\"", VD_BLOCK_DEVICE_PROP);
7221 		return;
7222 	}
7223 	if (((len = strlen(curr_dev)) == strlen(prev_dev)) &&
7224 	    (strncmp(curr_dev, prev_dev, len) == 0))
7225 		return;	/* no relevant (supported) change */
7226 
7227 	/* Validate that options have not changed */
7228 	vds_get_options(prev_md, prev_vd_node, &prev_options);
7229 	vds_get_options(curr_md, curr_vd_node, &curr_options);
7230 	if (prev_options != curr_options) {
7231 		PRN("Not changing vdisk:  options changed from %lx to %lx",
7232 		    prev_options, curr_options);
7233 		return;
7234 	}
7235 
7236 	PR0("Changing vdisk ID %lu", prev_id);
7237 
7238 	/* Remove old state, which will close vdisk and reset */
7239 	if (mod_hash_destroy(vds->vd_table, (mod_hash_key_t)prev_id) != 0)
7240 		PRN("No entry found for vdisk ID %lu", prev_id);
7241 
7242 	/* Re-initialize vdisk with new state */
7243 	if (vds_init_vd(vds, curr_id, curr_dev, curr_options,
7244 	    curr_ldc_id) != 0) {
7245 		PRN("Failed to change vdisk ID %lu", curr_id);
7246 		return;
7247 	}
7248 }
7249 
7250 static int
7251 vds_process_md(void *arg, mdeg_result_t *md)
7252 {
7253 	int	i;
7254 	vds_t	*vds = arg;
7255 
7256 
7257 	if (md == NULL)
7258 		return (MDEG_FAILURE);
7259 	ASSERT(vds != NULL);
7260 
7261 	for (i = 0; i < md->removed.nelem; i++)
7262 		vds_remove_vd(vds, md->removed.mdp, md->removed.mdep[i]);
7263 	for (i = 0; i < md->match_curr.nelem; i++)
7264 		vds_change_vd(vds, md->match_prev.mdp, md->match_prev.mdep[i],
7265 		    md->match_curr.mdp, md->match_curr.mdep[i]);
7266 	for (i = 0; i < md->added.nelem; i++)
7267 		vds_add_vd(vds, md->added.mdp, md->added.mdep[i]);
7268 
7269 	return (MDEG_SUCCESS);
7270 }
7271 
7272 
7273 static int
7274 vds_do_attach(dev_info_t *dip)
7275 {
7276 	int			status, sz;
7277 	int			cfg_handle;
7278 	minor_t			instance = ddi_get_instance(dip);
7279 	vds_t			*vds;
7280 	mdeg_prop_spec_t	*pspecp;
7281 	mdeg_node_spec_t	*ispecp;
7282 
7283 	/*
7284 	 * The "cfg-handle" property of a vds node in an MD contains the MD's
7285 	 * notion of "instance", or unique identifier, for that node; OBP
7286 	 * stores the value of the "cfg-handle" MD property as the value of
7287 	 * the "reg" property on the node in the device tree it builds from
7288 	 * the MD and passes to Solaris.  Thus, we look up the devinfo node's
7289 	 * "reg" property value to uniquely identify this device instance when
7290 	 * registering with the MD event-generation framework.  If the "reg"
7291 	 * property cannot be found, the device tree state is presumably so
7292 	 * broken that there is no point in continuing.
7293 	 */
7294 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
7295 	    VD_REG_PROP)) {
7296 		PRN("vds \"%s\" property does not exist", VD_REG_PROP);
7297 		return (DDI_FAILURE);
7298 	}
7299 
7300 	/* Get the MD instance for later MDEG registration */
7301 	cfg_handle = ddi_prop_get_int(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
7302 	    VD_REG_PROP, -1);
7303 
7304 	if (ddi_soft_state_zalloc(vds_state, instance) != DDI_SUCCESS) {
7305 		PRN("Could not allocate state for instance %u", instance);
7306 		return (DDI_FAILURE);
7307 	}
7308 
7309 	if ((vds = ddi_get_soft_state(vds_state, instance)) == NULL) {
7310 		PRN("Could not get state for instance %u", instance);
7311 		ddi_soft_state_free(vds_state, instance);
7312 		return (DDI_FAILURE);
7313 	}
7314 
7315 	vds->dip	= dip;
7316 	vds->vd_table	= mod_hash_create_ptrhash("vds_vd_table", VDS_NCHAINS,
7317 	    vds_destroy_vd, sizeof (void *));
7318 
7319 	ASSERT(vds->vd_table != NULL);
7320 
7321 	if ((status = ldi_ident_from_dip(dip, &vds->ldi_ident)) != 0) {
7322 		PRN("ldi_ident_from_dip() returned errno %d", status);
7323 		return (DDI_FAILURE);
7324 	}
7325 	vds->initialized |= VDS_LDI;
7326 
7327 	/* Register for MD updates */
7328 	sz = sizeof (vds_prop_template);
7329 	pspecp = kmem_alloc(sz, KM_SLEEP);
7330 	bcopy(vds_prop_template, pspecp, sz);
7331 
7332 	VDS_SET_MDEG_PROP_INST(pspecp, cfg_handle);
7333 
7334 	/* initialize the complete prop spec structure */
7335 	ispecp = kmem_zalloc(sizeof (mdeg_node_spec_t), KM_SLEEP);
7336 	ispecp->namep = "virtual-device";
7337 	ispecp->specp = pspecp;
7338 
7339 	if (mdeg_register(ispecp, &vd_match, vds_process_md, vds,
7340 	    &vds->mdeg) != MDEG_SUCCESS) {
7341 		PRN("Unable to register for MD updates");
7342 		kmem_free(ispecp, sizeof (mdeg_node_spec_t));
7343 		kmem_free(pspecp, sz);
7344 		return (DDI_FAILURE);
7345 	}
7346 
7347 	vds->ispecp = ispecp;
7348 	vds->initialized |= VDS_MDEG;
7349 
7350 	/* Prevent auto-detaching so driver is available whenever MD changes */
7351 	if (ddi_prop_update_int(DDI_DEV_T_NONE, dip, DDI_NO_AUTODETACH, 1) !=
7352 	    DDI_PROP_SUCCESS) {
7353 		PRN("failed to set \"%s\" property for instance %u",
7354 		    DDI_NO_AUTODETACH, instance);
7355 	}
7356 
7357 	/* read any user defined driver types from conf file and update list */
7358 	vds_driver_types_update(vds);
7359 
7360 	ddi_report_dev(dip);
7361 	return (DDI_SUCCESS);
7362 }
7363 
7364 static int
7365 vds_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
7366 {
7367 	int	status;
7368 
7369 	switch (cmd) {
7370 	case DDI_ATTACH:
7371 		PR0("Attaching");
7372 		if ((status = vds_do_attach(dip)) != DDI_SUCCESS)
7373 			(void) vds_detach(dip, DDI_DETACH);
7374 		return (status);
7375 	case DDI_RESUME:
7376 		PR0("No action required for DDI_RESUME");
7377 		return (DDI_SUCCESS);
7378 	default:
7379 		return (DDI_FAILURE);
7380 	}
7381 }
7382 
7383 static struct dev_ops vds_ops = {
7384 	DEVO_REV,	/* devo_rev */
7385 	0,		/* devo_refcnt */
7386 	ddi_no_info,	/* devo_getinfo */
7387 	nulldev,	/* devo_identify */
7388 	nulldev,	/* devo_probe */
7389 	vds_attach,	/* devo_attach */
7390 	vds_detach,	/* devo_detach */
7391 	nodev,		/* devo_reset */
7392 	NULL,		/* devo_cb_ops */
7393 	NULL,		/* devo_bus_ops */
7394 	nulldev,	/* devo_power */
7395 	ddi_quiesce_not_needed,	/* devo_quiesce */
7396 };
7397 
7398 static struct modldrv modldrv = {
7399 	&mod_driverops,
7400 	"virtual disk server",
7401 	&vds_ops,
7402 };
7403 
7404 static struct modlinkage modlinkage = {
7405 	MODREV_1,
7406 	&modldrv,
7407 	NULL
7408 };
7409 
7410 
7411 int
7412 _init(void)
7413 {
7414 	int		status;
7415 
7416 	if ((status = ddi_soft_state_init(&vds_state, sizeof (vds_t), 1)) != 0)
7417 		return (status);
7418 
7419 	if ((status = mod_install(&modlinkage)) != 0) {
7420 		ddi_soft_state_fini(&vds_state);
7421 		return (status);
7422 	}
7423 
7424 	return (0);
7425 }
7426 
7427 int
7428 _info(struct modinfo *modinfop)
7429 {
7430 	return (mod_info(&modlinkage, modinfop));
7431 }
7432 
7433 int
7434 _fini(void)
7435 {
7436 	int	status;
7437 
7438 	if ((status = mod_remove(&modlinkage)) != 0)
7439 		return (status);
7440 	ddi_soft_state_fini(&vds_state);
7441 	return (0);
7442 }
7443