ctl_frontend_iscsi.c revision 287764
1/*-
2 * Copyright (c) 2012 The FreeBSD Foundation
3 * All rights reserved.
4 *
5 * This software was developed by Edward Tomasz Napierala under sponsorship
6 * from the FreeBSD Foundation.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 * $FreeBSD: head/sys/cam/ctl/ctl_frontend_iscsi.c 287764 2015-09-13 20:22:18Z mav $
30 */
31
32/*
33 * CTL frontend for the iSCSI protocol.
34 */
35
36#include <sys/cdefs.h>
37__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl_frontend_iscsi.c 287764 2015-09-13 20:22:18Z mav $");
38
39#include <sys/param.h>
40#include <sys/capsicum.h>
41#include <sys/condvar.h>
42#include <sys/file.h>
43#include <sys/kernel.h>
44#include <sys/kthread.h>
45#include <sys/lock.h>
46#include <sys/malloc.h>
47#include <sys/module.h>
48#include <sys/mutex.h>
49#include <sys/queue.h>
50#include <sys/sbuf.h>
51#include <sys/sysctl.h>
52#include <sys/systm.h>
53#include <sys/uio.h>
54#include <sys/unistd.h>
55#include <vm/uma.h>
56
57#include <cam/scsi/scsi_all.h>
58#include <cam/scsi/scsi_da.h>
59#include <cam/ctl/ctl_io.h>
60#include <cam/ctl/ctl.h>
61#include <cam/ctl/ctl_backend.h>
62#include <cam/ctl/ctl_error.h>
63#include <cam/ctl/ctl_frontend.h>
64#include <cam/ctl/ctl_debug.h>
65#include <cam/ctl/ctl_ha.h>
66#include <cam/ctl/ctl_ioctl.h>
67#include <cam/ctl/ctl_private.h>
68
69#include <dev/iscsi/icl.h>
70#include <dev/iscsi/icl_wrappers.h>
71#include <dev/iscsi/iscsi_proto.h>
72#include <cam/ctl/ctl_frontend_iscsi.h>
73
74#ifdef ICL_KERNEL_PROXY
75#include <sys/socketvar.h>
76#endif
77
78#ifdef ICL_KERNEL_PROXY
79FEATURE(cfiscsi_kernel_proxy, "iSCSI target built with ICL_KERNEL_PROXY");
80#endif
81
82static MALLOC_DEFINE(M_CFISCSI, "cfiscsi", "Memory used for CTL iSCSI frontend");
83static uma_zone_t cfiscsi_data_wait_zone;
84
85SYSCTL_NODE(_kern_cam_ctl, OID_AUTO, iscsi, CTLFLAG_RD, 0,
86    "CAM Target Layer iSCSI Frontend");
87static int debug = 1;
88SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, debug, CTLFLAG_RWTUN,
89    &debug, 1, "Enable debug messages");
90static int ping_timeout = 5;
91SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, ping_timeout, CTLFLAG_RWTUN,
92    &ping_timeout, 5, "Interval between ping (NOP-Out) requests, in seconds");
93static int login_timeout = 60;
94SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, login_timeout, CTLFLAG_RWTUN,
95    &login_timeout, 60, "Time to wait for ctld(8) to finish Login Phase, in seconds");
96static int maxcmdsn_delta = 256;
97SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, maxcmdsn_delta, CTLFLAG_RWTUN,
98    &maxcmdsn_delta, 256, "Number of commands the initiator can send "
99    "without confirmation");
100
101#define	CFISCSI_DEBUG(X, ...)						\
102	do {								\
103		if (debug > 1) {					\
104			printf("%s: " X "\n",				\
105			    __func__, ## __VA_ARGS__);			\
106		}							\
107	} while (0)
108
109#define	CFISCSI_WARN(X, ...)						\
110	do {								\
111		if (debug > 0) {					\
112			printf("WARNING: %s: " X "\n",			\
113			    __func__, ## __VA_ARGS__);			\
114		}							\
115	} while (0)
116
117#define	CFISCSI_SESSION_DEBUG(S, X, ...)				\
118	do {								\
119		if (debug > 1) {					\
120			printf("%s: %s (%s): " X "\n",			\
121			    __func__, S->cs_initiator_addr,		\
122			    S->cs_initiator_name, ## __VA_ARGS__);	\
123		}							\
124	} while (0)
125
126#define	CFISCSI_SESSION_WARN(S, X, ...)					\
127	do  {								\
128		if (debug > 0) {					\
129			printf("WARNING: %s (%s): " X "\n",		\
130			    S->cs_initiator_addr,			\
131			    S->cs_initiator_name, ## __VA_ARGS__);	\
132		}							\
133	} while (0)
134
135#define CFISCSI_SESSION_LOCK(X)		mtx_lock(&X->cs_lock)
136#define CFISCSI_SESSION_UNLOCK(X)	mtx_unlock(&X->cs_lock)
137#define CFISCSI_SESSION_LOCK_ASSERT(X)	mtx_assert(&X->cs_lock, MA_OWNED)
138
139#define	CONN_SESSION(X)			((struct cfiscsi_session *)(X)->ic_prv0)
140#define	PDU_SESSION(X)			CONN_SESSION((X)->ip_conn)
141#define	PDU_EXPDATASN(X)		(X)->ip_prv0
142#define	PDU_TOTAL_TRANSFER_LEN(X)	(X)->ip_prv1
143#define	PDU_R2TSN(X)			(X)->ip_prv2
144
145int		cfiscsi_init(void);
146static void	cfiscsi_online(void *arg);
147static void	cfiscsi_offline(void *arg);
148static int	cfiscsi_info(void *arg, struct sbuf *sb);
149static int	cfiscsi_ioctl(struct cdev *dev,
150		    u_long cmd, caddr_t addr, int flag, struct thread *td);
151static void	cfiscsi_datamove(union ctl_io *io);
152static void	cfiscsi_datamove_in(union ctl_io *io);
153static void	cfiscsi_datamove_out(union ctl_io *io);
154static void	cfiscsi_done(union ctl_io *io);
155static bool	cfiscsi_pdu_update_cmdsn(const struct icl_pdu *request);
156static void	cfiscsi_pdu_handle_nop_out(struct icl_pdu *request);
157static void	cfiscsi_pdu_handle_scsi_command(struct icl_pdu *request);
158static void	cfiscsi_pdu_handle_task_request(struct icl_pdu *request);
159static void	cfiscsi_pdu_handle_data_out(struct icl_pdu *request);
160static void	cfiscsi_pdu_handle_logout_request(struct icl_pdu *request);
161static void	cfiscsi_session_terminate(struct cfiscsi_session *cs);
162static struct cfiscsi_data_wait	*cfiscsi_data_wait_new(
163		    struct cfiscsi_session *cs, union ctl_io *io,
164		    uint32_t initiator_task_tag,
165		    uint32_t *target_transfer_tagp);
166static void	cfiscsi_data_wait_free(struct cfiscsi_session *cs,
167		    struct cfiscsi_data_wait *cdw);
168static struct cfiscsi_target	*cfiscsi_target_find(struct cfiscsi_softc
169		    *softc, const char *name, uint16_t tag);
170static struct cfiscsi_target	*cfiscsi_target_find_or_create(
171    struct cfiscsi_softc *softc, const char *name, const char *alias,
172    uint16_t tag);
173static void	cfiscsi_target_release(struct cfiscsi_target *ct);
174static void	cfiscsi_session_delete(struct cfiscsi_session *cs);
175
176static struct cfiscsi_softc cfiscsi_softc;
177extern struct ctl_softc *control_softc;
178
179static struct ctl_frontend cfiscsi_frontend =
180{
181	.name = "iscsi",
182	.init = cfiscsi_init,
183	.ioctl = cfiscsi_ioctl,
184};
185CTL_FRONTEND_DECLARE(ctlcfiscsi, cfiscsi_frontend);
186MODULE_DEPEND(ctlcfiscsi, icl, 1, 1, 1);
187
188static struct icl_pdu *
189cfiscsi_pdu_new_response(struct icl_pdu *request, int flags)
190{
191
192	return (icl_pdu_new(request->ip_conn, flags));
193}
194
195static bool
196cfiscsi_pdu_update_cmdsn(const struct icl_pdu *request)
197{
198	const struct iscsi_bhs_scsi_command *bhssc;
199	struct cfiscsi_session *cs;
200	uint32_t cmdsn, expstatsn;
201
202	cs = PDU_SESSION(request);
203
204	/*
205	 * Every incoming PDU - not just NOP-Out - resets the ping timer.
206	 * The purpose of the timeout is to reset the connection when it stalls;
207	 * we don't want this to happen when NOP-In or NOP-Out ends up delayed
208	 * in some queue.
209	 *
210	 * XXX: Locking?
211	 */
212	cs->cs_timeout = 0;
213
214	/*
215	 * Data-Out PDUs don't contain CmdSN.
216	 */
217	if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
218	    ISCSI_BHS_OPCODE_SCSI_DATA_OUT)
219		return (false);
220
221	/*
222	 * We're only using fields common for all the request
223	 * (initiator -> target) PDUs.
224	 */
225	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
226	cmdsn = ntohl(bhssc->bhssc_cmdsn);
227	expstatsn = ntohl(bhssc->bhssc_expstatsn);
228
229	CFISCSI_SESSION_LOCK(cs);
230#if 0
231	if (expstatsn != cs->cs_statsn) {
232		CFISCSI_SESSION_DEBUG(cs, "received PDU with ExpStatSN %d, "
233		    "while current StatSN is %d", expstatsn,
234		    cs->cs_statsn);
235	}
236#endif
237
238	if ((request->ip_bhs->bhs_opcode & ISCSI_BHS_OPCODE_IMMEDIATE) == 0) {
239		/*
240		 * The target MUST silently ignore any non-immediate command
241		 * outside of this range.
242		 */
243		if (ISCSI_SNLT(cmdsn, cs->cs_cmdsn) ||
244		    ISCSI_SNGT(cmdsn, cs->cs_cmdsn + maxcmdsn_delta)) {
245			CFISCSI_SESSION_UNLOCK(cs);
246			CFISCSI_SESSION_WARN(cs, "received PDU with CmdSN %u, "
247			    "while expected %u", cmdsn, cs->cs_cmdsn);
248			return (true);
249		}
250
251		/*
252		 * We don't support multiple connections now, so any
253		 * discontinuity in CmdSN means lost PDUs.  Since we don't
254		 * support PDU retransmission -- terminate the connection.
255		 */
256		if (cmdsn != cs->cs_cmdsn) {
257			CFISCSI_SESSION_UNLOCK(cs);
258			CFISCSI_SESSION_WARN(cs, "received PDU with CmdSN %u, "
259			    "while expected %u; dropping connection",
260			    cmdsn, cs->cs_cmdsn);
261			cfiscsi_session_terminate(cs);
262			return (true);
263		}
264		cs->cs_cmdsn++;
265	}
266
267	CFISCSI_SESSION_UNLOCK(cs);
268
269	return (false);
270}
271
272static void
273cfiscsi_pdu_handle(struct icl_pdu *request)
274{
275	struct cfiscsi_session *cs;
276	bool ignore;
277
278	cs = PDU_SESSION(request);
279
280	ignore = cfiscsi_pdu_update_cmdsn(request);
281	if (ignore) {
282		icl_pdu_free(request);
283		return;
284	}
285
286	/*
287	 * Handle the PDU; this includes e.g. receiving the remaining
288	 * part of PDU and submitting the SCSI command to CTL
289	 * or queueing a reply.  The handling routine is responsible
290	 * for freeing the PDU when it's no longer needed.
291	 */
292	switch (request->ip_bhs->bhs_opcode &
293	    ~ISCSI_BHS_OPCODE_IMMEDIATE) {
294	case ISCSI_BHS_OPCODE_NOP_OUT:
295		cfiscsi_pdu_handle_nop_out(request);
296		break;
297	case ISCSI_BHS_OPCODE_SCSI_COMMAND:
298		cfiscsi_pdu_handle_scsi_command(request);
299		break;
300	case ISCSI_BHS_OPCODE_TASK_REQUEST:
301		cfiscsi_pdu_handle_task_request(request);
302		break;
303	case ISCSI_BHS_OPCODE_SCSI_DATA_OUT:
304		cfiscsi_pdu_handle_data_out(request);
305		break;
306	case ISCSI_BHS_OPCODE_LOGOUT_REQUEST:
307		cfiscsi_pdu_handle_logout_request(request);
308		break;
309	default:
310		CFISCSI_SESSION_WARN(cs, "received PDU with unsupported "
311		    "opcode 0x%x; dropping connection",
312		    request->ip_bhs->bhs_opcode);
313		icl_pdu_free(request);
314		cfiscsi_session_terminate(cs);
315	}
316
317}
318
319static void
320cfiscsi_receive_callback(struct icl_pdu *request)
321{
322	struct cfiscsi_session *cs;
323
324	cs = PDU_SESSION(request);
325
326#ifdef ICL_KERNEL_PROXY
327	if (cs->cs_waiting_for_ctld || cs->cs_login_phase) {
328		if (cs->cs_login_pdu == NULL)
329			cs->cs_login_pdu = request;
330		else
331			icl_pdu_free(request);
332		cv_signal(&cs->cs_login_cv);
333		return;
334	}
335#endif
336
337	cfiscsi_pdu_handle(request);
338}
339
340static void
341cfiscsi_error_callback(struct icl_conn *ic)
342{
343	struct cfiscsi_session *cs;
344
345	cs = CONN_SESSION(ic);
346
347	CFISCSI_SESSION_WARN(cs, "connection error; dropping connection");
348	cfiscsi_session_terminate(cs);
349}
350
351static int
352cfiscsi_pdu_prepare(struct icl_pdu *response)
353{
354	struct cfiscsi_session *cs;
355	struct iscsi_bhs_scsi_response *bhssr;
356	bool advance_statsn = true;
357
358	cs = PDU_SESSION(response);
359
360	CFISCSI_SESSION_LOCK_ASSERT(cs);
361
362	/*
363	 * We're only using fields common for all the response
364	 * (target -> initiator) PDUs.
365	 */
366	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
367
368	/*
369	 * 10.8.3: "The StatSN for this connection is not advanced
370	 * after this PDU is sent."
371	 */
372	if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_R2T)
373		advance_statsn = false;
374
375	/*
376	 * 10.19.2: "However, when the Initiator Task Tag is set to 0xffffffff,
377	 * StatSN for the connection is not advanced after this PDU is sent."
378	 */
379	if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_NOP_IN &&
380	    bhssr->bhssr_initiator_task_tag == 0xffffffff)
381		advance_statsn = false;
382
383	/*
384	 * See the comment below - StatSN is not meaningful and must
385	 * not be advanced.
386	 */
387	if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_SCSI_DATA_IN &&
388	    (bhssr->bhssr_flags & BHSDI_FLAGS_S) == 0)
389		advance_statsn = false;
390
391	/*
392	 * 10.7.3: "The fields StatSN, Status, and Residual Count
393	 * only have meaningful content if the S bit is set to 1."
394	 */
395	if (bhssr->bhssr_opcode != ISCSI_BHS_OPCODE_SCSI_DATA_IN ||
396	    (bhssr->bhssr_flags & BHSDI_FLAGS_S))
397		bhssr->bhssr_statsn = htonl(cs->cs_statsn);
398	bhssr->bhssr_expcmdsn = htonl(cs->cs_cmdsn);
399	bhssr->bhssr_maxcmdsn = htonl(cs->cs_cmdsn + maxcmdsn_delta);
400
401	if (advance_statsn)
402		cs->cs_statsn++;
403
404	return (0);
405}
406
407static void
408cfiscsi_pdu_queue(struct icl_pdu *response)
409{
410	struct cfiscsi_session *cs;
411
412	cs = PDU_SESSION(response);
413
414	CFISCSI_SESSION_LOCK(cs);
415	cfiscsi_pdu_prepare(response);
416	icl_pdu_queue(response);
417	CFISCSI_SESSION_UNLOCK(cs);
418}
419
420static uint32_t
421cfiscsi_decode_lun(uint64_t encoded)
422{
423	uint8_t lun[8];
424	uint32_t result;
425
426	/*
427	 * The LUN field in iSCSI PDUs may look like an ordinary 64 bit number,
428	 * but is in fact an evil, multidimensional structure defined
429	 * in SCSI Architecture Model 5 (SAM-5), section 4.6.
430	 */
431	memcpy(lun, &encoded, sizeof(lun));
432	switch (lun[0] & 0xC0) {
433	case 0x00:
434		if ((lun[0] & 0x3f) != 0 || lun[2] != 0 || lun[3] != 0 ||
435		    lun[4] != 0 || lun[5] != 0 || lun[6] != 0 || lun[7] != 0) {
436			CFISCSI_WARN("malformed LUN "
437			    "(peripheral device addressing method): 0x%jx",
438			    (uintmax_t)encoded);
439			result = 0xffffffff;
440			break;
441		}
442		result = lun[1];
443		break;
444	case 0x40:
445		if (lun[2] != 0 || lun[3] != 0 || lun[4] != 0 || lun[5] != 0 ||
446		    lun[6] != 0 || lun[7] != 0) {
447			CFISCSI_WARN("malformed LUN "
448			    "(flat address space addressing method): 0x%jx",
449			    (uintmax_t)encoded);
450			result = 0xffffffff;
451			break;
452		}
453		result = ((lun[0] & 0x3f) << 8) + lun[1];
454		break;
455	case 0xC0:
456		if (lun[0] != 0xD2 || lun[4] != 0 || lun[5] != 0 ||
457		    lun[6] != 0 || lun[7] != 0) {
458			CFISCSI_WARN("malformed LUN (extended flat "
459			    "address space addressing method): 0x%jx",
460			    (uintmax_t)encoded);
461			result = 0xffffffff;
462			break;
463		}
464		result = (lun[1] << 16) + (lun[2] << 8) + lun[3];
465	default:
466		CFISCSI_WARN("unsupported LUN format 0x%jx",
467		    (uintmax_t)encoded);
468		result = 0xffffffff;
469		break;
470	}
471
472	return (result);
473}
474
475static void
476cfiscsi_pdu_handle_nop_out(struct icl_pdu *request)
477{
478	struct cfiscsi_session *cs;
479	struct iscsi_bhs_nop_out *bhsno;
480	struct iscsi_bhs_nop_in *bhsni;
481	struct icl_pdu *response;
482	void *data = NULL;
483	size_t datasize;
484	int error;
485
486	cs = PDU_SESSION(request);
487	bhsno = (struct iscsi_bhs_nop_out *)request->ip_bhs;
488
489	if (bhsno->bhsno_initiator_task_tag == 0xffffffff) {
490		/*
491		 * Nothing to do, iscsi_pdu_update_statsn() already
492		 * zeroed the timeout.
493		 */
494		icl_pdu_free(request);
495		return;
496	}
497
498	datasize = icl_pdu_data_segment_length(request);
499	if (datasize > 0) {
500		data = malloc(datasize, M_CFISCSI, M_NOWAIT | M_ZERO);
501		if (data == NULL) {
502			CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
503			    "dropping connection");
504			icl_pdu_free(request);
505			cfiscsi_session_terminate(cs);
506			return;
507		}
508		icl_pdu_get_data(request, 0, data, datasize);
509	}
510
511	response = cfiscsi_pdu_new_response(request, M_NOWAIT);
512	if (response == NULL) {
513		CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
514		    "droppping connection");
515		free(data, M_CFISCSI);
516		icl_pdu_free(request);
517		cfiscsi_session_terminate(cs);
518		return;
519	}
520	bhsni = (struct iscsi_bhs_nop_in *)response->ip_bhs;
521	bhsni->bhsni_opcode = ISCSI_BHS_OPCODE_NOP_IN;
522	bhsni->bhsni_flags = 0x80;
523	bhsni->bhsni_initiator_task_tag = bhsno->bhsno_initiator_task_tag;
524	bhsni->bhsni_target_transfer_tag = 0xffffffff;
525	if (datasize > 0) {
526		error = icl_pdu_append_data(response, data, datasize, M_NOWAIT);
527		if (error != 0) {
528			CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
529			    "dropping connection");
530			free(data, M_CFISCSI);
531			icl_pdu_free(request);
532			icl_pdu_free(response);
533			cfiscsi_session_terminate(cs);
534			return;
535		}
536		free(data, M_CFISCSI);
537	}
538
539	icl_pdu_free(request);
540	cfiscsi_pdu_queue(response);
541}
542
543static void
544cfiscsi_pdu_handle_scsi_command(struct icl_pdu *request)
545{
546	struct iscsi_bhs_scsi_command *bhssc;
547	struct cfiscsi_session *cs;
548	union ctl_io *io;
549	int error;
550
551	cs = PDU_SESSION(request);
552	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
553	//CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
554	//    bhssc->bhssc_initiator_task_tag);
555
556	if (request->ip_data_len > 0 && cs->cs_immediate_data == false) {
557		CFISCSI_SESSION_WARN(cs, "unsolicited data with "
558		    "ImmediateData=No; dropping connection");
559		icl_pdu_free(request);
560		cfiscsi_session_terminate(cs);
561		return;
562	}
563	io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
564	ctl_zero_io(io);
565	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = request;
566	io->io_hdr.io_type = CTL_IO_SCSI;
567	io->io_hdr.nexus.initid = cs->cs_ctl_initid;
568	io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
569	io->io_hdr.nexus.targ_lun = cfiscsi_decode_lun(bhssc->bhssc_lun);
570	io->scsiio.tag_num = bhssc->bhssc_initiator_task_tag;
571	switch ((bhssc->bhssc_flags & BHSSC_FLAGS_ATTR)) {
572	case BHSSC_FLAGS_ATTR_UNTAGGED:
573		io->scsiio.tag_type = CTL_TAG_UNTAGGED;
574		break;
575	case BHSSC_FLAGS_ATTR_SIMPLE:
576		io->scsiio.tag_type = CTL_TAG_SIMPLE;
577		break;
578	case BHSSC_FLAGS_ATTR_ORDERED:
579        	io->scsiio.tag_type = CTL_TAG_ORDERED;
580		break;
581	case BHSSC_FLAGS_ATTR_HOQ:
582        	io->scsiio.tag_type = CTL_TAG_HEAD_OF_QUEUE;
583		break;
584	case BHSSC_FLAGS_ATTR_ACA:
585		io->scsiio.tag_type = CTL_TAG_ACA;
586		break;
587	default:
588		io->scsiio.tag_type = CTL_TAG_UNTAGGED;
589		CFISCSI_SESSION_WARN(cs, "unhandled tag type %d",
590		    bhssc->bhssc_flags & BHSSC_FLAGS_ATTR);
591		break;
592	}
593	io->scsiio.cdb_len = sizeof(bhssc->bhssc_cdb); /* Which is 16. */
594	memcpy(io->scsiio.cdb, bhssc->bhssc_cdb, sizeof(bhssc->bhssc_cdb));
595	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
596	error = ctl_queue(io);
597	if (error != CTL_RETVAL_COMPLETE) {
598		CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d; "
599		    "dropping connection", error);
600		ctl_free_io(io);
601		refcount_release(&cs->cs_outstanding_ctl_pdus);
602		icl_pdu_free(request);
603		cfiscsi_session_terminate(cs);
604	}
605}
606
607static void
608cfiscsi_pdu_handle_task_request(struct icl_pdu *request)
609{
610	struct iscsi_bhs_task_management_request *bhstmr;
611	struct iscsi_bhs_task_management_response *bhstmr2;
612	struct icl_pdu *response;
613	struct cfiscsi_session *cs;
614	union ctl_io *io;
615	int error;
616
617	cs = PDU_SESSION(request);
618	bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
619	io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
620	ctl_zero_io(io);
621	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = request;
622	io->io_hdr.io_type = CTL_IO_TASK;
623	io->io_hdr.nexus.initid = cs->cs_ctl_initid;
624	io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
625	io->io_hdr.nexus.targ_lun = cfiscsi_decode_lun(bhstmr->bhstmr_lun);
626	io->taskio.tag_type = CTL_TAG_SIMPLE; /* XXX */
627
628	switch (bhstmr->bhstmr_function & ~0x80) {
629	case BHSTMR_FUNCTION_ABORT_TASK:
630#if 0
631		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_ABORT_TASK");
632#endif
633		io->taskio.task_action = CTL_TASK_ABORT_TASK;
634		io->taskio.tag_num = bhstmr->bhstmr_referenced_task_tag;
635		break;
636	case BHSTMR_FUNCTION_ABORT_TASK_SET:
637#if 0
638		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_ABORT_TASK_SET");
639#endif
640		io->taskio.task_action = CTL_TASK_ABORT_TASK_SET;
641		break;
642	case BHSTMR_FUNCTION_LOGICAL_UNIT_RESET:
643#if 0
644		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_LOGICAL_UNIT_RESET");
645#endif
646		io->taskio.task_action = CTL_TASK_LUN_RESET;
647		break;
648	case BHSTMR_FUNCTION_TARGET_WARM_RESET:
649#if 0
650		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_TARGET_WARM_RESET");
651#endif
652		io->taskio.task_action = CTL_TASK_TARGET_RESET;
653		break;
654	case BHSTMR_FUNCTION_TARGET_COLD_RESET:
655#if 0
656		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_TARGET_COLD_RESET");
657#endif
658		io->taskio.task_action = CTL_TASK_TARGET_RESET;
659		break;
660	default:
661		CFISCSI_SESSION_DEBUG(cs, "unsupported function 0x%x",
662		    bhstmr->bhstmr_function & ~0x80);
663		ctl_free_io(io);
664
665		response = cfiscsi_pdu_new_response(request, M_NOWAIT);
666		if (response == NULL) {
667			CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
668			    "dropping connection");
669			icl_pdu_free(request);
670			cfiscsi_session_terminate(cs);
671			return;
672		}
673		bhstmr2 = (struct iscsi_bhs_task_management_response *)
674		    response->ip_bhs;
675		bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
676		bhstmr2->bhstmr_flags = 0x80;
677		bhstmr2->bhstmr_response =
678		    BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
679		bhstmr2->bhstmr_initiator_task_tag =
680		    bhstmr->bhstmr_initiator_task_tag;
681		icl_pdu_free(request);
682		cfiscsi_pdu_queue(response);
683		return;
684	}
685
686	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
687	error = ctl_queue(io);
688	if (error != CTL_RETVAL_COMPLETE) {
689		CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d; "
690		    "dropping connection", error);
691		ctl_free_io(io);
692		refcount_release(&cs->cs_outstanding_ctl_pdus);
693		icl_pdu_free(request);
694		cfiscsi_session_terminate(cs);
695	}
696}
697
698static bool
699cfiscsi_handle_data_segment(struct icl_pdu *request, struct cfiscsi_data_wait *cdw)
700{
701	struct iscsi_bhs_data_out *bhsdo;
702	struct cfiscsi_session *cs;
703	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
704	size_t copy_len, len, off, buffer_offset;
705	int ctl_sg_count;
706	union ctl_io *io;
707
708	cs = PDU_SESSION(request);
709
710	KASSERT((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
711	    ISCSI_BHS_OPCODE_SCSI_DATA_OUT ||
712	    (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
713	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
714	    ("bad opcode 0x%x", request->ip_bhs->bhs_opcode));
715
716	/*
717	 * We're only using fields common for Data-Out and SCSI Command PDUs.
718	 */
719	bhsdo = (struct iscsi_bhs_data_out *)request->ip_bhs;
720
721	io = cdw->cdw_ctl_io;
722	KASSERT((io->io_hdr.flags & CTL_FLAG_DATA_MASK) != CTL_FLAG_DATA_IN,
723	    ("CTL_FLAG_DATA_IN"));
724
725#if 0
726	CFISCSI_SESSION_DEBUG(cs, "received %zd bytes out of %d",
727	    request->ip_data_len, io->scsiio.kern_total_len);
728#endif
729
730	if (io->scsiio.kern_sg_entries > 0) {
731		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
732		ctl_sg_count = io->scsiio.kern_sg_entries;
733	} else {
734		ctl_sglist = &ctl_sg_entry;
735		ctl_sglist->addr = io->scsiio.kern_data_ptr;
736		ctl_sglist->len = io->scsiio.kern_data_len;
737		ctl_sg_count = 1;
738	}
739
740	if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
741	    ISCSI_BHS_OPCODE_SCSI_DATA_OUT)
742		buffer_offset = ntohl(bhsdo->bhsdo_buffer_offset);
743	else
744		buffer_offset = 0;
745	len = icl_pdu_data_segment_length(request);
746
747	/*
748	 * Make sure the offset, as sent by the initiator, matches the offset
749	 * we're supposed to be at in the scatter-gather list.
750	 */
751	if (buffer_offset >
752	    io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled ||
753	    buffer_offset + len <=
754	    io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled) {
755		CFISCSI_SESSION_WARN(cs, "received bad buffer offset %zd, "
756		    "expected %zd; dropping connection", buffer_offset,
757		    (size_t)io->scsiio.kern_rel_offset +
758		    (size_t)io->scsiio.ext_data_filled);
759		ctl_set_data_phase_error(&io->scsiio);
760		cfiscsi_session_terminate(cs);
761		return (true);
762	}
763
764	/*
765	 * This is the offset within the PDU data segment, as opposed
766	 * to buffer_offset, which is the offset within the task (SCSI
767	 * command).
768	 */
769	off = io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled -
770	    buffer_offset;
771
772	/*
773	 * Iterate over the scatter/gather segments, filling them with data
774	 * from the PDU data segment.  Note that this can get called multiple
775	 * times for one SCSI command; the cdw structure holds state for the
776	 * scatter/gather list.
777	 */
778	for (;;) {
779		KASSERT(cdw->cdw_sg_index < ctl_sg_count,
780		    ("cdw->cdw_sg_index >= ctl_sg_count"));
781		if (cdw->cdw_sg_len == 0) {
782			cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
783			cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
784		}
785		KASSERT(off <= len, ("len > off"));
786		copy_len = len - off;
787		if (copy_len > cdw->cdw_sg_len)
788			copy_len = cdw->cdw_sg_len;
789
790		icl_pdu_get_data(request, off, cdw->cdw_sg_addr, copy_len);
791		cdw->cdw_sg_addr += copy_len;
792		cdw->cdw_sg_len -= copy_len;
793		off += copy_len;
794		io->scsiio.ext_data_filled += copy_len;
795
796		if (cdw->cdw_sg_len == 0) {
797			/*
798			 * End of current segment.
799			 */
800			if (cdw->cdw_sg_index == ctl_sg_count - 1) {
801				/*
802				 * Last segment in scatter/gather list.
803				 */
804				break;
805			}
806			cdw->cdw_sg_index++;
807		}
808
809		if (off == len) {
810			/*
811			 * End of PDU payload.
812			 */
813			break;
814		}
815	}
816
817	if (len > off) {
818		/*
819		 * In case of unsolicited data, it's possible that the buffer
820		 * provided by CTL is smaller than negotiated FirstBurstLength.
821		 * Just ignore the superfluous data; will ask for them with R2T
822		 * on next call to cfiscsi_datamove().
823		 *
824		 * This obviously can only happen with SCSI Command PDU.
825		 */
826		if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
827		    ISCSI_BHS_OPCODE_SCSI_COMMAND)
828			return (true);
829
830		CFISCSI_SESSION_WARN(cs, "received too much data: got %zd bytes, "
831		    "expected %zd; dropping connection",
832		    icl_pdu_data_segment_length(request), off);
833		ctl_set_data_phase_error(&io->scsiio);
834		cfiscsi_session_terminate(cs);
835		return (true);
836	}
837
838	if (io->scsiio.ext_data_filled == cdw->cdw_r2t_end &&
839	    (bhsdo->bhsdo_flags & BHSDO_FLAGS_F) == 0) {
840		CFISCSI_SESSION_WARN(cs, "got the final packet without "
841		    "the F flag; flags = 0x%x; dropping connection",
842		    bhsdo->bhsdo_flags);
843		ctl_set_data_phase_error(&io->scsiio);
844		cfiscsi_session_terminate(cs);
845		return (true);
846	}
847
848	if (io->scsiio.ext_data_filled != cdw->cdw_r2t_end &&
849	    (bhsdo->bhsdo_flags & BHSDO_FLAGS_F) != 0) {
850		if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
851		    ISCSI_BHS_OPCODE_SCSI_DATA_OUT) {
852			CFISCSI_SESSION_WARN(cs, "got the final packet, but the "
853			    "transmitted size was %zd bytes instead of %d; "
854			    "dropping connection",
855			    (size_t)io->scsiio.ext_data_filled,
856			    cdw->cdw_r2t_end);
857			ctl_set_data_phase_error(&io->scsiio);
858			cfiscsi_session_terminate(cs);
859			return (true);
860		} else {
861			/*
862			 * For SCSI Command PDU, this just means we need to
863			 * solicit more data by sending R2T.
864			 */
865			return (false);
866		}
867	}
868
869	if (io->scsiio.ext_data_filled == cdw->cdw_r2t_end) {
870#if 0
871		CFISCSI_SESSION_DEBUG(cs, "no longer expecting Data-Out with target "
872		    "transfer tag 0x%x", cdw->cdw_target_transfer_tag);
873#endif
874
875		return (true);
876	}
877
878	return (false);
879}
880
881static void
882cfiscsi_pdu_handle_data_out(struct icl_pdu *request)
883{
884	struct iscsi_bhs_data_out *bhsdo;
885	struct cfiscsi_session *cs;
886	struct cfiscsi_data_wait *cdw = NULL;
887	union ctl_io *io;
888	bool done;
889
890	cs = PDU_SESSION(request);
891	bhsdo = (struct iscsi_bhs_data_out *)request->ip_bhs;
892
893	CFISCSI_SESSION_LOCK(cs);
894	TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next) {
895#if 0
896		CFISCSI_SESSION_DEBUG(cs, "have ttt 0x%x, itt 0x%x; looking for "
897		    "ttt 0x%x, itt 0x%x",
898		    bhsdo->bhsdo_target_transfer_tag,
899		    bhsdo->bhsdo_initiator_task_tag,
900		    cdw->cdw_target_transfer_tag, cdw->cdw_initiator_task_tag));
901#endif
902		if (bhsdo->bhsdo_target_transfer_tag ==
903		    cdw->cdw_target_transfer_tag)
904			break;
905	}
906	CFISCSI_SESSION_UNLOCK(cs);
907	if (cdw == NULL) {
908		CFISCSI_SESSION_WARN(cs, "data transfer tag 0x%x, initiator task tag "
909		    "0x%x, not found; dropping connection",
910		    bhsdo->bhsdo_target_transfer_tag, bhsdo->bhsdo_initiator_task_tag);
911		icl_pdu_free(request);
912		cfiscsi_session_terminate(cs);
913		return;
914	}
915
916	if (cdw->cdw_datasn != ntohl(bhsdo->bhsdo_datasn)) {
917		CFISCSI_SESSION_WARN(cs, "received Data-Out PDU with "
918		    "DataSN %u, while expected %u; dropping connection",
919		    ntohl(bhsdo->bhsdo_datasn), cdw->cdw_datasn);
920		icl_pdu_free(request);
921		cfiscsi_session_terminate(cs);
922		return;
923	}
924	cdw->cdw_datasn++;
925
926	io = cdw->cdw_ctl_io;
927	KASSERT((io->io_hdr.flags & CTL_FLAG_DATA_MASK) != CTL_FLAG_DATA_IN,
928	    ("CTL_FLAG_DATA_IN"));
929
930	done = cfiscsi_handle_data_segment(request, cdw);
931	if (done) {
932		CFISCSI_SESSION_LOCK(cs);
933		TAILQ_REMOVE(&cs->cs_waiting_for_data_out, cdw, cdw_next);
934		CFISCSI_SESSION_UNLOCK(cs);
935		done = (io->scsiio.ext_data_filled != cdw->cdw_r2t_end ||
936		    io->scsiio.ext_data_filled == io->scsiio.kern_data_len);
937		cfiscsi_data_wait_free(cs, cdw);
938		if (done)
939			io->scsiio.be_move_done(io);
940		else
941			cfiscsi_datamove_out(io);
942	}
943
944	icl_pdu_free(request);
945}
946
947static void
948cfiscsi_pdu_handle_logout_request(struct icl_pdu *request)
949{
950	struct iscsi_bhs_logout_request *bhslr;
951	struct iscsi_bhs_logout_response *bhslr2;
952	struct icl_pdu *response;
953	struct cfiscsi_session *cs;
954
955	cs = PDU_SESSION(request);
956	bhslr = (struct iscsi_bhs_logout_request *)request->ip_bhs;
957	switch (bhslr->bhslr_reason & 0x7f) {
958	case BHSLR_REASON_CLOSE_SESSION:
959	case BHSLR_REASON_CLOSE_CONNECTION:
960		response = cfiscsi_pdu_new_response(request, M_NOWAIT);
961		if (response == NULL) {
962			CFISCSI_SESSION_DEBUG(cs, "failed to allocate memory");
963			icl_pdu_free(request);
964			cfiscsi_session_terminate(cs);
965			return;
966		}
967		bhslr2 = (struct iscsi_bhs_logout_response *)response->ip_bhs;
968		bhslr2->bhslr_opcode = ISCSI_BHS_OPCODE_LOGOUT_RESPONSE;
969		bhslr2->bhslr_flags = 0x80;
970		bhslr2->bhslr_response = BHSLR_RESPONSE_CLOSED_SUCCESSFULLY;
971		bhslr2->bhslr_initiator_task_tag =
972		    bhslr->bhslr_initiator_task_tag;
973		icl_pdu_free(request);
974		cfiscsi_pdu_queue(response);
975		cfiscsi_session_terminate(cs);
976		break;
977	case BHSLR_REASON_REMOVE_FOR_RECOVERY:
978		response = cfiscsi_pdu_new_response(request, M_NOWAIT);
979		if (response == NULL) {
980			CFISCSI_SESSION_WARN(cs,
981			    "failed to allocate memory; dropping connection");
982			icl_pdu_free(request);
983			cfiscsi_session_terminate(cs);
984			return;
985		}
986		bhslr2 = (struct iscsi_bhs_logout_response *)response->ip_bhs;
987		bhslr2->bhslr_opcode = ISCSI_BHS_OPCODE_LOGOUT_RESPONSE;
988		bhslr2->bhslr_flags = 0x80;
989		bhslr2->bhslr_response = BHSLR_RESPONSE_RECOVERY_NOT_SUPPORTED;
990		bhslr2->bhslr_initiator_task_tag =
991		    bhslr->bhslr_initiator_task_tag;
992		icl_pdu_free(request);
993		cfiscsi_pdu_queue(response);
994		break;
995	default:
996		CFISCSI_SESSION_WARN(cs, "invalid reason 0%x; dropping connection",
997		    bhslr->bhslr_reason);
998		icl_pdu_free(request);
999		cfiscsi_session_terminate(cs);
1000		break;
1001	}
1002}
1003
1004static void
1005cfiscsi_callout(void *context)
1006{
1007	struct icl_pdu *cp;
1008	struct iscsi_bhs_nop_in *bhsni;
1009	struct cfiscsi_session *cs;
1010
1011	cs = context;
1012
1013	if (cs->cs_terminating)
1014		return;
1015
1016	callout_schedule(&cs->cs_callout, 1 * hz);
1017
1018	atomic_add_int(&cs->cs_timeout, 1);
1019
1020#ifdef ICL_KERNEL_PROXY
1021	if (cs->cs_waiting_for_ctld || cs->cs_login_phase) {
1022		if (login_timeout > 0 && cs->cs_timeout > login_timeout) {
1023			CFISCSI_SESSION_WARN(cs, "login timed out after "
1024			    "%d seconds; dropping connection", cs->cs_timeout);
1025			cfiscsi_session_terminate(cs);
1026		}
1027		return;
1028	}
1029#endif
1030
1031	if (ping_timeout <= 0) {
1032		/*
1033		 * Pings are disabled.  Don't send NOP-In in this case;
1034		 * user might have disabled pings to work around problems
1035		 * with certain initiators that can't properly handle
1036		 * NOP-In, such as iPXE.  Reset the timeout, to avoid
1037		 * triggering reconnection, should the user decide to
1038		 * reenable them.
1039		 */
1040		cs->cs_timeout = 0;
1041		return;
1042	}
1043
1044	if (cs->cs_timeout >= ping_timeout) {
1045		CFISCSI_SESSION_WARN(cs, "no ping reply (NOP-Out) after %d seconds; "
1046		    "dropping connection",  ping_timeout);
1047		cfiscsi_session_terminate(cs);
1048		return;
1049	}
1050
1051	/*
1052	 * If the ping was reset less than one second ago - which means
1053	 * that we've received some PDU during the last second - assume
1054	 * the traffic flows correctly and don't bother sending a NOP-Out.
1055	 *
1056	 * (It's 2 - one for one second, and one for incrementing is_timeout
1057	 * earlier in this routine.)
1058	 */
1059	if (cs->cs_timeout < 2)
1060		return;
1061
1062	cp = icl_pdu_new(cs->cs_conn, M_NOWAIT);
1063	if (cp == NULL) {
1064		CFISCSI_SESSION_WARN(cs, "failed to allocate memory");
1065		return;
1066	}
1067	bhsni = (struct iscsi_bhs_nop_in *)cp->ip_bhs;
1068	bhsni->bhsni_opcode = ISCSI_BHS_OPCODE_NOP_IN;
1069	bhsni->bhsni_flags = 0x80;
1070	bhsni->bhsni_initiator_task_tag = 0xffffffff;
1071
1072	cfiscsi_pdu_queue(cp);
1073}
1074
1075static struct cfiscsi_data_wait *
1076cfiscsi_data_wait_new(struct cfiscsi_session *cs, union ctl_io *io,
1077    uint32_t initiator_task_tag, uint32_t *target_transfer_tagp)
1078{
1079	struct cfiscsi_data_wait *cdw;
1080	int error;
1081
1082	cdw = uma_zalloc(cfiscsi_data_wait_zone, M_NOWAIT | M_ZERO);
1083	if (cdw == NULL) {
1084		CFISCSI_SESSION_WARN(cs,
1085		    "failed to allocate %zd bytes", sizeof(*cdw));
1086		return (NULL);
1087	}
1088
1089	error = icl_conn_transfer_setup(cs->cs_conn, io, target_transfer_tagp,
1090	    &cdw->cdw_icl_prv);
1091	if (error != 0) {
1092		CFISCSI_SESSION_WARN(cs,
1093		    "icl_conn_transfer_setup() failed with error %d", error);
1094		uma_zfree(cfiscsi_data_wait_zone, cdw);
1095		return (NULL);
1096	}
1097
1098	cdw->cdw_ctl_io = io;
1099	cdw->cdw_target_transfer_tag = *target_transfer_tagp;
1100	cdw->cdw_initiator_task_tag = initiator_task_tag;
1101
1102	return (cdw);
1103}
1104
1105static void
1106cfiscsi_data_wait_free(struct cfiscsi_session *cs,
1107    struct cfiscsi_data_wait *cdw)
1108{
1109
1110	icl_conn_transfer_done(cs->cs_conn, cdw->cdw_icl_prv);
1111	uma_zfree(cfiscsi_data_wait_zone, cdw);
1112}
1113
1114static void
1115cfiscsi_session_terminate_tasks(struct cfiscsi_session *cs)
1116{
1117	struct cfiscsi_data_wait *cdw;
1118	union ctl_io *io;
1119	int error, last, wait;
1120
1121	if (cs->cs_target == NULL)
1122		return;		/* No target yet, so nothing to do. */
1123	io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
1124	ctl_zero_io(io);
1125	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = cs;
1126	io->io_hdr.io_type = CTL_IO_TASK;
1127	io->io_hdr.nexus.initid = cs->cs_ctl_initid;
1128	io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
1129	io->io_hdr.nexus.targ_lun = 0;
1130	io->taskio.tag_type = CTL_TAG_SIMPLE; /* XXX */
1131	io->taskio.task_action = CTL_TASK_I_T_NEXUS_RESET;
1132	wait = cs->cs_outstanding_ctl_pdus;
1133	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1134	error = ctl_queue(io);
1135	if (error != CTL_RETVAL_COMPLETE) {
1136		CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d", error);
1137		refcount_release(&cs->cs_outstanding_ctl_pdus);
1138		ctl_free_io(io);
1139	}
1140
1141	CFISCSI_SESSION_LOCK(cs);
1142	while ((cdw = TAILQ_FIRST(&cs->cs_waiting_for_data_out)) != NULL) {
1143		TAILQ_REMOVE(&cs->cs_waiting_for_data_out, cdw, cdw_next);
1144		CFISCSI_SESSION_UNLOCK(cs);
1145		/*
1146		 * Set nonzero port status; this prevents backends from
1147		 * assuming that the data transfer actually succeeded
1148		 * and writing uninitialized data to disk.
1149		 */
1150		cdw->cdw_ctl_io->scsiio.io_hdr.port_status = 42;
1151		cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
1152		cfiscsi_data_wait_free(cs, cdw);
1153		CFISCSI_SESSION_LOCK(cs);
1154	}
1155	CFISCSI_SESSION_UNLOCK(cs);
1156
1157	/*
1158	 * Wait for CTL to terminate all the tasks.
1159	 */
1160	if (wait > 0)
1161		CFISCSI_SESSION_WARN(cs,
1162		    "waiting for CTL to terminate %d tasks", wait);
1163	for (;;) {
1164		refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1165		last = refcount_release(&cs->cs_outstanding_ctl_pdus);
1166		if (last != 0)
1167			break;
1168		tsleep(__DEVOLATILE(void *, &cs->cs_outstanding_ctl_pdus),
1169		    0, "cfiscsi_terminate", hz / 100);
1170	}
1171	if (wait > 0)
1172		CFISCSI_SESSION_WARN(cs, "tasks terminated");
1173}
1174
1175static void
1176cfiscsi_maintenance_thread(void *arg)
1177{
1178	struct cfiscsi_session *cs;
1179
1180	cs = arg;
1181
1182	for (;;) {
1183		CFISCSI_SESSION_LOCK(cs);
1184		if (cs->cs_terminating == false)
1185			cv_wait(&cs->cs_maintenance_cv, &cs->cs_lock);
1186		CFISCSI_SESSION_UNLOCK(cs);
1187
1188		if (cs->cs_terminating) {
1189
1190			/*
1191			 * We used to wait up to 30 seconds to deliver queued
1192			 * PDUs to the initiator.  We also tried hard to deliver
1193			 * SCSI Responses for the aborted PDUs.  We don't do
1194			 * that anymore.  We might need to revisit that.
1195			 */
1196			callout_drain(&cs->cs_callout);
1197			icl_conn_close(cs->cs_conn);
1198
1199			/*
1200			 * At this point ICL receive thread is no longer
1201			 * running; no new tasks can be queued.
1202			 */
1203			cfiscsi_session_terminate_tasks(cs);
1204			cfiscsi_session_delete(cs);
1205			kthread_exit();
1206			return;
1207		}
1208		CFISCSI_SESSION_DEBUG(cs, "nothing to do");
1209	}
1210}
1211
1212static void
1213cfiscsi_session_terminate(struct cfiscsi_session *cs)
1214{
1215
1216	if (cs->cs_terminating)
1217		return;
1218	cs->cs_terminating = true;
1219	cv_signal(&cs->cs_maintenance_cv);
1220#ifdef ICL_KERNEL_PROXY
1221	cv_signal(&cs->cs_login_cv);
1222#endif
1223}
1224
1225static int
1226cfiscsi_session_register_initiator(struct cfiscsi_session *cs)
1227{
1228	struct cfiscsi_target *ct;
1229	char *name;
1230	int i;
1231
1232	KASSERT(cs->cs_ctl_initid == -1, ("already registered"));
1233
1234	ct = cs->cs_target;
1235	name = strdup(cs->cs_initiator_id, M_CTL);
1236	i = ctl_add_initiator(&ct->ct_port, -1, 0, name);
1237	if (i < 0) {
1238		CFISCSI_SESSION_WARN(cs, "ctl_add_initiator failed with error %d",
1239		    i);
1240		cs->cs_ctl_initid = -1;
1241		return (1);
1242	}
1243	cs->cs_ctl_initid = i;
1244#if 0
1245	CFISCSI_SESSION_DEBUG(cs, "added initiator id %d", i);
1246#endif
1247
1248	return (0);
1249}
1250
1251static void
1252cfiscsi_session_unregister_initiator(struct cfiscsi_session *cs)
1253{
1254	int error;
1255
1256	if (cs->cs_ctl_initid == -1)
1257		return;
1258
1259	error = ctl_remove_initiator(&cs->cs_target->ct_port, cs->cs_ctl_initid);
1260	if (error != 0) {
1261		CFISCSI_SESSION_WARN(cs, "ctl_remove_initiator failed with error %d",
1262		    error);
1263	}
1264	cs->cs_ctl_initid = -1;
1265}
1266
1267static struct cfiscsi_session *
1268cfiscsi_session_new(struct cfiscsi_softc *softc, const char *offload)
1269{
1270	struct cfiscsi_session *cs;
1271	int error;
1272
1273	cs = malloc(sizeof(*cs), M_CFISCSI, M_NOWAIT | M_ZERO);
1274	if (cs == NULL) {
1275		CFISCSI_WARN("malloc failed");
1276		return (NULL);
1277	}
1278	cs->cs_ctl_initid = -1;
1279
1280	refcount_init(&cs->cs_outstanding_ctl_pdus, 0);
1281	TAILQ_INIT(&cs->cs_waiting_for_data_out);
1282	mtx_init(&cs->cs_lock, "cfiscsi_lock", NULL, MTX_DEF);
1283	cv_init(&cs->cs_maintenance_cv, "cfiscsi_mt");
1284#ifdef ICL_KERNEL_PROXY
1285	cv_init(&cs->cs_login_cv, "cfiscsi_login");
1286#endif
1287
1288	cs->cs_conn = icl_new_conn(offload, "cfiscsi", &cs->cs_lock);
1289	if (cs->cs_conn == NULL) {
1290		free(cs, M_CFISCSI);
1291		return (NULL);
1292	}
1293	cs->cs_conn->ic_receive = cfiscsi_receive_callback;
1294	cs->cs_conn->ic_error = cfiscsi_error_callback;
1295	cs->cs_conn->ic_prv0 = cs;
1296
1297	error = kthread_add(cfiscsi_maintenance_thread, cs, NULL, NULL, 0, 0, "cfiscsimt");
1298	if (error != 0) {
1299		CFISCSI_SESSION_WARN(cs, "kthread_add(9) failed with error %d", error);
1300		free(cs, M_CFISCSI);
1301		return (NULL);
1302	}
1303
1304	mtx_lock(&softc->lock);
1305	cs->cs_id = ++softc->last_session_id;
1306	TAILQ_INSERT_TAIL(&softc->sessions, cs, cs_next);
1307	mtx_unlock(&softc->lock);
1308
1309	/*
1310	 * Start pinging the initiator.
1311	 */
1312	callout_init(&cs->cs_callout, 1);
1313	callout_reset(&cs->cs_callout, 1 * hz, cfiscsi_callout, cs);
1314
1315	return (cs);
1316}
1317
1318static void
1319cfiscsi_session_delete(struct cfiscsi_session *cs)
1320{
1321	struct cfiscsi_softc *softc;
1322
1323	softc = &cfiscsi_softc;
1324
1325	KASSERT(cs->cs_outstanding_ctl_pdus == 0,
1326	    ("destroying session with outstanding CTL pdus"));
1327	KASSERT(TAILQ_EMPTY(&cs->cs_waiting_for_data_out),
1328	    ("destroying session with non-empty queue"));
1329
1330	cfiscsi_session_unregister_initiator(cs);
1331	if (cs->cs_target != NULL)
1332		cfiscsi_target_release(cs->cs_target);
1333	icl_conn_close(cs->cs_conn);
1334	icl_conn_free(cs->cs_conn);
1335
1336	mtx_lock(&softc->lock);
1337	TAILQ_REMOVE(&softc->sessions, cs, cs_next);
1338	cv_signal(&softc->sessions_cv);
1339	mtx_unlock(&softc->lock);
1340
1341	free(cs, M_CFISCSI);
1342}
1343
1344int
1345cfiscsi_init(void)
1346{
1347	struct cfiscsi_softc *softc;
1348	int retval;
1349
1350	softc = &cfiscsi_softc;
1351	retval = 0;
1352	bzero(softc, sizeof(*softc));
1353	mtx_init(&softc->lock, "cfiscsi", NULL, MTX_DEF);
1354
1355	cv_init(&softc->sessions_cv, "cfiscsi_sessions");
1356#ifdef ICL_KERNEL_PROXY
1357	cv_init(&softc->accept_cv, "cfiscsi_accept");
1358#endif
1359	TAILQ_INIT(&softc->sessions);
1360	TAILQ_INIT(&softc->targets);
1361
1362	cfiscsi_data_wait_zone = uma_zcreate("cfiscsi_data_wait",
1363	    sizeof(struct cfiscsi_data_wait), NULL, NULL, NULL, NULL,
1364	    UMA_ALIGN_PTR, 0);
1365
1366	return (0);
1367}
1368
1369#ifdef ICL_KERNEL_PROXY
1370static void
1371cfiscsi_accept(struct socket *so, struct sockaddr *sa, int portal_id)
1372{
1373	struct cfiscsi_session *cs;
1374
1375	cs = cfiscsi_session_new(&cfiscsi_softc, NULL);
1376	if (cs == NULL) {
1377		CFISCSI_WARN("failed to create session");
1378		return;
1379	}
1380
1381	icl_conn_handoff_sock(cs->cs_conn, so);
1382	cs->cs_initiator_sa = sa;
1383	cs->cs_portal_id = portal_id;
1384	cs->cs_waiting_for_ctld = true;
1385	cv_signal(&cfiscsi_softc.accept_cv);
1386}
1387#endif
1388
1389static void
1390cfiscsi_online(void *arg)
1391{
1392	struct cfiscsi_softc *softc;
1393	struct cfiscsi_target *ct;
1394	int online;
1395
1396	ct = (struct cfiscsi_target *)arg;
1397	softc = ct->ct_softc;
1398
1399	mtx_lock(&softc->lock);
1400	if (ct->ct_online) {
1401		mtx_unlock(&softc->lock);
1402		return;
1403	}
1404	ct->ct_online = 1;
1405	online = softc->online++;
1406	mtx_unlock(&softc->lock);
1407	if (online > 0)
1408		return;
1409
1410#ifdef ICL_KERNEL_PROXY
1411	if (softc->listener != NULL)
1412		icl_listen_free(softc->listener);
1413	softc->listener = icl_listen_new(cfiscsi_accept);
1414#endif
1415}
1416
1417static void
1418cfiscsi_offline(void *arg)
1419{
1420	struct cfiscsi_softc *softc;
1421	struct cfiscsi_target *ct;
1422	struct cfiscsi_session *cs;
1423	int online;
1424
1425	ct = (struct cfiscsi_target *)arg;
1426	softc = ct->ct_softc;
1427
1428	mtx_lock(&softc->lock);
1429	if (!ct->ct_online) {
1430		mtx_unlock(&softc->lock);
1431		return;
1432	}
1433	ct->ct_online = 0;
1434	online = --softc->online;
1435
1436	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1437		if (cs->cs_target == ct)
1438			cfiscsi_session_terminate(cs);
1439	}
1440	do {
1441		TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1442			if (cs->cs_target == ct)
1443				break;
1444		}
1445		if (cs != NULL)
1446			cv_wait(&softc->sessions_cv, &softc->lock);
1447	} while (cs != NULL && ct->ct_online == 0);
1448	mtx_unlock(&softc->lock);
1449	if (online > 0)
1450		return;
1451
1452#ifdef ICL_KERNEL_PROXY
1453	icl_listen_free(softc->listener);
1454	softc->listener = NULL;
1455#endif
1456}
1457
1458static int
1459cfiscsi_info(void *arg, struct sbuf *sb)
1460{
1461	struct cfiscsi_target *ct = (struct cfiscsi_target *)arg;
1462	int retval;
1463
1464	retval = sbuf_printf(sb, "\t<cfiscsi_state>%d</cfiscsi_state>\n",
1465	    ct->ct_state);
1466	return (retval);
1467}
1468
1469static void
1470cfiscsi_ioctl_handoff(struct ctl_iscsi *ci)
1471{
1472	struct cfiscsi_softc *softc;
1473	struct cfiscsi_session *cs, *cs2;
1474	struct cfiscsi_target *ct;
1475	struct ctl_iscsi_handoff_params *cihp;
1476	int error;
1477
1478	cihp = (struct ctl_iscsi_handoff_params *)&(ci->data);
1479	softc = &cfiscsi_softc;
1480
1481	CFISCSI_DEBUG("new connection from %s (%s) to %s",
1482	    cihp->initiator_name, cihp->initiator_addr,
1483	    cihp->target_name);
1484
1485	ct = cfiscsi_target_find(softc, cihp->target_name,
1486	    cihp->portal_group_tag);
1487	if (ct == NULL) {
1488		ci->status = CTL_ISCSI_ERROR;
1489		snprintf(ci->error_str, sizeof(ci->error_str),
1490		    "%s: target not found", __func__);
1491		return;
1492	}
1493
1494#ifdef ICL_KERNEL_PROXY
1495	if (cihp->socket > 0 && cihp->connection_id > 0) {
1496		snprintf(ci->error_str, sizeof(ci->error_str),
1497		    "both socket and connection_id set");
1498		ci->status = CTL_ISCSI_ERROR;
1499		cfiscsi_target_release(ct);
1500		return;
1501	}
1502	if (cihp->socket == 0) {
1503		mtx_lock(&cfiscsi_softc.lock);
1504		TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1505			if (cs->cs_id == cihp->connection_id)
1506				break;
1507		}
1508		if (cs == NULL) {
1509			mtx_unlock(&cfiscsi_softc.lock);
1510			snprintf(ci->error_str, sizeof(ci->error_str),
1511			    "connection not found");
1512			ci->status = CTL_ISCSI_ERROR;
1513			cfiscsi_target_release(ct);
1514			return;
1515		}
1516		mtx_unlock(&cfiscsi_softc.lock);
1517	} else {
1518#endif
1519		cs = cfiscsi_session_new(softc, cihp->offload);
1520		if (cs == NULL) {
1521			ci->status = CTL_ISCSI_ERROR;
1522			snprintf(ci->error_str, sizeof(ci->error_str),
1523			    "%s: cfiscsi_session_new failed", __func__);
1524			cfiscsi_target_release(ct);
1525			return;
1526		}
1527#ifdef ICL_KERNEL_PROXY
1528	}
1529#endif
1530
1531	/*
1532	 * First PDU of Full Feature phase has the same CmdSN as the last
1533	 * PDU from the Login Phase received from the initiator.  Thus,
1534	 * the -1 below.
1535	 */
1536	cs->cs_cmdsn = cihp->cmdsn;
1537	cs->cs_statsn = cihp->statsn;
1538	cs->cs_max_data_segment_length = cihp->max_recv_data_segment_length;
1539	cs->cs_max_burst_length = cihp->max_burst_length;
1540	cs->cs_immediate_data = !!cihp->immediate_data;
1541	if (cihp->header_digest == CTL_ISCSI_DIGEST_CRC32C)
1542		cs->cs_conn->ic_header_crc32c = true;
1543	if (cihp->data_digest == CTL_ISCSI_DIGEST_CRC32C)
1544		cs->cs_conn->ic_data_crc32c = true;
1545
1546	strlcpy(cs->cs_initiator_name,
1547	    cihp->initiator_name, sizeof(cs->cs_initiator_name));
1548	strlcpy(cs->cs_initiator_addr,
1549	    cihp->initiator_addr, sizeof(cs->cs_initiator_addr));
1550	strlcpy(cs->cs_initiator_alias,
1551	    cihp->initiator_alias, sizeof(cs->cs_initiator_alias));
1552	memcpy(cs->cs_initiator_isid,
1553	    cihp->initiator_isid, sizeof(cs->cs_initiator_isid));
1554	snprintf(cs->cs_initiator_id, sizeof(cs->cs_initiator_id),
1555	    "%s,i,0x%02x%02x%02x%02x%02x%02x", cs->cs_initiator_name,
1556	    cihp->initiator_isid[0], cihp->initiator_isid[1],
1557	    cihp->initiator_isid[2], cihp->initiator_isid[3],
1558	    cihp->initiator_isid[4], cihp->initiator_isid[5]);
1559
1560	mtx_lock(&softc->lock);
1561	if (ct->ct_online == 0) {
1562		mtx_unlock(&softc->lock);
1563		cfiscsi_session_terminate(cs);
1564		cfiscsi_target_release(ct);
1565		ci->status = CTL_ISCSI_ERROR;
1566		snprintf(ci->error_str, sizeof(ci->error_str),
1567		    "%s: port offline", __func__);
1568		return;
1569	}
1570	cs->cs_target = ct;
1571	mtx_unlock(&softc->lock);
1572
1573	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1574restart:
1575	if (!cs->cs_terminating) {
1576		mtx_lock(&softc->lock);
1577		TAILQ_FOREACH(cs2, &softc->sessions, cs_next) {
1578			if (cs2 != cs && cs2->cs_tasks_aborted == false &&
1579			    cs->cs_target == cs2->cs_target &&
1580			    strcmp(cs->cs_initiator_id, cs2->cs_initiator_id) == 0) {
1581				cfiscsi_session_terminate(cs2);
1582				mtx_unlock(&softc->lock);
1583				pause("cfiscsi_reinstate", 1);
1584				goto restart;
1585			}
1586		}
1587		mtx_unlock(&softc->lock);
1588	}
1589
1590	/*
1591	 * Register initiator with CTL.
1592	 */
1593	cfiscsi_session_register_initiator(cs);
1594
1595#ifdef ICL_KERNEL_PROXY
1596	if (cihp->socket > 0) {
1597#endif
1598		error = icl_conn_handoff(cs->cs_conn, cihp->socket);
1599		if (error != 0) {
1600			cfiscsi_session_terminate(cs);
1601			refcount_release(&cs->cs_outstanding_ctl_pdus);
1602			ci->status = CTL_ISCSI_ERROR;
1603			snprintf(ci->error_str, sizeof(ci->error_str),
1604			    "%s: icl_conn_handoff failed with error %d",
1605			    __func__, error);
1606			return;
1607		}
1608#ifdef ICL_KERNEL_PROXY
1609	}
1610#endif
1611
1612#ifdef ICL_KERNEL_PROXY
1613	cs->cs_login_phase = false;
1614
1615	/*
1616	 * First PDU of the Full Feature phase has likely already arrived.
1617	 * We have to pick it up and execute properly.
1618	 */
1619	if (cs->cs_login_pdu != NULL) {
1620		CFISCSI_SESSION_DEBUG(cs, "picking up first PDU");
1621		cfiscsi_pdu_handle(cs->cs_login_pdu);
1622		cs->cs_login_pdu = NULL;
1623	}
1624#endif
1625
1626	refcount_release(&cs->cs_outstanding_ctl_pdus);
1627	ci->status = CTL_ISCSI_OK;
1628}
1629
1630static void
1631cfiscsi_ioctl_list(struct ctl_iscsi *ci)
1632{
1633	struct ctl_iscsi_list_params *cilp;
1634	struct cfiscsi_session *cs;
1635	struct cfiscsi_softc *softc;
1636	struct sbuf *sb;
1637	int error;
1638
1639	cilp = (struct ctl_iscsi_list_params *)&(ci->data);
1640	softc = &cfiscsi_softc;
1641
1642	sb = sbuf_new(NULL, NULL, cilp->alloc_len, SBUF_FIXEDLEN);
1643	if (sb == NULL) {
1644		ci->status = CTL_ISCSI_ERROR;
1645		snprintf(ci->error_str, sizeof(ci->error_str),
1646		    "Unable to allocate %d bytes for iSCSI session list",
1647		    cilp->alloc_len);
1648		return;
1649	}
1650
1651	sbuf_printf(sb, "<ctlislist>\n");
1652	mtx_lock(&softc->lock);
1653	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1654#ifdef ICL_KERNEL_PROXY
1655		if (cs->cs_target == NULL)
1656			continue;
1657#endif
1658		error = sbuf_printf(sb, "<connection id=\"%d\">"
1659		    "<initiator>%s</initiator>"
1660		    "<initiator_addr>%s</initiator_addr>"
1661		    "<initiator_alias>%s</initiator_alias>"
1662		    "<target>%s</target>"
1663		    "<target_alias>%s</target_alias>"
1664		    "<target_portal_group_tag>%u</target_portal_group_tag>"
1665		    "<header_digest>%s</header_digest>"
1666		    "<data_digest>%s</data_digest>"
1667		    "<max_data_segment_length>%zd</max_data_segment_length>"
1668		    "<immediate_data>%d</immediate_data>"
1669		    "<iser>%d</iser>"
1670		    "<offload>%s</offload>"
1671		    "</connection>\n",
1672		    cs->cs_id,
1673		    cs->cs_initiator_name, cs->cs_initiator_addr, cs->cs_initiator_alias,
1674		    cs->cs_target->ct_name, cs->cs_target->ct_alias,
1675		    cs->cs_target->ct_tag,
1676		    cs->cs_conn->ic_header_crc32c ? "CRC32C" : "None",
1677		    cs->cs_conn->ic_data_crc32c ? "CRC32C" : "None",
1678		    cs->cs_max_data_segment_length,
1679		    cs->cs_immediate_data,
1680		    cs->cs_conn->ic_iser,
1681		    cs->cs_conn->ic_offload);
1682		if (error != 0)
1683			break;
1684	}
1685	mtx_unlock(&softc->lock);
1686	error = sbuf_printf(sb, "</ctlislist>\n");
1687	if (error != 0) {
1688		sbuf_delete(sb);
1689		ci->status = CTL_ISCSI_LIST_NEED_MORE_SPACE;
1690		snprintf(ci->error_str, sizeof(ci->error_str),
1691		    "Out of space, %d bytes is too small", cilp->alloc_len);
1692		return;
1693	}
1694	sbuf_finish(sb);
1695
1696	error = copyout(sbuf_data(sb), cilp->conn_xml, sbuf_len(sb) + 1);
1697	cilp->fill_len = sbuf_len(sb) + 1;
1698	ci->status = CTL_ISCSI_OK;
1699	sbuf_delete(sb);
1700}
1701
1702static void
1703cfiscsi_ioctl_logout(struct ctl_iscsi *ci)
1704{
1705	struct icl_pdu *response;
1706	struct iscsi_bhs_asynchronous_message *bhsam;
1707	struct ctl_iscsi_logout_params *cilp;
1708	struct cfiscsi_session *cs;
1709	struct cfiscsi_softc *softc;
1710	int found = 0;
1711
1712	cilp = (struct ctl_iscsi_logout_params *)&(ci->data);
1713	softc = &cfiscsi_softc;
1714
1715	mtx_lock(&softc->lock);
1716	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1717		if (cilp->all == 0 && cs->cs_id != cilp->connection_id &&
1718		    strcmp(cs->cs_initiator_name, cilp->initiator_name) != 0 &&
1719		    strcmp(cs->cs_initiator_addr, cilp->initiator_addr) != 0)
1720			continue;
1721
1722		response = icl_pdu_new(cs->cs_conn, M_NOWAIT);
1723		if (response == NULL) {
1724			ci->status = CTL_ISCSI_ERROR;
1725			snprintf(ci->error_str, sizeof(ci->error_str),
1726			    "Unable to allocate memory");
1727			mtx_unlock(&softc->lock);
1728			return;
1729		}
1730		bhsam =
1731		    (struct iscsi_bhs_asynchronous_message *)response->ip_bhs;
1732		bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1733		bhsam->bhsam_flags = 0x80;
1734		bhsam->bhsam_async_event = BHSAM_EVENT_TARGET_REQUESTS_LOGOUT;
1735		bhsam->bhsam_parameter3 = htons(10);
1736		cfiscsi_pdu_queue(response);
1737		found++;
1738	}
1739	mtx_unlock(&softc->lock);
1740
1741	if (found == 0) {
1742		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1743		snprintf(ci->error_str, sizeof(ci->error_str),
1744		    "No matching connections found");
1745		return;
1746	}
1747
1748	ci->status = CTL_ISCSI_OK;
1749}
1750
1751static void
1752cfiscsi_ioctl_terminate(struct ctl_iscsi *ci)
1753{
1754	struct icl_pdu *response;
1755	struct iscsi_bhs_asynchronous_message *bhsam;
1756	struct ctl_iscsi_terminate_params *citp;
1757	struct cfiscsi_session *cs;
1758	struct cfiscsi_softc *softc;
1759	int found = 0;
1760
1761	citp = (struct ctl_iscsi_terminate_params *)&(ci->data);
1762	softc = &cfiscsi_softc;
1763
1764	mtx_lock(&softc->lock);
1765	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1766		if (citp->all == 0 && cs->cs_id != citp->connection_id &&
1767		    strcmp(cs->cs_initiator_name, citp->initiator_name) != 0 &&
1768		    strcmp(cs->cs_initiator_addr, citp->initiator_addr) != 0)
1769			continue;
1770
1771		response = icl_pdu_new(cs->cs_conn, M_NOWAIT);
1772		if (response == NULL) {
1773			/*
1774			 * Oh well.  Just terminate the connection.
1775			 */
1776		} else {
1777			bhsam = (struct iscsi_bhs_asynchronous_message *)
1778			    response->ip_bhs;
1779			bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1780			bhsam->bhsam_flags = 0x80;
1781			bhsam->bhsam_0xffffffff = 0xffffffff;
1782			bhsam->bhsam_async_event =
1783			    BHSAM_EVENT_TARGET_TERMINATES_SESSION;
1784			cfiscsi_pdu_queue(response);
1785		}
1786		cfiscsi_session_terminate(cs);
1787		found++;
1788	}
1789	mtx_unlock(&softc->lock);
1790
1791	if (found == 0) {
1792		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1793		snprintf(ci->error_str, sizeof(ci->error_str),
1794		    "No matching connections found");
1795		return;
1796	}
1797
1798	ci->status = CTL_ISCSI_OK;
1799}
1800
1801static void
1802cfiscsi_ioctl_limits(struct ctl_iscsi *ci)
1803{
1804	struct ctl_iscsi_limits_params *cilp;
1805	int error;
1806
1807	cilp = (struct ctl_iscsi_limits_params *)&(ci->data);
1808
1809	error = icl_limits(cilp->offload, &cilp->data_segment_limit);
1810	if (error != 0) {
1811		ci->status = CTL_ISCSI_ERROR;
1812		snprintf(ci->error_str, sizeof(ci->error_str),
1813			"%s: icl_limits failed with error %d",
1814			__func__, error);
1815		return;
1816	}
1817
1818	ci->status = CTL_ISCSI_OK;
1819}
1820
1821#ifdef ICL_KERNEL_PROXY
1822static void
1823cfiscsi_ioctl_listen(struct ctl_iscsi *ci)
1824{
1825	struct ctl_iscsi_listen_params *cilp;
1826	struct sockaddr *sa;
1827	int error;
1828
1829	cilp = (struct ctl_iscsi_listen_params *)&(ci->data);
1830
1831	if (cfiscsi_softc.listener == NULL) {
1832		CFISCSI_DEBUG("no listener");
1833		snprintf(ci->error_str, sizeof(ci->error_str), "no listener");
1834		ci->status = CTL_ISCSI_ERROR;
1835		return;
1836	}
1837
1838	error = getsockaddr(&sa, (void *)cilp->addr, cilp->addrlen);
1839	if (error != 0) {
1840		CFISCSI_DEBUG("getsockaddr, error %d", error);
1841		snprintf(ci->error_str, sizeof(ci->error_str), "getsockaddr failed");
1842		ci->status = CTL_ISCSI_ERROR;
1843		return;
1844	}
1845
1846	error = icl_listen_add(cfiscsi_softc.listener, cilp->iser, cilp->domain,
1847	    cilp->socktype, cilp->protocol, sa, cilp->portal_id);
1848	if (error != 0) {
1849		free(sa, M_SONAME);
1850		CFISCSI_DEBUG("icl_listen_add, error %d", error);
1851		snprintf(ci->error_str, sizeof(ci->error_str),
1852		    "icl_listen_add failed, error %d", error);
1853		ci->status = CTL_ISCSI_ERROR;
1854		return;
1855	}
1856
1857	ci->status = CTL_ISCSI_OK;
1858}
1859
1860static void
1861cfiscsi_ioctl_accept(struct ctl_iscsi *ci)
1862{
1863	struct ctl_iscsi_accept_params *ciap;
1864	struct cfiscsi_session *cs;
1865	int error;
1866
1867	ciap = (struct ctl_iscsi_accept_params *)&(ci->data);
1868
1869	mtx_lock(&cfiscsi_softc.lock);
1870	for (;;) {
1871		TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1872			if (cs->cs_waiting_for_ctld)
1873				break;
1874		}
1875		if (cs != NULL)
1876			break;
1877		error = cv_wait_sig(&cfiscsi_softc.accept_cv, &cfiscsi_softc.lock);
1878		if (error != 0) {
1879			mtx_unlock(&cfiscsi_softc.lock);
1880			snprintf(ci->error_str, sizeof(ci->error_str), "interrupted");
1881			ci->status = CTL_ISCSI_ERROR;
1882			return;
1883		}
1884	}
1885	mtx_unlock(&cfiscsi_softc.lock);
1886
1887	cs->cs_waiting_for_ctld = false;
1888	cs->cs_login_phase = true;
1889
1890	ciap->connection_id = cs->cs_id;
1891	ciap->portal_id = cs->cs_portal_id;
1892	ciap->initiator_addrlen = cs->cs_initiator_sa->sa_len;
1893	error = copyout(cs->cs_initiator_sa, ciap->initiator_addr,
1894	    cs->cs_initiator_sa->sa_len);
1895	if (error != 0) {
1896		snprintf(ci->error_str, sizeof(ci->error_str),
1897		    "copyout failed with error %d", error);
1898		ci->status = CTL_ISCSI_ERROR;
1899		return;
1900	}
1901
1902	ci->status = CTL_ISCSI_OK;
1903}
1904
1905static void
1906cfiscsi_ioctl_send(struct ctl_iscsi *ci)
1907{
1908	struct ctl_iscsi_send_params *cisp;
1909	struct cfiscsi_session *cs;
1910	struct icl_pdu *ip;
1911	size_t datalen;
1912	void *data;
1913	int error;
1914
1915	cisp = (struct ctl_iscsi_send_params *)&(ci->data);
1916
1917	mtx_lock(&cfiscsi_softc.lock);
1918	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1919		if (cs->cs_id == cisp->connection_id)
1920			break;
1921	}
1922	if (cs == NULL) {
1923		mtx_unlock(&cfiscsi_softc.lock);
1924		snprintf(ci->error_str, sizeof(ci->error_str), "connection not found");
1925		ci->status = CTL_ISCSI_ERROR;
1926		return;
1927	}
1928	mtx_unlock(&cfiscsi_softc.lock);
1929
1930#if 0
1931	if (cs->cs_login_phase == false)
1932		return (EBUSY);
1933#endif
1934
1935	if (cs->cs_terminating) {
1936		snprintf(ci->error_str, sizeof(ci->error_str), "connection is terminating");
1937		ci->status = CTL_ISCSI_ERROR;
1938		return;
1939	}
1940
1941	datalen = cisp->data_segment_len;
1942	/*
1943	 * XXX
1944	 */
1945	//if (datalen > CFISCSI_MAX_DATA_SEGMENT_LENGTH) {
1946	if (datalen > 65535) {
1947		snprintf(ci->error_str, sizeof(ci->error_str), "data segment too big");
1948		ci->status = CTL_ISCSI_ERROR;
1949		return;
1950	}
1951	if (datalen > 0) {
1952		data = malloc(datalen, M_CFISCSI, M_WAITOK);
1953		error = copyin(cisp->data_segment, data, datalen);
1954		if (error != 0) {
1955			free(data, M_CFISCSI);
1956			snprintf(ci->error_str, sizeof(ci->error_str), "copyin error %d", error);
1957			ci->status = CTL_ISCSI_ERROR;
1958			return;
1959		}
1960	}
1961
1962	ip = icl_pdu_new(cs->cs_conn, M_WAITOK);
1963	memcpy(ip->ip_bhs, cisp->bhs, sizeof(*ip->ip_bhs));
1964	if (datalen > 0) {
1965		icl_pdu_append_data(ip, data, datalen, M_WAITOK);
1966		free(data, M_CFISCSI);
1967	}
1968	CFISCSI_SESSION_LOCK(cs);
1969	icl_pdu_queue(ip);
1970	CFISCSI_SESSION_UNLOCK(cs);
1971	ci->status = CTL_ISCSI_OK;
1972}
1973
1974static void
1975cfiscsi_ioctl_receive(struct ctl_iscsi *ci)
1976{
1977	struct ctl_iscsi_receive_params *cirp;
1978	struct cfiscsi_session *cs;
1979	struct icl_pdu *ip;
1980	void *data;
1981	int error;
1982
1983	cirp = (struct ctl_iscsi_receive_params *)&(ci->data);
1984
1985	mtx_lock(&cfiscsi_softc.lock);
1986	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1987		if (cs->cs_id == cirp->connection_id)
1988			break;
1989	}
1990	if (cs == NULL) {
1991		mtx_unlock(&cfiscsi_softc.lock);
1992		snprintf(ci->error_str, sizeof(ci->error_str),
1993		    "connection not found");
1994		ci->status = CTL_ISCSI_ERROR;
1995		return;
1996	}
1997	mtx_unlock(&cfiscsi_softc.lock);
1998
1999#if 0
2000	if (is->is_login_phase == false)
2001		return (EBUSY);
2002#endif
2003
2004	CFISCSI_SESSION_LOCK(cs);
2005	while (cs->cs_login_pdu == NULL && cs->cs_terminating == false) {
2006		error = cv_wait_sig(&cs->cs_login_cv, &cs->cs_lock);
2007		if (error != 0) {
2008			CFISCSI_SESSION_UNLOCK(cs);
2009			snprintf(ci->error_str, sizeof(ci->error_str),
2010			    "interrupted by signal");
2011			ci->status = CTL_ISCSI_ERROR;
2012			return;
2013		}
2014	}
2015
2016	if (cs->cs_terminating) {
2017		CFISCSI_SESSION_UNLOCK(cs);
2018		snprintf(ci->error_str, sizeof(ci->error_str),
2019		    "connection terminating");
2020		ci->status = CTL_ISCSI_ERROR;
2021		return;
2022	}
2023	ip = cs->cs_login_pdu;
2024	cs->cs_login_pdu = NULL;
2025	CFISCSI_SESSION_UNLOCK(cs);
2026
2027	if (ip->ip_data_len > cirp->data_segment_len) {
2028		icl_pdu_free(ip);
2029		snprintf(ci->error_str, sizeof(ci->error_str),
2030		    "data segment too big");
2031		ci->status = CTL_ISCSI_ERROR;
2032		return;
2033	}
2034
2035	copyout(ip->ip_bhs, cirp->bhs, sizeof(*ip->ip_bhs));
2036	if (ip->ip_data_len > 0) {
2037		data = malloc(ip->ip_data_len, M_CFISCSI, M_WAITOK);
2038		icl_pdu_get_data(ip, 0, data, ip->ip_data_len);
2039		copyout(data, cirp->data_segment, ip->ip_data_len);
2040		free(data, M_CFISCSI);
2041	}
2042
2043	icl_pdu_free(ip);
2044	ci->status = CTL_ISCSI_OK;
2045}
2046
2047#endif /* !ICL_KERNEL_PROXY */
2048
2049static void
2050cfiscsi_ioctl_port_create(struct ctl_req *req)
2051{
2052	struct cfiscsi_target *ct;
2053	struct ctl_port *port;
2054	const char *target, *alias, *tags;
2055	struct scsi_vpd_id_descriptor *desc;
2056	ctl_options_t opts;
2057	int retval, len, idlen;
2058	uint16_t tag;
2059
2060	ctl_init_opts(&opts, req->num_args, req->kern_args);
2061	target = ctl_get_opt(&opts, "cfiscsi_target");
2062	alias = ctl_get_opt(&opts, "cfiscsi_target_alias");
2063	tags = ctl_get_opt(&opts, "cfiscsi_portal_group_tag");
2064	if (target == NULL || tags == NULL) {
2065		req->status = CTL_LUN_ERROR;
2066		snprintf(req->error_str, sizeof(req->error_str),
2067		    "Missing required argument");
2068		ctl_free_opts(&opts);
2069		return;
2070	}
2071	tag = strtol(tags, (char **)NULL, 10);
2072	ct = cfiscsi_target_find_or_create(&cfiscsi_softc, target, alias, tag);
2073	if (ct == NULL) {
2074		req->status = CTL_LUN_ERROR;
2075		snprintf(req->error_str, sizeof(req->error_str),
2076		    "failed to create target \"%s\"", target);
2077		ctl_free_opts(&opts);
2078		return;
2079	}
2080	if (ct->ct_state == CFISCSI_TARGET_STATE_ACTIVE) {
2081		req->status = CTL_LUN_ERROR;
2082		snprintf(req->error_str, sizeof(req->error_str),
2083		    "target \"%s\" already exists", target);
2084		cfiscsi_target_release(ct);
2085		ctl_free_opts(&opts);
2086		return;
2087	}
2088	port = &ct->ct_port;
2089	// WAT
2090	if (ct->ct_state == CFISCSI_TARGET_STATE_DYING)
2091		goto done;
2092
2093	port->frontend = &cfiscsi_frontend;
2094	port->port_type = CTL_PORT_ISCSI;
2095	/* XXX KDM what should the real number be here? */
2096	port->num_requested_ctl_io = 4096;
2097	port->port_name = "iscsi";
2098	port->physical_port = tag;
2099	port->virtual_port = ct->ct_target_id;
2100	port->port_online = cfiscsi_online;
2101	port->port_offline = cfiscsi_offline;
2102	port->port_info = cfiscsi_info;
2103	port->onoff_arg = ct;
2104	port->fe_datamove = cfiscsi_datamove;
2105	port->fe_done = cfiscsi_done;
2106
2107	/* XXX KDM what should we report here? */
2108	/* XXX These should probably be fetched from CTL. */
2109	port->max_targets = 1;
2110	port->max_target_id = 15;
2111	port->targ_port = -1;
2112
2113	port->options = opts;
2114	STAILQ_INIT(&opts);
2115
2116	/* Generate Port ID. */
2117	idlen = strlen(target) + strlen(",t,0x0001") + 1;
2118	idlen = roundup2(idlen, 4);
2119	len = sizeof(struct scsi_vpd_device_id) + idlen;
2120	port->port_devid = malloc(sizeof(struct ctl_devid) + len,
2121	    M_CTL, M_WAITOK | M_ZERO);
2122	port->port_devid->len = len;
2123	desc = (struct scsi_vpd_id_descriptor *)port->port_devid->data;
2124	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2125	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2126	    SVPD_ID_TYPE_SCSI_NAME;
2127	desc->length = idlen;
2128	snprintf(desc->identifier, idlen, "%s,t,0x%4.4x", target, tag);
2129
2130	/* Generate Target ID. */
2131	idlen = strlen(target) + 1;
2132	idlen = roundup2(idlen, 4);
2133	len = sizeof(struct scsi_vpd_device_id) + idlen;
2134	port->target_devid = malloc(sizeof(struct ctl_devid) + len,
2135	    M_CTL, M_WAITOK | M_ZERO);
2136	port->target_devid->len = len;
2137	desc = (struct scsi_vpd_id_descriptor *)port->target_devid->data;
2138	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2139	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_TARGET |
2140	    SVPD_ID_TYPE_SCSI_NAME;
2141	desc->length = idlen;
2142	strlcpy(desc->identifier, target, idlen);
2143
2144	retval = ctl_port_register(port);
2145	if (retval != 0) {
2146		ctl_free_opts(&port->options);
2147		cfiscsi_target_release(ct);
2148		free(port->port_devid, M_CFISCSI);
2149		free(port->target_devid, M_CFISCSI);
2150		req->status = CTL_LUN_ERROR;
2151		snprintf(req->error_str, sizeof(req->error_str),
2152		    "ctl_port_register() failed with error %d", retval);
2153		return;
2154	}
2155done:
2156	ct->ct_state = CFISCSI_TARGET_STATE_ACTIVE;
2157	req->status = CTL_LUN_OK;
2158	memcpy(req->kern_args[0].kvalue, &port->targ_port,
2159	    sizeof(port->targ_port)); //XXX
2160}
2161
2162static void
2163cfiscsi_ioctl_port_remove(struct ctl_req *req)
2164{
2165	struct cfiscsi_target *ct;
2166	const char *target, *tags;
2167	ctl_options_t opts;
2168	uint16_t tag;
2169
2170	ctl_init_opts(&opts, req->num_args, req->kern_args);
2171	target = ctl_get_opt(&opts, "cfiscsi_target");
2172	tags = ctl_get_opt(&opts, "cfiscsi_portal_group_tag");
2173	if (target == NULL || tags == NULL) {
2174		ctl_free_opts(&opts);
2175		req->status = CTL_LUN_ERROR;
2176		snprintf(req->error_str, sizeof(req->error_str),
2177		    "Missing required argument");
2178		return;
2179	}
2180	tag = strtol(tags, (char **)NULL, 10);
2181	ct = cfiscsi_target_find(&cfiscsi_softc, target, tag);
2182	if (ct == NULL) {
2183		ctl_free_opts(&opts);
2184		req->status = CTL_LUN_ERROR;
2185		snprintf(req->error_str, sizeof(req->error_str),
2186		    "can't find target \"%s\"", target);
2187		return;
2188	}
2189	if (ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE) {
2190		ctl_free_opts(&opts);
2191		req->status = CTL_LUN_ERROR;
2192		snprintf(req->error_str, sizeof(req->error_str),
2193		    "target \"%s\" is already dying", target);
2194		return;
2195	}
2196	ctl_free_opts(&opts);
2197
2198	ct->ct_state = CFISCSI_TARGET_STATE_DYING;
2199	ctl_port_offline(&ct->ct_port);
2200	cfiscsi_target_release(ct);
2201	cfiscsi_target_release(ct);
2202	req->status = CTL_LUN_OK;
2203}
2204
2205static int
2206cfiscsi_ioctl(struct cdev *dev,
2207    u_long cmd, caddr_t addr, int flag, struct thread *td)
2208{
2209	struct ctl_iscsi *ci;
2210	struct ctl_req *req;
2211
2212	if (cmd == CTL_PORT_REQ) {
2213		req = (struct ctl_req *)addr;
2214		switch (req->reqtype) {
2215		case CTL_REQ_CREATE:
2216			cfiscsi_ioctl_port_create(req);
2217			break;
2218		case CTL_REQ_REMOVE:
2219			cfiscsi_ioctl_port_remove(req);
2220			break;
2221		default:
2222			req->status = CTL_LUN_ERROR;
2223			snprintf(req->error_str, sizeof(req->error_str),
2224			    "Unsupported request type %d", req->reqtype);
2225		}
2226		return (0);
2227	}
2228
2229	if (cmd != CTL_ISCSI)
2230		return (ENOTTY);
2231
2232	ci = (struct ctl_iscsi *)addr;
2233	switch (ci->type) {
2234	case CTL_ISCSI_HANDOFF:
2235		cfiscsi_ioctl_handoff(ci);
2236		break;
2237	case CTL_ISCSI_LIST:
2238		cfiscsi_ioctl_list(ci);
2239		break;
2240	case CTL_ISCSI_LOGOUT:
2241		cfiscsi_ioctl_logout(ci);
2242		break;
2243	case CTL_ISCSI_TERMINATE:
2244		cfiscsi_ioctl_terminate(ci);
2245		break;
2246	case CTL_ISCSI_LIMITS:
2247		cfiscsi_ioctl_limits(ci);
2248		break;
2249#ifdef ICL_KERNEL_PROXY
2250	case CTL_ISCSI_LISTEN:
2251		cfiscsi_ioctl_listen(ci);
2252		break;
2253	case CTL_ISCSI_ACCEPT:
2254		cfiscsi_ioctl_accept(ci);
2255		break;
2256	case CTL_ISCSI_SEND:
2257		cfiscsi_ioctl_send(ci);
2258		break;
2259	case CTL_ISCSI_RECEIVE:
2260		cfiscsi_ioctl_receive(ci);
2261		break;
2262#else
2263	case CTL_ISCSI_LISTEN:
2264	case CTL_ISCSI_ACCEPT:
2265	case CTL_ISCSI_SEND:
2266	case CTL_ISCSI_RECEIVE:
2267		ci->status = CTL_ISCSI_ERROR;
2268		snprintf(ci->error_str, sizeof(ci->error_str),
2269		    "%s: CTL compiled without ICL_KERNEL_PROXY",
2270		    __func__);
2271		break;
2272#endif /* !ICL_KERNEL_PROXY */
2273	default:
2274		ci->status = CTL_ISCSI_ERROR;
2275		snprintf(ci->error_str, sizeof(ci->error_str),
2276		    "%s: invalid iSCSI request type %d", __func__, ci->type);
2277		break;
2278	}
2279
2280	return (0);
2281}
2282
2283static void
2284cfiscsi_target_hold(struct cfiscsi_target *ct)
2285{
2286
2287	refcount_acquire(&ct->ct_refcount);
2288}
2289
2290static void
2291cfiscsi_target_release(struct cfiscsi_target *ct)
2292{
2293	struct cfiscsi_softc *softc;
2294
2295	softc = ct->ct_softc;
2296	mtx_lock(&softc->lock);
2297	if (refcount_release(&ct->ct_refcount)) {
2298		TAILQ_REMOVE(&softc->targets, ct, ct_next);
2299		mtx_unlock(&softc->lock);
2300		if (ct->ct_state != CFISCSI_TARGET_STATE_INVALID) {
2301			ct->ct_state = CFISCSI_TARGET_STATE_INVALID;
2302			if (ctl_port_deregister(&ct->ct_port) != 0)
2303				printf("%s: ctl_port_deregister() failed\n",
2304				    __func__);
2305		}
2306		free(ct, M_CFISCSI);
2307
2308		return;
2309	}
2310	mtx_unlock(&softc->lock);
2311}
2312
2313static struct cfiscsi_target *
2314cfiscsi_target_find(struct cfiscsi_softc *softc, const char *name, uint16_t tag)
2315{
2316	struct cfiscsi_target *ct;
2317
2318	mtx_lock(&softc->lock);
2319	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2320		if (ct->ct_tag != tag ||
2321		    strcmp(name, ct->ct_name) != 0 ||
2322		    ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE)
2323			continue;
2324		cfiscsi_target_hold(ct);
2325		mtx_unlock(&softc->lock);
2326		return (ct);
2327	}
2328	mtx_unlock(&softc->lock);
2329
2330	return (NULL);
2331}
2332
2333static struct cfiscsi_target *
2334cfiscsi_target_find_or_create(struct cfiscsi_softc *softc, const char *name,
2335    const char *alias, uint16_t tag)
2336{
2337	struct cfiscsi_target *ct, *newct;
2338
2339	if (name[0] == '\0' || strlen(name) >= CTL_ISCSI_NAME_LEN)
2340		return (NULL);
2341
2342	newct = malloc(sizeof(*newct), M_CFISCSI, M_WAITOK | M_ZERO);
2343
2344	mtx_lock(&softc->lock);
2345	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2346		if (ct->ct_tag != tag ||
2347		    strcmp(name, ct->ct_name) != 0 ||
2348		    ct->ct_state == CFISCSI_TARGET_STATE_INVALID)
2349			continue;
2350		cfiscsi_target_hold(ct);
2351		mtx_unlock(&softc->lock);
2352		free(newct, M_CFISCSI);
2353		return (ct);
2354	}
2355
2356	strlcpy(newct->ct_name, name, sizeof(newct->ct_name));
2357	if (alias != NULL)
2358		strlcpy(newct->ct_alias, alias, sizeof(newct->ct_alias));
2359	newct->ct_tag = tag;
2360	refcount_init(&newct->ct_refcount, 1);
2361	newct->ct_softc = softc;
2362	if (TAILQ_EMPTY(&softc->targets))
2363		softc->last_target_id = 0;
2364	newct->ct_target_id = ++softc->last_target_id;
2365	TAILQ_INSERT_TAIL(&softc->targets, newct, ct_next);
2366	mtx_unlock(&softc->lock);
2367
2368	return (newct);
2369}
2370
2371static void
2372cfiscsi_datamove_in(union ctl_io *io)
2373{
2374	struct cfiscsi_session *cs;
2375	struct icl_pdu *request, *response;
2376	const struct iscsi_bhs_scsi_command *bhssc;
2377	struct iscsi_bhs_data_in *bhsdi;
2378	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2379	size_t len, expected_len, sg_len, buffer_offset;
2380	const char *sg_addr;
2381	int ctl_sg_count, error, i;
2382
2383	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2384	cs = PDU_SESSION(request);
2385
2386	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2387	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2388	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2389	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2390
2391	if (io->scsiio.kern_sg_entries > 0) {
2392		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2393		ctl_sg_count = io->scsiio.kern_sg_entries;
2394	} else {
2395		ctl_sglist = &ctl_sg_entry;
2396		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2397		ctl_sglist->len = io->scsiio.kern_data_len;
2398		ctl_sg_count = 1;
2399	}
2400
2401	/*
2402	 * This is the total amount of data to be transferred within the current
2403	 * SCSI command.  We need to record it so that we can properly report
2404	 * underflow/underflow.
2405	 */
2406	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2407
2408	/*
2409	 * This is the offset within the current SCSI command; for the first
2410	 * call to cfiscsi_datamove() it will be 0, and for subsequent ones
2411	 * it will be the sum of lengths of previous ones.
2412	 */
2413	buffer_offset = io->scsiio.kern_rel_offset;
2414
2415	/*
2416	 * This is the transfer length expected by the initiator.  In theory,
2417	 * it could be different from the correct amount of data from the SCSI
2418	 * point of view, even if that doesn't make any sense.
2419	 */
2420	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2421#if 0
2422	if (expected_len != io->scsiio.kern_total_len) {
2423		CFISCSI_SESSION_DEBUG(cs, "expected transfer length %zd, "
2424		    "actual length %zd", expected_len,
2425		    (size_t)io->scsiio.kern_total_len);
2426	}
2427#endif
2428
2429	if (buffer_offset >= expected_len) {
2430#if 0
2431		CFISCSI_SESSION_DEBUG(cs, "buffer_offset = %zd, "
2432		    "already sent the expected len", buffer_offset);
2433#endif
2434		io->scsiio.be_move_done(io);
2435		return;
2436	}
2437
2438	i = 0;
2439	sg_addr = NULL;
2440	sg_len = 0;
2441	response = NULL;
2442	bhsdi = NULL;
2443	for (;;) {
2444		if (response == NULL) {
2445			response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2446			if (response == NULL) {
2447				CFISCSI_SESSION_WARN(cs, "failed to "
2448				    "allocate memory; dropping connection");
2449				ctl_set_busy(&io->scsiio);
2450				io->scsiio.be_move_done(io);
2451				cfiscsi_session_terminate(cs);
2452				return;
2453			}
2454			bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
2455			bhsdi->bhsdi_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_IN;
2456			bhsdi->bhsdi_initiator_task_tag =
2457			    bhssc->bhssc_initiator_task_tag;
2458			bhsdi->bhsdi_datasn = htonl(PDU_EXPDATASN(request));
2459			PDU_EXPDATASN(request)++;
2460			bhsdi->bhsdi_buffer_offset = htonl(buffer_offset);
2461		}
2462
2463		KASSERT(i < ctl_sg_count, ("i >= ctl_sg_count"));
2464		if (sg_len == 0) {
2465			sg_addr = ctl_sglist[i].addr;
2466			sg_len = ctl_sglist[i].len;
2467			KASSERT(sg_len > 0, ("sg_len <= 0"));
2468		}
2469
2470		len = sg_len;
2471
2472		/*
2473		 * Truncate to maximum data segment length.
2474		 */
2475		KASSERT(response->ip_data_len < cs->cs_max_data_segment_length,
2476		    ("ip_data_len %zd >= max_data_segment_length %zd",
2477		    response->ip_data_len, cs->cs_max_data_segment_length));
2478		if (response->ip_data_len + len >
2479		    cs->cs_max_data_segment_length) {
2480			len = cs->cs_max_data_segment_length -
2481			    response->ip_data_len;
2482			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2483			    len, sg_len));
2484		}
2485
2486		/*
2487		 * Truncate to expected data transfer length.
2488		 */
2489		KASSERT(buffer_offset + response->ip_data_len < expected_len,
2490		    ("buffer_offset %zd + ip_data_len %zd >= expected_len %zd",
2491		    buffer_offset, response->ip_data_len, expected_len));
2492		if (buffer_offset + response->ip_data_len + len > expected_len) {
2493			CFISCSI_SESSION_DEBUG(cs, "truncating from %zd "
2494			    "to expected data transfer length %zd",
2495			    buffer_offset + response->ip_data_len + len, expected_len);
2496			len = expected_len - (buffer_offset + response->ip_data_len);
2497			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2498			    len, sg_len));
2499		}
2500
2501		error = icl_pdu_append_data(response, sg_addr, len, M_NOWAIT);
2502		if (error != 0) {
2503			CFISCSI_SESSION_WARN(cs, "failed to "
2504			    "allocate memory; dropping connection");
2505			icl_pdu_free(response);
2506			ctl_set_busy(&io->scsiio);
2507			io->scsiio.be_move_done(io);
2508			cfiscsi_session_terminate(cs);
2509			return;
2510		}
2511		sg_addr += len;
2512		sg_len -= len;
2513
2514		KASSERT(buffer_offset + response->ip_data_len <= expected_len,
2515		    ("buffer_offset %zd + ip_data_len %zd > expected_len %zd",
2516		    buffer_offset, response->ip_data_len, expected_len));
2517		if (buffer_offset + response->ip_data_len == expected_len) {
2518			/*
2519			 * Already have the amount of data the initiator wanted.
2520			 */
2521			break;
2522		}
2523
2524		if (sg_len == 0) {
2525			/*
2526			 * End of scatter-gather segment;
2527			 * proceed to the next one...
2528			 */
2529			if (i == ctl_sg_count - 1) {
2530				/*
2531				 * ... unless this was the last one.
2532				 */
2533				break;
2534			}
2535			i++;
2536		}
2537
2538		if (response->ip_data_len == cs->cs_max_data_segment_length) {
2539			/*
2540			 * Can't stuff more data into the current PDU;
2541			 * queue it.  Note that's not enough to check
2542			 * for kern_data_resid == 0 instead; there
2543			 * may be several Data-In PDUs for the final
2544			 * call to cfiscsi_datamove(), and we want
2545			 * to set the F flag only on the last of them.
2546			 */
2547			buffer_offset += response->ip_data_len;
2548			if (buffer_offset == io->scsiio.kern_total_len ||
2549			    buffer_offset == expected_len) {
2550				buffer_offset -= response->ip_data_len;
2551				break;
2552			}
2553			cfiscsi_pdu_queue(response);
2554			response = NULL;
2555			bhsdi = NULL;
2556		}
2557	}
2558	if (response != NULL) {
2559		buffer_offset += response->ip_data_len;
2560		if (buffer_offset == io->scsiio.kern_total_len ||
2561		    buffer_offset == expected_len) {
2562			bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2563			if (io->io_hdr.status == CTL_SUCCESS) {
2564				bhsdi->bhsdi_flags |= BHSDI_FLAGS_S;
2565				if (PDU_TOTAL_TRANSFER_LEN(request) <
2566				    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2567					bhsdi->bhsdi_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2568					bhsdi->bhsdi_residual_count =
2569					    htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2570					    PDU_TOTAL_TRANSFER_LEN(request));
2571				} else if (PDU_TOTAL_TRANSFER_LEN(request) >
2572				    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2573					bhsdi->bhsdi_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2574					bhsdi->bhsdi_residual_count =
2575					    htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2576					    ntohl(bhssc->bhssc_expected_data_transfer_length));
2577				}
2578				bhsdi->bhsdi_status = io->scsiio.scsi_status;
2579				io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
2580			}
2581		}
2582		KASSERT(response->ip_data_len > 0, ("sending empty Data-In"));
2583		cfiscsi_pdu_queue(response);
2584	}
2585
2586	io->scsiio.be_move_done(io);
2587}
2588
2589static void
2590cfiscsi_datamove_out(union ctl_io *io)
2591{
2592	struct cfiscsi_session *cs;
2593	struct icl_pdu *request, *response;
2594	const struct iscsi_bhs_scsi_command *bhssc;
2595	struct iscsi_bhs_r2t *bhsr2t;
2596	struct cfiscsi_data_wait *cdw;
2597	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2598	uint32_t expected_len, r2t_off, r2t_len;
2599	uint32_t target_transfer_tag;
2600	bool done;
2601
2602	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2603	cs = PDU_SESSION(request);
2604
2605	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2606	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2607	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2608	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2609
2610	/*
2611	 * We need to record it so that we can properly report
2612	 * underflow/underflow.
2613	 */
2614	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2615
2616	/*
2617	 * Report write underflow as error since CTL and backends don't
2618	 * really support it, and SCSI does not tell how to do it right.
2619	 */
2620	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2621	if (io->scsiio.kern_rel_offset + io->scsiio.kern_data_len >
2622	    expected_len) {
2623		io->scsiio.io_hdr.port_status = 43;
2624		io->scsiio.be_move_done(io);
2625		return;
2626	}
2627
2628	target_transfer_tag =
2629	    atomic_fetchadd_32(&cs->cs_target_transfer_tag, 1);
2630	cdw = cfiscsi_data_wait_new(cs, io, bhssc->bhssc_initiator_task_tag,
2631	    &target_transfer_tag);
2632	if (cdw == NULL) {
2633		CFISCSI_SESSION_WARN(cs, "failed to "
2634		    "allocate memory; dropping connection");
2635		ctl_set_busy(&io->scsiio);
2636		io->scsiio.be_move_done(io);
2637		cfiscsi_session_terminate(cs);
2638		return;
2639	}
2640#if 0
2641	CFISCSI_SESSION_DEBUG(cs, "expecting Data-Out with initiator "
2642	    "task tag 0x%x, target transfer tag 0x%x",
2643	    bhssc->bhssc_initiator_task_tag, target_transfer_tag);
2644#endif
2645
2646	cdw->cdw_ctl_io = io;
2647	cdw->cdw_target_transfer_tag = target_transfer_tag;
2648	cdw->cdw_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2649	cdw->cdw_r2t_end = io->scsiio.kern_data_len;
2650	cdw->cdw_datasn = 0;
2651
2652	/* Set initial data pointer for the CDW respecting ext_data_filled. */
2653	if (io->scsiio.kern_sg_entries > 0) {
2654		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2655	} else {
2656		ctl_sglist = &ctl_sg_entry;
2657		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2658		ctl_sglist->len = io->scsiio.kern_data_len;
2659	}
2660	cdw->cdw_sg_index = 0;
2661	cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
2662	cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
2663	r2t_off = io->scsiio.ext_data_filled;
2664	while (r2t_off > 0) {
2665		if (r2t_off >= cdw->cdw_sg_len) {
2666			r2t_off -= cdw->cdw_sg_len;
2667			cdw->cdw_sg_index++;
2668			cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
2669			cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
2670			continue;
2671		}
2672		cdw->cdw_sg_addr += r2t_off;
2673		cdw->cdw_sg_len -= r2t_off;
2674		r2t_off = 0;
2675	}
2676
2677	if (cs->cs_immediate_data &&
2678	    io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled <
2679	    icl_pdu_data_segment_length(request)) {
2680		done = cfiscsi_handle_data_segment(request, cdw);
2681		if (done) {
2682			cfiscsi_data_wait_free(cs, cdw);
2683			io->scsiio.be_move_done(io);
2684			return;
2685		}
2686	}
2687
2688	r2t_off = io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled;
2689	r2t_len = MIN(io->scsiio.kern_data_len - io->scsiio.ext_data_filled,
2690	    cs->cs_max_burst_length);
2691	cdw->cdw_r2t_end = io->scsiio.ext_data_filled + r2t_len;
2692
2693	CFISCSI_SESSION_LOCK(cs);
2694	TAILQ_INSERT_TAIL(&cs->cs_waiting_for_data_out, cdw, cdw_next);
2695	CFISCSI_SESSION_UNLOCK(cs);
2696
2697	/*
2698	 * XXX: We should limit the number of outstanding R2T PDUs
2699	 * 	per task to MaxOutstandingR2T.
2700	 */
2701	response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2702	if (response == NULL) {
2703		CFISCSI_SESSION_WARN(cs, "failed to "
2704		    "allocate memory; dropping connection");
2705		ctl_set_busy(&io->scsiio);
2706		io->scsiio.be_move_done(io);
2707		cfiscsi_session_terminate(cs);
2708		return;
2709	}
2710	bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
2711	bhsr2t->bhsr2t_opcode = ISCSI_BHS_OPCODE_R2T;
2712	bhsr2t->bhsr2t_flags = 0x80;
2713	bhsr2t->bhsr2t_lun = bhssc->bhssc_lun;
2714	bhsr2t->bhsr2t_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2715	bhsr2t->bhsr2t_target_transfer_tag = target_transfer_tag;
2716	/*
2717	 * XXX: Here we assume that cfiscsi_datamove() won't ever
2718	 *	be running concurrently on several CPUs for a given
2719	 *	command.
2720	 */
2721	bhsr2t->bhsr2t_r2tsn = htonl(PDU_R2TSN(request));
2722	PDU_R2TSN(request)++;
2723	/*
2724	 * This is the offset within the current SCSI command;
2725	 * i.e. for the first call of datamove(), it will be 0,
2726	 * and for subsequent ones it will be the sum of lengths
2727	 * of previous ones.
2728	 *
2729	 * The ext_data_filled is to account for unsolicited
2730	 * (immediate) data that might have already arrived.
2731	 */
2732	bhsr2t->bhsr2t_buffer_offset = htonl(r2t_off);
2733	/*
2734	 * This is the total length (sum of S/G lengths) this call
2735	 * to cfiscsi_datamove() is supposed to handle, limited by
2736	 * MaxBurstLength.
2737	 */
2738	bhsr2t->bhsr2t_desired_data_transfer_length = htonl(r2t_len);
2739	cfiscsi_pdu_queue(response);
2740}
2741
2742static void
2743cfiscsi_datamove(union ctl_io *io)
2744{
2745
2746	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
2747		cfiscsi_datamove_in(io);
2748	else {
2749		/* We hadn't received anything during this datamove yet. */
2750		io->scsiio.ext_data_filled = 0;
2751		cfiscsi_datamove_out(io);
2752	}
2753}
2754
2755static void
2756cfiscsi_scsi_command_done(union ctl_io *io)
2757{
2758	struct icl_pdu *request, *response;
2759	struct iscsi_bhs_scsi_command *bhssc;
2760	struct iscsi_bhs_scsi_response *bhssr;
2761#ifdef DIAGNOSTIC
2762	struct cfiscsi_data_wait *cdw;
2763#endif
2764	struct cfiscsi_session *cs;
2765	uint16_t sense_length;
2766
2767	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2768	cs = PDU_SESSION(request);
2769	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
2770	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2771	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2772	    ("replying to wrong opcode 0x%x", bhssc->bhssc_opcode));
2773
2774	//CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
2775	//    bhssc->bhssc_initiator_task_tag);
2776
2777#ifdef DIAGNOSTIC
2778	CFISCSI_SESSION_LOCK(cs);
2779	TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next)
2780		KASSERT(bhssc->bhssc_initiator_task_tag !=
2781		    cdw->cdw_initiator_task_tag, ("dangling cdw"));
2782	CFISCSI_SESSION_UNLOCK(cs);
2783#endif
2784
2785	/*
2786	 * Do not return status for aborted commands.
2787	 * There are exceptions, but none supported by CTL yet.
2788	 */
2789	if (((io->io_hdr.flags & CTL_FLAG_ABORT) &&
2790	     (io->io_hdr.flags & CTL_FLAG_ABORT_STATUS) == 0) ||
2791	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)) {
2792		ctl_free_io(io);
2793		icl_pdu_free(request);
2794		return;
2795	}
2796
2797	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2798	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
2799	bhssr->bhssr_opcode = ISCSI_BHS_OPCODE_SCSI_RESPONSE;
2800	bhssr->bhssr_flags = 0x80;
2801	/*
2802	 * XXX: We don't deal with bidirectional under/overflows;
2803	 *	does anything actually support those?
2804	 */
2805	if (PDU_TOTAL_TRANSFER_LEN(request) <
2806	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2807		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2808		bhssr->bhssr_residual_count =
2809		    htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2810		    PDU_TOTAL_TRANSFER_LEN(request));
2811		//CFISCSI_SESSION_DEBUG(cs, "underflow; residual count %d",
2812		//    ntohl(bhssr->bhssr_residual_count));
2813	} else if (PDU_TOTAL_TRANSFER_LEN(request) >
2814	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2815		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2816		bhssr->bhssr_residual_count =
2817		    htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2818		    ntohl(bhssc->bhssc_expected_data_transfer_length));
2819		//CFISCSI_SESSION_DEBUG(cs, "overflow; residual count %d",
2820		//    ntohl(bhssr->bhssr_residual_count));
2821	}
2822	bhssr->bhssr_response = BHSSR_RESPONSE_COMMAND_COMPLETED;
2823	bhssr->bhssr_status = io->scsiio.scsi_status;
2824	bhssr->bhssr_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2825	bhssr->bhssr_expdatasn = htonl(PDU_EXPDATASN(request));
2826
2827	if (io->scsiio.sense_len > 0) {
2828#if 0
2829		CFISCSI_SESSION_DEBUG(cs, "returning %d bytes of sense data",
2830		    io->scsiio.sense_len);
2831#endif
2832		sense_length = htons(io->scsiio.sense_len);
2833		icl_pdu_append_data(response,
2834		    &sense_length, sizeof(sense_length), M_WAITOK);
2835		icl_pdu_append_data(response,
2836		    &io->scsiio.sense_data, io->scsiio.sense_len, M_WAITOK);
2837	}
2838
2839	ctl_free_io(io);
2840	icl_pdu_free(request);
2841	cfiscsi_pdu_queue(response);
2842}
2843
2844static void
2845cfiscsi_task_management_done(union ctl_io *io)
2846{
2847	struct icl_pdu *request, *response;
2848	struct iscsi_bhs_task_management_request *bhstmr;
2849	struct iscsi_bhs_task_management_response *bhstmr2;
2850	struct cfiscsi_data_wait *cdw, *tmpcdw;
2851	struct cfiscsi_session *cs, *tcs;
2852	struct cfiscsi_softc *softc;
2853	int cold_reset = 0;
2854
2855	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2856	cs = PDU_SESSION(request);
2857	bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
2858	KASSERT((bhstmr->bhstmr_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2859	    ISCSI_BHS_OPCODE_TASK_REQUEST,
2860	    ("replying to wrong opcode 0x%x", bhstmr->bhstmr_opcode));
2861
2862#if 0
2863	CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x; referenced task tag 0x%x",
2864	    bhstmr->bhstmr_initiator_task_tag,
2865	    bhstmr->bhstmr_referenced_task_tag);
2866#endif
2867
2868	if ((bhstmr->bhstmr_function & ~0x80) ==
2869	    BHSTMR_FUNCTION_ABORT_TASK) {
2870		/*
2871		 * Make sure we no longer wait for Data-Out for this command.
2872		 */
2873		CFISCSI_SESSION_LOCK(cs);
2874		TAILQ_FOREACH_SAFE(cdw,
2875		    &cs->cs_waiting_for_data_out, cdw_next, tmpcdw) {
2876			if (bhstmr->bhstmr_referenced_task_tag !=
2877			    cdw->cdw_initiator_task_tag)
2878				continue;
2879
2880#if 0
2881			CFISCSI_SESSION_DEBUG(cs, "removing csw for initiator task "
2882			    "tag 0x%x", bhstmr->bhstmr_initiator_task_tag);
2883#endif
2884			TAILQ_REMOVE(&cs->cs_waiting_for_data_out,
2885			    cdw, cdw_next);
2886			cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
2887			cfiscsi_data_wait_free(cs, cdw);
2888		}
2889		CFISCSI_SESSION_UNLOCK(cs);
2890	}
2891	if ((bhstmr->bhstmr_function & ~0x80) ==
2892	    BHSTMR_FUNCTION_TARGET_COLD_RESET &&
2893	    io->io_hdr.status == CTL_SUCCESS)
2894		cold_reset = 1;
2895
2896	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2897	bhstmr2 = (struct iscsi_bhs_task_management_response *)
2898	    response->ip_bhs;
2899	bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
2900	bhstmr2->bhstmr_flags = 0x80;
2901	if (io->io_hdr.status == CTL_SUCCESS) {
2902		bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_COMPLETE;
2903	} else {
2904		/*
2905		 * XXX: How to figure out what exactly went wrong?  iSCSI spec
2906		 * 	expects us to provide detailed error, e.g. "Task does
2907		 * 	not exist" or "LUN does not exist".
2908		 */
2909		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED");
2910		bhstmr2->bhstmr_response =
2911		    BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
2912	}
2913	bhstmr2->bhstmr_initiator_task_tag = bhstmr->bhstmr_initiator_task_tag;
2914
2915	ctl_free_io(io);
2916	icl_pdu_free(request);
2917	cfiscsi_pdu_queue(response);
2918
2919	if (cold_reset) {
2920		softc = cs->cs_target->ct_softc;
2921		mtx_lock(&softc->lock);
2922		TAILQ_FOREACH(tcs, &softc->sessions, cs_next) {
2923			if (tcs->cs_target == cs->cs_target)
2924				cfiscsi_session_terminate(tcs);
2925		}
2926		mtx_unlock(&softc->lock);
2927	}
2928}
2929
2930static void
2931cfiscsi_done(union ctl_io *io)
2932{
2933	struct icl_pdu *request;
2934	struct cfiscsi_session *cs;
2935
2936	KASSERT(((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE),
2937		("invalid CTL status %#x", io->io_hdr.status));
2938
2939	if (io->io_hdr.io_type == CTL_IO_TASK &&
2940	    io->taskio.task_action == CTL_TASK_I_T_NEXUS_RESET) {
2941		/*
2942		 * Implicit task termination has just completed; nothing to do.
2943		 */
2944		cs = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2945		cs->cs_tasks_aborted = true;
2946		refcount_release(&cs->cs_outstanding_ctl_pdus);
2947		wakeup(__DEVOLATILE(void *, &cs->cs_outstanding_ctl_pdus));
2948		ctl_free_io(io);
2949		return;
2950	}
2951
2952	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2953	cs = PDU_SESSION(request);
2954	refcount_release(&cs->cs_outstanding_ctl_pdus);
2955
2956	switch (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) {
2957	case ISCSI_BHS_OPCODE_SCSI_COMMAND:
2958		cfiscsi_scsi_command_done(io);
2959		break;
2960	case ISCSI_BHS_OPCODE_TASK_REQUEST:
2961		cfiscsi_task_management_done(io);
2962		break;
2963	default:
2964		panic("cfiscsi_done called with wrong opcode 0x%x",
2965		    request->ip_bhs->bhs_opcode);
2966	}
2967}
2968