xref: /titanic_44/usr/src/uts/sun4v/io/vdc.c (revision 7752631cb397da3298ed0b30d6bfee48679c340f)
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 2007 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  * LDoms virtual disk client (vdc) device driver
31  *
32  * This driver runs on a guest logical domain and communicates with the virtual
33  * disk server (vds) driver running on the service domain which is exporting
34  * virtualized "disks" to the guest logical domain.
35  *
36  * The driver can be divided into four sections:
37  *
38  * 1) generic device driver housekeeping
39  *	_init, _fini, attach, detach, ops structures, etc.
40  *
41  * 2) communication channel setup
42  *	Setup the communications link over the LDC channel that vdc uses to
43  *	talk to the vDisk server. Initialise the descriptor ring which
44  *	allows the LDC clients to transfer data via memory mappings.
45  *
46  * 3) Support exported to upper layers (filesystems, etc)
47  *	The upper layers call into vdc via strategy(9E) and DKIO(7I)
48  *	ioctl calls. vdc will copy the data to be written to the descriptor
49  *	ring or maps the buffer to store the data read by the vDisk
50  *	server into the descriptor ring. It then sends a message to the
51  *	vDisk server requesting it to complete the operation.
52  *
53  * 4) Handling responses from vDisk server.
54  *	The vDisk server will ACK some or all of the messages vdc sends to it
55  *	(this is configured during the handshake). Upon receipt of an ACK
56  *	vdc will check the descriptor ring and signal to the upper layer
57  *	code waiting on the IO.
58  */
59 
60 #include <sys/atomic.h>
61 #include <sys/conf.h>
62 #include <sys/disp.h>
63 #include <sys/ddi.h>
64 #include <sys/dkio.h>
65 #include <sys/efi_partition.h>
66 #include <sys/fcntl.h>
67 #include <sys/file.h>
68 #include <sys/mach_descrip.h>
69 #include <sys/modctl.h>
70 #include <sys/mdeg.h>
71 #include <sys/note.h>
72 #include <sys/open.h>
73 #include <sys/sdt.h>
74 #include <sys/stat.h>
75 #include <sys/sunddi.h>
76 #include <sys/types.h>
77 #include <sys/promif.h>
78 #include <sys/vtoc.h>
79 #include <sys/archsystm.h>
80 #include <sys/sysmacros.h>
81 
82 #include <sys/cdio.h>
83 #include <sys/dktp/fdisk.h>
84 #include <sys/scsi/generic/sense.h>
85 #include <sys/scsi/impl/uscsi.h>	/* Needed for defn of USCSICMD ioctl */
86 
87 #include <sys/ldoms.h>
88 #include <sys/ldc.h>
89 #include <sys/vio_common.h>
90 #include <sys/vio_mailbox.h>
91 #include <sys/vdsk_common.h>
92 #include <sys/vdsk_mailbox.h>
93 #include <sys/vdc.h>
94 
95 /*
96  * function prototypes
97  */
98 
99 /* standard driver functions */
100 static int	vdc_open(dev_t *dev, int flag, int otyp, cred_t *cred);
101 static int	vdc_close(dev_t dev, int flag, int otyp, cred_t *cred);
102 static int	vdc_strategy(struct buf *buf);
103 static int	vdc_print(dev_t dev, char *str);
104 static int	vdc_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
105 static int	vdc_read(dev_t dev, struct uio *uio, cred_t *cred);
106 static int	vdc_write(dev_t dev, struct uio *uio, cred_t *cred);
107 static int	vdc_ioctl(dev_t dev, int cmd, intptr_t arg, int mode,
108 			cred_t *credp, int *rvalp);
109 static int	vdc_aread(dev_t dev, struct aio_req *aio, cred_t *cred);
110 static int	vdc_awrite(dev_t dev, struct aio_req *aio, cred_t *cred);
111 
112 static int	vdc_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd,
113 			void *arg, void **resultp);
114 static int	vdc_attach(dev_info_t *dip, ddi_attach_cmd_t cmd);
115 static int	vdc_detach(dev_info_t *dip, ddi_detach_cmd_t cmd);
116 
117 /* setup */
118 static void	vdc_min(struct buf *bufp);
119 static int	vdc_send(vdc_t *vdc, caddr_t pkt, size_t *msglen);
120 static int	vdc_do_ldc_init(vdc_t *vdc);
121 static int	vdc_start_ldc_connection(vdc_t *vdc);
122 static int	vdc_create_device_nodes(vdc_t *vdc);
123 static int	vdc_create_device_nodes_efi(vdc_t *vdc);
124 static int	vdc_create_device_nodes_vtoc(vdc_t *vdc);
125 static int	vdc_create_device_nodes_props(vdc_t *vdc);
126 static int	vdc_get_ldc_id(dev_info_t *dip, uint64_t *ldc_id);
127 static int	vdc_do_ldc_up(vdc_t *vdc);
128 static void	vdc_terminate_ldc(vdc_t *vdc);
129 static int	vdc_init_descriptor_ring(vdc_t *vdc);
130 static void	vdc_destroy_descriptor_ring(vdc_t *vdc);
131 static int	vdc_setup_devid(vdc_t *vdc);
132 static void	vdc_store_efi(vdc_t *vdc, struct dk_gpt *efi);
133 
134 /* handshake with vds */
135 static int		vdc_init_ver_negotiation(vdc_t *vdc, vio_ver_t ver);
136 static int		vdc_ver_negotiation(vdc_t *vdcp);
137 static int		vdc_init_attr_negotiation(vdc_t *vdc);
138 static int		vdc_attr_negotiation(vdc_t *vdcp);
139 static int		vdc_init_dring_negotiate(vdc_t *vdc);
140 static int		vdc_dring_negotiation(vdc_t *vdcp);
141 static int		vdc_send_rdx(vdc_t *vdcp);
142 static int		vdc_rdx_exchange(vdc_t *vdcp);
143 static boolean_t	vdc_is_supported_version(vio_ver_msg_t *ver_msg);
144 
145 /* processing incoming messages from vDisk server */
146 static void	vdc_process_msg_thread(vdc_t *vdc);
147 static int	vdc_recv(vdc_t *vdc, vio_msg_t *msgp, size_t *nbytesp);
148 
149 static uint_t	vdc_handle_cb(uint64_t event, caddr_t arg);
150 static int	vdc_process_data_msg(vdc_t *vdc, vio_msg_t *msg);
151 static int	vdc_process_err_msg(vdc_t *vdc, vio_msg_t msg);
152 static int	vdc_handle_ver_msg(vdc_t *vdc, vio_ver_msg_t *ver_msg);
153 static int	vdc_handle_attr_msg(vdc_t *vdc, vd_attr_msg_t *attr_msg);
154 static int	vdc_handle_dring_reg_msg(vdc_t *vdc, vio_dring_reg_msg_t *msg);
155 static int 	vdc_send_request(vdc_t *vdcp, int operation,
156 		    caddr_t addr, size_t nbytes, int slice, diskaddr_t offset,
157 		    int cb_type, void *cb_arg, vio_desc_direction_t dir);
158 static int	vdc_map_to_shared_dring(vdc_t *vdcp, int idx);
159 static int 	vdc_populate_descriptor(vdc_t *vdcp, int operation,
160 		    caddr_t addr, size_t nbytes, int slice, diskaddr_t offset,
161 		    int cb_type, void *cb_arg, vio_desc_direction_t dir);
162 static int 	vdc_do_sync_op(vdc_t *vdcp, int operation,
163 		    caddr_t addr, size_t nbytes, int slice, diskaddr_t offset,
164 		    int cb_type, void *cb_arg, vio_desc_direction_t dir);
165 
166 static int	vdc_wait_for_response(vdc_t *vdcp, vio_msg_t *msgp);
167 static int	vdc_drain_response(vdc_t *vdcp);
168 static int	vdc_depopulate_descriptor(vdc_t *vdc, uint_t idx);
169 static int	vdc_populate_mem_hdl(vdc_t *vdcp, vdc_local_desc_t *ldep);
170 static int	vdc_verify_seq_num(vdc_t *vdc, vio_dring_msg_t *dring_msg);
171 
172 /* dkio */
173 static int	vd_process_ioctl(dev_t dev, int cmd, caddr_t arg, int mode);
174 static int	vdc_create_fake_geometry(vdc_t *vdc);
175 static int	vdc_setup_disk_layout(vdc_t *vdc);
176 static int	vdc_null_copy_func(vdc_t *vdc, void *from, void *to,
177 		    int mode, int dir);
178 static int	vdc_get_wce_convert(vdc_t *vdc, void *from, void *to,
179 		    int mode, int dir);
180 static int	vdc_set_wce_convert(vdc_t *vdc, void *from, void *to,
181 		    int mode, int dir);
182 static int	vdc_get_vtoc_convert(vdc_t *vdc, void *from, void *to,
183 		    int mode, int dir);
184 static int	vdc_set_vtoc_convert(vdc_t *vdc, void *from, void *to,
185 		    int mode, int dir);
186 static int	vdc_get_geom_convert(vdc_t *vdc, void *from, void *to,
187 		    int mode, int dir);
188 static int	vdc_set_geom_convert(vdc_t *vdc, void *from, void *to,
189 		    int mode, int dir);
190 static int	vdc_uscsicmd_convert(vdc_t *vdc, void *from, void *to,
191 		    int mode, int dir);
192 static int	vdc_get_efi_convert(vdc_t *vdc, void *from, void *to,
193 		    int mode, int dir);
194 static int	vdc_set_efi_convert(vdc_t *vdc, void *from, void *to,
195 		    int mode, int dir);
196 
197 /*
198  * Module variables
199  */
200 
201 /*
202  * Tunable variables to control how long vdc waits before timing out on
203  * various operations
204  */
205 static int	vdc_retries = 10;
206 static int	vdc_hshake_retries = 3;
207 
208 /* calculated from 'vdc_usec_timeout' during attach */
209 static uint64_t	vdc_hz_timeout;				/* units: Hz */
210 static uint64_t	vdc_usec_timeout = 30 * MICROSEC;	/* 30s units: ns */
211 
212 static uint64_t vdc_hz_min_ldc_delay;
213 static uint64_t vdc_min_timeout_ldc = 1 * MILLISEC;
214 static uint64_t vdc_hz_max_ldc_delay;
215 static uint64_t vdc_max_timeout_ldc = 100 * MILLISEC;
216 
217 static uint64_t vdc_ldc_read_init_delay = 1 * MILLISEC;
218 static uint64_t vdc_ldc_read_max_delay = 100 * MILLISEC;
219 
220 /* values for dumping - need to run in a tighter loop */
221 static uint64_t	vdc_usec_timeout_dump = 100 * MILLISEC;	/* 0.1s units: ns */
222 static int	vdc_dump_retries = 100;
223 
224 /* Count of the number of vdc instances attached */
225 static volatile uint32_t	vdc_instance_count = 0;
226 
227 /* Soft state pointer */
228 static void	*vdc_state;
229 
230 /*
231  * Controlling the verbosity of the error/debug messages
232  *
233  * vdc_msglevel - controls level of messages
234  * vdc_matchinst - 64-bit variable where each bit corresponds
235  *                 to the vdc instance the vdc_msglevel applies.
236  */
237 int		vdc_msglevel = 0x0;
238 uint64_t	vdc_matchinst = 0ull;
239 
240 /*
241  * Supported vDisk protocol version pairs.
242  *
243  * The first array entry is the latest and preferred version.
244  */
245 static const vio_ver_t	vdc_version[] = {{1, 0}};
246 
247 static struct cb_ops vdc_cb_ops = {
248 	vdc_open,	/* cb_open */
249 	vdc_close,	/* cb_close */
250 	vdc_strategy,	/* cb_strategy */
251 	vdc_print,	/* cb_print */
252 	vdc_dump,	/* cb_dump */
253 	vdc_read,	/* cb_read */
254 	vdc_write,	/* cb_write */
255 	vdc_ioctl,	/* cb_ioctl */
256 	nodev,		/* cb_devmap */
257 	nodev,		/* cb_mmap */
258 	nodev,		/* cb_segmap */
259 	nochpoll,	/* cb_chpoll */
260 	ddi_prop_op,	/* cb_prop_op */
261 	NULL,		/* cb_str */
262 	D_MP | D_64BIT,	/* cb_flag */
263 	CB_REV,		/* cb_rev */
264 	vdc_aread,	/* cb_aread */
265 	vdc_awrite	/* cb_awrite */
266 };
267 
268 static struct dev_ops vdc_ops = {
269 	DEVO_REV,	/* devo_rev */
270 	0,		/* devo_refcnt */
271 	vdc_getinfo,	/* devo_getinfo */
272 	nulldev,	/* devo_identify */
273 	nulldev,	/* devo_probe */
274 	vdc_attach,	/* devo_attach */
275 	vdc_detach,	/* devo_detach */
276 	nodev,		/* devo_reset */
277 	&vdc_cb_ops,	/* devo_cb_ops */
278 	NULL,		/* devo_bus_ops */
279 	nulldev		/* devo_power */
280 };
281 
282 static struct modldrv modldrv = {
283 	&mod_driverops,
284 	"virtual disk client %I%",
285 	&vdc_ops,
286 };
287 
288 static struct modlinkage modlinkage = {
289 	MODREV_1,
290 	&modldrv,
291 	NULL
292 };
293 
294 /* -------------------------------------------------------------------------- */
295 
296 /*
297  * Device Driver housekeeping and setup
298  */
299 
300 int
301 _init(void)
302 {
303 	int	status;
304 
305 	if ((status = ddi_soft_state_init(&vdc_state, sizeof (vdc_t), 1)) != 0)
306 		return (status);
307 	if ((status = mod_install(&modlinkage)) != 0)
308 		ddi_soft_state_fini(&vdc_state);
309 	vdc_efi_init(vd_process_ioctl);
310 	return (status);
311 }
312 
313 int
314 _info(struct modinfo *modinfop)
315 {
316 	return (mod_info(&modlinkage, modinfop));
317 }
318 
319 int
320 _fini(void)
321 {
322 	int	status;
323 
324 	if ((status = mod_remove(&modlinkage)) != 0)
325 		return (status);
326 	vdc_efi_fini();
327 	ddi_soft_state_fini(&vdc_state);
328 	return (0);
329 }
330 
331 static int
332 vdc_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd,  void *arg, void **resultp)
333 {
334 	_NOTE(ARGUNUSED(dip))
335 
336 	int	instance = VDCUNIT((dev_t)arg);
337 	vdc_t	*vdc = NULL;
338 
339 	switch (cmd) {
340 	case DDI_INFO_DEVT2DEVINFO:
341 		if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
342 			*resultp = NULL;
343 			return (DDI_FAILURE);
344 		}
345 		*resultp = vdc->dip;
346 		return (DDI_SUCCESS);
347 	case DDI_INFO_DEVT2INSTANCE:
348 		*resultp = (void *)(uintptr_t)instance;
349 		return (DDI_SUCCESS);
350 	default:
351 		*resultp = NULL;
352 		return (DDI_FAILURE);
353 	}
354 }
355 
356 static int
357 vdc_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
358 {
359 	int	instance;
360 	int	rv;
361 	vdc_t	*vdc = NULL;
362 
363 	switch (cmd) {
364 	case DDI_DETACH:
365 		/* the real work happens below */
366 		break;
367 	case DDI_SUSPEND:
368 		/* nothing to do for this non-device */
369 		return (DDI_SUCCESS);
370 	default:
371 		return (DDI_FAILURE);
372 	}
373 
374 	ASSERT(cmd == DDI_DETACH);
375 	instance = ddi_get_instance(dip);
376 	DMSGX(1, "[%d] Entered\n", instance);
377 
378 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
379 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
380 		return (DDI_FAILURE);
381 	}
382 
383 	if (vdc->open_count) {
384 		DMSG(vdc, 0, "[%d] Cannot detach: device is open", instance);
385 		return (DDI_FAILURE);
386 	}
387 
388 	DMSG(vdc, 0, "[%d] proceeding...\n", instance);
389 
390 	/* mark instance as detaching */
391 	vdc->lifecycle	= VDC_LC_DETACHING;
392 
393 	/*
394 	 * try and disable callbacks to prevent another handshake
395 	 */
396 	rv = ldc_set_cb_mode(vdc->ldc_handle, LDC_CB_DISABLE);
397 	DMSG(vdc, 0, "callback disabled (rv=%d)\n", rv);
398 
399 	if (vdc->initialized & VDC_THREAD) {
400 		mutex_enter(&vdc->read_lock);
401 		if ((vdc->read_state == VDC_READ_WAITING) ||
402 		    (vdc->read_state == VDC_READ_RESET)) {
403 			vdc->read_state = VDC_READ_RESET;
404 			cv_signal(&vdc->read_cv);
405 		}
406 
407 		mutex_exit(&vdc->read_lock);
408 
409 		/* wake up any thread waiting for connection to come online */
410 		mutex_enter(&vdc->lock);
411 		if (vdc->state == VDC_STATE_INIT_WAITING) {
412 			DMSG(vdc, 0,
413 			    "[%d] write reset - move to resetting state...\n",
414 			    instance);
415 			vdc->state = VDC_STATE_RESETTING;
416 			cv_signal(&vdc->initwait_cv);
417 		}
418 		mutex_exit(&vdc->lock);
419 
420 		/* now wait until state transitions to VDC_STATE_DETACH */
421 		thread_join(vdc->msg_proc_thr->t_did);
422 		ASSERT(vdc->state == VDC_STATE_DETACH);
423 		DMSG(vdc, 0, "[%d] Reset thread exit and join ..\n",
424 		    vdc->instance);
425 	}
426 
427 	mutex_enter(&vdc->lock);
428 
429 	if (vdc->initialized & VDC_DRING)
430 		vdc_destroy_descriptor_ring(vdc);
431 
432 	if (vdc->initialized & VDC_LDC)
433 		vdc_terminate_ldc(vdc);
434 
435 	mutex_exit(&vdc->lock);
436 
437 	if (vdc->initialized & VDC_MINOR) {
438 		ddi_prop_remove_all(dip);
439 		ddi_remove_minor_node(dip, NULL);
440 	}
441 
442 	if (vdc->initialized & VDC_LOCKS) {
443 		mutex_destroy(&vdc->lock);
444 		mutex_destroy(&vdc->read_lock);
445 		cv_destroy(&vdc->initwait_cv);
446 		cv_destroy(&vdc->dring_free_cv);
447 		cv_destroy(&vdc->membind_cv);
448 		cv_destroy(&vdc->sync_pending_cv);
449 		cv_destroy(&vdc->sync_blocked_cv);
450 		cv_destroy(&vdc->read_cv);
451 		cv_destroy(&vdc->running_cv);
452 	}
453 
454 	if (vdc->minfo)
455 		kmem_free(vdc->minfo, sizeof (struct dk_minfo));
456 
457 	if (vdc->cinfo)
458 		kmem_free(vdc->cinfo, sizeof (struct dk_cinfo));
459 
460 	if (vdc->vtoc)
461 		kmem_free(vdc->vtoc, sizeof (struct vtoc));
462 
463 	if (vdc->label)
464 		kmem_free(vdc->label, DK_LABEL_SIZE);
465 
466 	if (vdc->devid) {
467 		ddi_devid_unregister(dip);
468 		ddi_devid_free(vdc->devid);
469 	}
470 
471 	if (vdc->initialized & VDC_SOFT_STATE)
472 		ddi_soft_state_free(vdc_state, instance);
473 
474 	DMSG(vdc, 0, "[%d] End %p\n", instance, (void *)vdc);
475 
476 	return (DDI_SUCCESS);
477 }
478 
479 
480 static int
481 vdc_do_attach(dev_info_t *dip)
482 {
483 	int		instance;
484 	vdc_t		*vdc = NULL;
485 	int		status;
486 
487 	ASSERT(dip != NULL);
488 
489 	instance = ddi_get_instance(dip);
490 	if (ddi_soft_state_zalloc(vdc_state, instance) != DDI_SUCCESS) {
491 		cmn_err(CE_NOTE, "[%d] Couldn't alloc state structure",
492 		    instance);
493 		return (DDI_FAILURE);
494 	}
495 
496 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
497 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
498 		return (DDI_FAILURE);
499 	}
500 
501 	/*
502 	 * We assign the value to initialized in this case to zero out the
503 	 * variable and then set bits in it to indicate what has been done
504 	 */
505 	vdc->initialized = VDC_SOFT_STATE;
506 
507 	vdc_hz_timeout = drv_usectohz(vdc_usec_timeout);
508 
509 	vdc_hz_min_ldc_delay = drv_usectohz(vdc_min_timeout_ldc);
510 	vdc_hz_max_ldc_delay = drv_usectohz(vdc_max_timeout_ldc);
511 
512 	vdc->dip	= dip;
513 	vdc->instance	= instance;
514 	vdc->open_count	= 0;
515 	vdc->vdisk_type	= VD_DISK_TYPE_UNK;
516 	vdc->vdisk_label = VD_DISK_LABEL_UNK;
517 	vdc->state	= VDC_STATE_INIT;
518 	vdc->lifecycle	= VDC_LC_ATTACHING;
519 	vdc->ldc_state	= 0;
520 	vdc->session_id = 0;
521 	vdc->block_size = DEV_BSIZE;
522 	vdc->max_xfer_sz = maxphys / DEV_BSIZE;
523 
524 	vdc->vtoc = NULL;
525 	vdc->cinfo = NULL;
526 	vdc->minfo = NULL;
527 
528 	mutex_init(&vdc->lock, NULL, MUTEX_DRIVER, NULL);
529 	cv_init(&vdc->initwait_cv, NULL, CV_DRIVER, NULL);
530 	cv_init(&vdc->dring_free_cv, NULL, CV_DRIVER, NULL);
531 	cv_init(&vdc->membind_cv, NULL, CV_DRIVER, NULL);
532 	cv_init(&vdc->running_cv, NULL, CV_DRIVER, NULL);
533 
534 	vdc->threads_pending = 0;
535 	vdc->sync_op_pending = B_FALSE;
536 	vdc->sync_op_blocked = B_FALSE;
537 	cv_init(&vdc->sync_pending_cv, NULL, CV_DRIVER, NULL);
538 	cv_init(&vdc->sync_blocked_cv, NULL, CV_DRIVER, NULL);
539 
540 	/* init blocking msg read functionality */
541 	mutex_init(&vdc->read_lock, NULL, MUTEX_DRIVER, NULL);
542 	cv_init(&vdc->read_cv, NULL, CV_DRIVER, NULL);
543 	vdc->read_state = VDC_READ_IDLE;
544 
545 	vdc->initialized |= VDC_LOCKS;
546 
547 	/* initialise LDC channel which will be used to communicate with vds */
548 	if ((status = vdc_do_ldc_init(vdc)) != 0) {
549 		cmn_err(CE_NOTE, "[%d] Couldn't initialize LDC", instance);
550 		goto return_status;
551 	}
552 
553 	/* initialize the thread responsible for managing state with server */
554 	vdc->msg_proc_thr = thread_create(NULL, 0, vdc_process_msg_thread,
555 	    vdc, 0, &p0, TS_RUN, minclsyspri);
556 	if (vdc->msg_proc_thr == NULL) {
557 		cmn_err(CE_NOTE, "[%d] Failed to create msg processing thread",
558 		    instance);
559 		return (DDI_FAILURE);
560 	}
561 
562 	vdc->initialized |= VDC_THREAD;
563 
564 	atomic_inc_32(&vdc_instance_count);
565 
566 	/*
567 	 * Once the handshake is complete, we can use the DRing to send
568 	 * requests to the vDisk server to calculate the geometry and
569 	 * VTOC of the "disk"
570 	 */
571 	status = vdc_setup_disk_layout(vdc);
572 	if (status != 0) {
573 		DMSG(vdc, 0, "[%d] Failed to discover disk layout (err%d)",
574 			vdc->instance, status);
575 		goto return_status;
576 	}
577 
578 	/*
579 	 * Now that we have the device info we can create the
580 	 * device nodes and properties
581 	 */
582 	status = vdc_create_device_nodes(vdc);
583 	if (status) {
584 		DMSG(vdc, 0, "[%d] Failed to create device nodes",
585 				instance);
586 		goto return_status;
587 	}
588 	status = vdc_create_device_nodes_props(vdc);
589 	if (status) {
590 		DMSG(vdc, 0, "[%d] Failed to create device nodes"
591 				" properties (%d)", instance, status);
592 		goto return_status;
593 	}
594 
595 	/*
596 	 * Setup devid
597 	 */
598 	if (vdc_setup_devid(vdc)) {
599 		DMSG(vdc, 0, "[%d] No device id available\n", instance);
600 	}
601 
602 	ddi_report_dev(dip);
603 	vdc->lifecycle	= VDC_LC_ONLINE;
604 	DMSG(vdc, 0, "[%d] Attach tasks successful\n", instance);
605 
606 return_status:
607 	DMSG(vdc, 0, "[%d] Attach completed\n", instance);
608 	return (status);
609 }
610 
611 static int
612 vdc_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
613 {
614 	int	status;
615 
616 	switch (cmd) {
617 	case DDI_ATTACH:
618 		if ((status = vdc_do_attach(dip)) != 0)
619 			(void) vdc_detach(dip, DDI_DETACH);
620 		return (status);
621 	case DDI_RESUME:
622 		/* nothing to do for this non-device */
623 		return (DDI_SUCCESS);
624 	default:
625 		return (DDI_FAILURE);
626 	}
627 }
628 
629 static int
630 vdc_do_ldc_init(vdc_t *vdc)
631 {
632 	int			status = 0;
633 	ldc_status_t		ldc_state;
634 	ldc_attr_t		ldc_attr;
635 	uint64_t		ldc_id = 0;
636 	dev_info_t		*dip = NULL;
637 
638 	ASSERT(vdc != NULL);
639 
640 	dip = vdc->dip;
641 	vdc->initialized |= VDC_LDC;
642 
643 	if ((status = vdc_get_ldc_id(dip, &ldc_id)) != 0) {
644 		DMSG(vdc, 0, "[%d] Failed to get LDC channel ID property",
645 				vdc->instance);
646 		return (EIO);
647 	}
648 	vdc->ldc_id = ldc_id;
649 
650 	ldc_attr.devclass = LDC_DEV_BLK;
651 	ldc_attr.instance = vdc->instance;
652 	ldc_attr.mode = LDC_MODE_UNRELIABLE;	/* unreliable transport */
653 	ldc_attr.mtu = VD_LDC_MTU;
654 
655 	if ((vdc->initialized & VDC_LDC_INIT) == 0) {
656 		status = ldc_init(ldc_id, &ldc_attr, &vdc->ldc_handle);
657 		if (status != 0) {
658 			DMSG(vdc, 0, "[%d] ldc_init(chan %ld) returned %d",
659 					vdc->instance, ldc_id, status);
660 			return (status);
661 		}
662 		vdc->initialized |= VDC_LDC_INIT;
663 	}
664 	status = ldc_status(vdc->ldc_handle, &ldc_state);
665 	if (status != 0) {
666 		DMSG(vdc, 0, "[%d] Cannot discover LDC status [err=%d]",
667 				vdc->instance, status);
668 		return (status);
669 	}
670 	vdc->ldc_state = ldc_state;
671 
672 	if ((vdc->initialized & VDC_LDC_CB) == 0) {
673 		status = ldc_reg_callback(vdc->ldc_handle, vdc_handle_cb,
674 		    (caddr_t)vdc);
675 		if (status != 0) {
676 			DMSG(vdc, 0, "[%d] LDC callback reg. failed (%d)",
677 					vdc->instance, status);
678 			return (status);
679 		}
680 		vdc->initialized |= VDC_LDC_CB;
681 	}
682 
683 	vdc->initialized |= VDC_LDC;
684 
685 	/*
686 	 * At this stage we have initialised LDC, we will now try and open
687 	 * the connection.
688 	 */
689 	if (vdc->ldc_state == LDC_INIT) {
690 		status = ldc_open(vdc->ldc_handle);
691 		if (status != 0) {
692 			DMSG(vdc, 0, "[%d] ldc_open(chan %ld) returned %d",
693 					vdc->instance, vdc->ldc_id, status);
694 			return (status);
695 		}
696 		vdc->initialized |= VDC_LDC_OPEN;
697 	}
698 
699 	return (status);
700 }
701 
702 static int
703 vdc_start_ldc_connection(vdc_t *vdc)
704 {
705 	int		status = 0;
706 
707 	ASSERT(vdc != NULL);
708 
709 	ASSERT(MUTEX_HELD(&vdc->lock));
710 
711 	status = vdc_do_ldc_up(vdc);
712 
713 	DMSG(vdc, 0, "[%d] Finished bringing up LDC\n", vdc->instance);
714 
715 	return (status);
716 }
717 
718 static int
719 vdc_stop_ldc_connection(vdc_t *vdcp)
720 {
721 	int	status;
722 
723 	DMSG(vdcp, 0, ": Resetting connection to vDisk server : state %d\n",
724 		vdcp->state);
725 
726 	status = ldc_down(vdcp->ldc_handle);
727 	DMSG(vdcp, 0, "ldc_down() = %d\n", status);
728 
729 	vdcp->initialized &= ~VDC_HANDSHAKE;
730 	DMSG(vdcp, 0, "initialized=%x\n", vdcp->initialized);
731 
732 	return (status);
733 }
734 
735 static int
736 vdc_create_device_nodes_efi(vdc_t *vdc)
737 {
738 	ddi_remove_minor_node(vdc->dip, "h");
739 	ddi_remove_minor_node(vdc->dip, "h,raw");
740 
741 	if (ddi_create_minor_node(vdc->dip, "wd", S_IFBLK,
742 		VD_MAKE_DEV(vdc->instance, VD_EFI_WD_SLICE),
743 		DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
744 		cmn_err(CE_NOTE, "[%d] Couldn't add block node 'wd'",
745 		    vdc->instance);
746 		return (EIO);
747 	}
748 
749 	/* if any device node is created we set this flag */
750 	vdc->initialized |= VDC_MINOR;
751 
752 	if (ddi_create_minor_node(vdc->dip, "wd,raw", S_IFCHR,
753 		VD_MAKE_DEV(vdc->instance, VD_EFI_WD_SLICE),
754 		DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
755 		cmn_err(CE_NOTE, "[%d] Couldn't add block node 'wd,raw'",
756 		    vdc->instance);
757 		return (EIO);
758 	}
759 
760 	return (0);
761 }
762 
763 static int
764 vdc_create_device_nodes_vtoc(vdc_t *vdc)
765 {
766 	ddi_remove_minor_node(vdc->dip, "wd");
767 	ddi_remove_minor_node(vdc->dip, "wd,raw");
768 
769 	if (ddi_create_minor_node(vdc->dip, "h", S_IFBLK,
770 		VD_MAKE_DEV(vdc->instance, VD_EFI_WD_SLICE),
771 		DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
772 		cmn_err(CE_NOTE, "[%d] Couldn't add block node 'h'",
773 		    vdc->instance);
774 		return (EIO);
775 	}
776 
777 	/* if any device node is created we set this flag */
778 	vdc->initialized |= VDC_MINOR;
779 
780 	if (ddi_create_minor_node(vdc->dip, "h,raw", S_IFCHR,
781 		VD_MAKE_DEV(vdc->instance, VD_EFI_WD_SLICE),
782 		DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
783 		cmn_err(CE_NOTE, "[%d] Couldn't add block node 'h,raw'",
784 		    vdc->instance);
785 		return (EIO);
786 	}
787 
788 	return (0);
789 }
790 
791 /*
792  * Function:
793  *	vdc_create_device_nodes
794  *
795  * Description:
796  *	This function creates the block and character device nodes under
797  *	/devices along with the node properties. It is called as part of
798  *	the attach(9E) of the instance during the handshake with vds after
799  *	vds has sent the attributes to vdc.
800  *
801  *	If the device is of type VD_DISK_TYPE_SLICE then the minor node
802  *	of 2 is used in keeping with the Solaris convention that slice 2
803  *	refers to a whole disk. Slices start at 'a'
804  *
805  * Parameters:
806  *	vdc 		- soft state pointer
807  *
808  * Return Values
809  *	0		- Success
810  *	EIO		- Failed to create node
811  *	EINVAL		- Unknown type of disk exported
812  */
813 static int
814 vdc_create_device_nodes(vdc_t *vdc)
815 {
816 	char		name[sizeof ("s,raw")];
817 	dev_info_t	*dip = NULL;
818 	int		instance, status;
819 	int		num_slices = 1;
820 	int		i;
821 
822 	ASSERT(vdc != NULL);
823 
824 	instance = vdc->instance;
825 	dip = vdc->dip;
826 
827 	switch (vdc->vdisk_type) {
828 	case VD_DISK_TYPE_DISK:
829 		num_slices = V_NUMPAR;
830 		break;
831 	case VD_DISK_TYPE_SLICE:
832 		num_slices = 1;
833 		break;
834 	case VD_DISK_TYPE_UNK:
835 	default:
836 		return (EINVAL);
837 	}
838 
839 	/*
840 	 * Minor nodes are different for EFI disks: EFI disks do not have
841 	 * a minor node 'g' for the minor number corresponding to slice
842 	 * VD_EFI_WD_SLICE (slice 7) instead they have a minor node 'wd'
843 	 * representing the whole disk.
844 	 */
845 	for (i = 0; i < num_slices; i++) {
846 
847 		if (i == VD_EFI_WD_SLICE) {
848 			if (vdc->vdisk_label == VD_DISK_LABEL_EFI)
849 				status = vdc_create_device_nodes_efi(vdc);
850 			else
851 				status = vdc_create_device_nodes_vtoc(vdc);
852 			if (status != 0)
853 				return (status);
854 			continue;
855 		}
856 
857 		(void) snprintf(name, sizeof (name), "%c", 'a' + i);
858 		if (ddi_create_minor_node(dip, name, S_IFBLK,
859 		    VD_MAKE_DEV(instance, i), DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
860 			cmn_err(CE_NOTE, "[%d] Couldn't add block node '%s'",
861 				instance, name);
862 			return (EIO);
863 		}
864 
865 		/* if any device node is created we set this flag */
866 		vdc->initialized |= VDC_MINOR;
867 
868 		(void) snprintf(name, sizeof (name), "%c%s",
869 			'a' + i, ",raw");
870 		if (ddi_create_minor_node(dip, name, S_IFCHR,
871 		    VD_MAKE_DEV(instance, i), DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
872 			cmn_err(CE_NOTE, "[%d] Couldn't add raw node '%s'",
873 				instance, name);
874 			return (EIO);
875 		}
876 	}
877 
878 	return (0);
879 }
880 
881 /*
882  * Function:
883  *	vdc_create_device_nodes_props
884  *
885  * Description:
886  *	This function creates the block and character device nodes under
887  *	/devices along with the node properties. It is called as part of
888  *	the attach(9E) of the instance during the handshake with vds after
889  *	vds has sent the attributes to vdc.
890  *
891  * Parameters:
892  *	vdc 		- soft state pointer
893  *
894  * Return Values
895  *	0		- Success
896  *	EIO		- Failed to create device node property
897  *	EINVAL		- Unknown type of disk exported
898  */
899 static int
900 vdc_create_device_nodes_props(vdc_t *vdc)
901 {
902 	dev_info_t	*dip = NULL;
903 	int		instance;
904 	int		num_slices = 1;
905 	int64_t		size = 0;
906 	dev_t		dev;
907 	int		rv;
908 	int		i;
909 
910 	ASSERT(vdc != NULL);
911 
912 	instance = vdc->instance;
913 	dip = vdc->dip;
914 
915 	if ((vdc->vtoc == NULL) || (vdc->vtoc->v_sanity != VTOC_SANE)) {
916 		DMSG(vdc, 0, "![%d] Could not create device node property."
917 				" No VTOC available", instance);
918 		return (ENXIO);
919 	}
920 
921 	switch (vdc->vdisk_type) {
922 	case VD_DISK_TYPE_DISK:
923 		num_slices = V_NUMPAR;
924 		break;
925 	case VD_DISK_TYPE_SLICE:
926 		num_slices = 1;
927 		break;
928 	case VD_DISK_TYPE_UNK:
929 	default:
930 		return (EINVAL);
931 	}
932 
933 	for (i = 0; i < num_slices; i++) {
934 		dev = makedevice(ddi_driver_major(dip),
935 			VD_MAKE_DEV(instance, i));
936 
937 		size = vdc->vtoc->v_part[i].p_size * vdc->vtoc->v_sectorsz;
938 		DMSG(vdc, 0, "[%d] sz %ld (%ld Mb)  p_size %lx\n",
939 				instance, size, size / (1024 * 1024),
940 				vdc->vtoc->v_part[i].p_size);
941 
942 		rv = ddi_prop_update_int64(dev, dip, VDC_SIZE_PROP_NAME, size);
943 		if (rv != DDI_PROP_SUCCESS) {
944 			cmn_err(CE_NOTE, "[%d] Couldn't add '%s' prop of [%ld]",
945 				instance, VDC_SIZE_PROP_NAME, size);
946 			return (EIO);
947 		}
948 
949 		rv = ddi_prop_update_int64(dev, dip, VDC_NBLOCKS_PROP_NAME,
950 			lbtodb(size));
951 		if (rv != DDI_PROP_SUCCESS) {
952 			cmn_err(CE_NOTE, "[%d] Couldn't add '%s' prop [%llu]",
953 				instance, VDC_NBLOCKS_PROP_NAME, lbtodb(size));
954 			return (EIO);
955 		}
956 	}
957 
958 	return (0);
959 }
960 
961 static int
962 vdc_open(dev_t *dev, int flag, int otyp, cred_t *cred)
963 {
964 	_NOTE(ARGUNUSED(cred))
965 
966 	int		instance;
967 	vdc_t		*vdc;
968 
969 	ASSERT(dev != NULL);
970 	instance = VDCUNIT(*dev);
971 
972 	if ((otyp != OTYP_CHR) && (otyp != OTYP_BLK))
973 		return (EINVAL);
974 
975 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
976 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
977 		return (ENXIO);
978 	}
979 
980 	DMSG(vdc, 0, "minor = %d flag = %x, otyp = %x\n",
981 			getminor(*dev), flag, otyp);
982 
983 	mutex_enter(&vdc->lock);
984 	vdc->open_count++;
985 	mutex_exit(&vdc->lock);
986 
987 	return (0);
988 }
989 
990 static int
991 vdc_close(dev_t dev, int flag, int otyp, cred_t *cred)
992 {
993 	_NOTE(ARGUNUSED(cred))
994 
995 	int	instance;
996 	vdc_t	*vdc;
997 
998 	instance = VDCUNIT(dev);
999 
1000 	if ((otyp != OTYP_CHR) && (otyp != OTYP_BLK))
1001 		return (EINVAL);
1002 
1003 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
1004 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
1005 		return (ENXIO);
1006 	}
1007 
1008 	DMSG(vdc, 0, "[%d] flag = %x, otyp = %x\n", instance, flag, otyp);
1009 	if (vdc->dkio_flush_pending) {
1010 		DMSG(vdc, 0,
1011 		    "[%d] Cannot detach: %d outstanding DKIO flushes\n",
1012 		    instance, vdc->dkio_flush_pending);
1013 		return (EBUSY);
1014 	}
1015 
1016 	/*
1017 	 * Should not need the mutex here, since the framework should protect
1018 	 * against more opens on this device, but just in case.
1019 	 */
1020 	mutex_enter(&vdc->lock);
1021 	vdc->open_count--;
1022 	mutex_exit(&vdc->lock);
1023 
1024 	return (0);
1025 }
1026 
1027 static int
1028 vdc_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp, int *rvalp)
1029 {
1030 	_NOTE(ARGUNUSED(credp))
1031 	_NOTE(ARGUNUSED(rvalp))
1032 
1033 	return (vd_process_ioctl(dev, cmd, (caddr_t)arg, mode));
1034 }
1035 
1036 static int
1037 vdc_print(dev_t dev, char *str)
1038 {
1039 	cmn_err(CE_NOTE, "vdc%d:  %s", VDCUNIT(dev), str);
1040 	return (0);
1041 }
1042 
1043 static int
1044 vdc_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
1045 {
1046 	int	rv;
1047 	size_t	nbytes = nblk * DEV_BSIZE;
1048 	int	instance = VDCUNIT(dev);
1049 	vdc_t	*vdc = NULL;
1050 
1051 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
1052 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
1053 		return (ENXIO);
1054 	}
1055 
1056 	DMSG(vdc, 2, "[%d] dump %ld bytes at block 0x%lx : addr=0x%p\n",
1057 	    instance, nbytes, blkno, (void *)addr);
1058 	rv = vdc_send_request(vdc, VD_OP_BWRITE, addr, nbytes,
1059 	    VDCPART(dev), blkno, CB_STRATEGY, 0, VIO_write_dir);
1060 	if (rv) {
1061 		DMSG(vdc, 0, "Failed to do a disk dump (err=%d)\n", rv);
1062 		return (rv);
1063 	}
1064 
1065 	if (ddi_in_panic())
1066 		(void) vdc_drain_response(vdc);
1067 
1068 	DMSG(vdc, 0, "[%d] End\n", instance);
1069 
1070 	return (0);
1071 }
1072 
1073 /* -------------------------------------------------------------------------- */
1074 
1075 /*
1076  * Disk access routines
1077  *
1078  */
1079 
1080 /*
1081  * vdc_strategy()
1082  *
1083  * Return Value:
1084  *	0:	As per strategy(9E), the strategy() function must return 0
1085  *		[ bioerror(9f) sets b_flags to the proper error code ]
1086  */
1087 static int
1088 vdc_strategy(struct buf *buf)
1089 {
1090 	int	rv = -1;
1091 	vdc_t	*vdc = NULL;
1092 	int	instance = VDCUNIT(buf->b_edev);
1093 	int	op = (buf->b_flags & B_READ) ? VD_OP_BREAD : VD_OP_BWRITE;
1094 
1095 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
1096 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
1097 		bioerror(buf, ENXIO);
1098 		biodone(buf);
1099 		return (0);
1100 	}
1101 
1102 	DMSG(vdc, 2, "[%d] %s %ld bytes at block %llx : b_addr=0x%p\n",
1103 	    instance, (buf->b_flags & B_READ) ? "Read" : "Write",
1104 	    buf->b_bcount, buf->b_lblkno, (void *)buf->b_un.b_addr);
1105 	DTRACE_IO2(vstart, buf_t *, buf, vdc_t *, vdc);
1106 
1107 	bp_mapin(buf);
1108 
1109 	rv = vdc_send_request(vdc, op, (caddr_t)buf->b_un.b_addr,
1110 	    buf->b_bcount, VDCPART(buf->b_edev), buf->b_lblkno,
1111 	    CB_STRATEGY, buf, (op == VD_OP_BREAD) ? VIO_read_dir :
1112 	    VIO_write_dir);
1113 
1114 	ASSERT(rv == 0 || rv == EINVAL);
1115 
1116 	/*
1117 	 * If the request was successfully sent, the strategy call returns and
1118 	 * the ACK handler calls the bioxxx functions when the vDisk server is
1119 	 * done.
1120 	 */
1121 	if (rv) {
1122 		DMSG(vdc, 0, "Failed to read/write (err=%d)\n", rv);
1123 		bioerror(buf, rv);
1124 		biodone(buf);
1125 	}
1126 
1127 	return (0);
1128 }
1129 
1130 /*
1131  * Function:
1132  *	vdc_min
1133  *
1134  * Description:
1135  *	Routine to limit the size of a data transfer. Used in
1136  *	conjunction with physio(9F).
1137  *
1138  * Arguments:
1139  *	bp - pointer to the indicated buf(9S) struct.
1140  *
1141  */
1142 static void
1143 vdc_min(struct buf *bufp)
1144 {
1145 	vdc_t	*vdc = NULL;
1146 	int	instance = VDCUNIT(bufp->b_edev);
1147 
1148 	vdc = ddi_get_soft_state(vdc_state, instance);
1149 	VERIFY(vdc != NULL);
1150 
1151 	if (bufp->b_bcount > (vdc->max_xfer_sz * vdc->block_size)) {
1152 		bufp->b_bcount = vdc->max_xfer_sz * vdc->block_size;
1153 	}
1154 }
1155 
1156 static int
1157 vdc_read(dev_t dev, struct uio *uio, cred_t *cred)
1158 {
1159 	_NOTE(ARGUNUSED(cred))
1160 
1161 	DMSGX(1, "[%d] Entered", VDCUNIT(dev));
1162 	return (physio(vdc_strategy, NULL, dev, B_READ, vdc_min, uio));
1163 }
1164 
1165 static int
1166 vdc_write(dev_t dev, struct uio *uio, cred_t *cred)
1167 {
1168 	_NOTE(ARGUNUSED(cred))
1169 
1170 	DMSGX(1, "[%d] Entered", VDCUNIT(dev));
1171 	return (physio(vdc_strategy, NULL, dev, B_WRITE, vdc_min, uio));
1172 }
1173 
1174 static int
1175 vdc_aread(dev_t dev, struct aio_req *aio, cred_t *cred)
1176 {
1177 	_NOTE(ARGUNUSED(cred))
1178 
1179 	DMSGX(1, "[%d] Entered", VDCUNIT(dev));
1180 	return (aphysio(vdc_strategy, anocancel, dev, B_READ, vdc_min, aio));
1181 }
1182 
1183 static int
1184 vdc_awrite(dev_t dev, struct aio_req *aio, cred_t *cred)
1185 {
1186 	_NOTE(ARGUNUSED(cred))
1187 
1188 	DMSGX(1, "[%d] Entered", VDCUNIT(dev));
1189 	return (aphysio(vdc_strategy, anocancel, dev, B_WRITE, vdc_min, aio));
1190 }
1191 
1192 
1193 /* -------------------------------------------------------------------------- */
1194 
1195 /*
1196  * Handshake support
1197  */
1198 
1199 
1200 /*
1201  * Function:
1202  *	vdc_init_ver_negotiation()
1203  *
1204  * Description:
1205  *
1206  * Arguments:
1207  *	vdc	- soft state pointer for this instance of the device driver.
1208  *
1209  * Return Code:
1210  *	0	- Success
1211  */
1212 static int
1213 vdc_init_ver_negotiation(vdc_t *vdc, vio_ver_t ver)
1214 {
1215 	vio_ver_msg_t	pkt;
1216 	size_t		msglen = sizeof (pkt);
1217 	int		status = -1;
1218 
1219 	ASSERT(vdc != NULL);
1220 	ASSERT(mutex_owned(&vdc->lock));
1221 
1222 	DMSG(vdc, 0, "[%d] Entered.\n", vdc->instance);
1223 
1224 	/*
1225 	 * set the Session ID to a unique value
1226 	 * (the lower 32 bits of the clock tick)
1227 	 */
1228 	vdc->session_id = ((uint32_t)gettick() & 0xffffffff);
1229 	DMSG(vdc, 0, "[%d] Set SID to 0x%lx\n", vdc->instance, vdc->session_id);
1230 
1231 	pkt.tag.vio_msgtype = VIO_TYPE_CTRL;
1232 	pkt.tag.vio_subtype = VIO_SUBTYPE_INFO;
1233 	pkt.tag.vio_subtype_env = VIO_VER_INFO;
1234 	pkt.tag.vio_sid = vdc->session_id;
1235 	pkt.dev_class = VDEV_DISK;
1236 	pkt.ver_major = ver.major;
1237 	pkt.ver_minor = ver.minor;
1238 
1239 	status = vdc_send(vdc, (caddr_t)&pkt, &msglen);
1240 	DMSG(vdc, 0, "[%d] Ver info sent (status = %d)\n",
1241 	    vdc->instance, status);
1242 	if ((status != 0) || (msglen != sizeof (vio_ver_msg_t))) {
1243 		DMSG(vdc, 0, "[%d] Failed to send Ver negotiation info: "
1244 				"id(%lx) rv(%d) size(%ld)",
1245 				vdc->instance, vdc->ldc_handle,
1246 				status, msglen);
1247 		if (msglen != sizeof (vio_ver_msg_t))
1248 			status = ENOMSG;
1249 	}
1250 
1251 	return (status);
1252 }
1253 
1254 /*
1255  * Function:
1256  *	vdc_ver_negotiation()
1257  *
1258  * Description:
1259  *
1260  * Arguments:
1261  *	vdcp	- soft state pointer for this instance of the device driver.
1262  *
1263  * Return Code:
1264  *	0	- Success
1265  */
1266 static int
1267 vdc_ver_negotiation(vdc_t *vdcp)
1268 {
1269 	vio_msg_t vio_msg;
1270 	int status;
1271 
1272 	if (status = vdc_init_ver_negotiation(vdcp, vdc_version[0]))
1273 		return (status);
1274 
1275 	/* release lock and wait for response */
1276 	mutex_exit(&vdcp->lock);
1277 	status = vdc_wait_for_response(vdcp, &vio_msg);
1278 	mutex_enter(&vdcp->lock);
1279 	if (status) {
1280 		DMSG(vdcp, 0,
1281 		    "[%d] Failed waiting for Ver negotiation response, rv(%d)",
1282 		    vdcp->instance, status);
1283 		return (status);
1284 	}
1285 
1286 	/* check type and sub_type ... */
1287 	if (vio_msg.tag.vio_msgtype != VIO_TYPE_CTRL ||
1288 	    vio_msg.tag.vio_subtype == VIO_SUBTYPE_INFO) {
1289 		DMSG(vdcp, 0, "[%d] Invalid ver negotiation response\n",
1290 				vdcp->instance);
1291 		return (EPROTO);
1292 	}
1293 
1294 	return (vdc_handle_ver_msg(vdcp, (vio_ver_msg_t *)&vio_msg));
1295 }
1296 
1297 /*
1298  * Function:
1299  *	vdc_init_attr_negotiation()
1300  *
1301  * Description:
1302  *
1303  * Arguments:
1304  *	vdc	- soft state pointer for this instance of the device driver.
1305  *
1306  * Return Code:
1307  *	0	- Success
1308  */
1309 static int
1310 vdc_init_attr_negotiation(vdc_t *vdc)
1311 {
1312 	vd_attr_msg_t	pkt;
1313 	size_t		msglen = sizeof (pkt);
1314 	int		status;
1315 
1316 	ASSERT(vdc != NULL);
1317 	ASSERT(mutex_owned(&vdc->lock));
1318 
1319 	DMSG(vdc, 0, "[%d] entered\n", vdc->instance);
1320 
1321 	/* fill in tag */
1322 	pkt.tag.vio_msgtype = VIO_TYPE_CTRL;
1323 	pkt.tag.vio_subtype = VIO_SUBTYPE_INFO;
1324 	pkt.tag.vio_subtype_env = VIO_ATTR_INFO;
1325 	pkt.tag.vio_sid = vdc->session_id;
1326 	/* fill in payload */
1327 	pkt.max_xfer_sz = vdc->max_xfer_sz;
1328 	pkt.vdisk_block_size = vdc->block_size;
1329 	pkt.xfer_mode = VIO_DRING_MODE;
1330 	pkt.operations = 0;	/* server will set bits of valid operations */
1331 	pkt.vdisk_type = 0;	/* server will set to valid device type */
1332 	pkt.vdisk_size = 0;	/* server will set to valid size */
1333 
1334 	status = vdc_send(vdc, (caddr_t)&pkt, &msglen);
1335 	DMSG(vdc, 0, "Attr info sent (status = %d)\n", status);
1336 
1337 	if ((status != 0) || (msglen != sizeof (vio_ver_msg_t))) {
1338 		DMSG(vdc, 0, "[%d] Failed to send Attr negotiation info: "
1339 				"id(%lx) rv(%d) size(%ld)",
1340 				vdc->instance, vdc->ldc_handle,
1341 				status, msglen);
1342 		if (msglen != sizeof (vio_ver_msg_t))
1343 			status = ENOMSG;
1344 	}
1345 
1346 	return (status);
1347 }
1348 
1349 /*
1350  * Function:
1351  *	vdc_attr_negotiation()
1352  *
1353  * Description:
1354  *
1355  * Arguments:
1356  *	vdc	- soft state pointer for this instance of the device driver.
1357  *
1358  * Return Code:
1359  *	0	- Success
1360  */
1361 static int
1362 vdc_attr_negotiation(vdc_t *vdcp)
1363 {
1364 	int status;
1365 	vio_msg_t vio_msg;
1366 
1367 	if (status = vdc_init_attr_negotiation(vdcp))
1368 		return (status);
1369 
1370 	/* release lock and wait for response */
1371 	mutex_exit(&vdcp->lock);
1372 	status = vdc_wait_for_response(vdcp, &vio_msg);
1373 	mutex_enter(&vdcp->lock);
1374 	if (status) {
1375 		DMSG(vdcp, 0,
1376 		    "[%d] Failed waiting for Attr negotiation response, rv(%d)",
1377 		    vdcp->instance, status);
1378 		return (status);
1379 	}
1380 
1381 	/* check type and sub_type ... */
1382 	if (vio_msg.tag.vio_msgtype != VIO_TYPE_CTRL ||
1383 	    vio_msg.tag.vio_subtype == VIO_SUBTYPE_INFO) {
1384 		DMSG(vdcp, 0, "[%d] Invalid attr negotiation response\n",
1385 				vdcp->instance);
1386 		return (EPROTO);
1387 	}
1388 
1389 	return (vdc_handle_attr_msg(vdcp, (vd_attr_msg_t *)&vio_msg));
1390 }
1391 
1392 
1393 /*
1394  * Function:
1395  *	vdc_init_dring_negotiate()
1396  *
1397  * Description:
1398  *
1399  * Arguments:
1400  *	vdc	- soft state pointer for this instance of the device driver.
1401  *
1402  * Return Code:
1403  *	0	- Success
1404  */
1405 static int
1406 vdc_init_dring_negotiate(vdc_t *vdc)
1407 {
1408 	vio_dring_reg_msg_t	pkt;
1409 	size_t			msglen = sizeof (pkt);
1410 	int			status = -1;
1411 	int			retry;
1412 	int			nretries = 10;
1413 
1414 	ASSERT(vdc != NULL);
1415 	ASSERT(mutex_owned(&vdc->lock));
1416 
1417 	for (retry = 0; retry < nretries; retry++) {
1418 		status = vdc_init_descriptor_ring(vdc);
1419 		if (status != EAGAIN)
1420 			break;
1421 		drv_usecwait(vdc_min_timeout_ldc);
1422 	}
1423 
1424 	if (status != 0) {
1425 		DMSG(vdc, 0, "[%d] Failed to init DRing (status = %d)\n",
1426 				vdc->instance, status);
1427 		return (status);
1428 	}
1429 
1430 	DMSG(vdc, 0, "[%d] Init of descriptor ring completed (status = %d)\n",
1431 			vdc->instance, status);
1432 
1433 	/* fill in tag */
1434 	pkt.tag.vio_msgtype = VIO_TYPE_CTRL;
1435 	pkt.tag.vio_subtype = VIO_SUBTYPE_INFO;
1436 	pkt.tag.vio_subtype_env = VIO_DRING_REG;
1437 	pkt.tag.vio_sid = vdc->session_id;
1438 	/* fill in payload */
1439 	pkt.dring_ident = 0;
1440 	pkt.num_descriptors = vdc->dring_len;
1441 	pkt.descriptor_size = vdc->dring_entry_size;
1442 	pkt.options = (VIO_TX_DRING | VIO_RX_DRING);
1443 	pkt.ncookies = vdc->dring_cookie_count;
1444 	pkt.cookie[0] = vdc->dring_cookie[0];	/* for now just one cookie */
1445 
1446 	status = vdc_send(vdc, (caddr_t)&pkt, &msglen);
1447 	if (status != 0) {
1448 		DMSG(vdc, 0, "[%d] Failed to register DRing (err = %d)",
1449 				vdc->instance, status);
1450 	}
1451 
1452 	return (status);
1453 }
1454 
1455 
1456 /*
1457  * Function:
1458  *	vdc_dring_negotiation()
1459  *
1460  * Description:
1461  *
1462  * Arguments:
1463  *	vdc	- soft state pointer for this instance of the device driver.
1464  *
1465  * Return Code:
1466  *	0	- Success
1467  */
1468 static int
1469 vdc_dring_negotiation(vdc_t *vdcp)
1470 {
1471 	int status;
1472 	vio_msg_t vio_msg;
1473 
1474 	if (status = vdc_init_dring_negotiate(vdcp))
1475 		return (status);
1476 
1477 	/* release lock and wait for response */
1478 	mutex_exit(&vdcp->lock);
1479 	status = vdc_wait_for_response(vdcp, &vio_msg);
1480 	mutex_enter(&vdcp->lock);
1481 	if (status) {
1482 		DMSG(vdcp, 0,
1483 		    "[%d] Failed waiting for Dring negotiation response,"
1484 		    " rv(%d)", vdcp->instance, status);
1485 		return (status);
1486 	}
1487 
1488 	/* check type and sub_type ... */
1489 	if (vio_msg.tag.vio_msgtype != VIO_TYPE_CTRL ||
1490 	    vio_msg.tag.vio_subtype == VIO_SUBTYPE_INFO) {
1491 		DMSG(vdcp, 0, "[%d] Invalid Dring negotiation response\n",
1492 				vdcp->instance);
1493 		return (EPROTO);
1494 	}
1495 
1496 	return (vdc_handle_dring_reg_msg(vdcp,
1497 		    (vio_dring_reg_msg_t *)&vio_msg));
1498 }
1499 
1500 
1501 /*
1502  * Function:
1503  *	vdc_send_rdx()
1504  *
1505  * Description:
1506  *
1507  * Arguments:
1508  *	vdc	- soft state pointer for this instance of the device driver.
1509  *
1510  * Return Code:
1511  *	0	- Success
1512  */
1513 static int
1514 vdc_send_rdx(vdc_t *vdcp)
1515 {
1516 	vio_msg_t	msg;
1517 	size_t		msglen = sizeof (vio_msg_t);
1518 	int		status;
1519 
1520 	/*
1521 	 * Send an RDX message to vds to indicate we are ready
1522 	 * to send data
1523 	 */
1524 	msg.tag.vio_msgtype = VIO_TYPE_CTRL;
1525 	msg.tag.vio_subtype = VIO_SUBTYPE_INFO;
1526 	msg.tag.vio_subtype_env = VIO_RDX;
1527 	msg.tag.vio_sid = vdcp->session_id;
1528 	status = vdc_send(vdcp, (caddr_t)&msg, &msglen);
1529 	if (status != 0) {
1530 		DMSG(vdcp, 0, "[%d] Failed to send RDX message (%d)",
1531 		    vdcp->instance, status);
1532 	}
1533 
1534 	return (status);
1535 }
1536 
1537 /*
1538  * Function:
1539  *	vdc_handle_rdx()
1540  *
1541  * Description:
1542  *
1543  * Arguments:
1544  *	vdc	- soft state pointer for this instance of the device driver.
1545  *	msgp	- received msg
1546  *
1547  * Return Code:
1548  *	0	- Success
1549  */
1550 static int
1551 vdc_handle_rdx(vdc_t *vdcp, vio_rdx_msg_t *msgp)
1552 {
1553 	_NOTE(ARGUNUSED(vdcp))
1554 	_NOTE(ARGUNUSED(msgp))
1555 
1556 	ASSERT(msgp->tag.vio_msgtype == VIO_TYPE_CTRL);
1557 	ASSERT(msgp->tag.vio_subtype == VIO_SUBTYPE_ACK);
1558 	ASSERT(msgp->tag.vio_subtype_env == VIO_RDX);
1559 
1560 	DMSG(vdcp, 1, "[%d] Got an RDX msg", vdcp->instance);
1561 
1562 	return (0);
1563 }
1564 
1565 /*
1566  * Function:
1567  *	vdc_rdx_exchange()
1568  *
1569  * Description:
1570  *
1571  * Arguments:
1572  *	vdc	- soft state pointer for this instance of the device driver.
1573  *
1574  * Return Code:
1575  *	0	- Success
1576  */
1577 static int
1578 vdc_rdx_exchange(vdc_t *vdcp)
1579 {
1580 	int status;
1581 	vio_msg_t vio_msg;
1582 
1583 	if (status = vdc_send_rdx(vdcp))
1584 		return (status);
1585 
1586 	/* release lock and wait for response */
1587 	mutex_exit(&vdcp->lock);
1588 	status = vdc_wait_for_response(vdcp, &vio_msg);
1589 	mutex_enter(&vdcp->lock);
1590 	if (status) {
1591 		DMSG(vdcp, 0,
1592 		    "[%d] Failed waiting for RDX response,"
1593 		    " rv(%d)", vdcp->instance, status);
1594 		return (status);
1595 	}
1596 
1597 	/* check type and sub_type ... */
1598 	if (vio_msg.tag.vio_msgtype != VIO_TYPE_CTRL ||
1599 	    vio_msg.tag.vio_subtype != VIO_SUBTYPE_ACK) {
1600 		DMSG(vdcp, 0, "[%d] Invalid RDX response\n",
1601 				vdcp->instance);
1602 		return (EPROTO);
1603 	}
1604 
1605 	return (vdc_handle_rdx(vdcp, (vio_rdx_msg_t *)&vio_msg));
1606 }
1607 
1608 
1609 /* -------------------------------------------------------------------------- */
1610 
1611 /*
1612  * LDC helper routines
1613  */
1614 
1615 static int
1616 vdc_recv(vdc_t *vdc, vio_msg_t *msgp, size_t *nbytesp)
1617 {
1618 	int		status;
1619 	boolean_t	q_has_pkts = B_FALSE;
1620 	int		delay_time;
1621 	size_t		len;
1622 
1623 	mutex_enter(&vdc->read_lock);
1624 
1625 	if (vdc->read_state == VDC_READ_IDLE)
1626 		vdc->read_state = VDC_READ_WAITING;
1627 
1628 	while (vdc->read_state != VDC_READ_PENDING) {
1629 
1630 		/* detect if the connection has been reset */
1631 		if (vdc->read_state == VDC_READ_RESET) {
1632 			status = ECONNRESET;
1633 			goto done;
1634 		}
1635 
1636 		cv_wait(&vdc->read_cv, &vdc->read_lock);
1637 	}
1638 
1639 	/*
1640 	 * Until we get a blocking ldc read we have to retry
1641 	 * until the entire LDC message has arrived before
1642 	 * ldc_read() will succeed. Note we also bail out if
1643 	 * the chanel is reset or goes away.
1644 	 */
1645 	delay_time = vdc_ldc_read_init_delay;
1646 loop:
1647 	len = *nbytesp;
1648 	status = ldc_read(vdc->ldc_handle, (caddr_t)msgp, &len);
1649 	switch (status) {
1650 	case EAGAIN:
1651 		delay_time *= 2;
1652 		if (delay_time >= vdc_ldc_read_max_delay)
1653 			delay_time = vdc_ldc_read_max_delay;
1654 		delay(delay_time);
1655 		goto loop;
1656 
1657 	case 0:
1658 		if (len == 0) {
1659 			DMSG(vdc, 0, "[%d] ldc_read returned 0 bytes with "
1660 				"no error!\n", vdc->instance);
1661 			goto loop;
1662 		}
1663 
1664 		*nbytesp = len;
1665 
1666 		/*
1667 		 * If there are pending messages, leave the
1668 		 * read state as pending. Otherwise, set the state
1669 		 * back to idle.
1670 		 */
1671 		status = ldc_chkq(vdc->ldc_handle, &q_has_pkts);
1672 		if (status == 0 && !q_has_pkts)
1673 			vdc->read_state = VDC_READ_IDLE;
1674 
1675 		break;
1676 	default:
1677 		DMSG(vdc, 0, "ldc_read returned %d\n", status);
1678 		break;
1679 	}
1680 
1681 done:
1682 	mutex_exit(&vdc->read_lock);
1683 
1684 	return (status);
1685 }
1686 
1687 
1688 
1689 #ifdef DEBUG
1690 void
1691 vdc_decode_tag(vdc_t *vdcp, vio_msg_t *msg)
1692 {
1693 	char *ms, *ss, *ses;
1694 	switch (msg->tag.vio_msgtype) {
1695 #define	Q(_s)	case _s : ms = #_s; break;
1696 	Q(VIO_TYPE_CTRL)
1697 	Q(VIO_TYPE_DATA)
1698 	Q(VIO_TYPE_ERR)
1699 #undef Q
1700 	default: ms = "unknown"; break;
1701 	}
1702 
1703 	switch (msg->tag.vio_subtype) {
1704 #define	Q(_s)	case _s : ss = #_s; break;
1705 	Q(VIO_SUBTYPE_INFO)
1706 	Q(VIO_SUBTYPE_ACK)
1707 	Q(VIO_SUBTYPE_NACK)
1708 #undef Q
1709 	default: ss = "unknown"; break;
1710 	}
1711 
1712 	switch (msg->tag.vio_subtype_env) {
1713 #define	Q(_s)	case _s : ses = #_s; break;
1714 	Q(VIO_VER_INFO)
1715 	Q(VIO_ATTR_INFO)
1716 	Q(VIO_DRING_REG)
1717 	Q(VIO_DRING_UNREG)
1718 	Q(VIO_RDX)
1719 	Q(VIO_PKT_DATA)
1720 	Q(VIO_DESC_DATA)
1721 	Q(VIO_DRING_DATA)
1722 #undef Q
1723 	default: ses = "unknown"; break;
1724 	}
1725 
1726 	DMSG(vdcp, 3, "(%x/%x/%x) message : (%s/%s/%s)\n",
1727 	    msg->tag.vio_msgtype, msg->tag.vio_subtype,
1728 	    msg->tag.vio_subtype_env, ms, ss, ses);
1729 }
1730 #endif
1731 
1732 /*
1733  * Function:
1734  *	vdc_send()
1735  *
1736  * Description:
1737  *	The function encapsulates the call to write a message using LDC.
1738  *	If LDC indicates that the call failed due to the queue being full,
1739  *	we retry the ldc_write() [ up to 'vdc_retries' time ], otherwise
1740  *	we return the error returned by LDC.
1741  *
1742  * Arguments:
1743  *	ldc_handle	- LDC handle for the channel this instance of vdc uses
1744  *	pkt		- address of LDC message to be sent
1745  *	msglen		- the size of the message being sent. When the function
1746  *			  returns, this contains the number of bytes written.
1747  *
1748  * Return Code:
1749  *	0		- Success.
1750  *	EINVAL		- pkt or msglen were NULL
1751  *	ECONNRESET	- The connection was not up.
1752  *	EWOULDBLOCK	- LDC queue is full
1753  *	xxx		- other error codes returned by ldc_write
1754  */
1755 static int
1756 vdc_send(vdc_t *vdc, caddr_t pkt, size_t *msglen)
1757 {
1758 	size_t	size = 0;
1759 	int	status = 0;
1760 	clock_t delay_ticks;
1761 
1762 	ASSERT(vdc != NULL);
1763 	ASSERT(mutex_owned(&vdc->lock));
1764 	ASSERT(msglen != NULL);
1765 	ASSERT(*msglen != 0);
1766 
1767 #ifdef DEBUG
1768 	vdc_decode_tag(vdc, (vio_msg_t *)pkt);
1769 #endif
1770 	/*
1771 	 * Wait indefinitely to send if channel
1772 	 * is busy, but bail out if we succeed or
1773 	 * if the channel closes or is reset.
1774 	 */
1775 	delay_ticks = vdc_hz_min_ldc_delay;
1776 	do {
1777 		size = *msglen;
1778 		status = ldc_write(vdc->ldc_handle, pkt, &size);
1779 		if (status == EWOULDBLOCK) {
1780 			delay(delay_ticks);
1781 			/* geometric backoff */
1782 			delay_ticks *= 2;
1783 			if (delay_ticks > vdc_hz_max_ldc_delay)
1784 				delay_ticks = vdc_hz_max_ldc_delay;
1785 		}
1786 	} while (status == EWOULDBLOCK);
1787 
1788 	/* if LDC had serious issues --- reset vdc state */
1789 	if (status == EIO || status == ECONNRESET) {
1790 		/* LDC had serious issues --- reset vdc state */
1791 		mutex_enter(&vdc->read_lock);
1792 		if ((vdc->read_state == VDC_READ_WAITING) ||
1793 		    (vdc->read_state == VDC_READ_RESET))
1794 			cv_signal(&vdc->read_cv);
1795 		vdc->read_state = VDC_READ_RESET;
1796 		mutex_exit(&vdc->read_lock);
1797 
1798 		/* wake up any waiters in the reset thread */
1799 		if (vdc->state == VDC_STATE_INIT_WAITING) {
1800 			DMSG(vdc, 0, "[%d] write reset - "
1801 			    "vdc is resetting ..\n", vdc->instance);
1802 			vdc->state = VDC_STATE_RESETTING;
1803 			cv_signal(&vdc->initwait_cv);
1804 		}
1805 
1806 		return (ECONNRESET);
1807 	}
1808 
1809 	/* return the last size written */
1810 	*msglen = size;
1811 
1812 	return (status);
1813 }
1814 
1815 /*
1816  * Function:
1817  *	vdc_get_ldc_id()
1818  *
1819  * Description:
1820  *	This function gets the 'ldc-id' for this particular instance of vdc.
1821  *	The id returned is the guest domain channel endpoint LDC uses for
1822  *	communication with vds.
1823  *
1824  * Arguments:
1825  *	dip	- dev info pointer for this instance of the device driver.
1826  *	ldc_id	- pointer to variable used to return the 'ldc-id' found.
1827  *
1828  * Return Code:
1829  *	0	- Success.
1830  *	ENOENT	- Expected node or property did not exist.
1831  *	ENXIO	- Unexpected error communicating with MD framework
1832  */
1833 static int
1834 vdc_get_ldc_id(dev_info_t *dip, uint64_t *ldc_id)
1835 {
1836 	int		status = ENOENT;
1837 	char		*node_name = NULL;
1838 	md_t		*mdp = NULL;
1839 	int		num_nodes;
1840 	int		num_vdevs;
1841 	int		num_chans;
1842 	mde_cookie_t	rootnode;
1843 	mde_cookie_t	*listp = NULL;
1844 	mde_cookie_t	*chanp = NULL;
1845 	boolean_t	found_inst = B_FALSE;
1846 	int		listsz;
1847 	int		idx;
1848 	uint64_t	md_inst;
1849 	int		obp_inst;
1850 	int		instance = ddi_get_instance(dip);
1851 
1852 	ASSERT(ldc_id != NULL);
1853 	*ldc_id = 0;
1854 
1855 	/*
1856 	 * Get the OBP instance number for comparison with the MD instance
1857 	 *
1858 	 * The "cfg-handle" property of a vdc node in an MD contains the MD's
1859 	 * notion of "instance", or unique identifier, for that node; OBP
1860 	 * stores the value of the "cfg-handle" MD property as the value of
1861 	 * the "reg" property on the node in the device tree it builds from
1862 	 * the MD and passes to Solaris.  Thus, we look up the devinfo node's
1863 	 * "reg" property value to uniquely identify this device instance.
1864 	 * If the "reg" property cannot be found, the device tree state is
1865 	 * presumably so broken that there is no point in continuing.
1866 	 */
1867 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, OBP_REG)) {
1868 		cmn_err(CE_WARN, "'%s' property does not exist", OBP_REG);
1869 		return (ENOENT);
1870 	}
1871 	obp_inst = ddi_prop_get_int(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
1872 			OBP_REG, -1);
1873 	DMSGX(1, "[%d] OBP inst=%d\n", instance, obp_inst);
1874 
1875 	/*
1876 	 * We now walk the MD nodes and if an instance of a vdc node matches
1877 	 * the instance got from OBP we get the ldc-id property.
1878 	 */
1879 	if ((mdp = md_get_handle()) == NULL) {
1880 		cmn_err(CE_WARN, "unable to init machine description");
1881 		return (ENXIO);
1882 	}
1883 
1884 	num_nodes = md_node_count(mdp);
1885 	ASSERT(num_nodes > 0);
1886 
1887 	listsz = num_nodes * sizeof (mde_cookie_t);
1888 
1889 	/* allocate memory for nodes */
1890 	listp = kmem_zalloc(listsz, KM_SLEEP);
1891 	chanp = kmem_zalloc(listsz, KM_SLEEP);
1892 
1893 	rootnode = md_root_node(mdp);
1894 	ASSERT(rootnode != MDE_INVAL_ELEM_COOKIE);
1895 
1896 	/*
1897 	 * Search for all the virtual devices, we will then check to see which
1898 	 * ones are disk nodes.
1899 	 */
1900 	num_vdevs = md_scan_dag(mdp, rootnode,
1901 			md_find_name(mdp, VDC_MD_VDEV_NAME),
1902 			md_find_name(mdp, "fwd"), listp);
1903 
1904 	if (num_vdevs <= 0) {
1905 		cmn_err(CE_NOTE, "No '%s' node found", VDC_MD_VDEV_NAME);
1906 		status = ENOENT;
1907 		goto done;
1908 	}
1909 
1910 	DMSGX(1, "[%d] num_vdevs=%d\n", instance, num_vdevs);
1911 	for (idx = 0; idx < num_vdevs; idx++) {
1912 		status = md_get_prop_str(mdp, listp[idx], "name", &node_name);
1913 		if ((status != 0) || (node_name == NULL)) {
1914 			cmn_err(CE_NOTE, "Unable to get name of node type '%s'"
1915 					": err %d", VDC_MD_VDEV_NAME, status);
1916 			continue;
1917 		}
1918 
1919 		DMSGX(1, "[%d] Found node '%s'\n", instance, node_name);
1920 		if (strcmp(VDC_MD_DISK_NAME, node_name) == 0) {
1921 			status = md_get_prop_val(mdp, listp[idx],
1922 					VDC_MD_CFG_HDL, &md_inst);
1923 			DMSGX(1, "[%d] vdc inst in MD=%lx\n",
1924 			    instance, md_inst);
1925 			if ((status == 0) && (md_inst == obp_inst)) {
1926 				found_inst = B_TRUE;
1927 				break;
1928 			}
1929 		}
1930 	}
1931 
1932 	if (!found_inst) {
1933 		DMSGX(0, "Unable to find correct '%s' node", VDC_MD_DISK_NAME);
1934 		status = ENOENT;
1935 		goto done;
1936 	}
1937 	DMSGX(0, "[%d] MD inst=%lx\n", instance, md_inst);
1938 
1939 	/* get the channels for this node */
1940 	num_chans = md_scan_dag(mdp, listp[idx],
1941 			md_find_name(mdp, VDC_MD_CHAN_NAME),
1942 			md_find_name(mdp, "fwd"), chanp);
1943 
1944 	/* expecting at least one channel */
1945 	if (num_chans <= 0) {
1946 		cmn_err(CE_NOTE, "No '%s' node for '%s' port",
1947 				VDC_MD_CHAN_NAME, VDC_MD_VDEV_NAME);
1948 		status = ENOENT;
1949 		goto done;
1950 
1951 	} else if (num_chans != 1) {
1952 		DMSGX(0, "[%d] Expected 1 '%s' node for '%s' port, found %d\n",
1953 			instance, VDC_MD_CHAN_NAME, VDC_MD_VDEV_NAME,
1954 			num_chans);
1955 	}
1956 
1957 	/*
1958 	 * We use the first channel found (index 0), irrespective of how
1959 	 * many are there in total.
1960 	 */
1961 	if (md_get_prop_val(mdp, chanp[0], VDC_ID_PROP, ldc_id) != 0) {
1962 		cmn_err(CE_NOTE, "Channel '%s' property not found",
1963 				VDC_ID_PROP);
1964 		status = ENOENT;
1965 	}
1966 
1967 	DMSGX(0, "[%d] LDC id is 0x%lx\n", instance, *ldc_id);
1968 
1969 done:
1970 	if (chanp)
1971 		kmem_free(chanp, listsz);
1972 	if (listp)
1973 		kmem_free(listp, listsz);
1974 
1975 	(void) md_fini_handle(mdp);
1976 
1977 	return (status);
1978 }
1979 
1980 static int
1981 vdc_do_ldc_up(vdc_t *vdc)
1982 {
1983 	int		status;
1984 	ldc_status_t	ldc_state;
1985 
1986 	DMSG(vdc, 0, "[%d] Bringing up channel %lx\n",
1987 	    vdc->instance, vdc->ldc_id);
1988 
1989 	if (vdc->lifecycle == VDC_LC_DETACHING)
1990 		return (EINVAL);
1991 
1992 	if ((status = ldc_up(vdc->ldc_handle)) != 0) {
1993 		switch (status) {
1994 		case ECONNREFUSED:	/* listener not ready at other end */
1995 			DMSG(vdc, 0, "[%d] ldc_up(%lx,...) return %d\n",
1996 					vdc->instance, vdc->ldc_id, status);
1997 			status = 0;
1998 			break;
1999 		default:
2000 			DMSG(vdc, 0, "[%d] Failed to bring up LDC: "
2001 			    "channel=%ld, err=%d", vdc->instance, vdc->ldc_id,
2002 			    status);
2003 			break;
2004 		}
2005 	}
2006 
2007 	if (ldc_status(vdc->ldc_handle, &ldc_state) == 0) {
2008 		vdc->ldc_state = ldc_state;
2009 		if (ldc_state == LDC_UP) {
2010 			DMSG(vdc, 0, "[%d] LDC channel already up\n",
2011 			    vdc->instance);
2012 			vdc->seq_num = 1;
2013 			vdc->seq_num_reply = 0;
2014 		}
2015 	}
2016 
2017 	return (status);
2018 }
2019 
2020 /*
2021  * Function:
2022  *	vdc_terminate_ldc()
2023  *
2024  * Description:
2025  *
2026  * Arguments:
2027  *	vdc	- soft state pointer for this instance of the device driver.
2028  *
2029  * Return Code:
2030  *	None
2031  */
2032 static void
2033 vdc_terminate_ldc(vdc_t *vdc)
2034 {
2035 	int	instance = ddi_get_instance(vdc->dip);
2036 
2037 	ASSERT(vdc != NULL);
2038 	ASSERT(mutex_owned(&vdc->lock));
2039 
2040 	DMSG(vdc, 0, "[%d] initialized=%x\n", instance, vdc->initialized);
2041 
2042 	if (vdc->initialized & VDC_LDC_OPEN) {
2043 		DMSG(vdc, 0, "[%d] ldc_close()\n", instance);
2044 		(void) ldc_close(vdc->ldc_handle);
2045 	}
2046 	if (vdc->initialized & VDC_LDC_CB) {
2047 		DMSG(vdc, 0, "[%d] ldc_unreg_callback()\n", instance);
2048 		(void) ldc_unreg_callback(vdc->ldc_handle);
2049 	}
2050 	if (vdc->initialized & VDC_LDC) {
2051 		DMSG(vdc, 0, "[%d] ldc_fini()\n", instance);
2052 		(void) ldc_fini(vdc->ldc_handle);
2053 		vdc->ldc_handle = NULL;
2054 	}
2055 
2056 	vdc->initialized &= ~(VDC_LDC | VDC_LDC_CB | VDC_LDC_OPEN);
2057 }
2058 
2059 /* -------------------------------------------------------------------------- */
2060 
2061 /*
2062  * Descriptor Ring helper routines
2063  */
2064 
2065 /*
2066  * Function:
2067  *	vdc_init_descriptor_ring()
2068  *
2069  * Description:
2070  *
2071  * Arguments:
2072  *	vdc	- soft state pointer for this instance of the device driver.
2073  *
2074  * Return Code:
2075  *	0	- Success
2076  */
2077 static int
2078 vdc_init_descriptor_ring(vdc_t *vdc)
2079 {
2080 	vd_dring_entry_t	*dep = NULL;	/* DRing Entry pointer */
2081 	int	status = 0;
2082 	int	i;
2083 
2084 	DMSG(vdc, 0, "[%d] initialized=%x\n", vdc->instance, vdc->initialized);
2085 
2086 	ASSERT(vdc != NULL);
2087 	ASSERT(mutex_owned(&vdc->lock));
2088 	ASSERT(vdc->ldc_handle != NULL);
2089 
2090 	/* ensure we have enough room to store max sized block */
2091 	ASSERT(maxphys <= VD_MAX_BLOCK_SIZE);
2092 
2093 	if ((vdc->initialized & VDC_DRING_INIT) == 0) {
2094 		DMSG(vdc, 0, "[%d] ldc_mem_dring_create\n", vdc->instance);
2095 		/*
2096 		 * Calculate the maximum block size we can transmit using one
2097 		 * Descriptor Ring entry from the attributes returned by the
2098 		 * vDisk server. This is subject to a minimum of 'maxphys'
2099 		 * as we do not have the capability to split requests over
2100 		 * multiple DRing entries.
2101 		 */
2102 		if ((vdc->max_xfer_sz * vdc->block_size) < maxphys) {
2103 			DMSG(vdc, 0, "[%d] using minimum DRing size\n",
2104 					vdc->instance);
2105 			vdc->dring_max_cookies = maxphys / PAGESIZE;
2106 		} else {
2107 			vdc->dring_max_cookies =
2108 				(vdc->max_xfer_sz * vdc->block_size) / PAGESIZE;
2109 		}
2110 		vdc->dring_entry_size = (sizeof (vd_dring_entry_t) +
2111 				(sizeof (ldc_mem_cookie_t) *
2112 					(vdc->dring_max_cookies - 1)));
2113 		vdc->dring_len = VD_DRING_LEN;
2114 
2115 		status = ldc_mem_dring_create(vdc->dring_len,
2116 				vdc->dring_entry_size, &vdc->ldc_dring_hdl);
2117 		if ((vdc->ldc_dring_hdl == NULL) || (status != 0)) {
2118 			DMSG(vdc, 0, "[%d] Descriptor ring creation failed",
2119 					vdc->instance);
2120 			return (status);
2121 		}
2122 		vdc->initialized |= VDC_DRING_INIT;
2123 	}
2124 
2125 	if ((vdc->initialized & VDC_DRING_BOUND) == 0) {
2126 		DMSG(vdc, 0, "[%d] ldc_mem_dring_bind\n", vdc->instance);
2127 		vdc->dring_cookie =
2128 			kmem_zalloc(sizeof (ldc_mem_cookie_t), KM_SLEEP);
2129 
2130 		status = ldc_mem_dring_bind(vdc->ldc_handle, vdc->ldc_dring_hdl,
2131 				LDC_SHADOW_MAP|LDC_DIRECT_MAP, LDC_MEM_RW,
2132 				&vdc->dring_cookie[0],
2133 				&vdc->dring_cookie_count);
2134 		if (status != 0) {
2135 			DMSG(vdc, 0, "[%d] Failed to bind descriptor ring "
2136 				"(%lx) to channel (%lx) status=%d\n",
2137 				vdc->instance, vdc->ldc_dring_hdl,
2138 				vdc->ldc_handle, status);
2139 			return (status);
2140 		}
2141 		ASSERT(vdc->dring_cookie_count == 1);
2142 		vdc->initialized |= VDC_DRING_BOUND;
2143 	}
2144 
2145 	status = ldc_mem_dring_info(vdc->ldc_dring_hdl, &vdc->dring_mem_info);
2146 	if (status != 0) {
2147 		DMSG(vdc, 0,
2148 		    "[%d] Failed to get info for descriptor ring (%lx)\n",
2149 		    vdc->instance, vdc->ldc_dring_hdl);
2150 		return (status);
2151 	}
2152 
2153 	if ((vdc->initialized & VDC_DRING_LOCAL) == 0) {
2154 		DMSG(vdc, 0, "[%d] local dring\n", vdc->instance);
2155 
2156 		/* Allocate the local copy of this dring */
2157 		vdc->local_dring =
2158 			kmem_zalloc(vdc->dring_len * sizeof (vdc_local_desc_t),
2159 						KM_SLEEP);
2160 		vdc->initialized |= VDC_DRING_LOCAL;
2161 	}
2162 
2163 	/*
2164 	 * Mark all DRing entries as free and initialize the private
2165 	 * descriptor's memory handles. If any entry is initialized,
2166 	 * we need to free it later so we set the bit in 'initialized'
2167 	 * at the start.
2168 	 */
2169 	vdc->initialized |= VDC_DRING_ENTRY;
2170 	for (i = 0; i < vdc->dring_len; i++) {
2171 		dep = VDC_GET_DRING_ENTRY_PTR(vdc, i);
2172 		dep->hdr.dstate = VIO_DESC_FREE;
2173 
2174 		status = ldc_mem_alloc_handle(vdc->ldc_handle,
2175 				&vdc->local_dring[i].desc_mhdl);
2176 		if (status != 0) {
2177 			DMSG(vdc, 0, "![%d] Failed to alloc mem handle for"
2178 					" descriptor %d", vdc->instance, i);
2179 			return (status);
2180 		}
2181 		vdc->local_dring[i].is_free = B_TRUE;
2182 		vdc->local_dring[i].dep = dep;
2183 	}
2184 
2185 	/* Initialize the starting index */
2186 	vdc->dring_curr_idx = 0;
2187 
2188 	return (status);
2189 }
2190 
2191 /*
2192  * Function:
2193  *	vdc_destroy_descriptor_ring()
2194  *
2195  * Description:
2196  *
2197  * Arguments:
2198  *	vdc	- soft state pointer for this instance of the device driver.
2199  *
2200  * Return Code:
2201  *	None
2202  */
2203 static void
2204 vdc_destroy_descriptor_ring(vdc_t *vdc)
2205 {
2206 	vdc_local_desc_t	*ldep = NULL;	/* Local Dring Entry Pointer */
2207 	ldc_mem_handle_t	mhdl = NULL;
2208 	ldc_mem_info_t		minfo;
2209 	int			status = -1;
2210 	int			i;	/* loop */
2211 
2212 	ASSERT(vdc != NULL);
2213 	ASSERT(mutex_owned(&vdc->lock));
2214 
2215 	DMSG(vdc, 0, "[%d] Entered\n", vdc->instance);
2216 
2217 	if (vdc->initialized & VDC_DRING_ENTRY) {
2218 		DMSG(vdc, 0,
2219 		    "[%d] Removing Local DRing entries\n", vdc->instance);
2220 		for (i = 0; i < vdc->dring_len; i++) {
2221 			ldep = &vdc->local_dring[i];
2222 			mhdl = ldep->desc_mhdl;
2223 
2224 			if (mhdl == NULL)
2225 				continue;
2226 
2227 			if ((status = ldc_mem_info(mhdl, &minfo)) != 0) {
2228 				DMSG(vdc, 0,
2229 				    "ldc_mem_info returned an error: %d\n",
2230 				    status);
2231 
2232 				/*
2233 				 * This must mean that the mem handle
2234 				 * is not valid. Clear it out so that
2235 				 * no one tries to use it.
2236 				 */
2237 				ldep->desc_mhdl = NULL;
2238 				continue;
2239 			}
2240 
2241 			if (minfo.status == LDC_BOUND) {
2242 				(void) ldc_mem_unbind_handle(mhdl);
2243 			}
2244 
2245 			(void) ldc_mem_free_handle(mhdl);
2246 
2247 			ldep->desc_mhdl = NULL;
2248 		}
2249 		vdc->initialized &= ~VDC_DRING_ENTRY;
2250 	}
2251 
2252 	if (vdc->initialized & VDC_DRING_LOCAL) {
2253 		DMSG(vdc, 0, "[%d] Freeing Local DRing\n", vdc->instance);
2254 		kmem_free(vdc->local_dring,
2255 				vdc->dring_len * sizeof (vdc_local_desc_t));
2256 		vdc->initialized &= ~VDC_DRING_LOCAL;
2257 	}
2258 
2259 	if (vdc->initialized & VDC_DRING_BOUND) {
2260 		DMSG(vdc, 0, "[%d] Unbinding DRing\n", vdc->instance);
2261 		status = ldc_mem_dring_unbind(vdc->ldc_dring_hdl);
2262 		if (status == 0) {
2263 			vdc->initialized &= ~VDC_DRING_BOUND;
2264 		} else {
2265 			DMSG(vdc, 0, "[%d] Error %d unbinding DRing %lx",
2266 				vdc->instance, status, vdc->ldc_dring_hdl);
2267 		}
2268 		kmem_free(vdc->dring_cookie, sizeof (ldc_mem_cookie_t));
2269 	}
2270 
2271 	if (vdc->initialized & VDC_DRING_INIT) {
2272 		DMSG(vdc, 0, "[%d] Destroying DRing\n", vdc->instance);
2273 		status = ldc_mem_dring_destroy(vdc->ldc_dring_hdl);
2274 		if (status == 0) {
2275 			vdc->ldc_dring_hdl = NULL;
2276 			bzero(&vdc->dring_mem_info, sizeof (ldc_mem_info_t));
2277 			vdc->initialized &= ~VDC_DRING_INIT;
2278 		} else {
2279 			DMSG(vdc, 0, "[%d] Error %d destroying DRing (%lx)",
2280 				vdc->instance, status, vdc->ldc_dring_hdl);
2281 		}
2282 	}
2283 }
2284 
2285 /*
2286  * Function:
2287  *	vdc_map_to_shared_ring()
2288  *
2289  * Description:
2290  *	Copy contents of the local descriptor to the shared
2291  *	memory descriptor.
2292  *
2293  * Arguments:
2294  *	vdcp	- soft state pointer for this instance of the device driver.
2295  *	idx	- descriptor ring index
2296  *
2297  * Return Code:
2298  *	None
2299  */
2300 static int
2301 vdc_map_to_shared_dring(vdc_t *vdcp, int idx)
2302 {
2303 	vdc_local_desc_t	*ldep;
2304 	vd_dring_entry_t	*dep;
2305 	int			rv;
2306 
2307 	ldep = &(vdcp->local_dring[idx]);
2308 
2309 	/* for now leave in the old pop_mem_hdl stuff */
2310 	if (ldep->nbytes > 0) {
2311 		rv = vdc_populate_mem_hdl(vdcp, ldep);
2312 		if (rv) {
2313 			DMSG(vdcp, 0, "[%d] Cannot populate mem handle\n",
2314 			    vdcp->instance);
2315 			return (rv);
2316 		}
2317 	}
2318 
2319 	/*
2320 	 * fill in the data details into the DRing
2321 	 */
2322 	dep = ldep->dep;
2323 	ASSERT(dep != NULL);
2324 
2325 	dep->payload.req_id = VDC_GET_NEXT_REQ_ID(vdcp);
2326 	dep->payload.operation = ldep->operation;
2327 	dep->payload.addr = ldep->offset;
2328 	dep->payload.nbytes = ldep->nbytes;
2329 	dep->payload.status = (uint32_t)-1;	/* vds will set valid value */
2330 	dep->payload.slice = ldep->slice;
2331 	dep->hdr.dstate = VIO_DESC_READY;
2332 	dep->hdr.ack = 1;		/* request an ACK for every message */
2333 
2334 	return (0);
2335 }
2336 
2337 /*
2338  * Function:
2339  *	vdc_send_request
2340  *
2341  * Description:
2342  *	This routine writes the data to be transmitted to vds into the
2343  *	descriptor, notifies vds that the ring has been updated and
2344  *	then waits for the request to be processed.
2345  *
2346  * Arguments:
2347  *	vdcp	  - the soft state pointer
2348  *	operation - operation we want vds to perform (VD_OP_XXX)
2349  *	addr	  - address of data buf to be read/written.
2350  *	nbytes	  - number of bytes to read/write
2351  *	slice	  - the disk slice this request is for
2352  *	offset	  - relative disk offset
2353  *	cb_type   - type of call - STRATEGY or SYNC
2354  *	cb_arg	  - parameter to be sent to server (depends on VD_OP_XXX type)
2355  *			. mode for ioctl(9e)
2356  *			. LP64 diskaddr_t (block I/O)
2357  *	dir	  - direction of operation (READ/WRITE/BOTH)
2358  *
2359  * Return Codes:
2360  *	0
2361  *	EAGAIN
2362  *		EFAULT
2363  *		ENXIO
2364  *		EIO
2365  */
2366 static int
2367 vdc_send_request(vdc_t *vdcp, int operation, caddr_t addr,
2368     size_t nbytes, int slice, diskaddr_t offset, int cb_type,
2369     void *cb_arg, vio_desc_direction_t dir)
2370 {
2371 	ASSERT(vdcp != NULL);
2372 	ASSERT(slice < V_NUMPAR);
2373 
2374 	mutex_enter(&vdcp->lock);
2375 
2376 	do {
2377 		while (vdcp->state != VDC_STATE_RUNNING) {
2378 			cv_wait(&vdcp->running_cv, &vdcp->lock);
2379 
2380 			/* return error if detaching */
2381 			if (vdcp->state == VDC_STATE_DETACH) {
2382 				mutex_exit(&vdcp->lock);
2383 				return (ENXIO);
2384 			}
2385 		}
2386 
2387 	} while (vdc_populate_descriptor(vdcp, operation, addr,
2388 	    nbytes, slice, offset, cb_type, cb_arg, dir));
2389 
2390 	mutex_exit(&vdcp->lock);
2391 	return (0);
2392 }
2393 
2394 
2395 /*
2396  * Function:
2397  *	vdc_populate_descriptor
2398  *
2399  * Description:
2400  *	This routine writes the data to be transmitted to vds into the
2401  *	descriptor, notifies vds that the ring has been updated and
2402  *	then waits for the request to be processed.
2403  *
2404  * Arguments:
2405  *	vdcp	  - the soft state pointer
2406  *	operation - operation we want vds to perform (VD_OP_XXX)
2407  *	addr	  - address of data buf to be read/written.
2408  *	nbytes	  - number of bytes to read/write
2409  *	slice	  - the disk slice this request is for
2410  *	offset	  - relative disk offset
2411  *	cb_type   - type of call - STRATEGY or SYNC
2412  *	cb_arg	  - parameter to be sent to server (depends on VD_OP_XXX type)
2413  *			. mode for ioctl(9e)
2414  *			. LP64 diskaddr_t (block I/O)
2415  *	dir	  - direction of operation (READ/WRITE/BOTH)
2416  *
2417  * Return Codes:
2418  *	0
2419  *	EAGAIN
2420  *		EFAULT
2421  *		ENXIO
2422  *		EIO
2423  */
2424 static int
2425 vdc_populate_descriptor(vdc_t *vdcp, int operation, caddr_t addr,
2426     size_t nbytes, int slice, diskaddr_t offset, int cb_type,
2427     void *cb_arg, vio_desc_direction_t dir)
2428 {
2429 	vdc_local_desc_t	*local_dep = NULL; /* Local Dring Pointer */
2430 	int			idx;		/* Index of DRing entry used */
2431 	int			next_idx;
2432 	vio_dring_msg_t		dmsg;
2433 	size_t			msglen;
2434 	int			rv;
2435 
2436 	ASSERT(MUTEX_HELD(&vdcp->lock));
2437 	vdcp->threads_pending++;
2438 loop:
2439 	DMSG(vdcp, 2, ": dring_curr_idx = %d\n", vdcp->dring_curr_idx);
2440 
2441 	/* Get next available D-Ring entry */
2442 	idx = vdcp->dring_curr_idx;
2443 	local_dep = &(vdcp->local_dring[idx]);
2444 
2445 	if (!local_dep->is_free) {
2446 		DMSG(vdcp, 2, "[%d]: dring full - waiting for space\n",
2447 		    vdcp->instance);
2448 		cv_wait(&vdcp->dring_free_cv, &vdcp->lock);
2449 		if (vdcp->state == VDC_STATE_RUNNING ||
2450 		    vdcp->state == VDC_STATE_HANDLE_PENDING) {
2451 			goto loop;
2452 		}
2453 		vdcp->threads_pending--;
2454 		return (ECONNRESET);
2455 	}
2456 
2457 	next_idx = idx + 1;
2458 	if (next_idx >= vdcp->dring_len)
2459 		next_idx = 0;
2460 	vdcp->dring_curr_idx = next_idx;
2461 
2462 	ASSERT(local_dep->is_free);
2463 
2464 	local_dep->operation = operation;
2465 	local_dep->addr = addr;
2466 	local_dep->nbytes = nbytes;
2467 	local_dep->slice = slice;
2468 	local_dep->offset = offset;
2469 	local_dep->cb_type = cb_type;
2470 	local_dep->cb_arg = cb_arg;
2471 	local_dep->dir = dir;
2472 
2473 	local_dep->is_free = B_FALSE;
2474 
2475 	rv = vdc_map_to_shared_dring(vdcp, idx);
2476 	if (rv) {
2477 		DMSG(vdcp, 0, "[%d]: cannot bind memory - waiting ..\n",
2478 		    vdcp->instance);
2479 		/* free the descriptor */
2480 		local_dep->is_free = B_TRUE;
2481 		vdcp->dring_curr_idx = idx;
2482 		cv_wait(&vdcp->membind_cv, &vdcp->lock);
2483 		if (vdcp->state == VDC_STATE_RUNNING ||
2484 		    vdcp->state == VDC_STATE_HANDLE_PENDING) {
2485 			goto loop;
2486 		}
2487 		vdcp->threads_pending--;
2488 		return (ECONNRESET);
2489 	}
2490 
2491 	/*
2492 	 * Send a msg with the DRing details to vds
2493 	 */
2494 	VIO_INIT_DRING_DATA_TAG(dmsg);
2495 	VDC_INIT_DRING_DATA_MSG_IDS(dmsg, vdcp);
2496 	dmsg.dring_ident = vdcp->dring_ident;
2497 	dmsg.start_idx = idx;
2498 	dmsg.end_idx = idx;
2499 	vdcp->seq_num++;
2500 
2501 	DTRACE_IO2(send, vio_dring_msg_t *, &dmsg, vdc_t *, vdcp);
2502 
2503 	DMSG(vdcp, 2, "ident=0x%lx, st=%u, end=%u, seq=%ld\n",
2504 	    vdcp->dring_ident, dmsg.start_idx, dmsg.end_idx, dmsg.seq_num);
2505 
2506 	/*
2507 	 * note we're still holding the lock here to
2508 	 * make sure the message goes out in order !!!...
2509 	 */
2510 	msglen = sizeof (dmsg);
2511 	rv = vdc_send(vdcp, (caddr_t)&dmsg, &msglen);
2512 	switch (rv) {
2513 	case ECONNRESET:
2514 		/*
2515 		 * vdc_send initiates the reset on failure.
2516 		 * Since the transaction has already been put
2517 		 * on the local dring, it will automatically get
2518 		 * retried when the channel is reset. Given that,
2519 		 * it is ok to just return success even though the
2520 		 * send failed.
2521 		 */
2522 		rv = 0;
2523 		break;
2524 
2525 	case 0: /* EOK */
2526 		DMSG(vdcp, 1, "sent via LDC: rv=%d\n", rv);
2527 		break;
2528 
2529 	default:
2530 		goto cleanup_and_exit;
2531 	}
2532 
2533 	vdcp->threads_pending--;
2534 	return (rv);
2535 
2536 cleanup_and_exit:
2537 	DMSG(vdcp, 0, "unexpected error, rv=%d\n", rv);
2538 	return (ENXIO);
2539 }
2540 
2541 /*
2542  * Function:
2543  *	vdc_do_sync_op
2544  *
2545  * Description:
2546  * 	Wrapper around vdc_populate_descriptor that blocks until the
2547  * 	response to the message is available.
2548  *
2549  * Arguments:
2550  *	vdcp	  - the soft state pointer
2551  *	operation - operation we want vds to perform (VD_OP_XXX)
2552  *	addr	  - address of data buf to be read/written.
2553  *	nbytes	  - number of bytes to read/write
2554  *	slice	  - the disk slice this request is for
2555  *	offset	  - relative disk offset
2556  *	cb_type   - type of call - STRATEGY or SYNC
2557  *	cb_arg	  - parameter to be sent to server (depends on VD_OP_XXX type)
2558  *			. mode for ioctl(9e)
2559  *			. LP64 diskaddr_t (block I/O)
2560  *	dir	  - direction of operation (READ/WRITE/BOTH)
2561  *
2562  * Return Codes:
2563  *	0
2564  *	EAGAIN
2565  *		EFAULT
2566  *		ENXIO
2567  *		EIO
2568  */
2569 static int
2570 vdc_do_sync_op(vdc_t *vdcp, int operation, caddr_t addr, size_t nbytes,
2571     int slice, diskaddr_t offset, int cb_type, void *cb_arg,
2572     vio_desc_direction_t dir)
2573 {
2574 	int status;
2575 
2576 	ASSERT(cb_type == CB_SYNC);
2577 
2578 	/*
2579 	 * Grab the lock, if blocked wait until the server
2580 	 * response causes us to wake up again.
2581 	 */
2582 	mutex_enter(&vdcp->lock);
2583 	vdcp->sync_op_cnt++;
2584 	while (vdcp->sync_op_blocked && vdcp->state != VDC_STATE_DETACH)
2585 		cv_wait(&vdcp->sync_blocked_cv, &vdcp->lock);
2586 
2587 	if (vdcp->state == VDC_STATE_DETACH) {
2588 		cv_broadcast(&vdcp->sync_blocked_cv);
2589 		vdcp->sync_op_cnt--;
2590 		mutex_exit(&vdcp->lock);
2591 		return (ENXIO);
2592 	}
2593 
2594 	/* now block anyone other thread entering after us */
2595 	vdcp->sync_op_blocked = B_TRUE;
2596 	vdcp->sync_op_pending = B_TRUE;
2597 	mutex_exit(&vdcp->lock);
2598 
2599 	/*
2600 	 * No need to check return value - will return error only
2601 	 * in the DETACH case and we can fall through
2602 	 */
2603 	(void) vdc_send_request(vdcp, operation, addr,
2604 	    nbytes, slice, offset, cb_type, cb_arg, dir);
2605 
2606 	/*
2607 	 * block until our transaction completes.
2608 	 * Also anyone else waiting also gets to go next.
2609 	 */
2610 	mutex_enter(&vdcp->lock);
2611 	while (vdcp->sync_op_pending && vdcp->state != VDC_STATE_DETACH)
2612 		cv_wait(&vdcp->sync_pending_cv, &vdcp->lock);
2613 
2614 	DMSG(vdcp, 2, ": operation returned %d\n", vdcp->sync_op_status);
2615 	if (vdcp->state == VDC_STATE_DETACH) {
2616 		vdcp->sync_op_pending = B_FALSE;
2617 		status = ENXIO;
2618 	} else {
2619 		status = vdcp->sync_op_status;
2620 	}
2621 
2622 	vdcp->sync_op_status = 0;
2623 	vdcp->sync_op_blocked = B_FALSE;
2624 	vdcp->sync_op_cnt--;
2625 
2626 	/* signal the next waiting thread */
2627 	cv_signal(&vdcp->sync_blocked_cv);
2628 	mutex_exit(&vdcp->lock);
2629 
2630 	return (status);
2631 }
2632 
2633 
2634 /*
2635  * Function:
2636  *	vdc_drain_response()
2637  *
2638  * Description:
2639  * 	When a guest is panicking, the completion of requests needs to be
2640  * 	handled differently because interrupts are disabled and vdc
2641  * 	will not get messages. We have to poll for the messages instead.
2642  *
2643  * Arguments:
2644  *	vdc	- soft state pointer for this instance of the device driver.
2645  *
2646  * Return Code:
2647  *	0	- Success
2648  */
2649 static int
2650 vdc_drain_response(vdc_t *vdc)
2651 {
2652 	int 			rv, idx, retries;
2653 	size_t			msglen;
2654 	vdc_local_desc_t 	*ldep = NULL;	/* Local Dring Entry Pointer */
2655 	vio_dring_msg_t		dmsg;
2656 
2657 	mutex_enter(&vdc->lock);
2658 
2659 	retries = 0;
2660 	for (;;) {
2661 		msglen = sizeof (dmsg);
2662 		rv = ldc_read(vdc->ldc_handle, (caddr_t)&dmsg, &msglen);
2663 		if (rv) {
2664 			rv = EINVAL;
2665 			break;
2666 		}
2667 
2668 		/*
2669 		 * if there are no packets wait and check again
2670 		 */
2671 		if ((rv == 0) && (msglen == 0)) {
2672 			if (retries++ > vdc_dump_retries) {
2673 				rv = EAGAIN;
2674 				break;
2675 			}
2676 
2677 			drv_usecwait(vdc_usec_timeout_dump);
2678 			continue;
2679 		}
2680 
2681 		/*
2682 		 * Ignore all messages that are not ACKs/NACKs to
2683 		 * DRing requests.
2684 		 */
2685 		if ((dmsg.tag.vio_msgtype != VIO_TYPE_DATA) ||
2686 		    (dmsg.tag.vio_subtype_env != VIO_DRING_DATA)) {
2687 			DMSG(vdc, 0, "discard pkt: type=%d sub=%d env=%d\n",
2688 			    dmsg.tag.vio_msgtype,
2689 			    dmsg.tag.vio_subtype,
2690 			    dmsg.tag.vio_subtype_env);
2691 			continue;
2692 		}
2693 
2694 		/*
2695 		 * set the appropriate return value for the current request.
2696 		 */
2697 		switch (dmsg.tag.vio_subtype) {
2698 		case VIO_SUBTYPE_ACK:
2699 			rv = 0;
2700 			break;
2701 		case VIO_SUBTYPE_NACK:
2702 			rv = EAGAIN;
2703 			break;
2704 		default:
2705 			continue;
2706 		}
2707 
2708 		idx = dmsg.start_idx;
2709 		if (idx >= vdc->dring_len) {
2710 			DMSG(vdc, 0, "[%d] Bogus ack data : start %d\n",
2711 			    vdc->instance, idx);
2712 			continue;
2713 		}
2714 		ldep = &vdc->local_dring[idx];
2715 		if (ldep->dep->hdr.dstate != VIO_DESC_DONE) {
2716 			DMSG(vdc, 0, "[%d] Entry @ %d - state !DONE %d\n",
2717 			    vdc->instance, idx, ldep->dep->hdr.dstate);
2718 			continue;
2719 		}
2720 
2721 		DMSG(vdc, 1, "[%d] Depopulating idx=%d state=%d\n",
2722 		    vdc->instance, idx, ldep->dep->hdr.dstate);
2723 		rv = vdc_depopulate_descriptor(vdc, idx);
2724 		if (rv) {
2725 			DMSG(vdc, 0,
2726 			    "[%d] Entry @ %d - depopulate failed ..\n",
2727 			    vdc->instance, idx);
2728 		}
2729 
2730 		/* if this is the last descriptor - break out of loop */
2731 		if ((idx + 1) % vdc->dring_len == vdc->dring_curr_idx)
2732 			break;
2733 	}
2734 
2735 	mutex_exit(&vdc->lock);
2736 	DMSG(vdc, 0, "End idx=%d\n", idx);
2737 
2738 	return (rv);
2739 }
2740 
2741 
2742 /*
2743  * Function:
2744  *	vdc_depopulate_descriptor()
2745  *
2746  * Description:
2747  *
2748  * Arguments:
2749  *	vdc	- soft state pointer for this instance of the device driver.
2750  *	idx	- Index of the Descriptor Ring entry being modified
2751  *
2752  * Return Code:
2753  *	0	- Success
2754  */
2755 static int
2756 vdc_depopulate_descriptor(vdc_t *vdc, uint_t idx)
2757 {
2758 	vd_dring_entry_t *dep = NULL;		/* Dring Entry Pointer */
2759 	vdc_local_desc_t *ldep = NULL;		/* Local Dring Entry Pointer */
2760 	int		status = ENXIO;
2761 	int		operation;
2762 	int		rv = 0;
2763 
2764 	ASSERT(vdc != NULL);
2765 	ASSERT(idx < vdc->dring_len);
2766 	ldep = &vdc->local_dring[idx];
2767 	ASSERT(ldep != NULL);
2768 	ASSERT(MUTEX_HELD(&vdc->lock));
2769 
2770 	DMSG(vdc, 2, ": idx = %d\n", idx);
2771 	dep = ldep->dep;
2772 	ASSERT(dep != NULL);
2773 	ASSERT((dep->hdr.dstate == VIO_DESC_DONE) ||
2774 			(dep->payload.status == ECANCELED));
2775 
2776 	VDC_MARK_DRING_ENTRY_FREE(vdc, idx);
2777 
2778 	ldep->is_free = B_TRUE;
2779 	DMSG(vdc, 2, ": is_free = %d\n", ldep->is_free);
2780 	status = dep->payload.status;
2781 	operation = dep->payload.operation;
2782 
2783 	/* the DKIO FLUSH operation never bind handles so we can return now */
2784 	if (operation == VD_OP_FLUSH)
2785 		return (status);
2786 
2787 	/*
2788 	 * If the upper layer passed in a misaligned address we copied the
2789 	 * data into an aligned buffer before sending it to LDC - we now
2790 	 * copy it back to the original buffer.
2791 	 */
2792 	if (ldep->align_addr) {
2793 		ASSERT(ldep->addr != NULL);
2794 
2795 		if (dep->payload.nbytes > 0)
2796 			bcopy(ldep->align_addr, ldep->addr,
2797 			    dep->payload.nbytes);
2798 		kmem_free(ldep->align_addr,
2799 			sizeof (caddr_t) * P2ROUNDUP(ldep->nbytes, 8));
2800 		ldep->align_addr = NULL;
2801 	}
2802 
2803 	rv = ldc_mem_unbind_handle(ldep->desc_mhdl);
2804 	if (rv != 0) {
2805 		DMSG(vdc, 0, "?[%d] unbind mhdl 0x%lx @ idx %d failed (%d)",
2806 				vdc->instance, ldep->desc_mhdl, idx, rv);
2807 		/*
2808 		 * The error returned by the vDisk server is more informative
2809 		 * and thus has a higher priority but if it isn't set we ensure
2810 		 * that this function returns an error.
2811 		 */
2812 		if (status == 0)
2813 			status = EINVAL;
2814 	}
2815 
2816 	cv_signal(&vdc->membind_cv);
2817 	cv_signal(&vdc->dring_free_cv);
2818 
2819 	return (status);
2820 }
2821 
2822 /*
2823  * Function:
2824  *	vdc_populate_mem_hdl()
2825  *
2826  * Description:
2827  *
2828  * Arguments:
2829  *	vdc	- soft state pointer for this instance of the device driver.
2830  *	idx	- Index of the Descriptor Ring entry being modified
2831  *	addr	- virtual address being mapped in
2832  *	nybtes	- number of bytes in 'addr'
2833  *	operation - the vDisk operation being performed (VD_OP_xxx)
2834  *
2835  * Return Code:
2836  *	0	- Success
2837  */
2838 static int
2839 vdc_populate_mem_hdl(vdc_t *vdcp, vdc_local_desc_t *ldep)
2840 {
2841 	vd_dring_entry_t	*dep = NULL;
2842 	ldc_mem_handle_t	mhdl;
2843 	caddr_t			vaddr;
2844 	size_t			nbytes;
2845 	uint8_t			perm = LDC_MEM_RW;
2846 	uint8_t			maptype;
2847 	int			rv = 0;
2848 	int			i;
2849 
2850 	ASSERT(vdcp != NULL);
2851 
2852 	dep = ldep->dep;
2853 	mhdl = ldep->desc_mhdl;
2854 
2855 	switch (ldep->dir) {
2856 	case VIO_read_dir:
2857 		perm = LDC_MEM_W;
2858 		break;
2859 
2860 	case VIO_write_dir:
2861 		perm = LDC_MEM_R;
2862 		break;
2863 
2864 	case VIO_both_dir:
2865 		perm = LDC_MEM_RW;
2866 		break;
2867 
2868 	default:
2869 		ASSERT(0);	/* catch bad programming in vdc */
2870 	}
2871 
2872 	/*
2873 	 * LDC expects any addresses passed in to be 8-byte aligned. We need
2874 	 * to copy the contents of any misaligned buffers to a newly allocated
2875 	 * buffer and bind it instead (and copy the the contents back to the
2876 	 * original buffer passed in when depopulating the descriptor)
2877 	 */
2878 	vaddr = ldep->addr;
2879 	nbytes = ldep->nbytes;
2880 	if (((uint64_t)vaddr & 0x7) != 0) {
2881 		ASSERT(ldep->align_addr == NULL);
2882 		ldep->align_addr =
2883 			kmem_alloc(sizeof (caddr_t) *
2884 				P2ROUNDUP(nbytes, 8), KM_SLEEP);
2885 		DMSG(vdcp, 0, "[%d] Misaligned address %p reallocating "
2886 		    "(buf=%p nb=%ld op=%d)\n",
2887 		    vdcp->instance, (void *)vaddr, (void *)ldep->align_addr,
2888 		    nbytes, ldep->operation);
2889 		if (perm != LDC_MEM_W)
2890 			bcopy(vaddr, ldep->align_addr, nbytes);
2891 		vaddr = ldep->align_addr;
2892 	}
2893 
2894 	maptype = LDC_IO_MAP|LDC_SHADOW_MAP|LDC_DIRECT_MAP;
2895 	rv = ldc_mem_bind_handle(mhdl, vaddr, P2ROUNDUP(nbytes, 8),
2896 		maptype, perm, &dep->payload.cookie[0],
2897 		&dep->payload.ncookies);
2898 	DMSG(vdcp, 2, "[%d] bound mem handle; ncookies=%d\n",
2899 			vdcp->instance, dep->payload.ncookies);
2900 	if (rv != 0) {
2901 		DMSG(vdcp, 0, "[%d] Failed to bind LDC memory handle "
2902 		    "(mhdl=%p, buf=%p, err=%d)\n",
2903 		    vdcp->instance, (void *)mhdl, (void *)vaddr, rv);
2904 		if (ldep->align_addr) {
2905 			kmem_free(ldep->align_addr,
2906 				sizeof (caddr_t) * P2ROUNDUP(nbytes, 8));
2907 			ldep->align_addr = NULL;
2908 		}
2909 		return (EAGAIN);
2910 	}
2911 
2912 	/*
2913 	 * Get the other cookies (if any).
2914 	 */
2915 	for (i = 1; i < dep->payload.ncookies; i++) {
2916 		rv = ldc_mem_nextcookie(mhdl, &dep->payload.cookie[i]);
2917 		if (rv != 0) {
2918 			(void) ldc_mem_unbind_handle(mhdl);
2919 			DMSG(vdcp, 0, "?[%d] Failed to get next cookie "
2920 					"(mhdl=%lx cnum=%d), err=%d",
2921 					vdcp->instance, mhdl, i, rv);
2922 			if (ldep->align_addr) {
2923 				kmem_free(ldep->align_addr,
2924 					sizeof (caddr_t) * ldep->nbytes);
2925 				ldep->align_addr = NULL;
2926 			}
2927 			return (EAGAIN);
2928 		}
2929 	}
2930 
2931 	return (rv);
2932 }
2933 
2934 /*
2935  * Interrupt handlers for messages from LDC
2936  */
2937 
2938 /*
2939  * Function:
2940  *	vdc_handle_cb()
2941  *
2942  * Description:
2943  *
2944  * Arguments:
2945  *	event	- Type of event (LDC_EVT_xxx) that triggered the callback
2946  *	arg	- soft state pointer for this instance of the device driver.
2947  *
2948  * Return Code:
2949  *	0	- Success
2950  */
2951 static uint_t
2952 vdc_handle_cb(uint64_t event, caddr_t arg)
2953 {
2954 	ldc_status_t	ldc_state;
2955 	int		rv = 0;
2956 
2957 	vdc_t	*vdc = (vdc_t *)(void *)arg;
2958 
2959 	ASSERT(vdc != NULL);
2960 
2961 	DMSG(vdc, 1, "evt=%lx seqID=%ld\n", event, vdc->seq_num);
2962 
2963 	/*
2964 	 * Depending on the type of event that triggered this callback,
2965 	 * we modify the handshake state or read the data.
2966 	 *
2967 	 * NOTE: not done as a switch() as event could be triggered by
2968 	 * a state change and a read request. Also the ordering	of the
2969 	 * check for the event types is deliberate.
2970 	 */
2971 	if (event & LDC_EVT_UP) {
2972 		DMSG(vdc, 0, "[%d] Received LDC_EVT_UP\n", vdc->instance);
2973 
2974 		mutex_enter(&vdc->lock);
2975 
2976 		/* get LDC state */
2977 		rv = ldc_status(vdc->ldc_handle, &ldc_state);
2978 		if (rv != 0) {
2979 			DMSG(vdc, 0, "[%d] Couldn't get LDC status %d",
2980 			    vdc->instance, rv);
2981 			return (LDC_SUCCESS);
2982 		}
2983 		if (vdc->ldc_state != LDC_UP && ldc_state == LDC_UP) {
2984 			/*
2985 			 * Reset the transaction sequence numbers when
2986 			 * LDC comes up. We then kick off the handshake
2987 			 * negotiation with the vDisk server.
2988 			 */
2989 			vdc->seq_num = 1;
2990 			vdc->seq_num_reply = 0;
2991 			vdc->ldc_state = ldc_state;
2992 			cv_signal(&vdc->initwait_cv);
2993 		}
2994 
2995 		mutex_exit(&vdc->lock);
2996 	}
2997 
2998 	if (event & LDC_EVT_READ) {
2999 		DMSG(vdc, 0, "[%d] Received LDC_EVT_READ\n", vdc->instance);
3000 		mutex_enter(&vdc->read_lock);
3001 		cv_signal(&vdc->read_cv);
3002 		vdc->read_state = VDC_READ_PENDING;
3003 		mutex_exit(&vdc->read_lock);
3004 
3005 		/* that's all we have to do - no need to handle DOWN/RESET */
3006 		return (LDC_SUCCESS);
3007 	}
3008 
3009 	if (event & (LDC_EVT_RESET|LDC_EVT_DOWN)) {
3010 
3011 		DMSG(vdc, 0, "[%d] Received LDC RESET event\n", vdc->instance);
3012 
3013 		mutex_enter(&vdc->lock);
3014 		/*
3015 		 * Need to wake up any readers so they will
3016 		 * detect that a reset has occurred.
3017 		 */
3018 		mutex_enter(&vdc->read_lock);
3019 		if ((vdc->read_state == VDC_READ_WAITING) ||
3020 		    (vdc->read_state == VDC_READ_RESET))
3021 			cv_signal(&vdc->read_cv);
3022 		vdc->read_state = VDC_READ_RESET;
3023 		mutex_exit(&vdc->read_lock);
3024 
3025 		/* wake up any threads waiting for connection to come up */
3026 		if (vdc->state == VDC_STATE_INIT_WAITING) {
3027 			vdc->state = VDC_STATE_RESETTING;
3028 			cv_signal(&vdc->initwait_cv);
3029 		}
3030 
3031 		mutex_exit(&vdc->lock);
3032 	}
3033 
3034 	if (event & ~(LDC_EVT_UP | LDC_EVT_RESET | LDC_EVT_DOWN | LDC_EVT_READ))
3035 		DMSG(vdc, 0, "![%d] Unexpected LDC event (%lx) received",
3036 				vdc->instance, event);
3037 
3038 	return (LDC_SUCCESS);
3039 }
3040 
3041 /*
3042  * Function:
3043  *	vdc_wait_for_response()
3044  *
3045  * Description:
3046  *	Block waiting for a response from the server. If there is
3047  *	no data the thread block on the read_cv that is signalled
3048  *	by the callback when an EVT_READ occurs.
3049  *
3050  * Arguments:
3051  *	vdcp	- soft state pointer for this instance of the device driver.
3052  *
3053  * Return Code:
3054  *	0	- Success
3055  */
3056 static int
3057 vdc_wait_for_response(vdc_t *vdcp, vio_msg_t *msgp)
3058 {
3059 	size_t		nbytes = sizeof (*msgp);
3060 	int		status;
3061 
3062 	ASSERT(vdcp != NULL);
3063 
3064 	DMSG(vdcp, 1, "[%d] Entered\n", vdcp->instance);
3065 
3066 	status = vdc_recv(vdcp, msgp, &nbytes);
3067 	DMSG(vdcp, 3, "vdc_read() done.. status=0x%x size=0x%x\n",
3068 		status, (int)nbytes);
3069 	if (status) {
3070 		DMSG(vdcp, 0, "?[%d] Error %d reading LDC msg\n",
3071 				vdcp->instance, status);
3072 		return (status);
3073 	}
3074 
3075 	if (nbytes < sizeof (vio_msg_tag_t)) {
3076 		DMSG(vdcp, 0, "?[%d] Expect %lu bytes; recv'd %lu\n",
3077 			vdcp->instance, sizeof (vio_msg_tag_t), nbytes);
3078 		return (ENOMSG);
3079 	}
3080 
3081 	DMSG(vdcp, 2, "[%d] (%x/%x/%x)\n", vdcp->instance,
3082 	    msgp->tag.vio_msgtype,
3083 	    msgp->tag.vio_subtype,
3084 	    msgp->tag.vio_subtype_env);
3085 
3086 	/*
3087 	 * Verify the Session ID of the message
3088 	 *
3089 	 * Every message after the Version has been negotiated should
3090 	 * have the correct session ID set.
3091 	 */
3092 	if ((msgp->tag.vio_sid != vdcp->session_id) &&
3093 	    (msgp->tag.vio_subtype_env != VIO_VER_INFO)) {
3094 		DMSG(vdcp, 0, "[%d] Invalid SID: received 0x%x, "
3095 				"expected 0x%lx [seq num %lx @ %d]",
3096 			vdcp->instance, msgp->tag.vio_sid,
3097 			vdcp->session_id,
3098 			((vio_dring_msg_t *)msgp)->seq_num,
3099 			((vio_dring_msg_t *)msgp)->start_idx);
3100 		return (ENOMSG);
3101 	}
3102 	return (0);
3103 }
3104 
3105 
3106 /*
3107  * Function:
3108  *	vdc_resubmit_backup_dring()
3109  *
3110  * Description:
3111  *	Resubmit each descriptor in the backed up dring to
3112  * 	vDisk server. The Dring was backed up during connection
3113  *	reset.
3114  *
3115  * Arguments:
3116  *	vdcp	- soft state pointer for this instance of the device driver.
3117  *
3118  * Return Code:
3119  *	0	- Success
3120  */
3121 static int
3122 vdc_resubmit_backup_dring(vdc_t *vdcp)
3123 {
3124 	int		count;
3125 	int		b_idx;
3126 	int		rv;
3127 	int		dring_size;
3128 	int		status;
3129 	vio_msg_t	vio_msg;
3130 	vdc_local_desc_t	*curr_ldep;
3131 
3132 	ASSERT(MUTEX_NOT_HELD(&vdcp->lock));
3133 	ASSERT(vdcp->state == VDC_STATE_HANDLE_PENDING);
3134 
3135 	DMSG(vdcp, 1, "restoring pending dring entries (len=%d, tail=%d)\n",
3136 	    vdcp->local_dring_backup_len, vdcp->local_dring_backup_tail);
3137 
3138 	/*
3139 	 * Walk the backup copy of the local descriptor ring and
3140 	 * resubmit all the outstanding transactions.
3141 	 */
3142 	b_idx = vdcp->local_dring_backup_tail;
3143 	for (count = 0; count < vdcp->local_dring_backup_len; count++) {
3144 
3145 		curr_ldep = &(vdcp->local_dring_backup[b_idx]);
3146 
3147 		/* only resubmit oustanding transactions */
3148 		if (!curr_ldep->is_free) {
3149 
3150 			DMSG(vdcp, 1, "resubmitting entry idx=%x\n", b_idx);
3151 			mutex_enter(&vdcp->lock);
3152 			rv = vdc_populate_descriptor(vdcp, curr_ldep->operation,
3153 			    curr_ldep->addr, curr_ldep->nbytes,
3154 			    curr_ldep->slice, curr_ldep->offset,
3155 			    curr_ldep->cb_type, curr_ldep->cb_arg,
3156 			    curr_ldep->dir);
3157 			mutex_exit(&vdcp->lock);
3158 			if (rv) {
3159 				DMSG(vdcp, 1, "[%d] cannot resubmit entry %d\n",
3160 				    vdcp->instance, b_idx);
3161 				return (rv);
3162 			}
3163 
3164 			/* Wait for the response message. */
3165 			DMSG(vdcp, 1, "waiting for response to idx=%x\n",
3166 			    b_idx);
3167 			status = vdc_wait_for_response(vdcp, &vio_msg);
3168 			if (status) {
3169 				DMSG(vdcp, 1, "[%d] wait_for_response "
3170 				    "returned err=%d\n", vdcp->instance,
3171 				    status);
3172 				return (status);
3173 			}
3174 
3175 			DMSG(vdcp, 1, "processing msg for idx=%x\n", b_idx);
3176 			status = vdc_process_data_msg(vdcp, &vio_msg);
3177 			if (status) {
3178 				DMSG(vdcp, 1, "[%d] process_data_msg "
3179 				    "returned err=%d\n", vdcp->instance,
3180 				    status);
3181 				return (status);
3182 			}
3183 		}
3184 
3185 		/* get the next element to submit */
3186 		if (++b_idx >= vdcp->local_dring_backup_len)
3187 			b_idx = 0;
3188 	}
3189 
3190 	/* all done - now clear up pending dring copy */
3191 	dring_size = vdcp->local_dring_backup_len *
3192 		sizeof (vdcp->local_dring_backup[0]);
3193 
3194 	(void) kmem_free(vdcp->local_dring_backup, dring_size);
3195 
3196 	vdcp->local_dring_backup = NULL;
3197 
3198 	return (0);
3199 }
3200 
3201 /*
3202  * Function:
3203  *	vdc_backup_local_dring()
3204  *
3205  * Description:
3206  *	Backup the current dring in the event of a reset. The Dring
3207  *	transactions will be resubmitted to the server when the
3208  *	connection is restored.
3209  *
3210  * Arguments:
3211  *	vdcp	- soft state pointer for this instance of the device driver.
3212  *
3213  * Return Code:
3214  *	NONE
3215  */
3216 static void
3217 vdc_backup_local_dring(vdc_t *vdcp)
3218 {
3219 	int dring_size;
3220 
3221 	ASSERT(vdcp->state == VDC_STATE_RESETTING);
3222 
3223 	/*
3224 	 * If the backup dring is stil around, it means
3225 	 * that the last restore did not complete. However,
3226 	 * since we never got back into the running state,
3227 	 * the backup copy we have is still valid.
3228 	 */
3229 	if (vdcp->local_dring_backup != NULL) {
3230 		DMSG(vdcp, 1, "reusing local descriptor ring backup "
3231 		    "(len=%d, tail=%d)\n", vdcp->local_dring_backup_len,
3232 		    vdcp->local_dring_backup_tail);
3233 		return;
3234 	}
3235 
3236 	DMSG(vdcp, 1, "backing up the local descriptor ring (len=%d, "
3237 	    "tail=%d)\n", vdcp->dring_len, vdcp->dring_curr_idx);
3238 
3239 	dring_size = vdcp->dring_len * sizeof (vdcp->local_dring[0]);
3240 
3241 	vdcp->local_dring_backup = kmem_alloc(dring_size, KM_SLEEP);
3242 	bcopy(vdcp->local_dring, vdcp->local_dring_backup, dring_size);
3243 
3244 	vdcp->local_dring_backup_tail = vdcp->dring_curr_idx;
3245 	vdcp->local_dring_backup_len = vdcp->dring_len;
3246 }
3247 
3248 /* -------------------------------------------------------------------------- */
3249 
3250 /*
3251  * The following functions process the incoming messages from vds
3252  */
3253 
3254 /*
3255  * Function:
3256  *      vdc_process_msg_thread()
3257  *
3258  * Description:
3259  *
3260  *	Main VDC message processing thread. Each vDisk instance
3261  * 	consists of a copy of this thread. This thread triggers
3262  * 	all the handshakes and data exchange with the server. It
3263  * 	also handles all channel resets
3264  *
3265  * Arguments:
3266  *      vdc     - soft state pointer for this instance of the device driver.
3267  *
3268  * Return Code:
3269  *      None
3270  */
3271 static void
3272 vdc_process_msg_thread(vdc_t *vdcp)
3273 {
3274 	int	status;
3275 
3276 	mutex_enter(&vdcp->lock);
3277 
3278 	for (;;) {
3279 
3280 #define	Q(_s)	(vdcp->state == _s) ? #_s :
3281 		DMSG(vdcp, 3, "state = %d (%s)\n", vdcp->state,
3282 		Q(VDC_STATE_INIT)
3283 		Q(VDC_STATE_INIT_WAITING)
3284 		Q(VDC_STATE_NEGOTIATE)
3285 		Q(VDC_STATE_HANDLE_PENDING)
3286 		Q(VDC_STATE_RUNNING)
3287 		Q(VDC_STATE_RESETTING)
3288 		Q(VDC_STATE_DETACH)
3289 		"UNKNOWN");
3290 
3291 		switch (vdcp->state) {
3292 		case VDC_STATE_INIT:
3293 
3294 			/* Check if have re-initializing repeatedly */
3295 			if (vdcp->hshake_cnt++ > vdc_hshake_retries) {
3296 				cmn_err(CE_NOTE, "[%d] disk access failed.\n",
3297 				    vdcp->instance);
3298 				vdcp->state = VDC_STATE_DETACH;
3299 				break;
3300 			}
3301 
3302 			/* Bring up connection with vds via LDC */
3303 			status = vdc_start_ldc_connection(vdcp);
3304 			switch (status) {
3305 			case EINVAL:
3306 				DMSG(vdcp, 0, "[%d] Could not start LDC",
3307 				    vdcp->instance);
3308 				vdcp->state = VDC_STATE_DETACH;
3309 				break;
3310 			case 0:
3311 				vdcp->state = VDC_STATE_INIT_WAITING;
3312 				break;
3313 			default:
3314 				vdcp->state = VDC_STATE_INIT_WAITING;
3315 				break;
3316 			}
3317 			break;
3318 
3319 		case VDC_STATE_INIT_WAITING:
3320 
3321 			/*
3322 			 * Let the callback event move us on
3323 			 * when channel is open to server
3324 			 */
3325 			while (vdcp->ldc_state != LDC_UP) {
3326 				cv_wait(&vdcp->initwait_cv, &vdcp->lock);
3327 				if (vdcp->state != VDC_STATE_INIT_WAITING) {
3328 					DMSG(vdcp, 0,
3329 				"state moved to %d out from under us...\n",
3330 					    vdcp->state);
3331 
3332 					break;
3333 				}
3334 			}
3335 			if (vdcp->state == VDC_STATE_INIT_WAITING &&
3336 			    vdcp->ldc_state == LDC_UP) {
3337 				vdcp->state = VDC_STATE_NEGOTIATE;
3338 			}
3339 			break;
3340 
3341 		case VDC_STATE_NEGOTIATE:
3342 			switch (status = vdc_ver_negotiation(vdcp)) {
3343 			case 0:
3344 				break;
3345 			default:
3346 				DMSG(vdcp, 0, "ver negotiate failed (%d)..\n",
3347 				    status);
3348 				goto reset;
3349 			}
3350 
3351 			switch (status = vdc_attr_negotiation(vdcp)) {
3352 			case 0:
3353 				break;
3354 			default:
3355 				DMSG(vdcp, 0, "attr negotiate failed (%d)..\n",
3356 				    status);
3357 				goto reset;
3358 			}
3359 
3360 			switch (status = vdc_dring_negotiation(vdcp)) {
3361 			case 0:
3362 				break;
3363 			default:
3364 				DMSG(vdcp, 0, "dring negotiate failed (%d)..\n",
3365 				    status);
3366 				goto reset;
3367 			}
3368 
3369 			switch (status = vdc_rdx_exchange(vdcp)) {
3370 			case 0:
3371 				vdcp->state = VDC_STATE_HANDLE_PENDING;
3372 				goto done;
3373 			default:
3374 				DMSG(vdcp, 0, "RDX xchg failed ..(%d)\n",
3375 				    status);
3376 				goto reset;
3377 			}
3378 reset:
3379 			DMSG(vdcp, 0, "negotiation failed: resetting (%d)\n",
3380 			    status);
3381 			vdcp->state = VDC_STATE_RESETTING;
3382 done:
3383 			DMSG(vdcp, 0, "negotiation complete (state=0x%x)...\n",
3384 			    vdcp->state);
3385 			break;
3386 
3387 		case VDC_STATE_HANDLE_PENDING:
3388 
3389 			mutex_exit(&vdcp->lock);
3390 			status = vdc_resubmit_backup_dring(vdcp);
3391 			mutex_enter(&vdcp->lock);
3392 
3393 			if (status)
3394 				vdcp->state = VDC_STATE_RESETTING;
3395 			else
3396 				vdcp->state = VDC_STATE_RUNNING;
3397 
3398 			break;
3399 
3400 		/* enter running state */
3401 		case VDC_STATE_RUNNING:
3402 			/*
3403 			 * Signal anyone waiting for the connection
3404 			 * to come on line.
3405 			 */
3406 			vdcp->hshake_cnt = 0;
3407 			cv_broadcast(&vdcp->running_cv);
3408 			mutex_exit(&vdcp->lock);
3409 
3410 			for (;;) {
3411 				vio_msg_t msg;
3412 				status = vdc_wait_for_response(vdcp, &msg);
3413 				if (status) break;
3414 
3415 				DMSG(vdcp, 1, "[%d] new pkt(s) available\n",
3416 					vdcp->instance);
3417 				status = vdc_process_data_msg(vdcp, &msg);
3418 				if (status) {
3419 					DMSG(vdcp, 1, "[%d] process_data_msg "
3420 					    "returned err=%d\n", vdcp->instance,
3421 					    status);
3422 					break;
3423 				}
3424 
3425 			}
3426 
3427 			mutex_enter(&vdcp->lock);
3428 
3429 			vdcp->state = VDC_STATE_RESETTING;
3430 			break;
3431 
3432 		case VDC_STATE_RESETTING:
3433 			DMSG(vdcp, 0, "Initiating channel reset "
3434 			    "(pending = %d)\n", (int)vdcp->threads_pending);
3435 
3436 			if (vdcp->self_reset) {
3437 				DMSG(vdcp, 0,
3438 				    "[%d] calling stop_ldc_connection.\n",
3439 				    vdcp->instance);
3440 				status = vdc_stop_ldc_connection(vdcp);
3441 				vdcp->self_reset = B_FALSE;
3442 			}
3443 
3444 			/*
3445 			 * Wait for all threads currently waiting
3446 			 * for a free dring entry to use.
3447 			 */
3448 			while (vdcp->threads_pending) {
3449 				cv_broadcast(&vdcp->membind_cv);
3450 				cv_broadcast(&vdcp->dring_free_cv);
3451 				mutex_exit(&vdcp->lock);
3452 				/* let them wake up */
3453 				drv_usecwait(vdc_min_timeout_ldc);
3454 				mutex_enter(&vdcp->lock);
3455 			}
3456 
3457 			ASSERT(vdcp->threads_pending == 0);
3458 
3459 			/* Sanity check that no thread is receiving */
3460 			ASSERT(vdcp->read_state != VDC_READ_WAITING);
3461 
3462 			vdcp->read_state = VDC_READ_IDLE;
3463 
3464 			vdc_backup_local_dring(vdcp);
3465 
3466 			/* cleanup the old d-ring */
3467 			vdc_destroy_descriptor_ring(vdcp);
3468 
3469 			/* go and start again */
3470 			vdcp->state = VDC_STATE_INIT;
3471 
3472 			break;
3473 
3474 		case VDC_STATE_DETACH:
3475 			DMSG(vdcp, 0, "[%d] Reset thread exit cleanup ..\n",
3476 			    vdcp->instance);
3477 
3478 			/*
3479 			 * Signal anyone waiting for connection
3480 			 * to come online
3481 			 */
3482 			cv_broadcast(&vdcp->running_cv);
3483 
3484 			while (vdcp->sync_op_pending) {
3485 				cv_signal(&vdcp->sync_pending_cv);
3486 				cv_signal(&vdcp->sync_blocked_cv);
3487 				mutex_exit(&vdcp->lock);
3488 				drv_usecwait(vdc_min_timeout_ldc);
3489 				mutex_enter(&vdcp->lock);
3490 			}
3491 
3492 			mutex_exit(&vdcp->lock);
3493 
3494 			DMSG(vdcp, 0, "[%d] Msg processing thread exiting ..\n",
3495 				vdcp->instance);
3496 			thread_exit();
3497 			break;
3498 		}
3499 	}
3500 }
3501 
3502 
3503 /*
3504  * Function:
3505  *	vdc_process_data_msg()
3506  *
3507  * Description:
3508  *	This function is called by the message processing thread each time
3509  *	a message with a msgtype of VIO_TYPE_DATA is received. It will either
3510  *	be an ACK or NACK from vds[1] which vdc handles as follows.
3511  *		ACK	- wake up the waiting thread
3512  *		NACK	- resend any messages necessary
3513  *
3514  *	[1] Although the message format allows it, vds should not send a
3515  *	    VIO_SUBTYPE_INFO message to vdc asking it to read data; if for
3516  *	    some bizarre reason it does, vdc will reset the connection.
3517  *
3518  * Arguments:
3519  *	vdc	- soft state pointer for this instance of the device driver.
3520  *	msg	- the LDC message sent by vds
3521  *
3522  * Return Code:
3523  *	0	- Success.
3524  *	> 0	- error value returned by LDC
3525  */
3526 static int
3527 vdc_process_data_msg(vdc_t *vdcp, vio_msg_t *msg)
3528 {
3529 	int			status = 0;
3530 	vio_dring_msg_t		*dring_msg;
3531 	vdc_local_desc_t	*ldep = NULL;
3532 	int			start, end;
3533 	int			idx;
3534 
3535 	dring_msg = (vio_dring_msg_t *)msg;
3536 
3537 	ASSERT(msg->tag.vio_msgtype == VIO_TYPE_DATA);
3538 	ASSERT(vdcp != NULL);
3539 
3540 	mutex_enter(&vdcp->lock);
3541 
3542 	/*
3543 	 * Check to see if the message has bogus data
3544 	 */
3545 	idx = start = dring_msg->start_idx;
3546 	end = dring_msg->end_idx;
3547 	if ((start >= vdcp->dring_len) ||
3548 	    (end >= vdcp->dring_len) || (end < -1)) {
3549 		DMSG(vdcp, 0, "[%d] Bogus ACK data : start %d, end %d\n",
3550 			vdcp->instance, start, end);
3551 		mutex_exit(&vdcp->lock);
3552 		return (EINVAL);
3553 	}
3554 
3555 	/*
3556 	 * Verify that the sequence number is what vdc expects.
3557 	 */
3558 	switch (vdc_verify_seq_num(vdcp, dring_msg)) {
3559 	case VDC_SEQ_NUM_TODO:
3560 		break;	/* keep processing this message */
3561 	case VDC_SEQ_NUM_SKIP:
3562 		mutex_exit(&vdcp->lock);
3563 		return (0);
3564 	case VDC_SEQ_NUM_INVALID:
3565 		mutex_exit(&vdcp->lock);
3566 		DMSG(vdcp, 0, "[%d] invalid seqno\n", vdcp->instance);
3567 		return (ENXIO);
3568 	}
3569 
3570 	if (msg->tag.vio_subtype == VIO_SUBTYPE_NACK) {
3571 		DMSG(vdcp, 0, "[%d] DATA NACK\n", vdcp->instance);
3572 		VDC_DUMP_DRING_MSG(dring_msg);
3573 		mutex_exit(&vdcp->lock);
3574 		return (EIO);
3575 
3576 	} else if (msg->tag.vio_subtype == VIO_SUBTYPE_INFO) {
3577 		mutex_exit(&vdcp->lock);
3578 		return (EPROTO);
3579 	}
3580 
3581 	DTRACE_IO2(recv, vio_dring_msg_t, dring_msg, vdc_t *, vdcp);
3582 	DMSG(vdcp, 1, ": start %d end %d\n", start, end);
3583 	ASSERT(start == end);
3584 
3585 	ldep = &vdcp->local_dring[idx];
3586 
3587 	DMSG(vdcp, 1, ": state 0x%x - cb_type 0x%x\n",
3588 		ldep->dep->hdr.dstate, ldep->cb_type);
3589 
3590 	if (ldep->dep->hdr.dstate == VIO_DESC_DONE) {
3591 		struct buf *bufp;
3592 
3593 		switch (ldep->cb_type) {
3594 		case CB_SYNC:
3595 			ASSERT(vdcp->sync_op_pending);
3596 
3597 			status = vdc_depopulate_descriptor(vdcp, idx);
3598 			vdcp->sync_op_status = status;
3599 			vdcp->sync_op_pending = B_FALSE;
3600 			cv_signal(&vdcp->sync_pending_cv);
3601 			break;
3602 
3603 		case CB_STRATEGY:
3604 			bufp = ldep->cb_arg;
3605 			ASSERT(bufp != NULL);
3606 			bufp->b_resid =
3607 				bufp->b_bcount - ldep->dep->payload.nbytes;
3608 			status = ldep->dep->payload.status; /* Future:ntoh */
3609 			if (status != 0) {
3610 				DMSG(vdcp, 1, "strategy status=%d\n", status);
3611 				bioerror(bufp, status);
3612 			}
3613 			status = vdc_depopulate_descriptor(vdcp, idx);
3614 			biodone(bufp);
3615 
3616 			DMSG(vdcp, 1,
3617 			    "strategy complete req=%ld bytes resp=%ld bytes\n",
3618 			    bufp->b_bcount, ldep->dep->payload.nbytes);
3619 			break;
3620 
3621 		default:
3622 			ASSERT(0);
3623 		}
3624 	}
3625 
3626 	/* let the arrival signal propogate */
3627 	mutex_exit(&vdcp->lock);
3628 
3629 	/* probe gives the count of how many entries were processed */
3630 	DTRACE_IO2(processed, int, 1, vdc_t *, vdcp);
3631 
3632 	return (0);
3633 }
3634 
3635 /*
3636  * Function:
3637  *	vdc_process_err_msg()
3638  *
3639  * NOTE: No error messages are used as part of the vDisk protocol
3640  */
3641 static int
3642 vdc_process_err_msg(vdc_t *vdc, vio_msg_t msg)
3643 {
3644 	_NOTE(ARGUNUSED(vdc))
3645 	_NOTE(ARGUNUSED(msg))
3646 
3647 	ASSERT(msg.tag.vio_msgtype == VIO_TYPE_ERR);
3648 	DMSG(vdc, 1, "[%d] Got an ERR msg", vdc->instance);
3649 
3650 	return (ENOTSUP);
3651 }
3652 
3653 /*
3654  * Function:
3655  *	vdc_handle_ver_msg()
3656  *
3657  * Description:
3658  *
3659  * Arguments:
3660  *	vdc	- soft state pointer for this instance of the device driver.
3661  *	ver_msg	- LDC message sent by vDisk server
3662  *
3663  * Return Code:
3664  *	0	- Success
3665  */
3666 static int
3667 vdc_handle_ver_msg(vdc_t *vdc, vio_ver_msg_t *ver_msg)
3668 {
3669 	int status = 0;
3670 
3671 	ASSERT(vdc != NULL);
3672 	ASSERT(mutex_owned(&vdc->lock));
3673 
3674 	if (ver_msg->tag.vio_subtype_env != VIO_VER_INFO) {
3675 		return (EPROTO);
3676 	}
3677 
3678 	if (ver_msg->dev_class != VDEV_DISK_SERVER) {
3679 		return (EINVAL);
3680 	}
3681 
3682 	switch (ver_msg->tag.vio_subtype) {
3683 	case VIO_SUBTYPE_ACK:
3684 		/*
3685 		 * We check to see if the version returned is indeed supported
3686 		 * (The server may have also adjusted the minor number downwards
3687 		 * and if so 'ver_msg' will contain the actual version agreed)
3688 		 */
3689 		if (vdc_is_supported_version(ver_msg)) {
3690 			vdc->ver.major = ver_msg->ver_major;
3691 			vdc->ver.minor = ver_msg->ver_minor;
3692 			ASSERT(vdc->ver.major > 0);
3693 		} else {
3694 			status = EPROTO;
3695 		}
3696 		break;
3697 
3698 	case VIO_SUBTYPE_NACK:
3699 		/*
3700 		 * call vdc_is_supported_version() which will return the next
3701 		 * supported version (if any) in 'ver_msg'
3702 		 */
3703 		(void) vdc_is_supported_version(ver_msg);
3704 		if (ver_msg->ver_major > 0) {
3705 			size_t len = sizeof (*ver_msg);
3706 
3707 			ASSERT(vdc->ver.major > 0);
3708 
3709 			/* reset the necessary fields and resend */
3710 			ver_msg->tag.vio_subtype = VIO_SUBTYPE_INFO;
3711 			ver_msg->dev_class = VDEV_DISK;
3712 
3713 			status = vdc_send(vdc, (caddr_t)ver_msg, &len);
3714 			DMSG(vdc, 0, "[%d] Resend VER info (LDC status = %d)\n",
3715 					vdc->instance, status);
3716 			if (len != sizeof (*ver_msg))
3717 				status = EBADMSG;
3718 		} else {
3719 			DMSG(vdc, 0, "[%d] No common version with "
3720 					"vDisk server", vdc->instance);
3721 			status = ENOTSUP;
3722 		}
3723 
3724 		break;
3725 	case VIO_SUBTYPE_INFO:
3726 		/*
3727 		 * Handle the case where vds starts handshake
3728 		 * (for now only vdc is the instigatior)
3729 		 */
3730 		status = ENOTSUP;
3731 		break;
3732 
3733 	default:
3734 		status = EINVAL;
3735 		break;
3736 	}
3737 
3738 	return (status);
3739 }
3740 
3741 /*
3742  * Function:
3743  *	vdc_handle_attr_msg()
3744  *
3745  * Description:
3746  *
3747  * Arguments:
3748  *	vdc	- soft state pointer for this instance of the device driver.
3749  *	attr_msg	- LDC message sent by vDisk server
3750  *
3751  * Return Code:
3752  *	0	- Success
3753  */
3754 static int
3755 vdc_handle_attr_msg(vdc_t *vdc, vd_attr_msg_t *attr_msg)
3756 {
3757 	int status = 0;
3758 
3759 	ASSERT(vdc != NULL);
3760 	ASSERT(mutex_owned(&vdc->lock));
3761 
3762 	if (attr_msg->tag.vio_subtype_env != VIO_ATTR_INFO) {
3763 		return (EPROTO);
3764 	}
3765 
3766 	switch (attr_msg->tag.vio_subtype) {
3767 	case VIO_SUBTYPE_ACK:
3768 		/*
3769 		 * We now verify the attributes sent by vds.
3770 		 */
3771 		vdc->vdisk_size = attr_msg->vdisk_size;
3772 		vdc->vdisk_type = attr_msg->vdisk_type;
3773 
3774 		DMSG(vdc, 0, "[%d] max_xfer_sz: sent %lx acked %lx\n",
3775 			vdc->instance, vdc->max_xfer_sz, attr_msg->max_xfer_sz);
3776 		DMSG(vdc, 0, "[%d] vdisk_block_size: sent %lx acked %x\n",
3777 			vdc->instance, vdc->block_size,
3778 			attr_msg->vdisk_block_size);
3779 
3780 		/*
3781 		 * We don't know at compile time what the vDisk server will
3782 		 * think are good values but we apply an large (arbitrary)
3783 		 * upper bound to prevent memory exhaustion in vdc if it was
3784 		 * allocating a DRing based of huge values sent by the server.
3785 		 * We probably will never exceed this except if the message
3786 		 * was garbage.
3787 		 */
3788 		if ((attr_msg->max_xfer_sz * attr_msg->vdisk_block_size) <=
3789 				(PAGESIZE * DEV_BSIZE)) {
3790 			vdc->max_xfer_sz = attr_msg->max_xfer_sz;
3791 			vdc->block_size = attr_msg->vdisk_block_size;
3792 		} else {
3793 			DMSG(vdc, 0, "[%d] vds block transfer size too big;"
3794 				" using max supported by vdc", vdc->instance);
3795 		}
3796 
3797 		if ((attr_msg->xfer_mode != VIO_DRING_MODE) ||
3798 		    (attr_msg->vdisk_size > INT64_MAX) ||
3799 		    (attr_msg->vdisk_type > VD_DISK_TYPE_DISK)) {
3800 			DMSG(vdc, 0, "[%d] Invalid attributes from vds",
3801 					vdc->instance);
3802 			status = EINVAL;
3803 			break;
3804 		}
3805 
3806 		break;
3807 
3808 	case VIO_SUBTYPE_NACK:
3809 		/*
3810 		 * vds could not handle the attributes we sent so we
3811 		 * stop negotiating.
3812 		 */
3813 		status = EPROTO;
3814 		break;
3815 
3816 	case VIO_SUBTYPE_INFO:
3817 		/*
3818 		 * Handle the case where vds starts the handshake
3819 		 * (for now; vdc is the only supported instigatior)
3820 		 */
3821 		status = ENOTSUP;
3822 		break;
3823 
3824 	default:
3825 		status = ENOTSUP;
3826 		break;
3827 	}
3828 
3829 	return (status);
3830 }
3831 
3832 /*
3833  * Function:
3834  *	vdc_handle_dring_reg_msg()
3835  *
3836  * Description:
3837  *
3838  * Arguments:
3839  *	vdc		- soft state pointer for this instance of the driver.
3840  *	dring_msg	- LDC message sent by vDisk server
3841  *
3842  * Return Code:
3843  *	0	- Success
3844  */
3845 static int
3846 vdc_handle_dring_reg_msg(vdc_t *vdc, vio_dring_reg_msg_t *dring_msg)
3847 {
3848 	int		status = 0;
3849 
3850 	ASSERT(vdc != NULL);
3851 	ASSERT(mutex_owned(&vdc->lock));
3852 
3853 	if (dring_msg->tag.vio_subtype_env != VIO_DRING_REG) {
3854 		return (EPROTO);
3855 	}
3856 
3857 	switch (dring_msg->tag.vio_subtype) {
3858 	case VIO_SUBTYPE_ACK:
3859 		/* save the received dring_ident */
3860 		vdc->dring_ident = dring_msg->dring_ident;
3861 		DMSG(vdc, 0, "[%d] Received dring ident=0x%lx\n",
3862 			vdc->instance, vdc->dring_ident);
3863 		break;
3864 
3865 	case VIO_SUBTYPE_NACK:
3866 		/*
3867 		 * vds could not handle the DRing info we sent so we
3868 		 * stop negotiating.
3869 		 */
3870 		DMSG(vdc, 0, "[%d] server could not register DRing\n",
3871 		    vdc->instance);
3872 		status = EPROTO;
3873 		break;
3874 
3875 	case VIO_SUBTYPE_INFO:
3876 		/*
3877 		 * Handle the case where vds starts handshake
3878 		 * (for now only vdc is the instigatior)
3879 		 */
3880 		status = ENOTSUP;
3881 		break;
3882 	default:
3883 		status = ENOTSUP;
3884 	}
3885 
3886 	return (status);
3887 }
3888 
3889 /*
3890  * Function:
3891  *	vdc_verify_seq_num()
3892  *
3893  * Description:
3894  *	This functions verifies that the sequence number sent back by the vDisk
3895  *	server with the latest message is what is expected (i.e. it is greater
3896  *	than the last seq num sent by the vDisk server and less than or equal
3897  *	to the last seq num generated by vdc).
3898  *
3899  *	It then checks the request ID to see if any requests need processing
3900  *	in the DRing.
3901  *
3902  * Arguments:
3903  *	vdc		- soft state pointer for this instance of the driver.
3904  *	dring_msg	- pointer to the LDC message sent by vds
3905  *
3906  * Return Code:
3907  *	VDC_SEQ_NUM_TODO	- Message needs to be processed
3908  *	VDC_SEQ_NUM_SKIP	- Message has already been processed
3909  *	VDC_SEQ_NUM_INVALID	- The seq numbers are so out of sync,
3910  *				  vdc cannot deal with them
3911  */
3912 static int
3913 vdc_verify_seq_num(vdc_t *vdc, vio_dring_msg_t *dring_msg)
3914 {
3915 	ASSERT(vdc != NULL);
3916 	ASSERT(dring_msg != NULL);
3917 	ASSERT(mutex_owned(&vdc->lock));
3918 
3919 	/*
3920 	 * Check to see if the messages were responded to in the correct
3921 	 * order by vds.
3922 	 */
3923 	if ((dring_msg->seq_num <= vdc->seq_num_reply) ||
3924 	    (dring_msg->seq_num > vdc->seq_num)) {
3925 		DMSG(vdc, 0, "?[%d] Bogus sequence_number %lu: "
3926 			"%lu > expected <= %lu (last proc req %lu sent %lu)\n",
3927 				vdc->instance, dring_msg->seq_num,
3928 				vdc->seq_num_reply, vdc->seq_num,
3929 				vdc->req_id_proc, vdc->req_id);
3930 		return (VDC_SEQ_NUM_INVALID);
3931 	}
3932 	vdc->seq_num_reply = dring_msg->seq_num;
3933 
3934 	if (vdc->req_id_proc < vdc->req_id)
3935 		return (VDC_SEQ_NUM_TODO);
3936 	else
3937 		return (VDC_SEQ_NUM_SKIP);
3938 }
3939 
3940 
3941 /*
3942  * Function:
3943  *	vdc_is_supported_version()
3944  *
3945  * Description:
3946  *	This routine checks if the major/minor version numbers specified in
3947  *	'ver_msg' are supported. If not it finds the next version that is
3948  *	in the supported version list 'vdc_version[]' and sets the fields in
3949  *	'ver_msg' to those values
3950  *
3951  * Arguments:
3952  *	ver_msg	- LDC message sent by vDisk server
3953  *
3954  * Return Code:
3955  *	B_TRUE	- Success
3956  *	B_FALSE	- Version not supported
3957  */
3958 static boolean_t
3959 vdc_is_supported_version(vio_ver_msg_t *ver_msg)
3960 {
3961 	int vdc_num_versions = sizeof (vdc_version) / sizeof (vdc_version[0]);
3962 
3963 	for (int i = 0; i < vdc_num_versions; i++) {
3964 		ASSERT(vdc_version[i].major > 0);
3965 		ASSERT((i == 0) ||
3966 		    (vdc_version[i].major < vdc_version[i-1].major));
3967 
3968 		/*
3969 		 * If the major versions match, adjust the minor version, if
3970 		 * necessary, down to the highest value supported by this
3971 		 * client. The server should support all minor versions lower
3972 		 * than the value it sent
3973 		 */
3974 		if (ver_msg->ver_major == vdc_version[i].major) {
3975 			if (ver_msg->ver_minor > vdc_version[i].minor) {
3976 				DMSGX(0,
3977 				    "Adjusting minor version from %u to %u",
3978 				    ver_msg->ver_minor, vdc_version[i].minor);
3979 				ver_msg->ver_minor = vdc_version[i].minor;
3980 			}
3981 			return (B_TRUE);
3982 		}
3983 
3984 		/*
3985 		 * If the message contains a higher major version number, set
3986 		 * the message's major/minor versions to the current values
3987 		 * and return false, so this message will get resent with
3988 		 * these values, and the server will potentially try again
3989 		 * with the same or a lower version
3990 		 */
3991 		if (ver_msg->ver_major > vdc_version[i].major) {
3992 			ver_msg->ver_major = vdc_version[i].major;
3993 			ver_msg->ver_minor = vdc_version[i].minor;
3994 			DMSGX(0, "Suggesting major/minor (0x%x/0x%x)\n",
3995 				ver_msg->ver_major, ver_msg->ver_minor);
3996 
3997 			return (B_FALSE);
3998 		}
3999 
4000 		/*
4001 		 * Otherwise, the message's major version is less than the
4002 		 * current major version, so continue the loop to the next
4003 		 * (lower) supported version
4004 		 */
4005 	}
4006 
4007 	/*
4008 	 * No common version was found; "ground" the version pair in the
4009 	 * message to terminate negotiation
4010 	 */
4011 	ver_msg->ver_major = 0;
4012 	ver_msg->ver_minor = 0;
4013 
4014 	return (B_FALSE);
4015 }
4016 /* -------------------------------------------------------------------------- */
4017 
4018 /*
4019  * DKIO(7) support
4020  */
4021 
4022 typedef struct vdc_dk_arg {
4023 	struct dk_callback	dkc;
4024 	int			mode;
4025 	dev_t			dev;
4026 	vdc_t			*vdc;
4027 } vdc_dk_arg_t;
4028 
4029 /*
4030  * Function:
4031  * 	vdc_dkio_flush_cb()
4032  *
4033  * Description:
4034  *	This routine is a callback for DKIOCFLUSHWRITECACHE which can be called
4035  *	by kernel code.
4036  *
4037  * Arguments:
4038  *	arg	- a pointer to a vdc_dk_arg_t structure.
4039  */
4040 void
4041 vdc_dkio_flush_cb(void *arg)
4042 {
4043 	struct vdc_dk_arg	*dk_arg = (struct vdc_dk_arg *)arg;
4044 	struct dk_callback	*dkc = NULL;
4045 	vdc_t			*vdc = NULL;
4046 	int			rv;
4047 
4048 	if (dk_arg == NULL) {
4049 		cmn_err(CE_NOTE, "?[Unk] DKIOCFLUSHWRITECACHE arg is NULL\n");
4050 		return;
4051 	}
4052 	dkc = &dk_arg->dkc;
4053 	vdc = dk_arg->vdc;
4054 	ASSERT(vdc != NULL);
4055 
4056 	rv = vdc_do_sync_op(vdc, VD_OP_FLUSH, NULL, 0,
4057 	    VDCPART(dk_arg->dev), 0, CB_SYNC, 0, VIO_both_dir);
4058 	if (rv != 0) {
4059 		DMSG(vdc, 0, "[%d] DKIOCFLUSHWRITECACHE failed %d : model %x\n",
4060 			vdc->instance, rv,
4061 			ddi_model_convert_from(dk_arg->mode & FMODELS));
4062 	}
4063 
4064 	/*
4065 	 * Trigger the call back to notify the caller the the ioctl call has
4066 	 * been completed.
4067 	 */
4068 	if ((dk_arg->mode & FKIOCTL) &&
4069 	    (dkc != NULL) &&
4070 	    (dkc->dkc_callback != NULL)) {
4071 		ASSERT(dkc->dkc_cookie != NULL);
4072 		(*dkc->dkc_callback)(dkc->dkc_cookie, rv);
4073 	}
4074 
4075 	/* Indicate that one less DKIO write flush is outstanding */
4076 	mutex_enter(&vdc->lock);
4077 	vdc->dkio_flush_pending--;
4078 	ASSERT(vdc->dkio_flush_pending >= 0);
4079 	mutex_exit(&vdc->lock);
4080 
4081 	/* free the mem that was allocated when the callback was dispatched */
4082 	kmem_free(arg, sizeof (vdc_dk_arg_t));
4083 }
4084 
4085 /*
4086  * This structure is used in the DKIO(7I) array below.
4087  */
4088 typedef struct vdc_dk_ioctl {
4089 	uint8_t		op;		/* VD_OP_XXX value */
4090 	int		cmd;		/* Solaris ioctl operation number */
4091 	size_t		nbytes;		/* size of structure to be copied */
4092 
4093 	/* function to convert between vDisk and Solaris structure formats */
4094 	int	(*convert)(vdc_t *vdc, void *vd_buf, void *ioctl_arg,
4095 	    int mode, int dir);
4096 } vdc_dk_ioctl_t;
4097 
4098 /*
4099  * Subset of DKIO(7I) operations currently supported
4100  */
4101 static vdc_dk_ioctl_t	dk_ioctl[] = {
4102 	{VD_OP_FLUSH,		DKIOCFLUSHWRITECACHE,	sizeof (int),
4103 		vdc_null_copy_func},
4104 	{VD_OP_GET_WCE,		DKIOCGETWCE,		sizeof (int),
4105 		vdc_get_wce_convert},
4106 	{VD_OP_SET_WCE,		DKIOCSETWCE,		sizeof (int),
4107 		vdc_set_wce_convert},
4108 	{VD_OP_GET_VTOC,	DKIOCGVTOC,		sizeof (vd_vtoc_t),
4109 		vdc_get_vtoc_convert},
4110 	{VD_OP_SET_VTOC,	DKIOCSVTOC,		sizeof (vd_vtoc_t),
4111 		vdc_set_vtoc_convert},
4112 	{VD_OP_GET_DISKGEOM,	DKIOCGGEOM,		sizeof (vd_geom_t),
4113 		vdc_get_geom_convert},
4114 	{VD_OP_GET_DISKGEOM,	DKIOCG_PHYGEOM,		sizeof (vd_geom_t),
4115 		vdc_get_geom_convert},
4116 	{VD_OP_GET_DISKGEOM, 	DKIOCG_VIRTGEOM,	sizeof (vd_geom_t),
4117 		vdc_get_geom_convert},
4118 	{VD_OP_SET_DISKGEOM,	DKIOCSGEOM,		sizeof (vd_geom_t),
4119 		vdc_set_geom_convert},
4120 	{VD_OP_GET_EFI,		DKIOCGETEFI,		0,
4121 		vdc_get_efi_convert},
4122 	{VD_OP_SET_EFI,		DKIOCSETEFI,		0,
4123 		vdc_set_efi_convert},
4124 
4125 	/*
4126 	 * These particular ioctls are not sent to the server - vdc fakes up
4127 	 * the necessary info.
4128 	 */
4129 	{0, DKIOCINFO, sizeof (struct dk_cinfo), vdc_null_copy_func},
4130 	{0, DKIOCGMEDIAINFO, sizeof (struct dk_minfo), vdc_null_copy_func},
4131 	{0, USCSICMD,	sizeof (struct uscsi_cmd), vdc_null_copy_func},
4132 	{0, DKIOCREMOVABLE, 0, vdc_null_copy_func},
4133 	{0, CDROMREADOFFSET, 0, vdc_null_copy_func}
4134 };
4135 
4136 /*
4137  * Function:
4138  *	vd_process_ioctl()
4139  *
4140  * Description:
4141  *	This routine processes disk specific ioctl calls
4142  *
4143  * Arguments:
4144  *	dev	- the device number
4145  *	cmd	- the operation [dkio(7I)] to be processed
4146  *	arg	- pointer to user provided structure
4147  *		  (contains data to be set or reference parameter for get)
4148  *	mode	- bit flag, indicating open settings, 32/64 bit type, etc
4149  *
4150  * Return Code:
4151  *	0
4152  *	EFAULT
4153  *	ENXIO
4154  *	EIO
4155  *	ENOTSUP
4156  */
4157 static int
4158 vd_process_ioctl(dev_t dev, int cmd, caddr_t arg, int mode)
4159 {
4160 	int		instance = VDCUNIT(dev);
4161 	vdc_t		*vdc = NULL;
4162 	int		rv = -1;
4163 	int		idx = 0;		/* index into dk_ioctl[] */
4164 	size_t		len = 0;		/* #bytes to send to vds */
4165 	size_t		alloc_len = 0;		/* #bytes to allocate mem for */
4166 	caddr_t		mem_p = NULL;
4167 	size_t		nioctls = (sizeof (dk_ioctl)) / (sizeof (dk_ioctl[0]));
4168 	struct vtoc	vtoc_saved;
4169 	vdc_dk_ioctl_t	*iop;
4170 
4171 	vdc = ddi_get_soft_state(vdc_state, instance);
4172 	if (vdc == NULL) {
4173 		cmn_err(CE_NOTE, "![%d] Could not get soft state structure",
4174 		    instance);
4175 		return (ENXIO);
4176 	}
4177 
4178 	DMSG(vdc, 0, "[%d] Processing ioctl(%x) for dev %lx : model %x\n",
4179 		instance, cmd, dev, ddi_model_convert_from(mode & FMODELS));
4180 
4181 	/*
4182 	 * Validate the ioctl operation to be performed.
4183 	 *
4184 	 * If we have looped through the array without finding a match then we
4185 	 * don't support this ioctl.
4186 	 */
4187 	for (idx = 0; idx < nioctls; idx++) {
4188 		if (cmd == dk_ioctl[idx].cmd)
4189 			break;
4190 	}
4191 
4192 	if (idx >= nioctls) {
4193 		DMSG(vdc, 0, "[%d] Unsupported ioctl (0x%x)\n",
4194 		    vdc->instance, cmd);
4195 		return (ENOTSUP);
4196 	}
4197 
4198 	iop = &(dk_ioctl[idx]);
4199 
4200 	if (cmd == DKIOCGETEFI || cmd == DKIOCSETEFI) {
4201 		/* size is not fixed for EFI ioctls, it depends on ioctl arg */
4202 		dk_efi_t	dk_efi;
4203 
4204 		rv = ddi_copyin(arg, &dk_efi, sizeof (dk_efi_t), mode);
4205 		if (rv != 0)
4206 			return (EFAULT);
4207 
4208 		len = sizeof (vd_efi_t) - 1 + dk_efi.dki_length;
4209 	} else {
4210 		len = iop->nbytes;
4211 	}
4212 
4213 	/*
4214 	 * Deal with the ioctls which the server does not provide. vdc can
4215 	 * fake these up and return immediately
4216 	 */
4217 	switch (cmd) {
4218 	case CDROMREADOFFSET:
4219 	case DKIOCREMOVABLE:
4220 	case USCSICMD:
4221 		return (ENOTTY);
4222 
4223 	case DKIOCINFO:
4224 		{
4225 			struct dk_cinfo	cinfo;
4226 			if (vdc->cinfo == NULL)
4227 				return (ENXIO);
4228 
4229 			bcopy(vdc->cinfo, &cinfo, sizeof (struct dk_cinfo));
4230 			cinfo.dki_partition = VDCPART(dev);
4231 
4232 			rv = ddi_copyout(&cinfo, (void *)arg,
4233 					sizeof (struct dk_cinfo), mode);
4234 			if (rv != 0)
4235 				return (EFAULT);
4236 
4237 			return (0);
4238 		}
4239 
4240 	case DKIOCGMEDIAINFO:
4241 		{
4242 			if (vdc->minfo == NULL)
4243 				return (ENXIO);
4244 
4245 			rv = ddi_copyout(vdc->minfo, (void *)arg,
4246 					sizeof (struct dk_minfo), mode);
4247 			if (rv != 0)
4248 				return (EFAULT);
4249 
4250 			return (0);
4251 		}
4252 
4253 	case DKIOCFLUSHWRITECACHE:
4254 		{
4255 			struct dk_callback *dkc = (struct dk_callback *)arg;
4256 			vdc_dk_arg_t	*dkarg = NULL;
4257 
4258 			DMSG(vdc, 1, "[%d] Flush W$: mode %x\n",
4259 			    instance, mode);
4260 
4261 			/*
4262 			 * If the backing device is not a 'real' disk then the
4263 			 * W$ operation request to the vDisk server will fail
4264 			 * so we might as well save the cycles and return now.
4265 			 */
4266 			if (vdc->vdisk_type != VD_DISK_TYPE_DISK)
4267 				return (ENOTTY);
4268 
4269 			/*
4270 			 * If arg is NULL, then there is no callback function
4271 			 * registered and the call operates synchronously; we
4272 			 * break and continue with the rest of the function and
4273 			 * wait for vds to return (i.e. after the request to
4274 			 * vds returns successfully, all writes completed prior
4275 			 * to the ioctl will have been flushed from the disk
4276 			 * write cache to persistent media.
4277 			 *
4278 			 * If a callback function is registered, we dispatch
4279 			 * the request on a task queue and return immediately.
4280 			 * The callback will deal with informing the calling
4281 			 * thread that the flush request is completed.
4282 			 */
4283 			if (dkc == NULL)
4284 				break;
4285 
4286 			dkarg = kmem_zalloc(sizeof (vdc_dk_arg_t), KM_SLEEP);
4287 
4288 			dkarg->mode = mode;
4289 			dkarg->dev = dev;
4290 			bcopy(dkc, &dkarg->dkc, sizeof (*dkc));
4291 
4292 			mutex_enter(&vdc->lock);
4293 			vdc->dkio_flush_pending++;
4294 			dkarg->vdc = vdc;
4295 			mutex_exit(&vdc->lock);
4296 
4297 			/* put the request on a task queue */
4298 			rv = taskq_dispatch(system_taskq, vdc_dkio_flush_cb,
4299 				(void *)dkarg, DDI_SLEEP);
4300 			if (rv == NULL) {
4301 				/* clean up if dispatch fails */
4302 				mutex_enter(&vdc->lock);
4303 				vdc->dkio_flush_pending--;
4304 				kmem_free(dkarg, sizeof (vdc_dk_arg_t));
4305 			}
4306 
4307 			return (rv == NULL ? ENOMEM : 0);
4308 		}
4309 	}
4310 
4311 	/* catch programming error in vdc - should be a VD_OP_XXX ioctl */
4312 	ASSERT(iop->op != 0);
4313 
4314 	/* LDC requires that the memory being mapped is 8-byte aligned */
4315 	alloc_len = P2ROUNDUP(len, sizeof (uint64_t));
4316 	DMSG(vdc, 1, "[%d] struct size %ld alloc %ld\n",
4317 	    instance, len, alloc_len);
4318 
4319 	ASSERT(alloc_len != 0);	/* sanity check */
4320 	mem_p = kmem_zalloc(alloc_len, KM_SLEEP);
4321 
4322 	if (cmd == DKIOCSVTOC) {
4323 		/*
4324 		 * Save a copy of the current VTOC so that we can roll back
4325 		 * if the setting of the new VTOC fails.
4326 		 */
4327 		bcopy(vdc->vtoc, &vtoc_saved, sizeof (struct vtoc));
4328 	}
4329 
4330 	/*
4331 	 * Call the conversion function for this ioctl whhich if necessary
4332 	 * converts from the Solaris format to the format ARC'ed
4333 	 * as part of the vDisk protocol (FWARC 2006/195)
4334 	 */
4335 	ASSERT(iop->convert != NULL);
4336 	rv = (iop->convert)(vdc, arg, mem_p, mode, VD_COPYIN);
4337 	if (rv != 0) {
4338 		DMSG(vdc, 0, "[%d] convert func returned %d for ioctl 0x%x\n",
4339 				instance, rv, cmd);
4340 		if (mem_p != NULL)
4341 			kmem_free(mem_p, alloc_len);
4342 		return (rv);
4343 	}
4344 
4345 	/*
4346 	 * send request to vds to service the ioctl.
4347 	 */
4348 	rv = vdc_do_sync_op(vdc, iop->op, mem_p, alloc_len,
4349 	    VDCPART(dev), 0, CB_SYNC, (void *)(uint64_t)mode,
4350 	    VIO_both_dir);
4351 
4352 	if (rv != 0) {
4353 		/*
4354 		 * This is not necessarily an error. The ioctl could
4355 		 * be returning a value such as ENOTTY to indicate
4356 		 * that the ioctl is not applicable.
4357 		 */
4358 		DMSG(vdc, 0, "[%d] vds returned %d for ioctl 0x%x\n",
4359 			instance, rv, cmd);
4360 		if (mem_p != NULL)
4361 			kmem_free(mem_p, alloc_len);
4362 
4363 		if (cmd == DKIOCSVTOC) {
4364 			/* update of the VTOC has failed, roll back */
4365 			bcopy(&vtoc_saved, vdc->vtoc, sizeof (struct vtoc));
4366 		}
4367 
4368 		return (rv);
4369 	}
4370 
4371 	if (cmd == DKIOCSVTOC) {
4372 		/*
4373 		 * The VTOC has been changed. We need to update the device
4374 		 * nodes to handle the case where an EFI label has been
4375 		 * changed to a VTOC label. We also try and update the device
4376 		 * node properties. Failing to set the properties should
4377 		 * not cause an error to be return the caller though.
4378 		 */
4379 		vdc->vdisk_label = VD_DISK_LABEL_VTOC;
4380 		(void) vdc_create_device_nodes_vtoc(vdc);
4381 
4382 		if (vdc_create_device_nodes_props(vdc)) {
4383 			DMSG(vdc, 0, "![%d] Failed to update device nodes"
4384 			    " properties", vdc->instance);
4385 		}
4386 
4387 	} else if (cmd == DKIOCSETEFI) {
4388 		/*
4389 		 * The EFI has been changed. We need to update the device
4390 		 * nodes to handle the case where a VTOC label has been
4391 		 * changed to an EFI label. We also try and update the device
4392 		 * node properties. Failing to set the properties should
4393 		 * not cause an error to be return the caller though.
4394 		 */
4395 		struct dk_gpt *efi;
4396 		size_t efi_len;
4397 
4398 		vdc->vdisk_label = VD_DISK_LABEL_EFI;
4399 		(void) vdc_create_device_nodes_efi(vdc);
4400 
4401 		rv = vdc_efi_alloc_and_read(dev, &efi, &efi_len);
4402 
4403 		if (rv == 0) {
4404 			vdc_store_efi(vdc, efi);
4405 			rv = vdc_create_device_nodes_props(vdc);
4406 			vd_efi_free(efi, efi_len);
4407 		}
4408 
4409 		if (rv) {
4410 			DMSG(vdc, 0, "![%d] Failed to update device nodes"
4411 			    " properties", vdc->instance);
4412 		}
4413 	}
4414 
4415 	/*
4416 	 * Call the conversion function (if it exists) for this ioctl
4417 	 * which converts from the format ARC'ed as part of the vDisk
4418 	 * protocol (FWARC 2006/195) back to a format understood by
4419 	 * the rest of Solaris.
4420 	 */
4421 	rv = (iop->convert)(vdc, mem_p, arg, mode, VD_COPYOUT);
4422 	if (rv != 0) {
4423 		DMSG(vdc, 0, "[%d] convert func returned %d for ioctl 0x%x\n",
4424 				instance, rv, cmd);
4425 		if (mem_p != NULL)
4426 			kmem_free(mem_p, alloc_len);
4427 		return (rv);
4428 	}
4429 
4430 	if (mem_p != NULL)
4431 		kmem_free(mem_p, alloc_len);
4432 
4433 	return (rv);
4434 }
4435 
4436 /*
4437  * Function:
4438  *
4439  * Description:
4440  *	This is an empty conversion function used by ioctl calls which
4441  *	do not need to convert the data being passed in/out to userland
4442  */
4443 static int
4444 vdc_null_copy_func(vdc_t *vdc, void *from, void *to, int mode, int dir)
4445 {
4446 	_NOTE(ARGUNUSED(vdc))
4447 	_NOTE(ARGUNUSED(from))
4448 	_NOTE(ARGUNUSED(to))
4449 	_NOTE(ARGUNUSED(mode))
4450 	_NOTE(ARGUNUSED(dir))
4451 
4452 	return (0);
4453 }
4454 
4455 static int
4456 vdc_get_wce_convert(vdc_t *vdc, void *from, void *to,
4457     int mode, int dir)
4458 {
4459 	_NOTE(ARGUNUSED(vdc))
4460 
4461 	if (dir == VD_COPYIN)
4462 		return (0);		/* nothing to do */
4463 
4464 	if (ddi_copyout(from, to, sizeof (int), mode) != 0)
4465 		return (EFAULT);
4466 
4467 	return (0);
4468 }
4469 
4470 static int
4471 vdc_set_wce_convert(vdc_t *vdc, void *from, void *to,
4472     int mode, int dir)
4473 {
4474 	_NOTE(ARGUNUSED(vdc))
4475 
4476 	if (dir == VD_COPYOUT)
4477 		return (0);		/* nothing to do */
4478 
4479 	if (ddi_copyin(from, to, sizeof (int), mode) != 0)
4480 		return (EFAULT);
4481 
4482 	return (0);
4483 }
4484 
4485 /*
4486  * Function:
4487  *	vdc_get_vtoc_convert()
4488  *
4489  * Description:
4490  *	This routine performs the necessary convertions from the DKIOCGVTOC
4491  *	Solaris structure to the format defined in FWARC 2006/195.
4492  *
4493  *	In the struct vtoc definition, the timestamp field is marked as not
4494  *	supported so it is not part of vDisk protocol (FWARC 2006/195).
4495  *	However SVM uses that field to check it can write into the VTOC,
4496  *	so we fake up the info of that field.
4497  *
4498  * Arguments:
4499  *	vdc	- the vDisk client
4500  *	from	- the buffer containing the data to be copied from
4501  *	to	- the buffer to be copied to
4502  *	mode	- flags passed to ioctl() call
4503  *	dir	- the "direction" of the copy - VD_COPYIN or VD_COPYOUT
4504  *
4505  * Return Code:
4506  *	0	- Success
4507  *	ENXIO	- incorrect buffer passed in.
4508  *	EFAULT	- ddi_copyout routine encountered an error.
4509  */
4510 static int
4511 vdc_get_vtoc_convert(vdc_t *vdc, void *from, void *to, int mode, int dir)
4512 {
4513 	int		i;
4514 	void		*tmp_mem = NULL;
4515 	void		*tmp_memp;
4516 	struct vtoc	vt;
4517 	struct vtoc32	vt32;
4518 	int		copy_len = 0;
4519 	int		rv = 0;
4520 
4521 	if (dir != VD_COPYOUT)
4522 		return (0);	/* nothing to do */
4523 
4524 	if ((from == NULL) || (to == NULL))
4525 		return (ENXIO);
4526 
4527 	if (ddi_model_convert_from(mode & FMODELS) == DDI_MODEL_ILP32)
4528 		copy_len = sizeof (struct vtoc32);
4529 	else
4530 		copy_len = sizeof (struct vtoc);
4531 
4532 	tmp_mem = kmem_alloc(copy_len, KM_SLEEP);
4533 
4534 	VD_VTOC2VTOC((vd_vtoc_t *)from, &vt);
4535 
4536 	/* fake the VTOC timestamp field */
4537 	for (i = 0; i < V_NUMPAR; i++) {
4538 		vt.timestamp[i] = vdc->vtoc->timestamp[i];
4539 	}
4540 
4541 	if (ddi_model_convert_from(mode & FMODELS) == DDI_MODEL_ILP32) {
4542 		vtoctovtoc32(vt, vt32);
4543 		tmp_memp = &vt32;
4544 	} else {
4545 		tmp_memp = &vt;
4546 	}
4547 	rv = ddi_copyout(tmp_memp, to, copy_len, mode);
4548 	if (rv != 0)
4549 		rv = EFAULT;
4550 
4551 	kmem_free(tmp_mem, copy_len);
4552 	return (rv);
4553 }
4554 
4555 /*
4556  * Function:
4557  *	vdc_set_vtoc_convert()
4558  *
4559  * Description:
4560  *	This routine performs the necessary convertions from the DKIOCSVTOC
4561  *	Solaris structure to the format defined in FWARC 2006/195.
4562  *
4563  * Arguments:
4564  *	vdc	- the vDisk client
4565  *	from	- Buffer with data
4566  *	to	- Buffer where data is to be copied to
4567  *	mode	- flags passed to ioctl
4568  *	dir	- direction of copy (in or out)
4569  *
4570  * Return Code:
4571  *	0	- Success
4572  *	ENXIO	- Invalid buffer passed in
4573  *	EFAULT	- ddi_copyin of data failed
4574  */
4575 static int
4576 vdc_set_vtoc_convert(vdc_t *vdc, void *from, void *to, int mode, int dir)
4577 {
4578 	void		*tmp_mem = NULL;
4579 	struct vtoc	vt;
4580 	struct vtoc	*vtp = &vt;
4581 	vd_vtoc_t	vtvd;
4582 	int		copy_len = 0;
4583 	int		rv = 0;
4584 
4585 	if (dir != VD_COPYIN)
4586 		return (0);	/* nothing to do */
4587 
4588 	if ((from == NULL) || (to == NULL))
4589 		return (ENXIO);
4590 
4591 	if (ddi_model_convert_from(mode & FMODELS) == DDI_MODEL_ILP32)
4592 		copy_len = sizeof (struct vtoc32);
4593 	else
4594 		copy_len = sizeof (struct vtoc);
4595 
4596 	tmp_mem = kmem_alloc(copy_len, KM_SLEEP);
4597 
4598 	rv = ddi_copyin(from, tmp_mem, copy_len, mode);
4599 	if (rv != 0) {
4600 		kmem_free(tmp_mem, copy_len);
4601 		return (EFAULT);
4602 	}
4603 
4604 	if (ddi_model_convert_from(mode & FMODELS) == DDI_MODEL_ILP32) {
4605 		vtoc32tovtoc((*(struct vtoc32 *)tmp_mem), vt);
4606 	} else {
4607 		vtp = tmp_mem;
4608 	}
4609 
4610 	/*
4611 	 * The VTOC is being changed, then vdc needs to update the copy
4612 	 * it saved in the soft state structure.
4613 	 */
4614 	bcopy(vtp, vdc->vtoc, sizeof (struct vtoc));
4615 
4616 	VTOC2VD_VTOC(vtp, &vtvd);
4617 	bcopy(&vtvd, to, sizeof (vd_vtoc_t));
4618 	kmem_free(tmp_mem, copy_len);
4619 
4620 	return (0);
4621 }
4622 
4623 /*
4624  * Function:
4625  *	vdc_get_geom_convert()
4626  *
4627  * Description:
4628  *	This routine performs the necessary convertions from the DKIOCGGEOM,
4629  *	DKIOCG_PHYSGEOM and DKIOG_VIRTGEOM Solaris structures to the format
4630  *	defined in FWARC 2006/195
4631  *
4632  * Arguments:
4633  *	vdc	- the vDisk client
4634  *	from	- Buffer with data
4635  *	to	- Buffer where data is to be copied to
4636  *	mode	- flags passed to ioctl
4637  *	dir	- direction of copy (in or out)
4638  *
4639  * Return Code:
4640  *	0	- Success
4641  *	ENXIO	- Invalid buffer passed in
4642  *	EFAULT	- ddi_copyout of data failed
4643  */
4644 static int
4645 vdc_get_geom_convert(vdc_t *vdc, void *from, void *to, int mode, int dir)
4646 {
4647 	_NOTE(ARGUNUSED(vdc))
4648 
4649 	struct dk_geom	geom;
4650 	int	copy_len = sizeof (struct dk_geom);
4651 	int	rv = 0;
4652 
4653 	if (dir != VD_COPYOUT)
4654 		return (0);	/* nothing to do */
4655 
4656 	if ((from == NULL) || (to == NULL))
4657 		return (ENXIO);
4658 
4659 	VD_GEOM2DK_GEOM((vd_geom_t *)from, &geom);
4660 	rv = ddi_copyout(&geom, to, copy_len, mode);
4661 	if (rv != 0)
4662 		rv = EFAULT;
4663 
4664 	return (rv);
4665 }
4666 
4667 /*
4668  * Function:
4669  *	vdc_set_geom_convert()
4670  *
4671  * Description:
4672  *	This routine performs the necessary convertions from the DKIOCSGEOM
4673  *	Solaris structure to the format defined in FWARC 2006/195.
4674  *
4675  * Arguments:
4676  *	vdc	- the vDisk client
4677  *	from	- Buffer with data
4678  *	to	- Buffer where data is to be copied to
4679  *	mode	- flags passed to ioctl
4680  *	dir	- direction of copy (in or out)
4681  *
4682  * Return Code:
4683  *	0	- Success
4684  *	ENXIO	- Invalid buffer passed in
4685  *	EFAULT	- ddi_copyin of data failed
4686  */
4687 static int
4688 vdc_set_geom_convert(vdc_t *vdc, void *from, void *to, int mode, int dir)
4689 {
4690 	_NOTE(ARGUNUSED(vdc))
4691 
4692 	vd_geom_t	vdgeom;
4693 	void		*tmp_mem = NULL;
4694 	int		copy_len = sizeof (struct dk_geom);
4695 	int		rv = 0;
4696 
4697 	if (dir != VD_COPYIN)
4698 		return (0);	/* nothing to do */
4699 
4700 	if ((from == NULL) || (to == NULL))
4701 		return (ENXIO);
4702 
4703 	tmp_mem = kmem_alloc(copy_len, KM_SLEEP);
4704 
4705 	rv = ddi_copyin(from, tmp_mem, copy_len, mode);
4706 	if (rv != 0) {
4707 		kmem_free(tmp_mem, copy_len);
4708 		return (EFAULT);
4709 	}
4710 	DK_GEOM2VD_GEOM((struct dk_geom *)tmp_mem, &vdgeom);
4711 	bcopy(&vdgeom, to, sizeof (vdgeom));
4712 	kmem_free(tmp_mem, copy_len);
4713 
4714 	return (0);
4715 }
4716 
4717 static int
4718 vdc_get_efi_convert(vdc_t *vdc, void *from, void *to, int mode, int dir)
4719 {
4720 	_NOTE(ARGUNUSED(vdc))
4721 
4722 	vd_efi_t	*vd_efi;
4723 	dk_efi_t	dk_efi;
4724 	int		rv = 0;
4725 	void		*uaddr;
4726 
4727 	if ((from == NULL) || (to == NULL))
4728 		return (ENXIO);
4729 
4730 	if (dir == VD_COPYIN) {
4731 
4732 		vd_efi = (vd_efi_t *)to;
4733 
4734 		rv = ddi_copyin(from, &dk_efi, sizeof (dk_efi_t), mode);
4735 		if (rv != 0)
4736 			return (EFAULT);
4737 
4738 		vd_efi->lba = dk_efi.dki_lba;
4739 		vd_efi->length = dk_efi.dki_length;
4740 		bzero(vd_efi->data, vd_efi->length);
4741 
4742 	} else {
4743 
4744 		rv = ddi_copyin(to, &dk_efi, sizeof (dk_efi_t), mode);
4745 		if (rv != 0)
4746 			return (EFAULT);
4747 
4748 		uaddr = dk_efi.dki_data;
4749 
4750 		dk_efi.dki_data = kmem_alloc(dk_efi.dki_length, KM_SLEEP);
4751 
4752 		VD_EFI2DK_EFI((vd_efi_t *)from, &dk_efi);
4753 
4754 		rv = ddi_copyout(dk_efi.dki_data, uaddr, dk_efi.dki_length,
4755 		    mode);
4756 		if (rv != 0)
4757 			return (EFAULT);
4758 
4759 		kmem_free(dk_efi.dki_data, dk_efi.dki_length);
4760 	}
4761 
4762 	return (0);
4763 }
4764 
4765 static int
4766 vdc_set_efi_convert(vdc_t *vdc, void *from, void *to, int mode, int dir)
4767 {
4768 	_NOTE(ARGUNUSED(vdc))
4769 
4770 	dk_efi_t	dk_efi;
4771 	void		*uaddr;
4772 
4773 	if (dir == VD_COPYOUT)
4774 		return (0);	/* nothing to do */
4775 
4776 	if ((from == NULL) || (to == NULL))
4777 		return (ENXIO);
4778 
4779 	if (ddi_copyin(from, &dk_efi, sizeof (dk_efi_t), mode) != 0)
4780 		return (EFAULT);
4781 
4782 	uaddr = dk_efi.dki_data;
4783 
4784 	dk_efi.dki_data = kmem_alloc(dk_efi.dki_length, KM_SLEEP);
4785 
4786 	if (ddi_copyin(uaddr, dk_efi.dki_data, dk_efi.dki_length, mode) != 0)
4787 		return (EFAULT);
4788 
4789 	DK_EFI2VD_EFI(&dk_efi, (vd_efi_t *)to);
4790 
4791 	kmem_free(dk_efi.dki_data, dk_efi.dki_length);
4792 
4793 	return (0);
4794 }
4795 
4796 /*
4797  * Function:
4798  *	vdc_create_fake_geometry()
4799  *
4800  * Description:
4801  *	This routine fakes up the disk info needed for some DKIO ioctls.
4802  *		- DKIOCINFO
4803  *		- DKIOCGMEDIAINFO
4804  *
4805  *	[ just like lofi(7D) and ramdisk(7D) ]
4806  *
4807  * Arguments:
4808  *	vdc	- soft state pointer for this instance of the device driver.
4809  *
4810  * Return Code:
4811  *	0	- Success
4812  */
4813 static int
4814 vdc_create_fake_geometry(vdc_t *vdc)
4815 {
4816 	ASSERT(vdc != NULL);
4817 
4818 	/*
4819 	 * Check if max_xfer_sz and vdisk_size are valid
4820 	 */
4821 	if (vdc->vdisk_size == 0 || vdc->max_xfer_sz == 0)
4822 		return (EIO);
4823 
4824 	/*
4825 	 * DKIOCINFO support
4826 	 */
4827 	vdc->cinfo = kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
4828 
4829 	(void) strcpy(vdc->cinfo->dki_cname, VDC_DRIVER_NAME);
4830 	(void) strcpy(vdc->cinfo->dki_dname, VDC_DRIVER_NAME);
4831 	/* max_xfer_sz is #blocks so we don't need to divide by DEV_BSIZE */
4832 	vdc->cinfo->dki_maxtransfer = vdc->max_xfer_sz;
4833 	vdc->cinfo->dki_ctype = DKC_SCSI_CCS;
4834 	vdc->cinfo->dki_flags = DKI_FMTVOL;
4835 	vdc->cinfo->dki_cnum = 0;
4836 	vdc->cinfo->dki_addr = 0;
4837 	vdc->cinfo->dki_space = 0;
4838 	vdc->cinfo->dki_prio = 0;
4839 	vdc->cinfo->dki_vec = 0;
4840 	vdc->cinfo->dki_unit = vdc->instance;
4841 	vdc->cinfo->dki_slave = 0;
4842 	/*
4843 	 * The partition number will be created on the fly depending on the
4844 	 * actual slice (i.e. minor node) that is used to request the data.
4845 	 */
4846 	vdc->cinfo->dki_partition = 0;
4847 
4848 	/*
4849 	 * DKIOCGMEDIAINFO support
4850 	 */
4851 	if (vdc->minfo == NULL)
4852 		vdc->minfo = kmem_zalloc(sizeof (struct dk_minfo), KM_SLEEP);
4853 	vdc->minfo->dki_media_type = DK_FIXED_DISK;
4854 	vdc->minfo->dki_capacity = vdc->vdisk_size;
4855 	vdc->minfo->dki_lbsize = DEV_BSIZE;
4856 
4857 	return (0);
4858 }
4859 
4860 /*
4861  * Function:
4862  *	vdc_setup_disk_layout()
4863  *
4864  * Description:
4865  *	This routine discovers all the necessary details about the "disk"
4866  *	by requesting the data that is available from the vDisk server and by
4867  *	faking up the rest of the data.
4868  *
4869  * Arguments:
4870  *	vdc	- soft state pointer for this instance of the device driver.
4871  *
4872  * Return Code:
4873  *	0	- Success
4874  */
4875 static int
4876 vdc_setup_disk_layout(vdc_t *vdc)
4877 {
4878 	buf_t	*buf;	/* BREAD requests need to be in a buf_t structure */
4879 	dev_t	dev;
4880 	int	slice = 0;
4881 	int	rv, error;
4882 
4883 	ASSERT(vdc != NULL);
4884 
4885 	if (vdc->vtoc == NULL)
4886 		vdc->vtoc = kmem_zalloc(sizeof (struct vtoc), KM_SLEEP);
4887 
4888 	dev = makedevice(ddi_driver_major(vdc->dip),
4889 				VD_MAKE_DEV(vdc->instance, 0));
4890 	rv = vd_process_ioctl(dev, DKIOCGVTOC, (caddr_t)vdc->vtoc, FKIOCTL);
4891 
4892 	if (rv && rv != ENOTSUP) {
4893 		DMSG(vdc, 0, "[%d] Failed to get VTOC (err=%d)",
4894 				vdc->instance, rv);
4895 		return (rv);
4896 	}
4897 
4898 	/*
4899 	 * The process of attempting to read VTOC will initiate
4900 	 * the handshake and establish a connection. Following
4901 	 * handshake, go ahead and create geometry.
4902 	 */
4903 	error = vdc_create_fake_geometry(vdc);
4904 	if (error != 0) {
4905 		DMSG(vdc, 0, "[%d] Failed to create disk geometry (err%d)",
4906 		    vdc->instance, error);
4907 		return (error);
4908 	}
4909 
4910 	if (rv == ENOTSUP) {
4911 		/*
4912 		 * If the device does not support VTOC then we try
4913 		 * to read an EFI label.
4914 		 */
4915 		struct dk_gpt *efi;
4916 		size_t efi_len;
4917 
4918 		rv = vdc_efi_alloc_and_read(dev, &efi, &efi_len);
4919 
4920 		if (rv) {
4921 			DMSG(vdc, 0, "[%d] Failed to get EFI (err=%d)",
4922 			    vdc->instance, rv);
4923 			return (rv);
4924 		}
4925 
4926 		vdc->vdisk_label = VD_DISK_LABEL_EFI;
4927 		vdc_store_efi(vdc, efi);
4928 		vd_efi_free(efi, efi_len);
4929 
4930 		return (0);
4931 	}
4932 
4933 	vdc->vdisk_label = VD_DISK_LABEL_VTOC;
4934 
4935 	/*
4936 	 * FUTURE: This could be default way for reading the VTOC
4937 	 * from the disk as supposed to sending the VD_OP_GET_VTOC
4938 	 * to the server. Currently this is a sanity check.
4939 	 *
4940 	 * find the slice that represents the entire "disk" and use that to
4941 	 * read the disk label. The convention in Solaris is that slice 2
4942 	 * represents the whole disk so we check that it is, otherwise we
4943 	 * default to slice 0
4944 	 */
4945 	if ((vdc->vdisk_type == VD_DISK_TYPE_DISK) &&
4946 	    (vdc->vtoc->v_part[2].p_tag == V_BACKUP)) {
4947 		slice = 2;
4948 	} else {
4949 		slice = 0;
4950 	}
4951 
4952 	/*
4953 	 * Read disk label from start of disk
4954 	 */
4955 	vdc->label = kmem_zalloc(DK_LABEL_SIZE, KM_SLEEP);
4956 	buf = kmem_alloc(sizeof (buf_t), KM_SLEEP);
4957 	bioinit(buf);
4958 	buf->b_un.b_addr = (caddr_t)vdc->label;
4959 	buf->b_bcount = DK_LABEL_SIZE;
4960 	buf->b_flags = B_BUSY | B_READ;
4961 	buf->b_dev = dev;
4962 	rv = vdc_send_request(vdc, VD_OP_BREAD, (caddr_t)vdc->label,
4963 	    DK_LABEL_SIZE, slice, 0, CB_STRATEGY, buf, VIO_read_dir);
4964 	if (rv) {
4965 		DMSG(vdc, 1, "[%d] Failed to read disk block 0\n",
4966 		    vdc->instance);
4967 		kmem_free(buf, sizeof (buf_t));
4968 		return (rv);
4969 	}
4970 	rv = biowait(buf);
4971 	biofini(buf);
4972 	kmem_free(buf, sizeof (buf_t));
4973 
4974 	return (rv);
4975 }
4976 
4977 /*
4978  * Function:
4979  *	vdc_setup_devid()
4980  *
4981  * Description:
4982  *	This routine discovers the devid of a vDisk. It requests the devid of
4983  *	the underlying device from the vDisk server, builds an encapsulated
4984  *	devid based on the retrieved devid and registers that new devid to
4985  *	the vDisk.
4986  *
4987  * Arguments:
4988  *	vdc	- soft state pointer for this instance of the device driver.
4989  *
4990  * Return Code:
4991  *	0	- A devid was succesfully registered for the vDisk
4992  */
4993 static int
4994 vdc_setup_devid(vdc_t *vdc)
4995 {
4996 	int rv;
4997 	vd_devid_t *vd_devid;
4998 	size_t bufsize, bufid_len;
4999 
5000 	/*
5001 	 * At first sight, we don't know the size of the devid that the
5002 	 * server will return but this size will be encoded into the
5003 	 * reply. So we do a first request using a default size then we
5004 	 * check if this size was large enough. If not then we do a second
5005 	 * request with the correct size returned by the server. Note that
5006 	 * ldc requires size to be 8-byte aligned.
5007 	 */
5008 	bufsize = P2ROUNDUP(VD_DEVID_SIZE(VD_DEVID_DEFAULT_LEN),
5009 	    sizeof (uint64_t));
5010 	vd_devid = kmem_zalloc(bufsize, KM_SLEEP);
5011 	bufid_len = bufsize - sizeof (vd_efi_t) - 1;
5012 
5013 	rv = vdc_do_sync_op(vdc, VD_OP_GET_DEVID, (caddr_t)vd_devid,
5014 	    bufsize, 0, 0, CB_SYNC, 0, VIO_both_dir);
5015 
5016 	DMSG(vdc, 2, "sync_op returned %d\n", rv);
5017 
5018 	if (rv) {
5019 		kmem_free(vd_devid, bufsize);
5020 		return (rv);
5021 	}
5022 
5023 	if (vd_devid->length > bufid_len) {
5024 		/*
5025 		 * The returned devid is larger than the buffer used. Try again
5026 		 * with a buffer with the right size.
5027 		 */
5028 		kmem_free(vd_devid, bufsize);
5029 		bufsize = P2ROUNDUP(VD_DEVID_SIZE(vd_devid->length),
5030 		    sizeof (uint64_t));
5031 		vd_devid = kmem_zalloc(bufsize, KM_SLEEP);
5032 		bufid_len = bufsize - sizeof (vd_efi_t) - 1;
5033 
5034 		rv = vdc_do_sync_op(vdc, VD_OP_GET_DEVID,
5035 		    (caddr_t)vd_devid, bufsize, 0, 0, CB_SYNC, 0,
5036 		    VIO_both_dir);
5037 
5038 		if (rv) {
5039 			kmem_free(vd_devid, bufsize);
5040 			return (rv);
5041 		}
5042 	}
5043 
5044 	/*
5045 	 * The virtual disk should have the same device id as the one associated
5046 	 * with the physical disk it is mapped on, otherwise sharing a disk
5047 	 * between a LDom and a non-LDom may not work (for example for a shared
5048 	 * SVM disk set).
5049 	 *
5050 	 * The DDI framework does not allow creating a device id with any
5051 	 * type so we first create a device id of type DEVID_ENCAP and then
5052 	 * we restore the orignal type of the physical device.
5053 	 */
5054 
5055 	DMSG(vdc, 2, ": devid length = %d\n", vd_devid->length);
5056 
5057 	/* build an encapsulated devid based on the returned devid */
5058 	if (ddi_devid_init(vdc->dip, DEVID_ENCAP, vd_devid->length,
5059 		vd_devid->id, &vdc->devid) != DDI_SUCCESS) {
5060 		DMSG(vdc, 1, "[%d] Fail to created devid\n", vdc->instance);
5061 		kmem_free(vd_devid, bufsize);
5062 		return (1);
5063 	}
5064 
5065 	DEVID_FORMTYPE((impl_devid_t *)vdc->devid, vd_devid->type);
5066 
5067 	ASSERT(ddi_devid_valid(vdc->devid) == DDI_SUCCESS);
5068 
5069 	kmem_free(vd_devid, bufsize);
5070 
5071 	if (ddi_devid_register(vdc->dip, vdc->devid) != DDI_SUCCESS) {
5072 		DMSG(vdc, 1, "[%d] Fail to register devid\n", vdc->instance);
5073 		return (1);
5074 	}
5075 
5076 	return (0);
5077 }
5078 
5079 static void
5080 vdc_store_efi(vdc_t *vdc, struct dk_gpt *efi)
5081 {
5082 	struct vtoc *vtoc = vdc->vtoc;
5083 
5084 	vd_efi_to_vtoc(efi, vtoc);
5085 	if (vdc->vdisk_type == VD_DISK_TYPE_SLICE) {
5086 		/*
5087 		 * vd_efi_to_vtoc() will store information about the EFI Sun
5088 		 * reserved partition (representing the entire disk) into
5089 		 * partition 7. However single-slice device will only have
5090 		 * that single partition and the vdc driver expects to find
5091 		 * information about that partition in slice 0. So we need
5092 		 * to copy information from slice 7 to slice 0.
5093 		 */
5094 		vtoc->v_part[0].p_tag = vtoc->v_part[VD_EFI_WD_SLICE].p_tag;
5095 		vtoc->v_part[0].p_flag = vtoc->v_part[VD_EFI_WD_SLICE].p_flag;
5096 		vtoc->v_part[0].p_start = vtoc->v_part[VD_EFI_WD_SLICE].p_start;
5097 		vtoc->v_part[0].p_size =  vtoc->v_part[VD_EFI_WD_SLICE].p_size;
5098 	}
5099 }
5100