xref: /titanic_41/usr/src/uts/sun4v/io/vds.c (revision 8ef4c21a581c38a44ac18b7363c4928cb3222303)
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 2006 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/mdeg.h>
41 #include <sys/modhash.h>
42 #include <sys/note.h>
43 #include <sys/pathname.h>
44 #include <sys/sunddi.h>
45 #include <sys/sunldi.h>
46 #include <sys/sysmacros.h>
47 #include <sys/vio_common.h>
48 #include <sys/vdsk_mailbox.h>
49 #include <sys/vdsk_common.h>
50 #include <sys/vtoc.h>
51 
52 
53 /* Virtual disk server initialization flags */
54 #define	VDS_LDI			0x01
55 #define	VDS_MDEG		0x02
56 
57 /* Virtual disk server tunable parameters */
58 #define	VDS_LDC_RETRIES		3
59 #define	VDS_NCHAINS		32
60 
61 /* Identification parameters for MD, synthetic dkio(7i) structures, etc. */
62 #define	VDS_NAME		"virtual-disk-server"
63 
64 #define	VD_NAME			"vd"
65 #define	VD_VOLUME_NAME		"vdisk"
66 #define	VD_ASCIILABEL		"Virtual Disk"
67 
68 #define	VD_CHANNEL_ENDPOINT	"channel-endpoint"
69 #define	VD_ID_PROP		"id"
70 #define	VD_BLOCK_DEVICE_PROP	"vds-block-device"
71 
72 /* Virtual disk initialization flags */
73 #define	VD_LOCKING		0x01
74 #define	VD_LDC			0x02
75 #define	VD_DRING		0x04
76 #define	VD_SID			0x08
77 #define	VD_SEQ_NUM		0x10
78 
79 /* Flags for opening/closing backing devices via LDI */
80 #define	VD_OPEN_FLAGS		(FEXCL | FREAD | FWRITE)
81 
82 /*
83  * By Solaris convention, slice/partition 2 represents the entire disk;
84  * unfortunately, this convention does not appear to be codified.
85  */
86 #define	VD_ENTIRE_DISK_SLICE	2
87 
88 /* Return a cpp token as a string */
89 #define	STRINGIZE(token)	#token
90 
91 /*
92  * Print a message prefixed with the current function name to the message log
93  * (and optionally to the console for verbose boots); these macros use cpp's
94  * concatenation of string literals and C99 variable-length-argument-list
95  * macros
96  */
97 #define	PRN(...)	_PRN("?%s():  "__VA_ARGS__, "")
98 #define	_PRN(format, ...)					\
99 	cmn_err(CE_CONT, format"%s", __func__, __VA_ARGS__)
100 
101 /* Return a pointer to the "i"th vdisk dring element */
102 #define	VD_DRING_ELEM(i)	((vd_dring_entry_t *)(void *)	\
103 	    (vd->dring + (i)*vd->descriptor_size))
104 
105 /* Return the virtual disk client's type as a string (for use in messages) */
106 #define	VD_CLIENT(vd)							\
107 	(((vd)->xfer_mode == VIO_DESC_MODE) ? "in-band client" :	\
108 	    (((vd)->xfer_mode == VIO_DRING_MODE) ? "dring client" :	\
109 		(((vd)->xfer_mode == 0) ? "null client" :		\
110 		    "unsupported client")))
111 
112 /* Debugging macros */
113 #ifdef DEBUG
114 #define	PR0 if (vd_msglevel > 0)	PRN
115 #define	PR1 if (vd_msglevel > 1)	PRN
116 #define	PR2 if (vd_msglevel > 2)	PRN
117 
118 #define	VD_DUMP_DRING_ELEM(elem)					\
119 	PRN("dst:%x op:%x st:%u nb:%lx addr:%lx ncook:%u\n",		\
120 	    elem->hdr.dstate,						\
121 	    elem->payload.operation,					\
122 	    elem->payload.status,					\
123 	    elem->payload.nbytes,					\
124 	    elem->payload.addr,						\
125 	    elem->payload.ncookies);
126 
127 #else	/* !DEBUG */
128 #define	PR0(...)
129 #define	PR1(...)
130 #define	PR2(...)
131 
132 #define	VD_DUMP_DRING_ELEM(elem)
133 
134 #endif	/* DEBUG */
135 
136 
137 /*
138  * Soft state structure for a vds instance
139  */
140 typedef struct vds {
141 	uint_t		initialized;	/* driver inst initialization flags */
142 	dev_info_t	*dip;		/* driver inst devinfo pointer */
143 	ldi_ident_t	ldi_ident;	/* driver's identifier for LDI */
144 	mod_hash_t	*vd_table;	/* table of virtual disks served */
145 	mdeg_handle_t	mdeg;		/* handle for MDEG operations  */
146 } vds_t;
147 
148 /*
149  * Types of descriptor-processing tasks
150  */
151 typedef enum vd_task_type {
152 	VD_NONFINAL_RANGE_TASK,	/* task for intermediate descriptor in range */
153 	VD_FINAL_RANGE_TASK,	/* task for last in a range of descriptors */
154 } vd_task_type_t;
155 
156 /*
157  * Structure describing the task for processing a descriptor
158  */
159 typedef struct vd_task {
160 	struct vd		*vd;		/* vd instance task is for */
161 	vd_task_type_t		type;		/* type of descriptor task */
162 	int			index;		/* dring elem index for task */
163 	vio_msg_t		*msg;		/* VIO message task is for */
164 	size_t			msglen;		/* length of message content */
165 	size_t			msgsize;	/* size of message buffer */
166 	vd_dring_payload_t	*request;	/* request task will perform */
167 	struct buf		buf;		/* buf(9s) for I/O request */
168 	ldc_mem_handle_t	mhdl;		/* task memory handle */
169 } vd_task_t;
170 
171 /*
172  * Soft state structure for a virtual disk instance
173  */
174 typedef struct vd {
175 	uint_t			initialized;	/* vdisk initialization flags */
176 	vds_t			*vds;		/* server for this vdisk */
177 	ddi_taskq_t		*startq;	/* queue for I/O start tasks */
178 	ddi_taskq_t		*completionq;	/* queue for completion tasks */
179 	ldi_handle_t		ldi_handle[V_NUMPAR];	/* LDI slice handles */
180 	dev_t			dev[V_NUMPAR];	/* dev numbers for slices */
181 	uint_t			nslices;	/* number of slices */
182 	size_t			vdisk_size;	/* number of blocks in vdisk */
183 	vd_disk_type_t		vdisk_type;	/* slice or entire disk */
184 	vd_disk_label_t		vdisk_label;	/* EFI or VTOC label */
185 	ushort_t		max_xfer_sz;	/* max xfer size in DEV_BSIZE */
186 	boolean_t		pseudo;		/* underlying pseudo dev */
187 	struct dk_efi		dk_efi;		/* synthetic for slice type */
188 	struct dk_geom		dk_geom;	/* synthetic for slice type */
189 	struct vtoc		vtoc;		/* synthetic for slice type */
190 	ldc_status_t		ldc_state;	/* LDC connection state */
191 	ldc_handle_t		ldc_handle;	/* handle for LDC comm */
192 	size_t			max_msglen;	/* largest LDC message len */
193 	vd_state_t		state;		/* client handshake state */
194 	uint8_t			xfer_mode;	/* transfer mode with client */
195 	uint32_t		sid;		/* client's session ID */
196 	uint64_t		seq_num;	/* message sequence number */
197 	uint64_t		dring_ident;	/* identifier of dring */
198 	ldc_dring_handle_t	dring_handle;	/* handle for dring ops */
199 	uint32_t		descriptor_size;	/* num bytes in desc */
200 	uint32_t		dring_len;	/* number of dring elements */
201 	caddr_t			dring;		/* address of dring */
202 	vd_task_t		inband_task;	/* task for inband descriptor */
203 	vd_task_t		*dring_task;	/* tasks dring elements */
204 
205 	kmutex_t		lock;		/* protects variables below */
206 	boolean_t		enabled;	/* is vdisk enabled? */
207 	boolean_t		reset_state;	/* reset connection state? */
208 	boolean_t		reset_ldc;	/* reset LDC channel? */
209 } vd_t;
210 
211 typedef struct vds_operation {
212 	uint8_t	operation;
213 	int	(*start)(vd_task_t *task);
214 	void	(*complete)(void *arg);
215 } vds_operation_t;
216 
217 typedef struct vd_ioctl {
218 	uint8_t		operation;		/* vdisk operation */
219 	const char	*operation_name;	/* vdisk operation name */
220 	size_t		nbytes;			/* size of operation buffer */
221 	int		cmd;			/* corresponding ioctl cmd */
222 	const char	*cmd_name;		/* ioctl cmd name */
223 	void		*arg;			/* ioctl cmd argument */
224 	/* convert input vd_buf to output ioctl_arg */
225 	void		(*copyin)(void *vd_buf, void *ioctl_arg);
226 	/* convert input ioctl_arg to output vd_buf */
227 	void		(*copyout)(void *ioctl_arg, void *vd_buf);
228 } vd_ioctl_t;
229 
230 /* Define trivial copyin/copyout conversion function flag */
231 #define	VD_IDENTITY	((void (*)(void *, void *))-1)
232 
233 
234 static int	vds_ldc_retries = VDS_LDC_RETRIES;
235 static void	*vds_state;
236 static uint64_t	vds_operations;	/* see vds_operation[] definition below */
237 
238 static int	vd_open_flags = VD_OPEN_FLAGS;
239 
240 /*
241  * Supported protocol version pairs, from highest (newest) to lowest (oldest)
242  *
243  * Each supported major version should appear only once, paired with (and only
244  * with) its highest supported minor version number (as the protocol requires
245  * supporting all lower minor version numbers as well)
246  */
247 static const vio_ver_t	vds_version[] = {{1, 0}};
248 static const size_t	vds_num_versions =
249     sizeof (vds_version)/sizeof (vds_version[0]);
250 
251 #ifdef DEBUG
252 static int	vd_msglevel;
253 #endif /* DEBUG */
254 
255 
256 static int
257 vd_start_bio(vd_task_t *task)
258 {
259 	int			rv, status = 0;
260 	vd_t			*vd		= task->vd;
261 	vd_dring_payload_t	*request	= task->request;
262 	struct buf		*buf		= &task->buf;
263 	uint8_t			mtype;
264 
265 
266 	ASSERT(vd != NULL);
267 	ASSERT(request != NULL);
268 	ASSERT(request->slice < vd->nslices);
269 	ASSERT((request->operation == VD_OP_BREAD) ||
270 	    (request->operation == VD_OP_BWRITE));
271 
272 	if (request->nbytes == 0)
273 		return (EINVAL);	/* no service for trivial requests */
274 
275 	PR1("%s %lu bytes at block %lu",
276 	    (request->operation == VD_OP_BREAD) ? "Read" : "Write",
277 	    request->nbytes, request->addr);
278 
279 	bioinit(buf);
280 	buf->b_flags		= B_BUSY;
281 	buf->b_bcount		= request->nbytes;
282 	buf->b_lblkno		= request->addr;
283 	buf->b_edev		= vd->dev[request->slice];
284 
285 	mtype = (&vd->inband_task == task) ? LDC_SHADOW_MAP : LDC_DIRECT_MAP;
286 
287 	/* Map memory exported by client */
288 	status = ldc_mem_map(task->mhdl, request->cookie, request->ncookies,
289 	    mtype, (request->operation == VD_OP_BREAD) ? LDC_MEM_W : LDC_MEM_R,
290 	    &(buf->b_un.b_addr), NULL);
291 	if (status != 0) {
292 		PRN("ldc_mem_map() returned err %d ", status);
293 		biofini(buf);
294 		return (status);
295 	}
296 
297 	status = ldc_mem_acquire(task->mhdl, 0, buf->b_bcount);
298 	if (status != 0) {
299 		(void) ldc_mem_unmap(task->mhdl);
300 		PRN("ldc_mem_map() returned err %d ", status);
301 		biofini(buf);
302 		return (status);
303 	}
304 
305 	buf->b_flags |= (request->operation == VD_OP_BREAD) ? B_READ : B_WRITE;
306 
307 	/* Start the block I/O */
308 	if ((status = ldi_strategy(vd->ldi_handle[request->slice], buf)) == 0)
309 		return (EINPROGRESS);	/* will complete on completionq */
310 
311 	/* Clean up after error */
312 	rv = ldc_mem_release(task->mhdl, 0, buf->b_bcount);
313 	if (rv) {
314 		PRN("ldc_mem_release() returned err %d ", status);
315 	}
316 	rv = ldc_mem_unmap(task->mhdl);
317 	if (rv) {
318 		PRN("ldc_mem_unmap() returned err %d ", status);
319 	}
320 
321 	biofini(buf);
322 	return (status);
323 }
324 
325 static int
326 send_msg(ldc_handle_t ldc_handle, void *msg, size_t msglen)
327 {
328 	int	retry, status;
329 	size_t	nbytes;
330 
331 
332 	for (retry = 0, status = EWOULDBLOCK;
333 	    retry < vds_ldc_retries && status == EWOULDBLOCK;
334 	    retry++) {
335 		PR1("ldc_write() attempt %d", (retry + 1));
336 		nbytes = msglen;
337 		status = ldc_write(ldc_handle, msg, &nbytes);
338 	}
339 
340 	if (status != 0) {
341 		PRN("ldc_write() returned errno %d", status);
342 		return (status);
343 	} else if (nbytes != msglen) {
344 		PRN("ldc_write() performed only partial write");
345 		return (EIO);
346 	}
347 
348 	PR1("SENT %lu bytes", msglen);
349 	return (0);
350 }
351 
352 static void
353 vd_need_reset(vd_t *vd, boolean_t reset_ldc)
354 {
355 	mutex_enter(&vd->lock);
356 	vd->reset_state	= B_TRUE;
357 	vd->reset_ldc	= reset_ldc;
358 	mutex_exit(&vd->lock);
359 }
360 
361 /*
362  * Reset the state of the connection with a client, if needed; reset the LDC
363  * transport as well, if needed.  This function should only be called from the
364  * "startq", as it waits for tasks on the "completionq" and will deadlock if
365  * called from that queue.
366  */
367 static void
368 vd_reset_if_needed(vd_t *vd)
369 {
370 	int		status = 0;
371 
372 
373 	mutex_enter(&vd->lock);
374 	if (!vd->reset_state) {
375 		ASSERT(!vd->reset_ldc);
376 		mutex_exit(&vd->lock);
377 		return;
378 	}
379 	mutex_exit(&vd->lock);
380 
381 
382 	PR0("Resetting connection state with %s", VD_CLIENT(vd));
383 
384 	/*
385 	 * Let any asynchronous I/O complete before possibly pulling the rug
386 	 * out from under it; defer checking vd->reset_ldc, as one of the
387 	 * asynchronous tasks might set it
388 	 */
389 	ddi_taskq_wait(vd->completionq);
390 
391 	if ((vd->initialized & VD_DRING) &&
392 	    ((status = ldc_mem_dring_unmap(vd->dring_handle)) != 0))
393 		PRN("ldc_mem_dring_unmap() returned errno %d", status);
394 
395 	if (vd->dring_task != NULL) {
396 		ASSERT(vd->dring_len != 0);
397 		/* Free all dring_task memory handles */
398 		for (int i = 0; i < vd->dring_len; i++)
399 			(void) ldc_mem_free_handle(vd->dring_task[i].mhdl);
400 		kmem_free(vd->dring_task,
401 		    (sizeof (*vd->dring_task)) * vd->dring_len);
402 		vd->dring_task = NULL;
403 	}
404 
405 
406 	mutex_enter(&vd->lock);
407 	if (vd->reset_ldc && ((status = ldc_down(vd->ldc_handle)) != 0))
408 		PRN("ldc_down() returned errno %d", status);
409 
410 	vd->initialized	&= ~(VD_SID | VD_SEQ_NUM | VD_DRING);
411 	vd->state	= VD_STATE_INIT;
412 	vd->max_msglen	= sizeof (vio_msg_t);	/* baseline vio message size */
413 
414 	vd->reset_state	= B_FALSE;
415 	vd->reset_ldc	= B_FALSE;
416 	mutex_exit(&vd->lock);
417 }
418 
419 static int
420 vd_mark_elem_done(vd_t *vd, int idx, int elem_status)
421 {
422 	boolean_t		accepted;
423 	int			status;
424 	vd_dring_entry_t	*elem = VD_DRING_ELEM(idx);
425 
426 
427 	/* Acquire the element */
428 	if ((status = ldc_mem_dring_acquire(vd->dring_handle, idx, idx)) != 0) {
429 		PRN("ldc_mem_dring_acquire() returned errno %d", status);
430 		return (status);
431 	}
432 
433 	/* Set the element's status and mark it done */
434 	accepted = (elem->hdr.dstate == VIO_DESC_ACCEPTED);
435 	if (accepted) {
436 		elem->payload.status	= elem_status;
437 		elem->hdr.dstate	= VIO_DESC_DONE;
438 	} else {
439 		/* Perhaps client timed out waiting for I/O... */
440 		PRN("element %u no longer \"accepted\"", idx);
441 		VD_DUMP_DRING_ELEM(elem);
442 	}
443 	/* Release the element */
444 	if ((status = ldc_mem_dring_release(vd->dring_handle, idx, idx)) != 0) {
445 		PRN("ldc_mem_dring_release() returned errno %d", status);
446 		return (status);
447 	}
448 
449 	return (accepted ? 0 : EINVAL);
450 }
451 
452 static void
453 vd_complete_bio(void *arg)
454 {
455 	int			status		= 0;
456 	vd_task_t		*task		= (vd_task_t *)arg;
457 	vd_t			*vd		= task->vd;
458 	vd_dring_payload_t	*request	= task->request;
459 	struct buf		*buf		= &task->buf;
460 
461 
462 	ASSERT(vd != NULL);
463 	ASSERT(request != NULL);
464 	ASSERT(task->msg != NULL);
465 	ASSERT(task->msglen >= sizeof (*task->msg));
466 	ASSERT(task->msgsize >= task->msglen);
467 
468 	/* Wait for the I/O to complete */
469 	request->status = biowait(buf);
470 
471 	/* Release the buffer */
472 	status = ldc_mem_release(task->mhdl, 0, buf->b_bcount);
473 	if (status) {
474 		PRN("ldc_mem_release() returned errno %d copying to client",
475 		    status);
476 	}
477 
478 	/* Unmap the memory */
479 	status = ldc_mem_unmap(task->mhdl);
480 	if (status) {
481 		PRN("ldc_mem_unmap() returned errno %d copying to client",
482 		    status);
483 	}
484 
485 	biofini(buf);
486 
487 	/* Update the dring element for a dring client */
488 	if ((status == 0) && (vd->xfer_mode == VIO_DRING_MODE))
489 		status = vd_mark_elem_done(vd, task->index, request->status);
490 
491 	/*
492 	 * If a transport error occurred, arrange to "nack" the message when
493 	 * the final task in the descriptor element range completes
494 	 */
495 	if (status != 0)
496 		task->msg->tag.vio_subtype = VIO_SUBTYPE_NACK;
497 
498 	/*
499 	 * Only the final task for a range of elements will respond to and
500 	 * free the message
501 	 */
502 	if (task->type == VD_NONFINAL_RANGE_TASK)
503 		return;
504 
505 	/*
506 	 * Send the "ack" or "nack" back to the client; if sending the message
507 	 * via LDC fails, arrange to reset both the connection state and LDC
508 	 * itself
509 	 */
510 	PR1("Sending %s",
511 	    (task->msg->tag.vio_subtype == VIO_SUBTYPE_ACK) ? "ACK" : "NACK");
512 	if (send_msg(vd->ldc_handle, task->msg, task->msglen) != 0)
513 		vd_need_reset(vd, B_TRUE);
514 
515 	/* Free the message now that it has been used for the reply */
516 	kmem_free(task->msg, task->msgsize);
517 }
518 
519 static void
520 vd_geom2dk_geom(void *vd_buf, void *ioctl_arg)
521 {
522 	VD_GEOM2DK_GEOM((vd_geom_t *)vd_buf, (struct dk_geom *)ioctl_arg);
523 }
524 
525 static void
526 vd_vtoc2vtoc(void *vd_buf, void *ioctl_arg)
527 {
528 	VD_VTOC2VTOC((vd_vtoc_t *)vd_buf, (struct vtoc *)ioctl_arg);
529 }
530 
531 static void
532 dk_geom2vd_geom(void *ioctl_arg, void *vd_buf)
533 {
534 	DK_GEOM2VD_GEOM((struct dk_geom *)ioctl_arg, (vd_geom_t *)vd_buf);
535 }
536 
537 static void
538 vtoc2vd_vtoc(void *ioctl_arg, void *vd_buf)
539 {
540 	VTOC2VD_VTOC((struct vtoc *)ioctl_arg, (vd_vtoc_t *)vd_buf);
541 }
542 
543 static void
544 vd_get_efi_in(void *vd_buf, void *ioctl_arg)
545 {
546 	vd_efi_t *vd_efi = (vd_efi_t *)vd_buf;
547 	dk_efi_t *dk_efi = (dk_efi_t *)ioctl_arg;
548 
549 	dk_efi->dki_lba = vd_efi->lba;
550 	dk_efi->dki_length = vd_efi->length;
551 	dk_efi->dki_data = kmem_zalloc(vd_efi->length, KM_SLEEP);
552 }
553 
554 static void
555 vd_get_efi_out(void *ioctl_arg, void *vd_buf)
556 {
557 	int len;
558 	vd_efi_t *vd_efi = (vd_efi_t *)vd_buf;
559 	dk_efi_t *dk_efi = (dk_efi_t *)ioctl_arg;
560 
561 	len = vd_efi->length;
562 	DK_EFI2VD_EFI(dk_efi, vd_efi);
563 	kmem_free(dk_efi->dki_data, len);
564 }
565 
566 static void
567 vd_set_efi_in(void *vd_buf, void *ioctl_arg)
568 {
569 	vd_efi_t *vd_efi = (vd_efi_t *)vd_buf;
570 	dk_efi_t *dk_efi = (dk_efi_t *)ioctl_arg;
571 
572 	dk_efi->dki_data = kmem_alloc(vd_efi->length, KM_SLEEP);
573 	VD_EFI2DK_EFI(vd_efi, dk_efi);
574 }
575 
576 static void
577 vd_set_efi_out(void *ioctl_arg, void *vd_buf)
578 {
579 	vd_efi_t *vd_efi = (vd_efi_t *)vd_buf;
580 	dk_efi_t *dk_efi = (dk_efi_t *)ioctl_arg;
581 
582 	kmem_free(dk_efi->dki_data, vd_efi->length);
583 }
584 
585 static int
586 vd_read_vtoc(ldi_handle_t handle, struct vtoc *vtoc, vd_disk_label_t *label)
587 {
588 	int status, rval;
589 	struct dk_gpt *efi;
590 	size_t efi_len;
591 
592 	*label = VD_DISK_LABEL_UNK;
593 
594 	status = ldi_ioctl(handle, DKIOCGVTOC, (intptr_t)vtoc,
595 	    (vd_open_flags | FKIOCTL), kcred, &rval);
596 
597 	if (status == 0) {
598 		*label = VD_DISK_LABEL_VTOC;
599 		return (0);
600 	} else if (status != ENOTSUP) {
601 		PRN("ldi_ioctl(DKIOCGVTOC) returned error %d", status);
602 		return (status);
603 	}
604 
605 	status = vds_efi_alloc_and_read(handle, &efi, &efi_len);
606 
607 	if (status) {
608 		PRN("vds_efi_alloc_and_read returned error %d", status);
609 		return (status);
610 	}
611 
612 	*label = VD_DISK_LABEL_EFI;
613 	vd_efi_to_vtoc(efi, vtoc);
614 	vd_efi_free(efi, efi_len);
615 
616 	return (0);
617 }
618 
619 static int
620 vd_do_slice_ioctl(vd_t *vd, int cmd, void *ioctl_arg)
621 {
622 	dk_efi_t *dk_ioc;
623 
624 	switch (vd->vdisk_label) {
625 
626 	case VD_DISK_LABEL_VTOC:
627 
628 		switch (cmd) {
629 		case DKIOCGGEOM:
630 			ASSERT(ioctl_arg != NULL);
631 			bcopy(&vd->dk_geom, ioctl_arg, sizeof (vd->dk_geom));
632 			return (0);
633 		case DKIOCGVTOC:
634 			ASSERT(ioctl_arg != NULL);
635 			bcopy(&vd->vtoc, ioctl_arg, sizeof (vd->vtoc));
636 			return (0);
637 		default:
638 			return (ENOTSUP);
639 		}
640 
641 	case VD_DISK_LABEL_EFI:
642 
643 		switch (cmd) {
644 		case DKIOCGETEFI:
645 			ASSERT(ioctl_arg != NULL);
646 			dk_ioc = (dk_efi_t *)ioctl_arg;
647 			if (dk_ioc->dki_length < vd->dk_efi.dki_length)
648 				return (EINVAL);
649 			bcopy(vd->dk_efi.dki_data, dk_ioc->dki_data,
650 			    vd->dk_efi.dki_length);
651 			return (0);
652 		default:
653 			return (ENOTSUP);
654 		}
655 
656 	default:
657 		return (ENOTSUP);
658 	}
659 }
660 
661 static int
662 vd_do_ioctl(vd_t *vd, vd_dring_payload_t *request, void* buf, vd_ioctl_t *ioctl)
663 {
664 	int	rval = 0, status;
665 	size_t	nbytes = request->nbytes;	/* modifiable copy */
666 
667 
668 	ASSERT(request->slice < vd->nslices);
669 	PR0("Performing %s", ioctl->operation_name);
670 
671 	/* Get data from client and convert, if necessary */
672 	if (ioctl->copyin != NULL)  {
673 		ASSERT(nbytes != 0 && buf != NULL);
674 		PR1("Getting \"arg\" data from client");
675 		if ((status = ldc_mem_copy(vd->ldc_handle, buf, 0, &nbytes,
676 			    request->cookie, request->ncookies,
677 			    LDC_COPY_IN)) != 0) {
678 			PRN("ldc_mem_copy() returned errno %d "
679 			    "copying from client", status);
680 			return (status);
681 		}
682 
683 		/* Convert client's data, if necessary */
684 		if (ioctl->copyin == VD_IDENTITY)	/* use client buffer */
685 			ioctl->arg = buf;
686 		else	/* convert client vdisk operation data to ioctl data */
687 			(ioctl->copyin)(buf, (void *)ioctl->arg);
688 	}
689 
690 	/*
691 	 * Handle single-slice block devices internally; otherwise, have the
692 	 * real driver perform the ioctl()
693 	 */
694 	if (vd->vdisk_type == VD_DISK_TYPE_SLICE && !vd->pseudo) {
695 		if ((status = vd_do_slice_ioctl(vd, ioctl->cmd,
696 			    (void *)ioctl->arg)) != 0)
697 			return (status);
698 	} else if ((status = ldi_ioctl(vd->ldi_handle[request->slice],
699 		    ioctl->cmd, (intptr_t)ioctl->arg, (vd_open_flags | FKIOCTL),
700 		    kcred, &rval)) != 0) {
701 		PR0("ldi_ioctl(%s) = errno %d", ioctl->cmd_name, status);
702 		return (status);
703 	}
704 #ifdef DEBUG
705 	if (rval != 0) {
706 		PRN("%s set rval = %d, which is not being returned to client",
707 		    ioctl->cmd_name, rval);
708 	}
709 #endif /* DEBUG */
710 
711 	/* Convert data and send to client, if necessary */
712 	if (ioctl->copyout != NULL)  {
713 		ASSERT(nbytes != 0 && buf != NULL);
714 		PR1("Sending \"arg\" data to client");
715 
716 		/* Convert ioctl data to vdisk operation data, if necessary */
717 		if (ioctl->copyout != VD_IDENTITY)
718 			(ioctl->copyout)((void *)ioctl->arg, buf);
719 
720 		if ((status = ldc_mem_copy(vd->ldc_handle, buf, 0, &nbytes,
721 			    request->cookie, request->ncookies,
722 			    LDC_COPY_OUT)) != 0) {
723 			PRN("ldc_mem_copy() returned errno %d "
724 			    "copying to client", status);
725 			return (status);
726 		}
727 	}
728 
729 	return (status);
730 }
731 
732 /*
733  * Open any slices which have become non-empty as a result of performing a
734  * set-VTOC operation for the client.
735  *
736  * When serving a full disk, vds attempts to exclusively open all of the
737  * disk's slices to prevent another thread or process in the service domain
738  * from "stealing" a slice or from performing I/O to a slice while a vds
739  * client is accessing it.  Unfortunately, underlying drivers, such as sd(7d)
740  * and cmdk(7d), return an error when attempting to open the device file for a
741  * slice which is currently empty according to the VTOC.  This driver behavior
742  * means that vds must skip opening empty slices when initializing a vdisk for
743  * full-disk service and try to open slices that become non-empty (via a
744  * set-VTOC operation) during use of the full disk in order to begin serving
745  * such slices to the client.  This approach has an inherent (and therefore
746  * unavoidable) race condition; it also means that failure to open a
747  * newly-non-empty slice has different semantics than failure to open an
748  * initially-non-empty slice:  Due to driver bahavior, opening a
749  * newly-non-empty slice is a necessary side effect of vds performing a
750  * (successful) set-VTOC operation for a client on an in-service (and in-use)
751  * disk in order to begin serving the slice; failure of this side-effect
752  * operation does not mean that the client's set-VTOC operation failed or that
753  * operations on other slices must fail.  Therefore, this function prints an
754  * error message on failure to open a slice, but does not return an error to
755  * its caller--unlike failure to open a slice initially, which results in an
756  * error that prevents serving the vdisk (and thereby requires an
757  * administrator to resolve the problem).  Note that, apart from another
758  * thread or process opening a new slice during the race-condition window,
759  * failure to open a slice in this function will likely indicate an underlying
760  * drive problem, which will also likely become evident in errors returned by
761  * operations on other slices, and which will require administrative
762  * intervention and possibly servicing the drive.
763  */
764 static void
765 vd_open_new_slices(vd_t *vd)
766 {
767 	int		status;
768 	struct vtoc	vtoc;
769 
770 	/* Get the (new) partitions for updated slice sizes */
771 	if ((status = vd_read_vtoc(vd->ldi_handle[0], &vtoc,
772 	    &vd->vdisk_label)) != 0) {
773 		PRN("vd_read_vtoc returned error %d", status);
774 		return;
775 	}
776 
777 	/* Open any newly-non-empty slices */
778 	for (int slice = 0; slice < vd->nslices; slice++) {
779 		/* Skip zero-length slices */
780 		if (vtoc.v_part[slice].p_size == 0) {
781 			if (vd->ldi_handle[slice] != NULL)
782 				PR0("Open slice %u now has zero length", slice);
783 			continue;
784 		}
785 
786 		/* Skip already-open slices */
787 		if (vd->ldi_handle[slice] != NULL)
788 			continue;
789 
790 		PR0("Opening newly-non-empty slice %u", slice);
791 		if ((status = ldi_open_by_dev(&vd->dev[slice], OTYP_BLK,
792 			    vd_open_flags, kcred, &vd->ldi_handle[slice],
793 			    vd->vds->ldi_ident)) != 0) {
794 			PRN("ldi_open_by_dev() returned errno %d "
795 			    "for slice %u", status, slice);
796 		}
797 	}
798 }
799 
800 #define	RNDSIZE(expr) P2ROUNDUP(sizeof (expr), sizeof (uint64_t))
801 static int
802 vd_ioctl(vd_task_t *task)
803 {
804 	int			i, status;
805 	void			*buf = NULL;
806 	struct dk_geom		dk_geom = {0};
807 	struct vtoc		vtoc = {0};
808 	struct dk_efi		dk_efi = {0};
809 	vd_t			*vd		= task->vd;
810 	vd_dring_payload_t	*request	= task->request;
811 	vd_ioctl_t		ioctl[] = {
812 		/* Command (no-copy) operations */
813 		{VD_OP_FLUSH, STRINGIZE(VD_OP_FLUSH), 0,
814 		    DKIOCFLUSHWRITECACHE, STRINGIZE(DKIOCFLUSHWRITECACHE),
815 		    NULL, NULL, NULL},
816 
817 		/* "Get" (copy-out) operations */
818 		{VD_OP_GET_WCE, STRINGIZE(VD_OP_GET_WCE), RNDSIZE(int),
819 		    DKIOCGETWCE, STRINGIZE(DKIOCGETWCE),
820 		    NULL, VD_IDENTITY, VD_IDENTITY},
821 		{VD_OP_GET_DISKGEOM, STRINGIZE(VD_OP_GET_DISKGEOM),
822 		    RNDSIZE(vd_geom_t),
823 		    DKIOCGGEOM, STRINGIZE(DKIOCGGEOM),
824 		    &dk_geom, NULL, dk_geom2vd_geom},
825 		{VD_OP_GET_VTOC, STRINGIZE(VD_OP_GET_VTOC), RNDSIZE(vd_vtoc_t),
826 		    DKIOCGVTOC, STRINGIZE(DKIOCGVTOC),
827 		    &vtoc, NULL, vtoc2vd_vtoc},
828 		{VD_OP_GET_EFI, STRINGIZE(VD_OP_GET_EFI), RNDSIZE(vd_efi_t),
829 		    DKIOCGETEFI, STRINGIZE(DKIOCGETEFI),
830 		    &dk_efi, vd_get_efi_in, vd_get_efi_out},
831 
832 		/* "Set" (copy-in) operations */
833 		{VD_OP_SET_WCE, STRINGIZE(VD_OP_SET_WCE), RNDSIZE(int),
834 		    DKIOCSETWCE, STRINGIZE(DKIOCSETWCE),
835 		    NULL, VD_IDENTITY, VD_IDENTITY},
836 		{VD_OP_SET_DISKGEOM, STRINGIZE(VD_OP_SET_DISKGEOM),
837 		    RNDSIZE(vd_geom_t),
838 		    DKIOCSGEOM, STRINGIZE(DKIOCSGEOM),
839 		    &dk_geom, vd_geom2dk_geom, NULL},
840 		{VD_OP_SET_VTOC, STRINGIZE(VD_OP_SET_VTOC), RNDSIZE(vd_vtoc_t),
841 		    DKIOCSVTOC, STRINGIZE(DKIOCSVTOC),
842 		    &vtoc, vd_vtoc2vtoc, NULL},
843 		{VD_OP_SET_EFI, STRINGIZE(VD_OP_SET_EFI), RNDSIZE(vd_efi_t),
844 		    DKIOCSETEFI, STRINGIZE(DKIOCSETEFI),
845 		    &dk_efi, vd_set_efi_in, vd_set_efi_out},
846 	};
847 	size_t		nioctls = (sizeof (ioctl))/(sizeof (ioctl[0]));
848 
849 
850 	ASSERT(vd != NULL);
851 	ASSERT(request != NULL);
852 	ASSERT(request->slice < vd->nslices);
853 
854 	/*
855 	 * Determine ioctl corresponding to caller's "operation" and
856 	 * validate caller's "nbytes"
857 	 */
858 	for (i = 0; i < nioctls; i++) {
859 		if (request->operation == ioctl[i].operation) {
860 			/* LDC memory operations require 8-byte multiples */
861 			ASSERT(ioctl[i].nbytes % sizeof (uint64_t) == 0);
862 
863 			if (request->operation == VD_OP_GET_EFI ||
864 			    request->operation == VD_OP_SET_EFI) {
865 				if (request->nbytes >= ioctl[i].nbytes)
866 					break;
867 				PRN("%s:  Expected at least nbytes = %lu, "
868 				    "got %lu", ioctl[i].operation_name,
869 				    ioctl[i].nbytes, request->nbytes);
870 				return (EINVAL);
871 			}
872 
873 			if (request->nbytes != ioctl[i].nbytes) {
874 				PRN("%s:  Expected nbytes = %lu, got %lu",
875 				    ioctl[i].operation_name, ioctl[i].nbytes,
876 				    request->nbytes);
877 				return (EINVAL);
878 			}
879 
880 			break;
881 		}
882 	}
883 	ASSERT(i < nioctls);	/* because "operation" already validated */
884 
885 	if (request->nbytes)
886 		buf = kmem_zalloc(request->nbytes, KM_SLEEP);
887 	status = vd_do_ioctl(vd, request, buf, &ioctl[i]);
888 	if (request->nbytes)
889 		kmem_free(buf, request->nbytes);
890 	if (vd->vdisk_type == VD_DISK_TYPE_DISK &&
891 	    (request->operation == VD_OP_SET_VTOC ||
892 	    request->operation == VD_OP_SET_EFI))
893 		vd_open_new_slices(vd);
894 	PR0("Returning %d", status);
895 	return (status);
896 }
897 
898 static int
899 vd_get_devid(vd_task_t *task)
900 {
901 	vd_t *vd = task->vd;
902 	vd_dring_payload_t *request = task->request;
903 	vd_devid_t *vd_devid;
904 	impl_devid_t *devid;
905 	int status, bufid_len, devid_len, len;
906 
907 	PR1("Get Device ID");
908 
909 	if (ddi_lyr_get_devid(vd->dev[request->slice],
910 	    (ddi_devid_t *)&devid) != DDI_SUCCESS) {
911 		/* the most common failure is that no devid is available */
912 		return (ENOENT);
913 	}
914 
915 	bufid_len = request->nbytes - sizeof (vd_devid_t) + 1;
916 	devid_len = DEVID_GETLEN(devid);
917 
918 	vd_devid = kmem_zalloc(request->nbytes, KM_SLEEP);
919 	vd_devid->length = devid_len;
920 	vd_devid->type = DEVID_GETTYPE(devid);
921 
922 	len = (devid_len > bufid_len)? bufid_len : devid_len;
923 
924 	bcopy(devid->did_id, vd_devid->id, len);
925 
926 	/* LDC memory operations require 8-byte multiples */
927 	ASSERT(request->nbytes % sizeof (uint64_t) == 0);
928 
929 	if ((status = ldc_mem_copy(vd->ldc_handle, (caddr_t)vd_devid, 0,
930 	    &request->nbytes, request->cookie, request->ncookies,
931 	    LDC_COPY_OUT)) != 0) {
932 		PRN("ldc_mem_copy() returned errno %d copying to client",
933 		    status);
934 	}
935 
936 	kmem_free(vd_devid, request->nbytes);
937 	ddi_devid_free((ddi_devid_t)devid);
938 
939 	return (status);
940 }
941 
942 /*
943  * Define the supported operations once the functions for performing them have
944  * been defined
945  */
946 static const vds_operation_t	vds_operation[] = {
947 	{VD_OP_BREAD,		vd_start_bio,	vd_complete_bio},
948 	{VD_OP_BWRITE,		vd_start_bio,	vd_complete_bio},
949 	{VD_OP_FLUSH,		vd_ioctl,	NULL},
950 	{VD_OP_GET_WCE,		vd_ioctl,	NULL},
951 	{VD_OP_SET_WCE,		vd_ioctl,	NULL},
952 	{VD_OP_GET_VTOC,	vd_ioctl,	NULL},
953 	{VD_OP_SET_VTOC,	vd_ioctl,	NULL},
954 	{VD_OP_GET_DISKGEOM,	vd_ioctl,	NULL},
955 	{VD_OP_SET_DISKGEOM,	vd_ioctl,	NULL},
956 	{VD_OP_GET_EFI,		vd_ioctl,	NULL},
957 	{VD_OP_SET_EFI,		vd_ioctl,	NULL},
958 	{VD_OP_GET_DEVID,	vd_get_devid,	NULL},
959 };
960 
961 static const size_t	vds_noperations =
962 	(sizeof (vds_operation))/(sizeof (vds_operation[0]));
963 
964 /*
965  * Process a task specifying a client I/O request
966  */
967 static int
968 vd_process_task(vd_task_t *task)
969 {
970 	int			i, status;
971 	vd_t			*vd		= task->vd;
972 	vd_dring_payload_t	*request	= task->request;
973 
974 
975 	ASSERT(vd != NULL);
976 	ASSERT(request != NULL);
977 
978 	/* Range-check slice */
979 	if (request->slice >= vd->nslices) {
980 		PRN("Invalid \"slice\" %u (max %u) for virtual disk",
981 		    request->slice, (vd->nslices - 1));
982 		return (EINVAL);
983 	}
984 
985 	/* Find the requested operation */
986 	for (i = 0; i < vds_noperations; i++)
987 		if (request->operation == vds_operation[i].operation)
988 			break;
989 	if (i == vds_noperations) {
990 		PRN("Unsupported operation %u", request->operation);
991 		return (ENOTSUP);
992 	}
993 
994 	/* Start the operation */
995 	if ((status = vds_operation[i].start(task)) != EINPROGRESS) {
996 		request->status = status;	/* op succeeded or failed */
997 		return (0);			/* but request completed */
998 	}
999 
1000 	ASSERT(vds_operation[i].complete != NULL);	/* debug case */
1001 	if (vds_operation[i].complete == NULL) {	/* non-debug case */
1002 		PRN("Unexpected return of EINPROGRESS "
1003 		    "with no I/O completion handler");
1004 		request->status = EIO;	/* operation failed */
1005 		return (0);		/* but request completed */
1006 	}
1007 
1008 	/* Queue a task to complete the operation */
1009 	status = ddi_taskq_dispatch(vd->completionq, vds_operation[i].complete,
1010 	    task, DDI_SLEEP);
1011 	/* ddi_taskq_dispatch(9f) guarantees success with DDI_SLEEP */
1012 	ASSERT(status == DDI_SUCCESS);
1013 
1014 	PR1("Operation in progress");
1015 	return (EINPROGRESS);	/* completion handler will finish request */
1016 }
1017 
1018 /*
1019  * Return true if the "type", "subtype", and "env" fields of the "tag" first
1020  * argument match the corresponding remaining arguments; otherwise, return false
1021  */
1022 boolean_t
1023 vd_msgtype(vio_msg_tag_t *tag, int type, int subtype, int env)
1024 {
1025 	return ((tag->vio_msgtype == type) &&
1026 		(tag->vio_subtype == subtype) &&
1027 		(tag->vio_subtype_env == env)) ? B_TRUE : B_FALSE;
1028 }
1029 
1030 /*
1031  * Check whether the major/minor version specified in "ver_msg" is supported
1032  * by this server.
1033  */
1034 static boolean_t
1035 vds_supported_version(vio_ver_msg_t *ver_msg)
1036 {
1037 	for (int i = 0; i < vds_num_versions; i++) {
1038 		ASSERT(vds_version[i].major > 0);
1039 		ASSERT((i == 0) ||
1040 		    (vds_version[i].major < vds_version[i-1].major));
1041 
1042 		/*
1043 		 * If the major versions match, adjust the minor version, if
1044 		 * necessary, down to the highest value supported by this
1045 		 * server and return true so this message will get "ack"ed;
1046 		 * the client should also support all minor versions lower
1047 		 * than the value it sent
1048 		 */
1049 		if (ver_msg->ver_major == vds_version[i].major) {
1050 			if (ver_msg->ver_minor > vds_version[i].minor) {
1051 				PR0("Adjusting minor version from %u to %u",
1052 				    ver_msg->ver_minor, vds_version[i].minor);
1053 				ver_msg->ver_minor = vds_version[i].minor;
1054 			}
1055 			return (B_TRUE);
1056 		}
1057 
1058 		/*
1059 		 * If the message contains a higher major version number, set
1060 		 * the message's major/minor versions to the current values
1061 		 * and return false, so this message will get "nack"ed with
1062 		 * these values, and the client will potentially try again
1063 		 * with the same or a lower version
1064 		 */
1065 		if (ver_msg->ver_major > vds_version[i].major) {
1066 			ver_msg->ver_major = vds_version[i].major;
1067 			ver_msg->ver_minor = vds_version[i].minor;
1068 			return (B_FALSE);
1069 		}
1070 
1071 		/*
1072 		 * Otherwise, the message's major version is less than the
1073 		 * current major version, so continue the loop to the next
1074 		 * (lower) supported version
1075 		 */
1076 	}
1077 
1078 	/*
1079 	 * No common version was found; "ground" the version pair in the
1080 	 * message to terminate negotiation
1081 	 */
1082 	ver_msg->ver_major = 0;
1083 	ver_msg->ver_minor = 0;
1084 	return (B_FALSE);
1085 }
1086 
1087 /*
1088  * Process a version message from a client.  vds expects to receive version
1089  * messages from clients seeking service, but never issues version messages
1090  * itself; therefore, vds can ACK or NACK client version messages, but does
1091  * not expect to receive version-message ACKs or NACKs (and will treat such
1092  * messages as invalid).
1093  */
1094 static int
1095 vd_process_ver_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
1096 {
1097 	vio_ver_msg_t	*ver_msg = (vio_ver_msg_t *)msg;
1098 
1099 
1100 	ASSERT(msglen >= sizeof (msg->tag));
1101 
1102 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO,
1103 		VIO_VER_INFO)) {
1104 		return (ENOMSG);	/* not a version message */
1105 	}
1106 
1107 	if (msglen != sizeof (*ver_msg)) {
1108 		PRN("Expected %lu-byte version message; "
1109 		    "received %lu bytes", sizeof (*ver_msg), msglen);
1110 		return (EBADMSG);
1111 	}
1112 
1113 	if (ver_msg->dev_class != VDEV_DISK) {
1114 		PRN("Expected device class %u (disk); received %u",
1115 		    VDEV_DISK, ver_msg->dev_class);
1116 		return (EBADMSG);
1117 	}
1118 
1119 	/*
1120 	 * We're talking to the expected kind of client; set our device class
1121 	 * for "ack/nack" back to the client
1122 	 */
1123 	ver_msg->dev_class = VDEV_DISK_SERVER;
1124 
1125 	/*
1126 	 * Check whether the (valid) version message specifies a version
1127 	 * supported by this server.  If the version is not supported, return
1128 	 * EBADMSG so the message will get "nack"ed; vds_supported_version()
1129 	 * will have updated the message with a supported version for the
1130 	 * client to consider
1131 	 */
1132 	if (!vds_supported_version(ver_msg))
1133 		return (EBADMSG);
1134 
1135 
1136 	/*
1137 	 * A version has been agreed upon; use the client's SID for
1138 	 * communication on this channel now
1139 	 */
1140 	ASSERT(!(vd->initialized & VD_SID));
1141 	vd->sid = ver_msg->tag.vio_sid;
1142 	vd->initialized |= VD_SID;
1143 
1144 	/*
1145 	 * When multiple versions are supported, this function should store
1146 	 * the negotiated major and minor version values in the "vd" data
1147 	 * structure to govern further communication; in particular, note that
1148 	 * the client might have specified a lower minor version for the
1149 	 * agreed major version than specifed in the vds_version[] array.  The
1150 	 * following assertions should help remind future maintainers to make
1151 	 * the appropriate changes to support multiple versions.
1152 	 */
1153 	ASSERT(vds_num_versions == 1);
1154 	ASSERT(ver_msg->ver_major == vds_version[0].major);
1155 	ASSERT(ver_msg->ver_minor == vds_version[0].minor);
1156 
1157 	PR0("Using major version %u, minor version %u",
1158 	    ver_msg->ver_major, ver_msg->ver_minor);
1159 	return (0);
1160 }
1161 
1162 static int
1163 vd_process_attr_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
1164 {
1165 	vd_attr_msg_t	*attr_msg = (vd_attr_msg_t *)msg;
1166 
1167 
1168 	ASSERT(msglen >= sizeof (msg->tag));
1169 
1170 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO,
1171 		VIO_ATTR_INFO)) {
1172 		PR0("Message is not an attribute message");
1173 		return (ENOMSG);
1174 	}
1175 
1176 	if (msglen != sizeof (*attr_msg)) {
1177 		PRN("Expected %lu-byte attribute message; "
1178 		    "received %lu bytes", sizeof (*attr_msg), msglen);
1179 		return (EBADMSG);
1180 	}
1181 
1182 	if (attr_msg->max_xfer_sz == 0) {
1183 		PRN("Received maximum transfer size of 0 from client");
1184 		return (EBADMSG);
1185 	}
1186 
1187 	if ((attr_msg->xfer_mode != VIO_DESC_MODE) &&
1188 	    (attr_msg->xfer_mode != VIO_DRING_MODE)) {
1189 		PRN("Client requested unsupported transfer mode");
1190 		return (EBADMSG);
1191 	}
1192 
1193 
1194 	/* Success:  valid message and transfer mode */
1195 	vd->xfer_mode = attr_msg->xfer_mode;
1196 	if (vd->xfer_mode == VIO_DESC_MODE) {
1197 		/*
1198 		 * The vd_dring_inband_msg_t contains one cookie; need room
1199 		 * for up to n-1 more cookies, where "n" is the number of full
1200 		 * pages plus possibly one partial page required to cover
1201 		 * "max_xfer_sz".  Add room for one more cookie if
1202 		 * "max_xfer_sz" isn't an integral multiple of the page size.
1203 		 * Must first get the maximum transfer size in bytes.
1204 		 */
1205 		size_t	max_xfer_bytes = attr_msg->vdisk_block_size ?
1206 		    attr_msg->vdisk_block_size*attr_msg->max_xfer_sz :
1207 		    attr_msg->max_xfer_sz;
1208 		size_t	max_inband_msglen =
1209 		    sizeof (vd_dring_inband_msg_t) +
1210 		    ((max_xfer_bytes/PAGESIZE +
1211 			((max_xfer_bytes % PAGESIZE) ? 1 : 0))*
1212 			(sizeof (ldc_mem_cookie_t)));
1213 
1214 		/*
1215 		 * Set the maximum expected message length to
1216 		 * accommodate in-band-descriptor messages with all
1217 		 * their cookies
1218 		 */
1219 		vd->max_msglen = MAX(vd->max_msglen, max_inband_msglen);
1220 
1221 		/*
1222 		 * Initialize the data structure for processing in-band I/O
1223 		 * request descriptors
1224 		 */
1225 		vd->inband_task.vd	= vd;
1226 		vd->inband_task.index	= 0;
1227 		vd->inband_task.type	= VD_FINAL_RANGE_TASK;	/* range == 1 */
1228 	}
1229 
1230 	/* Return the device's block size and max transfer size to the client */
1231 	attr_msg->vdisk_block_size	= DEV_BSIZE;
1232 	attr_msg->max_xfer_sz		= vd->max_xfer_sz;
1233 
1234 	attr_msg->vdisk_size = vd->vdisk_size;
1235 	attr_msg->vdisk_type = vd->vdisk_type;
1236 	attr_msg->operations = vds_operations;
1237 	PR0("%s", VD_CLIENT(vd));
1238 	return (0);
1239 }
1240 
1241 static int
1242 vd_process_dring_reg_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
1243 {
1244 	int			status;
1245 	size_t			expected;
1246 	ldc_mem_info_t		dring_minfo;
1247 	vio_dring_reg_msg_t	*reg_msg = (vio_dring_reg_msg_t *)msg;
1248 
1249 
1250 	ASSERT(msglen >= sizeof (msg->tag));
1251 
1252 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO,
1253 		VIO_DRING_REG)) {
1254 		PR0("Message is not a register-dring message");
1255 		return (ENOMSG);
1256 	}
1257 
1258 	if (msglen < sizeof (*reg_msg)) {
1259 		PRN("Expected at least %lu-byte register-dring message; "
1260 		    "received %lu bytes", sizeof (*reg_msg), msglen);
1261 		return (EBADMSG);
1262 	}
1263 
1264 	expected = sizeof (*reg_msg) +
1265 	    (reg_msg->ncookies - 1)*(sizeof (reg_msg->cookie[0]));
1266 	if (msglen != expected) {
1267 		PRN("Expected %lu-byte register-dring message; "
1268 		    "received %lu bytes", expected, msglen);
1269 		return (EBADMSG);
1270 	}
1271 
1272 	if (vd->initialized & VD_DRING) {
1273 		PRN("A dring was previously registered; only support one");
1274 		return (EBADMSG);
1275 	}
1276 
1277 	if (reg_msg->num_descriptors > INT32_MAX) {
1278 		PRN("reg_msg->num_descriptors = %u; must be <= %u (%s)",
1279 		    reg_msg->ncookies, INT32_MAX, STRINGIZE(INT32_MAX));
1280 		return (EBADMSG);
1281 	}
1282 
1283 	if (reg_msg->ncookies != 1) {
1284 		/*
1285 		 * In addition to fixing the assertion in the success case
1286 		 * below, supporting drings which require more than one
1287 		 * "cookie" requires increasing the value of vd->max_msglen
1288 		 * somewhere in the code path prior to receiving the message
1289 		 * which results in calling this function.  Note that without
1290 		 * making this change, the larger message size required to
1291 		 * accommodate multiple cookies cannot be successfully
1292 		 * received, so this function will not even get called.
1293 		 * Gracefully accommodating more dring cookies might
1294 		 * reasonably demand exchanging an additional attribute or
1295 		 * making a minor protocol adjustment
1296 		 */
1297 		PRN("reg_msg->ncookies = %u != 1", reg_msg->ncookies);
1298 		return (EBADMSG);
1299 	}
1300 
1301 	status = ldc_mem_dring_map(vd->ldc_handle, reg_msg->cookie,
1302 	    reg_msg->ncookies, reg_msg->num_descriptors,
1303 	    reg_msg->descriptor_size, LDC_DIRECT_MAP, &vd->dring_handle);
1304 	if (status != 0) {
1305 		PRN("ldc_mem_dring_map() returned errno %d", status);
1306 		return (status);
1307 	}
1308 
1309 	/*
1310 	 * To remove the need for this assertion, must call
1311 	 * ldc_mem_dring_nextcookie() successfully ncookies-1 times after a
1312 	 * successful call to ldc_mem_dring_map()
1313 	 */
1314 	ASSERT(reg_msg->ncookies == 1);
1315 
1316 	if ((status =
1317 		ldc_mem_dring_info(vd->dring_handle, &dring_minfo)) != 0) {
1318 		PRN("ldc_mem_dring_info() returned errno %d", status);
1319 		if ((status = ldc_mem_dring_unmap(vd->dring_handle)) != 0)
1320 			PRN("ldc_mem_dring_unmap() returned errno %d", status);
1321 		return (status);
1322 	}
1323 
1324 	if (dring_minfo.vaddr == NULL) {
1325 		PRN("Descriptor ring virtual address is NULL");
1326 		return (ENXIO);
1327 	}
1328 
1329 
1330 	/* Initialize for valid message and mapped dring */
1331 	PR1("descriptor size = %u, dring length = %u",
1332 	    vd->descriptor_size, vd->dring_len);
1333 	vd->initialized |= VD_DRING;
1334 	vd->dring_ident = 1;	/* "There Can Be Only One" */
1335 	vd->dring = dring_minfo.vaddr;
1336 	vd->descriptor_size = reg_msg->descriptor_size;
1337 	vd->dring_len = reg_msg->num_descriptors;
1338 	reg_msg->dring_ident = vd->dring_ident;
1339 
1340 	/*
1341 	 * Allocate and initialize a "shadow" array of data structures for
1342 	 * tasks to process I/O requests in dring elements
1343 	 */
1344 	vd->dring_task =
1345 	    kmem_zalloc((sizeof (*vd->dring_task)) * vd->dring_len, KM_SLEEP);
1346 	for (int i = 0; i < vd->dring_len; i++) {
1347 		vd->dring_task[i].vd		= vd;
1348 		vd->dring_task[i].index		= i;
1349 		vd->dring_task[i].request	= &VD_DRING_ELEM(i)->payload;
1350 
1351 		status = ldc_mem_alloc_handle(vd->ldc_handle,
1352 		    &(vd->dring_task[i].mhdl));
1353 		if (status) {
1354 			PRN("ldc_mem_alloc_handle() returned err %d ", status);
1355 			return (ENXIO);
1356 		}
1357 	}
1358 
1359 	return (0);
1360 }
1361 
1362 static int
1363 vd_process_dring_unreg_msg(vd_t *vd, vio_msg_t *msg, size_t msglen)
1364 {
1365 	vio_dring_unreg_msg_t	*unreg_msg = (vio_dring_unreg_msg_t *)msg;
1366 
1367 
1368 	ASSERT(msglen >= sizeof (msg->tag));
1369 
1370 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO,
1371 		VIO_DRING_UNREG)) {
1372 		PR0("Message is not an unregister-dring message");
1373 		return (ENOMSG);
1374 	}
1375 
1376 	if (msglen != sizeof (*unreg_msg)) {
1377 		PRN("Expected %lu-byte unregister-dring message; "
1378 		    "received %lu bytes", sizeof (*unreg_msg), msglen);
1379 		return (EBADMSG);
1380 	}
1381 
1382 	if (unreg_msg->dring_ident != vd->dring_ident) {
1383 		PRN("Expected dring ident %lu; received %lu",
1384 		    vd->dring_ident, unreg_msg->dring_ident);
1385 		return (EBADMSG);
1386 	}
1387 
1388 	return (0);
1389 }
1390 
1391 static int
1392 process_rdx_msg(vio_msg_t *msg, size_t msglen)
1393 {
1394 	ASSERT(msglen >= sizeof (msg->tag));
1395 
1396 	if (!vd_msgtype(&msg->tag, VIO_TYPE_CTRL, VIO_SUBTYPE_INFO, VIO_RDX)) {
1397 		PR0("Message is not an RDX message");
1398 		return (ENOMSG);
1399 	}
1400 
1401 	if (msglen != sizeof (vio_rdx_msg_t)) {
1402 		PRN("Expected %lu-byte RDX message; received %lu bytes",
1403 		    sizeof (vio_rdx_msg_t), msglen);
1404 		return (EBADMSG);
1405 	}
1406 
1407 	PR0("Valid RDX message");
1408 	return (0);
1409 }
1410 
1411 static int
1412 vd_check_seq_num(vd_t *vd, uint64_t seq_num)
1413 {
1414 	if ((vd->initialized & VD_SEQ_NUM) && (seq_num != vd->seq_num + 1)) {
1415 		PRN("Received seq_num %lu; expected %lu",
1416 		    seq_num, (vd->seq_num + 1));
1417 		vd_need_reset(vd, B_FALSE);
1418 		return (1);
1419 	}
1420 
1421 	vd->seq_num = seq_num;
1422 	vd->initialized |= VD_SEQ_NUM;	/* superfluous after first time... */
1423 	return (0);
1424 }
1425 
1426 /*
1427  * Return the expected size of an inband-descriptor message with all the
1428  * cookies it claims to include
1429  */
1430 static size_t
1431 expected_inband_size(vd_dring_inband_msg_t *msg)
1432 {
1433 	return ((sizeof (*msg)) +
1434 	    (msg->payload.ncookies - 1)*(sizeof (msg->payload.cookie[0])));
1435 }
1436 
1437 /*
1438  * Process an in-band descriptor message:  used with clients like OBP, with
1439  * which vds exchanges descriptors within VIO message payloads, rather than
1440  * operating on them within a descriptor ring
1441  */
1442 static int
1443 vd_process_desc_msg(vd_t *vd, vio_msg_t *msg, size_t msglen, size_t msgsize)
1444 {
1445 	size_t			expected;
1446 	vd_dring_inband_msg_t	*desc_msg = (vd_dring_inband_msg_t *)msg;
1447 
1448 
1449 	ASSERT(msglen >= sizeof (msg->tag));
1450 
1451 	if (!vd_msgtype(&msg->tag, VIO_TYPE_DATA, VIO_SUBTYPE_INFO,
1452 		VIO_DESC_DATA)) {
1453 		PR1("Message is not an in-band-descriptor message");
1454 		return (ENOMSG);
1455 	}
1456 
1457 	if (msglen < sizeof (*desc_msg)) {
1458 		PRN("Expected at least %lu-byte descriptor message; "
1459 		    "received %lu bytes", sizeof (*desc_msg), msglen);
1460 		return (EBADMSG);
1461 	}
1462 
1463 	if (msglen != (expected = expected_inband_size(desc_msg))) {
1464 		PRN("Expected %lu-byte descriptor message; "
1465 		    "received %lu bytes", expected, msglen);
1466 		return (EBADMSG);
1467 	}
1468 
1469 	if (vd_check_seq_num(vd, desc_msg->hdr.seq_num) != 0)
1470 		return (EBADMSG);
1471 
1472 	/*
1473 	 * Valid message:  Set up the in-band descriptor task and process the
1474 	 * request.  Arrange to acknowledge the client's message, unless an
1475 	 * error processing the descriptor task results in setting
1476 	 * VIO_SUBTYPE_NACK
1477 	 */
1478 	PR1("Valid in-band-descriptor message");
1479 	msg->tag.vio_subtype = VIO_SUBTYPE_ACK;
1480 	vd->inband_task.msg	= msg;
1481 	vd->inband_task.msglen	= msglen;
1482 	vd->inband_task.msgsize	= msgsize;
1483 	vd->inband_task.request	= &desc_msg->payload;
1484 	return (vd_process_task(&vd->inband_task));
1485 }
1486 
1487 static int
1488 vd_process_element(vd_t *vd, vd_task_type_t type, uint32_t idx,
1489     vio_msg_t *msg, size_t msglen, size_t msgsize)
1490 {
1491 	int			status;
1492 	boolean_t		ready;
1493 	vd_dring_entry_t	*elem = VD_DRING_ELEM(idx);
1494 
1495 
1496 	/* Accept the updated dring element */
1497 	if ((status = ldc_mem_dring_acquire(vd->dring_handle, idx, idx)) != 0) {
1498 		PRN("ldc_mem_dring_acquire() returned errno %d", status);
1499 		return (status);
1500 	}
1501 	ready = (elem->hdr.dstate == VIO_DESC_READY);
1502 	if (ready) {
1503 		elem->hdr.dstate = VIO_DESC_ACCEPTED;
1504 	} else {
1505 		PRN("descriptor %u not ready", idx);
1506 		VD_DUMP_DRING_ELEM(elem);
1507 	}
1508 	if ((status = ldc_mem_dring_release(vd->dring_handle, idx, idx)) != 0) {
1509 		PRN("ldc_mem_dring_release() returned errno %d", status);
1510 		return (status);
1511 	}
1512 	if (!ready)
1513 		return (EBUSY);
1514 
1515 
1516 	/* Initialize a task and process the accepted element */
1517 	PR1("Processing dring element %u", idx);
1518 	vd->dring_task[idx].type	= type;
1519 	vd->dring_task[idx].msg		= msg;
1520 	vd->dring_task[idx].msglen	= msglen;
1521 	vd->dring_task[idx].msgsize	= msgsize;
1522 	if ((status = vd_process_task(&vd->dring_task[idx])) != EINPROGRESS)
1523 		status = vd_mark_elem_done(vd, idx, elem->payload.status);
1524 
1525 	return (status);
1526 }
1527 
1528 static int
1529 vd_process_element_range(vd_t *vd, int start, int end,
1530     vio_msg_t *msg, size_t msglen, size_t msgsize)
1531 {
1532 	int		i, n, nelem, status = 0;
1533 	boolean_t	inprogress = B_FALSE;
1534 	vd_task_type_t	type;
1535 
1536 
1537 	ASSERT(start >= 0);
1538 	ASSERT(end >= 0);
1539 
1540 	/*
1541 	 * Arrange to acknowledge the client's message, unless an error
1542 	 * processing one of the dring elements results in setting
1543 	 * VIO_SUBTYPE_NACK
1544 	 */
1545 	msg->tag.vio_subtype = VIO_SUBTYPE_ACK;
1546 
1547 	/*
1548 	 * Process the dring elements in the range
1549 	 */
1550 	nelem = ((end < start) ? end + vd->dring_len : end) - start + 1;
1551 	for (i = start, n = nelem; n > 0; i = (i + 1) % vd->dring_len, n--) {
1552 		((vio_dring_msg_t *)msg)->end_idx = i;
1553 		type = (n == 1) ? VD_FINAL_RANGE_TASK : VD_NONFINAL_RANGE_TASK;
1554 		status = vd_process_element(vd, type, i, msg, msglen, msgsize);
1555 		if (status == EINPROGRESS)
1556 			inprogress = B_TRUE;
1557 		else if (status != 0)
1558 			break;
1559 	}
1560 
1561 	/*
1562 	 * If some, but not all, operations of a multi-element range are in
1563 	 * progress, wait for other operations to complete before returning
1564 	 * (which will result in "ack" or "nack" of the message).  Note that
1565 	 * all outstanding operations will need to complete, not just the ones
1566 	 * corresponding to the current range of dring elements; howevever, as
1567 	 * this situation is an error case, performance is less critical.
1568 	 */
1569 	if ((nelem > 1) && (status != EINPROGRESS) && inprogress)
1570 		ddi_taskq_wait(vd->completionq);
1571 
1572 	return (status);
1573 }
1574 
1575 static int
1576 vd_process_dring_msg(vd_t *vd, vio_msg_t *msg, size_t msglen, size_t msgsize)
1577 {
1578 	vio_dring_msg_t	*dring_msg = (vio_dring_msg_t *)msg;
1579 
1580 
1581 	ASSERT(msglen >= sizeof (msg->tag));
1582 
1583 	if (!vd_msgtype(&msg->tag, VIO_TYPE_DATA, VIO_SUBTYPE_INFO,
1584 		VIO_DRING_DATA)) {
1585 		PR1("Message is not a dring-data message");
1586 		return (ENOMSG);
1587 	}
1588 
1589 	if (msglen != sizeof (*dring_msg)) {
1590 		PRN("Expected %lu-byte dring message; received %lu bytes",
1591 		    sizeof (*dring_msg), msglen);
1592 		return (EBADMSG);
1593 	}
1594 
1595 	if (vd_check_seq_num(vd, dring_msg->seq_num) != 0)
1596 		return (EBADMSG);
1597 
1598 	if (dring_msg->dring_ident != vd->dring_ident) {
1599 		PRN("Expected dring ident %lu; received ident %lu",
1600 		    vd->dring_ident, dring_msg->dring_ident);
1601 		return (EBADMSG);
1602 	}
1603 
1604 	if (dring_msg->start_idx >= vd->dring_len) {
1605 		PRN("\"start_idx\" = %u; must be less than %u",
1606 		    dring_msg->start_idx, vd->dring_len);
1607 		return (EBADMSG);
1608 	}
1609 
1610 	if ((dring_msg->end_idx < 0) ||
1611 	    (dring_msg->end_idx >= vd->dring_len)) {
1612 		PRN("\"end_idx\" = %u; must be >= 0 and less than %u",
1613 		    dring_msg->end_idx, vd->dring_len);
1614 		return (EBADMSG);
1615 	}
1616 
1617 	/* Valid message; process range of updated dring elements */
1618 	PR1("Processing descriptor range, start = %u, end = %u",
1619 	    dring_msg->start_idx, dring_msg->end_idx);
1620 	return (vd_process_element_range(vd, dring_msg->start_idx,
1621 		dring_msg->end_idx, msg, msglen, msgsize));
1622 }
1623 
1624 static int
1625 recv_msg(ldc_handle_t ldc_handle, void *msg, size_t *nbytes)
1626 {
1627 	int	retry, status;
1628 	size_t	size = *nbytes;
1629 
1630 
1631 	for (retry = 0, status = ETIMEDOUT;
1632 	    retry < vds_ldc_retries && status == ETIMEDOUT;
1633 	    retry++) {
1634 		PR1("ldc_read() attempt %d", (retry + 1));
1635 		*nbytes = size;
1636 		status = ldc_read(ldc_handle, msg, nbytes);
1637 	}
1638 
1639 	if (status != 0) {
1640 		PRN("ldc_read() returned errno %d", status);
1641 		return (status);
1642 	} else if (*nbytes == 0) {
1643 		PR1("ldc_read() returned 0 and no message read");
1644 		return (ENOMSG);
1645 	}
1646 
1647 	PR1("RCVD %lu-byte message", *nbytes);
1648 	return (0);
1649 }
1650 
1651 static int
1652 vd_do_process_msg(vd_t *vd, vio_msg_t *msg, size_t msglen, size_t msgsize)
1653 {
1654 	int		status;
1655 
1656 
1657 	PR1("Processing (%x/%x/%x) message", msg->tag.vio_msgtype,
1658 	    msg->tag.vio_subtype, msg->tag.vio_subtype_env);
1659 
1660 	/*
1661 	 * Validate session ID up front, since it applies to all messages
1662 	 * once set
1663 	 */
1664 	if ((msg->tag.vio_sid != vd->sid) && (vd->initialized & VD_SID)) {
1665 		PRN("Expected SID %u, received %u", vd->sid,
1666 		    msg->tag.vio_sid);
1667 		return (EBADMSG);
1668 	}
1669 
1670 
1671 	/*
1672 	 * Process the received message based on connection state
1673 	 */
1674 	switch (vd->state) {
1675 	case VD_STATE_INIT:	/* expect version message */
1676 		if ((status = vd_process_ver_msg(vd, msg, msglen)) != 0)
1677 			return (status);
1678 
1679 		/* Version negotiated, move to that state */
1680 		vd->state = VD_STATE_VER;
1681 		return (0);
1682 
1683 	case VD_STATE_VER:	/* expect attribute message */
1684 		if ((status = vd_process_attr_msg(vd, msg, msglen)) != 0)
1685 			return (status);
1686 
1687 		/* Attributes exchanged, move to that state */
1688 		vd->state = VD_STATE_ATTR;
1689 		return (0);
1690 
1691 	case VD_STATE_ATTR:
1692 		switch (vd->xfer_mode) {
1693 		case VIO_DESC_MODE:	/* expect RDX message */
1694 			if ((status = process_rdx_msg(msg, msglen)) != 0)
1695 				return (status);
1696 
1697 			/* Ready to receive in-band descriptors */
1698 			vd->state = VD_STATE_DATA;
1699 			return (0);
1700 
1701 		case VIO_DRING_MODE:	/* expect register-dring message */
1702 			if ((status =
1703 				vd_process_dring_reg_msg(vd, msg, msglen)) != 0)
1704 				return (status);
1705 
1706 			/* One dring negotiated, move to that state */
1707 			vd->state = VD_STATE_DRING;
1708 			return (0);
1709 
1710 		default:
1711 			ASSERT("Unsupported transfer mode");
1712 			PRN("Unsupported transfer mode");
1713 			return (ENOTSUP);
1714 		}
1715 
1716 	case VD_STATE_DRING:	/* expect RDX, register-dring, or unreg-dring */
1717 		if ((status = process_rdx_msg(msg, msglen)) == 0) {
1718 			/* Ready to receive data */
1719 			vd->state = VD_STATE_DATA;
1720 			return (0);
1721 		} else if (status != ENOMSG) {
1722 			return (status);
1723 		}
1724 
1725 
1726 		/*
1727 		 * If another register-dring message is received, stay in
1728 		 * dring state in case the client sends RDX; although the
1729 		 * protocol allows multiple drings, this server does not
1730 		 * support using more than one
1731 		 */
1732 		if ((status =
1733 			vd_process_dring_reg_msg(vd, msg, msglen)) != ENOMSG)
1734 			return (status);
1735 
1736 		/*
1737 		 * Acknowledge an unregister-dring message, but reset the
1738 		 * connection anyway:  Although the protocol allows
1739 		 * unregistering drings, this server cannot serve a vdisk
1740 		 * without its only dring
1741 		 */
1742 		status = vd_process_dring_unreg_msg(vd, msg, msglen);
1743 		return ((status == 0) ? ENOTSUP : status);
1744 
1745 	case VD_STATE_DATA:
1746 		switch (vd->xfer_mode) {
1747 		case VIO_DESC_MODE:	/* expect in-band-descriptor message */
1748 			return (vd_process_desc_msg(vd, msg, msglen, msgsize));
1749 
1750 		case VIO_DRING_MODE:	/* expect dring-data or unreg-dring */
1751 			/*
1752 			 * Typically expect dring-data messages, so handle
1753 			 * them first
1754 			 */
1755 			if ((status = vd_process_dring_msg(vd, msg,
1756 				    msglen, msgsize)) != ENOMSG)
1757 				return (status);
1758 
1759 			/*
1760 			 * Acknowledge an unregister-dring message, but reset
1761 			 * the connection anyway:  Although the protocol
1762 			 * allows unregistering drings, this server cannot
1763 			 * serve a vdisk without its only dring
1764 			 */
1765 			status = vd_process_dring_unreg_msg(vd, msg, msglen);
1766 			return ((status == 0) ? ENOTSUP : status);
1767 
1768 		default:
1769 			ASSERT("Unsupported transfer mode");
1770 			PRN("Unsupported transfer mode");
1771 			return (ENOTSUP);
1772 		}
1773 
1774 	default:
1775 		ASSERT("Invalid client connection state");
1776 		PRN("Invalid client connection state");
1777 		return (ENOTSUP);
1778 	}
1779 }
1780 
1781 static int
1782 vd_process_msg(vd_t *vd, vio_msg_t *msg, size_t msglen, size_t msgsize)
1783 {
1784 	int		status;
1785 	boolean_t	reset_ldc = B_FALSE;
1786 
1787 
1788 	/*
1789 	 * Check that the message is at least big enough for a "tag", so that
1790 	 * message processing can proceed based on tag-specified message type
1791 	 */
1792 	if (msglen < sizeof (vio_msg_tag_t)) {
1793 		PRN("Received short (%lu-byte) message", msglen);
1794 		/* Can't "nack" short message, so drop the big hammer */
1795 		vd_need_reset(vd, B_TRUE);
1796 		return (EBADMSG);
1797 	}
1798 
1799 	/*
1800 	 * Process the message
1801 	 */
1802 	switch (status = vd_do_process_msg(vd, msg, msglen, msgsize)) {
1803 	case 0:
1804 		/* "ack" valid, successfully-processed messages */
1805 		msg->tag.vio_subtype = VIO_SUBTYPE_ACK;
1806 		break;
1807 
1808 	case EINPROGRESS:
1809 		/* The completion handler will "ack" or "nack" the message */
1810 		return (EINPROGRESS);
1811 	case ENOMSG:
1812 		PRN("Received unexpected message");
1813 		_NOTE(FALLTHROUGH);
1814 	case EBADMSG:
1815 	case ENOTSUP:
1816 		/* "nack" invalid messages */
1817 		msg->tag.vio_subtype = VIO_SUBTYPE_NACK;
1818 		break;
1819 
1820 	default:
1821 		/* "nack" failed messages */
1822 		msg->tag.vio_subtype = VIO_SUBTYPE_NACK;
1823 		/* An LDC error probably occurred, so try resetting it */
1824 		reset_ldc = B_TRUE;
1825 		break;
1826 	}
1827 
1828 	/* Send the "ack" or "nack" to the client */
1829 	PR1("Sending %s",
1830 	    (msg->tag.vio_subtype == VIO_SUBTYPE_ACK) ? "ACK" : "NACK");
1831 	if (send_msg(vd->ldc_handle, msg, msglen) != 0)
1832 		reset_ldc = B_TRUE;
1833 
1834 	/* Arrange to reset the connection for nack'ed or failed messages */
1835 	if ((status != 0) || reset_ldc)
1836 		vd_need_reset(vd, reset_ldc);
1837 
1838 	return (status);
1839 }
1840 
1841 static boolean_t
1842 vd_enabled(vd_t *vd)
1843 {
1844 	boolean_t	enabled;
1845 
1846 
1847 	mutex_enter(&vd->lock);
1848 	enabled = vd->enabled;
1849 	mutex_exit(&vd->lock);
1850 	return (enabled);
1851 }
1852 
1853 static void
1854 vd_recv_msg(void *arg)
1855 {
1856 	vd_t	*vd = (vd_t *)arg;
1857 	int	status = 0;
1858 
1859 
1860 	ASSERT(vd != NULL);
1861 	PR2("New task to receive incoming message(s)");
1862 	while (vd_enabled(vd) && status == 0) {
1863 		size_t		msglen, msgsize;
1864 		vio_msg_t	*vio_msg;
1865 
1866 
1867 		/*
1868 		 * Receive and process a message
1869 		 */
1870 		vd_reset_if_needed(vd);	/* can change vd->max_msglen */
1871 		msgsize = vd->max_msglen;	/* stable copy for alloc/free */
1872 		msglen	= msgsize;	/* actual length after recv_msg() */
1873 		vio_msg = kmem_alloc(msgsize, KM_SLEEP);
1874 		if ((status = recv_msg(vd->ldc_handle, vio_msg, &msglen)) ==
1875 		    0) {
1876 			if (vd_process_msg(vd, vio_msg, msglen, msgsize) ==
1877 			    EINPROGRESS)
1878 				continue;	/* handler will free msg */
1879 		} else if (status != ENOMSG) {
1880 			/* Probably an LDC failure; arrange to reset it */
1881 			vd_need_reset(vd, B_TRUE);
1882 		}
1883 		kmem_free(vio_msg, msgsize);
1884 	}
1885 	PR2("Task finished");
1886 }
1887 
1888 static uint_t
1889 vd_handle_ldc_events(uint64_t event, caddr_t arg)
1890 {
1891 	vd_t	*vd = (vd_t *)(void *)arg;
1892 
1893 
1894 	ASSERT(vd != NULL);
1895 
1896 	if (!vd_enabled(vd))
1897 		return (LDC_SUCCESS);
1898 
1899 	if (event & LDC_EVT_RESET) {
1900 		PR0("LDC channel was reset");
1901 		return (LDC_SUCCESS);
1902 	}
1903 
1904 	if (event & LDC_EVT_UP) {
1905 		PR0("LDC channel came up:  Resetting client connection state");
1906 		vd_need_reset(vd, B_FALSE);
1907 	}
1908 
1909 	if (event & LDC_EVT_READ) {
1910 		int	status;
1911 
1912 		PR1("New data available");
1913 		/* Queue a task to receive the new data */
1914 		status = ddi_taskq_dispatch(vd->startq, vd_recv_msg, vd,
1915 		    DDI_SLEEP);
1916 		/* ddi_taskq_dispatch(9f) guarantees success with DDI_SLEEP */
1917 		ASSERT(status == DDI_SUCCESS);
1918 	}
1919 
1920 	return (LDC_SUCCESS);
1921 }
1922 
1923 static uint_t
1924 vds_check_for_vd(mod_hash_key_t key, mod_hash_val_t *val, void *arg)
1925 {
1926 	_NOTE(ARGUNUSED(key, val))
1927 	(*((uint_t *)arg))++;
1928 	return (MH_WALK_TERMINATE);
1929 }
1930 
1931 
1932 static int
1933 vds_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
1934 {
1935 	uint_t	vd_present = 0;
1936 	minor_t	instance;
1937 	vds_t	*vds;
1938 
1939 
1940 	switch (cmd) {
1941 	case DDI_DETACH:
1942 		/* the real work happens below */
1943 		break;
1944 	case DDI_SUSPEND:
1945 		PR0("No action required for DDI_SUSPEND");
1946 		return (DDI_SUCCESS);
1947 	default:
1948 		PRN("Unrecognized \"cmd\"");
1949 		return (DDI_FAILURE);
1950 	}
1951 
1952 	ASSERT(cmd == DDI_DETACH);
1953 	instance = ddi_get_instance(dip);
1954 	if ((vds = ddi_get_soft_state(vds_state, instance)) == NULL) {
1955 		PRN("Could not get state for instance %u", instance);
1956 		ddi_soft_state_free(vds_state, instance);
1957 		return (DDI_FAILURE);
1958 	}
1959 
1960 	/* Do no detach when serving any vdisks */
1961 	mod_hash_walk(vds->vd_table, vds_check_for_vd, &vd_present);
1962 	if (vd_present) {
1963 		PR0("Not detaching because serving vdisks");
1964 		return (DDI_FAILURE);
1965 	}
1966 
1967 	PR0("Detaching");
1968 	if (vds->initialized & VDS_MDEG)
1969 		(void) mdeg_unregister(vds->mdeg);
1970 	if (vds->initialized & VDS_LDI)
1971 		(void) ldi_ident_release(vds->ldi_ident);
1972 	mod_hash_destroy_hash(vds->vd_table);
1973 	ddi_soft_state_free(vds_state, instance);
1974 	return (DDI_SUCCESS);
1975 }
1976 
1977 static boolean_t
1978 is_pseudo_device(dev_info_t *dip)
1979 {
1980 	dev_info_t	*parent, *root = ddi_root_node();
1981 
1982 
1983 	for (parent = ddi_get_parent(dip); (parent != NULL) && (parent != root);
1984 	    parent = ddi_get_parent(parent)) {
1985 		if (strcmp(ddi_get_name(parent), DEVI_PSEUDO_NEXNAME) == 0)
1986 			return (B_TRUE);
1987 	}
1988 
1989 	return (B_FALSE);
1990 }
1991 
1992 static int
1993 vd_setup_full_disk(vd_t *vd)
1994 {
1995 	int		rval, status;
1996 	major_t		major = getmajor(vd->dev[0]);
1997 	minor_t		minor = getminor(vd->dev[0]) - VD_ENTIRE_DISK_SLICE;
1998 	struct dk_minfo	dk_minfo;
1999 
2000 	/*
2001 	 * At this point, vdisk_size is set to the size of partition 2 but
2002 	 * this does not represent the size of the disk because partition 2
2003 	 * may not cover the entire disk and its size does not include reserved
2004 	 * blocks. So we update vdisk_size to be the size of the entire disk.
2005 	 */
2006 	if ((status = ldi_ioctl(vd->ldi_handle[0], DKIOCGMEDIAINFO,
2007 	    (intptr_t)&dk_minfo, (vd_open_flags | FKIOCTL),
2008 	    kcred, &rval)) != 0) {
2009 		PRN("ldi_ioctl(DKIOCGMEDIAINFO) returned errno %d",
2010 		    status);
2011 		return (status);
2012 	}
2013 	vd->vdisk_size = dk_minfo.dki_capacity;
2014 
2015 	/* Set full-disk parameters */
2016 	vd->vdisk_type	= VD_DISK_TYPE_DISK;
2017 	vd->nslices	= (sizeof (vd->dev))/(sizeof (vd->dev[0]));
2018 
2019 	/* Move dev number and LDI handle to entire-disk-slice array elements */
2020 	vd->dev[VD_ENTIRE_DISK_SLICE]		= vd->dev[0];
2021 	vd->dev[0]				= 0;
2022 	vd->ldi_handle[VD_ENTIRE_DISK_SLICE]	= vd->ldi_handle[0];
2023 	vd->ldi_handle[0]			= NULL;
2024 
2025 	/* Initialize device numbers for remaining slices and open them */
2026 	for (int slice = 0; slice < vd->nslices; slice++) {
2027 		/*
2028 		 * Skip the entire-disk slice, as it's already open and its
2029 		 * device known
2030 		 */
2031 		if (slice == VD_ENTIRE_DISK_SLICE)
2032 			continue;
2033 		ASSERT(vd->dev[slice] == 0);
2034 		ASSERT(vd->ldi_handle[slice] == NULL);
2035 
2036 		/*
2037 		 * Construct the device number for the current slice
2038 		 */
2039 		vd->dev[slice] = makedevice(major, (minor + slice));
2040 
2041 		/*
2042 		 * At least some underlying drivers refuse to open
2043 		 * devices for (currently) zero-length slices, so skip
2044 		 * them for now
2045 		 */
2046 		if (vd->vtoc.v_part[slice].p_size == 0) {
2047 			PR0("Skipping zero-length slice %u", slice);
2048 			continue;
2049 		}
2050 
2051 		/*
2052 		 * Open all non-empty slices of the disk to serve them to the
2053 		 * client.  Slices are opened exclusively to prevent other
2054 		 * threads or processes in the service domain from performing
2055 		 * I/O to slices being accessed by a client.  Failure to open
2056 		 * a slice results in vds not serving this disk, as the client
2057 		 * could attempt (and should be able) to access any non-empty
2058 		 * slice immediately.  Any slices successfully opened before a
2059 		 * failure will get closed by vds_destroy_vd() as a result of
2060 		 * the error returned by this function.
2061 		 */
2062 		PR0("Opening device major %u, minor %u = slice %u",
2063 		    major, minor, slice);
2064 		if ((status = ldi_open_by_dev(&vd->dev[slice], OTYP_BLK,
2065 			    vd_open_flags, kcred, &vd->ldi_handle[slice],
2066 			    vd->vds->ldi_ident)) != 0) {
2067 			PRN("ldi_open_by_dev() returned errno %d "
2068 			    "for slice %u", status, slice);
2069 			/* vds_destroy_vd() will close any open slices */
2070 			return (status);
2071 		}
2072 	}
2073 
2074 	return (0);
2075 }
2076 
2077 static int
2078 vd_setup_partition_efi(vd_t *vd)
2079 {
2080 	efi_gpt_t *gpt;
2081 	efi_gpe_t *gpe;
2082 	struct uuid uuid = EFI_RESERVED;
2083 	uint32_t crc;
2084 	int length;
2085 
2086 	length = sizeof (efi_gpt_t) + sizeof (efi_gpe_t);
2087 
2088 	gpt = kmem_zalloc(length, KM_SLEEP);
2089 	gpe = (efi_gpe_t *)(gpt + 1);
2090 
2091 	gpt->efi_gpt_Signature = LE_64(EFI_SIGNATURE);
2092 	gpt->efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
2093 	gpt->efi_gpt_HeaderSize = LE_32(sizeof (efi_gpt_t));
2094 	gpt->efi_gpt_FirstUsableLBA = LE_64(0ULL);
2095 	gpt->efi_gpt_LastUsableLBA = LE_64(vd->vdisk_size - 1);
2096 	gpt->efi_gpt_NumberOfPartitionEntries = LE_32(1);
2097 	gpt->efi_gpt_SizeOfPartitionEntry = LE_32(sizeof (efi_gpe_t));
2098 
2099 	UUID_LE_CONVERT(gpe->efi_gpe_PartitionTypeGUID, uuid);
2100 	gpe->efi_gpe_StartingLBA = gpt->efi_gpt_FirstUsableLBA;
2101 	gpe->efi_gpe_EndingLBA = gpt->efi_gpt_LastUsableLBA;
2102 
2103 	CRC32(crc, gpe, sizeof (efi_gpe_t), -1U, crc32_table);
2104 	gpt->efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
2105 
2106 	CRC32(crc, gpt, sizeof (efi_gpt_t), -1U, crc32_table);
2107 	gpt->efi_gpt_HeaderCRC32 = LE_32(~crc);
2108 
2109 	vd->dk_efi.dki_lba = 0;
2110 	vd->dk_efi.dki_length = length;
2111 	vd->dk_efi.dki_data = gpt;
2112 
2113 	return (0);
2114 }
2115 
2116 static int
2117 vd_setup_vd(char *device_path, vd_t *vd)
2118 {
2119 	int		rval, status;
2120 	dev_info_t	*dip;
2121 	struct dk_cinfo	dk_cinfo;
2122 
2123 	/*
2124 	 * We need to open with FNDELAY so that opening an empty partition
2125 	 * does not fail.
2126 	 */
2127 	if ((status = ldi_open_by_name(device_path, vd_open_flags | FNDELAY,
2128 	    kcred, &vd->ldi_handle[0], vd->vds->ldi_ident)) != 0) {
2129 		PRN("ldi_open_by_name(%s) = errno %d", device_path, status);
2130 		return (status);
2131 	}
2132 
2133 	/*
2134 	 * nslices must be updated now so that vds_destroy_vd() will close
2135 	 * the slice we have just opened in case of an error.
2136 	 */
2137 	vd->nslices = 1;
2138 
2139 	/* Get device number and size of backing device */
2140 	if ((status = ldi_get_dev(vd->ldi_handle[0], &vd->dev[0])) != 0) {
2141 		PRN("ldi_get_dev() returned errno %d for %s",
2142 		    status, device_path);
2143 		return (status);
2144 	}
2145 	if (ldi_get_size(vd->ldi_handle[0], &vd->vdisk_size) != DDI_SUCCESS) {
2146 		PRN("ldi_get_size() failed for %s", device_path);
2147 		return (EIO);
2148 	}
2149 	vd->vdisk_size = lbtodb(vd->vdisk_size);	/* convert to blocks */
2150 
2151 	/* Verify backing device supports dk_cinfo, dk_geom, and vtoc */
2152 	if ((status = ldi_ioctl(vd->ldi_handle[0], DKIOCINFO,
2153 		    (intptr_t)&dk_cinfo, (vd_open_flags | FKIOCTL), kcred,
2154 		    &rval)) != 0) {
2155 		PRN("ldi_ioctl(DKIOCINFO) returned errno %d for %s",
2156 		    status, device_path);
2157 		return (status);
2158 	}
2159 	if (dk_cinfo.dki_partition >= V_NUMPAR) {
2160 		PRN("slice %u >= maximum slice %u for %s",
2161 		    dk_cinfo.dki_partition, V_NUMPAR, device_path);
2162 		return (EIO);
2163 	}
2164 
2165 	status = vd_read_vtoc(vd->ldi_handle[0], &vd->vtoc, &vd->vdisk_label);
2166 
2167 	if (status != 0) {
2168 		PRN("vd_read_vtoc returned errno %d for %s",
2169 		    status, device_path);
2170 		return (status);
2171 	}
2172 
2173 	if (vd->vdisk_label == VD_DISK_LABEL_VTOC &&
2174 	    (status = ldi_ioctl(vd->ldi_handle[0], DKIOCGGEOM,
2175 	    (intptr_t)&vd->dk_geom, (vd_open_flags | FKIOCTL),
2176 	    kcred, &rval)) != 0) {
2177 		    PRN("ldi_ioctl(DKIOCGEOM) returned errno %d for %s",
2178 			status, device_path);
2179 		    return (status);
2180 	}
2181 
2182 	/* Store the device's max transfer size for return to the client */
2183 	vd->max_xfer_sz = dk_cinfo.dki_maxtransfer;
2184 
2185 
2186 	/* Determine if backing device is a pseudo device */
2187 	if ((dip = ddi_hold_devi_by_instance(getmajor(vd->dev[0]),
2188 		    dev_to_instance(vd->dev[0]), 0))  == NULL) {
2189 		PRN("%s is no longer accessible", device_path);
2190 		return (EIO);
2191 	}
2192 	vd->pseudo = is_pseudo_device(dip);
2193 	ddi_release_devi(dip);
2194 	if (vd->pseudo) {
2195 		vd->vdisk_type	= VD_DISK_TYPE_SLICE;
2196 		vd->nslices	= 1;
2197 		return (0);	/* ...and we're done */
2198 	}
2199 
2200 
2201 	/* If slice is entire-disk slice, initialize for full disk */
2202 	if (dk_cinfo.dki_partition == VD_ENTIRE_DISK_SLICE)
2203 		return (vd_setup_full_disk(vd));
2204 
2205 
2206 	/* Otherwise, we have a non-entire slice of a device */
2207 	vd->vdisk_type	= VD_DISK_TYPE_SLICE;
2208 	vd->nslices	= 1;
2209 
2210 	if (vd->vdisk_label == VD_DISK_LABEL_EFI) {
2211 		status = vd_setup_partition_efi(vd);
2212 		return (status);
2213 	}
2214 
2215 	/* Initialize dk_geom structure for single-slice device */
2216 	if (vd->dk_geom.dkg_nsect == 0) {
2217 		PRN("%s geometry claims 0 sectors per track", device_path);
2218 		return (EIO);
2219 	}
2220 	if (vd->dk_geom.dkg_nhead == 0) {
2221 		PRN("%s geometry claims 0 heads", device_path);
2222 		return (EIO);
2223 	}
2224 	vd->dk_geom.dkg_ncyl =
2225 	    vd->vdisk_size/vd->dk_geom.dkg_nsect/vd->dk_geom.dkg_nhead;
2226 	vd->dk_geom.dkg_acyl = 0;
2227 	vd->dk_geom.dkg_pcyl = vd->dk_geom.dkg_ncyl + vd->dk_geom.dkg_acyl;
2228 
2229 
2230 	/* Initialize vtoc structure for single-slice device */
2231 	bcopy(VD_VOLUME_NAME, vd->vtoc.v_volume,
2232 	    MIN(sizeof (VD_VOLUME_NAME), sizeof (vd->vtoc.v_volume)));
2233 	bzero(vd->vtoc.v_part, sizeof (vd->vtoc.v_part));
2234 	vd->vtoc.v_nparts = 1;
2235 	vd->vtoc.v_part[0].p_tag = V_UNASSIGNED;
2236 	vd->vtoc.v_part[0].p_flag = 0;
2237 	vd->vtoc.v_part[0].p_start = 0;
2238 	vd->vtoc.v_part[0].p_size = vd->vdisk_size;
2239 	bcopy(VD_ASCIILABEL, vd->vtoc.v_asciilabel,
2240 	    MIN(sizeof (VD_ASCIILABEL), sizeof (vd->vtoc.v_asciilabel)));
2241 
2242 
2243 	return (0);
2244 }
2245 
2246 static int
2247 vds_do_init_vd(vds_t *vds, uint64_t id, char *device_path, uint64_t ldc_id,
2248     vd_t **vdp)
2249 {
2250 	char			tq_name[TASKQ_NAMELEN];
2251 	int			status;
2252 	ddi_iblock_cookie_t	iblock = NULL;
2253 	ldc_attr_t		ldc_attr;
2254 	vd_t			*vd;
2255 
2256 
2257 	ASSERT(vds != NULL);
2258 	ASSERT(device_path != NULL);
2259 	ASSERT(vdp != NULL);
2260 	PR0("Adding vdisk for %s", device_path);
2261 
2262 	if ((vd = kmem_zalloc(sizeof (*vd), KM_NOSLEEP)) == NULL) {
2263 		PRN("No memory for virtual disk");
2264 		return (EAGAIN);
2265 	}
2266 	*vdp = vd;	/* assign here so vds_destroy_vd() can cleanup later */
2267 	vd->vds = vds;
2268 
2269 
2270 	/* Open vdisk and initialize parameters */
2271 	if ((status = vd_setup_vd(device_path, vd)) != 0)
2272 		return (status);
2273 	ASSERT(vd->nslices > 0 && vd->nslices <= V_NUMPAR);
2274 	PR0("vdisk_type = %s, pseudo = %s, nslices = %u",
2275 	    ((vd->vdisk_type == VD_DISK_TYPE_DISK) ? "disk" : "slice"),
2276 	    (vd->pseudo ? "yes" : "no"), vd->nslices);
2277 
2278 
2279 	/* Initialize locking */
2280 	if (ddi_get_soft_iblock_cookie(vds->dip, DDI_SOFTINT_MED,
2281 		&iblock) != DDI_SUCCESS) {
2282 		PRN("Could not get iblock cookie.");
2283 		return (EIO);
2284 	}
2285 
2286 	mutex_init(&vd->lock, NULL, MUTEX_DRIVER, iblock);
2287 	vd->initialized |= VD_LOCKING;
2288 
2289 
2290 	/* Create start and completion task queues for the vdisk */
2291 	(void) snprintf(tq_name, sizeof (tq_name), "vd_startq%lu", id);
2292 	PR1("tq_name = %s", tq_name);
2293 	if ((vd->startq = ddi_taskq_create(vds->dip, tq_name, 1,
2294 		    TASKQ_DEFAULTPRI, 0)) == NULL) {
2295 		PRN("Could not create task queue");
2296 		return (EIO);
2297 	}
2298 	(void) snprintf(tq_name, sizeof (tq_name), "vd_completionq%lu", id);
2299 	PR1("tq_name = %s", tq_name);
2300 	if ((vd->completionq = ddi_taskq_create(vds->dip, tq_name, 1,
2301 		    TASKQ_DEFAULTPRI, 0)) == NULL) {
2302 		PRN("Could not create task queue");
2303 		return (EIO);
2304 	}
2305 	vd->enabled = 1;	/* before callback can dispatch to startq */
2306 
2307 
2308 	/* Bring up LDC */
2309 	ldc_attr.devclass	= LDC_DEV_BLK_SVC;
2310 	ldc_attr.instance	= ddi_get_instance(vds->dip);
2311 	ldc_attr.mode		= LDC_MODE_UNRELIABLE;
2312 	ldc_attr.mtu		= VD_LDC_MTU;
2313 	if ((status = ldc_init(ldc_id, &ldc_attr, &vd->ldc_handle)) != 0) {
2314 		PRN("ldc_init(%lu) = errno %d", ldc_id, status);
2315 		return (status);
2316 	}
2317 	vd->initialized |= VD_LDC;
2318 
2319 	if ((status = ldc_reg_callback(vd->ldc_handle, vd_handle_ldc_events,
2320 		(caddr_t)vd)) != 0) {
2321 		PRN("ldc_reg_callback() returned errno %d", status);
2322 		return (status);
2323 	}
2324 
2325 	if ((status = ldc_open(vd->ldc_handle)) != 0) {
2326 		PRN("ldc_open() returned errno %d", status);
2327 		return (status);
2328 	}
2329 
2330 	/* Allocate the inband task memory handle */
2331 	status = ldc_mem_alloc_handle(vd->ldc_handle, &(vd->inband_task.mhdl));
2332 	if (status) {
2333 		PRN("ldc_mem_alloc_handle() returned err %d ", status);
2334 		return (ENXIO);
2335 	}
2336 
2337 	/* Add the successfully-initialized vdisk to the server's table */
2338 	if (mod_hash_insert(vds->vd_table, (mod_hash_key_t)id, vd) != 0) {
2339 		PRN("Error adding vdisk ID %lu to table", id);
2340 		return (EIO);
2341 	}
2342 
2343 	return (0);
2344 }
2345 
2346 /*
2347  * Destroy the state associated with a virtual disk
2348  */
2349 static void
2350 vds_destroy_vd(void *arg)
2351 {
2352 	vd_t	*vd = (vd_t *)arg;
2353 
2354 
2355 	if (vd == NULL)
2356 		return;
2357 
2358 	PR0("Destroying vdisk state");
2359 
2360 	if (vd->dk_efi.dki_data != NULL)
2361 		kmem_free(vd->dk_efi.dki_data, vd->dk_efi.dki_length);
2362 
2363 	/* Disable queuing requests for the vdisk */
2364 	if (vd->initialized & VD_LOCKING) {
2365 		mutex_enter(&vd->lock);
2366 		vd->enabled = 0;
2367 		mutex_exit(&vd->lock);
2368 	}
2369 
2370 	/* Drain and destroy start queue (*before* destroying completionq) */
2371 	if (vd->startq != NULL)
2372 		ddi_taskq_destroy(vd->startq);	/* waits for queued tasks */
2373 
2374 	/* Drain and destroy completion queue (*before* shutting down LDC) */
2375 	if (vd->completionq != NULL)
2376 		ddi_taskq_destroy(vd->completionq);	/* waits for tasks */
2377 
2378 	if (vd->dring_task != NULL) {
2379 		ASSERT(vd->dring_len != 0);
2380 		/* Free all dring_task memory handles */
2381 		for (int i = 0; i < vd->dring_len; i++)
2382 			(void) ldc_mem_free_handle(vd->dring_task[i].mhdl);
2383 		kmem_free(vd->dring_task,
2384 		    (sizeof (*vd->dring_task)) * vd->dring_len);
2385 	}
2386 
2387 	/* Free the inband task memory handle */
2388 	(void) ldc_mem_free_handle(vd->inband_task.mhdl);
2389 
2390 	/* Shut down LDC */
2391 	if (vd->initialized & VD_LDC) {
2392 		if (vd->initialized & VD_DRING)
2393 			(void) ldc_mem_dring_unmap(vd->dring_handle);
2394 		(void) ldc_unreg_callback(vd->ldc_handle);
2395 		(void) ldc_close(vd->ldc_handle);
2396 		(void) ldc_fini(vd->ldc_handle);
2397 	}
2398 
2399 	/* Close any open backing-device slices */
2400 	for (uint_t slice = 0; slice < vd->nslices; slice++) {
2401 		if (vd->ldi_handle[slice] != NULL) {
2402 			PR0("Closing slice %u", slice);
2403 			(void) ldi_close(vd->ldi_handle[slice],
2404 			    vd_open_flags | FNDELAY, kcred);
2405 		}
2406 	}
2407 
2408 	/* Free lock */
2409 	if (vd->initialized & VD_LOCKING)
2410 		mutex_destroy(&vd->lock);
2411 
2412 	/* Finally, free the vdisk structure itself */
2413 	kmem_free(vd, sizeof (*vd));
2414 }
2415 
2416 static int
2417 vds_init_vd(vds_t *vds, uint64_t id, char *device_path, uint64_t ldc_id)
2418 {
2419 	int	status;
2420 	vd_t	*vd = NULL;
2421 
2422 
2423 #ifdef lint
2424 	(void) vd;
2425 #endif	/* lint */
2426 
2427 	if ((status = vds_do_init_vd(vds, id, device_path, ldc_id, &vd)) != 0)
2428 		vds_destroy_vd(vd);
2429 
2430 	return (status);
2431 }
2432 
2433 static int
2434 vds_do_get_ldc_id(md_t *md, mde_cookie_t vd_node, mde_cookie_t *channel,
2435     uint64_t *ldc_id)
2436 {
2437 	int	num_channels;
2438 
2439 
2440 	/* Look for channel endpoint child(ren) of the vdisk MD node */
2441 	if ((num_channels = md_scan_dag(md, vd_node,
2442 		    md_find_name(md, VD_CHANNEL_ENDPOINT),
2443 		    md_find_name(md, "fwd"), channel)) <= 0) {
2444 		PRN("No \"%s\" found for virtual disk", VD_CHANNEL_ENDPOINT);
2445 		return (-1);
2446 	}
2447 
2448 	/* Get the "id" value for the first channel endpoint node */
2449 	if (md_get_prop_val(md, channel[0], VD_ID_PROP, ldc_id) != 0) {
2450 		PRN("No \"%s\" property found for \"%s\" of vdisk",
2451 		    VD_ID_PROP, VD_CHANNEL_ENDPOINT);
2452 		return (-1);
2453 	}
2454 
2455 	if (num_channels > 1) {
2456 		PRN("Using ID of first of multiple channels for this vdisk");
2457 	}
2458 
2459 	return (0);
2460 }
2461 
2462 static int
2463 vds_get_ldc_id(md_t *md, mde_cookie_t vd_node, uint64_t *ldc_id)
2464 {
2465 	int		num_nodes, status;
2466 	size_t		size;
2467 	mde_cookie_t	*channel;
2468 
2469 
2470 	if ((num_nodes = md_node_count(md)) <= 0) {
2471 		PRN("Invalid node count in Machine Description subtree");
2472 		return (-1);
2473 	}
2474 	size = num_nodes*(sizeof (*channel));
2475 	channel = kmem_zalloc(size, KM_SLEEP);
2476 	status = vds_do_get_ldc_id(md, vd_node, channel, ldc_id);
2477 	kmem_free(channel, size);
2478 
2479 	return (status);
2480 }
2481 
2482 static void
2483 vds_add_vd(vds_t *vds, md_t *md, mde_cookie_t vd_node)
2484 {
2485 	char		*device_path = NULL;
2486 	uint64_t	id = 0, ldc_id = 0;
2487 
2488 
2489 	if (md_get_prop_val(md, vd_node, VD_ID_PROP, &id) != 0) {
2490 		PRN("Error getting vdisk \"%s\"", VD_ID_PROP);
2491 		return;
2492 	}
2493 	PR0("Adding vdisk ID %lu", id);
2494 	if (md_get_prop_str(md, vd_node, VD_BLOCK_DEVICE_PROP,
2495 		&device_path) != 0) {
2496 		PRN("Error getting vdisk \"%s\"", VD_BLOCK_DEVICE_PROP);
2497 		return;
2498 	}
2499 
2500 	if (vds_get_ldc_id(md, vd_node, &ldc_id) != 0) {
2501 		PRN("Error getting LDC ID for vdisk %lu", id);
2502 		return;
2503 	}
2504 
2505 	if (vds_init_vd(vds, id, device_path, ldc_id) != 0) {
2506 		PRN("Failed to add vdisk ID %lu", id);
2507 		return;
2508 	}
2509 }
2510 
2511 static void
2512 vds_remove_vd(vds_t *vds, md_t *md, mde_cookie_t vd_node)
2513 {
2514 	uint64_t	id = 0;
2515 
2516 
2517 	if (md_get_prop_val(md, vd_node, VD_ID_PROP, &id) != 0) {
2518 		PRN("Unable to get \"%s\" property from vdisk's MD node",
2519 		    VD_ID_PROP);
2520 		return;
2521 	}
2522 	PR0("Removing vdisk ID %lu", id);
2523 	if (mod_hash_destroy(vds->vd_table, (mod_hash_key_t)id) != 0)
2524 		PRN("No vdisk entry found for vdisk ID %lu", id);
2525 }
2526 
2527 static void
2528 vds_change_vd(vds_t *vds, md_t *prev_md, mde_cookie_t prev_vd_node,
2529     md_t *curr_md, mde_cookie_t curr_vd_node)
2530 {
2531 	char		*curr_dev, *prev_dev;
2532 	uint64_t	curr_id = 0, curr_ldc_id = 0;
2533 	uint64_t	prev_id = 0, prev_ldc_id = 0;
2534 	size_t		len;
2535 
2536 
2537 	/* Validate that vdisk ID has not changed */
2538 	if (md_get_prop_val(prev_md, prev_vd_node, VD_ID_PROP, &prev_id) != 0) {
2539 		PRN("Error getting previous vdisk \"%s\" property",
2540 		    VD_ID_PROP);
2541 		return;
2542 	}
2543 	if (md_get_prop_val(curr_md, curr_vd_node, VD_ID_PROP, &curr_id) != 0) {
2544 		PRN("Error getting current vdisk \"%s\" property", VD_ID_PROP);
2545 		return;
2546 	}
2547 	if (curr_id != prev_id) {
2548 		PRN("Not changing vdisk:  ID changed from %lu to %lu",
2549 		    prev_id, curr_id);
2550 		return;
2551 	}
2552 
2553 	/* Validate that LDC ID has not changed */
2554 	if (vds_get_ldc_id(prev_md, prev_vd_node, &prev_ldc_id) != 0) {
2555 		PRN("Error getting LDC ID for vdisk %lu", prev_id);
2556 		return;
2557 	}
2558 
2559 	if (vds_get_ldc_id(curr_md, curr_vd_node, &curr_ldc_id) != 0) {
2560 		PRN("Error getting LDC ID for vdisk %lu", curr_id);
2561 		return;
2562 	}
2563 	if (curr_ldc_id != prev_ldc_id) {
2564 		_NOTE(NOTREACHED);	/* lint is confused */
2565 		PRN("Not changing vdisk:  "
2566 		    "LDC ID changed from %lu to %lu", prev_ldc_id, curr_ldc_id);
2567 		return;
2568 	}
2569 
2570 	/* Determine whether device path has changed */
2571 	if (md_get_prop_str(prev_md, prev_vd_node, VD_BLOCK_DEVICE_PROP,
2572 		&prev_dev) != 0) {
2573 		PRN("Error getting previous vdisk \"%s\"",
2574 		    VD_BLOCK_DEVICE_PROP);
2575 		return;
2576 	}
2577 	if (md_get_prop_str(curr_md, curr_vd_node, VD_BLOCK_DEVICE_PROP,
2578 		&curr_dev) != 0) {
2579 		PRN("Error getting current vdisk \"%s\"", VD_BLOCK_DEVICE_PROP);
2580 		return;
2581 	}
2582 	if (((len = strlen(curr_dev)) == strlen(prev_dev)) &&
2583 	    (strncmp(curr_dev, prev_dev, len) == 0))
2584 		return;	/* no relevant (supported) change */
2585 
2586 	PR0("Changing vdisk ID %lu", prev_id);
2587 	/* Remove old state, which will close vdisk and reset */
2588 	if (mod_hash_destroy(vds->vd_table, (mod_hash_key_t)prev_id) != 0)
2589 		PRN("No entry found for vdisk ID %lu", prev_id);
2590 	/* Re-initialize vdisk with new state */
2591 	if (vds_init_vd(vds, curr_id, curr_dev, curr_ldc_id) != 0) {
2592 		PRN("Failed to change vdisk ID %lu", curr_id);
2593 		return;
2594 	}
2595 }
2596 
2597 static int
2598 vds_process_md(void *arg, mdeg_result_t *md)
2599 {
2600 	int	i;
2601 	vds_t	*vds = arg;
2602 
2603 
2604 	if (md == NULL)
2605 		return (MDEG_FAILURE);
2606 	ASSERT(vds != NULL);
2607 
2608 	for (i = 0; i < md->removed.nelem; i++)
2609 		vds_remove_vd(vds, md->removed.mdp, md->removed.mdep[i]);
2610 	for (i = 0; i < md->match_curr.nelem; i++)
2611 		vds_change_vd(vds, md->match_prev.mdp, md->match_prev.mdep[i],
2612 		    md->match_curr.mdp, md->match_curr.mdep[i]);
2613 	for (i = 0; i < md->added.nelem; i++)
2614 		vds_add_vd(vds, md->added.mdp, md->added.mdep[i]);
2615 
2616 	return (MDEG_SUCCESS);
2617 }
2618 
2619 static int
2620 vds_do_attach(dev_info_t *dip)
2621 {
2622 	static char	reg_prop[] = "reg";	/* devinfo ID prop */
2623 
2624 	/* MDEG specification for a (particular) vds node */
2625 	static mdeg_prop_spec_t	vds_prop_spec[] = {
2626 		{MDET_PROP_STR, "name", {VDS_NAME}},
2627 		{MDET_PROP_VAL, "cfg-handle", {0}},
2628 		{MDET_LIST_END, NULL, {0}}};
2629 	static mdeg_node_spec_t	vds_spec = {"virtual-device", vds_prop_spec};
2630 
2631 	/* MDEG specification for matching a vd node */
2632 	static md_prop_match_t	vd_prop_spec[] = {
2633 		{MDET_PROP_VAL, VD_ID_PROP},
2634 		{MDET_LIST_END, NULL}};
2635 	static mdeg_node_match_t vd_spec = {"virtual-device-port",
2636 					    vd_prop_spec};
2637 
2638 	int			status;
2639 	uint64_t		cfg_handle;
2640 	minor_t			instance = ddi_get_instance(dip);
2641 	vds_t			*vds;
2642 
2643 
2644 	/*
2645 	 * The "cfg-handle" property of a vds node in an MD contains the MD's
2646 	 * notion of "instance", or unique identifier, for that node; OBP
2647 	 * stores the value of the "cfg-handle" MD property as the value of
2648 	 * the "reg" property on the node in the device tree it builds from
2649 	 * the MD and passes to Solaris.  Thus, we look up the devinfo node's
2650 	 * "reg" property value to uniquely identify this device instance when
2651 	 * registering with the MD event-generation framework.  If the "reg"
2652 	 * property cannot be found, the device tree state is presumably so
2653 	 * broken that there is no point in continuing.
2654 	 */
2655 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, reg_prop)) {
2656 		PRN("vds \"%s\" property does not exist", reg_prop);
2657 		return (DDI_FAILURE);
2658 	}
2659 
2660 	/* Get the MD instance for later MDEG registration */
2661 	cfg_handle = ddi_prop_get_int(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
2662 	    reg_prop, -1);
2663 
2664 	if (ddi_soft_state_zalloc(vds_state, instance) != DDI_SUCCESS) {
2665 		PRN("Could not allocate state for instance %u", instance);
2666 		return (DDI_FAILURE);
2667 	}
2668 
2669 	if ((vds = ddi_get_soft_state(vds_state, instance)) == NULL) {
2670 		PRN("Could not get state for instance %u", instance);
2671 		ddi_soft_state_free(vds_state, instance);
2672 		return (DDI_FAILURE);
2673 	}
2674 
2675 
2676 	vds->dip	= dip;
2677 	vds->vd_table	= mod_hash_create_ptrhash("vds_vd_table", VDS_NCHAINS,
2678 							vds_destroy_vd,
2679 							sizeof (void *));
2680 	ASSERT(vds->vd_table != NULL);
2681 
2682 	if ((status = ldi_ident_from_dip(dip, &vds->ldi_ident)) != 0) {
2683 		PRN("ldi_ident_from_dip() returned errno %d", status);
2684 		return (DDI_FAILURE);
2685 	}
2686 	vds->initialized |= VDS_LDI;
2687 
2688 	/* Register for MD updates */
2689 	vds_prop_spec[1].ps_val = cfg_handle;
2690 	if (mdeg_register(&vds_spec, &vd_spec, vds_process_md, vds,
2691 		&vds->mdeg) != MDEG_SUCCESS) {
2692 		PRN("Unable to register for MD updates");
2693 		return (DDI_FAILURE);
2694 	}
2695 	vds->initialized |= VDS_MDEG;
2696 
2697 	/* Prevent auto-detaching so driver is available whenever MD changes */
2698 	if (ddi_prop_update_int(DDI_DEV_T_NONE, dip, DDI_NO_AUTODETACH, 1) !=
2699 	    DDI_PROP_SUCCESS) {
2700 		PRN("failed to set \"%s\" property for instance %u",
2701 		    DDI_NO_AUTODETACH, instance);
2702 	}
2703 
2704 	ddi_report_dev(dip);
2705 	return (DDI_SUCCESS);
2706 }
2707 
2708 static int
2709 vds_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
2710 {
2711 	int	status;
2712 
2713 	switch (cmd) {
2714 	case DDI_ATTACH:
2715 		PR0("Attaching");
2716 		if ((status = vds_do_attach(dip)) != DDI_SUCCESS)
2717 			(void) vds_detach(dip, DDI_DETACH);
2718 		return (status);
2719 	case DDI_RESUME:
2720 		PR0("No action required for DDI_RESUME");
2721 		return (DDI_SUCCESS);
2722 	default:
2723 		return (DDI_FAILURE);
2724 	}
2725 }
2726 
2727 static struct dev_ops vds_ops = {
2728 	DEVO_REV,	/* devo_rev */
2729 	0,		/* devo_refcnt */
2730 	ddi_no_info,	/* devo_getinfo */
2731 	nulldev,	/* devo_identify */
2732 	nulldev,	/* devo_probe */
2733 	vds_attach,	/* devo_attach */
2734 	vds_detach,	/* devo_detach */
2735 	nodev,		/* devo_reset */
2736 	NULL,		/* devo_cb_ops */
2737 	NULL,		/* devo_bus_ops */
2738 	nulldev		/* devo_power */
2739 };
2740 
2741 static struct modldrv modldrv = {
2742 	&mod_driverops,
2743 	"virtual disk server v%I%",
2744 	&vds_ops,
2745 };
2746 
2747 static struct modlinkage modlinkage = {
2748 	MODREV_1,
2749 	&modldrv,
2750 	NULL
2751 };
2752 
2753 
2754 int
2755 _init(void)
2756 {
2757 	int		i, status;
2758 
2759 
2760 	if ((status = ddi_soft_state_init(&vds_state, sizeof (vds_t), 1)) != 0)
2761 		return (status);
2762 	if ((status = mod_install(&modlinkage)) != 0) {
2763 		ddi_soft_state_fini(&vds_state);
2764 		return (status);
2765 	}
2766 
2767 	/* Fill in the bit-mask of server-supported operations */
2768 	for (i = 0; i < vds_noperations; i++)
2769 		vds_operations |= 1 << (vds_operation[i].operation - 1);
2770 
2771 	return (0);
2772 }
2773 
2774 int
2775 _info(struct modinfo *modinfop)
2776 {
2777 	return (mod_info(&modlinkage, modinfop));
2778 }
2779 
2780 int
2781 _fini(void)
2782 {
2783 	int	status;
2784 
2785 
2786 	if ((status = mod_remove(&modlinkage)) != 0)
2787 		return (status);
2788 	ddi_soft_state_fini(&vds_state);
2789 	return (0);
2790 }
2791