xref: /illumos-gate/usr/src/uts/sun4v/io/vdc.c (revision 29368e86)
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 (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25 
26 /*
27  * LDoms virtual disk client (vdc) device driver
28  *
29  * This driver runs on a guest logical domain and communicates with the virtual
30  * disk server (vds) driver running on the service domain which is exporting
31  * virtualized "disks" to the guest logical domain.
32  *
33  * The driver can be divided into four sections:
34  *
35  * 1) generic device driver housekeeping
36  *	_init, _fini, attach, detach, ops structures, etc.
37  *
38  * 2) communication channel setup
39  *	Setup the communications link over the LDC channel that vdc uses to
40  *	talk to the vDisk server. Initialise the descriptor ring which
41  *	allows the LDC clients to transfer data via memory mappings.
42  *
43  * 3) Support exported to upper layers (filesystems, etc)
44  *	The upper layers call into vdc via strategy(9E) and DKIO(7I)
45  *	ioctl calls. vdc will copy the data to be written to the descriptor
46  *	ring or maps the buffer to store the data read by the vDisk
47  *	server into the descriptor ring. It then sends a message to the
48  *	vDisk server requesting it to complete the operation.
49  *
50  * 4) Handling responses from vDisk server.
51  *	The vDisk server will ACK some or all of the messages vdc sends to it
52  *	(this is configured during the handshake). Upon receipt of an ACK
53  *	vdc will check the descriptor ring and signal to the upper layer
54  *	code waiting on the IO.
55  */
56 
57 #include <sys/atomic.h>
58 #include <sys/conf.h>
59 #include <sys/disp.h>
60 #include <sys/ddi.h>
61 #include <sys/dkio.h>
62 #include <sys/efi_partition.h>
63 #include <sys/fcntl.h>
64 #include <sys/file.h>
65 #include <sys/kstat.h>
66 #include <sys/mach_descrip.h>
67 #include <sys/modctl.h>
68 #include <sys/mdeg.h>
69 #include <sys/note.h>
70 #include <sys/open.h>
71 #include <sys/random.h>
72 #include <sys/sdt.h>
73 #include <sys/stat.h>
74 #include <sys/sunddi.h>
75 #include <sys/types.h>
76 #include <sys/promif.h>
77 #include <sys/var.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/dktp/dadkio.h>
85 #include <sys/fs/dv_node.h>
86 #include <sys/mhd.h>
87 #include <sys/scsi/generic/sense.h>
88 #include <sys/scsi/impl/uscsi.h>
89 #include <sys/scsi/impl/services.h>
90 #include <sys/scsi/targets/sddef.h>
91 
92 #include <sys/ldoms.h>
93 #include <sys/ldc.h>
94 #include <sys/vio_common.h>
95 #include <sys/vio_mailbox.h>
96 #include <sys/vio_util.h>
97 #include <sys/vdsk_common.h>
98 #include <sys/vdsk_mailbox.h>
99 #include <sys/vdc.h>
100 
101 #define	VD_OLDVTOC_LIMIT	0x7fffffff
102 
103 /*
104  * function prototypes
105  */
106 
107 /* standard driver functions */
108 static int	vdc_open(dev_t *dev, int flag, int otyp, cred_t *cred);
109 static int	vdc_close(dev_t dev, int flag, int otyp, cred_t *cred);
110 static int	vdc_strategy(struct buf *buf);
111 static int	vdc_print(dev_t dev, char *str);
112 static int	vdc_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
113 static int	vdc_read(dev_t dev, struct uio *uio, cred_t *cred);
114 static int	vdc_write(dev_t dev, struct uio *uio, cred_t *cred);
115 static int	vdc_ioctl(dev_t dev, int cmd, intptr_t arg, int mode,
116 			cred_t *credp, int *rvalp);
117 static int	vdc_aread(dev_t dev, struct aio_req *aio, cred_t *cred);
118 static int	vdc_awrite(dev_t dev, struct aio_req *aio, cred_t *cred);
119 
120 static int	vdc_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd,
121 			void *arg, void **resultp);
122 static int	vdc_attach(dev_info_t *dip, ddi_attach_cmd_t cmd);
123 static int	vdc_detach(dev_info_t *dip, ddi_detach_cmd_t cmd);
124 static int	vdc_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
125 		    int mod_flags, char *name, caddr_t valuep, int *lengthp);
126 
127 /* setup */
128 static void	vdc_min(struct buf *bufp);
129 static int	vdc_send(vdc_t *vdc, caddr_t pkt, size_t *msglen);
130 static int	vdc_do_ldc_init(vdc_t *vdc, vdc_server_t *srvr);
131 static int	vdc_start_ldc_connection(vdc_t *vdc);
132 static int	vdc_create_device_nodes(vdc_t *vdc);
133 static int	vdc_create_device_nodes_efi(vdc_t *vdc);
134 static int	vdc_create_device_nodes_vtoc(vdc_t *vdc);
135 static void	vdc_create_io_kstats(vdc_t *vdc);
136 static void	vdc_create_err_kstats(vdc_t *vdc);
137 static void	vdc_set_err_kstats(vdc_t *vdc);
138 static int	vdc_get_md_node(dev_info_t *dip, md_t **mdpp,
139 		    mde_cookie_t *vd_nodep);
140 static int	vdc_init_ports(vdc_t *vdc, md_t *mdp, mde_cookie_t vd_nodep);
141 static void	vdc_fini_ports(vdc_t *vdc);
142 static void	vdc_switch_server(vdc_t *vdcp);
143 static int	vdc_do_ldc_up(vdc_t *vdc);
144 static void	vdc_terminate_ldc(vdc_t *vdc, vdc_server_t *srvr);
145 static int	vdc_init_descriptor_ring(vdc_t *vdc);
146 static void	vdc_destroy_descriptor_ring(vdc_t *vdc);
147 static int	vdc_setup_devid(vdc_t *vdc);
148 static void	vdc_store_label_efi(vdc_t *, efi_gpt_t *, efi_gpe_t *);
149 static void	vdc_store_label_vtoc(vdc_t *, struct dk_geom *,
150 		    struct extvtoc *);
151 static void	vdc_store_label_unk(vdc_t *vdc);
152 static boolean_t vdc_is_opened(vdc_t *vdc);
153 static void	vdc_update_size(vdc_t *vdc, size_t, size_t, size_t);
154 static int	vdc_update_vio_bsize(vdc_t *vdc, uint32_t);
155 
156 /* handshake with vds */
157 static int		vdc_init_ver_negotiation(vdc_t *vdc, vio_ver_t ver);
158 static int		vdc_ver_negotiation(vdc_t *vdcp);
159 static int		vdc_init_attr_negotiation(vdc_t *vdc);
160 static int		vdc_attr_negotiation(vdc_t *vdcp);
161 static int		vdc_init_dring_negotiate(vdc_t *vdc);
162 static int		vdc_dring_negotiation(vdc_t *vdcp);
163 static int		vdc_send_rdx(vdc_t *vdcp);
164 static int		vdc_rdx_exchange(vdc_t *vdcp);
165 static boolean_t	vdc_is_supported_version(vio_ver_msg_t *ver_msg);
166 
167 /* processing incoming messages from vDisk server */
168 static void	vdc_process_msg_thread(vdc_t *vdc);
169 static int	vdc_recv(vdc_t *vdc, vio_msg_t *msgp, size_t *nbytesp);
170 
171 static uint_t	vdc_handle_cb(uint64_t event, caddr_t arg);
172 static int	vdc_process_data_msg(vdc_t *vdc, vio_msg_t *msg);
173 static int	vdc_handle_ver_msg(vdc_t *vdc, vio_ver_msg_t *ver_msg);
174 static int	vdc_handle_attr_msg(vdc_t *vdc, vd_attr_msg_t *attr_msg);
175 static int	vdc_handle_dring_reg_msg(vdc_t *vdc, vio_dring_reg_msg_t *msg);
176 static int	vdc_send_request(vdc_t *vdcp, int operation,
177 		    caddr_t addr, size_t nbytes, int slice, diskaddr_t offset,
178 		    buf_t *bufp, vio_desc_direction_t dir, int flags);
179 static int	vdc_map_to_shared_dring(vdc_t *vdcp, int idx);
180 static int	vdc_populate_descriptor(vdc_t *vdcp, int operation,
181 		    caddr_t addr, size_t nbytes, int slice, diskaddr_t offset,
182 		    buf_t *bufp, vio_desc_direction_t dir, int flags);
183 static int	vdc_do_sync_op(vdc_t *vdcp, int operation, caddr_t addr,
184 		    size_t nbytes, int slice, diskaddr_t offset,
185 		    vio_desc_direction_t dir, boolean_t);
186 static int	vdc_do_op(vdc_t *vdc, int op, caddr_t addr, size_t nbytes,
187 		    int slice, diskaddr_t offset, struct buf *bufp,
188 		    vio_desc_direction_t dir, int flags);
189 
190 static int	vdc_wait_for_response(vdc_t *vdcp, vio_msg_t *msgp);
191 static int	vdc_drain_response(vdc_t *vdcp, struct buf *buf);
192 static int	vdc_depopulate_descriptor(vdc_t *vdc, uint_t idx);
193 static int	vdc_populate_mem_hdl(vdc_t *vdcp, vdc_local_desc_t *ldep);
194 static int	vdc_verify_seq_num(vdc_t *vdc, vio_dring_msg_t *dring_msg);
195 
196 /* dkio */
197 static int	vd_process_ioctl(dev_t dev, int cmd, caddr_t arg, int mode,
198 		    int *rvalp);
199 static int	vd_process_efi_ioctl(void *vdisk, int cmd, uintptr_t arg);
200 static void	vdc_create_fake_geometry(vdc_t *vdc);
201 static int	vdc_validate_geometry(vdc_t *vdc);
202 static void	vdc_validate(vdc_t *vdc);
203 static void	vdc_validate_task(void *arg);
204 static int	vdc_null_copy_func(vdc_t *vdc, void *from, void *to,
205 		    int mode, int dir);
206 static int	vdc_get_wce_convert(vdc_t *vdc, void *from, void *to,
207 		    int mode, int dir);
208 static int	vdc_set_wce_convert(vdc_t *vdc, void *from, void *to,
209 		    int mode, int dir);
210 static int	vdc_get_vtoc_convert(vdc_t *vdc, void *from, void *to,
211 		    int mode, int dir);
212 static int	vdc_set_vtoc_convert(vdc_t *vdc, void *from, void *to,
213 		    int mode, int dir);
214 static int	vdc_get_extvtoc_convert(vdc_t *vdc, void *from, void *to,
215 		    int mode, int dir);
216 static int	vdc_set_extvtoc_convert(vdc_t *vdc, void *from, void *to,
217 		    int mode, int dir);
218 static int	vdc_get_geom_convert(vdc_t *vdc, void *from, void *to,
219 		    int mode, int dir);
220 static int	vdc_set_geom_convert(vdc_t *vdc, void *from, void *to,
221 		    int mode, int dir);
222 static int	vdc_get_efi_convert(vdc_t *vdc, void *from, void *to,
223 		    int mode, int dir);
224 static int	vdc_set_efi_convert(vdc_t *vdc, void *from, void *to,
225 		    int mode, int dir);
226 
227 static void	vdc_ownership_update(vdc_t *vdc, int ownership_flags);
228 static int	vdc_access_set(vdc_t *vdc, uint64_t flags);
229 static vdc_io_t	*vdc_eio_queue(vdc_t *vdc, int index);
230 static void	vdc_eio_unqueue(vdc_t *vdc, clock_t deadline,
231 		    boolean_t complete_io);
232 static int	vdc_eio_check(vdc_t *vdc, int flags);
233 static void	vdc_eio_thread(void *arg);
234 
235 /*
236  * Module variables
237  */
238 
239 /*
240  * Number of handshake retries with the current server before switching to
241  * a different server. These retries are done so that we stick with the same
242  * server if vdc receives a LDC reset event during the initiation of the
243  * handshake. This can happen if vdc reset the LDC channel and then immediately
244  * retry a connexion before it has received the LDC reset event.
245  *
246  * If there is only one server then we "switch" to the same server. We also
247  * switch if the handshake has reached the attribute negotiate step whatever
248  * the number of handshake retries might be.
249  */
250 static uint_t vdc_hshake_retries = VDC_HSHAKE_RETRIES;
251 
252 /*
253  * If the handshake done during the attach fails then the two following
254  * variables will also be used to control the number of retries for the
255  * next handshakes. In that case, when a handshake is done after the
256  * attach (i.e. the vdc lifecycle is VDC_ONLINE_PENDING) then the handshake
257  * will be retried until we have done an attribution negotiation with each
258  * server, with a specified minimum total number of negotations (the value
259  * of the vdc_hattr_min_initial or vdc_hattr_min variable).
260  *
261  * This prevents new I/Os on a newly used vdisk to block forever if the
262  * attribute negotiations can not be done, and to limit the amount of time
263  * before I/Os will fail. Basically, attribute negotiations will fail when
264  * the service is up but the backend does not exist. In that case, vds will
265  * typically retry to access the backend during 50 seconds. So I/Os will fail
266  * after the following amount of time:
267  *
268  *	50 seconds x max(number of servers, vdc->hattr_min)
269  *
270  * After that the handshake done during the attach has failed then the next
271  * handshake will use vdc_attr_min_initial. This handshake will correspond to
272  * the very first I/O to the device. If this handshake also fails then
273  * vdc_hattr_min will be used for subsequent handshakes. We typically allow
274  * more retries for the first handshake (VDC_HATTR_MIN_INITIAL = 3) to give more
275  * time for the backend to become available (50s x VDC_HATTR_MIN_INITIAL = 150s)
276  * in case this is a critical vdisk (e.g. vdisk access during boot). Then we use
277  * a smaller value (VDC_HATTR_MIN = 1) to avoid waiting too long for each I/O.
278  */
279 static uint_t vdc_hattr_min_initial = VDC_HATTR_MIN_INITIAL;
280 static uint_t vdc_hattr_min = VDC_HATTR_MIN;
281 
282 /*
283  * Tunable variables to control how long vdc waits before timing out on
284  * various operations
285  */
286 static int	vdc_timeout = 0; /* units: seconds */
287 static int	vdc_ldcup_timeout = 1; /* units: seconds */
288 
289 static uint64_t vdc_hz_min_ldc_delay;
290 static uint64_t vdc_min_timeout_ldc = 1 * MILLISEC;
291 static uint64_t vdc_hz_max_ldc_delay;
292 static uint64_t vdc_max_timeout_ldc = 100 * MILLISEC;
293 
294 static uint64_t vdc_ldc_read_init_delay = 1 * MILLISEC;
295 static uint64_t vdc_ldc_read_max_delay = 100 * MILLISEC;
296 
297 /* values for dumping - need to run in a tighter loop */
298 static uint64_t	vdc_usec_timeout_dump = 100 * MILLISEC;	/* 0.1s units: ns */
299 static int	vdc_dump_retries = 100;
300 
301 static uint16_t	vdc_scsi_timeout = 60;	/* 60s units: seconds  */
302 
303 static uint64_t vdc_ownership_delay = 6 * MICROSEC; /* 6s units: usec */
304 
305 /* Count of the number of vdc instances attached */
306 static volatile uint32_t	vdc_instance_count = 0;
307 
308 /* Tunable to log all SCSI errors */
309 static boolean_t vdc_scsi_log_error = B_FALSE;
310 
311 /* Soft state pointer */
312 static void	*vdc_state;
313 
314 /*
315  * Controlling the verbosity of the error/debug messages
316  *
317  * vdc_msglevel - controls level of messages
318  * vdc_matchinst - 64-bit variable where each bit corresponds
319  *                 to the vdc instance the vdc_msglevel applies.
320  */
321 int		vdc_msglevel = 0x0;
322 uint64_t	vdc_matchinst = 0ull;
323 
324 /*
325  * Supported vDisk protocol version pairs.
326  *
327  * The first array entry is the latest and preferred version.
328  */
329 static const vio_ver_t	vdc_version[] = {{1, 1}};
330 
331 static struct cb_ops vdc_cb_ops = {
332 	vdc_open,	/* cb_open */
333 	vdc_close,	/* cb_close */
334 	vdc_strategy,	/* cb_strategy */
335 	vdc_print,	/* cb_print */
336 	vdc_dump,	/* cb_dump */
337 	vdc_read,	/* cb_read */
338 	vdc_write,	/* cb_write */
339 	vdc_ioctl,	/* cb_ioctl */
340 	nodev,		/* cb_devmap */
341 	nodev,		/* cb_mmap */
342 	nodev,		/* cb_segmap */
343 	nochpoll,	/* cb_chpoll */
344 	vdc_prop_op,	/* cb_prop_op */
345 	NULL,		/* cb_str */
346 	D_MP | D_64BIT,	/* cb_flag */
347 	CB_REV,		/* cb_rev */
348 	vdc_aread,	/* cb_aread */
349 	vdc_awrite	/* cb_awrite */
350 };
351 
352 static struct dev_ops vdc_ops = {
353 	DEVO_REV,	/* devo_rev */
354 	0,		/* devo_refcnt */
355 	vdc_getinfo,	/* devo_getinfo */
356 	nulldev,	/* devo_identify */
357 	nulldev,	/* devo_probe */
358 	vdc_attach,	/* devo_attach */
359 	vdc_detach,	/* devo_detach */
360 	nodev,		/* devo_reset */
361 	&vdc_cb_ops,	/* devo_cb_ops */
362 	NULL,		/* devo_bus_ops */
363 	nulldev,	/* devo_power */
364 	ddi_quiesce_not_needed,	/* devo_quiesce */
365 };
366 
367 static struct modldrv modldrv = {
368 	&mod_driverops,
369 	"virtual disk client",
370 	&vdc_ops,
371 };
372 
373 static struct modlinkage modlinkage = {
374 	MODREV_1,
375 	&modldrv,
376 	NULL
377 };
378 
379 /* -------------------------------------------------------------------------- */
380 
381 /*
382  * Device Driver housekeeping and setup
383  */
384 
385 int
_init(void)386 _init(void)
387 {
388 	int	status;
389 
390 	if ((status = ddi_soft_state_init(&vdc_state, sizeof (vdc_t), 1)) != 0)
391 		return (status);
392 	if ((status = mod_install(&modlinkage)) != 0)
393 		ddi_soft_state_fini(&vdc_state);
394 	return (status);
395 }
396 
397 int
_info(struct modinfo * modinfop)398 _info(struct modinfo *modinfop)
399 {
400 	return (mod_info(&modlinkage, modinfop));
401 }
402 
403 int
_fini(void)404 _fini(void)
405 {
406 	int	status;
407 
408 	if ((status = mod_remove(&modlinkage)) != 0)
409 		return (status);
410 	ddi_soft_state_fini(&vdc_state);
411 	return (0);
412 }
413 
414 static int
vdc_getinfo(dev_info_t * dip,ddi_info_cmd_t cmd,void * arg,void ** resultp)415 vdc_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd,  void *arg, void **resultp)
416 {
417 	_NOTE(ARGUNUSED(dip))
418 
419 	int	instance = VDCUNIT((dev_t)arg);
420 	vdc_t	*vdc = NULL;
421 
422 	switch (cmd) {
423 	case DDI_INFO_DEVT2DEVINFO:
424 		if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
425 			*resultp = NULL;
426 			return (DDI_FAILURE);
427 		}
428 		*resultp = vdc->dip;
429 		return (DDI_SUCCESS);
430 	case DDI_INFO_DEVT2INSTANCE:
431 		*resultp = (void *)(uintptr_t)instance;
432 		return (DDI_SUCCESS);
433 	default:
434 		*resultp = NULL;
435 		return (DDI_FAILURE);
436 	}
437 }
438 
439 static int
vdc_detach(dev_info_t * dip,ddi_detach_cmd_t cmd)440 vdc_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
441 {
442 	kt_did_t eio_tid, ownership_tid;
443 	int	instance;
444 	int	rv;
445 	vdc_server_t *srvr;
446 	vdc_t	*vdc = NULL;
447 
448 	switch (cmd) {
449 	case DDI_DETACH:
450 		/* the real work happens below */
451 		break;
452 	case DDI_SUSPEND:
453 		/* nothing to do for this non-device */
454 		return (DDI_SUCCESS);
455 	default:
456 		return (DDI_FAILURE);
457 	}
458 
459 	ASSERT(cmd == DDI_DETACH);
460 	instance = ddi_get_instance(dip);
461 	DMSGX(1, "[%d] Entered\n", instance);
462 
463 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
464 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
465 		return (DDI_FAILURE);
466 	}
467 
468 	if (vdc_is_opened(vdc)) {
469 		DMSG(vdc, 0, "[%d] Cannot detach: device is open", instance);
470 		return (DDI_FAILURE);
471 	}
472 
473 	if (vdc->dkio_flush_pending) {
474 		DMSG(vdc, 0,
475 		    "[%d] Cannot detach: %d outstanding DKIO flushes\n",
476 		    instance, vdc->dkio_flush_pending);
477 		return (DDI_FAILURE);
478 	}
479 
480 	if (vdc->validate_pending) {
481 		DMSG(vdc, 0,
482 		    "[%d] Cannot detach: %d outstanding validate request\n",
483 		    instance, vdc->validate_pending);
484 		return (DDI_FAILURE);
485 	}
486 
487 	DMSG(vdc, 0, "[%d] proceeding...\n", instance);
488 
489 	/* If we took ownership, release ownership */
490 	mutex_enter(&vdc->ownership_lock);
491 	if (vdc->ownership & VDC_OWNERSHIP_GRANTED) {
492 		rv = vdc_access_set(vdc, VD_ACCESS_SET_CLEAR);
493 		if (rv == 0) {
494 			vdc_ownership_update(vdc, VDC_OWNERSHIP_NONE);
495 		}
496 	}
497 	mutex_exit(&vdc->ownership_lock);
498 
499 	/* mark instance as detaching */
500 	mutex_enter(&vdc->lock);
501 	vdc->lifecycle	= VDC_LC_DETACHING;
502 	mutex_exit(&vdc->lock);
503 
504 	/*
505 	 * Try and disable callbacks to prevent another handshake. We have to
506 	 * disable callbacks for all servers.
507 	 */
508 	for (srvr = vdc->server_list; srvr != NULL; srvr = srvr->next) {
509 		rv = ldc_set_cb_mode(srvr->ldc_handle, LDC_CB_DISABLE);
510 		DMSG(vdc, 0, "callback disabled (ldc=%lu, rv=%d)\n",
511 		    srvr->ldc_id, rv);
512 	}
513 
514 	if (vdc->initialized & VDC_THREAD) {
515 		mutex_enter(&vdc->read_lock);
516 		if ((vdc->read_state == VDC_READ_WAITING) ||
517 		    (vdc->read_state == VDC_READ_RESET)) {
518 			vdc->read_state = VDC_READ_RESET;
519 			cv_signal(&vdc->read_cv);
520 		}
521 
522 		mutex_exit(&vdc->read_lock);
523 
524 		/* wake up any thread waiting for connection to come online */
525 		mutex_enter(&vdc->lock);
526 		if (vdc->state == VDC_STATE_INIT_WAITING) {
527 			DMSG(vdc, 0,
528 			    "[%d] write reset - move to resetting state...\n",
529 			    instance);
530 			vdc->state = VDC_STATE_RESETTING;
531 			cv_signal(&vdc->initwait_cv);
532 		} else if (vdc->state == VDC_STATE_FAILED) {
533 			vdc->io_pending = B_TRUE;
534 			cv_signal(&vdc->io_pending_cv);
535 		}
536 		mutex_exit(&vdc->lock);
537 
538 		/* now wait until state transitions to VDC_STATE_DETACH */
539 		thread_join(vdc->msg_proc_thr->t_did);
540 		ASSERT(vdc->state == VDC_STATE_DETACH);
541 		DMSG(vdc, 0, "[%d] Reset thread exit and join ..\n",
542 		    vdc->instance);
543 	}
544 
545 	mutex_enter(&vdc->lock);
546 
547 	if (vdc->initialized & VDC_DRING)
548 		vdc_destroy_descriptor_ring(vdc);
549 
550 	vdc_fini_ports(vdc);
551 
552 	if (vdc->eio_thread) {
553 		eio_tid = vdc->eio_thread->t_did;
554 		vdc->failfast_interval = 0;
555 		ASSERT(vdc->num_servers == 0);
556 		cv_signal(&vdc->eio_cv);
557 	} else {
558 		eio_tid = 0;
559 	}
560 
561 	if (vdc->ownership & VDC_OWNERSHIP_WANTED) {
562 		ownership_tid = vdc->ownership_thread->t_did;
563 		vdc->ownership = VDC_OWNERSHIP_NONE;
564 		cv_signal(&vdc->ownership_cv);
565 	} else {
566 		ownership_tid = 0;
567 	}
568 
569 	mutex_exit(&vdc->lock);
570 
571 	if (eio_tid != 0)
572 		thread_join(eio_tid);
573 
574 	if (ownership_tid != 0)
575 		thread_join(ownership_tid);
576 
577 	if (vdc->initialized & VDC_MINOR)
578 		ddi_remove_minor_node(dip, NULL);
579 
580 	if (vdc->io_stats) {
581 		kstat_delete(vdc->io_stats);
582 		vdc->io_stats = NULL;
583 	}
584 
585 	if (vdc->err_stats) {
586 		kstat_delete(vdc->err_stats);
587 		vdc->err_stats = NULL;
588 	}
589 
590 	if (vdc->initialized & VDC_LOCKS) {
591 		mutex_destroy(&vdc->lock);
592 		mutex_destroy(&vdc->read_lock);
593 		mutex_destroy(&vdc->ownership_lock);
594 		cv_destroy(&vdc->initwait_cv);
595 		cv_destroy(&vdc->dring_free_cv);
596 		cv_destroy(&vdc->membind_cv);
597 		cv_destroy(&vdc->sync_blocked_cv);
598 		cv_destroy(&vdc->read_cv);
599 		cv_destroy(&vdc->running_cv);
600 		cv_destroy(&vdc->io_pending_cv);
601 		cv_destroy(&vdc->ownership_cv);
602 		cv_destroy(&vdc->eio_cv);
603 	}
604 
605 	if (vdc->minfo)
606 		kmem_free(vdc->minfo, sizeof (struct dk_minfo));
607 
608 	if (vdc->cinfo)
609 		kmem_free(vdc->cinfo, sizeof (struct dk_cinfo));
610 
611 	if (vdc->vtoc)
612 		kmem_free(vdc->vtoc, sizeof (struct extvtoc));
613 
614 	if (vdc->geom)
615 		kmem_free(vdc->geom, sizeof (struct dk_geom));
616 
617 	if (vdc->devid) {
618 		ddi_devid_unregister(dip);
619 		ddi_devid_free(vdc->devid);
620 	}
621 
622 	if (vdc->initialized & VDC_SOFT_STATE)
623 		ddi_soft_state_free(vdc_state, instance);
624 
625 	DMSG(vdc, 0, "[%d] End %p\n", instance, (void *)vdc);
626 
627 	return (DDI_SUCCESS);
628 }
629 
630 
631 static int
vdc_do_attach(dev_info_t * dip)632 vdc_do_attach(dev_info_t *dip)
633 {
634 	int		instance;
635 	vdc_t		*vdc = NULL;
636 	int		status;
637 	md_t		*mdp;
638 	mde_cookie_t	vd_node;
639 
640 	ASSERT(dip != NULL);
641 
642 	instance = ddi_get_instance(dip);
643 	if (ddi_soft_state_zalloc(vdc_state, instance) != DDI_SUCCESS) {
644 		cmn_err(CE_NOTE, "[%d] Couldn't alloc state structure",
645 		    instance);
646 		return (DDI_FAILURE);
647 	}
648 
649 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
650 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
651 		return (DDI_FAILURE);
652 	}
653 
654 	/*
655 	 * We assign the value to initialized in this case to zero out the
656 	 * variable and then set bits in it to indicate what has been done
657 	 */
658 	vdc->initialized = VDC_SOFT_STATE;
659 
660 	vdc_hz_min_ldc_delay = drv_usectohz(vdc_min_timeout_ldc);
661 	vdc_hz_max_ldc_delay = drv_usectohz(vdc_max_timeout_ldc);
662 
663 	vdc->dip	= dip;
664 	vdc->instance	= instance;
665 	vdc->vdisk_type	= VD_DISK_TYPE_UNK;
666 	vdc->vdisk_label = VD_DISK_LABEL_UNK;
667 	vdc->state	= VDC_STATE_INIT;
668 	vdc->lifecycle	= VDC_LC_ATTACHING;
669 	vdc->session_id = 0;
670 	vdc->vdisk_bsize = DEV_BSIZE;
671 	vdc->vio_bmask = 0;
672 	vdc->vio_bshift = 0;
673 	vdc->max_xfer_sz = maxphys / vdc->vdisk_bsize;
674 
675 	/*
676 	 * We assume, for now, that the vDisk server will export 'read'
677 	 * operations to us at a minimum (this is needed because of checks
678 	 * in vdc for supported operations early in the handshake process).
679 	 * The vDisk server will return ENOTSUP if this is not the case.
680 	 * The value will be overwritten during the attribute exchange with
681 	 * the bitmask of operations exported by server.
682 	 */
683 	vdc->operations = VD_OP_MASK_READ;
684 
685 	vdc->vtoc = NULL;
686 	vdc->geom = NULL;
687 	vdc->cinfo = NULL;
688 	vdc->minfo = NULL;
689 
690 	mutex_init(&vdc->lock, NULL, MUTEX_DRIVER, NULL);
691 	cv_init(&vdc->initwait_cv, NULL, CV_DRIVER, NULL);
692 	cv_init(&vdc->dring_free_cv, NULL, CV_DRIVER, NULL);
693 	cv_init(&vdc->membind_cv, NULL, CV_DRIVER, NULL);
694 	cv_init(&vdc->running_cv, NULL, CV_DRIVER, NULL);
695 	cv_init(&vdc->io_pending_cv, NULL, CV_DRIVER, NULL);
696 
697 	vdc->io_pending = B_FALSE;
698 	vdc->threads_pending = 0;
699 	vdc->sync_op_blocked = B_FALSE;
700 	cv_init(&vdc->sync_blocked_cv, NULL, CV_DRIVER, NULL);
701 
702 	mutex_init(&vdc->ownership_lock, NULL, MUTEX_DRIVER, NULL);
703 	cv_init(&vdc->ownership_cv, NULL, CV_DRIVER, NULL);
704 	cv_init(&vdc->eio_cv, NULL, CV_DRIVER, NULL);
705 
706 	/* init blocking msg read functionality */
707 	mutex_init(&vdc->read_lock, NULL, MUTEX_DRIVER, NULL);
708 	cv_init(&vdc->read_cv, NULL, CV_DRIVER, NULL);
709 	vdc->read_state = VDC_READ_IDLE;
710 
711 	vdc->initialized |= VDC_LOCKS;
712 
713 	/* get device and port MD node for this disk instance */
714 	if (vdc_get_md_node(dip, &mdp, &vd_node) != 0) {
715 		cmn_err(CE_NOTE, "[%d] Could not get machine description node",
716 		    instance);
717 		return (DDI_FAILURE);
718 	}
719 
720 	if (vdc_init_ports(vdc, mdp, vd_node) != 0) {
721 		cmn_err(CE_NOTE, "[%d] Error initialising ports", instance);
722 		return (DDI_FAILURE);
723 	}
724 
725 	(void) md_fini_handle(mdp);
726 
727 	/* Create the kstats for saving the I/O statistics used by iostat(1M) */
728 	vdc_create_io_kstats(vdc);
729 	vdc_create_err_kstats(vdc);
730 
731 	/* Initialize remaining structures before starting the msg thread */
732 	vdc->vdisk_label = VD_DISK_LABEL_UNK;
733 	vdc->vtoc = kmem_zalloc(sizeof (struct extvtoc), KM_SLEEP);
734 	vdc->geom = kmem_zalloc(sizeof (struct dk_geom), KM_SLEEP);
735 	vdc->minfo = kmem_zalloc(sizeof (struct dk_minfo), KM_SLEEP);
736 
737 	/* initialize the thread responsible for managing state with server */
738 	vdc->msg_proc_thr = thread_create(NULL, 0, vdc_process_msg_thread,
739 	    vdc, 0, &p0, TS_RUN, minclsyspri);
740 	if (vdc->msg_proc_thr == NULL) {
741 		cmn_err(CE_NOTE, "[%d] Failed to create msg processing thread",
742 		    instance);
743 		return (DDI_FAILURE);
744 	}
745 
746 	/*
747 	 * If there are multiple servers then start the eio thread.
748 	 */
749 	if (vdc->num_servers > 1) {
750 		vdc->eio_thread = thread_create(NULL, 0, vdc_eio_thread, vdc, 0,
751 		    &p0, TS_RUN, v.v_maxsyspri - 2);
752 		if (vdc->eio_thread == NULL) {
753 			cmn_err(CE_NOTE, "[%d] Failed to create error "
754 			    "I/O thread", instance);
755 			return (DDI_FAILURE);
756 		}
757 	}
758 
759 	vdc->initialized |= VDC_THREAD;
760 
761 	atomic_inc_32(&vdc_instance_count);
762 
763 	/*
764 	 * Check the disk label. This will send requests and do the handshake.
765 	 * We don't really care about the disk label now. What we really need is
766 	 * the handshake do be done so that we know the type of the disk (slice
767 	 * or full disk) and the appropriate device nodes can be created.
768 	 */
769 
770 	mutex_enter(&vdc->lock);
771 	(void) vdc_validate_geometry(vdc);
772 	mutex_exit(&vdc->lock);
773 
774 	/*
775 	 * Now that we have the device info we can create the device nodes
776 	 */
777 	status = vdc_create_device_nodes(vdc);
778 	if (status) {
779 		DMSG(vdc, 0, "[%d] Failed to create device nodes",
780 		    instance);
781 		goto return_status;
782 	}
783 
784 	/*
785 	 * Fill in the fields of the error statistics kstat that were not
786 	 * available when creating the kstat
787 	 */
788 	vdc_set_err_kstats(vdc);
789 	ddi_report_dev(dip);
790 	ASSERT(vdc->lifecycle == VDC_LC_ONLINE ||
791 	    vdc->lifecycle == VDC_LC_ONLINE_PENDING);
792 	DMSG(vdc, 0, "[%d] Attach tasks successful\n", instance);
793 
794 return_status:
795 	DMSG(vdc, 0, "[%d] Attach completed\n", instance);
796 	return (status);
797 }
798 
799 static int
vdc_attach(dev_info_t * dip,ddi_attach_cmd_t cmd)800 vdc_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
801 {
802 	int	status;
803 
804 	switch (cmd) {
805 	case DDI_ATTACH:
806 		if ((status = vdc_do_attach(dip)) != 0)
807 			(void) vdc_detach(dip, DDI_DETACH);
808 		return (status);
809 	case DDI_RESUME:
810 		/* nothing to do for this non-device */
811 		return (DDI_SUCCESS);
812 	default:
813 		return (DDI_FAILURE);
814 	}
815 }
816 
817 static int
vdc_do_ldc_init(vdc_t * vdc,vdc_server_t * srvr)818 vdc_do_ldc_init(vdc_t *vdc, vdc_server_t *srvr)
819 {
820 	int			status = 0;
821 	ldc_status_t		ldc_state;
822 	ldc_attr_t		ldc_attr;
823 
824 	ASSERT(vdc != NULL);
825 	ASSERT(srvr != NULL);
826 
827 	ldc_attr.devclass = LDC_DEV_BLK;
828 	ldc_attr.instance = vdc->instance;
829 	ldc_attr.mode = LDC_MODE_UNRELIABLE;	/* unreliable transport */
830 	ldc_attr.mtu = VD_LDC_MTU;
831 
832 	if ((srvr->state & VDC_LDC_INIT) == 0) {
833 		status = ldc_init(srvr->ldc_id, &ldc_attr,
834 		    &srvr->ldc_handle);
835 		if (status != 0) {
836 			DMSG(vdc, 0, "[%d] ldc_init(chan %ld) returned %d",
837 			    vdc->instance, srvr->ldc_id, status);
838 			return (status);
839 		}
840 		srvr->state |= VDC_LDC_INIT;
841 	}
842 	status = ldc_status(srvr->ldc_handle, &ldc_state);
843 	if (status != 0) {
844 		DMSG(vdc, 0, "[%d] Cannot discover LDC status [err=%d]",
845 		    vdc->instance, status);
846 		goto init_exit;
847 	}
848 	srvr->ldc_state = ldc_state;
849 
850 	if ((srvr->state & VDC_LDC_CB) == 0) {
851 		status = ldc_reg_callback(srvr->ldc_handle, vdc_handle_cb,
852 		    (caddr_t)srvr);
853 		if (status != 0) {
854 			DMSG(vdc, 0, "[%d] LDC callback reg. failed (%d)",
855 			    vdc->instance, status);
856 			goto init_exit;
857 		}
858 		srvr->state |= VDC_LDC_CB;
859 	}
860 
861 	/*
862 	 * At this stage we have initialised LDC, we will now try and open
863 	 * the connection.
864 	 */
865 	if (srvr->ldc_state == LDC_INIT) {
866 		status = ldc_open(srvr->ldc_handle);
867 		if (status != 0) {
868 			DMSG(vdc, 0, "[%d] ldc_open(chan %ld) returned %d",
869 			    vdc->instance, srvr->ldc_id, status);
870 			goto init_exit;
871 		}
872 		srvr->state |= VDC_LDC_OPEN;
873 	}
874 
875 init_exit:
876 	if (status) {
877 		vdc_terminate_ldc(vdc, srvr);
878 	}
879 
880 	return (status);
881 }
882 
883 static int
vdc_start_ldc_connection(vdc_t * vdc)884 vdc_start_ldc_connection(vdc_t *vdc)
885 {
886 	int		status = 0;
887 
888 	ASSERT(vdc != NULL);
889 
890 	ASSERT(MUTEX_HELD(&vdc->lock));
891 
892 	status = vdc_do_ldc_up(vdc);
893 
894 	DMSG(vdc, 0, "[%d] Finished bringing up LDC\n", vdc->instance);
895 
896 	return (status);
897 }
898 
899 static int
vdc_stop_ldc_connection(vdc_t * vdcp)900 vdc_stop_ldc_connection(vdc_t *vdcp)
901 {
902 	int	status;
903 
904 	ASSERT(vdcp != NULL);
905 
906 	ASSERT(MUTEX_HELD(&vdcp->lock));
907 
908 	DMSG(vdcp, 0, ": Resetting connection to vDisk server : state %d\n",
909 	    vdcp->state);
910 
911 	status = ldc_down(vdcp->curr_server->ldc_handle);
912 	DMSG(vdcp, 0, "ldc_down() = %d\n", status);
913 
914 	vdcp->initialized &= ~VDC_HANDSHAKE;
915 	DMSG(vdcp, 0, "initialized=%x\n", vdcp->initialized);
916 
917 	return (status);
918 }
919 
920 static void
vdc_create_io_kstats(vdc_t * vdc)921 vdc_create_io_kstats(vdc_t *vdc)
922 {
923 	if (vdc->io_stats != NULL) {
924 		DMSG(vdc, 0, "[%d] I/O kstat already exists\n", vdc->instance);
925 		return;
926 	}
927 
928 	vdc->io_stats = kstat_create(VDC_DRIVER_NAME, vdc->instance, NULL,
929 	    "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
930 	if (vdc->io_stats != NULL) {
931 		vdc->io_stats->ks_lock = &vdc->lock;
932 		kstat_install(vdc->io_stats);
933 	} else {
934 		cmn_err(CE_NOTE, "[%d] Failed to create kstat: I/O statistics"
935 		    " will not be gathered", vdc->instance);
936 	}
937 }
938 
939 static void
vdc_create_err_kstats(vdc_t * vdc)940 vdc_create_err_kstats(vdc_t *vdc)
941 {
942 	vd_err_stats_t	*stp;
943 	char	kstatmodule_err[KSTAT_STRLEN];
944 	char	kstatname[KSTAT_STRLEN];
945 	int	ndata = (sizeof (vd_err_stats_t) / sizeof (kstat_named_t));
946 	int	instance = vdc->instance;
947 
948 	if (vdc->err_stats != NULL) {
949 		DMSG(vdc, 0, "[%d] ERR kstat already exists\n", vdc->instance);
950 		return;
951 	}
952 
953 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
954 	    "%serr", VDC_DRIVER_NAME);
955 	(void) snprintf(kstatname, sizeof (kstatname),
956 	    "%s%d,err", VDC_DRIVER_NAME, instance);
957 
958 	vdc->err_stats = kstat_create(kstatmodule_err, instance, kstatname,
959 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
960 
961 	if (vdc->err_stats == NULL) {
962 		cmn_err(CE_NOTE, "[%d] Failed to create kstat: Error statistics"
963 		    " will not be gathered", instance);
964 		return;
965 	}
966 
967 	stp = (vd_err_stats_t *)vdc->err_stats->ks_data;
968 	kstat_named_init(&stp->vd_softerrs,	"Soft Errors",
969 	    KSTAT_DATA_UINT32);
970 	kstat_named_init(&stp->vd_transerrs,	"Transport Errors",
971 	    KSTAT_DATA_UINT32);
972 	kstat_named_init(&stp->vd_protoerrs,	"Protocol Errors",
973 	    KSTAT_DATA_UINT32);
974 	kstat_named_init(&stp->vd_vid,		"Vendor",
975 	    KSTAT_DATA_CHAR);
976 	kstat_named_init(&stp->vd_pid,		"Product",
977 	    KSTAT_DATA_CHAR);
978 	kstat_named_init(&stp->vd_capacity,	"Size",
979 	    KSTAT_DATA_ULONGLONG);
980 
981 	vdc->err_stats->ks_update  = nulldev;
982 
983 	kstat_install(vdc->err_stats);
984 }
985 
986 static void
vdc_set_err_kstats(vdc_t * vdc)987 vdc_set_err_kstats(vdc_t *vdc)
988 {
989 	vd_err_stats_t  *stp;
990 
991 	if (vdc->err_stats == NULL)
992 		return;
993 
994 	mutex_enter(&vdc->lock);
995 
996 	stp = (vd_err_stats_t *)vdc->err_stats->ks_data;
997 	ASSERT(stp != NULL);
998 
999 	stp->vd_capacity.value.ui64 = vdc->vdisk_size * vdc->vdisk_bsize;
1000 	(void) strcpy(stp->vd_vid.value.c, "SUN");
1001 	(void) strcpy(stp->vd_pid.value.c, "VDSK");
1002 
1003 	mutex_exit(&vdc->lock);
1004 }
1005 
1006 static int
vdc_create_device_nodes_efi(vdc_t * vdc)1007 vdc_create_device_nodes_efi(vdc_t *vdc)
1008 {
1009 	ddi_remove_minor_node(vdc->dip, "h");
1010 	ddi_remove_minor_node(vdc->dip, "h,raw");
1011 
1012 	if (ddi_create_minor_node(vdc->dip, "wd", S_IFBLK,
1013 	    VD_MAKE_DEV(vdc->instance, VD_EFI_WD_SLICE),
1014 	    DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
1015 		cmn_err(CE_NOTE, "[%d] Couldn't add block node 'wd'",
1016 		    vdc->instance);
1017 		return (EIO);
1018 	}
1019 
1020 	/* if any device node is created we set this flag */
1021 	vdc->initialized |= VDC_MINOR;
1022 
1023 	if (ddi_create_minor_node(vdc->dip, "wd,raw", S_IFCHR,
1024 	    VD_MAKE_DEV(vdc->instance, VD_EFI_WD_SLICE),
1025 	    DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
1026 		cmn_err(CE_NOTE, "[%d] Couldn't add block node 'wd,raw'",
1027 		    vdc->instance);
1028 		return (EIO);
1029 	}
1030 
1031 	return (0);
1032 }
1033 
1034 static int
vdc_create_device_nodes_vtoc(vdc_t * vdc)1035 vdc_create_device_nodes_vtoc(vdc_t *vdc)
1036 {
1037 	ddi_remove_minor_node(vdc->dip, "wd");
1038 	ddi_remove_minor_node(vdc->dip, "wd,raw");
1039 
1040 	if (ddi_create_minor_node(vdc->dip, "h", S_IFBLK,
1041 	    VD_MAKE_DEV(vdc->instance, VD_EFI_WD_SLICE),
1042 	    DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
1043 		cmn_err(CE_NOTE, "[%d] Couldn't add block node 'h'",
1044 		    vdc->instance);
1045 		return (EIO);
1046 	}
1047 
1048 	/* if any device node is created we set this flag */
1049 	vdc->initialized |= VDC_MINOR;
1050 
1051 	if (ddi_create_minor_node(vdc->dip, "h,raw", S_IFCHR,
1052 	    VD_MAKE_DEV(vdc->instance, VD_EFI_WD_SLICE),
1053 	    DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
1054 		cmn_err(CE_NOTE, "[%d] Couldn't add block node 'h,raw'",
1055 		    vdc->instance);
1056 		return (EIO);
1057 	}
1058 
1059 	return (0);
1060 }
1061 
1062 /*
1063  * Function:
1064  *	vdc_create_device_nodes
1065  *
1066  * Description:
1067  *	This function creates the block and character device nodes under
1068  *	/devices. It is called as part of the attach(9E) of the instance
1069  *	during the handshake with vds after vds has sent the attributes
1070  *	to vdc.
1071  *
1072  *	If the device is of type VD_DISK_TYPE_SLICE then the minor node
1073  *	of 2 is used in keeping with the Solaris convention that slice 2
1074  *	refers to a whole disk. Slices start at 'a'
1075  *
1076  * Parameters:
1077  *	vdc		- soft state pointer
1078  *
1079  * Return Values
1080  *	0		- Success
1081  *	EIO		- Failed to create node
1082  */
1083 static int
vdc_create_device_nodes(vdc_t * vdc)1084 vdc_create_device_nodes(vdc_t *vdc)
1085 {
1086 	char		name[sizeof ("s,raw")];
1087 	dev_info_t	*dip = NULL;
1088 	int		instance, status;
1089 	int		num_slices = 1;
1090 	int		i;
1091 
1092 	ASSERT(vdc != NULL);
1093 
1094 	instance = vdc->instance;
1095 	dip = vdc->dip;
1096 
1097 	switch (vdc->vdisk_type) {
1098 	case VD_DISK_TYPE_DISK:
1099 	case VD_DISK_TYPE_UNK:
1100 		num_slices = V_NUMPAR;
1101 		break;
1102 	case VD_DISK_TYPE_SLICE:
1103 		num_slices = 1;
1104 		break;
1105 	default:
1106 		ASSERT(0);
1107 	}
1108 
1109 	/*
1110 	 * Minor nodes are different for EFI disks: EFI disks do not have
1111 	 * a minor node 'g' for the minor number corresponding to slice
1112 	 * VD_EFI_WD_SLICE (slice 7) instead they have a minor node 'wd'
1113 	 * representing the whole disk.
1114 	 */
1115 	for (i = 0; i < num_slices; i++) {
1116 
1117 		if (i == VD_EFI_WD_SLICE) {
1118 			if (vdc->vdisk_label == VD_DISK_LABEL_EFI)
1119 				status = vdc_create_device_nodes_efi(vdc);
1120 			else
1121 				status = vdc_create_device_nodes_vtoc(vdc);
1122 			if (status != 0)
1123 				return (status);
1124 			continue;
1125 		}
1126 
1127 		(void) snprintf(name, sizeof (name), "%c", 'a' + i);
1128 		if (ddi_create_minor_node(dip, name, S_IFBLK,
1129 		    VD_MAKE_DEV(instance, i), DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
1130 			cmn_err(CE_NOTE, "[%d] Couldn't add block node '%s'",
1131 			    instance, name);
1132 			return (EIO);
1133 		}
1134 
1135 		/* if any device node is created we set this flag */
1136 		vdc->initialized |= VDC_MINOR;
1137 
1138 		(void) snprintf(name, sizeof (name), "%c%s", 'a' + i, ",raw");
1139 
1140 		if (ddi_create_minor_node(dip, name, S_IFCHR,
1141 		    VD_MAKE_DEV(instance, i), DDI_NT_BLOCK, 0) != DDI_SUCCESS) {
1142 			cmn_err(CE_NOTE, "[%d] Couldn't add raw node '%s'",
1143 			    instance, name);
1144 			return (EIO);
1145 		}
1146 	}
1147 
1148 	return (0);
1149 }
1150 
1151 /*
1152  * Driver prop_op(9e) entry point function. Return the number of blocks for
1153  * the partition in question or forward the request to the property facilities.
1154  */
1155 static int
vdc_prop_op(dev_t dev,dev_info_t * dip,ddi_prop_op_t prop_op,int mod_flags,char * name,caddr_t valuep,int * lengthp)1156 vdc_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
1157     char *name, caddr_t valuep, int *lengthp)
1158 {
1159 	int instance = ddi_get_instance(dip);
1160 	vdc_t *vdc;
1161 	uint64_t nblocks;
1162 	uint_t blksize;
1163 
1164 	vdc = ddi_get_soft_state(vdc_state, instance);
1165 
1166 	if (dev == DDI_DEV_T_ANY || vdc == NULL) {
1167 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
1168 		    name, valuep, lengthp));
1169 	}
1170 
1171 	mutex_enter(&vdc->lock);
1172 	(void) vdc_validate_geometry(vdc);
1173 	if (vdc->vdisk_label == VD_DISK_LABEL_UNK) {
1174 		mutex_exit(&vdc->lock);
1175 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
1176 		    name, valuep, lengthp));
1177 	}
1178 	nblocks = vdc->slice[VDCPART(dev)].nblocks;
1179 	blksize = vdc->vdisk_bsize;
1180 	mutex_exit(&vdc->lock);
1181 
1182 	return (ddi_prop_op_nblocks_blksize(dev, dip, prop_op, mod_flags,
1183 	    name, valuep, lengthp, nblocks, blksize));
1184 }
1185 
1186 /*
1187  * Function:
1188  *	vdc_is_opened
1189  *
1190  * Description:
1191  *	This function checks if any slice of a given virtual disk is
1192  *	currently opened.
1193  *
1194  * Parameters:
1195  *	vdc		- soft state pointer
1196  *
1197  * Return Values
1198  *	B_TRUE		- at least one slice is opened.
1199  *	B_FALSE		- no slice is opened.
1200  */
1201 static boolean_t
vdc_is_opened(vdc_t * vdc)1202 vdc_is_opened(vdc_t *vdc)
1203 {
1204 	int i;
1205 
1206 	/* check if there's any layered open */
1207 	for (i = 0; i < V_NUMPAR; i++) {
1208 		if (vdc->open_lyr[i] > 0)
1209 			return (B_TRUE);
1210 	}
1211 
1212 	/* check if there is any other kind of open */
1213 	for (i = 0; i < OTYPCNT; i++) {
1214 		if (vdc->open[i] != 0)
1215 			return (B_TRUE);
1216 	}
1217 
1218 	return (B_FALSE);
1219 }
1220 
1221 static int
vdc_mark_opened(vdc_t * vdc,int slice,int flag,int otyp)1222 vdc_mark_opened(vdc_t *vdc, int slice, int flag, int otyp)
1223 {
1224 	uint8_t slicemask;
1225 	int i;
1226 
1227 	ASSERT(otyp < OTYPCNT);
1228 	ASSERT(slice < V_NUMPAR);
1229 	ASSERT(MUTEX_HELD(&vdc->lock));
1230 
1231 	slicemask = 1 << slice;
1232 
1233 	/*
1234 	 * If we have a single-slice disk which was unavailable during the
1235 	 * attach then a device was created for each 8 slices. Now that
1236 	 * the type is known, we prevent opening any slice other than 0
1237 	 * even if a device still exists.
1238 	 */
1239 	if (vdc->vdisk_type == VD_DISK_TYPE_SLICE && slice != 0)
1240 		return (EIO);
1241 
1242 	/* check if slice is already exclusively opened */
1243 	if (vdc->open_excl & slicemask)
1244 		return (EBUSY);
1245 
1246 	/* if open exclusive, check if slice is already opened */
1247 	if (flag & FEXCL) {
1248 		if (vdc->open_lyr[slice] > 0)
1249 			return (EBUSY);
1250 		for (i = 0; i < OTYPCNT; i++) {
1251 			if (vdc->open[i] & slicemask)
1252 				return (EBUSY);
1253 		}
1254 		vdc->open_excl |= slicemask;
1255 	}
1256 
1257 	/* mark slice as opened */
1258 	if (otyp == OTYP_LYR) {
1259 		vdc->open_lyr[slice]++;
1260 	} else {
1261 		vdc->open[otyp] |= slicemask;
1262 	}
1263 
1264 	return (0);
1265 }
1266 
1267 static void
vdc_mark_closed(vdc_t * vdc,int slice,int flag,int otyp)1268 vdc_mark_closed(vdc_t *vdc, int slice, int flag, int otyp)
1269 {
1270 	uint8_t slicemask;
1271 
1272 	ASSERT(otyp < OTYPCNT);
1273 	ASSERT(slice < V_NUMPAR);
1274 	ASSERT(MUTEX_HELD(&vdc->lock));
1275 
1276 	slicemask = 1 << slice;
1277 
1278 	if (otyp == OTYP_LYR) {
1279 		ASSERT(vdc->open_lyr[slice] > 0);
1280 		vdc->open_lyr[slice]--;
1281 	} else {
1282 		vdc->open[otyp] &= ~slicemask;
1283 	}
1284 
1285 	if (flag & FEXCL)
1286 		vdc->open_excl &= ~slicemask;
1287 }
1288 
1289 static int
vdc_open(dev_t * dev,int flag,int otyp,cred_t * cred)1290 vdc_open(dev_t *dev, int flag, int otyp, cred_t *cred)
1291 {
1292 	_NOTE(ARGUNUSED(cred))
1293 
1294 	int	instance, nodelay;
1295 	int	slice, status = 0;
1296 	vdc_t	*vdc;
1297 
1298 	ASSERT(dev != NULL);
1299 	instance = VDCUNIT(*dev);
1300 
1301 	if (otyp >= OTYPCNT)
1302 		return (EINVAL);
1303 
1304 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
1305 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
1306 		return (ENXIO);
1307 	}
1308 
1309 	DMSG(vdc, 0, "minor = %d flag = %x, otyp = %x\n",
1310 	    getminor(*dev), flag, otyp);
1311 
1312 	slice = VDCPART(*dev);
1313 
1314 	nodelay = flag & (FNDELAY | FNONBLOCK);
1315 
1316 	if ((flag & FWRITE) && (!nodelay) &&
1317 	    !(VD_OP_SUPPORTED(vdc->operations, VD_OP_BWRITE))) {
1318 		return (EROFS);
1319 	}
1320 
1321 	mutex_enter(&vdc->lock);
1322 
1323 	status = vdc_mark_opened(vdc, slice, flag, otyp);
1324 
1325 	if (status != 0) {
1326 		mutex_exit(&vdc->lock);
1327 		return (status);
1328 	}
1329 
1330 	/*
1331 	 * If the disk type is unknown then we have to wait for the
1332 	 * handshake to complete because we don't know if the slice
1333 	 * device we are opening effectively exists.
1334 	 */
1335 	if (vdc->vdisk_type != VD_DISK_TYPE_UNK && nodelay) {
1336 
1337 		/* don't resubmit a validate request if there's already one */
1338 		if (vdc->validate_pending > 0) {
1339 			mutex_exit(&vdc->lock);
1340 			return (0);
1341 		}
1342 
1343 		/* call vdc_validate() asynchronously to avoid blocking */
1344 		if (taskq_dispatch(system_taskq, vdc_validate_task,
1345 		    (void *)vdc, TQ_NOSLEEP) == TASKQID_INVALID) {
1346 			vdc_mark_closed(vdc, slice, flag, otyp);
1347 			mutex_exit(&vdc->lock);
1348 			return (ENXIO);
1349 		}
1350 
1351 		vdc->validate_pending++;
1352 		mutex_exit(&vdc->lock);
1353 		return (0);
1354 	}
1355 
1356 	mutex_exit(&vdc->lock);
1357 
1358 	vdc_validate(vdc);
1359 
1360 	mutex_enter(&vdc->lock);
1361 
1362 	if (vdc->vdisk_type == VD_DISK_TYPE_UNK ||
1363 	    (vdc->vdisk_type == VD_DISK_TYPE_SLICE && slice != 0) ||
1364 	    (!nodelay && (vdc->vdisk_label == VD_DISK_LABEL_UNK ||
1365 	    vdc->slice[slice].nblocks == 0))) {
1366 		vdc_mark_closed(vdc, slice, flag, otyp);
1367 		status = EIO;
1368 	}
1369 
1370 	mutex_exit(&vdc->lock);
1371 
1372 	return (status);
1373 }
1374 
1375 static int
vdc_close(dev_t dev,int flag,int otyp,cred_t * cred)1376 vdc_close(dev_t dev, int flag, int otyp, cred_t *cred)
1377 {
1378 	_NOTE(ARGUNUSED(cred))
1379 
1380 	int	instance;
1381 	int	slice;
1382 	int	rv, rval;
1383 	vdc_t	*vdc;
1384 
1385 	instance = VDCUNIT(dev);
1386 
1387 	if (otyp >= OTYPCNT)
1388 		return (EINVAL);
1389 
1390 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
1391 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
1392 		return (ENXIO);
1393 	}
1394 
1395 	DMSG(vdc, 0, "[%d] flag = %x, otyp = %x\n", instance, flag, otyp);
1396 
1397 	slice = VDCPART(dev);
1398 
1399 	/*
1400 	 * Attempt to flush the W$ on a close operation. If this is
1401 	 * not a supported IOCTL command or the backing device is read-only
1402 	 * do not fail the close operation.
1403 	 */
1404 	rv = vd_process_ioctl(dev, DKIOCFLUSHWRITECACHE, NULL, FKIOCTL, &rval);
1405 
1406 	if (rv != 0 && rv != ENOTSUP && rv != ENOTTY && rv != EROFS) {
1407 		DMSG(vdc, 0, "[%d] flush failed with error %d on close\n",
1408 		    instance, rv);
1409 		return (EIO);
1410 	}
1411 
1412 	mutex_enter(&vdc->lock);
1413 	vdc_mark_closed(vdc, slice, flag, otyp);
1414 	mutex_exit(&vdc->lock);
1415 
1416 	return (0);
1417 }
1418 
1419 static int
vdc_ioctl(dev_t dev,int cmd,intptr_t arg,int mode,cred_t * credp,int * rvalp)1420 vdc_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp, int *rvalp)
1421 {
1422 	_NOTE(ARGUNUSED(credp))
1423 
1424 	return (vd_process_ioctl(dev, cmd, (caddr_t)arg, mode, rvalp));
1425 }
1426 
1427 static int
vdc_print(dev_t dev,char * str)1428 vdc_print(dev_t dev, char *str)
1429 {
1430 	cmn_err(CE_NOTE, "vdc%d:  %s", VDCUNIT(dev), str);
1431 	return (0);
1432 }
1433 
1434 static int
vdc_dump(dev_t dev,caddr_t addr,daddr_t blkno,int nblk)1435 vdc_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
1436 {
1437 	int	rv, flags;
1438 	size_t	nbytes = nblk * DEV_BSIZE;
1439 	int	instance = VDCUNIT(dev);
1440 	vdc_t	*vdc = NULL;
1441 	diskaddr_t vio_blkno;
1442 
1443 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
1444 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
1445 		return (ENXIO);
1446 	}
1447 
1448 	DMSG(vdc, 2, "[%d] dump %ld bytes at block 0x%lx : addr=0x%p\n",
1449 	    instance, nbytes, blkno, (void *)addr);
1450 
1451 	/* convert logical block to vio block */
1452 	if ((blkno & vdc->vio_bmask) != 0) {
1453 		DMSG(vdc, 0, "Misaligned block number (%lu)\n", blkno);
1454 		return (EINVAL);
1455 	}
1456 	vio_blkno = blkno >> vdc->vio_bshift;
1457 
1458 	/*
1459 	 * If we are panicking, we need the state to be "running" so that we
1460 	 * can submit I/Os, but we don't want to check for any backend error.
1461 	 */
1462 	flags = (ddi_in_panic())? VDC_OP_STATE_RUNNING : VDC_OP_NORMAL;
1463 
1464 	rv = vdc_do_op(vdc, VD_OP_BWRITE, addr, nbytes, VDCPART(dev),
1465 	    vio_blkno, NULL, VIO_write_dir, flags);
1466 
1467 	if (rv) {
1468 		DMSG(vdc, 0, "Failed to do a disk dump (err=%d)\n", rv);
1469 		return (rv);
1470 	}
1471 
1472 	DMSG(vdc, 0, "[%d] End\n", instance);
1473 
1474 	return (0);
1475 }
1476 
1477 /* -------------------------------------------------------------------------- */
1478 
1479 /*
1480  * Disk access routines
1481  *
1482  */
1483 
1484 /*
1485  * vdc_strategy()
1486  *
1487  * Return Value:
1488  *	0:	As per strategy(9E), the strategy() function must return 0
1489  *		[ bioerror(9f) sets b_flags to the proper error code ]
1490  */
1491 static int
vdc_strategy(struct buf * buf)1492 vdc_strategy(struct buf *buf)
1493 {
1494 	diskaddr_t vio_blkno;
1495 	vdc_t	*vdc = NULL;
1496 	int	instance = VDCUNIT(buf->b_edev);
1497 	int	op = (buf->b_flags & B_READ) ? VD_OP_BREAD : VD_OP_BWRITE;
1498 	int	slice;
1499 
1500 	if ((vdc = ddi_get_soft_state(vdc_state, instance)) == NULL) {
1501 		cmn_err(CE_NOTE, "[%d] Couldn't get state structure", instance);
1502 		bioerror(buf, ENXIO);
1503 		biodone(buf);
1504 		return (0);
1505 	}
1506 
1507 	DMSG(vdc, 2, "[%d] %s %ld bytes at block %llx : b_addr=0x%p\n",
1508 	    instance, (buf->b_flags & B_READ) ? "Read" : "Write",
1509 	    buf->b_bcount, buf->b_lblkno, (void *)buf->b_un.b_addr);
1510 
1511 	bp_mapin(buf);
1512 
1513 	if ((long)buf->b_private == VD_SLICE_NONE) {
1514 		/* I/O using an absolute disk offset */
1515 		slice = VD_SLICE_NONE;
1516 	} else {
1517 		slice = VDCPART(buf->b_edev);
1518 	}
1519 
1520 	/*
1521 	 * In the buf structure, b_lblkno represents a logical block number
1522 	 * using a block size of 512 bytes. For the VIO request, this block
1523 	 * number has to be converted to be represented with the block size
1524 	 * used by the VIO protocol.
1525 	 */
1526 	if ((buf->b_lblkno & vdc->vio_bmask) != 0) {
1527 		bioerror(buf, EINVAL);
1528 		biodone(buf);
1529 		return (0);
1530 	}
1531 	vio_blkno = buf->b_lblkno >> vdc->vio_bshift;
1532 
1533 	/* submit the I/O, any error will be reported in the buf structure */
1534 	(void) vdc_do_op(vdc, op, (caddr_t)buf->b_un.b_addr,
1535 	    buf->b_bcount, slice, vio_blkno,
1536 	    buf, (op == VD_OP_BREAD) ? VIO_read_dir : VIO_write_dir,
1537 	    VDC_OP_NORMAL);
1538 
1539 	return (0);
1540 }
1541 
1542 /*
1543  * Function:
1544  *	vdc_min
1545  *
1546  * Description:
1547  *	Routine to limit the size of a data transfer. Used in
1548  *	conjunction with physio(9F).
1549  *
1550  * Arguments:
1551  *	bp - pointer to the indicated buf(9S) struct.
1552  *
1553  */
1554 static void
vdc_min(struct buf * bufp)1555 vdc_min(struct buf *bufp)
1556 {
1557 	vdc_t	*vdc = NULL;
1558 	int	instance = VDCUNIT(bufp->b_edev);
1559 
1560 	vdc = ddi_get_soft_state(vdc_state, instance);
1561 	VERIFY(vdc != NULL);
1562 
1563 	if (bufp->b_bcount > (vdc->max_xfer_sz * vdc->vdisk_bsize)) {
1564 		bufp->b_bcount = vdc->max_xfer_sz * vdc->vdisk_bsize;
1565 	}
1566 }
1567 
1568 static int
vdc_read(dev_t dev,struct uio * uio,cred_t * cred)1569 vdc_read(dev_t dev, struct uio *uio, cred_t *cred)
1570 {
1571 	_NOTE(ARGUNUSED(cred))
1572 
1573 	DMSGX(1, "[%d] Entered", VDCUNIT(dev));
1574 	return (physio(vdc_strategy, NULL, dev, B_READ, vdc_min, uio));
1575 }
1576 
1577 static int
vdc_write(dev_t dev,struct uio * uio,cred_t * cred)1578 vdc_write(dev_t dev, struct uio *uio, cred_t *cred)
1579 {
1580 	_NOTE(ARGUNUSED(cred))
1581 
1582 	DMSGX(1, "[%d] Entered", VDCUNIT(dev));
1583 	return (physio(vdc_strategy, NULL, dev, B_WRITE, vdc_min, uio));
1584 }
1585 
1586 static int
vdc_aread(dev_t dev,struct aio_req * aio,cred_t * cred)1587 vdc_aread(dev_t dev, struct aio_req *aio, cred_t *cred)
1588 {
1589 	_NOTE(ARGUNUSED(cred))
1590 
1591 	DMSGX(1, "[%d] Entered", VDCUNIT(dev));
1592 	return (aphysio(vdc_strategy, anocancel, dev, B_READ, vdc_min, aio));
1593 }
1594 
1595 static int
vdc_awrite(dev_t dev,struct aio_req * aio,cred_t * cred)1596 vdc_awrite(dev_t dev, struct aio_req *aio, cred_t *cred)
1597 {
1598 	_NOTE(ARGUNUSED(cred))
1599 
1600 	DMSGX(1, "[%d] Entered", VDCUNIT(dev));
1601 	return (aphysio(vdc_strategy, anocancel, dev, B_WRITE, vdc_min, aio));
1602 }
1603 
1604 
1605 /* -------------------------------------------------------------------------- */
1606 
1607 /*
1608  * Handshake support
1609  */
1610 
1611 
1612 /*
1613  * Function:
1614  *	vdc_init_ver_negotiation()
1615  *
1616  * Description:
1617  *
1618  * Arguments:
1619  *	vdc	- soft state pointer for this instance of the device driver.
1620  *
1621  * Return Code:
1622  *	0	- Success
1623  */
1624 static int
vdc_init_ver_negotiation(vdc_t * vdc,vio_ver_t ver)1625 vdc_init_ver_negotiation(vdc_t *vdc, vio_ver_t ver)
1626 {
1627 	vio_ver_msg_t	pkt;
1628 	size_t		msglen = sizeof (pkt);
1629 	int		status = -1;
1630 
1631 	ASSERT(vdc != NULL);
1632 	ASSERT(mutex_owned(&vdc->lock));
1633 
1634 	DMSG(vdc, 0, "[%d] Entered.\n", vdc->instance);
1635 
1636 	/*
1637 	 * set the Session ID to a unique value
1638 	 * (the lower 32 bits of the clock tick)
1639 	 */
1640 	vdc->session_id = ((uint32_t)gettick() & 0xffffffff);
1641 	DMSG(vdc, 0, "[%d] Set SID to 0x%lx\n", vdc->instance, vdc->session_id);
1642 
1643 	pkt.tag.vio_msgtype = VIO_TYPE_CTRL;
1644 	pkt.tag.vio_subtype = VIO_SUBTYPE_INFO;
1645 	pkt.tag.vio_subtype_env = VIO_VER_INFO;
1646 	pkt.tag.vio_sid = vdc->session_id;
1647 	pkt.dev_class = VDEV_DISK;
1648 	pkt.ver_major = ver.major;
1649 	pkt.ver_minor = ver.minor;
1650 
1651 	status = vdc_send(vdc, (caddr_t)&pkt, &msglen);
1652 	DMSG(vdc, 0, "[%d] Ver info sent (status = %d)\n",
1653 	    vdc->instance, status);
1654 	if ((status != 0) || (msglen != sizeof (vio_ver_msg_t))) {
1655 		DMSG(vdc, 0, "[%d] Failed to send Ver negotiation info: "
1656 		    "id(%lx) rv(%d) size(%ld)", vdc->instance,
1657 		    vdc->curr_server->ldc_handle, status, msglen);
1658 		if (msglen != sizeof (vio_ver_msg_t))
1659 			status = ENOMSG;
1660 	}
1661 
1662 	return (status);
1663 }
1664 
1665 /*
1666  * Function:
1667  *	vdc_ver_negotiation()
1668  *
1669  * Description:
1670  *
1671  * Arguments:
1672  *	vdcp	- soft state pointer for this instance of the device driver.
1673  *
1674  * Return Code:
1675  *	0	- Success
1676  */
1677 static int
vdc_ver_negotiation(vdc_t * vdcp)1678 vdc_ver_negotiation(vdc_t *vdcp)
1679 {
1680 	vio_msg_t vio_msg;
1681 	int status;
1682 
1683 	if (status = vdc_init_ver_negotiation(vdcp, vdc_version[0]))
1684 		return (status);
1685 
1686 	/* release lock and wait for response */
1687 	mutex_exit(&vdcp->lock);
1688 	status = vdc_wait_for_response(vdcp, &vio_msg);
1689 	mutex_enter(&vdcp->lock);
1690 	if (status) {
1691 		DMSG(vdcp, 0,
1692 		    "[%d] Failed waiting for Ver negotiation response, rv(%d)",
1693 		    vdcp->instance, status);
1694 		return (status);
1695 	}
1696 
1697 	/* check type and sub_type ... */
1698 	if (vio_msg.tag.vio_msgtype != VIO_TYPE_CTRL ||
1699 	    vio_msg.tag.vio_subtype == VIO_SUBTYPE_INFO) {
1700 		DMSG(vdcp, 0, "[%d] Invalid ver negotiation response\n",
1701 		    vdcp->instance);
1702 		return (EPROTO);
1703 	}
1704 
1705 	return (vdc_handle_ver_msg(vdcp, (vio_ver_msg_t *)&vio_msg));
1706 }
1707 
1708 /*
1709  * Function:
1710  *	vdc_init_attr_negotiation()
1711  *
1712  * Description:
1713  *
1714  * Arguments:
1715  *	vdc	- soft state pointer for this instance of the device driver.
1716  *
1717  * Return Code:
1718  *	0	- Success
1719  */
1720 static int
vdc_init_attr_negotiation(vdc_t * vdc)1721 vdc_init_attr_negotiation(vdc_t *vdc)
1722 {
1723 	vd_attr_msg_t	pkt;
1724 	size_t		msglen = sizeof (pkt);
1725 	int		status;
1726 
1727 	ASSERT(vdc != NULL);
1728 	ASSERT(mutex_owned(&vdc->lock));
1729 
1730 	DMSG(vdc, 0, "[%d] entered\n", vdc->instance);
1731 
1732 	/* fill in tag */
1733 	pkt.tag.vio_msgtype = VIO_TYPE_CTRL;
1734 	pkt.tag.vio_subtype = VIO_SUBTYPE_INFO;
1735 	pkt.tag.vio_subtype_env = VIO_ATTR_INFO;
1736 	pkt.tag.vio_sid = vdc->session_id;
1737 	/* fill in payload */
1738 	pkt.max_xfer_sz = vdc->max_xfer_sz;
1739 	pkt.vdisk_block_size = vdc->vdisk_bsize;
1740 	pkt.xfer_mode = VIO_DRING_MODE_V1_0;
1741 	pkt.operations = 0;	/* server will set bits of valid operations */
1742 	pkt.vdisk_type = 0;	/* server will set to valid device type */
1743 	pkt.vdisk_media = 0;	/* server will set to valid media type */
1744 	pkt.vdisk_size = 0;	/* server will set to valid size */
1745 
1746 	status = vdc_send(vdc, (caddr_t)&pkt, &msglen);
1747 	DMSG(vdc, 0, "Attr info sent (status = %d)\n", status);
1748 
1749 	if ((status != 0) || (msglen != sizeof (vd_attr_msg_t))) {
1750 		DMSG(vdc, 0, "[%d] Failed to send Attr negotiation info: "
1751 		    "id(%lx) rv(%d) size(%ld)", vdc->instance,
1752 		    vdc->curr_server->ldc_handle, status, msglen);
1753 		if (msglen != sizeof (vd_attr_msg_t))
1754 			status = ENOMSG;
1755 	}
1756 
1757 	return (status);
1758 }
1759 
1760 /*
1761  * Function:
1762  *	vdc_attr_negotiation()
1763  *
1764  * Description:
1765  *
1766  * Arguments:
1767  *	vdc	- soft state pointer for this instance of the device driver.
1768  *
1769  * Return Code:
1770  *	0	- Success
1771  */
1772 static int
vdc_attr_negotiation(vdc_t * vdcp)1773 vdc_attr_negotiation(vdc_t *vdcp)
1774 {
1775 	int status;
1776 	vio_msg_t vio_msg;
1777 
1778 	if (status = vdc_init_attr_negotiation(vdcp))
1779 		return (status);
1780 
1781 	/* release lock and wait for response */
1782 	mutex_exit(&vdcp->lock);
1783 	status = vdc_wait_for_response(vdcp, &vio_msg);
1784 	mutex_enter(&vdcp->lock);
1785 	if (status) {
1786 		DMSG(vdcp, 0,
1787 		    "[%d] Failed waiting for Attr negotiation response, rv(%d)",
1788 		    vdcp->instance, status);
1789 		return (status);
1790 	}
1791 
1792 	/* check type and sub_type ... */
1793 	if (vio_msg.tag.vio_msgtype != VIO_TYPE_CTRL ||
1794 	    vio_msg.tag.vio_subtype == VIO_SUBTYPE_INFO) {
1795 		DMSG(vdcp, 0, "[%d] Invalid attr negotiation response\n",
1796 		    vdcp->instance);
1797 		return (EPROTO);
1798 	}
1799 
1800 	return (vdc_handle_attr_msg(vdcp, (vd_attr_msg_t *)&vio_msg));
1801 }
1802 
1803 
1804 /*
1805  * Function:
1806  *	vdc_init_dring_negotiate()
1807  *
1808  * Description:
1809  *
1810  * Arguments:
1811  *	vdc	- soft state pointer for this instance of the device driver.
1812  *
1813  * Return Code:
1814  *	0	- Success
1815  */
1816 static int
vdc_init_dring_negotiate(vdc_t * vdc)1817 vdc_init_dring_negotiate(vdc_t *vdc)
1818 {
1819 	vio_dring_reg_msg_t	pkt;
1820 	size_t			msglen = sizeof (pkt);
1821 	int			status = -1;
1822 	int			retry;
1823 	int			nretries = 10;
1824 
1825 	ASSERT(vdc != NULL);
1826 	ASSERT(mutex_owned(&vdc->lock));
1827 
1828 	for (retry = 0; retry < nretries; retry++) {
1829 		status = vdc_init_descriptor_ring(vdc);
1830 		if (status != EAGAIN)
1831 			break;
1832 		drv_usecwait(vdc_min_timeout_ldc);
1833 	}
1834 
1835 	if (status != 0) {
1836 		DMSG(vdc, 0, "[%d] Failed to init DRing (status = %d)\n",
1837 		    vdc->instance, status);
1838 		return (status);
1839 	}
1840 
1841 	DMSG(vdc, 0, "[%d] Init of descriptor ring completed (status = %d)\n",
1842 	    vdc->instance, status);
1843 
1844 	/* fill in tag */
1845 	pkt.tag.vio_msgtype = VIO_TYPE_CTRL;
1846 	pkt.tag.vio_subtype = VIO_SUBTYPE_INFO;
1847 	pkt.tag.vio_subtype_env = VIO_DRING_REG;
1848 	pkt.tag.vio_sid = vdc->session_id;
1849 	/* fill in payload */
1850 	pkt.dring_ident = 0;
1851 	pkt.num_descriptors = vdc->dring_len;
1852 	pkt.descriptor_size = vdc->dring_entry_size;
1853 	pkt.options = (VIO_TX_DRING | VIO_RX_DRING);
1854 	pkt.ncookies = vdc->dring_cookie_count;
1855 	pkt.cookie[0] = vdc->dring_cookie[0];	/* for now just one cookie */
1856 
1857 	status = vdc_send(vdc, (caddr_t)&pkt, &msglen);
1858 	if (status != 0) {
1859 		DMSG(vdc, 0, "[%d] Failed to register DRing (err = %d)",
1860 		    vdc->instance, status);
1861 	}
1862 
1863 	return (status);
1864 }
1865 
1866 
1867 /*
1868  * Function:
1869  *	vdc_dring_negotiation()
1870  *
1871  * Description:
1872  *
1873  * Arguments:
1874  *	vdc	- soft state pointer for this instance of the device driver.
1875  *
1876  * Return Code:
1877  *	0	- Success
1878  */
1879 static int
vdc_dring_negotiation(vdc_t * vdcp)1880 vdc_dring_negotiation(vdc_t *vdcp)
1881 {
1882 	int status;
1883 	vio_msg_t vio_msg;
1884 
1885 	if (status = vdc_init_dring_negotiate(vdcp))
1886 		return (status);
1887 
1888 	/* release lock and wait for response */
1889 	mutex_exit(&vdcp->lock);
1890 	status = vdc_wait_for_response(vdcp, &vio_msg);
1891 	mutex_enter(&vdcp->lock);
1892 	if (status) {
1893 		DMSG(vdcp, 0,
1894 		    "[%d] Failed waiting for Dring negotiation response,"
1895 		    " rv(%d)", vdcp->instance, status);
1896 		return (status);
1897 	}
1898 
1899 	/* check type and sub_type ... */
1900 	if (vio_msg.tag.vio_msgtype != VIO_TYPE_CTRL ||
1901 	    vio_msg.tag.vio_subtype == VIO_SUBTYPE_INFO) {
1902 		DMSG(vdcp, 0, "[%d] Invalid Dring negotiation response\n",
1903 		    vdcp->instance);
1904 		return (EPROTO);
1905 	}
1906 
1907 	return (vdc_handle_dring_reg_msg(vdcp,
1908 	    (vio_dring_reg_msg_t *)&vio_msg));
1909 }
1910 
1911 
1912 /*
1913  * Function:
1914  *	vdc_send_rdx()
1915  *
1916  * Description:
1917  *
1918  * Arguments:
1919  *	vdc	- soft state pointer for this instance of the device driver.
1920  *
1921  * Return Code:
1922  *	0	- Success
1923  */
1924 static int
vdc_send_rdx(vdc_t * vdcp)1925 vdc_send_rdx(vdc_t *vdcp)
1926 {
1927 	vio_msg_t	msg;
1928 	size_t		msglen = sizeof (vio_msg_t);
1929 	int		status;
1930 
1931 	/*
1932 	 * Send an RDX message to vds to indicate we are ready
1933 	 * to send data
1934 	 */
1935 	msg.tag.vio_msgtype = VIO_TYPE_CTRL;
1936 	msg.tag.vio_subtype = VIO_SUBTYPE_INFO;
1937 	msg.tag.vio_subtype_env = VIO_RDX;
1938 	msg.tag.vio_sid = vdcp->session_id;
1939 	status = vdc_send(vdcp, (caddr_t)&msg, &msglen);
1940 	if (status != 0) {
1941 		DMSG(vdcp, 0, "[%d] Failed to send RDX message (%d)",
1942 		    vdcp->instance, status);
1943 	}
1944 
1945 	return (status);
1946 }
1947 
1948 /*
1949  * Function:
1950  *	vdc_handle_rdx()
1951  *
1952  * Description:
1953  *
1954  * Arguments:
1955  *	vdc	- soft state pointer for this instance of the device driver.
1956  *	msgp	- received msg
1957  *
1958  * Return Code:
1959  *	0	- Success
1960  */
1961 static int
vdc_handle_rdx(vdc_t * vdcp,vio_rdx_msg_t * msgp)1962 vdc_handle_rdx(vdc_t *vdcp, vio_rdx_msg_t *msgp)
1963 {
1964 	_NOTE(ARGUNUSED(vdcp))
1965 	_NOTE(ARGUNUSED(msgp))
1966 
1967 	ASSERT(msgp->tag.vio_msgtype == VIO_TYPE_CTRL);
1968 	ASSERT(msgp->tag.vio_subtype == VIO_SUBTYPE_ACK);
1969 	ASSERT(msgp->tag.vio_subtype_env == VIO_RDX);
1970 
1971 	DMSG(vdcp, 1, "[%d] Got an RDX msg", vdcp->instance);
1972 
1973 	return (0);
1974 }
1975 
1976 /*
1977  * Function:
1978  *	vdc_rdx_exchange()
1979  *
1980  * Description:
1981  *
1982  * Arguments:
1983  *	vdc	- soft state pointer for this instance of the device driver.
1984  *
1985  * Return Code:
1986  *	0	- Success
1987  */
1988 static int
vdc_rdx_exchange(vdc_t * vdcp)1989 vdc_rdx_exchange(vdc_t *vdcp)
1990 {
1991 	int status;
1992 	vio_msg_t vio_msg;
1993 
1994 	if (status = vdc_send_rdx(vdcp))
1995 		return (status);
1996 
1997 	/* release lock and wait for response */
1998 	mutex_exit(&vdcp->lock);
1999 	status = vdc_wait_for_response(vdcp, &vio_msg);
2000 	mutex_enter(&vdcp->lock);
2001 	if (status) {
2002 		DMSG(vdcp, 0, "[%d] Failed waiting for RDX response, rv(%d)",
2003 		    vdcp->instance, status);
2004 		return (status);
2005 	}
2006 
2007 	/* check type and sub_type ... */
2008 	if (vio_msg.tag.vio_msgtype != VIO_TYPE_CTRL ||
2009 	    vio_msg.tag.vio_subtype != VIO_SUBTYPE_ACK) {
2010 		DMSG(vdcp, 0, "[%d] Invalid RDX response\n", vdcp->instance);
2011 		return (EPROTO);
2012 	}
2013 
2014 	return (vdc_handle_rdx(vdcp, (vio_rdx_msg_t *)&vio_msg));
2015 }
2016 
2017 
2018 /* -------------------------------------------------------------------------- */
2019 
2020 /*
2021  * LDC helper routines
2022  */
2023 
2024 static int
vdc_recv(vdc_t * vdc,vio_msg_t * msgp,size_t * nbytesp)2025 vdc_recv(vdc_t *vdc, vio_msg_t *msgp, size_t *nbytesp)
2026 {
2027 	int		status;
2028 	uint64_t	delay_time;
2029 	size_t		len;
2030 
2031 	/*
2032 	 * Until we get a blocking ldc read we have to retry until the entire
2033 	 * LDC message has arrived before ldc_read() will return that message.
2034 	 * If ldc_read() succeed but returns a zero length message then that
2035 	 * means that the LDC queue is empty and we have to wait for a
2036 	 * notification from the LDC callback which will set the read_state to
2037 	 * VDC_READ_PENDING. Note we also bail out if the channel is reset or
2038 	 * goes away.
2039 	 */
2040 	delay_time = vdc_ldc_read_init_delay;
2041 
2042 	for (;;) {
2043 
2044 		len = *nbytesp;
2045 		/*
2046 		 * vdc->curr_server is protected by vdc->lock but to avoid
2047 		 * contentions we don't take the lock here. We can do this
2048 		 * safely because vdc_recv() is only called from thread
2049 		 * process_msg_thread() which is also the only thread that
2050 		 * can change vdc->curr_server.
2051 		 */
2052 		status = ldc_read(vdc->curr_server->ldc_handle,
2053 		    (caddr_t)msgp, &len);
2054 
2055 		if (status == EAGAIN) {
2056 			delay_time *= 2;
2057 			if (delay_time >= vdc_ldc_read_max_delay)
2058 				delay_time = vdc_ldc_read_max_delay;
2059 			delay(delay_time);
2060 			continue;
2061 		}
2062 
2063 		if (status != 0) {
2064 			DMSG(vdc, 0, "ldc_read returned %d\n", status);
2065 			break;
2066 		}
2067 
2068 		if (len != 0) {
2069 			*nbytesp = len;
2070 			break;
2071 		}
2072 
2073 		mutex_enter(&vdc->read_lock);
2074 
2075 		while (vdc->read_state != VDC_READ_PENDING) {
2076 
2077 			/* detect if the connection has been reset */
2078 			if (vdc->read_state == VDC_READ_RESET) {
2079 				mutex_exit(&vdc->read_lock);
2080 				return (ECONNRESET);
2081 			}
2082 
2083 			vdc->read_state = VDC_READ_WAITING;
2084 			cv_wait(&vdc->read_cv, &vdc->read_lock);
2085 		}
2086 
2087 		vdc->read_state = VDC_READ_IDLE;
2088 		mutex_exit(&vdc->read_lock);
2089 
2090 		delay_time = vdc_ldc_read_init_delay;
2091 	}
2092 
2093 	return (status);
2094 }
2095 
2096 
2097 
2098 #ifdef DEBUG
2099 void
vdc_decode_tag(vdc_t * vdcp,vio_msg_t * msg)2100 vdc_decode_tag(vdc_t *vdcp, vio_msg_t *msg)
2101 {
2102 	char *ms, *ss, *ses;
2103 	switch (msg->tag.vio_msgtype) {
2104 #define	Q(_s)	case _s : ms = #_s; break;
2105 	Q(VIO_TYPE_CTRL)
2106 	Q(VIO_TYPE_DATA)
2107 	Q(VIO_TYPE_ERR)
2108 #undef Q
2109 	default: ms = "unknown"; break;
2110 	}
2111 
2112 	switch (msg->tag.vio_subtype) {
2113 #define	Q(_s)	case _s : ss = #_s; break;
2114 	Q(VIO_SUBTYPE_INFO)
2115 	Q(VIO_SUBTYPE_ACK)
2116 	Q(VIO_SUBTYPE_NACK)
2117 #undef Q
2118 	default: ss = "unknown"; break;
2119 	}
2120 
2121 	switch (msg->tag.vio_subtype_env) {
2122 #define	Q(_s)	case _s : ses = #_s; break;
2123 	Q(VIO_VER_INFO)
2124 	Q(VIO_ATTR_INFO)
2125 	Q(VIO_DRING_REG)
2126 	Q(VIO_DRING_UNREG)
2127 	Q(VIO_RDX)
2128 	Q(VIO_PKT_DATA)
2129 	Q(VIO_DESC_DATA)
2130 	Q(VIO_DRING_DATA)
2131 #undef Q
2132 	default: ses = "unknown"; break;
2133 	}
2134 
2135 	DMSG(vdcp, 3, "(%x/%x/%x) message : (%s/%s/%s)\n",
2136 	    msg->tag.vio_msgtype, msg->tag.vio_subtype,
2137 	    msg->tag.vio_subtype_env, ms, ss, ses);
2138 }
2139 #endif
2140 
2141 /*
2142  * Function:
2143  *	vdc_send()
2144  *
2145  * Description:
2146  *	The function encapsulates the call to write a message using LDC.
2147  *	If LDC indicates that the call failed due to the queue being full,
2148  *	we retry the ldc_write(), otherwise we return the error returned by LDC.
2149  *
2150  * Arguments:
2151  *	ldc_handle	- LDC handle for the channel this instance of vdc uses
2152  *	pkt		- address of LDC message to be sent
2153  *	msglen		- the size of the message being sent. When the function
2154  *			  returns, this contains the number of bytes written.
2155  *
2156  * Return Code:
2157  *	0		- Success.
2158  *	EINVAL		- pkt or msglen were NULL
2159  *	ECONNRESET	- The connection was not up.
2160  *	EWOULDBLOCK	- LDC queue is full
2161  *	xxx		- other error codes returned by ldc_write
2162  */
2163 static int
vdc_send(vdc_t * vdc,caddr_t pkt,size_t * msglen)2164 vdc_send(vdc_t *vdc, caddr_t pkt, size_t *msglen)
2165 {
2166 	size_t	size = 0;
2167 	int	status = 0;
2168 	clock_t delay_ticks;
2169 
2170 	ASSERT(vdc != NULL);
2171 	ASSERT(mutex_owned(&vdc->lock));
2172 	ASSERT(msglen != NULL);
2173 	ASSERT(*msglen != 0);
2174 
2175 #ifdef DEBUG
2176 	vdc_decode_tag(vdc, (vio_msg_t *)(uintptr_t)pkt);
2177 #endif
2178 	/*
2179 	 * Wait indefinitely to send if channel
2180 	 * is busy, but bail out if we succeed or
2181 	 * if the channel closes or is reset.
2182 	 */
2183 	delay_ticks = vdc_hz_min_ldc_delay;
2184 	do {
2185 		size = *msglen;
2186 		status = ldc_write(vdc->curr_server->ldc_handle, pkt, &size);
2187 		if (status == EWOULDBLOCK) {
2188 			delay(delay_ticks);
2189 			/* geometric backoff */
2190 			delay_ticks *= 2;
2191 			if (delay_ticks > vdc_hz_max_ldc_delay)
2192 				delay_ticks = vdc_hz_max_ldc_delay;
2193 		}
2194 	} while (status == EWOULDBLOCK);
2195 
2196 	/* if LDC had serious issues --- reset vdc state */
2197 	if (status == EIO || status == ECONNRESET) {
2198 		/* LDC had serious issues --- reset vdc state */
2199 		mutex_enter(&vdc->read_lock);
2200 		if ((vdc->read_state == VDC_READ_WAITING) ||
2201 		    (vdc->read_state == VDC_READ_RESET))
2202 			cv_signal(&vdc->read_cv);
2203 		vdc->read_state = VDC_READ_RESET;
2204 		mutex_exit(&vdc->read_lock);
2205 
2206 		/* wake up any waiters in the reset thread */
2207 		if (vdc->state == VDC_STATE_INIT_WAITING) {
2208 			DMSG(vdc, 0, "[%d] write reset - "
2209 			    "vdc is resetting ..\n", vdc->instance);
2210 			vdc->state = VDC_STATE_RESETTING;
2211 			cv_signal(&vdc->initwait_cv);
2212 		}
2213 
2214 		return (ECONNRESET);
2215 	}
2216 
2217 	/* return the last size written */
2218 	*msglen = size;
2219 
2220 	return (status);
2221 }
2222 
2223 /*
2224  * Function:
2225  *	vdc_get_md_node
2226  *
2227  * Description:
2228  *	Get the MD, the device node for the given disk instance. The
2229  *	caller is responsible for cleaning up the reference to the
2230  *	returned MD (mdpp) by calling md_fini_handle().
2231  *
2232  * Arguments:
2233  *	dip	- dev info pointer for this instance of the device driver.
2234  *	mdpp	- the returned MD.
2235  *	vd_nodep - the returned device node.
2236  *
2237  * Return Code:
2238  *	0	- Success.
2239  *	ENOENT	- Expected node or property did not exist.
2240  *	ENXIO	- Unexpected error communicating with MD framework
2241  */
2242 static int
vdc_get_md_node(dev_info_t * dip,md_t ** mdpp,mde_cookie_t * vd_nodep)2243 vdc_get_md_node(dev_info_t *dip, md_t **mdpp, mde_cookie_t *vd_nodep)
2244 {
2245 	int		status = ENOENT;
2246 	char		*node_name = NULL;
2247 	md_t		*mdp = NULL;
2248 	int		num_nodes;
2249 	int		num_vdevs;
2250 	mde_cookie_t	rootnode;
2251 	mde_cookie_t	*listp = NULL;
2252 	boolean_t	found_inst = B_FALSE;
2253 	int		listsz;
2254 	int		idx;
2255 	uint64_t	md_inst;
2256 	int		obp_inst;
2257 	int		instance = ddi_get_instance(dip);
2258 
2259 	/*
2260 	 * Get the OBP instance number for comparison with the MD instance
2261 	 *
2262 	 * The "cfg-handle" property of a vdc node in an MD contains the MD's
2263 	 * notion of "instance", or unique identifier, for that node; OBP
2264 	 * stores the value of the "cfg-handle" MD property as the value of
2265 	 * the "reg" property on the node in the device tree it builds from
2266 	 * the MD and passes to Solaris.  Thus, we look up the devinfo node's
2267 	 * "reg" property value to uniquely identify this device instance.
2268 	 * If the "reg" property cannot be found, the device tree state is
2269 	 * presumably so broken that there is no point in continuing.
2270 	 */
2271 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, OBP_REG)) {
2272 		cmn_err(CE_WARN, "'%s' property does not exist", OBP_REG);
2273 		return (ENOENT);
2274 	}
2275 	obp_inst = ddi_prop_get_int(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
2276 	    OBP_REG, -1);
2277 	DMSGX(1, "[%d] OBP inst=%d\n", instance, obp_inst);
2278 
2279 	/*
2280 	 * We now walk the MD nodes to find the node for this vdisk.
2281 	 */
2282 	if ((mdp = md_get_handle()) == NULL) {
2283 		cmn_err(CE_WARN, "unable to init machine description");
2284 		return (ENXIO);
2285 	}
2286 
2287 	num_nodes = md_node_count(mdp);
2288 	ASSERT(num_nodes > 0);
2289 
2290 	listsz = num_nodes * sizeof (mde_cookie_t);
2291 
2292 	/* allocate memory for nodes */
2293 	listp = kmem_zalloc(listsz, KM_SLEEP);
2294 
2295 	rootnode = md_root_node(mdp);
2296 	ASSERT(rootnode != MDE_INVAL_ELEM_COOKIE);
2297 
2298 	/*
2299 	 * Search for all the virtual devices, we will then check to see which
2300 	 * ones are disk nodes.
2301 	 */
2302 	num_vdevs = md_scan_dag(mdp, rootnode,
2303 	    md_find_name(mdp, VDC_MD_VDEV_NAME),
2304 	    md_find_name(mdp, "fwd"), listp);
2305 
2306 	if (num_vdevs <= 0) {
2307 		cmn_err(CE_NOTE, "No '%s' node found", VDC_MD_VDEV_NAME);
2308 		status = ENOENT;
2309 		goto done;
2310 	}
2311 
2312 	DMSGX(1, "[%d] num_vdevs=%d\n", instance, num_vdevs);
2313 	for (idx = 0; idx < num_vdevs; idx++) {
2314 		status = md_get_prop_str(mdp, listp[idx], "name", &node_name);
2315 		if ((status != 0) || (node_name == NULL)) {
2316 			cmn_err(CE_NOTE, "Unable to get name of node type '%s'"
2317 			    ": err %d", VDC_MD_VDEV_NAME, status);
2318 			continue;
2319 		}
2320 
2321 		DMSGX(1, "[%d] Found node '%s'\n", instance, node_name);
2322 		if (strcmp(VDC_MD_DISK_NAME, node_name) == 0) {
2323 			status = md_get_prop_val(mdp, listp[idx],
2324 			    VDC_MD_CFG_HDL, &md_inst);
2325 			DMSGX(1, "[%d] vdc inst in MD=%lx\n",
2326 			    instance, md_inst);
2327 			if ((status == 0) && (md_inst == obp_inst)) {
2328 				found_inst = B_TRUE;
2329 				break;
2330 			}
2331 		}
2332 	}
2333 
2334 	if (!found_inst) {
2335 		DMSGX(0, "Unable to find correct '%s' node", VDC_MD_DISK_NAME);
2336 		status = ENOENT;
2337 		goto done;
2338 	}
2339 	DMSGX(0, "[%d] MD inst=%lx\n", instance, md_inst);
2340 
2341 	*vd_nodep = listp[idx];
2342 	*mdpp = mdp;
2343 done:
2344 	kmem_free(listp, listsz);
2345 	return (status);
2346 }
2347 
2348 /*
2349  * Function:
2350  *	vdc_init_ports
2351  *
2352  * Description:
2353  *	Initialize all the ports for this vdisk instance.
2354  *
2355  * Arguments:
2356  *	vdc	- soft state pointer for this instance of the device driver.
2357  *	mdp	- md pointer
2358  *	vd_nodep - device md node.
2359  *
2360  * Return Code:
2361  *	0	- Success.
2362  *	ENOENT	- Expected node or property did not exist.
2363  */
2364 static int
vdc_init_ports(vdc_t * vdc,md_t * mdp,mde_cookie_t vd_nodep)2365 vdc_init_ports(vdc_t *vdc, md_t *mdp, mde_cookie_t vd_nodep)
2366 {
2367 	int		status = 0;
2368 	int		idx;
2369 	int		num_nodes;
2370 	int		num_vports;
2371 	int		num_chans;
2372 	int		listsz;
2373 	mde_cookie_t	vd_port;
2374 	mde_cookie_t	*chanp = NULL;
2375 	mde_cookie_t	*portp = NULL;
2376 	vdc_server_t	*srvr;
2377 	vdc_server_t	*prev_srvr = NULL;
2378 
2379 	/*
2380 	 * We now walk the MD nodes to find the port nodes for this vdisk.
2381 	 */
2382 	num_nodes = md_node_count(mdp);
2383 	ASSERT(num_nodes > 0);
2384 
2385 	listsz = num_nodes * sizeof (mde_cookie_t);
2386 
2387 	/* allocate memory for nodes */
2388 	portp = kmem_zalloc(listsz, KM_SLEEP);
2389 	chanp = kmem_zalloc(listsz, KM_SLEEP);
2390 
2391 	num_vports = md_scan_dag(mdp, vd_nodep,
2392 	    md_find_name(mdp, VDC_MD_PORT_NAME),
2393 	    md_find_name(mdp, "fwd"), portp);
2394 	if (num_vports == 0) {
2395 		DMSGX(0, "Found no '%s' node for '%s' port\n",
2396 		    VDC_MD_PORT_NAME, VDC_MD_VDEV_NAME);
2397 		status = ENOENT;
2398 		goto done;
2399 	}
2400 
2401 	DMSGX(1, "Found %d '%s' node(s) for '%s' port\n",
2402 	    num_vports, VDC_MD_PORT_NAME, VDC_MD_VDEV_NAME);
2403 
2404 	vdc->num_servers = 0;
2405 	for (idx = 0; idx < num_vports; idx++) {
2406 
2407 		/* initialize this port */
2408 		vd_port = portp[idx];
2409 		srvr = kmem_zalloc(sizeof (vdc_server_t), KM_SLEEP);
2410 		srvr->vdcp = vdc;
2411 		srvr->svc_state = VDC_SERVICE_OFFLINE;
2412 		srvr->log_state = VDC_SERVICE_NONE;
2413 
2414 		/* get port id */
2415 		if (md_get_prop_val(mdp, vd_port, VDC_MD_ID, &srvr->id) != 0) {
2416 			cmn_err(CE_NOTE, "vDisk port '%s' property not found",
2417 			    VDC_MD_ID);
2418 			kmem_free(srvr, sizeof (vdc_server_t));
2419 			continue;
2420 		}
2421 
2422 		/* set the connection timeout */
2423 		if (md_get_prop_val(mdp, vd_port, VDC_MD_TIMEOUT,
2424 		    &srvr->ctimeout) != 0) {
2425 			srvr->ctimeout = 0;
2426 		}
2427 
2428 		/* get the ldc id */
2429 		num_chans = md_scan_dag(mdp, vd_port,
2430 		    md_find_name(mdp, VDC_MD_CHAN_NAME),
2431 		    md_find_name(mdp, "fwd"), chanp);
2432 
2433 		/* expecting at least one channel */
2434 		if (num_chans <= 0) {
2435 			cmn_err(CE_NOTE, "No '%s' node for '%s' port",
2436 			    VDC_MD_CHAN_NAME, VDC_MD_VDEV_NAME);
2437 			kmem_free(srvr, sizeof (vdc_server_t));
2438 			continue;
2439 		} else if (num_chans != 1) {
2440 			DMSGX(0, "Expected 1 '%s' node for '%s' port, "
2441 			    "found %d\n", VDC_MD_CHAN_NAME, VDC_MD_VDEV_NAME,
2442 			    num_chans);
2443 		}
2444 
2445 		/*
2446 		 * We use the first channel found (index 0), irrespective of how
2447 		 * many are there in total.
2448 		 */
2449 		if (md_get_prop_val(mdp, chanp[0], VDC_MD_ID,
2450 		    &srvr->ldc_id) != 0) {
2451 			cmn_err(CE_NOTE, "Channel '%s' property not found",
2452 			    VDC_MD_ID);
2453 			kmem_free(srvr, sizeof (vdc_server_t));
2454 			continue;
2455 		}
2456 
2457 		/*
2458 		 * now initialise LDC channel which will be used to
2459 		 * communicate with this server
2460 		 */
2461 		if (vdc_do_ldc_init(vdc, srvr) != 0) {
2462 			kmem_free(srvr, sizeof (vdc_server_t));
2463 			continue;
2464 		}
2465 
2466 		/* add server to list */
2467 		if (prev_srvr)
2468 			prev_srvr->next = srvr;
2469 		else
2470 			vdc->server_list = srvr;
2471 
2472 		prev_srvr = srvr;
2473 
2474 		/* inc numbers of servers */
2475 		vdc->num_servers++;
2476 	}
2477 
2478 	/* pick first server as current server */
2479 	if (vdc->server_list != NULL) {
2480 		vdc->curr_server = vdc->server_list;
2481 		status = 0;
2482 	} else {
2483 		status = ENOENT;
2484 	}
2485 
2486 done:
2487 	kmem_free(chanp, listsz);
2488 	kmem_free(portp, listsz);
2489 	return (status);
2490 }
2491 
2492 
2493 /*
2494  * Function:
2495  *	vdc_do_ldc_up
2496  *
2497  * Description:
2498  *	Bring the channel for the current server up.
2499  *
2500  * Arguments:
2501  *	vdc	- soft state pointer for this instance of the device driver.
2502  *
2503  * Return Code:
2504  *	0		- Success.
2505  *	EINVAL		- Driver is detaching / LDC error
2506  *	ECONNREFUSED	- Other end is not listening
2507  */
2508 static int
vdc_do_ldc_up(vdc_t * vdc)2509 vdc_do_ldc_up(vdc_t *vdc)
2510 {
2511 	int		status;
2512 	ldc_status_t	ldc_state;
2513 
2514 	ASSERT(MUTEX_HELD(&vdc->lock));
2515 
2516 	DMSG(vdc, 0, "[%d] Bringing up channel %lx\n",
2517 	    vdc->instance, vdc->curr_server->ldc_id);
2518 
2519 	if (vdc->lifecycle == VDC_LC_DETACHING)
2520 		return (EINVAL);
2521 
2522 	if ((status = ldc_up(vdc->curr_server->ldc_handle)) != 0) {
2523 		switch (status) {
2524 		case ECONNREFUSED:	/* listener not ready at other end */
2525 			DMSG(vdc, 0, "[%d] ldc_up(%lx,...) return %d\n",
2526 			    vdc->instance, vdc->curr_server->ldc_id, status);
2527 			status = 0;
2528 			break;
2529 		default:
2530 			DMSG(vdc, 0, "[%d] Failed to bring up LDC: "
2531 			    "channel=%ld, err=%d", vdc->instance,
2532 			    vdc->curr_server->ldc_id, status);
2533 			break;
2534 		}
2535 	}
2536 
2537 	if (ldc_status(vdc->curr_server->ldc_handle, &ldc_state) == 0) {
2538 		vdc->curr_server->ldc_state = ldc_state;
2539 		if (ldc_state == LDC_UP) {
2540 			DMSG(vdc, 0, "[%d] LDC channel already up\n",
2541 			    vdc->instance);
2542 			vdc->seq_num = 1;
2543 			vdc->seq_num_reply = 0;
2544 		}
2545 	}
2546 
2547 	return (status);
2548 }
2549 
2550 /*
2551  * Function:
2552  *	vdc_terminate_ldc()
2553  *
2554  * Description:
2555  *
2556  * Arguments:
2557  *	vdc	- soft state pointer for this instance of the device driver.
2558  *	srvr	- vdc per-server info structure
2559  *
2560  * Return Code:
2561  *	None
2562  */
2563 static void
vdc_terminate_ldc(vdc_t * vdc,vdc_server_t * srvr)2564 vdc_terminate_ldc(vdc_t *vdc, vdc_server_t *srvr)
2565 {
2566 	int	instance = ddi_get_instance(vdc->dip);
2567 
2568 	if (srvr->state & VDC_LDC_OPEN) {
2569 		DMSG(vdc, 0, "[%d] ldc_close()\n", instance);
2570 		(void) ldc_close(srvr->ldc_handle);
2571 	}
2572 	if (srvr->state & VDC_LDC_CB) {
2573 		DMSG(vdc, 0, "[%d] ldc_unreg_callback()\n", instance);
2574 		(void) ldc_unreg_callback(srvr->ldc_handle);
2575 	}
2576 	if (srvr->state & VDC_LDC_INIT) {
2577 		DMSG(vdc, 0, "[%d] ldc_fini()\n", instance);
2578 		(void) ldc_fini(srvr->ldc_handle);
2579 		srvr->ldc_handle = 0;
2580 	}
2581 
2582 	srvr->state &= ~(VDC_LDC_INIT | VDC_LDC_CB | VDC_LDC_OPEN);
2583 }
2584 
2585 /*
2586  * Function:
2587  *	vdc_fini_ports()
2588  *
2589  * Description:
2590  *	Finalize all ports by closing the channel associated with each
2591  *	port and also freeing the server structure.
2592  *
2593  * Arguments:
2594  *	vdc	- soft state pointer for this instance of the device driver.
2595  *
2596  * Return Code:
2597  *	None
2598  */
2599 static void
vdc_fini_ports(vdc_t * vdc)2600 vdc_fini_ports(vdc_t *vdc)
2601 {
2602 	int		instance = ddi_get_instance(vdc->dip);
2603 	vdc_server_t	*srvr, *prev_srvr;
2604 
2605 	ASSERT(vdc != NULL);
2606 	ASSERT(mutex_owned(&vdc->lock));
2607 
2608 	DMSG(vdc, 0, "[%d] initialized=%x\n", instance, vdc->initialized);
2609 
2610 	srvr = vdc->server_list;
2611 
2612 	while (srvr) {
2613 
2614 		vdc_terminate_ldc(vdc, srvr);
2615 
2616 		/* next server */
2617 		prev_srvr = srvr;
2618 		srvr = srvr->next;
2619 
2620 		/* free server */
2621 		kmem_free(prev_srvr, sizeof (vdc_server_t));
2622 	}
2623 
2624 	vdc->server_list = NULL;
2625 	vdc->num_servers = 0;
2626 }
2627 
2628 /* -------------------------------------------------------------------------- */
2629 
2630 /*
2631  * Descriptor Ring helper routines
2632  */
2633 
2634 /*
2635  * Function:
2636  *	vdc_init_descriptor_ring()
2637  *
2638  * Description:
2639  *
2640  * Arguments:
2641  *	vdc	- soft state pointer for this instance of the device driver.
2642  *
2643  * Return Code:
2644  *	0	- Success
2645  */
2646 static int
vdc_init_descriptor_ring(vdc_t * vdc)2647 vdc_init_descriptor_ring(vdc_t *vdc)
2648 {
2649 	vd_dring_entry_t	*dep = NULL;	/* DRing Entry pointer */
2650 	int	status = 0;
2651 	int	i;
2652 
2653 	DMSG(vdc, 0, "[%d] initialized=%x\n", vdc->instance, vdc->initialized);
2654 
2655 	ASSERT(vdc != NULL);
2656 	ASSERT(mutex_owned(&vdc->lock));
2657 
2658 	/* ensure we have enough room to store max sized block */
2659 	ASSERT(maxphys <= VD_MAX_BLOCK_SIZE);
2660 
2661 	if ((vdc->initialized & VDC_DRING_INIT) == 0) {
2662 		DMSG(vdc, 0, "[%d] ldc_mem_dring_create\n", vdc->instance);
2663 		/*
2664 		 * Calculate the maximum block size we can transmit using one
2665 		 * Descriptor Ring entry from the attributes returned by the
2666 		 * vDisk server. This is subject to a minimum of 'maxphys'
2667 		 * as we do not have the capability to split requests over
2668 		 * multiple DRing entries.
2669 		 */
2670 		if ((vdc->max_xfer_sz * vdc->vdisk_bsize) < maxphys) {
2671 			DMSG(vdc, 0, "[%d] using minimum DRing size\n",
2672 			    vdc->instance);
2673 			vdc->dring_max_cookies = maxphys / PAGESIZE;
2674 		} else {
2675 			vdc->dring_max_cookies =
2676 			    (vdc->max_xfer_sz * vdc->vdisk_bsize) / PAGESIZE;
2677 		}
2678 		vdc->dring_entry_size = (sizeof (vd_dring_entry_t) +
2679 		    (sizeof (ldc_mem_cookie_t) *
2680 		    (vdc->dring_max_cookies - 1)));
2681 		vdc->dring_len = VD_DRING_LEN;
2682 
2683 		status = ldc_mem_dring_create(vdc->dring_len,
2684 		    vdc->dring_entry_size, &vdc->dring_hdl);
2685 		if ((vdc->dring_hdl == 0) || (status != 0)) {
2686 			DMSG(vdc, 0, "[%d] Descriptor ring creation failed",
2687 			    vdc->instance);
2688 			return (status);
2689 		}
2690 		vdc->initialized |= VDC_DRING_INIT;
2691 	}
2692 
2693 	if ((vdc->initialized & VDC_DRING_BOUND) == 0) {
2694 		DMSG(vdc, 0, "[%d] ldc_mem_dring_bind\n", vdc->instance);
2695 		vdc->dring_cookie =
2696 		    kmem_zalloc(sizeof (ldc_mem_cookie_t), KM_SLEEP);
2697 
2698 		status = ldc_mem_dring_bind(vdc->curr_server->ldc_handle,
2699 		    vdc->dring_hdl,
2700 		    LDC_SHADOW_MAP|LDC_DIRECT_MAP, LDC_MEM_RW,
2701 		    &vdc->dring_cookie[0],
2702 		    &vdc->dring_cookie_count);
2703 		if (status != 0) {
2704 			DMSG(vdc, 0, "[%d] Failed to bind descriptor ring "
2705 			    "(%lx) to channel (%lx) status=%d\n",
2706 			    vdc->instance, vdc->dring_hdl,
2707 			    vdc->curr_server->ldc_handle, status);
2708 			return (status);
2709 		}
2710 		ASSERT(vdc->dring_cookie_count == 1);
2711 		vdc->initialized |= VDC_DRING_BOUND;
2712 	}
2713 
2714 	status = ldc_mem_dring_info(vdc->dring_hdl, &vdc->dring_mem_info);
2715 	if (status != 0) {
2716 		DMSG(vdc, 0,
2717 		    "[%d] Failed to get info for descriptor ring (%lx)\n",
2718 		    vdc->instance, vdc->dring_hdl);
2719 		return (status);
2720 	}
2721 
2722 	if ((vdc->initialized & VDC_DRING_LOCAL) == 0) {
2723 		DMSG(vdc, 0, "[%d] local dring\n", vdc->instance);
2724 
2725 		/* Allocate the local copy of this dring */
2726 		vdc->local_dring =
2727 		    kmem_zalloc(vdc->dring_len * sizeof (vdc_local_desc_t),
2728 		    KM_SLEEP);
2729 		vdc->initialized |= VDC_DRING_LOCAL;
2730 	}
2731 
2732 	/*
2733 	 * Mark all DRing entries as free and initialize the private
2734 	 * descriptor's memory handles. If any entry is initialized,
2735 	 * we need to free it later so we set the bit in 'initialized'
2736 	 * at the start.
2737 	 */
2738 	vdc->initialized |= VDC_DRING_ENTRY;
2739 	for (i = 0; i < vdc->dring_len; i++) {
2740 		dep = VDC_GET_DRING_ENTRY_PTR(vdc, i);
2741 		dep->hdr.dstate = VIO_DESC_FREE;
2742 
2743 		status = ldc_mem_alloc_handle(vdc->curr_server->ldc_handle,
2744 		    &vdc->local_dring[i].desc_mhdl);
2745 		if (status != 0) {
2746 			DMSG(vdc, 0, "![%d] Failed to alloc mem handle for"
2747 			    " descriptor %d", vdc->instance, i);
2748 			return (status);
2749 		}
2750 		vdc->local_dring[i].is_free = B_TRUE;
2751 		vdc->local_dring[i].dep = dep;
2752 	}
2753 
2754 	/* Initialize the starting index */
2755 	vdc->dring_curr_idx = VDC_DRING_FIRST_ENTRY;
2756 
2757 	return (status);
2758 }
2759 
2760 /*
2761  * Function:
2762  *	vdc_destroy_descriptor_ring()
2763  *
2764  * Description:
2765  *
2766  * Arguments:
2767  *	vdc	- soft state pointer for this instance of the device driver.
2768  *
2769  * Return Code:
2770  *	None
2771  */
2772 static void
vdc_destroy_descriptor_ring(vdc_t * vdc)2773 vdc_destroy_descriptor_ring(vdc_t *vdc)
2774 {
2775 	vdc_local_desc_t	*ldep = NULL;	/* Local Dring Entry Pointer */
2776 	ldc_mem_handle_t	mhdl = 0;
2777 	ldc_mem_info_t		minfo;
2778 	int			status = -1;
2779 	int			i;	/* loop */
2780 
2781 	ASSERT(vdc != NULL);
2782 	ASSERT(mutex_owned(&vdc->lock));
2783 
2784 	DMSG(vdc, 0, "[%d] Entered\n", vdc->instance);
2785 
2786 	if (vdc->initialized & VDC_DRING_ENTRY) {
2787 		DMSG(vdc, 0,
2788 		    "[%d] Removing Local DRing entries\n", vdc->instance);
2789 		for (i = 0; i < vdc->dring_len; i++) {
2790 			ldep = &vdc->local_dring[i];
2791 			mhdl = ldep->desc_mhdl;
2792 
2793 			if (mhdl == 0)
2794 				continue;
2795 
2796 			if ((status = ldc_mem_info(mhdl, &minfo)) != 0) {
2797 				DMSG(vdc, 0,
2798 				    "ldc_mem_info returned an error: %d\n",
2799 				    status);
2800 
2801 				/*
2802 				 * This must mean that the mem handle
2803 				 * is not valid. Clear it out so that
2804 				 * no one tries to use it.
2805 				 */
2806 				ldep->desc_mhdl = 0;
2807 				continue;
2808 			}
2809 
2810 			if (minfo.status == LDC_BOUND) {
2811 				(void) ldc_mem_unbind_handle(mhdl);
2812 			}
2813 
2814 			(void) ldc_mem_free_handle(mhdl);
2815 
2816 			ldep->desc_mhdl = 0;
2817 		}
2818 		vdc->initialized &= ~VDC_DRING_ENTRY;
2819 	}
2820 
2821 	if (vdc->initialized & VDC_DRING_LOCAL) {
2822 		DMSG(vdc, 0, "[%d] Freeing Local DRing\n", vdc->instance);
2823 		kmem_free(vdc->local_dring,
2824 		    vdc->dring_len * sizeof (vdc_local_desc_t));
2825 		vdc->initialized &= ~VDC_DRING_LOCAL;
2826 	}
2827 
2828 	if (vdc->initialized & VDC_DRING_BOUND) {
2829 		DMSG(vdc, 0, "[%d] Unbinding DRing\n", vdc->instance);
2830 		status = ldc_mem_dring_unbind(vdc->dring_hdl);
2831 		if (status == 0) {
2832 			vdc->initialized &= ~VDC_DRING_BOUND;
2833 		} else {
2834 			DMSG(vdc, 0, "[%d] Error %d unbinding DRing %lx",
2835 			    vdc->instance, status, vdc->dring_hdl);
2836 		}
2837 		kmem_free(vdc->dring_cookie, sizeof (ldc_mem_cookie_t));
2838 	}
2839 
2840 	if (vdc->initialized & VDC_DRING_INIT) {
2841 		DMSG(vdc, 0, "[%d] Destroying DRing\n", vdc->instance);
2842 		status = ldc_mem_dring_destroy(vdc->dring_hdl);
2843 		if (status == 0) {
2844 			vdc->dring_hdl = 0;
2845 			bzero(&vdc->dring_mem_info, sizeof (ldc_mem_info_t));
2846 			vdc->initialized &= ~VDC_DRING_INIT;
2847 		} else {
2848 			DMSG(vdc, 0, "[%d] Error %d destroying DRing (%lx)",
2849 			    vdc->instance, status, vdc->dring_hdl);
2850 		}
2851 	}
2852 }
2853 
2854 /*
2855  * Function:
2856  *	vdc_map_to_shared_dring()
2857  *
2858  * Description:
2859  *	Copy contents of the local descriptor to the shared
2860  *	memory descriptor.
2861  *
2862  * Arguments:
2863  *	vdcp	- soft state pointer for this instance of the device driver.
2864  *	idx	- descriptor ring index
2865  *
2866  * Return Code:
2867  *	None
2868  */
2869 static int
vdc_map_to_shared_dring(vdc_t * vdcp,int idx)2870 vdc_map_to_shared_dring(vdc_t *vdcp, int idx)
2871 {
2872 	vdc_local_desc_t	*ldep;
2873 	vd_dring_entry_t	*dep;
2874 	int			rv;
2875 
2876 	ldep = &(vdcp->local_dring[idx]);
2877 
2878 	/* for now leave in the old pop_mem_hdl stuff */
2879 	if (ldep->nbytes > 0) {
2880 		rv = vdc_populate_mem_hdl(vdcp, ldep);
2881 		if (rv) {
2882 			DMSG(vdcp, 0, "[%d] Cannot populate mem handle\n",
2883 			    vdcp->instance);
2884 			return (rv);
2885 		}
2886 	}
2887 
2888 	/*
2889 	 * fill in the data details into the DRing
2890 	 */
2891 	dep = ldep->dep;
2892 	ASSERT(dep != NULL);
2893 
2894 	dep->payload.req_id = VDC_GET_NEXT_REQ_ID(vdcp);
2895 	dep->payload.operation = ldep->operation;
2896 	dep->payload.addr = ldep->offset;
2897 	dep->payload.nbytes = ldep->nbytes;
2898 	dep->payload.status = (uint32_t)-1;	/* vds will set valid value */
2899 	dep->payload.slice = ldep->slice;
2900 	dep->hdr.dstate = VIO_DESC_READY;
2901 	dep->hdr.ack = 1;		/* request an ACK for every message */
2902 
2903 	return (0);
2904 }
2905 
2906 /*
2907  * Function:
2908  *	vdc_send_request
2909  *
2910  * Description:
2911  *	This routine writes the data to be transmitted to vds into the
2912  *	descriptor, notifies vds that the ring has been updated and
2913  *	then waits for the request to be processed.
2914  *
2915  * Arguments:
2916  *	vdcp	  - the soft state pointer
2917  *	operation - operation we want vds to perform (VD_OP_XXX)
2918  *	addr	  - address of data buf to be read/written.
2919  *	nbytes	  - number of bytes to read/write
2920  *	slice	  - the disk slice this request is for
2921  *	offset	  - relative disk offset
2922  *	bufp	  - buf of operation
2923  *	dir	  - direction of operation (READ/WRITE/BOTH)
2924  *
2925  * Return Codes:
2926  *	0
2927  *	ENXIO
2928  */
2929 static int
vdc_send_request(vdc_t * vdcp,int operation,caddr_t addr,size_t nbytes,int slice,diskaddr_t offset,buf_t * bufp,vio_desc_direction_t dir,int flags)2930 vdc_send_request(vdc_t *vdcp, int operation, caddr_t addr,
2931     size_t nbytes, int slice, diskaddr_t offset, buf_t *bufp,
2932     vio_desc_direction_t dir, int flags)
2933 {
2934 	int	rv = 0;
2935 
2936 	ASSERT(vdcp != NULL);
2937 	ASSERT(slice == VD_SLICE_NONE || slice < V_NUMPAR);
2938 
2939 	mutex_enter(&vdcp->lock);
2940 
2941 	/*
2942 	 * If this is a block read/write operation we update the I/O statistics
2943 	 * to indicate that the request is being put on the waitq to be
2944 	 * serviced. Operations which are resubmitted are already in the waitq.
2945 	 *
2946 	 * We do it here (a common routine for both synchronous and strategy
2947 	 * calls) for performance reasons - we are already holding vdc->lock
2948 	 * so there is no extra locking overhead. We would have to explicitly
2949 	 * grab the 'lock' mutex to update the stats if we were to do this
2950 	 * higher up the stack in vdc_strategy() et. al.
2951 	 */
2952 	if (((operation == VD_OP_BREAD) || (operation == VD_OP_BWRITE)) &&
2953 	    !(flags & VDC_OP_RESUBMIT)) {
2954 		DTRACE_IO1(start, buf_t *, bufp);
2955 		VD_KSTAT_WAITQ_ENTER(vdcp);
2956 	}
2957 
2958 	/*
2959 	 * If the request does not expect the state to be VDC_STATE_RUNNING
2960 	 * then we just try to populate the descriptor ring once.
2961 	 */
2962 	if (!(flags & VDC_OP_STATE_RUNNING)) {
2963 		rv = vdc_populate_descriptor(vdcp, operation, addr,
2964 		    nbytes, slice, offset, bufp, dir, flags);
2965 		goto done;
2966 	}
2967 
2968 	do {
2969 		while (vdcp->state != VDC_STATE_RUNNING) {
2970 
2971 			/* return error if detaching */
2972 			if (vdcp->state == VDC_STATE_DETACH) {
2973 				rv = ENXIO;
2974 				goto done;
2975 			}
2976 
2977 			/*
2978 			 * If we are panicking and the disk is not ready then
2979 			 * we can't send any request because we can't complete
2980 			 * the handshake now.
2981 			 */
2982 			if (ddi_in_panic()) {
2983 				rv = EIO;
2984 				goto done;
2985 			}
2986 
2987 			/*
2988 			 * If the state is faulted, notify that a new I/O is
2989 			 * being submitted to force the system to check if any
2990 			 * server has recovered.
2991 			 */
2992 			if (vdcp->state == VDC_STATE_FAILED) {
2993 				vdcp->io_pending = B_TRUE;
2994 				cv_signal(&vdcp->io_pending_cv);
2995 			}
2996 
2997 			cv_wait(&vdcp->running_cv, &vdcp->lock);
2998 
2999 			/* if service is still faulted then fail the request */
3000 			if (vdcp->state == VDC_STATE_FAILED) {
3001 				rv = EIO;
3002 				goto done;
3003 			}
3004 		}
3005 
3006 	} while (vdc_populate_descriptor(vdcp, operation, addr,
3007 	    nbytes, slice, offset, bufp, dir, flags & ~VDC_OP_RESUBMIT));
3008 
3009 done:
3010 	/*
3011 	 * If this is a block read/write we update the I/O statistics kstat
3012 	 * to indicate that this request has been placed on the queue for
3013 	 * processing (i.e sent to the vDisk server) - iostat(1M) will
3014 	 * report the time waiting for the vDisk server under the %b column
3015 	 *
3016 	 * In the case of an error we take it off the wait queue only if
3017 	 * the I/O was not resubmited.
3018 	 */
3019 	if ((operation == VD_OP_BREAD) || (operation == VD_OP_BWRITE)) {
3020 		if (rv == 0) {
3021 			VD_KSTAT_WAITQ_TO_RUNQ(vdcp);
3022 			DTRACE_PROBE1(send, buf_t *, bufp);
3023 		} else {
3024 			VD_UPDATE_ERR_STATS(vdcp, vd_transerrs);
3025 			if (!(flags & VDC_OP_RESUBMIT)) {
3026 				VD_KSTAT_WAITQ_EXIT(vdcp);
3027 				DTRACE_IO1(done, buf_t *, bufp);
3028 			}
3029 		}
3030 	}
3031 
3032 	mutex_exit(&vdcp->lock);
3033 
3034 	return (rv);
3035 }
3036 
3037 
3038 /*
3039  * Function:
3040  *	vdc_populate_descriptor
3041  *
3042  * Description:
3043  *	This routine writes the data to be transmitted to vds into the
3044  *	descriptor, notifies vds that the ring has been updated and
3045  *	then waits for the request to be processed.
3046  *
3047  * Arguments:
3048  *	vdcp	  - the soft state pointer
3049  *	operation - operation we want vds to perform (VD_OP_XXX)
3050  *	addr	  - address of data buf to be read/written.
3051  *	nbytes	  - number of bytes to read/write
3052  *	slice	  - the disk slice this request is for
3053  *	offset	  - relative disk offset
3054  *	bufp	  - buf of operation
3055  *	dir	  - direction of operation (READ/WRITE/BOTH)
3056  *
3057  * Return Codes:
3058  *	0
3059  *	EAGAIN
3060  *	ECONNRESET
3061  *	ENXIO
3062  */
3063 static int
vdc_populate_descriptor(vdc_t * vdcp,int operation,caddr_t addr,size_t nbytes,int slice,diskaddr_t offset,buf_t * bufp,vio_desc_direction_t dir,int flags)3064 vdc_populate_descriptor(vdc_t *vdcp, int operation, caddr_t addr,
3065     size_t nbytes, int slice, diskaddr_t offset,
3066     buf_t *bufp, vio_desc_direction_t dir, int flags)
3067 {
3068 	vdc_local_desc_t	*local_dep = NULL; /* Local Dring Pointer */
3069 	int			idx;		/* Index of DRing entry used */
3070 	int			next_idx;
3071 	vio_dring_msg_t		dmsg;
3072 	size_t			msglen;
3073 	int			rv;
3074 
3075 	ASSERT(MUTEX_HELD(&vdcp->lock));
3076 	vdcp->threads_pending++;
3077 loop:
3078 	DMSG(vdcp, 2, ": dring_curr_idx = %d\n", vdcp->dring_curr_idx);
3079 
3080 	if (flags & VDC_OP_DRING_RESERVED) {
3081 		/* use D-Ring reserved entry */
3082 		idx = VDC_DRING_FIRST_RESV;
3083 		local_dep = &(vdcp->local_dring[idx]);
3084 	} else {
3085 		/* Get next available D-Ring entry */
3086 		idx = vdcp->dring_curr_idx;
3087 		local_dep = &(vdcp->local_dring[idx]);
3088 
3089 		if (!local_dep->is_free) {
3090 			DMSG(vdcp, 2, "[%d]: dring full - waiting for space\n",
3091 			    vdcp->instance);
3092 			cv_wait(&vdcp->dring_free_cv, &vdcp->lock);
3093 			if (vdcp->state == VDC_STATE_RUNNING ||
3094 			    vdcp->state == VDC_STATE_HANDLE_PENDING) {
3095 				goto loop;
3096 			}
3097 			vdcp->threads_pending--;
3098 			return (ECONNRESET);
3099 		}
3100 
3101 		next_idx = idx + 1;
3102 		if (next_idx >= vdcp->dring_len)
3103 			next_idx = VDC_DRING_FIRST_ENTRY;
3104 		vdcp->dring_curr_idx = next_idx;
3105 	}
3106 
3107 	ASSERT(local_dep->is_free);
3108 
3109 	local_dep->operation = operation;
3110 	local_dep->addr = addr;
3111 	local_dep->nbytes = nbytes;
3112 	local_dep->slice = slice;
3113 	local_dep->offset = offset;
3114 	local_dep->buf = bufp;
3115 	local_dep->dir = dir;
3116 	local_dep->flags = flags;
3117 
3118 	local_dep->is_free = B_FALSE;
3119 
3120 	rv = vdc_map_to_shared_dring(vdcp, idx);
3121 	if (rv) {
3122 		if (flags & VDC_OP_DRING_RESERVED) {
3123 			DMSG(vdcp, 0, "[%d]: cannot bind memory - error\n",
3124 			    vdcp->instance);
3125 			/*
3126 			 * We can't wait if we are using reserved slot.
3127 			 * Free the descriptor and return.
3128 			 */
3129 			local_dep->is_free = B_TRUE;
3130 			vdcp->threads_pending--;
3131 			return (rv);
3132 		}
3133 		DMSG(vdcp, 0, "[%d]: cannot bind memory - waiting ..\n",
3134 		    vdcp->instance);
3135 		/* free the descriptor */
3136 		local_dep->is_free = B_TRUE;
3137 		vdcp->dring_curr_idx = idx;
3138 		cv_wait(&vdcp->membind_cv, &vdcp->lock);
3139 		if (vdcp->state == VDC_STATE_RUNNING ||
3140 		    vdcp->state == VDC_STATE_HANDLE_PENDING) {
3141 			goto loop;
3142 		}
3143 		vdcp->threads_pending--;
3144 		return (ECONNRESET);
3145 	}
3146 
3147 	/*
3148 	 * Send a msg with the DRing details to vds
3149 	 */
3150 	VIO_INIT_DRING_DATA_TAG(dmsg);
3151 	VDC_INIT_DRING_DATA_MSG_IDS(dmsg, vdcp);
3152 	dmsg.dring_ident = vdcp->dring_ident;
3153 	dmsg.start_idx = idx;
3154 	dmsg.end_idx = idx;
3155 	vdcp->seq_num++;
3156 
3157 	DTRACE_PROBE2(populate, int, vdcp->instance,
3158 	    vdc_local_desc_t *, local_dep);
3159 	DMSG(vdcp, 2, "ident=0x%lx, st=%u, end=%u, seq=%ld\n",
3160 	    vdcp->dring_ident, dmsg.start_idx, dmsg.end_idx, dmsg.seq_num);
3161 
3162 	/*
3163 	 * note we're still holding the lock here to
3164 	 * make sure the message goes out in order !!!...
3165 	 */
3166 	msglen = sizeof (dmsg);
3167 	rv = vdc_send(vdcp, (caddr_t)&dmsg, &msglen);
3168 	switch (rv) {
3169 	case ECONNRESET:
3170 		/*
3171 		 * vdc_send initiates the reset on failure.
3172 		 * Since the transaction has already been put
3173 		 * on the local dring, it will automatically get
3174 		 * retried when the channel is reset. Given that,
3175 		 * it is ok to just return success even though the
3176 		 * send failed.
3177 		 */
3178 		rv = 0;
3179 		break;
3180 
3181 	case 0: /* EOK */
3182 		DMSG(vdcp, 1, "sent via LDC: rv=%d\n", rv);
3183 		break;
3184 
3185 	default:
3186 		DMSG(vdcp, 0, "unexpected error, rv=%d\n", rv);
3187 		rv = ENXIO;
3188 		break;
3189 	}
3190 
3191 	vdcp->threads_pending--;
3192 	return (rv);
3193 }
3194 
3195 /*
3196  * Function:
3197  *	vdc_do_op
3198  *
3199  * Description:
3200  *	Wrapper around vdc_submit_request(). Each request is associated with a
3201  *	buf structure. If a buf structure is provided (bufp != NULL) then the
3202  *	request will be submitted with that buf, and the caller can wait for
3203  *	completion of the request with biowait(). If a buf structure is not
3204  *	provided (bufp == NULL) then a buf structure is created and the function
3205  *	waits for the completion of the request.
3206  *
3207  *	If the flag VD_OP_STATE_RUNNING is set then vdc_submit_request() will
3208  *	submit the request only when the vdisk is in state VD_STATE_RUNNING.
3209  *	If the vdisk is not in that state then the vdc_submit_request() will
3210  *	wait for that state to be reached. After the request is submitted, the
3211  *	reply will be processed asynchronously by the vdc_process_msg_thread()
3212  *	thread.
3213  *
3214  *	If the flag VD_OP_STATE_RUNNING is not set then vdc_submit_request()
3215  *	submit the request whatever the state of the vdisk is. Then vdc_do_op()
3216  *	will wait for a reply message, process the reply and complete the
3217  *	request.
3218  *
3219  * Arguments:
3220  *	vdc	- the soft state pointer
3221  *	op	- operation we want vds to perform (VD_OP_XXX)
3222  *	addr	- address of data buf to be read/written.
3223  *	nbytes	- number of bytes to read/write
3224  *	slice	- the disk slice this request is for
3225  *	offset	- relative disk offset
3226  *	bufp	- buf structure associated with the request (can be NULL).
3227  *	dir	- direction of operation (READ/WRITE/BOTH)
3228  *	flags	- flags for the request.
3229  *
3230  * Return Codes:
3231  *	0	- the request has been succesfully submitted and completed.
3232  *	!= 0	- the request has failed. In that case, if a buf structure
3233  *		  was provided (bufp != NULL) then the B_ERROR flag is set
3234  *		  and the b_error field of the buf structure is set to EIO.
3235  */
3236 static int
vdc_do_op(vdc_t * vdc,int op,caddr_t addr,size_t nbytes,int slice,diskaddr_t offset,struct buf * bufp,vio_desc_direction_t dir,int flags)3237 vdc_do_op(vdc_t *vdc, int op, caddr_t addr, size_t nbytes, int slice,
3238     diskaddr_t offset, struct buf *bufp, vio_desc_direction_t dir, int flags)
3239 {
3240 	vio_msg_t vio_msg;
3241 	struct buf buf;
3242 	int rv;
3243 
3244 	if (bufp == NULL) {
3245 		/*
3246 		 * We use buf just as a convenient way to get a notification
3247 		 * that the request is completed, so we initialize buf to the
3248 		 * minimum we need.
3249 		 */
3250 		bioinit(&buf);
3251 		buf.b_bcount = nbytes;
3252 		buf.b_flags = B_BUSY;
3253 		bufp = &buf;
3254 	}
3255 
3256 	rv = vdc_send_request(vdc, op, addr, nbytes, slice, offset, bufp,
3257 	    dir, flags);
3258 
3259 	if (rv != 0)
3260 		goto done;
3261 
3262 	/*
3263 	 * If the request should be done in VDC_STATE_RUNNING state then the
3264 	 * reply will be received and processed by vdc_process_msg_thread()
3265 	 * and we just have to handle the panic case. Otherwise we have to
3266 	 * wait for the reply message and process it.
3267 	 */
3268 	if (flags & VDC_OP_STATE_RUNNING) {
3269 
3270 		if (ddi_in_panic()) {
3271 			rv = vdc_drain_response(vdc, bufp);
3272 			goto done;
3273 		}
3274 
3275 	} else {
3276 		/* wait for the response message */
3277 		rv = vdc_wait_for_response(vdc, &vio_msg);
3278 
3279 		if (rv == 0)
3280 			rv = vdc_process_data_msg(vdc, &vio_msg);
3281 
3282 		if (rv) {
3283 			/*
3284 			 * If this is a block read/write we update the I/O
3285 			 * statistics kstat to take it off the run queue.
3286 			 * If it is a resubmit then it needs to stay in
3287 			 * in the waitq, and it will be removed when the
3288 			 * I/O is eventually completed or cancelled.
3289 			 */
3290 			mutex_enter(&vdc->lock);
3291 			if (op == VD_OP_BREAD || op == VD_OP_BWRITE) {
3292 				if (flags & VDC_OP_RESUBMIT) {
3293 					VD_KSTAT_RUNQ_BACK_TO_WAITQ(vdc);
3294 				} else {
3295 					VD_KSTAT_RUNQ_EXIT(vdc);
3296 					DTRACE_IO1(done, buf_t *, bufp);
3297 				}
3298 			}
3299 			mutex_exit(&vdc->lock);
3300 			goto done;
3301 		}
3302 
3303 	}
3304 
3305 	if (bufp == &buf)
3306 		rv = biowait(bufp);
3307 
3308 done:
3309 	if (bufp == &buf) {
3310 		biofini(bufp);
3311 	} else if (rv != 0) {
3312 		bioerror(bufp, EIO);
3313 		biodone(bufp);
3314 	}
3315 
3316 	return (rv);
3317 }
3318 
3319 /*
3320  * Function:
3321  *	vdc_do_sync_op
3322  *
3323  * Description:
3324  *	Wrapper around vdc_do_op that serializes requests.
3325  *
3326  * Arguments:
3327  *	vdcp	  - the soft state pointer
3328  *	operation - operation we want vds to perform (VD_OP_XXX)
3329  *	addr	  - address of data buf to be read/written.
3330  *	nbytes	  - number of bytes to read/write
3331  *	slice	  - the disk slice this request is for
3332  *	offset	  - relative disk offset
3333  *	dir	  - direction of operation (READ/WRITE/BOTH)
3334  *	rconflict - check for reservation conflict in case of failure
3335  *
3336  * rconflict should be set to B_TRUE by most callers. Callers invoking the
3337  * VD_OP_SCSICMD operation can set rconflict to B_FALSE if they check the
3338  * result of a successful operation with vdc_scsi_status().
3339  *
3340  * Return Codes:
3341  *	0
3342  *	EAGAIN
3343  *	EFAULT
3344  *	ENXIO
3345  *	EIO
3346  */
3347 static int
vdc_do_sync_op(vdc_t * vdcp,int operation,caddr_t addr,size_t nbytes,int slice,diskaddr_t offset,vio_desc_direction_t dir,boolean_t rconflict)3348 vdc_do_sync_op(vdc_t *vdcp, int operation, caddr_t addr, size_t nbytes,
3349     int slice, diskaddr_t offset, vio_desc_direction_t dir, boolean_t rconflict)
3350 {
3351 	int status;
3352 	int flags = VDC_OP_NORMAL;
3353 
3354 	/*
3355 	 * Grab the lock, if blocked wait until the server
3356 	 * response causes us to wake up again.
3357 	 */
3358 	mutex_enter(&vdcp->lock);
3359 	vdcp->sync_op_cnt++;
3360 	while (vdcp->sync_op_blocked && vdcp->state != VDC_STATE_DETACH) {
3361 		if (ddi_in_panic()) {
3362 			/* don't block if we are panicking */
3363 			vdcp->sync_op_cnt--;
3364 			mutex_exit(&vdcp->lock);
3365 			return (EIO);
3366 		} else {
3367 			cv_wait(&vdcp->sync_blocked_cv, &vdcp->lock);
3368 		}
3369 	}
3370 
3371 	if (vdcp->state == VDC_STATE_DETACH) {
3372 		cv_broadcast(&vdcp->sync_blocked_cv);
3373 		vdcp->sync_op_cnt--;
3374 		mutex_exit(&vdcp->lock);
3375 		return (ENXIO);
3376 	}
3377 
3378 	/* now block anyone other thread entering after us */
3379 	vdcp->sync_op_blocked = B_TRUE;
3380 
3381 	mutex_exit(&vdcp->lock);
3382 
3383 	if (!rconflict)
3384 		flags &= ~VDC_OP_ERRCHK_CONFLICT;
3385 
3386 	status = vdc_do_op(vdcp, operation, addr, nbytes, slice, offset,
3387 	    NULL, dir, flags);
3388 
3389 	mutex_enter(&vdcp->lock);
3390 
3391 	DMSG(vdcp, 2, ": operation returned %d\n", status);
3392 
3393 	if (vdcp->state == VDC_STATE_DETACH) {
3394 		status = ENXIO;
3395 	}
3396 
3397 	vdcp->sync_op_blocked = B_FALSE;
3398 	vdcp->sync_op_cnt--;
3399 
3400 	/* signal the next waiting thread */
3401 	cv_signal(&vdcp->sync_blocked_cv);
3402 
3403 	mutex_exit(&vdcp->lock);
3404 
3405 	return (status);
3406 }
3407 
3408 
3409 /*
3410  * Function:
3411  *	vdc_drain_response()
3412  *
3413  * Description:
3414  *	When a guest is panicking, the completion of requests needs to be
3415  *	handled differently because interrupts are disabled and vdc
3416  *	will not get messages. We have to poll for the messages instead.
3417  *
3418  *	Note: since we are panicking we don't implement	the io:::done
3419  *	DTrace probe or update the I/O statistics kstats.
3420  *
3421  * Arguments:
3422  *	vdc	- soft state pointer for this instance of the device driver.
3423  *	buf	- if buf is NULL then we drain all responses, otherwise we
3424  *		  poll until we receive a ACK/NACK for the specific I/O
3425  *		  described by buf.
3426  *
3427  * Return Code:
3428  *	0	- Success. If we were expecting a response to a particular
3429  *		  request then this means that a response has been received.
3430  */
3431 static int
vdc_drain_response(vdc_t * vdc,struct buf * buf)3432 vdc_drain_response(vdc_t *vdc, struct buf *buf)
3433 {
3434 	int			rv, idx, retries;
3435 	size_t			msglen;
3436 	vdc_local_desc_t	*ldep = NULL;	/* Local Dring Entry Pointer */
3437 	vio_dring_msg_t		dmsg;
3438 	struct buf		*mbuf;
3439</