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