xref: /illumos-gate/usr/src/uts/common/io/comstar/port/iscsit/iscsit.c (revision e44e85a7f9935f0428e188393e3da61b17e83884)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/cpuvar.h>
27 #include <sys/types.h>
28 #include <sys/conf.h>
29 #include <sys/stat.h>
30 #include <sys/file.h>
31 #include <sys/ddi.h>
32 #include <sys/sunddi.h>
33 #include <sys/modctl.h>
34 #include <sys/sysmacros.h>
35 #include <sys/socket.h>
36 #include <sys/strsubr.h>
37 #include <sys/nvpair.h>
38 
39 #include <sys/stmf.h>
40 #include <sys/stmf_ioctl.h>
41 #include <sys/portif.h>
42 #include <sys/idm/idm.h>
43 #include <sys/idm/idm_conn_sm.h>
44 #include <iscsit_isns.h>
45 #include <iscsit.h>
46 
47 #define	ISCSIT_VERSION		BUILD_DATE "-1.18dev"
48 #define	ISCSIT_NAME_VERSION	"COMSTAR ISCSIT v" ISCSIT_VERSION
49 
50 /*
51  * DDI entry points.
52  */
53 static int iscsit_drv_attach(dev_info_t *, ddi_attach_cmd_t);
54 static int iscsit_drv_detach(dev_info_t *, ddi_detach_cmd_t);
55 static int iscsit_drv_getinfo(dev_info_t *, ddi_info_cmd_t, void *, void **);
56 static int iscsit_drv_open(dev_t *, int, int, cred_t *);
57 static int iscsit_drv_close(dev_t, int, int, cred_t *);
58 static boolean_t iscsit_drv_busy(void);
59 static int iscsit_drv_ioctl(dev_t, int, intptr_t, int, cred_t *, int *);
60 
61 extern struct mod_ops mod_miscops;
62 
63 
64 static struct cb_ops iscsit_cb_ops = {
65 	iscsit_drv_open,	/* cb_open */
66 	iscsit_drv_close,	/* cb_close */
67 	nodev,			/* cb_strategy */
68 	nodev,			/* cb_print */
69 	nodev,			/* cb_dump */
70 	nodev,			/* cb_read */
71 	nodev,			/* cb_write */
72 	iscsit_drv_ioctl,	/* cb_ioctl */
73 	nodev,			/* cb_devmap */
74 	nodev,			/* cb_mmap */
75 	nodev,			/* cb_segmap */
76 	nochpoll,		/* cb_chpoll */
77 	ddi_prop_op,		/* cb_prop_op */
78 	NULL,			/* cb_streamtab */
79 	D_MP,			/* cb_flag */
80 	CB_REV,			/* cb_rev */
81 	nodev,			/* cb_aread */
82 	nodev,			/* cb_awrite */
83 };
84 
85 static struct dev_ops iscsit_dev_ops = {
86 	DEVO_REV,		/* devo_rev */
87 	0,			/* devo_refcnt */
88 	iscsit_drv_getinfo,	/* devo_getinfo */
89 	nulldev,		/* devo_identify */
90 	nulldev,		/* devo_probe */
91 	iscsit_drv_attach,	/* devo_attach */
92 	iscsit_drv_detach,	/* devo_detach */
93 	nodev,			/* devo_reset */
94 	&iscsit_cb_ops,		/* devo_cb_ops */
95 	NULL,			/* devo_bus_ops */
96 	NULL,			/* devo_power */
97 	ddi_quiesce_not_needed,	/* quiesce */
98 };
99 
100 static struct modldrv modldrv = {
101 	&mod_driverops,
102 	"iSCSI Target",
103 	&iscsit_dev_ops,
104 };
105 
106 static struct modlinkage modlinkage = {
107 	MODREV_1,
108 	&modldrv,
109 	NULL,
110 };
111 
112 
113 iscsit_global_t iscsit_global;
114 
115 kmem_cache_t	*iscsit_status_pdu_cache;
116 
117 boolean_t	iscsit_sm_logging = B_FALSE;
118 
119 static idm_status_t iscsit_init(dev_info_t *dip);
120 static idm_status_t iscsit_enable_svc(iscsit_hostinfo_t *hostinfo);
121 static void iscsit_disable_svc(void);
122 
123 static void
124 iscsit_op_scsi_task_mgmt(iscsit_conn_t *ict, idm_pdu_t *rx_pdu);
125 
126 static void
127 iscsit_pdu_op_noop(iscsit_conn_t *ict, idm_pdu_t *rx_pdu);
128 
129 static void
130 iscsit_pdu_op_login_cmd(iscsit_conn_t *ict, idm_pdu_t *rx_pdu);
131 
132 void
133 iscsit_pdu_op_text_cmd(iscsit_conn_t *ict, idm_pdu_t *rx_pdu);
134 
135 static void
136 iscsit_pdu_op_logout_cmd(iscsit_conn_t *ict, idm_pdu_t *rx_pdu);
137 
138 int iscsit_cmd_window();
139 
140 void
141 iscsit_set_cmdsn(iscsit_conn_t *ict, idm_pdu_t *rx_pdu);
142 
143 static void
144 iscsit_calc_rspsn(iscsit_conn_t *ict, idm_pdu_t *resp);
145 
146 static void
147 iscsit_deferred_dispatch(idm_pdu_t *rx_pdu);
148 
149 static void
150 iscsit_deferred(void *rx_pdu_void);
151 
152 static idm_status_t
153 iscsit_conn_accept(idm_conn_t *ic);
154 
155 static idm_status_t
156 iscsit_ffp_enabled(idm_conn_t *ic);
157 
158 static idm_status_t
159 iscsit_ffp_disabled(idm_conn_t *ic, idm_ffp_disable_t disable_class);
160 
161 static idm_status_t
162 iscsit_conn_lost(idm_conn_t *ic);
163 
164 static idm_status_t
165 iscsit_conn_destroy(idm_conn_t *ic);
166 
167 static stmf_data_buf_t *
168 iscsit_dbuf_alloc(scsi_task_t *task, uint32_t size, uint32_t *pminsize,
169     uint32_t flags);
170 
171 static void
172 iscsit_dbuf_free(stmf_dbuf_store_t *ds, stmf_data_buf_t *dbuf);
173 
174 static void
175 iscsit_buf_xfer_cb(idm_buf_t *idb, idm_status_t status);
176 
177 static void
178 iscsit_send_good_status_done(idm_pdu_t *pdu, idm_status_t status);
179 
180 static void
181 iscsit_send_status_done(idm_pdu_t *pdu, idm_status_t status);
182 
183 static stmf_status_t
184 iscsit_idm_to_stmf(idm_status_t idmrc);
185 
186 static iscsit_task_t *
187 iscsit_task_alloc(iscsit_conn_t *ict);
188 
189 static void
190 iscsit_task_free(iscsit_task_t *itask);
191 
192 static iscsit_task_t *
193 iscsit_tm_task_alloc(iscsit_conn_t *ict);
194 
195 static void
196 iscsit_tm_task_free(iscsit_task_t *itask);
197 
198 static idm_status_t
199 iscsit_task_start(iscsit_task_t *itask);
200 
201 static void
202 iscsit_task_done(iscsit_task_t *itask);
203 
204 static int
205 iscsit_status_pdu_constructor(void *pdu_void, void *arg, int flags);
206 
207 static void
208 iscsit_pp_cb(struct stmf_port_provider *pp, int cmd, void *arg, uint32_t flags);
209 
210 static it_cfg_status_t
211 iscsit_config_merge(it_config_t *cfg);
212 
213 static idm_status_t
214 iscsit_login_fail(idm_conn_t *ic);
215 
216 static boolean_t iscsit_cmdsn_in_window(iscsit_conn_t *ict, uint32_t cmdsn);
217 static void iscsit_send_direct_scsi_resp(iscsit_conn_t *ict, idm_pdu_t *rx_pdu,
218     uint8_t response, uint8_t cmd_status);
219 static void iscsit_send_task_mgmt_resp(idm_pdu_t *tm_resp_pdu,
220     uint8_t tm_status);
221 
222 int
223 _init(void)
224 {
225 	int rc;
226 
227 	rw_init(&iscsit_global.global_rwlock, NULL, RW_DRIVER, NULL);
228 	iscsit_global.global_svc_state = ISE_DETACHED;
229 
230 	if ((rc = mod_install(&modlinkage)) != 0) {
231 		rw_destroy(&iscsit_global.global_rwlock);
232 		return (rc);
233 	}
234 
235 	return (rc);
236 }
237 
238 int
239 _info(struct modinfo *modinfop)
240 {
241 	return (mod_info(&modlinkage, modinfop));
242 }
243 
244 int
245 _fini(void)
246 {
247 	int rc;
248 
249 	rc = mod_remove(&modlinkage);
250 
251 	if (rc == 0) {
252 		rw_destroy(&iscsit_global.global_rwlock);
253 	}
254 
255 	return (rc);
256 }
257 
258 /*
259  * DDI entry points.
260  */
261 
262 /* ARGSUSED */
263 static int
264 iscsit_drv_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg,
265     void **result)
266 {
267 	ulong_t instance = getminor((dev_t)arg);
268 
269 	switch (cmd) {
270 	case DDI_INFO_DEVT2DEVINFO:
271 		*result = iscsit_global.global_dip;
272 		return (DDI_SUCCESS);
273 
274 	case DDI_INFO_DEVT2INSTANCE:
275 		*result = (void *)instance;
276 		return (DDI_SUCCESS);
277 
278 	default:
279 		break;
280 	}
281 
282 	return (DDI_FAILURE);
283 }
284 
285 static int
286 iscsit_drv_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
287 {
288 	if (cmd != DDI_ATTACH) {
289 		return (DDI_FAILURE);
290 	}
291 
292 	if (ddi_get_instance(dip) != 0) {
293 		/* we only allow instance 0 to attach */
294 		return (DDI_FAILURE);
295 	}
296 
297 	/* create the minor node */
298 	if (ddi_create_minor_node(dip, ISCSIT_MODNAME, S_IFCHR, 0,
299 	    DDI_PSEUDO, 0) != DDI_SUCCESS) {
300 		cmn_err(CE_WARN, "iscsit_drv_attach: "
301 		    "failed creating minor node");
302 		return (DDI_FAILURE);
303 	}
304 
305 	if (iscsit_init(dip) != IDM_STATUS_SUCCESS) {
306 		cmn_err(CE_WARN, "iscsit_drv_attach: "
307 		    "failed to initialize");
308 		ddi_remove_minor_node(dip, NULL);
309 		return (DDI_FAILURE);
310 	}
311 
312 	iscsit_global.global_svc_state = ISE_DISABLED;
313 	iscsit_global.global_dip = dip;
314 
315 	return (DDI_SUCCESS);
316 }
317 
318 /*ARGSUSED*/
319 static int
320 iscsit_drv_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
321 {
322 	if (cmd != DDI_DETACH)
323 		return (DDI_FAILURE);
324 
325 	ISCSIT_GLOBAL_LOCK(RW_WRITER);
326 	if (iscsit_drv_busy()) {
327 		ISCSIT_GLOBAL_UNLOCK();
328 		return (EBUSY);
329 	}
330 
331 	iscsit_global.global_dip = NULL;
332 	ddi_remove_minor_node(dip, NULL);
333 
334 	ldi_ident_release(iscsit_global.global_li);
335 	iscsit_global.global_svc_state = ISE_DETACHED;
336 
337 	ISCSIT_GLOBAL_UNLOCK();
338 
339 	return (DDI_SUCCESS);
340 }
341 
342 /*ARGSUSED*/
343 static int
344 iscsit_drv_open(dev_t *devp, int flag, int otyp, cred_t *credp)
345 {
346 	return (0);
347 }
348 
349 /* ARGSUSED */
350 static int
351 iscsit_drv_close(dev_t dev, int flag, int otyp, cred_t *credp)
352 {
353 	return (0);
354 }
355 
356 static boolean_t
357 iscsit_drv_busy(void)
358 {
359 	switch (iscsit_global.global_svc_state) {
360 	case ISE_DISABLED:
361 	case ISE_DETACHED:
362 		return (B_FALSE);
363 	default:
364 		return (B_TRUE);
365 	}
366 	/* NOTREACHED */
367 }
368 
369 /* ARGSUSED */
370 static int
371 iscsit_drv_ioctl(dev_t drv, int cmd, intptr_t argp, int flag, cred_t *cred,
372     int *retval)
373 {
374 	iscsit_ioc_set_config_t		setcfg;
375 	iscsit_ioc_set_config32_t	setcfg32;
376 	/* iscsit_ioc_get_config_t	getcfg; */
377 	char				*cfg_pnvlist;
378 	nvlist_t			*cfg_nvlist;
379 	it_config_t			*cfg;
380 	idm_status_t			idmrc;
381 	int				rc = 0;
382 
383 	if (drv_priv(cred) != 0) {
384 		return (EPERM);
385 	}
386 
387 	ISCSIT_GLOBAL_LOCK(RW_WRITER);
388 
389 	/*
390 	 * Validate ioctl requests against global service state
391 	 */
392 	switch (iscsit_global.global_svc_state) {
393 	case ISE_ENABLED:
394 		if (cmd == ISCSIT_IOC_DISABLE_SVC) {
395 			iscsit_global.global_svc_state = ISE_DISABLING;
396 		} else if (cmd == ISCSIT_IOC_ENABLE_SVC) {
397 			/* Already enabled */
398 			ISCSIT_GLOBAL_UNLOCK();
399 			return (0);
400 		} else {
401 			iscsit_global.global_svc_state = ISE_BUSY;
402 		}
403 		break;
404 	case ISE_DISABLED:
405 		if (cmd == ISCSIT_IOC_ENABLE_SVC) {
406 			iscsit_global.global_svc_state = ISE_ENABLING;
407 		} else if (cmd == ISCSIT_IOC_DISABLE_SVC) {
408 			/* Already disabled */
409 			ISCSIT_GLOBAL_UNLOCK();
410 			return (0);
411 		} else {
412 			rc = EFAULT;
413 		}
414 		break;
415 	case ISE_ENABLING:
416 	case ISE_DISABLING:
417 		rc = EAGAIN;
418 		break;
419 	case ISE_DETACHED:
420 	default:
421 		rc = EFAULT;
422 		break;
423 	}
424 
425 	ISCSIT_GLOBAL_UNLOCK();
426 	if (rc != 0)
427 		return (rc);
428 
429 	/* Handle ioctl request (enable/disable have already been handled) */
430 	switch (cmd) {
431 	case ISCSIT_IOC_SET_CONFIG:
432 		switch (ddi_model_convert_from(flag & FMODELS)) {
433 		case DDI_MODEL_ILP32:
434 			if (ddi_copyin((void *)argp, &setcfg32,
435 			    sizeof (iscsit_ioc_set_config32_t), flag) != 0)
436 				return (EFAULT);
437 
438 			setcfg.set_cfg_pnvlist =
439 			    (char *)((uintptr_t)setcfg32.set_cfg_pnvlist);
440 			setcfg.set_cfg_vers = setcfg32.set_cfg_vers;
441 			setcfg.set_cfg_pnvlist_len =
442 			    setcfg32.set_cfg_pnvlist_len;
443 			break;
444 		case DDI_MODEL_NONE:
445 			if (ddi_copyin((void *)argp, &setcfg,
446 			    sizeof (iscsit_ioc_set_config_t), flag) != 0)
447 				return (EFAULT);
448 			break;
449 		}
450 
451 		/* Check API version */
452 		if (setcfg.set_cfg_vers != ISCSIT_API_VERS0) {
453 			return (EINVAL);
454 		}
455 
456 		/* Config is in packed nvlist format so unpack it */
457 		cfg_pnvlist = kmem_alloc(setcfg.set_cfg_pnvlist_len,
458 		    KM_SLEEP);
459 		ASSERT(cfg_pnvlist != NULL);
460 
461 		if (ddi_copyin(setcfg.set_cfg_pnvlist, cfg_pnvlist,
462 		    setcfg.set_cfg_pnvlist_len, flag) != 0) {
463 			kmem_free(cfg_pnvlist, setcfg.set_cfg_pnvlist_len);
464 			return (EFAULT);
465 		}
466 
467 		if (nvlist_unpack(cfg_pnvlist, setcfg.set_cfg_pnvlist_len,
468 		    &cfg_nvlist, KM_SLEEP) != 0) {
469 			kmem_free(cfg_pnvlist, setcfg.set_cfg_pnvlist_len);
470 			return (EINVAL);
471 		}
472 
473 		/* Translate nvlist */
474 		if (it_nv_to_config(cfg_nvlist, &cfg) != 0) {
475 			cmn_err(CE_WARN, "Configuration is invalid");
476 			kmem_free(cfg_pnvlist, setcfg.set_cfg_pnvlist_len);
477 			nvlist_free(cfg_nvlist);
478 			return (EINVAL);
479 		}
480 
481 		/* Update config */
482 		if (iscsit_config_merge(cfg) != 0) {
483 			kmem_free(cfg_pnvlist, setcfg.set_cfg_pnvlist_len);
484 			nvlist_free(cfg_nvlist);
485 			return (EIO);
486 		}
487 
488 		it_config_free_cmn(cfg);
489 		kmem_free(cfg_pnvlist, setcfg.set_cfg_pnvlist_len);
490 		nvlist_free(cfg_nvlist);
491 
492 		/*
493 		 * Now that the reconfig is complete set our state back to
494 		 * enabled.
495 		 */
496 		ISCSIT_GLOBAL_LOCK(RW_WRITER);
497 		iscsit_global.global_svc_state = ISE_ENABLED;
498 		ISCSIT_GLOBAL_UNLOCK();
499 		break;
500 	case ISCSIT_IOC_ENABLE_SVC: {
501 		iscsit_hostinfo_t hostinfo;
502 
503 		if (ddi_copyin((void *)argp, &hostinfo.length,
504 		    sizeof (hostinfo.length), flag) != 0) {
505 			iscsit_global.global_svc_state = ISE_DISABLED;
506 			return (EFAULT);
507 		}
508 
509 		if (hostinfo.length > sizeof (hostinfo.fqhn))
510 			hostinfo.length = sizeof (hostinfo.fqhn);
511 
512 		if (ddi_copyin((void *)((caddr_t)argp +
513 		    sizeof (hostinfo.length)), &hostinfo.fqhn,
514 		    hostinfo.length, flag) != 0) {
515 			iscsit_global.global_svc_state = ISE_DISABLED;
516 			return (EFAULT);
517 		}
518 
519 		idmrc = iscsit_enable_svc(&hostinfo);
520 		ISCSIT_GLOBAL_LOCK(RW_WRITER);
521 		if (idmrc == IDM_STATUS_SUCCESS) {
522 			iscsit_global.global_svc_state = ISE_ENABLED;
523 		} else {
524 			rc = EIO;
525 			iscsit_global.global_svc_state = ISE_DISABLED;
526 		}
527 		ISCSIT_GLOBAL_UNLOCK();
528 		break;
529 	}
530 	case ISCSIT_IOC_DISABLE_SVC:
531 		iscsit_disable_svc();
532 		ISCSIT_GLOBAL_LOCK(RW_WRITER);
533 		iscsit_global.global_svc_state = ISE_DISABLED;
534 		ISCSIT_GLOBAL_UNLOCK();
535 		break;
536 	default:
537 		rc = EINVAL;
538 	}
539 
540 	/* Don't forget to clear ISE_BUSY state */
541 	ASSERT(iscsit_global.global_svc_state != ISE_BUSY);
542 
543 	return (rc);
544 }
545 
546 static idm_status_t
547 iscsit_init(dev_info_t *dip)
548 {
549 	int			rc;
550 
551 	rc = ldi_ident_from_dip(dip, &iscsit_global.global_li);
552 	ASSERT(rc == 0);  /* Failure indicates invalid argument */
553 
554 	iscsit_global.global_svc_state = ISE_DISABLED;
555 
556 	return (IDM_STATUS_SUCCESS);
557 }
558 
559 /*
560  * iscsit_enable_svc
561  *
562  * registers all the configured targets and target portals with STMF
563  */
564 static idm_status_t
565 iscsit_enable_svc(iscsit_hostinfo_t *hostinfo)
566 {
567 	stmf_port_provider_t	*pp;
568 	stmf_dbuf_store_t	*dbuf_store;
569 	boolean_t		did_iscsit_isns_init;
570 	idm_status_t		retval = IDM_STATUS_SUCCESS;
571 
572 	ASSERT(iscsit_global.global_svc_state == ISE_ENABLING);
573 
574 	/*
575 	 * Make sure that can tell if we have partially allocated
576 	 * in case we need to exit and tear down anything allocated.
577 	 */
578 	iscsit_global.global_tsih_pool = NULL;
579 	iscsit_global.global_dbuf_store = NULL;
580 	iscsit_status_pdu_cache = NULL;
581 	pp = NULL;
582 	iscsit_global.global_pp = NULL;
583 	iscsit_global.global_default_tpg = NULL;
584 	did_iscsit_isns_init = B_FALSE;
585 	iscsit_global.global_dispatch_taskq = NULL;
586 
587 	/* Setup remaining fields in iscsit_global_t */
588 	idm_refcnt_init(&iscsit_global.global_refcnt,
589 	    &iscsit_global);
590 
591 	avl_create(&iscsit_global.global_discovery_sessions,
592 	    iscsit_sess_avl_compare, sizeof (iscsit_sess_t),
593 	    offsetof(iscsit_sess_t, ist_tgt_ln));
594 
595 	avl_create(&iscsit_global.global_target_list,
596 	    iscsit_tgt_avl_compare, sizeof (iscsit_tgt_t),
597 	    offsetof(iscsit_tgt_t, target_global_ln));
598 
599 	list_create(&iscsit_global.global_deleted_target_list,
600 	    sizeof (iscsit_tgt_t),
601 	    offsetof(iscsit_tgt_t, target_global_deleted_ln));
602 
603 	avl_create(&iscsit_global.global_tpg_list,
604 	    iscsit_tpg_avl_compare, sizeof (iscsit_tpg_t),
605 	    offsetof(iscsit_tpg_t, tpg_global_ln));
606 
607 	avl_create(&iscsit_global.global_ini_list,
608 	    iscsit_ini_avl_compare, sizeof (iscsit_ini_t),
609 	    offsetof(iscsit_ini_t, ini_global_ln));
610 
611 	iscsit_global.global_tsih_pool = vmem_create("iscsit_tsih_pool",
612 	    (void *)1, ISCSI_MAX_TSIH, 1, NULL, NULL, NULL, 0,
613 	    VM_SLEEP | VMC_IDENTIFIER);
614 
615 	/*
616 	 * Setup STMF dbuf store.  Our buffers are bound to a specific
617 	 * connection so we really can't let STMF cache buffers for us.
618 	 * Consequently we'll just allocate one global buffer store.
619 	 */
620 	dbuf_store = stmf_alloc(STMF_STRUCT_DBUF_STORE, 0, 0);
621 	if (dbuf_store == NULL) {
622 		retval = IDM_STATUS_FAIL;
623 		goto tear_down_and_return;
624 	}
625 	dbuf_store->ds_alloc_data_buf = iscsit_dbuf_alloc;
626 	dbuf_store->ds_free_data_buf = iscsit_dbuf_free;
627 	dbuf_store->ds_port_private = NULL;
628 	iscsit_global.global_dbuf_store = dbuf_store;
629 
630 	/* Status PDU cache */
631 	iscsit_status_pdu_cache = kmem_cache_create("iscsit_status_pdu_cache",
632 	    sizeof (idm_pdu_t) + sizeof (iscsi_scsi_rsp_hdr_t), 8,
633 	    &iscsit_status_pdu_constructor,
634 	    NULL, NULL, NULL, NULL, KM_SLEEP);
635 
636 	/* Default TPG and portal */
637 	iscsit_global.global_default_tpg = iscsit_tpg_createdefault();
638 	if (iscsit_global.global_default_tpg == NULL) {
639 		retval = IDM_STATUS_FAIL;
640 		goto tear_down_and_return;
641 	}
642 
643 	/* initialize isns client */
644 	(void) iscsit_isns_init(hostinfo);
645 	did_iscsit_isns_init = B_TRUE;
646 
647 	/* Register port provider */
648 	pp = stmf_alloc(STMF_STRUCT_PORT_PROVIDER, 0, 0);
649 	if (pp == NULL) {
650 		retval = IDM_STATUS_FAIL;
651 		goto tear_down_and_return;
652 	}
653 
654 	pp->pp_portif_rev = PORTIF_REV_1;
655 	pp->pp_instance = 0;
656 	pp->pp_name = ISCSIT_MODNAME;
657 	pp->pp_cb = iscsit_pp_cb;
658 
659 	iscsit_global.global_pp = pp;
660 
661 
662 	if (stmf_register_port_provider(pp) != STMF_SUCCESS) {
663 		retval = IDM_STATUS_FAIL;
664 		goto tear_down_and_return;
665 	}
666 
667 	iscsit_global.global_dispatch_taskq = taskq_create("iscsit_dispatch",
668 	    1, minclsyspri, 16, 16, TASKQ_PREPOPULATE);
669 
670 	return (IDM_STATUS_SUCCESS);
671 
672 tear_down_and_return:
673 
674 	if (iscsit_global.global_dispatch_taskq) {
675 		taskq_destroy(iscsit_global.global_dispatch_taskq);
676 		iscsit_global.global_dispatch_taskq = NULL;
677 	}
678 
679 	if (did_iscsit_isns_init)
680 		iscsit_isns_fini();
681 
682 	if (iscsit_global.global_default_tpg) {
683 		iscsit_tpg_destroydefault(iscsit_global.global_default_tpg);
684 		iscsit_global.global_default_tpg = NULL;
685 	}
686 
687 	if (iscsit_global.global_pp)
688 		iscsit_global.global_pp = NULL;
689 
690 	if (pp)
691 		stmf_free(pp);
692 
693 	if (iscsit_status_pdu_cache) {
694 		kmem_cache_destroy(iscsit_status_pdu_cache);
695 		iscsit_status_pdu_cache = NULL;
696 	}
697 
698 	if (iscsit_global.global_dbuf_store) {
699 		stmf_free(iscsit_global.global_dbuf_store);
700 		iscsit_global.global_dbuf_store = NULL;
701 	}
702 
703 	if (iscsit_global.global_tsih_pool) {
704 		vmem_destroy(iscsit_global.global_tsih_pool);
705 		iscsit_global.global_tsih_pool = NULL;
706 	}
707 
708 	avl_destroy(&iscsit_global.global_ini_list);
709 	avl_destroy(&iscsit_global.global_tpg_list);
710 	list_destroy(&iscsit_global.global_deleted_target_list);
711 	avl_destroy(&iscsit_global.global_target_list);
712 	avl_destroy(&iscsit_global.global_discovery_sessions);
713 
714 	idm_refcnt_destroy(&iscsit_global.global_refcnt);
715 
716 	return (retval);
717 }
718 
719 /*
720  * iscsit_disable_svc
721  *
722  * clean up all existing connections and deregister targets from STMF
723  */
724 static void
725 iscsit_disable_svc(void)
726 {
727 	iscsit_sess_t	*sess;
728 
729 	ASSERT(iscsit_global.global_svc_state == ISE_DISABLING);
730 
731 	/* tear down discovery sessions */
732 	for (sess = avl_first(&iscsit_global.global_discovery_sessions);
733 	    sess != NULL;
734 	    sess = AVL_NEXT(&iscsit_global.global_discovery_sessions, sess))
735 		iscsit_sess_close(sess);
736 
737 	/*
738 	 * Passing NULL to iscsit_config_merge tells it to go to an empty
739 	 * config.
740 	 */
741 	(void) iscsit_config_merge(NULL);
742 
743 	/*
744 	 * Wait until there are no more global references
745 	 */
746 	idm_refcnt_wait_ref(&iscsit_global.global_refcnt);
747 	idm_refcnt_destroy(&iscsit_global.global_refcnt);
748 
749 	/*
750 	 * Default TPG must be destroyed after global_refcnt is 0.
751 	 */
752 	iscsit_tpg_destroydefault(iscsit_global.global_default_tpg);
753 
754 	avl_destroy(&iscsit_global.global_discovery_sessions);
755 	list_destroy(&iscsit_global.global_deleted_target_list);
756 	avl_destroy(&iscsit_global.global_target_list);
757 	avl_destroy(&iscsit_global.global_tpg_list);
758 	avl_destroy(&iscsit_global.global_ini_list);
759 
760 	taskq_destroy(iscsit_global.global_dispatch_taskq);
761 
762 	iscsit_isns_fini();
763 
764 	stmf_free(iscsit_global.global_dbuf_store);
765 	iscsit_global.global_dbuf_store = NULL;
766 
767 	(void) stmf_deregister_port_provider(iscsit_global.global_pp);
768 	stmf_free(iscsit_global.global_pp);
769 	iscsit_global.global_pp = NULL;
770 
771 	kmem_cache_destroy(iscsit_status_pdu_cache);
772 	iscsit_status_pdu_cache = NULL;
773 
774 	vmem_destroy(iscsit_global.global_tsih_pool);
775 	iscsit_global.global_tsih_pool = NULL;
776 }
777 
778 void
779 iscsit_global_hold()
780 {
781 	idm_refcnt_hold(&iscsit_global.global_refcnt);
782 }
783 
784 void
785 iscsit_global_rele()
786 {
787 	idm_refcnt_rele(&iscsit_global.global_refcnt);
788 }
789 
790 void
791 iscsit_global_wait_ref()
792 {
793 	idm_refcnt_wait_ref(&iscsit_global.global_refcnt);
794 }
795 
796 /*
797  * IDM callbacks
798  */
799 
800 /*ARGSUSED*/
801 void
802 iscsit_rx_pdu(idm_conn_t *ic, idm_pdu_t *rx_pdu)
803 {
804 	iscsit_conn_t *ict = ic->ic_handle;
805 	switch (IDM_PDU_OPCODE(rx_pdu)) {
806 	case ISCSI_OP_SCSI_CMD:
807 		ASSERT(0); /* Shouldn't happen */
808 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
809 		break;
810 	case ISCSI_OP_SNACK_CMD:
811 		/*
812 		 * We'll need to handle this when we support ERL1/2.  For
813 		 * now we treat it as a protocol error.
814 		 */
815 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
816 		idm_conn_event(ic, CE_TRANSPORT_FAIL, NULL);
817 		break;
818 	case ISCSI_OP_SCSI_TASK_MGT_MSG:
819 		iscsit_set_cmdsn(ict, rx_pdu);
820 		iscsit_op_scsi_task_mgmt(ict, rx_pdu);
821 		break;
822 	case ISCSI_OP_NOOP_OUT:
823 	case ISCSI_OP_LOGIN_CMD:
824 	case ISCSI_OP_TEXT_CMD:
825 	case ISCSI_OP_LOGOUT_CMD:
826 		/*
827 		 * If/when we switch to userland processing these PDU's
828 		 * will be handled by iscsitd.
829 		 */
830 		iscsit_deferred_dispatch(rx_pdu);
831 		break;
832 	default:
833 		/* Protocol error */
834 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
835 		idm_conn_event(ic, CE_TRANSPORT_FAIL, NULL);
836 		break;
837 	}
838 }
839 
840 /*ARGSUSED*/
841 void
842 iscsit_rx_pdu_error(idm_conn_t *ic, idm_pdu_t *rx_pdu, idm_status_t status)
843 {
844 	idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
845 }
846 
847 void
848 iscsit_task_aborted(idm_task_t *idt, idm_status_t status)
849 {
850 	iscsit_task_t *itask = idt->idt_private;
851 
852 	switch (status) {
853 	case IDM_STATUS_SUSPENDED:
854 		break;
855 	case IDM_STATUS_ABORTED:
856 		mutex_enter(&itask->it_mutex);
857 		itask->it_aborted = B_TRUE;
858 		/*
859 		 * We rely on the fact that STMF tracks outstanding
860 		 * buffer transfers and will free all of our buffers
861 		 * before freeing the task so we don't need to
862 		 * explicitly free the buffers from iscsit/idm
863 		 */
864 		if (itask->it_stmf_abort) {
865 			mutex_exit(&itask->it_mutex);
866 			/*
867 			 * Task is no longer active
868 			 */
869 			iscsit_task_done(itask);
870 
871 			/*
872 			 * STMF has already asked for this task to be aborted
873 			 *
874 			 * STMF specification is wrong... says to return
875 			 * STMF_ABORTED, the code actually looks for
876 			 * STMF_ABORT_SUCCESS.
877 			 */
878 			stmf_task_lport_aborted(itask->it_stmf_task,
879 			    STMF_ABORT_SUCCESS, STMF_IOF_LPORT_DONE);
880 			return;
881 		} else {
882 			mutex_exit(&itask->it_mutex);
883 			/*
884 			 * Tell STMF to stop processing the task.
885 			 */
886 			stmf_abort(STMF_QUEUE_TASK_ABORT, itask->it_stmf_task,
887 			    STMF_ABORTED, NULL);
888 			return;
889 		}
890 		/*NOTREACHED*/
891 	default:
892 		ASSERT(0);
893 	}
894 }
895 
896 /*ARGSUSED*/
897 idm_status_t
898 iscsit_client_notify(idm_conn_t *ic, idm_client_notify_t icn,
899     uintptr_t data)
900 {
901 	idm_status_t rc = IDM_STATUS_SUCCESS;
902 
903 	/*
904 	 * IDM client notifications will never occur at interrupt level
905 	 * since they are generated from the connection state machine which
906 	 * running on taskq threads.
907 	 *
908 	 */
909 	switch (icn) {
910 	case CN_CONNECT_ACCEPT:
911 		rc = iscsit_conn_accept(ic); /* No data */
912 		break;
913 	case CN_FFP_ENABLED:
914 		rc = iscsit_ffp_enabled(ic); /* No data */
915 		break;
916 	case CN_FFP_DISABLED:
917 		/*
918 		 * Data indicates whether this was the result of an
919 		 * explicit logout request.
920 		 */
921 		rc = iscsit_ffp_disabled(ic, (idm_ffp_disable_t)data);
922 		break;
923 	case CN_CONNECT_LOST:
924 		rc = iscsit_conn_lost(ic);
925 		break;
926 	case CN_CONNECT_DESTROY:
927 		rc = iscsit_conn_destroy(ic);
928 		break;
929 	case CN_LOGIN_FAIL:
930 		/*
931 		 * Force the login state machine to completion
932 		 */
933 		rc = iscsit_login_fail(ic);
934 		break;
935 	default:
936 		rc = IDM_STATUS_REJECT;
937 		break;
938 	}
939 
940 	return (rc);
941 }
942 
943 
944 void
945 iscsit_build_hdr(idm_task_t *idm_task, idm_pdu_t *pdu, uint8_t opcode)
946 {
947 	iscsit_task_t *itask = idm_task->idt_private;
948 	iscsi_data_rsp_hdr_t *dh = (iscsi_data_rsp_hdr_t *)pdu->isp_hdr;
949 
950 	/*
951 	 * We acquired iscsit_sess_t.ist_sn_rwlock in iscsit_xfer_scsi_data
952 	 * in reader mode so we expect to be locked here
953 	 */
954 
955 	/*
956 	 * Lun is only required if the opcode == ISCSI_OP_SCSI_DATA_RSP
957 	 * and the 'A' bit is to be set
958 	 */
959 	dh->opcode = opcode;
960 	dh->itt = itask->it_itt;
961 	dh->ttt = itask->it_ttt;
962 	/* Maintain current statsn for RTT responses */
963 	dh->statsn = (opcode == ISCSI_OP_RTT_RSP) ?
964 	    htonl(itask->it_ict->ict_statsn) : 0;
965 	dh->expcmdsn = htonl(itask->it_ict->ict_sess->ist_expcmdsn);
966 	dh->maxcmdsn = htonl(itask->it_ict->ict_sess->ist_maxcmdsn);
967 
968 	/*
969 	 * IDM must set:
970 	 *
971 	 * data.flags and rtt.flags
972 	 * data.dlength
973 	 * data.datasn
974 	 * data.offset
975 	 * residual_count and cmd_status (if we ever implement phase collapse)
976 	 * rtt.rttsn
977 	 * rtt.data_offset
978 	 * rtt.data_length
979 	 */
980 }
981 
982 void
983 iscsit_keepalive(idm_conn_t *ic)
984 {
985 	idm_pdu_t		*nop_in_pdu;
986 	iscsi_nop_in_hdr_t	*nop_in;
987 	iscsit_conn_t		*ict = ic->ic_handle;
988 
989 	/*
990 	 * IDM noticed the connection has been idle for too long so it's
991 	 * time to provoke some activity.  Build and transmit an iSCSI
992 	 * nop-in PDU -- when the initiator responds it will be counted
993 	 * as "activity" and keep the connection alive.
994 	 *
995 	 * We don't actually care about the response here at the iscsit level
996 	 * so we will just throw it away without looking at it when it arrives.
997 	 */
998 	nop_in_pdu = idm_pdu_alloc(sizeof (*nop_in), 0);
999 	idm_pdu_init(nop_in_pdu, ic, NULL, NULL);
1000 
1001 	nop_in = (iscsi_nop_in_hdr_t *)nop_in_pdu->isp_hdr;
1002 	bzero(nop_in, sizeof (*nop_in));
1003 	nop_in->opcode = ISCSI_OP_NOOP_IN;
1004 	nop_in->flags = ISCSI_FLAG_FINAL;
1005 	nop_in->itt = ISCSI_RSVD_TASK_TAG;
1006 	/*
1007 	 * This works because we don't currently allocate ttt's anywhere else
1008 	 * in iscsit so as long as we stay out of IDM's range we are safe.
1009 	 * If we need to allocate ttt's for other PDU's in the future this will
1010 	 * need to be improved.
1011 	 */
1012 	mutex_enter(&ict->ict_mutex);
1013 	nop_in->ttt = ict->ict_keepalive_ttt;
1014 	ict->ict_keepalive_ttt++;
1015 	if (ict->ict_keepalive_ttt == ISCSI_RSVD_TASK_TAG)
1016 		ict->ict_keepalive_ttt = IDM_TASKIDS_MAX;
1017 	mutex_exit(&ict->ict_mutex);
1018 
1019 	iscsit_pdu_tx(nop_in_pdu);
1020 }
1021 
1022 static idm_status_t
1023 iscsit_conn_accept(idm_conn_t *ic)
1024 {
1025 	iscsit_conn_t *ict;
1026 
1027 	/*
1028 	 * We need to get a global hold here to ensure that the service
1029 	 * doesn't get shutdown prior to establishing a session. This
1030 	 * gets released in iscsit_conn_destroy().
1031 	 */
1032 	ISCSIT_GLOBAL_LOCK(RW_READER);
1033 	if (iscsit_global.global_svc_state != ISE_ENABLED) {
1034 		ISCSIT_GLOBAL_UNLOCK();
1035 		return (IDM_STATUS_FAIL);
1036 	}
1037 	iscsit_global_hold();
1038 	ISCSIT_GLOBAL_UNLOCK();
1039 
1040 	/*
1041 	 * Allocate an associated iscsit structure to represent this
1042 	 * connection.  We shouldn't really create a session until we
1043 	 * get the first login PDU.
1044 	 */
1045 	ict = kmem_zalloc(sizeof (*ict), KM_SLEEP);
1046 
1047 	ict->ict_ic = ic;
1048 	ict->ict_statsn = 1;
1049 	ict->ict_keepalive_ttt = IDM_TASKIDS_MAX; /* Avoid IDM TT range */
1050 	ic->ic_handle = ict;
1051 	mutex_init(&ict->ict_mutex, NULL, MUTEX_DRIVER, NULL);
1052 	idm_refcnt_init(&ict->ict_refcnt, ict);
1053 
1054 	/*
1055 	 * Initialize login state machine
1056 	 */
1057 	if (iscsit_login_sm_init(ict) != IDM_STATUS_SUCCESS) {
1058 		iscsit_global_rele();
1059 		/*
1060 		 * Cleanup the ict after idm notifies us about this failure
1061 		 */
1062 		return (IDM_STATUS_FAIL);
1063 	}
1064 
1065 	return (IDM_STATUS_SUCCESS);
1066 }
1067 
1068 idm_status_t
1069 iscsit_conn_reinstate(iscsit_conn_t *reinstate_ict, iscsit_conn_t *new_ict)
1070 {
1071 	idm_status_t	result;
1072 
1073 	/*
1074 	 * Note in new connection state that this connection is
1075 	 * reinstating an existing connection.
1076 	 */
1077 	new_ict->ict_reinstating = B_TRUE;
1078 	new_ict->ict_reinstate_conn = reinstate_ict;
1079 	new_ict->ict_statsn = reinstate_ict->ict_statsn;
1080 
1081 	/*
1082 	 * Now generate connection state machine event to existing connection
1083 	 * so that it starts the cleanup process.
1084 	 */
1085 	result = idm_conn_reinstate_event(reinstate_ict->ict_ic,
1086 	    new_ict->ict_ic);
1087 
1088 	return (result);
1089 }
1090 
1091 void
1092 iscsit_conn_hold(iscsit_conn_t *ict)
1093 {
1094 	idm_refcnt_hold(&ict->ict_refcnt);
1095 }
1096 
1097 void
1098 iscsit_conn_rele(iscsit_conn_t *ict)
1099 {
1100 	idm_refcnt_rele(&ict->ict_refcnt);
1101 }
1102 
1103 void
1104 iscsit_conn_dispatch_hold(iscsit_conn_t *ict)
1105 {
1106 	idm_refcnt_hold(&ict->ict_dispatch_refcnt);
1107 }
1108 
1109 void
1110 iscsit_conn_dispatch_rele(iscsit_conn_t *ict)
1111 {
1112 	idm_refcnt_rele(&ict->ict_dispatch_refcnt);
1113 }
1114 
1115 static idm_status_t
1116 iscsit_login_fail(idm_conn_t *ic)
1117 {
1118 	iscsit_conn_t *ict = ic->ic_handle;
1119 
1120 	/* Generate login state machine event */
1121 	iscsit_login_sm_event(ict, ILE_LOGIN_CONN_ERROR, NULL);
1122 
1123 	return (IDM_STATUS_SUCCESS);
1124 }
1125 
1126 static idm_status_t
1127 iscsit_ffp_enabled(idm_conn_t *ic)
1128 {
1129 	iscsit_conn_t *ict = ic->ic_handle;
1130 
1131 	/* Generate session state machine event */
1132 	iscsit_sess_sm_event(ict->ict_sess, SE_CONN_LOGGED_IN, ict);
1133 
1134 	return (IDM_STATUS_SUCCESS);
1135 }
1136 
1137 static idm_status_t
1138 iscsit_ffp_disabled(idm_conn_t *ic, idm_ffp_disable_t disable_class)
1139 {
1140 	iscsit_conn_t *ict = ic->ic_handle;
1141 
1142 	/* Generate session state machine event */
1143 	switch (disable_class) {
1144 	case FD_CONN_FAIL:
1145 		iscsit_sess_sm_event(ict->ict_sess, SE_CONN_FFP_FAIL, ict);
1146 		break;
1147 	case FD_CONN_LOGOUT:
1148 		iscsit_sess_sm_event(ict->ict_sess, SE_CONN_FFP_DISABLE, ict);
1149 		break;
1150 	case FD_SESS_LOGOUT:
1151 		iscsit_sess_sm_event(ict->ict_sess, SE_SESSION_CLOSE, ict);
1152 		break;
1153 	default:
1154 		ASSERT(0);
1155 	}
1156 
1157 	return (IDM_STATUS_SUCCESS);
1158 }
1159 
1160 static idm_status_t
1161 iscsit_conn_lost(idm_conn_t *ic)
1162 {
1163 	iscsit_conn_t *ict = ic->ic_handle;
1164 
1165 	mutex_enter(&ict->ict_mutex);
1166 	ict->ict_lost = B_TRUE;
1167 	mutex_exit(&ict->ict_mutex);
1168 
1169 	/*
1170 	 * Make sure there aren't any PDU's transitioning from the receive
1171 	 * handler to the dispatch taskq.
1172 	 */
1173 	idm_refcnt_wait_ref(&ict->ict_dispatch_refcnt);
1174 
1175 	return (IDM_STATUS_SUCCESS);
1176 }
1177 
1178 static idm_status_t
1179 iscsit_conn_destroy(idm_conn_t *ic)
1180 {
1181 	iscsit_conn_t *ict = ic->ic_handle;
1182 
1183 	mutex_enter(&ict->ict_mutex);
1184 	ict->ict_destroyed = B_TRUE;
1185 	mutex_exit(&ict->ict_mutex);
1186 
1187 	/* Generate session state machine event */
1188 	if (ict->ict_sess != NULL) {
1189 		/*
1190 		 * Session state machine will call iscsit_conn_destroy_done()
1191 		 * when it has removed references to this connection.
1192 		 */
1193 		iscsit_sess_sm_event(ict->ict_sess, SE_CONN_FAIL, ict);
1194 	}
1195 
1196 	ict->ict_ic = NULL;
1197 
1198 	idm_refcnt_wait_ref(&ict->ict_refcnt);
1199 
1200 	/* Reap the login state machine */
1201 	iscsit_login_sm_fini(ict);
1202 
1203 	/* Clean up any text command remnants */
1204 	iscsit_text_cmd_fini(ict);
1205 
1206 	mutex_destroy(&ict->ict_mutex);
1207 	idm_refcnt_destroy(&ict->ict_refcnt);
1208 	kmem_free(ict, sizeof (*ict));
1209 
1210 	iscsit_global_rele();
1211 
1212 	return (IDM_STATUS_SUCCESS);
1213 }
1214 
1215 /*
1216  * STMF-related functions
1217  *
1218  * iSCSI to STMF mapping
1219  *
1220  * Session == ?
1221  * Connection == bound to local port but not itself a local port
1222  * Target
1223  * Target portal (group?) == local port (really but we're not going to do this)
1224  *	iscsit needs to map connections to local ports (whatever we decide
1225  * 	they are)
1226  * Target == ?
1227  */
1228 
1229 /*ARGSUSED*/
1230 static stmf_data_buf_t *
1231 iscsit_dbuf_alloc(scsi_task_t *task, uint32_t size, uint32_t *pminsize,
1232     uint32_t flags)
1233 {
1234 	iscsit_task_t *itask = task->task_port_private;
1235 	idm_buf_t *idm_buffer;
1236 	iscsit_buf_t	*ibuf;
1237 	stmf_data_buf_t *result;
1238 
1239 	/*
1240 	 * Once the iSER picture is better understood it might make sense
1241 	 * to pre-allocate some registered buffers, similar to what
1242 	 * fct/qlt are doing.  In the meantime hopefully stmf can allocate
1243 	 * these things quickly.
1244 	 *
1245 	 * We can't support a transfer larger than MaxBurstLength bytes.
1246 	 */
1247 	if (size > itask->it_ict->ict_op.op_max_burst_length) {
1248 		*pminsize = itask->it_ict->ict_op.op_max_burst_length;
1249 		return (NULL);
1250 	}
1251 
1252 	/* Alloc buffer */
1253 	idm_buffer = idm_buf_alloc(itask->it_ict->ict_ic, NULL, size);
1254 	if (idm_buffer != NULL) {
1255 		result = stmf_alloc(STMF_STRUCT_DATA_BUF,
1256 		    sizeof (iscsit_buf_t), 0);
1257 		if (result != NULL) {
1258 			/* Fill in stmf_data_buf_t */
1259 			ibuf = result->db_port_private;
1260 			ibuf->ibuf_idm_buf = idm_buffer;
1261 			ibuf->ibuf_stmf_buf = result;
1262 			ibuf->ibuf_is_immed = B_FALSE;
1263 			result->db_flags = DB_DONT_CACHE;
1264 			result->db_buf_size = size;
1265 			result->db_data_size = size;
1266 			result->db_sglist_length = 1;
1267 			result->db_sglist[0].seg_addr = idm_buffer->idb_buf;
1268 			result->db_sglist[0].seg_length =
1269 			    idm_buffer->idb_buflen;
1270 			return (result);
1271 		}
1272 
1273 		/* Couldn't get the stmf_data_buf_t so free the buffer */
1274 		idm_buf_free(idm_buffer);
1275 	}
1276 
1277 	return (NULL);
1278 }
1279 
1280 /*ARGSUSED*/
1281 static void
1282 iscsit_dbuf_free(stmf_dbuf_store_t *ds, stmf_data_buf_t *dbuf)
1283 {
1284 	iscsit_buf_t *ibuf = dbuf->db_port_private;
1285 
1286 	if (ibuf->ibuf_is_immed) {
1287 		/*
1288 		 * The iscsit_buf_t structure itself will be freed with its
1289 		 * associated task.  Here we just need to free the PDU that
1290 		 * held the immediate data.
1291 		 */
1292 		idm_pdu_complete(ibuf->ibuf_immed_data_pdu, IDM_STATUS_SUCCESS);
1293 		ibuf->ibuf_immed_data_pdu = 0;
1294 	} else {
1295 		idm_buf_free(ibuf->ibuf_idm_buf);
1296 		stmf_free(dbuf);
1297 	}
1298 }
1299 
1300 /*ARGSUSED*/
1301 stmf_status_t
1302 iscsit_xfer_scsi_data(scsi_task_t *task, stmf_data_buf_t *dbuf,
1303     uint32_t ioflags)
1304 {
1305 	iscsit_task_t *iscsit_task = task->task_port_private;
1306 	iscsit_buf_t *ibuf = dbuf->db_port_private;
1307 	int idm_rc;
1308 
1309 	/*
1310 	 * If we are aborting then we can ignore this request
1311 	 */
1312 	if (iscsit_task->it_stmf_abort) {
1313 		return (STMF_SUCCESS);
1314 	}
1315 
1316 	/*
1317 	 * If it's not immediate data then start the transfer
1318 	 */
1319 	ASSERT(ibuf->ibuf_is_immed == B_FALSE);
1320 	if (dbuf->db_flags & DB_DIRECTION_TO_RPORT) {
1321 		/*
1322 		 * IDM will call iscsit_build_hdr so lock now to serialize
1323 		 * access to the SN values.  We need to lock here to enforce
1324 		 * lock ordering
1325 		 */
1326 		rw_enter(&iscsit_task->it_ict->ict_sess->ist_sn_rwlock,
1327 		    RW_READER);
1328 		idm_rc = idm_buf_tx_to_ini(iscsit_task->it_idm_task,
1329 		    ibuf->ibuf_idm_buf, dbuf->db_relative_offset,
1330 		    dbuf->db_data_size, &iscsit_buf_xfer_cb, dbuf);
1331 		rw_exit(&iscsit_task->it_ict->ict_sess->ist_sn_rwlock);
1332 
1333 		return (iscsit_idm_to_stmf(idm_rc));
1334 	} else if (dbuf->db_flags & DB_DIRECTION_FROM_RPORT) {
1335 		/* Grab the SN lock (see comment above) */
1336 		rw_enter(&iscsit_task->it_ict->ict_sess->ist_sn_rwlock,
1337 		    RW_READER);
1338 		idm_rc = idm_buf_rx_from_ini(iscsit_task->it_idm_task,
1339 		    ibuf->ibuf_idm_buf, dbuf->db_relative_offset,
1340 		    dbuf->db_data_size, &iscsit_buf_xfer_cb, dbuf);
1341 		rw_exit(&iscsit_task->it_ict->ict_sess->ist_sn_rwlock);
1342 
1343 		return (iscsit_idm_to_stmf(idm_rc));
1344 	}
1345 
1346 	/* What are we supposed to do if there is no direction? */
1347 	return (STMF_INVALID_ARG);
1348 }
1349 
1350 static void
1351 iscsit_buf_xfer_cb(idm_buf_t *idb, idm_status_t status)
1352 {
1353 	iscsit_task_t *itask = idb->idb_task_binding->idt_private;
1354 	stmf_data_buf_t *dbuf = idb->idb_cb_arg;
1355 
1356 	dbuf->db_xfer_status = iscsit_idm_to_stmf(status);
1357 
1358 	/*
1359 	 * If the task has been aborted then we don't need to call STMF
1360 	 */
1361 	if (itask->it_stmf_abort) {
1362 		return;
1363 	}
1364 
1365 	/*
1366 	 * COMSTAR currently requires port providers to support
1367 	 * the DB_SEND_STATUS_GOOD flag even if phase collapse is
1368 	 * not supported.  So we will roll our own... pretend we are
1369 	 * COMSTAR and ask for a status PDU.
1370 	 */
1371 	if ((dbuf->db_flags & DB_SEND_STATUS_GOOD) &&
1372 	    status == IDM_STATUS_SUCCESS) {
1373 		/*
1374 		 * If iscsit_send_scsi_status succeeds then the TX PDU
1375 		 * callback will call stmf_send_status_done and set
1376 		 * STMF_IOF_LPORT_DONE.  Consequently we don't need
1377 		 * to call stmf_data_xfer_done in that case.  We
1378 		 * still need to call it if we get a failure.
1379 		 *
1380 		 * To elaborate on this some more, upon successful
1381 		 * return from iscsit_send_scsi_status it's possible
1382 		 * that itask and idb have been freed and are no
1383 		 * longer valid.
1384 		 */
1385 		if (iscsit_send_scsi_status(itask->it_stmf_task, 0)
1386 		    != STMF_SUCCESS) {
1387 			/* Failed to send status */
1388 			dbuf->db_xfer_status = STMF_FAILURE;
1389 			stmf_data_xfer_done(itask->it_stmf_task, dbuf,
1390 			    STMF_IOF_LPORT_DONE);
1391 		}
1392 	} else {
1393 		stmf_data_xfer_done(itask->it_stmf_task, dbuf, 0);
1394 	}
1395 }
1396 
1397 
1398 /*ARGSUSED*/
1399 stmf_status_t
1400 iscsit_send_scsi_status(scsi_task_t *task, uint32_t ioflags)
1401 {
1402 	iscsit_task_t *itask = task->task_port_private;
1403 	iscsi_scsi_rsp_hdr_t *rsp;
1404 	idm_pdu_t *pdu;
1405 	int resp_datalen;
1406 
1407 	/*
1408 	 * If this task is aborted then we don't need to respond.
1409 	 */
1410 	if (itask->it_stmf_abort) {
1411 		return (STMF_SUCCESS);
1412 	}
1413 
1414 	/*
1415 	 * If this is a task management status, handle it elsewhere.
1416 	 */
1417 	if (task->task_mgmt_function != TM_NONE) {
1418 		/*
1419 		 * Don't wait for the PDU completion to tell STMF
1420 		 * the task is done -- it doesn't really matter and
1421 		 * it makes life complicated if STMF later asks us to
1422 		 * abort the request and we don't know whether the
1423 		 * status has been sent or not.
1424 		 */
1425 		itask->it_tm_responded = B_TRUE;
1426 		iscsit_send_task_mgmt_resp(itask->it_tm_pdu,
1427 		    (task->task_completion_status == STMF_SUCCESS) ?
1428 		    SCSI_TCP_TM_RESP_COMPLETE : SCSI_TCP_TM_RESP_FUNC_NOT_SUPP);
1429 		stmf_send_status_done(task, STMF_SUCCESS,
1430 		    STMF_IOF_LPORT_DONE);
1431 		return (STMF_SUCCESS);
1432 	}
1433 
1434 	/*
1435 	 * Remove the task from the session task list
1436 	 */
1437 	iscsit_task_done(itask);
1438 
1439 	/*
1440 	 * Send status
1441 	 */
1442 	mutex_enter(&itask->it_idm_task->idt_mutex);
1443 	if ((itask->it_idm_task->idt_state == TASK_ACTIVE) &&
1444 	    (task->task_completion_status == STMF_SUCCESS) &&
1445 	    (task->task_sense_length == 0) &&
1446 	    (task->task_resid == 0)) {
1447 		itask->it_idm_task->idt_state = TASK_COMPLETE;
1448 		/* PDU callback releases task hold */
1449 		idm_task_hold(itask->it_idm_task);
1450 		mutex_exit(&itask->it_idm_task->idt_mutex);
1451 		/*
1452 		 * Fast path.  Cached status PDU's are already
1453 		 * initialized.  We just need to fill in
1454 		 * connection and task information.
1455 		 */
1456 		pdu = kmem_cache_alloc(iscsit_status_pdu_cache, KM_SLEEP);
1457 		pdu->isp_ic = itask->it_ict->ict_ic;
1458 		pdu->isp_private = itask;
1459 
1460 		rsp = (iscsi_scsi_rsp_hdr_t *)pdu->isp_hdr;
1461 		rsp->itt = itask->it_itt;
1462 		rsp->cmd_status = task->task_scsi_status;
1463 		iscsit_pdu_tx(pdu);
1464 		return (STMF_SUCCESS);
1465 	} else {
1466 		if (itask->it_idm_task->idt_state != TASK_ACTIVE) {
1467 			mutex_exit(&itask->it_idm_task->idt_mutex);
1468 			return (STMF_FAILURE);
1469 		}
1470 		itask->it_idm_task->idt_state = TASK_COMPLETE;
1471 		/* PDU callback releases task hold */
1472 		idm_task_hold(itask->it_idm_task);
1473 		mutex_exit(&itask->it_idm_task->idt_mutex);
1474 
1475 		resp_datalen = (task->task_sense_length == 0) ? 0 :
1476 		    (task->task_sense_length + sizeof (uint16_t));
1477 
1478 		pdu = idm_pdu_alloc(sizeof (iscsi_hdr_t), resp_datalen);
1479 		idm_pdu_init(pdu, itask->it_ict->ict_ic, itask,
1480 		    iscsit_send_status_done);
1481 
1482 		rsp = (iscsi_scsi_rsp_hdr_t *)pdu->isp_hdr;
1483 		bzero(rsp, sizeof (*rsp));
1484 		rsp->opcode = ISCSI_OP_SCSI_RSP;
1485 
1486 		rsp->flags = ISCSI_FLAG_FINAL;
1487 		if (task->task_status_ctrl & TASK_SCTRL_OVER) {
1488 			rsp->flags |= ISCSI_FLAG_CMD_OVERFLOW;
1489 		} else if (task->task_status_ctrl & TASK_SCTRL_UNDER) {
1490 			rsp->flags |= ISCSI_FLAG_CMD_UNDERFLOW;
1491 		}
1492 
1493 		rsp->bi_residual_count = 0;
1494 		rsp->residual_count = htonl(task->task_resid);
1495 		rsp->itt = itask->it_itt;
1496 		rsp->response = ISCSI_STATUS_CMD_COMPLETED;
1497 		rsp->cmd_status = task->task_scsi_status;
1498 		if (task->task_sense_length != 0) {
1499 			/*
1500 			 * Add a byte to provide the sense length in
1501 			 * the response
1502 			 */
1503 			*(uint16_t *)((void *)pdu->isp_data) =
1504 			    htons(task->task_sense_length);
1505 			bcopy(task->task_sense_data,
1506 			    (uint8_t *)pdu->isp_data +
1507 			    sizeof (uint16_t),
1508 			    task->task_sense_length);
1509 			hton24(rsp->dlength, resp_datalen);
1510 		}
1511 
1512 		DTRACE_PROBE5(iscsi__scsi__response,
1513 		    iscsit_conn_t *, itask->it_ict,
1514 		    uint8_t, rsp->response,
1515 		    uint8_t, rsp->cmd_status,
1516 		    idm_pdu_t *, pdu,
1517 		    scsi_task_t *, task);
1518 
1519 		iscsit_pdu_tx(pdu);
1520 
1521 		return (STMF_SUCCESS);
1522 	}
1523 }
1524 
1525 /*ARGSUSED*/
1526 static void
1527 iscsit_send_good_status_done(idm_pdu_t *pdu, idm_status_t status)
1528 {
1529 	iscsit_task_t	*itask;
1530 	boolean_t	aborted;
1531 
1532 	itask = pdu->isp_private;
1533 	aborted = itask->it_stmf_abort;
1534 
1535 	/*
1536 	 * After releasing the hold the task may be freed at any time so
1537 	 * don't touch it.
1538 	 */
1539 	idm_task_rele(itask->it_idm_task);
1540 	if (!aborted) {
1541 		stmf_send_status_done(itask->it_stmf_task,
1542 		    iscsit_idm_to_stmf(pdu->isp_status), STMF_IOF_LPORT_DONE);
1543 	}
1544 	kmem_cache_free(iscsit_status_pdu_cache, pdu);
1545 }
1546 
1547 /*ARGSUSED*/
1548 static void
1549 iscsit_send_status_done(idm_pdu_t *pdu, idm_status_t status)
1550 {
1551 	iscsit_task_t	 *itask;
1552 	boolean_t	aborted;
1553 
1554 	itask = pdu->isp_private;
1555 	aborted = itask->it_stmf_abort;
1556 
1557 	/*
1558 	 * After releasing the hold the task may be freed at any time so
1559 	 * don't touch it.
1560 	 */
1561 	idm_task_rele(itask->it_idm_task);
1562 	if (!aborted) {
1563 		stmf_send_status_done(itask->it_stmf_task,
1564 		    iscsit_idm_to_stmf(pdu->isp_status), STMF_IOF_LPORT_DONE);
1565 	}
1566 	idm_pdu_free(pdu);
1567 }
1568 
1569 
1570 void
1571 iscsit_lport_task_free(scsi_task_t *task)
1572 {
1573 	iscsit_task_t *itask = task->task_port_private;
1574 
1575 	/* We only call idm_task_start for regular tasks, not task management */
1576 	if (task->task_mgmt_function == TM_NONE) {
1577 		idm_task_done(itask->it_idm_task);
1578 		iscsit_task_free(itask);
1579 		return;
1580 	} else {
1581 		iscsit_tm_task_free(itask);
1582 	}
1583 }
1584 
1585 /*ARGSUSED*/
1586 stmf_status_t
1587 iscsit_abort(stmf_local_port_t *lport, int abort_cmd, void *arg, uint32_t flags)
1588 {
1589 	scsi_task_t	*st = (scsi_task_t *)arg;
1590 	iscsit_task_t	*iscsit_task;
1591 	idm_task_t	*idt;
1592 
1593 	/*
1594 	 * If this is a task management request then there's really not much to
1595 	 * do.
1596 	 */
1597 	if (st->task_mgmt_function != TM_NONE) {
1598 		return (STMF_ABORT_SUCCESS);
1599 	}
1600 
1601 	/*
1602 	 * Regular task, start cleaning up
1603 	 */
1604 	iscsit_task = st->task_port_private;
1605 	idt = iscsit_task->it_idm_task;
1606 	mutex_enter(&iscsit_task->it_mutex);
1607 	iscsit_task->it_stmf_abort = B_TRUE;
1608 	if (iscsit_task->it_aborted) {
1609 		mutex_exit(&iscsit_task->it_mutex);
1610 		/*
1611 		 * Task is no longer active
1612 		 */
1613 		iscsit_task_done(iscsit_task);
1614 
1615 		/*
1616 		 * STMF specification is wrong... says to return
1617 		 * STMF_ABORTED, the code actually looks for
1618 		 * STMF_ABORT_SUCCESS.
1619 		 */
1620 		return (STMF_ABORT_SUCCESS);
1621 	} else {
1622 		mutex_exit(&iscsit_task->it_mutex);
1623 		/*
1624 		 * Call IDM to abort the task.  Due to a variety of
1625 		 * circumstances the task may already be in the process of
1626 		 * aborting.
1627 		 * We'll let IDM worry about rationalizing all that except
1628 		 * for one particular instance.  If the state of the task
1629 		 * is TASK_COMPLETE, we need to indicate to the framework
1630 		 * that we are in fact done.  This typically happens with
1631 		 * framework-initiated task management type requests
1632 		 * (e.g. abort task).
1633 		 */
1634 		if (idt->idt_state == TASK_COMPLETE) {
1635 			idm_refcnt_wait_ref(&idt->idt_refcnt);
1636 			return (STMF_ABORT_SUCCESS);
1637 		} else {
1638 			idm_task_abort(idt->idt_ic, idt, AT_TASK_MGMT_ABORT);
1639 			return (STMF_SUCCESS);
1640 		}
1641 	}
1642 
1643 	/*NOTREACHED*/
1644 }
1645 
1646 /*ARGSUSED*/
1647 void
1648 iscsit_ctl(stmf_local_port_t *lport, int cmd, void *arg)
1649 {
1650 	iscsit_tgt_t		*iscsit_tgt;
1651 
1652 	ASSERT((cmd == STMF_CMD_LPORT_ONLINE) ||
1653 	    (cmd == STMF_ACK_LPORT_ONLINE_COMPLETE) ||
1654 	    (cmd == STMF_CMD_LPORT_OFFLINE) ||
1655 	    (cmd == STMF_ACK_LPORT_OFFLINE_COMPLETE));
1656 
1657 	iscsit_tgt = (iscsit_tgt_t *)lport->lport_port_private;
1658 
1659 	switch (cmd) {
1660 	case STMF_CMD_LPORT_ONLINE:
1661 		iscsit_tgt_sm_event(iscsit_tgt, TE_STMF_ONLINE_REQ);
1662 		break;
1663 	case STMF_CMD_LPORT_OFFLINE:
1664 		iscsit_tgt_sm_event(iscsit_tgt, TE_STMF_OFFLINE_REQ);
1665 		break;
1666 	case STMF_ACK_LPORT_ONLINE_COMPLETE:
1667 		iscsit_tgt_sm_event(iscsit_tgt, TE_STMF_ONLINE_COMPLETE_ACK);
1668 		break;
1669 	case STMF_ACK_LPORT_OFFLINE_COMPLETE:
1670 		iscsit_tgt_sm_event(iscsit_tgt, TE_STMF_OFFLINE_COMPLETE_ACK);
1671 		break;
1672 
1673 	default:
1674 		break;
1675 	}
1676 }
1677 
1678 static stmf_status_t
1679 iscsit_idm_to_stmf(idm_status_t idmrc)
1680 {
1681 	switch (idmrc) {
1682 	case IDM_STATUS_SUCCESS:
1683 		return (STMF_SUCCESS);
1684 	default:
1685 		return (STMF_FAILURE);
1686 	}
1687 	/*NOTREACHED*/
1688 }
1689 
1690 
1691 /*
1692  * ISCSI protocol
1693  */
1694 
1695 void
1696 iscsit_op_scsi_cmd(idm_conn_t *ic, idm_pdu_t *rx_pdu)
1697 {
1698 	iscsit_conn_t		*ict;
1699 	iscsit_task_t		*itask;
1700 	scsi_task_t		*task;
1701 	iscsit_buf_t		*ibuf;
1702 	iscsi_scsi_cmd_hdr_t	*iscsi_scsi =
1703 	    (iscsi_scsi_cmd_hdr_t *)rx_pdu->isp_hdr;
1704 	iscsi_addl_hdr_t	*ahs_hdr;
1705 	uint16_t		addl_cdb_len = 0;
1706 
1707 	ict = ic->ic_handle;
1708 
1709 	itask = iscsit_task_alloc(ict);
1710 	if (itask == NULL) {
1711 		/* Finish processing request */
1712 		iscsit_set_cmdsn(ict, rx_pdu);
1713 
1714 		iscsit_send_direct_scsi_resp(ict, rx_pdu,
1715 		    ISCSI_STATUS_CMD_COMPLETED, STATUS_BUSY);
1716 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1717 		return;
1718 	}
1719 
1720 
1721 	/*
1722 	 * Note CmdSN and ITT in task.  IDM will have already validated this
1723 	 * request against the connection state so we don't need to check
1724 	 * that (the connection may have changed state in the meantime but
1725 	 * we will catch that when we try to send a response)
1726 	 */
1727 	itask->it_cmdsn = ntohl(iscsi_scsi->cmdsn);
1728 	itask->it_itt = iscsi_scsi->itt;
1729 
1730 	/*
1731 	 * Check for extended CDB AHS
1732 	 */
1733 	if (iscsi_scsi->hlength > 0) {
1734 		ahs_hdr = (iscsi_addl_hdr_t *)iscsi_scsi;
1735 		addl_cdb_len = ((ahs_hdr->ahs_hlen_hi << 8) |
1736 		    ahs_hdr->ahs_hlen_lo) - 1; /* Adjust for reserved byte */
1737 		if (((addl_cdb_len + 4) / sizeof (uint32_t)) >
1738 		    iscsi_scsi->hlength) {
1739 			/* Mangled header info, drop it */
1740 			idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1741 			return;
1742 		}
1743 	}
1744 
1745 	ict = rx_pdu->isp_ic->ic_handle; /* IDM client private */
1746 
1747 	/*
1748 	 * Add task to session list.  This function will also check to
1749 	 * ensure that the task does not already exist.
1750 	 */
1751 	if (iscsit_task_start(itask) != IDM_STATUS_SUCCESS) {
1752 		/*
1753 		 * Task exists, free all resources and reject.  Don't
1754 		 * update expcmdsn in this case because RFC 3720 says
1755 		 * "The CmdSN of the rejected command PDU (if it is a
1756 		 * non-immediate command) MUST NOT be considered received
1757 		 * by the target (i.e., a command sequence gap must be
1758 		 * assumed for the CmdSN), even though the CmdSN of the
1759 		 * rejected command PDU may be reliably ascertained.  Upon
1760 		 * receiving the Reject, the initiator MUST plug the CmdSN
1761 		 * gap in order to continue to use the session.  The gap
1762 		 * may be plugged either by transmitting a command PDU
1763 		 * with the same CmdSN, or by aborting the task (see section
1764 		 * 6.9 on how an abort may plug a CmdSN gap)." (Section 6.3)
1765 		 */
1766 		iscsit_task_free(itask);
1767 		iscsit_send_reject(ict, rx_pdu, ISCSI_REJECT_TASK_IN_PROGRESS);
1768 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1769 		return;
1770 	}
1771 
1772 	/* Update sequence numbers */
1773 	iscsit_set_cmdsn(ict, rx_pdu);
1774 
1775 	/*
1776 	 * Allocate STMF task
1777 	 */
1778 	itask->it_stmf_task = stmf_task_alloc(
1779 	    itask->it_ict->ict_sess->ist_lport,
1780 	    itask->it_ict->ict_sess->ist_stmf_sess, iscsi_scsi->lun,
1781 	    16 + addl_cdb_len, 0);
1782 	if (itask->it_stmf_task == NULL) {
1783 		/*
1784 		 * Either stmf really couldn't get memory for a task or,
1785 		 * more likely, the LU is currently in reset.  Either way
1786 		 * we have no choice but to fail the request.
1787 		 */
1788 		iscsit_task_done(itask);
1789 		iscsit_task_free(itask);
1790 		iscsit_send_direct_scsi_resp(ict, rx_pdu,
1791 		    ISCSI_STATUS_CMD_COMPLETED, STATUS_BUSY);
1792 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1793 		return;
1794 	}
1795 
1796 	task = itask->it_stmf_task;
1797 	task->task_port_private = itask;
1798 
1799 	bcopy(iscsi_scsi->lun, task->task_lun_no, sizeof (task->task_lun_no));
1800 
1801 	/*
1802 	 * iSCSI and Comstar use the same values.  Should we rely on this
1803 	 * or translate them bit-wise?
1804 	 */
1805 
1806 	task->task_flags =
1807 	    (((iscsi_scsi->flags & ISCSI_FLAG_CMD_READ) ? TF_READ_DATA : 0) |
1808 	    ((iscsi_scsi->flags & ISCSI_FLAG_CMD_WRITE) ? TF_WRITE_DATA : 0) |
1809 	    ((rx_pdu->isp_datalen == 0) ? 0 : TF_INITIAL_BURST));
1810 
1811 	switch (iscsi_scsi->flags & ISCSI_FLAG_CMD_ATTR_MASK) {
1812 	case ISCSI_ATTR_UNTAGGED:
1813 		break;
1814 	case ISCSI_ATTR_SIMPLE:
1815 		task->task_additional_flags |= TF_ATTR_SIMPLE_QUEUE;
1816 		break;
1817 	case ISCSI_ATTR_ORDERED:
1818 		task->task_additional_flags |= TF_ATTR_ORDERED_QUEUE;
1819 		break;
1820 	case ISCSI_ATTR_HEAD_OF_QUEUE:
1821 		task->task_additional_flags |= TF_ATTR_HEAD_OF_QUEUE;
1822 		break;
1823 	case ISCSI_ATTR_ACA:
1824 		task->task_additional_flags |= TF_ATTR_ACA;
1825 		break;
1826 	default:
1827 		/* Protocol error but just take it, treat as untagged */
1828 		break;
1829 	}
1830 
1831 
1832 	task->task_additional_flags = 0;
1833 	task->task_priority = 0;
1834 	task->task_mgmt_function = TM_NONE;
1835 
1836 	/*
1837 	 * This "task_max_nbufs" doesn't map well to BIDI.  We probably need
1838 	 * parameter for each direction.  "MaxOutstandingR2T" may very well
1839 	 * be set to one which could prevent us from doing simultaneous
1840 	 * transfers in each direction.
1841 	 */
1842 	task->task_max_nbufs = (iscsi_scsi->flags & ISCSI_FLAG_CMD_WRITE) ?
1843 	    ict->ict_op.op_max_outstanding_r2t : STMF_BUFS_MAX;
1844 	task->task_cmd_seq_no = ntohl(iscsi_scsi->itt);
1845 	task->task_expected_xfer_length = ntohl(iscsi_scsi->data_length);
1846 
1847 	/* Copy CDB */
1848 	bcopy(iscsi_scsi->scb, task->task_cdb, 16);
1849 	if (addl_cdb_len > 0) {
1850 		bcopy(ahs_hdr->ahs_extscb, task->task_cdb + 16, addl_cdb_len);
1851 	}
1852 
1853 	DTRACE_ISCSI_3(scsi__command, idm_conn_t *, ic,
1854 	    iscsi_scsi_cmd_hdr_t *, (iscsi_scsi_cmd_hdr_t *)rx_pdu->isp_hdr,
1855 	    scsi_task_t *, task);
1856 
1857 	/*
1858 	 * Copy the transport header into the task handle from the PDU
1859 	 * handle. The transport header describes this task's remote tagged
1860 	 * buffer.
1861 	 */
1862 	if (rx_pdu->isp_transport_hdrlen != 0) {
1863 		bcopy(rx_pdu->isp_transport_hdr,
1864 		    itask->it_idm_task->idt_transport_hdr,
1865 		    rx_pdu->isp_transport_hdrlen);
1866 	}
1867 
1868 	/*
1869 	 * Tell IDM about our new active task
1870 	 */
1871 	idm_task_start(itask->it_idm_task, (uintptr_t)itask->it_itt);
1872 
1873 	/*
1874 	 * If we have any immediate data then setup the immediate buffer
1875 	 * context that comes with the task
1876 	 */
1877 	if (rx_pdu->isp_datalen) {
1878 		ibuf = itask->it_immed_data;
1879 		ibuf->ibuf_immed_data_pdu = rx_pdu;
1880 		ibuf->ibuf_stmf_buf->db_data_size = rx_pdu->isp_datalen;
1881 		ibuf->ibuf_stmf_buf->db_buf_size = rx_pdu->isp_datalen;
1882 		ibuf->ibuf_stmf_buf->db_relative_offset = 0;
1883 		ibuf->ibuf_stmf_buf->db_sglist[0].seg_length =
1884 		    rx_pdu->isp_datalen;
1885 		ibuf->ibuf_stmf_buf->db_sglist[0].seg_addr = rx_pdu->isp_data;
1886 
1887 		DTRACE_ISCSI_8(xfer__start, idm_conn_t *, ic,
1888 		    uintptr_t, ibuf->ibuf_stmf_buf->db_sglist[0].seg_addr,
1889 		    uint32_t, ibuf->ibuf_stmf_buf->db_relative_offset,
1890 		    uint64_t, 0, uint32_t, 0, uint32_t, 0, /* no raddr */
1891 		    uint32_t, rx_pdu->isp_datalen, int, XFER_BUF_TX_TO_INI);
1892 
1893 		stmf_post_task(task, ibuf->ibuf_stmf_buf);
1894 
1895 		DTRACE_ISCSI_8(xfer__done, idm_conn_t *, ic,
1896 		    uintptr_t, ibuf->ibuf_stmf_buf->db_sglist[0].seg_addr,
1897 		    uint32_t, ibuf->ibuf_stmf_buf->db_relative_offset,
1898 		    uint64_t, 0, uint32_t, 0, uint32_t, 0, /* no raddr */
1899 		    uint32_t, rx_pdu->isp_datalen, int, XFER_BUF_TX_TO_INI);
1900 	} else {
1901 		stmf_post_task(task, NULL);
1902 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1903 	}
1904 }
1905 
1906 /*ARGSUSED*/
1907 void
1908 iscsit_deferred_dispatch(idm_pdu_t *rx_pdu)
1909 {
1910 	iscsit_conn_t *ict = rx_pdu->isp_ic->ic_handle;
1911 
1912 	/*
1913 	 * If the connection has been lost then ignore new PDU's
1914 	 */
1915 	mutex_enter(&ict->ict_mutex);
1916 	if (ict->ict_lost) {
1917 		mutex_exit(&ict->ict_mutex);
1918 		idm_pdu_complete(rx_pdu, IDM_STATUS_FAIL);
1919 		return;
1920 	}
1921 
1922 	/*
1923 	 * Grab a hold on the connection to prevent it from going away
1924 	 * between now and when the taskq function is called.
1925 	 */
1926 	iscsit_conn_dispatch_hold(ict);
1927 	mutex_exit(&ict->ict_mutex);
1928 
1929 	if (taskq_dispatch(iscsit_global.global_dispatch_taskq,
1930 	    iscsit_deferred, rx_pdu, DDI_NOSLEEP) == NULL) {
1931 		/*
1932 		 * In the unlikely scenario that we couldn't get the resources
1933 		 * to dispatch the PDU then just drop it.
1934 		 */
1935 		idm_pdu_complete(rx_pdu, IDM_STATUS_FAIL);
1936 		idm_conn_event(ict->ict_ic, CE_TRANSPORT_FAIL, NULL);
1937 		iscsit_conn_dispatch_rele(ict);
1938 	}
1939 }
1940 
1941 static void
1942 iscsit_deferred(void *rx_pdu_void)
1943 {
1944 	idm_pdu_t *rx_pdu = rx_pdu_void;
1945 	idm_conn_t *ic = rx_pdu->isp_ic;
1946 	iscsit_conn_t *ict = ic->ic_handle;
1947 
1948 	switch (IDM_PDU_OPCODE(rx_pdu)) {
1949 	case ISCSI_OP_NOOP_OUT:
1950 		iscsit_set_cmdsn(ict, rx_pdu);
1951 		iscsit_pdu_op_noop(ict, rx_pdu);
1952 		break;
1953 	case ISCSI_OP_LOGIN_CMD:
1954 		iscsit_pdu_op_login_cmd(ict, rx_pdu);
1955 		break;
1956 	case ISCSI_OP_TEXT_CMD:
1957 		iscsit_set_cmdsn(ict, rx_pdu);
1958 		iscsit_pdu_op_text_cmd(ict, rx_pdu);
1959 		break;
1960 	case ISCSI_OP_LOGOUT_CMD:
1961 		iscsit_set_cmdsn(ict, rx_pdu);
1962 		iscsit_pdu_op_logout_cmd(ict, rx_pdu);
1963 		break;
1964 	default:
1965 		/* Protocol error.  IDM should have caught this */
1966 		idm_pdu_complete(rx_pdu, IDM_STATUS_FAIL);
1967 		ASSERT(0);
1968 		break;
1969 	}
1970 
1971 	iscsit_conn_dispatch_rele(ict);
1972 }
1973 
1974 static void
1975 iscsit_send_direct_scsi_resp(iscsit_conn_t *ict, idm_pdu_t *rx_pdu,
1976     uint8_t response, uint8_t cmd_status)
1977 {
1978 	idm_pdu_t			*rsp_pdu;
1979 	idm_conn_t			*ic;
1980 	iscsi_scsi_rsp_hdr_t		*resp;
1981 	iscsi_scsi_cmd_hdr_t		*req =
1982 	    (iscsi_scsi_cmd_hdr_t *)rx_pdu->isp_hdr;
1983 
1984 	ic = ict->ict_ic;
1985 
1986 	rsp_pdu = idm_pdu_alloc(sizeof (iscsi_scsi_rsp_hdr_t), 0);
1987 	idm_pdu_init(rsp_pdu, ic, NULL, NULL);
1988 	resp = (iscsi_scsi_rsp_hdr_t *)rsp_pdu->isp_hdr;
1989 
1990 	resp->opcode = ISCSI_OP_SCSI_RSP;
1991 	resp->flags = ISCSI_FLAG_FINAL;
1992 	resp->response = response;
1993 	resp->cmd_status = cmd_status;
1994 	resp->itt = req->itt;
1995 	if ((response == ISCSI_STATUS_CMD_COMPLETED) &&
1996 	    (req->data_length != 0) &&
1997 	    ((req->flags & ISCSI_FLAG_CMD_READ) ||
1998 	    (req->flags & ISCSI_FLAG_CMD_WRITE))) {
1999 		resp->flags |= ISCSI_FLAG_CMD_UNDERFLOW;
2000 		resp->residual_count = req->data_length;
2001 	}
2002 
2003 	DTRACE_PROBE4(iscsi__scsi__direct__response,
2004 	    iscsit_conn_t *, ict,
2005 	    uint8_t, resp->response,
2006 	    uint8_t, resp->cmd_status,
2007 	    idm_pdu_t *, rsp_pdu);
2008 
2009 	iscsit_pdu_tx(rsp_pdu);
2010 }
2011 
2012 void
2013 iscsit_send_task_mgmt_resp(idm_pdu_t *tm_resp_pdu, uint8_t tm_status)
2014 {
2015 	iscsi_scsi_task_mgt_rsp_hdr_t	*tm_resp;
2016 
2017 	tm_resp = (iscsi_scsi_task_mgt_rsp_hdr_t *)tm_resp_pdu->isp_hdr;
2018 	tm_resp->response = tm_status;
2019 
2020 	DTRACE_PROBE3(iscsi__scsi__tm__response,
2021 	    iscsit_conn_t *, tm_resp_pdu->isp_ic->ic_handle,
2022 	    uint8_t, tm_resp->response,
2023 	    idm_pdu_t *, tm_resp_pdu);
2024 	iscsit_pdu_tx(tm_resp_pdu);
2025 }
2026 
2027 void
2028 iscsit_op_scsi_task_mgmt(iscsit_conn_t *ict, idm_pdu_t *rx_pdu)
2029 {
2030 	idm_pdu_t			*tm_resp_pdu;
2031 	iscsit_task_t			*itask;
2032 	iscsit_task_t			*tm_itask;
2033 	scsi_task_t			*task;
2034 	iscsi_scsi_task_mgt_hdr_t 	*iscsi_tm =
2035 	    (iscsi_scsi_task_mgt_hdr_t *)rx_pdu->isp_hdr;
2036 	iscsi_scsi_task_mgt_rsp_hdr_t 	*iscsi_tm_rsp =
2037 	    (iscsi_scsi_task_mgt_rsp_hdr_t *)rx_pdu->isp_hdr;
2038 	uint32_t			rtt, cmdsn, refcmdsn;
2039 	uint8_t				tm_func;
2040 
2041 	/*
2042 	 * Setup response PDU (response field will get filled in later)
2043 	 */
2044 	tm_resp_pdu = idm_pdu_alloc(sizeof (iscsi_scsi_task_mgt_rsp_hdr_t), 0);
2045 	if (tm_resp_pdu == NULL) {
2046 		/* Can't respond, just drop it */
2047 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2048 		return;
2049 	}
2050 	idm_pdu_init(tm_resp_pdu, ict->ict_ic, NULL, NULL);
2051 	iscsi_tm_rsp = (iscsi_scsi_task_mgt_rsp_hdr_t *)tm_resp_pdu->isp_hdr;
2052 	bzero(iscsi_tm_rsp, sizeof (iscsi_scsi_task_mgt_rsp_hdr_t));
2053 	iscsi_tm_rsp->opcode = ISCSI_OP_SCSI_TASK_MGT_RSP;
2054 	iscsi_tm_rsp->flags = ISCSI_FLAG_FINAL;
2055 	iscsi_tm_rsp->itt = rx_pdu->isp_hdr->itt;
2056 
2057 	/*
2058 	 * Figure out what we're being asked to do.
2059 	 */
2060 	DTRACE_PROBE4(iscsi__scsi__tm__request,
2061 	    iscsit_conn_t *, ict,
2062 	    uint8_t, (iscsi_tm->function & ISCSI_FLAG_TASK_MGMT_FUNCTION_MASK),
2063 	    uint32_t, iscsi_tm->rtt,
2064 	    idm_pdu_t *, rx_pdu);
2065 	switch (iscsi_tm->function & ISCSI_FLAG_TASK_MGMT_FUNCTION_MASK) {
2066 	case ISCSI_TM_FUNC_ABORT_TASK:
2067 		/*
2068 		 * STMF doesn't currently support the "abort task" task
2069 		 * management command although it does support aborting
2070 		 * an individual task.  We'll get STMF to abort the task
2071 		 * for us but handle the details of the task management
2072 		 * command ourselves.
2073 		 *
2074 		 * Find the task associated with the referenced task tag.
2075 		 */
2076 		rtt = iscsi_tm->rtt;
2077 		itask = (iscsit_task_t *)idm_task_find_by_handle(ict->ict_ic,
2078 		    (uintptr_t)rtt);
2079 
2080 		if (itask == NULL) {
2081 			cmdsn = ntohl(iscsi_tm->cmdsn);
2082 			refcmdsn = ntohl(iscsi_tm->refcmdsn);
2083 
2084 			/*
2085 			 * Task was not found.  If RefCmdSN is within the CmdSN
2086 			 * window and less than CmdSN of the TM function, return
2087 			 * "Function Complete".  Otherwise, return
2088 			 * "Task Does Not Exist".
2089 			 */
2090 
2091 			if (iscsit_cmdsn_in_window(ict, refcmdsn) &&
2092 			    (refcmdsn < cmdsn)) {
2093 				iscsit_send_task_mgmt_resp(tm_resp_pdu,
2094 				    SCSI_TCP_TM_RESP_COMPLETE);
2095 			} else {
2096 				iscsit_send_task_mgmt_resp(tm_resp_pdu,
2097 				    SCSI_TCP_TM_RESP_NO_TASK);
2098 			}
2099 		} else {
2100 
2101 			/*
2102 			 * Tell STMF to abort the task.  This will do no harm
2103 			 * if the task is already complete.
2104 			 */
2105 			stmf_abort(STMF_QUEUE_TASK_ABORT, itask->it_stmf_task,
2106 			    STMF_ABORTED, NULL);
2107 
2108 			/*
2109 			 * Make sure the task hasn't already completed
2110 			 */
2111 			mutex_enter(&itask->it_idm_task->idt_mutex);
2112 			if ((itask->it_idm_task->idt_state == TASK_COMPLETE) ||
2113 			    (itask->it_idm_task->idt_state == TASK_IDLE)) {
2114 				/*
2115 				 * Task is complete, return "Task Does Not
2116 				 * Exist"
2117 				 */
2118 				mutex_exit(&itask->it_idm_task->idt_mutex);
2119 				iscsit_send_task_mgmt_resp(tm_resp_pdu,
2120 				    SCSI_TCP_TM_RESP_NO_TASK);
2121 			} else {
2122 				/*
2123 				 * STMF is now aborting the task, return
2124 				 * "Function Complete"
2125 				 */
2126 				mutex_exit(&itask->it_idm_task->idt_mutex);
2127 				iscsit_send_task_mgmt_resp(tm_resp_pdu,
2128 				    SCSI_TCP_TM_RESP_COMPLETE);
2129 			}
2130 			idm_task_rele(itask->it_idm_task);
2131 		}
2132 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2133 		return;
2134 
2135 	case ISCSI_TM_FUNC_ABORT_TASK_SET:
2136 		tm_func = TM_ABORT_TASK_SET;
2137 		break;
2138 
2139 	case ISCSI_TM_FUNC_CLEAR_ACA:
2140 		tm_func = TM_CLEAR_ACA;
2141 		break;
2142 
2143 	case ISCSI_TM_FUNC_CLEAR_TASK_SET:
2144 		tm_func = TM_CLEAR_TASK_SET;
2145 		break;
2146 
2147 	case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
2148 		tm_func = TM_LUN_RESET;
2149 		break;
2150 
2151 	case ISCSI_TM_FUNC_TARGET_WARM_RESET:
2152 		tm_func = TM_TARGET_WARM_RESET;
2153 		break;
2154 
2155 	case ISCSI_TM_FUNC_TARGET_COLD_RESET:
2156 		tm_func = TM_TARGET_COLD_RESET;
2157 		break;
2158 
2159 	case ISCSI_TM_FUNC_TASK_REASSIGN:
2160 		/*
2161 		 * We do not currently support allegiance reassignment.  When
2162 		 * we start supporting ERL1+, we will need to.
2163 		 */
2164 		iscsit_send_task_mgmt_resp(tm_resp_pdu,
2165 		    SCSI_TCP_TM_RESP_NO_ALLG_REASSN);
2166 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2167 		return;
2168 
2169 	default:
2170 		iscsit_send_task_mgmt_resp(tm_resp_pdu,
2171 		    SCSI_TCP_TM_RESP_REJECTED);
2172 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2173 		return;
2174 	}
2175 
2176 	tm_itask = iscsit_tm_task_alloc(ict);
2177 	if (tm_itask == NULL) {
2178 		iscsit_send_task_mgmt_resp(tm_resp_pdu,
2179 		    SCSI_TCP_TM_RESP_REJECTED);
2180 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2181 		return;
2182 	}
2183 
2184 
2185 	task = stmf_task_alloc(ict->ict_sess->ist_lport,
2186 	    ict->ict_sess->ist_stmf_sess, iscsi_tm->lun,
2187 	    0, STMF_TASK_EXT_NONE);
2188 	if (task == NULL) {
2189 		/*
2190 		 * If this happens, either the LU is in reset, couldn't
2191 		 * get memory, or some other condition in which we simply
2192 		 * can't complete this request.  It would be nice to return
2193 		 * an error code like "busy" but the closest we have is
2194 		 * "rejected".
2195 		 */
2196 		iscsit_send_task_mgmt_resp(tm_resp_pdu,
2197 		    SCSI_TCP_TM_RESP_REJECTED);
2198 		iscsit_tm_task_free(tm_itask);
2199 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2200 		return;
2201 	}
2202 
2203 	tm_itask->it_tm_pdu = tm_resp_pdu;
2204 	tm_itask->it_stmf_task = task;
2205 	task->task_port_private = tm_itask;
2206 	task->task_mgmt_function = tm_func;
2207 	task->task_additional_flags = TASK_AF_NO_EXPECTED_XFER_LENGTH;
2208 	task->task_priority = 0;
2209 	task->task_max_nbufs = STMF_BUFS_MAX;
2210 	task->task_cmd_seq_no = iscsi_tm->itt;
2211 	task->task_expected_xfer_length = 0;
2212 
2213 	stmf_post_task(task, NULL);
2214 	idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2215 }
2216 
2217 static void
2218 iscsit_pdu_op_noop(iscsit_conn_t *ict, idm_pdu_t *rx_pdu)
2219 {
2220 	iscsi_nop_out_hdr_t *out = (iscsi_nop_out_hdr_t *)rx_pdu->isp_hdr;
2221 	iscsi_nop_in_hdr_t *in;
2222 	int resp_datalen;
2223 	idm_pdu_t *resp;
2224 
2225 	/* Ignore the response from initiator */
2226 	if ((out->itt == ISCSI_RSVD_TASK_TAG) ||
2227 	    (out->ttt != ISCSI_RSVD_TASK_TAG)) {
2228 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2229 		return;
2230 	}
2231 
2232 	/* Allocate a PDU to respond */
2233 	resp_datalen = ntoh24(out->dlength);
2234 	resp = idm_pdu_alloc(sizeof (iscsi_hdr_t), resp_datalen);
2235 	idm_pdu_init(resp, ict->ict_ic, NULL, NULL);
2236 	if (resp_datalen > 0) {
2237 		bcopy(rx_pdu->isp_data, resp->isp_data, resp_datalen);
2238 	}
2239 
2240 	in = (iscsi_nop_in_hdr_t *)resp->isp_hdr;
2241 	bzero(in, sizeof (*in));
2242 	in->opcode = ISCSI_OP_NOOP_IN;
2243 	in->flags = ISCSI_FLAG_FINAL;
2244 	bcopy(out->lun, in->lun, 8);
2245 	in->itt		= out->itt;
2246 	in->ttt		= ISCSI_RSVD_TASK_TAG;
2247 	hton24(in->dlength, resp_datalen);
2248 
2249 	/* Any other field in resp to be set? */
2250 	iscsit_pdu_tx(resp);
2251 	idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2252 }
2253 
2254 static void
2255 iscsit_pdu_op_login_cmd(iscsit_conn_t	*ict, idm_pdu_t *rx_pdu)
2256 {
2257 
2258 	/*
2259 	 * Submit PDU to login state machine.  State machine will free the
2260 	 * PDU.
2261 	 */
2262 	iscsit_login_sm_event(ict, ILE_LOGIN_RCV, rx_pdu);
2263 }
2264 
2265 void
2266 iscsit_pdu_op_logout_cmd(iscsit_conn_t	*ict, idm_pdu_t *rx_pdu)
2267 {
2268 	iscsi_logout_hdr_t 	*logout_req =
2269 	    (iscsi_logout_hdr_t *)rx_pdu->isp_hdr;
2270 	iscsi_logout_rsp_hdr_t	*logout_rsp;
2271 	idm_pdu_t *resp;
2272 
2273 	/* Allocate a PDU to respond */
2274 	resp = idm_pdu_alloc(sizeof (iscsi_hdr_t), 0);
2275 	idm_pdu_init(resp, ict->ict_ic, NULL, NULL);
2276 
2277 	/*
2278 	 * Logout results in the immediate termination of all tasks except
2279 	 * if the logout reason is ISCSI_LOGOUT_REASON_RECOVERY.  The
2280 	 * connection state machine will drive this task cleanup automatically
2281 	 * so we don't need to handle that here.
2282 	 */
2283 	logout_rsp = (iscsi_logout_rsp_hdr_t *)resp->isp_hdr;
2284 	bzero(logout_rsp, sizeof (*logout_rsp));
2285 	logout_rsp->opcode = ISCSI_OP_LOGOUT_RSP;
2286 	logout_rsp->flags = ISCSI_FLAG_FINAL;
2287 	logout_rsp->itt = logout_req->itt;
2288 	if ((logout_req->flags & ISCSI_FLAG_LOGOUT_REASON_MASK) >
2289 	    ISCSI_LOGOUT_REASON_RECOVERY) {
2290 		logout_rsp->response = ISCSI_LOGOUT_RECOVERY_UNSUPPORTED;
2291 	} else {
2292 		logout_rsp->response = ISCSI_LOGOUT_SUCCESS;
2293 	}
2294 
2295 	iscsit_pdu_tx(resp);
2296 	idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2297 }
2298 
2299 /*
2300  * Calculate the number of outstanding commands we can process
2301  */
2302 int
2303 iscsit_cmd_window()
2304 {
2305 	/* Will be better later */
2306 	return	(1024);
2307 }
2308 
2309 /*
2310  * Set local registers based on incoming PDU
2311  */
2312 void
2313 iscsit_set_cmdsn(iscsit_conn_t *ict, idm_pdu_t *rx_pdu)
2314 {
2315 	iscsit_sess_t *ist;
2316 	iscsi_scsi_cmd_hdr_t *req;
2317 
2318 	ist = ict->ict_sess;
2319 
2320 	req = (iscsi_scsi_cmd_hdr_t *)rx_pdu->isp_hdr;
2321 
2322 	rw_enter(&ist->ist_sn_rwlock, RW_WRITER);
2323 	ist->ist_expcmdsn = ntohl(req->cmdsn) + 1;
2324 	ist->ist_maxcmdsn = ntohl(req->cmdsn) + iscsit_cmd_window();
2325 	rw_exit(&ist->ist_sn_rwlock);
2326 }
2327 
2328 /*
2329  * Update local StatSN and set SNs in response
2330  */
2331 static void
2332 iscsit_calc_rspsn(iscsit_conn_t *ict, idm_pdu_t *resp)
2333 {
2334 	iscsit_sess_t *ist;
2335 	iscsi_scsi_rsp_hdr_t *rsp;
2336 
2337 	/* Get iSCSI session handle */
2338 	ist = ict->ict_sess;
2339 
2340 	rsp = (iscsi_scsi_rsp_hdr_t *)resp->isp_hdr;
2341 
2342 	/* Update StatSN */
2343 	rsp->statsn = htonl(ict->ict_statsn);
2344 	switch (IDM_PDU_OPCODE(resp)) {
2345 	case ISCSI_OP_RTT_RSP:
2346 		/* Do nothing */
2347 		break;
2348 	case ISCSI_OP_NOOP_IN:
2349 		/*
2350 		 * Refer to section 10.19.1, RFC3720.
2351 		 * Advance only if target is responding initiator
2352 		 */
2353 		if (((iscsi_nop_in_hdr_t *)rsp)->ttt == ISCSI_RSVD_TASK_TAG)
2354 			ict->ict_statsn++;
2355 		break;
2356 	case ISCSI_OP_SCSI_DATA_RSP:
2357 		if (rsp->flags & ISCSI_FLAG_DATA_STATUS)
2358 			ict->ict_statsn++;
2359 		else
2360 			rsp->statsn = 0;
2361 		break;
2362 	default:
2363 		ict->ict_statsn++;
2364 		break;
2365 	}
2366 
2367 	/* Set ExpCmdSN and MaxCmdSN */
2368 	rsp->maxcmdsn = htonl(ist->ist_maxcmdsn);
2369 	rsp->expcmdsn = htonl(ist->ist_expcmdsn);
2370 }
2371 
2372 /*
2373  * Wrapper funtion, calls iscsi_calc_rspsn and idm_pdu_tx
2374  */
2375 void
2376 iscsit_pdu_tx(idm_pdu_t *pdu)
2377 {
2378 	iscsit_conn_t *ict = pdu->isp_ic->ic_handle;
2379 
2380 	/*
2381 	 * Protect ict->ict_statsn, ist->ist_maxcmdsn, and ist->ist_expcmdsn
2382 	 * (which are used by iscsit_calc_rspsn) with the session mutex
2383 	 * (ist->ist_sn_mutex).
2384 	 */
2385 	rw_enter(&ict->ict_sess->ist_sn_rwlock, RW_WRITER);
2386 	iscsit_calc_rspsn(ict, pdu);
2387 	idm_pdu_tx(pdu);
2388 	rw_exit(&ict->ict_sess->ist_sn_rwlock);
2389 }
2390 
2391 /*
2392  * Internal functions
2393  */
2394 
2395 void
2396 iscsit_send_async_event(iscsit_conn_t *ict, uint8_t event)
2397 {
2398 	idm_pdu_t		*abt;
2399 	iscsi_async_evt_hdr_t	*async_abt;
2400 
2401 	/*
2402 	 * Get a PDU to build the abort request.
2403 	 */
2404 	abt = idm_pdu_alloc(sizeof (iscsi_hdr_t), 0);
2405 	if (abt == NULL) {
2406 		idm_conn_event(ict->ict_ic, CE_TRANSPORT_FAIL, NULL);
2407 		return;
2408 	}
2409 
2410 	idm_pdu_init(abt, ict->ict_ic, NULL, NULL);
2411 	abt->isp_datalen = 0;
2412 
2413 	async_abt = (iscsi_async_evt_hdr_t *)abt->isp_hdr;
2414 	bzero(async_abt, sizeof (*async_abt));
2415 	async_abt->opcode = ISCSI_OP_ASYNC_EVENT;
2416 	async_abt->async_event = event;
2417 	async_abt->flags = ISCSI_FLAG_FINAL;
2418 	async_abt->rsvd4[0] = 0xff;
2419 	async_abt->rsvd4[1] = 0xff;
2420 	async_abt->rsvd4[2] = 0xff;
2421 	async_abt->rsvd4[3] = 0xff;
2422 
2423 	switch (event) {
2424 	case ISCSI_ASYNC_EVENT_REQUEST_LOGOUT:
2425 		async_abt->param3 = htons(IDM_LOGOUT_SECONDS);
2426 		break;
2427 	case ISCSI_ASYNC_EVENT_SCSI_EVENT:
2428 	case ISCSI_ASYNC_EVENT_DROPPING_CONNECTION:
2429 	case ISCSI_ASYNC_EVENT_DROPPING_ALL_CONNECTIONS:
2430 	case ISCSI_ASYNC_EVENT_PARAM_NEGOTIATION:
2431 	default:
2432 		ASSERT(0);
2433 	}
2434 
2435 	iscsit_pdu_tx(abt);
2436 }
2437 
2438 void
2439 iscsit_send_reject(iscsit_conn_t *ict, idm_pdu_t *rejected_pdu, uint8_t reason)
2440 {
2441 	idm_pdu_t		*reject_pdu;
2442 	iscsi_reject_rsp_hdr_t	*reject;
2443 
2444 	/*
2445 	 * Get a PDU to build the abort request.
2446 	 */
2447 	reject_pdu = idm_pdu_alloc(sizeof (iscsi_hdr_t),
2448 	    rejected_pdu->isp_hdrlen);
2449 	if (reject_pdu == NULL) {
2450 		idm_conn_event(ict->ict_ic, CE_TRANSPORT_FAIL, NULL);
2451 		return;
2452 	}
2453 	idm_pdu_init(reject_pdu, ict->ict_ic, NULL, NULL);
2454 
2455 	reject_pdu->isp_datalen = rejected_pdu->isp_hdrlen;
2456 	bcopy(rejected_pdu->isp_hdr, reject_pdu->isp_data,
2457 	    rejected_pdu->isp_hdrlen);
2458 
2459 	reject = (iscsi_reject_rsp_hdr_t *)reject_pdu->isp_hdr;
2460 	bzero(reject, sizeof (*reject));
2461 	reject->opcode = ISCSI_OP_REJECT_MSG;
2462 	reject->reason = reason;
2463 	reject->flags = ISCSI_FLAG_FINAL;
2464 	hton24(reject->dlength, rejected_pdu->isp_hdrlen);
2465 	reject->must_be_ff[0] = 0xff;
2466 	reject->must_be_ff[1] = 0xff;
2467 	reject->must_be_ff[2] = 0xff;
2468 	reject->must_be_ff[3] = 0xff;
2469 
2470 	iscsit_pdu_tx(reject_pdu);
2471 }
2472 
2473 
2474 static iscsit_task_t *
2475 iscsit_task_alloc(iscsit_conn_t *ict)
2476 {
2477 	iscsit_task_t *itask;
2478 	iscsit_buf_t *immed_ibuf;
2479 
2480 	/*
2481 	 * Possible items to pre-alloc if we cache iscsit_task_t's:
2482 	 *
2483 	 * Status PDU w/ sense buffer
2484 	 * stmf_data_buf_t for immediate data
2485 	 */
2486 	itask = kmem_alloc(sizeof (iscsit_task_t) + sizeof (iscsit_buf_t) +
2487 	    sizeof (stmf_data_buf_t), KM_NOSLEEP);
2488 	if (itask != NULL) {
2489 		mutex_init(&itask->it_mutex, NULL, MUTEX_DRIVER, NULL);
2490 		itask->it_aborted = itask->it_stmf_abort =
2491 		    itask->it_tm_task = 0;
2492 
2493 		immed_ibuf = (iscsit_buf_t *)(itask + 1);
2494 		bzero(immed_ibuf, sizeof (*immed_ibuf));
2495 		immed_ibuf->ibuf_is_immed = B_TRUE;
2496 		immed_ibuf->ibuf_stmf_buf = (stmf_data_buf_t *)(immed_ibuf + 1);
2497 
2498 		bzero(immed_ibuf->ibuf_stmf_buf, sizeof (stmf_data_buf_t));
2499 		immed_ibuf->ibuf_stmf_buf->db_port_private = immed_ibuf;
2500 		immed_ibuf->ibuf_stmf_buf->db_sglist_length = 1;
2501 		immed_ibuf->ibuf_stmf_buf->db_flags = DB_DIRECTION_FROM_RPORT |
2502 		    DB_DONT_CACHE;
2503 		itask->it_immed_data = immed_ibuf;
2504 		itask->it_idm_task = idm_task_alloc(ict->ict_ic);
2505 		if (itask->it_idm_task != NULL) {
2506 			itask->it_idm_task->idt_private = itask;
2507 			itask->it_ict = ict;
2508 			itask->it_ttt = itask->it_idm_task->idt_tt;
2509 			return (itask);
2510 		} else {
2511 			kmem_free(itask, sizeof (iscsit_task_t) +
2512 			    sizeof (iscsit_buf_t) + sizeof (stmf_data_buf_t));
2513 		}
2514 	}
2515 
2516 	return (NULL);
2517 }
2518 
2519 static void
2520 iscsit_task_free(iscsit_task_t *itask)
2521 {
2522 	idm_task_free(itask->it_idm_task);
2523 	mutex_destroy(&itask->it_mutex);
2524 	kmem_free(itask, sizeof (iscsit_task_t) +
2525 	    sizeof (iscsit_buf_t) + sizeof (stmf_data_buf_t));
2526 }
2527 
2528 static iscsit_task_t *
2529 iscsit_tm_task_alloc(iscsit_conn_t *ict)
2530 {
2531 	iscsit_task_t *itask;
2532 
2533 	itask = kmem_zalloc(sizeof (iscsit_task_t), KM_NOSLEEP);
2534 	if (itask != NULL) {
2535 		idm_conn_hold(ict->ict_ic);
2536 		mutex_init(&itask->it_mutex, NULL, MUTEX_DRIVER, NULL);
2537 		itask->it_aborted = itask->it_stmf_abort =
2538 		    itask->it_tm_responded = 0;
2539 		itask->it_tm_pdu = NULL;
2540 		itask->it_tm_task = 1;
2541 		itask->it_ict = ict;
2542 	}
2543 
2544 	return (itask);
2545 }
2546 
2547 static void
2548 iscsit_tm_task_free(iscsit_task_t *itask)
2549 {
2550 	/*
2551 	 * If we responded then the call to idm_pdu_complete will free the
2552 	 * PDU.  Otherwise we got aborted before the TM function could
2553 	 * complete and we need to free the PDU explicitly.
2554 	 */
2555 	if (itask->it_tm_pdu != NULL && !itask->it_tm_responded)
2556 		idm_pdu_free(itask->it_tm_pdu);
2557 	idm_conn_rele(itask->it_ict->ict_ic);
2558 	mutex_destroy(&itask->it_mutex);
2559 	kmem_free(itask, sizeof (iscsit_task_t));
2560 }
2561 
2562 static idm_status_t
2563 iscsit_task_start(iscsit_task_t *itask)
2564 {
2565 	iscsit_sess_t *ist = itask->it_ict->ict_sess;
2566 	avl_index_t		where;
2567 
2568 	/*
2569 	 * Sanity check the ITT and ensure that this task does not already
2570 	 * exist.  If not then add the task to the session task list.
2571 	 */
2572 	mutex_enter(&ist->ist_mutex);
2573 	mutex_enter(&itask->it_mutex);
2574 	itask->it_active = 1;
2575 	if (avl_find(&ist->ist_task_list, itask, &where) == NULL) {
2576 		/* New task, add to AVL */
2577 		avl_insert(&ist->ist_task_list, itask, where);
2578 		mutex_exit(&itask->it_mutex);
2579 		mutex_exit(&ist->ist_mutex);
2580 		return (IDM_STATUS_SUCCESS);
2581 	}
2582 	mutex_exit(&itask->it_mutex);
2583 	mutex_exit(&ist->ist_mutex);
2584 
2585 	return (IDM_STATUS_REJECT);
2586 }
2587 
2588 static void
2589 iscsit_task_done(iscsit_task_t *itask)
2590 {
2591 	iscsit_sess_t *ist = itask->it_ict->ict_sess;
2592 
2593 	mutex_enter(&ist->ist_mutex);
2594 	mutex_enter(&itask->it_mutex);
2595 	if (itask->it_active) {
2596 		avl_remove(&ist->ist_task_list, itask);
2597 		itask->it_active = 0;
2598 	}
2599 	mutex_exit(&itask->it_mutex);
2600 	mutex_exit(&ist->ist_mutex);
2601 }
2602 
2603 /*
2604  * iscsit status PDU cache
2605  */
2606 
2607 /*ARGSUSED*/
2608 static int
2609 iscsit_status_pdu_constructor(void *pdu_void, void *arg, int flags)
2610 {
2611 	idm_pdu_t *pdu = pdu_void;
2612 	iscsi_scsi_rsp_hdr_t *rsp;
2613 
2614 	bzero(pdu, sizeof (idm_pdu_t));
2615 	pdu->isp_callback = iscsit_send_good_status_done;
2616 	pdu->isp_magic = IDM_PDU_MAGIC;
2617 	pdu->isp_hdr = (iscsi_hdr_t *)(pdu + 1); /* Ptr arithmetic */
2618 	pdu->isp_hdrlen = sizeof (iscsi_hdr_t);
2619 
2620 	/* Setup status response */
2621 	rsp = (iscsi_scsi_rsp_hdr_t *)pdu->isp_hdr;
2622 	bzero(rsp, sizeof (*rsp));
2623 	rsp->opcode = ISCSI_OP_SCSI_RSP;
2624 	rsp->flags = ISCSI_FLAG_FINAL;
2625 	rsp->response = ISCSI_STATUS_CMD_COMPLETED;
2626 
2627 	return (0);
2628 }
2629 
2630 /*
2631  * iscsit private data handler
2632  */
2633 
2634 /*ARGSUSED*/
2635 static void
2636 iscsit_pp_cb(struct stmf_port_provider *pp, int cmd, void *arg, uint32_t flags)
2637 {
2638 	it_config_t		*cfg;
2639 	nvlist_t		*nvl;
2640 
2641 	if ((cmd != STMF_PROVIDER_DATA_UPDATED) || (arg == NULL)) {
2642 		return;
2643 	}
2644 
2645 	nvl = (nvlist_t *)arg;
2646 
2647 	/* Translate nvlist */
2648 	if (it_nv_to_config(nvl, &cfg) != 0) {
2649 		cmn_err(CE_WARN, "Configuration is invalid");
2650 		return;
2651 	}
2652 
2653 	/* Update config */
2654 	(void) iscsit_config_merge(cfg);
2655 
2656 	it_config_free_cmn(cfg);
2657 }
2658 
2659 
2660 static it_cfg_status_t
2661 iscsit_config_merge(it_config_t *in_cfg)
2662 {
2663 	it_cfg_status_t	status;
2664 	it_config_t	*cfg;
2665 	it_config_t	tmp_cfg;
2666 	list_t		tpg_del_list;
2667 
2668 	if (in_cfg) {
2669 		cfg = in_cfg;
2670 	} else {
2671 		/* Make empty config */
2672 		bzero(&tmp_cfg, sizeof (tmp_cfg));
2673 		cfg = &tmp_cfg;
2674 	}
2675 
2676 	list_create(&tpg_del_list,  sizeof (iscsit_tpg_t),
2677 	    offsetof(iscsit_tpg_t, tpg_delete_ln));
2678 
2679 	/*
2680 	 * Update targets, initiator contexts, target portal groups,
2681 	 * and iSNS client
2682 	 */
2683 	ISCSIT_GLOBAL_LOCK(RW_WRITER);
2684 	if (((status = iscsit_config_merge_tpg(cfg, &tpg_del_list))
2685 	    != 0) ||
2686 	    ((status = iscsit_config_merge_tgt(cfg)) != 0) ||
2687 	    ((status = iscsit_config_merge_ini(cfg)) != 0) ||
2688 	    ((status = isnst_config_merge(cfg)) != 0)) {
2689 		ISCSIT_GLOBAL_UNLOCK();
2690 		return (status);
2691 	}
2692 
2693 	/* Update other global config parameters */
2694 	if (iscsit_global.global_props) {
2695 		nvlist_free(iscsit_global.global_props);
2696 		iscsit_global.global_props = NULL;
2697 	}
2698 	if (in_cfg) {
2699 		(void) nvlist_dup(cfg->config_global_properties,
2700 		    &iscsit_global.global_props, KM_SLEEP);
2701 	}
2702 	ISCSIT_GLOBAL_UNLOCK();
2703 
2704 	iscsit_config_destroy_tpgs(&tpg_del_list);
2705 
2706 	list_destroy(&tpg_del_list);
2707 
2708 	return (ITCFG_SUCCESS);
2709 }
2710 
2711 /*
2712  * iscsit_sna_lt[e]
2713  *
2714  * Compare serial numbers using serial number arithmetic as defined in
2715  * RFC 1982.
2716  *
2717  * NOTE: This code is duplicated in the isns server as well as iscsitgtd.  It
2718  * ought to be common.
2719  */
2720 
2721 static int
2722 iscsit_sna_lt(uint32_t sn1, uint32_t sn2)
2723 {
2724 	return ((sn1 != sn2) &&
2725 	    (((sn1 < sn2) && ((sn2 - sn1) < ISCSIT_SNA32_CHECK)) ||
2726 	    ((sn1 > sn2) && ((sn1 - sn2) > ISCSIT_SNA32_CHECK))));
2727 }
2728 
2729 static int
2730 iscsit_sna_lte(uint32_t sn1, uint32_t sn2)
2731 {
2732 	return ((sn1 == sn2) ||
2733 	    (((sn1 < sn2) && ((sn2 - sn1) < ISCSIT_SNA32_CHECK)) ||
2734 	    ((sn1 > sn2) && ((sn1 - sn2) > ISCSIT_SNA32_CHECK))));
2735 }
2736 
2737 
2738 static boolean_t
2739 iscsit_cmdsn_in_window(iscsit_conn_t *ict, uint32_t cmdsn)
2740 {
2741 	iscsit_sess_t	*ist = ict->ict_sess;
2742 	int		rval = B_TRUE;
2743 
2744 	ist = ict->ict_sess;
2745 
2746 	rw_enter(&ist->ist_sn_rwlock, RW_READER);
2747 
2748 	/*
2749 	 * If cmdsn is less than ist_expcmdsn - iscsit_cmd_window() or
2750 	 * greater than ist_expcmdsn, it's not in the window.
2751 	 */
2752 
2753 	if (iscsit_sna_lt(cmdsn, (ist->ist_expcmdsn - iscsit_cmd_window())) ||
2754 	    !iscsit_sna_lte(cmdsn, ist->ist_expcmdsn)) {
2755 		rval = B_FALSE;
2756 	}
2757 
2758 	rw_exit(&ist->ist_sn_rwlock);
2759 
2760 	return (rval);
2761 }
2762