xref: /illumos-gate/usr/src/uts/common/io/comstar/port/iscsit/iscsit.c (revision 17f1e64a433a4ca00ffed7539e10c297580a7002)
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 		/*
1323 		 * IDM will call iscsit_build_hdr so lock now to serialize
1324 		 * access to the SN values.  We need to lock here to enforce
1325 		 * lock ordering
1326 		 */
1327 		rw_enter(&iscsit_task->it_ict->ict_sess->ist_sn_rwlock,
1328 		    RW_READER);
1329 		idm_rc = idm_buf_tx_to_ini(iscsit_task->it_idm_task,
1330 		    ibuf->ibuf_idm_buf, dbuf->db_relative_offset,
1331 		    dbuf->db_data_size, &iscsit_buf_xfer_cb, dbuf);
1332 		rw_exit(&iscsit_task->it_ict->ict_sess->ist_sn_rwlock);
1333 
1334 		return (iscsit_idm_to_stmf(idm_rc));
1335 	} else if (dbuf->db_flags & DB_DIRECTION_FROM_RPORT) {
1336 		/* Grab the SN lock (see comment above) */
1337 		rw_enter(&iscsit_task->it_ict->ict_sess->ist_sn_rwlock,
1338 		    RW_READER);
1339 		idm_rc = idm_buf_rx_from_ini(iscsit_task->it_idm_task,
1340 		    ibuf->ibuf_idm_buf, dbuf->db_relative_offset,
1341 		    dbuf->db_data_size, &iscsit_buf_xfer_cb, dbuf);
1342 		rw_exit(&iscsit_task->it_ict->ict_sess->ist_sn_rwlock);
1343 
1344 		return (iscsit_idm_to_stmf(idm_rc));
1345 	}
1346 
1347 	/* What are we supposed to do if there is no direction? */
1348 	return (STMF_INVALID_ARG);
1349 }
1350 
1351 static void
1352 iscsit_buf_xfer_cb(idm_buf_t *idb, idm_status_t status)
1353 {
1354 	iscsit_task_t *itask = idb->idb_task_binding->idt_private;
1355 	stmf_data_buf_t *dbuf = idb->idb_cb_arg;
1356 
1357 	dbuf->db_xfer_status = iscsit_idm_to_stmf(status);
1358 
1359 	/*
1360 	 * If the task has been aborted then we don't need to call STMF
1361 	 */
1362 	if (itask->it_stmf_abort) {
1363 		return;
1364 	}
1365 
1366 	/*
1367 	 * COMSTAR currently requires port providers to support
1368 	 * the DB_SEND_STATUS_GOOD flag even if phase collapse is
1369 	 * not supported.  So we will roll our own... pretend we are
1370 	 * COMSTAR and ask for a status PDU.
1371 	 */
1372 	if ((dbuf->db_flags & DB_SEND_STATUS_GOOD) &&
1373 	    status == IDM_STATUS_SUCCESS) {
1374 		/*
1375 		 * If iscsit_send_scsi_status succeeds then the TX PDU
1376 		 * callback will call stmf_send_status_done and set
1377 		 * STMF_IOF_LPORT_DONE.  Consequently we don't need
1378 		 * to call stmf_data_xfer_done in that case.  We
1379 		 * still need to call it if we get a failure.
1380 		 *
1381 		 * To elaborate on this some more, upon successful
1382 		 * return from iscsit_send_scsi_status it's possible
1383 		 * that itask and idb have been freed and are no
1384 		 * longer valid.
1385 		 */
1386 		if (iscsit_send_scsi_status(itask->it_stmf_task, 0)
1387 		    != STMF_SUCCESS) {
1388 			/* Failed to send status */
1389 			dbuf->db_xfer_status = STMF_FAILURE;
1390 			stmf_data_xfer_done(itask->it_stmf_task, dbuf,
1391 			    STMF_IOF_LPORT_DONE);
1392 		}
1393 	} else {
1394 		stmf_data_xfer_done(itask->it_stmf_task, dbuf, 0);
1395 	}
1396 }
1397 
1398 
1399 /*ARGSUSED*/
1400 stmf_status_t
1401 iscsit_send_scsi_status(scsi_task_t *task, uint32_t ioflags)
1402 {
1403 	iscsit_task_t *itask = task->task_port_private;
1404 	iscsi_scsi_rsp_hdr_t *rsp;
1405 	idm_pdu_t *pdu;
1406 	int resp_datalen;
1407 
1408 	/*
1409 	 * If this task is aborted then we don't need to respond.
1410 	 */
1411 	if (itask->it_stmf_abort) {
1412 		return (STMF_SUCCESS);
1413 	}
1414 
1415 	/*
1416 	 * If this is a task management status, handle it elsewhere.
1417 	 */
1418 	if (task->task_mgmt_function != TM_NONE) {
1419 		/*
1420 		 * Don't wait for the PDU completion to tell STMF
1421 		 * the task is done -- it doesn't really matter and
1422 		 * it makes life complicated if STMF later asks us to
1423 		 * abort the request and we don't know whether the
1424 		 * status has been sent or not.
1425 		 */
1426 		itask->it_tm_responded = B_TRUE;
1427 		iscsit_send_task_mgmt_resp(itask->it_tm_pdu,
1428 		    (task->task_completion_status == STMF_SUCCESS) ?
1429 		    SCSI_TCP_TM_RESP_COMPLETE : SCSI_TCP_TM_RESP_FUNC_NOT_SUPP);
1430 		stmf_send_status_done(task, STMF_SUCCESS,
1431 		    STMF_IOF_LPORT_DONE);
1432 		return (STMF_SUCCESS);
1433 	}
1434 
1435 	/*
1436 	 * Remove the task from the session task list
1437 	 */
1438 	iscsit_task_done(itask);
1439 
1440 	/*
1441 	 * Send status
1442 	 */
1443 	mutex_enter(&itask->it_idm_task->idt_mutex);
1444 	if ((itask->it_idm_task->idt_state == TASK_ACTIVE) &&
1445 	    (task->task_completion_status == STMF_SUCCESS) &&
1446 	    (task->task_sense_length == 0) &&
1447 	    (task->task_resid == 0)) {
1448 		itask->it_idm_task->idt_state = TASK_COMPLETE;
1449 		/* PDU callback releases task hold */
1450 		idm_task_hold(itask->it_idm_task);
1451 		mutex_exit(&itask->it_idm_task->idt_mutex);
1452 		/*
1453 		 * Fast path.  Cached status PDU's are already
1454 		 * initialized.  We just need to fill in
1455 		 * connection and task information.
1456 		 */
1457 		pdu = kmem_cache_alloc(iscsit_status_pdu_cache, KM_SLEEP);
1458 		pdu->isp_ic = itask->it_ict->ict_ic;
1459 		pdu->isp_private = itask;
1460 
1461 		rsp = (iscsi_scsi_rsp_hdr_t *)pdu->isp_hdr;
1462 		rsp->itt = itask->it_itt;
1463 		rsp->cmd_status = task->task_scsi_status;
1464 		iscsit_pdu_tx(pdu);
1465 		return (STMF_SUCCESS);
1466 	} else {
1467 		if (itask->it_idm_task->idt_state != TASK_ACTIVE) {
1468 			mutex_exit(&itask->it_idm_task->idt_mutex);
1469 			return (STMF_FAILURE);
1470 		}
1471 		itask->it_idm_task->idt_state = TASK_COMPLETE;
1472 		/* PDU callback releases task hold */
1473 		idm_task_hold(itask->it_idm_task);
1474 		mutex_exit(&itask->it_idm_task->idt_mutex);
1475 
1476 		resp_datalen = (task->task_sense_length == 0) ? 0 :
1477 		    (task->task_sense_length + sizeof (uint16_t));
1478 
1479 		pdu = idm_pdu_alloc(sizeof (iscsi_hdr_t), resp_datalen);
1480 		idm_pdu_init(pdu, itask->it_ict->ict_ic, itask,
1481 		    iscsit_send_status_done);
1482 
1483 		rsp = (iscsi_scsi_rsp_hdr_t *)pdu->isp_hdr;
1484 		bzero(rsp, sizeof (*rsp));
1485 		rsp->opcode = ISCSI_OP_SCSI_RSP;
1486 
1487 		rsp->flags = ISCSI_FLAG_FINAL;
1488 		if (task->task_status_ctrl & TASK_SCTRL_OVER) {
1489 			rsp->flags |= ISCSI_FLAG_CMD_OVERFLOW;
1490 		} else if (task->task_status_ctrl & TASK_SCTRL_UNDER) {
1491 			rsp->flags |= ISCSI_FLAG_CMD_UNDERFLOW;
1492 		}
1493 
1494 		rsp->bi_residual_count = 0;
1495 		rsp->residual_count = htonl(task->task_resid);
1496 		rsp->itt = itask->it_itt;
1497 		rsp->response = ISCSI_STATUS_CMD_COMPLETED;
1498 		rsp->cmd_status = task->task_scsi_status;
1499 		if (task->task_sense_length != 0) {
1500 			/*
1501 			 * Add a byte to provide the sense length in
1502 			 * the response
1503 			 */
1504 			*(uint16_t *)((void *)pdu->isp_data) =
1505 			    htons(task->task_sense_length);
1506 			bcopy(task->task_sense_data,
1507 			    (uint8_t *)pdu->isp_data +
1508 			    sizeof (uint16_t),
1509 			    task->task_sense_length);
1510 			hton24(rsp->dlength, resp_datalen);
1511 		}
1512 
1513 		DTRACE_PROBE5(iscsi__scsi__response,
1514 		    iscsit_conn_t *, itask->it_ict,
1515 		    uint8_t, rsp->response,
1516 		    uint8_t, rsp->cmd_status,
1517 		    idm_pdu_t *, pdu,
1518 		    scsi_task_t *, task);
1519 
1520 		iscsit_pdu_tx(pdu);
1521 
1522 		return (STMF_SUCCESS);
1523 	}
1524 }
1525 
1526 /*ARGSUSED*/
1527 static void
1528 iscsit_send_good_status_done(idm_pdu_t *pdu, idm_status_t status)
1529 {
1530 	iscsit_task_t	*itask;
1531 	boolean_t	aborted;
1532 
1533 	itask = pdu->isp_private;
1534 	aborted = itask->it_stmf_abort;
1535 
1536 	/*
1537 	 * After releasing the hold the task may be freed at any time so
1538 	 * don't touch it.
1539 	 */
1540 	idm_task_rele(itask->it_idm_task);
1541 	if (!aborted) {
1542 		stmf_send_status_done(itask->it_stmf_task,
1543 		    iscsit_idm_to_stmf(pdu->isp_status), STMF_IOF_LPORT_DONE);
1544 	}
1545 	kmem_cache_free(iscsit_status_pdu_cache, pdu);
1546 }
1547 
1548 /*ARGSUSED*/
1549 static void
1550 iscsit_send_status_done(idm_pdu_t *pdu, idm_status_t status)
1551 {
1552 	iscsit_task_t	 *itask;
1553 	boolean_t	aborted;
1554 
1555 	itask = pdu->isp_private;
1556 	aborted = itask->it_stmf_abort;
1557 
1558 	/*
1559 	 * After releasing the hold the task may be freed at any time so
1560 	 * don't touch it.
1561 	 */
1562 	idm_task_rele(itask->it_idm_task);
1563 	if (!aborted) {
1564 		stmf_send_status_done(itask->it_stmf_task,
1565 		    iscsit_idm_to_stmf(pdu->isp_status), STMF_IOF_LPORT_DONE);
1566 	}
1567 	idm_pdu_free(pdu);
1568 }
1569 
1570 
1571 void
1572 iscsit_lport_task_free(scsi_task_t *task)
1573 {
1574 	iscsit_task_t *itask = task->task_port_private;
1575 
1576 	/* We only call idm_task_start for regular tasks, not task management */
1577 	if (task->task_mgmt_function == TM_NONE) {
1578 		idm_task_done(itask->it_idm_task);
1579 		iscsit_task_free(itask);
1580 		return;
1581 	} else {
1582 		iscsit_tm_task_free(itask);
1583 	}
1584 }
1585 
1586 /*ARGSUSED*/
1587 stmf_status_t
1588 iscsit_abort(stmf_local_port_t *lport, int abort_cmd, void *arg, uint32_t flags)
1589 {
1590 	scsi_task_t	*st = (scsi_task_t *)arg;
1591 	iscsit_task_t	*iscsit_task;
1592 	idm_task_t	*idt;
1593 
1594 	/*
1595 	 * If this is a task management request then there's really not much to
1596 	 * do.
1597 	 */
1598 	if (st->task_mgmt_function != TM_NONE) {
1599 		return (STMF_ABORT_SUCCESS);
1600 	}
1601 
1602 	/*
1603 	 * Regular task, start cleaning up
1604 	 */
1605 	iscsit_task = st->task_port_private;
1606 	idt = iscsit_task->it_idm_task;
1607 	mutex_enter(&iscsit_task->it_mutex);
1608 	iscsit_task->it_stmf_abort = B_TRUE;
1609 	if (iscsit_task->it_aborted) {
1610 		mutex_exit(&iscsit_task->it_mutex);
1611 		/*
1612 		 * Task is no longer active
1613 		 */
1614 		iscsit_task_done(iscsit_task);
1615 
1616 		/*
1617 		 * STMF specification is wrong... says to return
1618 		 * STMF_ABORTED, the code actually looks for
1619 		 * STMF_ABORT_SUCCESS.
1620 		 */
1621 		return (STMF_ABORT_SUCCESS);
1622 	} else {
1623 		mutex_exit(&iscsit_task->it_mutex);
1624 		/*
1625 		 * Call IDM to abort the task.  Due to a variety of
1626 		 * circumstances the task may already be in the process of
1627 		 * aborting.
1628 		 * We'll let IDM worry about rationalizing all that except
1629 		 * for one particular instance.  If the state of the task
1630 		 * is TASK_COMPLETE, we need to indicate to the framework
1631 		 * that we are in fact done.  This typically happens with
1632 		 * framework-initiated task management type requests
1633 		 * (e.g. abort task).
1634 		 */
1635 		if (idt->idt_state == TASK_COMPLETE) {
1636 			idm_refcnt_wait_ref(&idt->idt_refcnt);
1637 			return (STMF_ABORT_SUCCESS);
1638 		} else {
1639 			idm_task_abort(idt->idt_ic, idt, AT_TASK_MGMT_ABORT);
1640 			return (STMF_SUCCESS);
1641 		}
1642 	}
1643 
1644 	/*NOTREACHED*/
1645 }
1646 
1647 /*ARGSUSED*/
1648 void
1649 iscsit_ctl(stmf_local_port_t *lport, int cmd, void *arg)
1650 {
1651 	iscsit_tgt_t		*iscsit_tgt;
1652 
1653 	ASSERT((cmd == STMF_CMD_LPORT_ONLINE) ||
1654 	    (cmd == STMF_ACK_LPORT_ONLINE_COMPLETE) ||
1655 	    (cmd == STMF_CMD_LPORT_OFFLINE) ||
1656 	    (cmd == STMF_ACK_LPORT_OFFLINE_COMPLETE));
1657 
1658 	iscsit_tgt = (iscsit_tgt_t *)lport->lport_port_private;
1659 
1660 	switch (cmd) {
1661 	case STMF_CMD_LPORT_ONLINE:
1662 		iscsit_tgt_sm_event(iscsit_tgt, TE_STMF_ONLINE_REQ);
1663 		break;
1664 	case STMF_CMD_LPORT_OFFLINE:
1665 		iscsit_tgt_sm_event(iscsit_tgt, TE_STMF_OFFLINE_REQ);
1666 		break;
1667 	case STMF_ACK_LPORT_ONLINE_COMPLETE:
1668 		iscsit_tgt_sm_event(iscsit_tgt, TE_STMF_ONLINE_COMPLETE_ACK);
1669 		break;
1670 	case STMF_ACK_LPORT_OFFLINE_COMPLETE:
1671 		iscsit_tgt_sm_event(iscsit_tgt, TE_STMF_OFFLINE_COMPLETE_ACK);
1672 		break;
1673 
1674 	default:
1675 		break;
1676 	}
1677 }
1678 
1679 static stmf_status_t
1680 iscsit_idm_to_stmf(idm_status_t idmrc)
1681 {
1682 	switch (idmrc) {
1683 	case IDM_STATUS_SUCCESS:
1684 		return (STMF_SUCCESS);
1685 	default:
1686 		return (STMF_FAILURE);
1687 	}
1688 	/*NOTREACHED*/
1689 }
1690 
1691 
1692 /*
1693  * ISCSI protocol
1694  */
1695 
1696 void
1697 iscsit_op_scsi_cmd(idm_conn_t *ic, idm_pdu_t *rx_pdu)
1698 {
1699 	iscsit_conn_t		*ict;
1700 	iscsit_task_t		*itask;
1701 	scsi_task_t		*task;
1702 	iscsit_buf_t		*ibuf;
1703 	iscsi_scsi_cmd_hdr_t	*iscsi_scsi =
1704 	    (iscsi_scsi_cmd_hdr_t *)rx_pdu->isp_hdr;
1705 	iscsi_addl_hdr_t	*ahs_hdr;
1706 	uint16_t		addl_cdb_len = 0;
1707 
1708 	ict = ic->ic_handle;
1709 
1710 	itask = iscsit_task_alloc(ict);
1711 	if (itask == NULL) {
1712 		/* Finish processing request */
1713 		iscsit_set_cmdsn(ict, rx_pdu);
1714 
1715 		iscsit_send_direct_scsi_resp(ict, rx_pdu,
1716 		    ISCSI_STATUS_CMD_COMPLETED, STATUS_BUSY);
1717 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1718 		return;
1719 	}
1720 
1721 
1722 	/*
1723 	 * Note CmdSN and ITT in task.  IDM will have already validated this
1724 	 * request against the connection state so we don't need to check
1725 	 * that (the connection may have changed state in the meantime but
1726 	 * we will catch that when we try to send a response)
1727 	 */
1728 	itask->it_cmdsn = ntohl(iscsi_scsi->cmdsn);
1729 	itask->it_itt = iscsi_scsi->itt;
1730 
1731 	/*
1732 	 * Check for extended CDB AHS
1733 	 */
1734 	if (iscsi_scsi->hlength > 0) {
1735 		ahs_hdr = (iscsi_addl_hdr_t *)iscsi_scsi;
1736 		addl_cdb_len = ((ahs_hdr->ahs_hlen_hi << 8) |
1737 		    ahs_hdr->ahs_hlen_lo) - 1; /* Adjust for reserved byte */
1738 		if (((addl_cdb_len + 4) / sizeof (uint32_t)) >
1739 		    iscsi_scsi->hlength) {
1740 			/* Mangled header info, drop it */
1741 			idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1742 			return;
1743 		}
1744 	}
1745 
1746 	ict = rx_pdu->isp_ic->ic_handle; /* IDM client private */
1747 
1748 	/*
1749 	 * Add task to session list.  This function will also check to
1750 	 * ensure that the task does not already exist.
1751 	 */
1752 	if (iscsit_task_start(itask) != IDM_STATUS_SUCCESS) {
1753 		/*
1754 		 * Task exists, free all resources and reject.  Don't
1755 		 * update expcmdsn in this case because RFC 3720 says
1756 		 * "The CmdSN of the rejected command PDU (if it is a
1757 		 * non-immediate command) MUST NOT be considered received
1758 		 * by the target (i.e., a command sequence gap must be
1759 		 * assumed for the CmdSN), even though the CmdSN of the
1760 		 * rejected command PDU may be reliably ascertained.  Upon
1761 		 * receiving the Reject, the initiator MUST plug the CmdSN
1762 		 * gap in order to continue to use the session.  The gap
1763 		 * may be plugged either by transmitting a command PDU
1764 		 * with the same CmdSN, or by aborting the task (see section
1765 		 * 6.9 on how an abort may plug a CmdSN gap)." (Section 6.3)
1766 		 */
1767 		iscsit_task_free(itask);
1768 		iscsit_send_reject(ict, rx_pdu, ISCSI_REJECT_TASK_IN_PROGRESS);
1769 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1770 		return;
1771 	}
1772 
1773 	/* Update sequence numbers */
1774 	iscsit_set_cmdsn(ict, rx_pdu);
1775 
1776 	/*
1777 	 * Allocate STMF task
1778 	 */
1779 	itask->it_stmf_task = stmf_task_alloc(
1780 	    itask->it_ict->ict_sess->ist_lport,
1781 	    itask->it_ict->ict_sess->ist_stmf_sess, iscsi_scsi->lun,
1782 	    16 + addl_cdb_len, 0);
1783 	if (itask->it_stmf_task == NULL) {
1784 		/*
1785 		 * Either stmf really couldn't get memory for a task or,
1786 		 * more likely, the LU is currently in reset.  Either way
1787 		 * we have no choice but to fail the request.
1788 		 */
1789 		iscsit_task_done(itask);
1790 		iscsit_task_free(itask);
1791 		iscsit_send_direct_scsi_resp(ict, rx_pdu,
1792 		    ISCSI_STATUS_CMD_COMPLETED, STATUS_BUSY);
1793 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1794 		return;
1795 	}
1796 
1797 	task = itask->it_stmf_task;
1798 	task->task_port_private = itask;
1799 
1800 	bcopy(iscsi_scsi->lun, task->task_lun_no, sizeof (task->task_lun_no));
1801 
1802 	/*
1803 	 * iSCSI and Comstar use the same values.  Should we rely on this
1804 	 * or translate them bit-wise?
1805 	 */
1806 
1807 	task->task_flags =
1808 	    (((iscsi_scsi->flags & ISCSI_FLAG_CMD_READ) ? TF_READ_DATA : 0) |
1809 	    ((iscsi_scsi->flags & ISCSI_FLAG_CMD_WRITE) ? TF_WRITE_DATA : 0) |
1810 	    ((rx_pdu->isp_datalen == 0) ? 0 : TF_INITIAL_BURST));
1811 
1812 	switch (iscsi_scsi->flags & ISCSI_FLAG_CMD_ATTR_MASK) {
1813 	case ISCSI_ATTR_UNTAGGED:
1814 		break;
1815 	case ISCSI_ATTR_SIMPLE:
1816 		task->task_additional_flags |= TF_ATTR_SIMPLE_QUEUE;
1817 		break;
1818 	case ISCSI_ATTR_ORDERED:
1819 		task->task_additional_flags |= TF_ATTR_ORDERED_QUEUE;
1820 		break;
1821 	case ISCSI_ATTR_HEAD_OF_QUEUE:
1822 		task->task_additional_flags |= TF_ATTR_HEAD_OF_QUEUE;
1823 		break;
1824 	case ISCSI_ATTR_ACA:
1825 		task->task_additional_flags |= TF_ATTR_ACA;
1826 		break;
1827 	default:
1828 		/* Protocol error but just take it, treat as untagged */
1829 		break;
1830 	}
1831 
1832 
1833 	task->task_additional_flags = 0;
1834 	task->task_priority = 0;
1835 	task->task_mgmt_function = TM_NONE;
1836 
1837 	/*
1838 	 * This "task_max_nbufs" doesn't map well to BIDI.  We probably need
1839 	 * parameter for each direction.  "MaxOutstandingR2T" may very well
1840 	 * be set to one which could prevent us from doing simultaneous
1841 	 * transfers in each direction.
1842 	 */
1843 	task->task_max_nbufs = (iscsi_scsi->flags & ISCSI_FLAG_CMD_WRITE) ?
1844 	    ict->ict_op.op_max_outstanding_r2t : STMF_BUFS_MAX;
1845 	task->task_cmd_seq_no = ntohl(iscsi_scsi->itt);
1846 	task->task_expected_xfer_length = ntohl(iscsi_scsi->data_length);
1847 
1848 	/* Copy CDB */
1849 	bcopy(iscsi_scsi->scb, task->task_cdb, 16);
1850 	if (addl_cdb_len > 0) {
1851 		bcopy(ahs_hdr->ahs_extscb, task->task_cdb + 16, addl_cdb_len);
1852 	}
1853 
1854 	/*
1855 	 * Copy the transport header into the task handle from the PDU
1856 	 * handle. The transport header describes this task's remote tagged
1857 	 * buffer.
1858 	 */
1859 	if (rx_pdu->isp_transport_hdrlen != 0) {
1860 		bcopy(rx_pdu->isp_transport_hdr,
1861 		    itask->it_idm_task->idt_transport_hdr,
1862 		    rx_pdu->isp_transport_hdrlen);
1863 	}
1864 
1865 	/*
1866 	 * Tell IDM about our new active task
1867 	 */
1868 	idm_task_start(itask->it_idm_task, (uintptr_t)itask->it_itt);
1869 
1870 	/*
1871 	 * If we have any immediate data then setup the immediate buffer
1872 	 * context that comes with the task
1873 	 */
1874 	if (rx_pdu->isp_datalen) {
1875 		ibuf = itask->it_immed_data;
1876 		ibuf->ibuf_immed_data_pdu = rx_pdu;
1877 		ibuf->ibuf_stmf_buf->db_data_size = rx_pdu->isp_datalen;
1878 		ibuf->ibuf_stmf_buf->db_buf_size = rx_pdu->isp_datalen;
1879 		ibuf->ibuf_stmf_buf->db_relative_offset = 0;
1880 		ibuf->ibuf_stmf_buf->db_sglist[0].seg_length =
1881 		    rx_pdu->isp_datalen;
1882 		ibuf->ibuf_stmf_buf->db_sglist[0].seg_addr = rx_pdu->isp_data;
1883 
1884 		stmf_post_task(task, ibuf->ibuf_stmf_buf);
1885 	} else {
1886 		stmf_post_task(task, NULL);
1887 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
1888 	}
1889 }
1890 
1891 /*ARGSUSED*/
1892 void
1893 iscsit_deferred_dispatch(idm_pdu_t *rx_pdu)
1894 {
1895 	iscsit_conn_t *ict = rx_pdu->isp_ic->ic_handle;
1896 
1897 	/*
1898 	 * If the connection has been lost then ignore new PDU's
1899 	 */
1900 	mutex_enter(&ict->ict_mutex);
1901 	if (ict->ict_lost) {
1902 		mutex_exit(&ict->ict_mutex);
1903 		idm_pdu_complete(rx_pdu, IDM_STATUS_FAIL);
1904 		return;
1905 	}
1906 
1907 	/*
1908 	 * Grab a hold on the connection to prevent it from going away
1909 	 * between now and when the taskq function is called.
1910 	 */
1911 	iscsit_conn_dispatch_hold(ict);
1912 	mutex_exit(&ict->ict_mutex);
1913 
1914 	if (taskq_dispatch(iscsit_global.global_dispatch_taskq,
1915 	    iscsit_deferred, rx_pdu, DDI_NOSLEEP) == NULL) {
1916 		/*
1917 		 * In the unlikely scenario that we couldn't get the resources
1918 		 * to dispatch the PDU then just drop it.
1919 		 */
1920 		idm_pdu_complete(rx_pdu, IDM_STATUS_FAIL);
1921 		idm_conn_event(ict->ict_ic, CE_TRANSPORT_FAIL, NULL);
1922 		iscsit_conn_dispatch_rele(ict);
1923 	}
1924 }
1925 
1926 static void
1927 iscsit_deferred(void *rx_pdu_void)
1928 {
1929 	idm_pdu_t *rx_pdu = rx_pdu_void;
1930 	idm_conn_t *ic = rx_pdu->isp_ic;
1931 	iscsit_conn_t *ict = ic->ic_handle;
1932 
1933 	switch (IDM_PDU_OPCODE(rx_pdu)) {
1934 	case ISCSI_OP_NOOP_OUT:
1935 		iscsit_set_cmdsn(ict, rx_pdu);
1936 		iscsit_pdu_op_noop(ict, rx_pdu);
1937 		break;
1938 	case ISCSI_OP_LOGIN_CMD:
1939 		iscsit_pdu_op_login_cmd(ict, rx_pdu);
1940 		break;
1941 	case ISCSI_OP_TEXT_CMD:
1942 		iscsit_set_cmdsn(ict, rx_pdu);
1943 		iscsit_pdu_op_text_cmd(ict, rx_pdu);
1944 		break;
1945 	case ISCSI_OP_LOGOUT_CMD:
1946 		iscsit_set_cmdsn(ict, rx_pdu);
1947 		iscsit_pdu_op_logout_cmd(ict, rx_pdu);
1948 		break;
1949 	default:
1950 		/* Protocol error.  IDM should have caught this */
1951 		idm_pdu_complete(rx_pdu, IDM_STATUS_FAIL);
1952 		ASSERT(0);
1953 		break;
1954 	}
1955 
1956 	iscsit_conn_dispatch_rele(ict);
1957 }
1958 
1959 static void
1960 iscsit_send_direct_scsi_resp(iscsit_conn_t *ict, idm_pdu_t *rx_pdu,
1961     uint8_t response, uint8_t cmd_status)
1962 {
1963 	idm_pdu_t			*rsp_pdu;
1964 	idm_conn_t			*ic;
1965 	iscsi_scsi_rsp_hdr_t		*resp;
1966 	iscsi_scsi_cmd_hdr_t		*req =
1967 	    (iscsi_scsi_cmd_hdr_t *)rx_pdu->isp_hdr;
1968 
1969 	ic = ict->ict_ic;
1970 
1971 	rsp_pdu = idm_pdu_alloc(sizeof (iscsi_scsi_rsp_hdr_t), 0);
1972 	idm_pdu_init(rsp_pdu, ic, NULL, NULL);
1973 	resp = (iscsi_scsi_rsp_hdr_t *)rsp_pdu->isp_hdr;
1974 
1975 	resp->opcode = ISCSI_OP_SCSI_RSP;
1976 	resp->flags = ISCSI_FLAG_FINAL;
1977 	resp->response = response;
1978 	resp->cmd_status = cmd_status;
1979 	resp->itt = req->itt;
1980 	if ((response == ISCSI_STATUS_CMD_COMPLETED) &&
1981 	    (req->data_length != 0) &&
1982 	    ((req->flags & ISCSI_FLAG_CMD_READ) ||
1983 	    (req->flags & ISCSI_FLAG_CMD_WRITE))) {
1984 		resp->flags |= ISCSI_FLAG_CMD_UNDERFLOW;
1985 		resp->residual_count = req->data_length;
1986 	}
1987 
1988 	DTRACE_PROBE4(iscsi__scsi__direct__response,
1989 	    iscsit_conn_t *, ict,
1990 	    uint8_t, resp->response,
1991 	    uint8_t, resp->cmd_status,
1992 	    idm_pdu_t *, rsp_pdu);
1993 
1994 	iscsit_pdu_tx(rsp_pdu);
1995 }
1996 
1997 void
1998 iscsit_send_task_mgmt_resp(idm_pdu_t *tm_resp_pdu, uint8_t tm_status)
1999 {
2000 	iscsi_scsi_task_mgt_rsp_hdr_t	*tm_resp;
2001 
2002 	tm_resp = (iscsi_scsi_task_mgt_rsp_hdr_t *)tm_resp_pdu->isp_hdr;
2003 	tm_resp->response = tm_status;
2004 
2005 	DTRACE_PROBE3(iscsi__scsi__tm__response,
2006 	    iscsit_conn_t *, tm_resp_pdu->isp_ic->ic_handle,
2007 	    uint8_t, tm_resp->response,
2008 	    idm_pdu_t *, tm_resp_pdu);
2009 	iscsit_pdu_tx(tm_resp_pdu);
2010 }
2011 
2012 void
2013 iscsit_op_scsi_task_mgmt(iscsit_conn_t *ict, idm_pdu_t *rx_pdu)
2014 {
2015 	idm_pdu_t			*tm_resp_pdu;
2016 	iscsit_task_t			*itask;
2017 	iscsit_task_t			*tm_itask;
2018 	scsi_task_t			*task;
2019 	iscsi_scsi_task_mgt_hdr_t 	*iscsi_tm =
2020 	    (iscsi_scsi_task_mgt_hdr_t *)rx_pdu->isp_hdr;
2021 	iscsi_scsi_task_mgt_rsp_hdr_t 	*iscsi_tm_rsp =
2022 	    (iscsi_scsi_task_mgt_rsp_hdr_t *)rx_pdu->isp_hdr;
2023 	uint32_t			rtt, cmdsn, refcmdsn;
2024 	uint8_t				tm_func;
2025 
2026 	/*
2027 	 * Setup response PDU (response field will get filled in later)
2028 	 */
2029 	tm_resp_pdu = idm_pdu_alloc(sizeof (iscsi_scsi_task_mgt_rsp_hdr_t), 0);
2030 	if (tm_resp_pdu == NULL) {
2031 		/* Can't respond, just drop it */
2032 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2033 		return;
2034 	}
2035 	idm_pdu_init(tm_resp_pdu, ict->ict_ic, NULL, NULL);
2036 	iscsi_tm_rsp = (iscsi_scsi_task_mgt_rsp_hdr_t *)tm_resp_pdu->isp_hdr;
2037 	bzero(iscsi_tm_rsp, sizeof (iscsi_scsi_task_mgt_rsp_hdr_t));
2038 	iscsi_tm_rsp->opcode = ISCSI_OP_SCSI_TASK_MGT_RSP;
2039 	iscsi_tm_rsp->flags = ISCSI_FLAG_FINAL;
2040 	iscsi_tm_rsp->itt = rx_pdu->isp_hdr->itt;
2041 
2042 	/*
2043 	 * Figure out what we're being asked to do.
2044 	 */
2045 	DTRACE_PROBE4(iscsi__scsi__tm__request,
2046 	    iscsit_conn_t *, ict,
2047 	    uint8_t, (iscsi_tm->function & ISCSI_FLAG_TASK_MGMT_FUNCTION_MASK),
2048 	    uint32_t, iscsi_tm->rtt,
2049 	    idm_pdu_t *, rx_pdu);
2050 	switch (iscsi_tm->function & ISCSI_FLAG_TASK_MGMT_FUNCTION_MASK) {
2051 	case ISCSI_TM_FUNC_ABORT_TASK:
2052 		/*
2053 		 * STMF doesn't currently support the "abort task" task
2054 		 * management command although it does support aborting
2055 		 * an individual task.  We'll get STMF to abort the task
2056 		 * for us but handle the details of the task management
2057 		 * command ourselves.
2058 		 *
2059 		 * Find the task associated with the referenced task tag.
2060 		 */
2061 		rtt = iscsi_tm->rtt;
2062 		itask = (iscsit_task_t *)idm_task_find_by_handle(ict->ict_ic,
2063 		    (uintptr_t)rtt);
2064 
2065 		if (itask == NULL) {
2066 			cmdsn = ntohl(iscsi_tm->cmdsn);
2067 			refcmdsn = ntohl(iscsi_tm->refcmdsn);
2068 
2069 			/*
2070 			 * Task was not found.  If RefCmdSN is within the CmdSN
2071 			 * window and less than CmdSN of the TM function, return
2072 			 * "Function Complete".  Otherwise, return
2073 			 * "Task Does Not Exist".
2074 			 */
2075 
2076 			if (iscsit_cmdsn_in_window(ict, refcmdsn) &&
2077 			    (refcmdsn < cmdsn)) {
2078 				iscsit_send_task_mgmt_resp(tm_resp_pdu,
2079 				    SCSI_TCP_TM_RESP_COMPLETE);
2080 			} else {
2081 				iscsit_send_task_mgmt_resp(tm_resp_pdu,
2082 				    SCSI_TCP_TM_RESP_NO_TASK);
2083 			}
2084 		} else {
2085 
2086 			/*
2087 			 * Tell STMF to abort the task.  This will do no harm
2088 			 * if the task is already complete.
2089 			 */
2090 			stmf_abort(STMF_QUEUE_TASK_ABORT, itask->it_stmf_task,
2091 			    STMF_ABORTED, NULL);
2092 
2093 			/*
2094 			 * Make sure the task hasn't already completed
2095 			 */
2096 			mutex_enter(&itask->it_idm_task->idt_mutex);
2097 			if ((itask->it_idm_task->idt_state == TASK_COMPLETE) ||
2098 			    (itask->it_idm_task->idt_state == TASK_IDLE)) {
2099 				/*
2100 				 * Task is complete, return "Task Does Not
2101 				 * Exist"
2102 				 */
2103 				mutex_exit(&itask->it_idm_task->idt_mutex);
2104 				iscsit_send_task_mgmt_resp(tm_resp_pdu,
2105 				    SCSI_TCP_TM_RESP_NO_TASK);
2106 			} else {
2107 				/*
2108 				 * STMF is now aborting the task, return
2109 				 * "Function Complete"
2110 				 */
2111 				mutex_exit(&itask->it_idm_task->idt_mutex);
2112 				iscsit_send_task_mgmt_resp(tm_resp_pdu,
2113 				    SCSI_TCP_TM_RESP_COMPLETE);
2114 			}
2115 			idm_task_rele(itask->it_idm_task);
2116 		}
2117 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2118 		return;
2119 
2120 	case ISCSI_TM_FUNC_ABORT_TASK_SET:
2121 		tm_func = TM_ABORT_TASK_SET;
2122 		break;
2123 
2124 	case ISCSI_TM_FUNC_CLEAR_ACA:
2125 		tm_func = TM_CLEAR_ACA;
2126 		break;
2127 
2128 	case ISCSI_TM_FUNC_CLEAR_TASK_SET:
2129 		tm_func = TM_CLEAR_TASK_SET;
2130 		break;
2131 
2132 	case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
2133 		tm_func = TM_LUN_RESET;
2134 		break;
2135 
2136 	case ISCSI_TM_FUNC_TARGET_WARM_RESET:
2137 		tm_func = TM_TARGET_WARM_RESET;
2138 		break;
2139 
2140 	case ISCSI_TM_FUNC_TARGET_COLD_RESET:
2141 		tm_func = TM_TARGET_COLD_RESET;
2142 		break;
2143 
2144 	case ISCSI_TM_FUNC_TASK_REASSIGN:
2145 		/*
2146 		 * We do not currently support allegiance reassignment.  When
2147 		 * we start supporting ERL1+, we will need to.
2148 		 */
2149 		iscsit_send_task_mgmt_resp(tm_resp_pdu,
2150 		    SCSI_TCP_TM_RESP_NO_ALLG_REASSN);
2151 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2152 		return;
2153 
2154 	default:
2155 		iscsit_send_task_mgmt_resp(tm_resp_pdu,
2156 		    SCSI_TCP_TM_RESP_REJECTED);
2157 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2158 		return;
2159 	}
2160 
2161 	tm_itask = iscsit_tm_task_alloc(ict);
2162 	if (tm_itask == NULL) {
2163 		iscsit_send_task_mgmt_resp(tm_resp_pdu,
2164 		    SCSI_TCP_TM_RESP_REJECTED);
2165 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2166 		return;
2167 	}
2168 
2169 
2170 	task = stmf_task_alloc(ict->ict_sess->ist_lport,
2171 	    ict->ict_sess->ist_stmf_sess, iscsi_tm->lun,
2172 	    0, STMF_TASK_EXT_NONE);
2173 	if (task == NULL) {
2174 		/*
2175 		 * If this happens, either the LU is in reset, couldn't
2176 		 * get memory, or some other condition in which we simply
2177 		 * can't complete this request.  It would be nice to return
2178 		 * an error code like "busy" but the closest we have is
2179 		 * "rejected".
2180 		 */
2181 		iscsit_send_task_mgmt_resp(tm_resp_pdu,
2182 		    SCSI_TCP_TM_RESP_REJECTED);
2183 		iscsit_tm_task_free(tm_itask);
2184 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2185 		return;
2186 	}
2187 
2188 	tm_itask->it_tm_pdu = tm_resp_pdu;
2189 	tm_itask->it_stmf_task = task;
2190 	task->task_port_private = tm_itask;
2191 	task->task_mgmt_function = tm_func;
2192 	task->task_additional_flags = TASK_AF_NO_EXPECTED_XFER_LENGTH;
2193 	task->task_priority = 0;
2194 	task->task_max_nbufs = STMF_BUFS_MAX;
2195 	task->task_cmd_seq_no = iscsi_tm->itt;
2196 	task->task_expected_xfer_length = 0;
2197 
2198 	stmf_post_task(task, NULL);
2199 	idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2200 }
2201 
2202 static void
2203 iscsit_pdu_op_noop(iscsit_conn_t *ict, idm_pdu_t *rx_pdu)
2204 {
2205 	iscsi_nop_out_hdr_t *out = (iscsi_nop_out_hdr_t *)rx_pdu->isp_hdr;
2206 	iscsi_nop_in_hdr_t *in;
2207 	int resp_datalen;
2208 	idm_pdu_t *resp;
2209 
2210 	/* Ignore the response from initiator */
2211 	if ((out->itt == ISCSI_RSVD_TASK_TAG) ||
2212 	    (out->ttt != ISCSI_RSVD_TASK_TAG)) {
2213 		idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2214 		return;
2215 	}
2216 
2217 	/* Allocate a PDU to respond */
2218 	resp_datalen = ntoh24(out->dlength);
2219 	resp = idm_pdu_alloc(sizeof (iscsi_hdr_t), resp_datalen);
2220 	idm_pdu_init(resp, ict->ict_ic, NULL, NULL);
2221 	if (resp_datalen > 0) {
2222 		bcopy(rx_pdu->isp_data, resp->isp_data, resp_datalen);
2223 	}
2224 
2225 	in = (iscsi_nop_in_hdr_t *)resp->isp_hdr;
2226 	bzero(in, sizeof (*in));
2227 	in->opcode = ISCSI_OP_NOOP_IN;
2228 	in->flags = ISCSI_FLAG_FINAL;
2229 	bcopy(out->lun, in->lun, 8);
2230 	in->itt		= out->itt;
2231 	in->ttt		= ISCSI_RSVD_TASK_TAG;
2232 	hton24(in->dlength, resp_datalen);
2233 
2234 	/* Any other field in resp to be set? */
2235 	iscsit_pdu_tx(resp);
2236 	idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2237 }
2238 
2239 static void
2240 iscsit_pdu_op_login_cmd(iscsit_conn_t	*ict, idm_pdu_t *rx_pdu)
2241 {
2242 
2243 	/*
2244 	 * Submit PDU to login state machine.  State machine will free the
2245 	 * PDU.
2246 	 */
2247 	iscsit_login_sm_event(ict, ILE_LOGIN_RCV, rx_pdu);
2248 }
2249 
2250 void
2251 iscsit_pdu_op_logout_cmd(iscsit_conn_t	*ict, idm_pdu_t *rx_pdu)
2252 {
2253 	iscsi_logout_hdr_t 	*logout_req =
2254 	    (iscsi_logout_hdr_t *)rx_pdu->isp_hdr;
2255 	iscsi_logout_rsp_hdr_t	*logout_rsp;
2256 	idm_pdu_t *resp;
2257 
2258 	/* Allocate a PDU to respond */
2259 	resp = idm_pdu_alloc(sizeof (iscsi_hdr_t), 0);
2260 	idm_pdu_init(resp, ict->ict_ic, NULL, NULL);
2261 
2262 	/*
2263 	 * Logout results in the immediate termination of all tasks except
2264 	 * if the logout reason is ISCSI_LOGOUT_REASON_RECOVERY.  The
2265 	 * connection state machine will drive this task cleanup automatically
2266 	 * so we don't need to handle that here.
2267 	 */
2268 	logout_rsp = (iscsi_logout_rsp_hdr_t *)resp->isp_hdr;
2269 	bzero(logout_rsp, sizeof (*logout_rsp));
2270 	logout_rsp->opcode = ISCSI_OP_LOGOUT_RSP;
2271 	logout_rsp->flags = ISCSI_FLAG_FINAL;
2272 	logout_rsp->itt = logout_req->itt;
2273 	if ((logout_req->flags & ISCSI_FLAG_LOGOUT_REASON_MASK) >
2274 	    ISCSI_LOGOUT_REASON_RECOVERY) {
2275 		logout_rsp->response = ISCSI_LOGOUT_RECOVERY_UNSUPPORTED;
2276 	} else {
2277 		logout_rsp->response = ISCSI_LOGOUT_SUCCESS;
2278 	}
2279 
2280 	iscsit_pdu_tx(resp);
2281 	idm_pdu_complete(rx_pdu, IDM_STATUS_SUCCESS);
2282 }
2283 
2284 /*
2285  * Calculate the number of outstanding commands we can process
2286  */
2287 int
2288 iscsit_cmd_window()
2289 {
2290 	/* Will be better later */
2291 	return	(1024);
2292 }
2293 
2294 /*
2295  * Set local registers based on incoming PDU
2296  */
2297 void
2298 iscsit_set_cmdsn(iscsit_conn_t *ict, idm_pdu_t *rx_pdu)
2299 {
2300 	iscsit_sess_t *ist;
2301 	iscsi_scsi_cmd_hdr_t *req;
2302 
2303 	ist = ict->ict_sess;
2304 
2305 	req = (iscsi_scsi_cmd_hdr_t *)rx_pdu->isp_hdr;
2306 
2307 	rw_enter(&ist->ist_sn_rwlock, RW_WRITER);
2308 	ist->ist_expcmdsn = ntohl(req->cmdsn) + 1;
2309 	ist->ist_maxcmdsn = ntohl(req->cmdsn) + iscsit_cmd_window();
2310 	rw_exit(&ist->ist_sn_rwlock);
2311 }
2312 
2313 /*
2314  * Update local StatSN and set SNs in response
2315  */
2316 static void
2317 iscsit_calc_rspsn(iscsit_conn_t *ict, idm_pdu_t *resp)
2318 {
2319 	iscsit_sess_t *ist;
2320 	iscsi_scsi_rsp_hdr_t *rsp;
2321 
2322 	/* Get iSCSI session handle */
2323 	ist = ict->ict_sess;
2324 
2325 	rsp = (iscsi_scsi_rsp_hdr_t *)resp->isp_hdr;
2326 
2327 	/* Update StatSN */
2328 	rsp->statsn = htonl(ict->ict_statsn);
2329 	switch (IDM_PDU_OPCODE(resp)) {
2330 	case ISCSI_OP_RTT_RSP:
2331 		/* Do nothing */
2332 		break;
2333 	case ISCSI_OP_NOOP_IN:
2334 		/*
2335 		 * Refer to section 10.19.1, RFC3720.
2336 		 * Advance only if target is responding initiator
2337 		 */
2338 		if (((iscsi_nop_in_hdr_t *)rsp)->ttt == ISCSI_RSVD_TASK_TAG)
2339 			ict->ict_statsn++;
2340 		break;
2341 	case ISCSI_OP_SCSI_DATA_RSP:
2342 		if (rsp->flags & ISCSI_FLAG_DATA_STATUS)
2343 			ict->ict_statsn++;
2344 		else
2345 			rsp->statsn = 0;
2346 		break;
2347 	default:
2348 		ict->ict_statsn++;
2349 		break;
2350 	}
2351 
2352 	/* Set ExpCmdSN and MaxCmdSN */
2353 	rsp->maxcmdsn = htonl(ist->ist_maxcmdsn);
2354 	rsp->expcmdsn = htonl(ist->ist_expcmdsn);
2355 }
2356 
2357 /*
2358  * Wrapper funtion, calls iscsi_calc_rspsn and idm_pdu_tx
2359  */
2360 void
2361 iscsit_pdu_tx(idm_pdu_t *pdu)
2362 {
2363 	iscsit_conn_t *ict = pdu->isp_ic->ic_handle;
2364 
2365 	/*
2366 	 * Protect ict->ict_statsn, ist->ist_maxcmdsn, and ist->ist_expcmdsn
2367 	 * (which are used by iscsit_calc_rspsn) with the session mutex
2368 	 * (ist->ist_sn_mutex).
2369 	 */
2370 	rw_enter(&ict->ict_sess->ist_sn_rwlock, RW_WRITER);
2371 	iscsit_calc_rspsn(ict, pdu);
2372 	idm_pdu_tx(pdu);
2373 	rw_exit(&ict->ict_sess->ist_sn_rwlock);
2374 }
2375 
2376 /*
2377  * Internal functions
2378  */
2379 
2380 void
2381 iscsit_send_async_event(iscsit_conn_t *ict, uint8_t event)
2382 {
2383 	idm_pdu_t		*abt;
2384 	iscsi_async_evt_hdr_t	*async_abt;
2385 
2386 	/*
2387 	 * Get a PDU to build the abort request.
2388 	 */
2389 	abt = idm_pdu_alloc(sizeof (iscsi_hdr_t), 0);
2390 	if (abt == NULL) {
2391 		idm_conn_event(ict->ict_ic, CE_TRANSPORT_FAIL, NULL);
2392 		return;
2393 	}
2394 
2395 	idm_pdu_init(abt, ict->ict_ic, NULL, NULL);
2396 	abt->isp_datalen = 0;
2397 
2398 	async_abt = (iscsi_async_evt_hdr_t *)abt->isp_hdr;
2399 	bzero(async_abt, sizeof (*async_abt));
2400 	async_abt->opcode = ISCSI_OP_ASYNC_EVENT;
2401 	async_abt->async_event = event;
2402 	async_abt->flags = ISCSI_FLAG_FINAL;
2403 	async_abt->rsvd4[0] = 0xff;
2404 	async_abt->rsvd4[1] = 0xff;
2405 	async_abt->rsvd4[2] = 0xff;
2406 	async_abt->rsvd4[3] = 0xff;
2407 
2408 	switch (event) {
2409 	case ISCSI_ASYNC_EVENT_REQUEST_LOGOUT:
2410 		async_abt->param3 = htons(IDM_LOGOUT_SECONDS);
2411 		break;
2412 	case ISCSI_ASYNC_EVENT_SCSI_EVENT:
2413 	case ISCSI_ASYNC_EVENT_DROPPING_CONNECTION:
2414 	case ISCSI_ASYNC_EVENT_DROPPING_ALL_CONNECTIONS:
2415 	case ISCSI_ASYNC_EVENT_PARAM_NEGOTIATION:
2416 	default:
2417 		ASSERT(0);
2418 	}
2419 
2420 	iscsit_pdu_tx(abt);
2421 }
2422 
2423 void
2424 iscsit_send_reject(iscsit_conn_t *ict, idm_pdu_t *rejected_pdu, uint8_t reason)
2425 {
2426 	idm_pdu_t		*reject_pdu;
2427 	iscsi_reject_rsp_hdr_t	*reject;
2428 
2429 	/*
2430 	 * Get a PDU to build the abort request.
2431 	 */
2432 	reject_pdu = idm_pdu_alloc(sizeof (iscsi_hdr_t),
2433 	    rejected_pdu->isp_hdrlen);
2434 	if (reject_pdu == NULL) {
2435 		idm_conn_event(ict->ict_ic, CE_TRANSPORT_FAIL, NULL);
2436 		return;
2437 	}
2438 	idm_pdu_init(reject_pdu, ict->ict_ic, NULL, NULL);
2439 
2440 	reject_pdu->isp_datalen = rejected_pdu->isp_hdrlen;
2441 	bcopy(rejected_pdu->isp_hdr, reject_pdu->isp_data,
2442 	    rejected_pdu->isp_hdrlen);
2443 
2444 	reject = (iscsi_reject_rsp_hdr_t *)reject_pdu->isp_hdr;
2445 	bzero(reject, sizeof (*reject));
2446 	reject->opcode = ISCSI_OP_REJECT_MSG;
2447 	reject->reason = reason;
2448 	reject->flags = ISCSI_FLAG_FINAL;
2449 	hton24(reject->dlength, rejected_pdu->isp_hdrlen);
2450 	reject->must_be_ff[0] = 0xff;
2451 	reject->must_be_ff[1] = 0xff;
2452 	reject->must_be_ff[2] = 0xff;
2453 	reject->must_be_ff[3] = 0xff;
2454 
2455 	iscsit_pdu_tx(reject_pdu);
2456 }
2457 
2458 
2459 static iscsit_task_t *
2460 iscsit_task_alloc(iscsit_conn_t *ict)
2461 {
2462 	iscsit_task_t *itask;
2463 	iscsit_buf_t *immed_ibuf;
2464 
2465 	/*
2466 	 * Possible items to pre-alloc if we cache iscsit_task_t's:
2467 	 *
2468 	 * Status PDU w/ sense buffer
2469 	 * stmf_data_buf_t for immediate data
2470 	 */
2471 	itask = kmem_alloc(sizeof (iscsit_task_t) + sizeof (iscsit_buf_t) +
2472 	    sizeof (stmf_data_buf_t), KM_NOSLEEP);
2473 	if (itask != NULL) {
2474 		mutex_init(&itask->it_mutex, NULL, MUTEX_DRIVER, NULL);
2475 		itask->it_aborted = itask->it_stmf_abort =
2476 		    itask->it_tm_task = 0;
2477 
2478 		immed_ibuf = (iscsit_buf_t *)(itask + 1);
2479 		bzero(immed_ibuf, sizeof (*immed_ibuf));
2480 		immed_ibuf->ibuf_is_immed = B_TRUE;
2481 		immed_ibuf->ibuf_stmf_buf = (stmf_data_buf_t *)(immed_ibuf + 1);
2482 
2483 		bzero(immed_ibuf->ibuf_stmf_buf, sizeof (stmf_data_buf_t));
2484 		immed_ibuf->ibuf_stmf_buf->db_port_private = immed_ibuf;
2485 		immed_ibuf->ibuf_stmf_buf->db_sglist_length = 1;
2486 		immed_ibuf->ibuf_stmf_buf->db_flags = DB_DIRECTION_FROM_RPORT |
2487 		    DB_DONT_CACHE;
2488 		itask->it_immed_data = immed_ibuf;
2489 		itask->it_idm_task = idm_task_alloc(ict->ict_ic);
2490 		if (itask->it_idm_task != NULL) {
2491 			itask->it_idm_task->idt_private = itask;
2492 			itask->it_ict = ict;
2493 			itask->it_ttt = itask->it_idm_task->idt_tt;
2494 			return (itask);
2495 		} else {
2496 			kmem_free(itask, sizeof (iscsit_task_t) +
2497 			    sizeof (iscsit_buf_t) + sizeof (stmf_data_buf_t));
2498 		}
2499 	}
2500 
2501 	return (NULL);
2502 }
2503 
2504 static void
2505 iscsit_task_free(iscsit_task_t *itask)
2506 {
2507 	idm_task_free(itask->it_idm_task);
2508 	mutex_destroy(&itask->it_mutex);
2509 	kmem_free(itask, sizeof (iscsit_task_t) +
2510 	    sizeof (iscsit_buf_t) + sizeof (stmf_data_buf_t));
2511 }
2512 
2513 static iscsit_task_t *
2514 iscsit_tm_task_alloc(iscsit_conn_t *ict)
2515 {
2516 	iscsit_task_t *itask;
2517 
2518 	itask = kmem_zalloc(sizeof (iscsit_task_t), KM_NOSLEEP);
2519 	if (itask != NULL) {
2520 		idm_conn_hold(ict->ict_ic);
2521 		mutex_init(&itask->it_mutex, NULL, MUTEX_DRIVER, NULL);
2522 		itask->it_aborted = itask->it_stmf_abort =
2523 		    itask->it_tm_responded = 0;
2524 		itask->it_tm_pdu = NULL;
2525 		itask->it_tm_task = 1;
2526 		itask->it_ict = ict;
2527 	}
2528 
2529 	return (itask);
2530 }
2531 
2532 static void
2533 iscsit_tm_task_free(iscsit_task_t *itask)
2534 {
2535 	/*
2536 	 * If we responded then the call to idm_pdu_complete will free the
2537 	 * PDU.  Otherwise we got aborted before the TM function could
2538 	 * complete and we need to free the PDU explicitly.
2539 	 */
2540 	if (itask->it_tm_pdu != NULL && !itask->it_tm_responded)
2541 		idm_pdu_free(itask->it_tm_pdu);
2542 	idm_conn_rele(itask->it_ict->ict_ic);
2543 	mutex_destroy(&itask->it_mutex);
2544 	kmem_free(itask, sizeof (iscsit_task_t));
2545 }
2546 
2547 static idm_status_t
2548 iscsit_task_start(iscsit_task_t *itask)
2549 {
2550 	iscsit_sess_t *ist = itask->it_ict->ict_sess;
2551 	avl_index_t		where;
2552 
2553 	/*
2554 	 * Sanity check the ITT and ensure that this task does not already
2555 	 * exist.  If not then add the task to the session task list.
2556 	 */
2557 	mutex_enter(&ist->ist_mutex);
2558 	mutex_enter(&itask->it_mutex);
2559 	itask->it_active = 1;
2560 	if (avl_find(&ist->ist_task_list, itask, &where) == NULL) {
2561 		/* New task, add to AVL */
2562 		avl_insert(&ist->ist_task_list, itask, where);
2563 		mutex_exit(&itask->it_mutex);
2564 		mutex_exit(&ist->ist_mutex);
2565 		return (IDM_STATUS_SUCCESS);
2566 	}
2567 	mutex_exit(&itask->it_mutex);
2568 	mutex_exit(&ist->ist_mutex);
2569 
2570 	return (IDM_STATUS_REJECT);
2571 }
2572 
2573 static void
2574 iscsit_task_done(iscsit_task_t *itask)
2575 {
2576 	iscsit_sess_t *ist = itask->it_ict->ict_sess;
2577 
2578 	mutex_enter(&ist->ist_mutex);
2579 	mutex_enter(&itask->it_mutex);
2580 	if (itask->it_active) {
2581 		avl_remove(&ist->ist_task_list, itask);
2582 		itask->it_active = 0;
2583 	}
2584 	mutex_exit(&itask->it_mutex);
2585 	mutex_exit(&ist->ist_mutex);
2586 }
2587 
2588 /*
2589  * iscsit status PDU cache
2590  */
2591 
2592 /*ARGSUSED*/
2593 static int
2594 iscsit_status_pdu_constructor(void *pdu_void, void *arg, int flags)
2595 {
2596 	idm_pdu_t *pdu = pdu_void;
2597 	iscsi_scsi_rsp_hdr_t *rsp;
2598 
2599 	bzero(pdu, sizeof (idm_pdu_t));
2600 	pdu->isp_callback = iscsit_send_good_status_done;
2601 	pdu->isp_magic = IDM_PDU_MAGIC;
2602 	pdu->isp_hdr = (iscsi_hdr_t *)(pdu + 1); /* Ptr arithmetic */
2603 	pdu->isp_hdrlen = sizeof (iscsi_hdr_t);
2604 
2605 	/* Setup status response */
2606 	rsp = (iscsi_scsi_rsp_hdr_t *)pdu->isp_hdr;
2607 	bzero(rsp, sizeof (*rsp));
2608 	rsp->opcode = ISCSI_OP_SCSI_RSP;
2609 	rsp->flags = ISCSI_FLAG_FINAL;
2610 	rsp->response = ISCSI_STATUS_CMD_COMPLETED;
2611 
2612 	return (0);
2613 }
2614 
2615 /*
2616  * iscsit private data handler
2617  */
2618 
2619 /*ARGSUSED*/
2620 static void
2621 iscsit_pp_cb(struct stmf_port_provider *pp, int cmd, void *arg, uint32_t flags)
2622 {
2623 	it_config_t		*cfg;
2624 	nvlist_t		*nvl;
2625 
2626 	if ((cmd != STMF_PROVIDER_DATA_UPDATED) || (arg == NULL)) {
2627 		return;
2628 	}
2629 
2630 	nvl = (nvlist_t *)arg;
2631 
2632 	/* Translate nvlist */
2633 	if (it_nv_to_config(nvl, &cfg) != 0) {
2634 		cmn_err(CE_WARN, "Configuration is invalid");
2635 		return;
2636 	}
2637 
2638 	/* Update config */
2639 	(void) iscsit_config_merge(cfg);
2640 
2641 	it_config_free_cmn(cfg);
2642 }
2643 
2644 
2645 static it_cfg_status_t
2646 iscsit_config_merge(it_config_t *in_cfg)
2647 {
2648 	it_cfg_status_t	status;
2649 	it_config_t	*cfg;
2650 	it_config_t	tmp_cfg;
2651 	list_t		tpg_del_list;
2652 
2653 	if (in_cfg) {
2654 		cfg = in_cfg;
2655 	} else {
2656 		/* Make empty config */
2657 		bzero(&tmp_cfg, sizeof (tmp_cfg));
2658 		cfg = &tmp_cfg;
2659 	}
2660 
2661 	list_create(&tpg_del_list,  sizeof (iscsit_tpg_t),
2662 	    offsetof(iscsit_tpg_t, tpg_delete_ln));
2663 
2664 	/*
2665 	 * Update targets, initiator contexts, target portal groups,
2666 	 * and iSNS client
2667 	 */
2668 	ISCSIT_GLOBAL_LOCK(RW_WRITER);
2669 	if (((status = iscsit_config_merge_tpg(cfg, &tpg_del_list))
2670 	    != 0) ||
2671 	    ((status = iscsit_config_merge_tgt(cfg)) != 0) ||
2672 	    ((status = iscsit_config_merge_ini(cfg)) != 0) ||
2673 	    ((status = isnst_config_merge(cfg)) != 0)) {
2674 		ISCSIT_GLOBAL_UNLOCK();
2675 		return (status);
2676 	}
2677 
2678 	/* Update other global config parameters */
2679 	if (iscsit_global.global_props) {
2680 		nvlist_free(iscsit_global.global_props);
2681 		iscsit_global.global_props = NULL;
2682 	}
2683 	if (in_cfg) {
2684 		(void) nvlist_dup(cfg->config_global_properties,
2685 		    &iscsit_global.global_props, KM_SLEEP);
2686 	}
2687 	ISCSIT_GLOBAL_UNLOCK();
2688 
2689 	iscsit_config_destroy_tpgs(&tpg_del_list);
2690 
2691 	list_destroy(&tpg_del_list);
2692 
2693 	return (ITCFG_SUCCESS);
2694 }
2695 
2696 /*
2697  * iscsit_sna_lt[e]
2698  *
2699  * Compare serial numbers using serial number arithmetic as defined in
2700  * RFC 1982.
2701  *
2702  * NOTE: This code is duplicated in the isns server as well as iscsitgtd.  It
2703  * ought to be common.
2704  */
2705 
2706 static int
2707 iscsit_sna_lt(uint32_t sn1, uint32_t sn2)
2708 {
2709 	return ((sn1 != sn2) &&
2710 	    (((sn1 < sn2) && ((sn2 - sn1) < ISCSIT_SNA32_CHECK)) ||
2711 	    ((sn1 > sn2) && ((sn1 - sn2) > ISCSIT_SNA32_CHECK))));
2712 }
2713 
2714 static int
2715 iscsit_sna_lte(uint32_t sn1, uint32_t sn2)
2716 {
2717 	return ((sn1 == sn2) ||
2718 	    (((sn1 < sn2) && ((sn2 - sn1) < ISCSIT_SNA32_CHECK)) ||
2719 	    ((sn1 > sn2) && ((sn1 - sn2) > ISCSIT_SNA32_CHECK))));
2720 }
2721 
2722 
2723 static boolean_t
2724 iscsit_cmdsn_in_window(iscsit_conn_t *ict, uint32_t cmdsn)
2725 {
2726 	iscsit_sess_t	*ist = ict->ict_sess;
2727 	int		rval = B_TRUE;
2728 
2729 	ist = ict->ict_sess;
2730 
2731 	rw_enter(&ist->ist_sn_rwlock, RW_READER);
2732 
2733 	/*
2734 	 * If cmdsn is less than ist_expcmdsn - iscsit_cmd_window() or
2735 	 * greater than ist_expcmdsn, it's not in the window.
2736 	 */
2737 
2738 	if (iscsit_sna_lt(cmdsn, (ist->ist_expcmdsn - iscsit_cmd_window())) ||
2739 	    !iscsit_sna_lte(cmdsn, ist->ist_expcmdsn)) {
2740 		rval = B_FALSE;
2741 	}
2742 
2743 	rw_exit(&ist->ist_sn_rwlock);
2744 
2745 	return (rval);
2746 }
2747