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