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