xref: /illumos-gate/usr/src/uts/common/io/comstar/stmf/stmf.c (revision 3d78e6ab42c6ffc02ee9dbd101ff2551b77cb45f)
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  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 #include <sys/conf.h>
26 #include <sys/file.h>
27 #include <sys/ddi.h>
28 #include <sys/sunddi.h>
29 #include <sys/modctl.h>
30 #include <sys/scsi/scsi.h>
31 #include <sys/scsi/impl/scsi_reset_notify.h>
32 #include <sys/disp.h>
33 #include <sys/byteorder.h>
34 #include <sys/atomic.h>
35 #include <sys/ethernet.h>
36 #include <sys/sdt.h>
37 #include <sys/nvpair.h>
38 #include <sys/zone.h>
39 #include <sys/id_space.h>
40 
41 #include <stmf.h>
42 #include <lpif.h>
43 #include <portif.h>
44 #include <stmf_ioctl.h>
45 #include <stmf_impl.h>
46 #include <lun_map.h>
47 #include <stmf_state.h>
48 #include <pppt_ic_if.h>
49 #include <stmf_stats.h>
50 
51 /*
52  * Lock order:
53  * stmf_state_lock --> ilport_lock/iss_lockp --> ilu_task_lock
54  */
55 
56 static uint64_t stmf_session_counter = 0;
57 static uint16_t stmf_rtpid_counter = 0;
58 /* start messages at 1 */
59 static uint64_t stmf_proxy_msg_id = 1;
60 #define	MSG_ID_TM_BIT	0x8000000000000000
61 
62 static int stmf_attach(dev_info_t *dip, ddi_attach_cmd_t cmd);
63 static int stmf_detach(dev_info_t *dip, ddi_detach_cmd_t cmd);
64 static int stmf_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg,
65 	void **result);
66 static int stmf_open(dev_t *devp, int flag, int otype, cred_t *credp);
67 static int stmf_close(dev_t dev, int flag, int otype, cred_t *credp);
68 static int stmf_ioctl(dev_t dev, int cmd, intptr_t data, int mode,
69 	cred_t *credp, int *rval);
70 static int stmf_get_stmf_state(stmf_state_desc_t *std);
71 static int stmf_set_stmf_state(stmf_state_desc_t *std);
72 static void stmf_abort_task_offline(scsi_task_t *task, int offline_lu,
73     char *info);
74 static int stmf_set_alua_state(stmf_alua_state_desc_t *alua_state);
75 static void stmf_get_alua_state(stmf_alua_state_desc_t *alua_state);
76 stmf_xfer_data_t *stmf_prepare_tpgs_data(uint8_t ilu_alua);
77 void stmf_svc_init();
78 stmf_status_t stmf_svc_fini();
79 void stmf_svc(void *arg);
80 void stmf_svc_queue(int cmd, void *obj, stmf_state_change_info_t *info);
81 void stmf_check_freetask();
82 void stmf_abort_target_reset(scsi_task_t *task);
83 stmf_status_t stmf_lun_reset_poll(stmf_lu_t *lu, struct scsi_task *task,
84 							int target_reset);
85 void stmf_target_reset_poll(struct scsi_task *task);
86 void stmf_handle_lun_reset(scsi_task_t *task);
87 void stmf_handle_target_reset(scsi_task_t *task);
88 void stmf_xd_to_dbuf(stmf_data_buf_t *dbuf);
89 int stmf_load_ppd_ioctl(stmf_ppioctl_data_t *ppi, uint64_t *ppi_token,
90     uint32_t *err_ret);
91 int stmf_delete_ppd_ioctl(stmf_ppioctl_data_t *ppi);
92 int stmf_get_ppd_ioctl(stmf_ppioctl_data_t *ppi, stmf_ppioctl_data_t *ppi_out,
93     uint32_t *err_ret);
94 void stmf_delete_ppd(stmf_pp_data_t *ppd);
95 void stmf_delete_all_ppds();
96 void stmf_trace_clear();
97 void stmf_worker_init();
98 stmf_status_t stmf_worker_fini();
99 void stmf_worker_mgmt();
100 void stmf_worker_task(void *arg);
101 static void stmf_task_lu_free(scsi_task_t *task, stmf_i_scsi_session_t *iss);
102 static stmf_status_t stmf_ic_lu_reg(stmf_ic_reg_dereg_lun_msg_t *msg,
103     uint32_t type);
104 static stmf_status_t stmf_ic_lu_dereg(stmf_ic_reg_dereg_lun_msg_t *msg);
105 static stmf_status_t stmf_ic_rx_scsi_status(stmf_ic_scsi_status_msg_t *msg);
106 static stmf_status_t stmf_ic_rx_status(stmf_ic_status_msg_t *msg);
107 static stmf_status_t stmf_ic_rx_scsi_data(stmf_ic_scsi_data_msg_t *msg);
108 void stmf_task_lu_killall(stmf_lu_t *lu, scsi_task_t *tm_task, stmf_status_t s);
109 
110 /* pppt modhandle */
111 ddi_modhandle_t pppt_mod;
112 
113 /* pppt modload imported functions */
114 stmf_ic_reg_port_msg_alloc_func_t ic_reg_port_msg_alloc;
115 stmf_ic_dereg_port_msg_alloc_func_t ic_dereg_port_msg_alloc;
116 stmf_ic_reg_lun_msg_alloc_func_t ic_reg_lun_msg_alloc;
117 stmf_ic_dereg_lun_msg_alloc_func_t ic_dereg_lun_msg_alloc;
118 stmf_ic_lun_active_msg_alloc_func_t ic_lun_active_msg_alloc;
119 stmf_ic_scsi_cmd_msg_alloc_func_t ic_scsi_cmd_msg_alloc;
120 stmf_ic_scsi_data_xfer_done_msg_alloc_func_t ic_scsi_data_xfer_done_msg_alloc;
121 stmf_ic_session_create_msg_alloc_func_t ic_session_reg_msg_alloc;
122 stmf_ic_session_destroy_msg_alloc_func_t ic_session_dereg_msg_alloc;
123 stmf_ic_tx_msg_func_t ic_tx_msg;
124 stmf_ic_msg_free_func_t ic_msg_free;
125 
126 static void stmf_itl_task_start(stmf_i_scsi_task_t *itask);
127 static void stmf_itl_lu_new_task(stmf_i_scsi_task_t *itask);
128 static void stmf_itl_task_done(stmf_i_scsi_task_t *itask);
129 
130 static void stmf_lport_xfer_start(stmf_i_scsi_task_t *itask,
131     stmf_data_buf_t *dbuf);
132 static void stmf_lport_xfer_done(stmf_i_scsi_task_t *itask,
133     stmf_data_buf_t *dbuf);
134 
135 static void stmf_update_kstat_lu_q(scsi_task_t *, void());
136 static void stmf_update_kstat_lport_q(scsi_task_t *, void());
137 static void stmf_update_kstat_lu_io(scsi_task_t *, stmf_data_buf_t *);
138 static void stmf_update_kstat_lport_io(scsi_task_t *, stmf_data_buf_t *);
139 
140 static int stmf_irport_compare(const void *void_irport1,
141     const void *void_irport2);
142 static stmf_i_remote_port_t *stmf_irport_create(scsi_devid_desc_t *rport_devid);
143 static void stmf_irport_destroy(stmf_i_remote_port_t *irport);
144 static stmf_i_remote_port_t *stmf_irport_register(
145     scsi_devid_desc_t *rport_devid);
146 static stmf_i_remote_port_t *stmf_irport_lookup_locked(
147     scsi_devid_desc_t *rport_devid);
148 static void stmf_irport_deregister(stmf_i_remote_port_t *irport);
149 
150 static void stmf_teardown_itl_kstats(stmf_i_itl_kstat_t *ks);
151 static void stmf_delete_itl_kstat_by_lport(char *);
152 static void stmf_delete_itl_kstat_by_guid(char *);
153 static int stmf_itl_kstat_compare(const void*, const void*);
154 static stmf_i_itl_kstat_t *stmf_itl_kstat_lookup(char *kstat_nm);
155 static stmf_i_itl_kstat_t *stmf_itl_kstat_create(stmf_itl_data_t *itl,
156     char *nm, scsi_devid_desc_t *lport, scsi_devid_desc_t *lun);
157 
158 extern struct mod_ops mod_driverops;
159 
160 /* =====[ Tunables ]===== */
161 /* Internal tracing */
162 volatile int	stmf_trace_on = 1;
163 volatile int	stmf_trace_buf_size = (1 * 1024 * 1024);
164 /*
165  * The reason default task timeout is 75 is because we want the
166  * host to timeout 1st and mostly host timeout is 60 seconds.
167  */
168 volatile int	stmf_default_task_timeout = 75;
169 /*
170  * Setting this to one means, you are responsible for config load and keeping
171  * things in sync with persistent database.
172  */
173 volatile int	stmf_allow_modunload = 0;
174 
175 volatile int stmf_max_nworkers = 256;
176 volatile int stmf_min_nworkers = 4;
177 volatile int stmf_worker_scale_down_delay = 20;
178 
179 /* === [ Debugging and fault injection ] === */
180 #ifdef	DEBUG
181 volatile int stmf_drop_task_counter = 0;
182 volatile int stmf_drop_buf_counter = 0;
183 
184 #endif
185 
186 stmf_state_t		stmf_state;
187 static stmf_lu_t	*dlun0;
188 
189 static uint8_t stmf_first_zero[] =
190 	{ 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 0xff };
191 static uint8_t stmf_first_one[] =
192 	{ 0xff, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0 };
193 
194 static kmutex_t	trace_buf_lock;
195 static int	trace_buf_size;
196 static int	trace_buf_curndx;
197 caddr_t	stmf_trace_buf;
198 
199 static enum {
200 	STMF_WORKERS_DISABLED = 0,
201 	STMF_WORKERS_ENABLING,
202 	STMF_WORKERS_ENABLED
203 } stmf_workers_state = STMF_WORKERS_DISABLED;
204 static int stmf_i_max_nworkers;
205 static int stmf_i_min_nworkers;
206 static int stmf_nworkers_cur;		/* # of workers currently running */
207 static int stmf_nworkers_needed;	/* # of workers need to be running */
208 static int stmf_worker_sel_counter = 0;
209 static uint32_t stmf_cur_ntasks = 0;
210 static clock_t stmf_wm_last = 0;
211 /*
212  * This is equal to stmf_nworkers_cur while we are increasing # workers and
213  * stmf_nworkers_needed while we are decreasing the worker count.
214  */
215 static int stmf_nworkers_accepting_cmds;
216 static stmf_worker_t *stmf_workers = NULL;
217 static clock_t stmf_worker_mgmt_delay = 2;
218 static clock_t stmf_worker_scale_down_timer = 0;
219 static int stmf_worker_scale_down_qd = 0;
220 
221 static struct cb_ops stmf_cb_ops = {
222 	stmf_open,			/* open */
223 	stmf_close,			/* close */
224 	nodev,				/* strategy */
225 	nodev,				/* print */
226 	nodev,				/* dump */
227 	nodev,				/* read */
228 	nodev,				/* write */
229 	stmf_ioctl,			/* ioctl */
230 	nodev,				/* devmap */
231 	nodev,				/* mmap */
232 	nodev,				/* segmap */
233 	nochpoll,			/* chpoll */
234 	ddi_prop_op,			/* cb_prop_op */
235 	0,				/* streamtab */
236 	D_NEW | D_MP,			/* cb_flag */
237 	CB_REV,				/* rev */
238 	nodev,				/* aread */
239 	nodev				/* awrite */
240 };
241 
242 static struct dev_ops stmf_ops = {
243 	DEVO_REV,
244 	0,
245 	stmf_getinfo,
246 	nulldev,		/* identify */
247 	nulldev,		/* probe */
248 	stmf_attach,
249 	stmf_detach,
250 	nodev,			/* reset */
251 	&stmf_cb_ops,
252 	NULL,			/* bus_ops */
253 	NULL			/* power */
254 };
255 
256 #define	STMF_NAME		"COMSTAR STMF"
257 #define	STMF_MODULE_NAME	"stmf"
258 
259 static struct modldrv modldrv = {
260 	&mod_driverops,
261 	STMF_NAME,
262 	&stmf_ops
263 };
264 
265 static struct modlinkage modlinkage = {
266 	MODREV_1,
267 	&modldrv,
268 	NULL
269 };
270 
271 int
272 _init(void)
273 {
274 	int ret;
275 
276 	ret = mod_install(&modlinkage);
277 	if (ret)
278 		return (ret);
279 	stmf_trace_buf = kmem_zalloc(stmf_trace_buf_size, KM_SLEEP);
280 	trace_buf_size = stmf_trace_buf_size;
281 	trace_buf_curndx = 0;
282 	mutex_init(&trace_buf_lock, NULL, MUTEX_DRIVER, 0);
283 	bzero(&stmf_state, sizeof (stmf_state_t));
284 	/* STMF service is off by default */
285 	stmf_state.stmf_service_running = 0;
286 	mutex_init(&stmf_state.stmf_lock, NULL, MUTEX_DRIVER, NULL);
287 	cv_init(&stmf_state.stmf_cv, NULL, CV_DRIVER, NULL);
288 	stmf_session_counter = (uint64_t)ddi_get_lbolt();
289 	avl_create(&stmf_state.stmf_irportlist,
290 	    stmf_irport_compare, sizeof (stmf_i_remote_port_t),
291 	    offsetof(stmf_i_remote_port_t, irport_ln));
292 	stmf_state.stmf_ilport_inst_space =
293 	    id_space_create("lport-instances", 0, MAX_ILPORT);
294 	stmf_state.stmf_irport_inst_space =
295 	    id_space_create("rport-instances", 0, MAX_IRPORT);
296 	avl_create(&stmf_state.stmf_itl_kstat_list,
297 	    stmf_itl_kstat_compare, sizeof (stmf_i_itl_kstat_t),
298 	    offsetof(stmf_i_itl_kstat_t, iitl_kstat_ln));
299 	stmf_view_init();
300 	stmf_svc_init();
301 	stmf_dlun_init();
302 	return (ret);
303 }
304 
305 int
306 _fini(void)
307 {
308 	int ret;
309 	stmf_i_remote_port_t	*irport;
310 	stmf_i_itl_kstat_t	*ks_itl;
311 	void			*avl_dest_cookie = NULL;
312 
313 	if (stmf_state.stmf_service_running)
314 		return (EBUSY);
315 	if ((!stmf_allow_modunload) &&
316 	    (stmf_state.stmf_config_state != STMF_CONFIG_NONE)) {
317 		return (EBUSY);
318 	}
319 	if (stmf_state.stmf_nlps || stmf_state.stmf_npps) {
320 		return (EBUSY);
321 	}
322 	if (stmf_dlun_fini() != STMF_SUCCESS)
323 		return (EBUSY);
324 	if (stmf_worker_fini() != STMF_SUCCESS) {
325 		stmf_dlun_init();
326 		return (EBUSY);
327 	}
328 	if (stmf_svc_fini() != STMF_SUCCESS) {
329 		stmf_dlun_init();
330 		stmf_worker_init();
331 		return (EBUSY);
332 	}
333 
334 	ret = mod_remove(&modlinkage);
335 	if (ret) {
336 		stmf_svc_init();
337 		stmf_dlun_init();
338 		stmf_worker_init();
339 		return (ret);
340 	}
341 
342 	stmf_view_clear_config();
343 
344 	while ((irport = avl_destroy_nodes(&stmf_state.stmf_irportlist,
345 	    &avl_dest_cookie)) != NULL)
346 		stmf_irport_destroy(irport);
347 	avl_destroy(&stmf_state.stmf_irportlist);
348 	id_space_destroy(stmf_state.stmf_ilport_inst_space);
349 	id_space_destroy(stmf_state.stmf_irport_inst_space);
350 
351 	avl_dest_cookie = NULL;
352 	while ((ks_itl = avl_destroy_nodes(&stmf_state.stmf_itl_kstat_list,
353 	    &avl_dest_cookie)) != NULL) {
354 		stmf_teardown_itl_kstats(ks_itl);
355 		kmem_free(ks_itl, sizeof (ks_itl));
356 	}
357 	avl_destroy(&stmf_state.stmf_itl_kstat_list);
358 
359 	kmem_free(stmf_trace_buf, stmf_trace_buf_size);
360 	mutex_destroy(&trace_buf_lock);
361 	mutex_destroy(&stmf_state.stmf_lock);
362 	cv_destroy(&stmf_state.stmf_cv);
363 	return (ret);
364 }
365 
366 int
367 _info(struct modinfo *modinfop)
368 {
369 	return (mod_info(&modlinkage, modinfop));
370 }
371 
372 /* ARGSUSED */
373 static int
374 stmf_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg, void **result)
375 {
376 	switch (cmd) {
377 	case DDI_INFO_DEVT2DEVINFO:
378 		*result = stmf_state.stmf_dip;
379 		break;
380 	case DDI_INFO_DEVT2INSTANCE:
381 		*result =
382 		    (void *)(uintptr_t)ddi_get_instance(stmf_state.stmf_dip);
383 		break;
384 	default:
385 		return (DDI_FAILURE);
386 	}
387 
388 	return (DDI_SUCCESS);
389 }
390 
391 static int
392 stmf_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
393 {
394 	switch (cmd) {
395 	case DDI_ATTACH:
396 		stmf_state.stmf_dip = dip;
397 
398 		if (ddi_create_minor_node(dip, "admin", S_IFCHR, 0,
399 		    DDI_NT_STMF, 0) != DDI_SUCCESS) {
400 			break;
401 		}
402 		ddi_report_dev(dip);
403 		return (DDI_SUCCESS);
404 	}
405 
406 	return (DDI_FAILURE);
407 }
408 
409 static int
410 stmf_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
411 {
412 	switch (cmd) {
413 	case DDI_DETACH:
414 		ddi_remove_minor_node(dip, 0);
415 		return (DDI_SUCCESS);
416 	}
417 
418 	return (DDI_FAILURE);
419 }
420 
421 /* ARGSUSED */
422 static int
423 stmf_open(dev_t *devp, int flag, int otype, cred_t *credp)
424 {
425 	mutex_enter(&stmf_state.stmf_lock);
426 	if (stmf_state.stmf_exclusive_open) {
427 		mutex_exit(&stmf_state.stmf_lock);
428 		return (EBUSY);
429 	}
430 	if (flag & FEXCL) {
431 		if (stmf_state.stmf_opened) {
432 			mutex_exit(&stmf_state.stmf_lock);
433 			return (EBUSY);
434 		}
435 		stmf_state.stmf_exclusive_open = 1;
436 	}
437 	stmf_state.stmf_opened = 1;
438 	mutex_exit(&stmf_state.stmf_lock);
439 	return (0);
440 }
441 
442 /* ARGSUSED */
443 static int
444 stmf_close(dev_t dev, int flag, int otype, cred_t *credp)
445 {
446 	mutex_enter(&stmf_state.stmf_lock);
447 	stmf_state.stmf_opened = 0;
448 	if (stmf_state.stmf_exclusive_open &&
449 	    (stmf_state.stmf_config_state != STMF_CONFIG_INIT_DONE)) {
450 		stmf_state.stmf_config_state = STMF_CONFIG_NONE;
451 		stmf_delete_all_ppds();
452 		stmf_view_clear_config();
453 		stmf_view_init();
454 	}
455 	stmf_state.stmf_exclusive_open = 0;
456 	mutex_exit(&stmf_state.stmf_lock);
457 	return (0);
458 }
459 
460 int
461 stmf_copyin_iocdata(intptr_t data, int mode, stmf_iocdata_t **iocd,
462 						void **ibuf, void **obuf)
463 {
464 	int ret;
465 
466 	*ibuf = NULL;
467 	*obuf = NULL;
468 	*iocd = kmem_zalloc(sizeof (stmf_iocdata_t), KM_SLEEP);
469 
470 	ret = ddi_copyin((void *)data, *iocd, sizeof (stmf_iocdata_t), mode);
471 	if (ret)
472 		return (EFAULT);
473 	if ((*iocd)->stmf_version != STMF_VERSION_1) {
474 		ret = EINVAL;
475 		goto copyin_iocdata_done;
476 	}
477 	if ((*iocd)->stmf_ibuf_size) {
478 		*ibuf = kmem_zalloc((*iocd)->stmf_ibuf_size, KM_SLEEP);
479 		ret = ddi_copyin((void *)((unsigned long)(*iocd)->stmf_ibuf),
480 		    *ibuf, (*iocd)->stmf_ibuf_size, mode);
481 	}
482 	if ((*iocd)->stmf_obuf_size)
483 		*obuf = kmem_zalloc((*iocd)->stmf_obuf_size, KM_SLEEP);
484 
485 	if (ret == 0)
486 		return (0);
487 	ret = EFAULT;
488 copyin_iocdata_done:;
489 	if (*obuf) {
490 		kmem_free(*obuf, (*iocd)->stmf_obuf_size);
491 		*obuf = NULL;
492 	}
493 	if (*ibuf) {
494 		kmem_free(*ibuf, (*iocd)->stmf_ibuf_size);
495 		*ibuf = NULL;
496 	}
497 	kmem_free(*iocd, sizeof (stmf_iocdata_t));
498 	return (ret);
499 }
500 
501 int
502 stmf_copyout_iocdata(intptr_t data, int mode, stmf_iocdata_t *iocd, void *obuf)
503 {
504 	int ret;
505 
506 	if (iocd->stmf_obuf_size) {
507 		ret = ddi_copyout(obuf, (void *)(unsigned long)iocd->stmf_obuf,
508 		    iocd->stmf_obuf_size, mode);
509 		if (ret)
510 			return (EFAULT);
511 	}
512 	ret = ddi_copyout(iocd, (void *)data, sizeof (stmf_iocdata_t), mode);
513 	if (ret)
514 		return (EFAULT);
515 	return (0);
516 }
517 
518 /* ARGSUSED */
519 static int
520 stmf_ioctl(dev_t dev, int cmd, intptr_t data, int mode,
521 	cred_t *credp, int *rval)
522 {
523 	stmf_iocdata_t *iocd;
524 	void *ibuf = NULL, *obuf = NULL;
525 	slist_lu_t *luid_list;
526 	slist_target_port_t *lportid_list;
527 	stmf_i_lu_t *ilu;
528 	stmf_i_local_port_t *ilport;
529 	stmf_i_scsi_session_t *iss;
530 	slist_scsi_session_t *iss_list;
531 	sioc_lu_props_t *lup;
532 	sioc_target_port_props_t *lportp;
533 	stmf_ppioctl_data_t *ppi, *ppi_out = NULL;
534 	uint64_t *ppi_token = NULL;
535 	uint8_t *p_id, *id;
536 	stmf_state_desc_t *std;
537 	stmf_status_t ctl_ret;
538 	stmf_state_change_info_t ssi;
539 	int ret = 0;
540 	uint32_t n;
541 	int i;
542 	stmf_group_op_data_t *grp_entry;
543 	stmf_group_name_t *grpname;
544 	stmf_view_op_entry_t *ve;
545 	stmf_id_type_t idtype;
546 	stmf_id_data_t *id_entry;
547 	stmf_id_list_t	*id_list;
548 	stmf_view_entry_t *view_entry;
549 	uint32_t	veid;
550 
551 	if ((cmd & 0xff000000) != STMF_IOCTL) {
552 		return (ENOTTY);
553 	}
554 
555 	if (drv_priv(credp) != 0) {
556 		return (EPERM);
557 	}
558 
559 	ret = stmf_copyin_iocdata(data, mode, &iocd, &ibuf, &obuf);
560 	if (ret)
561 		return (ret);
562 	iocd->stmf_error = 0;
563 
564 	switch (cmd) {
565 	case STMF_IOCTL_LU_LIST:
566 		/* retrieves both registered/unregistered */
567 		mutex_enter(&stmf_state.stmf_lock);
568 		id_list = &stmf_state.stmf_luid_list;
569 		n = min(id_list->id_count,
570 		    (iocd->stmf_obuf_size)/sizeof (slist_lu_t));
571 		iocd->stmf_obuf_max_nentries = id_list->id_count;
572 		luid_list = (slist_lu_t *)obuf;
573 		id_entry = id_list->idl_head;
574 		for (i = 0; i < n; i++) {
575 			bcopy(id_entry->id_data, luid_list[i].lu_guid, 16);
576 			id_entry = id_entry->id_next;
577 		}
578 
579 		n = iocd->stmf_obuf_size/sizeof (slist_lu_t);
580 		for (ilu = stmf_state.stmf_ilulist; ilu; ilu = ilu->ilu_next) {
581 			id = (uint8_t *)ilu->ilu_lu->lu_id;
582 			if (stmf_lookup_id(id_list, 16, id + 4) == NULL) {
583 				iocd->stmf_obuf_max_nentries++;
584 				if (i < n) {
585 					bcopy(id + 4, luid_list[i].lu_guid,
586 					    sizeof (slist_lu_t));
587 					i++;
588 				}
589 			}
590 		}
591 		iocd->stmf_obuf_nentries = i;
592 		mutex_exit(&stmf_state.stmf_lock);
593 		break;
594 
595 	case STMF_IOCTL_REG_LU_LIST:
596 		mutex_enter(&stmf_state.stmf_lock);
597 		iocd->stmf_obuf_max_nentries = stmf_state.stmf_nlus;
598 		n = min(stmf_state.stmf_nlus,
599 		    (iocd->stmf_obuf_size)/sizeof (slist_lu_t));
600 		iocd->stmf_obuf_nentries = n;
601 		ilu = stmf_state.stmf_ilulist;
602 		luid_list = (slist_lu_t *)obuf;
603 		for (i = 0; i < n; i++) {
604 			uint8_t *id;
605 			id = (uint8_t *)ilu->ilu_lu->lu_id;
606 			bcopy(id + 4, luid_list[i].lu_guid, 16);
607 			ilu = ilu->ilu_next;
608 		}
609 		mutex_exit(&stmf_state.stmf_lock);
610 		break;
611 
612 	case STMF_IOCTL_VE_LU_LIST:
613 		mutex_enter(&stmf_state.stmf_lock);
614 		id_list = &stmf_state.stmf_luid_list;
615 		n = min(id_list->id_count,
616 		    (iocd->stmf_obuf_size)/sizeof (slist_lu_t));
617 		iocd->stmf_obuf_max_nentries = id_list->id_count;
618 		iocd->stmf_obuf_nentries = n;
619 		luid_list = (slist_lu_t *)obuf;
620 		id_entry = id_list->idl_head;
621 		for (i = 0; i < n; i++) {
622 			bcopy(id_entry->id_data, luid_list[i].lu_guid, 16);
623 			id_entry = id_entry->id_next;
624 		}
625 		mutex_exit(&stmf_state.stmf_lock);
626 		break;
627 
628 	case STMF_IOCTL_TARGET_PORT_LIST:
629 		mutex_enter(&stmf_state.stmf_lock);
630 		iocd->stmf_obuf_max_nentries = stmf_state.stmf_nlports;
631 		n = min(stmf_state.stmf_nlports,
632 		    (iocd->stmf_obuf_size)/sizeof (slist_target_port_t));
633 		iocd->stmf_obuf_nentries = n;
634 		ilport = stmf_state.stmf_ilportlist;
635 		lportid_list = (slist_target_port_t *)obuf;
636 		for (i = 0; i < n; i++) {
637 			uint8_t *id;
638 			id = (uint8_t *)ilport->ilport_lport->lport_id;
639 			bcopy(id, lportid_list[i].target, id[3] + 4);
640 			ilport = ilport->ilport_next;
641 		}
642 		mutex_exit(&stmf_state.stmf_lock);
643 		break;
644 
645 	case STMF_IOCTL_SESSION_LIST:
646 		p_id = (uint8_t *)ibuf;
647 		if ((p_id == NULL) || (iocd->stmf_ibuf_size < 4) ||
648 		    (iocd->stmf_ibuf_size < (p_id[3] + 4))) {
649 			ret = EINVAL;
650 			break;
651 		}
652 		mutex_enter(&stmf_state.stmf_lock);
653 		for (ilport = stmf_state.stmf_ilportlist; ilport; ilport =
654 		    ilport->ilport_next) {
655 			uint8_t *id;
656 			id = (uint8_t *)ilport->ilport_lport->lport_id;
657 			if ((p_id[3] == id[3]) &&
658 			    (bcmp(p_id + 4, id + 4, id[3]) == 0)) {
659 				break;
660 			}
661 		}
662 		if (ilport == NULL) {
663 			mutex_exit(&stmf_state.stmf_lock);
664 			ret = ENOENT;
665 			break;
666 		}
667 		iocd->stmf_obuf_max_nentries = ilport->ilport_nsessions;
668 		n = min(ilport->ilport_nsessions,
669 		    (iocd->stmf_obuf_size)/sizeof (slist_scsi_session_t));
670 		iocd->stmf_obuf_nentries = n;
671 		iss = ilport->ilport_ss_list;
672 		iss_list = (slist_scsi_session_t *)obuf;
673 		for (i = 0; i < n; i++) {
674 			uint8_t *id;
675 			id = (uint8_t *)iss->iss_ss->ss_rport_id;
676 			bcopy(id, iss_list[i].initiator, id[3] + 4);
677 			iss_list[i].creation_time = (uint32_t)
678 			    iss->iss_creation_time;
679 			if (iss->iss_ss->ss_rport_alias) {
680 				(void) strncpy(iss_list[i].alias,
681 				    iss->iss_ss->ss_rport_alias, 255);
682 				iss_list[i].alias[255] = 0;
683 			} else {
684 				iss_list[i].alias[0] = 0;
685 			}
686 			iss = iss->iss_next;
687 		}
688 		mutex_exit(&stmf_state.stmf_lock);
689 		break;
690 
691 	case STMF_IOCTL_GET_LU_PROPERTIES:
692 		p_id = (uint8_t *)ibuf;
693 		if ((iocd->stmf_ibuf_size < 16) ||
694 		    (iocd->stmf_obuf_size < sizeof (sioc_lu_props_t)) ||
695 		    (p_id[0] == 0)) {
696 			ret = EINVAL;
697 			break;
698 		}
699 		mutex_enter(&stmf_state.stmf_lock);
700 		for (ilu = stmf_state.stmf_ilulist; ilu; ilu = ilu->ilu_next) {
701 			if (bcmp(p_id, ilu->ilu_lu->lu_id->ident, 16) == 0)
702 				break;
703 		}
704 		if (ilu == NULL) {
705 			mutex_exit(&stmf_state.stmf_lock);
706 			ret = ENOENT;
707 			break;
708 		}
709 		lup = (sioc_lu_props_t *)obuf;
710 		bcopy(ilu->ilu_lu->lu_id->ident, lup->lu_guid, 16);
711 		lup->lu_state = ilu->ilu_state & 0x0f;
712 		lup->lu_present = 1; /* XXX */
713 		(void) strncpy(lup->lu_provider_name,
714 		    ilu->ilu_lu->lu_lp->lp_name, 255);
715 		lup->lu_provider_name[254] = 0;
716 		if (ilu->ilu_lu->lu_alias) {
717 			(void) strncpy(lup->lu_alias,
718 			    ilu->ilu_lu->lu_alias, 255);
719 			lup->lu_alias[255] = 0;
720 		} else {
721 			lup->lu_alias[0] = 0;
722 		}
723 		mutex_exit(&stmf_state.stmf_lock);
724 		break;
725 
726 	case STMF_IOCTL_GET_TARGET_PORT_PROPERTIES:
727 		p_id = (uint8_t *)ibuf;
728 		if ((p_id == NULL) ||
729 		    (iocd->stmf_ibuf_size < (p_id[3] + 4)) ||
730 		    (iocd->stmf_obuf_size <
731 		    sizeof (sioc_target_port_props_t))) {
732 			ret = EINVAL;
733 			break;
734 		}
735 		mutex_enter(&stmf_state.stmf_lock);
736 		for (ilport = stmf_state.stmf_ilportlist; ilport;
737 		    ilport = ilport->ilport_next) {
738 			uint8_t *id;
739 			id = (uint8_t *)ilport->ilport_lport->lport_id;
740 			if ((p_id[3] == id[3]) &&
741 			    (bcmp(p_id+4, id+4, id[3]) == 0))
742 				break;
743 		}
744 		if (ilport == NULL) {
745 			mutex_exit(&stmf_state.stmf_lock);
746 			ret = ENOENT;
747 			break;
748 		}
749 		lportp = (sioc_target_port_props_t *)obuf;
750 		bcopy(ilport->ilport_lport->lport_id, lportp->tgt_id,
751 		    ilport->ilport_lport->lport_id->ident_length + 4);
752 		lportp->tgt_state = ilport->ilport_state & 0x0f;
753 		lportp->tgt_present = 1; /* XXX */
754 		(void) strncpy(lportp->tgt_provider_name,
755 		    ilport->ilport_lport->lport_pp->pp_name, 255);
756 		lportp->tgt_provider_name[254] = 0;
757 		if (ilport->ilport_lport->lport_alias) {
758 			(void) strncpy(lportp->tgt_alias,
759 			    ilport->ilport_lport->lport_alias, 255);
760 			lportp->tgt_alias[255] = 0;
761 		} else {
762 			lportp->tgt_alias[0] = 0;
763 		}
764 		mutex_exit(&stmf_state.stmf_lock);
765 		break;
766 
767 	case STMF_IOCTL_SET_STMF_STATE:
768 		if ((ibuf == NULL) ||
769 		    (iocd->stmf_ibuf_size < sizeof (stmf_state_desc_t))) {
770 			ret = EINVAL;
771 			break;
772 		}
773 		ret = stmf_set_stmf_state((stmf_state_desc_t *)ibuf);
774 		break;
775 
776 	case STMF_IOCTL_GET_STMF_STATE:
777 		if ((obuf == NULL) ||
778 		    (iocd->stmf_obuf_size < sizeof (stmf_state_desc_t))) {
779 			ret = EINVAL;
780 			break;
781 		}
782 		ret = stmf_get_stmf_state((stmf_state_desc_t *)obuf);
783 		break;
784 
785 	case STMF_IOCTL_SET_ALUA_STATE:
786 		if ((ibuf == NULL) ||
787 		    (iocd->stmf_ibuf_size < sizeof (stmf_alua_state_desc_t))) {
788 			ret = EINVAL;
789 			break;
790 		}
791 		ret = stmf_set_alua_state((stmf_alua_state_desc_t *)ibuf);
792 		break;
793 
794 	case STMF_IOCTL_GET_ALUA_STATE:
795 		if ((obuf == NULL) ||
796 		    (iocd->stmf_obuf_size < sizeof (stmf_alua_state_desc_t))) {
797 			ret = EINVAL;
798 			break;
799 		}
800 		stmf_get_alua_state((stmf_alua_state_desc_t *)obuf);
801 		break;
802 
803 	case STMF_IOCTL_SET_LU_STATE:
804 		ssi.st_rflags = STMF_RFLAG_USER_REQUEST;
805 		ssi.st_additional_info = NULL;
806 		std = (stmf_state_desc_t *)ibuf;
807 		if ((ibuf == NULL) ||
808 		    (iocd->stmf_ibuf_size < sizeof (stmf_state_desc_t))) {
809 			ret = EINVAL;
810 			break;
811 		}
812 		p_id = std->ident;
813 		mutex_enter(&stmf_state.stmf_lock);
814 		if (stmf_state.stmf_inventory_locked) {
815 			mutex_exit(&stmf_state.stmf_lock);
816 			ret = EBUSY;
817 			break;
818 		}
819 		for (ilu = stmf_state.stmf_ilulist; ilu; ilu = ilu->ilu_next) {
820 			if (bcmp(p_id, ilu->ilu_lu->lu_id->ident, 16) == 0)
821 				break;
822 		}
823 		if (ilu == NULL) {
824 			mutex_exit(&stmf_state.stmf_lock);
825 			ret = ENOENT;
826 			break;
827 		}
828 		stmf_state.stmf_inventory_locked = 1;
829 		mutex_exit(&stmf_state.stmf_lock);
830 		cmd = (std->state == STMF_STATE_ONLINE) ? STMF_CMD_LU_ONLINE :
831 		    STMF_CMD_LU_OFFLINE;
832 		ctl_ret = stmf_ctl(cmd, (void *)ilu->ilu_lu, &ssi);
833 		if (ctl_ret == STMF_ALREADY)
834 			ret = 0;
835 		else if (ctl_ret == STMF_BUSY)
836 			ret = EBUSY;
837 		else if (ctl_ret != STMF_SUCCESS)
838 			ret = EIO;
839 		mutex_enter(&stmf_state.stmf_lock);
840 		stmf_state.stmf_inventory_locked = 0;
841 		mutex_exit(&stmf_state.stmf_lock);
842 		break;
843 
844 	case STMF_IOCTL_SET_TARGET_PORT_STATE:
845 		ssi.st_rflags = STMF_RFLAG_USER_REQUEST;
846 		ssi.st_additional_info = NULL;
847 		std = (stmf_state_desc_t *)ibuf;
848 		if ((ibuf == NULL) ||
849 		    (iocd->stmf_ibuf_size < sizeof (stmf_state_desc_t))) {
850 			ret = EINVAL;
851 			break;
852 		}
853 		p_id = std->ident;
854 		mutex_enter(&stmf_state.stmf_lock);
855 		if (stmf_state.stmf_inventory_locked) {
856 			mutex_exit(&stmf_state.stmf_lock);
857 			ret = EBUSY;
858 			break;
859 		}
860 		for (ilport = stmf_state.stmf_ilportlist; ilport;
861 		    ilport = ilport->ilport_next) {
862 			uint8_t *id;
863 			id = (uint8_t *)ilport->ilport_lport->lport_id;
864 			if ((id[3] == p_id[3]) &&
865 			    (bcmp(id+4, p_id+4, id[3]) == 0)) {
866 				break;
867 			}
868 		}
869 		if (ilport == NULL) {
870 			mutex_exit(&stmf_state.stmf_lock);
871 			ret = ENOENT;
872 			break;
873 		}
874 		stmf_state.stmf_inventory_locked = 1;
875 		mutex_exit(&stmf_state.stmf_lock);
876 		cmd = (std->state == STMF_STATE_ONLINE) ?
877 		    STMF_CMD_LPORT_ONLINE : STMF_CMD_LPORT_OFFLINE;
878 		ctl_ret = stmf_ctl(cmd, (void *)ilport->ilport_lport, &ssi);
879 		if (ctl_ret == STMF_ALREADY)
880 			ret = 0;
881 		else if (ctl_ret == STMF_BUSY)
882 			ret = EBUSY;
883 		else if (ctl_ret != STMF_SUCCESS)
884 			ret = EIO;
885 		mutex_enter(&stmf_state.stmf_lock);
886 		stmf_state.stmf_inventory_locked = 0;
887 		mutex_exit(&stmf_state.stmf_lock);
888 		break;
889 
890 	case STMF_IOCTL_ADD_HG_ENTRY:
891 		idtype = STMF_ID_TYPE_HOST;
892 		/* FALLTHROUGH */
893 	case STMF_IOCTL_ADD_TG_ENTRY:
894 		if (stmf_state.stmf_config_state == STMF_CONFIG_NONE) {
895 			ret = EACCES;
896 			iocd->stmf_error = STMF_IOCERR_UPDATE_NEED_CFG_INIT;
897 			break;
898 		}
899 		if (cmd == STMF_IOCTL_ADD_TG_ENTRY) {
900 			idtype = STMF_ID_TYPE_TARGET;
901 		}
902 		grp_entry = (stmf_group_op_data_t *)ibuf;
903 		if ((ibuf == NULL) ||
904 		    (iocd->stmf_ibuf_size < sizeof (stmf_group_op_data_t))) {
905 			ret = EINVAL;
906 			break;
907 		}
908 		if (grp_entry->group.name[0] == '*') {
909 			ret = EINVAL;
910 			break; /* not allowed */
911 		}
912 		mutex_enter(&stmf_state.stmf_lock);
913 		ret = stmf_add_group_member(grp_entry->group.name,
914 		    grp_entry->group.name_size,
915 		    grp_entry->ident + 4,
916 		    grp_entry->ident[3],
917 		    idtype,
918 		    &iocd->stmf_error);
919 		mutex_exit(&stmf_state.stmf_lock);
920 		break;
921 	case STMF_IOCTL_REMOVE_HG_ENTRY:
922 		idtype = STMF_ID_TYPE_HOST;
923 		/* FALLTHROUGH */
924 	case STMF_IOCTL_REMOVE_TG_ENTRY:
925 		if (stmf_state.stmf_config_state == STMF_CONFIG_NONE) {
926 			ret = EACCES;
927 			iocd->stmf_error = STMF_IOCERR_UPDATE_NEED_CFG_INIT;
928 			break;
929 		}
930 		if (cmd == STMF_IOCTL_REMOVE_TG_ENTRY) {
931 			idtype = STMF_ID_TYPE_TARGET;
932 		}
933 		grp_entry = (stmf_group_op_data_t *)ibuf;
934 		if ((ibuf == NULL) ||
935 		    (iocd->stmf_ibuf_size < sizeof (stmf_group_op_data_t))) {
936 			ret = EINVAL;
937 			break;
938 		}
939 		if (grp_entry->group.name[0] == '*') {
940 			ret = EINVAL;
941 			break; /* not allowed */
942 		}
943 		mutex_enter(&stmf_state.stmf_lock);
944 		ret = stmf_remove_group_member(grp_entry->group.name,
945 		    grp_entry->group.name_size,
946 		    grp_entry->ident + 4,
947 		    grp_entry->ident[3],
948 		    idtype,
949 		    &iocd->stmf_error);
950 		mutex_exit(&stmf_state.stmf_lock);
951 		break;
952 	case STMF_IOCTL_CREATE_HOST_GROUP:
953 		idtype = STMF_ID_TYPE_HOST_GROUP;
954 		/* FALLTHROUGH */
955 	case STMF_IOCTL_CREATE_TARGET_GROUP:
956 		if (stmf_state.stmf_config_state == STMF_CONFIG_NONE) {
957 			ret = EACCES;
958 			iocd->stmf_error = STMF_IOCERR_UPDATE_NEED_CFG_INIT;
959 			break;
960 		}
961 		grpname = (stmf_group_name_t *)ibuf;
962 
963 		if (cmd == STMF_IOCTL_CREATE_TARGET_GROUP)
964 			idtype = STMF_ID_TYPE_TARGET_GROUP;
965 		if ((ibuf == NULL) ||
966 		    (iocd->stmf_ibuf_size < sizeof (stmf_group_name_t))) {
967 			ret = EINVAL;
968 			break;
969 		}
970 		if (grpname->name[0] == '*') {
971 			ret = EINVAL;
972 			break; /* not allowed */
973 		}
974 		mutex_enter(&stmf_state.stmf_lock);
975 		ret = stmf_add_group(grpname->name,
976 		    grpname->name_size, idtype, &iocd->stmf_error);
977 		mutex_exit(&stmf_state.stmf_lock);
978 		break;
979 	case STMF_IOCTL_REMOVE_HOST_GROUP:
980 		idtype = STMF_ID_TYPE_HOST_GROUP;
981 		/* FALLTHROUGH */
982 	case STMF_IOCTL_REMOVE_TARGET_GROUP:
983 		if (stmf_state.stmf_config_state == STMF_CONFIG_NONE) {
984 			ret = EACCES;
985 			iocd->stmf_error = STMF_IOCERR_UPDATE_NEED_CFG_INIT;
986 			break;
987 		}
988 		grpname = (stmf_group_name_t *)ibuf;
989 		if (cmd == STMF_IOCTL_REMOVE_TARGET_GROUP)
990 			idtype = STMF_ID_TYPE_TARGET_GROUP;
991 		if ((ibuf == NULL) ||
992 		    (iocd->stmf_ibuf_size < sizeof (stmf_group_name_t))) {
993 			ret = EINVAL;
994 			break;
995 		}
996 		if (grpname->name[0] == '*') {
997 			ret = EINVAL;
998 			break; /* not allowed */
999 		}
1000 		mutex_enter(&stmf_state.stmf_lock);
1001 		ret = stmf_remove_group(grpname->name,
1002 		    grpname->name_size, idtype, &iocd->stmf_error);
1003 		mutex_exit(&stmf_state.stmf_lock);
1004 		break;
1005 	case STMF_IOCTL_VALIDATE_VIEW:
1006 	case STMF_IOCTL_ADD_VIEW_ENTRY:
1007 		if (stmf_state.stmf_config_state == STMF_CONFIG_NONE) {
1008 			ret = EACCES;
1009 			iocd->stmf_error = STMF_IOCERR_UPDATE_NEED_CFG_INIT;
1010 			break;
1011 		}
1012 		ve = (stmf_view_op_entry_t *)ibuf;
1013 		if ((ibuf == NULL) ||
1014 		    (iocd->stmf_ibuf_size < sizeof (stmf_view_op_entry_t))) {
1015 			ret = EINVAL;
1016 			break;
1017 		}
1018 		if (!ve->ve_lu_number_valid)
1019 			ve->ve_lu_nbr[2] = 0xFF;
1020 		if (ve->ve_all_hosts) {
1021 			ve->ve_host_group.name[0] = '*';
1022 			ve->ve_host_group.name_size = 1;
1023 		}
1024 		if (ve->ve_all_targets) {
1025 			ve->ve_target_group.name[0] = '*';
1026 			ve->ve_target_group.name_size = 1;
1027 		}
1028 		if (ve->ve_ndx_valid)
1029 			veid = ve->ve_ndx;
1030 		else
1031 			veid = 0xffffffff;
1032 		mutex_enter(&stmf_state.stmf_lock);
1033 		if (cmd == STMF_IOCTL_ADD_VIEW_ENTRY) {
1034 			ret = stmf_add_ve(ve->ve_host_group.name,
1035 			    ve->ve_host_group.name_size,
1036 			    ve->ve_target_group.name,
1037 			    ve->ve_target_group.name_size,
1038 			    ve->ve_guid,
1039 			    &veid,
1040 			    ve->ve_lu_nbr,
1041 			    &iocd->stmf_error);
1042 		} else {  /* STMF_IOCTL_VALIDATE_VIEW */
1043 			ret = stmf_validate_lun_ve(ve->ve_host_group.name,
1044 			    ve->ve_host_group.name_size,
1045 			    ve->ve_target_group.name,
1046 			    ve->ve_target_group.name_size,
1047 			    ve->ve_lu_nbr,
1048 			    &iocd->stmf_error);
1049 		}
1050 		mutex_exit(&stmf_state.stmf_lock);
1051 		if (ret == 0 &&
1052 		    (!ve->ve_ndx_valid || !ve->ve_lu_number_valid) &&
1053 		    iocd->stmf_obuf_size >= sizeof (stmf_view_op_entry_t)) {
1054 			stmf_view_op_entry_t *ve_ret =
1055 			    (stmf_view_op_entry_t *)obuf;
1056 			iocd->stmf_obuf_nentries = 1;
1057 			iocd->stmf_obuf_max_nentries = 1;
1058 			if (!ve->ve_ndx_valid) {
1059 				ve_ret->ve_ndx = veid;
1060 				ve_ret->ve_ndx_valid = 1;
1061 			}
1062 			if (!ve->ve_lu_number_valid) {
1063 				ve_ret->ve_lu_number_valid = 1;
1064 				bcopy(ve->ve_lu_nbr, ve_ret->ve_lu_nbr, 8);
1065 			}
1066 		}
1067 		break;
1068 	case STMF_IOCTL_REMOVE_VIEW_ENTRY:
1069 		if (stmf_state.stmf_config_state == STMF_CONFIG_NONE) {
1070 			ret = EACCES;
1071 			iocd->stmf_error = STMF_IOCERR_UPDATE_NEED_CFG_INIT;
1072 			break;
1073 		}
1074 		ve = (stmf_view_op_entry_t *)ibuf;
1075 		if ((ibuf == NULL) ||
1076 		    (iocd->stmf_ibuf_size < sizeof (stmf_view_op_entry_t))) {
1077 			ret = EINVAL;
1078 			break;
1079 		}
1080 		if (!ve->ve_ndx_valid) {
1081 			ret = EINVAL;
1082 			break;
1083 		}
1084 		mutex_enter(&stmf_state.stmf_lock);
1085 		ret = stmf_remove_ve_by_id(ve->ve_guid, ve->ve_ndx,
1086 		    &iocd->stmf_error);
1087 		mutex_exit(&stmf_state.stmf_lock);
1088 		break;
1089 	case STMF_IOCTL_GET_HG_LIST:
1090 		id_list = &stmf_state.stmf_hg_list;
1091 		/* FALLTHROUGH */
1092 	case STMF_IOCTL_GET_TG_LIST:
1093 		if (cmd == STMF_IOCTL_GET_TG_LIST)
1094 			id_list = &stmf_state.stmf_tg_list;
1095 		mutex_enter(&stmf_state.stmf_lock);
1096 		iocd->stmf_obuf_max_nentries = id_list->id_count;
1097 		n = min(id_list->id_count,
1098 		    (iocd->stmf_obuf_size)/sizeof (stmf_group_name_t));
1099 		iocd->stmf_obuf_nentries = n;
1100 		id_entry = id_list->idl_head;
1101 		grpname = (stmf_group_name_t *)obuf;
1102 		for (i = 0; i < n; i++) {
1103 			if (id_entry->id_data[0] == '*') {
1104 				if (iocd->stmf_obuf_nentries > 0) {
1105 					iocd->stmf_obuf_nentries--;
1106 				}
1107 				id_entry = id_entry->id_next;
1108 				continue;
1109 			}
1110 			grpname->name_size = id_entry->id_data_size;
1111 			bcopy(id_entry->id_data, grpname->name,
1112 			    id_entry->id_data_size);
1113 			grpname++;
1114 			id_entry = id_entry->id_next;
1115 		}
1116 		mutex_exit(&stmf_state.stmf_lock);
1117 		break;
1118 	case STMF_IOCTL_GET_HG_ENTRIES:
1119 		id_list = &stmf_state.stmf_hg_list;
1120 		/* FALLTHROUGH */
1121 	case STMF_IOCTL_GET_TG_ENTRIES:
1122 		grpname = (stmf_group_name_t *)ibuf;
1123 		if ((ibuf == NULL) ||
1124 		    (iocd->stmf_ibuf_size < sizeof (stmf_group_name_t))) {
1125 			ret = EINVAL;
1126 			break;
1127 		}
1128 		if (cmd == STMF_IOCTL_GET_TG_ENTRIES) {
1129 			id_list = &stmf_state.stmf_tg_list;
1130 		}
1131 		mutex_enter(&stmf_state.stmf_lock);
1132 		id_entry = stmf_lookup_id(id_list, grpname->name_size,
1133 		    grpname->name);
1134 		if (!id_entry)
1135 			ret = ENODEV;
1136 		else {
1137 			stmf_ge_ident_t *grp_entry;
1138 			id_list = (stmf_id_list_t *)id_entry->id_impl_specific;
1139 			iocd->stmf_obuf_max_nentries = id_list->id_count;
1140 			n = min(id_list->id_count,
1141 			    iocd->stmf_obuf_size/sizeof (stmf_ge_ident_t));
1142 			iocd->stmf_obuf_nentries = n;
1143 			id_entry = id_list->idl_head;
1144 			grp_entry = (stmf_ge_ident_t *)obuf;
1145 			for (i = 0; i < n; i++) {
1146 				bcopy(id_entry->id_data, grp_entry->ident,
1147 				    id_entry->id_data_size);
1148 				grp_entry->ident_size = id_entry->id_data_size;
1149 				id_entry = id_entry->id_next;
1150 				grp_entry++;
1151 			}
1152 		}
1153 		mutex_exit(&stmf_state.stmf_lock);
1154 		break;
1155 
1156 	case STMF_IOCTL_GET_VE_LIST:
1157 		n = iocd->stmf_obuf_size/sizeof (stmf_view_op_entry_t);
1158 		mutex_enter(&stmf_state.stmf_lock);
1159 		ve = (stmf_view_op_entry_t *)obuf;
1160 		for (id_entry = stmf_state.stmf_luid_list.idl_head;
1161 		    id_entry; id_entry = id_entry->id_next) {
1162 			for (view_entry = (stmf_view_entry_t *)
1163 			    id_entry->id_impl_specific; view_entry;
1164 			    view_entry = view_entry->ve_next) {
1165 				iocd->stmf_obuf_max_nentries++;
1166 				if (iocd->stmf_obuf_nentries >= n)
1167 					continue;
1168 				ve->ve_ndx_valid = 1;
1169 				ve->ve_ndx = view_entry->ve_id;
1170 				ve->ve_lu_number_valid = 1;
1171 				bcopy(view_entry->ve_lun, ve->ve_lu_nbr, 8);
1172 				bcopy(view_entry->ve_luid->id_data, ve->ve_guid,
1173 				    view_entry->ve_luid->id_data_size);
1174 				if (view_entry->ve_hg->id_data[0] == '*') {
1175 					ve->ve_all_hosts = 1;
1176 				} else {
1177 					bcopy(view_entry->ve_hg->id_data,
1178 					    ve->ve_host_group.name,
1179 					    view_entry->ve_hg->id_data_size);
1180 					ve->ve_host_group.name_size =
1181 					    view_entry->ve_hg->id_data_size;
1182 				}
1183 
1184 				if (view_entry->ve_tg->id_data[0] == '*') {
1185 					ve->ve_all_targets = 1;
1186 				} else {
1187 					bcopy(view_entry->ve_tg->id_data,
1188 					    ve->ve_target_group.name,
1189 					    view_entry->ve_tg->id_data_size);
1190 					ve->ve_target_group.name_size =
1191 					    view_entry->ve_tg->id_data_size;
1192 				}
1193 				ve++;
1194 				iocd->stmf_obuf_nentries++;
1195 			}
1196 		}
1197 		mutex_exit(&stmf_state.stmf_lock);
1198 		break;
1199 
1200 	case STMF_IOCTL_LU_VE_LIST:
1201 		p_id = (uint8_t *)ibuf;
1202 		if ((iocd->stmf_ibuf_size != 16) ||
1203 		    (iocd->stmf_obuf_size < sizeof (stmf_view_op_entry_t))) {
1204 			ret = EINVAL;
1205 			break;
1206 		}
1207 
1208 		n = iocd->stmf_obuf_size/sizeof (stmf_view_op_entry_t);
1209 		mutex_enter(&stmf_state.stmf_lock);
1210 		ve = (stmf_view_op_entry_t *)obuf;
1211 		for (id_entry = stmf_state.stmf_luid_list.idl_head;
1212 		    id_entry; id_entry = id_entry->id_next) {
1213 			if (bcmp(id_entry->id_data, p_id, 16) != 0)
1214 				continue;
1215 			for (view_entry = (stmf_view_entry_t *)
1216 			    id_entry->id_impl_specific; view_entry;
1217 			    view_entry = view_entry->ve_next) {
1218 				iocd->stmf_obuf_max_nentries++;
1219 				if (iocd->stmf_obuf_nentries >= n)
1220 					continue;
1221 				ve->ve_ndx_valid = 1;
1222 				ve->ve_ndx = view_entry->ve_id;
1223 				ve->ve_lu_number_valid = 1;
1224 				bcopy(view_entry->ve_lun, ve->ve_lu_nbr, 8);
1225 				bcopy(view_entry->ve_luid->id_data, ve->ve_guid,
1226 				    view_entry->ve_luid->id_data_size);
1227 				if (view_entry->ve_hg->id_data[0] == '*') {
1228 					ve->ve_all_hosts = 1;
1229 				} else {
1230 					bcopy(view_entry->ve_hg->id_data,
1231 					    ve->ve_host_group.name,
1232 					    view_entry->ve_hg->id_data_size);
1233 					ve->ve_host_group.name_size =
1234 					    view_entry->ve_hg->id_data_size;
1235 				}
1236 
1237 				if (view_entry->ve_tg->id_data[0] == '*') {
1238 					ve->ve_all_targets = 1;
1239 				} else {
1240 					bcopy(view_entry->ve_tg->id_data,
1241 					    ve->ve_target_group.name,
1242 					    view_entry->ve_tg->id_data_size);
1243 					ve->ve_target_group.name_size =
1244 					    view_entry->ve_tg->id_data_size;
1245 				}
1246 				ve++;
1247 				iocd->stmf_obuf_nentries++;
1248 			}
1249 			break;
1250 		}
1251 		mutex_exit(&stmf_state.stmf_lock);
1252 		break;
1253 
1254 	case STMF_IOCTL_LOAD_PP_DATA:
1255 		if (stmf_state.stmf_config_state == STMF_CONFIG_NONE) {
1256 			ret = EACCES;
1257 			iocd->stmf_error = STMF_IOCERR_UPDATE_NEED_CFG_INIT;
1258 			break;
1259 		}
1260 		ppi = (stmf_ppioctl_data_t *)ibuf;
1261 		if ((ppi == NULL) ||
1262 		    (iocd->stmf_ibuf_size < sizeof (stmf_ppioctl_data_t))) {
1263 			ret = EINVAL;
1264 			break;
1265 		}
1266 		/* returned token */
1267 		ppi_token = (uint64_t *)obuf;
1268 		if ((ppi_token == NULL) ||
1269 		    (iocd->stmf_obuf_size < sizeof (uint64_t))) {
1270 			ret = EINVAL;
1271 			break;
1272 		}
1273 		ret = stmf_load_ppd_ioctl(ppi, ppi_token, &iocd->stmf_error);
1274 		break;
1275 
1276 	case STMF_IOCTL_GET_PP_DATA:
1277 		if (stmf_state.stmf_config_state == STMF_CONFIG_NONE) {
1278 			ret = EACCES;
1279 			iocd->stmf_error = STMF_IOCERR_UPDATE_NEED_CFG_INIT;
1280 			break;
1281 		}
1282 		ppi = (stmf_ppioctl_data_t *)ibuf;
1283 		if (ppi == NULL ||
1284 		    (iocd->stmf_ibuf_size < sizeof (stmf_ppioctl_data_t))) {
1285 			ret = EINVAL;
1286 			break;
1287 		}
1288 		ppi_out = (stmf_ppioctl_data_t *)obuf;
1289 		if ((ppi_out == NULL) ||
1290 		    (iocd->stmf_obuf_size < sizeof (stmf_ppioctl_data_t))) {
1291 			ret = EINVAL;
1292 			break;
1293 		}
1294 		ret = stmf_get_ppd_ioctl(ppi, ppi_out, &iocd->stmf_error);
1295 		break;
1296 
1297 	case STMF_IOCTL_CLEAR_PP_DATA:
1298 		if (stmf_state.stmf_config_state == STMF_CONFIG_NONE) {
1299 			ret = EACCES;
1300 			iocd->stmf_error = STMF_IOCERR_UPDATE_NEED_CFG_INIT;
1301 			break;
1302 		}
1303 		ppi = (stmf_ppioctl_data_t *)ibuf;
1304 		if ((ppi == NULL) ||
1305 		    (iocd->stmf_ibuf_size < sizeof (stmf_ppioctl_data_t))) {
1306 			ret = EINVAL;
1307 			break;
1308 		}
1309 		ret = stmf_delete_ppd_ioctl(ppi);
1310 		break;
1311 
1312 	case STMF_IOCTL_CLEAR_TRACE:
1313 		stmf_trace_clear();
1314 		break;
1315 
1316 	case STMF_IOCTL_ADD_TRACE:
1317 		if (iocd->stmf_ibuf_size && ibuf) {
1318 			((uint8_t *)ibuf)[iocd->stmf_ibuf_size - 1] = 0;
1319 			stmf_trace("\nstradm", "%s\n", ibuf);
1320 		}
1321 		break;
1322 
1323 	case STMF_IOCTL_GET_TRACE_POSITION:
1324 		if (obuf && (iocd->stmf_obuf_size > 3)) {
1325 			mutex_enter(&trace_buf_lock);
1326 			*((int *)obuf) = trace_buf_curndx;
1327 			mutex_exit(&trace_buf_lock);
1328 		} else {
1329 			ret = EINVAL;
1330 		}
1331 		break;
1332 
1333 	case STMF_IOCTL_GET_TRACE:
1334 		if ((iocd->stmf_obuf_size == 0) || (iocd->stmf_ibuf_size < 4)) {
1335 			ret = EINVAL;
1336 			break;
1337 		}
1338 		i = *((int *)ibuf);
1339 		if ((i > trace_buf_size) || ((i + iocd->stmf_obuf_size) >
1340 		    trace_buf_size)) {
1341 			ret = EINVAL;
1342 			break;
1343 		}
1344 		mutex_enter(&trace_buf_lock);
1345 		bcopy(stmf_trace_buf + i, obuf, iocd->stmf_obuf_size);
1346 		mutex_exit(&trace_buf_lock);
1347 		break;
1348 
1349 	default:
1350 		ret = ENOTTY;
1351 	}
1352 
1353 	if (ret == 0) {
1354 		ret = stmf_copyout_iocdata(data, mode, iocd, obuf);
1355 	} else if (iocd->stmf_error) {
1356 		(void) stmf_copyout_iocdata(data, mode, iocd, obuf);
1357 	}
1358 	if (obuf) {
1359 		kmem_free(obuf, iocd->stmf_obuf_size);
1360 		obuf = NULL;
1361 	}
1362 	if (ibuf) {
1363 		kmem_free(ibuf, iocd->stmf_ibuf_size);
1364 		ibuf = NULL;
1365 	}
1366 	kmem_free(iocd, sizeof (stmf_iocdata_t));
1367 	return (ret);
1368 }
1369 
1370 static int
1371 stmf_get_service_state()
1372 {
1373 	stmf_i_local_port_t *ilport;
1374 	stmf_i_lu_t *ilu;
1375 	int online = 0;
1376 	int offline = 0;
1377 	int onlining = 0;
1378 	int offlining = 0;
1379 
1380 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
1381 	for (ilport = stmf_state.stmf_ilportlist; ilport != NULL;
1382 	    ilport = ilport->ilport_next) {
1383 		if (ilport->ilport_state == STMF_STATE_OFFLINE)
1384 			offline++;
1385 		else if (ilport->ilport_state == STMF_STATE_ONLINE)
1386 			online++;
1387 		else if (ilport->ilport_state == STMF_STATE_ONLINING)
1388 			onlining++;
1389 		else if (ilport->ilport_state == STMF_STATE_OFFLINING)
1390 			offlining++;
1391 	}
1392 
1393 	for (ilu = stmf_state.stmf_ilulist; ilu != NULL;
1394 	    ilu = ilu->ilu_next) {
1395 		if (ilu->ilu_state == STMF_STATE_OFFLINE)
1396 			offline++;
1397 		else if (ilu->ilu_state == STMF_STATE_ONLINE)
1398 			online++;
1399 		else if (ilu->ilu_state == STMF_STATE_ONLINING)
1400 			onlining++;
1401 		else if (ilu->ilu_state == STMF_STATE_OFFLINING)
1402 			offlining++;
1403 	}
1404 
1405 	if (stmf_state.stmf_service_running) {
1406 		if (onlining)
1407 			return (STMF_STATE_ONLINING);
1408 		else
1409 			return (STMF_STATE_ONLINE);
1410 	}
1411 
1412 	if (offlining) {
1413 		return (STMF_STATE_OFFLINING);
1414 	}
1415 
1416 	return (STMF_STATE_OFFLINE);
1417 }
1418 
1419 static int
1420 stmf_set_stmf_state(stmf_state_desc_t *std)
1421 {
1422 	stmf_i_local_port_t *ilport;
1423 	stmf_i_lu_t *ilu;
1424 	stmf_state_change_info_t ssi;
1425 	int svc_state;
1426 
1427 	ssi.st_rflags = STMF_RFLAG_USER_REQUEST;
1428 	ssi.st_additional_info = NULL;
1429 
1430 	mutex_enter(&stmf_state.stmf_lock);
1431 	if (!stmf_state.stmf_exclusive_open) {
1432 		mutex_exit(&stmf_state.stmf_lock);
1433 		return (EACCES);
1434 	}
1435 
1436 	if (stmf_state.stmf_inventory_locked) {
1437 		mutex_exit(&stmf_state.stmf_lock);
1438 		return (EBUSY);
1439 	}
1440 
1441 	if ((std->state != STMF_STATE_ONLINE) &&
1442 	    (std->state != STMF_STATE_OFFLINE)) {
1443 		mutex_exit(&stmf_state.stmf_lock);
1444 		return (EINVAL);
1445 	}
1446 
1447 	svc_state = stmf_get_service_state();
1448 	if ((svc_state == STMF_STATE_OFFLINING) ||
1449 	    (svc_state == STMF_STATE_ONLINING)) {
1450 		mutex_exit(&stmf_state.stmf_lock);
1451 		return (EBUSY);
1452 	}
1453 
1454 	if (svc_state == STMF_STATE_OFFLINE) {
1455 		if (std->config_state == STMF_CONFIG_INIT) {
1456 			if (std->state != STMF_STATE_OFFLINE) {
1457 				mutex_exit(&stmf_state.stmf_lock);
1458 				return (EINVAL);
1459 			}
1460 			stmf_state.stmf_config_state = STMF_CONFIG_INIT;
1461 			stmf_delete_all_ppds();
1462 			stmf_view_clear_config();
1463 			stmf_view_init();
1464 			mutex_exit(&stmf_state.stmf_lock);
1465 			return (0);
1466 		}
1467 		if ((stmf_state.stmf_config_state == STMF_CONFIG_INIT) ||
1468 		    (stmf_state.stmf_config_state == STMF_CONFIG_NONE)) {
1469 			if (std->config_state != STMF_CONFIG_INIT_DONE) {
1470 				mutex_exit(&stmf_state.stmf_lock);
1471 				return (EINVAL);
1472 			}
1473 			stmf_state.stmf_config_state = STMF_CONFIG_INIT_DONE;
1474 		}
1475 		if (std->state == STMF_STATE_OFFLINE) {
1476 			mutex_exit(&stmf_state.stmf_lock);
1477 			return (0);
1478 		}
1479 		if (stmf_state.stmf_config_state == STMF_CONFIG_INIT) {
1480 			mutex_exit(&stmf_state.stmf_lock);
1481 			return (EINVAL);
1482 		}
1483 		stmf_state.stmf_inventory_locked = 1;
1484 		stmf_state.stmf_service_running = 1;
1485 		mutex_exit(&stmf_state.stmf_lock);
1486 
1487 		for (ilport = stmf_state.stmf_ilportlist; ilport != NULL;
1488 		    ilport = ilport->ilport_next) {
1489 			if (ilport->ilport_prev_state != STMF_STATE_ONLINE)
1490 				continue;
1491 			(void) stmf_ctl(STMF_CMD_LPORT_ONLINE,
1492 			    ilport->ilport_lport, &ssi);
1493 		}
1494 
1495 		for (ilu = stmf_state.stmf_ilulist; ilu != NULL;
1496 		    ilu = ilu->ilu_next) {
1497 			if (ilu->ilu_prev_state != STMF_STATE_ONLINE)
1498 				continue;
1499 			(void) stmf_ctl(STMF_CMD_LU_ONLINE, ilu->ilu_lu, &ssi);
1500 		}
1501 		mutex_enter(&stmf_state.stmf_lock);
1502 		stmf_state.stmf_inventory_locked = 0;
1503 		mutex_exit(&stmf_state.stmf_lock);
1504 		return (0);
1505 	}
1506 
1507 	/* svc_state is STMF_STATE_ONLINE here */
1508 	if ((std->state != STMF_STATE_OFFLINE) ||
1509 	    (std->config_state == STMF_CONFIG_INIT)) {
1510 		mutex_exit(&stmf_state.stmf_lock);
1511 		return (EACCES);
1512 	}
1513 
1514 	stmf_state.stmf_inventory_locked = 1;
1515 	stmf_state.stmf_service_running = 0;
1516 
1517 	mutex_exit(&stmf_state.stmf_lock);
1518 	for (ilport = stmf_state.stmf_ilportlist; ilport != NULL;
1519 	    ilport = ilport->ilport_next) {
1520 		if (ilport->ilport_state != STMF_STATE_ONLINE)
1521 			continue;
1522 		(void) stmf_ctl(STMF_CMD_LPORT_OFFLINE,
1523 		    ilport->ilport_lport, &ssi);
1524 	}
1525 
1526 	for (ilu = stmf_state.stmf_ilulist; ilu != NULL;
1527 	    ilu = ilu->ilu_next) {
1528 		if (ilu->ilu_state != STMF_STATE_ONLINE)
1529 			continue;
1530 		(void) stmf_ctl(STMF_CMD_LU_OFFLINE, ilu->ilu_lu, &ssi);
1531 	}
1532 	mutex_enter(&stmf_state.stmf_lock);
1533 	stmf_state.stmf_inventory_locked = 0;
1534 	mutex_exit(&stmf_state.stmf_lock);
1535 	return (0);
1536 }
1537 
1538 static int
1539 stmf_get_stmf_state(stmf_state_desc_t *std)
1540 {
1541 	mutex_enter(&stmf_state.stmf_lock);
1542 	std->state = stmf_get_service_state();
1543 	std->config_state = stmf_state.stmf_config_state;
1544 	mutex_exit(&stmf_state.stmf_lock);
1545 
1546 	return (0);
1547 }
1548 
1549 /*
1550  * handles registration message from pppt for a logical unit
1551  */
1552 stmf_status_t
1553 stmf_ic_lu_reg(stmf_ic_reg_dereg_lun_msg_t *msg, uint32_t type)
1554 {
1555 	stmf_i_lu_provider_t	*ilp;
1556 	stmf_lu_provider_t	*lp;
1557 	mutex_enter(&stmf_state.stmf_lock);
1558 	for (ilp = stmf_state.stmf_ilplist; ilp != NULL; ilp = ilp->ilp_next) {
1559 		if (strcmp(msg->icrl_lu_provider_name,
1560 		    ilp->ilp_lp->lp_name) == 0) {
1561 			lp = ilp->ilp_lp;
1562 			mutex_exit(&stmf_state.stmf_lock);
1563 			lp->lp_proxy_msg(msg->icrl_lun_id, msg->icrl_cb_arg,
1564 			    msg->icrl_cb_arg_len, type);
1565 			return (STMF_SUCCESS);
1566 		}
1567 	}
1568 	mutex_exit(&stmf_state.stmf_lock);
1569 	return (STMF_SUCCESS);
1570 }
1571 
1572 /*
1573  * handles de-registration message from pppt for a logical unit
1574  */
1575 stmf_status_t
1576 stmf_ic_lu_dereg(stmf_ic_reg_dereg_lun_msg_t *msg)
1577 {
1578 	stmf_i_lu_provider_t	*ilp;
1579 	stmf_lu_provider_t	*lp;
1580 	mutex_enter(&stmf_state.stmf_lock);
1581 	for (ilp = stmf_state.stmf_ilplist; ilp != NULL; ilp = ilp->ilp_next) {
1582 		if (strcmp(msg->icrl_lu_provider_name,
1583 		    ilp->ilp_lp->lp_name) == 0) {
1584 			lp = ilp->ilp_lp;
1585 			mutex_exit(&stmf_state.stmf_lock);
1586 			lp->lp_proxy_msg(msg->icrl_lun_id, NULL, 0,
1587 			    STMF_MSG_LU_DEREGISTER);
1588 			return (STMF_SUCCESS);
1589 		}
1590 	}
1591 	mutex_exit(&stmf_state.stmf_lock);
1592 	return (STMF_SUCCESS);
1593 }
1594 
1595 /*
1596  * helper function to find a task that matches a task_msgid
1597  */
1598 scsi_task_t *
1599 find_task_from_msgid(uint8_t *lu_id, stmf_ic_msgid_t task_msgid)
1600 {
1601 	stmf_i_lu_t *ilu;
1602 	stmf_i_scsi_task_t *itask;
1603 
1604 	mutex_enter(&stmf_state.stmf_lock);
1605 	for (ilu = stmf_state.stmf_ilulist; ilu != NULL; ilu = ilu->ilu_next) {
1606 		if (bcmp(lu_id, ilu->ilu_lu->lu_id->ident, 16) == 0) {
1607 			break;
1608 		}
1609 	}
1610 
1611 	if (ilu == NULL) {
1612 		mutex_exit(&stmf_state.stmf_lock);
1613 		return (NULL);
1614 	}
1615 
1616 	mutex_enter(&ilu->ilu_task_lock);
1617 	for (itask = ilu->ilu_tasks; itask != NULL;
1618 	    itask = itask->itask_lu_next) {
1619 		if (itask->itask_flags & (ITASK_IN_FREE_LIST |
1620 		    ITASK_BEING_ABORTED)) {
1621 			continue;
1622 		}
1623 		if (itask->itask_proxy_msg_id == task_msgid) {
1624 			break;
1625 		}
1626 	}
1627 	mutex_exit(&ilu->ilu_task_lock);
1628 	mutex_exit(&stmf_state.stmf_lock);
1629 
1630 	if (itask != NULL) {
1631 		return (itask->itask_task);
1632 	} else {
1633 		/* task not found. Likely already aborted. */
1634 		return (NULL);
1635 	}
1636 }
1637 
1638 /*
1639  * message received from pppt/ic
1640  */
1641 stmf_status_t
1642 stmf_msg_rx(stmf_ic_msg_t *msg)
1643 {
1644 	mutex_enter(&stmf_state.stmf_lock);
1645 	if (stmf_state.stmf_alua_state != 1) {
1646 		mutex_exit(&stmf_state.stmf_lock);
1647 		cmn_err(CE_WARN, "stmf alua state is disabled");
1648 		ic_msg_free(msg);
1649 		return (STMF_FAILURE);
1650 	}
1651 	mutex_exit(&stmf_state.stmf_lock);
1652 
1653 	switch (msg->icm_msg_type) {
1654 		case STMF_ICM_REGISTER_LUN:
1655 			(void) stmf_ic_lu_reg(
1656 			    (stmf_ic_reg_dereg_lun_msg_t *)msg->icm_msg,
1657 			    STMF_MSG_LU_REGISTER);
1658 			break;
1659 		case STMF_ICM_LUN_ACTIVE:
1660 			(void) stmf_ic_lu_reg(
1661 			    (stmf_ic_reg_dereg_lun_msg_t *)msg->icm_msg,
1662 			    STMF_MSG_LU_ACTIVE);
1663 			break;
1664 		case STMF_ICM_DEREGISTER_LUN:
1665 			(void) stmf_ic_lu_dereg(
1666 			    (stmf_ic_reg_dereg_lun_msg_t *)msg->icm_msg);
1667 			break;
1668 		case STMF_ICM_SCSI_DATA:
1669 			(void) stmf_ic_rx_scsi_data(
1670 			    (stmf_ic_scsi_data_msg_t *)msg->icm_msg);
1671 			break;
1672 		case STMF_ICM_SCSI_STATUS:
1673 			(void) stmf_ic_rx_scsi_status(
1674 			    (stmf_ic_scsi_status_msg_t *)msg->icm_msg);
1675 			break;
1676 		case STMF_ICM_STATUS:
1677 			(void) stmf_ic_rx_status(
1678 			    (stmf_ic_status_msg_t *)msg->icm_msg);
1679 			break;
1680 		default:
1681 			cmn_err(CE_WARN, "unknown message received %d",
1682 			    msg->icm_msg_type);
1683 			ic_msg_free(msg);
1684 			return (STMF_FAILURE);
1685 	}
1686 	ic_msg_free(msg);
1687 	return (STMF_SUCCESS);
1688 }
1689 
1690 stmf_status_t
1691 stmf_ic_rx_status(stmf_ic_status_msg_t *msg)
1692 {
1693 	stmf_i_local_port_t *ilport;
1694 
1695 	if (msg->ics_msg_type != STMF_ICM_REGISTER_PROXY_PORT) {
1696 		/* for now, ignore other message status */
1697 		return (STMF_SUCCESS);
1698 	}
1699 
1700 	if (msg->ics_status != STMF_SUCCESS) {
1701 		return (STMF_SUCCESS);
1702 	}
1703 
1704 	mutex_enter(&stmf_state.stmf_lock);
1705 	for (ilport = stmf_state.stmf_ilportlist; ilport != NULL;
1706 	    ilport = ilport->ilport_next) {
1707 		if (msg->ics_msgid == ilport->ilport_reg_msgid) {
1708 			ilport->ilport_proxy_registered = 1;
1709 			break;
1710 		}
1711 	}
1712 	mutex_exit(&stmf_state.stmf_lock);
1713 	return (STMF_SUCCESS);
1714 }
1715 
1716 /*
1717  * handles scsi status message from pppt
1718  */
1719 stmf_status_t
1720 stmf_ic_rx_scsi_status(stmf_ic_scsi_status_msg_t *msg)
1721 {
1722 	scsi_task_t *task;
1723 
1724 	/* is this a task management command */
1725 	if (msg->icss_task_msgid & MSG_ID_TM_BIT) {
1726 		return (STMF_SUCCESS);
1727 	}
1728 
1729 	task = find_task_from_msgid(msg->icss_lun_id, msg->icss_task_msgid);
1730 
1731 	if (task == NULL) {
1732 		return (STMF_SUCCESS);
1733 	}
1734 
1735 	task->task_scsi_status = msg->icss_status;
1736 	task->task_sense_data = msg->icss_sense;
1737 	task->task_sense_length = msg->icss_sense_len;
1738 	(void) stmf_send_scsi_status(task, STMF_IOF_LU_DONE);
1739 
1740 	return (STMF_SUCCESS);
1741 }
1742 
1743 /*
1744  * handles scsi data message from pppt
1745  */
1746 stmf_status_t
1747 stmf_ic_rx_scsi_data(stmf_ic_scsi_data_msg_t *msg)
1748 {
1749 	stmf_i_scsi_task_t *itask;
1750 	scsi_task_t *task;
1751 	stmf_xfer_data_t *xd = NULL;
1752 	stmf_data_buf_t *dbuf;
1753 	uint32_t sz, minsz, xd_sz, asz;
1754 
1755 	/* is this a task management command */
1756 	if (msg->icsd_task_msgid & MSG_ID_TM_BIT) {
1757 		return (STMF_SUCCESS);
1758 	}
1759 
1760 	task = find_task_from_msgid(msg->icsd_lun_id, msg->icsd_task_msgid);
1761 	if (task == NULL) {
1762 		stmf_ic_msg_t *ic_xfer_done_msg = NULL;
1763 		static uint64_t data_msg_id;
1764 		stmf_status_t ic_ret = STMF_FAILURE;
1765 		mutex_enter(&stmf_state.stmf_lock);
1766 		data_msg_id = stmf_proxy_msg_id++;
1767 		mutex_exit(&stmf_state.stmf_lock);
1768 		/*
1769 		 * send xfer done status to pppt
1770 		 * for now, set the session id to 0 as we cannot
1771 		 * ascertain it since we cannot find the task
1772 		 */
1773 		ic_xfer_done_msg = ic_scsi_data_xfer_done_msg_alloc(
1774 		    msg->icsd_task_msgid, 0, STMF_FAILURE, data_msg_id);
1775 		if (ic_xfer_done_msg) {
1776 			ic_ret = ic_tx_msg(ic_xfer_done_msg);
1777 			if (ic_ret != STMF_IC_MSG_SUCCESS) {
1778 				cmn_err(CE_WARN, "unable to xmit proxy msg");
1779 			}
1780 		}
1781 		return (STMF_FAILURE);
1782 	}
1783 
1784 	itask = (stmf_i_scsi_task_t *)task->task_stmf_private;
1785 	dbuf = itask->itask_proxy_dbuf;
1786 
1787 	task->task_cmd_xfer_length = msg->icsd_data_len;
1788 
1789 	if (task->task_additional_flags &
1790 	    TASK_AF_NO_EXPECTED_XFER_LENGTH) {
1791 		task->task_expected_xfer_length =
1792 		    task->task_cmd_xfer_length;
1793 	}
1794 
1795 	sz = min(task->task_expected_xfer_length,
1796 	    task->task_cmd_xfer_length);
1797 
1798 	xd_sz = msg->icsd_data_len;
1799 	asz = xd_sz + sizeof (*xd) - 4;
1800 	xd = (stmf_xfer_data_t *)kmem_zalloc(asz, KM_NOSLEEP);
1801 
1802 	if (xd == NULL) {
1803 		stmf_abort(STMF_QUEUE_TASK_ABORT, task,
1804 		    STMF_ALLOC_FAILURE, NULL);
1805 		return (STMF_FAILURE);
1806 	}
1807 
1808 	xd->alloc_size = asz;
1809 	xd->size_left = xd_sz;
1810 	bcopy(msg->icsd_data, xd->buf, xd_sz);
1811 
1812 	sz = min(sz, xd->size_left);
1813 	xd->size_left = sz;
1814 	minsz = min(512, sz);
1815 
1816 	if (dbuf == NULL)
1817 		dbuf = stmf_alloc_dbuf(task, sz, &minsz, 0);
1818 	if (dbuf == NULL) {
1819 		kmem_free(xd, xd->alloc_size);
1820 		stmf_abort(STMF_QUEUE_TASK_ABORT, task,
1821 		    STMF_ALLOC_FAILURE, NULL);
1822 		return (STMF_FAILURE);
1823 	}
1824 	dbuf->db_lu_private = xd;
1825 	stmf_xd_to_dbuf(dbuf);
1826 
1827 	dbuf->db_flags = DB_DIRECTION_TO_RPORT;
1828 	(void) stmf_xfer_data(task, dbuf, 0);
1829 	return (STMF_SUCCESS);
1830 }
1831 
1832 stmf_status_t
1833 stmf_proxy_scsi_cmd(scsi_task_t *task, stmf_data_buf_t *dbuf)
1834 {
1835 	stmf_i_scsi_task_t *itask =
1836 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
1837 	stmf_i_local_port_t *ilport =
1838 	    (stmf_i_local_port_t *)task->task_lport->lport_stmf_private;
1839 	stmf_ic_msg_t *ic_cmd_msg;
1840 	stmf_ic_msg_status_t ic_ret;
1841 	stmf_status_t ret = STMF_FAILURE;
1842 
1843 	if (stmf_state.stmf_alua_state != 1) {
1844 		cmn_err(CE_WARN, "stmf alua state is disabled");
1845 		return (STMF_FAILURE);
1846 	}
1847 
1848 	if (ilport->ilport_proxy_registered == 0) {
1849 		return (STMF_FAILURE);
1850 	}
1851 
1852 	mutex_enter(&stmf_state.stmf_lock);
1853 	itask->itask_proxy_msg_id = stmf_proxy_msg_id++;
1854 	mutex_exit(&stmf_state.stmf_lock);
1855 	itask->itask_proxy_dbuf = dbuf;
1856 
1857 	/*
1858 	 * stmf will now take over the task handling for this task
1859 	 * but it still needs to be treated differently from other
1860 	 * default handled tasks, hence the ITASK_PROXY_TASK.
1861 	 * If this is a task management function, we're really just
1862 	 * duping the command to the peer. Set the TM bit so that
1863 	 * we can recognize this on return since we won't be completing
1864 	 * the proxied task in that case.
1865 	 */
1866 	if (task->task_mgmt_function) {
1867 		itask->itask_proxy_msg_id |= MSG_ID_TM_BIT;
1868 	} else {
1869 		itask->itask_flags |= ITASK_DEFAULT_HANDLING | ITASK_PROXY_TASK;
1870 	}
1871 	if (dbuf) {
1872 		ic_cmd_msg = ic_scsi_cmd_msg_alloc(itask->itask_proxy_msg_id,
1873 		    task, dbuf->db_data_size, dbuf->db_sglist[0].seg_addr,
1874 		    itask->itask_proxy_msg_id);
1875 	} else {
1876 		ic_cmd_msg = ic_scsi_cmd_msg_alloc(itask->itask_proxy_msg_id,
1877 		    task, 0, NULL, itask->itask_proxy_msg_id);
1878 	}
1879 	if (ic_cmd_msg) {
1880 		ic_ret = ic_tx_msg(ic_cmd_msg);
1881 		if (ic_ret == STMF_IC_MSG_SUCCESS) {
1882 			ret = STMF_SUCCESS;
1883 		}
1884 	}
1885 	return (ret);
1886 }
1887 
1888 
1889 stmf_status_t
1890 pppt_modload()
1891 {
1892 	int error;
1893 
1894 	if (pppt_mod == NULL && ((pppt_mod =
1895 	    ddi_modopen("drv/pppt", KRTLD_MODE_FIRST, &error)) == NULL)) {
1896 		cmn_err(CE_WARN, "Unable to load pppt");
1897 		return (STMF_FAILURE);
1898 	}
1899 
1900 	if (ic_reg_port_msg_alloc == NULL && ((ic_reg_port_msg_alloc =
1901 	    (stmf_ic_reg_port_msg_alloc_func_t)
1902 	    ddi_modsym(pppt_mod, "stmf_ic_reg_port_msg_alloc",
1903 	    &error)) == NULL)) {
1904 		cmn_err(CE_WARN,
1905 		    "Unable to find symbol - stmf_ic_reg_port_msg_alloc");
1906 		return (STMF_FAILURE);
1907 	}
1908 
1909 
1910 	if (ic_dereg_port_msg_alloc == NULL && ((ic_dereg_port_msg_alloc =
1911 	    (stmf_ic_dereg_port_msg_alloc_func_t)
1912 	    ddi_modsym(pppt_mod, "stmf_ic_dereg_port_msg_alloc",
1913 	    &error)) == NULL)) {
1914 		cmn_err(CE_WARN,
1915 		    "Unable to find symbol - stmf_ic_dereg_port_msg_alloc");
1916 		return (STMF_FAILURE);
1917 	}
1918 
1919 	if (ic_reg_lun_msg_alloc == NULL && ((ic_reg_lun_msg_alloc =
1920 	    (stmf_ic_reg_lun_msg_alloc_func_t)
1921 	    ddi_modsym(pppt_mod, "stmf_ic_reg_lun_msg_alloc",
1922 	    &error)) == NULL)) {
1923 		cmn_err(CE_WARN,
1924 		    "Unable to find symbol - stmf_ic_reg_lun_msg_alloc");
1925 		return (STMF_FAILURE);
1926 	}
1927 
1928 	if (ic_lun_active_msg_alloc == NULL && ((ic_lun_active_msg_alloc =
1929 	    (stmf_ic_lun_active_msg_alloc_func_t)
1930 	    ddi_modsym(pppt_mod, "stmf_ic_lun_active_msg_alloc",
1931 	    &error)) == NULL)) {
1932 		cmn_err(CE_WARN,
1933 		    "Unable to find symbol - stmf_ic_lun_active_msg_alloc");
1934 		return (STMF_FAILURE);
1935 	}
1936 
1937 	if (ic_dereg_lun_msg_alloc == NULL && ((ic_dereg_lun_msg_alloc =
1938 	    (stmf_ic_dereg_lun_msg_alloc_func_t)
1939 	    ddi_modsym(pppt_mod, "stmf_ic_dereg_lun_msg_alloc",
1940 	    &error)) == NULL)) {
1941 		cmn_err(CE_WARN,
1942 		    "Unable to find symbol - stmf_ic_dereg_lun_msg_alloc");
1943 		return (STMF_FAILURE);
1944 	}
1945 
1946 	if (ic_scsi_cmd_msg_alloc == NULL && ((ic_scsi_cmd_msg_alloc =
1947 	    (stmf_ic_scsi_cmd_msg_alloc_func_t)
1948 	    ddi_modsym(pppt_mod, "stmf_ic_scsi_cmd_msg_alloc",
1949 	    &error)) == NULL)) {
1950 		cmn_err(CE_WARN,
1951 		    "Unable to find symbol - stmf_ic_scsi_cmd_msg_alloc");
1952 		return (STMF_FAILURE);
1953 	}
1954 
1955 	if (ic_scsi_data_xfer_done_msg_alloc == NULL &&
1956 	    ((ic_scsi_data_xfer_done_msg_alloc =
1957 	    (stmf_ic_scsi_data_xfer_done_msg_alloc_func_t)
1958 	    ddi_modsym(pppt_mod, "stmf_ic_scsi_data_xfer_done_msg_alloc",
1959 	    &error)) == NULL)) {
1960 		cmn_err(CE_WARN,
1961 		    "Unable to find symbol -"
1962 		    "stmf_ic_scsi_data_xfer_done_msg_alloc");
1963 		return (STMF_FAILURE);
1964 	}
1965 
1966 	if (ic_session_reg_msg_alloc == NULL &&
1967 	    ((ic_session_reg_msg_alloc =
1968 	    (stmf_ic_session_create_msg_alloc_func_t)
1969 	    ddi_modsym(pppt_mod, "stmf_ic_session_create_msg_alloc",
1970 	    &error)) == NULL)) {
1971 		cmn_err(CE_WARN,
1972 		    "Unable to find symbol -"
1973 		    "stmf_ic_session_create_msg_alloc");
1974 		return (STMF_FAILURE);
1975 	}
1976 
1977 	if (ic_session_dereg_msg_alloc == NULL &&
1978 	    ((ic_session_dereg_msg_alloc =
1979 	    (stmf_ic_session_destroy_msg_alloc_func_t)
1980 	    ddi_modsym(pppt_mod, "stmf_ic_session_destroy_msg_alloc",
1981 	    &error)) == NULL)) {
1982 		cmn_err(CE_WARN,
1983 		    "Unable to find symbol -"
1984 		    "stmf_ic_session_destroy_msg_alloc");
1985 		return (STMF_FAILURE);
1986 	}
1987 
1988 	if (ic_tx_msg == NULL && ((ic_tx_msg =
1989 	    (stmf_ic_tx_msg_func_t)ddi_modsym(pppt_mod, "stmf_ic_tx_msg",
1990 	    &error)) == NULL)) {
1991 		cmn_err(CE_WARN, "Unable to find symbol - stmf_ic_tx_msg");
1992 		return (STMF_FAILURE);
1993 	}
1994 
1995 	if (ic_msg_free == NULL && ((ic_msg_free =
1996 	    (stmf_ic_msg_free_func_t)ddi_modsym(pppt_mod, "stmf_ic_msg_free",
1997 	    &error)) == NULL)) {
1998 		cmn_err(CE_WARN, "Unable to find symbol - stmf_ic_msg_free");
1999 		return (STMF_FAILURE);
2000 	}
2001 	return (STMF_SUCCESS);
2002 }
2003 
2004 static void
2005 stmf_get_alua_state(stmf_alua_state_desc_t *alua_state)
2006 {
2007 	mutex_enter(&stmf_state.stmf_lock);
2008 	alua_state->alua_node = stmf_state.stmf_alua_node;
2009 	alua_state->alua_state = stmf_state.stmf_alua_state;
2010 	mutex_exit(&stmf_state.stmf_lock);
2011 }
2012 
2013 
2014 static int
2015 stmf_set_alua_state(stmf_alua_state_desc_t *alua_state)
2016 {
2017 	stmf_i_local_port_t *ilport;
2018 	stmf_i_lu_t *ilu;
2019 	stmf_lu_t *lu;
2020 	stmf_ic_msg_status_t ic_ret;
2021 	stmf_ic_msg_t *ic_reg_lun, *ic_reg_port;
2022 	stmf_local_port_t *lport;
2023 	int ret = 0;
2024 
2025 	if (alua_state->alua_state > 1 || alua_state->alua_node > 1) {
2026 		return (EINVAL);
2027 	}
2028 
2029 	mutex_enter(&stmf_state.stmf_lock);
2030 	if (alua_state->alua_state == 1) {
2031 		if (pppt_modload() == STMF_FAILURE) {
2032 			ret = EIO;
2033 			goto err;
2034 		}
2035 		if (alua_state->alua_node != 0) {
2036 			/* reset existing rtpids to new base */
2037 			stmf_rtpid_counter = 255;
2038 		}
2039 		stmf_state.stmf_alua_node = alua_state->alua_node;
2040 		stmf_state.stmf_alua_state = 1;
2041 		/* register existing local ports with ppp */
2042 		for (ilport = stmf_state.stmf_ilportlist; ilport != NULL;
2043 		    ilport = ilport->ilport_next) {
2044 			/* skip standby ports and non-alua participants */
2045 			if (ilport->ilport_standby == 1 ||
2046 			    ilport->ilport_alua == 0) {
2047 				continue;
2048 			}
2049 			if (alua_state->alua_node != 0) {
2050 				ilport->ilport_rtpid =
2051 				    atomic_add_16_nv(&stmf_rtpid_counter, 1);
2052 			}
2053 			lport = ilport->ilport_lport;
2054 			ic_reg_port = ic_reg_port_msg_alloc(
2055 			    lport->lport_id, ilport->ilport_rtpid,
2056 			    0, NULL, stmf_proxy_msg_id);
2057 			if (ic_reg_port) {
2058 				ic_ret = ic_tx_msg(ic_reg_port);
2059 				if (ic_ret == STMF_IC_MSG_SUCCESS) {
2060 					ilport->ilport_reg_msgid =
2061 					    stmf_proxy_msg_id++;
2062 				} else {
2063 					cmn_err(CE_WARN,
2064 					    "error on port registration "
2065 					    "port - %s",
2066 					    ilport->ilport_kstat_tgt_name);
2067 				}
2068 			}
2069 		}
2070 		/* register existing logical units */
2071 		for (ilu = stmf_state.stmf_ilulist; ilu != NULL;
2072 		    ilu = ilu->ilu_next) {
2073 			if (ilu->ilu_access != STMF_LU_ACTIVE) {
2074 				continue;
2075 			}
2076 			/* register with proxy module */
2077 			lu = ilu->ilu_lu;
2078 			if (lu->lu_lp && lu->lu_lp->lp_lpif_rev == LPIF_REV_2 &&
2079 			    lu->lu_lp->lp_alua_support) {
2080 				ilu->ilu_alua = 1;
2081 				/* allocate the register message */
2082 				ic_reg_lun = ic_reg_lun_msg_alloc(
2083 				    lu->lu_id->ident, lu->lu_lp->lp_name,
2084 				    lu->lu_proxy_reg_arg_len,
2085 				    (uint8_t *)lu->lu_proxy_reg_arg,
2086 				    stmf_proxy_msg_id);
2087 				/* send the message */
2088 				if (ic_reg_lun) {
2089 					ic_ret = ic_tx_msg(ic_reg_lun);
2090 					if (ic_ret == STMF_IC_MSG_SUCCESS) {
2091 						stmf_proxy_msg_id++;
2092 					}
2093 				}
2094 			}
2095 		}
2096 	} else {
2097 		stmf_state.stmf_alua_state = 0;
2098 	}
2099 
2100 err:
2101 	mutex_exit(&stmf_state.stmf_lock);
2102 	return (ret);
2103 }
2104 
2105 
2106 typedef struct {
2107 	void	*bp;	/* back pointer from internal struct to main struct */
2108 	int	alloc_size;
2109 } __istmf_t;
2110 
2111 typedef struct {
2112 	__istmf_t	*fp;	/* Framework private */
2113 	void		*cp;	/* Caller private */
2114 	void		*ss;	/* struct specific */
2115 } __stmf_t;
2116 
2117 static struct {
2118 	int shared;
2119 	int fw_private;
2120 } stmf_sizes[] = { { 0, 0 },
2121 	{ GET_STRUCT_SIZE(stmf_lu_provider_t),
2122 		GET_STRUCT_SIZE(stmf_i_lu_provider_t) },
2123 	{ GET_STRUCT_SIZE(stmf_port_provider_t),
2124 		GET_STRUCT_SIZE(stmf_i_port_provider_t) },
2125 	{ GET_STRUCT_SIZE(stmf_local_port_t),
2126 		GET_STRUCT_SIZE(stmf_i_local_port_t) },
2127 	{ GET_STRUCT_SIZE(stmf_lu_t),
2128 		GET_STRUCT_SIZE(stmf_i_lu_t) },
2129 	{ GET_STRUCT_SIZE(stmf_scsi_session_t),
2130 		GET_STRUCT_SIZE(stmf_i_scsi_session_t) },
2131 	{ GET_STRUCT_SIZE(scsi_task_t),
2132 		GET_STRUCT_SIZE(stmf_i_scsi_task_t) },
2133 	{ GET_STRUCT_SIZE(stmf_data_buf_t),
2134 		GET_STRUCT_SIZE(__istmf_t) },
2135 	{ GET_STRUCT_SIZE(stmf_dbuf_store_t),
2136 		GET_STRUCT_SIZE(__istmf_t) }
2137 
2138 };
2139 
2140 void *
2141 stmf_alloc(stmf_struct_id_t struct_id, int additional_size, int flags)
2142 {
2143 	int stmf_size;
2144 	int kmem_flag;
2145 	__stmf_t *sh;
2146 
2147 	if ((struct_id == 0) || (struct_id >= STMF_MAX_STRUCT_IDS))
2148 		return (NULL);
2149 
2150 	if ((curthread->t_flag & T_INTR_THREAD) || (flags & AF_FORCE_NOSLEEP)) {
2151 		kmem_flag = KM_NOSLEEP;
2152 	} else {
2153 		kmem_flag = KM_SLEEP;
2154 	}
2155 
2156 	additional_size = (additional_size + 7) & (~7);
2157 	stmf_size = stmf_sizes[struct_id].shared +
2158 	    stmf_sizes[struct_id].fw_private + additional_size;
2159 
2160 	sh = (__stmf_t *)kmem_zalloc(stmf_size, kmem_flag);
2161 
2162 	if (sh == NULL)
2163 		return (NULL);
2164 
2165 	/*
2166 	 * In principle, the implementation inside stmf_alloc should not
2167 	 * be changed anyway. But the original order of framework private
2168 	 * data and caller private data does not support sglist in the caller
2169 	 * private data.
2170 	 * To work around this, the memory segments of framework private
2171 	 * data and caller private data are re-ordered here.
2172 	 * A better solution is to provide a specific interface to allocate
2173 	 * the sglist, then we will not need this workaround any more.
2174 	 * But before the new interface is available, the memory segment
2175 	 * ordering should be kept as is.
2176 	 */
2177 	sh->cp = GET_BYTE_OFFSET(sh, stmf_sizes[struct_id].shared);
2178 	sh->fp = (__istmf_t *)GET_BYTE_OFFSET(sh,
2179 	    stmf_sizes[struct_id].shared + additional_size);
2180 
2181 	sh->fp->bp = sh;
2182 	/* Just store the total size instead of storing additional size */
2183 	sh->fp->alloc_size = stmf_size;
2184 
2185 	return (sh);
2186 }
2187 
2188 void
2189 stmf_free(void *ptr)
2190 {
2191 	__stmf_t *sh = (__stmf_t *)ptr;
2192 
2193 	/*
2194 	 * So far we dont need any struct specific processing. If such
2195 	 * a need ever arises, then store the struct id in the framework
2196 	 * private section and get it here as sh->fp->struct_id.
2197 	 */
2198 	kmem_free(ptr, sh->fp->alloc_size);
2199 }
2200 
2201 /*
2202  * Given a pointer to stmf_lu_t, verifies if this lu is registered with the
2203  * framework and returns a pointer to framework private data for the lu.
2204  * Returns NULL if the lu was not found.
2205  */
2206 stmf_i_lu_t *
2207 stmf_lookup_lu(stmf_lu_t *lu)
2208 {
2209 	stmf_i_lu_t *ilu;
2210 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
2211 
2212 	for (ilu = stmf_state.stmf_ilulist; ilu != NULL; ilu = ilu->ilu_next) {
2213 		if (ilu->ilu_lu == lu)
2214 			return (ilu);
2215 	}
2216 	return (NULL);
2217 }
2218 
2219 /*
2220  * Given a pointer to stmf_local_port_t, verifies if this lport is registered
2221  * with the framework and returns a pointer to framework private data for
2222  * the lport.
2223  * Returns NULL if the lport was not found.
2224  */
2225 stmf_i_local_port_t *
2226 stmf_lookup_lport(stmf_local_port_t *lport)
2227 {
2228 	stmf_i_local_port_t *ilport;
2229 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
2230 
2231 	for (ilport = stmf_state.stmf_ilportlist; ilport != NULL;
2232 	    ilport = ilport->ilport_next) {
2233 		if (ilport->ilport_lport == lport)
2234 			return (ilport);
2235 	}
2236 	return (NULL);
2237 }
2238 
2239 stmf_status_t
2240 stmf_register_lu_provider(stmf_lu_provider_t *lp)
2241 {
2242 	stmf_i_lu_provider_t *ilp = (stmf_i_lu_provider_t *)lp->lp_stmf_private;
2243 	stmf_pp_data_t *ppd;
2244 	uint32_t cb_flags;
2245 
2246 	if (lp->lp_lpif_rev != LPIF_REV_1 && lp->lp_lpif_rev != LPIF_REV_2)
2247 		return (STMF_FAILURE);
2248 
2249 	mutex_enter(&stmf_state.stmf_lock);
2250 	ilp->ilp_next = stmf_state.stmf_ilplist;
2251 	stmf_state.stmf_ilplist = ilp;
2252 	stmf_state.stmf_nlps++;
2253 
2254 	/* See if we need to do a callback */
2255 	for (ppd = stmf_state.stmf_ppdlist; ppd != NULL; ppd = ppd->ppd_next) {
2256 		if (strcmp(ppd->ppd_name, lp->lp_name) == 0) {
2257 			break;
2258 		}
2259 	}
2260 	if ((ppd == NULL) || (ppd->ppd_nv == NULL)) {
2261 		goto rlp_bail_out;
2262 	}
2263 	ilp->ilp_ppd = ppd;
2264 	ppd->ppd_provider = ilp;
2265 	if (lp->lp_cb == NULL)
2266 		goto rlp_bail_out;
2267 	ilp->ilp_cb_in_progress = 1;
2268 	cb_flags = STMF_PCB_PREG_COMPLETE;
2269 	if (stmf_state.stmf_config_state == STMF_CONFIG_INIT)
2270 		cb_flags |= STMF_PCB_STMF_ONLINING;
2271 	mutex_exit(&stmf_state.stmf_lock);
2272 	lp->lp_cb(lp, STMF_PROVIDER_DATA_UPDATED, ppd->ppd_nv, cb_flags);
2273 	mutex_enter(&stmf_state.stmf_lock);
2274 	ilp->ilp_cb_in_progress = 0;
2275 
2276 rlp_bail_out:
2277 	mutex_exit(&stmf_state.stmf_lock);
2278 
2279 	return (STMF_SUCCESS);
2280 }
2281 
2282 stmf_status_t
2283 stmf_deregister_lu_provider(stmf_lu_provider_t *lp)
2284 {
2285 	stmf_i_lu_provider_t	**ppilp;
2286 	stmf_i_lu_provider_t *ilp = (stmf_i_lu_provider_t *)lp->lp_stmf_private;
2287 
2288 	mutex_enter(&stmf_state.stmf_lock);
2289 	if (ilp->ilp_nlus || ilp->ilp_cb_in_progress) {
2290 		mutex_exit(&stmf_state.stmf_lock);
2291 		return (STMF_BUSY);
2292 	}
2293 	for (ppilp = &stmf_state.stmf_ilplist; *ppilp != NULL;
2294 	    ppilp = &((*ppilp)->ilp_next)) {
2295 		if (*ppilp == ilp) {
2296 			*ppilp = ilp->ilp_next;
2297 			stmf_state.stmf_nlps--;
2298 			if (ilp->ilp_ppd) {
2299 				ilp->ilp_ppd->ppd_provider = NULL;
2300 				ilp->ilp_ppd = NULL;
2301 			}
2302 			mutex_exit(&stmf_state.stmf_lock);
2303 			return (STMF_SUCCESS);
2304 		}
2305 	}
2306 	mutex_exit(&stmf_state.stmf_lock);
2307 	return (STMF_NOT_FOUND);
2308 }
2309 
2310 stmf_status_t
2311 stmf_register_port_provider(stmf_port_provider_t *pp)
2312 {
2313 	stmf_i_port_provider_t *ipp =
2314 	    (stmf_i_port_provider_t *)pp->pp_stmf_private;
2315 	stmf_pp_data_t *ppd;
2316 	uint32_t cb_flags;
2317 
2318 	if (pp->pp_portif_rev != PORTIF_REV_1)
2319 		return (STMF_FAILURE);
2320 
2321 	mutex_enter(&stmf_state.stmf_lock);
2322 	ipp->ipp_next = stmf_state.stmf_ipplist;
2323 	stmf_state.stmf_ipplist = ipp;
2324 	stmf_state.stmf_npps++;
2325 	/* See if we need to do a callback */
2326 	for (ppd = stmf_state.stmf_ppdlist; ppd != NULL; ppd = ppd->ppd_next) {
2327 		if (strcmp(ppd->ppd_name, pp->pp_name) == 0) {
2328 			break;
2329 		}
2330 	}
2331 	if ((ppd == NULL) || (ppd->ppd_nv == NULL)) {
2332 		goto rpp_bail_out;
2333 	}
2334 	ipp->ipp_ppd = ppd;
2335 	ppd->ppd_provider = ipp;
2336 	if (pp->pp_cb == NULL)
2337 		goto rpp_bail_out;
2338 	ipp->ipp_cb_in_progress = 1;
2339 	cb_flags = STMF_PCB_PREG_COMPLETE;
2340 	if (stmf_state.stmf_config_state == STMF_CONFIG_INIT)
2341 		cb_flags |= STMF_PCB_STMF_ONLINING;
2342 	mutex_exit(&stmf_state.stmf_lock);
2343 	pp->pp_cb(pp, STMF_PROVIDER_DATA_UPDATED, ppd->ppd_nv, cb_flags);
2344 	mutex_enter(&stmf_state.stmf_lock);
2345 	ipp->ipp_cb_in_progress = 0;
2346 
2347 rpp_bail_out:
2348 	mutex_exit(&stmf_state.stmf_lock);
2349 
2350 	return (STMF_SUCCESS);
2351 }
2352 
2353 stmf_status_t
2354 stmf_deregister_port_provider(stmf_port_provider_t *pp)
2355 {
2356 	stmf_i_port_provider_t *ipp =
2357 	    (stmf_i_port_provider_t *)pp->pp_stmf_private;
2358 	stmf_i_port_provider_t **ppipp;
2359 
2360 	mutex_enter(&stmf_state.stmf_lock);
2361 	if (ipp->ipp_npps || ipp->ipp_cb_in_progress) {
2362 		mutex_exit(&stmf_state.stmf_lock);
2363 		return (STMF_BUSY);
2364 	}
2365 	for (ppipp = &stmf_state.stmf_ipplist; *ppipp != NULL;
2366 	    ppipp = &((*ppipp)->ipp_next)) {
2367 		if (*ppipp == ipp) {
2368 			*ppipp = ipp->ipp_next;
2369 			stmf_state.stmf_npps--;
2370 			if (ipp->ipp_ppd) {
2371 				ipp->ipp_ppd->ppd_provider = NULL;
2372 				ipp->ipp_ppd = NULL;
2373 			}
2374 			mutex_exit(&stmf_state.stmf_lock);
2375 			return (STMF_SUCCESS);
2376 		}
2377 	}
2378 	mutex_exit(&stmf_state.stmf_lock);
2379 	return (STMF_NOT_FOUND);
2380 }
2381 
2382 int
2383 stmf_load_ppd_ioctl(stmf_ppioctl_data_t *ppi, uint64_t *ppi_token,
2384     uint32_t *err_ret)
2385 {
2386 	stmf_i_port_provider_t		*ipp;
2387 	stmf_i_lu_provider_t		*ilp;
2388 	stmf_pp_data_t			*ppd;
2389 	nvlist_t			*nv;
2390 	int				s;
2391 	int				ret;
2392 
2393 	*err_ret = 0;
2394 
2395 	if ((ppi->ppi_lu_provider + ppi->ppi_port_provider) != 1) {
2396 		return (EINVAL);
2397 	}
2398 
2399 	mutex_enter(&stmf_state.stmf_lock);
2400 	for (ppd = stmf_state.stmf_ppdlist; ppd != NULL; ppd = ppd->ppd_next) {
2401 		if (ppi->ppi_lu_provider) {
2402 			if (!ppd->ppd_lu_provider)
2403 				continue;
2404 		} else if (ppi->ppi_port_provider) {
2405 			if (!ppd->ppd_port_provider)
2406 				continue;
2407 		}
2408 		if (strncmp(ppi->ppi_name, ppd->ppd_name, 254) == 0)
2409 			break;
2410 	}
2411 
2412 	if (ppd == NULL) {
2413 		/* New provider */
2414 		s = strlen(ppi->ppi_name);
2415 		if (s > 254) {
2416 			mutex_exit(&stmf_state.stmf_lock);
2417 			return (EINVAL);
2418 		}
2419 		s += sizeof (stmf_pp_data_t) - 7;
2420 
2421 		ppd = kmem_zalloc(s, KM_NOSLEEP);
2422 		if (ppd == NULL) {
2423 			mutex_exit(&stmf_state.stmf_lock);
2424 			return (ENOMEM);
2425 		}
2426 		ppd->ppd_alloc_size = s;
2427 		(void) strcpy(ppd->ppd_name, ppi->ppi_name);
2428 
2429 		/* See if this provider already exists */
2430 		if (ppi->ppi_lu_provider) {
2431 			ppd->ppd_lu_provider = 1;
2432 			for (ilp = stmf_state.stmf_ilplist; ilp != NULL;
2433 			    ilp = ilp->ilp_next) {
2434 				if (strcmp(ppi->ppi_name,
2435 				    ilp->ilp_lp->lp_name) == 0) {
2436 					ppd->ppd_provider = ilp;
2437 					ilp->ilp_ppd = ppd;
2438 					break;
2439 				}
2440 			}
2441 		} else {
2442 			ppd->ppd_port_provider = 1;
2443 			for (ipp = stmf_state.stmf_ipplist; ipp != NULL;
2444 			    ipp = ipp->ipp_next) {
2445 				if (strcmp(ppi->ppi_name,
2446 				    ipp->ipp_pp->pp_name) == 0) {
2447 					ppd->ppd_provider = ipp;
2448 					ipp->ipp_ppd = ppd;
2449 					break;
2450 				}
2451 			}
2452 		}
2453 
2454 		/* Link this ppd in */
2455 		ppd->ppd_next = stmf_state.stmf_ppdlist;
2456 		stmf_state.stmf_ppdlist = ppd;
2457 	}
2458 
2459 	/*
2460 	 * User is requesting that the token be checked.
2461 	 * If there was another set after the user's get
2462 	 * it's an error
2463 	 */
2464 	if (ppi->ppi_token_valid) {
2465 		if (ppi->ppi_token != ppd->ppd_token) {
2466 			*err_ret = STMF_IOCERR_PPD_UPDATED;
2467 			mutex_exit(&stmf_state.stmf_lock);
2468 			return (EINVAL);
2469 		}
2470 	}
2471 
2472 	if ((ret = nvlist_unpack((char *)ppi->ppi_data,
2473 	    (size_t)ppi->ppi_data_size, &nv, KM_NOSLEEP)) != 0) {
2474 		mutex_exit(&stmf_state.stmf_lock);
2475 		return (ret);
2476 	}
2477 
2478 	/* Free any existing lists and add this one to the ppd */
2479 	if (ppd->ppd_nv)
2480 		nvlist_free(ppd->ppd_nv);
2481 	ppd->ppd_nv = nv;
2482 
2483 	/* set the token for writes */
2484 	ppd->ppd_token++;
2485 	/* return token to caller */
2486 	if (ppi_token) {
2487 		*ppi_token = ppd->ppd_token;
2488 	}
2489 
2490 	/* If there is a provider registered, do the notifications */
2491 	if (ppd->ppd_provider) {
2492 		uint32_t cb_flags = 0;
2493 
2494 		if (stmf_state.stmf_config_state == STMF_CONFIG_INIT)
2495 			cb_flags |= STMF_PCB_STMF_ONLINING;
2496 		if (ppi->ppi_lu_provider) {
2497 			ilp = (stmf_i_lu_provider_t *)ppd->ppd_provider;
2498 			if (ilp->ilp_lp->lp_cb == NULL)
2499 				goto bail_out;
2500 			ilp->ilp_cb_in_progress = 1;
2501 			mutex_exit(&stmf_state.stmf_lock);
2502 			ilp->ilp_lp->lp_cb(ilp->ilp_lp,
2503 			    STMF_PROVIDER_DATA_UPDATED, ppd->ppd_nv, cb_flags);
2504 			mutex_enter(&stmf_state.stmf_lock);
2505 			ilp->ilp_cb_in_progress = 0;
2506 		} else {
2507 			ipp = (stmf_i_port_provider_t *)ppd->ppd_provider;
2508 			if (ipp->ipp_pp->pp_cb == NULL)
2509 				goto bail_out;
2510 			ipp->ipp_cb_in_progress = 1;
2511 			mutex_exit(&stmf_state.stmf_lock);
2512 			ipp->ipp_pp->pp_cb(ipp->ipp_pp,
2513 			    STMF_PROVIDER_DATA_UPDATED, ppd->ppd_nv, cb_flags);
2514 			mutex_enter(&stmf_state.stmf_lock);
2515 			ipp->ipp_cb_in_progress = 0;
2516 		}
2517 	}
2518 
2519 bail_out:
2520 	mutex_exit(&stmf_state.stmf_lock);
2521 
2522 	return (0);
2523 }
2524 
2525 void
2526 stmf_delete_ppd(stmf_pp_data_t *ppd)
2527 {
2528 	stmf_pp_data_t **pppd;
2529 
2530 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
2531 	if (ppd->ppd_provider) {
2532 		if (ppd->ppd_lu_provider) {
2533 			((stmf_i_lu_provider_t *)
2534 			    ppd->ppd_provider)->ilp_ppd = NULL;
2535 		} else {
2536 			((stmf_i_port_provider_t *)
2537 			    ppd->ppd_provider)->ipp_ppd = NULL;
2538 		}
2539 		ppd->ppd_provider = NULL;
2540 	}
2541 
2542 	for (pppd = &stmf_state.stmf_ppdlist; *pppd != NULL;
2543 	    pppd = &((*pppd)->ppd_next)) {
2544 		if (*pppd == ppd)
2545 			break;
2546 	}
2547 
2548 	if (*pppd == NULL)
2549 		return;
2550 
2551 	*pppd = ppd->ppd_next;
2552 	if (ppd->ppd_nv)
2553 		nvlist_free(ppd->ppd_nv);
2554 
2555 	kmem_free(ppd, ppd->ppd_alloc_size);
2556 }
2557 
2558 int
2559 stmf_delete_ppd_ioctl(stmf_ppioctl_data_t *ppi)
2560 {
2561 	stmf_pp_data_t *ppd;
2562 	int ret = ENOENT;
2563 
2564 	if ((ppi->ppi_lu_provider + ppi->ppi_port_provider) != 1) {
2565 		return (EINVAL);
2566 	}
2567 
2568 	mutex_enter(&stmf_state.stmf_lock);
2569 
2570 	for (ppd = stmf_state.stmf_ppdlist; ppd != NULL; ppd = ppd->ppd_next) {
2571 		if (ppi->ppi_lu_provider) {
2572 			if (!ppd->ppd_lu_provider)
2573 				continue;
2574 		} else if (ppi->ppi_port_provider) {
2575 			if (!ppd->ppd_port_provider)
2576 				continue;
2577 		}
2578 		if (strncmp(ppi->ppi_name, ppd->ppd_name, 254) == 0)
2579 			break;
2580 	}
2581 
2582 	if (ppd) {
2583 		ret = 0;
2584 		stmf_delete_ppd(ppd);
2585 	}
2586 	mutex_exit(&stmf_state.stmf_lock);
2587 
2588 	return (ret);
2589 }
2590 
2591 int
2592 stmf_get_ppd_ioctl(stmf_ppioctl_data_t *ppi, stmf_ppioctl_data_t *ppi_out,
2593     uint32_t *err_ret)
2594 {
2595 	stmf_pp_data_t *ppd;
2596 	size_t req_size;
2597 	int ret = ENOENT;
2598 	char *bufp = (char *)ppi_out->ppi_data;
2599 
2600 	if ((ppi->ppi_lu_provider + ppi->ppi_port_provider) != 1) {
2601 		return (EINVAL);
2602 	}
2603 
2604 	mutex_enter(&stmf_state.stmf_lock);
2605 
2606 	for (ppd = stmf_state.stmf_ppdlist; ppd != NULL; ppd = ppd->ppd_next) {
2607 		if (ppi->ppi_lu_provider) {
2608 			if (!ppd->ppd_lu_provider)
2609 				continue;
2610 		} else if (ppi->ppi_port_provider) {
2611 			if (!ppd->ppd_port_provider)
2612 				continue;
2613 		}
2614 		if (strncmp(ppi->ppi_name, ppd->ppd_name, 254) == 0)
2615 			break;
2616 	}
2617 
2618 	if (ppd && ppd->ppd_nv) {
2619 		ppi_out->ppi_token = ppd->ppd_token;
2620 		if ((ret = nvlist_size(ppd->ppd_nv, &req_size,
2621 		    NV_ENCODE_XDR)) != 0) {
2622 			goto done;
2623 		}
2624 		ppi_out->ppi_data_size = req_size;
2625 		if (req_size > ppi->ppi_data_size) {
2626 			*err_ret = STMF_IOCERR_INSUFFICIENT_BUF;
2627 			ret = EINVAL;
2628 			goto done;
2629 		}
2630 
2631 		if ((ret = nvlist_pack(ppd->ppd_nv, &bufp, &req_size,
2632 		    NV_ENCODE_XDR, 0)) != 0) {
2633 			goto done;
2634 		}
2635 		ret = 0;
2636 	}
2637 
2638 done:
2639 	mutex_exit(&stmf_state.stmf_lock);
2640 
2641 	return (ret);
2642 }
2643 
2644 void
2645 stmf_delete_all_ppds()
2646 {
2647 	stmf_pp_data_t *ppd, *nppd;
2648 
2649 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
2650 	for (ppd = stmf_state.stmf_ppdlist; ppd != NULL; ppd = nppd) {
2651 		nppd = ppd->ppd_next;
2652 		stmf_delete_ppd(ppd);
2653 	}
2654 }
2655 
2656 /*
2657  * 16 is the max string length of a protocol_ident, increase
2658  * the size if needed.
2659  */
2660 #define	STMF_KSTAT_LU_SZ	(STMF_GUID_INPUT + 1 + 256)
2661 #define	STMF_KSTAT_TGT_SZ	(256 * 2 + 16)
2662 
2663 /*
2664  * This array matches the Protocol Identifier in stmf_ioctl.h
2665  */
2666 #define	MAX_PROTO_STR_LEN	32
2667 
2668 char *protocol_ident[PROTOCOL_ANY] = {
2669 	"Fibre Channel",
2670 	"Parallel SCSI",
2671 	"SSA",
2672 	"IEEE_1394",
2673 	"SRP",
2674 	"iSCSI",
2675 	"SAS",
2676 	"ADT",
2677 	"ATAPI",
2678 	"UNKNOWN", "UNKNOWN", "UNKNOWN", "UNKNOWN", "UNKNOWN", "UNKNOWN"
2679 };
2680 
2681 /*
2682  * Update the lun wait/run queue count
2683  */
2684 static void
2685 stmf_update_kstat_lu_q(scsi_task_t *task, void func())
2686 {
2687 	stmf_i_lu_t		*ilu;
2688 	kstat_io_t		*kip;
2689 
2690 	if (task->task_lu == dlun0)
2691 		return;
2692 	ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
2693 	if (ilu != NULL && ilu->ilu_kstat_io != NULL) {
2694 		kip = KSTAT_IO_PTR(ilu->ilu_kstat_io);
2695 		if (kip != NULL) {
2696 			func(kip);
2697 		}
2698 	}
2699 }
2700 
2701 /*
2702  * Update the target(lport) wait/run queue count
2703  */
2704 static void
2705 stmf_update_kstat_lport_q(scsi_task_t *task, void func())
2706 {
2707 	stmf_i_local_port_t	*ilp;
2708 	kstat_io_t		*kip;
2709 
2710 	ilp = (stmf_i_local_port_t *)task->task_lport->lport_stmf_private;
2711 	if (ilp != NULL && ilp->ilport_kstat_io != NULL) {
2712 		kip = KSTAT_IO_PTR(ilp->ilport_kstat_io);
2713 		if (kip != NULL) {
2714 			mutex_enter(ilp->ilport_kstat_io->ks_lock);
2715 			func(kip);
2716 			mutex_exit(ilp->ilport_kstat_io->ks_lock);
2717 		}
2718 	}
2719 }
2720 
2721 static void
2722 stmf_update_kstat_lport_io(scsi_task_t *task, stmf_data_buf_t *dbuf)
2723 {
2724 	stmf_i_local_port_t	*ilp;
2725 	kstat_io_t		*kip;
2726 
2727 	ilp = (stmf_i_local_port_t *)task->task_lport->lport_stmf_private;
2728 	if (ilp != NULL && ilp->ilport_kstat_io != NULL) {
2729 		kip = KSTAT_IO_PTR(ilp->ilport_kstat_io);
2730 		if (kip != NULL) {
2731 			mutex_enter(ilp->ilport_kstat_io->ks_lock);
2732 			STMF_UPDATE_KSTAT_IO(kip, dbuf);
2733 			mutex_exit(ilp->ilport_kstat_io->ks_lock);
2734 		}
2735 	}
2736 }
2737 
2738 static void
2739 stmf_update_kstat_lu_io(scsi_task_t *task, stmf_data_buf_t *dbuf)
2740 {
2741 	stmf_i_lu_t		*ilu;
2742 	kstat_io_t		*kip;
2743 
2744 	ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
2745 	if (ilu != NULL && ilu->ilu_kstat_io != NULL) {
2746 		kip = KSTAT_IO_PTR(ilu->ilu_kstat_io);
2747 		if (kip != NULL) {
2748 			mutex_enter(ilu->ilu_kstat_io->ks_lock);
2749 			STMF_UPDATE_KSTAT_IO(kip, dbuf);
2750 			mutex_exit(ilu->ilu_kstat_io->ks_lock);
2751 		}
2752 	}
2753 }
2754 
2755 static void
2756 stmf_create_kstat_lu(stmf_i_lu_t *ilu)
2757 {
2758 	char				ks_nm[KSTAT_STRLEN];
2759 	stmf_kstat_lu_info_t		*ks_lu;
2760 
2761 	/* create kstat lun info */
2762 	ks_lu = (stmf_kstat_lu_info_t *)kmem_zalloc(STMF_KSTAT_LU_SZ,
2763 	    KM_NOSLEEP);
2764 	if (ks_lu == NULL) {
2765 		cmn_err(CE_WARN, "STMF: kmem_zalloc failed");
2766 		return;
2767 	}
2768 
2769 	bzero(ks_nm, sizeof (ks_nm));
2770 	(void) sprintf(ks_nm, "stmf_lu_%"PRIxPTR"", (uintptr_t)ilu);
2771 	if ((ilu->ilu_kstat_info = kstat_create(STMF_MODULE_NAME, 0,
2772 	    ks_nm, "misc", KSTAT_TYPE_NAMED,
2773 	    sizeof (stmf_kstat_lu_info_t) / sizeof (kstat_named_t),
2774 	    KSTAT_FLAG_VIRTUAL)) == NULL) {
2775 		kmem_free(ks_lu, STMF_KSTAT_LU_SZ);
2776 		cmn_err(CE_WARN, "STMF: kstat_create lu failed");
2777 		return;
2778 	}
2779 
2780 	ilu->ilu_kstat_info->ks_data_size = STMF_KSTAT_LU_SZ;
2781 	ilu->ilu_kstat_info->ks_data = ks_lu;
2782 
2783 	kstat_named_init(&ks_lu->i_lun_guid, "lun-guid",
2784 	    KSTAT_DATA_STRING);
2785 	kstat_named_init(&ks_lu->i_lun_alias, "lun-alias",
2786 	    KSTAT_DATA_STRING);
2787 
2788 	/* convert guid to hex string */
2789 	int		i;
2790 	uint8_t		*p = ilu->ilu_lu->lu_id->ident;
2791 	bzero(ilu->ilu_ascii_hex_guid, sizeof (ilu->ilu_ascii_hex_guid));
2792 	for (i = 0; i < STMF_GUID_INPUT / 2; i++) {
2793 		(void) sprintf(&ilu->ilu_ascii_hex_guid[i * 2], "%02x", p[i]);
2794 	}
2795 	kstat_named_setstr(&ks_lu->i_lun_guid,
2796 	    (const char *)ilu->ilu_ascii_hex_guid);
2797 	kstat_named_setstr(&ks_lu->i_lun_alias,
2798 	    (const char *)ilu->ilu_lu->lu_alias);
2799 	kstat_install(ilu->ilu_kstat_info);
2800 
2801 	/* create kstat lun io */
2802 	bzero(ks_nm, sizeof (ks_nm));
2803 	(void) sprintf(ks_nm, "stmf_lu_io_%"PRIxPTR"", (uintptr_t)ilu);
2804 	if ((ilu->ilu_kstat_io = kstat_create(STMF_MODULE_NAME, 0,
2805 	    ks_nm, "io", KSTAT_TYPE_IO, 1, 0)) == NULL) {
2806 		cmn_err(CE_WARN, "STMF: kstat_create lu_io failed");
2807 		return;
2808 	}
2809 	mutex_init(&ilu->ilu_kstat_lock, NULL, MUTEX_DRIVER, 0);
2810 	ilu->ilu_kstat_io->ks_lock = &ilu->ilu_kstat_lock;
2811 	kstat_install(ilu->ilu_kstat_io);
2812 }
2813 
2814 static void
2815 stmf_create_kstat_lport(stmf_i_local_port_t *ilport)
2816 {
2817 	char				ks_nm[KSTAT_STRLEN];
2818 	stmf_kstat_tgt_info_t		*ks_tgt;
2819 	int				id, len;
2820 
2821 	/* create kstat lport info */
2822 	ks_tgt = (stmf_kstat_tgt_info_t *)kmem_zalloc(STMF_KSTAT_TGT_SZ,
2823 	    KM_NOSLEEP);
2824 	if (ks_tgt == NULL) {
2825 		cmn_err(CE_WARN, "STMF: kmem_zalloc failed");
2826 		return;
2827 	}
2828 
2829 	bzero(ks_nm, sizeof (ks_nm));
2830 	(void) sprintf(ks_nm, "stmf_tgt_%"PRIxPTR"", (uintptr_t)ilport);
2831 	if ((ilport->ilport_kstat_info = kstat_create(STMF_MODULE_NAME,
2832 	    0, ks_nm, "misc", KSTAT_TYPE_NAMED,
2833 	    sizeof (stmf_kstat_tgt_info_t) / sizeof (kstat_named_t),
2834 	    KSTAT_FLAG_VIRTUAL)) == NULL) {
2835 		kmem_free(ks_tgt, STMF_KSTAT_TGT_SZ);
2836 		cmn_err(CE_WARN, "STMF: kstat_create target failed");
2837 		return;
2838 	}
2839 
2840 	ilport->ilport_kstat_info->ks_data_size = STMF_KSTAT_TGT_SZ;
2841 	ilport->ilport_kstat_info->ks_data = ks_tgt;
2842 
2843 	kstat_named_init(&ks_tgt->i_tgt_name, "target-name",
2844 	    KSTAT_DATA_STRING);
2845 	kstat_named_init(&ks_tgt->i_tgt_alias, "target-alias",
2846 	    KSTAT_DATA_STRING);
2847 	kstat_named_init(&ks_tgt->i_protocol, "protocol",
2848 	    KSTAT_DATA_STRING);
2849 
2850 	/* ident might not be null terminated */
2851 	len = ilport->ilport_lport->lport_id->ident_length;
2852 	bcopy(ilport->ilport_lport->lport_id->ident,
2853 	    ilport->ilport_kstat_tgt_name, len);
2854 	ilport->ilport_kstat_tgt_name[len + 1] = NULL;
2855 	kstat_named_setstr(&ks_tgt->i_tgt_name,
2856 	    (const char *)ilport->ilport_kstat_tgt_name);
2857 	kstat_named_setstr(&ks_tgt->i_tgt_alias,
2858 	    (const char *)ilport->ilport_lport->lport_alias);
2859 	/* protocol */
2860 	if ((id = ilport->ilport_lport->lport_id->protocol_id) > PROTOCOL_ANY) {
2861 		cmn_err(CE_WARN, "STMF: protocol_id out of bound");
2862 		id = PROTOCOL_ANY;
2863 	}
2864 	kstat_named_setstr(&ks_tgt->i_protocol, protocol_ident[id]);
2865 	kstat_install(ilport->ilport_kstat_info);
2866 
2867 	/* create kstat lport io */
2868 	bzero(ks_nm, sizeof (ks_nm));
2869 	(void) sprintf(ks_nm, "stmf_tgt_io_%"PRIxPTR"", (uintptr_t)ilport);
2870 	if ((ilport->ilport_kstat_io = kstat_create(STMF_MODULE_NAME, 0,
2871 	    ks_nm, "io", KSTAT_TYPE_IO, 1, 0)) == NULL) {
2872 		cmn_err(CE_WARN, "STMF: kstat_create target_io failed");
2873 		return;
2874 	}
2875 	mutex_init(&ilport->ilport_kstat_lock, NULL, MUTEX_DRIVER, 0);
2876 	ilport->ilport_kstat_io->ks_lock = &ilport->ilport_kstat_lock;
2877 	kstat_install(ilport->ilport_kstat_io);
2878 }
2879 
2880 /*
2881  * set the asymmetric access state for a logical unit
2882  * caller is responsible for establishing SCSI unit attention on
2883  * state change
2884  */
2885 stmf_status_t
2886 stmf_set_lu_access(stmf_lu_t *lu, uint8_t access_state)
2887 {
2888 	stmf_i_lu_t *ilu;
2889 	uint8_t *p1, *p2;
2890 
2891 	if ((access_state != STMF_LU_STANDBY) &&
2892 	    (access_state != STMF_LU_ACTIVE)) {
2893 		return (STMF_INVALID_ARG);
2894 	}
2895 
2896 	p1 = &lu->lu_id->ident[0];
2897 	mutex_enter(&stmf_state.stmf_lock);
2898 	if (stmf_state.stmf_inventory_locked) {
2899 		mutex_exit(&stmf_state.stmf_lock);
2900 		return (STMF_BUSY);
2901 	}
2902 
2903 	for (ilu = stmf_state.stmf_ilulist; ilu != NULL; ilu = ilu->ilu_next) {
2904 		p2 = &ilu->ilu_lu->lu_id->ident[0];
2905 		if (bcmp(p1, p2, 16) == 0) {
2906 			break;
2907 		}
2908 	}
2909 
2910 	if (!ilu) {
2911 		ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
2912 	} else {
2913 		/*
2914 		 * We're changing access state on an existing logical unit
2915 		 * Send the proxy registration message for this logical unit
2916 		 * if we're in alua mode.
2917 		 * If the requested state is STMF_LU_ACTIVE, we want to register
2918 		 * this logical unit.
2919 		 * If the requested state is STMF_LU_STANDBY, we're going to
2920 		 * abort all tasks for this logical unit.
2921 		 */
2922 		if (stmf_state.stmf_alua_state == 1 &&
2923 		    access_state == STMF_LU_ACTIVE) {
2924 			stmf_ic_msg_status_t ic_ret = STMF_IC_MSG_SUCCESS;
2925 			stmf_ic_msg_t *ic_reg_lun;
2926 			if (lu->lu_lp && lu->lu_lp->lp_lpif_rev == LPIF_REV_2 &&
2927 			    lu->lu_lp->lp_alua_support) {
2928 				ilu->ilu_alua = 1;
2929 				/* allocate the register message */
2930 				ic_reg_lun = ic_lun_active_msg_alloc(p1,
2931 				    lu->lu_lp->lp_name,
2932 				    lu->lu_proxy_reg_arg_len,
2933 				    (uint8_t *)lu->lu_proxy_reg_arg,
2934 				    stmf_proxy_msg_id);
2935 				/* send the message */
2936 				if (ic_reg_lun) {
2937 					ic_ret = ic_tx_msg(ic_reg_lun);
2938 					if (ic_ret == STMF_IC_MSG_SUCCESS) {
2939 						stmf_proxy_msg_id++;
2940 					}
2941 				}
2942 			}
2943 		} else if (stmf_state.stmf_alua_state == 1 &&
2944 		    access_state == STMF_LU_STANDBY) {
2945 			/* abort all tasks for this lu */
2946 			stmf_task_lu_killall(lu, NULL, STMF_ABORTED);
2947 		}
2948 	}
2949 
2950 	ilu->ilu_access = access_state;
2951 
2952 	mutex_exit(&stmf_state.stmf_lock);
2953 	return (STMF_SUCCESS);
2954 }
2955 
2956 
2957 stmf_status_t
2958 stmf_register_lu(stmf_lu_t *lu)
2959 {
2960 	stmf_i_lu_t *ilu;
2961 	uint8_t *p1, *p2;
2962 	stmf_state_change_info_t ssci;
2963 	stmf_id_data_t *luid;
2964 
2965 	if ((lu->lu_id->ident_type != ID_TYPE_NAA) ||
2966 	    (lu->lu_id->ident_length != 16) ||
2967 	    ((lu->lu_id->ident[0] & 0xf0) != 0x60)) {
2968 		return (STMF_INVALID_ARG);
2969 	}
2970 	p1 = &lu->lu_id->ident[0];
2971 	mutex_enter(&stmf_state.stmf_lock);
2972 	if (stmf_state.stmf_inventory_locked) {
2973 		mutex_exit(&stmf_state.stmf_lock);
2974 		return (STMF_BUSY);
2975 	}
2976 
2977 	for (ilu = stmf_state.stmf_ilulist; ilu != NULL; ilu = ilu->ilu_next) {
2978 		p2 = &ilu->ilu_lu->lu_id->ident[0];
2979 		if (bcmp(p1, p2, 16) == 0) {
2980 			mutex_exit(&stmf_state.stmf_lock);
2981 			return (STMF_ALREADY);
2982 		}
2983 	}
2984 
2985 	ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
2986 	luid = stmf_lookup_id(&stmf_state.stmf_luid_list,
2987 	    lu->lu_id->ident_length, lu->lu_id->ident);
2988 	if (luid) {
2989 		luid->id_pt_to_object = (void *)ilu;
2990 		ilu->ilu_luid = luid;
2991 	}
2992 	ilu->ilu_alias = NULL;
2993 
2994 	ilu->ilu_next = stmf_state.stmf_ilulist;
2995 	ilu->ilu_prev = NULL;
2996 	if (ilu->ilu_next)
2997 		ilu->ilu_next->ilu_prev = ilu;
2998 	stmf_state.stmf_ilulist = ilu;
2999 	stmf_state.stmf_nlus++;
3000 	if (lu->lu_lp) {
3001 		((stmf_i_lu_provider_t *)
3002 		    (lu->lu_lp->lp_stmf_private))->ilp_nlus++;
3003 	}
3004 	ilu->ilu_cur_task_cntr = &ilu->ilu_task_cntr1;
3005 	STMF_EVENT_ALLOC_HANDLE(ilu->ilu_event_hdl);
3006 	stmf_create_kstat_lu(ilu);
3007 	/*
3008 	 * register with proxy module if available and logical unit
3009 	 * is in active state
3010 	 */
3011 	if (stmf_state.stmf_alua_state == 1 &&
3012 	    ilu->ilu_access == STMF_LU_ACTIVE) {
3013 		stmf_ic_msg_status_t ic_ret = STMF_IC_MSG_SUCCESS;
3014 		stmf_ic_msg_t *ic_reg_lun;
3015 		if (lu->lu_lp && lu->lu_lp->lp_lpif_rev == LPIF_REV_2 &&
3016 		    lu->lu_lp->lp_alua_support) {
3017 			ilu->ilu_alua = 1;
3018 			/* allocate the register message */
3019 			ic_reg_lun = ic_reg_lun_msg_alloc(p1,
3020 			    lu->lu_lp->lp_name, lu->lu_proxy_reg_arg_len,
3021 			    (uint8_t *)lu->lu_proxy_reg_arg, stmf_proxy_msg_id);
3022 			/* send the message */
3023 			if (ic_reg_lun) {
3024 				ic_ret = ic_tx_msg(ic_reg_lun);
3025 				if (ic_ret == STMF_IC_MSG_SUCCESS) {
3026 					stmf_proxy_msg_id++;
3027 				}
3028 			}
3029 		}
3030 	}
3031 	mutex_exit(&stmf_state.stmf_lock);
3032 
3033 	/* XXX we should probably check if this lu can be brought online */
3034 	ilu->ilu_prev_state = STMF_STATE_ONLINE;
3035 	if (stmf_state.stmf_service_running) {
3036 		ssci.st_rflags = 0;
3037 		ssci.st_additional_info = NULL;
3038 		(void) stmf_ctl(STMF_CMD_LU_ONLINE, lu, &ssci);
3039 	}
3040 
3041 	/* XXX: Generate event */
3042 	return (STMF_SUCCESS);
3043 }
3044 
3045 stmf_status_t
3046 stmf_deregister_lu(stmf_lu_t *lu)
3047 {
3048 	stmf_i_lu_t *ilu;
3049 
3050 	mutex_enter(&stmf_state.stmf_lock);
3051 	if (stmf_state.stmf_inventory_locked) {
3052 		mutex_exit(&stmf_state.stmf_lock);
3053 		return (STMF_BUSY);
3054 	}
3055 	ilu = stmf_lookup_lu(lu);
3056 	if (ilu == NULL) {
3057 		mutex_exit(&stmf_state.stmf_lock);
3058 		return (STMF_INVALID_ARG);
3059 	}
3060 	if (ilu->ilu_state == STMF_STATE_OFFLINE) {
3061 		ASSERT(ilu->ilu_ntasks == ilu->ilu_ntasks_free);
3062 		while (ilu->ilu_flags & ILU_STALL_DEREGISTER) {
3063 			cv_wait(&stmf_state.stmf_cv, &stmf_state.stmf_lock);
3064 		}
3065 		if (ilu->ilu_ntasks) {
3066 			stmf_i_scsi_task_t *itask, *nitask;
3067 
3068 			nitask = ilu->ilu_tasks;
3069 			do {
3070 				itask = nitask;
3071 				nitask = itask->itask_lu_next;
3072 				lu->lu_task_free(itask->itask_task);
3073 				stmf_free(itask->itask_task);
3074 			} while (nitask != NULL);
3075 
3076 			ilu->ilu_tasks = ilu->ilu_free_tasks = NULL;
3077 			ilu->ilu_ntasks = ilu->ilu_ntasks_free = 0;
3078 		}
3079 		/* de-register with proxy if available */
3080 		if (ilu->ilu_access == STMF_LU_ACTIVE &&
3081 		    stmf_state.stmf_alua_state == 1) {
3082 			/* de-register with proxy module */
3083 			stmf_ic_msg_status_t ic_ret = STMF_IC_MSG_SUCCESS;
3084 			stmf_ic_msg_t *ic_dereg_lun;
3085 			if (lu->lu_lp && lu->lu_lp->lp_lpif_rev == LPIF_REV_2 &&
3086 			    lu->lu_lp->lp_alua_support) {
3087 				ilu->ilu_alua = 1;
3088 				/* allocate the de-register message */
3089 				ic_dereg_lun = ic_dereg_lun_msg_alloc(
3090 				    lu->lu_id->ident, lu->lu_lp->lp_name, 0,
3091 				    NULL, stmf_proxy_msg_id);
3092 				/* send the message */
3093 				if (ic_dereg_lun) {
3094 					ic_ret = ic_tx_msg(ic_dereg_lun);
3095 					if (ic_ret == STMF_IC_MSG_SUCCESS) {
3096 						stmf_proxy_msg_id++;
3097 					}
3098 				}
3099 			}
3100 		}
3101 
3102 		if (ilu->ilu_next)
3103 			ilu->ilu_next->ilu_prev = ilu->ilu_prev;
3104 		if (ilu->ilu_prev)
3105 			ilu->ilu_prev->ilu_next = ilu->ilu_next;
3106 		else
3107 			stmf_state.stmf_ilulist = ilu->ilu_next;
3108 		stmf_state.stmf_nlus--;
3109 
3110 		if (ilu == stmf_state.stmf_svc_ilu_draining) {
3111 			stmf_state.stmf_svc_ilu_draining = ilu->ilu_next;
3112 		}
3113 		if (ilu == stmf_state.stmf_svc_ilu_timing) {
3114 			stmf_state.stmf_svc_ilu_timing = ilu->ilu_next;
3115 		}
3116 		if (lu->lu_lp) {
3117 			((stmf_i_lu_provider_t *)
3118 			    (lu->lu_lp->lp_stmf_private))->ilp_nlus--;
3119 		}
3120 		if (ilu->ilu_luid) {
3121 			((stmf_id_data_t *)ilu->ilu_luid)->id_pt_to_object =
3122 			    NULL;
3123 			ilu->ilu_luid = NULL;
3124 		}
3125 		STMF_EVENT_FREE_HANDLE(ilu->ilu_event_hdl);
3126 	} else {
3127 		mutex_exit(&stmf_state.stmf_lock);
3128 		return (STMF_BUSY);
3129 	}
3130 	if (ilu->ilu_kstat_info) {
3131 		kmem_free(ilu->ilu_kstat_info->ks_data,
3132 		    ilu->ilu_kstat_info->ks_data_size);
3133 		kstat_delete(ilu->ilu_kstat_info);
3134 	}
3135 	if (ilu->ilu_kstat_io) {
3136 		kstat_delete(ilu->ilu_kstat_io);
3137 		mutex_destroy(&ilu->ilu_kstat_lock);
3138 	}
3139 	stmf_delete_itl_kstat_by_guid(ilu->ilu_ascii_hex_guid);
3140 	mutex_exit(&stmf_state.stmf_lock);
3141 	return (STMF_SUCCESS);
3142 }
3143 
3144 void
3145 stmf_set_port_standby(stmf_local_port_t *lport, uint16_t rtpid)
3146 {
3147 	stmf_i_local_port_t *ilport =
3148 	    (stmf_i_local_port_t *)lport->lport_stmf_private;
3149 	ilport->ilport_rtpid = rtpid;
3150 	ilport->ilport_standby = 1;
3151 }
3152 
3153 void
3154 stmf_set_port_alua(stmf_local_port_t *lport)
3155 {
3156 	stmf_i_local_port_t *ilport =
3157 	    (stmf_i_local_port_t *)lport->lport_stmf_private;
3158 	ilport->ilport_alua = 1;
3159 }
3160 
3161 stmf_status_t
3162 stmf_register_local_port(stmf_local_port_t *lport)
3163 {
3164 	stmf_i_local_port_t *ilport;
3165 	stmf_state_change_info_t ssci;
3166 	int start_workers = 0;
3167 
3168 	mutex_enter(&stmf_state.stmf_lock);
3169 	if (stmf_state.stmf_inventory_locked) {
3170 		mutex_exit(&stmf_state.stmf_lock);
3171 		return (STMF_BUSY);
3172 	}
3173 	ilport = (stmf_i_local_port_t *)lport->lport_stmf_private;
3174 	rw_init(&ilport->ilport_lock, NULL, RW_DRIVER, NULL);
3175 
3176 	ilport->ilport_instance =
3177 	    id_alloc_nosleep(stmf_state.stmf_ilport_inst_space);
3178 	if (ilport->ilport_instance == -1) {
3179 		mutex_exit(&stmf_state.stmf_lock);
3180 		return (STMF_FAILURE);
3181 	}
3182 	ilport->ilport_next = stmf_state.stmf_ilportlist;
3183 	ilport->ilport_prev = NULL;
3184 	if (ilport->ilport_next)
3185 		ilport->ilport_next->ilport_prev = ilport;
3186 	stmf_state.stmf_ilportlist = ilport;
3187 	stmf_state.stmf_nlports++;
3188 	if (lport->lport_pp) {
3189 		((stmf_i_port_provider_t *)
3190 		    (lport->lport_pp->pp_stmf_private))->ipp_npps++;
3191 	}
3192 	ilport->ilport_tg =
3193 	    stmf_lookup_group_for_target(lport->lport_id->ident,
3194 	    lport->lport_id->ident_length);
3195 
3196 	/*
3197 	 * rtpid will/must be set if this is a standby port
3198 	 * only register ports that are not standby (proxy) ports
3199 	 * and ports that are alua participants (ilport_alua == 1)
3200 	 */
3201 	if (ilport->ilport_standby == 0) {
3202 		ilport->ilport_rtpid = atomic_add_16_nv(&stmf_rtpid_counter, 1);
3203 	}
3204 
3205 	if (stmf_state.stmf_alua_state == 1 &&
3206 	    ilport->ilport_standby == 0 &&
3207 	    ilport->ilport_alua == 1) {
3208 		stmf_ic_msg_t *ic_reg_port;
3209 		stmf_ic_msg_status_t ic_ret;
3210 		stmf_local_port_t *lport;
3211 		lport = ilport->ilport_lport;
3212 		ic_reg_port = ic_reg_port_msg_alloc(
3213 		    lport->lport_id, ilport->ilport_rtpid,
3214 		    0, NULL, stmf_proxy_msg_id);
3215 		if (ic_reg_port) {
3216 			ic_ret = ic_tx_msg(ic_reg_port);
3217 			if (ic_ret == STMF_IC_MSG_SUCCESS) {
3218 				ilport->ilport_reg_msgid = stmf_proxy_msg_id++;
3219 			} else {
3220 				cmn_err(CE_WARN, "error on port registration "
3221 				"port - %s", ilport->ilport_kstat_tgt_name);
3222 			}
3223 		}
3224 	}
3225 	STMF_EVENT_ALLOC_HANDLE(ilport->ilport_event_hdl);
3226 	stmf_create_kstat_lport(ilport);
3227 	if (stmf_workers_state == STMF_WORKERS_DISABLED) {
3228 		stmf_workers_state = STMF_WORKERS_ENABLING;
3229 		start_workers = 1;
3230 	}
3231 	mutex_exit(&stmf_state.stmf_lock);
3232 
3233 	if (start_workers)
3234 		stmf_worker_init();
3235 
3236 	/* XXX we should probably check if this lport can be brought online */
3237 	ilport->ilport_prev_state = STMF_STATE_ONLINE;
3238 	if (stmf_state.stmf_service_running) {
3239 		ssci.st_rflags = 0;
3240 		ssci.st_additional_info = NULL;
3241 		(void) stmf_ctl(STMF_CMD_LPORT_ONLINE, lport, &ssci);
3242 	}
3243 
3244 	/* XXX: Generate event */
3245 	return (STMF_SUCCESS);
3246 }
3247 
3248 stmf_status_t
3249 stmf_deregister_local_port(stmf_local_port_t *lport)
3250 {
3251 	stmf_i_local_port_t *ilport;
3252 
3253 	mutex_enter(&stmf_state.stmf_lock);
3254 	if (stmf_state.stmf_inventory_locked) {
3255 		mutex_exit(&stmf_state.stmf_lock);
3256 		return (STMF_BUSY);
3257 	}
3258 
3259 	ilport = (stmf_i_local_port_t *)lport->lport_stmf_private;
3260 
3261 	/*
3262 	 * deregister ports that are not standby (proxy)
3263 	 */
3264 	if (stmf_state.stmf_alua_state == 1 &&
3265 	    ilport->ilport_standby == 0 &&
3266 	    ilport->ilport_alua == 1) {
3267 		stmf_ic_msg_t *ic_dereg_port;
3268 		stmf_ic_msg_status_t ic_ret;
3269 		ic_dereg_port = ic_dereg_port_msg_alloc(
3270 		    lport->lport_id, 0, NULL, stmf_proxy_msg_id);
3271 		if (ic_dereg_port) {
3272 			ic_ret = ic_tx_msg(ic_dereg_port);
3273 			if (ic_ret == STMF_IC_MSG_SUCCESS) {
3274 				stmf_proxy_msg_id++;
3275 			}
3276 		}
3277 	}
3278 
3279 	if (ilport->ilport_nsessions == 0) {
3280 		if (ilport->ilport_next)
3281 			ilport->ilport_next->ilport_prev = ilport->ilport_prev;
3282 		if (ilport->ilport_prev)
3283 			ilport->ilport_prev->ilport_next = ilport->ilport_next;
3284 		else
3285 			stmf_state.stmf_ilportlist = ilport->ilport_next;
3286 		id_free(stmf_state.stmf_ilport_inst_space,
3287 		    ilport->ilport_instance);
3288 		rw_destroy(&ilport->ilport_lock);
3289 		stmf_state.stmf_nlports--;
3290 		if (lport->lport_pp) {
3291 			((stmf_i_port_provider_t *)
3292 			    (lport->lport_pp->pp_stmf_private))->ipp_npps--;
3293 		}
3294 		ilport->ilport_tg = NULL;
3295 		STMF_EVENT_FREE_HANDLE(ilport->ilport_event_hdl);
3296 	} else {
3297 		mutex_exit(&stmf_state.stmf_lock);
3298 		return (STMF_BUSY);
3299 	}
3300 	if (ilport->ilport_kstat_info) {
3301 		kmem_free(ilport->ilport_kstat_info->ks_data,
3302 		    ilport->ilport_kstat_info->ks_data_size);
3303 		kstat_delete(ilport->ilport_kstat_info);
3304 	}
3305 	if (ilport->ilport_kstat_io) {
3306 		kstat_delete(ilport->ilport_kstat_io);
3307 		mutex_destroy(&ilport->ilport_kstat_lock);
3308 	}
3309 	stmf_delete_itl_kstat_by_lport(ilport->ilport_kstat_tgt_name);
3310 	mutex_exit(&stmf_state.stmf_lock);
3311 	return (STMF_SUCCESS);
3312 }
3313 
3314 /*
3315  * Rport id/instance mappings remain valid until STMF is unloaded
3316  */
3317 static int
3318 stmf_irport_compare(const void *void_irport1, const void *void_irport2)
3319 {
3320 	const	stmf_i_remote_port_t	*irport1 = void_irport1;
3321 	const	stmf_i_remote_port_t	*irport2 = void_irport2;
3322 	int			result;
3323 
3324 	/* Sort by code set then ident */
3325 	if (irport1->irport_id->code_set <
3326 	    irport2->irport_id->code_set) {
3327 		return (-1);
3328 	} else if (irport1->irport_id->code_set >
3329 	    irport2->irport_id->code_set) {
3330 		return (1);
3331 	}
3332 
3333 	/* Next by ident length */
3334 	if (irport1->irport_id->ident_length <
3335 	    irport2->irport_id->ident_length) {
3336 		return (-1);
3337 	} else if (irport1->irport_id->ident_length >
3338 	    irport2->irport_id->ident_length) {
3339 		return (1);
3340 	}
3341 
3342 	/* Code set and ident length both match, now compare idents */
3343 	result = memcmp(irport1->irport_id->ident,
3344 	    irport2->irport_id->ident,
3345 	    irport1->irport_id->ident_length);
3346 
3347 	if (result < 0) {
3348 		return (-1);
3349 	} else if (result > 0) {
3350 		return (1);
3351 	}
3352 
3353 	return (0);
3354 }
3355 
3356 static stmf_i_remote_port_t *
3357 stmf_irport_create(scsi_devid_desc_t *rport_devid)
3358 {
3359 	int			alloc_len;
3360 	stmf_i_remote_port_t	*irport;
3361 
3362 	/*
3363 	 * Lookup will bump the refcnt if there's an existing rport
3364 	 * context for this identifier.
3365 	 */
3366 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
3367 
3368 	alloc_len = sizeof (*irport) + sizeof (scsi_devid_desc_t) +
3369 	    rport_devid->ident_length - 1;
3370 	irport = kmem_zalloc(alloc_len, KM_NOSLEEP);
3371 	if (irport == NULL) {
3372 		return (NULL);
3373 	}
3374 
3375 	irport->irport_instance =
3376 	    id_alloc_nosleep(stmf_state.stmf_irport_inst_space);
3377 	if (irport->irport_instance == -1) {
3378 		kmem_free(irport, alloc_len);
3379 		return (NULL);
3380 	}
3381 
3382 	irport->irport_id =
3383 	    (struct scsi_devid_desc *)(irport + 1); /* Ptr. Arith. */
3384 	bcopy(rport_devid, irport->irport_id,
3385 	    sizeof (scsi_devid_desc_t) + rport_devid->ident_length - 1);
3386 	irport->irport_refcnt = 1;
3387 	mutex_init(&irport->irport_mutex, NULL, MUTEX_DEFAULT, NULL);
3388 
3389 	return (irport);
3390 }
3391 
3392 static void
3393 stmf_irport_destroy(stmf_i_remote_port_t *irport)
3394 {
3395 	id_free(stmf_state.stmf_irport_inst_space, irport->irport_instance);
3396 	mutex_destroy(&irport->irport_mutex);
3397 	kmem_free(irport, sizeof (*irport) + sizeof (scsi_devid_desc_t) +
3398 	    irport->irport_id->ident_length - 1);
3399 }
3400 
3401 static stmf_i_remote_port_t *
3402 stmf_irport_register(scsi_devid_desc_t *rport_devid)
3403 {
3404 	stmf_i_remote_port_t	*irport;
3405 
3406 	mutex_enter(&stmf_state.stmf_lock);
3407 
3408 	/*
3409 	 * Lookup will bump the refcnt if there's an existing rport
3410 	 * context for this identifier.
3411 	 */
3412 	if ((irport = stmf_irport_lookup_locked(rport_devid)) != NULL) {
3413 		mutex_exit(&stmf_state.stmf_lock);
3414 		return (irport);
3415 	}
3416 
3417 	irport = stmf_irport_create(rport_devid);
3418 	if (irport == NULL) {
3419 		mutex_exit(&stmf_state.stmf_lock);
3420 		return (NULL);
3421 	}
3422 
3423 	avl_add(&stmf_state.stmf_irportlist, irport);
3424 	mutex_exit(&stmf_state.stmf_lock);
3425 
3426 	return (irport);
3427 }
3428 
3429 static stmf_i_remote_port_t *
3430 stmf_irport_lookup_locked(scsi_devid_desc_t *rport_devid)
3431 {
3432 	stmf_i_remote_port_t	*irport;
3433 	stmf_i_remote_port_t	tmp_irport;
3434 
3435 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
3436 	tmp_irport.irport_id = rport_devid;
3437 	irport = avl_find(&stmf_state.stmf_irportlist, &tmp_irport, NULL);
3438 	if (irport != NULL) {
3439 		mutex_enter(&irport->irport_mutex);
3440 		irport->irport_refcnt++;
3441 		mutex_exit(&irport->irport_mutex);
3442 	}
3443 
3444 	return (irport);
3445 }
3446 
3447 static void
3448 stmf_irport_deregister(stmf_i_remote_port_t *irport)
3449 {
3450 	/*
3451 	 * If we were actually going to remove unreferenced remote ports
3452 	 * we would want to acquire stmf_state.stmf_lock before getting
3453 	 * the irport mutex.
3454 	 *
3455 	 * Instead we're just going to leave it there even if unreferenced.
3456 	 */
3457 	mutex_enter(&irport->irport_mutex);
3458 	irport->irport_refcnt--;
3459 	mutex_exit(&irport->irport_mutex);
3460 }
3461 
3462 /*
3463  * Port provider has to make sure that register/deregister session and
3464  * port are serialized calls.
3465  */
3466 stmf_status_t
3467 stmf_register_scsi_session(stmf_local_port_t *lport, stmf_scsi_session_t *ss)
3468 {
3469 	stmf_i_scsi_session_t *iss;
3470 	stmf_i_local_port_t *ilport = (stmf_i_local_port_t *)
3471 	    lport->lport_stmf_private;
3472 	uint8_t		lun[8];
3473 
3474 	/*
3475 	 * Port state has to be online to register a scsi session. It is
3476 	 * possible that we started an offline operation and a new SCSI
3477 	 * session started at the same time (in that case also we are going
3478 	 * to fail the registeration). But any other state is simply
3479 	 * a bad port provider implementation.
3480 	 */
3481 	if (ilport->ilport_state != STMF_STATE_ONLINE) {
3482 		if (ilport->ilport_state != STMF_STATE_OFFLINING) {
3483 			stmf_trace(lport->lport_alias, "Port is trying to "
3484 			    "register a session while the state is neither "
3485 			    "online nor offlining");
3486 		}
3487 		return (STMF_FAILURE);
3488 	}
3489 	bzero(lun, 8);
3490 	iss = (stmf_i_scsi_session_t *)ss->ss_stmf_private;
3491 	if ((iss->iss_irport = stmf_irport_register(ss->ss_rport_id)) == NULL) {
3492 		stmf_trace(lport->lport_alias, "Could not register "
3493 		    "remote port during session registration");
3494 		return (STMF_FAILURE);
3495 	}
3496 
3497 	iss->iss_flags |= ISS_BEING_CREATED;
3498 
3499 	/* sessions use the ilport_lock. No separate lock is required */
3500 	iss->iss_lockp = &ilport->ilport_lock;
3501 
3502 	if (iss->iss_sm != NULL)
3503 		cmn_err(CE_PANIC, "create lun map called with non NULL map");
3504 	iss->iss_sm = (stmf_lun_map_t *)kmem_zalloc(sizeof (stmf_lun_map_t),
3505 	    KM_SLEEP);
3506 
3507 	mutex_enter(&stmf_state.stmf_lock);
3508 	rw_enter(&ilport->ilport_lock, RW_WRITER);
3509 	(void) stmf_session_create_lun_map(ilport, iss);
3510 	ilport->ilport_nsessions++;
3511 	iss->iss_next = ilport->ilport_ss_list;
3512 	ilport->ilport_ss_list = iss;
3513 	rw_exit(&ilport->ilport_lock);
3514 	mutex_exit(&stmf_state.stmf_lock);
3515 
3516 	iss->iss_creation_time = ddi_get_time();
3517 	ss->ss_session_id = atomic_add_64_nv(&stmf_session_counter, 1);
3518 	iss->iss_flags &= ~ISS_BEING_CREATED;
3519 	/* XXX should we remove ISS_LUN_INVENTORY_CHANGED on new session? */
3520 	iss->iss_flags &= ~ISS_LUN_INVENTORY_CHANGED;
3521 	DTRACE_PROBE2(session__online, stmf_local_port_t *, lport,
3522 	    stmf_scsi_session_t *, ss);
3523 	return (STMF_SUCCESS);
3524 }
3525 
3526 void
3527 stmf_deregister_scsi_session(stmf_local_port_t *lport, stmf_scsi_session_t *ss)
3528 {
3529 	stmf_i_local_port_t *ilport = (stmf_i_local_port_t *)
3530 	    lport->lport_stmf_private;
3531 	stmf_i_scsi_session_t *iss, **ppss;
3532 	int found = 0;
3533 	stmf_ic_msg_t *ic_session_dereg;
3534 	stmf_status_t ic_ret = STMF_FAILURE;
3535 
3536 	DTRACE_PROBE2(session__offline, stmf_local_port_t *, lport,
3537 	    stmf_scsi_session_t *, ss);
3538 
3539 	iss = (stmf_i_scsi_session_t *)ss->ss_stmf_private;
3540 	if (ss->ss_rport_alias) {
3541 		ss->ss_rport_alias = NULL;
3542 	}
3543 
3544 try_dereg_ss_again:
3545 	mutex_enter(&stmf_state.stmf_lock);
3546 	atomic_and_32(&iss->iss_flags,
3547 	    ~(ISS_LUN_INVENTORY_CHANGED | ISS_GOT_INITIAL_LUNS));
3548 	if (iss->iss_flags & ISS_EVENT_ACTIVE) {
3549 		mutex_exit(&stmf_state.stmf_lock);
3550 		delay(1);
3551 		goto try_dereg_ss_again;
3552 	}
3553 
3554 	/* dereg proxy session if not standby port */
3555 	if (stmf_state.stmf_alua_state == 1 &&
3556 	    ilport->ilport_standby == 0 &&
3557 	    ilport->ilport_alua == 1) {
3558 		ic_session_dereg = ic_session_dereg_msg_alloc(
3559 		    ss, stmf_proxy_msg_id);
3560 		if (ic_session_dereg) {
3561 			ic_ret = ic_tx_msg(ic_session_dereg);
3562 			if (ic_ret == STMF_IC_MSG_SUCCESS) {
3563 				stmf_proxy_msg_id++;
3564 			}
3565 		}
3566 	}
3567 
3568 	rw_enter(&ilport->ilport_lock, RW_WRITER);
3569 	for (ppss = &ilport->ilport_ss_list; *ppss != NULL;
3570 	    ppss = &((*ppss)->iss_next)) {
3571 		if (iss == (*ppss)) {
3572 			*ppss = (*ppss)->iss_next;
3573 			found = 1;
3574 			break;
3575 		}
3576 	}
3577 	if (!found) {
3578 		cmn_err(CE_PANIC, "Deregister session called for non existent"
3579 		    " session");
3580 	}
3581 	ilport->ilport_nsessions--;
3582 
3583 	stmf_irport_deregister(iss->iss_irport);
3584 	(void) stmf_session_destroy_lun_map(ilport, iss);
3585 	rw_exit(&ilport->ilport_lock);
3586 	mutex_exit(&stmf_state.stmf_lock);
3587 }
3588 
3589 stmf_i_scsi_session_t *
3590 stmf_session_id_to_issptr(uint64_t session_id, int stay_locked)
3591 {
3592 	stmf_i_local_port_t *ilport;
3593 	stmf_i_scsi_session_t *iss;
3594 
3595 	mutex_enter(&stmf_state.stmf_lock);
3596 	for (ilport = stmf_state.stmf_ilportlist; ilport != NULL;
3597 	    ilport = ilport->ilport_next) {
3598 		rw_enter(&ilport->ilport_lock, RW_WRITER);
3599 		for (iss = ilport->ilport_ss_list; iss != NULL;
3600 		    iss = iss->iss_next) {
3601 			if (iss->iss_ss->ss_session_id == session_id) {
3602 				if (!stay_locked)
3603 					rw_exit(&ilport->ilport_lock);
3604 				mutex_exit(&stmf_state.stmf_lock);
3605 				return (iss);
3606 			}
3607 		}
3608 		rw_exit(&ilport->ilport_lock);
3609 	}
3610 	mutex_exit(&stmf_state.stmf_lock);
3611 	return (NULL);
3612 }
3613 
3614 #define	MAX_ALIAS		128
3615 
3616 static int
3617 stmf_itl_kstat_compare(const void *itl_kstat_1, const void *itl_kstat_2)
3618 {
3619 	const	stmf_i_itl_kstat_t	*kstat_nm1 = itl_kstat_1;
3620 	const	stmf_i_itl_kstat_t	*kstat_nm2 = itl_kstat_2;
3621 	int	ret;
3622 
3623 	ret = strcmp(kstat_nm1->iitl_kstat_nm, kstat_nm2->iitl_kstat_nm);
3624 	if (ret < 0) {
3625 		return (-1);
3626 	} else if (ret > 0) {
3627 		return (1);
3628 	}
3629 	return (0);
3630 }
3631 
3632 static stmf_i_itl_kstat_t *
3633 stmf_itl_kstat_lookup(char *kstat_nm)
3634 {
3635 	stmf_i_itl_kstat_t	tmp;
3636 	stmf_i_itl_kstat_t	*itl_kstat;
3637 
3638 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
3639 	(void) strcpy(tmp.iitl_kstat_nm, kstat_nm);
3640 	itl_kstat = avl_find(&stmf_state.stmf_itl_kstat_list, &tmp, NULL);
3641 	return (itl_kstat);
3642 }
3643 
3644 static void
3645 stmf_delete_itl_kstat_by_lport(char *tgt)
3646 {
3647 	stmf_i_itl_kstat_t	*ks_itl, *next;
3648 
3649 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
3650 	ks_itl = avl_first(&stmf_state.stmf_itl_kstat_list);
3651 	for (; ks_itl != NULL; ks_itl = next) {
3652 		next = AVL_NEXT(&stmf_state.stmf_itl_kstat_list, ks_itl);
3653 		if (strcmp(ks_itl->iitl_kstat_lport, tgt) == 0) {
3654 			stmf_teardown_itl_kstats(ks_itl);
3655 			avl_remove(&stmf_state.stmf_itl_kstat_list, ks_itl);
3656 			kmem_free(ks_itl, sizeof (stmf_i_itl_kstat_t));
3657 		}
3658 	}
3659 }
3660 
3661 static void
3662 stmf_delete_itl_kstat_by_guid(char *guid)
3663 {
3664 	stmf_i_itl_kstat_t	*ks_itl, *next;
3665 
3666 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
3667 	ks_itl = avl_first(&stmf_state.stmf_itl_kstat_list);
3668 	for (; ks_itl != NULL; ks_itl = next) {
3669 		next = AVL_NEXT(&stmf_state.stmf_itl_kstat_list, ks_itl);
3670 		if (strcmp(ks_itl->iitl_kstat_guid, guid) == 0) {
3671 			stmf_teardown_itl_kstats(ks_itl);
3672 			avl_remove(&stmf_state.stmf_itl_kstat_list, ks_itl);
3673 			kmem_free(ks_itl, sizeof (stmf_i_itl_kstat_t));
3674 		}
3675 	}
3676 }
3677 
3678 static stmf_i_itl_kstat_t *
3679 stmf_itl_kstat_create(stmf_itl_data_t *itl, char *nm,
3680     scsi_devid_desc_t *lport, scsi_devid_desc_t *lun)
3681 {
3682 	stmf_i_itl_kstat_t	*ks_itl;
3683 	int			i, len;
3684 
3685 	ASSERT(mutex_owned(&stmf_state.stmf_lock));
3686 	if ((ks_itl = stmf_itl_kstat_lookup(nm)) != NULL)
3687 		return (ks_itl);
3688 
3689 	len = sizeof (stmf_i_itl_kstat_t);
3690 	ks_itl = kmem_zalloc(len, KM_NOSLEEP);
3691 	if (ks_itl == NULL)
3692 		return (NULL);
3693 
3694 	(void) strcpy(ks_itl->iitl_kstat_nm, nm);
3695 	bcopy(lport->ident, ks_itl->iitl_kstat_lport, lport->ident_length);
3696 	ks_itl->iitl_kstat_lport[lport->ident_length] = '\0';
3697 	for (i = 0; i < STMF_GUID_INPUT / 2; i++) {
3698 		(void) sprintf(&ks_itl->iitl_kstat_guid[i * 2], "%02x",
3699 		    lun->ident[i]);
3700 	}
3701 	ks_itl->iitl_kstat_strbuf = itl->itl_kstat_strbuf;
3702 	ks_itl->iitl_kstat_strbuflen = itl->itl_kstat_strbuflen;
3703 	ks_itl->iitl_kstat_info = itl->itl_kstat_info;
3704 	ks_itl->iitl_kstat_taskq = itl->itl_kstat_taskq;
3705 	ks_itl->iitl_kstat_lu_xfer = itl->itl_kstat_lu_xfer;
3706 	ks_itl->iitl_kstat_lport_xfer = itl->itl_kstat_lport_xfer;
3707 	avl_add(&stmf_state.stmf_itl_kstat_list, ks_itl);
3708 
3709 	return (ks_itl);
3710 }
3711 
3712 stmf_status_t
3713 stmf_setup_itl_kstats(stmf_itl_data_t *itl)
3714 {
3715 	char				ks_itl_id[32];
3716 	char				ks_nm[KSTAT_STRLEN];
3717 	char				ks_itl_nm[KSTAT_STRLEN];
3718 	stmf_kstat_itl_info_t		*ks_itl;
3719 	stmf_scsi_session_t		*ss;
3720 	stmf_i_scsi_session_t		*iss;
3721 	stmf_i_local_port_t		*ilport;
3722 	char				*strbuf;
3723 	int				id, len, i;
3724 	char				*rport_alias;
3725 	char				*lport_alias;
3726 	char				*lu_alias;
3727 	stmf_i_itl_kstat_t		*tmp_kstat;
3728 
3729 	/*
3730 	 * Allocate enough memory in the ITL to hold the relevant
3731 	 * identifiers.
3732 	 * rport and lport identifiers come from the stmf_scsi_session_t.
3733 	 * ident might not be null terminated.
3734 	 */
3735 	ss = itl->itl_session->iss_ss;
3736 	iss = ss->ss_stmf_private;
3737 	ilport = ss->ss_lport->lport_stmf_private;
3738 	(void) snprintf(ks_itl_id, 32, "%d.%d.%d",
3739 	    iss->iss_irport->irport_instance, ilport->ilport_instance,
3740 	    itl->itl_lun);
3741 
3742 	(void) snprintf(ks_itl_nm, KSTAT_STRLEN, "itl_%s", ks_itl_id);
3743 	/*
3744 	 * let's verify this itl_kstat already exist
3745 	 */
3746 	if ((tmp_kstat = stmf_itl_kstat_lookup(ks_itl_nm)) != NULL) {
3747 		itl->itl_kstat_strbuf = tmp_kstat->iitl_kstat_strbuf;
3748 		itl->itl_kstat_strbuflen = tmp_kstat->iitl_kstat_strbuflen;
3749 		itl->itl_kstat_info = tmp_kstat->iitl_kstat_info;
3750 		itl->itl_kstat_taskq = tmp_kstat->iitl_kstat_taskq;
3751 		itl->itl_kstat_lu_xfer = tmp_kstat->iitl_kstat_lu_xfer;
3752 		itl->itl_kstat_lport_xfer = tmp_kstat->iitl_kstat_lport_xfer;
3753 		return (STMF_SUCCESS);
3754 	}
3755 
3756 	/* New itl_kstat */
3757 	rport_alias = (ss->ss_rport_alias == NULL) ?
3758 	    "" : ss->ss_rport_alias;
3759 	lport_alias = (ss->ss_lport->lport_alias == NULL) ?
3760 	    "" : ss->ss_lport->lport_alias;
3761 	lu_alias = (itl->itl_ilu->ilu_lu->lu_alias == NULL) ?
3762 	    "" : itl->itl_ilu->ilu_lu->lu_alias;
3763 
3764 	itl->itl_kstat_strbuflen = (ss->ss_rport_id->ident_length + 1) +
3765 	    (strnlen(rport_alias, MAX_ALIAS) + 1) +
3766 	    (ss->ss_lport->lport_id->ident_length + 1) +
3767 	    (strnlen(lport_alias, MAX_ALIAS) + 1) +
3768 	    (STMF_GUID_INPUT + 1) +
3769 	    (strnlen(lu_alias, MAX_ALIAS) + 1) +
3770 	    MAX_PROTO_STR_LEN;
3771 	itl->itl_kstat_strbuf = kmem_zalloc(itl->itl_kstat_strbuflen,
3772 	    KM_NOSLEEP);
3773 	if (itl->itl_kstat_strbuf == NULL) {
3774 		return (STMF_ALLOC_FAILURE);
3775 	}
3776 
3777 	ks_itl = (stmf_kstat_itl_info_t *)kmem_zalloc(sizeof (*ks_itl),
3778 	    KM_NOSLEEP);
3779 	if (ks_itl == NULL) {
3780 		kmem_free(itl->itl_kstat_strbuf, itl->itl_kstat_strbuflen);
3781 		return (STMF_ALLOC_FAILURE);
3782 	}
3783 
3784 	if ((itl->itl_kstat_info = kstat_create(STMF_MODULE_NAME,
3785 	    0, ks_itl_nm, "misc", KSTAT_TYPE_NAMED,
3786 	    sizeof (stmf_kstat_itl_info_t) / sizeof (kstat_named_t),
3787 	    KSTAT_FLAG_VIRTUAL)) == NULL) {
3788 		goto itl_kstat_cleanup;
3789 	}
3790 
3791 	itl->itl_kstat_info->ks_data_size += itl->itl_kstat_strbuflen;
3792 	itl->itl_kstat_info->ks_data = ks_itl;
3793 
3794 	kstat_named_init(&ks_itl->i_rport_name, "rport-name",
3795 	    KSTAT_DATA_STRING);
3796 	kstat_named_init(&ks_itl->i_rport_alias, "rport-alias",
3797 	    KSTAT_DATA_STRING);
3798 	kstat_named_init(&ks_itl->i_lport_name, "lport-name",
3799 	    KSTAT_DATA_STRING);
3800 	kstat_named_init(&ks_itl->i_lport_alias, "lport-alias",
3801 	    KSTAT_DATA_STRING);
3802 	kstat_named_init(&ks_itl->i_protocol, "protocol",
3803 	    KSTAT_DATA_STRING);
3804 	kstat_named_init(&ks_itl->i_lu_guid, "lu-guid",
3805 	    KSTAT_DATA_STRING);
3806 	kstat_named_init(&ks_itl->i_lu_alias, "lu-alias",
3807 	    KSTAT_DATA_STRING);
3808 	kstat_named_init(&ks_itl->i_lu_number, "lu-number",
3809 	    KSTAT_DATA_UINT64);
3810 	kstat_named_init(&ks_itl->i_task_waitq_elapsed, "task-waitq-elapsed",
3811 	    KSTAT_DATA_UINT64);
3812 	kstat_named_init(&ks_itl->i_task_read_elapsed, "task-read-elapsed",
3813 	    KSTAT_DATA_UINT64);
3814 	kstat_named_init(&ks_itl->i_task_write_elapsed, "task-write-elapsed",
3815 	    KSTAT_DATA_UINT64);
3816 	kstat_named_init(&ks_itl->i_lu_read_elapsed, "lu-read-elapsed",
3817 	    KSTAT_DATA_UINT64);
3818 	kstat_named_init(&ks_itl->i_lu_write_elapsed, "lu-write-elapsed",
3819 	    KSTAT_DATA_UINT64);
3820 	kstat_named_init(&ks_itl->i_lport_read_elapsed, "lport-read-elapsed",
3821 	    KSTAT_DATA_UINT64);
3822 	kstat_named_init(&ks_itl->i_lport_write_elapsed, "lport-write-elapsed",
3823 	    KSTAT_DATA_UINT64);
3824 
3825 	strbuf = itl->itl_kstat_strbuf;
3826 
3827 	/* Rport */
3828 	len = ss->ss_rport_id->ident_length;
3829 	bcopy(ss->ss_rport_id->ident, strbuf, len);
3830 	strbuf += len;
3831 	*strbuf = '\0';
3832 	kstat_named_setstr(&ks_itl->i_rport_name, strbuf - len);
3833 	strbuf++;
3834 
3835 	len = strnlen(rport_alias, MAX_ALIAS);
3836 	(void) strncpy(strbuf, rport_alias, len + 1);
3837 	kstat_named_setstr(&ks_itl->i_rport_alias, strbuf);
3838 	strbuf += len + 1;
3839 
3840 	/* Lport */
3841 	len = ss->ss_lport->lport_id->ident_length;
3842 	bcopy(ss->ss_lport->lport_id->ident, strbuf, len);
3843 	strbuf += len;
3844 	*strbuf = '\0';
3845 	kstat_named_setstr(&ks_itl->i_lport_name, strbuf - len);
3846 	strbuf++;
3847 
3848 	len = strnlen(lport_alias, MAX_ALIAS);
3849 	(void) strncpy(strbuf, lport_alias, len + 1);
3850 	kstat_named_setstr(&ks_itl->i_lport_alias, strbuf);
3851 	strbuf += len + 1;
3852 
3853 	id = (ss->ss_lport->lport_id->protocol_id > PROTOCOL_ANY) ?
3854 	    PROTOCOL_ANY : ss->ss_lport->lport_id->protocol_id;
3855 	kstat_named_setstr(&ks_itl->i_protocol, protocol_ident[id]);
3856 
3857 	/* LU */
3858 	for (i = 0; i < STMF_GUID_INPUT / 2; i++) {
3859 		(void) sprintf(&strbuf[i * 2], "%02x",
3860 		    itl->itl_ilu->ilu_lu->lu_id->ident[i]);
3861 	}
3862 	kstat_named_setstr(&ks_itl->i_lu_guid, strbuf);
3863 	strbuf += STMF_GUID_INPUT + 1;
3864 
3865 	len = strnlen(lu_alias, MAX_ALIAS);
3866 	(void) strncpy(strbuf, lu_alias, len + 1);
3867 	kstat_named_setstr(&ks_itl->i_lu_alias, strbuf);
3868 	strbuf += len + 1;
3869 
3870 	ks_itl->i_lu_number.value.ui64 = itl->itl_lun;
3871 
3872 	/* Now create the I/O kstats */
3873 	(void) snprintf(ks_nm, KSTAT_STRLEN, "itl_tasks_%s",  ks_itl_id);
3874 	if ((itl->itl_kstat_taskq = kstat_create(STMF_MODULE_NAME, 0,
3875 	    ks_nm, "io", KSTAT_TYPE_IO, 1, 0)) == NULL) {
3876 		goto itl_kstat_cleanup;
3877 	}
3878 
3879 	(void) snprintf(ks_nm, KSTAT_STRLEN, "itl_lu_%s",  ks_itl_id);
3880 	if ((itl->itl_kstat_lu_xfer = kstat_create(STMF_MODULE_NAME, 0,
3881 	    ks_nm, "io", KSTAT_TYPE_IO, 1, 0)) == NULL) {
3882 		goto itl_kstat_cleanup;
3883 	}
3884 
3885 	(void) snprintf(ks_nm, KSTAT_STRLEN, "itl_lport_%s",  ks_itl_id);
3886 	if ((itl->itl_kstat_lport_xfer = kstat_create(STMF_MODULE_NAME, 0,
3887 	    ks_nm, "io", KSTAT_TYPE_IO, 1, 0)) == NULL) {
3888 		goto itl_kstat_cleanup;
3889 	}
3890 
3891 	/* Install all the kstats */
3892 	kstat_install(itl->itl_kstat_info);
3893 	kstat_install(itl->itl_kstat_taskq);
3894 	kstat_install(itl->itl_kstat_lu_xfer);
3895 	kstat_install(itl->itl_kstat_lport_xfer);
3896 
3897 	/* Add new itl_kstat to stmf_itl_kstat_list */
3898 	if (stmf_itl_kstat_create(itl, ks_itl_nm, ss->ss_lport->lport_id,
3899 	    itl->itl_ilu->ilu_lu->lu_id) != NULL)
3900 		return (STMF_SUCCESS);
3901 
3902 itl_kstat_cleanup:
3903 	if (itl->itl_kstat_taskq)
3904 		kstat_delete(itl->itl_kstat_taskq);
3905 	if (itl->itl_kstat_lu_xfer)
3906 		kstat_delete(itl->itl_kstat_lu_xfer);
3907 	if (itl->itl_kstat_lport_xfer)
3908 		kstat_delete(itl->itl_kstat_lport_xfer);
3909 	if (itl->itl_kstat_info)
3910 		kstat_delete(itl->itl_kstat_info);
3911 	kmem_free(ks_itl, sizeof (*ks_itl));
3912 	kmem_free(itl->itl_kstat_strbuf, itl->itl_kstat_strbuflen);
3913 	cmn_err(CE_WARN, "STMF: kstat_create itl failed");
3914 	return (STMF_ALLOC_FAILURE);
3915 }
3916 
3917 static void
3918 stmf_teardown_itl_kstats(stmf_i_itl_kstat_t *ks)
3919 {
3920 	kstat_delete(ks->iitl_kstat_lport_xfer);
3921 	kstat_delete(ks->iitl_kstat_lu_xfer);
3922 	kstat_delete(ks->iitl_kstat_taskq);
3923 	kmem_free(ks->iitl_kstat_info->ks_data, sizeof (stmf_kstat_itl_info_t));
3924 	kstat_delete(ks->iitl_kstat_info);
3925 	kmem_free(ks->iitl_kstat_strbuf, ks->iitl_kstat_strbuflen);
3926 }
3927 
3928 void
3929 stmf_release_itl_handle(stmf_lu_t *lu, stmf_itl_data_t *itl)
3930 {
3931 	stmf_itl_data_t **itlpp;
3932 	stmf_i_lu_t *ilu;
3933 
3934 	ASSERT(itl->itl_flags & STMF_ITL_BEING_TERMINATED);
3935 
3936 	ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
3937 	mutex_enter(&ilu->ilu_task_lock);
3938 	for (itlpp = &ilu->ilu_itl_list; (*itlpp) != NULL;
3939 	    itlpp = &(*itlpp)->itl_next) {
3940 		if ((*itlpp) == itl)
3941 			break;
3942 	}
3943 	ASSERT((*itlpp) != NULL);
3944 	*itlpp = itl->itl_next;
3945 	mutex_exit(&ilu->ilu_task_lock);
3946 	lu->lu_abort(lu, STMF_LU_ITL_HANDLE_REMOVED, itl->itl_handle,
3947 	    (uint32_t)itl->itl_hdlrm_reason);
3948 
3949 	kmem_free(itl, sizeof (*itl));
3950 }
3951 
3952 stmf_status_t
3953 stmf_register_itl_handle(stmf_lu_t *lu, uint8_t *lun,
3954     stmf_scsi_session_t *ss, uint64_t session_id, void *itl_handle)
3955 {
3956 	stmf_itl_data_t *itl;
3957 	stmf_i_scsi_session_t *iss;
3958 	stmf_lun_map_ent_t *lun_map_ent;
3959 	stmf_i_lu_t *ilu;
3960 	uint16_t n;
3961 
3962 	ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
3963 	if (ss == NULL) {
3964 		iss = stmf_session_id_to_issptr(session_id, 1);
3965 		if (iss == NULL)
3966 			return (STMF_NOT_FOUND);
3967 	} else {
3968 		iss = (stmf_i_scsi_session_t *)ss->ss_stmf_private;
3969 	}
3970 
3971 	/*
3972 	 * Acquire stmf_lock for stmf_itl_kstat_lookup.
3973 	 */
3974 	mutex_enter(&stmf_state.stmf_lock);
3975 	rw_enter(iss->iss_lockp, RW_WRITER);
3976 	n = ((uint16_t)lun[1] | (((uint16_t)(lun[0] & 0x3F)) << 8));
3977 	lun_map_ent = (stmf_lun_map_ent_t *)
3978 	    stmf_get_ent_from_map(iss->iss_sm, n);
3979 	if ((lun_map_ent == NULL) || (lun_map_ent->ent_lu != lu)) {
3980 		rw_exit(iss->iss_lockp);
3981 		mutex_exit(&stmf_state.stmf_lock);
3982 		return (STMF_NOT_FOUND);
3983 	}
3984 	if (lun_map_ent->ent_itl_datap != NULL) {
3985 		rw_exit(iss->iss_lockp);
3986 		mutex_exit(&stmf_state.stmf_lock);
3987 		return (STMF_ALREADY);
3988 	}
3989 
3990 	itl = (stmf_itl_data_t *)kmem_zalloc(sizeof (*itl), KM_NOSLEEP);
3991 	if (itl == NULL) {
3992 		rw_exit(iss->iss_lockp);
3993 		mutex_exit(&stmf_state.stmf_lock);
3994 		return (STMF_ALLOC_FAILURE);
3995 	}
3996 
3997 	itl->itl_ilu = ilu;
3998 	itl->itl_session = iss;
3999 	itl->itl_counter = 1;
4000 	itl->itl_lun = n;
4001 	itl->itl_handle = itl_handle;
4002 
4003 	if (stmf_setup_itl_kstats(itl) != STMF_SUCCESS) {
4004 		kmem_free(itl, sizeof (*itl));
4005 		rw_exit(iss->iss_lockp);
4006 		mutex_exit(&stmf_state.stmf_lock);
4007 		return (STMF_ALLOC_FAILURE);
4008 	}
4009 
4010 	mutex_enter(&ilu->ilu_task_lock);
4011 	itl->itl_next = ilu->ilu_itl_list;
4012 	ilu->ilu_itl_list = itl;
4013 	mutex_exit(&ilu->ilu_task_lock);
4014 	lun_map_ent->ent_itl_datap = itl;
4015 	rw_exit(iss->iss_lockp);
4016 	mutex_exit(&stmf_state.stmf_lock);
4017 
4018 	return (STMF_SUCCESS);
4019 }
4020 
4021 void
4022 stmf_do_itl_dereg(stmf_lu_t *lu, stmf_itl_data_t *itl, uint8_t hdlrm_reason)
4023 {
4024 	uint8_t old, new;
4025 
4026 	do {
4027 		old = new = itl->itl_flags;
4028 		if (old & STMF_ITL_BEING_TERMINATED)
4029 			return;
4030 		new |= STMF_ITL_BEING_TERMINATED;
4031 	} while (atomic_cas_8(&itl->itl_flags, old, new) != old);
4032 	itl->itl_hdlrm_reason = hdlrm_reason;
4033 
4034 	ASSERT(itl->itl_counter);
4035 
4036 	if (atomic_add_32_nv(&itl->itl_counter, -1))
4037 		return;
4038 
4039 	drv_usecwait(10);
4040 	if (itl->itl_counter)
4041 		return;
4042 
4043 	stmf_release_itl_handle(lu, itl);
4044 }
4045 
4046 stmf_status_t
4047 stmf_deregister_all_lu_itl_handles(stmf_lu_t *lu)
4048 {
4049 	stmf_i_lu_t *ilu;
4050 	stmf_i_local_port_t *ilport;
4051 	stmf_i_scsi_session_t *iss;
4052 	stmf_lun_map_t *lm;
4053 	stmf_lun_map_ent_t *ent;
4054 	uint32_t nmaps, nu;
4055 	stmf_itl_data_t **itl_list;
4056 	int i;
4057 
4058 	ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
4059 
4060 dereg_itl_start:;
4061 	nmaps = ilu->ilu_ref_cnt;
4062 	if (nmaps == 0)
4063 		return (STMF_NOT_FOUND);
4064 	itl_list = (stmf_itl_data_t **)kmem_zalloc(
4065 	    nmaps * sizeof (stmf_itl_data_t *), KM_SLEEP);
4066 	mutex_enter(&stmf_state.stmf_lock);
4067 	if (nmaps != ilu->ilu_ref_cnt) {
4068 		/* Something changed, start all over */
4069 		mutex_exit(&stmf_state.stmf_lock);
4070 		kmem_free(itl_list, nmaps * sizeof (stmf_itl_data_t *));
4071 		goto dereg_itl_start;
4072 	}
4073 	nu = 0;
4074 	for (ilport = stmf_state.stmf_ilportlist; ilport != NULL;
4075 	    ilport = ilport->ilport_next) {
4076 		rw_enter(&ilport->ilport_lock, RW_WRITER);
4077 		for (iss = ilport->ilport_ss_list; iss != NULL;
4078 		    iss = iss->iss_next) {
4079 			lm = iss->iss_sm;
4080 			if (!lm)
4081 				continue;
4082 			for (i = 0; i < lm->lm_nentries; i++) {
4083 				if (lm->lm_plus[i] == NULL)
4084 					continue;
4085 				ent = (stmf_lun_map_ent_t *)lm->lm_plus[i];
4086 				if ((ent->ent_lu == lu) &&
4087 				    (ent->ent_itl_datap)) {
4088 					itl_list[nu++] = ent->ent_itl_datap;
4089 					ent->ent_itl_datap = NULL;
4090 					if (nu == nmaps) {
4091 						rw_exit(&ilport->ilport_lock);
4092 						goto dai_scan_done;
4093 					}
4094 				}
4095 			} /* lun table for a session */
4096 		} /* sessions */
4097 		rw_exit(&ilport->ilport_lock);
4098 	} /* ports */
4099 
4100 dai_scan_done:
4101 	mutex_exit(&stmf_state.stmf_lock);
4102 
4103 	for (i = 0; i < nu; i++) {
4104 		stmf_do_itl_dereg(lu, itl_list[i],
4105 		    STMF_ITL_REASON_DEREG_REQUEST);
4106 	}
4107 	kmem_free(itl_list, nmaps * sizeof (stmf_itl_data_t *));
4108 
4109 	return (STMF_SUCCESS);
4110 }
4111 
4112 stmf_status_t
4113 stmf_deregister_itl_handle(stmf_lu_t *lu, uint8_t *lun,
4114     stmf_scsi_session_t *ss, uint64_t session_id, void *itl_handle)
4115 {
4116 	stmf_i_scsi_session_t *iss;
4117 	stmf_itl_data_t *itl;
4118 	stmf_lun_map_ent_t *ent;
4119 	stmf_lun_map_t *lm;
4120 	int i;
4121 	uint16_t n;
4122 
4123 	if (ss == NULL) {
4124 		if (session_id == STMF_SESSION_ID_NONE)
4125 			return (STMF_INVALID_ARG);
4126 		iss = stmf_session_id_to_issptr(session_id, 1);
4127 		if (iss == NULL)
4128 			return (STMF_NOT_FOUND);
4129 	} else {
4130 		iss = (stmf_i_scsi_session_t *)ss->ss_stmf_private;
4131 		rw_enter(iss->iss_lockp, RW_WRITER);
4132 	}
4133 	lm = iss->iss_sm;
4134 	if (lm == NULL) {
4135 		rw_exit(iss->iss_lockp);
4136 		return (STMF_NOT_FOUND);
4137 	}
4138 
4139 	if (lun) {
4140 		n = ((uint16_t)lun[1] | (((uint16_t)(lun[0] & 0x3F)) << 8));
4141 		ent = (stmf_lun_map_ent_t *)
4142 		    stmf_get_ent_from_map(iss->iss_sm, n);
4143 	} else {
4144 		if (itl_handle == NULL) {
4145 			rw_exit(iss->iss_lockp);
4146 			return (STMF_INVALID_ARG);
4147 		}
4148 		ent = NULL;
4149 		for (i = 0; i < lm->lm_nentries; i++) {
4150 			if (lm->lm_plus[i] == NULL)
4151 				continue;
4152 			ent = (stmf_lun_map_ent_t *)lm->lm_plus[i];
4153 			if (ent->ent_itl_datap &&
4154 			    (ent->ent_itl_datap->itl_handle == itl_handle)) {
4155 				break;
4156 			}
4157 		}
4158 	}
4159 	if ((ent == NULL) || (ent->ent_lu != lu) ||
4160 	    (ent->ent_itl_datap == NULL)) {
4161 		rw_exit(iss->iss_lockp);
4162 		return (STMF_NOT_FOUND);
4163 	}
4164 	itl = ent->ent_itl_datap;
4165 	ent->ent_itl_datap = NULL;
4166 	rw_exit(iss->iss_lockp);
4167 	stmf_do_itl_dereg(lu, itl, STMF_ITL_REASON_DEREG_REQUEST);
4168 
4169 	return (STMF_SUCCESS);
4170 }
4171 
4172 stmf_status_t
4173 stmf_get_itl_handle(stmf_lu_t *lu, uint8_t *lun, stmf_scsi_session_t *ss,
4174     uint64_t session_id, void **itl_handle_retp)
4175 {
4176 	stmf_i_scsi_session_t *iss;
4177 	stmf_lun_map_ent_t *ent;
4178 	stmf_lun_map_t *lm;
4179 	stmf_status_t ret;
4180 	int i;
4181 	uint16_t n;
4182 
4183 	if (ss == NULL) {
4184 		iss = stmf_session_id_to_issptr(session_id, 1);
4185 		if (iss == NULL)
4186 			return (STMF_NOT_FOUND);
4187 	} else {
4188 		iss = (stmf_i_scsi_session_t *)ss->ss_stmf_private;
4189 		rw_enter(iss->iss_lockp, RW_WRITER);
4190 	}
4191 
4192 	ent = NULL;
4193 	if (lun == NULL) {
4194 		lm = iss->iss_sm;
4195 		for (i = 0; i < lm->lm_nentries; i++) {
4196 			if (lm->lm_plus[i] == NULL)
4197 				continue;
4198 			ent = (stmf_lun_map_ent_t *)lm->lm_plus[i];
4199 			if (ent->ent_lu == lu)
4200 				break;
4201 		}
4202 	} else {
4203 		n = ((uint16_t)lun[1] | (((uint16_t)(lun[0] & 0x3F)) << 8));
4204 		ent = (stmf_lun_map_ent_t *)
4205 		    stmf_get_ent_from_map(iss->iss_sm, n);
4206 		if (lu && (ent->ent_lu != lu))
4207 			ent = NULL;
4208 	}
4209 	if (ent && ent->ent_itl_datap) {
4210 		*itl_handle_retp = ent->ent_itl_datap->itl_handle;
4211 		ret = STMF_SUCCESS;
4212 	} else {
4213 		ret = STMF_NOT_FOUND;
4214 	}
4215 
4216 	rw_exit(iss->iss_lockp);
4217 	return (ret);
4218 }
4219 
4220 stmf_data_buf_t *
4221 stmf_alloc_dbuf(scsi_task_t *task, uint32_t size, uint32_t *pminsize,
4222     uint32_t flags)
4223 {
4224 	stmf_i_scsi_task_t *itask =
4225 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
4226 	stmf_local_port_t *lport = task->task_lport;
4227 	stmf_data_buf_t *dbuf;
4228 	uint8_t ndx;
4229 
4230 	ndx = stmf_first_zero[itask->itask_allocated_buf_map];
4231 	if (ndx == 0xff)
4232 		return (NULL);
4233 	dbuf = itask->itask_dbufs[ndx] = lport->lport_ds->ds_alloc_data_buf(
4234 	    task, size, pminsize, flags);
4235 	if (dbuf) {
4236 		task->task_cur_nbufs++;
4237 		itask->itask_allocated_buf_map |= (1 << ndx);
4238 		dbuf->db_handle = ndx;
4239 		return (dbuf);
4240 	}
4241 
4242 	return (NULL);
4243 }
4244 
4245 void
4246 stmf_free_dbuf(scsi_task_t *task, stmf_data_buf_t *dbuf)
4247 {
4248 	stmf_i_scsi_task_t *itask =
4249 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
4250 	stmf_local_port_t *lport = task->task_lport;
4251 
4252 	itask->itask_allocated_buf_map &= ~(1 << dbuf->db_handle);
4253 	task->task_cur_nbufs--;
4254 	lport->lport_ds->ds_free_data_buf(lport->lport_ds, dbuf);
4255 }
4256 
4257 stmf_data_buf_t *
4258 stmf_handle_to_buf(scsi_task_t *task, uint8_t h)
4259 {
4260 	stmf_i_scsi_task_t *itask;
4261 
4262 	itask = (stmf_i_scsi_task_t *)task->task_stmf_private;
4263 	if (h > 3)
4264 		return (NULL);
4265 	return (itask->itask_dbufs[h]);
4266 }
4267 
4268 /* ARGSUSED */
4269 struct scsi_task *
4270 stmf_task_alloc(struct stmf_local_port *lport, stmf_scsi_session_t *ss,
4271 			uint8_t *lun, uint16_t cdb_length_in, uint16_t ext_id)
4272 {
4273 	stmf_lu_t *lu;
4274 	stmf_i_scsi_session_t *iss;
4275 	stmf_i_lu_t *ilu;
4276 	stmf_i_scsi_task_t *itask;
4277 	stmf_i_scsi_task_t **ppitask;
4278 	scsi_task_t *task;
4279 	uint64_t *p;
4280 	uint8_t	*l;
4281 	stmf_lun_map_ent_t *lun_map_ent;
4282 	uint16_t cdb_length;
4283 	uint16_t luNbr;
4284 	uint8_t new_task = 0;
4285 
4286 	/*
4287 	 * We allocate 7 extra bytes for CDB to provide a cdb pointer which
4288 	 * is guaranteed to be 8 byte aligned. Some LU providers like OSD
4289 	 * depend upon this alignment.
4290 	 */
4291 	if (cdb_length_in >= 16)
4292 		cdb_length = cdb_length_in + 7;
4293 	else
4294 		cdb_length = 16 + 7;
4295 	iss = (stmf_i_scsi_session_t *)ss->ss_stmf_private;
4296 	luNbr = ((uint16_t)lun[1] | (((uint16_t)(lun[0] & 0x3F)) << 8));
4297 	rw_enter(iss->iss_lockp, RW_READER);
4298 	lun_map_ent =
4299 	    (stmf_lun_map_ent_t *)stmf_get_ent_from_map(iss->iss_sm, luNbr);
4300 	if (!lun_map_ent) {
4301 		lu = dlun0;
4302 	} else {
4303 		lu = lun_map_ent->ent_lu;
4304 	}
4305 	ilu = lu->lu_stmf_private;
4306 	if (ilu->ilu_flags & ILU_RESET_ACTIVE) {
4307 		rw_exit(iss->iss_lockp);
4308 		return (NULL);
4309 	}
4310 	do {
4311 		if (ilu->ilu_free_tasks == NULL) {
4312 			new_task = 1;
4313 			break;
4314 		}
4315 		mutex_enter(&ilu->ilu_task_lock);
4316 		for (ppitask = &ilu->ilu_free_tasks; (*ppitask != NULL) &&
4317 		    ((*ppitask)->itask_cdb_buf_size < cdb_length);
4318 		    ppitask = &((*ppitask)->itask_lu_free_next))
4319 			;
4320 		if (*ppitask) {
4321 			itask = *ppitask;
4322 			*ppitask = (*ppitask)->itask_lu_free_next;
4323 			ilu->ilu_ntasks_free--;
4324 			if (ilu->ilu_ntasks_free < ilu->ilu_ntasks_min_free)
4325 				ilu->ilu_ntasks_min_free = ilu->ilu_ntasks_free;
4326 		} else {
4327 			new_task = 1;
4328 		}
4329 		mutex_exit(&ilu->ilu_task_lock);
4330 	/* CONSTCOND */
4331 	} while (0);
4332 
4333 	if (!new_task) {
4334 		task = itask->itask_task;
4335 		task->task_timeout = 0;
4336 		p = (uint64_t *)&task->task_flags;
4337 		*p++ = 0; *p++ = 0; p++; p++; *p++ = 0; *p++ = 0; *p = 0;
4338 		itask->itask_ncmds = 0;
4339 	} else {
4340 		task = (scsi_task_t *)stmf_alloc(STMF_STRUCT_SCSI_TASK,
4341 		    cdb_length, AF_FORCE_NOSLEEP);
4342 		if (task == NULL) {
4343 			rw_exit(iss->iss_lockp);
4344 			return (NULL);
4345 		}
4346 		task->task_lu = lu;
4347 		l = task->task_lun_no;
4348 		l[0] = lun[0];
4349 		l[1] = lun[1];
4350 		l[2] = lun[2];
4351 		l[3] = lun[3];
4352 		l[4] = lun[4];
4353 		l[5] = lun[5];
4354 		l[6] = lun[6];
4355 		l[7] = lun[7];
4356 		task->task_cdb = (uint8_t *)task->task_port_private;
4357 		if ((ulong_t)(task->task_cdb) & 7ul) {
4358 			task->task_cdb = (uint8_t *)(((ulong_t)
4359 			    (task->task_cdb) + 7ul) & ~(7ul));
4360 		}
4361 		itask = (stmf_i_scsi_task_t *)task->task_stmf_private;
4362 		itask->itask_cdb_buf_size = cdb_length;
4363 	}
4364 	task->task_session = ss;
4365 	task->task_lport = lport;
4366 	task->task_cdb_length = cdb_length_in;
4367 	itask->itask_flags = ITASK_IN_TRANSITION;
4368 	itask->itask_waitq_time = 0;
4369 	itask->itask_lu_read_time = itask->itask_lu_write_time = 0;
4370 	itask->itask_lport_read_time = itask->itask_lport_write_time = 0;
4371 	itask->itask_read_xfer = itask->itask_write_xfer = 0;
4372 
4373 	if (new_task) {
4374 		if (lu->lu_task_alloc(task) != STMF_SUCCESS) {
4375 			rw_exit(iss->iss_lockp);
4376 			stmf_free(task);
4377 			return (NULL);
4378 		}
4379 		mutex_enter(&ilu->ilu_task_lock);
4380 		if (ilu->ilu_flags & ILU_RESET_ACTIVE) {
4381 			mutex_exit(&ilu->ilu_task_lock);
4382 			rw_exit(iss->iss_lockp);
4383 			stmf_free(task);
4384 			return (NULL);
4385 		}
4386 		itask->itask_lu_next = ilu->ilu_tasks;
4387 		if (ilu->ilu_tasks)
4388 			ilu->ilu_tasks->itask_lu_prev = itask;
4389 		ilu->ilu_tasks = itask;
4390 		/* kmem_zalloc automatically makes itask->itask_lu_prev NULL */
4391 		ilu->ilu_ntasks++;
4392 		mutex_exit(&ilu->ilu_task_lock);
4393 	}
4394 
4395 	itask->itask_ilu_task_cntr = ilu->ilu_cur_task_cntr;
4396 	atomic_add_32(itask->itask_ilu_task_cntr, 1);
4397 	itask->itask_start_time = ddi_get_lbolt();
4398 
4399 	if ((lun_map_ent != NULL) && ((itask->itask_itl_datap =
4400 	    lun_map_ent->ent_itl_datap) != NULL)) {
4401 		atomic_add_32(&itask->itask_itl_datap->itl_counter, 1);
4402 		task->task_lu_itl_handle = itask->itask_itl_datap->itl_handle;
4403 	} else {
4404 		itask->itask_itl_datap = NULL;
4405 		task->task_lu_itl_handle = NULL;
4406 	}
4407 
4408 	rw_exit(iss->iss_lockp);
4409 	return (task);
4410 }
4411 
4412 static void
4413 stmf_task_lu_free(scsi_task_t *task, stmf_i_scsi_session_t *iss)
4414 {
4415 	stmf_i_scsi_task_t *itask =
4416 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
4417 	stmf_i_lu_t *ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
4418 
4419 	ASSERT(rw_lock_held(iss->iss_lockp));
4420 	itask->itask_flags = ITASK_IN_FREE_LIST;
4421 	itask->itask_proxy_msg_id = 0;
4422 	mutex_enter(&ilu->ilu_task_lock);
4423 	itask->itask_lu_free_next = ilu->ilu_free_tasks;
4424 	ilu->ilu_free_tasks = itask;
4425 	ilu->ilu_ntasks_free++;
4426 	mutex_exit(&ilu->ilu_task_lock);
4427 	atomic_add_32(itask->itask_ilu_task_cntr, -1);
4428 }
4429 
4430 void
4431 stmf_task_lu_check_freelist(stmf_i_lu_t *ilu)
4432 {
4433 	uint32_t	num_to_release, ndx;
4434 	stmf_i_scsi_task_t *itask;
4435 	stmf_lu_t	*lu = ilu->ilu_lu;
4436 
4437 	ASSERT(ilu->ilu_ntasks_min_free <= ilu->ilu_ntasks_free);
4438 
4439 	/* free half of the minimal free of the free tasks */
4440 	num_to_release = (ilu->ilu_ntasks_min_free + 1) / 2;
4441 	if (!num_to_release) {
4442 		return;
4443 	}
4444 	for (ndx = 0; ndx < num_to_release; ndx++) {
4445 		mutex_enter(&ilu->ilu_task_lock);
4446 		itask = ilu->ilu_free_tasks;
4447 		if (itask == NULL) {
4448 			mutex_exit(&ilu->ilu_task_lock);
4449 			break;
4450 		}
4451 		ilu->ilu_free_tasks = itask->itask_lu_free_next;
4452 		ilu->ilu_ntasks_free--;
4453 		mutex_exit(&ilu->ilu_task_lock);
4454 
4455 		lu->lu_task_free(itask->itask_task);
4456 		mutex_enter(&ilu->ilu_task_lock);
4457 		if (itask->itask_lu_next)
4458 			itask->itask_lu_next->itask_lu_prev =
4459 			    itask->itask_lu_prev;
4460 		if (itask->itask_lu_prev)
4461 			itask->itask_lu_prev->itask_lu_next =
4462 			    itask->itask_lu_next;
4463 		else
4464 			ilu->ilu_tasks = itask->itask_lu_next;
4465 
4466 		ilu->ilu_ntasks--;
4467 		mutex_exit(&ilu->ilu_task_lock);
4468 		stmf_free(itask->itask_task);
4469 	}
4470 }
4471 
4472 /*
4473  * Called with stmf_lock held
4474  */
4475 void
4476 stmf_check_freetask()
4477 {
4478 	stmf_i_lu_t *ilu;
4479 	clock_t	endtime = ddi_get_lbolt() + drv_usectohz(10000);
4480 
4481 	/* stmf_svc_ilu_draining may get changed after stmf_lock is released */
4482 	while ((ilu = stmf_state.stmf_svc_ilu_draining) != NULL) {
4483 		stmf_state.stmf_svc_ilu_draining = ilu->ilu_next;
4484 		if (!ilu->ilu_ntasks_min_free) {
4485 			ilu->ilu_ntasks_min_free = ilu->ilu_ntasks_free;
4486 			continue;
4487 		}
4488 		ilu->ilu_flags |= ILU_STALL_DEREGISTER;
4489 		mutex_exit(&stmf_state.stmf_lock);
4490 		stmf_task_lu_check_freelist(ilu);
4491 		/*
4492 		 * we do not care about the accuracy of
4493 		 * ilu_ntasks_min_free, so we don't lock here
4494 		 */
4495 		ilu->ilu_ntasks_min_free = ilu->ilu_ntasks_free;
4496 		mutex_enter(&stmf_state.stmf_lock);
4497 		ilu->ilu_flags &= ~ILU_STALL_DEREGISTER;
4498 		cv_broadcast(&stmf_state.stmf_cv);
4499 		if (ddi_get_lbolt() >= endtime)
4500 			break;
4501 	}
4502 }
4503 
4504 void
4505 stmf_do_ilu_timeouts(stmf_i_lu_t *ilu)
4506 {
4507 	clock_t l = ddi_get_lbolt();
4508 	clock_t ps = drv_usectohz(1000000);
4509 	stmf_i_scsi_task_t *itask;
4510 	scsi_task_t *task;
4511 	uint32_t to;
4512 
4513 	mutex_enter(&ilu->ilu_task_lock);
4514 	for (itask = ilu->ilu_tasks; itask != NULL;
4515 	    itask = itask->itask_lu_next) {
4516 		if (itask->itask_flags & (ITASK_IN_FREE_LIST |
4517 		    ITASK_BEING_ABORTED)) {
4518 			continue;
4519 		}
4520 		task = itask->itask_task;
4521 		if (task->task_timeout == 0)
4522 			to = stmf_default_task_timeout;
4523 		else
4524 			to = task->task_timeout;
4525 		if ((itask->itask_start_time + (to * ps)) > l)
4526 			continue;
4527 		stmf_abort(STMF_QUEUE_TASK_ABORT, task,
4528 		    STMF_TIMEOUT, NULL);
4529 	}
4530 	mutex_exit(&ilu->ilu_task_lock);
4531 }
4532 
4533 /*
4534  * Called with stmf_lock held
4535  */
4536 void
4537 stmf_check_ilu_timing()
4538 {
4539 	stmf_i_lu_t *ilu;
4540 	clock_t	endtime = ddi_get_lbolt() + drv_usectohz(10000);
4541 
4542 	/* stmf_svc_ilu_timing may get changed after stmf_lock is released */
4543 	while ((ilu = stmf_state.stmf_svc_ilu_timing) != NULL) {
4544 		stmf_state.stmf_svc_ilu_timing = ilu->ilu_next;
4545 		if (ilu->ilu_cur_task_cntr == (&ilu->ilu_task_cntr1)) {
4546 			if (ilu->ilu_task_cntr2 == 0) {
4547 				ilu->ilu_cur_task_cntr = &ilu->ilu_task_cntr2;
4548 				continue;
4549 			}
4550 		} else {
4551 			if (ilu->ilu_task_cntr1 == 0) {
4552 				ilu->ilu_cur_task_cntr = &ilu->ilu_task_cntr1;
4553 				continue;
4554 			}
4555 		}
4556 		/*
4557 		 * If we are here then it means that there is some slowdown
4558 		 * in tasks on this lu. We need to check.
4559 		 */
4560 		ilu->ilu_flags |= ILU_STALL_DEREGISTER;
4561 		mutex_exit(&stmf_state.stmf_lock);
4562 		stmf_do_ilu_timeouts(ilu);
4563 		mutex_enter(&stmf_state.stmf_lock);
4564 		ilu->ilu_flags &= ~ILU_STALL_DEREGISTER;
4565 		cv_broadcast(&stmf_state.stmf_cv);
4566 		if (ddi_get_lbolt() >= endtime)
4567 			break;
4568 	}
4569 }
4570 
4571 /*
4572  * Kills all tasks on a lu except tm_task
4573  */
4574 void
4575 stmf_task_lu_killall(stmf_lu_t *lu, scsi_task_t *tm_task, stmf_status_t s)
4576 {
4577 	stmf_i_lu_t *ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
4578 	stmf_i_scsi_task_t *itask;
4579 
4580 	mutex_enter(&ilu->ilu_task_lock);
4581 
4582 	for (itask = ilu->ilu_tasks; itask != NULL;
4583 	    itask = itask->itask_lu_next) {
4584 		if (itask->itask_flags & ITASK_IN_FREE_LIST)
4585 			continue;
4586 		if (itask->itask_task == tm_task)
4587 			continue;
4588 		stmf_abort(STMF_QUEUE_TASK_ABORT, itask->itask_task, s, NULL);
4589 	}
4590 	mutex_exit(&ilu->ilu_task_lock);
4591 }
4592 
4593 void
4594 stmf_free_task_bufs(stmf_i_scsi_task_t *itask, stmf_local_port_t *lport)
4595 {
4596 	int i;
4597 	uint8_t map;
4598 
4599 	if ((map = itask->itask_allocated_buf_map) != 0) {
4600 		for (i = 0; i < 4; i++) {
4601 			if (map & 1) {
4602 				stmf_data_buf_t *dbuf;
4603 
4604 				dbuf = itask->itask_dbufs[i];
4605 				if (dbuf->db_lu_private) {
4606 					dbuf->db_lu_private = NULL;
4607 				}
4608 				if (dbuf->db_xfer_start_timestamp != NULL) {
4609 					stmf_lport_xfer_done(itask, dbuf);
4610 				}
4611 				lport->lport_ds->ds_free_data_buf(
4612 				    lport->lport_ds, dbuf);
4613 			}
4614 			map >>= 1;
4615 		}
4616 		itask->itask_allocated_buf_map = 0;
4617 	}
4618 }
4619 
4620 void
4621 stmf_task_free(scsi_task_t *task)
4622 {
4623 	stmf_local_port_t *lport = task->task_lport;
4624 	stmf_i_scsi_task_t *itask = (stmf_i_scsi_task_t *)
4625 	    task->task_stmf_private;
4626 	stmf_i_scsi_session_t *iss = (stmf_i_scsi_session_t *)
4627 	    task->task_session->ss_stmf_private;
4628 
4629 	stmf_free_task_bufs(itask, lport);
4630 	stmf_itl_task_done(itask);
4631 	DTRACE_PROBE2(stmf__task__end, scsi_task_t *, task,
4632 	    hrtime_t,
4633 	    itask->itask_done_timestamp - itask->itask_start_timestamp);
4634 	if (itask->itask_itl_datap) {
4635 		if (atomic_add_32_nv(&itask->itask_itl_datap->itl_counter,
4636 		    -1) == 0) {
4637 			stmf_release_itl_handle(task->task_lu,
4638 			    itask->itask_itl_datap);
4639 		}
4640 	}
4641 
4642 	rw_enter(iss->iss_lockp, RW_READER);
4643 	lport->lport_task_free(task);
4644 	if (itask->itask_worker) {
4645 		atomic_add_32(&stmf_cur_ntasks, -1);
4646 		atomic_add_32(&itask->itask_worker->worker_ref_count, -1);
4647 	}
4648 	/*
4649 	 * After calling stmf_task_lu_free, the task pointer can no longer
4650 	 * be trusted.
4651 	 */
4652 	stmf_task_lu_free(task, iss);
4653 	rw_exit(iss->iss_lockp);
4654 }
4655 
4656 void
4657 stmf_post_task(scsi_task_t *task, stmf_data_buf_t *dbuf)
4658 {
4659 	stmf_i_scsi_task_t *itask = (stmf_i_scsi_task_t *)
4660 	    task->task_stmf_private;
4661 	stmf_i_lu_t *ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
4662 	int nv;
4663 	uint32_t old, new;
4664 	uint32_t ct;
4665 	stmf_worker_t *w, *w1;
4666 	uint8_t tm;
4667 
4668 	if (task->task_max_nbufs > 4)
4669 		task->task_max_nbufs = 4;
4670 	task->task_cur_nbufs = 0;
4671 	/* Latest value of currently running tasks */
4672 	ct = atomic_add_32_nv(&stmf_cur_ntasks, 1);
4673 
4674 	/* Select the next worker using round robin */
4675 	nv = (int)atomic_add_32_nv((uint32_t *)&stmf_worker_sel_counter, 1);
4676 	if (nv >= stmf_nworkers_accepting_cmds) {
4677 		int s = nv;
4678 		do {
4679 			nv -= stmf_nworkers_accepting_cmds;
4680 		} while (nv >= stmf_nworkers_accepting_cmds);
4681 		if (nv < 0)
4682 			nv = 0;
4683 		/* Its ok if this cas fails */
4684 		(void) atomic_cas_32((uint32_t *)&stmf_worker_sel_counter,
4685 		    s, nv);
4686 	}
4687 	w = &stmf_workers[nv];
4688 
4689 	/*
4690 	 * A worker can be pinned by interrupt. So select the next one
4691 	 * if it has lower load.
4692 	 */
4693 	if ((nv + 1) >= stmf_nworkers_accepting_cmds) {
4694 		w1 = stmf_workers;
4695 	} else {
4696 		w1 = &stmf_workers[nv + 1];
4697 	}
4698 	if (w1->worker_queue_depth < w->worker_queue_depth)
4699 		w = w1;
4700 
4701 	mutex_enter(&w->worker_lock);
4702 	if (((w->worker_flags & STMF_WORKER_STARTED) == 0) ||
4703 	    (w->worker_flags & STMF_WORKER_TERMINATE)) {
4704 		/*
4705 		 * Maybe we are in the middle of a change. Just go to
4706 		 * the 1st worker.
4707 		 */
4708 		mutex_exit(&w->worker_lock);
4709 		w = stmf_workers;
4710 		mutex_enter(&w->worker_lock);
4711 	}
4712 	itask->itask_worker = w;
4713 	/*
4714 	 * Track max system load inside the worker as we already have the
4715 	 * worker lock (no point implementing another lock). The service
4716 	 * thread will do the comparisons and figure out the max overall
4717 	 * system load.
4718 	 */
4719 	if (w->worker_max_sys_qdepth_pu < ct)
4720 		w->worker_max_sys_qdepth_pu = ct;
4721 
4722 	do {
4723 		old = new = itask->itask_flags;
4724 		new |= ITASK_KNOWN_TO_TGT_PORT | ITASK_IN_WORKER_QUEUE;
4725 		if (task->task_mgmt_function) {
4726 			tm = task->task_mgmt_function;
4727 			if ((tm == TM_TARGET_RESET) ||
4728 			    (tm == TM_TARGET_COLD_RESET) ||
4729 			    (tm == TM_TARGET_WARM_RESET)) {
4730 				new |= ITASK_DEFAULT_HANDLING;
4731 			}
4732 		} else if (task->task_cdb[0] == SCMD_REPORT_LUNS) {
4733 			new |= ITASK_DEFAULT_HANDLING;
4734 		}
4735 		new &= ~ITASK_IN_TRANSITION;
4736 	} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
4737 
4738 	stmf_itl_task_start(itask);
4739 
4740 	itask->itask_worker_next = NULL;
4741 	if (w->worker_task_tail) {
4742 		w->worker_task_tail->itask_worker_next = itask;
4743 	} else {
4744 		w->worker_task_head = itask;
4745 	}
4746 	w->worker_task_tail = itask;
4747 	if (++(w->worker_queue_depth) > w->worker_max_qdepth_pu) {
4748 		w->worker_max_qdepth_pu = w->worker_queue_depth;
4749 	}
4750 	/* Measure task waitq time */
4751 	itask->itask_waitq_enter_timestamp = gethrtime();
4752 	atomic_add_32(&w->worker_ref_count, 1);
4753 	itask->itask_cmd_stack[0] = ITASK_CMD_NEW_TASK;
4754 	itask->itask_ncmds = 1;
4755 	if (dbuf) {
4756 		itask->itask_allocated_buf_map = 1;
4757 		itask->itask_dbufs[0] = dbuf;
4758 		dbuf->db_handle = 0;
4759 	} else {
4760 		itask->itask_allocated_buf_map = 0;
4761 		itask->itask_dbufs[0] = NULL;
4762 	}
4763 
4764 	if ((w->worker_flags & STMF_WORKER_ACTIVE) == 0) {
4765 		w->worker_signal_timestamp = gethrtime();
4766 		DTRACE_PROBE2(worker__signal, stmf_worker_t *, w,
4767 		    scsi_task_t *, task);
4768 		cv_signal(&w->worker_cv);
4769 	}
4770 	mutex_exit(&w->worker_lock);
4771 
4772 	/*
4773 	 * This can only happen if during stmf_task_alloc(), ILU_RESET_ACTIVE
4774 	 * was set between checking of ILU_RESET_ACTIVE and clearing of the
4775 	 * ITASK_IN_FREE_LIST flag. Take care of these "sneaked-in" tasks here.
4776 	 */
4777 	if (ilu->ilu_flags & ILU_RESET_ACTIVE) {
4778 		stmf_abort(STMF_QUEUE_TASK_ABORT, task, STMF_ABORTED, NULL);
4779 	}
4780 }
4781 
4782 /*
4783  * ++++++++++++++ ABORT LOGIC ++++++++++++++++++++
4784  * Once ITASK_BEING_ABORTED is set, ITASK_KNOWN_TO_LU can be reset already
4785  * i.e. before ITASK_BEING_ABORTED being set. But if it was not, it cannot
4786  * be reset until the LU explicitly calls stmf_task_lu_aborted(). Of course
4787  * the LU will make this call only if we call the LU's abort entry point.
4788  * we will only call that entry point if ITASK_KNOWN_TO_LU was set.
4789  *
4790  * Same logic applies for the port.
4791  *
4792  * Also ITASK_BEING_ABORTED will not be allowed to set if both KNOWN_TO_LU
4793  * and KNOWN_TO_TGT_PORT are reset.
4794  *
4795  * +++++++++++++++++++++++++++++++++++++++++++++++
4796  */
4797 
4798 stmf_status_t
4799 stmf_xfer_data(scsi_task_t *task, stmf_data_buf_t *dbuf, uint32_t ioflags)
4800 {
4801 	stmf_status_t ret;
4802 
4803 	stmf_i_scsi_task_t *itask =
4804 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
4805 
4806 	if (ioflags & STMF_IOF_LU_DONE) {
4807 		uint32_t new, old;
4808 		do {
4809 			new = old = itask->itask_flags;
4810 			if (new & ITASK_BEING_ABORTED)
4811 				return (STMF_ABORTED);
4812 			new &= ~ITASK_KNOWN_TO_LU;
4813 		} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
4814 	}
4815 	if (itask->itask_flags & ITASK_BEING_ABORTED)
4816 		return (STMF_ABORTED);
4817 #ifdef	DEBUG
4818 	if (!(ioflags & STMF_IOF_STATS_ONLY) && stmf_drop_buf_counter > 0) {
4819 		if (atomic_add_32_nv((uint32_t *)&stmf_drop_buf_counter, -1) ==
4820 		    1)
4821 			return (STMF_SUCCESS);
4822 	}
4823 #endif
4824 
4825 	stmf_update_kstat_lu_io(task, dbuf);
4826 	stmf_update_kstat_lport_io(task, dbuf);
4827 	stmf_lport_xfer_start(itask, dbuf);
4828 	if (ioflags & STMF_IOF_STATS_ONLY) {
4829 		stmf_lport_xfer_done(itask, dbuf);
4830 		return (STMF_SUCCESS);
4831 	}
4832 
4833 	ret = task->task_lport->lport_xfer_data(task, dbuf, ioflags);
4834 
4835 	/*
4836 	 * Port provider may have already called the buffer callback in
4837 	 * which case dbuf->db_xfer_start_timestamp will be 0.
4838 	 */
4839 	if ((ret != STMF_SUCCESS) && (dbuf->db_xfer_start_timestamp != 0)) {
4840 		stmf_lport_xfer_done(itask, dbuf);
4841 	}
4842 
4843 	return (ret);
4844 }
4845 
4846 void
4847 stmf_data_xfer_done(scsi_task_t *task, stmf_data_buf_t *dbuf, uint32_t iof)
4848 {
4849 	stmf_i_scsi_task_t *itask =
4850 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
4851 	stmf_worker_t *w = itask->itask_worker;
4852 	uint32_t new, old;
4853 	uint8_t update_queue_flags, free_it, queue_it;
4854 
4855 	stmf_lport_xfer_done(itask, dbuf);
4856 
4857 	mutex_enter(&w->worker_lock);
4858 	do {
4859 		new = old = itask->itask_flags;
4860 		if (old & ITASK_BEING_ABORTED) {
4861 			mutex_exit(&w->worker_lock);
4862 			return;
4863 		}
4864 		free_it = 0;
4865 		if (iof & STMF_IOF_LPORT_DONE) {
4866 			new &= ~ITASK_KNOWN_TO_TGT_PORT;
4867 			task->task_completion_status = dbuf->db_xfer_status;
4868 			free_it = 1;
4869 		}
4870 		/*
4871 		 * If the task is known to LU then queue it. But if
4872 		 * it is already queued (multiple completions) then
4873 		 * just update the buffer information by grabbing the
4874 		 * worker lock. If the task is not known to LU,
4875 		 * completed/aborted, then see if we need to
4876 		 * free this task.
4877 		 */
4878 		if (old & ITASK_KNOWN_TO_LU) {
4879 			free_it = 0;
4880 			update_queue_flags = 1;
4881 			if (old & ITASK_IN_WORKER_QUEUE) {
4882 				queue_it = 0;
4883 			} else {
4884 				queue_it = 1;
4885 				new |= ITASK_IN_WORKER_QUEUE;
4886 			}
4887 		} else {
4888 			update_queue_flags = 0;
4889 			queue_it = 0;
4890 		}
4891 	} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
4892 
4893 	if (update_queue_flags) {
4894 		uint8_t cmd = (dbuf->db_handle << 5) | ITASK_CMD_DATA_XFER_DONE;
4895 
4896 		ASSERT(itask->itask_ncmds < ITASK_MAX_NCMDS);
4897 		itask->itask_cmd_stack[itask->itask_ncmds++] = cmd;
4898 		if (queue_it) {
4899 			itask->itask_worker_next = NULL;
4900 			if (w->worker_task_tail) {
4901 				w->worker_task_tail->itask_worker_next = itask;
4902 			} else {
4903 				w->worker_task_head = itask;
4904 			}
4905 			w->worker_task_tail = itask;
4906 			/* Measure task waitq time */
4907 			itask->itask_waitq_enter_timestamp = gethrtime();
4908 			if (++(w->worker_queue_depth) >
4909 			    w->worker_max_qdepth_pu) {
4910 				w->worker_max_qdepth_pu = w->worker_queue_depth;
4911 			}
4912 			if ((w->worker_flags & STMF_WORKER_ACTIVE) == 0)
4913 				cv_signal(&w->worker_cv);
4914 		}
4915 	}
4916 	mutex_exit(&w->worker_lock);
4917 
4918 	if (free_it) {
4919 		if ((itask->itask_flags & (ITASK_KNOWN_TO_LU |
4920 		    ITASK_KNOWN_TO_TGT_PORT | ITASK_IN_WORKER_QUEUE |
4921 		    ITASK_BEING_ABORTED)) == 0) {
4922 			stmf_task_free(task);
4923 		}
4924 	}
4925 }
4926 
4927 stmf_status_t
4928 stmf_send_scsi_status(scsi_task_t *task, uint32_t ioflags)
4929 {
4930 	DTRACE_PROBE1(scsi__send__status, scsi_task_t *, task);
4931 
4932 	stmf_i_scsi_task_t *itask =
4933 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
4934 	if (ioflags & STMF_IOF_LU_DONE) {
4935 		uint32_t new, old;
4936 		do {
4937 			new = old = itask->itask_flags;
4938 			if (new & ITASK_BEING_ABORTED)
4939 				return (STMF_ABORTED);
4940 			new &= ~ITASK_KNOWN_TO_LU;
4941 		} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
4942 	}
4943 
4944 	if (!(itask->itask_flags & ITASK_KNOWN_TO_TGT_PORT)) {
4945 		return (STMF_SUCCESS);
4946 	}
4947 
4948 	if (itask->itask_flags & ITASK_BEING_ABORTED)
4949 		return (STMF_ABORTED);
4950 
4951 	if (task->task_additional_flags & TASK_AF_NO_EXPECTED_XFER_LENGTH) {
4952 		task->task_status_ctrl = 0;
4953 		task->task_resid = 0;
4954 	} else if (task->task_cmd_xfer_length >
4955 	    task->task_expected_xfer_length) {
4956 		task->task_status_ctrl = TASK_SCTRL_OVER;
4957 		task->task_resid = task->task_cmd_xfer_length -
4958 		    task->task_expected_xfer_length;
4959 	} else if (task->task_nbytes_transferred <
4960 	    task->task_expected_xfer_length) {
4961 		task->task_status_ctrl = TASK_SCTRL_UNDER;
4962 		task->task_resid = task->task_expected_xfer_length -
4963 		    task->task_nbytes_transferred;
4964 	} else {
4965 		task->task_status_ctrl = 0;
4966 		task->task_resid = 0;
4967 	}
4968 	return (task->task_lport->lport_send_status(task, ioflags));
4969 }
4970 
4971 void
4972 stmf_send_status_done(scsi_task_t *task, stmf_status_t s, uint32_t iof)
4973 {
4974 	stmf_i_scsi_task_t *itask =
4975 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
4976 	stmf_worker_t *w = itask->itask_worker;
4977 	uint32_t new, old;
4978 	uint8_t free_it, queue_it;
4979 
4980 	mutex_enter(&w->worker_lock);
4981 	do {
4982 		new = old = itask->itask_flags;
4983 		if (old & ITASK_BEING_ABORTED) {
4984 			mutex_exit(&w->worker_lock);
4985 			return;
4986 		}
4987 		free_it = 0;
4988 		if (iof & STMF_IOF_LPORT_DONE) {
4989 			new &= ~ITASK_KNOWN_TO_TGT_PORT;
4990 			free_it = 1;
4991 		}
4992 		/*
4993 		 * If the task is known to LU then queue it. But if
4994 		 * it is already queued (multiple completions) then
4995 		 * just update the buffer information by grabbing the
4996 		 * worker lock. If the task is not known to LU,
4997 		 * completed/aborted, then see if we need to
4998 		 * free this task.
4999 		 */
5000 		if (old & ITASK_KNOWN_TO_LU) {
5001 			free_it = 0;
5002 			queue_it = 1;
5003 			if (old & ITASK_IN_WORKER_QUEUE) {
5004 				cmn_err(CE_PANIC, "status completion received"
5005 				    " when task is already in worker queue "
5006 				    " task = %p", (void *)task);
5007 			}
5008 			new |= ITASK_IN_WORKER_QUEUE;
5009 		} else {
5010 			queue_it = 0;
5011 		}
5012 	} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
5013 	task->task_completion_status = s;
5014 
5015 
5016 	if (queue_it) {
5017 		ASSERT(itask->itask_ncmds < ITASK_MAX_NCMDS);
5018 		itask->itask_cmd_stack[itask->itask_ncmds++] =
5019 		    ITASK_CMD_STATUS_DONE;
5020 		itask->itask_worker_next = NULL;
5021 		if (w->worker_task_tail) {
5022 			w->worker_task_tail->itask_worker_next = itask;
5023 		} else {
5024 			w->worker_task_head = itask;
5025 		}
5026 		w->worker_task_tail = itask;
5027 		/* Measure task waitq time */
5028 		itask->itask_waitq_enter_timestamp = gethrtime();
5029 		if (++(w->worker_queue_depth) > w->worker_max_qdepth_pu) {
5030 			w->worker_max_qdepth_pu = w->worker_queue_depth;
5031 		}
5032 		if ((w->worker_flags & STMF_WORKER_ACTIVE) == 0)
5033 			cv_signal(&w->worker_cv);
5034 	}
5035 	mutex_exit(&w->worker_lock);
5036 
5037 	if (free_it) {
5038 		if ((itask->itask_flags & (ITASK_KNOWN_TO_LU |
5039 		    ITASK_KNOWN_TO_TGT_PORT | ITASK_IN_WORKER_QUEUE |
5040 		    ITASK_BEING_ABORTED)) == 0) {
5041 			stmf_task_free(task);
5042 		} else {
5043 			cmn_err(CE_PANIC, "LU is done with the task but LPORT "
5044 			    " is not done, itask %p itask_flags %x",
5045 			    (void *)itask, itask->itask_flags);
5046 		}
5047 	}
5048 }
5049 
5050 void
5051 stmf_task_lu_done(scsi_task_t *task)
5052 {
5053 	stmf_i_scsi_task_t *itask =
5054 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
5055 	stmf_worker_t *w = itask->itask_worker;
5056 	uint32_t new, old;
5057 
5058 	mutex_enter(&w->worker_lock);
5059 	do {
5060 		new = old = itask->itask_flags;
5061 		if (old & ITASK_BEING_ABORTED) {
5062 			mutex_exit(&w->worker_lock);
5063 			return;
5064 		}
5065 		if (old & ITASK_IN_WORKER_QUEUE) {
5066 			cmn_err(CE_PANIC, "task_lu_done received"
5067 			    " when task is in worker queue "
5068 			    " task = %p", (void *)task);
5069 		}
5070 		new &= ~ITASK_KNOWN_TO_LU;
5071 	} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
5072 
5073 	mutex_exit(&w->worker_lock);
5074 
5075 	if ((itask->itask_flags & (ITASK_KNOWN_TO_LU |
5076 	    ITASK_KNOWN_TO_TGT_PORT | ITASK_IN_WORKER_QUEUE |
5077 	    ITASK_BEING_ABORTED)) == 0) {
5078 		stmf_task_free(task);
5079 	} else {
5080 		cmn_err(CE_PANIC, "stmf_lu_done should be the last stage but "
5081 		    " the task is still not done, task = %p", (void *)task);
5082 	}
5083 }
5084 
5085 void
5086 stmf_queue_task_for_abort(scsi_task_t *task, stmf_status_t s)
5087 {
5088 	stmf_i_scsi_task_t *itask =
5089 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
5090 	stmf_worker_t *w;
5091 	uint32_t old, new;
5092 
5093 	do {
5094 		old = new = itask->itask_flags;
5095 		if ((old & ITASK_BEING_ABORTED) ||
5096 		    ((old & (ITASK_KNOWN_TO_TGT_PORT |
5097 		    ITASK_KNOWN_TO_LU)) == 0)) {
5098 			return;
5099 		}
5100 		new |= ITASK_BEING_ABORTED;
5101 	} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
5102 	task->task_completion_status = s;
5103 	itask->itask_start_time = ddi_get_lbolt();
5104 
5105 	if (((w = itask->itask_worker) == NULL) ||
5106 	    (itask->itask_flags & ITASK_IN_TRANSITION)) {
5107 		return;
5108 	}
5109 
5110 	/* Queue it and get out */
5111 	mutex_enter(&w->worker_lock);
5112 	if (itask->itask_flags & ITASK_IN_WORKER_QUEUE) {
5113 		mutex_exit(&w->worker_lock);
5114 		return;
5115 	}
5116 	atomic_or_32(&itask->itask_flags, ITASK_IN_WORKER_QUEUE);
5117 	itask->itask_worker_next = NULL;
5118 	if (w->worker_task_tail) {
5119 		w->worker_task_tail->itask_worker_next = itask;
5120 	} else {
5121 		w->worker_task_head = itask;
5122 	}
5123 	w->worker_task_tail = itask;
5124 	if (++(w->worker_queue_depth) > w->worker_max_qdepth_pu) {
5125 		w->worker_max_qdepth_pu = w->worker_queue_depth;
5126 	}
5127 	if ((w->worker_flags & STMF_WORKER_ACTIVE) == 0)
5128 		cv_signal(&w->worker_cv);
5129 	mutex_exit(&w->worker_lock);
5130 }
5131 
5132 void
5133 stmf_abort(int abort_cmd, scsi_task_t *task, stmf_status_t s, void *arg)
5134 {
5135 	stmf_i_scsi_task_t *itask = NULL;
5136 	uint32_t old, new, f, rf;
5137 
5138 	DTRACE_PROBE2(scsi__task__abort, scsi_task_t *, task,
5139 	    stmf_status_t, s);
5140 
5141 	switch (abort_cmd) {
5142 	case STMF_QUEUE_ABORT_LU:
5143 		stmf_task_lu_killall((stmf_lu_t *)arg, task, s);
5144 		return;
5145 	case STMF_QUEUE_TASK_ABORT:
5146 		stmf_queue_task_for_abort(task, s);
5147 		return;
5148 	case STMF_REQUEUE_TASK_ABORT_LPORT:
5149 		rf = ITASK_TGT_PORT_ABORT_CALLED;
5150 		f = ITASK_KNOWN_TO_TGT_PORT;
5151 		break;
5152 	case STMF_REQUEUE_TASK_ABORT_LU:
5153 		rf = ITASK_LU_ABORT_CALLED;
5154 		f = ITASK_KNOWN_TO_LU;
5155 		break;
5156 	default:
5157 		return;
5158 	}
5159 	itask = (stmf_i_scsi_task_t *)task->task_stmf_private;
5160 	f |= ITASK_BEING_ABORTED | rf;
5161 	do {
5162 		old = new = itask->itask_flags;
5163 		if ((old & f) != f) {
5164 			return;
5165 		}
5166 		new &= ~rf;
5167 	} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
5168 }
5169 
5170 void
5171 stmf_task_lu_aborted(scsi_task_t *task, stmf_status_t s, uint32_t iof)
5172 {
5173 	char			 info[STMF_CHANGE_INFO_LEN];
5174 	stmf_i_scsi_task_t	*itask = TASK_TO_ITASK(task);
5175 	unsigned long long	st;
5176 
5177 	st = s;	/* gcc fix */
5178 	if ((s != STMF_ABORT_SUCCESS) && (s != STMF_NOT_FOUND)) {
5179 		(void) snprintf(info, STMF_CHANGE_INFO_LEN,
5180 		    "task %p, lu failed to abort ret=%llx", (void *)task, st);
5181 	} else if ((iof & STMF_IOF_LU_DONE) == 0) {
5182 		(void) snprintf(info, STMF_CHANGE_INFO_LEN,
5183 		    "Task aborted but LU is not finished, task ="
5184 		    "%p, s=%llx, iof=%x", (void *)task, st, iof);
5185 	} else {
5186 		/*
5187 		 * LU abort successfully
5188 		 */
5189 		atomic_and_32(&itask->itask_flags, ~ITASK_KNOWN_TO_LU);
5190 		return;
5191 	}
5192 
5193 	info[STMF_CHANGE_INFO_LEN - 1] = 0;
5194 	stmf_abort_task_offline(task, 1, info);
5195 }
5196 
5197 void
5198 stmf_task_lport_aborted(scsi_task_t *task, stmf_status_t s, uint32_t iof)
5199 {
5200 	char			info[STMF_CHANGE_INFO_LEN];
5201 	stmf_i_scsi_task_t	*itask = TASK_TO_ITASK(task);
5202 	unsigned long long	st;
5203 	uint32_t		old, new;
5204 
5205 	st = s;
5206 	if ((s != STMF_ABORT_SUCCESS) && (s != STMF_NOT_FOUND)) {
5207 		(void) snprintf(info, STMF_CHANGE_INFO_LEN,
5208 		    "task %p, tgt port failed to abort ret=%llx", (void *)task,
5209 		    st);
5210 	} else if ((iof & STMF_IOF_LPORT_DONE) == 0) {
5211 		(void) snprintf(info, STMF_CHANGE_INFO_LEN,
5212 		    "Task aborted but tgt port is not finished, "
5213 		    "task=%p, s=%llx, iof=%x", (void *)task, st, iof);
5214 	} else {
5215 		/*
5216 		 * LPORT abort successfully
5217 		 */
5218 		do {
5219 			old = new = itask->itask_flags;
5220 			if (!(old & ITASK_KNOWN_TO_TGT_PORT))
5221 				return;
5222 			new &= ~ITASK_KNOWN_TO_TGT_PORT;
5223 		} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
5224 		return;
5225 	}
5226 
5227 	info[STMF_CHANGE_INFO_LEN - 1] = 0;
5228 	stmf_abort_task_offline(task, 0, info);
5229 }
5230 
5231 stmf_status_t
5232 stmf_task_poll_lu(scsi_task_t *task, uint32_t timeout)
5233 {
5234 	stmf_i_scsi_task_t *itask = (stmf_i_scsi_task_t *)
5235 	    task->task_stmf_private;
5236 	stmf_worker_t *w = itask->itask_worker;
5237 	int i;
5238 
5239 	ASSERT(itask->itask_flags & ITASK_KNOWN_TO_LU);
5240 	mutex_enter(&w->worker_lock);
5241 	if (itask->itask_ncmds >= ITASK_MAX_NCMDS) {
5242 		mutex_exit(&w->worker_lock);
5243 		return (STMF_BUSY);
5244 	}
5245 	for (i = 0; i < itask->itask_ncmds; i++) {
5246 		if (itask->itask_cmd_stack[i] == ITASK_CMD_POLL_LU) {
5247 			mutex_exit(&w->worker_lock);
5248 			return (STMF_SUCCESS);
5249 		}
5250 	}
5251 	itask->itask_cmd_stack[itask->itask_ncmds++] = ITASK_CMD_POLL_LU;
5252 	if (timeout == ITASK_DEFAULT_POLL_TIMEOUT) {
5253 		itask->itask_poll_timeout = ddi_get_lbolt() + 1;
5254 	} else {
5255 		clock_t t = drv_usectohz(timeout * 1000);
5256 		if (t == 0)
5257 			t = 1;
5258 		itask->itask_poll_timeout = ddi_get_lbolt() + t;
5259 	}
5260 	if ((itask->itask_flags & ITASK_IN_WORKER_QUEUE) == 0) {
5261 		itask->itask_worker_next = NULL;
5262 		if (w->worker_task_tail) {
5263 			w->worker_task_tail->itask_worker_next = itask;
5264 		} else {
5265 			w->worker_task_head = itask;
5266 		}
5267 		w->worker_task_tail = itask;
5268 		if (++(w->worker_queue_depth) > w->worker_max_qdepth_pu) {
5269 			w->worker_max_qdepth_pu = w->worker_queue_depth;
5270 		}
5271 		atomic_or_32(&itask->itask_flags, ITASK_IN_WORKER_QUEUE);
5272 		if ((w->worker_flags & STMF_WORKER_ACTIVE) == 0)
5273 			cv_signal(&w->worker_cv);
5274 	}
5275 	mutex_exit(&w->worker_lock);
5276 	return (STMF_SUCCESS);
5277 }
5278 
5279 stmf_status_t
5280 stmf_task_poll_lport(scsi_task_t *task, uint32_t timeout)
5281 {
5282 	stmf_i_scsi_task_t *itask = (stmf_i_scsi_task_t *)
5283 	    task->task_stmf_private;
5284 	stmf_worker_t *w = itask->itask_worker;
5285 	int i;
5286 
5287 	ASSERT(itask->itask_flags & ITASK_KNOWN_TO_TGT_PORT);
5288 	mutex_enter(&w->worker_lock);
5289 	if (itask->itask_ncmds >= ITASK_MAX_NCMDS) {
5290 		mutex_exit(&w->worker_lock);
5291 		return (STMF_BUSY);
5292 	}
5293 	for (i = 0; i < itask->itask_ncmds; i++) {
5294 		if (itask->itask_cmd_stack[i] == ITASK_CMD_POLL_LPORT) {
5295 			mutex_exit(&w->worker_lock);
5296 			return (STMF_SUCCESS);
5297 		}
5298 	}
5299 	itask->itask_cmd_stack[itask->itask_ncmds++] = ITASK_CMD_POLL_LPORT;
5300 	if (timeout == ITASK_DEFAULT_POLL_TIMEOUT) {
5301 		itask->itask_poll_timeout = ddi_get_lbolt() + 1;
5302 	} else {
5303 		clock_t t = drv_usectohz(timeout * 1000);
5304 		if (t == 0)
5305 			t = 1;
5306 		itask->itask_poll_timeout = ddi_get_lbolt() + t;
5307 	}
5308 	if ((itask->itask_flags & ITASK_IN_WORKER_QUEUE) == 0) {
5309 		itask->itask_worker_next = NULL;
5310 		if (w->worker_task_tail) {
5311 			w->worker_task_tail->itask_worker_next = itask;
5312 		} else {
5313 			w->worker_task_head = itask;
5314 		}
5315 		w->worker_task_tail = itask;
5316 		if (++(w->worker_queue_depth) > w->worker_max_qdepth_pu) {
5317 			w->worker_max_qdepth_pu = w->worker_queue_depth;
5318 		}
5319 		if ((w->worker_flags & STMF_WORKER_ACTIVE) == 0)
5320 			cv_signal(&w->worker_cv);
5321 	}
5322 	mutex_exit(&w->worker_lock);
5323 	return (STMF_SUCCESS);
5324 }
5325 
5326 void
5327 stmf_do_task_abort(scsi_task_t *task)
5328 {
5329 	stmf_i_scsi_task_t	*itask = TASK_TO_ITASK(task);
5330 	stmf_lu_t		*lu;
5331 	stmf_local_port_t	*lport;
5332 	unsigned long long	 ret;
5333 	uint32_t		 old, new;
5334 	uint8_t			 call_lu_abort, call_port_abort;
5335 	char			 info[STMF_CHANGE_INFO_LEN];
5336 
5337 	lu = task->task_lu;
5338 	lport = task->task_lport;
5339 	do {
5340 		old = new = itask->itask_flags;
5341 		if ((old & (ITASK_KNOWN_TO_LU | ITASK_LU_ABORT_CALLED)) ==
5342 		    ITASK_KNOWN_TO_LU) {
5343 			new |= ITASK_LU_ABORT_CALLED;
5344 			call_lu_abort = 1;
5345 		} else {
5346 			call_lu_abort = 0;
5347 		}
5348 	} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
5349 
5350 	if (call_lu_abort) {
5351 		if ((itask->itask_flags & ITASK_DEFAULT_HANDLING) == 0) {
5352 			ret = lu->lu_abort(lu, STMF_LU_ABORT_TASK, task, 0);
5353 		} else {
5354 			ret = dlun0->lu_abort(lu, STMF_LU_ABORT_TASK, task, 0);
5355 		}
5356 		if ((ret == STMF_ABORT_SUCCESS) || (ret == STMF_NOT_FOUND)) {
5357 			stmf_task_lu_aborted(task, ret, STMF_IOF_LU_DONE);
5358 		} else if (ret == STMF_BUSY) {
5359 			atomic_and_32(&itask->itask_flags,
5360 			    ~ITASK_LU_ABORT_CALLED);
5361 		} else if (ret != STMF_SUCCESS) {
5362 			(void) snprintf(info, STMF_CHANGE_INFO_LEN,
5363 			    "Abort failed by LU %p, ret %llx", (void *)lu, ret);
5364 			info[STMF_CHANGE_INFO_LEN - 1] = 0;
5365 			stmf_abort_task_offline(task, 1, info);
5366 		}
5367 	} else if (itask->itask_flags & ITASK_KNOWN_TO_LU) {
5368 		if (ddi_get_lbolt() > (itask->itask_start_time +
5369 		    STMF_SEC2TICK(lu->lu_abort_timeout?
5370 		    lu->lu_abort_timeout : ITASK_DEFAULT_ABORT_TIMEOUT))) {
5371 			(void) snprintf(info, STMF_CHANGE_INFO_LEN,
5372 			    "lu abort timed out");
5373 			info[STMF_CHANGE_INFO_LEN - 1] = 0;
5374 			stmf_abort_task_offline(itask->itask_task, 1, info);
5375 		}
5376 	}
5377 
5378 	do {
5379 		old = new = itask->itask_flags;
5380 		if ((old & (ITASK_KNOWN_TO_TGT_PORT |
5381 		    ITASK_TGT_PORT_ABORT_CALLED)) == ITASK_KNOWN_TO_TGT_PORT) {
5382 			new |= ITASK_TGT_PORT_ABORT_CALLED;
5383 			call_port_abort = 1;
5384 		} else {
5385 			call_port_abort = 0;
5386 		}
5387 	} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
5388 	if (call_port_abort) {
5389 		ret = lport->lport_abort(lport, STMF_LPORT_ABORT_TASK, task, 0);
5390 		if ((ret == STMF_ABORT_SUCCESS) || (ret == STMF_NOT_FOUND)) {
5391 			stmf_task_lport_aborted(task, ret, STMF_IOF_LPORT_DONE);
5392 		} else if (ret == STMF_BUSY) {
5393 			atomic_and_32(&itask->itask_flags,
5394 			    ~ITASK_TGT_PORT_ABORT_CALLED);
5395 		} else if (ret != STMF_SUCCESS) {
5396 			(void) snprintf(info, STMF_CHANGE_INFO_LEN,
5397 			    "Abort failed by tgt port %p ret %llx",
5398 			    (void *)lport, ret);
5399 			info[STMF_CHANGE_INFO_LEN - 1] = 0;
5400 			stmf_abort_task_offline(task, 0, info);
5401 		}
5402 	} else if (itask->itask_flags & ITASK_KNOWN_TO_TGT_PORT) {
5403 		if (ddi_get_lbolt() > (itask->itask_start_time +
5404 		    STMF_SEC2TICK(lport->lport_abort_timeout?
5405 		    lport->lport_abort_timeout :
5406 		    ITASK_DEFAULT_ABORT_TIMEOUT))) {
5407 			(void) snprintf(info, STMF_CHANGE_INFO_LEN,
5408 			    "lport abort timed out");
5409 			info[STMF_CHANGE_INFO_LEN - 1] = 0;
5410 			stmf_abort_task_offline(itask->itask_task, 0, info);
5411 		}
5412 	}
5413 }
5414 
5415 stmf_status_t
5416 stmf_ctl(int cmd, void *obj, void *arg)
5417 {
5418 	stmf_status_t			ret;
5419 	stmf_i_lu_t			*ilu;
5420 	stmf_i_local_port_t		*ilport;
5421 	stmf_state_change_info_t	*ssci = (stmf_state_change_info_t *)arg;
5422 
5423 	mutex_enter(&stmf_state.stmf_lock);
5424 	ret = STMF_INVALID_ARG;
5425 	if (cmd & STMF_CMD_LU_OP) {
5426 		ilu = stmf_lookup_lu((stmf_lu_t *)obj);
5427 		if (ilu == NULL) {
5428 			goto stmf_ctl_lock_exit;
5429 		}
5430 		DTRACE_PROBE3(lu__state__change,
5431 		    stmf_lu_t *, ilu->ilu_lu,
5432 		    int, cmd, stmf_state_change_info_t *, ssci);
5433 	} else if (cmd & STMF_CMD_LPORT_OP) {
5434 		ilport = stmf_lookup_lport((stmf_local_port_t *)obj);
5435 		if (ilport == NULL) {
5436 			goto stmf_ctl_lock_exit;
5437 		}
5438 		DTRACE_PROBE3(lport__state__change,
5439 		    stmf_local_port_t *, ilport->ilport_lport,
5440 		    int, cmd, stmf_state_change_info_t *, ssci);
5441 	} else {
5442 		goto stmf_ctl_lock_exit;
5443 	}
5444 
5445 	switch (cmd) {
5446 	case STMF_CMD_LU_ONLINE:
5447 		switch (ilu->ilu_state) {
5448 			case STMF_STATE_OFFLINE:
5449 				ret = STMF_SUCCESS;
5450 				break;
5451 			case STMF_STATE_ONLINE:
5452 			case STMF_STATE_ONLINING:
5453 				ret = STMF_ALREADY;
5454 				break;
5455 			case STMF_STATE_OFFLINING:
5456 				ret = STMF_BUSY;
5457 				break;
5458 			default:
5459 				ret = STMF_BADSTATE;
5460 				break;
5461 		}
5462 		if (ret != STMF_SUCCESS)
5463 			goto stmf_ctl_lock_exit;
5464 
5465 		ilu->ilu_state = STMF_STATE_ONLINING;
5466 		mutex_exit(&stmf_state.stmf_lock);
5467 		stmf_svc_queue(cmd, obj, (stmf_state_change_info_t *)arg);
5468 		break;
5469 
5470 	case STMF_CMD_LU_ONLINE_COMPLETE:
5471 		if (ilu->ilu_state != STMF_STATE_ONLINING) {
5472 			ret = STMF_BADSTATE;
5473 			goto stmf_ctl_lock_exit;
5474 		}
5475 		if (((stmf_change_status_t *)arg)->st_completion_status ==
5476 		    STMF_SUCCESS) {
5477 			ilu->ilu_state = STMF_STATE_ONLINE;
5478 			mutex_exit(&stmf_state.stmf_lock);
5479 			((stmf_lu_t *)obj)->lu_ctl((stmf_lu_t *)obj,
5480 			    STMF_ACK_LU_ONLINE_COMPLETE, arg);
5481 			mutex_enter(&stmf_state.stmf_lock);
5482 			stmf_add_lu_to_active_sessions((stmf_lu_t *)obj);
5483 		} else {
5484 			/* XXX: should throw a meesage an record more data */
5485 			ilu->ilu_state = STMF_STATE_OFFLINE;
5486 		}
5487 		ret = STMF_SUCCESS;
5488 		goto stmf_ctl_lock_exit;
5489 
5490 	case STMF_CMD_LU_OFFLINE:
5491 		switch (ilu->ilu_state) {
5492 			case STMF_STATE_ONLINE:
5493 				ret = STMF_SUCCESS;
5494 				break;
5495 			case STMF_STATE_OFFLINE:
5496 			case STMF_STATE_OFFLINING:
5497 				ret = STMF_ALREADY;
5498 				break;
5499 			case STMF_STATE_ONLINING:
5500 				ret = STMF_BUSY;
5501 				break;
5502 			default:
5503 				ret = STMF_BADSTATE;
5504 				break;
5505 		}
5506 		if (ret != STMF_SUCCESS)
5507 			goto stmf_ctl_lock_exit;
5508 		ilu->ilu_state = STMF_STATE_OFFLINING;
5509 		mutex_exit(&stmf_state.stmf_lock);
5510 		stmf_svc_queue(cmd, obj, (stmf_state_change_info_t *)arg);
5511 		break;
5512 
5513 	case STMF_CMD_LU_OFFLINE_COMPLETE:
5514 		if (ilu->ilu_state != STMF_STATE_OFFLINING) {
5515 			ret = STMF_BADSTATE;
5516 			goto stmf_ctl_lock_exit;
5517 		}
5518 		if (((stmf_change_status_t *)arg)->st_completion_status ==
5519 		    STMF_SUCCESS) {
5520 			ilu->ilu_state = STMF_STATE_OFFLINE;
5521 			mutex_exit(&stmf_state.stmf_lock);
5522 			((stmf_lu_t *)obj)->lu_ctl((stmf_lu_t *)obj,
5523 			    STMF_ACK_LU_OFFLINE_COMPLETE, arg);
5524 			mutex_enter(&stmf_state.stmf_lock);
5525 		} else {
5526 			ilu->ilu_state = STMF_STATE_ONLINE;
5527 			stmf_add_lu_to_active_sessions((stmf_lu_t *)obj);
5528 		}
5529 		mutex_exit(&stmf_state.stmf_lock);
5530 		break;
5531 
5532 	/*
5533 	 * LPORT_ONLINE/OFFLINE has nothing to do with link offline/online.
5534 	 * It's related with hardware disable/enable.
5535 	 */
5536 	case STMF_CMD_LPORT_ONLINE:
5537 		switch (ilport->ilport_state) {
5538 			case STMF_STATE_OFFLINE:
5539 				ret = STMF_SUCCESS;
5540 				break;
5541 			case STMF_STATE_ONLINE:
5542 			case STMF_STATE_ONLINING:
5543 				ret = STMF_ALREADY;
5544 				break;
5545 			case STMF_STATE_OFFLINING:
5546 				ret = STMF_BUSY;
5547 				break;
5548 			default:
5549 				ret = STMF_BADSTATE;
5550 				break;
5551 		}
5552 		if (ret != STMF_SUCCESS)
5553 			goto stmf_ctl_lock_exit;
5554 
5555 		/*
5556 		 * Only user request can recover the port from the
5557 		 * FORCED_OFFLINE state
5558 		 */
5559 		if (ilport->ilport_flags & ILPORT_FORCED_OFFLINE) {
5560 			if (!(ssci->st_rflags & STMF_RFLAG_USER_REQUEST)) {
5561 				ret = STMF_FAILURE;
5562 				goto stmf_ctl_lock_exit;
5563 			}
5564 		}
5565 
5566 		/*
5567 		 * Avoid too frequent request to online
5568 		 */
5569 		if (ssci->st_rflags & STMF_RFLAG_USER_REQUEST) {
5570 			ilport->ilport_online_times = 0;
5571 			ilport->ilport_avg_interval = 0;
5572 		}
5573 		if ((ilport->ilport_avg_interval < STMF_AVG_ONLINE_INTERVAL) &&
5574 		    (ilport->ilport_online_times >= 4)) {
5575 			ret = STMF_FAILURE;
5576 			ilport->ilport_flags |= ILPORT_FORCED_OFFLINE;
5577 			stmf_trace(NULL, "stmf_ctl: too frequent request to "
5578 			    "online the port");
5579 			cmn_err(CE_WARN, "stmf_ctl: too frequent request to "
5580 			    "online the port, set FORCED_OFFLINE now");
5581 			goto stmf_ctl_lock_exit;
5582 		}
5583 		if (ilport->ilport_online_times > 0) {
5584 			if (ilport->ilport_online_times == 1) {
5585 				ilport->ilport_avg_interval = ddi_get_lbolt() -
5586 				    ilport->ilport_last_online_clock;
5587 			} else {
5588 				ilport->ilport_avg_interval =
5589 				    (ilport->ilport_avg_interval +
5590 				    ddi_get_lbolt() -
5591 				    ilport->ilport_last_online_clock) >> 1;
5592 			}
5593 		}
5594 		ilport->ilport_last_online_clock = ddi_get_lbolt();
5595 		ilport->ilport_online_times++;
5596 
5597 		/*
5598 		 * Submit online service request
5599 		 */
5600 		ilport->ilport_flags &= ~ILPORT_FORCED_OFFLINE;
5601 		ilport->ilport_state = STMF_STATE_ONLINING;
5602 		mutex_exit(&stmf_state.stmf_lock);
5603 		stmf_svc_queue(cmd, obj, (stmf_state_change_info_t *)arg);
5604 		break;
5605 
5606 	case STMF_CMD_LPORT_ONLINE_COMPLETE:
5607 		if (ilport->ilport_state != STMF_STATE_ONLINING) {
5608 			ret = STMF_BADSTATE;
5609 			goto stmf_ctl_lock_exit;
5610 		}
5611 		if (((stmf_change_status_t *)arg)->st_completion_status ==
5612 		    STMF_SUCCESS) {
5613 			ilport->ilport_state = STMF_STATE_ONLINE;
5614 			mutex_exit(&stmf_state.stmf_lock);
5615 			((stmf_local_port_t *)obj)->lport_ctl(
5616 			    (stmf_local_port_t *)obj,
5617 			    STMF_ACK_LPORT_ONLINE_COMPLETE, arg);
5618 			mutex_enter(&stmf_state.stmf_lock);
5619 		} else {
5620 			ilport->ilport_state = STMF_STATE_OFFLINE;
5621 		}
5622 		ret = STMF_SUCCESS;
5623 		goto stmf_ctl_lock_exit;
5624 
5625 	case STMF_CMD_LPORT_OFFLINE:
5626 		switch (ilport->ilport_state) {
5627 			case STMF_STATE_ONLINE:
5628 				ret = STMF_SUCCESS;
5629 				break;
5630 			case STMF_STATE_OFFLINE:
5631 			case STMF_STATE_OFFLINING:
5632 				ret = STMF_ALREADY;
5633 				break;
5634 			case STMF_STATE_ONLINING:
5635 				ret = STMF_BUSY;
5636 				break;
5637 			default:
5638 				ret = STMF_BADSTATE;
5639 				break;
5640 		}
5641 		if (ret != STMF_SUCCESS)
5642 			goto stmf_ctl_lock_exit;
5643 
5644 		ilport->ilport_state = STMF_STATE_OFFLINING;
5645 		mutex_exit(&stmf_state.stmf_lock);
5646 		stmf_svc_queue(cmd, obj, (stmf_state_change_info_t *)arg);
5647 		break;
5648 
5649 	case STMF_CMD_LPORT_OFFLINE_COMPLETE:
5650 		if (ilport->ilport_state != STMF_STATE_OFFLINING) {
5651 			ret = STMF_BADSTATE;
5652 			goto stmf_ctl_lock_exit;
5653 		}
5654 		if (((stmf_change_status_t *)arg)->st_completion_status ==
5655 		    STMF_SUCCESS) {
5656 			ilport->ilport_state = STMF_STATE_OFFLINE;
5657 			mutex_exit(&stmf_state.stmf_lock);
5658 			((stmf_local_port_t *)obj)->lport_ctl(
5659 			    (stmf_local_port_t *)obj,
5660 			    STMF_ACK_LPORT_OFFLINE_COMPLETE, arg);
5661 			mutex_enter(&stmf_state.stmf_lock);
5662 		} else {
5663 			ilport->ilport_state = STMF_STATE_ONLINE;
5664 		}
5665 		mutex_exit(&stmf_state.stmf_lock);
5666 		break;
5667 
5668 	default:
5669 		cmn_err(CE_WARN, "Invalid ctl cmd received %x", cmd);
5670 		ret = STMF_INVALID_ARG;
5671 		goto stmf_ctl_lock_exit;
5672 	}
5673 
5674 	return (STMF_SUCCESS);
5675 
5676 stmf_ctl_lock_exit:;
5677 	mutex_exit(&stmf_state.stmf_lock);
5678 	return (ret);
5679 }
5680 
5681 /* ARGSUSED */
5682 stmf_status_t
5683 stmf_info_impl(uint32_t cmd, void *arg1, void *arg2, uint8_t *buf,
5684 						uint32_t *bufsizep)
5685 {
5686 	return (STMF_NOT_SUPPORTED);
5687 }
5688 
5689 /* ARGSUSED */
5690 stmf_status_t
5691 stmf_info(uint32_t cmd, void *arg1, void *arg2, uint8_t *buf,
5692 						uint32_t *bufsizep)
5693 {
5694 	uint32_t cl = SI_GET_CLASS(cmd);
5695 
5696 	if (cl == SI_STMF) {
5697 		return (stmf_info_impl(cmd, arg1, arg2, buf, bufsizep));
5698 	}
5699 	if (cl == SI_LPORT) {
5700 		return (((stmf_local_port_t *)arg1)->lport_info(cmd, arg1,
5701 		    arg2, buf, bufsizep));
5702 	} else if (cl == SI_LU) {
5703 		return (((stmf_lu_t *)arg1)->lu_info(cmd, arg1, arg2, buf,
5704 		    bufsizep));
5705 	}
5706 
5707 	return (STMF_NOT_SUPPORTED);
5708 }
5709 
5710 /*
5711  * Used by port providers. pwwn is 8 byte wwn, sdid is the devid used by
5712  * stmf to register local ports. The ident should have 20 bytes in buffer
5713  * space to convert the wwn to "wwn.xxxxxxxxxxxxxxxx" string.
5714  */
5715 void
5716 stmf_wwn_to_devid_desc(scsi_devid_desc_t *sdid, uint8_t *wwn,
5717     uint8_t protocol_id)
5718 {
5719 	char wwn_str[20+1];
5720 
5721 	sdid->protocol_id = protocol_id;
5722 	sdid->piv = 1;
5723 	sdid->code_set = CODE_SET_ASCII;
5724 	sdid->association = ID_IS_TARGET_PORT;
5725 	sdid->ident_length = 20;
5726 	/* Convert wwn value to "wwn.XXXXXXXXXXXXXXXX" format */
5727 	(void) snprintf(wwn_str, sizeof (wwn_str),
5728 	    "wwn.%02X%02X%02X%02X%02X%02X%02X%02X",
5729 	    wwn[0], wwn[1], wwn[2], wwn[3], wwn[4], wwn[5], wwn[6], wwn[7]);
5730 	bcopy(wwn_str, (char *)sdid->ident, 20);
5731 }
5732 
5733 
5734 stmf_xfer_data_t *
5735 stmf_prepare_tpgs_data(uint8_t ilu_alua)
5736 {
5737 	stmf_xfer_data_t *xd;
5738 	stmf_i_local_port_t *ilport;
5739 	uint8_t *p;
5740 	uint32_t sz, asz, nports = 0, nports_standby = 0;
5741 
5742 	mutex_enter(&stmf_state.stmf_lock);
5743 	/* check if any ports are standby and create second group */
5744 	for (ilport = stmf_state.stmf_ilportlist; ilport;
5745 	    ilport = ilport->ilport_next) {
5746 		if (ilport->ilport_standby == 1) {
5747 			nports_standby++;
5748 		} else {
5749 			nports++;
5750 		}
5751 	}
5752 
5753 	/* The spec only allows for 255 ports to be reported per group */
5754 	nports = min(nports, 255);
5755 	nports_standby = min(nports_standby, 255);
5756 	sz = (nports * 4) + 12;
5757 	if (nports_standby && ilu_alua) {
5758 		sz += (nports_standby * 4) + 8;
5759 	}
5760 	asz = sz + sizeof (*xd) - 4;
5761 	xd = (stmf_xfer_data_t *)kmem_zalloc(asz, KM_NOSLEEP);
5762 	if (xd == NULL) {
5763 		mutex_exit(&stmf_state.stmf_lock);
5764 		return (NULL);
5765 	}
5766 	xd->alloc_size = asz;
5767 	xd->size_left = sz;
5768 
5769 	p = xd->buf;
5770 
5771 	*((uint32_t *)p) = BE_32(sz - 4);
5772 	p += 4;
5773 	p[0] = 0x80;	/* PREF */
5774 	p[1] = 5;	/* AO_SUP, S_SUP */
5775 	if (stmf_state.stmf_alua_node == 1) {
5776 		p[3] = 1;	/* Group 1 */
5777 	} else {
5778 		p[3] = 0;	/* Group 0 */
5779 	}
5780 	p[7] = nports & 0xff;
5781 	p += 8;
5782 	for (ilport = stmf_state.stmf_ilportlist; ilport;
5783 	    ilport = ilport->ilport_next) {
5784 		if (ilport->ilport_standby == 1) {
5785 			continue;
5786 		}
5787 		((uint16_t *)p)[1] = BE_16(ilport->ilport_rtpid);
5788 		p += 4;
5789 	}
5790 	if (nports_standby && ilu_alua) {
5791 		p[0] = 0x02;	/* Non PREF, Standby */
5792 		p[1] = 5;	/* AO_SUP, S_SUP */
5793 		if (stmf_state.stmf_alua_node == 1) {
5794 			p[3] = 0;	/* Group 0 */
5795 		} else {
5796 			p[3] = 1;	/* Group 1 */
5797 		}
5798 		p[7] = nports_standby & 0xff;
5799 		p += 8;
5800 		for (ilport = stmf_state.stmf_ilportlist; ilport;
5801 		    ilport = ilport->ilport_next) {
5802 			if (ilport->ilport_standby == 0) {
5803 				continue;
5804 			}
5805 			((uint16_t *)p)[1] = BE_16(ilport->ilport_rtpid);
5806 			p += 4;
5807 		}
5808 	}
5809 
5810 	mutex_exit(&stmf_state.stmf_lock);
5811 
5812 	return (xd);
5813 }
5814 
5815 struct scsi_devid_desc *
5816 stmf_scsilib_get_devid_desc(uint16_t rtpid)
5817 {
5818 	scsi_devid_desc_t *devid = NULL;
5819 	stmf_i_local_port_t *ilport;
5820 
5821 	mutex_enter(&stmf_state.stmf_lock);
5822 
5823 	for (ilport = stmf_state.stmf_ilportlist; ilport;
5824 	    ilport = ilport->ilport_next) {
5825 		if (ilport->ilport_rtpid == rtpid) {
5826 			scsi_devid_desc_t *id = ilport->ilport_lport->lport_id;
5827 			uint32_t id_sz = sizeof (scsi_devid_desc_t) - 1 +
5828 			    id->ident_length;
5829 			devid = (scsi_devid_desc_t *)kmem_zalloc(id_sz,
5830 			    KM_NOSLEEP);
5831 			if (devid != NULL) {
5832 				bcopy(id, devid, id_sz);
5833 			}
5834 			break;
5835 		}
5836 	}
5837 
5838 	mutex_exit(&stmf_state.stmf_lock);
5839 	return (devid);
5840 }
5841 
5842 uint16_t
5843 stmf_scsilib_get_lport_rtid(struct scsi_devid_desc *devid)
5844 {
5845 	stmf_i_local_port_t	*ilport;
5846 	scsi_devid_desc_t	*id;
5847 	uint16_t		rtpid = 0;
5848 
5849 	mutex_enter(&stmf_state.stmf_lock);
5850 	for (ilport = stmf_state.stmf_ilportlist; ilport;
5851 	    ilport = ilport->ilport_next) {
5852 		id = ilport->ilport_lport->lport_id;
5853 		if ((devid->ident_length == id->ident_length) &&
5854 		    (memcmp(devid->ident, id->ident, id->ident_length) == 0)) {
5855 			rtpid = ilport->ilport_rtpid;
5856 			break;
5857 		}
5858 	}
5859 	mutex_exit(&stmf_state.stmf_lock);
5860 	return (rtpid);
5861 }
5862 
5863 static uint16_t stmf_lu_id_gen_number = 0;
5864 
5865 stmf_status_t
5866 stmf_scsilib_uniq_lu_id(uint32_t company_id, scsi_devid_desc_t *lu_id)
5867 {
5868 	return (stmf_scsilib_uniq_lu_id2(company_id, 0, lu_id));
5869 }
5870 
5871 stmf_status_t
5872 stmf_scsilib_uniq_lu_id2(uint32_t company_id, uint32_t host_id,
5873     scsi_devid_desc_t *lu_id)
5874 {
5875 	uint8_t *p;
5876 	struct timeval32 timestamp32;
5877 	uint32_t *t = (uint32_t *)&timestamp32;
5878 	struct ether_addr mac;
5879 	uint8_t *e = (uint8_t *)&mac;
5880 	int hid = (int)host_id;
5881 
5882 	if (company_id == COMPANY_ID_NONE)
5883 		company_id = COMPANY_ID_SUN;
5884 
5885 	if (lu_id->ident_length != 0x10)
5886 		return (STMF_INVALID_ARG);
5887 
5888 	p = (uint8_t *)lu_id;
5889 
5890 	atomic_add_16(&stmf_lu_id_gen_number, 1);
5891 
5892 	p[0] = 0xf1; p[1] = 3; p[2] = 0; p[3] = 0x10;
5893 	p[4] = ((company_id >> 20) & 0xf) | 0x60;
5894 	p[5] = (company_id >> 12) & 0xff;
5895 	p[6] = (company_id >> 4) & 0xff;
5896 	p[7] = (company_id << 4) & 0xf0;
5897 	if (hid == 0 && !localetheraddr((struct ether_addr *)NULL, &mac)) {
5898 		hid = BE_32((int)zone_get_hostid(NULL));
5899 	}
5900 	if (hid != 0) {
5901 		e[0] = (hid >> 24) & 0xff;
5902 		e[1] = (hid >> 16) & 0xff;
5903 		e[2] = (hid >> 8) & 0xff;
5904 		e[3] = hid & 0xff;
5905 		e[4] = e[5] = 0;
5906 	}
5907 	bcopy(e, p+8, 6);
5908 	uniqtime32(&timestamp32);
5909 	*t = BE_32(*t);
5910 	bcopy(t, p+14, 4);
5911 	p[18] = (stmf_lu_id_gen_number >> 8) & 0xff;
5912 	p[19] = stmf_lu_id_gen_number & 0xff;
5913 
5914 	return (STMF_SUCCESS);
5915 }
5916 
5917 /*
5918  * saa is sense key, ASC, ASCQ
5919  */
5920 void
5921 stmf_scsilib_send_status(scsi_task_t *task, uint8_t st, uint32_t saa)
5922 {
5923 	uint8_t sd[18];
5924 	task->task_scsi_status = st;
5925 	if (st == 2) {
5926 		bzero(sd, 18);
5927 		sd[0] = 0x70;
5928 		sd[2] = (saa >> 16) & 0xf;
5929 		sd[7] = 10;
5930 		sd[12] = (saa >> 8) & 0xff;
5931 		sd[13] = saa & 0xff;
5932 		task->task_sense_data = sd;
5933 		task->task_sense_length = 18;
5934 	} else {
5935 		task->task_sense_data = NULL;
5936 		task->task_sense_length = 0;
5937 	}
5938 	(void) stmf_send_scsi_status(task, STMF_IOF_LU_DONE);
5939 }
5940 
5941 uint32_t
5942 stmf_scsilib_prepare_vpd_page83(scsi_task_t *task, uint8_t *page,
5943     uint32_t page_len, uint8_t byte0, uint32_t vpd_mask)
5944 {
5945 	uint8_t		*p = NULL;
5946 	uint8_t		small_buf[32];
5947 	uint32_t	sz = 0;
5948 	uint32_t	n = 4;
5949 	uint32_t	m = 0;
5950 	uint32_t	last_bit = 0;
5951 
5952 	if (page_len < 4)
5953 		return (0);
5954 	if (page_len > 65535)
5955 		page_len = 65535;
5956 
5957 	page[0] = byte0;
5958 	page[1] = 0x83;
5959 
5960 	/* CONSTCOND */
5961 	while (1) {
5962 		m += sz;
5963 		if (sz && (page_len > n)) {
5964 			uint32_t copysz;
5965 			copysz = page_len > (n + sz) ? sz : page_len - n;
5966 			bcopy(p, page + n, copysz);
5967 			n += copysz;
5968 		}
5969 		vpd_mask &= ~last_bit;
5970 		if (vpd_mask == 0)
5971 			break;
5972 
5973 		if (vpd_mask & STMF_VPD_LU_ID) {
5974 			last_bit = STMF_VPD_LU_ID;
5975 			sz = task->task_lu->lu_id->ident_length + 4;
5976 			p = (uint8_t *)task->task_lu->lu_id;
5977 			continue;
5978 		} else if (vpd_mask & STMF_VPD_TARGET_ID) {
5979 			last_bit = STMF_VPD_TARGET_ID;
5980 			sz = task->task_lport->lport_id->ident_length + 4;
5981 			p = (uint8_t *)task->task_lport->lport_id;
5982 			continue;
5983 		} else if (vpd_mask & STMF_VPD_TP_GROUP) {
5984 			stmf_i_local_port_t *ilport;
5985 			last_bit = STMF_VPD_TP_GROUP;
5986 			p = small_buf;
5987 			bzero(p, 8);
5988 			p[0] = 1;
5989 			p[1] = 0x15;
5990 			p[3] = 4;
5991 			ilport = (stmf_i_local_port_t *)
5992 			    task->task_lport->lport_stmf_private;
5993 			/*
5994 			 * If we're in alua mode, group 1 contains all alua
5995 			 * participating ports and all standby ports
5996 			 * > 255. Otherwise, if we're in alua mode, any local
5997 			 * ports (non standby/pppt) are also in group 1 if the
5998 			 * alua node is 1. Otherwise the group is 0.
5999 			 */
6000 			if ((stmf_state.stmf_alua_state &&
6001 			    (ilport->ilport_alua || ilport->ilport_standby) &&
6002 			    ilport->ilport_rtpid > 255) ||
6003 			    (stmf_state.stmf_alua_node == 1 &&
6004 			    ilport->ilport_standby != 1)) {
6005 				p[7] = 1;	/* Group 1 */
6006 			}
6007 			sz = 8;
6008 			continue;
6009 		} else if (vpd_mask & STMF_VPD_RELATIVE_TP_ID) {
6010 			stmf_i_local_port_t *ilport;
6011 
6012 			last_bit = STMF_VPD_RELATIVE_TP_ID;
6013 			p = small_buf;
6014 			bzero(p, 8);
6015 			p[0] = 1;
6016 			p[1] = 0x14;
6017 			p[3] = 4;
6018 			ilport = (stmf_i_local_port_t *)
6019 			    task->task_lport->lport_stmf_private;
6020 			p[6] = (ilport->ilport_rtpid >> 8) & 0xff;
6021 			p[7] = ilport->ilport_rtpid & 0xff;
6022 			sz = 8;
6023 			continue;
6024 		} else {
6025 			cmn_err(CE_WARN, "Invalid vpd_mask");
6026 			break;
6027 		}
6028 	}
6029 
6030 	page[2] = (m >> 8) & 0xff;
6031 	page[3] = m & 0xff;
6032 
6033 	return (n);
6034 }
6035 
6036 void
6037 stmf_scsilib_handle_report_tpgs(scsi_task_t *task, stmf_data_buf_t *dbuf)
6038 {
6039 	stmf_i_scsi_task_t *itask =
6040 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
6041 	stmf_i_lu_t *ilu =
6042 	    (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
6043 	stmf_xfer_data_t *xd;
6044 	uint32_t sz, minsz;
6045 
6046 	itask->itask_flags |= ITASK_DEFAULT_HANDLING;
6047 	task->task_cmd_xfer_length =
6048 	    ((((uint32_t)task->task_cdb[6]) << 24) |
6049 	    (((uint32_t)task->task_cdb[7]) << 16) |
6050 	    (((uint32_t)task->task_cdb[8]) << 8) |
6051 	    ((uint32_t)task->task_cdb[9]));
6052 
6053 	if (task->task_additional_flags &
6054 	    TASK_AF_NO_EXPECTED_XFER_LENGTH) {
6055 		task->task_expected_xfer_length =
6056 		    task->task_cmd_xfer_length;
6057 	}
6058 
6059 	if (task->task_cmd_xfer_length == 0) {
6060 		stmf_scsilib_send_status(task, STATUS_GOOD, 0);
6061 		return;
6062 	}
6063 	if (task->task_cmd_xfer_length < 4) {
6064 		stmf_scsilib_send_status(task, STATUS_CHECK,
6065 		    STMF_SAA_INVALID_FIELD_IN_CDB);
6066 		return;
6067 	}
6068 
6069 	sz = min(task->task_expected_xfer_length,
6070 	    task->task_cmd_xfer_length);
6071 
6072 	xd = stmf_prepare_tpgs_data(ilu->ilu_alua);
6073 
6074 	if (xd == NULL) {
6075 		stmf_abort(STMF_QUEUE_TASK_ABORT, task,
6076 		    STMF_ALLOC_FAILURE, NULL);
6077 		return;
6078 	}
6079 
6080 	sz = min(sz, xd->size_left);
6081 	xd->size_left = sz;
6082 	minsz = min(512, sz);
6083 
6084 	if (dbuf == NULL)
6085 		dbuf = stmf_alloc_dbuf(task, sz, &minsz, 0);
6086 	if (dbuf == NULL) {
6087 		kmem_free(xd, xd->alloc_size);
6088 		stmf_abort(STMF_QUEUE_TASK_ABORT, task,
6089 		    STMF_ALLOC_FAILURE, NULL);
6090 		return;
6091 	}
6092 	dbuf->db_lu_private = xd;
6093 	stmf_xd_to_dbuf(dbuf);
6094 
6095 	dbuf->db_flags = DB_DIRECTION_TO_RPORT;
6096 	(void) stmf_xfer_data(task, dbuf, 0);
6097 
6098 }
6099 
6100 void
6101 stmf_scsilib_handle_task_mgmt(scsi_task_t *task)
6102 {
6103 
6104 	switch (task->task_mgmt_function) {
6105 	/*
6106 	 * For now we will abort all I/Os on the LU in case of ABORT_TASK_SET
6107 	 * and ABORT_TASK. But unlike LUN_RESET we will not reset LU state
6108 	 * in these cases. This needs to be changed to abort only the required
6109 	 * set.
6110 	 */
6111 	case TM_ABORT_TASK:
6112 	case TM_ABORT_TASK_SET:
6113 	case TM_CLEAR_TASK_SET:
6114 	case TM_LUN_RESET:
6115 		stmf_handle_lun_reset(task);
6116 		/* issue the reset to the proxy node as well */
6117 		if (stmf_state.stmf_alua_state == 1) {
6118 			(void) stmf_proxy_scsi_cmd(task, NULL);
6119 		}
6120 		return;
6121 	case TM_TARGET_RESET:
6122 	case TM_TARGET_COLD_RESET:
6123 	case TM_TARGET_WARM_RESET:
6124 		stmf_handle_target_reset(task);
6125 		return;
6126 	default:
6127 		/* We dont support this task mgmt function */
6128 		stmf_scsilib_send_status(task, STATUS_CHECK,
6129 		    STMF_SAA_INVALID_FIELD_IN_CMD_IU);
6130 		return;
6131 	}
6132 }
6133 
6134 void
6135 stmf_handle_lun_reset(scsi_task_t *task)
6136 {
6137 	stmf_i_scsi_task_t *itask;
6138 	stmf_i_lu_t *ilu;
6139 
6140 	itask = (stmf_i_scsi_task_t *)task->task_stmf_private;
6141 	ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
6142 
6143 	/*
6144 	 * To sync with target reset, grab this lock. The LU is not going
6145 	 * anywhere as there is atleast one task pending (this task).
6146 	 */
6147 	mutex_enter(&stmf_state.stmf_lock);
6148 
6149 	if (ilu->ilu_flags & ILU_RESET_ACTIVE) {
6150 		mutex_exit(&stmf_state.stmf_lock);
6151 		stmf_scsilib_send_status(task, STATUS_CHECK,
6152 		    STMF_SAA_OPERATION_IN_PROGRESS);
6153 		return;
6154 	}
6155 	atomic_or_32(&ilu->ilu_flags, ILU_RESET_ACTIVE);
6156 	mutex_exit(&stmf_state.stmf_lock);
6157 
6158 	/*
6159 	 * Mark this task as the one causing LU reset so that we know who
6160 	 * was responsible for setting the ILU_RESET_ACTIVE. In case this
6161 	 * task itself gets aborted, we will clear ILU_RESET_ACTIVE.
6162 	 */
6163 	itask->itask_flags |= ITASK_DEFAULT_HANDLING | ITASK_CAUSING_LU_RESET;
6164 
6165 	/* Initiatiate abort on all commands on this LU except this one */
6166 	stmf_abort(STMF_QUEUE_ABORT_LU, task, STMF_ABORTED, task->task_lu);
6167 
6168 	/* Start polling on this task */
6169 	if (stmf_task_poll_lu(task, ITASK_DEFAULT_POLL_TIMEOUT)
6170 	    != STMF_SUCCESS) {
6171 		stmf_abort(STMF_QUEUE_TASK_ABORT, task, STMF_ALLOC_FAILURE,
6172 		    NULL);
6173 		return;
6174 	}
6175 }
6176 
6177 void
6178 stmf_handle_target_reset(scsi_task_t *task)
6179 {
6180 	stmf_i_scsi_task_t *itask;
6181 	stmf_i_lu_t *ilu;
6182 	stmf_i_scsi_session_t *iss;
6183 	stmf_lun_map_t *lm;
6184 	stmf_lun_map_ent_t *lm_ent;
6185 	int i, lf;
6186 
6187 	itask = (stmf_i_scsi_task_t *)task->task_stmf_private;
6188 	iss = (stmf_i_scsi_session_t *)task->task_session->ss_stmf_private;
6189 	ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
6190 
6191 	/*
6192 	 * To sync with LUN reset, grab this lock. The session is not going
6193 	 * anywhere as there is atleast one task pending (this task).
6194 	 */
6195 	mutex_enter(&stmf_state.stmf_lock);
6196 
6197 	/* Grab the session lock as a writer to prevent any changes in it */
6198 	rw_enter(iss->iss_lockp, RW_WRITER);
6199 
6200 	if (iss->iss_flags & ISS_RESET_ACTIVE) {
6201 		rw_exit(iss->iss_lockp);
6202 		mutex_exit(&stmf_state.stmf_lock);
6203 		stmf_scsilib_send_status(task, STATUS_CHECK,
6204 		    STMF_SAA_OPERATION_IN_PROGRESS);
6205 		return;
6206 	}
6207 	atomic_or_32(&iss->iss_flags, ISS_RESET_ACTIVE);
6208 
6209 	/*
6210 	 * Now go through each LUN in this session and make sure all of them
6211 	 * can be reset.
6212 	 */
6213 	lm = iss->iss_sm;
6214 	for (i = 0, lf = 0; i < lm->lm_nentries; i++) {
6215 		if (lm->lm_plus[i] == NULL)
6216 			continue;
6217 		lf++;
6218 		lm_ent = (stmf_lun_map_ent_t *)lm->lm_plus[i];
6219 		ilu = (stmf_i_lu_t *)(lm_ent->ent_lu->lu_stmf_private);
6220 		if (ilu->ilu_flags & ILU_RESET_ACTIVE) {
6221 			atomic_and_32(&iss->iss_flags, ~ISS_RESET_ACTIVE);
6222 			rw_exit(iss->iss_lockp);
6223 			mutex_exit(&stmf_state.stmf_lock);
6224 			stmf_scsilib_send_status(task, STATUS_CHECK,
6225 			    STMF_SAA_OPERATION_IN_PROGRESS);
6226 			return;
6227 		}
6228 	}
6229 	if (lf == 0) {
6230 		/* No luns in this session */
6231 		atomic_and_32(&iss->iss_flags, ~ISS_RESET_ACTIVE);
6232 		rw_exit(iss->iss_lockp);
6233 		mutex_exit(&stmf_state.stmf_lock);
6234 		stmf_scsilib_send_status(task, STATUS_GOOD, 0);
6235 		return;
6236 	}
6237 
6238 	/* ok, start the damage */
6239 	itask->itask_flags |= ITASK_DEFAULT_HANDLING |
6240 	    ITASK_CAUSING_TARGET_RESET;
6241 	for (i = 0; i < lm->lm_nentries; i++) {
6242 		if (lm->lm_plus[i] == NULL)
6243 			continue;
6244 		lm_ent = (stmf_lun_map_ent_t *)lm->lm_plus[i];
6245 		ilu = (stmf_i_lu_t *)(lm_ent->ent_lu->lu_stmf_private);
6246 		atomic_or_32(&ilu->ilu_flags, ILU_RESET_ACTIVE);
6247 	}
6248 
6249 	for (i = 0; i < lm->lm_nentries; i++) {
6250 		if (lm->lm_plus[i] == NULL)
6251 			continue;
6252 		lm_ent = (stmf_lun_map_ent_t *)lm->lm_plus[i];
6253 		stmf_abort(STMF_QUEUE_ABORT_LU, task, STMF_ABORTED,
6254 		    lm_ent->ent_lu);
6255 	}
6256 
6257 	rw_exit(iss->iss_lockp);
6258 	mutex_exit(&stmf_state.stmf_lock);
6259 
6260 	/* Start polling on this task */
6261 	if (stmf_task_poll_lu(task, ITASK_DEFAULT_POLL_TIMEOUT)
6262 	    != STMF_SUCCESS) {
6263 		stmf_abort(STMF_QUEUE_TASK_ABORT, task, STMF_ALLOC_FAILURE,
6264 		    NULL);
6265 		return;
6266 	}
6267 }
6268 
6269 int
6270 stmf_handle_cmd_during_ic(stmf_i_scsi_task_t *itask)
6271 {
6272 	scsi_task_t *task = itask->itask_task;
6273 	stmf_i_scsi_session_t *iss = (stmf_i_scsi_session_t *)
6274 	    task->task_session->ss_stmf_private;
6275 
6276 	rw_enter(iss->iss_lockp, RW_WRITER);
6277 	if (((iss->iss_flags & ISS_LUN_INVENTORY_CHANGED) == 0) ||
6278 	    (task->task_cdb[0] == SCMD_INQUIRY)) {
6279 		rw_exit(iss->iss_lockp);
6280 		return (0);
6281 	}
6282 	atomic_and_32(&iss->iss_flags,
6283 	    ~(ISS_LUN_INVENTORY_CHANGED | ISS_GOT_INITIAL_LUNS));
6284 	rw_exit(iss->iss_lockp);
6285 
6286 	if (task->task_cdb[0] == SCMD_REPORT_LUNS) {
6287 		return (0);
6288 	}
6289 	stmf_scsilib_send_status(task, STATUS_CHECK,
6290 	    STMF_SAA_REPORT_LUN_DATA_HAS_CHANGED);
6291 	return (1);
6292 }
6293 
6294 void
6295 stmf_worker_init()
6296 {
6297 	uint32_t i;
6298 
6299 	/* Make local copy of global tunables */
6300 	stmf_i_max_nworkers = stmf_max_nworkers;
6301 	stmf_i_min_nworkers = stmf_min_nworkers;
6302 
6303 	ASSERT(stmf_workers == NULL);
6304 	if (stmf_i_min_nworkers < 4) {
6305 		stmf_i_min_nworkers = 4;
6306 	}
6307 	if (stmf_i_max_nworkers < stmf_i_min_nworkers) {
6308 		stmf_i_max_nworkers = stmf_i_min_nworkers;
6309 	}
6310 	stmf_workers = (stmf_worker_t *)kmem_zalloc(
6311 	    sizeof (stmf_worker_t) * stmf_i_max_nworkers, KM_SLEEP);
6312 	for (i = 0; i < stmf_i_max_nworkers; i++) {
6313 		stmf_worker_t *w = &stmf_workers[i];
6314 		mutex_init(&w->worker_lock, NULL, MUTEX_DRIVER, NULL);
6315 		cv_init(&w->worker_cv, NULL, CV_DRIVER, NULL);
6316 	}
6317 	stmf_worker_mgmt_delay = drv_usectohz(20 * 1000);
6318 	stmf_workers_state = STMF_WORKERS_ENABLED;
6319 
6320 	/* Workers will be started by stmf_worker_mgmt() */
6321 
6322 	/* Lets wait for atleast one worker to start */
6323 	while (stmf_nworkers_cur == 0)
6324 		delay(drv_usectohz(20 * 1000));
6325 	stmf_worker_mgmt_delay = drv_usectohz(3 * 1000 * 1000);
6326 }
6327 
6328 stmf_status_t
6329 stmf_worker_fini()
6330 {
6331 	int i;
6332 	clock_t sb;
6333 
6334 	if (stmf_workers_state == STMF_WORKERS_DISABLED)
6335 		return (STMF_SUCCESS);
6336 	ASSERT(stmf_workers);
6337 	stmf_workers_state = STMF_WORKERS_DISABLED;
6338 	stmf_worker_mgmt_delay = drv_usectohz(20 * 1000);
6339 	cv_signal(&stmf_state.stmf_cv);
6340 
6341 	sb = ddi_get_lbolt() + drv_usectohz(10 * 1000 * 1000);
6342 	/* Wait for all the threads to die */
6343 	while (stmf_nworkers_cur != 0) {
6344 		if (ddi_get_lbolt() > sb) {
6345 			stmf_workers_state = STMF_WORKERS_ENABLED;
6346 			return (STMF_BUSY);
6347 		}
6348 		delay(drv_usectohz(100 * 1000));
6349 	}
6350 	for (i = 0; i < stmf_i_max_nworkers; i++) {
6351 		stmf_worker_t *w = &stmf_workers[i];
6352 		mutex_destroy(&w->worker_lock);
6353 		cv_destroy(&w->worker_cv);
6354 	}
6355 	kmem_free(stmf_workers, sizeof (stmf_worker_t) * stmf_i_max_nworkers);
6356 	stmf_workers = NULL;
6357 
6358 	return (STMF_SUCCESS);
6359 }
6360 
6361 void
6362 stmf_worker_task(void *arg)
6363 {
6364 	stmf_worker_t *w;
6365 	stmf_i_scsi_session_t *iss;
6366 	scsi_task_t *task;
6367 	stmf_i_scsi_task_t *itask;
6368 	stmf_data_buf_t *dbuf;
6369 	stmf_lu_t *lu;
6370 	clock_t wait_timer = 0;
6371 	clock_t wait_ticks, wait_delta = 0;
6372 	uint32_t old, new;
6373 	uint8_t curcmd;
6374 	uint8_t abort_free;
6375 	uint8_t wait_queue;
6376 	uint8_t dec_qdepth;
6377 
6378 	w = (stmf_worker_t *)arg;
6379 	wait_ticks = drv_usectohz(10000);
6380 
6381 	DTRACE_PROBE1(worker__create, stmf_worker_t, w);
6382 	mutex_enter(&w->worker_lock);
6383 	w->worker_flags |= STMF_WORKER_STARTED | STMF_WORKER_ACTIVE;
6384 stmf_worker_loop:;
6385 	if ((w->worker_ref_count == 0) &&
6386 	    (w->worker_flags & STMF_WORKER_TERMINATE)) {
6387 		w->worker_flags &= ~(STMF_WORKER_STARTED |
6388 		    STMF_WORKER_ACTIVE | STMF_WORKER_TERMINATE);
6389 		w->worker_tid = NULL;
6390 		mutex_exit(&w->worker_lock);
6391 		DTRACE_PROBE1(worker__destroy, stmf_worker_t, w);
6392 		thread_exit();
6393 	}
6394 	/* CONSTCOND */
6395 	while (1) {
6396 		dec_qdepth = 0;
6397 		if (wait_timer && (ddi_get_lbolt() >= wait_timer)) {
6398 			wait_timer = 0;
6399 			wait_delta = 0;
6400 			if (w->worker_wait_head) {
6401 				ASSERT(w->worker_wait_tail);
6402 				if (w->worker_task_head == NULL)
6403 					w->worker_task_head =
6404 					    w->worker_wait_head;
6405 				else
6406 					w->worker_task_tail->itask_worker_next =
6407 					    w->worker_wait_head;
6408 				w->worker_task_tail = w->worker_wait_tail;
6409 				w->worker_wait_head = w->worker_wait_tail =
6410 				    NULL;
6411 			}
6412 		}
6413 		if ((itask = w->worker_task_head) == NULL) {
6414 			break;
6415 		}
6416 		task = itask->itask_task;
6417 		DTRACE_PROBE2(worker__active, stmf_worker_t, w,
6418 		    scsi_task_t *, task);
6419 		w->worker_task_head = itask->itask_worker_next;
6420 		if (w->worker_task_head == NULL)
6421 			w->worker_task_tail = NULL;
6422 
6423 		wait_queue = 0;
6424 		abort_free = 0;
6425 		if (itask->itask_ncmds > 0) {
6426 			curcmd = itask->itask_cmd_stack[itask->itask_ncmds - 1];
6427 		} else {
6428 			ASSERT(itask->itask_flags & ITASK_BEING_ABORTED);
6429 		}
6430 		do {
6431 			old = itask->itask_flags;
6432 			if (old & ITASK_BEING_ABORTED) {
6433 				itask->itask_ncmds = 1;
6434 				curcmd = itask->itask_cmd_stack[0] =
6435 				    ITASK_CMD_ABORT;
6436 				goto out_itask_flag_loop;
6437 			} else if ((curcmd & ITASK_CMD_MASK) ==
6438 			    ITASK_CMD_NEW_TASK) {
6439 				/*
6440 				 * set ITASK_KSTAT_IN_RUNQ, this flag
6441 				 * will not reset until task completed
6442 				 */
6443 				new = old | ITASK_KNOWN_TO_LU |
6444 				    ITASK_KSTAT_IN_RUNQ;
6445 			} else {
6446 				goto out_itask_flag_loop;
6447 			}
6448 		} while (atomic_cas_32(&itask->itask_flags, old, new) != old);
6449 
6450 out_itask_flag_loop:
6451 
6452 		/*
6453 		 * Decide if this task needs to go to a queue and/or if
6454 		 * we can decrement the itask_cmd_stack.
6455 		 */
6456 		if (curcmd == ITASK_CMD_ABORT) {
6457 			if (itask->itask_flags & (ITASK_KNOWN_TO_LU |
6458 			    ITASK_KNOWN_TO_TGT_PORT)) {
6459 				wait_queue = 1;
6460 			} else {
6461 				abort_free = 1;
6462 			}
6463 		} else if ((curcmd & ITASK_CMD_POLL) &&
6464 		    (itask->itask_poll_timeout > ddi_get_lbolt())) {
6465 			wait_queue = 1;
6466 		}
6467 
6468 		if (wait_queue) {
6469 			itask->itask_worker_next = NULL;
6470 			if (w->worker_wait_tail) {
6471 				w->worker_wait_tail->itask_worker_next = itask;
6472 			} else {
6473 				w->worker_wait_head = itask;
6474 			}
6475 			w->worker_wait_tail = itask;
6476 			if (wait_timer == 0) {
6477 				wait_timer = ddi_get_lbolt() + wait_ticks;
6478 				wait_delta = wait_ticks;
6479 			}
6480 		} else if ((--(itask->itask_ncmds)) != 0) {
6481 			itask->itask_worker_next = NULL;
6482 			if (w->worker_task_tail) {
6483 				w->worker_task_tail->itask_worker_next = itask;
6484 			} else {
6485 				w->worker_task_head = itask;
6486 			}
6487 			w->worker_task_tail = itask;
6488 		} else {
6489 			atomic_and_32(&itask->itask_flags,
6490 			    ~ITASK_IN_WORKER_QUEUE);
6491 			/*
6492 			 * This is where the queue depth should go down by
6493 			 * one but we delay that on purpose to account for
6494 			 * the call into the provider. The actual decrement
6495 			 * happens after the worker has done its job.
6496 			 */
6497 			dec_qdepth = 1;
6498 			itask->itask_waitq_time +=
6499 			    gethrtime() - itask->itask_waitq_enter_timestamp;
6500 		}
6501 
6502 		/* We made it here means we are going to call LU */
6503 		if ((itask->itask_flags & ITASK_DEFAULT_HANDLING) == 0)
6504 			lu = task->task_lu;
6505 		else
6506 			lu = dlun0;
6507 		dbuf = itask->itask_dbufs[ITASK_CMD_BUF_NDX(curcmd)];
6508 		mutex_exit(&w->worker_lock);
6509 		curcmd &= ITASK_CMD_MASK;
6510 		switch (curcmd) {
6511 		case ITASK_CMD_NEW_TASK:
6512 			iss = (stmf_i_scsi_session_t *)
6513 			    task->task_session->ss_stmf_private;
6514 			stmf_itl_lu_new_task(itask);
6515 			if (iss->iss_flags & ISS_LUN_INVENTORY_CHANGED) {
6516 				if (stmf_handle_cmd_during_ic(itask))
6517 					break;
6518 			}
6519 #ifdef	DEBUG
6520 			if (stmf_drop_task_counter > 0) {
6521 				if (atomic_add_32_nv(
6522 				    (uint32_t *)&stmf_drop_task_counter,
6523 				    -1) == 1) {
6524 					break;
6525 				}
6526 			}
6527 #endif
6528 			DTRACE_PROBE1(scsi__task__start, scsi_task_t *, task);
6529 			lu->lu_new_task(task, dbuf);
6530 			break;
6531 		case ITASK_CMD_DATA_XFER_DONE:
6532 			lu->lu_dbuf_xfer_done(task, dbuf);
6533 			break;
6534 		case ITASK_CMD_STATUS_DONE:
6535 			lu->lu_send_status_done(task);
6536 			break;
6537 		case ITASK_CMD_ABORT:
6538 			if (abort_free) {
6539 				stmf_task_free(task);
6540 			} else {
6541 				stmf_do_task_abort(task);
6542 			}
6543 			break;
6544 		case ITASK_CMD_POLL_LU:
6545 			if (!wait_queue) {
6546 				lu->lu_task_poll(task);
6547 			}
6548 			break;
6549 		case ITASK_CMD_POLL_LPORT:
6550 			if (!wait_queue)
6551 				task->task_lport->lport_task_poll(task);
6552 			break;
6553 		case ITASK_CMD_SEND_STATUS:
6554 		/* case ITASK_CMD_XFER_DATA: */
6555 			break;
6556 		}
6557 		mutex_enter(&w->worker_lock);
6558 		if (dec_qdepth) {
6559 			w->worker_queue_depth--;
6560 		}
6561 	}
6562 	if ((w->worker_flags & STMF_WORKER_TERMINATE) && (wait_timer == 0)) {
6563 		if (w->worker_ref_count == 0)
6564 			goto stmf_worker_loop;
6565 		else {
6566 			wait_timer = ddi_get_lbolt() + 1;
6567 			wait_delta = 1;
6568 		}
6569 	}
6570 	w->worker_flags &= ~STMF_WORKER_ACTIVE;
6571 	if (wait_timer) {
6572 		DTRACE_PROBE1(worker__timed__sleep, stmf_worker_t, w);
6573 		(void) cv_reltimedwait(&w->worker_cv, &w->worker_lock,
6574 		    wait_delta, TR_CLOCK_TICK);
6575 	} else {
6576 		DTRACE_PROBE1(worker__sleep, stmf_worker_t, w);
6577 		cv_wait(&w->worker_cv, &w->worker_lock);
6578 	}
6579 	DTRACE_PROBE1(worker__wakeup, stmf_worker_t, w);
6580 	w->worker_flags |= STMF_WORKER_ACTIVE;
6581 	goto stmf_worker_loop;
6582 }
6583 
6584 void
6585 stmf_worker_mgmt()
6586 {
6587 	int i;
6588 	int workers_needed;
6589 	uint32_t qd;
6590 	clock_t tps, d = 0;
6591 	uint32_t cur_max_ntasks = 0;
6592 	stmf_worker_t *w;
6593 
6594 	/* Check if we are trying to increase the # of threads */
6595 	for (i = stmf_nworkers_cur; i < stmf_nworkers_needed; i++) {
6596 		if (stmf_workers[i].worker_flags & STMF_WORKER_STARTED) {
6597 			stmf_nworkers_cur++;
6598 			stmf_nworkers_accepting_cmds++;
6599 		} else {
6600 			/* Wait for transition to complete */
6601 			return;
6602 		}
6603 	}
6604 	/* Check if we are trying to decrease the # of workers */
6605 	for (i = (stmf_nworkers_cur - 1); i >= stmf_nworkers_needed; i--) {
6606 		if ((stmf_workers[i].worker_flags & STMF_WORKER_STARTED) == 0) {
6607 			stmf_nworkers_cur--;
6608 			/*
6609 			 * stmf_nworkers_accepting_cmds has already been
6610 			 * updated by the request to reduce the # of workers.
6611 			 */
6612 		} else {
6613 			/* Wait for transition to complete */
6614 			return;
6615 		}
6616 	}
6617 	/* Check if we are being asked to quit */
6618 	if (stmf_workers_state != STMF_WORKERS_ENABLED) {
6619 		if (stmf_nworkers_cur) {
6620 			workers_needed = 0;
6621 			goto worker_mgmt_trigger_change;
6622 		}
6623 		return;
6624 	}
6625 	/* Check if we are starting */
6626 	if (stmf_nworkers_cur < stmf_i_min_nworkers) {
6627 		workers_needed = stmf_i_min_nworkers;
6628 		goto worker_mgmt_trigger_change;
6629 	}
6630 
6631 	tps = drv_usectohz(1 * 1000 * 1000);
6632 	if ((stmf_wm_last != 0) &&
6633 	    ((d = ddi_get_lbolt() - stmf_wm_last) > tps)) {
6634 		qd = 0;
6635 		for (i = 0; i < stmf_nworkers_accepting_cmds; i++) {
6636 			qd += stmf_workers[i].worker_max_qdepth_pu;
6637 			stmf_workers[i].worker_max_qdepth_pu = 0;
6638 			if (stmf_workers[i].worker_max_sys_qdepth_pu >
6639 			    cur_max_ntasks) {
6640 				cur_max_ntasks =
6641 				    stmf_workers[i].worker_max_sys_qdepth_pu;
6642 			}
6643 			stmf_workers[i].worker_max_sys_qdepth_pu = 0;
6644 		}
6645 	}
6646 	stmf_wm_last = ddi_get_lbolt();
6647 	if (d <= tps) {
6648 		/* still ramping up */
6649 		return;
6650 	}
6651 	/* max qdepth cannot be more than max tasks */
6652 	if (qd > cur_max_ntasks)
6653 		qd = cur_max_ntasks;
6654 
6655 	/* See if we have more workers */
6656 	if (qd < stmf_nworkers_accepting_cmds) {
6657 		/*
6658 		 * Since we dont reduce the worker count right away, monitor
6659 		 * the highest load during the scale_down_delay.
6660 		 */
6661 		if (qd > stmf_worker_scale_down_qd)
6662 			stmf_worker_scale_down_qd = qd;
6663 		if (stmf_worker_scale_down_timer == 0) {
6664 			stmf_worker_scale_down_timer = ddi_get_lbolt() +
6665 			    drv_usectohz(stmf_worker_scale_down_delay *
6666 			    1000 * 1000);
6667 			return;
6668 		}
6669 		if (ddi_get_lbolt() < stmf_worker_scale_down_timer) {
6670 			return;
6671 		}
6672 		/* Its time to reduce the workers */
6673 		if (stmf_worker_scale_down_qd < stmf_i_min_nworkers)
6674 			stmf_worker_scale_down_qd = stmf_i_min_nworkers;
6675 		if (stmf_worker_scale_down_qd > stmf_i_max_nworkers)
6676 			stmf_worker_scale_down_qd = stmf_i_max_nworkers;
6677 		if (stmf_worker_scale_down_qd == stmf_nworkers_cur)
6678 			return;
6679 		workers_needed = stmf_worker_scale_down_qd;
6680 		stmf_worker_scale_down_qd = 0;
6681 		goto worker_mgmt_trigger_change;
6682 	}
6683 	stmf_worker_scale_down_qd = 0;
6684 	stmf_worker_scale_down_timer = 0;
6685 	if (qd > stmf_i_max_nworkers)
6686 		qd = stmf_i_max_nworkers;
6687 	if (qd < stmf_i_min_nworkers)
6688 		qd = stmf_i_min_nworkers;
6689 	if (qd == stmf_nworkers_cur)
6690 		return;
6691 	workers_needed = qd;
6692 	goto worker_mgmt_trigger_change;
6693 
6694 	/* NOTREACHED */
6695 	return;
6696 
6697 worker_mgmt_trigger_change:
6698 	ASSERT(workers_needed != stmf_nworkers_cur);
6699 	if (workers_needed > stmf_nworkers_cur) {
6700 		stmf_nworkers_needed = workers_needed;
6701 		for (i = stmf_nworkers_cur; i < workers_needed; i++) {
6702 			w = &stmf_workers[i];
6703 			w->worker_tid = thread_create(NULL, 0, stmf_worker_task,
6704 			    (void *)&stmf_workers[i], 0, &p0, TS_RUN,
6705 			    minclsyspri);
6706 		}
6707 		return;
6708 	}
6709 	/* At this point we know that we are decreasing the # of workers */
6710 	stmf_nworkers_accepting_cmds = workers_needed;
6711 	stmf_nworkers_needed = workers_needed;
6712 	/* Signal the workers that its time to quit */
6713 	for (i = (stmf_nworkers_cur - 1); i >= stmf_nworkers_needed; i--) {
6714 		w = &stmf_workers[i];
6715 		ASSERT(w && (w->worker_flags & STMF_WORKER_STARTED));
6716 		mutex_enter(&w->worker_lock);
6717 		w->worker_flags |= STMF_WORKER_TERMINATE;
6718 		if ((w->worker_flags & STMF_WORKER_ACTIVE) == 0)
6719 			cv_signal(&w->worker_cv);
6720 		mutex_exit(&w->worker_lock);
6721 	}
6722 }
6723 
6724 /*
6725  * Fills out a dbuf from stmf_xfer_data_t (contained in the db_lu_private).
6726  * If all the data has been filled out, frees the xd and makes
6727  * db_lu_private NULL.
6728  */
6729 void
6730 stmf_xd_to_dbuf(stmf_data_buf_t *dbuf)
6731 {
6732 	stmf_xfer_data_t *xd;
6733 	uint8_t *p;
6734 	int i;
6735 	uint32_t s;
6736 
6737 	xd = (stmf_xfer_data_t *)dbuf->db_lu_private;
6738 	dbuf->db_data_size = 0;
6739 	dbuf->db_relative_offset = xd->size_done;
6740 	for (i = 0; i < dbuf->db_sglist_length; i++) {
6741 		s = min(xd->size_left, dbuf->db_sglist[i].seg_length);
6742 		p = &xd->buf[xd->size_done];
6743 		bcopy(p, dbuf->db_sglist[i].seg_addr, s);
6744 		xd->size_left -= s;
6745 		xd->size_done += s;
6746 		dbuf->db_data_size += s;
6747 		if (xd->size_left == 0) {
6748 			kmem_free(xd, xd->alloc_size);
6749 			dbuf->db_lu_private = NULL;
6750 			return;
6751 		}
6752 	}
6753 }
6754 
6755 /* ARGSUSED */
6756 stmf_status_t
6757 stmf_dlun0_task_alloc(scsi_task_t *task)
6758 {
6759 	return (STMF_SUCCESS);
6760 }
6761 
6762 void
6763 stmf_dlun0_new_task(scsi_task_t *task, stmf_data_buf_t *dbuf)
6764 {
6765 	uint8_t *cdbp = (uint8_t *)&task->task_cdb[0];
6766 	stmf_i_scsi_session_t *iss;
6767 	uint32_t sz, minsz;
6768 	uint8_t *p;
6769 	stmf_xfer_data_t *xd;
6770 	uint8_t inq_page_length = 31;
6771 
6772 	if (task->task_mgmt_function) {
6773 		stmf_scsilib_handle_task_mgmt(task);
6774 		return;
6775 	}
6776 
6777 	switch (cdbp[0]) {
6778 	case SCMD_INQUIRY:
6779 		/*
6780 		 * Basic protocol checks.  In addition, only reply to
6781 		 * standard inquiry.  Otherwise, the LU provider needs
6782 		 * to respond.
6783 		 */
6784 
6785 		if (cdbp[2] || (cdbp[1] & 1) || cdbp[5]) {
6786 			stmf_scsilib_send_status(task, STATUS_CHECK,
6787 			    STMF_SAA_INVALID_FIELD_IN_CDB);
6788 			return;
6789 		}
6790 
6791 		task->task_cmd_xfer_length =
6792 		    (((uint32_t)cdbp[3]) << 8) | cdbp[4];
6793 
6794 		if (task->task_additional_flags &
6795 		    TASK_AF_NO_EXPECTED_XFER_LENGTH) {
6796 			task->task_expected_xfer_length =
6797 			    task->task_cmd_xfer_length;
6798 		}
6799 
6800 		sz = min(task->task_expected_xfer_length,
6801 		    min(36, task->task_cmd_xfer_length));
6802 		minsz = 36;
6803 
6804 		if (sz == 0) {
6805 			stmf_scsilib_send_status(task, STATUS_GOOD, 0);
6806 			return;
6807 		}
6808 
6809 		if (dbuf && (dbuf->db_sglist[0].seg_length < 36)) {
6810 			/*
6811 			 * Ignore any preallocated dbuf if the size is less
6812 			 * than 36. It will be freed during the task_free.
6813 			 */
6814 			dbuf = NULL;
6815 		}
6816 		if (dbuf == NULL)
6817 			dbuf = stmf_alloc_dbuf(task, minsz, &minsz, 0);
6818 		if ((dbuf == NULL) || (dbuf->db_sglist[0].seg_length < sz)) {
6819 			stmf_abort(STMF_QUEUE_TASK_ABORT, task,
6820 			    STMF_ALLOC_FAILURE, NULL);
6821 			return;
6822 		}
6823 		dbuf->db_lu_private = NULL;
6824 
6825 		p = dbuf->db_sglist[0].seg_addr;
6826 
6827 		/*
6828 		 * Standard inquiry handling only.
6829 		 */
6830 
6831 		bzero(p, inq_page_length + 5);
6832 
6833 		p[0] = DPQ_SUPPORTED | DTYPE_UNKNOWN;
6834 		p[2] = 5;
6835 		p[3] = 0x12;
6836 		p[4] = inq_page_length;
6837 		p[6] = 0x80;
6838 
6839 		(void) strncpy((char *)p+8, "SUN     ", 8);
6840 		(void) strncpy((char *)p+16, "COMSTAR	       ", 16);
6841 		(void) strncpy((char *)p+32, "1.0 ", 4);
6842 
6843 		dbuf->db_data_size = sz;
6844 		dbuf->db_relative_offset = 0;
6845 		dbuf->db_flags = DB_DIRECTION_TO_RPORT;
6846 		(void) stmf_xfer_data(task, dbuf, 0);
6847 
6848 		return;
6849 
6850 	case SCMD_REPORT_LUNS:
6851 		task->task_cmd_xfer_length =
6852 		    ((((uint32_t)task->task_cdb[6]) << 24) |
6853 		    (((uint32_t)task->task_cdb[7]) << 16) |
6854 		    (((uint32_t)task->task_cdb[8]) << 8) |
6855 		    ((uint32_t)task->task_cdb[9]));
6856 
6857 		if (task->task_additional_flags &
6858 		    TASK_AF_NO_EXPECTED_XFER_LENGTH) {
6859 			task->task_expected_xfer_length =
6860 			    task->task_cmd_xfer_length;
6861 		}
6862 
6863 		sz = min(task->task_expected_xfer_length,
6864 		    task->task_cmd_xfer_length);
6865 
6866 		if (sz < 16) {
6867 			stmf_scsilib_send_status(task, STATUS_CHECK,
6868 			    STMF_SAA_INVALID_FIELD_IN_CDB);
6869 			return;
6870 		}
6871 
6872 		iss = (stmf_i_scsi_session_t *)
6873 		    task->task_session->ss_stmf_private;
6874 		rw_enter(iss->iss_lockp, RW_WRITER);
6875 		xd = stmf_session_prepare_report_lun_data(iss->iss_sm);
6876 		rw_exit(iss->iss_lockp);
6877 
6878 		if (xd == NULL) {
6879 			stmf_abort(STMF_QUEUE_TASK_ABORT, task,
6880 			    STMF_ALLOC_FAILURE, NULL);
6881 			return;
6882 		}
6883 
6884 		sz = min(sz, xd->size_left);
6885 		xd->size_left = sz;
6886 		minsz = min(512, sz);
6887 
6888 		if (dbuf == NULL)
6889 			dbuf = stmf_alloc_dbuf(task, sz, &minsz, 0);
6890 		if (dbuf == NULL) {
6891 			kmem_free(xd, xd->alloc_size);
6892 			stmf_abort(STMF_QUEUE_TASK_ABORT, task,
6893 			    STMF_ALLOC_FAILURE, NULL);
6894 			return;
6895 		}
6896 		dbuf->db_lu_private = xd;
6897 		stmf_xd_to_dbuf(dbuf);
6898 
6899 		atomic_and_32(&iss->iss_flags,
6900 		    ~(ISS_LUN_INVENTORY_CHANGED | ISS_GOT_INITIAL_LUNS));
6901 		dbuf->db_flags = DB_DIRECTION_TO_RPORT;
6902 		(void) stmf_xfer_data(task, dbuf, 0);
6903 		return;
6904 	}
6905 
6906 	stmf_scsilib_send_status(task, STATUS_CHECK, STMF_SAA_INVALID_OPCODE);
6907 }
6908 
6909 void
6910 stmf_dlun0_dbuf_done(scsi_task_t *task, stmf_data_buf_t *dbuf)
6911 {
6912 	stmf_i_scsi_task_t *itask =
6913 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
6914 
6915 	if (dbuf->db_xfer_status != STMF_SUCCESS) {
6916 		stmf_abort(STMF_QUEUE_TASK_ABORT, task,
6917 		    dbuf->db_xfer_status, NULL);
6918 		return;
6919 	}
6920 	task->task_nbytes_transferred = dbuf->db_data_size;
6921 	if (dbuf->db_lu_private) {
6922 		/* There is more */
6923 		stmf_xd_to_dbuf(dbuf);
6924 		(void) stmf_xfer_data(task, dbuf, 0);
6925 		return;
6926 	}
6927 	/*
6928 	 * If this is a proxy task, it will need to be completed from the
6929 	 * proxy port provider. This message lets pppt know that the xfer
6930 	 * is complete. When we receive the status from pppt, we will
6931 	 * then relay that status back to the lport.
6932 	 */
6933 	if (itask->itask_flags & ITASK_PROXY_TASK) {
6934 		stmf_ic_msg_t *ic_xfer_done_msg = NULL;
6935 		stmf_status_t ic_ret = STMF_FAILURE;
6936 		uint64_t session_msg_id;
6937 		mutex_enter(&stmf_state.stmf_lock);
6938 		session_msg_id = stmf_proxy_msg_id++;
6939 		mutex_exit(&stmf_state.stmf_lock);
6940 		/* send xfer done status to pppt */
6941 		ic_xfer_done_msg = ic_scsi_data_xfer_done_msg_alloc(
6942 		    itask->itask_proxy_msg_id,
6943 		    task->task_session->ss_session_id,
6944 		    STMF_SUCCESS, session_msg_id);
6945 		if (ic_xfer_done_msg) {
6946 			ic_ret = ic_tx_msg(ic_xfer_done_msg);
6947 			if (ic_ret != STMF_IC_MSG_SUCCESS) {
6948 				cmn_err(CE_WARN, "unable to xmit session msg");
6949 			}
6950 		}
6951 		/* task will be completed from pppt */
6952 		return;
6953 	}
6954 	stmf_scsilib_send_status(task, STATUS_GOOD, 0);
6955 }
6956 
6957 /* ARGSUSED */
6958 void
6959 stmf_dlun0_status_done(scsi_task_t *task)
6960 {
6961 }
6962 
6963 /* ARGSUSED */
6964 void
6965 stmf_dlun0_task_free(scsi_task_t *task)
6966 {
6967 }
6968 
6969 /* ARGSUSED */
6970 stmf_status_t
6971 stmf_dlun0_abort(struct stmf_lu *lu, int abort_cmd, void *arg, uint32_t flags)
6972 {
6973 	scsi_task_t *task = (scsi_task_t *)arg;
6974 	stmf_i_scsi_task_t *itask =
6975 	    (stmf_i_scsi_task_t *)task->task_stmf_private;
6976 	stmf_i_lu_t *ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
6977 	int i;
6978 	uint8_t map;
6979 
6980 	if ((task->task_mgmt_function) && (itask->itask_flags &
6981 	    (ITASK_CAUSING_LU_RESET | ITASK_CAUSING_TARGET_RESET))) {
6982 		switch (task->task_mgmt_function) {
6983 		case TM_ABORT_TASK:
6984 		case TM_ABORT_TASK_SET:
6985 		case TM_CLEAR_TASK_SET:
6986 		case TM_LUN_RESET:
6987 			atomic_and_32(&ilu->ilu_flags, ~ILU_RESET_ACTIVE);
6988 			break;
6989 		case TM_TARGET_RESET:
6990 		case TM_TARGET_COLD_RESET:
6991 		case TM_TARGET_WARM_RESET:
6992 			stmf_abort_target_reset(task);
6993 			break;
6994 		}
6995 		return (STMF_ABORT_SUCCESS);
6996 	}
6997 
6998 	/*
6999 	 * OK so its not a task mgmt. Make sure we free any xd sitting
7000 	 * inside any dbuf.
7001 	 */
7002 	if ((map = itask->itask_allocated_buf_map) != 0) {
7003 		for (i = 0; i < 4; i++) {
7004 			if ((map & 1) &&
7005 			    ((itask->itask_dbufs[i])->db_lu_private)) {
7006 				stmf_xfer_data_t *xd;
7007 				stmf_data_buf_t *dbuf;
7008 
7009 				dbuf = itask->itask_dbufs[i];
7010 				xd = (stmf_xfer_data_t *)dbuf->db_lu_private;
7011 				dbuf->db_lu_private = NULL;
7012 				kmem_free(xd, xd->alloc_size);
7013 			}
7014 			map >>= 1;
7015 		}
7016 	}
7017 	return (STMF_ABORT_SUCCESS);
7018 }
7019 
7020 void
7021 stmf_dlun0_task_poll(struct scsi_task *task)
7022 {
7023 	/* Right now we only do this for handling task management functions */
7024 	ASSERT(task->task_mgmt_function);
7025 
7026 	switch (task->task_mgmt_function) {
7027 	case TM_ABORT_TASK:
7028 	case TM_ABORT_TASK_SET:
7029 	case TM_CLEAR_TASK_SET:
7030 	case TM_LUN_RESET:
7031 		(void) stmf_lun_reset_poll(task->task_lu, task, 0);
7032 		return;
7033 	case TM_TARGET_RESET:
7034 	case TM_TARGET_COLD_RESET:
7035 	case TM_TARGET_WARM_RESET:
7036 		stmf_target_reset_poll(task);
7037 		return;
7038 	}
7039 }
7040 
7041 /* ARGSUSED */
7042 void
7043 stmf_dlun0_ctl(struct stmf_lu *lu, int cmd, void *arg)
7044 {
7045 	/* This function will never be called */
7046 	cmn_err(CE_WARN, "stmf_dlun0_ctl called with cmd %x", cmd);
7047 }
7048 
7049 void
7050 stmf_dlun_init()
7051 {
7052 	stmf_i_lu_t *ilu;
7053 
7054 	dlun0 = stmf_alloc(STMF_STRUCT_STMF_LU, 0, 0);
7055 	dlun0->lu_task_alloc = stmf_dlun0_task_alloc;
7056 	dlun0->lu_new_task = stmf_dlun0_new_task;
7057 	dlun0->lu_dbuf_xfer_done = stmf_dlun0_dbuf_done;
7058 	dlun0->lu_send_status_done = stmf_dlun0_status_done;
7059 	dlun0->lu_task_free = stmf_dlun0_task_free;
7060 	dlun0->lu_abort = stmf_dlun0_abort;
7061 	dlun0->lu_task_poll = stmf_dlun0_task_poll;
7062 	dlun0->lu_ctl = stmf_dlun0_ctl;
7063 
7064 	ilu = (stmf_i_lu_t *)dlun0->lu_stmf_private;
7065 	ilu->ilu_cur_task_cntr = &ilu->ilu_task_cntr1;
7066 }
7067 
7068 stmf_status_t
7069 stmf_dlun_fini()
7070 {
7071 	stmf_i_lu_t *ilu;
7072 
7073 	ilu = (stmf_i_lu_t *)dlun0->lu_stmf_private;
7074 
7075 	ASSERT(ilu->ilu_ntasks == ilu->ilu_ntasks_free);
7076 	if (ilu->ilu_ntasks) {
7077 		stmf_i_scsi_task_t *itask, *nitask;
7078 
7079 		nitask = ilu->ilu_tasks;
7080 		do {
7081 			itask = nitask;
7082 			nitask = itask->itask_lu_next;
7083 			dlun0->lu_task_free(itask->itask_task);
7084 			stmf_free(itask->itask_task);
7085 		} while (nitask != NULL);
7086 
7087 	}
7088 	stmf_free(dlun0);
7089 	return (STMF_SUCCESS);
7090 }
7091 
7092 void
7093 stmf_abort_target_reset(scsi_task_t *task)
7094 {
7095 	stmf_i_scsi_session_t *iss = (stmf_i_scsi_session_t *)
7096 	    task->task_session->ss_stmf_private;
7097 	stmf_lun_map_t *lm;
7098 	stmf_lun_map_ent_t *lm_ent;
7099 	stmf_i_lu_t *ilu;
7100 	int i;
7101 
7102 	rw_enter(iss->iss_lockp, RW_READER);
7103 	lm = iss->iss_sm;
7104 	for (i = 0; i < lm->lm_nentries; i++) {
7105 		if (lm->lm_plus[i] == NULL)
7106 			continue;
7107 		lm_ent = (stmf_lun_map_ent_t *)lm->lm_plus[i];
7108 		ilu = (stmf_i_lu_t *)lm_ent->ent_lu->lu_stmf_private;
7109 		if (ilu->ilu_flags & ILU_RESET_ACTIVE) {
7110 			atomic_and_32(&ilu->ilu_flags, ~ILU_RESET_ACTIVE);
7111 		}
7112 	}
7113 	atomic_and_32(&iss->iss_flags, ~ISS_RESET_ACTIVE);
7114 	rw_exit(iss->iss_lockp);
7115 }
7116 
7117 /*
7118  * The return value is only used by function managing target reset.
7119  */
7120 stmf_status_t
7121 stmf_lun_reset_poll(stmf_lu_t *lu, struct scsi_task *task, int target_reset)
7122 {
7123 	stmf_i_lu_t *ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
7124 	int ntasks_pending;
7125 
7126 	ntasks_pending = ilu->ilu_ntasks - ilu->ilu_ntasks_free;
7127 	/*
7128 	 * This function is also used during Target reset. The idea is that
7129 	 * once all the commands are aborted, call the LU's reset entry
7130 	 * point (abort entry point with a reset flag). But if this Task
7131 	 * mgmt is running on this LU then all the tasks cannot be aborted.
7132 	 * one task (this task) will still be running which is OK.
7133 	 */
7134 	if ((ntasks_pending == 0) || ((task->task_lu == lu) &&
7135 	    (ntasks_pending == 1))) {
7136 		stmf_status_t ret;
7137 
7138 		if ((task->task_mgmt_function == TM_LUN_RESET) ||
7139 		    (task->task_mgmt_function == TM_TARGET_RESET) ||
7140 		    (task->task_mgmt_function == TM_TARGET_WARM_RESET) ||
7141 		    (task->task_mgmt_function == TM_TARGET_COLD_RESET)) {
7142 			ret = lu->lu_abort(lu, STMF_LU_RESET_STATE, task, 0);
7143 		} else {
7144 			ret = STMF_SUCCESS;
7145 		}
7146 		if (ret == STMF_SUCCESS) {
7147 			atomic_and_32(&ilu->ilu_flags, ~ILU_RESET_ACTIVE);
7148 		}
7149 		if (target_reset) {
7150 			return (ret);
7151 		}
7152 		if (ret == STMF_SUCCESS) {
7153 			stmf_scsilib_send_status(task, STATUS_GOOD, 0);
7154 			return (ret);
7155 		}
7156 		if (ret != STMF_BUSY) {
7157 			stmf_abort(STMF_QUEUE_TASK_ABORT, task, ret, NULL);
7158 			return (ret);
7159 		}
7160 	}
7161 
7162 	if (target_reset) {
7163 		/* Tell target reset polling code that we are not done */
7164 		return (STMF_BUSY);
7165 	}
7166 
7167 	if (stmf_task_poll_lu(task, ITASK_DEFAULT_POLL_TIMEOUT)
7168 	    != STMF_SUCCESS) {
7169 		stmf_abort(STMF_QUEUE_TASK_ABORT, task,
7170 		    STMF_ALLOC_FAILURE, NULL);
7171 		return (STMF_SUCCESS);
7172 	}
7173 
7174 	return (STMF_SUCCESS);
7175 }
7176 
7177 void
7178 stmf_target_reset_poll(struct scsi_task *task)
7179 {
7180 	stmf_i_scsi_session_t *iss = (stmf_i_scsi_session_t *)
7181 	    task->task_session->ss_stmf_private;
7182 	stmf_lun_map_t *lm;
7183 	stmf_lun_map_ent_t *lm_ent;
7184 	stmf_i_lu_t *ilu;
7185 	stmf_status_t ret;
7186 	int i;
7187 	int not_done = 0;
7188 
7189 	ASSERT(iss->iss_flags & ISS_RESET_ACTIVE);
7190 
7191 	rw_enter(iss->iss_lockp, RW_READER);
7192 	lm = iss->iss_sm;
7193 	for (i = 0; i < lm->lm_nentries; i++) {
7194 		if (lm->lm_plus[i] == NULL)
7195 			continue;
7196 		lm_ent = (stmf_lun_map_ent_t *)lm->lm_plus[i];
7197 		ilu = (stmf_i_lu_t *)lm_ent->ent_lu->lu_stmf_private;
7198 		if (ilu->ilu_flags & ILU_RESET_ACTIVE) {
7199 			rw_exit(iss->iss_lockp);
7200 			ret = stmf_lun_reset_poll(lm_ent->ent_lu, task, 1);
7201 			rw_enter(iss->iss_lockp, RW_READER);
7202 			if (ret == STMF_SUCCESS)
7203 				continue;
7204 			not_done = 1;
7205 			if (ret != STMF_BUSY) {
7206 				rw_exit(iss->iss_lockp);
7207 				stmf_abort(STMF_QUEUE_TASK_ABORT, task,
7208 				    STMF_ABORTED, NULL);
7209 				return;
7210 			}
7211 		}
7212 	}
7213 	rw_exit(iss->iss_lockp);
7214 
7215 	if (not_done) {
7216 		if (stmf_task_poll_lu(task, ITASK_DEFAULT_POLL_TIMEOUT)
7217 		    != STMF_SUCCESS) {
7218 			stmf_abort(STMF_QUEUE_TASK_ABORT, task,
7219 			    STMF_ALLOC_FAILURE, NULL);
7220 			return;
7221 		}
7222 		return;
7223 	}
7224 
7225 	atomic_and_32(&iss->iss_flags, ~ISS_RESET_ACTIVE);
7226 
7227 	stmf_scsilib_send_status(task, STATUS_GOOD, 0);
7228 }
7229 
7230 stmf_status_t
7231 stmf_lu_add_event(stmf_lu_t *lu, int eventid)
7232 {
7233 	stmf_i_lu_t *ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
7234 
7235 	if ((eventid < 0) || (eventid >= STMF_MAX_NUM_EVENTS)) {
7236 		return (STMF_INVALID_ARG);
7237 	}
7238 
7239 	STMF_EVENT_ADD(ilu->ilu_event_hdl, eventid);
7240 	return (STMF_SUCCESS);
7241 }
7242 
7243 stmf_status_t
7244 stmf_lu_remove_event(stmf_lu_t *lu, int eventid)
7245 {
7246 	stmf_i_lu_t *ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
7247 
7248 	if (eventid == STMF_EVENT_ALL) {
7249 		STMF_EVENT_CLEAR_ALL(ilu->ilu_event_hdl);
7250 		return (STMF_SUCCESS);
7251 	}
7252 
7253 	if ((eventid < 0) || (eventid >= STMF_MAX_NUM_EVENTS)) {
7254 		return (STMF_INVALID_ARG);
7255 	}
7256 
7257 	STMF_EVENT_REMOVE(ilu->ilu_event_hdl, eventid);
7258 	return (STMF_SUCCESS);
7259 }
7260 
7261 stmf_status_t
7262 stmf_lport_add_event(stmf_local_port_t *lport, int eventid)
7263 {
7264 	stmf_i_local_port_t *ilport =
7265 	    (stmf_i_local_port_t *)lport->lport_stmf_private;
7266 
7267 	if ((eventid < 0) || (eventid >= STMF_MAX_NUM_EVENTS)) {
7268 		return (STMF_INVALID_ARG);
7269 	}
7270 
7271 	STMF_EVENT_ADD(ilport->ilport_event_hdl, eventid);
7272 	return (STMF_SUCCESS);
7273 }
7274 
7275 stmf_status_t
7276 stmf_lport_remove_event(stmf_local_port_t *lport, int eventid)
7277 {
7278 	stmf_i_local_port_t *ilport =
7279 	    (stmf_i_local_port_t *)lport->lport_stmf_private;
7280 
7281 	if (eventid == STMF_EVENT_ALL) {
7282 		STMF_EVENT_CLEAR_ALL(ilport->ilport_event_hdl);
7283 		return (STMF_SUCCESS);
7284 	}
7285 
7286 	if ((eventid < 0) || (eventid >= STMF_MAX_NUM_EVENTS)) {
7287 		return (STMF_INVALID_ARG);
7288 	}
7289 
7290 	STMF_EVENT_REMOVE(ilport->ilport_event_hdl, eventid);
7291 	return (STMF_SUCCESS);
7292 }
7293 
7294 void
7295 stmf_generate_lu_event(stmf_i_lu_t *ilu, int eventid, void *arg, uint32_t flags)
7296 {
7297 	if (STMF_EVENT_ENABLED(ilu->ilu_event_hdl, eventid) &&
7298 	    (ilu->ilu_lu->lu_event_handler != NULL)) {
7299 		ilu->ilu_lu->lu_event_handler(ilu->ilu_lu, eventid, arg, flags);
7300 	}
7301 }
7302 
7303 void
7304 stmf_generate_lport_event(stmf_i_local_port_t *ilport, int eventid, void *arg,
7305 				uint32_t flags)
7306 {
7307 	if (STMF_EVENT_ENABLED(ilport->ilport_event_hdl, eventid) &&
7308 	    (ilport->ilport_lport->lport_event_handler != NULL)) {
7309 		ilport->ilport_lport->lport_event_handler(
7310 		    ilport->ilport_lport, eventid, arg, flags);
7311 	}
7312 }
7313 
7314 /*
7315  * With the possibility of having multiple itl sessions pointing to the
7316  * same itl_kstat_info, the ilu_kstat_lock mutex is used to synchronize
7317  * the kstat update of the ilu_kstat_io, itl_kstat_taskq and itl_kstat_lu_xfer
7318  * statistics.
7319  */
7320 void
7321 stmf_itl_task_start(stmf_i_scsi_task_t *itask)
7322 {
7323 	stmf_itl_data_t	*itl = itask->itask_itl_datap;
7324 	scsi_task_t	*task = itask->itask_task;
7325 	stmf_i_lu_t	*ilu;
7326 
7327 	if (itl == NULL || task->task_lu == dlun0)
7328 		return;
7329 	ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
7330 	mutex_enter(ilu->ilu_kstat_io->ks_lock);
7331 	itask->itask_start_timestamp = gethrtime();
7332 	kstat_waitq_enter(KSTAT_IO_PTR(itl->itl_kstat_taskq));
7333 	stmf_update_kstat_lu_q(itask->itask_task, kstat_waitq_enter);
7334 	mutex_exit(ilu->ilu_kstat_io->ks_lock);
7335 
7336 	stmf_update_kstat_lport_q(itask->itask_task, kstat_waitq_enter);
7337 }
7338 
7339 void
7340 stmf_itl_lu_new_task(stmf_i_scsi_task_t *itask)
7341 {
7342 	stmf_itl_data_t	*itl = itask->itask_itl_datap;
7343 	scsi_task_t	*task = itask->itask_task;
7344 	stmf_i_lu_t	*ilu;
7345 
7346 	if (itl == NULL || task->task_lu == dlun0)
7347 		return;
7348 	ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
7349 	mutex_enter(ilu->ilu_kstat_io->ks_lock);
7350 	kstat_waitq_to_runq(KSTAT_IO_PTR(itl->itl_kstat_taskq));
7351 	stmf_update_kstat_lu_q(itask->itask_task, kstat_waitq_to_runq);
7352 	mutex_exit(ilu->ilu_kstat_io->ks_lock);
7353 
7354 	stmf_update_kstat_lport_q(itask->itask_task, kstat_waitq_to_runq);
7355 }
7356 
7357 void
7358 stmf_itl_task_done(stmf_i_scsi_task_t *itask)
7359 {
7360 	stmf_itl_data_t		*itl = itask->itask_itl_datap;
7361 	scsi_task_t		*task = itask->itask_task;
7362 	kstat_io_t		*kip;
7363 	hrtime_t		elapsed_time;
7364 	stmf_kstat_itl_info_t	*itli;
7365 	stmf_i_lu_t	*ilu;
7366 
7367 	if (itl == NULL || task->task_lu == dlun0)
7368 		return;
7369 	ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
7370 
7371 	mutex_enter(ilu->ilu_kstat_io->ks_lock);
7372 	itli = (stmf_kstat_itl_info_t *)KSTAT_NAMED_PTR(itl->itl_kstat_info);
7373 	kip = KSTAT_IO_PTR(itl->itl_kstat_taskq);
7374 
7375 	itli->i_task_waitq_elapsed.value.ui64 += itask->itask_waitq_time;
7376 
7377 	itask->itask_done_timestamp = gethrtime();
7378 	elapsed_time =
7379 	    itask->itask_done_timestamp - itask->itask_start_timestamp;
7380 
7381 	if (task->task_flags & TF_READ_DATA) {
7382 		kip->reads++;
7383 		kip->nread += itask->itask_read_xfer;
7384 		itli->i_task_read_elapsed.value.ui64 += elapsed_time;
7385 		itli->i_lu_read_elapsed.value.ui64 +=
7386 		    itask->itask_lu_read_time;
7387 		itli->i_lport_read_elapsed.value.ui64 +=
7388 		    itask->itask_lport_read_time;
7389 	}
7390 
7391 	if (task->task_flags & TF_WRITE_DATA) {
7392 		kip->writes++;
7393 		kip->nwritten += itask->itask_write_xfer;
7394 		itli->i_task_write_elapsed.value.ui64 += elapsed_time;
7395 		itli->i_lu_write_elapsed.value.ui64 +=
7396 		    itask->itask_lu_write_time;
7397 		itli->i_lport_write_elapsed.value.ui64 +=
7398 		    itask->itask_lport_write_time;
7399 	}
7400 
7401 	if (itask->itask_flags & ITASK_KSTAT_IN_RUNQ) {
7402 		kstat_runq_exit(kip);
7403 		stmf_update_kstat_lu_q(task, kstat_runq_exit);
7404 		mutex_exit(ilu->ilu_kstat_io->ks_lock);
7405 		stmf_update_kstat_lport_q(task, kstat_runq_exit);
7406 	} else {
7407 		kstat_waitq_exit(kip);
7408 		stmf_update_kstat_lu_q(task, kstat_waitq_exit);
7409 		mutex_exit(ilu->ilu_kstat_io->ks_lock);
7410 		stmf_update_kstat_lport_q(task, kstat_waitq_exit);
7411 	}
7412 }
7413 
7414 void
7415 stmf_lu_xfer_start(scsi_task_t *task)
7416 {
7417 	stmf_i_scsi_task_t *itask = task->task_stmf_private;
7418 	stmf_itl_data_t	*itl = itask->itask_itl_datap;
7419 	stmf_i_lu_t	*ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
7420 	kstat_io_t		*kip;
7421 
7422 	if (itl == NULL || task->task_lu == dlun0)
7423 		return;
7424 
7425 	kip = KSTAT_IO_PTR(itl->itl_kstat_lu_xfer);
7426 	mutex_enter(ilu->ilu_kstat_io->ks_lock);
7427 	kstat_runq_enter(kip);
7428 	mutex_exit(ilu->ilu_kstat_io->ks_lock);
7429 }
7430 
7431 void
7432 stmf_lu_xfer_done(scsi_task_t *task, boolean_t read, uint64_t xfer_bytes,
7433     hrtime_t elapsed_time)
7434 {
7435 	stmf_i_scsi_task_t	*itask = task->task_stmf_private;
7436 	stmf_itl_data_t		*itl = itask->itask_itl_datap;
7437 	stmf_i_lu_t	*ilu = (stmf_i_lu_t *)task->task_lu->lu_stmf_private;
7438 	kstat_io_t		*kip;
7439 
7440 	if (itl == NULL || task->task_lu == dlun0)
7441 		return;
7442 
7443 	if (read) {
7444 		atomic_add_64((uint64_t *)&itask->itask_lu_read_time,
7445 		    elapsed_time);
7446 	} else {
7447 		atomic_add_64((uint64_t *)&itask->itask_lu_write_time,
7448 		    elapsed_time);
7449 	}
7450 
7451 	kip = KSTAT_IO_PTR(itl->itl_kstat_lu_xfer);
7452 	mutex_enter(ilu->ilu_kstat_io->ks_lock);
7453 	kstat_runq_exit(kip);
7454 	if (read) {
7455 		kip->reads++;
7456 		kip->nread += xfer_bytes;
7457 	} else {
7458 		kip->writes++;
7459 		kip->nwritten += xfer_bytes;
7460 	}
7461 	mutex_exit(ilu->ilu_kstat_io->ks_lock);
7462 }
7463 
7464 static void
7465 stmf_lport_xfer_start(stmf_i_scsi_task_t *itask, stmf_data_buf_t *dbuf)
7466 {
7467 	stmf_itl_data_t		*itl = itask->itask_itl_datap;
7468 
7469 	if (itl == NULL)
7470 		return;
7471 
7472 	DTRACE_PROBE2(scsi__xfer__start, scsi_task_t *, itask->itask_task,
7473 	    stmf_data_buf_t *, dbuf);
7474 
7475 	dbuf->db_xfer_start_timestamp = gethrtime();
7476 }
7477 
7478 static void
7479 stmf_lport_xfer_done(stmf_i_scsi_task_t *itask, stmf_data_buf_t *dbuf)
7480 {
7481 	stmf_itl_data_t		*itl = itask->itask_itl_datap;
7482 	scsi_task_t		*task;
7483 	stmf_i_local_port_t	*ilp;
7484 	kstat_io_t		*kip;
7485 	hrtime_t		elapsed_time;
7486 	uint64_t		xfer_size;
7487 
7488 	if (itl == NULL)
7489 		return;
7490 
7491 	task = (scsi_task_t *)itask->itask_task;
7492 	ilp = (stmf_i_local_port_t *)task->task_lport->lport_stmf_private;
7493 	xfer_size = (dbuf->db_xfer_status == STMF_SUCCESS) ?
7494 	    dbuf->db_data_size : 0;
7495 
7496 	elapsed_time = gethrtime() - dbuf->db_xfer_start_timestamp;
7497 	if (dbuf->db_flags & DB_DIRECTION_TO_RPORT) {
7498 		atomic_add_64((uint64_t *)&itask->itask_lport_read_time,
7499 		    elapsed_time);
7500 		atomic_add_64((uint64_t *)&itask->itask_read_xfer,
7501 		    xfer_size);
7502 	} else {
7503 		atomic_add_64((uint64_t *)&itask->itask_lport_write_time,
7504 		    elapsed_time);
7505 		atomic_add_64((uint64_t *)&itask->itask_write_xfer,
7506 		    xfer_size);
7507 	}
7508 
7509 	DTRACE_PROBE3(scsi__xfer__end, scsi_task_t *, itask->itask_task,
7510 	    stmf_data_buf_t *, dbuf, hrtime_t, elapsed_time);
7511 
7512 	kip = KSTAT_IO_PTR(itl->itl_kstat_lport_xfer);
7513 	mutex_enter(ilp->ilport_kstat_io->ks_lock);
7514 	if (dbuf->db_flags & DB_DIRECTION_TO_RPORT) {
7515 		kip->reads++;
7516 		kip->nread += xfer_size;
7517 	} else {
7518 		kip->writes++;
7519 		kip->nwritten += xfer_size;
7520 	}
7521 	mutex_exit(ilp->ilport_kstat_io->ks_lock);
7522 
7523 	dbuf->db_xfer_start_timestamp = 0;
7524 }
7525 
7526 void
7527 stmf_svc_init()
7528 {
7529 	if (stmf_state.stmf_svc_flags & STMF_SVC_STARTED)
7530 		return;
7531 	stmf_state.stmf_svc_taskq = ddi_taskq_create(0, "STMF_SVC_TASKQ", 1,
7532 	    TASKQ_DEFAULTPRI, 0);
7533 	(void) ddi_taskq_dispatch(stmf_state.stmf_svc_taskq,
7534 	    stmf_svc, 0, DDI_SLEEP);
7535 }
7536 
7537 stmf_status_t
7538 stmf_svc_fini()
7539 {
7540 	uint32_t i;
7541 
7542 	mutex_enter(&stmf_state.stmf_lock);
7543 	if (stmf_state.stmf_svc_flags & STMF_SVC_STARTED) {
7544 		stmf_state.stmf_svc_flags |= STMF_SVC_TERMINATE;
7545 		cv_signal(&stmf_state.stmf_cv);
7546 	}
7547 	mutex_exit(&stmf_state.stmf_lock);
7548 
7549 	/* Wait for 5 seconds */
7550 	for (i = 0; i < 500; i++) {
7551 		if (stmf_state.stmf_svc_flags & STMF_SVC_STARTED)
7552 			delay(drv_usectohz(10000));
7553 		else
7554 			break;
7555 	}
7556 	if (i == 500)
7557 		return (STMF_BUSY);
7558 
7559 	ddi_taskq_destroy(stmf_state.stmf_svc_taskq);
7560 
7561 	return (STMF_SUCCESS);
7562 }
7563 
7564 /* ARGSUSED */
7565 void
7566 stmf_svc(void *arg)
7567 {
7568 	stmf_svc_req_t *req, **preq;
7569 	clock_t td;
7570 	clock_t	drain_start, drain_next = 0;
7571 	clock_t	timing_start, timing_next = 0;
7572 	clock_t worker_delay = 0;
7573 	int deq;
7574 	stmf_lu_t *lu;
7575 	stmf_i_lu_t *ilu;
7576 	stmf_local_port_t *lport;
7577 	stmf_i_local_port_t *ilport, *next_ilport;
7578 	stmf_i_scsi_session_t *iss;
7579 
7580 	td = drv_usectohz(20000);
7581 
7582 	mutex_enter(&stmf_state.stmf_lock);
7583 	stmf_state.stmf_svc_flags |= STMF_SVC_STARTED | STMF_SVC_ACTIVE;
7584 
7585 stmf_svc_loop:
7586 	if (stmf_state.stmf_svc_flags & STMF_SVC_TERMINATE) {
7587 		stmf_state.stmf_svc_flags &=
7588 		    ~(STMF_SVC_STARTED | STMF_SVC_ACTIVE);
7589 		mutex_exit(&stmf_state.stmf_lock);
7590 		return;
7591 	}
7592 
7593 	if (stmf_state.stmf_svc_active) {
7594 		int waitq_add = 0;
7595 		req = stmf_state.stmf_svc_active;
7596 		stmf_state.stmf_svc_active = req->svc_next;
7597 
7598 		switch (req->svc_cmd) {
7599 		case STMF_CMD_LPORT_ONLINE:
7600 			/* Fallthrough */
7601 		case STMF_CMD_LPORT_OFFLINE:
7602 			/* Fallthrough */
7603 		case STMF_CMD_LU_ONLINE:
7604 			/* Nothing to do */
7605 			waitq_add = 1;
7606 			break;
7607 
7608 		case STMF_CMD_LU_OFFLINE:
7609 			/* Remove all mappings of this LU */
7610 			stmf_session_lu_unmapall((stmf_lu_t *)req->svc_obj);
7611 			/* Kill all the pending I/Os for this LU */
7612 			mutex_exit(&stmf_state.stmf_lock);
7613 			stmf_task_lu_killall((stmf_lu_t *)req->svc_obj, NULL,
7614 			    STMF_ABORTED);
7615 			mutex_enter(&stmf_state.stmf_lock);
7616 			waitq_add = 1;
7617 			break;
7618 		default:
7619 			cmn_err(CE_PANIC, "stmf_svc: unknown cmd %d",
7620 			    req->svc_cmd);
7621 		}
7622 
7623 		if (waitq_add) {
7624 			/* Put it in the wait queue */
7625 			req->svc_next = stmf_state.stmf_svc_waiting;
7626 			stmf_state.stmf_svc_waiting = req;
7627 		}
7628 	}
7629 
7630 	/* The waiting list is not going to be modified by anybody else */
7631 	mutex_exit(&stmf_state.stmf_lock);
7632 
7633 	for (preq = &stmf_state.stmf_svc_waiting; (*preq) != NULL; ) {
7634 		req = *preq;
7635 		deq = 0;
7636 
7637 		switch (req->svc_cmd) {
7638 		case STMF_CMD_LU_ONLINE:
7639 			lu = (stmf_lu_t *)req->svc_obj;
7640 			deq = 1;
7641 			lu->lu_ctl(lu, req->svc_cmd, &req->svc_info);
7642 			break;
7643 
7644 		case STMF_CMD_LU_OFFLINE:
7645 			lu = (stmf_lu_t *)req->svc_obj;
7646 			ilu = (stmf_i_lu_t *)lu->lu_stmf_private;
7647 			if (ilu->ilu_ntasks != ilu->ilu_ntasks_free)
7648 				break;
7649 			deq = 1;
7650 			lu->lu_ctl(lu, req->svc_cmd, &req->svc_info);
7651 			break;
7652 
7653 		case STMF_CMD_LPORT_OFFLINE:
7654 			/* Fallthrough */
7655 		case STMF_CMD_LPORT_ONLINE:
7656 			lport = (stmf_local_port_t *)req->svc_obj;
7657 			deq = 1;
7658 			lport->lport_ctl(lport, req->svc_cmd, &req->svc_info);
7659 			break;
7660 		}
7661 		if (deq) {
7662 			*preq = req->svc_next;
7663 			kmem_free(req, req->svc_req_alloc_size);
7664 		} else {
7665 			preq = &req->svc_next;
7666 		}
7667 	}
7668 
7669 	mutex_enter(&stmf_state.stmf_lock);
7670 	if (stmf_state.stmf_svc_active == NULL) {
7671 		/* Do timeouts */
7672 		if (stmf_state.stmf_nlus &&
7673 		    ((!timing_next) || (ddi_get_lbolt() >= timing_next))) {
7674 			if (!stmf_state.stmf_svc_ilu_timing) {
7675 				/* we are starting a new round */
7676 				stmf_state.stmf_svc_ilu_timing =
7677 				    stmf_state.stmf_ilulist;
7678 				timing_start = ddi_get_lbolt();
7679 			}
7680 			stmf_check_ilu_timing();
7681 			if (!stmf_state.stmf_svc_ilu_timing) {
7682 				/* we finished a complete round */
7683 				timing_next =
7684 				    timing_start + drv_usectohz(5*1000*1000);
7685 			} else {
7686 				/* we still have some ilu items to check */
7687 				timing_next =
7688 				    ddi_get_lbolt() + drv_usectohz(1*1000*1000);
7689 			}
7690 			if (stmf_state.stmf_svc_active)
7691 				goto stmf_svc_loop;
7692 		}
7693 		/* Check if there are free tasks to clear */
7694 		if (stmf_state.stmf_nlus &&
7695 		    ((!drain_next) || (ddi_get_lbolt() >= drain_next))) {
7696 			if (!stmf_state.stmf_svc_ilu_draining) {
7697 				/* we are starting a new round */
7698 				stmf_state.stmf_svc_ilu_draining =
7699 				    stmf_state.stmf_ilulist;
7700 				drain_start = ddi_get_lbolt();
7701 			}
7702 			stmf_check_freetask();
7703 			if (!stmf_state.stmf_svc_ilu_draining) {
7704 				/* we finished a complete round */
7705 				drain_next =
7706 				    drain_start + drv_usectohz(10*1000*1000);
7707 			} else {
7708 				/* we still have some ilu items to check */
7709 				drain_next =
7710 				    ddi_get_lbolt() + drv_usectohz(1*1000*1000);
7711 			}
7712 			if (stmf_state.stmf_svc_active)
7713 				goto stmf_svc_loop;
7714 		}
7715 
7716 		/* Check if we need to run worker_mgmt */
7717 		if (ddi_get_lbolt() > worker_delay) {
7718 			stmf_worker_mgmt();
7719 			worker_delay = ddi_get_lbolt() +
7720 			    stmf_worker_mgmt_delay;
7721 		}
7722 
7723 		/* Check if any active session got its 1st LUN */
7724 		if (stmf_state.stmf_process_initial_luns) {
7725 			int stmf_level = 0;
7726 			int port_level;
7727 			for (ilport = stmf_state.stmf_ilportlist; ilport;
7728 			    ilport = next_ilport) {
7729 				int ilport_lock_held;
7730 				next_ilport = ilport->ilport_next;
7731 				if ((ilport->ilport_flags &
7732 				    ILPORT_SS_GOT_INITIAL_LUNS) == 0) {
7733 					continue;
7734 				}
7735 				port_level = 0;
7736 				rw_enter(&ilport->ilport_lock, RW_READER);
7737 				ilport_lock_held = 1;
7738 				for (iss = ilport->ilport_ss_list; iss;
7739 				    iss = iss->iss_next) {
7740 					if ((iss->iss_flags &
7741 					    ISS_GOT_INITIAL_LUNS) == 0) {
7742 						continue;
7743 					}
7744 					port_level++;
7745 					stmf_level++;
7746 					atomic_and_32(&iss->iss_flags,
7747 					    ~ISS_GOT_INITIAL_LUNS);
7748 					atomic_or_32(&iss->iss_flags,
7749 					    ISS_EVENT_ACTIVE);
7750 					rw_exit(&ilport->ilport_lock);
7751 					ilport_lock_held = 0;
7752 					mutex_exit(&stmf_state.stmf_lock);
7753 					stmf_generate_lport_event(ilport,
7754 					    LPORT_EVENT_INITIAL_LUN_MAPPED,
7755 					    iss->iss_ss, 0);
7756 					atomic_and_32(&iss->iss_flags,
7757 					    ~ISS_EVENT_ACTIVE);
7758 					mutex_enter(&stmf_state.stmf_lock);
7759 					/*
7760 					 * scan all the ilports again as the
7761 					 * ilport list might have changed.
7762 					 */
7763 					next_ilport =
7764 					    stmf_state.stmf_ilportlist;
7765 					break;
7766 				}
7767 				if (port_level == 0) {
7768 					atomic_and_32(&ilport->ilport_flags,
7769 					    ~ILPORT_SS_GOT_INITIAL_LUNS);
7770 				}
7771 				/* drop the lock if we are holding it. */
7772 				if (ilport_lock_held == 1)
7773 					rw_exit(&ilport->ilport_lock);
7774 
7775 				/* Max 4 session at a time */
7776 				if (stmf_level >= 4) {
7777 					break;
7778 				}
7779 			}
7780 			if (stmf_level == 0) {
7781 				stmf_state.stmf_process_initial_luns = 0;
7782 			}
7783 		}
7784 
7785 		stmf_state.stmf_svc_flags &= ~STMF_SVC_ACTIVE;
7786 		(void) cv_reltimedwait(&stmf_state.stmf_cv,
7787 		    &stmf_state.stmf_lock, td, TR_CLOCK_TICK);
7788 		stmf_state.stmf_svc_flags |= STMF_SVC_ACTIVE;
7789 	}
7790 	goto stmf_svc_loop;
7791 }
7792 
7793 void
7794 stmf_svc_queue(int cmd, void *obj, stmf_state_change_info_t *info)
7795 {
7796 	stmf_svc_req_t *req;
7797 	int s;
7798 
7799 	ASSERT(!mutex_owned(&stmf_state.stmf_lock));
7800 	s = sizeof (stmf_svc_req_t);
7801 	if (info->st_additional_info) {
7802 		s += strlen(info->st_additional_info) + 1;
7803 	}
7804 	req = kmem_zalloc(s, KM_SLEEP);
7805 
7806 	req->svc_cmd = cmd;
7807 	req->svc_obj = obj;
7808 	req->svc_info.st_rflags = info->st_rflags;
7809 	if (info->st_additional_info) {
7810 		req->svc_info.st_additional_info = (char *)(GET_BYTE_OFFSET(req,
7811 		    sizeof (stmf_svc_req_t)));
7812 		(void) strcpy(req->svc_info.st_additional_info,
7813 		    info->st_additional_info);
7814 	}
7815 	req->svc_req_alloc_size = s;
7816 
7817 	mutex_enter(&stmf_state.stmf_lock);
7818 	req->svc_next = stmf_state.stmf_svc_active;
7819 	stmf_state.stmf_svc_active = req;
7820 	if ((stmf_state.stmf_svc_flags & STMF_SVC_ACTIVE) == 0) {
7821 		cv_signal(&stmf_state.stmf_cv);
7822 	}
7823 	mutex_exit(&stmf_state.stmf_lock);
7824 }
7825 
7826 void
7827 stmf_trace(caddr_t ident, const char *fmt, ...)
7828 {
7829 	va_list args;
7830 	char tbuf[160];
7831 	int len;
7832 
7833 	if (!stmf_trace_on)
7834 		return;
7835 	len = snprintf(tbuf, 158, "%s:%07lu: ", ident ? ident : "",
7836 	    ddi_get_lbolt());
7837 	va_start(args, fmt);
7838 	len += vsnprintf(tbuf + len, 158 - len, fmt, args);
7839 	va_end(args);
7840 
7841 	if (len > 158) {
7842 		len = 158;
7843 	}
7844 	tbuf[len++] = '\n';
7845 	tbuf[len] = 0;
7846 
7847 	mutex_enter(&trace_buf_lock);
7848 	bcopy(tbuf, &stmf_trace_buf[trace_buf_curndx], len+1);
7849 	trace_buf_curndx += len;
7850 	if (trace_buf_curndx > (trace_buf_size - 320))
7851 		trace_buf_curndx = 0;
7852 	mutex_exit(&trace_buf_lock);
7853 }
7854 
7855 void
7856 stmf_trace_clear()
7857 {
7858 	if (!stmf_trace_on)
7859 		return;
7860 	mutex_enter(&trace_buf_lock);
7861 	trace_buf_curndx = 0;
7862 	if (trace_buf_size > 0)
7863 		stmf_trace_buf[0] = 0;
7864 	mutex_exit(&trace_buf_lock);
7865 }
7866 
7867 static void
7868 stmf_abort_task_offline(scsi_task_t *task, int offline_lu, char *info)
7869 {
7870 	stmf_state_change_info_t	change_info;
7871 	void				*ctl_private;
7872 	uint32_t			ctl_cmd;
7873 	int				msg = 0;
7874 
7875 	stmf_trace("FROM STMF", "abort_task_offline called for %s: %s",
7876 	    offline_lu ? "LU" : "LPORT", info ? info : "no additional info");
7877 	change_info.st_additional_info = info;
7878 	if (offline_lu) {
7879 		change_info.st_rflags = STMF_RFLAG_RESET |
7880 		    STMF_RFLAG_LU_ABORT;
7881 		ctl_private = task->task_lu;
7882 		if (((stmf_i_lu_t *)
7883 		    task->task_lu->lu_stmf_private)->ilu_state ==
7884 		    STMF_STATE_ONLINE) {
7885 			msg = 1;
7886 		}
7887 		ctl_cmd = STMF_CMD_LU_OFFLINE;
7888 	} else {
7889 		change_info.st_rflags = STMF_RFLAG_RESET |
7890 		    STMF_RFLAG_LPORT_ABORT;
7891 		ctl_private = task->task_lport;
7892 		if (((stmf_i_local_port_t *)
7893 		    task->task_lport->lport_stmf_private)->ilport_state ==
7894 		    STMF_STATE_ONLINE) {
7895 			msg = 1;
7896 		}
7897 		ctl_cmd = STMF_CMD_LPORT_OFFLINE;
7898 	}
7899 
7900 	if (msg) {
7901 		stmf_trace(0, "Calling stmf_ctl to offline %s : %s",
7902 		    offline_lu ? "LU" : "LPORT", info ? info :
7903 		    "<no additional info>");
7904 	}
7905 	(void) stmf_ctl(ctl_cmd, ctl_private, &change_info);
7906 }
7907