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