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