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